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
Manage files from public Google Drive URL using PyDrive
37,913,458
<p>I`m using PyDrive QuickStart script to list my Google Drive files.</p> <p>Code:</p> <pre><code>from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive gauth = GoogleAuth() gauth.LocalWebserverAuth() drive = GoogleDrive(gauth) file_list = drive.ListFile({'q': "'root' in parents and trashed=fals...
1
2016-06-20T01:12:38Z
37,936,411
<ol> <li><p>You need to get the folder ID. You can find the ID in the URL of the folder. An example would be: <code>https://drive.google.com/open?id=0B-schRXnDFZeX0t0RnhQVXXXXXX</code> (the part of the URL after the <code>id=</code>).</p></li> <li><p>List contents of a folder based on ID. Given your code you replace <...
1
2016-06-21T05:42:30Z
[ "python", "google-api-python-client", "pydrive" ]
Use regex in Python to rule out string
37,913,573
<p>I'm using pandas to clean the data as below:</p> <pre><code>s3 = pd.DataFrame({'title':["intermediate" ,"Basmati/sadri" ,"temperate japonica" ,"Temperate japonica" , "Japonica" ,"Tropical japonica" ,"Aromatic (basmati/sandri type" , "indica" , "Aus/boro" , "Aus" ,"aus" ,"japonica" , "tropical japnica", "" , "Indica...
2
2016-06-20T01:35:22Z
37,913,776
<p>The following should work. It uses three cases, separated by or (<code>|</code>) operators.</p> <ul> <li>a negative lookahead to ensure the title does not start with either <code>japonica</code> or <code>indica</code>, with some other characters required.</li> <li>an or statement to ensure that if the title does st...
1
2016-06-20T02:12:18Z
[ "python", "regex", "pandas" ]
Microsoft word/office dictionary thesaurus via python script
37,913,600
<p>I was wondering if it is possible to use the dictionary installed with Microsoft office via a python script. I really would like to use the thesaurus to find synonyms for certain words. I know I could use the nltk package, but I will not be able to install it on every system due to a very crabby systems admin. May...
0
2016-06-20T01:39:20Z
37,920,600
<p>Since the computers in question already have python, you can install the NLTK for your own use without admin privileges. The NLTK itself is pretty small, but you can further trim it down to produce a customized installation that only contains the modules you need for this task.</p> <p>You don't say what resource yo...
1
2016-06-20T10:49:40Z
[ "python", "nltk" ]
Mystery newline being added to the end of QPlainTextEdit
37,913,651
<p>I'm making a kind of command line simulator using Python 2.7 and PyQt5, and the way it works is every character you type it listens for the key. When you press it it calls <code>self.parse()</code> which does stuff.</p> <p>When I load up the window it works fine, and the cursor is placed after the prompt (<code>C:...
1
2016-06-20T01:48:18Z
37,928,902
<p>You need to bypass the normal handling of return/enter, and then use <code>insertPlainText</code> to control how newlines are entered:</p> <pre><code>class CmdLine(QtWidgets.QMainWindow): def __init__(self): super(CmdLine, self).__init__() ... self.plainTextEdit.insertPlainText("C:\\&gt;...
1
2016-06-20T17:57:33Z
[ "python", "python-2.7", "pyqt", "newline", "pyqt5" ]
How to retrieve input data from django-generated forms
37,913,784
<p>So I have this code in one of my templates in a django app:</p> <pre><code>{% for key, value in Monday.items %} {% for k, v in value.items %} {% if k == 'song'%} &lt;form&gt; {{ key }} : &lt;input type="text" value="{{ v }}"/&gt; &lt;input ty...
0
2016-06-20T02:13:43Z
37,914,470
<p>something like this?</p> <pre><code>&lt;input type="text" value="{{ v }}"/&gt; &lt;input type="submit" value="change" class="change_btn"/&gt;&lt;br&gt; </code></pre> <p>js</p> <pre><code>$('.change_btn').on('click', function(){ var changed_txt = $(this).prev().val(); // send this changed text to backend ...
0
2016-06-20T04:01:19Z
[ "python", "json", "django" ]
bluetooth error no advertisable device
37,913,796
<pre><code>#! /usr/bin/python import bluetooth import uuid server_socket = bluetooth.BluetoothSocket( bluetooth.RFCOMM ) port = 1 server_socket.bind(("",port)) server_socket.listen(1) uuID = ##generated uuid bluetooth.advertise_service( server_socket, "test", service_id=uuID ) client_socket, client_address = serv...
0
2016-06-20T02:15:06Z
38,042,873
<p>Looks like to advertise it just needed: "sudo hciconfig hci0 piscan"</p> <p>And to connect it needed bluetooth.PORT_ANY from that import, so I'm marking this as answered.</p> <p>To anyone that finds this because of their own problems with this. You have an answer now. Good luck.</p>
0
2016-06-26T20:27:17Z
[ "android", "python", "sockets", "bluetooth", "raspberry-pi3" ]
Simple jes Function to switch a pictures color from red to green or blue?
37,913,822
<p>The title says it all, im just looking for a simple way to change all of a photos red pixels to green or blue.</p>
0
2016-06-20T02:19:03Z
38,238,284
<p>Assuming you mean swapping the red and blue value for each pixel, then this is how you can do it. If not, there should be enough here to get you pretty close.</p> <p>def swapRedwithBlue(sourceImage):</p> <pre><code>width = getWidth(sourceImage) height = getHeight(sourceImage) for x in range(width): for y in ran...
0
2016-07-07T05:47:42Z
[ "python", "jython", "jes" ]
Install XGBoost on EC2 Instance
37,913,906
<p>I would be very grateful if someone could tell me how to install XGBoost on EC2. I have set up the EC2 instance and installed Numpy/SKlearn like this:</p> <pre><code>sudo yum -y install gcc-c++ python27-devel atlas-sse3-devel lapack-devel wget https://pypi.python.org/packages/source/v/virtualenv/virtualenv-1.11.2.t...
0
2016-06-20T02:33:27Z
37,913,917
<p>I just realized, I needed to upgrade pip first: </p> <pre><code>pip install --upgrade pip </code></pre> <p>I will leave the question for others though. Thanks! </p>
0
2016-06-20T02:35:04Z
[ "python", "amazon-web-services", "numpy", "amazon-ec2", "xgboost" ]
How to download file from web using request module?
37,913,921
<p>I am using python to download files from webpage, and after I submit the request, I get the headers like below:</p> <pre><code>&gt;&gt;&gt; r.headers {'Content-Disposition': 'attachment; filename="report20160619-013623.csv";', 'Content-Transfer-Encoding': 'binary', 'Expires': '0', 'Keep-Alive': 'timeout=5, max=100...
1
2016-06-20T02:35:18Z
37,914,079
<p>You will read the response and then write it out as a file to a location you specify. </p> <pre><code>csv = r.text outfile = open('/path/to/my.csv', 'w') outfile.write(csv) outfile.close() </code></pre>
3
2016-06-20T03:02:10Z
[ "python", "download", "python-requests" ]
Numpy - check if elements of a array belong to another array
37,913,957
<p>I have 2 numpy arrays:</p> <pre><code>xarr = np.array([1.1, 1.2, 1.3, 1.4, 1.5]) y = np.array([1.1,1.2]) </code></pre> <p>I want to check whether each element of <code>xarr</code> belongs to <code>y</code> or equals <code>1.3</code>. If an element belongs to <code>y</code>, return "y", if an element equals 1.3, re...
2
2016-06-20T02:40:27Z
37,914,026
<p>You can make use of <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.in1d.html" rel="nofollow">numpy.in1d</a>, the rest is pretty simple:</p> <p>The key part:</p> <pre><code>In [25]: np.in1d(xarr, y) Out[25]: array([ True, True, False, False, False], dtype=bool) </code></pre> <p>Whole ex...
3
2016-06-20T02:54:31Z
[ "python", "numpy" ]
Jinja template parses variable as literal string
37,914,007
<p>I'm having a problem where Jinja is treating a variable I'm passing to it as a literal string, which screws up the URL routing work done by Flask.</p> <p><code>app.py</code> - each "course" has its designated URL, as shown by <code>/course/&lt;name&gt;</code>.</p> <pre><code>@app.route("/course/&lt;name&gt;") @log...
1
2016-06-20T02:49:56Z
37,914,171
<p><code>{{</code> begins a block of Python code. Things you do inside it follow Python behavior rules, not those of Jinja. You are passing the value <code>{{ course }}</code> as <code>name</code> to <code>url_for</code>. Just use <code>course</code> as a variable. </p> <pre><code>{{ url_for('course', name=course.name...
1
2016-06-20T03:18:14Z
[ "python", "flask", "jinja2" ]
why do I get different hash value everytime I call hexdigest() in hashlib?
37,914,013
<p>I want to have a unique hash for the same string in python. I use following code for getting a hash :</p> <pre><code>import hashlib mysha1 = hashlib.sha1() mysha1.update("my_url") print mysha1.hexdigest() mysha1.update("my_url") print mysha1.hexdigest() # which is generating a different hash </code></pre> <p>is th...
2
2016-06-20T02:52:02Z
37,914,043
<p>the <code>update()</code> function feeds strings to be concatenated.</p> <p><a href="https://docs.python.org/2/library/hashlib.html">https://docs.python.org/2/library/hashlib.html</a></p> <pre><code>&gt;&gt;&gt; import hashlib &gt;&gt;&gt; mysha1 = hashlib.sha1() &gt;&gt;&gt; mysha1.update("my_url") &gt;&gt;&gt; p...
5
2016-06-20T02:56:10Z
[ "python", "hash" ]
why do I get different hash value everytime I call hexdigest() in hashlib?
37,914,013
<p>I want to have a unique hash for the same string in python. I use following code for getting a hash :</p> <pre><code>import hashlib mysha1 = hashlib.sha1() mysha1.update("my_url") print mysha1.hexdigest() mysha1.update("my_url") print mysha1.hexdigest() # which is generating a different hash </code></pre> <p>is th...
2
2016-06-20T02:52:02Z
37,914,045
<p>When you call <code>update("my_url")</code>, you're <a href="https://docs.python.org/2/library/hashlib.html" rel="nofollow">concatenating</a> that string to the hash input.</p> <blockquote> <p>You can now feed this object with arbitrary strings using the update() method. At any point you can ask it for the digest...
3
2016-06-20T02:56:37Z
[ "python", "hash" ]
why do I get different hash value everytime I call hexdigest() in hashlib?
37,914,013
<p>I want to have a unique hash for the same string in python. I use following code for getting a hash :</p> <pre><code>import hashlib mysha1 = hashlib.sha1() mysha1.update("my_url") print mysha1.hexdigest() mysha1.update("my_url") print mysha1.hexdigest() # which is generating a different hash </code></pre> <p>is th...
2
2016-06-20T02:52:02Z
37,914,124
<p>Just do not call <code>update</code> more than once, for example:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import hashlib &gt;&gt;&gt; mysha1 = hashlib.sha1() &gt;&gt;&gt; mysha1.update("my_url") &gt;&gt;&gt; mysha1.hexdigest() 'ebde90b9f0c047ff9f86bec3b71afe5d00594030' &gt;&gt;&gt; mysha1.h...
1
2016-06-20T03:10:49Z
[ "python", "hash" ]
Parsing XML lxml should I skip or remove comment blocking parsing
37,914,042
<p>I have an XML file which first line begins with </p> <pre><code>&lt;!-- </code></pre> <p>Is there a way for lxml to skip this line and treat line 2 as the 1st line or should I remove it before handing to lxml?</p> <p>for example I tried implementing the example from the lxml documentation</p> <pre><code>&gt;&gt;...
2
2016-06-20T02:56:08Z
37,915,462
<p>Kill the copyright notice. You have an extended ascii character (the copyright symbol) in an xml document without encoding specified, without an xml declaration tag, in a python 3 unicode environment. I can't imagine good things happening. Remove the copyright symbol and see of your problems go away.</p>
0
2016-06-20T05:59:20Z
[ "python", "xml", "lxml" ]
Parsing XML lxml should I skip or remove comment blocking parsing
37,914,042
<p>I have an XML file which first line begins with </p> <pre><code>&lt;!-- </code></pre> <p>Is there a way for lxml to skip this line and treat line 2 as the 1st line or should I remove it before handing to lxml?</p> <p>for example I tried implementing the example from the lxml documentation</p> <pre><code>&gt;&gt;...
2
2016-06-20T02:56:08Z
37,942,281
<p>The comment should really cause no issues with <em>etree</em> and does not on my machine using python2 or python3, if you do want to remove comments though you can pass <code>parser=et.HTMLParser(remove_comments=True)</code> or <code>parser=et.XMLParser(remove_comments=True))</code> depending on what you want:</p> ...
2
2016-06-21T10:44:42Z
[ "python", "xml", "lxml" ]
Cannot access google spreadsheet
37,914,136
<p>I am trying to learn Google's gdata Python API, and trying to get initial access to a test spreadsheet in my drive. heres the code I am using as a test:</p> <pre><code>from oauth2client.service_account import ServiceAccountCredentials import gdata.spreadsheets.client # 認証に必要な情報 client_email = "5950...
0
2016-06-20T03:12:29Z
37,919,852
<p>Google has rolled out v4 api for spreadsheets with a basket full of options. since i found it hard to use the google client library, I wrote an python library (<a href="https://github.com/nithinmurali/pygsheets" rel="nofollow">pygsheets</a>) for google spread sheets on top of google python client. The library is in ...
1
2016-06-20T10:13:15Z
[ "python", "google-apps-script", "google-api", "google-spreadsheet", "google-spreadsheet-api" ]
How to return index of specific pairs of values?
37,914,204
<p>I need to find the index (row number) of specific pairs of value from an array. Below is example array.</p> <pre><code>A=[[357 131] [319 171] [229 196] [398 135] [242 148] ] </code></pre> <p>I want to know the index of [229 196] and [242 148] as their row number </p> <pre><code> 3 and 5 </code></p...
1
2016-06-20T03:23:46Z
37,914,262
<p>Your syntax is wrong. You may want to change from</p> <pre><code>A.index ([229 196]) </code></pre> <p>to </p> <pre><code>A.index([229, 196]) </code></pre>
0
2016-06-20T03:32:30Z
[ "python", "arrays" ]
How to return index of specific pairs of values?
37,914,204
<p>I need to find the index (row number) of specific pairs of value from an array. Below is example array.</p> <pre><code>A=[[357 131] [319 171] [229 196] [398 135] [242 148] ] </code></pre> <p>I want to know the index of [229 196] and [242 148] as their row number </p> <pre><code> 3 and 5 </code></p...
1
2016-06-20T03:23:46Z
37,914,276
<p>Are you sure your components are lists of <code>ints</code>? <code>[229 196]</code> should raise a syntax error.</p> <p>If you are, indeed, using lists of ints, the following should work:</p> <pre><code>A.index([229, 196]) A.index([242, 148]) </code></pre> <p>Otherwise try:</p> <pre><code>A.index(["229 196"]) <...
0
2016-06-20T03:34:32Z
[ "python", "arrays" ]
How to return index of specific pairs of values?
37,914,204
<p>I need to find the index (row number) of specific pairs of value from an array. Below is example array.</p> <pre><code>A=[[357 131] [319 171] [229 196] [398 135] [242 148] ] </code></pre> <p>I want to know the index of [229 196] and [242 148] as their row number </p> <pre><code> 3 and 5 </code></p...
1
2016-06-20T03:23:46Z
37,914,295
<p>You may want to take a look at the <a href="https://docs.python.org/3/library/array.html" rel="nofollow">documentation regarding arrays</a>. <code>A</code> should be defined this way :</p> <pre><code>&gt;&gt;&gt; A=[[357,131],[319,171],[229,196],[398,135],[242,148]] </code></pre> <p>Your guess was right though, re...
0
2016-06-20T03:36:35Z
[ "python", "arrays" ]
Copying the Matching Columns from CSV File
37,914,320
<p><strong>Input:</strong></p> <p>I have two csv files (file1.csv and file2.csv). </p> <p>file1 looks like:</p> <pre><code>ID,Name,Gender 1,Smith,M 2,John,M </code></pre> <p>file2 looks like:</p> <pre><code>name,gender,city,id </code></pre> <p><strong>Problem:</strong></p> <p>I want to compare the header of file...
0
2016-06-20T03:40:07Z
37,914,551
<p>You don't need Python for this. This is a task for SQL.</p> <p><a href="http://sqlitebrowser.org/" rel="nofollow">SQLite Browser</a> supports CSV Import. Take the below steps to get the desired output:</p> <ul> <li>Download and install SQLite Browser</li> <li>Create a new Database</li> <li>Import both CSV's as t...
1
2016-06-20T04:14:53Z
[ "python", "csv", "for-loop", "dictionary" ]
Copying the Matching Columns from CSV File
37,914,320
<p><strong>Input:</strong></p> <p>I have two csv files (file1.csv and file2.csv). </p> <p>file1 looks like:</p> <pre><code>ID,Name,Gender 1,Smith,M 2,John,M </code></pre> <p>file2 looks like:</p> <pre><code>name,gender,city,id </code></pre> <p><strong>Problem:</strong></p> <p>I want to compare the header of file...
0
2016-06-20T03:40:07Z
37,914,962
<p>I had a crack on this problem using python without taking performance into consideration. Took me quite a while, phew!</p> <p>This is my solution.</p> <pre><code>import csv csv_data1_filepath = './file1.csv' csv_data2_filepath = './file2.csv' def main(): # import nem config and data into memory data1 = ...
1
2016-06-20T05:10:27Z
[ "python", "csv", "for-loop", "dictionary" ]
Python sort using key and lambda, what does lambda do?
37,914,387
<p>So I have a list of values like so:</p> <pre><code>{ "values": [ { "date": "2015-04-15T11:15:34", "val": 30 }, { "val": 90, "date": "2015-04-19T11:15:34" }, { "val": 25, "date": "2015-04-16T11:15...
0
2016-06-20T03:49:58Z
37,914,446
<p>A <code>lambda</code> expression is simply a concise way of writing a function. It's especially handy in cases like the one you give where you only need to use the function once, and it needs to be used as an expression (e.g. an argument to a function).</p> <p>Here's an alternative version of your example, using <c...
3
2016-06-20T03:57:58Z
[ "python", "lambda" ]
Python Pandas - Iterating inside Groupby to find time differences
37,914,411
<p>I have a <strong>Pandas dataframe</strong> which look <a href="http://i.stack.imgur.com/dWWI1.png" rel="nofollow">like this</a></p> <p>The customer number is unique to each customer, but repeats itself if the customer visits again. I want to groupby customer number. Then in each groupby object, I want to find out t...
1
2016-06-20T03:53:43Z
37,914,835
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.diff.html" rel="nofollow"><code>diff</code></a>:</p> <pre><c...
1
2016-06-20T04:54:25Z
[ "python", "datetime", "pandas", "group-by" ]
How do you allow certain views in Django Rest Framework to be accessed with an unauthenticated request?
37,914,425
<p>I'm working on a basic Django Rest Framework API app and i'm trying to implement a Token based authentication system. I want to block off every view thats requested via an unauthenticated request except for the login and signup views. Currently when I try to login or sign up the request is denied and I get "Authenti...
1
2016-06-20T03:55:27Z
37,919,839
<p>You can set the default permission policy globally as described in the <a href="http://www.django-rest-framework.org/api-guide/permissions/#setting-the-permission-policy" rel="nofollow">docs</a> and then override the <code>permission_classes</code> only for the sign up and login like so:</p> <pre><code>... from res...
0
2016-06-20T10:12:35Z
[ "python", "django", "authentication", "django-rest-framework", "django-rest-auth" ]
How to store a list of uneven numpy arrays?
37,914,482
<p>Let's say I have following numpy arrays:</p> <pre><code>import numpy as np a = np.array([1, 2]) b = np.array([1]) c = np.array([1, 4, 8, 10]) </code></pre> <p>How can I do something like <code>np.vstack((a, b, c))</code> without any error? I know there is a pure python way <code>l = [a, b, c]</code> but that's not...
2
2016-06-20T04:03:22Z
37,915,805
<pre><code>In [863]: a = np.array([1, 2]) In [864]: b = np.array([1]) In [865]: c = np.array([1, 4, 8, 10]) </code></pre> <p>A list of these 3 arrays:</p> <pre><code>In [866]: ll=[a,b,c] </code></pre> <p>An object dtype array made from this list:</p> <pre><code>In [867]: A=np.array(ll) In [868]: A Out[868]: array(...
1
2016-06-20T06:26:35Z
[ "python", "arrays", "numpy" ]
How to store a list of uneven numpy arrays?
37,914,482
<p>Let's say I have following numpy arrays:</p> <pre><code>import numpy as np a = np.array([1, 2]) b = np.array([1]) c = np.array([1, 4, 8, 10]) </code></pre> <p>How can I do something like <code>np.vstack((a, b, c))</code> without any error? I know there is a pure python way <code>l = [a, b, c]</code> but that's not...
2
2016-06-20T04:03:22Z
37,917,250
<p>To get numpy speed, you need to imbed the vectors into an array. Either a 2D array or 1D array could work. You could make an array of zeros that is large enough to hold all the values. Then put the vectors in that array. Or, you could make a large 1D array and concatenate the vectors end to end. </p> <pre><code>...
0
2016-06-20T07:57:41Z
[ "python", "arrays", "numpy" ]
Read a csv to dictionary with particular column value as key
37,914,515
<p>I am trying to read a csv into a dictionary in python</p> <pre><code>Name Value time count sample A 00:00 45 sample A 01:00 46 sample A 02:00 50 sample A 03:00 85 sample A 04:00 87 abb B 00:00 40 abb B 01:00 55 </code></pre> <p>I want the ...
0
2016-06-20T04:08:44Z
37,914,580
<p>read in file then split to abstract key and value </p> <pre><code>with open(file,'rb') as f: res = {} reader = csv.reader(f) for i,line in enumerate(reader): if i == 0: continue keyWord = line.split(' ')[1] timeKeyword = 'time:' + line.split(' ')[2] countValue = line.split(' ')[3] res[keyWor...
0
2016-06-20T04:20:58Z
[ "python", "csv", "dictionary" ]
What is the best way in python to assign each of the same element of one list to the same indices on another list?
37,914,565
<p>I thought about having a <em>word</em> as a string, making it into a "regularList" of strings, generating a "dummyList" which contains a string '-'for each letter in the <em>word</em>, then looping through the "regularList", simultaneously removing each instance of my guessed letter from "regularList" and reassignin...
2
2016-06-20T04:17:29Z
37,914,743
<pre><code>word = 'aardvark' def changeLetter(word): guess = raw_input('Guess a letter:') # When called, guess:a print word dummyList = [] for i in word: dummyList.append('_ ') print dummyList regularList = [list(i) for i in word.split('\n')] print regularList numIters = 0 p...
3
2016-06-20T04:43:35Z
[ "python", "list" ]
What is the best way in python to assign each of the same element of one list to the same indices on another list?
37,914,565
<p>I thought about having a <em>word</em> as a string, making it into a "regularList" of strings, generating a "dummyList" which contains a string '-'for each letter in the <em>word</em>, then looping through the "regularList", simultaneously removing each instance of my guessed letter from "regularList" and reassignin...
2
2016-06-20T04:17:29Z
37,914,744
<p>Maybe with enumerate and then remove the elements:</p> <pre><code>for index, element in enumerate(regularList): if element == "a": dummyList[index] = element regularList.remove("a") </code></pre>
0
2016-06-20T04:43:53Z
[ "python", "list" ]
What is the best way in python to assign each of the same element of one list to the same indices on another list?
37,914,565
<p>I thought about having a <em>word</em> as a string, making it into a "regularList" of strings, generating a "dummyList" which contains a string '-'for each letter in the <em>word</em>, then looping through the "regularList", simultaneously removing each instance of my guessed letter from "regularList" and reassignin...
2
2016-06-20T04:17:29Z
37,916,062
<p>The accepted answer is way too long, you can just use a clean list comprehension</p> <pre><code>currentWord = [letter if letter in guessedLetters else "_" for letter in solution] </code></pre> <p>A fully functioning guess the word program without win logic would be 6 lines</p> <pre><code>solution = "aardvark" gue...
0
2016-06-20T06:41:51Z
[ "python", "list" ]
Does adding column to a DataFrame involve copying data?
37,914,575
<p>My question is about performance only, not semantics.</p> <p>Does adding a new column to a df cause the data in the existing DataFrame to be physically copied to a new memory location (to ensure that the DataFrame occupies contiguous memory, for example)?</p> <pre><code># using pandas 0.18.1, python 3.5 import pan...
2
2016-06-20T04:20:28Z
37,915,539
<p>I think from my experiments that <code>loc</code> is slowier and align new <code>Series</code> with different index the slowiest:</p> <blockquote> <p>But I have no idea if the data in the other columns can stay where it was, or need to be moved sometimes.</p> </blockquote> <p>I think data are not moved, new colu...
1
2016-06-20T06:06:21Z
[ "python", "performance", "python-3.x", "pandas", "internal" ]
Python multiple inheritance, calling second base class method, if both base classes holding same method
37,914,582
<pre><code>class A: def amethod(self): print("Base1") class B(): def amethod(self): print("Base3") class Derived(A,B): pass instance = Derived() instance.amethod() #Now i want to call B method amethod().. please let me know the way.** </code></pre> <p>Python multiple inheritance, calling second base c...
2
2016-06-20T04:21:30Z
37,914,649
<p>try to use composition</p> <blockquote> +Avoid multiple inheritance at all costs, as it's too complex to be reliable. If you're stuck with it, then be prepared to know the class hierarchy and spend time finding where everything is coming from.<br> +Use composition to package code into modules that are used in many ...
1
2016-06-20T04:30:25Z
[ "python", "class" ]
Python multiple inheritance, calling second base class method, if both base classes holding same method
37,914,582
<pre><code>class A: def amethod(self): print("Base1") class B(): def amethod(self): print("Base3") class Derived(A,B): pass instance = Derived() instance.amethod() #Now i want to call B method amethod().. please let me know the way.** </code></pre> <p>Python multiple inheritance, calling second base c...
2
2016-06-20T04:21:30Z
37,914,767
<p>galaxyan's answer suggesting composition is probably the best one. Multiple inheritance is often complicated to design and debug, and unless you know what you're doing, it can be difficult to get right. But if you really do want it, here's an answer explaining how you can make it work:</p> <p>For multiple inheritan...
1
2016-06-20T04:46:33Z
[ "python", "class" ]
listing Outlook emails by specific date in Python
37,914,621
<p>I'm using Python 3. I'm trying to extract (list / print show) outlook emails by date.</p> <p>I was trying a loop.. maybe WHILE or IF statement.</p> <p>Can it be done since ones a string and the other is a date. Please concide what I've got so far: Thanks. </p> <pre><code> 1. import win32com.client, datetime 2...
1
2016-06-20T04:26:48Z
37,915,184
<p><strong>Edit:</strong> The outlook API has a method, <a href="https://msdn.microsoft.com/en-us/library/office/ff869662.aspx" rel="nofollow"><code>Items.Find</code></a>, for searching the contents of <code>.Items</code>. If this is the extent of what you want to do, that's probably how you should do it. My original...
0
2016-06-20T05:33:18Z
[ "python", "loops", "email", "date", "outlook" ]
listing Outlook emails by specific date in Python
37,914,621
<p>I'm using Python 3. I'm trying to extract (list / print show) outlook emails by date.</p> <p>I was trying a loop.. maybe WHILE or IF statement.</p> <p>Can it be done since ones a string and the other is a date. Please concide what I've got so far: Thanks. </p> <pre><code> 1. import win32com.client, datetime 2...
1
2016-06-20T04:26:48Z
38,193,427
<p>Ive completed the code. Thanks for help.</p> <pre><code>`import sys, win32com.client, datetime # Connect with MS Outlook - must be open. outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace ("MAPI") # connect to Sent Items s = outlook.GetDefaultFolder(5).Items # "5" refers to the sent item of a ...
0
2016-07-04T23:43:51Z
[ "python", "loops", "email", "date", "outlook" ]
Custom settings and wsgi in django 1.10 give me error
37,914,645
<p>I have this bug with custom settings running the server:</p> <pre><code> salahaddin@TulipanROG  ~/Proyectos/tiempoturco/tiempoturco  (tiempoturco)  ./manage.py runserver ...
1
2016-06-20T04:30:03Z
38,804,837
<p>try changing the MIDDLEWARE_CLASSES</p> <pre><code>MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.a...
6
2016-08-06T13:35:58Z
[ "python", "django", "wsgi" ]
Custom settings and wsgi in django 1.10 give me error
37,914,645
<p>I have this bug with custom settings running the server:</p> <pre><code> salahaddin@TulipanROG  ~/Proyectos/tiempoturco/tiempoturco  (tiempoturco)  ./manage.py runserver ...
1
2016-06-20T04:30:03Z
39,004,873
<p>I had a similar problem with when upgrading my app to django 1.10. First I would try changing MIDDLEWARE_CLASSES to MIDDLEWARE because with Django 1.10 they introduced a new style of middleware outline here: </p> <p><a href="https://docs.djangoproject.com/en/1.10/releases/1.10/" rel="nofollow">https://docs.djangopr...
3
2016-08-17T19:32:47Z
[ "python", "django", "wsgi" ]
Custom settings and wsgi in django 1.10 give me error
37,914,645
<p>I have this bug with custom settings running the server:</p> <pre><code> salahaddin@TulipanROG  ~/Proyectos/tiempoturco/tiempoturco  (tiempoturco)  ./manage.py runserver ...
1
2016-06-20T04:30:03Z
39,902,895
<p>I would add that in addition to what mol mentioned, during process of upgrading Django I had to temporary disable the linked virtual host. Also try freshly upgrading to Django 1.10 (uninstall Django 1.9, then install Django 1.10).</p> <p>You might need to additionally clear all Django sessions as well.</p>
0
2016-10-06T18:09:22Z
[ "python", "django", "wsgi" ]
Python not importing Leap Motion library
37,914,792
<p>I am trying to get the basics of Leap Motion running in python.</p> <pre><code>import os, sys, inspect, thread, time </code></pre> <p>Code can be seen here.. <a href="http://pastie.org/10883595" rel="nofollow">http://pastie.org/10883595</a></p> <p>I get an error ....</p> <pre><code>Traceback (most recent call l...
1
2016-06-20T04:50:22Z
37,950,003
<p>You need three files in the path: Leap.py, LeapPython, and libLeap (exact filenames and extensions vary by platform).</p> <p>Leap.py loads LeapPython, which loads libLeap. If you are missing any of the three files you will get the same "no module" error message.</p>
0
2016-06-21T16:36:07Z
[ "python", "leap-motion" ]
Normalising rows in numpy matrix
37,914,795
<p>I am trying to normalize rows of a numpy matrix using L2 norm (unity length). </p> <p>I am seeing a problem when I do that. </p> <p>Assuming my matrix 'b' is as follows: </p> <p><a href="http://i.stack.imgur.com/VwPUm.png" rel="nofollow"><img src="http://i.stack.imgur.com/VwPUm.png" alt="enter image description h...
1
2016-06-20T04:50:40Z
37,914,890
<p>The problem comes from the fact that <code>b</code> has type <code>int</code> so when you fill in row by row, <code>numpy</code> automatically converts the results of you computation (<code>float</code>) to <code>int</code>, hence the zeros. One way to avoid that is to define <code>b</code> with type <code>float</co...
2
2016-06-20T05:01:47Z
[ "python", "numpy", "matrix" ]
Django template How to Convert numbers to Words
37,914,941
<p>I am searching for a template tag to convert a value like 522 to five hundred twenty two only. Looking in docs i came across </p> <blockquote> <p>django.contrib.humanize</p> </blockquote> <p>which has a build in tag intword but it works only with number with numbers greater than a million.</p> <p>as a alternati...
1
2016-06-20T05:06:44Z
37,914,954
<p>Check out this library: <a href="https://pypi.python.org/pypi/num2words" rel="nofollow">num2words</a></p> <p>Straight from the docs:</p> <pre><code>&gt;&gt;&gt; from num2words import num2words &gt;&gt;&gt; num2words(42) forty-two &gt;&gt;&gt; num2words(42, ordinal=True) forty-second &gt;&gt;&gt; num2words(42, lang...
1
2016-06-20T05:09:33Z
[ "python", "django", "django-templates", "django-template-filters" ]
Django unicode objects from Angular request
37,915,029
<p>When I call a post request from angular and pass a data then receive in django views, the data becomes an object with unicode keys and values.</p> <p>Sample.</p> <pre><code>//from angular $http.post("url_here",{"name" : "alde","grade" : 94}) //views.py data_from_angular = json.loads(request.body.decode("utf-8")) ...
1
2016-06-20T05:16:56Z
37,915,098
<p>The u-prefix just means that you have a Unicode string. When you really use the string, it won't appear in your data. </p> <p>If you really wish to convert it to normal string you can convert both key and value using dictionary comprehension and <code>str</code> keyword.:</p> <pre><code>data_from_angular = dict((s...
1
2016-06-20T05:24:01Z
[ "python", "angularjs", "django", "unicode" ]
Django unicode objects from Angular request
37,915,029
<p>When I call a post request from angular and pass a data then receive in django views, the data becomes an object with unicode keys and values.</p> <p>Sample.</p> <pre><code>//from angular $http.post("url_here",{"name" : "alde","grade" : 94}) //views.py data_from_angular = json.loads(request.body.decode("utf-8")) ...
1
2016-06-20T05:16:56Z
37,915,240
<p>I think this should work</p> <pre><code>data_from_angular = json.loads(request.body.decode("utf-8")) another_dict = dict() for k, v in data_from_angular.iteritems(): if v.isdigit(): another_dict[k] = v elif v.isalpha(): another_dict[k] = v else: # do something here </code></pre> ...
0
2016-06-20T05:39:28Z
[ "python", "angularjs", "django", "unicode" ]
Get the frequency for each of the ngram terms using sklearn
37,915,038
<p>I am extracting the ngrams from a pandas dataframe using the following method:</p> <pre><code>def extractNGrams(df, ngram_size, min_freq): """Extract NGrams from a list of Strings Keyword arguments: df -- the pandas dataframe containing the sentences ngram_size -- defining the n for ngrams min_f...
0
2016-06-20T05:17:59Z
37,961,749
<p>Posting the code I used for getting counts</p> <pre><code>train_data_features = X_train_counts.toarray() vocab = vect.get_feature_names() dist = np.sum(train_data_features, axis=0) ngram_freq = {} # For each, print the vocabulary word and the frequency for tag, count in zip(vocab, dist): #print(tag, count) ...
0
2016-06-22T07:49:56Z
[ "python", "scikit-learn" ]
Write contents of csv to .txt files with one file per row?
37,915,175
<p>I have a csv in the following format:</p> <pre><code>0 | Hello 1 | Hi 2 | GoodDay </code></pre> <p>I need to copy each row to a text file, so output will be:</p> <pre><code>0.txt -&gt; Hello 1.txt -&gt; Hi 2.txt -&gt; GoodDay </code></pre> <p>I try (edited):</p> <pre><code>df=pd.read_csv('result.csv') for x in ...
1
2016-06-20T05:32:28Z
37,915,251
<p>First convert to <code>ndarray</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.values.html" rel="nofollow"><code>values</code></a> and then use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.ndarray.tofile.html" rel="nofollow"><code>tofile</code></...
1
2016-06-20T05:40:19Z
[ "python", "csv", "pandas", "dataframe" ]
Removing leading digits from string using Python?
37,915,189
<p>I see many questions asking how to remove leading zeroes from a string, but I have not seen any that ask how to remove any and all leading digits from a string.</p> <p>I have been experimenting with combinations of <code>lstrip</code>, <code>type</code> function, <code>isdigit</code>, slice notation and regex witho...
1
2016-06-20T05:34:28Z
37,915,249
<p>A simple way could be to denote all digits with <a href="https://docs.python.org/2/library/string.html#string.digits" rel="nofollow"><code>string.digits</code></a>, which quite simply provides you with a string containing all digit characters <code>'0123456789'</code> to remove with <a href="https://docs.python.org/...
4
2016-06-20T05:40:16Z
[ "python", "string", "python-2.7" ]
Removing leading digits from string using Python?
37,915,189
<p>I see many questions asking how to remove leading zeroes from a string, but I have not seen any that ask how to remove any and all leading digits from a string.</p> <p>I have been experimenting with combinations of <code>lstrip</code>, <code>type</code> function, <code>isdigit</code>, slice notation and regex witho...
1
2016-06-20T05:34:28Z
37,915,274
<p>Using regexes from <a href="https://docs.python.org/2/library/re.html" rel="nofollow">re</a>: </p> <pre><code>import re re.sub('^\d+', '', '1234AB456') </code></pre> <p>Becomes:</p> <pre><code>'AB456' </code></pre> <p>replaces any positive amount of digits at the beginning of the string with empty string.</p>
1
2016-06-20T05:42:41Z
[ "python", "string", "python-2.7" ]
Removing leading digits from string using Python?
37,915,189
<p>I see many questions asking how to remove leading zeroes from a string, but I have not seen any that ask how to remove any and all leading digits from a string.</p> <p>I have been experimenting with combinations of <code>lstrip</code>, <code>type</code> function, <code>isdigit</code>, slice notation and regex witho...
1
2016-06-20T05:34:28Z
37,916,244
<p>I want to point out that though both Mitch and RebelWithoutAPulse's answer are correct, they do not do the same thing.</p> <p>Mitch's answer left-strips any characters in the set '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'.</p> <pre><code>&gt;&gt;&gt; from string import digits &gt;&gt;&gt; digits '0123456789'...
3
2016-06-20T06:54:25Z
[ "python", "string", "python-2.7" ]
Django-Autocomplete-light widgets not showing up
37,915,224
<p>I've just installed Django-Autocomplete-Light and followed the guide on their <a href="https://django-autocomplete-light.readthedocs.io/en/master/install.html" rel="nofollow">site</a>. I've setup the autocomplete-view and it works as intended (returning a JASON of autocomplete options). I can't seem to get the widge...
1
2016-06-20T05:37:45Z
38,121,874
<p>After some testing, I found out that this was working perfectly on Firefox and Chrome incognito mode. I've disabled all chrome extensions and now it works on my regular chrome as well. </p> <p>The problem most likely was one of the extensions but I didn't manage to narrow it down to a specific extension.</p> <p>TL...
1
2016-06-30T11:31:54Z
[ "python", "django", "autocomplete", "django-autocomplete-light" ]
Fastest way to Compare the [1:] elements of a value in 2 dict of lists
37,915,484
<p>I have the following two massive dictionaries:</p> <pre><code>Dic1={0:['F','15','O+','5'],1:['M','12','O+'],2:[F,'20','O-'],3:['F','10','A+'],4:['M','45','?']...} Dic2={0:['M','15','O+','5'],1:['M','12','O+'],2:[F,'20','A-'],3:['F','10','A+'],4:['F','15','?'],5:['M','10','A+']...} </code></pre> <p>and I need to c...
1
2016-06-20T06:01:47Z
37,920,788
<p>The following should generate the desired results:</p> <pre><code>Dic1={0:['F','15','O+','5'],1:['M','12','O+'],2:['F','20','O-'],3:['F','10','A+'],4:['M','45','?']} Dic2={0:['M','15','O+','5'],1:['M','12','O+'],2:['F','20','A-'],3:['F','10','A+'],4:['F','15','?'],5:['M','10','A+']} for i in Dic1.keys(): if Di...
0
2016-06-20T10:59:01Z
[ "python", "performance", "dictionary", "comparison" ]
Django Tenant and Django Guardian configuration settings.py
37,915,556
<p>I have been experiencing issues configuring Django Tenant and Django Guardian. I want to separate users per schema. Where should I put Guardian and how should I configure it? So far I also tried switching it from TENANT_APP to SHARED_APP (I get a different error something to do with other prerequisites, auth) and I...
0
2016-06-20T06:07:30Z
37,927,477
<pre><code>SHARED_APPS = ( #tenant requirements 'tenant_schemas', 'myapp.clients', 'django.contrib.contenttypes', 'django.contrib.staticfiles', 'django.contrib.auth', 'myapp.users', 'guardian', 'oauth2_provider', 'rest_framework', ) TENANT_APPS = ( 'django.contrib.contenttyp...
0
2016-06-20T16:28:36Z
[ "python", "django", "multi-tenant" ]
python 3.6 mongoengine cannot catch exception
37,915,617
<p>I have a django 1.9 project and am using mongoengine to connect to mongodb instance.</p> <p>I have a model as follows:</p> <pre><code>from django.db import models from mongoengine import * class Employee(Document): email = StringField(required=True, unique=True) first_name = StringField(max_length=50) ...
0
2016-06-20T06:10:59Z
37,917,748
<p>I got to solve the issue.</p> <p>The <code>try except</code> was not working since the <code>DuplicateKeyError exception</code> was not being triggered from the <code>save()</code> method but instead from the <code>create()</code> method.</p> <p>Quoting from the documentation:<a href="http://docs.mongoengine.org/...
1
2016-06-20T08:28:22Z
[ "python", "django", "python-3.x", "mongoengine", "pymongo-3.x" ]
python 3.6 mongoengine cannot catch exception
37,915,617
<p>I have a django 1.9 project and am using mongoengine to connect to mongodb instance.</p> <p>I have a model as follows:</p> <pre><code>from django.db import models from mongoengine import * class Employee(Document): email = StringField(required=True, unique=True) first_name = StringField(max_length=50) ...
0
2016-06-20T06:10:59Z
37,927,714
<p>As you saw yourself in the docs, <code>create</code> returns a saved document, so if you use it</p> <ul> <li>you don't have to save it a second time</li> <li><p>you must catch save exceptions in there</p> <pre><code>try: employee = models.Employee.objects.create( email="pedro.kong@company.com", ...
1
2016-06-20T16:42:46Z
[ "python", "django", "python-3.x", "mongoengine", "pymongo-3.x" ]
Itertools product ValueError: too many values to unpack (expected 2)
37,915,700
<p>I know this question gets repeated a lot but I haven't seen one that deals with this specific problem. I got this function that takes the length of a numpy array, and then takes the cross product:</p> <pre><code>def solve(tab, vacios): if vacios == 0: return is_valid( tab ) #Not important here larg...
-3
2016-06-20T06:18:19Z
37,915,790
<p>You are producing a combination of <code>large-1</code> values every iteration, because that's what you set the <code>repeat</code> argument to:</p> <pre><code>product(range(large), repeat=(large-1): </code></pre> <p>but are unpacking values into two variables, <code>fila</code> and <code>col</code>:</p> <pre><co...
2
2016-06-20T06:25:28Z
[ "python", "python-3.x", "numpy", "itertools" ]
How to get all of the pages and files with status of a website using Scrapy?
37,915,866
<p>I used this <a href="https://github.com/alecxe/broken-links-checker" rel="nofollow">one</a> as base of my script to get all of the pages with their status. But how to check if the files(images, downloadables[pdf,doc], CSS, etc.) referenced on those pages do exists? I'm completely new with Python and this is my curre...
0
2016-06-20T06:29:36Z
37,921,062
<p>You need to do a <code>HEAD</code> request. These requests do not download the content only headers which explain what the content is. </p> <p>For example you can check:</p> <pre><code>if response.headers['Content-Length'] &gt; 0: #check whether the body is not empty if 'image' in response.headers['Content-T...
0
2016-06-20T11:11:44Z
[ "python", "scrapy" ]
Load csv file on Google Drive in Python EC2 script
37,915,973
<p>I am using EC2 for the first time, to run a machine learning task. I have set up my EC2 instance and my python script runs as intended. However, the script needs to read 3 large csv files during its run. </p> <p>I have uploaded the csv files to Google Drive. I would like to be able to read the data via my ec2 scri...
0
2016-06-20T06:36:48Z
37,963,468
<p>This is what worked for me. I ended up using S3. Make sure to set the permissions on your S3 buckets correctly. Then, simply:</p> <pre><code>conn = boto.connect_s3('access_key', 'secret_key') bucket = conn.get_bucket('bucket_name') df = pd.read_csv('file_address', index_col=0) </code></pre>
0
2016-06-22T09:10:11Z
[ "python", "google-drive-sdk" ]
How to write unittests for an optional dependency in a python package?
37,916,040
<p>Based on availability of pandas package in working environment a method returns two different outputs :</p> <ul> <li>A <code>pandas.DataFrame</code> if pandas is available</li> <li>Otherwise a <code>numpy.recarray</code> object.</li> </ul> <p>How should I write unittest for this class ?</p> <p>One solution I can ...
7
2016-06-20T06:40:11Z
37,917,159
<p>IMHO, you should alway run the tests not requiring PANDAS, because nothing prevents you to.</p> <p>But you should indeed skip the requiring pandas if pandas is not present <em>at test time</em>, because you would get uninformative errors simply caused by the absence of an optional component.</p> <p>That way, when ...
4
2016-06-20T07:52:14Z
[ "python", "python-unittest" ]
How to write unittests for an optional dependency in a python package?
37,916,040
<p>Based on availability of pandas package in working environment a method returns two different outputs :</p> <ul> <li>A <code>pandas.DataFrame</code> if pandas is available</li> <li>Otherwise a <code>numpy.recarray</code> object.</li> </ul> <p>How should I write unittest for this class ?</p> <p>One solution I can ...
7
2016-06-20T06:40:11Z
37,917,565
<p>If you want to test both cases (which you should), you could possibly force the import of Pandas to fail by adding <code>None</code> to the <code>'pandas'</code> entry in <code>sys.modules</code>, making sure to add it back again (or delete the entry if it didn't exist in the first place) once the test is done.</p> ...
5
2016-06-20T08:18:03Z
[ "python", "python-unittest" ]
Import python modules from files
37,916,065
<p>How do I import modules from *py file? I have file pythonScript.py with lines: import os, sys. If I import the file pythonScript these lines does not execute. Usung one on these modules I'm getting name error. </p>
0
2016-06-20T06:42:06Z
37,917,869
<p>It sounds like you haven't fully understood the way imports work.</p> <p>If you run:</p> <pre><code>import my_module </code></pre> <p>then anything contained in the <code>my_module.py</code> module is namespaced to <code>my_module</code>. So to use this module, you would have to type:</p> <pre><code>result = my_...
1
2016-06-20T08:35:22Z
[ "python", "file", "import" ]
Django run code on application start but not on migrations
37,916,077
<p>Hi I want to start a background thread that runs the first time my Application is running. I have implemeted it using the ready() function of the application config.</p> <pre><code>class MyappConfig(AppConfig): name = 'myApp' def ready(self): try: thread = threading.Thread(target=xxxx...
0
2016-06-20T06:43:24Z
37,917,682
<p>You can avoid executing code if the script is called with "python manage.py [migrate]":</p> <pre><code>import sys if not 'manage.py' in sys.argv: .... </code></pre>
1
2016-06-20T08:24:18Z
[ "python", "django" ]
How to run async process from handler in aiohttp
37,916,115
<p>I'm trying to understand how to run an asynchronous process from coroutine handler within aioweb framework. Here is an example of code:</p> <pre><code>def process(request): # this function can do some calc based on given request # e.g. fetch/process some data and store it in DB # but http handler don't ...
1
2016-06-20T06:45:42Z
37,932,597
<p>I guess you should define your existing <code>process</code> function as a coroutine (<code>async def</code> should do the job to wrap your function as a coroutine) and use <code>asyncio.ensure_future</code> in your main <code>handle</code> function.</p> <pre><code>async def process(request): # Do your stuff wi...
2
2016-06-20T22:07:07Z
[ "python", "asynchronous", "aiohttp" ]
Angular http post not passing data to django view
37,916,195
<p>I am trying to pass the data using angular $http post to django view but it is not happening. Every time I pass the data it shows empty dict, that means I am not using POST request correctly. I am new in integration django and angular app, so it would be great if someone can help me out with this.</p> <p><strong>ap...
0
2016-06-20T06:51:51Z
37,916,457
<p>Try this.</p> <p>If you don't wrap/jsonify the login_data your existing view should be able to unpack it. I'm pretty sure angular automatically handles the json conversion, but I don't think django does.</p> <pre><code>vm.login = function() { vm.authMsg = ''; var login_data = {'username': vm.accou...
1
2016-06-20T07:08:24Z
[ "python", "angularjs", "django" ]
how to pass the name of a variable as a variable
37,916,881
<p>How can I set the variable I want to change as a function argument? I want to define only one function, and not set_a(value), set_b(value), set_c(value), ...</p> <pre><code>class MyVarClass: def __init__(self): self.a = 1 self.b = 2 self.c = 3 # this works, but I don't want to write n f...
0
2016-06-20T07:34:56Z
37,916,959
<p>what about using a <code>dict</code>:</p> <pre><code>class MyVarClass: def __init__(self): self.vars = {"a": 1, "b": 2, "c": 3} def set_vars(myvar_object, var_name, value): myvar_object.vars[var_name] = value </code></pre>
0
2016-06-20T07:39:14Z
[ "python" ]
how to pass the name of a variable as a variable
37,916,881
<p>How can I set the variable I want to change as a function argument? I want to define only one function, and not set_a(value), set_b(value), set_c(value), ...</p> <pre><code>class MyVarClass: def __init__(self): self.a = 1 self.b = 2 self.c = 3 # this works, but I don't want to write n f...
0
2016-06-20T07:34:56Z
37,916,964
<p>This is done with setattr. </p> <pre><code>def set_vars(myvar_object, var_name, value): setattr(myvar_object, var_name, value) </code></pre> <p>This isn't necessarily the best way of doing this. It often suggests a different data structure would be better, but in case that isn't the case here.</p> <p>You'll...
1
2016-06-20T07:39:41Z
[ "python" ]
how to pass the name of a variable as a variable
37,916,881
<p>How can I set the variable I want to change as a function argument? I want to define only one function, and not set_a(value), set_b(value), set_c(value), ...</p> <pre><code>class MyVarClass: def __init__(self): self.a = 1 self.b = 2 self.c = 3 # this works, but I don't want to write n f...
0
2016-06-20T07:34:56Z
37,917,002
<p>What you usually do is to create a method to the class like this:</p> <pre><code>class MyVarClass: def __init__(self): self.a = 1 self.b = 2 self.c = 3 def set_a(self, value): self.a = value </code></pre> <p>If, for some reason, can't do it like this and you only have the n...
5
2016-06-20T07:42:18Z
[ "python" ]
how to pass the name of a variable as a variable
37,916,881
<p>How can I set the variable I want to change as a function argument? I want to define only one function, and not set_a(value), set_b(value), set_c(value), ...</p> <pre><code>class MyVarClass: def __init__(self): self.a = 1 self.b = 2 self.c = 3 # this works, but I don't want to write n f...
0
2016-06-20T07:34:56Z
37,917,090
<pre><code>** var_name = '' class MyVarClass: def __init__(self): self.a = 1 self.b = 2 self.c = 3 # this is what I actually want: def set_vars(myvar, var_name, value): myvar.var_name = value print (myvar.var_name) myvar = MyVarClass() set_vars(myvar, "b", 6) ** </code></pre...
0
2016-06-20T07:48:18Z
[ "python" ]
Caffe: Predict an image from snapshot as simple as possible
37,916,885
<p>Is there any way to EASILY use a Caffe Snapshot to predict a new Image?</p> <p>and by "EASILY" I mean:</p> <ol> <li>no changing the <code>train.prototxt</code> to <code>deploy.prototxt</code> by hand and careful considerations.</li> <li>no converting the files to LMDB (or some other format like that) and just usin...
1
2016-06-20T07:35:10Z
37,917,707
<p>You do need to <em>manually</em> change your <code>train_val.prototxt</code> to <code>deploy.protoxt</code>.<br> However, this change is easier than you think. </p> <p>copy <code>train_val.prototxt</code> to a new <code>deploy.prototxt</code> and edit <code>deploy.prototxt</code> according to the following steps:</...
1
2016-06-20T08:25:43Z
[ "python", "neural-network", "deep-learning", "caffe", "conv-neural-network" ]
Split odd rows of DataFrame without double iloc
37,917,022
<p>Test <code>df</code>:</p> <pre><code>import pandas as pd df = pd.DataFrame({'A':[1,2,3,7,8,4], 'B':[4,5,6,1,4,6], 'C':[7,8,9,2,7,3], 'D':[4,5,2,1,0,6]}) df.set_index(['A','B'], inplace=True) print (df) C D A B 1 4 7 4 2 5 8 5 3 6 9 2 7 1 ...
3
2016-06-20T07:43:34Z
37,917,269
<p>Wouldn't this work?</p> <pre><code>df2 = df.iloc[:-2:2] C D A B 1 4 7 4 3 6 9 2 </code></pre>
3
2016-06-20T07:58:49Z
[ "python", "pandas", "indexing", "dataframe" ]
PYTHON: Multiple Substitutions Using Regular Expressions
37,917,066
<p>I have lists coming from db of the type: </p> <pre><code>[[63], [426], [255], [167], [648], [364, 194], [686, 14]] </code></pre> <p>I want to convert these like: </p> <pre><code>63 -1 426 -1 255 -1 167 -1 648 -1 364 194 -1 686 14 -1 -2 and newline </code></pre> <p>i.e, separate within internal lists if more...
-4
2016-06-20T07:46:45Z
37,917,206
<p><strong>UPDATE:</strong> Solution to handles nested lists:</p> <pre><code>final_list = [] my_list = [[63], [426], [255], [167], [648], [364, 194], [686, [7, 77, 777], 14]] def recursive_convert(item): if type(item) is list: for i in item: recursive_convert(i) else: final_list.ap...
0
2016-06-20T07:54:47Z
[ "python", "regex", "string" ]
PYTHON: Multiple Substitutions Using Regular Expressions
37,917,066
<p>I have lists coming from db of the type: </p> <pre><code>[[63], [426], [255], [167], [648], [364, 194], [686, 14]] </code></pre> <p>I want to convert these like: </p> <pre><code>63 -1 426 -1 255 -1 167 -1 648 -1 364 194 -1 686 14 -1 -2 and newline </code></pre> <p>i.e, separate within internal lists if more...
-4
2016-06-20T07:46:45Z
37,917,291
<p>You can try this :</p> <pre><code>array = [[63], [426], [255], [167], [648], [364, 194], [686, 14]] out = '' for group in array: for elt in group: out += str(elt) + ' ' out += '-1 ' out += '-2 \n' print(out) </code></pre> <p>Which outputs :</p> <pre><code>63 -1 426 -1 255 -1 167 -1 648 -1 364...
0
2016-06-20T07:59:42Z
[ "python", "regex", "string" ]
PYTHON: Multiple Substitutions Using Regular Expressions
37,917,066
<p>I have lists coming from db of the type: </p> <pre><code>[[63], [426], [255], [167], [648], [364, 194], [686, 14]] </code></pre> <p>I want to convert these like: </p> <pre><code>63 -1 426 -1 255 -1 167 -1 648 -1 364 194 -1 686 14 -1 -2 and newline </code></pre> <p>i.e, separate within internal lists if more...
-4
2016-06-20T07:46:45Z
37,928,223
<p>Taking a "customer is always right" approach, despite it being the <em>wrong</em> way to solve the problem, we could do something with regular expressions and string operations. To handle arbitrary list depth, you'd need to also include your favorite implementation of a <em>flatten</em> routine:</p> <pre><code>imp...
0
2016-06-20T17:13:20Z
[ "python", "regex", "string" ]
Python script executable with py2exe or pyinstaller
37,917,082
<p>My program contains 3 files (2x .py and .json). I would like to make single exe file. I tried py2exe with basic setup settings:</p> <pre><code>from distutils.core import setup import py2exe setup(console = ['my_main_file.py']) </code></pre> <p>It doesn't work. When I run exe file from dist directory terminal wind...
1
2016-06-20T07:47:52Z
37,928,798
<p>I solved it! I launched my .exe file from terminal and received an error "there is no file myfile.json" or something like that. I simply copied this file to disc directory and program works.</p>
0
2016-06-20T17:51:32Z
[ "python", "py2exe", "pyinstaller" ]
decode utf8 to big5
37,917,142
<p>every one,I am trying to send sms by python, I can send it,but I need to send in Chinese, which is big5,I have to decode utf8 to big5,here is my sms python code</p> <blockquote> <p>trydecode.py</p> </blockquote> <pre><code>import urllib import urllib2 def sendsms(phonenumber,textcontent): textcontent.decod...
0
2016-06-20T07:51:35Z
37,917,201
<p>I think you forgot to save it to change the variable. </p> <p><code>textcontent = textcontent.decode('utf8').encode('big5')</code></p>
3
2016-06-20T07:54:20Z
[ "python", "utf-8", "big5" ]
Simple extending csr matrix by adding a column
37,917,170
<p>I have this code</p> <pre><code>import numpy as np from scipy.sparse import csr_matrix q = csr_matrix([[1.], [0.]]) ones = np.ones((2, 1)) </code></pre> <p>and now how to add ones column to matrix q to have result shape (2, 2)? (matrix q is sparse and I don't want to change type from csr)</p>
0
2016-06-20T07:52:41Z
37,928,764
<p>The code for <code>sparse.hstack</code> is</p> <pre><code>return bmat([blocks], format=format, dtype=dtype) </code></pre> <p>for <code>bmat</code>, then <code>blocks</code> is a <code>1xN</code> array. If they are all <code>csc</code>, it does a fast version of stack:</p> <pre><code>A = _compressed_sparse_stack(...
1
2016-06-20T17:49:51Z
[ "python", "numpy", "data-science" ]
Adding an extra index to Pandas DataFrame
37,917,378
<p>I have a list of DataFrame, which is read something like this</p> <pre><code>data = [pd.read_csv(f, index_col=None, header=None) for f in temp] flow = pd.DataFrame(data) </code></pre> <p>If I print the <code>flow</code> I get an output of </p> <pre><code>[[.... [128 rows x 14 columns]] [128 rows x 14 columns]] . ...
1
2016-06-20T08:04:58Z
37,939,246
<p>Try this:</p> <pre><code>flow = flow.set_index([flow.index, new_data]).rename_axis(['idx_col1','idx_col2']) </code></pre>
1
2016-06-21T08:29:11Z
[ "python", "pandas" ]
Can I inherit WebsiteCrmPartnerAssign class of Reseller module in odoo
37,917,382
<p>How to inherit WebsiteCrmPartnerAssign class of Reseller module in odoo. Since the class name is not mentioned....please help me with this qwery..</p>
0
2016-06-20T08:05:12Z
37,917,510
<p>You can inherit the class like, how you inherit a Python class. I didn't try it, but i have read it from a book and it should work. </p> <pre><code>from openerp.addons.website_crm_partner_assign.controllers.main import WebsiteCrmPartnerAssign class MyClass(WebsiteCrmPartnerAssign): ... </code></pre>
0
2016-06-20T08:14:16Z
[ "python", "odoo-9" ]
How to capture the image fast using gstreamer
37,917,425
<p>I wanted to capture the image by 300milliseconds or less. But i capture the image by 800millisecond by using the codes below. Anybody can help me solve this? Been trying this for quite long but no idea why i cant capture the image by 300millisecond. I using raspberry pi to capture the image. </p> <pre><code>import...
0
2016-06-20T08:08:22Z
37,992,914
<p>What I'd suggest trying is to use a pipeline of this form: </p> <blockquote> <p>v4l2src ! videoconvert ! clockoverlay ! timeoverlay ! jpegenc ! fakesink name=sink</p> </blockquote> <p>Then in take_photo(), grab the fakesink, access the <code>last-sample</code> property. Extract the data from the sample and re...
0
2016-06-23T13:22:01Z
[ "python", "python-2.7", "gstreamer", "raspberry-pi3" ]
setWindowLong, cannot remove WS_POPUP with different users
37,917,443
<p>I want to pull a Window into another one. Therfore I use python with pywin32.</p> <p>I want to remove with setWindowLong the WS_POPUP style.</p> <p>This works fine, when the loggedin user and the processes involved are the same.</p> <p>But when the processes are running under an diffrent user, I get an Access Den...
-1
2016-06-20T08:09:46Z
37,920,400
<p>The documentation for <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms644898.aspx" rel="nofollow">SetWindowLongPtr</a> contains the following section on the <em>hWnd</em> argument:</p> <blockquote> <p>The SetWindowLongPtr function fails if the process that owns the window specified by the hWnd...
0
2016-06-20T10:39:53Z
[ "python", "security", "winapi" ]
Assign the result of a loop to a variable in Python
37,917,615
<p>Consider a list I want to parse using a <code>for</code> :</p> <pre><code>friends = ["Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris"] for i in friends: print i </code></pre> <p>will return :</p> <pre><code>"Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris" </code></pre> <p>However, if I w...
-1
2016-06-20T08:21:09Z
37,917,808
<p>If I understand well, you'd like to dynamically create variables. Here it is.</p> <pre><code>from collections import OrderedDict friends = ["Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris"] d = OrderedDict() for idx, value in enumerate(friends): key = 'var' + str(idx) d[key] = value print(d) #...
0
2016-06-20T08:32:04Z
[ "python", "list", "list-comprehension" ]
Assign the result of a loop to a variable in Python
37,917,615
<p>Consider a list I want to parse using a <code>for</code> :</p> <pre><code>friends = ["Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris"] for i in friends: print i </code></pre> <p>will return :</p> <pre><code>"Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris" </code></pre> <p>However, if I w...
-1
2016-06-20T08:21:09Z
37,917,874
<p>If you want to join the values in <code>friends</code> into a comma-separated string, that would be</p> <pre><code>s = ','.join(friends) </code></pre> <p>If you want to include quotes around the names, maybe something like</p> <pre><code>s = ','.join(['"{0}"'.format(x) for x in friends]) </code></pre>
-1
2016-06-20T08:35:37Z
[ "python", "list", "list-comprehension" ]
Assign the result of a loop to a variable in Python
37,917,615
<p>Consider a list I want to parse using a <code>for</code> :</p> <pre><code>friends = ["Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris"] for i in friends: print i </code></pre> <p>will return :</p> <pre><code>"Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris" </code></pre> <p>However, if I w...
-1
2016-06-20T08:21:09Z
37,917,978
<p>Try this at the end of the loop:</p> <pre><code>the_variable = the_variable + i </code></pre> <p>However, if you are to do this, you should add a space to the end of every item in the dictionary, otherwise it will output:</p> <pre><code>JoeZoeBradAngelinaZukiThandiParis </code></pre>
-1
2016-06-20T08:40:34Z
[ "python", "list", "list-comprehension" ]
Assign the result of a loop to a variable in Python
37,917,615
<p>Consider a list I want to parse using a <code>for</code> :</p> <pre><code>friends = ["Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris"] for i in friends: print i </code></pre> <p>will return :</p> <pre><code>"Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris" </code></pre> <p>However, if I w...
-1
2016-06-20T08:21:09Z
37,919,812
<pre><code>var = '' friends = ["Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris"] for i in friends: var=i </code></pre> <p>if list and loop are in function then declare var as global</p> <pre><code>global var </code></pre> <p>in starting of function</p>
0
2016-06-20T10:10:46Z
[ "python", "list", "list-comprehension" ]
How to catch integers in dictionary keys, most of them string, but some is integers that I need to remove
37,917,652
<p>How to catch integers in dictionary keys, most of them string, but some is integers that i need to remove.</p> <p>I tried this:</p> <pre><code>def print_words(filename): dict = create_dict(filename) for key, val in sorted(dict.items()): # Integer filter here! # if not isinstance(dict.key,...
0
2016-06-20T08:23:01Z
37,917,736
<p>You already have <code>key</code> and <code>val</code> in your loop, <code>dict.key</code> is wrong.</p> <p>You can use this instead:</p> <pre><code>{k:v for k, v in d.items() if not isinstance(k, int)} </code></pre> <p>Or, just replace the line that doesn't work for you with:</p> <pre><code>if not isinstance(ke...
0
2016-06-20T08:27:38Z
[ "python", "dictionary", "isinstance" ]
Run Python script when Directory is updated
37,917,802
<p>I have a script which i want to execute when specific directory is updated. To be more specific: development team have 4 directories (lets say "a", "b", "c" and "d") which they update from time to time. I have a script which take as a parameter name of directory. I wan to execute this script with parameter "a" when ...
1
2016-06-20T08:31:33Z
37,918,490
<p>You can do that using python itself, with <code>watchdog</code> library.</p> <pre><code>from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler class FileHandler(PatternMatchingEventHandler): def process(self, event): print event.src_path, event.event_type # ...
2
2016-06-20T09:05:26Z
[ "python", "jenkins", "jenkins-plugins" ]
use pyinstaller to build exe from webpy
37,917,858
<p>I was trying to use '<strong>pyinstaller</strong>' to turn my '<strong>webpycode.py</strong>' into a .exe like '<strong>webpycode.exe</strong>', and I do have successfully created a webpycode.exe. When I executed it, I got this <a href="http://i.stack.imgur.com/whYNu.jpg" rel="nofollow">telling me the inter face is...
0
2016-06-20T08:34:47Z
38,611,720
<p>This worked for me:</p> <pre><code>pyinstaller.exe webcode.py --hidden-import=webcode </code></pre>
0
2016-07-27T11:29:48Z
[ "python", "pyinstaller", "web.py" ]
PyQt: give parent when creating a widget?
37,918,012
<p>Let's assume I want to create a dialog box, a child of my main program:</p> <pre><code>from PyQt4 import QtGui, QtCore class WizardJournal(QtGui.QDialog): def __init__(self, parent): super(WizardJournal, self).__init__(parent) self.parent = parent self.initUI() def initUI(self...
1
2016-06-20T08:42:01Z
37,928,086
<p>Given the way your example is currently structured, neither the dialog nor any of its child widgets will be deleted when it is closed.</p> <p>You can see this by changing the end of the example to look like this:</p> <pre><code> app.exec_() print('\n'.join(repr(w) for w in app.allWidgets())) </code></pre> ...
2
2016-06-20T17:04:42Z
[ "python", "memory", "pyqt" ]
Pyyhon encryption code - Help me understand the logic of a Python code which has some encryption logic in it
37,918,095
<p>I have a python code. I am pretty new to python. could some one please explain what this piece of code dose. </p> <p>From what I can understand this piece of code is trying to decry-pt the ID's. We pass in the ID's with a CSV file. I am unable to understand the logic line by line. Specially the hashfn.hexdigest and...
-4
2016-06-20T08:45:53Z
37,918,666
<p>This code creates a hash table from a CSV (comma separated value) file. It operates as follows.</p> <ul> <li>It opens the output file <code>ID_nos_hashed.csv</code></li> <li>It opens the date source <code>ID_nos_input.csv</code>. It is most likely a list of CSVs where each line of this file is a data record.</li> <...
1
2016-06-20T09:14:09Z
[ "python" ]
Gtk.EntryCompletion() popup status to resolve keybind conflict
37,918,111
<p>I have the <strong>Gtk.Entry()</strong> with <strong>Gtk.EntryCompletion()</strong>, have binded the arrows key to do different function i.e. navigate through the command history like in terminal.</p> <p>But navigation on <strong>Completion Popup</strong> will, conflict with history navigation, Is there any way t...
1
2016-06-20T08:47:05Z
38,002,611
<p>You need to set the inline selection option to <code>True</code> with <code>entrycompletion.set_inline_selection(True)</code>. This will connect the key press event to the completion pop-up menu. </p> <pre><code>#!/usr/bin/env python3 import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk entry...
1
2016-06-23T22:00:25Z
[ "python", "python-3.x", "gtk", "gtk3", "pygobject" ]
unittests for infinite loop
37,918,163
<p>I am stucked at this code for creating unittest for infinite loop.</p> <pre><code>try: while True: time.sleep(60) except: fun() </code></pre> <p>Please let me know how can we create unittests for infinite loop?</p>
0
2016-06-20T08:49:03Z
37,920,074
<p>You could code the infinite loop using the <a href="https://docs.python.org/3.5/library/itertools.html#itertools.count" rel="nofollow"><code>itertools.count</code></a> funсtion instead of <code>while True: ...</code>. This might make the code slightly less efficient, but it makes it possible to <a href="https://doc...
2
2016-06-20T10:23:41Z
[ "python", "unit-testing" ]
unittests for infinite loop
37,918,163
<p>I am stucked at this code for creating unittest for infinite loop.</p> <pre><code>try: while True: time.sleep(60) except: fun() </code></pre> <p>Please let me know how can we create unittests for infinite loop?</p>
0
2016-06-20T08:49:03Z
37,921,058
<p>What behaviour are you testing? There doesn't appear to be any side effects or return value here. There isn't really anything to test. If it's just that <code>fun</code> is called after the loop then that sounds like over-specification. If it's just that some invariant is maintained after the loop ends then you can ...
1
2016-06-20T11:11:33Z
[ "python", "unit-testing" ]
Multiline chart from dataframe using nvd3
37,918,184
<p>The nvd3 line chart in the example below uses python list as data source. But how to plot multiline from a pandas dataframe without explicitly stating the columns i.e. like in pandas plot: <code>df.plot()</code> df could contain <code>x</code> columns.</p> <pre><code>from nvd3 import lineChart # Open File for test...
0
2016-06-20T08:50:05Z
37,922,672
<p>IIUC, the <code>chart</code> takes the data as <code>list</code>, so you would have to convert your <code>index</code> and <code>column</code> data to <code>list</code> like so (assuming your <code>column</code> names are <code>col1</code> and <code>col2</code> respectively:</p> <pre><code>def plot_nvd3(df, ydata='...
0
2016-06-20T12:31:31Z
[ "python", "pandas", "nvd3.js" ]
Using python with Anaconda in Windows
37,918,215
<p>I have just installed Anaconda on my computer because I need to use Numpy. Well, when I use python I for some reason hav to be in the same folder as python.exe and off course now that I want to use Anaconda I have to be in the Anaconda3\Scripts folder where python.exe isn't. This is a nightmare, how can I use anacon...
1
2016-06-20T08:51:28Z
37,918,313
<p>I think you are referring to the command-line use of <code>python</code>?</p> <p>If you have admin priviliges on your machine you can add <code>python</code> to your environment variables, making it available in the console anywhere. (Sorry for different spellings, I am not on an english machine)</p> <ol> <li>Pres...
0
2016-06-20T08:56:04Z
[ "python", "windows", "numpy", "cmd", "anaconda" ]
Using python with Anaconda in Windows
37,918,215
<p>I have just installed Anaconda on my computer because I need to use Numpy. Well, when I use python I for some reason hav to be in the same folder as python.exe and off course now that I want to use Anaconda I have to be in the Anaconda3\Scripts folder where python.exe isn't. This is a nightmare, how can I use anacon...
1
2016-06-20T08:51:28Z
37,918,326
<p>To be able to do that in the command line you just have to add Python and also the Anaconda3\Scripts directory to your system path.</p> <p>Here is a good tutorial on setting your path in Windows: <a href="http://www.computerhope.com/issues/ch000549.htm" rel="nofollow">http://www.computerhope.com/issues/ch000549.htm...
0
2016-06-20T08:56:47Z
[ "python", "windows", "numpy", "cmd", "anaconda" ]
Luigid Syntax Error
37,918,254
<p>I am trying to use luigi in the central-scheduler mode. Whenever i try to run the central scheduler by using the command</p> <pre><code>$ luigid </code></pre> <p>It returns a syntax error</p> <pre><code>Traceback (most recent call last): File "/usr/local/bin/luigid", line 9, in &lt;module&gt; load_entry_po...
0
2016-06-20T08:53:15Z
37,918,851
<p>Dont know why, but downgrading tornado does the job.</p> <pre><code> $ sudo pip install tornado==4.1 $ luigid Defaulting to basic logging; consider specifying logging_conf_file in luigi.cfg. 2016-06-20 14:52:02,038 luigi.scheduler[5400] INFO: No prior state file exists at /var/lib/lui ...... </code></pre>
2
2016-06-20T09:23:04Z
[ "python", "python-asyncio", "luigi" ]
Python3 segfaults when using ctypes on xlib, python2 works
37,918,260
<p>The following code was scrounged up on the Internet years ago and works quite well in python2. It supplies the current idle time on the X server.</p> <pre><code>import ctypes, os, subprocess class XScreenSaverInfo( ctypes.Structure ): _fields_ = [("window", ctypes.c_ulong), ("state", ctypes.c_int), ("k...
0
2016-06-20T08:53:27Z
37,918,510
<p>There was no significant change in Python 3's <code>ctypes</code> module. <em>However</em> in Python3 <code>os.environ</code> values are <em>unicode</em> strings, contrary to the byte strings of python2 and this <a href="http://stackoverflow.com/questions/7256283/differences-in-ctypes-between-python-2-and-3">causes ...
3
2016-06-20T09:06:20Z
[ "python", "python-3.x", "python-2.x", "xlib" ]
Using a context manager with a coroutine
37,918,275
<p>This code does not work</p> <pre><code>from contextlib import contextmanager import tornado.ioloop import tornado.web from...
2
2016-06-20T08:54:02Z
37,923,062
<p>The structure of the code is correct, and it's fine to mix context managers and coroutines this way. The <code>@contextmanager</code> and <code>@coroutine</code> decorators each assign their own meanings to <code>yield</code> within their decorated functions, but they remain independent.</p> <p>As written, this cod...
3
2016-06-20T12:50:52Z
[ "python", "asynchronous", "tornado", "coroutine" ]
Using a context manager with a coroutine
37,918,275
<p>This code does not work</p> <pre><code>from contextlib import contextmanager import tornado.ioloop import tornado.web from...
2
2016-06-20T08:54:02Z
37,924,265
<p>This is a mechanic of <code>contextlib.contextmanager</code>, when an exception is raised inside the <code>with</code> block that error is thrown into <code>hello</code> so that it has access to the exception details and is given a change to suppress it (like a true context manager) for example:</p> <pre><code>from...
1
2016-06-20T13:48:58Z
[ "python", "asynchronous", "tornado", "coroutine" ]
How to change values of a dataframe through groupby in pandas
37,918,513
<p>Here I have a dataframe:</p> <pre><code>print te_c.head(10) Price Vol tradeDate 0 9 1 1994-05-09 1 3 2 1994-05-10 2 3 2 1994-05-10 3 3 2 1994-05-10 4 3 2 1994-05-10 5 4 3 1994-05-11 6 4 3 1...
0
2016-06-20T09:06:26Z
37,922,050
<p>You can use the information on the <code>group index</code> stored in the <code>grouper</code> attribute of a <code>groupby</code> object:</p> <pre><code>te_c['new_vol'] = te_c.Vol.mul(te_c.groupby('tradeDate').grouper.group_info[0] + 1) Price Vol tradeDate new_vol 0 9 1 1994-05-09 1 1 ...
0
2016-06-20T12:00:25Z
[ "python", "pandas", "dataframe", "group-by", "unique" ]
How to add a new row to an existing DataFrame which is the sum of two rows?
37,918,586
<p>I have a DataFrame looks as follow:</p> <pre><code> Name1 Name2 Val1 1.2 2.2 Val2 2.3 4.2 </code></pre> <p>What I want is as follow:</p> <pre><code> Name1 Name2 Val1 1.2 2.2 Val2 2.3 4.2 Val3 0.52 0.52 </code></pre> <p>The values in <code>Val3</code> is <code>Val1/Vals2<...
0
2016-06-20T09:10:32Z
37,918,884
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#selection-by-label" rel="nofollow"><code>.loc</code> to grab each row individually</a> and divide them. Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.append.html" rel="nofollow"><code>.append</code></a> to a...
0
2016-06-20T09:24:48Z
[ "python", "pandas", "dataframe" ]