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
import java package into a jython project in Eclipse or PyCharm
38,197,501
<p>Using Eclipse + PyDev + jython. Need to import a java package to use a Java class inside a Python program (using Max OSX).</p> <p>For import, I mean statement in Python like <code>from com.a.b.c</code>. Wondering where should I put the Java jar file which contains <code>com.a.b.c</code>? Thanks.</p> <p>BTW, if any...
1
2016-07-05T07:21:36Z
38,268,613
<p>The import semantics do not differ that much from <code>CPython</code>s from what I see in the <a href="http://www.jython.org/jythonbook/en/1.0/ModulesPackages.html#module-search-path-and-loading" rel="nofollow"><code>Jython Docs</code></a>.</p> <p>First a search is made for the <code>.jar</code> file in the curren...
2
2016-07-08T14:02:07Z
[ "java", "python", "eclipse", "pycharm", "jython" ]
running python script on windows IOT rpi
38,197,599
<p>I have rpi 2 running windows IOT and I want to run python script on it. unfortunately I am having this error after the deploy</p> <p>I wrote the script using visual studio 2015 as a windows iot core background application.</p> <p>The error it gives me is </p> <pre><code>Severity Code Description Project F...
-1
2016-07-05T07:27:29Z
38,304,434
<p>I think this question should first of all be asked at <a href="http://raspberrypi.stackexchange.com">Raspberry Pi StackExchange Forum</a>.</p> <p>And from the the Error Messages that both of you seem to be having is somehow your network interfaces such as <strong>Loopback Addresses</strong> cannot be accessed using...
0
2016-07-11T10:16:42Z
[ "python", "visual-studio-2015", "raspberry-pi2", "iot", "windows-iot-core-10" ]
Python: sort a dictionary by values while maintain alphabetically in case of ties
38,197,722
<p>So, I want to sort a dictionary by values and maintain alphabetically in case of ties if the item values are of the same. However, the python dictionary does not save data alphabetically, how to fix it? Thank you in advance!</p> <p>Here is my code:</p> <pre><code>from collections import Counter test = "betty bough...
1
2016-07-05T07:34:52Z
38,197,797
<p>Use the <a href="https://docs.python.org/2/library/heapq.html#heapq.nsmallest" rel="nofollow"><code>heapq.nsmallest()</code> function</a> with a custom key, passing in a <em>negative</em> count to invert the sort for that part, and the key itself to be returned in alphabetical order:</p> <pre><code>import heapq to...
3
2016-07-05T07:39:03Z
[ "python", "sorting", "dictionary" ]
Python: sort a dictionary by values while maintain alphabetically in case of ties
38,197,722
<p>So, I want to sort a dictionary by values and maintain alphabetically in case of ties if the item values are of the same. However, the python dictionary does not save data alphabetically, how to fix it? Thank you in advance!</p> <p>Here is my code:</p> <pre><code>from collections import Counter test = "betty bough...
1
2016-07-05T07:34:52Z
38,198,046
<p>Alternatively - you could mix <code>Counter</code> and <code>OrderedDict</code>:</p> <pre><code>from collections import Counter, OrderedDict class OrderedCounter(Counter, OrderedDict): pass test = "betty bought a bit of butter but the butter was bitter" mc = OrderedCounter(sorted(test.split())).most_common(3)...
1
2016-07-05T07:53:31Z
[ "python", "sorting", "dictionary" ]
how to do partially match variable with array in python
38,197,735
<p>I have a script to do a partial match variable with array but it is not working</p> <pre><code>import re b = "Arun" links_check_arr = ['Arun sdsdds',"dsds","arun ijiji"] for links_find in links_check_arr: if b in list(links_find): print links_find print b </code></pre> <p>Above script is not ...
0
2016-07-05T07:35:45Z
38,197,928
<p>With your first example, I think you're looking for <code>.split()</code> instead of <code>list()</code>.</p> <pre><code>for links_find in links_check_arr: if b in links_find.split(): print links_find print b </code></pre> <p>I'm assuming what you're looking for is similar to checking if <code...
0
2016-07-05T07:46:52Z
[ "python", "arrays", "comparison" ]
how to write nested json data to CSV using python
38,197,816
<p>I have data which I fetched from URL and I get a JSON containing the data as nested LIST and DICTIONARY. Now I want to write this data into CSV file. </p> <pre><code>{ "type": "abs", "format": "cdg", "version": "6", "data": { "fff": { "version": "6", "id": "fff", "key": "266", "...
0
2016-07-05T07:40:02Z
38,199,782
<pre><code>import csv import json json_file='sample.json' with open(json_file, 'r') as json_data: x = json.load(json_data) f = csv.writer(open("test.csv", "w")) f.writerow(["type", "format", "version", "data__","data__|__version","data__|__id","info_attack","info_defense"]) types=x["type"] format=x["format"] roo...
0
2016-07-05T09:27:39Z
[ "python", "json", "csv" ]
Java calling Python function using PythonInterpreter
38,197,856
<p>I have a python module auth.py:</p> <pre><code>keys= { "s1": ["k1", "k2"], "s2": ["k1", "k2"] } def get_keys_by_name(name): return keys[name] </code></pre> <p>And the calling Java code:</p> <pre><code>String keyname= "somename" interpreter.exec("from services.framework import auth"); List&lt;String&g...
0
2016-07-05T07:42:46Z
38,198,226
<p>I think that your problem is that the python interpreter is interpreting the java variable keyname as a Python variable within the python program rather than as a string. Add quotes to around keyname and you won't get this error. I other words </p> <p>Instead of using:</p> <pre><code>List&lt;String&gt; keys = (L...
1
2016-07-05T08:05:43Z
[ "java", "python", "jython" ]
Java calling Python function using PythonInterpreter
38,197,856
<p>I have a python module auth.py:</p> <pre><code>keys= { "s1": ["k1", "k2"], "s2": ["k1", "k2"] } def get_keys_by_name(name): return keys[name] </code></pre> <p>And the calling Java code:</p> <pre><code>String keyname= "somename" interpreter.exec("from services.framework import auth"); List&lt;String&g...
0
2016-07-05T07:42:46Z
38,198,581
<p>As per request my comment as an answer :)</p> <p>Passing a key with value <code>abc</code> to <code>eval("auth.get_keys_by_name(" + keyname+ ")")</code> would result in <code>auth.get_keys_by_name(abc)</code> being evaluated, i.e. the interpreter will probably look for a variable named <code>abc</code> and since th...
1
2016-07-05T08:25:12Z
[ "java", "python", "jython" ]
ImportError: No module named win32service
38,197,879
<p>I am using odoo8 with python 2.7.9 (64 bit) on eclipse IDE. Python software got corrupted so I had to reinstall it.Now I am facing this new problem <code>ImportError: No module named win32service</code></p>
0
2016-07-05T07:43:55Z
38,198,005
<p>You need to install pywin32 from here: </p> <p><a href="https://sourceforge.net/projects/pywin32/files/pywin32/" rel="nofollow">https://sourceforge.net/projects/pywin32/files/pywin32/</a></p>
2
2016-07-05T07:51:16Z
[ "python", "openerp", "odoo-8" ]
According to a defined array filling in the dictionary
38,197,957
<p>I am new to python. I have dictionary called data_dict which contains many values to single given key. Two of those value are salary and exercised_stock_options. I want to update these two value in the dictionary for every key. The corresponding salary and stock values for each key are in lists salary_rescale, and s...
-1
2016-07-05T07:48:48Z
38,198,035
<p>You can simply do</p> <pre><code>for key in data_dict: data_dict[key]['salary_rescaled'] = salary_rescaled data_dict[key]['stock_rescaled'] = stock_rescaled </code></pre> <p>I hope I have answered the question, or else you can post comments</p>
0
2016-07-05T07:52:49Z
[ "python", "dictionary" ]
Pandas: How to plot multiple time series into a single plot from a single dataframe?
38,197,964
<p>I have the following pandas DataFrame.</p> <pre><code>import pandas as pd df = pd.read_csv('filename.csv') print(df) time Group blocks 0 1 A 4 1 2 A 7 2 3 A 12 3 4 A 17 4 5 A 21 5 6 ...
2
2016-07-05T07:49:16Z
38,198,715
<p>Look at this variants. The first is Andrews' curves and the second is a multiline plot which are grouped by one column <code>Month</code>. The dataframe <code>data</code> includes three columns <code>Temperature</code>, <code>Day</code>, and <code>Month</code>:</p> <pre><code>import pandas as pd import statsmodels....
1
2016-07-05T08:33:03Z
[ "python", "pandas", "matplotlib" ]
Multiple types of User with many mutual attributes
38,198,066
<p>How to create two <code>User</code> types with many mutual attributes? As far as I know, the best practise for creating two types of <code>User</code> is to create 2 <code>UserProfiles</code>. I have types - <code>Firm</code> and <code>Person</code>. So I've decided to create two <code>UserProfiles</code>:</p> <pre...
1
2016-07-05T07:55:11Z
38,198,270
<p>There are many ways to do this <a href="https://docs.djangoproject.com/en/1.9/topics/db/models/#model-inheritance" rel="nofollow">https://docs.djangoproject.com/en/1.9/topics/db/models/#model-inheritance</a></p> <p>Simplest would be creating <a href="https://docs.djangoproject.com/en/1.9/topics/db/models/#abstract-...
1
2016-07-05T08:08:54Z
[ "python", "django", "django-models", "django-users" ]
Looping in directory names (string error)
38,198,137
<p>I'm fairly new to python, so I apologise in advance for not having the most optimal code :)</p> <p>Anyways, I'm trying to do some plots with the matplotlib package, and is currently at this:</p> <pre><code>import os import numpy as np import matplotlib.pyplot as plt import re PATH_TO_YDATA1 = '401\PTV-06' PATH_TO...
1
2016-07-05T08:00:21Z
38,198,234
<p>Within your loop, <code>pathname</code> is not referring to the variables that you defined earlier, it is simply a string. To get the value of a variable (the actual path) from a string containing the variable name, you can use <code>eval(pathname)</code>. For example:</p> <pre><code>PATH_TO_YDATA1 = '401\PTV-06' P...
2
2016-07-05T08:06:26Z
[ "python", "matplotlib" ]
Looping in directory names (string error)
38,198,137
<p>I'm fairly new to python, so I apologise in advance for not having the most optimal code :)</p> <p>Anyways, I'm trying to do some plots with the matplotlib package, and is currently at this:</p> <pre><code>import os import numpy as np import matplotlib.pyplot as plt import re PATH_TO_YDATA1 = '401\PTV-06' PATH_TO...
1
2016-07-05T08:00:21Z
38,200,231
<p>I'd strongly recommend a different approach. In passing: if you ever need to resort to <code>eval</code> it is probable (but not certain) that you are doing something the wrong way.</p> <p>In this case use a list, not lots of individual variables:</p> <pre><code>PATHS_TO_YDATA = [ '401\PTV-06', '401\PTV-...
1
2016-07-05T09:49:25Z
[ "python", "matplotlib" ]
Convert python regex backreference to lower
38,198,224
<p>I created function for replace string with dictionary,</p> <pre><code>def tolower(text): patterns = { "\[(.*?)\]": (r"[\1-123]").lower() } for key in patterns: text = re.sub(key, patterns[key], text) return text print tolower("[IMG]UPPER[/IMG]") </code></pre> <p>But I want python ba...
0
2016-07-05T08:05:37Z
38,198,428
<p>Change to using a callable as the replacement argument:</p> <pre><code>import re def tolower(text): patterns = { "\[(.*?)\]": lambda m: '[{}-123]'.format(m.group(1).lower()) } for key in patterns: text = re.sub(key, patterns[key], text) return text print(tolower("[IMG]UPPER[/IMG]"))...
1
2016-07-05T08:16:46Z
[ "python" ]
Convert python regex backreference to lower
38,198,224
<p>I created function for replace string with dictionary,</p> <pre><code>def tolower(text): patterns = { "\[(.*?)\]": (r"[\1-123]").lower() } for key in patterns: text = re.sub(key, patterns[key], text) return text print tolower("[IMG]UPPER[/IMG]") </code></pre> <p>But I want python ba...
0
2016-07-05T08:05:37Z
38,198,468
<p>You can pass a function to <a href="http://docs.python.org/library/re.html#re.sub" rel="nofollow"><code>re.sub()</code></a> that will allow you to do this, here is an example:</p> <pre><code> def replaceLower(match): return '[' + match.group(1).lower() + '-123]' </code></pre> <p>To use it, instead of having e...
1
2016-07-05T08:19:14Z
[ "python" ]
Passing keywords recursively
38,198,304
<p>I've got a function that looks like this:</p> <pre><code>def bootstrap(instrument, parallel_process=True, **kw): prices = instrument.prices(**kw) </code></pre> <p>I want to be able to pass through keyword arguments, so the inner bits know what to do.</p> <p>I'm going to call it all with something like:</p> <...
2
2016-07-05T08:10:43Z
38,198,587
<p>I believe that this does what you want:</p> <pre><code>def prices(**kw_in): kw = dict(ccy_index=True) # Defaults kw.update(kw_in) print(kw["ccy_index"]) </code></pre> <p>In this way, you can pass arguments around recursively via <code>**kw</code> and also have assigned defaults at every stage.</p> <p>Usi...
1
2016-07-05T08:25:28Z
[ "python", "python-3.x", "recursion" ]
How do I change pixel values for an Image in Python?
38,198,379
<p>I am working on an Image Processing Project and I am a beginner at Python and using PIL. Any help would be appreciated.</p> <p>So, what I am doing is, I have an image of space with stars and noise. What I want to do is keep only the brighter pixels and filter out the dull ones. For now, this is my basic step at try...
2
2016-07-05T08:14:20Z
38,199,116
<p>You have made a silly mistake. In Line 6 You have written <code>pixelsNew = im.load</code>() instead of <code>pixelsNew = img.load()</code> This should work now.</p> <pre><code>from PIL import Image im = Image.open('nuvfits1.png') pixelMap = im.load() img = Image.new( im.mode, im.size) pixelsNew = img.load() for ...
1
2016-07-05T08:53:41Z
[ "python", "image-processing", "error-handling", "python-imaging-library", "pixel" ]
How do I change pixel values for an Image in Python?
38,198,379
<p>I am working on an Image Processing Project and I am a beginner at Python and using PIL. Any help would be appreciated.</p> <p>So, what I am doing is, I have an image of space with stars and noise. What I want to do is keep only the brighter pixels and filter out the dull ones. For now, this is my basic step at try...
2
2016-07-05T08:14:20Z
38,433,000
<p>The if block should be followed by an else block, so that "normal" pixels that do not meet your criteria retain their original values.</p> <pre><code>from PIL import Image im = Image.open('leaf.jpg') pixelMap = im.load() img = Image.new( im.mode, im.size) pixelsNew = img.load() for i in range(img.size[0]): for...
1
2016-07-18T09:21:53Z
[ "python", "image-processing", "error-handling", "python-imaging-library", "pixel" ]
Python: Send string + appended byte value over socket to C application
38,198,404
<p>I want to send a string "DeploymentMessage" with a specific value appended (0) through a Python script to a C application. The C application will look at the last byte of the received packet and see the value (0) and take certain actions.</p> <p>This works and is detected correctly by the C app:</p> <pre><code>MES...
-2
2016-07-05T08:15:29Z
38,206,471
<p>You want the <code>chr</code> function to convert a number to a string value:</p> <pre><code>NUMBER = 1 MESSAGE = "DeploymentMessage" print repr(MESSAGE + chr(NUMBER)) </code></pre> <p>However, as @paul-stelian points out, your C program will typically need a way to identify the end of the string, so you may want ...
0
2016-07-05T14:48:30Z
[ "python", "c", "string", "sockets" ]
How to use multiple decorators with spyne
38,198,523
<p>I have a problem with multiple decorators with spyne. I want to add universal try/except decorator to each method in class. My code looks like this:</p> <pre><code>def try_except(fn): def wrapped(*args, **kwargs): try: return fn(*args, **kwargs) except Exception: ...
2
2016-07-05T08:22:17Z
38,233,308
<p>I don't recommend decorators. Not because they are not supported, but because they are not very powerful and also have cryptic behaviour.</p> <p>For exception handling, you can override <code>call_wrapper</code> function of either <code>Application</code> or <code>ServiceBase</code> in a class in your project and u...
1
2016-07-06T20:35:19Z
[ "python", "web-services", "wcf", "python-decorators", "spyne" ]
Split element in a list
38,198,606
<p>I have an input string:</p> <blockquote> <p>"[u'$799,900', u'$1,698,000', u'$998,000', u'$1,299,000', u'$1,000,000', u'$499,950', u'$995,000', u'$998,000', u'$2,000,000', u'$988,000', u'$979,000', u'$1,285,000', u'$988,000', u'$579,000', u'$700,000', u'$1,100,000', u'$1,557,000', u'$999,888', u'$798,000', ...
0
2016-07-05T08:27:01Z
38,199,655
<p>You have several problems in your code.</p> <hr> <h2>Create a variable which will hold the values</h2> <p>Unrelated to your current question, but important if you want to expand upon your solution:</p> <p>You are iterating over lines of file, but aren't keeping a variable that holds the values you have gone thro...
2
2016-07-05T09:21:25Z
[ "python", "regex", "list" ]
Pandas dataframe to AnguarJS
38,198,728
<p>I have a RESTful architecture where AngularJS consumes DRF apis. Now with pandas, I converted my dataframe to html table but I can not figure out how to send it to AngularJS and render it. The dataframe table looks like this-</p> <pre><code>&lt;table border="1" class="dataframe table"&gt; &lt;thead&gt; &lt;tr sty...
0
2016-07-05T08:33:41Z
38,198,844
<p>Would it not be easier to <code>pandas.DataFrame.to_json()</code> then render in AngluarJS? feels like the html step is adding complexity. </p>
1
2016-07-05T08:39:43Z
[ "python", "angularjs", "django", "rest", "pandas" ]
Pandas dataframe to AnguarJS
38,198,728
<p>I have a RESTful architecture where AngularJS consumes DRF apis. Now with pandas, I converted my dataframe to html table but I can not figure out how to send it to AngularJS and render it. The dataframe table looks like this-</p> <pre><code>&lt;table border="1" class="dataframe table"&gt; &lt;thead&gt; &lt;tr sty...
0
2016-07-05T08:33:41Z
38,200,410
<p>It worked without changing anything. Saved the dataframe to <code>textfiled()</code> after <code>.to_html</code>, serialized it with drf and used ng-sanitize in AngularJS and the tables rendered.</p>
0
2016-07-05T09:56:13Z
[ "python", "angularjs", "django", "rest", "pandas" ]
Create Windows DSN using python3
38,198,812
<p>Is it possible to create ODBC data source in windows using python 3?</p> <p>Following statement runs successfully with python2 but not with python3, why? ODBCCP32 is available only in py2?</p> <p><code>ctypes.windll.ODBCCP32.SQLConfigDataSource(0, 4, "Microsoft Access Driver (*.mdb)", 'Uid="Admin"\x00DESCRIPTION="...
-2
2016-07-05T08:38:16Z
38,204,798
<p>It wasn't working because all strings in python3 are unicode strings by default.</p> <p>So I had to convert it to 'bytes' object liket this: <code>ctypes.windll.ODBCCP32.SQLConfigDataSource(0, 4, bytes('Microsoft Access Driver (*.mdb)', 'iso-8859-1'), bytes('Uid=Admin\x00DESCRIPTION=pyscript\x00DSN=PYTEST\x00pwd=\x...
0
2016-07-05T13:30:16Z
[ "python", "database", "windows", "odbc" ]
Read images starting with a specific words together in Python
38,198,933
<p>I have many images to read. for example <em>300</em> images with the names of <code>a1.jpg</code>, <code>a2.jpg</code>, ..., <code>a100.jpg</code>, <code>b1.jpg</code>, ..., <code>b100.jpg</code>, <code>c1.jpg</code>, <code>c2.jpg</code>, ..., <code>c100.jpg</code>. I want to use <code>imread()</code> function in a ...
0
2016-07-05T08:44:16Z
38,199,066
<p>Quick &amp; Dirty:</p> <pre><code>charToRead = 'a' for i in range(100): s = charToRead + str(i+1) + '.jpg' print(s) im=misc.imread(s) </code></pre>
0
2016-07-05T08:51:20Z
[ "python" ]
Read images starting with a specific words together in Python
38,198,933
<p>I have many images to read. for example <em>300</em> images with the names of <code>a1.jpg</code>, <code>a2.jpg</code>, ..., <code>a100.jpg</code>, <code>b1.jpg</code>, ..., <code>b100.jpg</code>, <code>c1.jpg</code>, <code>c2.jpg</code>, ..., <code>c100.jpg</code>. I want to use <code>imread()</code> function in a ...
0
2016-07-05T08:44:16Z
38,199,072
<p>You can list out all the images in a list first and loop over them. Suppose , </p> <pre><code>a = ['a1.jpg', 'a2.jpg', 'a100.jpg','b10.jpg','c100.jpg'] matching = [s for s in a if s.startswith('a')] </code></pre> <p>The matching will be a list of all images having name started with 'a' character. </p>
0
2016-07-05T08:51:35Z
[ "python" ]
Read images starting with a specific words together in Python
38,198,933
<p>I have many images to read. for example <em>300</em> images with the names of <code>a1.jpg</code>, <code>a2.jpg</code>, ..., <code>a100.jpg</code>, <code>b1.jpg</code>, ..., <code>b100.jpg</code>, <code>c1.jpg</code>, <code>c2.jpg</code>, ..., <code>c100.jpg</code>. I want to use <code>imread()</code> function in a ...
0
2016-07-05T08:44:16Z
38,199,108
<p>It has nothing to do with <code>imread</code> itself.</p> <p>Given that you already have the list of file names, you have several options:</p> <ol> <li><p>Use <code>filter</code> to end up with only the filenames you want:</p> <pre><code>relevant_files = filter(lambda name: name.startswith('a'), list_of_files) fo...
2
2016-07-05T08:53:06Z
[ "python" ]
Read images starting with a specific words together in Python
38,198,933
<p>I have many images to read. for example <em>300</em> images with the names of <code>a1.jpg</code>, <code>a2.jpg</code>, ..., <code>a100.jpg</code>, <code>b1.jpg</code>, ..., <code>b100.jpg</code>, <code>c1.jpg</code>, <code>c2.jpg</code>, ..., <code>c100.jpg</code>. I want to use <code>imread()</code> function in a ...
0
2016-07-05T08:44:16Z
38,199,176
<p>If all your image are in the same repertory, you can browse all the file name in this repertory, check if it start by a, if yes then display it imread. It would do soemthing like :</p> <pre><code>import os for file in os.listdir("/mydir"): if file.endswith(".jpg") and file.startwith("a"): im=misc.imrea...
0
2016-07-05T08:56:33Z
[ "python" ]
Read images starting with a specific words together in Python
38,198,933
<p>I have many images to read. for example <em>300</em> images with the names of <code>a1.jpg</code>, <code>a2.jpg</code>, ..., <code>a100.jpg</code>, <code>b1.jpg</code>, ..., <code>b100.jpg</code>, <code>c1.jpg</code>, <code>c2.jpg</code>, ..., <code>c100.jpg</code>. I want to use <code>imread()</code> function in a ...
0
2016-07-05T08:44:16Z
38,199,227
<p>This is an interesting place to use <code>iterools.groupby</code></p> <pre><code>&gt;&gt;&gt; x = ['a1.jpg', 'a2.jpg', 'b1.jpg', 'b2.jpg'] &gt;&gt;&gt; groups = itertools.groupby(x, lambda t:t[0]) &gt;&gt;&gt; for key,l in groups: ... print (key) ... for j in l: ... print (" ",j) ... a (' ', 'a1.jpg') ('...
1
2016-07-05T08:58:54Z
[ "python" ]
Download directory/files from FTP location using python script
38,198,987
<p>Download not working in python?</p> <p>I've written a simple python program, to get files from FTP location but when I execute it, it gives an error [Errno 13] Permission denied message.</p> <p>My code is as follows. Any idea why it's not working ?</p> <pre><code>import ftplib from ftplib import FTP, error_perm ...
0
2016-07-05T08:47:14Z
38,199,760
<p>The documentation of ftplib says (emphasize mine):</p> <blockquote> <p>FTP.retrbinary(command, callback[, maxblocksize[, rest]]) </p> <p>Retrieve a file in binary transfer mode. command should be an appropriate RETR command: 'RETR filename'. <strong>The callback function is called for each block</strong> of ...
0
2016-07-05T09:26:14Z
[ "python", "ftplib" ]
Python returns MagicMock object instead of return_value
38,199,008
<p>I have a python file <code>a.py</code> which contains two classes <code>A</code> and <code>B</code>.</p> <pre><code>class A(object): def method_a(self): return "Class A method a" class B(object): def method_b(self): a = A() print a.method_a() </code></pre> <p>I would like to unitte...
1
2016-07-05T08:48:12Z
38,199,345
<p>When you <code>@mock.patch('a.A')</code>, you are replacing the class <code>A</code> in the code under test with <code>mock_a</code>. </p> <p>In <code>B.method_b</code> you then set <code>a = A()</code>, which is now <code>a = mock_a()</code> - i.e. <code>a</code> is the <code>return_value</code> of <code>mock_a</c...
1
2016-07-05T09:05:29Z
[ "python", "python-unittest", "magicmock" ]
Does the timeout parameter in Python's sqlite3 module affect the speed of normal transactions?
38,199,064
<p>I am running a Python script on an Android phone using <a href="http://www.github.com/damonkohler/sl4a" rel="nofollow">SL4A</a> (sadly now basically dead). SL4A provides Python 2.6.</p> <p>This script (along with some other processes) accesses an sqlite database using Python's built in <a href="https://docs.python...
0
2016-07-05T08:51:15Z
38,203,235
<p>The <a href="http://www.sqlite.org/c3ref/busy_timeout.html" rel="nofollow">timeout</a> matters only if two transactions actually conflict.</p>
1
2016-07-05T12:16:51Z
[ "android", "python", "sqlite3", "sl4a" ]
How to check if the snapshot is now 'completed'
38,199,084
<p>i am using boto3 to create snapshot of a id and i just need to check if the snapshot is finished creating , but the following loop doesn't do that and just runs to infinity .</p> <pre><code>regions = ['eu-central-1'] for region in regions: ec2 = boto3.resource('ec2', region, aws_access_key_id=ACCESS_KEY, aws_se...
0
2016-07-05T08:51:51Z
38,199,800
<p>You should call <a href="http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Snapshot.load" rel="nofollow"><code>snapshot.load()</code></a> before the loop and after your <code>sleep</code> statement. </p> <p>Just tested it on an AWS micro instance and it works when added to your code.</p> <pre><...
2
2016-07-05T09:28:30Z
[ "python", "boto3" ]
How to check if the snapshot is now 'completed'
38,199,084
<p>i am using boto3 to create snapshot of a id and i just need to check if the snapshot is finished creating , but the following loop doesn't do that and just runs to infinity .</p> <pre><code>regions = ['eu-central-1'] for region in regions: ec2 = boto3.resource('ec2', region, aws_access_key_id=ACCESS_KEY, aws_se...
0
2016-07-05T08:51:51Z
38,211,289
<p>Maximillian brings up <code>load</code>, but I recommend you use the <a href="http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Waiter.SnapshotCompleted" rel="nofollow">waiter</a>. This will handle all the waiting logic for you and return when your snapshot is completed. For that resource, you wo...
1
2016-07-05T19:32:20Z
[ "python", "boto3" ]
Making a standalone python script that can be run by another software
38,199,164
<p>I am currently interning at a place where they've asked me to make a standalone python program to do something (say X).<br> Now, that program is to be run by some commands sent by their proprietary software which is written in their proprietary language. Now the reason I'm saying proprietary so many times is because...
0
2016-07-05T08:55:59Z
38,199,923
<p>Any programm can execute any other program (if it has the appropriate rights) so there is no real distinction between "python file" and "python executable" (that is because python is an interpreted language. The python source files and the "final python program" are "identical" (asuming cpython), in contrast to e.g....
0
2016-07-05T09:33:50Z
[ "python", "api", "opencv", "python-standalone" ]
exception if module does not exist
38,199,219
<p>Is it possible to do try exception (or something else) if a module exists or not? I have a code as(all of them are defined, just not included here):</p> <pre><code>import matplotlib.pyplot as plt import numpy as np def scf: A = np.array(plist, dtype="float") np.savetxt("foo.dat", A, delimit...
-1
2016-07-05T08:58:37Z
38,199,262
<p>Importing a module that does not exist will raise <code>ImportError</code>, which you can catch like any other exception with a try/except block.</p>
0
2016-07-05T09:01:08Z
[ "python", "python-module" ]
Get a document with find_one (pymongo)
38,199,241
<p>I got a documentstructure like this: </p> <pre><code>{ "_id": "106.xxx.xxx.xxx", "maxAge": 48, "origin": "some_origin", "time": "2016-07-04 11:41:47" } </code></pre> <p>_id contains an IP-Adress which i want to get with the find_one function of pymongo. I am calling it like this: </p> <pre><code>...
0
2016-07-05T08:59:54Z
38,199,859
<p>Check that if <code>ip</code> is of type string. This might be creating the problem during search. If its not try typecasting it to string.</p>
0
2016-07-05T09:31:05Z
[ "python", "mongodb", "pymongo", "bottle" ]
Get a document with find_one (pymongo)
38,199,241
<p>I got a documentstructure like this: </p> <pre><code>{ "_id": "106.xxx.xxx.xxx", "maxAge": 48, "origin": "some_origin", "time": "2016-07-04 11:41:47" } </code></pre> <p>_id contains an IP-Adress which i want to get with the find_one function of pymongo. I am calling it like this: </p> <pre><code>...
0
2016-07-05T08:59:54Z
38,199,916
<p>That means it cannot find the document.</p> <p>Be sure that the document exist and you are querying on the correct type - string.</p> <p>Also test your pymongo connection (change my values with yours):</p> <pre><code>from pymongo import MongoClient client = MongoClient('localhost') db_name = 'test_db' db = client...
0
2016-07-05T09:33:34Z
[ "python", "mongodb", "pymongo", "bottle" ]
execute makefile from the command line not from sh.exe
38,199,373
<p>I'm trying to install a python package with C/C++ bindings (PyQt4, popplerqt4). When I try to build the package (SIP package needed for the binding) I get this error:</p> <pre><code>/bin/sh: -c: line 1: syntax error:unexpected end of file </code></pre> <p><a href="http://i.stack.imgur.com/9ckDf.png" rel="nofollow"...
1
2016-07-05T09:06:32Z
38,199,691
<p>Per the documentation you have referred to, write:</p> <pre><code>SHELL := cmd </code></pre> <p>in your makefile (near the top, conventionally) to tell <code>make</code> to invoke <code>cmd</code> as the shell program. <code>cmd</code> is the Windows shell.</p>
0
2016-07-05T09:23:14Z
[ "python", "windows", "makefile", "sh", "gnu-make" ]
How to use the dropna() to drop itme which is < 1?
38,199,408
<p>I have a DataFrame as follow:</p> <pre><code>mydf = pd.DataFrame({'Name1':(4.2, 0.3), 'Name2':(0.2, 4.2), 'Name3':(3.3, 5.5)}, index=('Val1', 'Val2')) </code></pre> <p>How can I drop a column in which any item's value &lt; 1?</p>
0
2016-07-05T09:08:35Z
38,199,496
<p>This selects columns where all elements are <code>&gt;=1</code> (complement of any of them being smaller than 1):</p> <pre><code>mydf.ix[:, ~(mydf&lt;1).any()] Out[9]: Name3 Val1 3.3 Val2 5.5 </code></pre>
1
2016-07-05T09:13:19Z
[ "python", "pandas" ]
How to use the dropna() to drop itme which is < 1?
38,199,408
<p>I have a DataFrame as follow:</p> <pre><code>mydf = pd.DataFrame({'Name1':(4.2, 0.3), 'Name2':(0.2, 4.2), 'Name3':(3.3, 5.5)}, index=('Val1', 'Val2')) </code></pre> <p>How can I drop a column in which any item's value &lt; 1?</p>
0
2016-07-05T09:08:35Z
38,200,761
<p>Another solution using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html" rel="nofollow">dropna</a> is:</p> <pre><code>df Out[34]: Name1 Name2 Name3 Val1 4.2 0.2 3.3 Val2 0.3 4.2 5.5 In [35]: df[df&lt;1]=np.nan In [36]: df Out[36]: Name1 ...
1
2016-07-05T10:13:26Z
[ "python", "pandas" ]
Why the order of listed files in a directory change between Windows and Ubuntu?
38,199,429
<p>I have noticed that the order in which Python 3.4 lists files in a directory varies depending on which OS an script is executed. I have a script that list files in a directory using the 'os' package. The order of the list varies depending if I run the script in Windows 10 or Ubuntu 14.04 LTS. For Windows 10 the orde...
0
2016-07-05T09:10:16Z
38,199,486
<p>Straight from <code>os.listdir</code> <a href="https://docs.python.org/3.4/library/os.html" rel="nofollow">documentation</a>:</p> <blockquote> <p>The list is in arbitrary order, and does not include the special entries '.' and '..' even if they are present in the directory.</p> </blockquote>
2
2016-07-05T09:12:46Z
[ "python", "windows", "ubuntu-14.04" ]
Plain Text export from Google Docs with PYdrive has a centered dot in Github
38,199,430
<p>I wrote a Pydrive script which downloads all the files in a specific folder.</p> <p>The docs get downloaded as 'sampleTitle.md' with the mimetype of 'text/plain'.</p> <p>then they simply get commited and pushed to my repo.</p> <p>Here is my python code for pydrive:</p> <pre><code>def checkFile(arg): if arg['...
0
2016-07-05T09:10:19Z
38,242,332
<p>When a file with mimetype "application/vnd.google-apps.document" is downloaded as "text/plain" a BOM gets inserted.</p> <p>This BOM seems to be interpreted as a whitespace in nano and · in github.</p> <p>The following command for removing BOMs works when the data gets renamed.</p> <p>not working:</p> <pre><code...
0
2016-07-07T09:46:29Z
[ "python", "github", "google-drive-sdk", "markdown", "pydrive" ]
kNN Classifier - importance of DataFrame column order - is this a scikit bug, pandas bug or by design?
38,199,537
<p>We have this sci-py code:</p> <pre><code>import pandas as pd from sklearn.neighbors import KNeighborsClassifier df = pd.DataFrame({'Category':['X','X','X','X','X','X','Y','Y','Y','Y','Y'] ,'Age':[10,20,30,35,32,33,27,70,40,50,60] ,'Weight':[15,16,21,33,7,8,9,11,31,38...
3
2016-07-05T09:15:50Z
38,201,247
<p>I don't think there is a bug, but I agree it could be better documented. You have to provide the dataframe in the correct order.</p> <p>As scikit was built with numpy in mind the Dataframe is converted to a numpy 2d array (this also during the <code>fit</code> part), and it does not save the headers order. </p> <p...
2
2016-07-05T10:36:31Z
[ "python", "pandas", "scikit-learn" ]
Neural network with 'tanh' as activation and 'cross-entropy' as cost function did not work
38,199,601
<p>I have implemented a simple neural network. It works well with 'sigmoid + cross-entropy', 'sigmoid + quadratic cost', and 'tanh + quadratic cost', but it did not work with 'tanh + cross-entropy' (no better than randomly guess). Can anybody please help me figure out why? Just see the code of FullConnectedLayer:</p> ...
1
2016-07-05T09:18:52Z
38,201,086
<p>Looks like you're using <code>tanh</code> in your output layer, where <code>tanh</code> has the range <code>-1, +1</code> and the expected outputs are in the range <code>0, +1</code>. This doesn't matter for the <code>Sigmoid</code> which does produce outputs in the range <code>0, +1</code>.</p>
1
2016-07-05T10:28:36Z
[ "python", "machine-learning", "neural-network" ]
Neural network with 'tanh' as activation and 'cross-entropy' as cost function did not work
38,199,601
<p>I have implemented a simple neural network. It works well with 'sigmoid + cross-entropy', 'sigmoid + quadratic cost', and 'tanh + quadratic cost', but it did not work with 'tanh + cross-entropy' (no better than randomly guess). Can anybody please help me figure out why? Just see the code of FullConnectedLayer:</p> ...
1
2016-07-05T09:18:52Z
38,201,126
<p>Cross entropy expects it's inputs to be logits, which are in the range 0 to 1. The Tanh method transforms the input to values in the range -1 to 1 which cross entropy can't handle.</p> <p>Some possible fixes would be to rescale the input in the final layer in the input is tanh and the cost cross-entropy.</p>
0
2016-07-05T10:30:11Z
[ "python", "machine-learning", "neural-network" ]
How to put a table into a QMessageBox
38,199,616
<p>I actually have two questions : - can I have a "Show details" button elsewhere in a QMessageBox (like in a QDialog for exemple)? - how can I put a tableWidget into a QMessageBox?</p> <p>Thank you</p>
0
2016-07-05T09:19:24Z
38,506,107
<pre><code>#This is the example code for put a tableWidget into a QMessageBox. #If your are not expecting this answer, sorry. import sys from PyQt4 import QtCore, QtGui class MyMessageBox(QtGui.QMessageBox): def __init__(self): QtGui.QMessageBox.__init__(self) self.setSizeGripEnabled (True) ...
0
2016-07-21T13:49:19Z
[ "python", "pyqt" ]
Python crashes with SFrame
38,199,649
<p>I am doing a course on ML on Coursera. I am using graphlab for this course</p> <p>When I execute the below line, my python gets crashed. Please help me in solving this. I have no clue why it crashes everytime</p> <pre><code>sf = graphlab.SFrame('people-example.csv') </code></pre> <p><a href="http://i.stack.imgur....
0
2016-07-05T09:20:59Z
38,216,250
<p>SFrame syntax requires that you use:</p> <pre><code>sf = graphlab.SFrame.read_csv('people-example.csv') </code></pre> <p>That should would, I'm not sure why python would crash as result of incorrect syntax.</p>
0
2016-07-06T04:17:02Z
[ "python", "graphlab", "sframe" ]
Python crashes with SFrame
38,199,649
<p>I am doing a course on ML on Coursera. I am using graphlab for this course</p> <p>When I execute the below line, my python gets crashed. Please help me in solving this. I have no clue why it crashes everytime</p> <pre><code>sf = graphlab.SFrame('people-example.csv') </code></pre> <p><a href="http://i.stack.imgur....
0
2016-07-05T09:20:59Z
39,734,559
<p>What I had to do to fix this (on my firewalled Windows 10 system). First I completely uninstalled Anaconda2 and reinstalled it from scratch.</p> <p>Second go to Turi, register and download the GraphLab license file.</p> <p>Then in a browser go to pypi.python.org/simple/ and download the GraphLab-Create (currently ...
1
2016-09-27T21:26:11Z
[ "python", "graphlab", "sframe" ]
Concatenate Pandas Dataframes Rows side by side / top and bottom in same time
38,199,803
<p>I've problem. I want to create a new dataframe from another one. I want to avoid duplicate rows. It mean if there is same mails, I should concatenate them side-by-side otherwise top and bottom. But the problem is I'm getting value indexing error every time.</p> <pre><code>pandas.indexes.base.InvalidIndexError: Rein...
1
2016-07-05T09:28:38Z
38,200,261
<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>, but first create groups by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow"><code>cumcount</code></a...
1
2016-07-05T09:50:57Z
[ "python", "pandas", "indexing", "dataframe", "concatenation" ]
Creating a class in python using a string as the class name
38,199,956
<p>I have been looking for this for quite sometime and also looked at previously asked questions like:</p> <p><a href="http://stackoverflow.com/questions/3451779/how-to-dynamically-create-an-instance-of-a-class-in-python">how to dynamically create an instance of a class in python?</a></p> <p><a href="http://stackover...
0
2016-07-05T09:35:23Z
38,295,966
<p>You could store the classes you're dynamically creating into a dictionary, mapping class names to classes. This way you can use such a dictionary to access your classes by name later in your code, e.g. to create instances. For example:</p> <pre><code>store_list = {'store1', 'storeabc', 'store234'} name2class = {} f...
1
2016-07-10T19:57:56Z
[ "python" ]
Python Pandas - Compare specific rows and combine
38,200,084
<p>I have following data sets:</p> <pre><code>Group LowerTier UpperTier Value 1 0 99 0 1 100 199 0 1 200 299 10 1 300 1000 20 2 0 249 0 2 250 1000 5 (...)...
0
2016-07-05T09:40:48Z
38,200,254
<p>Did you try <code>groupby</code> with <code>aggregate</code>?</p> <pre><code>df.groupby(['Group','Value'],as_index=False).agg({'LowerTier':min,'UpperTier':max}) </code></pre> <p>First create the dataframe:</p> <pre><code>df = pd.DataFrame({'Group':[1,1,1,1,2,2],'LowerTier':[0,100,200,300,0,250],'UpperTier':[99,19...
3
2016-07-05T09:50:45Z
[ "python", "pandas", "rows" ]
Python3.5 and os.makedirs() not working
38,200,094
<p>In my python script is a method that should create parent directory for path defined in input. Script finishes without any exception, but no directory was created. I run python3.5 in Ubuntu 14.04.</p> <pre><code>def create_parent_directory(path): dir_name = os.path.dirname(path) if not os.path.exists(dir_na...
0
2016-07-05T09:41:23Z
38,203,546
<p>The directory you're trying to create already exists.</p> <p><code>os.path.dirname("/home/bla/blabla/MyPath")</code> returns the directory that <code>MyPath</code> is in, that is, <code>/home/bla/blabla</code>. If your script lies in the directory <code>/home/bla/blabla</code>, and you want to create a <code>MyPath...
0
2016-07-05T12:31:58Z
[ "python", "path", "directory", "operating-system" ]
Using a button to re-start an algorithm
38,200,163
<p>I am trying to make a simple math game. Now I've researched all over the internet, and worked on it for hours, but I can't seem to make this simple game to work.</p> <p><strong>How the game works:</strong> The game asks the user a question, the user gives the answer in a entry bar, the user clicks the button, and t...
0
2016-07-05T09:44:56Z
38,203,129
<p>A big problem with tkinter is that while loops that require user interact to exit kills it.</p> <p>Here are my adjustments.</p> <pre><code>class GamePage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.count = 0 self.price = 0 self.label ...
0
2016-07-05T12:11:14Z
[ "python", "tkinter" ]
How do I get only those lines that has highest value if they are inside a timewindow?
38,200,280
<p>I am new to the python and scripting in general, so I would really appreciate some guidance in writing a python script. So, to the point:</p> <p>I have a big number of files in a directory. Some files are empty, other contain rows like that:</p> <p>16 2009-09-30T20:07:59.659Z 0.05 0.27 13.559 6<br> 16 2009-09-30T2...
0
2016-07-05T09:51:31Z
38,205,091
<p>you said in the comments you know how to merge multiple files into 1 sorted by <code>t</code> and that the 6 second windows start with the first row and are based on actual data.</p> <p>so, you need a way to remember the maximum threshold per window and write only after you are sure you processed all rows in a wind...
0
2016-07-05T13:43:42Z
[ "python", "rows" ]
How to get newly created id? DJANGO
38,200,284
<p>I have two tables that are linked together, the Delivery table and Stock table. They are linked together by the delivery_id being a foreign key in the Stock table. My dilemma is that I have to get the newly created ID from the Delivery form to my Stock form. How do I do it?</p> <pre><code>def delivery(request): ...
-1
2016-07-05T09:51:48Z
38,201,445
<p>Well, to help with your code, you should have posted your model codes. But anyway, to 'link' the models you should follow these steps in your code:</p> <h1>Instantiating models and Creating Relationships</h1> <p>This step is about to create a variable that refers to the Delivery model.</p> <pre><code>from YourApp...
1
2016-07-05T10:45:28Z
[ "python", "django" ]
Searching a field in SQL to see if it contains a python variable
38,200,291
<p>I am using the Canari Framework to build a series of transforms within Malteog that scan a MySQL database and return the results as entities. </p> <p>I've got the entire thing working bar the LIKE operator within the SQL statement. Here's the code:</p> <pre><code>#==================================================...
1
2016-07-05T09:51:59Z
38,201,387
<p>The SQL LIKE operator needs special "wildcard" markers ("%" in MySQL) before and/or after the value (depending on if you want a "starts with", "endswith" or "contains" search). You have to add those wildcards around your argument, ie:</p> <pre><code>cursor.execute(statement, {'tq': "%{}%".format(target)}) </code></...
0
2016-07-05T10:42:28Z
[ "python", "mysql", "python-2.7" ]
plot all columns of a text file with python (equivalent of -nxy option in xmgrace)
38,200,293
<p>I have a text file with N columns (N unknown or quite large), say data.txt. I would like to plot the last N-1 columns versus the first column with python. In other words, how can I get python to work like a 'xmgrace -nxy data.txt'</p> <p>many thanks in advance</p>
0
2016-07-05T09:52:08Z
38,200,587
<p>Use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html" rel="nofollow"><code>np.genfromtxt()</code></a> to read the file, and then just plot in a loop, like this:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt data = np.genfromtxt('data.txt') fig, ax = plt.subplo...
1
2016-07-05T10:04:41Z
[ "python", "matplotlib", "xmgrace" ]
How to config timeout when using the RPC interface of aria2?
38,200,311
<p>I'm using the <code>xmlrpclib</code> of Python to interact with <code>aria2</code> to manage files to download.</p> <p>In the <a href="https://aria2.github.io/manual/en/html/aria2c.html#rpc-interface" rel="nofollow">documentation</a>, the only option that's shown in example is: <code>dir</code>.</p> <p>I can also ...
0
2016-07-05T09:52:38Z
38,201,815
<p>You need to set timeout on the <code>socket</code> library level:</p> <pre><code>import socket socket.setdefaulttimeout(&lt;your_value&gt;) </code></pre> <p>This value will be used by <code>xmlrpclib</code>.</p>
0
2016-07-05T11:03:59Z
[ "python", "download", "aria2" ]
What would be the best way to collect the titles (in bulk) of a subreddit
38,200,514
<p>I am looking to collect the titles of all of the posts on a subreddit, and I wanted to know what would be the best way of going about this?</p> <p>I've looked around and found some stuff talking about Python and bots. I've also had a brief look at the API and am unsure in which direction to go.</p> <p>As I do not ...
1
2016-07-05T10:00:37Z
38,200,754
<p>PHP; in 25 lines:</p> <pre><code>$subreddit = 'pokemon'; $max_pages = 10; // Set variables with default data $page = 0; $after = ''; $titles = ''; do { $url = 'http://www.reddit.com/r/' . $subreddit . '/new.json?limit=25&amp;after=' . $after; // Set URL you want to fetch $ch = curl_init($url); //...
1
2016-07-05T10:13:17Z
[ "php", "python", "automation", "bots", "reddit" ]
Unable to read regex in a JSON file as a string in Python
38,200,642
<p>I need to read the below JSON file into Python with regex intact. I will be using the regular expressions in the program.</p> <pre><code>{ "Title": "Sample Compliance Check", "Checks": { "6": { "+": ["^interfa.*", "^ip address 192\.168\.0"], "description": "All interfaces wit...
1
2016-07-05T10:07:44Z
38,201,288
<p>Raw string formatting and "normal string formatting" in python do not change the way the string is stored, but only how you can enter the string. So the following strings are both equal:</p> <pre><code>"\\a" == r"\a" </code></pre> <p>Python shows you backslashes escaped, but if you try the regex you will see that ...
3
2016-07-05T10:38:40Z
[ "python", "json", "regex" ]
Splitting multiple/all columns of a pandas dataframe
38,200,655
<p>I have a pandas dataframe full of tuple (it could be the same with arrays) and I would like to split all the columns into even more columns (each array or tuple has the same length). Let's take this as an example:</p> <pre><code>df=pd.DataFrame([[(1,2),(3,4)],[(5,6),(7,8)]], df.columns=['column0', 'column1']) </co...
0
2016-07-05T10:08:31Z
38,200,855
<p>IIUC you can use:</p> <pre><code>df=pd.DataFrame([[(1,2),(3,4)],[(5,6),(7,8)]], columns=['column0', 'column1']) print (df) column0 column1 0 (1, 2) (3, 4) 1 (5, 6) (7, 8) for col in df.columns: df[col]=df[col].apply(lambda s: pd.Series({'feature1':s[0], 'feature2':s[1]})) print (df) column0 column...
1
2016-07-05T10:17:35Z
[ "python", "pandas", "split", "multiple-columns" ]
Splitting multiple/all columns of a pandas dataframe
38,200,655
<p>I have a pandas dataframe full of tuple (it could be the same with arrays) and I would like to split all the columns into even more columns (each array or tuple has the same length). Let's take this as an example:</p> <pre><code>df=pd.DataFrame([[(1,2),(3,4)],[(5,6),(7,8)]], df.columns=['column0', 'column1']) </co...
0
2016-07-05T10:08:31Z
38,202,202
<p>You could extract the DataFrame values as a NumPy array, use <code>IT.chain.from_iterable</code> to extract the ints from the tuples, and then reshape and rebuild the array into a new DataFrame:</p> <pre><code>import itertools as IT import numpy as np import pandas as pd df = pd.DataFrame([[(1,2),(3,4)],[(5,6),(7,8...
1
2016-07-05T11:22:31Z
[ "python", "pandas", "split", "multiple-columns" ]
Splitting multiple/all columns of a pandas dataframe
38,200,655
<p>I have a pandas dataframe full of tuple (it could be the same with arrays) and I would like to split all the columns into even more columns (each array or tuple has the same length). Let's take this as an example:</p> <pre><code>df=pd.DataFrame([[(1,2),(3,4)],[(5,6),(7,8)]], df.columns=['column0', 'column1']) </co...
0
2016-07-05T10:08:31Z
38,202,246
<p>You may iterate over each column you want to split and assign the new columns to your DataFrame:</p> <pre><code>import pandas as pd df=pd.DataFrame( [ [ (1,2), (3,4)], [ (5,6), (7,8)] ], columns=['column0', 'column1']) # empty DataFrame df2 = pd.DataFrame() for col in df.columns: # names o...
1
2016-07-05T11:24:57Z
[ "python", "pandas", "split", "multiple-columns" ]
Error using the substraction operator for two datetime64 empty series
38,200,663
<p>I have a dataframe with two datetime64 columns:</p> <pre><code>In [119]: df.dtypes Out[119]: beg datetime64[ns] end datetime64[ns] dtype: object </code></pre> <p>Sometimes, this dataframe can be empty. In this case, the substraction of <code>end</code> by <code>beg</code> fails using the minus operator but ...
0
2016-07-05T10:08:46Z
38,202,210
<p>It's answered in the documentation and in the sentence you copy-pasted:</p> <blockquote> <p>but with support to substitute a fill_value for missing data in one of the inputs</p> </blockquote> <p>It supports empty dataframes and missing data where the minus operator doesn't.<br> With pandas and numpy, it's good p...
0
2016-07-05T11:23:06Z
[ "python", "pandas" ]
extract text from html mail odoo
38,200,739
<p>I want to get the email body but not in html format . I have used Beautifulsoup and data = re.sub(r'&lt;.*?>', '', html2) to remove the html tags but it didn't work I can't receieve email to applicant </p> <pre><code>def message_new(self, cr, uid, msg, custom_values=None, context=None): """ Overrides mail_thr...
0
2016-07-05T10:12:31Z
38,200,880
<p>I've been using <a href="https://docs.python.org/2/library/htmlparser.html" rel="nofollow" title="HTMLParser">HTMLParser</a> with good success for the exact same thing: stripping out the HTML tags but keep the data.</p> <pre><code>from HTMLParser import HTMLParser class MLStripper(HTMLParser): def __init__(sel...
0
2016-07-05T10:18:25Z
[ "python", "openerp" ]
Azure Flask HTTP Error 500.0 - INTERNAL SERVER ERROR
38,200,782
<p>I have a simple flask web app hosted on Microsoft Azure which allows users to login, upload files, view uploaded files and logout. <br/> Now to handle users more efficiently I decided to use session from flask. <br/> here is my sample code</p> <pre><code>'''import statements''' from flask import render_template, re...
0
2016-07-05T10:14:19Z
40,091,279
<p>Have you set app.secret_key before using session variable? I had same issue, it worked locally, but threw 'Internal Server Error' in azure, because I set it in if _name__ == '_main__' block like this:</p> <pre><code>if __name__ == '__main__': HOST = environ.get('SERVER_HOST', 'localhost') try: PORT = int(...
0
2016-10-17T16:23:48Z
[ "python", "session", "azure", "flask", "flask-login" ]
How to compute all second derivatives (only the diagonal of the Hessian matrix) in Tensorflow?
38,200,982
<p>I have a <strong>loss</strong> value/function and I would like to compute all the second derivatives with respect to a tensor <strong>f</strong> (of size n). I managed to use tf.gradients twice, but when applying it for the second time, it sums the derivatives across the first input (see <em>second_derivatives</em> ...
3
2016-07-05T10:23:35Z
38,205,212
<p><code>tf.gradients([f1,f2,f3],...)</code> computes gradient of <code>f=f1+f2+f3</code> Also, differentiating with respect to <code>x[0]</code> is problematic because <code>x[0]</code> refers to a new <code>Slice</code> node which is not an ancestor of your loss, so derivative with respect to it will be <code>None</c...
2
2016-07-05T13:49:10Z
[ "python", "tensorflow" ]
Write to a textfile with python script that is executed from cron
38,200,984
<p>Every time I run the script from cron, the file to which i write my stdout is empty, the files gets modified but nothing is written. While running the script from terminal works. </p> <p>Example of what i'm trying to do:</p> <blockquote> <p>run.py</p> </blockquote> <pre><code>#!/bin/python2 import os os.chdir('...
0
2016-07-05T10:23:39Z
38,204,920
<p>It is quite possible that your issue is due to the fact that you have opened the file and then written to it....but left it open. You then attempt to open the file a second time but due to caching the data written to it is not yet available. If you change the first module to do the following instead:</p> <pre><code...
1
2016-07-05T13:35:32Z
[ "python", "cron" ]
Python/PyAudio - buffer underruns
38,201,017
<p>The code below keeps causing buffer underruns. synth_instance.play returns a list of interleaved stereo frames in floats (-1,1) of size (frames_num * 2).</p> <p>It seems to me that stream.write doesn't write all the frames i supply it with for some reason.</p> <p>I've tried using pyaudio in callback mode but I do...
1
2016-07-05T10:24:49Z
38,221,048
<p>OP here. I'll post what I think is the answer for people googling about it. If I'm wrong and if someone more knowlegdeable is reading this please correct me because I'm just learning to program audio and lower level programming.</p> <p>The thing is that Python is just too slow for any real-time audio stuff. </p> <...
0
2016-07-06T09:49:46Z
[ "python", "pyaudio", "portaudio" ]
Efficiently check if value is present in any of given ranges
38,201,057
<p>I have two pandas DataFrame objects:</p> <ul> <li><p><code>A</code> contains <code>'start'</code> and <code>'finish'</code> columns</p></li> <li><p><code>B</code> has column <code>'date'</code></p></li> </ul> <p>The goal is to efficiently create a boolean mask indicating if <code>date</code> is in <code>[start, fi...
4
2016-07-05T10:27:09Z
38,202,852
<p>IIUC you want the output to be <code>True</code> if there is at least one interval in which the date is?</p> <p>Is an <code>apply(lambda)</code> efficient enough for you? (It might be a little long for a big dataframe as it iterates over the rows of <code>B</code>). If it is, you can try this:</p> <pre><code>def i...
1
2016-07-05T11:56:30Z
[ "python", "datetime", "pandas", "dataframe" ]
Efficiently check if value is present in any of given ranges
38,201,057
<p>I have two pandas DataFrame objects:</p> <ul> <li><p><code>A</code> contains <code>'start'</code> and <code>'finish'</code> columns</p></li> <li><p><code>B</code> has column <code>'date'</code></p></li> </ul> <p>The goal is to efficiently create a boolean mask indicating if <code>date</code> is in <code>[start, fi...
4
2016-07-05T10:27:09Z
38,203,511
<p>You can do it with a O(n) complexity. The idea is to transform the representation. In A, you store one row per interval. I would suggest a dataframe which stores one row per transition (ie entering an interval, leaving an interval).</p> <pre><code>A = pd.DataFrame( data={ 'start': [1, 50, 30], '...
4
2016-07-05T12:30:16Z
[ "python", "datetime", "pandas", "dataframe" ]
reshape numpy adding extra dimension for lagged values
38,201,151
<p>I'm having trouble reshaping a numpy array for a recurrent neural network. I have an array that looks like this </p> <pre><code> 10 day 15 day 25 day 24 295.775 275.283333 281.16 25 296.000 275.483333 281.56 26 295.825 275.500000 281.75 27 295.425 275.350000 281.91 28 ...
1
2016-07-05T10:31:25Z
38,201,415
<p>I think what you are after is simply this:</p> <pre><code>np.array([arr[i:i+4] for i range(len(arr)-4)]) </code></pre>
1
2016-07-05T10:44:03Z
[ "python", "arrays", "numpy", "multidimensional-array", "reshape" ]
Python - pass value back to main() based on when a button is pressed
38,201,209
<p>Forgive me if this is a badly mangled way of doing things, but I'm new to development in general.</p> <p>I am trying to create a window with a number of buttons using tkinter, each button having the name of a player on it using a class called from main(). </p> <p>I then want to be able to use the name on the butt...
1
2016-07-05T10:34:15Z
38,202,524
<p>You are already accessing it. I personally don't like returning to the main function, instead I suggest creating a top-level class to link back to. This should help make things flow better.</p> <pre><code>import tkinter as tk from tkinter import ttk import random class PlayerWindow(): def __init__(self, master...
2
2016-07-05T11:39:52Z
[ "python", "python-3.x", "tkinter" ]
What 3D editor tool should I use with Panda3D
38,201,287
<p>I was trying to convert an <code>.obj</code> with a <code>.mtl</code> file to <code>.egg</code> file through <code>obj2egg</code>. After conversion, when I checked the <code>.egg</code> file with <code>pview</code>, it was in all white. I am using Microsoft 3D Builder since it is pre-installed on my PC. I would be g...
0
2016-07-05T10:38:39Z
38,204,566
<p>Well Blender 3d have an extension to export .egg file. The file format it is used to by Panda 3d game engine. Here is one link from Panda 3d Manual <a href="http://www.panda3d.org/manual/index.php/Converting_from_Blender" rel="nofollow">http://www.panda3d.org/manual/index.php/Converting_from_Blender</a> You may find...
1
2016-07-05T13:20:54Z
[ "python", "panda3d" ]
Python: How do I convert a string inside a list to a json inside a list whilst retaining the double quotes
38,201,319
<p>This is for python 3.x, I'm struggling to convert the following </p> <pre><code>['{"from": "USD", "to": "EUR"}'] </code></pre> <p>to</p> <pre><code>[{"from": "USD", "to": "EUR"}] </code></pre> <p>I have tried using ast.literal_eval(s) but that returns my json in single quotes, I've been trying different combinat...
0
2016-07-05T10:39:45Z
38,201,518
<pre><code>&gt;&gt;&gt; c=['{"from": "USD", "to": "EUR"}'] &gt;&gt;&gt; c[0] '{"from": "USD", "to": "EUR"}' &gt;&gt;&gt; eval( c[0]) {'to': 'EUR', 'from': 'USD'} &gt;&gt;&gt; p=eval(c[0]) &gt;&gt;&gt; print p {'to': 'EUR', 'from': 'USD'} &gt;&gt;&gt; type(p) &lt;type 'dict'&gt; </code></pre>
0
2016-07-05T10:49:08Z
[ "python", "python-3.x", "parsing" ]
Python: How do I convert a string inside a list to a json inside a list whilst retaining the double quotes
38,201,319
<p>This is for python 3.x, I'm struggling to convert the following </p> <pre><code>['{"from": "USD", "to": "EUR"}'] </code></pre> <p>to</p> <pre><code>[{"from": "USD", "to": "EUR"}] </code></pre> <p>I have tried using ast.literal_eval(s) but that returns my json in single quotes, I've been trying different combinat...
0
2016-07-05T10:39:45Z
38,201,534
<p>Use <code>json.loads</code> and <code>json.dumps</code>. It will take care of it for you:</p> <pre><code>import json a = ['{"from": "USD", "to": "EUR"}'] obj = json.loads(a[0]) print(obj, type(obj)) &gt;&gt; {'to': 'EUR', 'from': 'USD'} &lt;class 'dict'&gt; print(json.dumps(obj), type(json.dumps(obj))) &gt;&gt; {...
3
2016-07-05T10:50:12Z
[ "python", "python-3.x", "parsing" ]
Fit data in Python (sine wave?)
38,201,406
<p>I have data which I would like to visualise. Here is my code:</p> <pre><code>import numpy as np from scipy.optimize import curve_fit xdata = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) ydata = np.array([26.2, 27.2, 27.9, 27.9, 27.2, 26.2, 25.3, 24.5, 24.2, 24.4, 24.7, 25.4]) def func(x, p1,p2,p3): r...
-4
2016-07-05T10:43:43Z
38,202,391
<p>Finally, <code>np.polyfit()</code> gave the desired result:</p> <pre><code>z = np.polyfit(xdata, ydata, 6) f = np.poly1d(z) x_new = np.linspace(xdata[0], xdata[-1], 150) y_new = f(x_new) plt.plot(xdata,ydata,'o', x_new, y_new) </code></pre> <p>I guess, the biggest part of my problem was the wrong assumption that...
0
2016-07-05T11:32:54Z
[ "python", "numpy", "matplotlib", "data-fitting" ]
index function not assigned to duck
38,201,533
<p>I'm stuck here</p> <p>INSTRUCTIONS </p> <p>Use the <code>.index(item</code>) function to find the index of "duck". Assign that result to a variable called duck_index.</p> <p>Then <code>.insert(index, item)</code> the string "cobra" at that index.</p> <p>CODE </p> <pre><code>animals = ["aardvark", "badger", "duc...
-6
2016-07-05T10:50:07Z
38,203,484
<p>The answer is the question...</p> <pre><code>animals = ["aardvark", "badger", "duck", "emu", "fennec fox"] duck_index = animals.index("duck") # retrieve the index of "duck" and assign it to variable duck_index animals.insert(duck_index, "cobra") # insert "cobra" at duck_index print(animals) </code></pre>
0
2016-07-05T12:28:56Z
[ "python" ]
Pandas DatetimeIndex from MongoDB ISODate
38,201,666
<p>I am having some difficulty working with times/timezones. I have raw JSON data of the form</p> <pre><code>{ "Date": "28 Sep 2009 00:00:00", .... } </code></pre> <p>This data is then loaded into MongoDB, and this string representation of the date is transformed into a <a href="https://developer.mozilla.org/en/d...
6
2016-07-05T10:57:04Z
38,265,022
<p>I have managed to get around this for now by changing my <code>groupby</code> to the following</p> <pre><code>frame.groupby([pd.DatetimeIndex([x.date() for x in frame.index])]).sum() </code></pre> <p>so where I was originally trying to <code>groupby</code></p> <pre><code>idx = pd.DatetimeIndex([x['Date'] for x i...
0
2016-07-08T11:00:01Z
[ "python", "mongodb", "datetime", "pandas", "time" ]
Pandas DatetimeIndex from MongoDB ISODate
38,201,666
<p>I am having some difficulty working with times/timezones. I have raw JSON data of the form</p> <pre><code>{ "Date": "28 Sep 2009 00:00:00", .... } </code></pre> <p>This data is then loaded into MongoDB, and this string representation of the date is transformed into a <a href="https://developer.mozilla.org/en/d...
6
2016-07-05T10:57:04Z
38,296,215
<p>I was able to reproduce the error with the following data:</p> <pre><code>idx0 = pd.date_range('2011-11-11', periods=4) idx1 = idx0.tz_localize(tz.tzutc()) idx2 = idx1.tz_convert(tz.tzlocal()) df = pd.DataFrame([1, 2, 3, 4]) df.groupby(idx2).sum() Out[20]: 0 1970-01-01 00:00:00-05:00 9...
2
2016-07-10T20:31:22Z
[ "python", "mongodb", "datetime", "pandas", "time" ]
Google storage Service account authentication requires PyOpenSSL after some time
38,201,707
<p>I use google storage via the python <a href="https://github.com/GoogleCloudPlatform/gcs-oauth2-boto-plugin/issues/26" rel="nofollow">boto plugin</a></p> <p>My python scripts <strong>works as expected for about an hour or so</strong>. Then it gives me the error:</p> <pre><code>Service account authentication require...
1
2016-07-05T10:58:47Z
38,220,723
<p>this problem was caused by a too old python version</p> <p>I don't have these problems with python 2.7.9+</p>
1
2016-07-06T09:34:19Z
[ "python", "google-cloud-storage", "pyopenssl" ]
Extracting individual JSON objects
38,201,922
<p>I have the below JSON file which I'm getting from a API.</p> <pre><code>{"Key-1":"Value-1", "Key-2":[{"Value-2"::Child_Value-1","Value-3":"Child_Value-2"}] } {"Key-21":"Value-21", "Key-22":[{"Value-22":"Child_Value-21","Value-23":"Child_Value-22"}] } {"Key-31":"Value-31", "Key-32":[{"Value-32":"Child_Value-31","Val...
0
2016-07-05T11:08:37Z
38,202,440
<p>This does exactly what your question asks for (although I suspect it is not actually what you want)</p> <pre><code>filecount = 0 newfilecontents = '' with open('junksrc.txt', mode='r', encoding='utf-8') as src: srclines = src.readlines() for line in srclines: if '{"Key' in line: newfile...
0
2016-07-05T11:35:23Z
[ "python", "json", "bash", "shell", "unix" ]
Extracting individual JSON objects
38,201,922
<p>I have the below JSON file which I'm getting from a API.</p> <pre><code>{"Key-1":"Value-1", "Key-2":[{"Value-2"::Child_Value-1","Value-3":"Child_Value-2"}] } {"Key-21":"Value-21", "Key-22":[{"Value-22":"Child_Value-21","Value-23":"Child_Value-22"}] } {"Key-31":"Value-31", "Key-32":[{"Value-32":"Child_Value-31","Val...
0
2016-07-05T11:08:37Z
38,202,546
<p>Here's something that will be very slow and not equipped to deal with errors in the data, but it might work. It's a generator that finds the first '{', and then the next '}', and tries to parse the bit in between as JSON. If that fails, it looks for the next '}' and tries again. It yields the successfully parsed bit...
1
2016-07-05T11:41:10Z
[ "python", "json", "bash", "shell", "unix" ]
Extracting individual JSON objects
38,201,922
<p>I have the below JSON file which I'm getting from a API.</p> <pre><code>{"Key-1":"Value-1", "Key-2":[{"Value-2"::Child_Value-1","Value-3":"Child_Value-2"}] } {"Key-21":"Value-21", "Key-22":[{"Value-22":"Child_Value-21","Value-23":"Child_Value-22"}] } {"Key-31":"Value-31", "Key-32":[{"Value-32":"Child_Value-31","Val...
0
2016-07-05T11:08:37Z
38,205,146
<p>If you get <a href="https://stedolan.github.io/jq/" rel="nofollow"><code>jq</code></a>, you can preprocess your data into a form which is easily parsed by the standard library's JSON parser:</p> <pre><code>$ jq -s '.' tmp.json [ { "Key-1": "Value-1", "Key-2": [ { "Value-2": "Child_Value-1", ...
0
2016-07-05T13:46:10Z
[ "python", "json", "bash", "shell", "unix" ]
microsoft.scripting.hosting.scriptscope does not contain a definition for 'SomeFunction'
38,201,928
<p>I'm working for Ironpython. I want to execute python code which is need an area for storing the csv (from running python) and my code is as follows:</p> <pre><code>using System; using IronPython.Hosting; using Microsoft.Scripting.Hosting; using Microsoft.Build.BuildEngine; using System.Collections.Generic; using Sy...
2
2016-07-05T11:08:48Z
38,218,569
<p>I've already solved this ,thanks a lot tehjoker. The problem is at my python code so bad. when i take this out <code>if __name__ == '__main__':</code> C# can call Ironpython without any error but when I changed this at my original (delete the if code) python can't run. I would be perfect if anyone can describe this...
1
2016-07-06T07:37:23Z
[ "c#", "python", "visual-studio-2013", "visual-studio-2015", "ironpython" ]
How do I add transparency to shape in python pptx?
38,202,582
<pre><code>def new_presentation(): prs=Presentation() img="C:/Users/Dennis/Desktop/Tom-Hiddleston-4-1024x768.jpg" mainsld=new_slide(prs, 6) mainshp=mainsld.shapes mainshp.add_picture(img, 0,0, Inches(10)) titleshape=mainshp.add_shape(MSO_SHAPE.RECTANGLE, Inches(0), Inches(1), Inches(10), Inches(...
0
2016-07-05T11:43:23Z
38,209,424
<p><code>FillFormat.transparency</code> is not implemented yet. The part of the documentation where you saw that may have been an analysis page, which is a precursor to development.</p> <p>This is the analysis page: <a href="http://python-pptx.readthedocs.io/en/latest/dev/analysis/features/dml-fill.html?highlight=tran...
0
2016-07-05T17:36:40Z
[ "python", "python-2.7", "transparency", "presentation", "python-pptx" ]
Result from Support Vector Machine confusing
38,202,617
<p>Hi here is the code image for prediction value ,but i cannot understand about the result... using SVM technique...</p> <p><a href="http://i.stack.imgur.com/ktFa9.png" rel="nofollow"><img src="http://i.stack.imgur.com/ktFa9.png" alt="enter image description here"></a></p> <p>and here is the result for my code </p> ...
-1
2016-07-05T11:44:52Z
38,212,021
<p>The result is pretty trivial. You are looking at accuracy on your <strong>training set</strong>, and you are using SVM with rbf kernel, which can overfit to any dataset, and it does so perfectly - it simply remembers all your training points, thus produces perfect predictions on training points. This is not the way ...
0
2016-07-05T20:18:55Z
[ "python", "numpy", "svm", "miniconda" ]
How to "unconcatenate" a dataframe in Pandas?
38,202,888
<p>I have the following pandas DataFrame.</p> <pre><code>import pandas as pd df = pd.read_csv('filename.csv') print(df) time Group blocks 0 1 A 4 1 2 A 7 2 3 A 12 3 4 A 17 4 5 A 21 5 6 ...
1
2016-07-05T11:58:12Z
38,202,952
<p>is that what you want?</p> <pre><code>In [84]: df.pivot_table(index='time', columns='Group') Out[84]: blocks Group A B time 1 4.0 1.0 2 7.0 1.5 3 12.0 3.0 4 17.0 5.0 5 21.0 6.0 6 26.0 NaN 7 33.0 NaN 8 39.0 NaN 9 48.0 NaN 10 59.0 Na...
2
2016-07-05T12:01:30Z
[ "python", "pandas", "dataframe", "concatenation" ]
Get exact value from elasticsearch results in python
38,202,889
<p>I am new to the elastic search and python and need some help. I want elastic search to return the exact results like a SQL query does. In python-elasticsearch, I am getting the results as:</p> <pre><code>{u'_id': u'33', u'_index': u'data', u'_score': 1.0, u'_source': {u'business_id': u'P1fJb2WQ1mXoiudj8UE44w'}, ...
1
2016-07-05T11:58:18Z
38,202,968
<p>You get a <a href="http://www.tutorialspoint.com/python/python_dictionary.htm" rel="nofollow">python dictionary</a> returned. You can access the information as follows:</p> <pre><code>entry = {u'_id': u'33', u'_index': u'data', u'_score': 1.0, u'_source': {u'business_id': u'P1fJb2WQ1mXoiudj8UE44w'}, u'_type': u...
1
2016-07-05T12:02:14Z
[ "python", "elasticsearch", "response" ]
Vim Syntax Highlighting: highlight `self` python keyword with regex
38,203,042
<p>I am trying to customize the syntax highlighting for python in vim. I want to highlight the keyword <code>self</code> but only when it is followed by a <code>.</code>. Here is the code I came up with:</p> <pre><code>syn match pythonBoolean "\(\Wself\)\%(\.\)" </code></pre> <p>Unfortunately, the <code>.</code...
1
2016-07-05T12:06:18Z
38,203,580
<p>How about using <a href="http://www.regular-expressions.info/lookaround.html" rel="nofollow">lookbehinds and lookaheads</a>? A valid regex for an occurence of self preceded by any non-word character <code>[^a-zA-Z0-9_]</code> and followed by <code>.</code> in common regex syntax is: <code>(?&lt;=\W)(self)(?=\.)</cod...
1
2016-07-05T12:33:25Z
[ "python", "vim", "vi", "macvim" ]
Vim Syntax Highlighting: highlight `self` python keyword with regex
38,203,042
<p>I am trying to customize the syntax highlighting for python in vim. I want to highlight the keyword <code>self</code> but only when it is followed by a <code>.</code>. Here is the code I came up with:</p> <pre><code>syn match pythonBoolean "\(\Wself\)\%(\.\)" </code></pre> <p>Unfortunately, the <code>.</code...
1
2016-07-05T12:06:18Z
38,203,779
<p>You need to use the <strong>lookaround</strong>:</p> <pre><code>:syn match pythonBoolean "\(\W\|^\)\zsself\ze\." </code></pre> <p>or</p> <pre><code>:syn match pythonBoolean "\(\W\|^\)\@&lt;=self\(\.\)\@=" </code></pre>
3
2016-07-05T12:42:25Z
[ "python", "vim", "vi", "macvim" ]
Vim Syntax Highlighting: highlight `self` python keyword with regex
38,203,042
<p>I am trying to customize the syntax highlighting for python in vim. I want to highlight the keyword <code>self</code> but only when it is followed by a <code>.</code>. Here is the code I came up with:</p> <pre><code>syn match pythonBoolean "\(\Wself\)\%(\.\)" </code></pre> <p>Unfortunately, the <code>.</code...
1
2016-07-05T12:06:18Z
38,219,404
<p>As an alternative to lookbehind and lookahead, which tend to slow down vim:</p> <pre><code>syn match pythonBoolean "\&lt;self\ze\." </code></pre> <p>Or, in case you want to highlight all objects:</p> <pre><code>syn match pythonBoolean "\&lt;\w\+\ze\." </code></pre>
0
2016-07-06T08:25:20Z
[ "python", "vim", "vi", "macvim" ]
How can I return value from a function to a variable declared before it (without global variables)?
38,203,205
<p>The following does have the variable declared before the function however when printing the variable within the function the value desired is outputted however when printed after the function the value of the variable remains the same as it did when declared.</p> <pre><code>foo = 0 def method(bar, baz): foo = ba...
-2
2016-07-05T12:15:35Z
38,203,636
<p>I'm not entirely sure this is what you want, since strictly speaking you cannot have a global variable without having a global variable. What you can do is having a <em>mutable</em> global variable which you can modify without an explicit <code>global</code>.</p> <pre><code>foo = [] # list is mutable, just like di...
0
2016-07-05T12:35:38Z
[ "python", "function", "variables", "global-variables" ]
Adding widgets over canvas in tkinter
38,203,230
<p>I want to put a small image and other widgets over a canvas on which an image is displayed. I've tried options such as<code>compound</code> and other things. </p> <p>Background picture is fine and the small image that I want to put over the background image shows fine but it's always top or bottom of the window. I ...
0
2016-07-05T12:16:35Z
38,203,978
<p>Have you considered using the <code>paste</code> method, which lets you define the position of the pasted image through a box argument?</p> <p>See <a href="http://effbot.org/imagingbook/imagetk.htm" rel="nofollow">http://effbot.org/imagingbook/imagetk.htm</a>.</p> <p>Please also take a look at this thread: <a href...
0
2016-07-05T12:52:05Z
[ "python", "tkinter" ]
Adding widgets over canvas in tkinter
38,203,230
<p>I want to put a small image and other widgets over a canvas on which an image is displayed. I've tried options such as<code>compound</code> and other things. </p> <p>Background picture is fine and the small image that I want to put over the background image shows fine but it's always top or bottom of the window. I ...
0
2016-07-05T12:16:35Z
38,206,433
<p>You are looking to draw the widgets over the canvas, this means you must specify the canvas as the parent widget, not the <code>root</code> as you did. For that, modify <code>lo = Label(root, image=login)</code> to <code>lo = Label(canvas, image=login)</code></p> <p>Also, do not forget to specify the rows and colum...
0
2016-07-05T14:46:24Z
[ "python", "tkinter" ]
Adding widgets over canvas in tkinter
38,203,230
<p>I want to put a small image and other widgets over a canvas on which an image is displayed. I've tried options such as<code>compound</code> and other things. </p> <p>Background picture is fine and the small image that I want to put over the background image shows fine but it's always top or bottom of the window. I ...
0
2016-07-05T12:16:35Z
38,223,841
<p>This question isn't about images at all, it's just a basic layout problem. You'll have the same issues with or without images. The problem is simply that you aren't giving any options to grid, so it naturally puts things at the top. Tkinter also has the behavior that a containing widget (eg: your canvas) will shrink...
0
2016-07-06T12:19:07Z
[ "python", "tkinter" ]
Adding widgets over canvas in tkinter
38,203,230
<p>I want to put a small image and other widgets over a canvas on which an image is displayed. I've tried options such as<code>compound</code> and other things. </p> <p>Background picture is fine and the small image that I want to put over the background image shows fine but it's always top or bottom of the window. I ...
0
2016-07-05T12:16:35Z
38,336,240
<p>In order to add any widgets over or the foreground of any background image or canvas, the row and column values of all the widgets must be same as of the background image. so, my above mentioned program would be like this :</p> <pre><code>from Tkinter import * root = Tk() root.iconbitmap('E:/a.ico') root.title('...
0
2016-07-12T18:17:35Z
[ "python", "tkinter" ]
multiprocessing of video frames in python
38,203,239
<p>I am new to multiprocessing in python. I want to extract features from each frame of hour long video files. Processing each frame takes on the order of 30 ms. I thought multiprocessing was a good idea because each frame is processed independentle of all other frames.</p> <p>I want to store the results of the featur...
4
2016-07-05T12:16:59Z
38,203,626
<p>Multiprocessing creates some overhead for starting several processes and bringing them all back together.</p> <p>Your code does that for <em>every</em> frame.</p> <p>Try splitting your video into N evenly-sized pieces and processing <em>them</em> in parallel.</p> <p>Put N equal to number of cores on your machine ...
1
2016-07-05T12:35:01Z
[ "python", "multiprocessing" ]