title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Can I compile boost.python module without bjam?
37,973,803
<p>Boost.python module provides a easy way of blinding c/c++ codes into Python. However, most tutorials assume that bjam is used to compile this module. I was wondering if I do not compile this module can I still use this module? What I mean "do not compile this module" is including all the source files of Boost.pytho...
1
2016-06-22T16:36:57Z
37,979,379
<p>Yes, absolutely, it's a library like any other.</p> <p>I always use it with CMake, but anything will do. You need to</p> <ul> <li>Add to include paths the location of the boost headers.</li> <li>Add to include paths the location of python headers (usually installed with Python, location depends on OS)</li> <li>Lin...
0
2016-06-22T22:38:56Z
[ "python", "c++", "boost" ]
Minimax python - how to efficiently find alternating max and mins in a tree
37,973,944
<p>The following code I'm using to minimax a tree looks awful. Surely there is a way to simplify this and use a function instead of a int.MaxValue</p> <pre><code>if depth%2==1: min = 9999 for child in currentRoot.children: if child.score &lt; min: min = child.score currentRoot.score = m...
0
2016-06-22T16:43:44Z
37,974,063
<pre><code>def findNewScore(isEven): if isEven: root.score = max([c.score for c in root.children] + [-999]) else: root.score = min([c.score for c in root.children] + [999]) return root.score </code></pre> <p>Or even just:</p> <pre><code>def findNewScore(isEven): s = sorted(c.score for ...
0
2016-06-22T16:49:49Z
[ "python", "minimax" ]
Minimax python - how to efficiently find alternating max and mins in a tree
37,973,944
<p>The following code I'm using to minimax a tree looks awful. Surely there is a way to simplify this and use a function instead of a int.MaxValue</p> <pre><code>if depth%2==1: min = 9999 for child in currentRoot.children: if child.score &lt; min: min = child.score currentRoot.score = m...
0
2016-06-22T16:43:44Z
37,974,066
<p>First, don't use <code>min</code> and <code>max</code> for variable names as this shadows the built-in functions. Second, use these built-in functions!</p> <p>You can use your current logic to pick out whether you want <code>min</code> or <code>max</code> and then pass a generator expression to access each child's ...
2
2016-06-22T16:50:02Z
[ "python", "minimax" ]
Changing class from python 3 to python 2.7
37,973,999
<p>Okay so i am trying to learn python from a book that teaches you by instructing you on how to make a text based adventure game. The only problem is that I use python 2.7 and the book is made in python 3. I have been able to get by so far but I rand into a problem with this code.</p> <pre><code>class Person : ag...
0
2016-06-22T16:46:36Z
37,978,544
<p>While I would agree with the above comments that this book seems highly suspect, I can offer a bit of a hint as how to move forward. </p> <ol> <li>Remember that classes are intentionally dynamic, constant variables are fine, but do your initialization inside an <code>__init__():</code> function. </li> <li>Object fu...
0
2016-06-22T21:26:26Z
[ "python", "python-2.7", "python-3.x" ]
A function similar to build-in map but support numpy broadcast
37,974,002
<p>I want to write a function <code>amap</code> which is similar to build-in <code>map</code> but support numpy broadcast and output array. It would work like this:</p> <pre><code>&gt;&gt;&gt; amap(lambda x:x**2, 1) array(1) &gt;&gt;&gt; amap(lambda x:x**2, [1, 2]) array([1, 4]) &gt;&gt;&gt; amap(lambda x,y:y**2+x**2,...
0
2016-06-22T16:46:39Z
37,974,109
<p>Use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html" rel="nofollow"><code>numpy.vectorize</code></a> directly?</p> <pre><code>&gt;&gt;&gt; numpy.vectorize(lambda x:x**2)(1) array(1) &gt;&gt;&gt; numpy.vectorize(lambda x:x**2)([1,2]) array([1, 4]) &gt;&gt;&gt; numpy.vectorize(lambda...
0
2016-06-22T16:52:04Z
[ "python", "arrays", "numpy" ]
Python: if any strings in a list match regex
37,974,047
<p>I need to check if any of the strings in a list match a regex. If any do, I want to continue. The way I've always done it in the past is using list comprehension with something like:</p> <pre><code>r = re.compile('.*search.*') if [line for line in output if r.match(line)]: do_stuff() </code></pre> <p>Which I n...
0
2016-06-22T16:48:57Z
37,974,167
<p>You can use the builtin <code>any()</code>:</p> <pre><code>if any(re.match(line) for line in output): do_stuff() </code></pre> <p>Passing in the lazy generator to <code>any()</code> will allow it to exit on the first match without having to check any farther into the iterable.</p>
5
2016-06-22T16:55:29Z
[ "python", "regex" ]
find next row in DataFrame based on column values
37,974,068
<p>I have a DataFrame with a non-unique sorted datetime index where I need to find the next row after a specific match on some columns of data.</p> <p>I can find the correct row with DataFrame.query() which gives me a new DataFrame, but I don't know how I can locate where this row is in the original DataFrame. Here is...
0
2016-06-22T16:50:08Z
37,974,193
<p>You could create a boolean mask, then shift it down by one row:</p> <pre><code>mask = ((df['BID_PRICE'] == 77.692) &amp; (df['BID_QTY'] == 100.0)).shift(1) df.loc[mask] </code></pre> <p>yields</p> <pre><code>In [17]: df.loc[mask] Out[17]: ASK_PRICE ASK_QTY BID_PRICE BID_QTY 2016-06-19...
1
2016-06-22T16:57:01Z
[ "python", "numpy", "pandas" ]
find next row in DataFrame based on column values
37,974,068
<p>I have a DataFrame with a non-unique sorted datetime index where I need to find the next row after a specific match on some columns of data.</p> <p>I can find the correct row with DataFrame.query() which gives me a new DataFrame, but I don't know how I can locate where this row is in the original DataFrame. Here is...
0
2016-06-22T16:50:08Z
37,974,222
<p>Does this work? Just reset the index, and identified the index of the row you're after </p> <pre><code>df = pd.DataFrame(index=ts_index, data={'BID_PRICE': bid_price, 'BID_QTY': bid_qty, 'ASK_PRICE': ask_price, 'ASK_QTY': ask_qty}) df.reset_index(inplace = True) most_recent_match = df.query('(BID_PRICE == 77...
1
2016-06-22T16:58:51Z
[ "python", "numpy", "pandas" ]
Is numpy accumulate the right thing for this?
37,974,141
<p>I've got a <code>pandas.Series</code> of integers that looks like this:</p> <pre><code>1959-09-22 191.0 1959-09-23 196.0 1959-09-24 222.0 1959-09-25 232.0 1959-09-28 232.0 1959-09-29 242.0 1959-09-30 241.0 1959-10-01 247.0 1959-10-02 251.0 1959-10-05 275.0 1959-10-06 294.0 1959-10-0...
2
2016-06-22T16:54:10Z
37,974,319
<p>Here's an approach to also support forward-filling -</p> <pre><code>def process_close_diffs(arr,percent_close,FORWARD_FILL=False): # Get thresholds for each element starting from the second element until last thresh = (percent_close/100.0)*(arr[:-1]) # Get the differentiations betwen consecutive elemen...
0
2016-06-22T17:03:59Z
[ "python", "numpy", "pandas" ]
Is numpy accumulate the right thing for this?
37,974,141
<p>I've got a <code>pandas.Series</code> of integers that looks like this:</p> <pre><code>1959-09-22 191.0 1959-09-23 196.0 1959-09-24 222.0 1959-09-25 232.0 1959-09-28 232.0 1959-09-29 242.0 1959-09-30 241.0 1959-10-01 247.0 1959-10-02 251.0 1959-10-05 275.0 1959-10-06 294.0 1959-10-0...
2
2016-06-22T16:54:10Z
37,975,253
<p>pandas approach:</p> <pre><code>s[np.abs(s.pct_change() &lt; 0.1)] = np.nan s.ffill() </code></pre> <p>Demo:</p> <pre><code>In [193]: s[np.abs(s.pct_change() &lt; 0.1)] = np.nan In [194]: s Out[194]: date 1959-09-22 191.0 1959-09-23 NaN 1959-09-24 222.0 1959-09-25 NaN 1959-09-28 NaN 1959-09-...
0
2016-06-22T18:02:32Z
[ "python", "numpy", "pandas" ]
Iterate over a dictionary with lists to create n subplots
37,974,169
<p><a href="http://i.stack.imgur.com/sxhgY.png" rel="nofollow">Type of chart that I want</a> So I have a dictionary with several lists:</p> <pre><code>{'A' : [1,2,4,6,7,8,10], 'B' : [1,2,4,6,4,3,7], 'C' : [3,2,1,6,2,3,4]} </code></pre> <p>At the same time, these dictionaries are generated by a function, and they have...
2
2016-06-22T16:55:36Z
37,975,925
<p>Might be a way to do it without looping, but here's a way to do it with looping. Unless you have loads and loads of these dictionaries this should work fine:</p> <pre><code>import numpy as np import seaborn as sns from matplotlib import pyplot as plt data = {'A' : [1,2,4,6,7,8,10],'B' : [1,2,4,6,4,3,7], 'C' : [3,2...
1
2016-06-22T18:40:37Z
[ "python", "loops", "dictionary", "matplotlib" ]
Writing to io.BytesIO in csv fails in python3
37,974,199
<p>I am trying to write python 2/3 compatible code to write strings to csv file object. This code:</p> <pre><code>line_as_list = [line.encode() for line in line_as_list] writer_file = io.BytesIO() writer = csv.writer(writer_file, dialect=dialect, delimiter=self.delimiter) for line in line_as_list: assert isinstan...
1
2016-06-22T16:57:21Z
37,974,772
<p>In Python3 <code>csv.writer</code> expects a file-like object opened in text mode. In Python2, <code>csv.writer</code> expects a file-like object opened in binary mode.</p> <p>Therefore, in Python3, use <code>io.StringIO</code>, while in Python2 use <code>io.BytesIO</code>:</p> <pre><code>import io import csv impo...
2
2016-06-22T17:34:43Z
[ "python", "string", "python-3.x", "csv", "bytesio" ]
How can I make a script wait for a button press?
37,974,353
<p>I apologize if the answer to this question is obvious, but I am unfamiliar with the inner workings of Python.</p> <p>Basic Scenario: I have a Python script that does stuff. Periodically, when certain conditions are met (like a flag variable being set), I want the script to pause and wait for the user to press a GUI...
1
2016-06-22T17:06:52Z
37,974,874
<p>If you're planning on using a GUI button (especially tkinter), you shouldn't need to do anything- GUIs tend to run their own infinite loop dealing with drawing and handling events. The moment you all a .mainloop() for tkinter, nothing after that point in your code will be executed except callbacks and tkinter events...
1
2016-06-22T17:40:59Z
[ "python", "python-3.x", "user-interface", "tkinter", "wait" ]
how to extract a headline form a url?
37,974,359
<p>I have a dataset of headlines, such as</p> <pre><code>http://www.stackoverflow.com/lifestyle/tech/this-is-a-very-nice-headline-my-friend/2013/04/26/acjhrjk-2e1-1krjke4-9el8c-2eheje_story.html?tid=sm_fb http://www.stackoverflow.com/2015/07/15/sports/baseball/another-very-nice.html?smid=tw-somedia&amp;seid=auto htt...
1
2016-06-22T17:07:21Z
37,975,054
<p>After all, regular expressions might not be your best bet.<br> However, with the specifications you came up with, you could do the following:</p> <pre><code>import re urls = ['http://www.stackoverflow.com/lifestyle/tech/this-is-a-very-nice-headline-my-friend/2013/04/26/acjhrjk-2e1-1krjke4-9el8c-2eheje_story.html?t...
1
2016-06-22T17:51:01Z
[ "python", "regex", "string", "url-parameters", "urlparse" ]
How to architect a PyQt5 project using QML with multiple python files?
37,974,446
<p>I'm just getting started using PyQt5 and QML and currently have a main.py file that has some simple code:</p> <pre><code>if __name__ == '__main__': app = QGuiApplication(sys.argv) engine = QQmlApplicationEngine() engine.load('QML/MainWindow.qml') sys.exit(app.exec_()) </code></pre> <p>In my MainWin...
0
2016-06-22T17:13:05Z
38,019,080
<p>I ended up solving this by doing the following:</p> <p>Main.py:</p> <pre><code>def settings_clicked(): stackView.push(Settings(engine, stackView).load()) if __name__ == '__main__': app = QGuiApplication(sys.argv) engine = QQmlEngine() component = QQmlComponent(engine) component.loadUrl(QUrl(...
1
2016-06-24T17:30:54Z
[ "python", "qt", "qml", "pyqt5" ]
Pandas mean across multiple columns
37,974,475
<p>I have a dataframe which I created using numpy arrays (MnthIdx, Val1, Val2, Val3) as:</p> <pre><code>import pandas as pd import numpy as np dfout3 = pd.DataFrame({'Idx': MnthIdx, 'Col1': Val1, 'Col2': Val2, 'Col3': Val3)}) MeanTable1 = pd.pivot_...
1
2016-06-22T17:15:03Z
37,974,811
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a> with 3 columns as parameter <code>values</code>. <code>Aggfunc=[np.mean]</code> can be omited, because this is default aggregating function. Last if need output as <code>num...
1
2016-06-22T17:37:26Z
[ "python", "pandas", "pivot-table" ]
Pandas mean across multiple columns
37,974,475
<p>I have a dataframe which I created using numpy arrays (MnthIdx, Val1, Val2, Val3) as:</p> <pre><code>import pandas as pd import numpy as np dfout3 = pd.DataFrame({'Idx': MnthIdx, 'Col1': Val1, 'Col2': Val2, 'Col3': Val3)}) MeanTable1 = pd.pivot_...
1
2016-06-22T17:15:03Z
37,975,859
<p>Working off jezael answer: </p> <pre><code>df = pd.pivot_table(dfout3, index=['Idx'], values=['Col1', 'Col2', 'Col3']) means = [ np.asarray(df[x]) for x in list(df)] 'MeanTable1','MeanTable2','MeanTable3' = means </code></pre> <p>or </p> <pre><code>(MeanTable1,MeanTable2,MeanTable3) = [ np.asarray(df[x]) for x...
1
2016-06-22T18:36:46Z
[ "python", "pandas", "pivot-table" ]
SQLite3 Columns Are Not Unique
37,974,508
<p>I'm inserting data from some csv files into my SQLite3 database with a python script I wrote. When I run the script, it inserts the first row into the database, but gives this error when trying to inset the second:</p> <pre><code>sqlite3.IntegrityError: columns column_name1, column_name2 are not unique. </code></pr...
0
2016-06-22T17:17:30Z
37,975,086
<p>The error may be due to duplicate column names in the INSERT INTO statement. I am guessing it is a typo and you meant column_name3 in the INSERT INTO statement.</p>
0
2016-06-22T17:53:07Z
[ "python", "database", "sqlite", "csv", "sqlite3" ]
SQLite3 Columns Are Not Unique
37,974,508
<p>I'm inserting data from some csv files into my SQLite3 database with a python script I wrote. When I run the script, it inserts the first row into the database, but gives this error when trying to inset the second:</p> <pre><code>sqlite3.IntegrityError: columns column_name1, column_name2 are not unique. </code></pr...
0
2016-06-22T17:17:30Z
37,975,437
<p>If SQLite is reporting an IntegrityError error it's very likely that there really is a PRIMARY KEY or UNIQUE KEY on those two columns and that you are mistaken when you state there is not. Ensure that you're really looking at the same instance of the database.</p> <p>Also, do <em>not</em> write your SQL statement ...
2
2016-06-22T18:13:25Z
[ "python", "database", "sqlite", "csv", "sqlite3" ]
Database fields not updating through REST API after migrating to ParseServer from parse.com
37,974,549
<p>I migrated from parse.com to an hosted ParseSever. Most of the things are working, however I found that for one class, the fields are not updated. The HTTP request returns 200 in logs and in Python, updatedAt field shows the recent timestamp, but the fields are not changed. In the python code and its printout below...
0
2016-06-22T17:20:23Z
37,975,657
<p>I found that every non-GET request must have a "Content-Type" field now. This was not required on parse.com. I am thinking may be ParseServer can be set-up with a default content type that would allow one to omit this parameter and then old code will work w/o modifications. The modified working code snippet is belo...
0
2016-06-22T18:25:21Z
[ "python", "mongodb", "rest", "parse.com", "parse-server" ]
Left truncate using python 3.5 str.format?
37,974,565
<p><em>Q: Is is possible to create a format string using Python 3.5's string formatting syntax to left truncate?</em></p> <p>Basically what I want to do is take a git SHA:</p> <pre><code>"c1e33f6717b9d0125b53688d315aff9cf8dd9977" </code></pre> <p>And using only a format string, get the display only the right 8 chars...
1
2016-06-22T17:21:19Z
37,975,336
<p>Is subclassing <code>str</code> an option?</p> <pre><code>foo="c1e33f6717b9d0125b53688d315aff9cf8dd9977" class CustomStr(str): def __format__(self, spec): if spec == 'trunc_left': return self[-8:] else: return super().__format__(spec) s = CustomStr(foo) print('{}'.form...
1
2016-06-22T18:07:18Z
[ "python", "string", "python-3.x", "string-formatting" ]
Left truncate using python 3.5 str.format?
37,974,565
<p><em>Q: Is is possible to create a format string using Python 3.5's string formatting syntax to left truncate?</em></p> <p>Basically what I want to do is take a git SHA:</p> <pre><code>"c1e33f6717b9d0125b53688d315aff9cf8dd9977" </code></pre> <p>And using only a format string, get the display only the right 8 chars...
1
2016-06-22T17:21:19Z
37,975,370
<p>Here is a slightly more flexible version of your 'inflexible and cumbersome' solution.</p> <pre><code>&gt;&gt;&gt; hash = "c1e33f6717b9d0125b53688d315aff9cf8dd9977" &gt;&gt;&gt; ''.join(['{{0[{}]}}'.format(i) for i in range(len(hash)-8, len(hash))]).format(hash) 'f8dd9977' </code></pre> <p>It will always grab the ...
-4
2016-06-22T18:09:35Z
[ "python", "string", "python-3.x", "string-formatting" ]
Left truncate using python 3.5 str.format?
37,974,565
<p><em>Q: Is is possible to create a format string using Python 3.5's string formatting syntax to left truncate?</em></p> <p>Basically what I want to do is take a git SHA:</p> <pre><code>"c1e33f6717b9d0125b53688d315aff9cf8dd9977" </code></pre> <p>And using only a format string, get the display only the right 8 chars...
1
2016-06-22T17:21:19Z
37,976,797
<p>So here is my solution, with thanks to @JacquesGaudin and folks on #Python for providing much guidance...</p> <pre><code>class MyStr(object): """Additional format string options.""" def __init__(self, obj): super(MyStr, self).__init__() self.obj = obj def __format__(self, spec): ...
1
2016-06-22T19:34:29Z
[ "python", "string", "python-3.x", "string-formatting" ]
no log file produced
37,974,668
<p>I'm new to logging in Python and have tried to build a basic logger that writes to a file. The problem I have is that the file is not created, yet there are not any errors thrown. Any ideas?</p> <p>Using Spyder IDE in Anaconda (in case that is applicable)</p> <p>Code:</p> <pre><code>import pandas as pd import l...
1
2016-06-22T17:27:47Z
37,974,883
<p>Appears the problem is with Spyder IDE v. 2.3.8 (maybe mine is outdated). The log file is created in command prompt but in Spyder the log file isn't created.</p>
-1
2016-06-22T17:41:20Z
[ "python", "logging" ]
no log file produced
37,974,668
<p>I'm new to logging in Python and have tried to build a basic logger that writes to a file. The problem I have is that the file is not created, yet there are not any errors thrown. Any ideas?</p> <p>Using Spyder IDE in Anaconda (in case that is applicable)</p> <p>Code:</p> <pre><code>import pandas as pd import l...
1
2016-06-22T17:27:47Z
37,974,917
<p>I'm using python 2.7.11 on osx, I reproduced your steps as also explained <a href="https://docs.python.org/2/howto/logging.html" rel="nofollow">here</a></p> <pre><code>import logging format = "%(asctime)s %(message)s" logging.basicConfig(format=format, level=logging.DEBUG, filename='logfile.log') logging.info("Hell...
0
2016-06-22T17:42:40Z
[ "python", "logging" ]
Import successfully without __init__.py?
37,974,843
<p>I am just curious about what is exactly the use of <code>__init__.py</code>? Yes, the answer is this file makes the directory an importable package. However, Consider the following example:</p> <p>project/</p> <pre><code>foo/ __init__.py a.py bar/ b.py </code></pre> <p>if I want to import a into ...
2
2016-06-22T17:39:06Z
37,974,923
<blockquote> <p>if I want to import a into b, I have to add following statement:</p> </blockquote> <p>No! You'd just say: <code>import foo.a</code>. All this is provided you run the entire package at once using <code>python -m main.module</code> where <code>main.module</code> is the entry point to your entire appli...
0
2016-06-22T17:42:54Z
[ "python", "import" ]
Import successfully without __init__.py?
37,974,843
<p>I am just curious about what is exactly the use of <code>__init__.py</code>? Yes, the answer is this file makes the directory an importable package. However, Consider the following example:</p> <p>project/</p> <pre><code>foo/ __init__.py a.py bar/ b.py </code></pre> <p>if I want to import a into ...
2
2016-06-22T17:39:06Z
37,974,964
<p>If you <em>really</em> want to avoid <code>__init__.py</code> for some reason, you don't <code>sys.path</code>. Rather, create a module object and set its <code>__path__</code> to a list of directories.</p>
0
2016-06-22T17:45:26Z
[ "python", "import" ]
Import successfully without __init__.py?
37,974,843
<p>I am just curious about what is exactly the use of <code>__init__.py</code>? Yes, the answer is this file makes the directory an importable package. However, Consider the following example:</p> <p>project/</p> <pre><code>foo/ __init__.py a.py bar/ b.py </code></pre> <p>if I want to import a into ...
2
2016-06-22T17:39:06Z
37,974,994
<p>When you import something it has to either:</p> <ol> <li>Retrieve an already loaded module or</li> <li>Load the module that was imported</li> </ol> <p>When you do <code>import foo</code> and python finds a folder called <code>foo</code> in a folder on your <code>sys.path</code> then it will look in that folder for...
0
2016-06-22T17:47:21Z
[ "python", "import" ]
Import successfully without __init__.py?
37,974,843
<p>I am just curious about what is exactly the use of <code>__init__.py</code>? Yes, the answer is this file makes the directory an importable package. However, Consider the following example:</p> <p>project/</p> <pre><code>foo/ __init__.py a.py bar/ b.py </code></pre> <p>if I want to import a into ...
2
2016-06-22T17:39:06Z
37,975,003
<p><code>__init__.py</code> has nothing to do with whether Python can find your package. You've run your code in such a way that your package isn't on the search path by default, but if you had run it differently or configured your <code>PYTHONPATH</code> differently, the <code>sys.path.append</code> would have been un...
2
2016-06-22T17:47:54Z
[ "python", "import" ]
Assign data to separate dataframes, combining and sort by year
37,974,887
<p>I have <code>40</code> years of data so I was trying to assign each of them to a dataframe individually then store them all in a new dataframe, then sort them. Below is what i have so far:</p> <pre><code>import pandas as pd from pandas import DataFrame year = 1976 count = 1 for i in range(0,40): df[count] = ...
3
2016-06-22T17:41:36Z
37,974,958
<p>I think you need to initialize your dictionary:</p> <pre><code>df = {} for i in range(0,40): df[count] = pd.read_excel('42003h'+str(year)+'.xlsx', sheet_name = 'Sheet1') </code></pre>
0
2016-06-22T17:45:04Z
[ "python", "sorting", "pandas", "dataframe", "concat" ]
Assign data to separate dataframes, combining and sort by year
37,974,887
<p>I have <code>40</code> years of data so I was trying to assign each of them to a dataframe individually then store them all in a new dataframe, then sort them. Below is what i have so far:</p> <pre><code>import pandas as pd from pandas import DataFrame year = 1976 count = 1 for i in range(0,40): df[count] = ...
3
2016-06-22T17:41:36Z
37,974,966
<p>I think you can first create list of <code>Dataframes</code> <code>dfs</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> it to one <code>df</code> . <code>count</code> is not necessary. Last IIUC <a href="http://pandas.pydata.org...
1
2016-06-22T17:45:33Z
[ "python", "sorting", "pandas", "dataframe", "concat" ]
Assign data to separate dataframes, combining and sort by year
37,974,887
<p>I have <code>40</code> years of data so I was trying to assign each of them to a dataframe individually then store them all in a new dataframe, then sort them. Below is what i have so far:</p> <pre><code>import pandas as pd from pandas import DataFrame year = 1976 count = 1 for i in range(0,40): df[count] = ...
3
2016-06-22T17:41:36Z
37,975,026
<p>i would do it this way:</p> <pre><code>import glob import pandas as pd files = glob.glob('42003h*.xlsx') # if you want to merge your DFs horizontally then add: `axis=1` parameter df = pd.concat([pd.read_excel(f) for f in files], ignore_index=True).sort_values('year') count = len(files) </code></pre>
0
2016-06-22T17:49:04Z
[ "python", "sorting", "pandas", "dataframe", "concat" ]
How to interpret length of None type object as zero?
37,974,962
<p>I need to sort a list like below with increasing order of string length </p> <pre><code>lst = [None, 'abc', 'a', 'ab'] </code></pre> <p>I'm using the below code to do that</p> <pre><code>lst.sort(key = lambda s: len(s)) </code></pre> <p>But It's producing error</p> <blockquote> <p>TypeError: object of type 'N...
-1
2016-06-22T17:45:17Z
37,974,986
<p>You can use a ternary operator:</p> <pre><code>lst.sort(key = lambda s: 0 if s is None else len(s)) </code></pre> <p><code>0</code> is returned when the item is <code>None</code> and <code>len(s)</code> for other items</p>
2
2016-06-22T17:46:38Z
[ "python", "list", "sorting", "python-3.x" ]
python script expected an indent block in if statement
37,974,988
<p>I'm trying to write a basic backup script from one folder to another, and I got it to work - but the directory structure was not being copied over, just the files. I'm trying to copy in the subfolder as well, so that, for example, <code>c:\temp\docs\file.txt</code> goes to <code>d:\temp\docs\file.txt</code> instead...
0
2016-06-22T17:46:59Z
37,975,047
<p>what's up with the weirdness with the space before the semi-colon? I've not seen it done that way before, that appears to be where this script is choking up. </p> <p>change </p> <pre><code>if subdir == source_folder : </code></pre> <p>with </p> <pre><code>if subdir == source_folder: </code></pre>
0
2016-06-22T17:50:27Z
[ "python" ]
python script expected an indent block in if statement
37,974,988
<p>I'm trying to write a basic backup script from one folder to another, and I got it to work - but the directory structure was not being copied over, just the files. I'm trying to copy in the subfolder as well, so that, for example, <code>c:\temp\docs\file.txt</code> goes to <code>d:\temp\docs\file.txt</code> instead...
0
2016-06-22T17:46:59Z
37,975,095
<p>You're intermixing tabs and spaces.</p> <p><a href="http://i.stack.imgur.com/3oXfK.png" rel="nofollow"><img src="http://i.stack.imgur.com/3oXfK.png" alt="enter image description here"></a></p> <p>Use one or the other, not both. Preferably spaces.</p>
4
2016-06-22T17:53:27Z
[ "python" ]
python script expected an indent block in if statement
37,974,988
<p>I'm trying to write a basic backup script from one folder to another, and I got it to work - but the directory structure was not being copied over, just the files. I'm trying to copy in the subfolder as well, so that, for example, <code>c:\temp\docs\file.txt</code> goes to <code>d:\temp\docs\file.txt</code> instead...
0
2016-06-22T17:46:59Z
37,975,100
<p>This error typically means there is an error in indentation. Check you don't mix <em>tabs</em> and <em>spaces</em>.</p> <p>You can use <a href="https://www.pylint.org/" rel="nofollow">https://www.pylint.org/</a> to detect them or if it something simple paste the code at <a href="http://pep8online.com" rel="nofollow...
1
2016-06-22T17:53:36Z
[ "python" ]
Timestamp Regex python (2016-06-22 07:55:35,232 )
37,975,052
<p>I am finding difficult to form a regex for the above timestamp pattern in python. I have to search for the timestamp that matches this pattern in a list in python .</p> <p>Eg, </p> <p>2016-06-22 07:55:35,232 [12] INFO </p> <p>In the above line i have to search 2016-06-22 07:55:35,232 .</p> <p>I have tried with t...
0
2016-06-22T17:50:54Z
37,975,279
<p>Your problem is the <code>$</code> sign at the end -- remove it from your regex. You do not get anything back because <code>$</code> (end of line) does not match <code>[12] INFO</code></p> <pre><code>&gt;&gt;&gt; re.findall("^\\d{4}[-]?\\d{1,2}[-]?\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}[,]?\\d{1,3}$", '2016-06-22 07:55...
1
2016-06-22T18:04:04Z
[ "python" ]
Timestamp Regex python (2016-06-22 07:55:35,232 )
37,975,052
<p>I am finding difficult to form a regex for the above timestamp pattern in python. I have to search for the timestamp that matches this pattern in a list in python .</p> <p>Eg, </p> <p>2016-06-22 07:55:35,232 [12] INFO </p> <p>In the above line i have to search 2016-06-22 07:55:35,232 .</p> <p>I have tried with t...
0
2016-06-22T17:50:54Z
37,975,391
<p>Encapsulating your regex with <code>^</code> and <code>$</code> ensures that the string will only ever be matched by your regex if the regex matches the entire string, since <code>^</code> signifies beginning of the string and <code>$</code> signifies the end. If you want it to be able to match anywhere, you should ...
0
2016-06-22T18:10:41Z
[ "python" ]
Timestamp Regex python (2016-06-22 07:55:35,232 )
37,975,052
<p>I am finding difficult to form a regex for the above timestamp pattern in python. I have to search for the timestamp that matches this pattern in a list in python .</p> <p>Eg, </p> <p>2016-06-22 07:55:35,232 [12] INFO </p> <p>In the above line i have to search 2016-06-22 07:55:35,232 .</p> <p>I have tried with t...
0
2016-06-22T17:50:54Z
37,976,420
<p>Your pattern works fine, but you are only matching at the end of string because of <code>$</code>.</p> <p>If you want to match just this:</p> <pre><code>2016-06-22 07:55:35,232 </code></pre> <p>You can use this regular expression.</p> <pre><code>(?P&lt;date&gt;\d{4}[-]?\d{1,2}[-]?\d{1,2} \d{1,2}:\d{1,2}:\d{1,2}[...
0
2016-06-22T19:10:24Z
[ "python" ]
Retrieve JSON key and value
37,975,065
<p>I am POSTing a .json object to my server with different keys attached.</p> <pre><code>ID, time, content </code></pre> <p>On my server I want to then wrap this again in another .json file with another APIs key and value formatting. </p> <p>So... I want to store the key and value for 'content' Currently i can obt...
-1
2016-06-22T17:51:55Z
37,975,257
<p>Your JSON_obj here is acting as a dictionary, so you can use Python's <code>items</code> (Python 3+) or <code>iteritems</code> (Python 2.7) functions:</p> <pre><code>for k,v in json_obj.iteritems(): foo = {k: v} # do something with foo </code></pre>
0
2016-06-22T18:02:55Z
[ "python", "json" ]
Retrieve JSON key and value
37,975,065
<p>I am POSTing a .json object to my server with different keys attached.</p> <pre><code>ID, time, content </code></pre> <p>On my server I want to then wrap this again in another .json file with another APIs key and value formatting. </p> <p>So... I want to store the key and value for 'content' Currently i can obt...
-1
2016-06-22T17:51:55Z
37,975,402
<p>Solved, thanks SuperSaiyan you triggered this thought. Just create a new dictionary:</p> <pre><code>content = json_obj['content'] test_obj = {'content':content} </code></pre> <p>Could also:</p> <pre><code>test_obj = {'content':json_obj['content']} </code></pre>
0
2016-06-22T18:11:19Z
[ "python", "json" ]
What is an elegant way to convert the result of [x for x in y] from list to a regular variable?
37,975,087
<p>What is an elegant way to convert the result of <code>[x for x in y]</code> from list to a regular variable?</p> <pre><code>result= [x for x in range(10) if x==7] </code></pre> <p>The result of the above will be <code>[7]</code>. I am now using <code>result=result[0]</code> but ...it does not look right :-)</p> <...
2
2016-06-22T17:53:12Z
37,975,132
<p>You can use <code>next</code> that retrieves the next object from the iterator. The parameter that goes within <code>next</code> is a <em><a href="https://wiki.python.org/moin/Generators" rel="nofollow">generator</a></em>. This allows saves you from fully constructing the list and then filtering for <code>7</code>. ...
2
2016-06-22T17:55:42Z
[ "python" ]
What is an elegant way to convert the result of [x for x in y] from list to a regular variable?
37,975,087
<p>What is an elegant way to convert the result of <code>[x for x in y]</code> from list to a regular variable?</p> <pre><code>result= [x for x in range(10) if x==7] </code></pre> <p>The result of the above will be <code>[7]</code>. I am now using <code>result=result[0]</code> but ...it does not look right :-)</p> <...
2
2016-06-22T17:53:12Z
37,975,137
<p>You have a list comprehension on the right hand side. It evaluates to a list.</p> <p>You want to pick up the first element (which is perhaps the only element for the kind of problems you are trying to solve) from it, so index the 0-th element in the list returned by the list comprehension, just like you would do it...
2
2016-06-22T17:55:49Z
[ "python" ]
How to manipulate user uploaded files in django without saving it?
37,975,156
<p>I'm making an app which gets data from a csv file and generates a graph using it. All files contains the same structure. I've decided I'm not going to store the files, because of server prices. I'm going to use heroku for now to host this app. It's a Django app. I'm wondering how I could only open the file and extra...
1
2016-06-22T17:57:00Z
37,975,449
<p>I'll assume you're using <code>Django 1.9</code> (if not, please update your question to reflect your version of Django).</p> <p>First, using the HTML <code>&lt;form&gt;</code> tag, you'll want to include <code>enctype="multipart/form-data"</code> as an attribute.</p> <p>Assuming you'll name your <code>&lt;input&g...
2
2016-06-22T18:14:05Z
[ "python", "django", "heroku" ]
How do I keep the test size constant in cross validation using train_test_split?
37,975,184
<p>I am working with a matrix <code>X</code> and a label for each row in this matrix <code>y</code>. <code>X</code> is defined as: </p> <pre><code>df = pd.read_csv("./data/svm_matrix_0.csv", sep=',',header=None, encoding="ISO-8859-1") df2 = df.convert_objects(convert_numeric=True) X = df_2.values </code></pre> <p><c...
2
2016-06-22T17:58:49Z
37,976,869
<p>What you can do is separate the test data first ...</p> <pre><code>X_train_prev, X_test_prev, y_train_prev, y_test_prev = train_test_split(X, y, test_size = 0.2) </code></pre> <p>Now run the for loop changing the train size but testing on the **previous test data*</p> <p>like this - </p> <pre><code>array = [0.1,...
1
2016-06-22T19:39:13Z
[ "python", "csv", "for-loop", "scikit-learn", "svm" ]
How should I approach patching a Plotly syntax error under Python2.6?
37,975,192
<p>I am forced to use Python2.6 for a CGI project and am attempting to use Plotly to create histograms. </p> <p>Here is the function that creates my histogram figure:</p> <pre><code>def getHistogram(self, dataset_uuid, target, title, xaxisTitle, yaxisTitle): maxThreshold = self.getMaxThreshold(dataset_uuid, targe...
0
2016-06-22T17:59:16Z
37,976,424
<p>I solved this by installing an older version of Plotly, specifically version 1.6.7 from <a href="https://github.com/plotly/plotly.py/releases" rel="nofollow">https://github.com/plotly/plotly.py/releases</a>.</p>
0
2016-06-22T19:10:45Z
[ "python", "python-2.6", "plotly" ]
Python: accept unicode strings as regular strings in doctests
37,975,197
<p>Writing doctests for a method that abbreviates a dictionary by searching for a passed key word in the keys of the original dictionary, and returning the new, abbreviated dictionary. My docstring looks as follows:</p> <pre><code>def abbreviate_dict(key_word, original_dict): """ &gt;&gt;&gt; orig_dict = {appl...
1
2016-06-22T17:59:25Z
37,996,837
<p>You can set the <code>ALLOW_UNICODE</code> flag (either globally or per test), see the <a href="http://pytest.org/latest/doctest.html" rel="nofollow">pytest docs</a> for details.</p> <p>Example:</p> <pre><code>[pytest] doctest_optionflags = ALLOW_UNICODE </code></pre> <p>or</p> <pre><code># content of example.rs...
2
2016-06-23T16:13:38Z
[ "python", "python-2.7", "testing", "py.test", "doctest" ]
why not saved foreign key value in django
37,975,217
<p>I have a django project,that use Sqlite db. and have two simple table.</p> <p>Person :</p> <ol> <li>MeliCode</li> <li>FName</li> </ol> <p>Mark : </p> <ol> <li>PersonId -> Foreign key</li> <li>Grade</li> </ol> <p>this is my models code : </p> <pre><code>&lt;code&gt; from django.db import models class Person(m...
-1
2016-06-22T18:00:27Z
37,977,642
<p>The cause of the error is because you've provided a field with a different name to the actual field in your model</p> <pre><code>class Marks(forms.ModelForm): person = forms.ModelMultipleChoiceField(Person.objects.all(), label='Name') grade = forms.CharField(label='Mark') </code></pre> <p><code>person</cod...
0
2016-06-22T20:26:20Z
[ "python", "django", "django-models" ]
How to handle "UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' "?
37,975,221
<p>I am trying to access a table on a SQL Server using the Python 2.7 module adodbapi, and print certain information to the command prompt (Windows). Here is my original code snippet:</p> <pre><code>query_str = "SELECT id, headline, state, severity FROM GPS3.Defect ORDER BY id" cur.execute(query_str) dr_data = cur.fe...
0
2016-06-22T18:00:43Z
37,980,766
<p>Your error message does not agree with the statement that you are printing on a Windows command prompt. It does not default to the <code>ascii</code> codec. On US Windows, it defaults to <code>cp437</code>.</p> <p>You can just print Unicode to the console without trying to encode it. Python will encode the Unico...
0
2016-06-23T01:20:23Z
[ "python", "python-2.7", "unicode", "encoding", "utf-8" ]
How to send scraped data through reddit bot
37,975,255
<p>So I've got this bot that I want to use to reply with the box score of the mets game anytime someone says "mets score" on a specific subreddit. This is my first python project and I plan on using it on a dummy subreddit I created as a learning tool. I'm having trouble sending the scores from the website I scraped th...
0
2016-06-22T18:02:52Z
37,977,787
<p>I think I'll just put you out of your misery ;). There are multiple issues with your code snippet:</p> <pre><code>comment.reply('heres the score to last nights mets game...' scores()) </code></pre> <p>The <code>.reply()</code> method requires a string or an object that can have a good enough representation as a st...
0
2016-06-22T20:34:02Z
[ "python", "web-scraping", "bots", "reddit" ]
Beautiful Soup table scraping only scrapes some of the time
37,975,348
<p>I'm working to extract a specific table out of a couple documents, that holds the signatures of the directors, for a couple companies using BeautifulSoup4. My program finds a heading above the section that holds the tables, then counts two tables down from that spot to find the correct table (The documents being gov...
1
2016-06-22T18:08:00Z
37,975,522
<p>The problem is the <code>&amp;nbsp;</code> between the <code>Section</code> and <code>13</code>:</p> <pre><code>&lt;font size="2"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Pursuant to the requirements of Section&amp;nbsp;13 or 15(d) of the Securities Exchange Act of 1934, Ab...
2
2016-06-22T18:17:41Z
[ "python", "web-scraping", "beautifulsoup", "bs4", "edgar" ]
Get all the values that start with a number in a data frame
37,975,452
<p>From a column (company_name) in a data frame df1, I want to get all the values which starts with a number. I am writing the code as - </p> <pre><code>df2 = df1[df1.company_name.str[0].isdigit()].copy() </code></pre> <p>I receive the following error - </p> <blockquote> <p>AttributeError: 'Series' object has no a...
1
2016-06-22T18:14:07Z
37,975,481
<p>You need add <code>str</code>, because <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.isdigit.html" rel="nofollow"><code>str.isdigit</code></a>. Also I think <code>copy()</code> is not necessary:</p> <pre><code>df2 = df1[df1.company_name.str[0].str.isdigit()] </code></pre> <p>Samp...
1
2016-06-22T18:15:33Z
[ "python", "string", "pandas", "filter", "dataframe" ]
program that generates addition problems randomly and displays them to the user
37,975,518
<p>I'm trying to write a program that generates random numbers, asks user to guess addition output and when the user fails to guess output correctly then it should print the total number of guesses performed. my code is as follows. Any help is highly appreciated.</p> <pre><code>from random import randint a = randint(0...
-7
2016-06-22T18:17:16Z
37,975,695
<p>For one, your indentation is messed up. And you seem to have multiple different versions of python code- <code>print()</code> as a function is python3, <code>print</code> as a statement is python2. Also python3 uses <code>input()</code> instead of <code>raw_input()</code>. In this answer, I'll be assuming python3 an...
0
2016-06-22T18:27:49Z
[ "python" ]
NoReverseMatch: Unable to set named group in URL in Django
37,975,633
<p>I am getting this error for going to the url : <code>http://127.0.0.1:9000/mypolls/anyerror</code></p> <pre><code>NoReverseMatch at /mypolls/anyerror Reverse for 'mypolls' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['mypolls/(?P&lt;error_message&gt;.*)$'] </code></pre> <p>My urls...
1
2016-06-22T18:24:09Z
37,976,301
<p>The problem was in base.html. I did not give the keyword argument in url for mypolls in base.html. Now I have set the url as: </p> <pre><code>{% url "mypolls" error_message="" %} </code></pre> <p>and it is working fine. Thanks @Alasdair and everyone.</p>
1
2016-06-22T19:02:50Z
[ "python", "regex", "django" ]
Replacing data from dataframe with data from another dataframe
37,975,655
<p>I currently have a dataframe and a csv file.</p> <p>In the csv file, I have about 30 columns, including one column of ZIP codes (e.g., "10001", "08983", "85321"). CSV is 3400 rows x 30 columns.</p> <p>In the dataframe, I have a column of ZIP codes and a matching column of scores:</p> <pre><code>zipcode score 997...
1
2016-06-22T18:25:13Z
37,975,787
<p>Have you tried loading the csv into a list and then looping through the items in the list.</p> <pre><code>import csv sFile = "myfile.csv" with open(sFile, 'rb') as f: reader = csv.reader(f) yourList = list(reader) for item in yourList: #search and replace based on each item </code></pre> <p>You can al...
0
2016-06-22T18:33:06Z
[ "python", "python-2.7", "csv", "pandas", "dataframe" ]
Throttling connection speed in Automated test in El Capitan?
37,975,672
<p>So I was planning on writing an automated test using python-selenium(really webdriver) that uses a <a href="http://stackoverflow.com/questions/325463/launch-a-shell-command-with-in-a-python-script-wait-for-the-termination-and-ret">subprocess</a> to throttle the connection speed before a suite of tests. I found this ...
0
2016-06-22T18:26:26Z
38,992,051
<p>I was able to throttle network using network link conditioner. To install network link conditioner, you need to get Hardware IO Tools. More details are available in <a href="http://stackoverflow.com/questions/9659382/installing-apples-network-link-conditioner-tool">Installing Apples Network Link Conditioner Tool</a>...
1
2016-08-17T08:50:56Z
[ "python", "shell", "automated-tests", "osx-elcapitan", "packets" ]
Python: how to find values in another dataframe?
37,975,673
<p>I have two DataFrames, <code>df1</code>: </p> <pre><code>df1.head(6) t day node s e i r sm em im 491325 100 0 0 9 12 21 95 2 4 17 491326 100 0 1 8 16 17 140 7 5 40 491327 100 0 2 8 9 17 143 0 4 38 491328 100 0 3 ...
1
2016-06-22T18:26:29Z
37,975,768
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a>, first select in <code>df1</code> only columns <code>r</code> and <code>node</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.ht...
0
2016-06-22T18:32:06Z
[ "python", "pandas", "merge" ]
Python: how to find values in another dataframe?
37,975,673
<p>I have two DataFrames, <code>df1</code>: </p> <pre><code>df1.head(6) t day node s e i r sm em im 491325 100 0 0 9 12 21 95 2 4 17 491326 100 0 1 8 16 17 140 7 5 40 491327 100 0 2 8 9 17 143 0 4 38 491328 100 0 3 ...
1
2016-06-22T18:26:29Z
37,975,785
<p>You can use merge, but first you have to delete the dummy r column from df2:</p> <pre><code>In [11]: del df2["r"] In [12]: df2.merge(df1[["r", "node"]]) Out[12]: node original lat lon r 0 0 50405 1.299033 103.83828 95 1 1 50404 1.299033 103.83828 140 2 2 50405 1....
1
2016-06-22T18:33:03Z
[ "python", "pandas", "merge" ]
How to add an extra row to pandas dataframe at index 2 without overwriting existing index
37,975,694
<p>Before writing my output dataframe to an excel file, I need to add an extra row to my dataframe. Below is my example dataframe:</p> <pre><code> ----------------------------- | Col1 | Col2 | Col3 | Col4 | ----------------------------- 0 | CA1 | CB1 | CC2 | CD1 | 1 | CA5 | CB5 | CC5 | CD5 | 2 ...
-2
2016-06-22T18:27:46Z
37,976,727
<p>Will this work for you? First, convert <code>mydict</code> to a dataframe and then use <code>pd.concat</code></p> <pre><code>mydict = mydict= {'Col1': 'P', 'Col2': 'Q', 'Col3': 'R', 'Col4': 'S'} df1 = pd.DataFrame(data=mydict, index=[0]) data = np.array([['CA1', 'CB1', 'CC2', 'CD1'], ['CA5', 'CB5'...
0
2016-06-22T19:29:53Z
[ "python", "pandas" ]
Reversing ctrl+leftclick in Spyder
37,975,744
<p>I have a very simple question. I started using Spyder and have used ctrl + LeftClick to inspect the source code of a class, method, function, etc. </p> <p>How do I "go back" once I have ctrl+LeftClick-ed? I've looked around a bit but have not found this simple thing (for example <a href="http://stackoverflow.com/qu...
1
2016-06-22T18:31:09Z
38,013,361
<p>This should work I have tried it :</p> <blockquote> <p>Press <code>Ctrl + W</code> </p> </blockquote>
0
2016-06-24T12:21:13Z
[ "python", "spyder" ]
Maximum number of bind parameters in SQLAlchemy
37,975,897
<p>I have a question about the maximum number of bind parameters that can be passed to a query I wish to execute using SQLAlchemy.</p> <p>My query is a set of SELECT statements all grouped together via UNION (about 100+) and each select statement will be passed a different value. The reason why I need to do this via a...
0
2016-06-22T18:39:12Z
38,109,565
<p>I was able to achieve my goal by using a VALUES list in Postgresql:</p> <pre><code>SELECT col1, col2, col3 FROM TABLE a, VALUES(('x1','x2','x3'), ('y1','y2','y3'), ('z1','z2','z3')) AS t(col1, col2, col3) WHERE a.col1=t.col1 AND lower(a.col2) % t.name </code></pre>
0
2016-06-29T20:34:37Z
[ "python", "postgresql", "sqlalchemy" ]
How to use python to query database in parallel
37,975,904
<p>I have two functions which I use to query database. Assuming two separate queries, how to run these in parallel to query same database, and also wait for both results to return before continuing the execution of the rest of the code?</p> <pre><code>def query1(param1, param2): result = None logging.info("Con...
1
2016-06-22T18:39:31Z
37,976,284
<p>Here is a multi-threaded code that does what you're trying to accomplish:</p> <pre><code>from threading import Thread, Lock class DatabaseWorker(Thread): __lock = Lock() def __init__(self, db, query, result_queue): Thread.__init__(self) self.db = db self.query = query self....
0
2016-06-22T19:01:28Z
[ "python", "database", "parallel-processing" ]
Python importing from MS Access: "Invalid connection string attribute"
37,975,909
<p>I am trying to import data from a MS Access database</p> <pre><code>import pyodbc connStr = """ import pypyodbc Driver={Microsoft Access Driver (*.mdb, *.accdb)} DBQ = C:\\Users\\haesh\\Desktop\\Comp Sci CC\\Database1.accdb; """ cnxn = pyodbc.connect(connStr) </code></pre> <p>However I get this error </p> <pre...
1
2016-06-22T18:39:38Z
37,976,196
<p>The <code>import pypyodbc</code> does not belong in the ODBC connection string. Also, connection strings can be confused by line breaks and white space. You should have better luck with this:</p> <pre class="lang-python prettyprint-override"><code>connStr = ( r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};...
1
2016-06-22T18:56:42Z
[ "python", "ms-access", "python-3.3" ]
How to focus view on QLabel
37,975,912
<p>I want to find QLabel with specific text and focus view on it. Finding widget with desired text is easy, but I couldn't figure out how to focus view on it. The code so far looks like this:</p> <pre><code>import sys from PySide import QtCore, QtGui class MainWindow(QtGui.QMainWindow): def __init__(self): ...
1
2016-06-22T18:39:46Z
37,979,813
<p>You can use <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qscrollarea.html#ensureWidgetVisible" rel="nofollow"><code>ensureWidgetVisible()</code></a></p> <pre><code>self.scroll.ensureWidgetVisible(w) </code></pre>
0
2016-06-22T23:22:40Z
[ "python", "pyside" ]
Split complicated strings in Python dynamically
37,975,964
<p>I have been having difficulty with organizing a function that will handle strings in the manner I want. I have looked into a handful previous questions <a href="http://stackoverflow.com/questions/4982531/how-do-i-split-a-comma-delimited-string-in-python-except-for-the-commas-that-are">1</a>, <a href="http://stackove...
4
2016-06-22T18:43:09Z
37,976,086
<p>Use <a href="https://docs.python.org/2/library/ast.html#ast.literal_eval"><code>ast</code>'s <code>literal_eval</code></a>!</p> <pre><code>from ast import literal_eval s = """('Vdfbr76','gsdf','gsfd','',NULL), ('Vkdfb23l','gsfd','gsfg','ggg@df.gf',NULL), ('4asg0124e','Lead Actor/SFX MUA/Prop designer','John Smith'...
8
2016-06-22T18:50:50Z
[ "python", "regex", "string", "split" ]
Traceback error from python selenium script (Works intermittently)
37,976,045
<p>I have written a selenium script in Python to automate posting to a particular website. I have run it in the past, and it has worked flawlessly. However, i went to run the script and am now suddenly receiving the below. I believe it is a problem with the module loading somehow. In addition sometimes firefox will o...
1
2016-06-22T18:48:16Z
37,980,385
<ol> <li>try run FF in console, with same user and path which you use for run python script</li> <li>setup log_file for webdriver</li> <li>maybe better use PhantomJS driver?</li> </ol>
0
2016-06-23T00:31:43Z
[ "python", "linux", "selenium", "webdriver" ]
convert to multiindex dataframe w/horizontal display and rename columns
37,976,155
<p>let's say i have the following code:</p> <pre><code>df1 = pd.DataFrame(np.random.randn(10,4), columns=['A','B','C','D']) df1['dataframe'] = 'df1' df2 = pd.DataFrame(np.random.randn(10,4), columns=['A','B','C','D']) df2['dataframe'] = 'df2' df = pd.concat([df1, df2]) df.reset_index().set_index(['dataframe','index'])...
1
2016-06-22T18:54:29Z
37,980,898
<p>OK, from that starting point you firstly want to call <code>reset_index</code> again like so:</p> <pre><code>df.reset_index(drop=True) </code></pre> <p>Now you should have only one level in the index, and the columns <code>A</code>, <code>B</code>, <code>C</code>, <code>D</code>, and <code>dataframe</code>.</p> <...
0
2016-06-23T01:37:07Z
[ "python", "python-2.7", "pandas", "dataframe", "multi-index" ]
convert to multiindex dataframe w/horizontal display and rename columns
37,976,155
<p>let's say i have the following code:</p> <pre><code>df1 = pd.DataFrame(np.random.randn(10,4), columns=['A','B','C','D']) df1['dataframe'] = 'df1' df2 = pd.DataFrame(np.random.randn(10,4), columns=['A','B','C','D']) df2['dataframe'] = 'df2' df = pd.concat([df1, df2]) df.reset_index().set_index(['dataframe','index'])...
1
2016-06-22T18:54:29Z
37,993,000
<p>Using the <code>dataframe</code> generated by the original code snippet, we can create two separate <code>dataframes</code> based on which <code>dataframe</code> they belong to, then drop the <code>"dataframe"</code> column from both. We then assign the new column names to each of the <code>columns</code> properties...
0
2016-06-23T13:25:31Z
[ "python", "python-2.7", "pandas", "dataframe", "multi-index" ]
how to insert .txt into python to define a keyword list
37,976,160
<p>I would like to insert a .txt file such as notepad to define a keyword list. For example my current code is something like this :</p> <pre><code>key_word_list = ['pig,dog,cat'] </code></pre> <p>My real list is much bigger and it would be a lot more organised to have it in a .txt file </p> <p>i would like to know ...
-3
2016-06-22T18:54:49Z
37,976,270
<p>It is possible. You would use something like this:</p> <pre><code>with open('fileName.txt', 'r') as f: yourList = [yourList.strip() for yourList in f] </code></pre> <p>Then you could print using print(yourList)</p>
0
2016-06-22T19:00:29Z
[ "python" ]
Pass info from plot to function
37,976,235
<p>I want to write interactive simulation using graph-tool. What I would like to do is first to visualize the graph, then pick nodes as an input for later actual simulation. How do I pass information from plot to function?</p> <p>What I did so far - I looked through documentation and examples which do not provide such...
1
2016-06-22T18:58:55Z
37,977,088
<p>If you invoke <a href="https://graph-tool.skewed.de/static/doc/draw.html#graph_tool.draw.graph_draw" rel="nofollow"><code>graph_draw</code></a> with <code>output</code> parameter set to <code>None</code> (which is the default), it returns a: </p> <blockquote> <p>Boolean-valued vertex property map marking the vert...
2
2016-06-22T19:52:42Z
[ "python", "graph-tool" ]
saving modified screens in python/pygame for later use
37,976,237
<p>When using python and pygame: after loading the screen with the background image and blitting new objects (Text, circles, rectangles, etc.), is there a way to save the modified screen so as to be recalled later in the program? Specifically, I am setting the background and blitting new objects and would like to save...
1
2016-06-22T18:59:02Z
37,977,559
<p>Blitting works both ways, meaning you can blit something onto the display screen, but you can also blit the screen onto another surface. So simply make a new surface the same size of your display surface and blit the screen onto that surface for later use.</p>
0
2016-06-22T20:21:19Z
[ "python", "background", "pygame", "screen", "sprite" ]
saving modified screens in python/pygame for later use
37,976,237
<p>When using python and pygame: after loading the screen with the background image and blitting new objects (Text, circles, rectangles, etc.), is there a way to save the modified screen so as to be recalled later in the program? Specifically, I am setting the background and blitting new objects and would like to save...
1
2016-06-22T18:59:02Z
38,003,221
<p>found a solution and it works better than I expected:</p> <p>after blitted my raw background onto my surface and then adding numerous circles, rectangles and text to make an image with multiple dial, gauges and labels I ran the following:</p> <pre><code>pygame.display.update() window = pygame.display.set_mode((800...
0
2016-06-23T22:58:04Z
[ "python", "background", "pygame", "screen", "sprite" ]
Rendering/Raising A Validation Error on an HTML Template in Django
37,976,380
<p>I'm attempting to list a validation error on my HTML template if the form on that template isn't properly submitted. My forms.py file includes a function (clean_email) that will catch any string that's entered that doesn't include an "@" symbol, and it actually works. Therefore, any form that I attempt to submit wit...
1
2016-06-22T19:07:55Z
37,976,559
<p>Apart from using models.EmailField (which you should be doing) you need to change <code>{{ contactform.errors }}</code> to <code>{{ contactform.email.errors }}</code></p>
1
2016-06-22T19:20:02Z
[ "python", "html", "django", "forms" ]
Rendering/Raising A Validation Error on an HTML Template in Django
37,976,380
<p>I'm attempting to list a validation error on my HTML template if the form on that template isn't properly submitted. My forms.py file includes a function (clean_email) that will catch any string that's entered that doesn't include an "@" symbol, and it actually works. Therefore, any form that I attempt to submit wit...
1
2016-06-22T19:07:55Z
37,976,983
<p>I figured it out. Before the validation error could even be raised, I was attempting to generate a brand new form. </p> <pre><code>contactform = ContactForm() </code></pre> <p>^That code in my views.py file would make it so an entirely new form was created on my HTML template. Once I got rid of it, everything work...
1
2016-06-22T19:46:56Z
[ "python", "html", "django", "forms" ]
Replacing word in CSV without knowing it's position with python
37,976,523
<p>I'm trying to find occurrences of the word NIL inside several huge CSV files and replace them for an empty string. I've looked up solutions but the one <strong>I tried doesn't work because the line is a list</strong> and the other ones I've found seem to be with specific position but I can't know where the NIL will ...
1
2016-06-22T19:17:19Z
37,976,606
<p>Use a try/except if <em>Nil</em> is not in every row getting the index and just assign to an empty string:</p> <pre><code>try: row[row.index("NIL")] = "" except IndexError: pass </code></pre> <p><em>index</em> will find where Nil is in your list, once you have that the assignment will replace it:</p> <p...
2
2016-06-22T19:22:36Z
[ "python", "csv" ]
Python UDP Sockets with Multiple Interfaces
37,976,551
<p>I'm Writing a script in python2.7 on a windows XP machine. The machine is connected to multiple networks using different network cards.</p> <p>I'm running into an issue where I've bound a UDP Socket to a specific interface(I understand that you can accomplish this in windows by just providing the network cards exis...
3
2016-06-22T19:19:34Z
38,129,891
<p>Given the output from "route", it looks like you're 10.10.10.12 and 10.31.9.0 interfaces have been configured with overlapping subnets. The OS is choosing to use 10.10.10.12 for all 10.x.x.x addresses as it's the first rule that applies.</p> <p>Having overlapping subnets is normally a network configuration error: i...
0
2016-06-30T17:37:01Z
[ "python", "sockets", "networking", "udp", "windows-xp" ]
Python UDP Sockets with Multiple Interfaces
37,976,551
<p>I'm Writing a script in python2.7 on a windows XP machine. The machine is connected to multiple networks using different network cards.</p> <p>I'm running into an issue where I've bound a UDP Socket to a specific interface(I understand that you can accomplish this in windows by just providing the network cards exis...
3
2016-06-22T19:19:34Z
38,543,172
<p>Turns out, the Packets that my "server" was sending where not IP kosher. so they where getting rejected at the network and transport layers. Solution was to not use python socket class, but instead communicate directly to OSI-L2 using <a href="https://www.winpcap.org/" rel="nofollow">winpcap</a> and ctypes</p>
0
2016-07-23T15:03:24Z
[ "python", "sockets", "networking", "udp", "windows-xp" ]
Simple plots of eigenvectors for sklearn.decomposition.PCA
37,976,564
<p>I'm trying to understand how <code>Principal Component Analysis</code> works and I am testing it on the <code>sklearn.datasets.load_iris</code> dataset. I understand how each step works (e.g. standardize the data, covariance, eigendecomposition, sort for highest eigenvalue, transform original data to new axis using...
1
2016-06-22T19:20:15Z
37,977,244
<p>I think you are asking the wrong question. The eigenvectors ARE the the principal components (PC1, PC2, etc.). So plotting the eigenvectors in the [PC1, PC2, PC3] 3D plot is simply plotting the three orthogonal axes of that plot.</p> <p>You probably want to visualize how the eigenvectors look in your original coord...
0
2016-06-22T20:02:50Z
[ "python", "matplotlib", "machine-learning", "scikit-learn", "pca" ]
Pandas Pivot table - incremental column names
37,976,592
<p>I am trying to use Pandas pivot_table to move line items on my receipts as columns, leaving only one row per receipt. My main challenge is to name my new columns counting numbers as needed and fill with NaNs. </p> <p>I am trying to make this:</p> <pre><code>customer_id receipt_id item_id 01 100 420 ...
2
2016-06-22T19:21:42Z
37,976,689
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow"><code>cumcount</code></a> for creating column names and to remove <code>[]</code> from parameter <code>values</code>:</p> <pre><code>df['g'] = df.groupby(['customer_id','receipt_...
1
2016-06-22T19:27:37Z
[ "python", "pandas", "dataframe", "pivot-table", "dynamic-columns" ]
Pandas Pivot table - incremental column names
37,976,592
<p>I am trying to use Pandas pivot_table to move line items on my receipts as columns, leaving only one row per receipt. My main challenge is to name my new columns counting numbers as needed and fill with NaNs. </p> <p>I am trying to make this:</p> <pre><code>customer_id receipt_id item_id 01 100 420 ...
2
2016-06-22T19:21:42Z
37,976,803
<p>alternative solution (it might be slower - i didn't test timing):</p> <pre><code>In [243]: df.groupby(['customer_id','receipt_id'])['item_id'].apply(list).apply(pd.Series).reset_index() Out[243]: customer_id receipt_id 0 1 2 3 0 1 100 420.0 NaN NaN NaN 1 ...
1
2016-06-22T19:34:53Z
[ "python", "pandas", "dataframe", "pivot-table", "dynamic-columns" ]
Python read .txt File -> list
37,976,716
<p>I have a .txt File and I want to get the values in a list. The format of the txt file should be:</p> <pre><code>value0,timestamp0 value1,timestamp1 ... ... ... </code></pre> <p>In the end I want to get a list with </p> <pre><code>[[value0,timestamp0],[value1,timestamp1],.....] </code></pre> <p>I know it's easy t...
1
2016-06-22T19:29:09Z
37,976,895
<p>I coded a quickie using your example, and not using 13 but len("timestamp") so you can adapt</p> <pre><code>instr = "value,timestampvalue2,timestampvalue3,timestampvalue4,timestamp" previous_i = 0 for i,c in enumerate(instr): if c==",": next_i = i+len("timestamp")+1 print(instr[previous_i:next_...
0
2016-06-22T19:41:14Z
[ "python", "list", "file", "python-3.x", "readfile" ]
Python read .txt File -> list
37,976,716
<p>I have a .txt File and I want to get the values in a list. The format of the txt file should be:</p> <pre><code>value0,timestamp0 value1,timestamp1 ... ... ... </code></pre> <p>In the end I want to get a list with </p> <pre><code>[[value0,timestamp0],[value1,timestamp1],.....] </code></pre> <p>I know it's easy t...
1
2016-06-22T19:29:09Z
37,976,898
<p>You will have to strip the last , but you can insert a comma after every 13 chars following a comma:</p> <pre><code>import re s = "-0.1351197,1466615025472-0.25672746,1466615025501-0.3661744,1466615025531-0.4646‌​7665,1466615025561-0.5533287,1466615025591-0.63311553,1466615025621-0.7049236,146‌​6615025652-0...
1
2016-06-22T19:41:26Z
[ "python", "list", "file", "python-3.x", "readfile" ]
Python read .txt File -> list
37,976,716
<p>I have a .txt File and I want to get the values in a list. The format of the txt file should be:</p> <pre><code>value0,timestamp0 value1,timestamp1 ... ... ... </code></pre> <p>In the end I want to get a list with </p> <pre><code>[[value0,timestamp0],[value1,timestamp1],.....] </code></pre> <p>I know it's easy t...
1
2016-06-22T19:29:09Z
37,977,069
<pre><code>import re input = "value0,0123456789012value1,0123456789012value2,0123456789012value3" for (line, value, timestamp) in re.findall("(([^,]+),(.{13}))", input): print value, timestamp </code></pre>
1
2016-06-22T19:51:36Z
[ "python", "list", "file", "python-3.x", "readfile" ]
Python read .txt File -> list
37,976,716
<p>I have a .txt File and I want to get the values in a list. The format of the txt file should be:</p> <pre><code>value0,timestamp0 value1,timestamp1 ... ... ... </code></pre> <p>In the end I want to get a list with </p> <pre><code>[[value0,timestamp0],[value1,timestamp1],.....] </code></pre> <p>I know it's easy t...
1
2016-06-22T19:29:09Z
37,977,258
<p>I think you could do something like this:</p> <pre><code>direction = [] for line in open(filename): list = line.split(',') v = list[0] for s in list[1:]: t = s[:13] direction.append([float(v), long(t)]) v = s[13:] </code></pre> <p>If you're using python 3.X, then the long functi...
0
2016-06-22T20:03:48Z
[ "python", "list", "file", "python-3.x", "readfile" ]
How to conditionally update DataFrame column in Pandas based on list
37,976,823
<p>Supposed I have a dataframe with one column:</p> <pre><code>df = pd.DataFrame(np.random.randint(0,9,size=(100, 1)), columns=['number']) </code></pre> <p>I have two lists, one list containing even numbers, the other containing odd numbers.</p> <pre><code>odd_numbers = [1,3,5,7,9] even_numbers = [0,2,4,6,8] </code>...
2
2016-06-22T19:36:12Z
37,976,890
<p>I think you can use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a>:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(np.random.randint(0,9,size=(100, 1)), columns=['number']) df['odd_or_even'] = np.where(df.n...
0
2016-06-22T19:40:55Z
[ "python", "list", "pandas", "dataframe", "contains" ]
How to conditionally update DataFrame column in Pandas based on list
37,976,823
<p>Supposed I have a dataframe with one column:</p> <pre><code>df = pd.DataFrame(np.random.randint(0,9,size=(100, 1)), columns=['number']) </code></pre> <p>I have two lists, one list containing even numbers, the other containing odd numbers.</p> <pre><code>odd_numbers = [1,3,5,7,9] even_numbers = [0,2,4,6,8] </code>...
2
2016-06-22T19:36:12Z
37,977,132
<p>A <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow">map</a> version:</p> <p>First, create a dictionary:</p> <pre><code>d = {**{o: "odd" for o in odd_numbers}, **{e: "even" for e in even_numbers}} </code></pre> <p>Then use map on the series:</p> <pre><code>df['o...
0
2016-06-22T19:55:05Z
[ "python", "list", "pandas", "dataframe", "contains" ]
Improve recursive algorithm for finite products of primes
37,976,952
<p>From the book How to Read and Do Proofs by Daniel Solow, I took the following problem:</p> <blockquote> <p>Any integer n >= 2 can be expressed as a finite product of primes.</p> </blockquote> <p>After looking at the proof by induction in the book, I tried then to implement an algorithm to verify it:</p> <pre><c...
1
2016-06-22T19:44:28Z
37,977,171
<p>To remove the list, simply make it an in-line construction:</p> <pre><code>def products(n): if n == 2 or fermat(n): return [n] else: num = first_prime_divisor(n, 2) return products(n//num) + [num] </code></pre> <p>From here, the main problem is the inefficiency of your recursion; yo...
0
2016-06-22T19:58:36Z
[ "python", "recursion", "induction" ]
Block Scoping in python - is it similar to javascript hoisting when inside a function?
37,976,957
<p>I am currently trying to understand this piece of code in python</p> <pre><code>def foo(a): if a==12: var = "Same" else: var = "different" </code></pre> <p>I read and understand the fact that python does not support block based scoping. So everything created inside a function (whether inside a loop or ...
4
2016-06-22T19:44:48Z
37,977,312
<p>You got it. Any name assigned inside a function that isn't explicitly declared with <code>global</code> (with Py3 adding <code>nonlocal</code> to indicate it's not in local scope, but to look in wrapping scopes rather than jumping straight to global scope) is a local variable from the beginning of the function (it h...
2
2016-06-22T20:07:25Z
[ "javascript", "python" ]
Saving a Pandas DataFrame to a JSON string
37,976,996
<p>I realize that this may seem like a question that has already been asked here, but none of the solutions seem to work. I start out with a dictionary that looks something along the line of this:</p> <p><code>{'2016-05-08': 1, '2016-05-09': nan, '2016-05-05': nan, '2016-05-06': nan, '2016-05-07': nan, '2016-05-11': n...
1
2016-06-22T19:47:49Z
37,977,113
<p>If your summary columns give you the data you expect, add the columns to the dataframe. </p> <p>Try</p> <pre><code>df['std'] = pd.Series(df.std(axis=1), index=df.index) df['mean'] = pd.Series(df.mean(axis=1), index=df.index) </code></pre> <p>Then export to JSON. </p> <p>Edit: ok, I see that you see it works ...
1
2016-06-22T19:54:17Z
[ "python", "json", "pandas", "dataframe" ]
Access several columns in an array in Python
37,977,013
<p>I'm new to python and numpy. Suppose I have an array <code>A = np.random.rand(10,100)</code> , how do i access some of its columns easily?</p> <p>In <code>Matlab</code> I would write something like <code>B = A(:,[2,4,6:10,50:80])</code>. What is the equivalent of this line of code in Python?</p> <p>I've looked at ...
2
2016-06-22T19:48:46Z
37,977,570
<p>As <code>Benjamin</code> suggested, <code>np.r_</code> handles an expression like this nicely</p> <pre><code>In [1329]: np.r_[2,4,6:10,50:80] Out[1329]: array([ 2, 4, 6, 7, 8, 9, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 7...
2
2016-06-22T20:21:47Z
[ "python", "arrays", "numpy" ]
How can I delete an specific row and column in a list?
37,977,023
<p>I need some tips. I have a square list "y" ("y" has a nxn size). This is an example:</p> <pre><code>y=[[20,30,35,40], [10,25,55,45], [15,39,19,59], [25,35,24,17]] </code></pre> <p>I have another list "x"("x" has a nx2 size).This is an example:</p> <pre><code>x=[[1,1] [2,0] [3,0] [4,1]] </code></...
0
2016-06-22T19:49:06Z
38,028,727
<p>The function</p> <pre><code>def remove(a,i,j): return [row[:j] + row[j+1:] for k,row in enumerate(a) if k != i] </code></pre> <p>answers your stated question ("how can I delete a specific row and column from a list"), though it is still obscure exactly which rows and columns you want to remove.</p> <p>In the ...
1
2016-06-25T12:53:17Z
[ "python", "list" ]
Pandas: Set first 2 hours of every group to NaN
37,977,118
<p>I am trying to clean my data by setting 'value' to NaN for the first 2 hours of every 'state' group.</p> <p>My dataframe looks like this:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; &gt;&gt;&gt; rng = pd.date_range('1/1/2016', periods=6, freq='H') &gt;&gt;&gt; &gt...
1
2016-06-22T19:54:24Z
37,977,220
<p>Find all <code>indexes</code> by first <code>2H</code>, then change <code>index</code> to <code>Multiindex</code>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.swaplevel.html" rel="nofollow"><code>swaplevel</code></a> for matching <a href="http://pandas.pydata.org/pandas-docs/stabl...
1
2016-06-22T20:01:07Z
[ "python", "python-3.x", "pandas", "indexing" ]
How to change this function from creating a circular gradient to an elliptical gradient?
37,977,179
<p>I am trying to create a function that doesn't rely on a perfect circle for a transparency gradient, but rather an elliptical that can be a perfect circle or can be an ellipse. Currently my function creates a square that contains a 1/4th of a circular gradient that is later mirrored in 3 directions to make a circle.<...
1
2016-06-22T19:59:01Z
37,978,723
<p>I don't understand your function because of the variable naming. However:</p> <p><a href="http://i.stack.imgur.com/WhpCp.png" rel="nofollow"><img src="http://i.stack.imgur.com/WhpCp.png" alt="Ellipse"></a></p> <p>The <code>a^2</code> and <code>b^2</code> parts are what causes the squashing in one direction or the ...
0
2016-06-22T21:39:04Z
[ "python", "math", "geometry", "trigonometry" ]
How to change this function from creating a circular gradient to an elliptical gradient?
37,977,179
<p>I am trying to create a function that doesn't rely on a perfect circle for a transparency gradient, but rather an elliptical that can be a perfect circle or can be an ellipse. Currently my function creates a square that contains a 1/4th of a circular gradient that is later mirrored in 3 directions to make a circle.<...
1
2016-06-22T19:59:01Z
37,983,354
<p>To obtain axis-aligned elliptical gradient, just use scale coefficients for dx and dy. For example: <code>dx = 2.0 * dx</code></p> <p>P.S. Your code </p> <pre><code> t = math.atan2(dy, dx) r = math.sqrt(dx ** 2 + dy ** 2) ux = r * math.cos(t) uy = r * math.sin(t) </code></pre> <p>is completely useless - it giv...
0
2016-06-23T05:55:11Z
[ "python", "math", "geometry", "trigonometry" ]
How do i get the value of an item in tkinter when using a class?
37,977,302
<p>I wanted to learn a bit of tkinter. I followed a couple guides by <a href="https://www.youtube.com/watch?v=Ccct5D2AyNM&amp;list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M&amp;index=40" rel="nofollow">sentdex</a> on Youtube and feel like I have a good understanding of the basics. However, now I am trying to write a script th...
1
2016-06-22T20:06:47Z
37,977,598
<p>Well I fixed it, you should use self."variable-name" to declare an accessible attribute.</p> <pre><code>from tkinter import * from tkinter import messagebox import sys, datetime class Window(Frame): def __init__(self, master = None): Frame.__init__(self, master) self.master = master self.init_window()...
2
2016-06-22T20:23:15Z
[ "python", "python-3.x", "tkinter" ]
Google API Domain Admin Access
37,977,358
<p>I'm working on a script using Python that will access all students' Google calendars using their Google accounts and then add their school schedule into their calendar. I have figured out adding and deleting events and calendars using the API, but my question is how do I add a specific event to a specific calendar u...
0
2016-06-22T20:09:38Z
38,876,630
<p>Solved:</p> <p>The issue was that my client_secrets.json file for oauth 2.0 was set to my personal google account and not the admin account. I cleared the storage.json file where credentials were stored, re ran the program with the admin account logged in, and it worked! Hoped this helps.</p>
0
2016-08-10T14:43:44Z
[ "python", "calendar", "google-api", "google-admin-sdk" ]
Django's "check" cannot import settings
37,977,487
<p>Since the project is evolving I would like to start executing the system check framework of Django on dev environment. The technology stack is Ubuntu, PostgreSQL, Django1.9 + UWSGI. But...</p> <pre><code>django-admin check </code></pre> <p>outputs the following error:</p> <pre><code>ImportError: No module named m...
0
2016-06-22T20:17:24Z
37,977,794
<p>you seem to append to the sys path in the wsgi but the admin <code>check</code> won't be using that.</p> <p>Make sure you add the project path to the sys path for the environment you're using</p>
1
2016-06-22T20:34:17Z
[ "python", "django", "static-analysis" ]
Execute python script on Jenkins with variables
37,977,531
<p>I have created a job in Jenkins, for which user provides the value of a specific parameter, let's say PYTHON_PARM, as an input. On this job I execute a python script (using Python Plugin). The problem is that I want to use as a variable the user input $PYTHON_PARM parameter. This is not considered as an environment ...
0
2016-06-22T20:19:50Z
38,075,436
<p>Solution: from os import environ</p> <p>Type = environ['Type']</p>
1
2016-06-28T11:49:23Z
[ "python", "jenkins" ]
Python Pandas as pd set to_csv location
37,977,558
<p>I've got this script working based on another stack overflow post and I'm so close to having it do what I want it to do. The last step is getting the new csv to save in the second location I add as an argument. In this code i'd like to replace "removed.csv" with destination, but it's not working. It saves it where t...
0
2016-06-22T20:21:17Z
37,977,666
<p>You could just set the exact path. </p> <p>As in:</p> <pre><code>new_df.to_csv(r"C:\users\mthiesen\desktop\python\removed.csv", index=False) </code></pre> <p>or something like this:</p> <pre><code>path_to_output = r'C:\Users\clickhere\Desktop' new_df.to_csv(path_to_output + r'\output.csv') </code></pre> <p>Note...
0
2016-06-22T20:27:11Z
[ "python", "csv", "pandas" ]
How to modify numpy arrays in Spark dataframe?
37,977,608
<p><strong>Problem:</strong><br> No assignments are allowed inside lambda or dataframe transforms, this means we usually have to create a new structure for every data manipulation done in Dataframes with Spark.</p> <p><strong>Example (Python):</strong><br> I have previously gotten around this issue by simply creating ...
0
2016-06-22T20:24:19Z
37,978,876
<p>The source of the problem is much simpler than that. When you execute <code>sc.parallelize(a)</code> input array is converted to list and elements of this list become elements of the <code>RDD</code>. So when you execute <code>map</code> it applies the function to each element of the input separately. So it is equiv...
0
2016-06-22T21:51:11Z
[ "python", "numpy", "apache-spark", "pyspark", "apache-spark-sql" ]