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
Project IA in Python -- UnboundLocalError: local variable 'x' referenced before assignment
39,399,444
<p>`</p> <pre><code>def iterativeDeepeningSearch(problem): def depthLimitedDFS(node, problem, depth): if depth==0: return if problem.isGoalState(node[-1]): return node for move, acao, c in problem.getSuccessors(node[-1]): if move not in node: ...
-2
2016-09-08T20:14:33Z
39,399,491
<p>What <strong>python</strong> is saying to you is that you are trying to use <code>x</code> before any assignment on it. That is: you didn't use <code>x</code> <strong>at all</strong> and you are trying to inspect a possible value on it (which doesn't make sense).</p> <p>What is <code>x</code> supposed to do in your...
1
2016-09-08T20:17:29Z
[ "python", "python-2.7", "search", "graph" ]
Django form creates new instance instead updating a existing one
39,399,547
<p>I've seen this question asked a lot of time here but I can't figure out why it doesn't work in my case. I have the following view code:</p> <pre><code>def edit(request, coffee_id=None): coffee = get_object_or_404(Drink, pk=coffee_id) if coffee_id else Drink() if request.method == 'POST': form = CoffeeForm(reque...
0
2016-09-08T20:20:59Z
39,399,849
<p>get_object_or_404 errors out if the Drink with the given id doesn't exist.</p> <p>Are you sure POSTing is done against /edit/1? Because if the form action doesn't have the ID, a new Drink is created.</p> <p>I'd recommend you go with separate create and edit views. Possibly use class based views, but if you have re...
0
2016-09-08T20:40:04Z
[ "python", "django" ]
Django form creates new instance instead updating a existing one
39,399,547
<p>I've seen this question asked a lot of time here but I can't figure out why it doesn't work in my case. I have the following view code:</p> <pre><code>def edit(request, coffee_id=None): coffee = get_object_or_404(Drink, pk=coffee_id) if coffee_id else Drink() if request.method == 'POST': form = CoffeeForm(reque...
0
2016-09-08T20:20:59Z
39,399,963
<p>You should use <code>CoffeeForm</code>, not <code>ModelForm</code> when calling <code>super</code>. </p> <pre><code>class CoffeeForm(forms.ModelForm): class Meta: model = Drink fields = ('time', 'location', 'type') def __init__(self, *args, **kwargs): super(CoffeeForm, self).__init...
1
2016-09-08T20:48:13Z
[ "python", "django" ]
How to access MIFARE 1k memory blocks with Gemalto Prox-SU reader?
39,399,577
<p>I have just recently jumped into smartcard programming.</p> <p>I am using Gemalto Prox-SU reader and have several blank MIFARE Classic 1k cards available, on a Ubuntu 16.04 machine. I have installed the Gemalto Prox-SU reader and got the reader to detect a card through a script in python using <a href="https://gith...
1
2016-09-08T20:22:56Z
39,460,391
<p>The typical flow for reading MIFARE Classic 1K cards with the Prox-SU reader (see the <a href="http://support.gemalto.com/fileadmin/user_upload/drivers/Prox-DU_and_Prox-SU/DOC118569D_Prox-DUSU_RefMan.pdf" rel="nofollow">manual</a>) is:</p> <ol> <li><p>Load an authentication key. For instance, if your card is readab...
0
2016-09-12T23:59:13Z
[ "python", "mifare", "apdu", "contactless-smartcard", "gemalto" ]
ValueError: unsupported format character '}' when use % string formatting
39,399,600
<p>I'm trying to generate some LaTeX markup by using Python % string formatting. I use named fields in the string and use a dictionary with matching keys for the data. However, I get the error <code>ValueError: unsupported format character '}'</code>. Why isn't this code working?</p> <pre><code>LaTeXentry = '''\\su...
1
2016-09-08T20:24:45Z
39,399,693
<p>You have to add <code>s</code> like in standard formating <code>%s</code> - so you need <code>%(title)s</code>, <code>%(date)s</code>, etc.</p>
1
2016-09-08T20:30:41Z
[ "python", "string-formatting" ]
Deploy fabric script to multiple users of a same machine
39,399,620
<p>Is it possible (and how) to run a fab script for multiple users on a same machine. For example, say I have users <code>user1</code> and <code>user2</code> on a remote machine and I want to use a fabfile that runs a bash script that uses the <code>$HOME</code> environment variable. I need to run the bash script twice...
2
2016-09-08T20:26:19Z
39,400,581
<p>Something like this? You could run multiple commands and add as many users as you need.</p> <pre><code>for i in user1 user2 user3 ; do su -c "/some/directory/Script" ${i} done </code></pre>
0
2016-09-08T21:35:43Z
[ "python", "bash", "fabric" ]
interacting python and abaqus
39,399,635
<p>I need for an algorithm to update an input file, I found out that I can modify a .py file and run it in abaqus.</p> <p>But because of the process is necessary to automatize, I'm trying to open a script and run it in abaqus </p> <p>I tried this: os.system('abaqus cae script=C:\Users\Samuel\abaqus-1\script1.py')</p>...
1
2016-09-08T20:27:06Z
40,007,983
<p>Maybe this sentence is incorrect - </p> <pre><code>os.system('abaqus cae script=C:\Users\Samuel\abaqus-1\script1.py') </code></pre> <p>You have to run a python script in Abaqus using the command </p> <pre><code>abaqus cae noGUI=nameOfScript.py </code></pre> <p>So in your case, </p> <pre><code>os.system('abaqus ...
1
2016-10-12T20:41:16Z
[ "python", "abaqus" ]
How to get the value from a list + input
39,399,672
<p>So sorry for the vague title but this is my problem. (I just started this study)</p> <h2>For example</h2> <pre><code>list_1 = [a, b, c, d, e, f] input_1 = input('question1') input_2 = input('question2') </code></pre> <p>lets say they chose</p> <pre><code>input_1 = b input_2 = f </code></pre> <p>I need someth...
0
2016-09-08T20:29:35Z
39,399,754
<p>You will probably want to loop through the list and compare characters like you would numbers.</p> <pre><code>for i in range(len(list_1)): if list_1[i] &gt; input_1 and list_1[i] &lt; input_2: print list_1[i] </code></pre>
0
2016-09-08T20:34:56Z
[ "python", "list", "for-loop", "input" ]
How to get the value from a list + input
39,399,672
<p>So sorry for the vague title but this is my problem. (I just started this study)</p> <h2>For example</h2> <pre><code>list_1 = [a, b, c, d, e, f] input_1 = input('question1') input_2 = input('question2') </code></pre> <p>lets say they chose</p> <pre><code>input_1 = b input_2 = f </code></pre> <p>I need someth...
0
2016-09-08T20:29:35Z
39,399,763
<pre><code>if input_1 in list_1 and input_2 in list_1: print(list_1[list_1.index(input_1)+1:list_1.index(input_2)]) else: print('didn't find input_1 or input_2) </code></pre> <p>This?</p> <p>if you need to auto print the rest of the list from before input_2 or after input_1 you can just add if statements lik...
0
2016-09-08T20:35:15Z
[ "python", "list", "for-loop", "input" ]
How to get the value from a list + input
39,399,672
<p>So sorry for the vague title but this is my problem. (I just started this study)</p> <h2>For example</h2> <pre><code>list_1 = [a, b, c, d, e, f] input_1 = input('question1') input_2 = input('question2') </code></pre> <p>lets say they chose</p> <pre><code>input_1 = b input_2 = f </code></pre> <p>I need someth...
0
2016-09-08T20:29:35Z
39,399,783
<p><code>input_1</code> and <code>input_2</code> are elements in the list. </p> <p>You can use slice in python to get the elements present between the input elements.</p> <pre><code> index_1 = list_1.index(input_1) index_2 = list_l.index(input_2) new_list = list_1[index_1:index_2] print new_list </code></pre>
0
2016-09-08T20:36:19Z
[ "python", "list", "for-loop", "input" ]
How to get the value from a list + input
39,399,672
<p>So sorry for the vague title but this is my problem. (I just started this study)</p> <h2>For example</h2> <pre><code>list_1 = [a, b, c, d, e, f] input_1 = input('question1') input_2 = input('question2') </code></pre> <p>lets say they chose</p> <pre><code>input_1 = b input_2 = f </code></pre> <p>I need someth...
0
2016-09-08T20:29:35Z
39,399,797
<p>You probably want to use the list.index() method, you can find documentation <a href="https://docs.python.org/2/tutorial/datastructures.html#more-on-lists" rel="nofollow">here</a>.</p> <p>In your case, this will look like </p> <pre><code>i1 = list_1.index(input_1) i2 = list_1.index(input_2) if i2 &gt; i1: pri...
0
2016-09-08T20:37:17Z
[ "python", "list", "for-loop", "input" ]
How to get the value from a list + input
39,399,672
<p>So sorry for the vague title but this is my problem. (I just started this study)</p> <h2>For example</h2> <pre><code>list_1 = [a, b, c, d, e, f] input_1 = input('question1') input_2 = input('question2') </code></pre> <p>lets say they chose</p> <pre><code>input_1 = b input_2 = f </code></pre> <p>I need someth...
0
2016-09-08T20:29:35Z
39,399,823
<p>You can loop through the list and take out indices for each of the inputs then test for the conditions you want. Something like this:</p> <pre><code>list1 = ['a', 'b', 'c', 'd', 'f'] input_1 = 'b' input_2 = 'f' input_1_index = -1 input_2_index = -1 for i in range(len(list1)): if list1[i] == input_1: ...
0
2016-09-08T20:39:02Z
[ "python", "list", "for-loop", "input" ]
How to get the value from a list + input
39,399,672
<p>So sorry for the vague title but this is my problem. (I just started this study)</p> <h2>For example</h2> <pre><code>list_1 = [a, b, c, d, e, f] input_1 = input('question1') input_2 = input('question2') </code></pre> <p>lets say they chose</p> <pre><code>input_1 = b input_2 = f </code></pre> <p>I need someth...
0
2016-09-08T20:29:35Z
39,399,950
<p>This is my version of what you're trying to do. Make sure alphabet is the whole list of letters and you a way of checking if user input is a string from the alphabet.</p> <pre><code>alphabet = ['a', 'b', 'c', 'd'] input_1 = str(input("")) input_2 = str(input("")) Input1Pos = alphabet.index(input_1) Input2Pos = a...
0
2016-09-08T20:47:22Z
[ "python", "list", "for-loop", "input" ]
Python list return 'None'
39,399,870
<p>Code:</p> <pre><code>puzzle1= [ [7,0,0,0,0,0,2,1,8], [0,4,8,6,2,9,0,0,0], [0,0,3,0,0,1,0,0,0], [0,0,7,0,0,8,0,3,2], [0,0,9,7,0,6,5,0,0], [6,8,0,1,0,0,7,0,0], [0,0,0,2,0,0,4,0,0], [0,0,0,4,1,5,8,7,0], [3,5,4,0,0,0,0,0,6] ...
0
2016-09-08T20:41:14Z
39,399,935
<p>If <code>redo</code> is <code>True</code>, you are recursively calling your function, and somewhere down the stack, once <code>redo</code> is <code>False</code>, you print and return the result. However, this result is not propagated up the call stack, thus the outermost function call will return nothing, i.e. <code...
1
2016-09-08T20:46:02Z
[ "python", "list", "return" ]
Python list return 'None'
39,399,870
<p>Code:</p> <pre><code>puzzle1= [ [7,0,0,0,0,0,2,1,8], [0,4,8,6,2,9,0,0,0], [0,0,3,0,0,1,0,0,0], [0,0,7,0,0,8,0,3,2], [0,0,9,7,0,6,5,0,0], [6,8,0,1,0,0,7,0,0], [0,0,0,2,0,0,4,0,0], [0,0,0,4,1,5,8,7,0], [3,5,4,0,0,0,0,0,6] ...
0
2016-09-08T20:41:14Z
39,400,081
<p>@tobias_k is right. </p> <p>In every recursive function you have a base case and a recursive case. The base case is when you reach the end of your recursion and return the final value from your recursive function. The recursive case is where the function calls itself again.</p> <p><strong>You need to be returning ...
2
2016-09-08T20:57:16Z
[ "python", "list", "return" ]
How do I split an input String into seperate usable integers in python
39,399,962
<p>I'm trying to split a Input String xyz into 3 tokens and then seperating into 3 integers called x, y, and z. I want it to do this so that I have to do less input and then be able to use them for the coordinates of <code>mc.setblocks(x1, y1, z1, x, y, z, BlockId)</code>. How do I Separate it so that it turns out ...
0
2016-09-08T20:48:03Z
39,400,016
<p>You can take the string that is in <code>xyz1</code> and split it and turn them into integers like this</p> <pre><code>xyz_list = [int(x) for x in xyz1.split(' ')] </code></pre> <p>If you don't want these integers in a list and would prefer to store them into separate variables, just do this</p> <pre><code>x = xy...
1
2016-09-08T20:52:15Z
[ "python", "split", "coordinates", "tokenize", "minecraft" ]
How do I split an input String into seperate usable integers in python
39,399,962
<p>I'm trying to split a Input String xyz into 3 tokens and then seperating into 3 integers called x, y, and z. I want it to do this so that I have to do less input and then be able to use them for the coordinates of <code>mc.setblocks(x1, y1, z1, x, y, z, BlockId)</code>. How do I Separate it so that it turns out ...
0
2016-09-08T20:48:03Z
39,400,039
<p>You can use the <code>split()</code> method of the <code>string</code> object, which defaults to splitting on whitespace characters. This will give you a list of separate strings. To convert each string to an <code>integer</code>, you could use a comprehension. Assuming the input is in correct form, the following...
1
2016-09-08T20:54:17Z
[ "python", "split", "coordinates", "tokenize", "minecraft" ]
How do I split an input String into seperate usable integers in python
39,399,962
<p>I'm trying to split a Input String xyz into 3 tokens and then seperating into 3 integers called x, y, and z. I want it to do this so that I have to do less input and then be able to use them for the coordinates of <code>mc.setblocks(x1, y1, z1, x, y, z, BlockId)</code>. How do I Separate it so that it turns out ...
0
2016-09-08T20:48:03Z
39,400,221
<p>I tried writing this less "pythonically" so you can see what's happening:</p> <pre><code>xyz1 = input("Enter first 3 coordinates (example: 102 36 74): ") tokens = xyz1.split() # returns a list (ArrayList) of tokenized values try: x = int(tokens[0]) # sets x,y,z to the first three tokens y = int(tokens[1]...
0
2016-09-08T21:07:26Z
[ "python", "split", "coordinates", "tokenize", "minecraft" ]
Kivy- kv language VKeyboard
39,400,003
<p>I'd like to add VKeyboard widget for my app written using Kivy 1.9.0. I using Python 2.7.12. Is there a way to add this widget to application via kv language? Because while trying method below there is bug: 'ValueError: No JSON object could be decoded'</p> <pre><code> Button: background_color:1,...
1
2016-09-08T20:51:17Z
39,400,464
<pre><code>Traceback (most recent call last): File "C:/Users/joran/.PyCharm50/config/scratches/scratch_33", line 3, in &lt;module&gt; data = json.load(open(os.path.expanduser("~/layout1.json"))) File "C:\Python27\lib\json\__init__.py", line 290, in load **kw) File "C:\Python27\lib\json\__init__.py", line ...
0
2016-09-08T21:26:17Z
[ "python", "widget", "kivy", "virtual-keyboard" ]
Python Pandas Group by date using datetime data
39,400,115
<p>I have a column <code>Date_Time</code> that I wish to groupby date time without creating a new column. Is this possible the current code I have does not work.</p> <pre><code>df = pd.groupby(df,by=[df['Date_Time'].date()]) </code></pre>
4
2016-09-08T20:59:53Z
39,400,136
<p>You can use <code>groupby</code> by dates of column <code>Date_Time</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.date.html" rel="nofollow"><code>dt.date</code></a>:</p> <pre><code>df = df.groupby([df['Date_Time'].dt.date]).mean() </code></pre> <p>Sample:</p> <pre><code...
4
2016-09-08T21:01:12Z
[ "python", "date", "datetime", "pandas", "group-by" ]
Python Pandas Group by date using datetime data
39,400,115
<p>I have a column <code>Date_Time</code> that I wish to groupby date time without creating a new column. Is this possible the current code I have does not work.</p> <pre><code>df = pd.groupby(df,by=[df['Date_Time'].date()]) </code></pre>
4
2016-09-08T20:59:53Z
39,400,375
<p>Credit to @jezrael for his setup dataframe</p> <hr> <p>You can set the index to be <code>'Date_Time'</code> and use <code>pd.TimeGrouper</code></p> <pre><code>df.set_index('Date_Time').groupby(pd.TimeGrouper('D')).mean().dropna() </code></pre> <p><a href="http://i.stack.imgur.com/JpCfM.png" rel="nofollow"><img s...
4
2016-09-08T21:19:02Z
[ "python", "date", "datetime", "pandas", "group-by" ]
Error when saving multiple figures to a one multi-page PDF document
39,400,135
<p>I'm trying to save several figures to one multi-page PDF document. My code is as follows:</p> <pre><code>import matplotlib.backends.backend_pdf pdf = matplotlib.backends.backend_pdf.PdfPages('output.pdf') sns.set_style('darkgrid') g = sns.factorplot(data=df, x='Date', y='Pro...
1
2016-09-08T21:01:07Z
39,408,904
<p><code>g</code> and <code>f</code> are not <a href="http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure" rel="nofollow"><code>matplotlib.figure.Figure</code></a> objects, they are <a href="https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.FacetGrid.html" rel="nofollow"><code>seaborn.axis...
3
2016-09-09T10:00:13Z
[ "python", "matplotlib", "seaborn", "pdfpages" ]
Sending data from Autodesk Maya to an external application using commandPort (python scripting)
39,400,302
<p>I have a implemented a C# application which communicates to Autodesk Maya using a TCP Connection. Maya acts as the server and my application acts as the host. </p> <p>The python script that is executed in Maya is - </p> <pre><code>import socket import maya.cmds as cmds flag = None cmds.commandPort(name = "localhos...
0
2016-09-08T21:13:33Z
39,407,511
<p>i changed some parts for mayas side</p> <pre><code>import socket import maya.cmds as cmds from functools import partial FLAG = None class Hermes(object): def __init__(self, **kwargs): self.host_id = kwargs['host_id'] cmds.commandPort(name = "localhost:{0}".format(self.host_id), stp = "python") ...
0
2016-09-09T08:49:54Z
[ "c#", "python", "sockets", "tcpclient", "maya" ]
Is making a python wrapper for the Azure-PowerShell SDK a stupid idea?
39,400,319
<p>My opinion of the Azure-Python SDK is not high for Azure RM. What takes 1 line in PowerShell takes 10 in Python. That is the opposite of what python is supposed to do.</p> <p>So, my idea is to create python package which comes with a directory containing a few template .ps1 scripts. You would define a few variables...
0
2016-09-08T21:15:16Z
39,467,065
<p>@RobTruxal, It seems that a feasible way to call PowerShell in Python is using the module <code>subprocess</code>, such as the code below as reference.</p> <pre><code>import subprocess subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", "your-script.ps1", "arguments"]) </code></pre> ...
0
2016-09-13T09:51:48Z
[ "python", "powershell", "azure" ]
Is making a python wrapper for the Azure-PowerShell SDK a stupid idea?
39,400,319
<p>My opinion of the Azure-Python SDK is not high for Azure RM. What takes 1 line in PowerShell takes 10 in Python. That is the opposite of what python is supposed to do.</p> <p>So, my idea is to create python package which comes with a directory containing a few template .ps1 scripts. You would define a few variables...
0
2016-09-08T21:15:16Z
39,477,085
<p>@RobTruxal, the new CLI for Azure will be in Python and will be released as a preview soon. You can already try it from the github account: <a href="https://github.com/Azure/azure-cli" rel="nofollow">https://github.com/Azure/azure-cli</a></p> <p>The Azure SDK for Python is not supposed to mimic the Powershell cmdle...
1
2016-09-13T18:51:56Z
[ "python", "powershell", "azure" ]
Comparing two DataFrames by one column with a return of three different outputs with Panadas
39,400,332
<p>I am beginner in Python and coding. I need help comparing two dataframes of different lengths and with different column labels except one. The column that is the same between the two datasets is the column I want to compare the dataframe by. My data looks like this:</p> <pre><code> df: 'fruits' 'trees' 's...
6
2016-09-08T21:16:03Z
39,400,455
<p><strong><em>Setup Reference</em></strong></p> <pre><code>from StringIO import StringIO import pandas as pd txt1 = """fruits,trees,sports,countries bananas,mongolia,basketball,Spain grapes,Oak,rugby,Thailand oranges,Osage,Orange baseball,Egypt apples,Maple,golf,Chile""" txt2 = """cars,flowers,countries,vegetables ...
4
2016-09-08T21:25:39Z
[ "python", "pandas", "numpy", "dataframe" ]
Using a list comprehension to label data that is common to two lists
39,400,336
<p>I have two lists, A and B. I want to generate a third list that is 1 if the corresponding entry in A has an entry in the list B at the end of the string and 0 otherwise.</p> <pre><code>A = ['Mary Sue', 'John Doe', 'Alice Stella', 'James May', 'Susie May'] B = ['Smith', 'Stirling', 'Doe'] </code></pre> <p>I want a...
4
2016-09-08T21:16:18Z
39,400,405
<pre><code>&gt;&gt;&gt; [[0, 1][name.split()[-1] in set(B)] for name in A] [0, 1, 0, 0, 0] </code></pre> <p>edit: For finer control over the check.</p> <p><a href="https://docs.python.org/2/library/stdtypes.html#str.split" rel="nofollow"><strong><code>str.split</code></strong></a> can take a parameter which is the ma...
0
2016-09-08T21:21:41Z
[ "python", "python-3.x", "list-comprehension" ]
Using a list comprehension to label data that is common to two lists
39,400,336
<p>I have two lists, A and B. I want to generate a third list that is 1 if the corresponding entry in A has an entry in the list B at the end of the string and 0 otherwise.</p> <pre><code>A = ['Mary Sue', 'John Doe', 'Alice Stella', 'James May', 'Susie May'] B = ['Smith', 'Stirling', 'Doe'] </code></pre> <p>I want a...
4
2016-09-08T21:16:18Z
39,400,411
<p>Your condition needs to hold the <code>B</code> list. Your proposed solution will generate a <code>0</code> or <code>1</code> for every pair of (A, B) elements.</p> <pre><code>[1 if any(full.endswith(last) for last in B) else 0 for full in A] </code></pre> <p>But you can also take advantage of <code>bool</code> to...
2
2016-09-08T21:22:03Z
[ "python", "python-3.x", "list-comprehension" ]
Using a list comprehension to label data that is common to two lists
39,400,336
<p>I have two lists, A and B. I want to generate a third list that is 1 if the corresponding entry in A has an entry in the list B at the end of the string and 0 otherwise.</p> <pre><code>A = ['Mary Sue', 'John Doe', 'Alice Stella', 'James May', 'Susie May'] B = ['Smith', 'Stirling', 'Doe'] </code></pre> <p>I want a...
4
2016-09-08T21:16:18Z
39,400,421
<p><code>[1 if a.split(' ')[1] in B else 0 for a in A]</code></p>
0
2016-09-08T21:22:53Z
[ "python", "python-3.x", "list-comprehension" ]
Using a list comprehension to label data that is common to two lists
39,400,336
<p>I have two lists, A and B. I want to generate a third list that is 1 if the corresponding entry in A has an entry in the list B at the end of the string and 0 otherwise.</p> <pre><code>A = ['Mary Sue', 'John Doe', 'Alice Stella', 'James May', 'Susie May'] B = ['Smith', 'Stirling', 'Doe'] </code></pre> <p>I want a...
4
2016-09-08T21:16:18Z
39,400,970
<p>How big is B in real life? You could turn it into a regular expression.</p> <pre><code>A = ['Mary Sue', 'John Doe', 'Alice Stella', 'James May', 'Susie May'] B = ['Smith', 'Stirling', 'Doe'] </code></pre> <p>turn B into <code>".*(?:Smith|Stirling|Doe)$"</code> then compile to regex </p> <pre><code>import re en...
0
2016-09-08T22:14:13Z
[ "python", "python-3.x", "list-comprehension" ]
Using a list comprehension to label data that is common to two lists
39,400,336
<p>I have two lists, A and B. I want to generate a third list that is 1 if the corresponding entry in A has an entry in the list B at the end of the string and 0 otherwise.</p> <pre><code>A = ['Mary Sue', 'John Doe', 'Alice Stella', 'James May', 'Susie May'] B = ['Smith', 'Stirling', 'Doe'] </code></pre> <p>I want a...
4
2016-09-08T21:16:18Z
39,401,250
<p>A much faster way is to pass a tuple to <em>endswith</em>:</p> <pre><code>In [8]: A = ['Mary Sue', 'John Doe', 'Alice Stella', 'James May', 'Susie May'] In [9]: B = ['Smith', 'Stirling', 'Doe'] In [10]: A *= 1000 In [11]: %%timeit t = tuple(B)...
2
2016-09-08T22:44:53Z
[ "python", "python-3.x", "list-comprehension" ]
Use dataframe column as arguments in function - iPython
39,400,348
<p>I am new with python and any help would be appreciated!</p> <p>I have a dataframe with one column with coordinates:</p> <pre><code>gridReference (190000, 200000) (560000, 250000) (560000, 250000) (560000, 250000) (560000, 250000) (560000, 250000) (320000, 80000) </code></pre> <p>I also have a function which conve...
0
2016-09-08T21:17:12Z
39,424,049
<p>To answer directly to your question you can do </p> <pre><code>f = lambda x: toConvert(x[0],x[1]) df['gridReference'].map(f) </code></pre> <p>But actually why do you need a Pandas DataFrame for that? You can just do the same with list of tuples or with tuple of tuples and performance should be the same. I bel...
0
2016-09-10T08:12:38Z
[ "python", "pandas", "dataframe" ]
pip install returns code 1 error with saga_python. Any ideas?
39,400,423
<p>I am trying to install saga-python (package for SAGA GIS) and cmd python keeps returning the same error: python setup.py egg_info failed with code 1 in C:\Users\MyUser\AppData\Local\Temp\pip-build-7uieglh9\saga-python. Any ideas why it occurs? </p> <p>Also, tried a few tips from this question's answers: <a href="h...
0
2016-09-08T21:23:00Z
39,400,480
<p>This package only for python 2.X. See <a href="https://github.com/radical-cybertools/saga-python/issues/399" rel="nofollow">issue</a></p>
1
2016-09-08T21:27:27Z
[ "python", "pip", "python-3.5.2" ]
Python does not start for loop
39,400,466
<pre><code>old = [[0 for x in range(3)] for y in range(10)] count =0 # check if the number has non-repeating digits def different(number): digit_list = [0] * 4 i = 0 while i: digit_list[i] = number%10 number /= 10 i += 1 for x in range(0,3): for y in range(x+1,3): ...
0
2016-09-08T21:26:24Z
39,400,556
<p>The while loop in your different() function does nothing as while(0) will prevent the loop from running. Even if that would run, your different() function will always return false. At least in the last loop it will compare digit_list[3] == digit_list[3] as both loop range until 3. This is always true and the functio...
0
2016-09-08T21:33:52Z
[ "python", "python-3.x", "for-loop" ]
Pandas: keeping only first row of data in each 60 second bin
39,400,684
<p>What's the best way to keep only the first row of each 60 second bin of data in pandas? i.e. For every row that occurs at increasing time <code>t</code>, I want to delete all rows that occur up to <code>t+60</code> seconds.</p> <p>I know there's some combination of <code>groupby().first()</code> that I can probably...
3
2016-09-08T21:46:40Z
39,400,830
<p>see <a class='doc-link' href="http://stackoverflow.com/documentation/pandas/1751/indexing-and-selecting-data/19351/path-dependent-slicing#t=201609082151350926644">Path Dependent Slicing</a></p> <h3>Solution</h3> <pre><code>def td60(ta): d = np.timedelta64(int(6e10)) tp = ta + d j = 0 yield j fo...
3
2016-09-08T22:00:34Z
[ "python", "pandas", "dataframe" ]
Pandas: keeping only first row of data in each 60 second bin
39,400,684
<p>What's the best way to keep only the first row of each 60 second bin of data in pandas? i.e. For every row that occurs at increasing time <code>t</code>, I want to delete all rows that occur up to <code>t+60</code> seconds.</p> <p>I know there's some combination of <code>groupby().first()</code> that I can probably...
3
2016-09-08T21:46:40Z
39,400,864
<p><strong>UPDATE:</strong> thanks to <a href="http://stackoverflow.com/questions/39400684/pandas-keeping-only-first-row-of-data-in-each-60-second-bin/39400864?noredirect=1#comment66127957_39400864">@piRSquared</a> - he noticed that my previous solution was incorrect. Here is another attempt:</p> <p>data:</p> <pre><c...
3
2016-09-08T22:03:17Z
[ "python", "pandas", "dataframe" ]
Python - Type Checking Instances of Objects
39,400,708
<p>I'm creating a class that emulates numeric types so as to be able to use basic arithmetic operators, like <code>+</code>, <code>-</code>, etc on instances of this class. However, I want to be able to handle the operation in different ways depending on what types the operands are. For instance, if I'm creating a clas...
0
2016-09-08T21:48:32Z
39,400,778
<p>You forgot to have <code>foo_c</code> inherit from <code>object</code>, so you're getting an old-style class. Make it inherit from <code>object</code>:</p> <pre><code>class foo_c(object): ... </code></pre>
1
2016-09-08T21:55:12Z
[ "python", "class", "object", "instance", "typechecking" ]
Can I use range of str to get a loop of 12 months?
39,400,722
<p>I would like to use this loop-function for all 12 months. Any idea how to alter the date, tried with a string of values, but I am just lost. Thankful for inputs.</p> <pre><code>y=str('02','03','04') # Months (Can I use Range here in some way?) q=('01.'+(y)+'.'+(year)) # Date in file, where the loop break with open...
0
2016-09-08T21:49:38Z
39,400,771
<p>Here is one way:</p> <pre><code>for month in range(1, 13): month = '%02d' % month print('01.' + month + '.' + '2016') </code></pre> <p>Here is another:</p> <pre><code>months = ['%02d' % month for month in range(1, 13)] print (months) </code></pre>
0
2016-09-08T21:54:44Z
[ "python", "string", "loops" ]
Can I use range of str to get a loop of 12 months?
39,400,722
<p>I would like to use this loop-function for all 12 months. Any idea how to alter the date, tried with a string of values, but I am just lost. Thankful for inputs.</p> <pre><code>y=str('02','03','04') # Months (Can I use Range here in some way?) q=('01.'+(y)+'.'+(year)) # Date in file, where the loop break with open...
0
2016-09-08T21:49:38Z
39,400,865
<p>If you want to loop through an array of strings, you don't need range.</p> <pre><code>Months = ['Jan', 'Feb', 'Mar'] for mo in Months: print mo </code></pre> <p>If you are just looking for how to pick out the month field from the date.</p> <pre><code>date='01.11.2016' print date.split('.')[1] '11' </code></pr...
0
2016-09-08T22:03:19Z
[ "python", "string", "loops" ]
How to process Python Pandas data frames in batches?
39,400,851
<p>I have three very long lists of Pandas data frames. For example:</p> <pre><code>list_a = [tablea1, tablea2, tablea3, tablea4] list_b = [tableb1, tableb2, tableb3, tableb4] list_c = [tablec1, tablec2, tablec3, tablec4] </code></pre> <p>I want to do something like this:</p> <pre><code>tablea1 = pd.concat([tablea1...
0
2016-09-08T22:02:00Z
39,412,726
<p>@qqzj The problem that you will run into is that python doesn't exactly have this feature available. As @Boud <a href="http://stackoverflow.com/a/8989916/624829">mentions</a>, the reference to tablea1, tableb1, tablec1 etc are lost after concatenation. </p> <p>I'll illustrate a quick and dirty example of the workar...
0
2016-09-09T13:30:10Z
[ "python", "pandas" ]
How to process Python Pandas data frames in batches?
39,400,851
<p>I have three very long lists of Pandas data frames. For example:</p> <pre><code>list_a = [tablea1, tablea2, tablea3, tablea4] list_b = [tableb1, tableb2, tableb3, tableb4] list_c = [tablec1, tablec2, tablec3, tablec4] </code></pre> <p>I want to do something like this:</p> <pre><code>tablea1 = pd.concat([tablea1...
0
2016-09-08T22:02:00Z
39,456,370
<p>Thanks for zhqiat's sample codes. Let me expand a bit on it. Here this problem can be solved using exec statement.</p> <pre><code>import pandas as pd import numpy as np tablea1 = pd.DataFrame(np.random.randn(10, 4)) tableb1 = pd.DataFrame(np.random.randn(10, 4)) tablec1 = pd.DataFrame(np.random.randn(10, 4)) tabl...
0
2016-09-12T18:17:15Z
[ "python", "pandas" ]
await for any future asyncio
39,400,885
<p>I'm trying to use asyncio to handle concurrent network I/O. A very large number of functions are to be scheduled at a single point which vary greatly in time it takes for each to complete. Received data is then processed in a separate process for each output.</p> <p>The order in which the data is processed is not r...
1
2016-09-08T22:05:10Z
39,407,084
<p>Looks like you are looking for <a href="https://docs.python.org/3/library/asyncio-task.html#asyncio.wait" rel="nofollow">asyncio.wait</a> with <code>return_when=asyncio.FIRST_COMPLETED</code>.</p> <pre><code>def fetch(x): sleep() async def main(): futures = [loop.run_in_executor(None, fetch, x) for x in ra...
1
2016-09-09T08:26:02Z
[ "python", "python-asyncio", "executor" ]
Return any number of matching groups with re findall in python
39,400,940
<p>I have a relatively complex string that contains a bunch of data. I am trying to extract the relevant pieces of the string using a regex command. The portions I am interested in are contained in square brackets, like this:</p> <pre><code>s = '"data":["value":3.44}] lol haha "data":["value":55.34}] ...
0
2016-09-08T22:11:07Z
39,400,983
<p>It's because quantifiers are greedy by default. So <code>.*</code> will match everything between the first <code>"data":</code> and the last <code>[</code>, so there's only one <code>[...]</code> left to match.</p> <p>Use non-greedy quantifiers by adding <code>?</code>.</p> <pre><code>l = re.findall(r'\"data\"\:.*...
2
2016-09-08T22:15:15Z
[ "python", "regex" ]
Return any number of matching groups with re findall in python
39,400,940
<p>I have a relatively complex string that contains a bunch of data. I am trying to extract the relevant pieces of the string using a regex command. The portions I am interested in are contained in square brackets, like this:</p> <pre><code>s = '"data":["value":3.44}] lol haha "data":["value":55.34}] ...
0
2016-09-08T22:11:07Z
39,401,049
<p>You can also use <a href="https://docs.python.org/2/library/re.html#re.finditer" rel="nofollow"><code>finditer</code></a> to extract the relevant content iteratively:</p> <pre><code>import re s = '"data":["value":3.44}] lol haha "data":["value":55.34}] "data":["value":2.44}] lol haha "data":["value":56.34}]' for m...
1
2016-09-08T22:21:53Z
[ "python", "regex" ]
pandas iterrows throwing error
39,400,957
<p>I am trying to do a change data capture on two dataframes. The logic is to merge two dataframes and group by one keys and then run a loop for groups having count >1 to see which column 'updated'. I am getting strange error. any help is appreciated. code</p> <pre><code>import pandas as pd import numpy as np pd.set_...
0
2016-09-08T22:12:58Z
39,401,927
<p>Why not do as suggested and use <code>apply</code>? Something like:</p> <pre><code>def print_rows(rows): print rows group_by_1.apply(print_rows) </code></pre>
0
2016-09-09T00:10:15Z
[ "python", "pandas" ]
pandas iterrows throwing error
39,400,957
<p>I am trying to do a change data capture on two dataframes. The logic is to merge two dataframes and group by one keys and then run a loop for groups having count >1 to see which column 'updated'. I am getting strange error. any help is appreciated. code</p> <pre><code>import pandas as pd import numpy as np pd.set_...
0
2016-09-08T22:12:58Z
39,402,263
<p>Your <code>GroupBy</code> object supports iteration, so instead of</p> <pre><code>for i,rows in group_by_1.iterrows(): print("rownumber", i) print (rows) </code></pre> <p>you need to do something like</p> <pre><code>for name, group in group_by_1: print name print group </code></pre> <p>then you c...
0
2016-09-09T00:54:27Z
[ "python", "pandas" ]
A Python list of Numpy Arrays to CSV?
39,401,012
<p>I have a Python list of Numpy arrays storing X, Y, Z coordinates - like this:</p> <pre><code>[array([-0.22424938, 0.16117005, -0.39249256]) array([-0.22424938, 0.16050598, -0.39249256]) array([-0.22424938, 0.1598419 , -0.39249256]) ..., array([ 0.09214371, -0.26184322, -0.39249256]) array([ 0.09214371, -0.262507...
0
2016-09-08T22:17:13Z
39,401,055
<p>Use the <a href="https://docs.python.org/2/library/csv.html#module-csv" rel="nofollow"><code>csv</code></a> module with its <a href="https://docs.python.org/2/library/csv.html#csv.csvwriter.writerows" rel="nofollow"><code>writerows</code></a> method:</p> <pre><code>import csv with open('my_data.txt', 'w') as f: ...
2
2016-09-08T22:22:37Z
[ "python", "arrays", "csv", "numpy" ]
A Python list of Numpy Arrays to CSV?
39,401,012
<p>I have a Python list of Numpy arrays storing X, Y, Z coordinates - like this:</p> <pre><code>[array([-0.22424938, 0.16117005, -0.39249256]) array([-0.22424938, 0.16050598, -0.39249256]) array([-0.22424938, 0.1598419 , -0.39249256]) ..., array([ 0.09214371, -0.26184322, -0.39249256]) array([ 0.09214371, -0.262507...
0
2016-09-08T22:17:13Z
39,401,287
<p><code>np.savetxt</code> will write the list:</p> <pre><code>In [553]: data=[array([-0.22424938, 0.16117005, -0.39249256]), ...: array([-0.22424938, 0.16050598, -0.39249256]), ...: array([-0.22424938, 0.1598419 , -0.39249256]), ...: array([ 0.09214371, -0.26184322, -0.39249256]), ...: array([ ...
1
2016-09-08T22:49:20Z
[ "python", "arrays", "csv", "numpy" ]
Pandas: Query tool doesn't work if column headers are tuples: TypeError: argument of type 'int' is not iterable
39,401,029
<p>TLDR: The df.query() tool doesn't seem to work if the df's columns are tuples or even tuples converted into strings. How can I work around this to get the slice I'm aiming for?</p> <hr> <p><strong>Long Version:</strong> I have a pandas dataframe that looks like this (although there are a lot more columns and rows....
0
2016-09-08T22:19:27Z
39,401,578
<p>You can build a list of conditions and logically condense them with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.all.html" rel="nofollow"><code>np.all</code></a> instead of using <code>query</code>:</p> <pre><code>for dosage_comb in product(*dict_of_dose_ranges.values()): dosage_items = zi...
1
2016-09-08T23:24:15Z
[ "python", "pandas", "typeerror" ]
Callback with Decorator or Parameter in Python?
39,401,066
<p>I'm designing an API. What's preferred using </p> <pre><code>@event1 def event_callback(): print "wooop" </code></pre> <p>or something like:</p> <pre><code>def event_callback(): print "wooop" event1(callback=event_callback) </code></pre>
1
2016-09-08T22:23:33Z
39,401,149
<p>The two alternatives are entirely equivalent. Decorator syntax was introduced because particularly for long functions it was easy to miss the decoration call following the definition, so you should use a decorator.</p>
0
2016-09-08T22:32:05Z
[ "python", "callback" ]
Why repeat(n) does not work with create in Reactive extensions
39,401,088
<pre><code>from rx import Observable, Observer from __future__ import print_function import random def create_observable(observer): while True: observer.on_next(random.randint(1,100)) Observable.create(create_observable).take_while(lambda x: x&gt;50).repeat(6).subscribe(print) </code></pre> <p>gives<...
1
2016-09-08T22:25:58Z
40,088,963
<p>The posted code gets 6 times a sequence of random integers in the range [51, 100].</p> <p>Try with </p> <pre><code>(Observable.create(create_observable) .take_while(lambda x: x &gt; 50) .select_many(lambda x: Observable.just(x).repeat(6)) .subscribe(print)) </code></pre> <p>or just </p> <pre><code>(O...
0
2016-10-17T14:24:01Z
[ "python", "reactivex", "rx-py" ]
manager.GetIOSettings() -> None in Mac Python FBX SDK bindings
39,401,092
<p>Fresh install of the python bindings for the FBX SDK on a Mac, into site-packages of an anaconda python 2.7.12 installation. Success when importing fbx and FbxCommon. Success creating manager, scene, and importer objects for an fbx file import. here's the code</p> <pre><code>import fbx manager = fbx.FbxManager.Cre...
0
2016-09-08T22:26:15Z
39,416,792
<p>If the manager does not have an IOSettings, you can create one for it:</p> <pre><code>if not manager.GetIOSettings(): ios = fbx.FbxIOSettings.Create(manager, fbx.IOSROOT) manager.SetIOSettings(ios) </code></pre> <p>(discovered in the FbxCommon.py file from the python SDK bindings)</p>
0
2016-09-09T17:24:12Z
[ "python", "fbx" ]
Add multiple Elements to Set in a Dictionary
39,401,150
<p>I am trying to achieve the following structure.</p> <pre><code>{0: set([1]), 1: set([2]), 2: set([0,3]), 3: set([3])} </code></pre> <p>Following is my code : </p> <pre><code>class Graph(object): """ This is the graph class which will store the information regarding the graph like vertices and edges. ...
1
2016-09-08T22:32:11Z
39,401,190
<p><code>set.update()</code> expects an <em>iterable</em> of values. Use <a href="https://docs.python.org/2/library/stdtypes.html#set.add" rel="nofollow"><code>set.add()</code></a> to add <em>one</em> value:</p> <pre><code>if value[0] in temp_dict: temp_dict[value[0]].add(value[1]) </code></pre> <p>Rather than te...
3
2016-09-08T22:36:12Z
[ "python", "graph", "set" ]
Add multiple Elements to Set in a Dictionary
39,401,150
<p>I am trying to achieve the following structure.</p> <pre><code>{0: set([1]), 1: set([2]), 2: set([0,3]), 3: set([3])} </code></pre> <p>Following is my code : </p> <pre><code>class Graph(object): """ This is the graph class which will store the information regarding the graph like vertices and edges. ...
1
2016-09-08T22:32:11Z
39,401,391
<p>You can use <a href="https://docs.python.org/2/library/collections.html#defaultdict-objects" rel="nofollow"><code>defaultdict</code></a> using <code>set</code> as its default value.</p> <pre><code>from collections import defaultdict class Graph(object): """ This is the graph class which will store the informat...
1
2016-09-08T23:00:39Z
[ "python", "graph", "set" ]
Celery equivalent of a JoinableQueue
39,401,374
<p>What would be Celery's equivalent of a <a href="https://docs.python.org/2/library/multiprocessing.html#multiprocessing.JoinableQueue"><code>multiprocessing.JoinableQueue</code></a> (or <a href="http://www.gevent.org/gevent.queue.html#gevent.queue.JoinableQueue"><code>gevent.queue.JoinableQueue</code></a>)?</p> <p>T...
7
2016-09-08T22:58:40Z
39,687,121
<p>It might not be perfect, but this is what I came up with eventually.</p> <p>It's basically a <code>JoinableQueue</code> wrapper on top of an existing Celery queue, based on a shared Redis counter and a list listener. It requires the queue name to be the same as it's routing key (due to internal implementation detai...
0
2016-09-25T13:00:40Z
[ "python", "queue", "celery", "python-multiprocessing", "gevent" ]
python & pandas - Split large dataframe into multiple dataframes and plot diagrams
39,401,473
<p>I'm under the similar condition with <a href="http://stackoverflow.com/questions/19790790/splitting-dataframe-into-multiple-dataframes">this case</a>. I'm working on a project which has a large dataframe with about half-million of rows. And about 2000 of users are involving in this.( I get this number by <code>value...
0
2016-09-08T23:10:00Z
39,401,617
<p>No need to sort first. You may try this with your original DataFrame:</p> <pre><code># import third-party libraries import pandas as pd import numpy as np # Define a function takes the database, and return a dictionary def splitting_dataframe(df): d = {} # Define an empty dicti...
0
2016-09-08T23:28:43Z
[ "python", "pandas", "matplotlib", "dataframe", "split" ]
python & pandas - Split large dataframe into multiple dataframes and plot diagrams
39,401,473
<p>I'm under the similar condition with <a href="http://stackoverflow.com/questions/19790790/splitting-dataframe-into-multiple-dataframes">this case</a>. I'm working on a project which has a large dataframe with about half-million of rows. And about 2000 of users are involving in this.( I get this number by <code>value...
0
2016-09-08T23:10:00Z
39,401,701
<p><code>[g for _, g in df.groupby('NoUsager')]</code> gives you a list of data frames where each dataframe contains one unique <code>NoUsager</code>. But I think what you need is something like:</p> <pre><code>for k, g in df.groupby('NoUsager'): g.plot(kind = ..., x = ..., y = ...) etc.. </code></pre>
3
2016-09-08T23:41:18Z
[ "python", "pandas", "matplotlib", "dataframe", "split" ]
How to add data labels to a bar chart in Bokeh?
39,401,481
<p>In the Bokeh guide there are examples of various bar charts that can be created. <a href="http://bokeh.pydata.org/en/0.10.0/docs/user_guide/charts.html#id4" rel="nofollow">http://bokeh.pydata.org/en/0.10.0/docs/user_guide/charts.html#id4</a></p> <p>This code will create one:</p> <pre><code>from bokeh.charts import...
1
2016-09-08T23:11:31Z
39,542,303
<p>Yes, you can add labels to each bar of the chart. There are a few ways to do this. By default, your labels are tied to your data. But you can change what is displayed. Here are a few ways to do that using your example:</p> <pre><code>from bokeh.charts import Bar, output_file, show from bokeh.sampledata.autompg ...
3
2016-09-17T02:20:42Z
[ "python", "bokeh" ]
How to add data labels to a bar chart in Bokeh?
39,401,481
<p>In the Bokeh guide there are examples of various bar charts that can be created. <a href="http://bokeh.pydata.org/en/0.10.0/docs/user_guide/charts.html#id4" rel="nofollow">http://bokeh.pydata.org/en/0.10.0/docs/user_guide/charts.html#id4</a></p> <p>This code will create one:</p> <pre><code>from bokeh.charts import...
1
2016-09-08T23:11:31Z
39,656,707
<p>Ben Love excellent reply to this question. It worked like charm for me. I have been struggling around to plot bar chart where we were fetching the data inside the pandas dataframe. The code block I have used to plot the Bar Chart with x_range as labels below.</p> <p>Stored labels inside the pandas dataframe. The ke...
0
2016-09-23T08:57:01Z
[ "python", "bokeh" ]
How do I get all the rows of data for a specific month,or days; over a range of many years using pandas DataFrame?
39,401,487
<p>I am attempting to find seasonal trends in the stock market. I want to have the ability to see how an asset has preformed i.e. what is the average return for appl(apple computer) in the month of May, since 1990? Also I would like to see i.e how has aapl performed between September and December since 1990. Finally I...
1
2016-09-08T23:12:15Z
39,401,591
<p>Use the standard libraries <a href="https://docs.python.org/2/library/datetime.html" rel="nofollow"><strong><code>datetime</code></strong></a> and write helper functions to do the conversions you want. Then make a new column by applying the helper function to the Date column.</p> <pre><code>from datetime import da...
1
2016-09-08T23:25:52Z
[ "python", "pandas", "dataframe", "time-series" ]
Python: "IndexError: string index out of range" Beginner
39,401,571
<p>I know, I know, this question has been asked plenty of times before. But I can't figure out how to fix it here - in this particular instance. When I subtract 2, which is what was recommended, I still get the same error within if statement. Thanks The code (at least it should) take a string "s" and measure it agains...
0
2016-09-08T23:23:34Z
39,401,685
<p>That is because you are using index <code>j</code> of <code>order</code> list to access <code>s</code> list. It is possible that <code>j</code> is greater than <code>len(s)</code> hence the <code>IndexError</code>.</p> <p>I don't know what you are trying to achieve with the code. But in any case heres what you can ...
2
2016-09-08T23:38:22Z
[ "python", "for-loop", "indexing" ]
Convert single quotes to double quotes for Dictionary key/value pair
39,401,579
<p>I have a dictionory with key value pair in single inverted commas as follows:</p> <pre><code>filename = 'sub-310621_task-EMOTION_acq-LR_bold.nii.gz' intended_for ={"IntendedFor", filename} </code></pre> <p>AS i am want to write this dictionary to a json file i have to have filename in between two inverted commas e...
0
2016-09-08T23:24:27Z
39,401,748
<p>The apostrophes or quotation marks on the ends of a string literal are not included in the string - <code>'asdf'</code> and <code>"asdf"</code> represent identical strings. Neither the key nor the value in your dict actually include the character <code>'</code> or <code>"</code>, so you don't need to perform a conve...
1
2016-09-08T23:47:43Z
[ "python", "json", "dictionary" ]
Convert single quotes to double quotes for Dictionary key/value pair
39,401,579
<p>I have a dictionory with key value pair in single inverted commas as follows:</p> <pre><code>filename = 'sub-310621_task-EMOTION_acq-LR_bold.nii.gz' intended_for ={"IntendedFor", filename} </code></pre> <p>AS i am want to write this dictionary to a json file i have to have filename in between two inverted commas e...
0
2016-09-08T23:24:27Z
39,401,959
<p>Rather than trying to build the JSON string yourself you should use the <a href="https://docs.python.org/3.5/library/json.html" rel="nofollow">json</a> module to do the encoding.</p> <p>The <code>json.dumps()</code> method takes an object such as a dictionary with key value pairs and converts it into a JSON complia...
0
2016-09-09T00:15:41Z
[ "python", "json", "dictionary" ]
I don't understand this sentence
39,401,603
<p>I'm new to learning Python and I'm making a lot of questions these days. I tried to make a Bulls and Cows game, but I failed and then I searched on the internet for the code. I found this sentence and I don't know what it does:</p> <pre><code>while True: guess = raw_input('\nNext guess [%i]: ' % guesses).st...
0
2016-09-08T23:27:38Z
39,401,627
<p>Typically, code in python needs complete itself on one line. If you would, instead, like to have line breaks to continue an expression to the next line (the most obvious reason being to increase readability) then you can insert a <code>\</code> at the end of the line. </p> <p>This tells python to treat the next lin...
1
2016-09-08T23:30:40Z
[ "python" ]
Python re.search function regex issue
39,401,604
<p>I have the following code:</p> <pre><code>#!/usr/bin/python import time, uuid, hmac, hashlib, base64, json import urllib3 import certifi import datetime import requests import re from datetime import datetime http = urllib3.PoolManager( cert_reqs='CERT_REQUIRED', # Force certificate check. ca_certs=certif...
0
2016-09-08T23:27:40Z
39,401,682
<pre><code>re.search(r'(?!52\.39\.62\.8)', log) </code></pre> <p>You're matching <em>any</em> empty string that is not followed by the ip address - every string will match, as this will match the end of any string.</p> <p>reverse your logic and output the line to the log only if <code>re.search</code> for the ip addr...
0
2016-09-08T23:38:03Z
[ "python", "regex" ]
Python re.search function regex issue
39,401,604
<p>I have the following code:</p> <pre><code>#!/usr/bin/python import time, uuid, hmac, hashlib, base64, json import urllib3 import certifi import datetime import requests import re from datetime import datetime http = urllib3.PoolManager( cert_reqs='CERT_REQUIRED', # Force certificate check. ca_certs=certif...
0
2016-09-08T23:27:40Z
39,404,008
<p>If the IP address is always flanked by specific characters, e.g.: <code>(52.39.62.8):</code>, you can use <code>in</code> for exact contains:</p> <pre><code>if '(52.39.62.8):' not in log: logfile.write(log + '\n') </code></pre>
1
2016-09-09T04:44:35Z
[ "python", "regex" ]
Prepare my bigdata with Spark via Python
39,401,690
<p>My 100m in size, quantized data:</p> <pre><code>(1424411938', [3885, 7898]) (3333333333', [3885, 7898]) </code></pre> <p>Desired result:</p> <pre><code>(3885, [3333333333, 1424411938]) (7898, [3333333333, 1424411938]) </code></pre> <p>So what I want, is to transform the data so that I group 3885 (for example) wi...
0
2016-09-08T23:39:38Z
39,401,827
<p>You can use a bunch of basic pyspark transformations to achieve this.</p> <pre><code>&gt;&gt;&gt; rdd = sc.parallelize([(1424411938, [3885, 7898]),(3333333333, [3885, 7898])]) &gt;&gt;&gt; r = rdd.flatMap(lambda x: ((a,x[0]) for a in x[1])) </code></pre> <p>We used <code>flatMap</code> to have a key, value pair fo...
1
2016-09-08T23:56:51Z
[ "python", "algorithm", "apache-spark", "bigdata", "distributed-computing" ]
Python list or pandas dataframe arbitrary indexing and slicing
39,401,709
<p>I have used both R and Python extensively in my work, and at times I get the syntax between them confused.</p> <p>In R, if I wanted to create a model from only <strong><em>some</em></strong> features of my data set, I can do something like this:</p> <pre><code>subset = df[1:1000, c(1,5,14:18,24)] </code></pre> <p...
0
2016-09-08T23:42:23Z
39,401,764
<p>You can use <code>iloc</code> for integer indexing in pandas:</p> <pre><code>df.iloc[0:10000, [0, 4] + range(13,18) + [23]] </code></pre> <p>As commented by @root, in Python 3, you need to explicitly convert <code>range()</code> to list by <code>df.iloc[0:10000, [0, 4] + list(range(13,18)) + [23]]</code></p>
2
2016-09-08T23:49:28Z
[ "python", "pandas", "numpy", "slice" ]
Python list or pandas dataframe arbitrary indexing and slicing
39,401,709
<p>I have used both R and Python extensively in my work, and at times I get the syntax between them confused.</p> <p>In R, if I wanted to create a model from only <strong><em>some</em></strong> features of my data set, I can do something like this:</p> <pre><code>subset = df[1:1000, c(1,5,14:18,24)] </code></pre> <p...
0
2016-09-08T23:42:23Z
39,402,012
<p>Try this, The first square brackets filter. The second set of square brackets slice. </p> <pre><code>df[[0,4]+ range(13,18)+[23]][:1000] </code></pre>
1
2016-09-09T00:22:20Z
[ "python", "pandas", "numpy", "slice" ]
Python list or pandas dataframe arbitrary indexing and slicing
39,401,709
<p>I have used both R and Python extensively in my work, and at times I get the syntax between them confused.</p> <p>In R, if I wanted to create a model from only <strong><em>some</em></strong> features of my data set, I can do something like this:</p> <pre><code>subset = df[1:1000, c(1,5,14:18,24)] </code></pre> <p...
0
2016-09-08T23:42:23Z
39,402,051
<p>In a file of <code>index_tricks</code>, <code>numpy</code> defines a class instance that converts a scalars and slices into an enumerated list, using the <code>r_</code> method:</p> <pre><code>In [560]: np.r_[1,5,14:18,24] Out[560]: array([ 1, 5, 14, 15, 16, 17, 24]) </code></pre> <p>It's an instance with a <code...
3
2016-09-09T00:28:57Z
[ "python", "pandas", "numpy", "slice" ]
plot Latitude longitude points from dataframe on folium map - iPython
39,401,729
<p>I have a dataframe with lat/lon coordinates </p> <pre><code>latlon (51.249443914705175, -0.13878830247011467) (51.249443914705175, -0.13878830247011467) (51.249768239976866, -2.8610415615063034) ... </code></pre> <p>I would like to plot these on to a Folium map but I'm not sure of how to iterate through each of th...
0
2016-09-08T23:45:10Z
39,401,823
<p>This can solve your issue</p> <pre><code>import folium mapit = None latlon = [ (51.249443914705175, -0.13878830247011467), (51.249443914705175, -0.13878830247011467), (51.249768239976866, -2.8610415615063034)] for coord in latlon: mapit = folium.Map( location=[ coord[0], coord[1] ] ) mapit.save( 'map.html') </...
0
2016-09-08T23:56:11Z
[ "python", "dataframe", "ipython", "folium" ]
Python is not printing my input in while loop
39,401,791
<p>I'm having trouble with my python code as it is not printing anything after I input something into the compiler. </p> <p>I'm trying to write code that uses a while loop and allows the user to enter an album's artist and title. Then I should be able to call <code>make_album</code> with the user's input and print the...
0
2016-09-08T23:52:21Z
39,401,900
<p>I suggest to print out the type of your "a_name" and see what it says.</p> <p>My guess is that your usage of <code>input</code> does not yield what you expect. Try <code>raw_input</code> instead.</p> <p>The python course has the following to say on <a href="http://www.python-course.eu/input.php" rel="nofollow"><c...
0
2016-09-09T00:06:04Z
[ "python" ]
Python is not printing my input in while loop
39,401,791
<p>I'm having trouble with my python code as it is not printing anything after I input something into the compiler. </p> <p>I'm trying to write code that uses a while loop and allows the user to enter an album's artist and title. Then I should be able to call <code>make_album</code> with the user's input and print the...
0
2016-09-08T23:52:21Z
39,402,010
<p>If you call to your <code>make_album</code> method in the bottom of your code it'll only show your three cd variables (or constants?), but that will only happen if you pass to it something to print.</p> <p>You're returning <code>CD.title()</code>, but what's title? a method from CD? where is it defined?, there's no...
0
2016-09-09T00:21:51Z
[ "python" ]
Pandas group_by date and resample
39,401,821
<p>I have some data frame that looks like this:</p> <pre><code> A B C date 0 J Y 2 2013-02-01 14:21:02.070030 1 X X 0 2013-02-01 15:49:33.110849 2 Y D 9 2013-02-01 06:47:19.369514 3 Y C 17 2013-02-01 08:56:11.751781 4 3 J 21 2013-02-01 14:19:12.017232 </code></pre> <p>I'...
2
2016-09-08T23:55:54Z
39,402,120
<p><code>resample</code> is in some sense just a special case of groupby - rather than grouping on distinct values, which is what <code>grouppy('date')</code> would do, it groups a time-based transformation of the index, which is why you need to set the index. Alternatively, you could do:</p> <pre><code>df.groupby(pd...
4
2016-09-09T00:36:04Z
[ "python", "pandas" ]
How can I show realtime text analysis of a Django form Textarea (models.TextField)?
39,401,867
<p>OK, so I have a model class <code>Recipe</code> and a form class <code>AddRecipeForm</code> that is based on <code>Recipe</code> (<code>via forms.ModelForm</code>).</p> <p>The form shows up in my html template and works, but I want to implement a special type of form validation. Basically, I want to do some text pr...
0
2016-09-09T00:01:45Z
39,431,749
<p>Don't get Django's Form class involved and don't worry about django-channels. You just need to setup a simple API that takes a JSON of whatever is in your text field and returns a result of processed text. JavaScript would be responsible for calling the API via AJAX and doing something with the response.</p> <p>It'...
1
2016-09-11T00:20:25Z
[ "jquery", "python", "django", "forms" ]
Maximize quadratic objective with linear constraints in R: Rsolnp or Auglag
39,401,978
<p>I am trying to find a solution to the following optimization problem using either auglag or Rsolnp. </p> <pre><code>Max t(w1 - w2) * Kf * Sf * t(Kf) * (w1 - w2) subject to Kc * w1 = Kc * w2 and sum(w1) = 1 and sum(w2) = 1 and w1,w2 &gt;= 0 Sc and Sf are variance covariance matrices at the coarse and fine level resp...
3
2016-09-09T00:17:35Z
39,404,661
<p>I solved your problem about <code>solnp</code>. <code>?solnp</code> says <code>fun</code>, <code>ineqfun</code> and <code>eqfun</code> return <code>vector</code> but yours return <code>matrix</code>. So I added <code>c(...)</code> to them.</p> <pre><code>library(Rsolnp) krdsol &lt;- solnp(par = theta, ...
0
2016-09-09T05:50:17Z
[ "python", "matlab", "mathematical-optimization" ]
Split function splitting words with punctuations. Want to prevent. After splitting how to Alphabetize?
39,402,069
<p>I have two issues. Here goes the code: </p> <pre><code>Read =open("C:\Users\Moondra\Desktop/test1.txt",'r') text =Read.read() words =text.split() print(words) print(words.sort()) ##counts=dict() ##for word in words: ## counts[word] = counts.get(word,0)+1 ## ## ##print counts </code></pre> <p>And the tex...
0
2016-09-09T00:30:54Z
39,402,490
<p>This code should work for what you described:</p> <pre><code>import re with open("C:\Users\Moondra\Desktop/test1.txt", 'r') as file: file = file.read() words_list = re.findall(r"[\w]+", file) words_list = sorted(words_list, key=str.lower) patterns = ["Hello"] counter = 0 for word in words_list: for pat...
2
2016-09-09T01:28:16Z
[ "python", "text", "split" ]
Generating points on a circle
39,402,109
<pre><code>import random import math import matplotlib.pyplot as plt def circle(): x = [] y = [] for i in range(0,1000): angle = random.uniform(0,1)*(math.pi*2) x.append(math.cos(angle)); y.append(math.sin(angle)); plt.scatter(x,y) plt.show() circle() </code></pre> <p>I've...
1
2016-09-09T00:35:11Z
39,402,126
<p>It is a circle -- The problem is that the aspect ratio of your axes is not 1 so it looks like an oval when you plot it. To get an aspect ratio of 1, you can use:</p> <pre><code>plt.axes().set_aspect('equal', 'datalim') # before `plt.show()` </code></pre> <p>This is highlighted in a <a href="http://matplotlib.org...
2
2016-09-09T00:36:49Z
[ "python", "matplotlib" ]
Replacing a certain part of a string in a Pandas Data Frame with Regex
39,402,154
<p>My data frame has a date column (that currently are strings). I am trying to fix a problem with the column.</p> <pre><code>df[:15] Date Customer ID 0 01/25/2016 104064596300 1 02/28/2015 102077474472 2 11/17/2016 106430081724 3 02/24/2016 107770391692 4 10/05/2016 106523680888 5 02/24/2016 ...
2
2016-09-09T00:39:56Z
39,402,337
<p>Do not treat date as strings. You can first transform the string format of date to timestamp, then slice.</p> <pre><code>import pandas ad pd df.loc[:, 'Date'] = pd.DatetimeIndex(df['Date'], name='Date') df = df.set_index('Date') df['2015-09': '2016-02'] </code></pre> <p>Update:</p> <pre><code>df.loc[:, 'year_mont...
2
2016-09-09T01:03:45Z
[ "python", "regex", "pandas", "numpy", "substring" ]
Raise an error and after that return a value in Python
39,402,158
<p>I want to raise an error and then return a value.</p> <pre><code>raise ValueError('Max Iter Reached') return x </code></pre> <p>And make both lines work.</p> <p>Now I found this question is stupid and I decided to print an error message.</p> <pre><code>print 'Max Iter Reached' return x </code></pre>
0
2016-09-09T00:40:47Z
39,402,183
<p>It does not make sense but In case you need it. </p> <pre><code>def your_method(self): ...... try: raise ValueError('Max Iter Reached') except ValueError as e: return value </code></pre>
1
2016-09-09T00:45:22Z
[ "python" ]
Raise an error and after that return a value in Python
39,402,158
<p>I want to raise an error and then return a value.</p> <pre><code>raise ValueError('Max Iter Reached') return x </code></pre> <p>And make both lines work.</p> <p>Now I found this question is stupid and I decided to print an error message.</p> <pre><code>print 'Max Iter Reached' return x </code></pre>
0
2016-09-09T00:40:47Z
39,402,228
<p>This is impossible. A function can <em>either</em> return a value <em>or</em> raise an exception. It <em>cannot</em> do both. Calling <code>return</code> or <code>raise</code> will absolutely terminate the function.</p> <p>You could encode a return value inside the exception message, like this:</p> <pre><code>r...
3
2016-09-09T00:51:23Z
[ "python" ]
How to print function on if statement?
39,402,210
<p>How do I print the function 'play' in the if statement on line 5?</p> <pre><code>print("Deal 'Em\nby Imago Games") print("1. Play\n2. Credits") select = input() if select == 1: def play() elif select == 1: print("Bye") def play(): print("Welcome to Deal 'Em\nLet me teach you the basics!") </code></pre>
0
2016-09-09T00:48:53Z
39,402,240
<p>You can put either just <code>play()</code> on line 5 (remove the <code>def</code>) or change the <code>play</code> function to return the string instead of printing it. <code>def</code> is only used when you define the function, not when you call it.</p>
0
2016-09-09T00:52:18Z
[ "python" ]
How to print function on if statement?
39,402,210
<p>How do I print the function 'play' in the if statement on line 5?</p> <pre><code>print("Deal 'Em\nby Imago Games") print("1. Play\n2. Credits") select = input() if select == 1: def play() elif select == 1: print("Bye") def play(): print("Welcome to Deal 'Em\nLet me teach you the basics!") </code></pre>
0
2016-09-09T00:48:53Z
39,402,247
<p>Just leave it as play(), the print is already inside the function</p>
0
2016-09-09T00:52:51Z
[ "python" ]
How to print function on if statement?
39,402,210
<p>How do I print the function 'play' in the if statement on line 5?</p> <pre><code>print("Deal 'Em\nby Imago Games") print("1. Play\n2. Credits") select = input() if select == 1: def play() elif select == 1: print("Bye") def play(): print("Welcome to Deal 'Em\nLet me teach you the basics!") </code></pre>
0
2016-09-09T00:48:53Z
39,402,261
<p>Instead of <code>def play()</code> on line 5, use <code>play()</code> to simply call the function. Also, you should work on the structure of your code and place all the function definitions before calling them.</p>
0
2016-09-09T00:54:08Z
[ "python" ]
How to print function on if statement?
39,402,210
<p>How do I print the function 'play' in the if statement on line 5?</p> <pre><code>print("Deal 'Em\nby Imago Games") print("1. Play\n2. Credits") select = input() if select == 1: def play() elif select == 1: print("Bye") def play(): print("Welcome to Deal 'Em\nLet me teach you the basics!") </code></pre>
0
2016-09-09T00:48:53Z
39,402,355
<p>There are three major problems in your code:</p> <ul> <li><code>play()</code> is defined before usage. You have to define the function earlier in your code.</li> <li>to call the function use <code>play()</code> without <code>def</code></li> <li>your <code>elif</code> has the same condition as the <code>if</code> an...
3
2016-09-09T01:05:50Z
[ "python" ]
Django search as input is entered into form
39,402,314
<p>I currently have a working search form in my project that passes through form data to the GET request. Pretty standard. What I'm wanting to do is search as data is entered into the search form, so that results will display in real time with search data. This is much like what Google does with the instant desktop res...
0
2016-09-09T01:01:25Z
39,404,039
<p>you can save the request.data in to session and if any data is associated with session search data you can put in to value of search box.</p> <pre><code>request.session['search'] = request.GET.get('q','') </code></pre> <p>templete :</p> <pre><code>{% if request.session.search %} {{request.session.search}} {% endi...
0
2016-09-09T04:47:57Z
[ "python", "django", "search" ]
Scrapy: TypeError: 'Request' object is not iterable
39,402,361
<p>I'm making a spider using Scrapy (1.1.2) to scrap products. I managed to get it to work and scrape enough data, but now, I want for each element to make new request to the <code>product page</code> and scrap, for example the product description.</p> <p>First, here's my last working code</p> <p><strong>spider.py</s...
0
2016-09-09T01:07:01Z
39,403,418
<p>The error you experience (<code>TypeError: 'Request' object is not iterable</code>) happened because a <code>Request</code> instance is being put into a field of the item (in the updated <code>get_meta</code> method function), while the feed exporter cannot serialize it.</p> <p>You would need to return the get meta...
1
2016-09-09T03:31:31Z
[ "python", "python-2.7", "scrapy", "scrapy-spider" ]
Process as string for each item in dataframe or list in Python
39,402,412
<p>I'm trying something very simple on python. </p> <p><code>zips = sempmme['Zip code'].unique()</code></p> <p>I want to apply <code>zipcode.isequal('12345')</code> for each <code>zips</code> but I'm not sure how to do it in pythonic efficient way. </p> <p>I tried 'zipcode.isequal(lambda x: x in zips)' and even for ...
-1
2016-09-09T01:16:56Z
39,402,873
<p>Depending on what your goal in "applying <code>zipcode.isequal</code> for each <code>zips</code>"...</p> <p>To return a list where each element is the return value of <code>zipcode.isequal()</code> of the elements in zips:</p> <pre><code>cities = [zipcode.isequal(str(zip)) for zip in zips] </code></pre> <p>or ret...
1
2016-09-09T02:22:04Z
[ "python", "dataframe", "zipcode" ]
Django - Click on link won't redirect me to the page unless i right click and open in new tab
39,402,445
<p>I'm fairly new to django and I'm working on a project for some reason clicking on my links won't redirect me to the desired page, nothing happens, but i cant open it bu right click > open in new tab here is my template</p> <p><strong>index.html:</strong></p> <pre><code>&lt;ul class="list"&gt; {% for movie in...
2
2016-09-09T01:20:41Z
39,406,898
<p>This is most likely a JavaScript issue, this has nothing to do with Django. Your Django setup is working fine, I tested it is well.</p> <p>There is an identical issue faced by someone else <a href="http://stackoverflow.com/questions/20724590/a-href-not-working">here</a>, and it was revealed that JavaScript was the ...
1
2016-09-09T08:14:41Z
[ "python", "django" ]
Is there a batch version of Tweepy's 'destroy_friendship()' function?
39,402,457
<p>It appears that Tweepy's destroy_friendship() function, which unfollows a Twitter user, can only unfollow one user at a time - this presumably means that to unfollow many users, you have to make many API calls, and this counts against your rate limit.</p> <p>Is there a batch version of the destroy_friendship() call...
2
2016-09-09T01:23:56Z
39,403,285
<p>Twitter's API does not have a call to destroy more than one friendship at a time. See the doc <a href="https://dev.twitter.com/rest/reference/post/friendships/destroy" rel="nofollow">here</a>. However, you don't have to wait for <code>destroy_friendship()</code> to finish before calling it again. It will be faster i...
3
2016-09-09T03:16:58Z
[ "python", "twitter", "tweepy" ]
What does the regex [^\s]*? mean?
39,402,495
<p>I am starting to learn python spider to download some pictures on the web and I found the code as follows. I know some basic regex. I knew <code>\.jpg</code> means <code>.jpg</code> and <code>|</code> means <code>or</code>. what's the meaning of <code>[^\s]*?</code> of the first line? I am wondering why using <code...
-5
2016-09-09T01:28:44Z
39,402,538
<p>Alright, so to answer your first question, I'll break down <code>[^\s]*?</code>.</p> <ul> <li><p>The square brackets (<code>[]</code>) indicate a <a href="http://www.regular-expressions.info/charclass.html" rel="nofollow"><em>character class</em></a>. A character class basically means that you want to match anythin...
5
2016-09-09T01:36:04Z
[ "python", "regex" ]
Difference between add and iadd?
39,402,501
<p>I'm not understanding the purpose of the in-place operators like iadd, imul, etc.</p> <blockquote> <p>Many operations have an “in-place” version. The following functions provide a more primitive access to in-place operators than the usual syntax does; for example, the statement x += y is equivalent to x =...
0
2016-09-09T01:29:44Z
39,402,740
<p>The "in-place" functions for immutable objects cannot be implemented using an <a href="https://en.wikipedia.org/wiki/In-place_algorithm" rel="nofollow">in-place algorithm</a>, while for mutable objects they could be. The simple truth is that immutable objects don't change. </p> <p>Otherwise, usage of "in-place" v...
0
2016-09-09T02:04:40Z
[ "python", "python-2.7", "operators" ]
How can I redirect only part of a stream?
39,402,535
<p>I'm using Python on bash on Linux. I would like to be able to suppress error messages from a particular module, but keep other error messages. An example would probably be the most efficient way to convey what I want:</p> <hr> <h3>File: <code>module.py</code></h3> <pre><code>import sys sys.stderr.write('Undesired...
0
2016-09-09T01:35:40Z
39,403,058
<p>There is an example here in the accepted answer that might help you</p> <p><a href="http://stackoverflow.com/questions/6796492/temporarily-redirect-stdout-stderr">Temporarily Redirect stdout/stderr</a></p> <p>but in your case, it assumes that you could do </p> <pre><code>import module </code></pre> <p><em>after<...
1
2016-09-09T02:45:18Z
[ "python", "linux", "bash", "file-descriptor", "io-redirection" ]
How can I redirect only part of a stream?
39,402,535
<p>I'm using Python on bash on Linux. I would like to be able to suppress error messages from a particular module, but keep other error messages. An example would probably be the most efficient way to convey what I want:</p> <hr> <h3>File: <code>module.py</code></h3> <pre><code>import sys sys.stderr.write('Undesired...
0
2016-09-09T01:35:40Z
39,405,885
<p><a href="http://stackoverflow.com/a/39403058/5214181">akubot's answer</a> and some experimentation led me to the answer to this question, so I'm going to accept it.</p> <p>Do this:</p> <pre><code>$ exec 3&gt;&amp;1 </code></pre> <p>Then change <code>script.py</code> to be the following:</p> <pre><code>import sys...
1
2016-09-09T07:16:06Z
[ "python", "linux", "bash", "file-descriptor", "io-redirection" ]
I use crispy-forms work in django,render failures after the first click the submit button,the second time click the submit button has no response
39,402,624
<p>I am ready to use crispy-froms to my django projection,but in the test,there happen a question,I do not know where happened mistakes.So I post the code here. If someone can point out the mistake,I will appreciate it. forms:</p> <pre><code>class TestForm(forms.ModelForm): name = forms.CharField(widget=forms.Tex...
0
2016-09-09T01:47:59Z
39,403,528
<p>Most probably it's because your ajax event is bind to an element which is being replaced by the returned data. Try binding it to document.</p> <p>Instead of </p> <pre><code>$('#button-id-save').on('click', function(event){ ... } </code></pre> <p>Try this</p> <pre><code>$(document).on("click", "#button-id-save", ...
0
2016-09-09T03:45:11Z
[ "python", "ajax", "django" ]
`For x in locals():` -- RuntimeError: Why does locals() change size?
39,402,652
<p>I have a function and want to get the arguments passed to it. I tried achieving this via <code>locals()</code>, but I end up getting the keys of <code>locals()</code>, not the value-pairs:</p> <pre><code>&gt;&gt;&gt;def print_params(i,j,k): for x in locals(): print(x) &gt;&gt;&gt;print_params('a','b','c...
0
2016-09-09T01:53:55Z
39,402,732
<p>When you call <code>for x in locals()</code>, <code>locals()</code> is evaluated then its first item is stored in <code>x</code>. <code>x</code> wasn't defined before, hence it is being added to the <code>locals</code> dictionary during the first loop and the second loop notices the change.</p> <p>One way of workar...
0
2016-09-09T02:03:59Z
[ "python", "iteration" ]
`For x in locals():` -- RuntimeError: Why does locals() change size?
39,402,652
<p>I have a function and want to get the arguments passed to it. I tried achieving this via <code>locals()</code>, but I end up getting the keys of <code>locals()</code>, not the value-pairs:</p> <pre><code>&gt;&gt;&gt;def print_params(i,j,k): for x in locals(): print(x) &gt;&gt;&gt;print_params('a','b','c...
0
2016-09-09T01:53:55Z
39,402,759
<blockquote> <p>Can someone explain what's happening? From the single value I got to print (before it errors out), I can see that the error arises when the loop attempts to iterate to the next element of locals(); then, as the dict has been modified, it loses its place. I can't make sense of why the dictionary size s...
1
2016-09-09T02:06:59Z
[ "python", "iteration" ]
Python: how to access already instantiated class object in PyQt?
39,402,655
<p>I have a simple subclass of a base class, QLineEdit, which is just an editable text box from PyQt5: </p> <pre><code>class pQLineEdit(QtWidgets.QLineEdit): def __init__(self, parent = None): QtWidgets.QWidget.__init__(self,parent) def mouseDoubleClickEvent(self,e): self.setText("Test") </cod...
-1
2016-09-09T01:54:14Z
39,417,046
<p>At the risk of stating the obvious: if you want to access a variable, you need to put it somewhere that is accessible. The local scope of a function is not accessible to any code outside of that function.</p> <p>To make a variable accessible to another module, it must be assigned in the global scope, or be assigned...
1
2016-09-09T17:42:13Z
[ "python", "oop", "pyqt" ]
Can't make a date query with PyMongo
39,402,679
<p>the issue is the following. I have a mongo collection with the variable jobdate, which is as of now a string I would suppose.However, I need to run a route to query said variable in the following way:</p> <pre><code>@app.route('/active_jobs/&lt;jobdate&gt;', methods = ['GET']) def get_a_date(jobdate): ajobs = mong...
2
2016-09-09T01:56:48Z
39,804,383
<p>Although string matching should also work, it would be best to store the date in mongo as a date object. You can do so by using strptime. For the format YYYY-MM-DD it should work out to something like this in POST:</p> <pre><code>from datetime.datetime import strptime jobdate = strptime(request.json['jobdate'], "%...
0
2016-10-01T08:09:24Z
[ "python", "mongodb", "date", "pymongo" ]
Python: Creating map with 2 lists
39,402,690
<p>I want to create map data from 2 list data. I have a simple example like below. What I want to do is create 'new_map' data like below. If it contains specific data, the value should be True.</p> <pre><code>all_s = ['s1', 's2', 's3', 's4'] data = ['s2', 's4'] new_map = {'s1': False, 's2': True, 's3': False, 's4': Tr...
0
2016-09-09T01:57:55Z
39,402,720
<p>This should do it quickly and efficiently in a pythonic manner:</p> <pre><code> data_set = set(data) new_map = {k: k in data_set for k in all_s} </code></pre>
4
2016-09-09T02:01:37Z
[ "python", "python-3.x" ]