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
Identify symbols in string
38,064,044
<p>I am implementing a simple DSL. I have the following input string:</p> <pre><code>txt = 'Hi, my name is &lt;&lt;name&gt;&gt;. I was born in &lt;&lt;city&gt;&gt;.' </code></pre> <p>And I have the following data:</p> <pre><code>{ 'name': 'John', 'city': 'Paris', 'more': 'xxx', 'data': 'yyy', ... } </code...
1
2016-06-27T22:14:12Z
38,064,293
<pre><code>import re def tokenize(text): found_variables = [] def replace_and_capture(match): found_variables.append(match.group(1)) return "{{{}}}".format(match.group(1)) return re.sub(r'&lt;&lt;([^&gt;]+)&gt;&gt;', replace_and_capture, text), found_variables fmt, vars = tokenize('Hi, my ...
1
2016-06-27T22:37:26Z
[ "python", "tokenize" ]
adding a column to pandas dataframe based on contents of another dataframe
38,064,098
<p>I have two dataframes <code>df</code> and <code>times</code>, representing maintenance records and monthly times, respectively. I'd like to append a column to <code>times</code> based on the data in <code>df</code>:</p> <pre><code>#df represents car maintenance records data = {"07-18-2012": ["replaced wheels", 45, ...
1
2016-06-27T22:18:36Z
38,064,740
<p>well, it's definitely not the best solution, because it loops through your <code>df.index</code>:</p> <pre><code>for d in df.index: times.ix[times['months'] &gt;= d, 'days_since_maintenance'] = times['months'] - d In [123]: times Out[123]: months days_since_maintenance 0 2013-12-31 531 ...
0
2016-06-27T23:23:54Z
[ "python", "pandas", "dataframe" ]
adding a column to pandas dataframe based on contents of another dataframe
38,064,098
<p>I have two dataframes <code>df</code> and <code>times</code>, representing maintenance records and monthly times, respectively. I'd like to append a column to <code>times</code> based on the data in <code>df</code>:</p> <pre><code>#df represents car maintenance records data = {"07-18-2012": ["replaced wheels", 45, ...
1
2016-06-27T22:18:36Z
38,064,916
<pre><code>df['dates'] = df.index def days_from_closest(x, df): closest = df[df['dates'] &lt; x].ix[-1] return x - closest.dates times['days_since_maintenance'] = times['months'].apply(lambda x: days_from_closest(x, df)) months days_since_maintenance 0 2013-12-31 531 days 1 2014-01-3...
0
2016-06-27T23:47:05Z
[ "python", "pandas", "dataframe" ]
adding a column to pandas dataframe based on contents of another dataframe
38,064,098
<p>I have two dataframes <code>df</code> and <code>times</code>, representing maintenance records and monthly times, respectively. I'd like to append a column to <code>times</code> based on the data in <code>df</code>:</p> <pre><code>#df represents car maintenance records data = {"07-18-2012": ["replaced wheels", 45, ...
1
2016-06-27T22:18:36Z
38,080,924
<p><code>apply</code> works, but utilize <code>index</code> rather than appending a new column for <code>dates</code>:</p> <pre><code>def days_since_x(row, df): '''returns days between the row date and the most recent maintenance date in df''' #filter records all_maint_prior = df[(df.index &lt;= row)...
1
2016-06-28T15:53:56Z
[ "python", "pandas", "dataframe" ]
Write java program as a String using Python
38,064,119
<p>I am trying to write a script that will generate a java file that will be used in Android Studio. the reason I am doing that is because I will be generating different JSON files with different information and I want to generate the appropriate java files using these JSON files if that make sense. Currently, I am tes...
-1
2016-06-27T22:21:01Z
38,064,154
<p><code>json.dump</code> will result in a JSON representation of your string. (E.g. <code>foo</code> becomes <code>"foo"</code>.)</p> <p>You should just write the content of the string directly into the file:</p> <pre><code>with open('data.java', 'w') as out_file: out_file.write(wholeProgram) </code></pre>
5
2016-06-27T22:24:46Z
[ "java", "python", "json" ]
How to put a production version of django site online?
38,064,137
<p>I have been developing a django application. I am using digital ocean. So I have placed my website folder into the <code>../var/www/html/[app_name]</code> folder.</p> <p>Normally, when I want to put my website online for users to use, I use: </p> <pre><code>cd ../var/www/html/[app_name] python manage.py runserver...
0
2016-06-27T22:23:36Z
38,064,191
<p>Running <code>python manage.py runserver [my_ip_address]:8080</code> in a production environment is not the best.</p> <p>And the problem is not as trivial as you think. Digital ocean has a good tutorial on setting up a production environment: <a href="https://www.digitalocean.com/community/tutorials/how-to-set-up-d...
3
2016-06-27T22:28:18Z
[ "python", "django" ]
How to extract string between key substring and "/" with regex?
38,064,184
<p>I have a string that's</p> <pre><code>/path/to/file?_subject_ID_SOMEOTHERSTRING </code></pre> <p>the path/to/file part changes depends on situation, and <code>subject_ID</code> is always there. I try to write a regex that extract only <code>file</code> part of the string. Using <code>?subject_ID</code> is definite...
1
2016-06-27T22:27:46Z
38,064,294
<p>It's pretty simple, really. Just match a <code>/</code> before and <code>?subject_ID</code> after:</p> <pre><code>([^/?]*)\?subject_ID </code></pre> <p>The <code>[^/?]*</code> (as opposed to <code>.*</code>) is because otherwise it'd match the part before, too. The <code>?</code> in the character class </p> <p>If...
2
2016-06-27T22:37:44Z
[ "python", "regex" ]
How to extract string between key substring and "/" with regex?
38,064,184
<p>I have a string that's</p> <pre><code>/path/to/file?_subject_ID_SOMEOTHERSTRING </code></pre> <p>the path/to/file part changes depends on situation, and <code>subject_ID</code> is always there. I try to write a regex that extract only <code>file</code> part of the string. Using <code>?subject_ID</code> is definite...
1
2016-06-27T22:27:46Z
38,064,355
<p>As for your <code>'(.*[\/]).*\?_subject_ID'</code> regex approach, you just need to add a capturing group around the second <code>.*</code>. You could use <a href="https://regex101.com/r/uU3vH7/1" rel="nofollow"><code>r'(.*/)(.*)\?_subject_ID'</code></a> (then, there will be <code>.group(1)</code> and <code>.group(2...
3
2016-06-27T22:43:23Z
[ "python", "regex" ]
Is it faster to iterate a small list within an any() statement?
38,064,206
<p>Consider the following operation in the limit of low length iterables,</p> <pre><code>d = (3, slice(None, None, None), slice(None, None, None)) In [215]: %timeit any([type(i) == slice for i in d]) 1000000 loops, best of 3: 695 ns per loop In [214]: %timeit any(type(i) == slice for i in d) 1000000 loops, best of 3...
4
2016-06-27T22:29:26Z
38,064,344
<p>The catch is the size of the items you are applying <code>any</code> on. Repeat the same process on a larger dataset:</p> <pre><code>In [2]: d = ([3] * 1000) + [slice(None, None, None), slice(None, None, None)]*1000 In [3]: %timeit any([type(i) == slice for i in d]) 1000 loops, best of 3: 736 µs per loop In [4]:...
2
2016-06-27T22:42:30Z
[ "python", "list", "caching", "optimization", "iteration" ]
Better way to create my lists in classes?
38,064,284
<p>I've been working on making my text based game more realistic, and one design I would like to implement is to make sure the rooms stay 'static' to a point (i.e. a player uses a potion in the room, if they come back to that room that potion should no longer be there.)</p> <p>This is how my code is basically set up (...
1
2016-06-27T22:36:38Z
38,064,347
<p>First, let's look at your example (I'll simplify it):</p> <pre><code>class Room(Scene): potions = [Potion() for x in range(3)] </code></pre> <p>What you have done there is create a class attribute <code>potions</code> that are shared among <em>all</em> instances of <code>Room</code>. For example, you'll see my...
4
2016-06-27T22:42:34Z
[ "python", "list", "variables", "global" ]
How to read a compressed binary file as an array of floats
38,064,360
<p>I need to read a compressed unformatted binary file in as an array of floats. The only way that I have found to do this, is to use os to unzip, read it using np.fromfile, and then zip it up again. </p> <pre><code>os.system('gunzip filename.gz') array = np.fromfile('filename','f4') os.system('gzip filename') </code>...
1
2016-06-27T22:43:50Z
38,064,394
<p>After you've read the file content, you should be able to get an array using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromstring.html" rel="nofollow"><code>numpy.fromstring</code></a>:</p> <pre><code>import gzip import numpy as np f=gzip.GzipFile('filename') file_content = f.read() array ...
2
2016-06-27T22:47:11Z
[ "python", "arrays", "binary" ]
Iterate from a certain row of a csv file in Python
38,064,374
<p>I have a csv file with many millions of rows. I want to start iterating from the 10,000,000 row. At the moment I have the code:</p> <pre><code> with open(csv_file, encoding='UTF-8') as f: r = csv.reader(f) for row_number, row in enumerate(r): if row_number &lt; 10000000: ...
1
2016-06-27T22:45:28Z
38,064,407
<p>You could use <a href="https://docs.python.org/3/library/itertools.html#itertools.islice" rel="nofollow"><em>islice</em></a>:</p> <pre><code>from itertools import islice with open(csv_file, encoding='UTF-8') as f: r = csv.reader(f) for row in islice(r, 10000000, None): process_row(row) </cod...
2
2016-06-27T22:48:18Z
[ "python", "python-3.x", "csv" ]
TensorFlow - Tflearning error feed_dict
38,064,449
<p>I am working on a classification problem in python. Fact is, I'm not good yet in TensorFlow. So I have the same problem since a long time now and I don't know how to fix it. I hope you could help me :)</p> <p>This is my data :</p> <p>X : 8000 pictures : 32*32px and 3 colors (rgb), so I load a matrix X.shape = (800...
0
2016-06-27T22:53:08Z
38,068,261
<p>Paraphrased from the source code :</p> <p>The number of inputs don't match the expected ones. If you are using ipython notebook, make sure you didn't run the graph construction cell multiple times. Or enclose the graph construction in the <code>with tf.Graph().as_default()</code> block.</p>
2
2016-06-28T06:08:37Z
[ "python", "tensorflow", "deep-learning" ]
Python27 - on windows 8.1 or 10 not showing the printers
38,064,514
<p>I have 32-bit Python and win32print of 32bit installed. When i execute the following code on windows 8 or 10 i do not get any printers output list. only its printing: <code>()</code></p> <p><a href="http://i.stack.imgur.com/IlDts.png" rel="nofollow"><img src="http://i.stack.imgur.com/IlDts.png" alt="enter image des...
1
2016-06-27T22:59:24Z
38,083,096
<p>See documentation for <a href="http://timgolden.me.uk/pywin32-docs/win32print__EnumPrinters_meth.html" rel="nofollow">(EnumPrinters/Python)</a> and <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/dd162692(v=vs.85).aspx" rel="nofollow">(EnumPrinters/WinAPI)</a></p> <p>Typical WinAPI input for <code...
1
2016-06-28T17:54:22Z
[ "python", "windows", "winapi", "printing" ]
Pass estimator to custom score function via sklearn.metrics.make_scorer
38,064,637
<p>I'd like to make a custom scoring function involving classification probabilities as follows:</p> <pre><code>def custom_score(y_true, y_pred_proba): error = ... return error my_scorer = make_scorer(custom_score, needs_proba=True) gs = GridSearchCV(estimator=KNeighborsClassifier(), param_...
0
2016-06-27T23:13:36Z
38,064,878
<p>There is an alternative way to make a scorer <a href="http://scikit-learn.org/stable/modules/model_evaluation.html#implementing-your-own-scoring-object" rel="nofollow">mentioned in the documentation</a>. Using this method I can do the following:</p> <pre><code>def my_scorer(clf, X, y_true): class_labels = clf.c...
0
2016-06-27T23:42:33Z
[ "python", "scikit-learn" ]
I am trying to write a function that returns the value for a gapper estimate of scale of a dataset. Can someone take a look?
38,064,685
<p>If you don't care about context and just want to look at the code, skip down two paragraphs.</p> <p>I am working on a project where I am measuring velocity dispersions of galaxy clusters, given galaxy redshift data collected from our group's telescope at the south pole (SPT). For clusters that have very few member ...
0
2016-06-27T23:17:17Z
38,064,928
<p>Your weights are wrong. In the loop <code>i</code> takes the values <code>0, 1, ..., n-2</code>, so</p> <pre><code>w[0] = 0, w[1] = 1*(n-1), ..., w[n-2] = (n-2)*2 </code></pre> <p>The loop is also unnecessary. Here is a vectorized implementation:</p> <pre><code>def gDispersion(v): """ Returns the gapper veloc...
2
2016-06-27T23:47:57Z
[ "python", "math", "statistics", "astropy", "code-statistics" ]
Interpolating a numpy array to fit another array
38,064,697
<p>Say I have <code>some_data</code> of shape <code>(1, n)</code>. I have new <code>incoming_data</code> of shape <code>(1, n±x)</code>, where x is some positive integer much smaller than <code>n</code>. I would like to squeeze or stretch <code>incoming_data</code> such that it is of the same length as <code>n</code>....
1
2016-06-27T23:18:59Z
38,065,352
<p>You can implement this simple compression or stretching of your data using <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html" rel="nofollow"><code>scipy.interpolate.interp1d</code></a>. I'm not saying it necessarily makes sense (it makes a huge difference what kind of inter...
3
2016-06-28T00:44:47Z
[ "python", "arrays", "numpy", "interpolation" ]
How to store series of values in python
38,064,763
<p>I just started with python a few days ago, anda i`m having some problems in finding a solution.</p> <p>So, i've been using pycharm and i've downloaded some modules like <em>xlrd, xlwings, and xlwt</em> to analyse and format my excel data.</p> <p>My maine goal is to find the highest values from a column that as pos...
0
2016-06-27T23:26:25Z
38,065,166
<p>You can use the <code>max(some_List)</code> function. It returns the maximum value in a list.</p> <p>In the same way, you can use the <code>min(some_List)</code> function. It returns the minimum value of a list.</p> <p>I am not aware of any function that returns the 2 maximum and the 2 minimum values of a list. Yo...
1
2016-06-28T00:18:32Z
[ "python", "excel", "store" ]
How to store series of values in python
38,064,763
<p>I just started with python a few days ago, anda i`m having some problems in finding a solution.</p> <p>So, i've been using pycharm and i've downloaded some modules like <em>xlrd, xlwings, and xlwt</em> to analyse and format my excel data.</p> <p>My maine goal is to find the highest values from a column that as pos...
0
2016-06-27T23:26:25Z
38,066,586
<p>To surmise the tools python allows you:</p> <ol> <li><p><code>sorted(l)</code> which takes a list like yours and returns a new list in descending order i.e., the max value is at index 0 or <code>l[0]</code></p></li> <li><p><code>max(l)</code> which returns the maximum value</p></li> <li><p><code>min(l)</code> which...
0
2016-06-28T03:30:27Z
[ "python", "excel", "store" ]
Python variable scope and execution
38,064,775
<p>I am executing a python script:</p> <pre><code>exec(open("process.py").read(), globals()) </code></pre> <p>Is it possible to make all variables set within "process.py" local to that particular file?</p>
0
2016-06-27T23:28:32Z
38,064,828
<p>You could execute the file's contents in a new dict instead of this code's own globals:</p> <pre><code>with open("process.py") as f: exec(f.read(), {}) </code></pre> <p>This is a weird way to structure a Python program, though. Usually, you'd organize your code into modules and functions instead of <code>exec<...
0
2016-06-27T23:35:32Z
[ "python" ]
Listing only pandas rows that match a criteria based on function output
38,064,793
<p>I have a line defined by <code>mx+b</code>, where <code>m,b</code> are variables acquired from <code>np.linalg.lstsq</code>.</p> <p>Also have created a function called distance defined as:</p> <pre><code>def distance(x0, y0, slope, yintercept): """Returns the euclidean distance between a line and a point""...
0
2016-06-27T23:30:43Z
38,065,067
<p>You can use df.apply() to iterate over rows and access multiple columns for a function.</p> <p><code>df[df.apply(distance, axis=1)] </code></p> <p>axis=1 here tells apply to iterate over rows. df.apply() will iterate over columns if axis=0. The result of this statement is a dataframe, which is a subset of <code>df...
1
2016-06-28T00:06:11Z
[ "python", "numpy", "pandas" ]
i need help to extract files from a zip file usingpython
38,064,846
<p>i have created a zip file called shoppy and put "cats.txt" in it and now i want to extract it but my code doesn't work it gives me this error </p> <pre><code>AttributeError: '_io.TextIOWrapper' object has no attribute 'extract' </code></pre> <p>here is my code</p> <pre><code>from zipfile import * z=open("shoppy...
0
2016-06-27T23:37:46Z
38,065,106
<p>The first problem is that <code>open()</code> refers to the builtin function, not to any function in the <code>zipfile</code> - there is no <code>zipfile.open()</code> function.</p> <p>To open a zip file use the <a href="https://docs.python.org/3/library/zipfile.html#zipfile.ZipFile" rel="nofollow"><code>zipfile.Zi...
1
2016-06-28T00:11:14Z
[ "python", "zip", "extract" ]
Subprocess popen second instance of Kivy gives module import error
38,064,862
<p>I'm trying to run two instances of Kivy. I know you're not supposed to try and open a second window as per the docs but I need a second window, can't do without. It's either open up a second window or bail on Kivy. </p> <p>Given that every Python GUI library I've looked into has a less than appealing aesthetic I'd ...
1
2016-06-27T23:40:34Z
38,069,404
<p>As per the comments there is a mismatch between the python interpreter you are using in your IDE, which is <em>python3.4</em> and what interpreter <em>python</em> refers to in your <em>subprocess</em> call which is most likely python2. To solve it you just need to specify to use the python3 interpreter, you also do...
0
2016-06-28T07:12:23Z
[ "python", "kivy" ]
Python: multi-dimensional lists - appending one 2D list into another list
38,064,885
<p>I'm looking to create a master array/list that takes several two dimensional lists and integrates them into the larger list.</p> <p>For example I have a <code>TableA[]</code> which has <code>dates</code> as one array/list and <code>prices</code> as another array/list. I have another as TableB[] which has the same. ...
0
2016-06-27T23:42:55Z
38,065,115
<p>Python's fairly friendly about this sort of thing and will let you have lists as elements of lists . Here's an example of one way to do it.</p> <p><code>TableA = [['01/01/2000', '$10'], ['02/01/2000', '$11']]</code></p> <p>If you entered this straight into the python interpreter, you'd define TableA as a list with...
0
2016-06-28T00:11:53Z
[ "python", "arrays", "list", "multidimensional-array" ]
Pandas. ValueError: Length of values does not match length of index
38,064,951
<p>Please Help ! I have almost the same structure of SMA and EMA code. SMA code is OK, but EMA code gets an error: "ValueError: Length of values does not match length of index."</p> <p>SMA(simple moving average) code:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt window_length = 20 df = pd.read_c...
-1
2016-06-27T23:49:48Z
38,065,233
<p><strong>You append ema twice! in the first 'If' statement</strong> Whereas in SMA you append only once. Remove one.. </p> <pre><code>for i in range(len(close)): if i+1 &lt; window_length: sma = sum(close[:window_length]) / window_length multiplier = 2 / float(1 + window...
0
2016-06-28T00:27:18Z
[ "python" ]
selenium : Click on dynamic radio button using python
38,064,987
<p>I'm trying to click on a radio button on a web page which is dynamic. I tried classname, xpath and nothing works. </p> <p>The code that contains the radio button is : </p> <pre><code>&lt;input id="radiofield-1247-inputEl" class="x-form-field x-form-radio x-form-cb" type="button" hidefocus="true" autocomplete="off"...
0
2016-06-27T23:55:28Z
38,070,161
<p>You're trying <code>type="radio"</code> while on provided <code>HTML</code> it's <code>type="button"</code>...</p> <p>Try following <code>XPath</code>:</p> <pre><code>driver.find_element_by_xpath('//input[contains(@id, "radiofield-")][@role="radio"]') </code></pre>
0
2016-06-28T07:48:06Z
[ "python", "selenium" ]
Tkinter Button unable to find callback command
38,065,003
<p>I'm working on a program that reads and parses a config file for an embedded hardware system I'm working on. I'm trying to use tkinter and python to make a simple GUI for reading and writing this file. I have the file IO and parsing mostly working, but I'm having trouble getting all the parts integrated with the GUI...
0
2016-06-27T23:57:25Z
38,065,055
<p>items which are defined in the class namespace are bound to the class. In this case, you have a couple options...</p> <p>One option is that you could make it a <code>staticmethod</code>:</p> <pre><code>class Application(Frame): @staticmethod def openCfg(): name = getNameFromFile() nameEntr...
2
2016-06-28T00:03:59Z
[ "python", "python-3.x", "tkinter" ]
pyspark: join using schema? Or converting the schema to a list?
38,065,009
<p>I am using the following code to join two data frames:</p> <pre><code>new_df = df_1.join(df_2, on=['field_A', 'field_B', 'field_C'], how='left_outer') </code></pre> <p>The above code works fine, but sometimes <code>df_1</code> and <code>df_2</code> have hundreds of columns. Is it possible to join using the schema ...
2
2016-06-27T23:58:22Z
38,065,332
<p>You can't join on schema, if what you meant was somehow having <code>join</code> incorporate the column dtypes. What you can do is extract the column names out first, then pass them through as the list argument for <code>on=</code>, like this:</p> <pre><code>join_cols = df_1.columns df_1.join(df_2, on=join_cols, h...
2
2016-06-28T00:41:08Z
[ "python", "pyspark", "spark-dataframe" ]
Understanding xarray groupby
38,065,129
<p>I am trying to count the number of members in each group, akin to <code>pandas.DataFrame.groupby.count</code>. However, it doesn't seem to be working. Here is an example:</p> <pre><code>In [1]: xr_test = xr.DataArray(np.random.rand(6), coords=[[10,10,11,12,12,12]], dims=['dim0']) xr_test Out[1]: &lt;xarray....
0
2016-06-28T00:13:03Z
38,073,919
<p>This is a bug! Xarray currently makes the (in this case mistaken) assumption that coordinates corresponding to dimensions have all unique values. This usually a good idea, but shouldn't be required. If you make another coordinate this should work properly, e.g., <code> xr_test = xr.DataArray(np.random.rand(6), coord...
1
2016-06-28T10:39:53Z
[ "python", "python-xarray" ]
Get values in numpy array either side of a specified value
38,065,145
<p>I have a numpy array, provided at random, which for this example looks like:</p> <pre><code>a = [10, 8, 6, 4, 2, -2, -4, -6, -8, -10, 1] </code></pre> <p>ideally, in this example, the values would be between -10 and 10 but this cannot be guaranteed (as above).</p> <p>I want to retrive the 2 values closest to zero...
0
2016-06-28T00:16:09Z
38,065,256
<p>This function should do the job:</p> <pre><code>import numpy as np def my_func(x): left = np.where(x[:-1]&gt;0)[0][-1] right = 1 + np.where(x[1:]&lt;0)[0][0] return x[left], x[right] </code></pre> <p>Demo:</p> <pre><code>&gt;&gt;&gt; a = np.array([10, 8, 6, 4, 2, -2, -4, -6, -8, -10, 1]) &gt;&gt;&gt; ...
1
2016-06-28T00:30:36Z
[ "python", "arrays", "numpy", "slice" ]
TypeError: missing 1 required positional argument: 'ponto'
38,065,160
<p>This is my full code and i got this error too:</p> <p>line 176, in get_ponto_local matriz_local=matriz * matriz_ponto TypeError: unsupported operand type(s) for *: 'Matriz' and 'Matriz'</p> <p>class Camara:</p> <pre><code>def __init__(self, posicao, olhar_para, vertical, distancia_olho_plano_projeca...
-1
2016-06-28T00:17:37Z
38,065,202
<p>You need to create an <em>instance</em> of your <code>Camara</code> class.</p> <p>As it is you are calling <code>local_para_global()</code> as if it were a class method of class <code>Camara</code>.</p> <p>Something like this should fix it:</p> <pre><code>camara = Camara(...) # instantiate an object of class C...
0
2016-06-28T00:23:18Z
[ "python" ]
3D numpy array in Theano
38,065,172
<p>I'm having a 3D NumpyArray which I want to through in a Keras Neural Network.</p> <p>Because of one hot encoding the array became a 3D array.</p> <pre><code> [ [[0,1,0,0], [1,0,0,0]], [[0,0,0,1], [1,1,0,0]], [[0,0,1,0], [0,0,0,1]] ] </code></pre> <p>Since Keras can only compute 2D arrays, my qu...
-1
2016-06-28T00:19:02Z
38,065,208
<p>You can use <code>numpy.ndarray.flatten</code> to make it into a <code>1D</code> array. Example:</p> <pre><code>import numpy as np a = np.array( [ [[0, 1, 0, 0], [1, 0, 0, 0]], [[0, 0, 0, 1], [1, 1, 0, 0]], [[0, 0, 1, 0], [0, 0, 0, 1]] ] ) a.flatten() </code></pre> <p>From this,...
0
2016-06-28T00:24:48Z
[ "python", "numpy", "neural-network", "theano", "keras" ]
treadking live streaming with python
38,065,222
<p>I am trying to call live streaming api from tradeking (<a href="https://developers.tradeking.com/documentation/node-streaming" rel="nofollow">https://developers.tradeking.com/documentation/node-streaming</a>)</p> <p>Following is my code:</p> <pre><code>import requests from requests_oauthlib import OAuth1 CK = "C...
0
2016-06-28T00:26:19Z
38,065,321
<p>I think that the exception is raised in <code>s.get(...)</code> which will perform an actual HTTP GET operation and return a <code>Response</code> object.</p> <p>The subsequent lines dealing with prepared requests seem wrong and won't work on <code>Response</code> objects, but that code is not being executed due to...
1
2016-06-28T00:39:59Z
[ "python" ]
Define strong-typed variables in Python
38,065,382
<p>Intellisence can't able help with Python members of an object because the object type will only be known at runtime. Is there a way to specify the type of the variable?</p> <p>E.g.</p> <pre><code>import xml.etree.ElementTree root = xml.etree.ElementTree.parse(x).getroot() for data in root.findall('./data'): d...
0
2016-06-28T00:48:41Z
38,065,569
<p>There is a way to force vanilla PyCharm to think of it as something, however, it does incur overhead:</p> <pre><code>root = xml.etree.ElementTree.parse(x).getroot() for data in root.findall('./data'): if isinstance(data, xml.etree.ElementTree.Element): data. </code></pre> <p>By ...
2
2016-06-28T01:14:18Z
[ "python", "strong-typing" ]
pyqtgraph - Is it possible to have a ImageView without histogram?
38,065,570
<p>I currently have a <a href="http://www.pyqtgraph.org/documentation/widgets/imageview.html" rel="nofollow">ImageView</a> showing a Dicom image, but i don't want that histogram on the side. And with possible,move those two buttons to another place. How can I make that?</p>
0
2016-06-28T01:14:21Z
38,068,765
<p>The special thing with ImageView is that you get the histogram. Another way of display an image is by adding an <a href="http://www.pyqtgraph.org/documentation/graphicsItems/imageitem.html" rel="nofollow">ImageItem</a> to a basic plot and hiding the axes. Tackling the problem this way would give you good control ove...
1
2016-06-28T06:38:27Z
[ "python", "pyqt", "dicom", "pyqtgraph" ]
pyqtgraph - Is it possible to have a ImageView without histogram?
38,065,570
<p>I currently have a <a href="http://www.pyqtgraph.org/documentation/widgets/imageview.html" rel="nofollow">ImageView</a> showing a Dicom image, but i don't want that histogram on the side. And with possible,move those two buttons to another place. How can I make that?</p>
0
2016-06-28T01:14:21Z
38,078,871
<p>Here's an ImageItem without an histogram on the side. Maybe it's what you're looking for.</p> <pre><code>import pyqtgraph as pg imageWidget = pg.GraphicsLayoutWidget() vb = imageWidget.addViewBox(row=1, col=1) img = pg.ImageItem() vb.addItem(img) vb.setAspectLocked(True) </code></pre>
0
2016-06-28T14:23:45Z
[ "python", "pyqt", "dicom", "pyqtgraph" ]
pyodbc result set has data type embedded
38,065,578
<p>I am querying Teradata using pyodbc and flask with the intention of charting the data using d3. </p> <p>The result set has two columns, one is a decimal and the other an integer. When I pass the results to my html page and log the output I am getting something along these lines: </p> <pre><code>[(Decimal(&amp; #39...
1
2016-06-28T01:15:07Z
38,065,707
<pre><code>import re processed = [] for piece in results: processed.append([re.sub(".*?(-?\d+\.\d+).*", "\1", repr(piece[0])), piece[1]] </code></pre> <p>Something along those lines. It's displaying that data because it's of type <code>Decimal</code> (the teradata kind). I'm guessing <a href="https://docs.python.o...
0
2016-06-28T01:31:48Z
[ "javascript", "python", "flask", "pyodbc" ]
pyodbc result set has data type embedded
38,065,578
<p>I am querying Teradata using pyodbc and flask with the intention of charting the data using d3. </p> <p>The result set has two columns, one is a decimal and the other an integer. When I pass the results to my html page and log the output I am getting something along these lines: </p> <pre><code>[(Decimal(&amp; #39...
1
2016-06-28T01:15:07Z
38,066,560
<p>I think the better approach is as provided in <strong><a href="http://stackoverflow.com/a/3885198/4244780">this</a></strong> answer, as it is best to <code>dumps</code> the data of the query into a <code>json</code> object so you can easily retrieve it from the client side using JS, without the need to parse it usin...
0
2016-06-28T03:27:05Z
[ "javascript", "python", "flask", "pyodbc" ]
How to get the position where UnicodeDecodeError occurred?
38,065,646
<p>How can I get a position of where did UnicodeDecodeError occurred? I found material over <a href="https://docs.python.org/3/library/exceptions.html#UnicodeError" rel="nofollow">here</a> and tried to implement it below. But I just get an error <code>NameError: name 'err' is not defined</code></p> <p>I searched all o...
2
2016-06-28T01:23:56Z
38,065,724
<p>That information is stored in the exception itself. You can get the exception object with the <code>as</code> keyword, and use the <code>start</code> attribute:</p> <pre><code>while True: try: data = data.decode("utf-8") except UnicodeDecodeError as e: data = data[:e.start] + data[e.end:] ...
4
2016-06-28T01:34:49Z
[ "python", "python-3.x", "exception", "exception-handling" ]
How to get the position where UnicodeDecodeError occurred?
38,065,646
<p>How can I get a position of where did UnicodeDecodeError occurred? I found material over <a href="https://docs.python.org/3/library/exceptions.html#UnicodeError" rel="nofollow">here</a> and tried to implement it below. But I just get an error <code>NameError: name 'err' is not defined</code></p> <p>I searched all o...
2
2016-06-28T01:23:56Z
38,065,761
<p>In case you just want to ignore the error and decode the rest, you can do:</p> <pre><code>data = data.decode("utf-8", errors='ignore') </code></pre>
0
2016-06-28T01:38:58Z
[ "python", "python-3.x", "exception", "exception-handling" ]
Getting "unresolved reference: print" in pycharm community version 2016.1.4
38,065,650
<p>I have already tried "invalidate cache and restart" <a href="http://stackoverflow.com/questions/22738455/pycharm-unresolved-reference-print">(as found here)</a>.</p> <p>And I have already tried turning on "collect run-time types for information for code insight" <a href="http://stackoverflow.com/questions/23689183/...
0
2016-06-28T01:24:35Z
38,065,897
<p>Well, I "fixed" it, although I don't usually consider completely uninstalling the software, then having to delete settings from C:\Users\myname (which weren't caught by uninstall.exe), then making a new directory, creating new .py files and manually copy+pasting the contents of the old ones into it, a "fix".</p> <p...
0
2016-06-28T01:56:34Z
[ "python", "pycharm" ]
How can I add fields such as company name, company website, etc to a django user form?
38,065,828
<p>How can I add fields like company name and website to the standard django user authentication form? I already have used their default fields for username, password, etc, but I'd love to add these fields as well. I know there are a couple of ways to do this, but what would you think is best? I've looked at the django...
-1
2016-06-28T01:47:40Z
38,065,905
<p>The easiest way for you to extend the user by creating OneOneOneField:</p> <pre><code>class Profile(models.Model): user = models.OneOnOneFiled(User,blank=True,null=True) phone = models.CharField(max_length=200,blank=True,null=True) location = models.CharField(max_length=200,blank=True,null=True) ...
0
2016-06-28T01:57:54Z
[ "python", "django", "django-models", "django-forms", "web-frameworks" ]
How to "skip" individual functions in a multi-function python script based on argument values
38,065,852
<p>I am dealing with a MS batch (***.bat) wrapper that calls a python script with currently 5 argument values.</p> <p>I want to feed <code>sys.argv(6)</code> to the python script in order to optionally "skip" a certain function within.</p> <p>To speak in batch language, i would like to circumvent a subroutine in <co...
0
2016-06-28T01:50:09Z
38,066,154
<p>Pass the argument to your script, e.g. in your bat file:</p> <pre><code>python myscript.py %6 </code></pre> <p>Then in <code>myscript.py</code>:</p> <pre><code>import sys def function1(): pass def function2(): pass if __name__ == "__main__": if len(sys.argv) &gt; 1 and sys.argv[1] == 'yes': ...
1
2016-06-28T02:34:12Z
[ "python", "batch-file", "cmd", "subroutine", "goto" ]
How to "skip" individual functions in a multi-function python script based on argument values
38,065,852
<p>I am dealing with a MS batch (***.bat) wrapper that calls a python script with currently 5 argument values.</p> <p>I want to feed <code>sys.argv(6)</code> to the python script in order to optionally "skip" a certain function within.</p> <p>To speak in batch language, i would like to circumvent a subroutine in <co...
0
2016-06-28T01:50:09Z
38,066,268
<p>Its better to start using python <strong>argparser</strong>. It gives lot of functionalities, help and description: </p> <p><strong>sample.py:</strong></p> <pre><code>import argparse def function1(): print("Function 1") def function2(): print("Function 2") if __name__ == '__main__': parser = argpa...
0
2016-06-28T02:49:29Z
[ "python", "batch-file", "cmd", "subroutine", "goto" ]
How to remove the adjacent duplicate value in a numpy array?
38,065,898
<p>Given a numpy array, I wish to remove the adjacent duplicate non-zero value and all the zero value. For instance, for an array like that: <code>[0,0,1,1,1,2,2,0,1,3,3,3]</code>, I'd like to transform it to: <code>[1,2,1,3]</code>. Do you know how to do it? I just know <code>np.unique(arr)</code> but it would remove ...
2
2016-06-28T01:56:40Z
38,065,958
<p>You can use the <code>groupby</code> method from <code>itertools</code> combined with list comprehension for this problem:</p> <pre><code>from itertools import groupby [k for k,g in groupby(a) if k!=0] # [1,2,1,3] </code></pre> <p><em>Data</em>:</p> <pre><code>a = [0,0,1,1,1,2,2,0,1,3,3,3] </code></pre>
3
2016-06-28T02:06:29Z
[ "python", "arrays", "numpy" ]
How to remove the adjacent duplicate value in a numpy array?
38,065,898
<p>Given a numpy array, I wish to remove the adjacent duplicate non-zero value and all the zero value. For instance, for an array like that: <code>[0,0,1,1,1,2,2,0,1,3,3,3]</code>, I'd like to transform it to: <code>[1,2,1,3]</code>. Do you know how to do it? I just know <code>np.unique(arr)</code> but it would remove ...
2
2016-06-28T01:56:40Z
38,066,090
<p>Here's one way:</p> <pre><code>In [62]: x Out[62]: array([0, 0, 1, 1, 1, 2, 2, 0, 1, 3, 3, 3]) In [63]: selection = np.ones(len(x), dtype=bool) In [64]: selection[1:] = x[1:] != x[:-1] In [65]: selection &amp;= x != 0 In [66]: x[selection] Out[66]: array([1, 2, 1, 3]) </code></pre>
2
2016-06-28T02:25:11Z
[ "python", "arrays", "numpy" ]
How to remove the adjacent duplicate value in a numpy array?
38,065,898
<p>Given a numpy array, I wish to remove the adjacent duplicate non-zero value and all the zero value. For instance, for an array like that: <code>[0,0,1,1,1,2,2,0,1,3,3,3]</code>, I'd like to transform it to: <code>[1,2,1,3]</code>. Do you know how to do it? I just know <code>np.unique(arr)</code> but it would remove ...
2
2016-06-28T01:56:40Z
38,066,375
<pre><code>import numpy as np a = np.array([0,0,1,1,1,2,2,0,1,3,3,3]) </code></pre> <p>Use <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#integer-array-indexing" rel="nofollow">integer indexing</a> to choose the non-zero elements</p> <pre><code>b = a[a.nonzero()] &gt;&gt;&gt; b array([1, 1, ...
1
2016-06-28T03:03:18Z
[ "python", "arrays", "numpy" ]
How to remove the adjacent duplicate value in a numpy array?
38,065,898
<p>Given a numpy array, I wish to remove the adjacent duplicate non-zero value and all the zero value. For instance, for an array like that: <code>[0,0,1,1,1,2,2,0,1,3,3,3]</code>, I'd like to transform it to: <code>[1,2,1,3]</code>. Do you know how to do it? I just know <code>np.unique(arr)</code> but it would remove ...
2
2016-06-28T01:56:40Z
38,066,819
<pre><code>&gt;&gt;&gt; import numpy as NP &gt;&gt;&gt; a = NP.array([0,0,1,1,1,2,2,0,1,3,3,3]) </code></pre> <p>first, remove the zeros:</p> <pre><code>&gt;&gt;&gt; idx = a==0 &gt;&gt;&gt; a = a[-idx1] &gt;&gt;&gt; a array([1, 1, 1, 2, 2, 1, 3, 3, 3]) </code></pre> <p>now remove the consecutive duplicates</p> <p...
0
2016-06-28T03:59:35Z
[ "python", "arrays", "numpy" ]
How to convert a column of type Series to datetime weekdays format in python?
38,065,968
<p>I have the following data and python code</p> <pre><code>Time Started Date Submitted Status 10/29/2015 17:34 10/29/2015 17:34 Complete 10/29/2015 17:35 10/29/2015 17:35 Complete 10/29/2015 17:36 10/29/2015 17:37 Complete import pandas as pd from datetime import datetime, timedelta from pandas...
1
2016-06-28T02:07:33Z
38,065,980
<p>Add parameter <code>parse_dates</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a> for convert to <code>datetime</code>:</p> <pre><code>import pandas as pd import io temp=u"""Time Started,Date Submitted,Status 10/29/2015 17:34,10/...
0
2016-06-28T02:09:54Z
[ "python", "python-2.7", "datetime", "pandas", "datetime-format" ]
How to subtract numbers from a set from another set in python?
38,066,025
<p>I want to subtract the values inside of two lists.</p> <pre><code>a = [1,2,3,4] b = [1,0,1,5] c = a - b #c should be = [0,2,2,-1] </code></pre> <p>The answer to <a href="http://stackoverflow.com/questions/11280536/how-can-i-add-the-corresponding-elements-of-several-lists-of-numbers">How can I add the corresponding...
0
2016-06-28T02:15:19Z
38,066,041
<pre><code>c = [a1 - b1 for (a1, b1) in zip(a, b)] </code></pre>
2
2016-06-28T02:17:54Z
[ "python", "python-3.x" ]
How to subtract numbers from a set from another set in python?
38,066,025
<p>I want to subtract the values inside of two lists.</p> <pre><code>a = [1,2,3,4] b = [1,0,1,5] c = a - b #c should be = [0,2,2,-1] </code></pre> <p>The answer to <a href="http://stackoverflow.com/questions/11280536/how-can-i-add-the-corresponding-elements-of-several-lists-of-numbers">How can I add the corresponding...
0
2016-06-28T02:15:19Z
38,066,141
<p>Probably <a href="https://docs.python.org/3/library/itertools.html#itertools.starmap" rel="nofollow"><code>itertools.starmap</code></a> would be useful in your case:</p> <pre><code>&gt;&gt;&gt; a = [1,2,3,4] &gt;&gt;&gt; b = [1,0,1,5] &gt;&gt;&gt; &gt;&gt;&gt; import itertools as it &gt;&gt;&gt; &gt;&gt;&gt; impo...
2
2016-06-28T02:31:57Z
[ "python", "python-3.x" ]
How to subtract numbers from a set from another set in python?
38,066,025
<p>I want to subtract the values inside of two lists.</p> <pre><code>a = [1,2,3,4] b = [1,0,1,5] c = a - b #c should be = [0,2,2,-1] </code></pre> <p>The answer to <a href="http://stackoverflow.com/questions/11280536/how-can-i-add-the-corresponding-elements-of-several-lists-of-numbers">How can I add the corresponding...
0
2016-06-28T02:15:19Z
38,066,355
<p>Most people use <code>numpy</code> for numerical operations (although p.magalhaes has the answer for "pure" python).</p> <pre><code>import numpy as np a=np.array([1,2,3,4]) b=np.array([1,0,1,5]) c = a - b c </code></pre> <p>returns</p> <pre><code>array([ 0, 2, 2, -1]) </code></pre>
0
2016-06-28T03:01:35Z
[ "python", "python-3.x" ]
Meta decorator with parameters, defined in explicit functions
38,066,029
<p>I want an explicit replacement for a common decorator idiom.</p> <p>There is a clever one-line decorator that has been <a href="https://en.wikipedia.org/wiki/Copy_and_paste_programming" rel="nofollow">copy-pasted</a> without explanation in many code bases for many years:</p> <pre class="lang-python prettyprint-ove...
1
2016-06-28T02:15:51Z
38,066,048
<p>Since I don't quite know how the details of the original are meant to work, I may have this wrong:</p> <pre class="lang-python prettyprint-override"><code>import functools def decorator_with_arguments(decorator): """ Wrap a decorator, allowing it to accept arbitrary arguments. """ @functools.wraps(decorat...
1
2016-06-28T02:18:29Z
[ "python", "decorator", "python-decorators", "idiomatic" ]
python request response (binary)
38,066,036
<p>I am trying to do a small project with Python to use TD Ameritrade API. In the API instruction by TD, it says the request URL for PriceHistory is:</p> <p><a href="https://apis.tdameritrade.com/apps/100/PriceHistory?source=##SourceID#" rel="nofollow">https://apis.tdameritrade.com/apps/100/PriceHistory?source=##Sourc...
0
2016-06-28T02:17:43Z
38,066,416
<p>Perhaps you should verify that the get request actually returns something. You could use Postmaster or Advanced Rest Client to perform the <code>GET</code> request and check out the response. I suspect doing this will enlighten what is actually taking place. If you've already done this can you let me know what the r...
-1
2016-06-28T03:08:09Z
[ "python", "binary", "response" ]
python request response (binary)
38,066,036
<p>I am trying to do a small project with Python to use TD Ameritrade API. In the API instruction by TD, it says the request URL for PriceHistory is:</p> <p><a href="https://apis.tdameritrade.com/apps/100/PriceHistory?source=##SourceID#" rel="nofollow">https://apis.tdameritrade.com/apps/100/PriceHistory?source=##Sourc...
0
2016-06-28T02:17:43Z
38,077,636
<p>update:</p> <pre><code>EOR_url = (the above URL, omitted here) r = request.get(EOR_url) h = binascii.b2a_hex(r.content) print h </code></pre> <p>now it is printing out results just like that given in the TD API instruction:</p> <p>00 00 00 01 00 04 41 4D 54 44 00 00 00 00 02 41 97 33 33 41 99 5C 29 41 90 3D 71 41...
0
2016-06-28T13:30:05Z
[ "python", "binary", "response" ]
Running phantomjs on linux using python
38,066,060
<p>I followed <a href="http://stackoverflow.com/questions/8778513/how-can-i-setup-run-phantomjs-on-ubuntu">this link</a> and now when I type <code>phan</code> and then tab (<code>\t</code>) it does autocomplete to phantomJS.</p> <p>Yet if I run <code>phantomJS -v</code> or <code>phantomJS --version</code> I get:</p> ...
0
2016-06-28T02:20:55Z
38,099,484
<p>It very much sounds like a 64 vs 32 bits issue.</p> <p>To find out whats the version of your ubuntu, you can run</p> <pre><code>$ uname -i x86_64 </code></pre> <p>Then make sure to <a href="http://phantomjs.org/download.html" rel="nofollow">download</a> the correct version of phantom</p> <ul> <li>32 bits version...
2
2016-06-29T12:25:32Z
[ "python", "linux", "phantomjs" ]
Python‘s print function failed in Docker
38,066,067
<p>I want to print something in my python Docker. But it failed when print function in While loop. It works when it like this:</p> <pre><code>import time time.sleep(5) print('hello') </code></pre> <p>But it failed, it means, nothing will be show up in my terminal, when it like this:</p> <pre><code>import time whil...
-1
2016-06-28T02:22:06Z
38,089,545
<p>I have fixed it by another question. You can simply run the python like this in Dockerfile:</p> <pre><code>CMD python -u app.py </code></pre>
-1
2016-06-29T02:49:55Z
[ "python", "docker" ]
How to order the items downloaded by scrapy?
38,066,083
<p>So since it looks like Scrapy downloads images in a random order, I've been trying to find a way to sort images in either one of two ways:</p> <ol> <li>Download in the order which the urls were scraped </li> <li>Sort the files (perhaps by using meta data?) by the order which they came in the url list</li> </ol> <p...
0
2016-06-28T02:24:14Z
38,066,538
<p>A solution that may or may not work depending on the page would be for you to parse the HTML using lxml and building your own tree structure for images. You traverse the HTML tree and find the levels of the images and build your own tree out of it. Pretend you have this page:</p> <pre><code> |x| |x| |x| |x| |x|...
1
2016-06-28T03:23:43Z
[ "python", "scrapy" ]
Scrapy FormRequest , trying to send a post request (FormRequest) with currency change formdata
38,066,229
<p>I've been trying to scrapy the following <a href="https://www.mooda.com/en/" rel="nofollow">Website</a> but with the currency changed to 'SAR' from the upper left settings form , i tried sending a scrapy request like this: </p> <pre><code>r = Request(url='https://www.mooda.com/en/', cookies=[{'name': 'currency', ...
2
2016-06-28T02:44:46Z
38,069,653
<p>It is all about the <em>frontend</em> cookie, I will show you how to do it with requests first, the logic will be exactly the same with Scrapy:</p> <pre><code>head = { "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0"} # import requests from bs4 import BeautifulSoup...
0
2016-06-28T07:24:38Z
[ "python", "web-scraping", "scrapy", "scrapy-spider", "scrapy-shell" ]
How to training/testing without make all of the data float32 in Keras?
38,066,307
<p>I'm trying to do image recognition, so I looked at <a href="https://github.com/fchollet/keras/blob/master/examples/cifar10_cnn.py" rel="nofollow">the CIFAR10</a> example of Keras.</p> <p>Before fitting the model to the data, the data (<code>X_train</code>/<code>X_test</code>) needs to be normalize to 0-1 and conver...
2
2016-06-28T02:53:54Z
38,103,927
<p>You can do the conversion once and store the normalized, converted data to a file which you load for training, this way you don't need to convert it every time.</p> <p>For example (<code>normalize.py</code> / python 3):</p> <pre><code>from keras.datasets import cifar10 import pickle (X_train, y_train), (X_test, y...
1
2016-06-29T15:25:59Z
[ "python", "keras" ]
signal handler not working in python
38,066,396
<p>I am writing an asynchronous video playing program on Raspberry Pi. I need to run omxplayer in a subprocess and receive input in main process. When some input is received, main process would send the signal to the subprocess. </p> <p>Here is my code:</p> <pre><code>def worker(): p = subprocess.Popen(['omxplaye...
1
2016-06-28T03:05:52Z
38,075,468
<p>According to the code you posted, the worker will call <code>Popen</code> set the signal handler and then it will exit. </p> <p>The subsequent call to <code>os.kill</code> in your code will send the signal to an already expired process.</p> <p>In general, it's better not to use signals to communicate between proce...
2
2016-06-28T11:50:49Z
[ "python", "subprocess", "multiprocessing", "signals" ]
Django file upload form constructor explained
38,066,404
<p>As I go through Django tutorial, I'm confused about the way the form is constructed, here is the <a href="https://docs.djangoproject.com/en/1.9/topics/http/file-uploads/#basic-file-uploads" rel="nofollow">link</a> where the following code is from:</p> <p>forms.py</p> <pre><code>from django import forms class Uplo...
0
2016-06-28T03:06:25Z
38,066,522
<p>here is the constructor declaration: <a href="https://github.com/django/django/blob/master/django/forms/forms.py#L72-L98" rel="nofollow">https://github.com/django/django/blob/master/django/forms/forms.py#L72-L98</a> </p> <p>Question answered?</p>
2
2016-06-28T03:21:29Z
[ "python", "django" ]
How trustworthy is Google API?
38,066,481
<p>im currently learning Python and Im looking into writing a few tools that utilizes Google API so i can manipulate Google Sheets. But im wondering how "stable" it is. </p> <p>My understanding is that they recently updated to v4 of their API for Google Sheets. Which means there were 3 versions before that. </p> <p>H...
-1
2016-06-28T03:16:04Z
38,067,927
<p>Generally when an API is updated, the previous version remains available for a while (in a <em>deprecated</em> state). Currently, Google Spreadsheets API v3 is still available according to the <a href="https://developers.google.com/google-apps/spreadsheets/" rel="nofollow">API Documentation</a>; however, it is depre...
1
2016-06-28T05:43:27Z
[ "python", "google-api", "google-spreadsheet", "google-sheets-api" ]
Stop replacement by pattern?
38,066,494
<p>Say my file look like this:</p> <pre><code>some lines tom some lines beginword a b some lines endword jim some lines beginword x y some lines endword ... </code></pre> <p>Want to be:</p> <pre><code>some lines tom some lines beginword ZZ b some lines endword jim some lines beginword x y some lines endword </code><...
0
2016-06-28T03:17:47Z
38,066,644
<p>Use <a href="https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops" rel="nofollow">break</a> statement</p> <pre><code>input = open("file", "r") output = open("file_updated", "w") dummy = "" item = [] for line in input: dummy += line if line.find("tom" + ...
0
2016-06-28T03:38:14Z
[ "python" ]
Sorting Input from Multiple HIDs in Windows
38,066,526
<p>I have found a number of answers in pulling information from HIDs in Linux, but not many in Windows.</p> <p>I have created a system where a person can scan an ID badge when entering a briefing that logs their attendance into a database. It utilizes a Python 3.4 front end which queries and then updates a MongoDB da...
0
2016-06-28T03:21:55Z
38,120,429
<p>In this scenario I will suggest using scanners/readers that can emulate serial (COM) port. As HID device writes to same bus then there is a huge probability that output from two or more devices could by mixed-up.</p> <p>More over I will add a device id string to a prefix like <code>dev01</code>. Binding to a com po...
0
2016-06-30T10:26:24Z
[ "python", "mongodb", "windows-7", "barcode-scanner", "hid" ]
Numpy 3D array arranging and reshaping
38,066,536
<p>I have a 3D numpy array that I need to reshape and arrange. For example, I have <code>x=np.array([np.array([np.array([1,0,1]),np.array([1,1,1]),np.array([0,1,0]),np.array([1,1,0])]),np.array([np.array([0,0,1]),np.array([0,0,0]),np.array([0,1,1]),np.array([1,0,0])]),np.array([np.array([1,0,0]),np.array([1,0,1]),np.ar...
1
2016-06-28T03:23:24Z
38,066,624
<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.swapaxes.html" rel="nofollow"><code>swapaxes</code></a> will do what you want. That is, if your input array is <code>x</code> and your desired output is <code>y</code>, then</p> <pre><code>np.all(y==np.swapaxes(x, 1, 0)) </code></pre> <p>should gi...
3
2016-06-28T03:35:40Z
[ "python", "numpy" ]
Uber Rides/Python - How to configure Oauth w. Apache
38,066,571
<p>I'm new to this so I apologize in advance. I am actually an AppleScript developer and would merely like to use Uber Rides.py into a script, and I have virtually no knowledge in Python. (Just looking for an 'easy' way to initiate a Uber ride within a more complex script using Homebridge and Siri). </p> <p>I've built...
1
2016-06-28T03:28:49Z
38,066,664
<p>Same person from GitHub. After digging around, I came up with <a href="http://stackoverflow.com/a/36834041/5817707">this</a>.</p> <p>Basically there is probably a configuration issue in either your example/config.yaml or in your app dashboard. Make sure you configured both of those correctly. the example/config.yam...
0
2016-06-28T03:40:16Z
[ "python", "apache", "oauth", "applescript", "uber-api" ]
What is the Python equivalent of Java's UnsupportedOperationException?
38,066,640
<p>I'm looking at Python's <a href="https://docs.python.org/2/library/exceptions.html" rel="nofollow">built-in exceptions</a> and wondering what the closest equivalent of Java's <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/UnsupportedOperationException.html" rel="nofollow"><code>UnsupportedOperationExce...
1
2016-06-28T03:37:50Z
38,066,697
<p>The closest equivalent is to simply not implement the unsupported method. The resulting exception if you try to use the nonexistent method is an <code>AttributeError</code>.</p>
5
2016-06-28T03:44:03Z
[ "java", "python", "exception", "custom-exceptions" ]
What is the Python equivalent of Java's UnsupportedOperationException?
38,066,640
<p>I'm looking at Python's <a href="https://docs.python.org/2/library/exceptions.html" rel="nofollow">built-in exceptions</a> and wondering what the closest equivalent of Java's <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/UnsupportedOperationException.html" rel="nofollow"><code>UnsupportedOperationExce...
1
2016-06-28T03:37:50Z
38,066,718
<p>I don't know Java, but looking at what you linked to (and a few examples online), I'd say there is no single equivalent. That is quite a broad description for an exception type.</p> <p>If the operation isn't supported because the types of the operands are wrong, you'd use TypeError. If it isn't supported because ...
1
2016-06-28T03:46:32Z
[ "java", "python", "exception", "custom-exceptions" ]
np.ndarray with Periodic Boundary conditions
38,066,785
<h2>Problem</h2> <p>To impose <code>np.ndarray</code> periodic boundary conditions as laid out below</p> <h2>Details</h2> <ul> <li>Wrap the indexing of a python <code>np.ndarray</code> around the boundaries in <code>n</code>-dimensions</li> <li>This is a periodic boundary condition forming an <code>n</code>-dimensio...
0
2016-06-28T03:56:21Z
38,066,786
<h2>Wrap function</h2> <p>A simple function can be written with the <code>mod</code> function, <code>%</code> in basic python and generalised to operate on an <code>n</code>-dimensional tuple given a specific shape.</p> <pre><code>def latticeWrapIdx(index, lattice_shape): """returns periodic lattice index fo...
0
2016-06-28T03:56:21Z
[ "python", "numpy", "multidimensional-array", "indexing", "boundary" ]
Print reverse of a number
38,066,801
<p>I tried running the following code. I tried returning value of j also but it just doesn't work. </p> <pre><code>def reverse(n): j=0 while(n!=0): j=j*10 j=j + (n%10) n=n/10 print(j) reverse(45) </code></pre>
-2
2016-06-28T03:57:56Z
38,066,998
<p>Here is a program to reverse a number</p> <pre><code>def reverse(n): v = [] for item in reversed(list(str(n))): v.append(item) return ''.join(v) print(reverse("45")) </code></pre> <p>returns</p> <pre><code>54 </code></pre> <p>The reverse() function creates an array, adds each digit from the ...
1
2016-06-28T04:19:20Z
[ "python", "python-3.x" ]
Print reverse of a number
38,066,801
<p>I tried running the following code. I tried returning value of j also but it just doesn't work. </p> <pre><code>def reverse(n): j=0 while(n!=0): j=j*10 j=j + (n%10) n=n/10 print(j) reverse(45) </code></pre>
-2
2016-06-28T03:57:56Z
38,067,023
<p>Here is the correct code for Python 3:</p> <pre><code>import sys def reverse(x): while x&gt;0: sys.stdout.write(str(x%10)) x = x//10 # x = x/10 (Python 2) print() # print (Python 2) </code></pre>
0
2016-06-28T04:22:36Z
[ "python", "python-3.x" ]
Print reverse of a number
38,066,801
<p>I tried running the following code. I tried returning value of j also but it just doesn't work. </p> <pre><code>def reverse(n): j=0 while(n!=0): j=j*10 j=j + (n%10) n=n/10 print(j) reverse(45) </code></pre>
-2
2016-06-28T03:57:56Z
38,068,642
<p>Actually, you made one mistake only: for Python 3 you need to use an integer division: n = n // 10. Here is the correct code without str and list:</p> <pre><code>def reverse(n): j = 0 while n != 0: j = j * 10 j = j + (n%10) n = n // 10 print(j) reverse(12345) </code></pre>
0
2016-06-28T06:30:45Z
[ "python", "python-3.x" ]
Print reverse of a number
38,066,801
<p>I tried running the following code. I tried returning value of j also but it just doesn't work. </p> <pre><code>def reverse(n): j=0 while(n!=0): j=j*10 j=j + (n%10) n=n/10 print(j) reverse(45) </code></pre>
-2
2016-06-28T03:57:56Z
38,071,379
<pre><code>number = 45 int(str(number)[::-1]) </code></pre>
0
2016-06-28T08:50:31Z
[ "python", "python-3.x" ]
Python best way to remove char from string by index
38,066,836
<p>I'm removing an char from string like this:</p> <pre><code>S = "abcd" Index=1 #index of string to remove ListS = list(S) ListS.pop(Index) S = "".join(ListS) print S #"acd" </code></pre> <p>I'm sure that this is <strong>not</strong> the best way to do it. </p> <p><strong>EDIT</strong> I didn't mentioned that I nee...
0
2016-06-28T04:02:02Z
38,066,869
<p>You can bypass all the list operations with slicing:</p> <pre><code>S = S[:1] + S[2:] </code></pre> <p>or more generally</p> <pre><code>S = S[:Index] + S[Index + 1:] </code></pre> <p>Many answers to your question (including ones like this) can be found here: <a href="http://stackoverflow.com/q/3559559/2988730">H...
5
2016-06-28T04:05:39Z
[ "python", "string", "python-2.7", "python-3.x", "substring" ]
Python best way to remove char from string by index
38,066,836
<p>I'm removing an char from string like this:</p> <pre><code>S = "abcd" Index=1 #index of string to remove ListS = list(S) ListS.pop(Index) S = "".join(ListS) print S #"acd" </code></pre> <p>I'm sure that this is <strong>not</strong> the best way to do it. </p> <p><strong>EDIT</strong> I didn't mentioned that I nee...
0
2016-06-28T04:02:02Z
38,066,941
<p>Slicing is the best and easiest approach I can think of, here are some other alternatives:</p> <pre><code>&gt;&gt;&gt; s = 'abcd' &gt;&gt;&gt; def remove(s, indx): return ''.join(x for x in s if s.index(x) != indx) &gt;&gt;&gt; remove(s, 1) 'acd' &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; def remove(s, indx)...
2
2016-06-28T04:14:25Z
[ "python", "string", "python-2.7", "python-3.x", "substring" ]
Python best way to remove char from string by index
38,066,836
<p>I'm removing an char from string like this:</p> <pre><code>S = "abcd" Index=1 #index of string to remove ListS = list(S) ListS.pop(Index) S = "".join(ListS) print S #"acd" </code></pre> <p>I'm sure that this is <strong>not</strong> the best way to do it. </p> <p><strong>EDIT</strong> I didn't mentioned that I nee...
0
2016-06-28T04:02:02Z
38,066,942
<p>You can replace the Index character with "".</p> <pre><code>str = "ab1cd1ef" Index = 3 print(str.replace(str[Index],"",1)) </code></pre>
-1
2016-06-28T04:14:27Z
[ "python", "string", "python-2.7", "python-3.x", "substring" ]
Why 'self' needed for patch and assert in Python?
38,066,839
<p>I usually use:</p> <pre><code>def create_patch(self, name, value = None): patcher = patch(name) mock = patcher.start() mock.return_value = value self.addCleanup(patcher.stop) return mock def assertXmlEqual(self, a, b): with open(a, 'r') as f: axml = f.read() with open(b, 'r') as...
0
2016-06-28T04:02:18Z
38,067,013
<p>You can create a base test case and then have all of your other test cases inherit from <em>that</em> instead of <code>unittest.TestCase</code>:</p> <pre><code>class MyBaseTestCase(unittest.TestCase): def create_patch(self, name, value = None): patcher = patch(name) mock = patcher.start() ...
2
2016-06-28T04:20:38Z
[ "python", "unit-testing", "mocking", "patch", "assert" ]
How can I convert a string sent over UART to integer in python?
38,066,860
<p>I'm having difficulty converting a string I'm receiving over UART to the decimal version of it. I read in one byte with <code>port.read(1)</code> then print it</p> <pre><code>print "%s: %s" % ( time.ctime(time.time()), str) </code></pre> <p>This prints out the expected character that matches with the decimal value...
0
2016-06-28T04:04:55Z
38,066,987
<p>python works perfectly, it is your avr code that is broken.</p> <p>remember what you are sending is a byte with the value 0 to 100, then on the python side you are treating this byte as a string, but characters are mapped through ascii or unicode character maps, so you are getting some characters, but not necessary...
0
2016-06-28T04:18:26Z
[ "python", "utf-8", "avr", "avr-gcc" ]
create anaconda python environment with all packages
38,066,873
<p>I want to create an anaconda python environment with <strong>all</strong> of the packages that Continuum includes in its default Anaconda installer. Based on some internet search I used the following command:</p> <pre><code>conda create -n env_full python=3 </code></pre> <p>However, only handful of packages would ...
0
2016-06-28T04:06:23Z
38,084,286
<p>Surely you don't mean install <em>all</em> available packages, right? Continuum's default channel alone has 635 of them, and there are countless others on other channels. </p> <p>I think @cel is right above to assume that you're specifically asking to install all of the packages that Continuum includes in its defau...
2
2016-06-28T19:03:09Z
[ "python", "anaconda" ]
reading hash from md5 in python
38,066,894
<p>I can't seem to find anything on the interwebs on this.</p> <p>Basically I have a bunch of xml files with a respective md5 file for each</p> <p>I want to be able to compare each xml with its md5 hash to ensure they have been sent to us correctly.</p> <p>I have tried running this as a binary file but I don't think...
1
2016-06-28T04:09:09Z
38,067,210
<p>Use <a href="https://docs.python.org/3/library/binascii.html#binascii.hexlify" rel="nofollow"><code>binascii.hexlify</code></a> to get hexa-decimal representation:</p> <pre><code>&gt;&gt;&gt; import binascii &gt;&gt;&gt; binascii.hexlify(b' \xc0\xff\xae\x91\x1c\tJ\xc5~\xbe\x8d\x93\xad\xf3\x0c') b'20c0ffae911c094ac5...
1
2016-06-28T04:44:45Z
[ "python", "xml", "python-3.x", "md5" ]
Best way to have a custom FloatField with an editable comment parameter
38,066,896
<p>I'm fairly new to Django and I mostly write code for scientific and engineering applications. Python is great for these and I find myself wanting to share some of the apps with a better interface - hence my interest in Django. </p> <p>In one application that I'm trying to port over to Django, there are dozens of pa...
0
2016-06-28T04:09:20Z
38,067,185
<blockquote> <p>In one application that I'm trying to port over to Django, there are dozens of parameters that each have a comment associated with them that is user editable.</p> </blockquote> <p>If I understand you correctly, you are describing at least two distinct fields: the float, and the text. You won't be...
0
2016-06-28T04:41:26Z
[ "python", "django" ]
Best way to have a custom FloatField with an editable comment parameter
38,066,896
<p>I'm fairly new to Django and I mostly write code for scientific and engineering applications. Python is great for these and I find myself wanting to share some of the apps with a better interface - hence my interest in Django. </p> <p>In one application that I'm trying to port over to Django, there are dozens of pa...
0
2016-06-28T04:09:20Z
38,068,483
<p>Django has a <a href="https://docs.djangoproject.com/en/1.9/ref/forms/fields/#django.forms.MultiValueField" rel="nofollow">MultiValueField field type</a> that is to be subclassed for situations where a form displays two or more fields that are turned into a single value to be stored in the database. In reverse, a si...
0
2016-06-28T06:22:42Z
[ "python", "django" ]
Python Exception Handling -- Return to Line, Continue
38,066,925
<p>I do a lot of Project Euler coding problems, and Python is my go-to language. A lot of programs typically take forever to complete, so I'm working on implementing something that'll help give diagnostic info on the state of the program: when a <code>KeyboardInterrupt</code> occurs I want to be able print how long the...
3
2016-06-28T04:12:44Z
38,067,167
<p>In general you can never return execution to the specific code segment after an exception was triggered within a try block, given that the exception could occur deep somewhere with a number of other states that are influenced by other side effects in other threads. While this is likely not the case with your progra...
2
2016-06-28T04:39:36Z
[ "python", "exception", "continue", "keyboardinterrupt" ]
Python Exception Handling -- Return to Line, Continue
38,066,925
<p>I do a lot of Project Euler coding problems, and Python is my go-to language. A lot of programs typically take forever to complete, so I'm working on implementing something that'll help give diagnostic info on the state of the program: when a <code>KeyboardInterrupt</code> occurs I want to be able print how long the...
3
2016-06-28T04:12:44Z
38,067,187
<blockquote> <p>“Yeah,” said Harry. “In . . . in a minute. I’ll just clear this up.” He indicated the smashed bowl on the floor. Ron nodded and left. “ Reparo, ” Harry muttered, pointing his wand at the broken pieces They flew back together, good as new, but there was no re- turning the murtlap ...
1
2016-06-28T04:41:46Z
[ "python", "exception", "continue", "keyboardinterrupt" ]
Converting ratio to floating points
38,066,944
<p>I have a list of data in the form of "x : y", and I am trying to convert it to the floating point number x/y. Below is my code</p> <pre><code>def ratio_to_float (ratio): [numer,denum] = ratio.split(" : ") if int(denum) == 0: num = math.inf else: num = int(numer)/int(denum) return num...
0
2016-06-28T04:14:30Z
38,067,012
<p><code>.split(":")</code> remove spaces.</p> <p>Code:</p> <pre><code>def ratio_to_float(ratio): numer,denum = ratio.split(":") if int(denum) == 0: num = math.inf print(num) else: num = int(numer)/int(denum) print(num) return num ratio_to_float("10:5") </code></pre> ...
0
2016-06-28T04:20:30Z
[ "python", "python-3.x" ]
Converting ratio to floating points
38,066,944
<p>I have a list of data in the form of "x : y", and I am trying to convert it to the floating point number x/y. Below is my code</p> <pre><code>def ratio_to_float (ratio): [numer,denum] = ratio.split(" : ") if int(denum) == 0: num = math.inf else: num = int(numer)/int(denum) return num...
0
2016-06-28T04:14:30Z
38,067,068
<p>The error you're getting says that <code>split</code> is only returning a one-value list at some point. That means that somewhere while your program is running it is calling your function with a string that does not contain <code>" : "</code> in it. If you're operating on a list of ratios, perhaps one is malformed (...
1
2016-06-28T04:27:29Z
[ "python", "python-3.x" ]
Converting ratio to floating points
38,066,944
<p>I have a list of data in the form of "x : y", and I am trying to convert it to the floating point number x/y. Below is my code</p> <pre><code>def ratio_to_float (ratio): [numer,denum] = ratio.split(" : ") if int(denum) == 0: num = math.inf else: num = int(numer)/int(denum) return num...
0
2016-06-28T04:14:30Z
38,067,118
<p>Also you can do this by making a List. <strong>Tha main reason to use a list, you can take many floating number and getting a result by iteration.</strong><br> remove <code>space</code> from <code>ratio.split(" : ")</code> to <code>ratio.split(":")</code></p> <pre><code>def ratio_to_float(ratio): numer = ratio....
0
2016-06-28T04:33:12Z
[ "python", "python-3.x" ]
Converting ratio to floating points
38,066,944
<p>I have a list of data in the form of "x : y", and I am trying to convert it to the floating point number x/y. Below is my code</p> <pre><code>def ratio_to_float (ratio): [numer,denum] = ratio.split(" : ") if int(denum) == 0: num = math.inf else: num = int(numer)/int(denum) return num...
0
2016-06-28T04:14:30Z
38,067,383
<p>If you're working with a <code>pandas</code> series, then here's my take on it. You can use the builtin <code>fractions.Fraction</code> class and a bit of string manipulation to do the lifting...</p> <pre><code>import pandas as pd from fractions import Fraction s = pd.Series(["37 : 63", "100 : 0", "45 : 55"]) def...
0
2016-06-28T05:00:06Z
[ "python", "python-3.x" ]
Unable to install urllib.request on Python 3.5
38,066,976
<p>I'm trying to install the urllib.request module but I get this error each time : <em>Could not find a version that satisfies the requirement urllib (from versions: ) No matching distribution found for urllib</em></p> <p>How do I install urllib for Python 3.5?</p>
0
2016-06-28T04:17:24Z
38,067,008
<p>It's part of the standard library: <a href="https://docs.python.org/3/library/urllib.request.html" rel="nofollow">https://docs.python.org/3/library/urllib.request.html</a></p>
0
2016-06-28T04:20:16Z
[ "python", "request", "urllib", "python-module" ]
dev_appserver.py does nothing
38,067,195
<p>Currently I'm new to appengine with python and now I'm following this tutorial. <a href="https://cloud.google.com/appengine/docs/python/gettingstartedpython27/creating-guestbook#objectives" rel="nofollow">https://cloud.google.com/appengine/docs/python/gettingstartedpython27/creating-guestbook#objectives</a> Somehow,...
0
2016-06-28T04:42:00Z
38,097,620
<p>I solved on it on my own guys. I was using gitbash so I switched to cmd and removed the slash at the end and it worked.</p>
0
2016-06-29T10:58:57Z
[ "python", "google-app-engine", "google-app-engine-python" ]
Comparing list values between two dictionaries that have no matching keys
38,067,263
<p>I have two dictionaries where they keys won't match, but values will. All values in each dictionary contain 3 list items as ints.</p> <pre><code>dict1 = {'red':[1,2,3],'blue':[2,3,4],'orange':[3,4,5]} dict2 = {'green':[3,4,5],'yellow':[2,3,4],'red':[5,2,6]} </code></pre> <p>I would like to compare each list and f...
0
2016-06-28T04:49:55Z
38,067,304
<p>You can use a list comprehension (which is just a shortcut for "for loops"):</p> <pre><code>matching = [(k1, k2) for k1 in dict1 for k2 in dict2 if dict1[k1] == dict2[k2]] print matching # [('blue', 'yellow'), ('orange', 'green')] </code></pre>
1
2016-06-28T04:53:38Z
[ "python", "list", "dictionary", "compare" ]
Comparing list values between two dictionaries that have no matching keys
38,067,263
<p>I have two dictionaries where they keys won't match, but values will. All values in each dictionary contain 3 list items as ints.</p> <pre><code>dict1 = {'red':[1,2,3],'blue':[2,3,4],'orange':[3,4,5]} dict2 = {'green':[3,4,5],'yellow':[2,3,4],'red':[5,2,6]} </code></pre> <p>I would like to compare each list and f...
0
2016-06-28T04:49:55Z
38,067,386
<p>For any case if you don't understand Julien's answer, this doing the same thing.</p> <pre><code>dict1 = {'red':[1,2,3],'blue':[2,3,4],'orange':[3,4,5]} dict2 = {'green':[3,4,5],'yellow':[2,3,4],'red':[5,2,6]} for k1,v1 in dict1.items(): #each key and value in dict1 for k2,v2 in dict2.items(): #each key and va...
-1
2016-06-28T05:00:28Z
[ "python", "list", "dictionary", "compare" ]
Comparing list values between two dictionaries that have no matching keys
38,067,263
<p>I have two dictionaries where they keys won't match, but values will. All values in each dictionary contain 3 list items as ints.</p> <pre><code>dict1 = {'red':[1,2,3],'blue':[2,3,4],'orange':[3,4,5]} dict2 = {'green':[3,4,5],'yellow':[2,3,4],'red':[5,2,6]} </code></pre> <p>I would like to compare each list and f...
0
2016-06-28T04:49:55Z
38,068,720
<p>Just keep it nice and simple:</p> <pre><code>dict1 = {'red':[1,2,3],'blue':[2,3,4],'orange':[3,4,5]} dict2 = {'green':[3,4,5],'yellow':[2,3,4],'red':[5,2,6]} matches = [] for key1 in dict1: for key2 in dict2: if dict1[key1] == dict2[key2]: matches.append((key1, key2)) print(matches) </cod...
1
2016-06-28T06:35:14Z
[ "python", "list", "dictionary", "compare" ]
optimize function that includes large matrix operations
38,067,292
<p>I might do a poor job of explaining this, so I'll use an example somewhat similar to my problem, but here goes:</p> <p>I need to compute a complex operation (repeatedly) that is a function of only a few scalars, say, x1, x2 and x3. Then a matrix whose elements are determined by a function of x1, x2, x3 (and the ro...
2
2016-06-28T04:52:30Z
38,068,018
<p>Expressing the problem in <code>einsum</code> terms might help:</p> <pre><code>np.einsum('ij,jk,kl,lm,nm-&gt;in', X, A, B, C, X) </code></pre> <p>which might profitably be broken into 2 steps:</p> <pre><code>ABC = np.einsum('jk,kl,lm-&gt;jm', A, B, C) # k by k np.einsum('ij,jm,nm-&gt;in', X, ABC, X) </code></pre>...
1
2016-06-28T05:51:37Z
[ "python", "numpy", "linear-algebra", "theano", "sympy" ]
optimize function that includes large matrix operations
38,067,292
<p>I might do a poor job of explaining this, so I'll use an example somewhat similar to my problem, but here goes:</p> <p>I need to compute a complex operation (repeatedly) that is a function of only a few scalars, say, x1, x2 and x3. Then a matrix whose elements are determined by a function of x1, x2, x3 (and the ro...
2
2016-06-28T04:52:30Z
38,082,874
<p>Since you mentioned SymPy, you can easily compute the whole thing once with </p> <pre><code>x1, x2, x3 = symbols('x1, x2, x3') X = Matrix(...) A = Matrix(...) B = Matrix(...) C = Matrix(...) </code></pre> <p>(replace <code>...</code> with the actual matrix entries). Then compute the product</p> <pre><code>result ...
1
2016-06-28T17:40:34Z
[ "python", "numpy", "linear-algebra", "theano", "sympy" ]
Getting 'integer out of range' error sqlalchemy
38,067,315
<p>So, I am using <code>odo</code> for data migration but came across this error: </p> <pre><code>sqlalchemy.exc.DataError: (psycopg2.DataError) integer out of range </code></pre> <p>Both the source and the destination tables have the same schema but in the sql statement being executed in the backend the integer va...
0
2016-06-28T04:54:51Z
38,074,845
<p>The sql string should be:</p> <pre><code>INSERT INTO table2 (col1, col2, col3) VALUES ( %(col1)s::numeric::int, %(col2)s::numeric::int, %(col3)s::numeric::int ) </code></pre> <p>If the target column is not nullable and the source value can be <code>None</code> then coalesce it:</p> <pre><code> co...
0
2016-06-28T11:21:44Z
[ "python", "postgresql", "sqlalchemy", "blaze", "odo" ]
Database Cursor
38,067,324
<p>In Python, what is a database "cursor" most like?</p> <ol> <li><p>A method within a class</p></li> <li><p>A Python dictionary</p></li> <li><p>A function</p></li> <li><p>A file handle</p></li> </ol> <p>I have searched on internet but I am not getting proper justification of this question.</p>
2
2016-06-28T04:55:23Z
38,067,356
<p>According to the <a href="https://www.python.org/dev/peps/pep-0249/#cursor-objects" rel="nofollow">PEP 249 (Python Database API Specification)</a>, it is an <strong>object</strong> which is expected to have certain attributes and methods defined. Optionally, <a href="https://www.python.org/dev/peps/pep-0249/#iter" r...
2
2016-06-28T04:58:11Z
[ "python", "database", "cursor" ]
Database Cursor
38,067,324
<p>In Python, what is a database "cursor" most like?</p> <ol> <li><p>A method within a class</p></li> <li><p>A Python dictionary</p></li> <li><p>A function</p></li> <li><p>A file handle</p></li> </ol> <p>I have searched on internet but I am not getting proper justification of this question.</p>
2
2016-06-28T04:55:23Z
38,067,434
<p>Probably it is <em>most like</em> a file handle.</p> <p>That does not mean that it is a file handle, and a cursor is actually an object - an instance of a <code>Cursor</code> class (depending on the actual db driver in use).</p> <p>The reason that it's similar to a file handle is that you can consume data from it,...
1
2016-06-28T05:05:08Z
[ "python", "database", "cursor" ]
Creating datetime in pandas from year and julian day
38,067,348
<pre><code> ad_name adl_name year JD 0 united_states_of_america colorado 2000 1 1 united_states_of_america colorado 2000 2 2 united_states_of_america colorado 2000 3 3 united_states_of_america colorado 2000 4 4 united_states_of_america colorado 2000 5 </code></pre> ...
1
2016-06-28T04:57:46Z
38,067,408
<p>You need add to <code>year</code> column <code>JD</code> converted <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html" rel="nofollow"><code>to_timedelta</code></a>:</p> <pre><code>df['date'] = pd.to_datetime(df.year, format='%Y') + pd.to_timedelta(df.JD - 1, unit='d') print (df)...
1
2016-06-28T05:02:03Z
[ "python", "datetime", "pandas", "dataframe", "time-series" ]