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 |
|---|---|---|---|---|---|---|---|---|---|
How to use TensorFlow gradient descent optimizer to solve optimization problems | 38,067,443 | <p>I'm trying to use TensorFlow's Gradient Descent Optimizer to solve 2-dimension Rosenbrock function, but as I ran the program, the optimizer sometimes goes towards the infinity. Also sometime, without changing anything, it can find the right neighborhood but not pinpoint the optimal solution.</p>
<p>My code is as fo... | 1 | 2016-06-28T05:05:59Z | 38,071,363 | <p>If you decrease the variation of initial x1/x2 (e.g. use -3/3 instead of -10/10) and decrease the learning rate by a factor of 10, it shouldn't blow up as often. Decreasing learning rate when you see things diverging is often a good thing to try.</p>
<p>Also, the function you're optimizing is made for being difficu... | 2 | 2016-06-28T08:49:42Z | [
"python",
"optimization",
"tensorflow"
] |
How to use TensorFlow gradient descent optimizer to solve optimization problems | 38,067,443 | <p>I'm trying to use TensorFlow's Gradient Descent Optimizer to solve 2-dimension Rosenbrock function, but as I ran the program, the optimizer sometimes goes towards the infinity. Also sometime, without changing anything, it can find the right neighborhood but not pinpoint the optimal solution.</p>
<p>My code is as fo... | 1 | 2016-06-28T05:05:59Z | 38,071,816 | <p>Yes, like @etarion says this is an optimization problem, your TensorFlow code is fine.</p>
<p>One way to make sure the gradients never explode is to clip them in the range <code>[-10., 10.]</code> for instance:</p>
<pre class="lang-py prettyprint-override"><code>opt = tf.train.GradientDescentOptimizer(0.0001)
grad... | 2 | 2016-06-28T09:08:51Z | [
"python",
"optimization",
"tensorflow"
] |
Calculate the total counts using pandas pivot table | 38,067,486 | <p>I have a dataframe like this:</p>
<pre><code>student class subject date status
jack class-1 maths 20150101 fail
jack class-1 maths 20150205 win
jack class-1 maths 20150310 fail
jack class-1 maths 20150... | 1 | 2016-06-28T05:09:24Z | 38,067,535 | <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 <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a>:</p>
<pre><code>df = df.p... | 0 | 2016-06-28T05:14:30Z | [
"python",
"pandas",
"dataframe",
"pivot",
"multiple-columns"
] |
Get Paragraph Content | 38,067,523 | <p>I am a bit confused in getting content of the paragraph tag.</p>
<pre><code><div class="SomeID">
<p>What a voice! </p>
</div>
</code></pre>
<p>I reached at this point </p>
<pre><code>list = soup.find_all("div","SomeID")
</code></pre>
<p>But how to get the paragraph content.(What a voice!)... | -1 | 2016-06-28T05:13:28Z | 38,067,536 | <p>You can actually do it one go with a <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors" rel="nofollow">CSS selector</a>:</p>
<pre><code>for p in soup.select("div.SomeID > p"):
print(p.get_text(strip=True))
</code></pre>
<p>Or, if you need a single <code>p</code> element:</p>
<pr... | 1 | 2016-06-28T05:14:32Z | [
"python",
"python-2.7",
"beautifulsoup",
"pydev"
] |
How to change the datetime format in pandas | 38,067,704 | <p>DOB column sample value is in the format - <code>1/1/2016</code> which by default gets converted to object as shown below</p>
<pre><code>DOB object
</code></pre>
<p>Converting to date format</p>
<pre><code>df['DOB'] = pd.to_datetime(df['DOB'])
</code></pre>
<p>Date converts to</p>
<pre><code>2016-01-26
</... | 2 | 2016-06-28T05:26:50Z | 38,067,805 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.strftime.html" rel="nofollow"><code>dt.strftime</code></a>, if need convert <code>datetime</code> to other formats, but then <code>dtype</code> of column is <code>object</code> (<code>string</code>):</p>
<pre><code>import pa... | 1 | 2016-06-28T05:34:37Z | [
"python",
"datetime",
"pandas"
] |
Panda: How to pivot one column in rows into columns | 38,067,726 | <p>Given this dataframe:</p>
<pre><code> feature score searchTerm
0 a 0.534509 pizza
1 b 0.586020 pizza
2 c 0.588972 pizza
3 a 0.566261 chinese
4 b 0.572405 chinese
5 c 0.489369 chinese
6 a 0.499068 thai
7 b 0.431068 thai
8 c 0.441617 thai
</code></pr... | 3 | 2016-06-28T05:28:32Z | 38,067,747 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="nofollow"><code>pivot</code></a>:</p>
<pre><code>df1 = df.pivot(index='searchTerm', columns='feature', values='score').reset_index()
print (df1)
feature searchTerm a b c
0 ch... | 3 | 2016-06-28T05:30:07Z | [
"python",
"pandas",
"dataframe",
"pivot",
"multiple-columns"
] |
Convert column containing string and NAN to list of integers in Pandas | 38,067,771 | <p>I have a data frame that I read from a CSV file, which contains some columns that contain lists. However they end up as a strings in Pandas, like column B in this example. I would like to turn this column into a new column containing a list of integers. A couple of complications. 1) The original column has some ... | 1 | 2016-06-28T05:31:49Z | 38,069,064 | <p>This should get it done:</p>
<pre><code>b = df.B.str.extract(r'\[(.*)\]', expand=False).str.split(',', expand=True).fillna(np.nan)
df['D'] = pd.DataFrame(b.apply(lambda x: tuple(x.values))).applymap(list)
</code></pre>
| 1 | 2016-06-28T06:53:44Z | [
"python",
"string",
"list",
"pandas",
"dataframe"
] |
How to write data in multiple nested dictionary into a .csv or .txt file in table format? | 38,067,809 | <p>I wrote a script to read data from a file and store them in 3 dictionaries.</p>
<p>For example,</p>
<pre><code>d1 = {'Ben': {'Skill': 'true', 'Magic': 'false'}, 'Tom': {'Skill': 'true', 'Magic': 'true'}}
d2 = {'Ben': {'Strength': 'wo_mana', 'Int': 'wi_mana', 'Speed': 'wo_mana'}, 'Tom': {'Int': 'wi_mana', 'Agility'... | 0 | 2016-06-28T05:34:49Z | 38,068,029 | <ol>
<li>It wouldn't make sense to have multiple rows for a record in csv so add both the lines to one. For example: <code>Strength = 1.10; Speed = 1.50</code></li>
</ol>
<p>So first store your result in a list and then join the list with <code>;</code>(or any char other then <code>,</code>)</p>
<ol start="2">
<li>Si... | 0 | 2016-06-28T05:52:39Z | [
"python",
"python-2.7",
"csv",
"dictionary"
] |
Odoo t-field image is appearing empty to public | 38,067,886 | <p>I have a simple controller when shows the people comment in the website along with their pictures. Everything works fine except the image is not appearing when the user logout. </p>
<p>here is my controller</p>
<pre><code> @http.route('/page/homepage', type='http', auth='public', website=True)
def comment_list(... | 0 | 2016-06-28T05:40:24Z | 38,071,676 | <p>Use img tag.
like</p>
<pre><code><span>
<img t-att-src="'p.image'" t-att-class="'img-rounded'" t-att-widget="'image'" />
</span>
</code></pre>
<p>Hope it will help you.</p>
| 0 | 2016-06-28T09:03:15Z | [
"python",
"openerp",
"odoo-8",
"odoo-9"
] |
Odoo t-field image is appearing empty to public | 38,067,886 | <p>I have a simple controller when shows the people comment in the website along with their pictures. Everything works fine except the image is not appearing when the user logout. </p>
<p>here is my controller</p>
<pre><code> @http.route('/page/homepage', type='http', auth='public', website=True)
def comment_list(... | 0 | 2016-06-28T05:40:24Z | 38,153,796 | <p>I found the problem, it was due to security reason, i add an open access rule of the module. and it worked!</p>
| 0 | 2016-07-01T20:59:41Z | [
"python",
"openerp",
"odoo-8",
"odoo-9"
] |
how to use pandas drop nan number, not drop all the row | 38,068,023 | <p>I need just delete the <code>NaN</code> element, not delete all the rows.</p>
<p>I hava a python dataframe list like :</p>
<pre><code>[[2.0, 3.0, 5.0, nan], [1.0, 3.0, 5.0, 6.0], [2.0, 5.0, nan, nan]]
</code></pre>
<p>How can I use pandas to change it as follow : just delete the <code>NaN</code> element</p>
<... | 0 | 2016-06-28T05:52:03Z | 38,068,242 | <p>If you want to print the data frame (df) without "nan" being displayed, you could just replace it with blank by </p>
<pre><code>df2=df.fillna("")
</code></pre>
<p>The resulting dataframe, (df2) will have the same number of rows and columns as original but blanks instead of nan.</p>
| -2 | 2016-06-28T06:06:55Z | [
"python",
"list",
"pandas",
"dataframe",
null
] |
how to use pandas drop nan number, not drop all the row | 38,068,023 | <p>I need just delete the <code>NaN</code> element, not delete all the rows.</p>
<p>I hava a python dataframe list like :</p>
<pre><code>[[2.0, 3.0, 5.0, nan], [1.0, 3.0, 5.0, 6.0], [2.0, 5.0, nan, nan]]
</code></pre>
<p>How can I use pandas to change it as follow : just delete the <code>NaN</code> element</p>
<... | 0 | 2016-06-28T05:52:03Z | 38,068,385 | <p>I think it is problem remove <code>NaN</code> from <code>DataFrame</code>, very nice it explain <a href="http://stackoverflow.com/questions/38068023/how-to-use-pandas-drop-nan-number-not-drop-all-the-row/38068385#comment63574586_38068023">Christoph Terasa</a>:</p>
<blockquote>
<p>Since pandas.DataFrames need to b... | 1 | 2016-06-28T06:16:48Z | [
"python",
"list",
"pandas",
"dataframe",
null
] |
how to use pandas drop nan number, not drop all the row | 38,068,023 | <p>I need just delete the <code>NaN</code> element, not delete all the rows.</p>
<p>I hava a python dataframe list like :</p>
<pre><code>[[2.0, 3.0, 5.0, nan], [1.0, 3.0, 5.0, 6.0], [2.0, 5.0, nan, nan]]
</code></pre>
<p>How can I use pandas to change it as follow : just delete the <code>NaN</code> element</p>
<... | 0 | 2016-06-28T05:52:03Z | 38,069,130 | <p>@jezrael is correct. pandas requires the dataframe to be rectangular. However, you can change the shape of your rectangle.</p>
<pre><code>df = pd.DataFrame([[2.0, 3.0, 5.0, np.nan], [1.0, 3.0, 5.0, 6.0], [2.0, 5.0, np.nan, np.nan]])
df
0 1 2 3
0 2.0 3.0 5.0 NaN
1 1.0 3.0 5.0 6.0
2 2.0 5.... | 1 | 2016-06-28T06:57:36Z | [
"python",
"list",
"pandas",
"dataframe",
null
] |
how to use pandas drop nan number, not drop all the row | 38,068,023 | <p>I need just delete the <code>NaN</code> element, not delete all the rows.</p>
<p>I hava a python dataframe list like :</p>
<pre><code>[[2.0, 3.0, 5.0, nan], [1.0, 3.0, 5.0, 6.0], [2.0, 5.0, nan, nan]]
</code></pre>
<p>How can I use pandas to change it as follow : just delete the <code>NaN</code> element</p>
<... | 0 | 2016-06-28T05:52:03Z | 38,069,205 | <p>Try this:</p>
<pre><code>df.replace('NaN', 0)
</code></pre>
<p>then simply exclude the 0</p>
<pre><code>df = df[df[] > 0]
</code></pre>
| 0 | 2016-06-28T07:01:19Z | [
"python",
"list",
"pandas",
"dataframe",
null
] |
deleting a file after uploading to s3 in python | 38,068,100 | <pre><code>def upload(s):
conn=tinys3.Connection("AKIAJPOZEBO47FJYS3OA","04IZL8X9wlzBB5LkLlZD5GI/",tls=True)
f = open(s,'rb')
z=str(datetime.datetime.now().date())
x=z+'/'+s
conn.upload(x,f,'crawling1')
os.remove(s)
</code></pre>
<p>The file is not deleting after i upload to <code>s3</... | 0 | 2016-06-28T05:58:04Z | 38,068,200 | <p>You have to close the file before you can delete it:</p>
<pre><code>import os
a = open('a')
os.remove('a')
>> Traceback (most recent call last):
File "main.py", line 35, in <module>
os.remove('a')
PermissionError: [WinError 32] The process cannot access the file because
it is being used... | 0 | 2016-06-28T06:04:12Z | [
"python",
"amazon-s3"
] |
Finding conditional probability of trigram in python nltk | 38,068,539 | <p>I have started learning <code>NLTK</code> and I am following a tutorial from <a href="http://www.katrinerk.com/courses/python-worksheets/language-models-in-python" rel="nofollow">here</a>, where they find conditional probability using bigrams like this.</p>
<pre><code>import nltk
from nltk.corpus import brown
cfreq... | 1 | 2016-06-28T06:25:45Z | 38,068,845 | <p>You can use the n-gram model described <a href="http://www.nltk.org/_modules/nltk/model/ngram.html" rel="nofollow">here</a>.</p>
<p>An example for usage:</p>
<pre><code>from nltk.util import ngrams
input= '...'
N = 3
trigrams = ngrams(input.split(), N)
for grams in trigrams:
print grams
</code></pre>
<p>I stro... | 0 | 2016-06-28T06:43:06Z | [
"python",
"nlp",
"nltk",
"n-gram"
] |
Finding conditional probability of trigram in python nltk | 38,068,539 | <p>I have started learning <code>NLTK</code> and I am following a tutorial from <a href="http://www.katrinerk.com/courses/python-worksheets/language-models-in-python" rel="nofollow">here</a>, where they find conditional probability using bigrams like this.</p>
<pre><code>import nltk
from nltk.corpus import brown
cfreq... | 1 | 2016-06-28T06:25:45Z | 38,098,159 | <p><code>nltk.ConditionalFreqDist</code> expects its data as a sequence of <code>(condition, item)</code> tuples. <code>nltk.trigrams</code> returns tuples of length 3, which causes the exact error you posted.</p>
<p>From your post it's not exactly clear what you want to use as conditions, but the convention when doin... | 2 | 2016-06-29T11:24:35Z | [
"python",
"nlp",
"nltk",
"n-gram"
] |
Dynamic For Loops in Python | 38,068,669 | <p>i understand that to create dynamic for loops, recursive or itertools module in python is the way to go. Lets say I am doing it in recursive.</p>
<p>What I want is</p>
<pre><code>for var1 in range(var1_lowerlimit, var1_upperlimit, var1_stepsize):
for var2 in range(var2_lowerlimit, var2_upperlimit, var2_stepsiz... | -1 | 2016-06-28T06:32:22Z | 38,068,846 | <p>Use the <code>itertools.product()</code> function to generate the values over a variable number of ranges:</p>
<pre><code>for values in product(*(range(*b) for b in boundaries_list)):
# do things with the values tuple, do_whatever(*values) perhaps
</code></pre>
<p>Don't try to set a variable number of variable... | 2 | 2016-06-28T06:43:11Z | [
"python",
"for-loop",
"dynamic"
] |
Dynamic For Loops in Python | 38,068,669 | <p>i understand that to create dynamic for loops, recursive or itertools module in python is the way to go. Lets say I am doing it in recursive.</p>
<p>What I want is</p>
<pre><code>for var1 in range(var1_lowerlimit, var1_upperlimit, var1_stepsize):
for var2 in range(var2_lowerlimit, var2_upperlimit, var2_stepsiz... | -1 | 2016-06-28T06:32:22Z | 38,087,826 | <p>Just for fun, I thought that I would implement this using recursion to perhaps demonstrate the pythonic style. Of course, the <em>most</em> pythonic way would be to use the <code>itertools</code> package as demonstrated by Martijn Pieters. </p>
<pre><code>def dynamic_for_loop(boundaries, *vargs):
if not boundar... | 0 | 2016-06-28T23:21:44Z | [
"python",
"for-loop",
"dynamic"
] |
Pandas Series.map() function converting the non-numeric values to numbers? | 38,068,814 | <p>I tried converting the non-numeric values to numeric values to compute a decision tree. But, the <code>NaN</code> value pops each and every time I call the <code>map()</code> function.</p>
<p>Here's the code and necessary Information.</p>
<p>And Here's the o/p I'm getting.</p>
<p><a href="http://i.stack.imgur.com... | -1 | 2016-06-28T06:41:09Z | 38,069,095 | <pre><code>df = df.drop("education", 1)
</code></pre>
<p>You just used drop() about the col of education. The col of education has no meaning for building a decision tree, so just discard it.</p>
| 0 | 2016-06-28T06:55:13Z | [
"python",
"pandas"
] |
Pandas Series.map() function converting the non-numeric values to numbers? | 38,068,814 | <p>I tried converting the non-numeric values to numeric values to compute a decision tree. But, the <code>NaN</code> value pops each and every time I call the <code>map()</code> function.</p>
<p>Here's the code and necessary Information.</p>
<p>And Here's the o/p I'm getting.</p>
<p><a href="http://i.stack.imgur.com... | -1 | 2016-06-28T06:41:09Z | 38,069,329 | <p>It looks like some spaces are before or after text in column:</p>
<pre><code>df = pd.DataFrame({'education' : ['BS ','MS ','MS ']})
print (df)
education
0 BS
1 MS
2 MS
x={'BS':1,'MS':2,'CODE CAMP':3,'PHD':4}
df['education']=df['education'].map(x)
print (df)
education
0 NaN
1 ... | 2 | 2016-06-28T07:08:10Z | [
"python",
"pandas"
] |
Python script to match actual start of line ignoring tabs and spaces | 38,068,975 | <p>I think my question is pretty much self-explanatory, but still I would post an example for more clarity.</p>
<p>I have following fully working script to comment/uncomment the lines in a Javascript file opened in the Gedit editor.</p>
<pre><code>#! /usr/bin/env python
import sys
import StringIO
block = sys.stdin.re... | 0 | 2016-06-28T06:49:55Z | 38,069,128 | <p>You can use regex replacements to do this. For example, this line of code should do what you want</p>
<pre><code>line = re.sub(r"^(\s*)(\S.*)", r"\1//~\2", line)
</code></pre>
<p>This regex matches 0 or more space characters [(\s*)], then matches the rest of the string [(\S.*)]. It then replaces this with the 1st ... | 0 | 2016-06-28T06:57:32Z | [
"javascript",
"python",
"regex",
"pattern-matching",
"gedit"
] |
How to upload an image and get make it public in Google Cloud Bucket | 38,069,038 | <p>I am trying to upload an image to google cloud bucket and get its URI(gc://my_bucket/file.jpg) using python. </p>
<p>Can anyone please tell me how to do that as I don't have any prior experience in python.</p>
| 1 | 2016-06-28T06:52:34Z | 38,086,934 | <p>Here's the easiest way I know of. It requires first installing <a href="https://github.com/GoogleCloudPlatform/gcloud-python" rel="nofollow">gcloud-python</a>, which you can do with the command <code>pip install --upgrade gcloud</code>:</p>
<pre><code>from gcloud import storage
bucket_name = 'name-of-bucket'
objec... | 0 | 2016-06-28T21:54:08Z | [
"python",
"google-cloud-storage"
] |
neo4j BOLT query does not always work consitently | 38,069,059 | <p>I'm using BOLT for NEO4j and I have a simple query to find the length between to nodes (start and stop) of arbitrary length</p>
<pre><code>stmt = MATCH (n:Month {ID: {start} }),(m:Month {ID: {stop}}),p = shortestPath((n)-[r:nextMonth*..100000]-(m)) RETURN LENGTH(p)
dict = {'start': '201507', 'stop': '201509'}
resul... | 0 | 2016-06-28T06:53:27Z | 38,081,761 | <p>Try run this:</p>
<p><code>result = session.run(stmt, dict).peek()[0]</code></p>
<p>All the time when I get a return of "session.run()", I use the method peek() (if the return is just one line). Otherwise it's better use the result with a loop because this return a collection object who helps on performance of you... | 0 | 2016-06-28T16:37:42Z | [
"python",
"neo4j",
"cypher"
] |
neo4j BOLT query does not always work consitently | 38,069,059 | <p>I'm using BOLT for NEO4j and I have a simple query to find the length between to nodes (start and stop) of arbitrary length</p>
<pre><code>stmt = MATCH (n:Month {ID: {start} }),(m:Month {ID: {stop}}),p = shortestPath((n)-[r:nextMonth*..100000]-(m)) RETURN LENGTH(p)
dict = {'start': '201507', 'stop': '201509'}
resul... | 0 | 2016-06-28T06:53:27Z | 38,088,634 | <p>I actually found the root cause of my problem. </p>
<p>I used two sessions:</p>
<p>Session1 was there to create the nodes (statement no shown above)
Session2 was to find the length of the path (shown above)</p>
<p>Adding the smallest delay (time.sleep(0.1) between the creation and path query solved the issue.</p>... | 1 | 2016-06-29T01:00:13Z | [
"python",
"neo4j",
"cypher"
] |
How to order items a dictionary in Python, based on part of strings contained in the values? | 38,069,136 | <p>I need to order the items in a <code>dictionary</code>, based on a the last characters of of the strings in the values.</p>
<p>For example, my dictionary is <code>{1:'001 abc', 2:'001 xyz', 3:'001 efg'}</code></p>
<p>but I need to sort it so its <code>{1:'001 abc', 3:'001 efg', 2:'001 xyz}</code></p>
<p>(the ... | 0 | 2016-06-28T06:57:48Z | 38,069,211 | <p>Use an <a href="https://docs.python.org/2/library/collections.html#collections.OrderedDict" rel="nofollow">ordered dict</a>:</p>
<pre><code>from collections import OrderedDict
d = OrderedDict()
for k, v in sorted({1:'001 abc', 2:'001 xyz', 3:'001 efg'}.items(), key=lambda t: t[1]):
d[k] = v
d
>> OrderedDi... | 0 | 2016-06-28T07:01:35Z | [
"python",
"string",
"sorting",
"dictionary"
] |
How to order items a dictionary in Python, based on part of strings contained in the values? | 38,069,136 | <p>I need to order the items in a <code>dictionary</code>, based on a the last characters of of the strings in the values.</p>
<p>For example, my dictionary is <code>{1:'001 abc', 2:'001 xyz', 3:'001 efg'}</code></p>
<p>but I need to sort it so its <code>{1:'001 abc', 3:'001 efg', 2:'001 xyz}</code></p>
<p>(the ... | 0 | 2016-06-28T06:57:48Z | 38,069,224 | <p>Dicts aren't sorted, so there's no way to "order the items in a dictionary."</p>
<p>But you can sort <em>the elements</em> in the dictionary however you like.</p>
<p>For example:</p>
<pre><code>d = { 1: '001 abc', 2: '001 xyz', 3: '001 efg' }
for key, value in sorted(d.items(), key=lambda item: item[1]):
pr... | 0 | 2016-06-28T07:02:14Z | [
"python",
"string",
"sorting",
"dictionary"
] |
I want store output of python pyspider script to csv or json | 38,069,236 | <p>Here My code which i made:</p>
<pre><code>import json
from pyspider.libs.base_handler import *
f = open("demo.txt","w")
class Handler(BaseHandler):
crawl_config = {
}
@every(minutes=0,seconds = 0)
def on_start(self):
self.crawl('Any URL', callback=self.index_page)
@config(priority=2)
... | 0 | 2016-06-28T07:02:43Z | 38,111,562 | <p>You can download the data from webui, or append the data to a file by override <code>on_result</code> method.</p>
| 0 | 2016-06-29T23:13:29Z | [
"python",
"json",
"csv",
"pyspider"
] |
Model is not defined | 38,069,283 | <p>I'm using Flask and Peewee to create models for <code>Users</code> and <code>Appointments</code>, and each of them have a <code>ForeignKeyField</code> referencing each other. The problem is, if I define one above the other, Flask will give me <code>x is not defined</code>.</p>
<p>For example:</p>
<pre><code>class ... | 0 | 2016-06-28T07:05:20Z | 38,069,326 | <p>You can define it as a string as far as i know:</p>
<pre><code>class User(Model):
appointments = ForeignKeyField("Appointment", related_name='appointments')
class Appointment(Model):
with_doctor = ForeignKeyField(User, related_name='doctor')
</code></pre>
<p>if the declaration is before the creation, you ha... | 0 | 2016-06-28T07:08:00Z | [
"python",
"flask",
"peewee",
"flask-peewee"
] |
Model is not defined | 38,069,283 | <p>I'm using Flask and Peewee to create models for <code>Users</code> and <code>Appointments</code>, and each of them have a <code>ForeignKeyField</code> referencing each other. The problem is, if I define one above the other, Flask will give me <code>x is not defined</code>.</p>
<p>For example:</p>
<pre><code>class ... | 0 | 2016-06-28T07:05:20Z | 38,069,766 | <p>try some changes like this, an example for Names & Addresses :</p>
<pre><code>class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
addresses = db.relationship('Address', backref='person', lazy='dynamic')
class Address(db.Model):
id = db.Column(db.Integer, primary_key=True)
perso... | 0 | 2016-06-28T07:29:48Z | [
"python",
"flask",
"peewee",
"flask-peewee"
] |
Model is not defined | 38,069,283 | <p>I'm using Flask and Peewee to create models for <code>Users</code> and <code>Appointments</code>, and each of them have a <code>ForeignKeyField</code> referencing each other. The problem is, if I define one above the other, Flask will give me <code>x is not defined</code>.</p>
<p>For example:</p>
<pre><code>class ... | 0 | 2016-06-28T07:05:20Z | 38,074,883 | <p>You generally don't define the foreign key on both sides of the relationship, especially when the relationship isn't a one-to-one.</p>
<p>You should also set the <code>related_name</code> to something that makes sense on the related model. <code>user.appointments</code> is probably a better name for accessing a <co... | 1 | 2016-06-28T11:23:00Z | [
"python",
"flask",
"peewee",
"flask-peewee"
] |
Thread timer issues python | 38,069,328 | <p>I am trying to use the thread.Timer class, but I keep getting crashes.
Here is the idea : i have a code that launches an optimisation on a web application. When the optimisation is launched, i want to send periodic requests to the web app server to know if the optimisation is finished, or still executing.</p>
<pre>... | 0 | 2016-06-28T07:08:08Z | 38,070,354 | <p>I do not know what is the error message you've got, but it might be that the object that function checkPeriodically is part of it doesn't exists anymore. </p>
<p>Here example of working code: (I"m keeping reference to the object until all jobs are done).</p>
<pre><code>import threading
import time
class cls:
... | 1 | 2016-06-28T07:58:09Z | [
"python",
"html",
"python-multithreading",
"mechanize-python"
] |
Integrating R script with Python - Error in loading packages | 38,069,406 | <p>(Sorry about bits and pieces of poor formatting in question)</p>
<p>I am trying to create a GUI in Python for my Sentiment Analysis Program which has been coded in R. It looks like as follows.</p>
<pre><code>#!/usr/bin/python
from os import *
from subprocess import *
from tkinter import *
class Application(Frame)... | 0 | 2016-06-28T07:12:27Z | 38,208,879 | <p>For various environments, when calling R scripts with specialized packages from Python, the library paths may not be fully recognized on the Python end.</p>
<p>To resolve, try placing <a href="http://www.inside-r.org/r-doc/base/.libPaths" rel="nofollow">.libPaths()</a> at top of code in R to explicitly define locat... | 0 | 2016-07-05T17:01:48Z | [
"python",
"user-interface"
] |
"ImportError: cannot import name SkipTest" while importing numpy in python | 38,069,417 | <p>I am having problem while importing numpy.</p>
<p>Please fin below version information:</p>
<pre><code># cat /etc/redhat-release
CentOS release 6.5 (Final)
# python -V
Python 2.6.6
</code></pre>
<p>I have already installed numpy (re-installed several times) using pip.</p>
<pre><code># pip install numpy
</code><... | 1 | 2016-06-28T07:13:07Z | 38,074,080 | <p>Seems like I have to upgrade my python version.
In fact, after installing python2.7 everything is smooth.</p>
<p>I have installed python2.7 followed by numpy as below:</p>
<pre><code>yum install python27
scl enable python27 bash
pip2.7 install numpy
</code></pre>
<p>Then I was able to import numpy using python2.7... | 0 | 2016-06-28T10:46:25Z | [
"python",
"numpy",
"importerror"
] |
"ImportError: cannot import name SkipTest" while importing numpy in python | 38,069,417 | <p>I am having problem while importing numpy.</p>
<p>Please fin below version information:</p>
<pre><code># cat /etc/redhat-release
CentOS release 6.5 (Final)
# python -V
Python 2.6.6
</code></pre>
<p>I have already installed numpy (re-installed several times) using pip.</p>
<pre><code># pip install numpy
</code><... | 1 | 2016-06-28T07:13:07Z | 38,081,563 | <p>Indeed, newer numpies no longer support python 2.6</p>
| 1 | 2016-06-28T16:28:21Z | [
"python",
"numpy",
"importerror"
] |
Getting Twitter Followers using Twitter's REST API | 38,069,439 | <p>I am using python script to get the followers for a specific user. The script runs perfectly and it returns the IDs of the followers when i use user lookup API it only returns 3 result. The script is like this:</p>
<pre><code>#!/usr/bin/python
from twitter import *
import sys
import csv
import json
config = {}
... | 0 | 2016-06-28T07:14:10Z | 38,070,140 | <p>your issue is in those 2 lines</p>
<p>(I assumed second line is intended although it is not in the question)</p>
<pre><code>for n in range(0, len(query["ids"]), 100):
ids = query["ids"][n:n+100]
</code></pre>
<p>those lines will create multi ids arrays and they overwrite each other</p>
<p>so first iteration ... | 1 | 2016-06-28T07:46:56Z | [
"python",
"twitter-bootstrap",
"twitter"
] |
Python: Nesting an "If" statement inside a "while" loop? | 38,069,471 | <p>I'm new to Python, which is why I'm having trouble on a problem which others might find easy.</p>
<p>Background to this problem: Euler Project, question 2. The problem essentially asks us to add all the even terms in the Fibonacci sequence, so long that each term is under 4,000,000. I decided to do the problem a li... | 2 | 2016-06-28T07:15:46Z | 38,069,674 | <p>You have a <strong>floating point problem</strong> (which you can read on <a href="https://docs.python.org/2/tutorial/floatingpoint.html" rel="nofollow">here</a>)- the returned value 'nFib' is not an integer and not a rounded value. I ran your code and added print for this value in every iteration and got: <br></p>
... | 2 | 2016-06-28T07:25:53Z | [
"python",
"loops",
"if-statement",
"while-loop",
"fibonacci"
] |
Python: Nesting an "If" statement inside a "while" loop? | 38,069,471 | <p>I'm new to Python, which is why I'm having trouble on a problem which others might find easy.</p>
<p>Background to this problem: Euler Project, question 2. The problem essentially asks us to add all the even terms in the Fibonacci sequence, so long that each term is under 4,000,000. I decided to do the problem a li... | 2 | 2016-06-28T07:15:46Z | 38,069,774 | <p>Solution provided by Gal Dreiman is fine but, conversion with in function is more better, below is your revised code:</p>
<pre><code>def Fibonacci(n):
return int((1/(5**0.5))*((((1+5**0.5)/2)**n)-(((1-5**0.5)/2)**n)))
</code></pre>
| 2 | 2016-06-28T07:30:13Z | [
"python",
"loops",
"if-statement",
"while-loop",
"fibonacci"
] |
Python: Nesting an "If" statement inside a "while" loop? | 38,069,471 | <p>I'm new to Python, which is why I'm having trouble on a problem which others might find easy.</p>
<p>Background to this problem: Euler Project, question 2. The problem essentially asks us to add all the even terms in the Fibonacci sequence, so long that each term is under 4,000,000. I decided to do the problem a li... | 2 | 2016-06-28T07:15:46Z | 38,069,779 | <p>The problem is with <code>nFib%2==0</code> comparison. Here you try to compare the float LHS with integer 0. So either modify the if loop as below or modify the return as <code>return int((1/(5**0.5))*((((1+5**0.5)/2)**n)-(((1-5**0.5)/2)**n)))</code>.</p>
<pre><code>>>> def Fibonacci(n):
... return (1/... | 2 | 2016-06-28T07:30:28Z | [
"python",
"loops",
"if-statement",
"while-loop",
"fibonacci"
] |
Run tornado.testing.AsyncTestCase using asyncio event loop | 38,069,480 | <p>I have an asyncio based class which I want to unit test. Using <code>tornado.testing.AsyncTestCase</code> this works quite well and easily. However, one specific method of my class uses <code>asyncio.ensure_future</code> to schedule execution of another method. This never finishes in the <code>AsyncTestCase</code>, ... | 0 | 2016-06-28T07:16:14Z | 38,072,145 | <p>Turns out to be simple enough...</p>
<pre><code>class TestSubjectTest(AsyncTestCase):
def get_new_ioloop(self): # override this method
return tornado.platform.asyncio.AsyncIOMainLoop()
</code></pre>
<p>I was trying this before, but directly returned <code>asyncio.get_event_loop()</code>, which didn't ... | 0 | 2016-06-28T09:22:01Z | [
"python",
"unit-testing",
"python-3.x",
"tornado",
"python-asyncio"
] |
Change mean pooling to max pooling in a framework-free CNN implementation with Python | 38,069,538 | <p>I've implemented a simple CNN program with Python that can machine learn on the MNIST data set. I've implemented 3 layers: </p>
<ol>
<li>ConvPoolLayer, which convolves and then does mean pooling </li>
<li>FullyConnectedLayer, which is a fully connected hidden layer</li>
<li>SoftmaxLayer, which basically gives the s... | 2 | 2016-06-28T07:19:07Z | 38,237,613 | <ol>
<li><p>[updated] For forward propagation for max pooling use : </p>
<p><code>skimage.measure.block_reduce(activation, block_size=(1, 1, 2, 2), func=np.max)</code></p></li>
<li><p>Your backpropagation for mean pooling is not fully correct. You should devide delta by number of pooled cells (4 in your case). See equ... | 2 | 2016-07-07T04:38:28Z | [
"python",
"algorithm",
"performance",
"optimization",
"machine-learning"
] |
How to find all possible ascending and descending order from a list? | 38,069,868 | <p>I have a list of number:</p>
<pre><code>number = [1,2,3,4,5,6,...,20]
</code></pre>
<p>I would like to generate all possible ascending and descending order of 6 total from my list. </p>
<pre><code>possible_ordered:
[1,2,3,4,5,6]
[2,3,4,5,6,7]
[3,4,5,6,7,8]
...
[15,16,17,18,19,20]
[20,19,18,17,16,15]
[15,14,13,1... | -1 | 2016-06-28T07:34:47Z | 38,070,620 | <p>Try this:</p>
<pre><code>a = list(range(1, 21))
b = list(range(20, 0, -1)) # the revers of a
print([a[start: start + 6] for start in range(len(a) - 5)] +
[b[start: start + 6] for start in range(len(a) - 5)])
</code></pre>
<p>Output:</p>
<pre><code>[[1, 2, 3, 4, 5, 6],
[2, 3, 4, 5, 6, 7],
[3, 4, 5, 6, 7, ... | 0 | 2016-06-28T08:12:54Z | [
"python",
"sorting"
] |
which method i should use in this python code.. multithreading or multiprocessing? | 38,070,056 | <p>I need to run the following loop n times parallely : i.e
one iteration should not wait for its preceding iteration to finish.
I want all the iterations to run simultaneously for all values of 'n' so that I can reduce runtime and get results faster.</p>
<pre><code>for i in range(0,n):
api=str('some API string ... | 0 | 2016-06-28T07:42:57Z | 38,071,400 | <p>Get you max thread number, and divide n with the number of threads and if need balance it.
Then just pass to the threads the parameters start and end of the loop.</p>
<p>ex:</p>
<pre><code>def function(start, end):
for i in range(start,end):
[your code]
</code></pre>
<p>To save the result you can ma... | 0 | 2016-06-28T08:51:38Z | [
"python",
"multithreading",
"multiprocessing"
] |
Is python`s SysLogHandler nonBlocking? | 38,070,061 | <p>I am trying to create a python script that well periodically connect to haproxy socket, send a "show info" command and exit. This script will be used along with keepalived in order to determine, through this script, when to switch master/slave servers. Therefore, my goal is that my python script been non-blocking. ... | 0 | 2016-06-28T07:43:02Z | 38,070,134 | <p>The <a href="https://docs.python.org/3/library/logging.html" rel="nofollow">python documentation</a> on logging is the main point where you should start.</p>
<p><code>SysLogHandler</code> is a subclass of <code>Handler</code>(There are many more. See the docs).</p>
<p><a href="https://docs.python.org/3/library/log... | 0 | 2016-06-28T07:46:34Z | [
"python"
] |
check multiple column indices for existence | 38,070,072 | <p>Is there a more sophisticated way of doing</p>
<pre><code>if numpy.all(map(lambda c: c in df.columns, ['Column 1', 'Columns 2'])):
do_something()
</code></pre>
| 0 | 2016-06-28T07:43:33Z | 38,070,190 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.isin.html" rel="nofollow"><code>Index.isin</code></a>:</p>
<pre><code>df = pd.DataFrame({'A':[1,2,3],
'B':[4,5,6],
'C':[7,8,9],
'D':[1,3,5],
'E':[5,3,6]... | 2 | 2016-06-28T07:49:22Z | [
"python",
"pandas"
] |
List printer function flexibility | 38,070,370 | <p>I am writing a program in Python 3 and I have a function which prints out all the items in a list and also receives, verifies and returns user inputs.</p>
<pre><code>def printer(my_list):
for item in range(len(my_list)):
print("{}. {}",format(item + 1, my_list[item]))
</code></pre>
<p>This is a simplified ve... | -4 | 2016-06-28T07:58:54Z | 38,071,111 | <p>Is this what you are looking for?</p>
<pre><code>def printer(my_list, label=True):
#check if label is True
if label:
for number,item in enumerate(my_list):
print number+1, item #print labeled index (+1 to begin with 1) & item
else:
for item in my_list:
print item... | -1 | 2016-06-28T08:36:37Z | [
"python",
"string",
"list",
"python-3.x",
"printing"
] |
Monkey patching with subclass | 38,070,396 | <p><em>Context:<a href="https://cherrypy.readthedocs.io/en/3.3.0/refman/lib/sessions.html" rel="nofollow">cherrypy session</a> currently locks on request start and releases the lock when the request ends. Hence concurrent requests are processed serially and getting blocked.</em></p>
<p>Is it possible to extend a class... | 2 | 2016-06-28T08:00:39Z | 38,078,273 | <h1>UPD (Oct 1, 2016):</h1>
<p>This <a href="https://github.com/cherrypy/cherrypy/pull/1495" rel="nofollow">pull request</a> (merged on Sep 4, 2016 and available for <code>CherryPy >= 8.1</code>) introduces a new way of specifying session class.
Smth like this should serve your needs:</p>
<pre><code>import cherryp... | 0 | 2016-06-28T13:58:13Z | [
"python",
"cherrypy",
"monkeypatching"
] |
Write a program that performs mathematical computation | 38,070,435 | <p>I'm taking my very first programming class ever and the second lab is already kicking my butt. </p>
<p>the prof wants us to write a program that will get measurement from the user in feet with a decimal (input) and then display that number in feet and inches separately (output).</p>
<p>I'm confused on how to get s... | -1 | 2016-06-28T08:02:34Z | 38,070,565 | <p>The feet you will print is just the integer part of userFeet. The inches is the decimal one after the conversion. Much like 200 min is 3 hours and 20 mins âº. So:</p>
<pre><code>from math import floor
print ("This program will convert your measurement (in feet) into feet and inches.")
print ()
# input section
use... | 1 | 2016-06-28T08:10:16Z | [
"python",
"math",
"decimal",
"computation"
] |
Write a program that performs mathematical computation | 38,070,435 | <p>I'm taking my very first programming class ever and the second lab is already kicking my butt. </p>
<p>the prof wants us to write a program that will get measurement from the user in feet with a decimal (input) and then display that number in feet and inches separately (output).</p>
<p>I'm confused on how to get s... | -1 | 2016-06-28T08:02:34Z | 38,070,575 | <p>A couple hints:</p>
<p>userFeet cannot be an integer (since it contains decimals).</p>
<p>The number of feet can be floored to integer from the float/double type.</p>
<p>The number of inches can be calculated by multiplying the difference of userFeet and feet (<code>userFeet - feet</code>) with 12 and rounding it... | 0 | 2016-06-28T08:10:37Z | [
"python",
"math",
"decimal",
"computation"
] |
Write a program that performs mathematical computation | 38,070,435 | <p>I'm taking my very first programming class ever and the second lab is already kicking my butt. </p>
<p>the prof wants us to write a program that will get measurement from the user in feet with a decimal (input) and then display that number in feet and inches separately (output).</p>
<p>I'm confused on how to get s... | -1 | 2016-06-28T08:02:34Z | 38,070,608 | <pre><code>10.25 feet => 10feet + 0.25 feet => 10feet and 0.25*12inch => 10feet 3inch
</code></pre>
<p>So take the decimal part and multiply by 12 to get it in inches then just show the number of feet and number of inches together.</p>
| 0 | 2016-06-28T08:12:15Z | [
"python",
"math",
"decimal",
"computation"
] |
Write a program that performs mathematical computation | 38,070,435 | <p>I'm taking my very first programming class ever and the second lab is already kicking my butt. </p>
<p>the prof wants us to write a program that will get measurement from the user in feet with a decimal (input) and then display that number in feet and inches separately (output).</p>
<p>I'm confused on how to get s... | -1 | 2016-06-28T08:02:34Z | 38,070,813 | <p>I will try to mend your code with comments to what I have changed.</p>
<pre><code>import math # This is a module. This allows you to access more commands. You can see the full list of "math" commands with this link: https://docs.python.org/2/library/math.html
print ("This program will convert your measurement (in ... | 1 | 2016-06-28T08:21:49Z | [
"python",
"math",
"decimal",
"computation"
] |
pcscd protocol changes but atr does not | 38,070,499 | <p>I've been working on hid omnikey 5325 cl and trying to get the ATR value. I'm using pcscd and pyscard library on Ubuntu. System automatically gets the ATR using T0 protocol but I need RAW return. On windows using helloprox or omnikey's official software I can get what I need, but on ubuntu even though I've change th... | 0 | 2016-06-28T08:06:16Z | 38,085,495 | <p>Some considerations, which may be helpful, even if they don't add to a full answer:</p>
<ul>
<li>You are working with contactless cards or tags</li>
<li>These tags <strong>have no</strong> ATR, but depending on the protocol something like ATQB or ATS, which is completely differently structured.</li>
<li>PCSC is a d... | 0 | 2016-06-28T20:14:50Z | [
"python",
"smartcard",
"pcsc",
"pyscard"
] |
pcscd protocol changes but atr does not | 38,070,499 | <p>I've been working on hid omnikey 5325 cl and trying to get the ATR value. I'm using pcscd and pyscard library on Ubuntu. System automatically gets the ATR using T0 protocol but I need RAW return. On windows using helloprox or omnikey's official software I can get what I need, but on ubuntu even though I've change th... | 0 | 2016-06-28T08:06:16Z | 38,120,863 | <p>After contacting the Omnikey support, the problem is solved.
As in <a href="http://www.hidglobal.com/node/5487" rel="nofollow">developer guide</a> I was looking for the config file "/etc/cmrfid.ini" to change the prox format. The file name was changed into "/etc/Omnikey.ini"</p>
| 0 | 2016-06-30T10:46:14Z | [
"python",
"smartcard",
"pcsc",
"pyscard"
] |
dimension not matching for a nd array | 38,070,622 | <p>I have created an nd array from a file as:</p>
<pre><code>for i in range(int(atoms)):
next(finp)
for j in range(int(ldata[2])):
aatom[i][j] = [float(x) for x in
finp.readline().strip().split()]
</code></pre>
<p>Which I am expecting to be a 3d array(<code>i,j,x</code>). But it... | 0 | 2016-06-28T08:13:03Z | 38,071,032 | <p>Your nested lists are probably of different lengths, forcing NumPy to create an array of <code>dtype=object</code>, meaning an array of <code>list</code>s instead of <code>float</code>s.</p>
<p>compare</p>
<pre><code>a = [range(3), range(2)] # different lenghts in inner lists
aa = np.array(a)
print aa
print aa.sh... | 1 | 2016-06-28T08:32:40Z | [
"python"
] |
A generic approach to handle the PUT , POST , DELETE, GET request in python , django | 38,070,676 | <p>So currently what i am doing is that i make class for different type of reuests , suppose there is GET request to fetch some records , so my class will inherit a class that handles the GET requests and all the cases for a GET request will be handled there . So is anyone can suggest a generic approach to handle all k... | 0 | 2016-06-28T08:15:55Z | 38,071,638 | <p>there are already <a href="https://www.djangopackages.com/grids/g/api/" rel="nofollow">multiple frameworks</a> that will help you with the task in hand, best known are <a href="http://www.django-rest-framework.org/" rel="nofollow">Django REST Framework</a> and <a href="http://django-tastypie.readthedocs.io/en/latest... | 0 | 2016-06-28T09:01:16Z | [
"python",
"django"
] |
Write a Python formatted generator | 38,070,718 | <p>To generate a <strong>Tecplot</strong> file I use:</p>
<pre><code>import numpy as np
x, y = np.genfromtxt('./files.dat', unpack=True)
nb_value = x.size
x_splitted = np.split(x, nb_value // 1000 + 1)
y_splitted = np.split(y, nb_value // 1000 + 1)
with open('./test.dat', 'w') as f:
f.write('TITLE = \" YOUPI \" ... | 0 | 2016-06-28T08:17:37Z | 38,070,763 | <p>Formatting specifiers come after a <code>:</code> colon:</p>
<pre><code>["{:.7E}".format(val) for val in y_splitted[idx]]
</code></pre>
<p>Note that I had to adjust your list comprehension syntax as well; you only want to apply each <code>val</code> to <code>str.format()</code>, not the whole loop. In essence, you... | 2 | 2016-06-28T08:19:50Z | [
"python",
"io",
"generator"
] |
Scrapy - Manual Login | 38,070,810 | <p>I am building a very simple scraper using scrapy in order to scrape a certain element from a set of urls. However, I have to be logged in to the website in order to do this and I can not get the login part of my scraper working.</p>
<p>Is it possible to login to the website manually and then let my scraper do the s... | 0 | 2016-06-28T08:21:41Z | 38,082,207 | <p>I understand what you're asking but you just can't "Manually login" using scrapy, you have to inject cookies onto it.</p>
<p>The best way I see to do this is by using Selenium to login and let it create cookies to feed scrapy here's how:</p>
<pre><code>def get_cookies(self):
driver = webdriver.Firefox()
ba... | 0 | 2016-06-28T17:02:25Z | [
"python",
"login",
"scrapy",
"manual"
] |
Matching placeholders in Python | 38,070,930 | <p>I have a set of phrases which I check against in a piece of text. </p>
<p>A straightforward phrase of the form 'as soon as possible' is easy to check for, like so:</p>
<pre><code>if phrase in text:
...
</code></pre>
<p>I also have phrases of the form 'a {JJ} amount of' where JJ is a placeholder for any adject... | -1 | 2016-06-28T08:28:09Z | 38,070,993 | <p>You can use regular expressions to accomplish. For your example, you can do something like this:</p>
<pre><code>re.findall(r"a\s\w+?\samount of", text)
</code></pre>
<p>this will return all instances of the phrase given in your example. <code>\s\w+?\s</code> will match a single word, so you can simply modify the w... | 0 | 2016-06-28T08:31:03Z | [
"python",
"string",
"parsing",
"nlp"
] |
python error setting an array element with a sequence | 38,071,097 | <p>I trying to explore different classifier for this example in scikit-learn
website <a href="http://scikit-learn.org/stable/tutorial/text_analytics/working_with_text_data.html" rel="nofollow">http://scikit-learn.org/stable/tutorial/text_analytics/working_with_text_data.html</a>. However, the code below produced an er... | 0 | 2016-06-28T08:36:02Z | 38,071,320 | <p>The <code>TensorFlowLinearClassifier</code> does not handle CSR matrix as input, you can follow the progress in <a href="https://github.com/tensorflow/tensorflow/issues/2161" rel="nofollow">that issue</a>.</p>
<hr>
<p>What you can do for now is convert <code>X_train_tfidf</code> to a numpy matrix before feeding it... | 1 | 2016-06-28T08:47:35Z | [
"python",
"numpy",
"scikit-learn",
"tensorflow",
"skflow"
] |
Django: How do I call a model function in views that accesses form data and stores the result in the database? | 38,071,106 | <p>I am a beginner in Django. I am developing an app in Django. I need to store the result of a form in the database, and call a function in views, and then store the result of that function in my database again.
In models.py, this is my model class with the calculate function: </p>
<pre><code>class f1New(models.Model... | 0 | 2016-06-28T08:36:22Z | 38,072,052 | <p>I have absolutely no idea what you are asking here. As Rajesh comments, if <code>v1</code> is always calculated from the other elements, why are you accepting it in the form at all? </p>
<p>It's <em>possible</em> that you are after this:</p>
<pre><code>class F1Model(models.Model):
...
def calculate(self):
... | 0 | 2016-06-28T09:18:20Z | [
"python",
"django",
"database",
"forms",
"views"
] |
Getting data from AJAX in Python | 38,071,132 | <p>I follow the website and successfully get the AJAX data from jobs page for Apple.com</p>
<p>The teaching website: <a href="http://toddhayton.com/2015/03/11/scraping-ajax-pages-with-python/" rel="nofollow">http://toddhayton.com/2015/03/11/scraping-ajax-pages-with-python/</a></p>
<p>here is the complete code, which ... | 0 | 2016-06-28T08:37:42Z | 38,072,527 | <p>In that code you are using <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow">Beautiful Soup</a>, which is a HTML parser. This tool provides to you the <code>findAll</code> method, which will find all the "requisition" tags on the document. So, this methods return a list containing all t... | 0 | 2016-06-28T09:39:24Z | [
"python",
"web-crawler"
] |
2 dimensional dictionary with iteration | 38,071,332 | <p>I would like to collect the installed packages and their versions of hosts to create a grid. The hosts don't necessarily have the same packages. For example: </p>
<p><a href="http://i.stack.imgur.com/6gaAc.png" rel="nofollow"><img src="http://i.stack.imgur.com/6gaAc.png" alt="enter image description here"></a></p>
... | 1 | 2016-06-28T08:48:31Z | 38,071,766 | <p>Using a <code>defaultdict</code> would be a good choice. You could fill your dictionary as shown in this example:</p>
<pre><code>from collections import defaultdict
versions = defaultdict(dict)
versions["openssl"]["host1"] = "1.0.1e"
versions["openssl"]["host2"] = "1.0.1e"
...
</code></pre>
<p>By using a <code>d... | 4 | 2016-06-28T09:06:51Z | [
"python",
"dictionary",
"set"
] |
2 dimensional dictionary with iteration | 38,071,332 | <p>I would like to collect the installed packages and their versions of hosts to create a grid. The hosts don't necessarily have the same packages. For example: </p>
<p><a href="http://i.stack.imgur.com/6gaAc.png" rel="nofollow"><img src="http://i.stack.imgur.com/6gaAc.png" alt="enter image description here"></a></p>
... | 1 | 2016-06-28T08:48:31Z | 38,071,782 | <p>Dict is best for storing these data:</p>
<pre><code> dict_data = {host:packagename for (host,packagename) in map(None, hosts, packagenames)}
</code></pre>
<p>Try this if this works.</p>
| 0 | 2016-06-28T09:07:26Z | [
"python",
"dictionary",
"set"
] |
2 dimensional dictionary with iteration | 38,071,332 | <p>I would like to collect the installed packages and their versions of hosts to create a grid. The hosts don't necessarily have the same packages. For example: </p>
<p><a href="http://i.stack.imgur.com/6gaAc.png" rel="nofollow"><img src="http://i.stack.imgur.com/6gaAc.png" alt="enter image description here"></a></p>
... | 1 | 2016-06-28T08:48:31Z | 38,072,210 | <p>If you'd rather not use a <code>defaultdict</code>, this is how it would have been done before they were available: </p>
<pre><code>pack_host = {}
for ...
# read values
pack_host.setdefault(package, {})[host] = version
</code></pre>
<p>the <code>dictionary.setdefault(key,default)</code> method is oddly-na... | 0 | 2016-06-28T09:24:36Z | [
"python",
"dictionary",
"set"
] |
How to store list of Pandas data frame for easy access | 38,071,373 | <p>I have a list of data frame,</p>
<pre><code>df1 =
Stock Year Profit CountPercent
AAPL 2012 1 38.77
AAPL 2013 1 33.33
df2 =
Stock Year Profit CountPercent
GOOG 2012 1 43.47
GOOG 2013 1 32.35
df3 =
Stock Year Profit CountPercent
... | 0 | 2016-06-28T08:50:07Z | 38,071,526 | <p>If values in columns <code>Stock</code> are same, you can remove this column by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow"><code>iloc</code></a> and use <code>dict comprehension</code> (key is first value of column <code>Stock</code> in each <code>df</co... | 0 | 2016-06-28T08:56:41Z | [
"python",
"list",
"pandas",
"dataframe"
] |
How to store list of Pandas data frame for easy access | 38,071,373 | <p>I have a list of data frame,</p>
<pre><code>df1 =
Stock Year Profit CountPercent
AAPL 2012 1 38.77
AAPL 2013 1 33.33
df2 =
Stock Year Profit CountPercent
GOOG 2012 1 43.47
GOOG 2013 1 32.35
df3 =
Stock Year Profit CountPercent
... | 0 | 2016-06-28T08:50:07Z | 38,074,286 | <p>I think if all your DFs have the same shape, then it would be more natural to store your data as <code>pandas.Panel</code> instead of list of DFs - this is how <a href="https://pandas-datareader.readthedocs.io/en/latest/remote_data.html" rel="nofollow">pandas_datareader</a> is working</p>
<pre><code>import io
impor... | 0 | 2016-06-28T10:56:02Z | [
"python",
"list",
"pandas",
"dataframe"
] |
Summing up DenseVectors after a groupByKey() works in Pyspark Shell but not in a Spark-Submit | 38,071,376 | <p>So here's some example code of what I'm trying to do:</p>
<p><strong>First, I'm building sentence feature vectors using Word2Vec:</strong></p>
<pre><code>from pyspark.ml.feature import Word2Vec
# Input data: Each row is a bag of words from a sentence or document.
documentDF = sqlContext.createDataFrame([
("Hi... | 0 | 2016-06-28T08:50:23Z | 38,074,863 | <p>Figured it out!
The problem was that I had an import function in my script as follows:</p>
<pre><code>from pyspark.sql.functions import *
</code></pre>
<p>This imported the sum() function which replaced the in-built pythonic sum(). When I removed this import function, it worked correctly. When the pythonic inbuilt... | 1 | 2016-06-28T11:22:27Z | [
"python",
"apache-spark",
"pyspark"
] |
Execute shell, get and display result realtime using PHP | 38,071,395 | <p>I need to do some long process using Python which will be called using PHP(my main language) and display the result real time.</p>
<p>Lets say this is my Python script(<code>a.py</code>).</p>
<pre><code>import time
for x in range(10):
print "S;adasdasd;",x
time.sleep(0.5)
</code></pre>
<p>I have try so m... | 1 | 2016-06-28T08:51:24Z | 38,473,602 | <blockquote>
<p>PHP always wait until script is done then displaying it.</p>
</blockquote>
<p>In this case, it's not PHP's fault; it's because Python fully buffers its standard output if that goes to a pipe. Fortunately, Python has the handy option <code>-u</code> to disable stdout and stderr buffering, so using</p>... | 0 | 2016-07-20T06:15:31Z | [
"php",
"python",
"shell",
"real-time"
] |
Python 3.5.1: Change file name | 38,071,397 | <pre><code>import os
import re
def rename_files():
#get file names from a folder
file_list = os.listdir("/Users/myname/Desktop/Python")
#print (file_list)
saved_path = os.getcwd()
print(saved_path)
os.chdir("/Users/myname/Desktop/Python")
#rename each file
for file_name in file_list:
os.rename(file-name, re.sub... | 0 | 2016-06-28T08:51:26Z | 38,071,695 | <blockquote>
<p>removing all NUMBERS from the file names</p>
</blockquote>
<p>If you're removing all numbers then why do you need an assertion: <code>(?!\d*$)</code></p>
<p>When you can simply do: </p>
<pre><code>os.rename(file_name, re.sub("[0-9]", "", file_name))
</code></pre>
<p>And you're doing it wrong:</p>
... | 2 | 2016-06-28T09:04:03Z | [
"python",
"python-3.5"
] |
beautifulsoup find_all can't get div data | 38,071,406 | <p>I try to get html data from website,but data_table is return null
and try to trace the code,when I try to get header data it will return html context </p>
<pre><code> import requests
from bs4 import BeautifulSoup
import html.parser
from html.parser import HTMLParser
import time
from random... | 1 | 2016-06-28T08:51:51Z | 38,071,989 | <p>When you visit the page in your browser you have to acknowledge that you are over 18 before you get to the actual content so that is the page you are getting, you need to so a post to <code>https://www.ptt.cc/ask/over18</code> with the data <code>yes=yes</code> and <code>from = "/bbs/Gossiping/index{the_number}.html... | 1 | 2016-06-28T09:15:45Z | [
"python",
"python-3.x",
"beautifulsoup"
] |
Plot 2 boxplots , each from different pandas dataframe in a figure? | 38,071,436 | <p>I want to plot boxplots for each of the dataframes side by side. Below is an example dataset.</p>
<p>data 1 :</p>
<h2>id |type |activity | feature1</h2>
<p>1 | A | ACTIVE | 12</p>
<p>2 | B | INACTIVE| 10</p>
<p>3 | C | ACTIVE| 9</p>
<p>data 2:</p>
<p>id | type | activity | feature1</p>
<p>1 | A | ACTIVE | 13... | 0 | 2016-06-28T08:52:54Z | 38,072,512 | <p>Use <code>return_type='axes'</code> to get <code>data1.boxplot</code> to return a <code>matplotlib</code> Axes object. Then pass that axes to the second call to <code>boxplot</code> using <code>ax=ax</code>. This will cause both boxplots to be drawn on the same axes.</p>
<p>Alternatively if you just want them plott... | 0 | 2016-06-28T09:38:30Z | [
"python",
"pandas",
"matplotlib",
"boxplot"
] |
What is the difference made by using Transpose? | 38,071,497 | <p>I was learning how convolution works then I encountered this..when I try this</p>
<pre><code>rng = numpy.random.RandomState(23455)
input = T.tensor4(name='input')
w_shp = (2, 3, 9, 9)
w_bound = numpy.sqrt(3 * 9 * 9)
print w_bound
W = theano.shared( numpy.asarray(
rng.uniform(
low=-1.0 / ... | 0 | 2016-06-28T08:55:20Z | 38,118,456 | <p>The original image is a 3d array, with dimensions (pixel rows, pixel columns, channels). Channels are the color channels (e.g. RGB). <code>img.transpose(2, 0, 1)</code> re-orders the dimensions of the array to be (channels, pixel rows, pixel columns). The rest of your code requires this initial ordering. It ensures ... | 0 | 2016-06-30T09:02:06Z | [
"python",
"theano",
"transpose",
"conv-neural-network"
] |
python select sublist effectively | 38,071,619 | <p>I have a long (many Millions) list of Transactions in the form [account_id, transactiontyp, data], each account has many Transactions. I want to select all transactions for a given short list (approx. 20000) of accounts. Example:</p>
<pre><code>longlist=[['a','t1',5],['a','t1',9],['b','t1',3],['c','t5',8]]
shortli... | 0 | 2016-06-28T09:00:50Z | 38,071,879 | <p>Using <code>set</code> (<code>shortlist = set(['a', 'c']</code>) would have a break-even at around <em>20</em> accounts. I'd expect it to be at least 2 decades faster if <code>shortlist</code> has 20k accounts.</p>
<p>If this selection is repeated many times, you'd benefit <em>even</em> more by using a dictionary t... | 3 | 2016-06-28T09:11:09Z | [
"python",
"python-2.7",
"sublist"
] |
Requests/urllib3 Retry warning when downloading image | 38,071,633 | <p>I'm downloading some images sequentially using the following code, but am getting lots of <code>WARNING: Retrying</code> messages. It's worth noting the image url which causes this vary's every time and sometimes never happens.</p>
<pre><code>session = requests.Session()
session.keep_alive = False
adapter = request... | 1 | 2016-06-28T09:01:11Z | 38,072,836 | <p>Just disable the <em>urllib3</em> warnings:</p>
<pre><code>import urllib3
urllib3.disable_warnings()
</code></pre>
<p>Or as the <a href="http://urllib3.readthedocs.io/en/latest/security.html#within-the-code" rel="nofollow">urllib3 docs</a> suggest you can capture the warnings with the <code>logging</code> module:... | 0 | 2016-06-28T09:51:17Z | [
"python",
"python-requests"
] |
Requests/urllib3 Retry warning when downloading image | 38,071,633 | <p>I'm downloading some images sequentially using the following code, but am getting lots of <code>WARNING: Retrying</code> messages. It's worth noting the image url which causes this vary's every time and sometimes never happens.</p>
<pre><code>session = requests.Session()
session.keep_alive = False
adapter = request... | 1 | 2016-06-28T09:01:11Z | 38,185,795 | <p>Turns out I was trying to disable the wrong thing. I just had todo</p>
<pre><code>import logging
logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.CRITICAL)
</code></pre>
| 0 | 2016-07-04T13:20:00Z | [
"python",
"python-requests"
] |
Sqlachemy, Recursively fetch children and ancestors with relations | 38,071,683 | <p>using properties and hybrid transformers did a little help in traversing the following trees;</p>
<pre><code>class Category(db.Model):
__tablename__ = 'category'
id = db.Column(db.Integer, primary_key=True)
parent = db.Column(db.Integer, db.ForeignKey('category.id'), nullable=True)
name = db.Column(... | 0 | 2016-06-28T09:03:29Z | 38,293,412 | <p>With Postgresql you can use recursive queries. In your case, you can use the methods:</p>
<pre><code>@staticmethod
def get_parents_list(category_id):
beginning_getter = Session.query(Category).\
filter(Category.id == category_id).cte(name='parent_for', recursive=True)
with_recursive = beginning_gett... | 1 | 2016-07-10T15:21:07Z | [
"python",
"flask",
"sqlalchemy",
"flask-sqlalchemy"
] |
Using Python 2.7 to get a download link from a web page | 38,071,703 | <p>So I'm making this program to make a repetitive task less annoying. It's suppose to take a link, filter for a "Download STV Demo" button, grab the url from that button and use it to download. The downloading files from url works fine, I just can't get the url open. It will download from stackoverflow, just not the s... | 0 | 2016-06-28T09:04:21Z | 38,072,245 | <p>The content of that page is generated dynamically via Javascript from their API.</p>
<pre><code>>>> import requests
>>>
>>> requests.get('http://sizzlingstats.com/api/stats/479453').json()['stats']['stvUrl']
u'http://sizzlingstv.s3.amazonaws.com/stv/479453.zip'
</code></pre>
<p>You're ge... | 0 | 2016-06-28T09:26:13Z | [
"python",
"filter",
"web-scraping",
"beautifulsoup"
] |
Using Python 2.7 to get a download link from a web page | 38,071,703 | <p>So I'm making this program to make a repetitive task less annoying. It's suppose to take a link, filter for a "Download STV Demo" button, grab the url from that button and use it to download. The downloading files from url works fine, I just can't get the url open. It will download from stackoverflow, just not the s... | 0 | 2016-06-28T09:04:21Z | 38,084,653 | <p>Lets look at your code:
first you are importing many modules that you don't use (maybe this isn't hole code) and some others you use but you won't need them, actually you only need:</p>
<pre><code>from urllib2 import urlopen
</code></pre>
<p>(you'll see later why) and maybe <code>win32clipboard</code> for your inp... | -1 | 2016-06-28T19:23:56Z | [
"python",
"filter",
"web-scraping",
"beautifulsoup"
] |
How to start tail in konsole with subprocess | 38,071,704 | <p>I am using tail to output the listing from a solver using:</p>
<pre><code>outputListing = exportFileName.split(".pc")[0] + ".out"
solver_run = subprocess.Popen([solver_path, "-visual", "-solvargs", "-nt 4 -fp 2", exportFilePath, outputListing])
if os.sep == "\\":
subprocess.Popen(["wintail",outputListing], she... | 0 | 2016-06-28T09:04:22Z | 38,094,330 | <p>I found the solution by myself. One have to use:</p>
<pre><code>subprocess.Popen(["konsole", "-e","$SHELL", "-c","tail -f " + outputListing])
</code></pre>
<p>so the key was to add "$SHELL" and "-c" to the call</p>
| 0 | 2016-06-29T08:35:41Z | [
"python",
"subprocess",
"tail"
] |
Use LinearColorMapper in Bokeh high-level charts | 38,071,722 | <p>Is there any way to use <code>LinearColorMapper</code> in Bokeh high-level charts ?</p>
<p>I'd like to generate a <code>ScatterChart</code> ; I know that I can use <code>color</code> and <code>palette</code> constructor parameters, but I need to map given colours for given range, which those two parameters cannot g... | 0 | 2016-06-28T09:05:09Z | 39,382,820 | <p><a href="https://github.com/bokeh/bokeh/blob/master/examples/plotting/file/color_scatter.py" rel="nofollow">This example</a> should prove helpful to you.</p>
<p>LinearColorMapper seems to work well on some levels - plotting a figure, but I had trouble using it for Circle fill_color. The Texas Unemployment example ... | 0 | 2016-09-08T04:52:47Z | [
"python",
"charts",
"bokeh"
] |
print out all the requested URLs during loading a web page | 38,071,731 | <p>In my project, there is some need to get a certain requested URL in Chrome Dev Tools by Python during loading a web page,
<a href="http://i.stack.imgur.com/shSOu.png" rel="nofollow"><img src="http://i.stack.imgur.com/shSOu.png" alt="enter image description here"></a></p>
<p>I think get the URL by Qt WebEngine is a... | 0 | 2016-06-28T09:05:37Z | 38,351,999 | <p>I use Qt with C++, but in Python should be something similar,</p>
<p>If you are trying to handle HTTP/HTTPS urls, you could subclass QWebEnginePage, and reimplement </p>
<pre><code>acceptNavigationRequest(const QUrl &url, QWebEnginePage::NavigationType type, bool main).
</code></pre>
<p>To use your own QWebEn... | 0 | 2016-07-13T12:38:54Z | [
"python",
"qt",
"qt5",
"pyqt5",
"qtwebengine"
] |
VTK interactor and PyQt running parallel | 38,071,733 | <p>I need to get a vtkChartParallelCoordinates and other graphs that use vtkContextView running parallel with a PyQt application. The problem is that both of them use an infinite loop for user mouse interaction and I can run only one of them at a time. When I start the vtk interactor by view.GetInteractor().Start() the... | 0 | 2016-06-28T09:05:38Z | 38,126,926 | <p>I am not sure whether I have completely understood your first question. However, I attach a python prototype to display your vtk graph within a Qt main window with the QVTKRenderWindowInteractor class. As for the first question, I think that by the attached method you could easily connect pyQt events with vtk events... | 0 | 2016-06-30T15:02:35Z | [
"python",
"pyqt",
"vtk"
] |
How to slice process itertools.product in python? | 38,071,828 | <p>I want to process a very large <code>itertools.product</code> object. The issue is something like this:</p>
<pre><code>import string
from itertools import product
text = string.lowercase[:] + string.uppercase[:] + '0123456789'
items = product(text, repeat=5)
for item in items:
#do something
</code></pre>
<p>I ... | 3 | 2016-06-28T09:09:18Z | 38,072,057 | <p>You can use <a href="https://docs.python.org/3.5/library/itertools.html#itertools.islice"><code>islice</code></a> to do this.</p>
<pre><code>from itertools import product, islice
import string
text = string.ascii_letters + string.digits
for item in islice(product(text,repeat=5), 300000, 600000):
# do somethin... | 6 | 2016-06-28T09:18:24Z | [
"python",
"itertools"
] |
astropy.fits: Manipulating image data from a fits Table? (e.g., 3072R x 2C) | 38,071,909 | <p>I'm currently having a little issue with a fits file. The data is in table format, a format I haven't previously used. I'm a python user, and rely heavily on astropy.fits to manipulate fits images. A quick output of the info gives: </p>
<pre><code>No. Name Type Cards Dimensions Format
0 P... | 0 | 2016-06-28T09:12:33Z | 38,078,262 | <p>I used astropy.io.fits during my internship in Astrophysics and this is my process to open file .fits and make some operations :</p>
<pre><code># Opening the .fits file which is named SMASH.fits
field = fits.open(SMASH.fits)
# Data fits reading
tbdata = field[1].data
</code></pre>
<p>Now, with this ki... | 0 | 2016-06-28T13:57:32Z | [
"python",
"arrays",
"numpy",
"astropy",
"fits"
] |
astropy.fits: Manipulating image data from a fits Table? (e.g., 3072R x 2C) | 38,071,909 | <p>I'm currently having a little issue with a fits file. The data is in table format, a format I haven't previously used. I'm a python user, and rely heavily on astropy.fits to manipulate fits images. A quick output of the info gives: </p>
<pre><code>No. Name Type Cards Dimensions Format
0 P... | 0 | 2016-06-28T09:12:33Z | 38,078,802 | <p>I can't be sure without seeing the full traceback but I think the exception you're getting is from this:</p>
<pre><code>image_XRAY_SKYVIEW_R1 = numpy.array(image_XRAY_SKYVIEW_R1)
</code></pre>
<p>There's no reason to manually wrap <code>numpy.array()</code> around the array. It's already a Numpy array. But in th... | 1 | 2016-06-28T14:20:31Z | [
"python",
"arrays",
"numpy",
"astropy",
"fits"
] |
How to randomly select from a drop-down menu using selenium? | 38,071,912 | <p>I'm pretty new to python 3 and have been learning to automate some of my web task I do using selenium. </p>
<p>So say their are 3 drop-down list on the page, Month, Day, & Year. When selecting a drop-down menu, how exactly can I randomly select a option listed in the menu?</p>
<pre><code> month = ['Jan', 'F... | 1 | 2016-06-28T09:12:41Z | 38,072,251 | <p>You can use <code>random.choice</code>, so your code would be:</p>
<pre><code>import random
month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
day = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'
'11', '12', '13', '14', '15', '16', '17', '18', '19'... | 1 | 2016-06-28T09:26:24Z | [
"python",
"selenium"
] |
How to randomly select from a drop-down menu using selenium? | 38,071,912 | <p>I'm pretty new to python 3 and have been learning to automate some of my web task I do using selenium. </p>
<p>So say their are 3 drop-down list on the page, Month, Day, & Year. When selecting a drop-down menu, how exactly can I randomly select a option listed in the menu?</p>
<pre><code> month = ['Jan', 'F... | 1 | 2016-06-28T09:12:41Z | 38,082,162 | <p>Just use <code>select_by_index(i)</code> where <code>i</code> is randomly selected from the number of available options in the dropdown. It will be more flexible and you won't have to maintain a list of months, days, years... and deal with leap years or months with varying days, 28 v 30 v 31, etc.</p>
<pre><code>mo... | 0 | 2016-06-28T16:59:49Z | [
"python",
"selenium"
] |
Python OpenCV - Update camera index of live webcam view | 38,071,978 | <p>I am viewing a webcam camera live feed. I would like to incorporate this into a Tkinter GUI and have a dropdown selection that allows one to change the camera index, and therefore the webcam being used, on the fly.
How can this be achieved?</p>
<p>Example code:</p>
<pre><code>import cv2
def show_webcam(mirror=Fal... | 1 | 2016-06-28T09:15:10Z | 38,076,216 | <p>To change camera at run time all you need to change is the index you pass in
<code>cv2.VideoCapture(index)</code>.</p>
<p>Find out how many camera you will be using for your app and for 3 cameras, you can change it through changing index to 0 or 1 or 2.</p>
<p>Add one more parameter as index
<code>show_webcam(mir... | 2 | 2016-06-28T12:24:52Z | [
"python",
"opencv",
"webcam"
] |
How to get arguments for 2 different objects from the command line when there is a naming conflict in Python argparse | 38,071,986 | <p>I have two classes, A and B, that each have their own argument parser defined (using argparse)
I now want to add functionality to A, so that it calls class B. I am doing this using composition (i.e A has an instance of object B)</p>
<p>I asked here how to combine two arg parse objects, so that argparseA will now in... | 1 | 2016-06-28T09:15:29Z | 38,086,900 | <p>I'm going to guess that you are trying my <code>parents</code> suggestion, and illustrate what might be going on. But even if you've adopted another approach this may help.</p>
<pre><code>import argparse
parserA=argparse.ArgumentParser()
a1=parserA.add_argument('-f','--foo','--bar')
print(a1)
print()
parserB=arg... | 3 | 2016-06-28T21:51:06Z | [
"python",
"python-2.7",
"oop",
"argparse"
] |
Query task state - Celery & redis | 38,072,048 | <p>Okay so I have a relatively simple problem I think, and it's like I'm hitting a brick wall with it. I have a flask app, and a webpage that allows you to run a number of scripts on the server side using celery & redis(broker). </p>
<p>All I want to do, is when I start a task to give it a name/id (task will be po... | 0 | 2016-06-28T09:18:13Z | 38,072,522 | <p>When you start a task with <code>delay</code> or <code>apply_async</code> an object <code>AsyncResult</code>is created and contains the id of the task. To get it you just have to store it in a variable.</p>
<p>For example </p>
<pre><code>@app.route('/start_upgrade/<task_name>')
def start_upgrade(task_name)... | 0 | 2016-06-28T09:39:09Z | [
"python",
"redis",
"celery",
"celery-task"
] |
Query task state - Celery & redis | 38,072,048 | <p>Okay so I have a relatively simple problem I think, and it's like I'm hitting a brick wall with it. I have a flask app, and a webpage that allows you to run a number of scripts on the server side using celery & redis(broker). </p>
<p>All I want to do, is when I start a task to give it a name/id (task will be po... | 0 | 2016-06-28T09:18:13Z | 38,078,654 | <p>I ended up figuring out a solution for my question from arthur's post. </p>
<p>In conjunction with redis I created these functions</p>
<pre><code>import redis
from celery.result import AsyncResult
redis_cache = redis.StrictRedis(host='localhost', port=6379, db=0)
def check_task_status(task_name):
task_id = r... | 0 | 2016-06-28T14:14:11Z | [
"python",
"redis",
"celery",
"celery-task"
] |
Initializing a big matrix with numpy taking way too long | 38,072,175 | <p>I am working in python and I have encountered a problem: I have to initialize a huge array (21 x 2000 x 4000 matrix) so that I can copy a submatrix on it.
The problem is that I want it to be really quick since it is for a real-time application, but when I run numpy.ones((21,2000,4000)), it takes about one minute to ... | 0 | 2016-06-28T09:23:15Z | 38,072,496 | <p>I guess there's not a faster way. The matrix you're building is quite large (8 byte float64 x 21 x 2000 x 4000 = 1.25 GB), and might be using up a large fraction of the physical memory on your system; thus, the one minute that you're waiting might be because the operating system has to page other stuff out to make ... | 1 | 2016-06-28T09:37:39Z | [
"python",
"numpy",
"matrix"
] |
Print an sqlalchemy row | 38,072,275 | <p>All I'd like to do is print a single row of an sqlalchemy table row.</p>
<p>Say I have:</p>
<pre><code>from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class ATable(Base):
__tablename__ = 'atable'
id = Column(Integer, pri... | 0 | 2016-06-28T09:27:20Z | 38,078,261 | <p>To be clear - you want a general method to print "col: value" without hardcoding the column names? I do not use SQLAlchemy much, but a <code>__str__</code> method like this should work:</p>
<pre><code>def __str__(self):
output = ''
for c in self.__table__.columns:
output += '{}: {}\n'.format(c.name,... | 0 | 2016-06-28T13:57:32Z | [
"python",
"sql",
"postgresql",
"sqlalchemy"
] |
Iterate through JSON [Python] | 38,072,280 | <p>I am reading the following JSON file in python:</p>
<pre><code> {
"name": "Property",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"uuid": {
"type": "string"
},
"userID": {
"type": "number"
},
"address": {
... | 0 | 2016-06-28T09:27:27Z | 38,072,480 | <p>Iterating over a dictionary yields its keys. <code>properties</code> is a dictionary:</p>
<pre><code>properties = data["properties"]
</code></pre>
<p>and when you iterate over it in:</p>
<pre><code>for property in properties:
print ('Property name: ' + property)
# propertyType = property["type"]
# pri... | 1 | 2016-06-28T09:37:04Z | [
"python",
"json"
] |
How to Strip Time from Date Time and store in PSQL using Python? | 38,072,338 | <p>I have a situation where i want to strip time from my date time object and store in database (PSQL precisely)</p>
<p>How do you do it ?</p>
<pre><code>>>> print(datetime.now())
2016-06-28 16:22:30.918715
</code></pre>
<p>What i want is </p>
<pre><code>2016-06-28
</code></pre>
<p>and store it into PSQL ... | 0 | 2016-06-28T09:30:28Z | 38,072,339 | <p>I am posting this answer cause it took me around an hour to find the answer and hope it helps to someone.
The best solution as for of now i have found is </p>
<pre><code>dt = datetime.today()
2016-06-28 16:22:30.918715
dt.strftime('%Y-%m-%d')
2016-06-28
</code></pre>
<p>Basically psql stores data in type string s... | 0 | 2016-06-28T09:30:28Z | [
"python",
"date",
"datetime",
"psql"
] |
Unexpected Performance Decrease | 38,072,433 | <p>I have to parse a huge (250 MB) text file, which for some reason is only a single line, causing every text editor I tried (Notepad++, Visual Studio, Matlab) to fail loading it. Therefore I read it piece by piece, and parse it whenever a logical line (starting with <code>#</code>) is completely read:</p>
<pre><code>... | 3 | 2016-06-28T09:34:59Z | 38,073,347 | <p>Your second version not only works slower but also works incorrectly.</p>
<p>In your first version you reset the <code>line</code> with assignment (<code>line = buffer[i+1:]</code>), whereas in the second version you only append to <code>line</code>. As a result, in the second version, in the end <code>line</code> ... | 1 | 2016-06-28T10:12:55Z | [
"python"
] |
Unexpected Performance Decrease | 38,072,433 | <p>I have to parse a huge (250 MB) text file, which for some reason is only a single line, causing every text editor I tried (Notepad++, Visual Studio, Matlab) to fail loading it. Therefore I read it piece by piece, and parse it whenever a logical line (starting with <code>#</code>) is completely read:</p>
<pre><code>... | 3 | 2016-06-28T09:34:59Z | 38,074,520 | <p>If I understood correctly what you want to do, than both versions of your code are wrong. Like @Leon said in second version you are missing <code>line = ""</code> after <code>ProcessLine(line)</code>, and in first version just the first line is correct, and than like you sad if line is shorter than buffer, you use ... | 1 | 2016-06-28T11:06:47Z | [
"python"
] |
How to rotate a function and get coordinates in python? | 38,072,524 | <p><a href="https://postimg.org/image/uzdalt4s1/" rel="nofollow">https://postimg.org/image/uzdalt4s1/</a></p>
<p>The script below will give coordinates of a point going through a sine function (figure A in URL image)</p>
<p>Similar to figure A, how do I get coordinates of a rotated function? (figure B)</p>
<pre><cod... | 1 | 2016-06-28T09:39:10Z | 38,081,072 | <p>this should work:</p>
<pre><code>from time import sleep
import math
def get_rotated_coordinates(x, y, fi, angle = 'deg'):
''' function rotates coordinates x and y for angle fi, variable
angle tells if angle fi is in degrees or radians, default value
is 'deg' for degrees, but you can also use 'rad' for ... | 0 | 2016-06-28T16:01:49Z | [
"python",
"graph",
"coordinates"
] |
Freeswitch 1.6 installation for ESL python | 38,072,591 | <p>I'm running Freeswitch 1.6 and Mac 10.10.5
My Freeswitch server will be in AWS and need to install Python ESL module in my local environment to start development using ESL.
I havent been able to find ESL module. I got the whole source and tried to build only Python library.</p>
<p>I used <a href="https://freeswitch... | 2 | 2016-06-28T09:41:52Z | 38,072,652 | <p>The following solution solved it for me:</p>
<p>From <a href="https://freeswitch.org/jira/browse/ESL-92" rel="nofollow">https://freeswitch.org/jira/browse/ESL-92</a></p>
<p>There is a bug in the <code>ld</code> command that ships with Mac OS X post Mavericks, due to which the "-x" flag strips extra symbols. The bu... | 2 | 2016-06-28T09:44:14Z | [
"python",
"swig",
"freeswitch"
] |
Django Queryset, accessing all query except those belongs to logged users? | 38,072,626 | <p>i know this:</p>
<pre><code>queryset = Item.objects.filter(user=self.request.user)
</code></pre>
<p>I want query for opposite of that, where i get Items of all user except logged one.</p>
| 1 | 2016-06-28T09:43:08Z | 38,072,681 | <p>The opposite of filter is <code>exclude</code>:</p>
<pre><code>queryset = Item.objects.exclude(user=self.request.user)
</code></pre>
| 3 | 2016-06-28T09:45:22Z | [
"python",
"django",
"django-models",
"django-views",
"django-queryset"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.