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
Django exclude field in admin if creator of this object is request user
39,974,962
<p>How can I exclude a field from the Django admin if the creator of this object is current user. Is there any way to customise my model in <code>admin.py</code>?</p> <pre><code>class Toys(BaseModel): name = models.CharField(max_length=255) tags = models.ManyToManyField(Tag, related_name='Item_tags') price...
0
2016-10-11T10:09:32Z
39,977,581
<p>First, you need to add a field to your model to store the creator.</p> <pre><code>class Toys(BaseModel): creator = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=255) tags = models.ManyToManyField(Tag, related_name='Item_tags') price = models.CharField(max_lengt...
1
2016-10-11T12:46:06Z
[ "python", "django", "django-admin" ]
How to convert a list of strings into a list of integers - many things dont seem to work
39,974,985
<p>I have a problem. I would like to convert a list of strings with 594 elements, among them many empty, to a list of integers. I already looked up many answers here, but neither list comprehensions, neither map function seems to work. My command prompt simply says int argument must be a string or a number, not a list....
0
2016-10-11T10:10:56Z
39,975,035
<p>The approaches you mentioned should work, but you're not building your data correctly; you don't have a list of strings but a list of lists - <code>re.findall</code> <em>returns</em> a list:</p> <pre><code>numbers = re.findall('[0-9]+', line) numlist.append(numbers) # appending a list to numlist </code></pre> <p>Y...
3
2016-10-11T10:13:19Z
[ "python", "list" ]
Escape backslash in Python parameterized MySQL query
39,975,020
<p>I am working on excel files and database storaging, precisely I am storaging excel data to MySQL database. At some point I am executing this query:</p> <pre><code>query_for_id = ''' SELECT id FROM attivita WHERE attivita = '{0}' '''.format(attivita) </code></pre> <p>And when I print the query result I get this:</p...
0
2016-10-11T10:12:36Z
39,975,299
<p>I think that in your case better to use arguments to execute</p> <pre><code>query_for_id = ''' SELECT id FROM attivita WHERE attivita = %(attivita)s ''' cursor.execute(query_for_id, { 'attivita': attivita }) </code></pre> <p><a href="https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-ex...
1
2016-10-11T10:29:29Z
[ "python", "mysql", "sql" ]
Ordered list of text and element data of an html element with beautifulsoup
39,975,101
<p>I would like to parse the content of the following div element with BeautifulSoup (bs4):</p> <pre><code>&lt;div&gt;&lt;!--block--&gt;&amp;nbsp; &amp;nbsp; Some text is here&amp;nbsp;&lt;br&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; - Another text&amp;nbsp;&lt;br&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; - ...
1
2016-10-11T09:10:06Z
39,975,864
<p>tag.contents is what I was looking for.</p>
0
2016-10-11T11:06:57Z
[ "python", "html", "screen-scraping" ]
Subprocess calls the wrong version of 'time'
39,975,103
<p>I'm trying to call the shell keyword version of 'time' via </p> <pre><code>subprocess.check_output('time ls',stderr=subprocess.STDOUT,shell=True) </code></pre> <p>this is giving me the output (which is /usr/bin/time output):</p> <pre><code>0.00user 0.00system 0:00.00elapsed ?%CPU (0avgtext+0avgdata 1992maxresiden...
0
2016-10-11T10:16:48Z
39,999,562
<p>It is because <code>time</code> is a also a built in function in Bash. So you need to specify that you want to use Bash as your shell:</p> <pre><code>print subprocess.check_output('time ls', stderr=subprocess.STDOUT,\ shell=True, executable='/bin/bash') </code></pre>
2
2016-10-12T13:14:50Z
[ "python", "linux", "shell", "time", "subprocess" ]
deleting printed line from screen
39,975,187
<p>I have code that runs for various lengths of time, during which a thread runs and displays a spinning cursor. When the code finishes it's task it prints some output, sets an event and the cursor stops. However this leaves the last character that was printed on the screen. I would like this to be removed.</p> <pre><...
2
2016-10-11T10:21:48Z
39,997,927
<p>The problem is that the main thread does not wait for the <em>spinning_cursor</em> one. So here is what happens (I could reproduce it):</p> <pre><code>main | spinning --------------------------------------------------------------------------- starts spinning thread ...
1
2016-10-12T11:52:17Z
[ "python", "multithreading" ]
How to access the value of a ctypes.LP_c_char pointer?
39,975,430
<p>I have defined a struct : </p> <pre><code>class FILE_HANDLE(Structure): _fields_ = [ ("handle_bytes", c_uint), ("handle_type", c_int), ("f_handle", POINTER(c_char)) ] </code></pre> <p>The struct is initialised :</p> <pre><code>buf = create_string_buffer(f_handle.handle_bytes) fh = FILE_HANDLE(c_uint(8...
0
2016-10-11T10:38:32Z
40,028,465
<p>fh.f_handle is shown as LP_c_char because you defined the struct that way.</p> <pre><code>buf = create_string_buffer(8) print type(buf) fh = FILE_HANDLE(c_uint(8), c_int(0), buf) print type(fh.f_handle) </code></pre> <p>Will output</p> <pre><code>&lt;class 'ctypes.c_char_Array_8'&gt; &lt;class 'ctypes.LP_c_char'&...
0
2016-10-13T18:33:08Z
[ "python", "ctypes" ]
How to access the value of a ctypes.LP_c_char pointer?
39,975,430
<p>I have defined a struct : </p> <pre><code>class FILE_HANDLE(Structure): _fields_ = [ ("handle_bytes", c_uint), ("handle_type", c_int), ("f_handle", POINTER(c_char)) ] </code></pre> <p>The struct is initialised :</p> <pre><code>buf = create_string_buffer(f_handle.handle_bytes) fh = FILE_HANDLE(c_uint(8...
0
2016-10-11T10:38:32Z
40,048,004
<p>Everything actually looks right for what you've shown, but without seeing the explicit C definition of the structure and function you are calling it is difficult to see the problem.</p> <p>Here's an example that works with what you have shown. I inferred what the C definitions <em>should</em> be from what you have...
0
2016-10-14T16:33:51Z
[ "python", "ctypes" ]
How to determine number of function/builtin/callable parameters programmatically?
39,975,486
<p>I want to be able to classify an unknown function/builtin/callable based on its number of arguments.</p> <p>I may write a piece of code like that:</p> <pre><code>if numberOfParameters(f) == 0: noParameters.append(f) elif numberOfParameters(f) == 1: oneParameter.append(f) else: manyParameters.append(f) ...
1
2016-10-11T10:41:18Z
39,975,814
<p>From Python 3.3</p> <blockquote> <p>New in version 3.3.</p> </blockquote> <p><a href="https://docs.python.org/3/library/inspect.html#introspecting-callables-with-the-signature-object" rel="nofollow"><strong>Introspecting callables with the Signature object</strong></a></p> <pre><code>&gt;&gt;&gt; import inspect...
1
2016-10-11T11:03:41Z
[ "python", "python-2.7", "function", "python-3.x", "callable" ]
How to determine number of function/builtin/callable parameters programmatically?
39,975,486
<p>I want to be able to classify an unknown function/builtin/callable based on its number of arguments.</p> <p>I may write a piece of code like that:</p> <pre><code>if numberOfParameters(f) == 0: noParameters.append(f) elif numberOfParameters(f) == 1: oneParameter.append(f) else: manyParameters.append(f) ...
1
2016-10-11T10:41:18Z
39,976,055
<p>You can somewhat do this, but only in Python 3. This is when <code>ArgumentClinic</code> made information about the signature of objects available.</p> <p>Take note, not all built-ins are actually available as of right now, currently:</p> <pre><code>__import__ vars max print dir __build_class__ min iter round geta...
0
2016-10-11T11:17:59Z
[ "python", "python-2.7", "function", "python-3.x", "callable" ]
Dynamically select from a dataframe using the values of another
39,975,528
<p>Using Pandas.py, I have csv of this format, which is dynamically created:</p> <pre><code>time,name,status 2016-10-09 00:15:50,10.0.0.24,REJECTED 2016-10-09 00:15:50,10.0.0.24,REJECTED 2016-10-09 00:15:54,10.0.0.24,accepted 2016-10-09 00:15:57,10.0.0.24,accepted 2016-10-09 00:15:58,10.0.0.103,accepted 2016-10-09 00:...
1
2016-10-11T10:43:54Z
39,979,180
<p><strong><em>assumed imports</em></strong></p> <pre><code>import pandas as pd import numpy as np </code></pre> <p><strong><em>general solution</em></strong><br> for more than 2 types of status</p> <pre><code>g = df.groupby('name') pd.concat([ g.status.size().rename(''), g.time.last().rename(''), ...
0
2016-10-11T14:08:32Z
[ "python", "csv", "pandas" ]
How get a fragment of the code from External HTML (web site) with python
39,975,555
<p>i want to get a fragment from a HTML website with pithon.</p> <p>for example from the url <a href="http://steven-universe.wikia.com/wiki/Steven_Universe_Wiki" rel="nofollow">http://steven-universe.wikia.com/wiki/Steven_Universe_Wiki</a> i want to get the text in the box "next Episode", as a string , how can i get i...
-3
2016-10-11T10:45:04Z
39,976,110
<p>First of all download BeautifulSoup latest version from <a href="https://pypi.python.org/pypi/beautifulsoup4" rel="nofollow">here</a> and requests from <a href="http://docs.python-requests.org/en/master/" rel="nofollow">here</a> </p> <pre><code>from bs4 import BeautifulSoup import requests con = requests.get(url)....
0
2016-10-11T11:21:08Z
[ "python", "html" ]
Python 27: How to fix/store a value to a method to preserve its interface?
39,975,659
<p>If everything is an object in python then why does the following not work?</p> <pre><code>class Hello(object): def hello(self): print(x) h = Hello() h.hello.x = "hello world" </code></pre> <p>When doing this I get:</p> <pre><code>AttributeError: 'instancemethod' object has no attribute 'value' </cod...
0
2016-10-11T10:52:37Z
39,975,790
<p>The <code>x</code> in the first version is not defined: the way you write the code, it should be a global variable; the way you use it, it should be an attribute of the object. You want to do something like</p> <pre><code>class Hello(object): def __init__(self, x): self.x = x def hello(self): ...
-1
2016-10-11T11:01:38Z
[ "python", "python-2.7" ]
Python 27: How to fix/store a value to a method to preserve its interface?
39,975,659
<p>If everything is an object in python then why does the following not work?</p> <pre><code>class Hello(object): def hello(self): print(x) h = Hello() h.hello.x = "hello world" </code></pre> <p>When doing this I get:</p> <pre><code>AttributeError: 'instancemethod' object has no attribute 'value' </cod...
0
2016-10-11T10:52:37Z
39,975,900
<p><strong>This answer was referring to the question before it was editet; it might not be appropriate anymore.</strong></p> <p>Actually, there is a solution to this question. In python 3, you can directly assign attributes to bound methods, whereas in python 2.7 it is not that straightforward.</p> <p>Look at a class...
4
2016-10-11T11:09:23Z
[ "python", "python-2.7" ]
Python 27: How to fix/store a value to a method to preserve its interface?
39,975,659
<p>If everything is an object in python then why does the following not work?</p> <pre><code>class Hello(object): def hello(self): print(x) h = Hello() h.hello.x = "hello world" </code></pre> <p>When doing this I get:</p> <pre><code>AttributeError: 'instancemethod' object has no attribute 'value' </cod...
0
2016-10-11T10:52:37Z
39,976,593
<p>After your edit, this seems to me as if you seek a possibility to <em>route</em> certain events to certain functions, right?</p> <p>Instead of binding new attributes to existing <em>instance methods</em>, you should think about setting up a clean and extendable event routing system.</p> <h2>A Basic Routing Core</h...
2
2016-10-11T11:49:04Z
[ "python", "python-2.7" ]
Competitive Programming Python: Repeated sum of digits Error
39,975,692
<p>Don't know It's right place to ask this or not. But I was feeling completely stuck. Couldn't find better way to solve it.</p> <p>I am newbie in competitive Programming. I was solving <code>Repeated sum of digits problem</code> Here is The Question.</p> <p><code>Given an integer N, recursively sum digits of N until...
2
2016-10-11T10:54:47Z
39,976,109
<p>You have not implemented the code properly. You are iterating over <code>i</code> from <code>0</code> to <code>t</code>. Why?? The methodology goes as follows:</p> <p><code>N = 12345</code></p> <p>Calculate the sum of digits(1+2+3+4+5 = 15).</p> <p>Check if it is less than 10. If so, then the current sum is the a...
2
2016-10-11T11:21:08Z
[ "python" ]
undefined symbol: PyOS_mystrnicmp
39,975,712
<p>I tried installing <code>pysqlite</code>, but I'm having some trouble using it.</p> <pre><code>&gt;&gt;&gt; import pysqlite2.dbapi2 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/data/.pyenv/versions/2.7.5/lib/python2.7/site-packages/pysqlite2/dbapi2.py", line 28, in &...
0
2016-10-11T10:56:08Z
39,995,741
<p>As <a href="https://groups.google.com/forum/#!topic/python-sqlite/04Ocf7aP1so" rel="nofollow">https://groups.google.com/forum/#!topic/python-sqlite/04Ocf7aP1so</a> points out, a <a href="http://bugs.python.org/issue18603" rel="nofollow">bug</a> was reported that appears to be fixed in newer versions of Python. Upgra...
0
2016-10-12T09:57:25Z
[ "python", "cpython" ]
pandas ewm and rolling methods to not fill in NAs
39,975,812
<p>Is there a parameter for ewm and rolling methods to not fill in the NAs?</p> <pre><code>&gt;&gt;&gt; A = pd.Series([1,2,3,4,np.nan,5,6]) &gt;&gt;&gt; A 0 1.0 1 2.0 2 3.0 3 4.0 4 NaN 5 5.0 6 6.0 dtype: float64 &gt;&gt;&gt; eA = A.ewm(alpha = 0.5, ignore_na=True).mean() &gt;&gt;&gt; eA 0 1.000...
1
2016-10-11T11:03:35Z
39,977,211
<p>Unfortunately this currently isn't supported in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.ewm.html#pandas.Series.ewm" rel="nofollow"><code>ewm</code></a>, you'd have to overwrite with <code>NaN</code> using your proposed method or filter our the <code>NaN</code> rows so that <code>...
1
2016-10-11T12:25:54Z
[ "python", "pandas" ]
Handling accents in Oracle from Python
39,975,885
<p>I have the following code:</p> <pre><code> #!/usr/bin/python # coding=UTF-8 import cx_Oracle def oracle_connection(user, passwd, host, port, service): oracle_con_details = user+'/'+passwd+'@'+host+':'+port+'/'+service try: oracle_connection = cx_Oracle.connect(oracle_con_details) except c...
1
2016-10-11T11:08:20Z
40,016,537
<p>Adding this to my python code solved it. </p> <pre><code>import os os.environ["NLS_LANG"] = "SPANISH_SPAIN.UTF8" </code></pre>
1
2016-10-13T08:58:45Z
[ "python", "oracle", "unicode", "ascii" ]
Error ValueError: cannot reindex from a duplicate axis because of concatenating dataframes
39,975,957
<p>I implemented experimental environment in my project. </p> <p>This component is based on Scikit learn. </p> <p>In this compnent I read the given CSV into pandas dataframe. After that I selected the best features and reduced the dimensions of the given dataframe from 100 to 5. After that I added to this reduced d...
1
2016-10-11T11:12:11Z
40,014,731
<p>I found the problem:</p> <p>After the concatenation of the dataframes, the index is changed and when we add the row :</p> <pre><code>reduced_dataframe["Id"] = id_series </code></pre> <p>We got an error.</p> <p>The solution is to reset the index : </p> <pre><code>features_dataframe = pd.concat(dataframes, axis=0...
0
2016-10-13T07:23:58Z
[ "python", "csv", "scikit-learn" ]
Django Migrations - what benefits do they bring?
39,975,996
<p>I am pretty sure that <a href="https://docs.djangoproject.com/en/1.10/topics/migrations/" rel="nofollow">Django Migrations</a> bring many benefits to the Django platform. I am just having a hard time identifying those benefits.</p> <p>Maybe someone could explain to me in what circumstances Django Migrations can be ...
-3
2016-10-11T11:14:22Z
39,976,115
<p>The migrations make it easy to maintain database updates.</p> <p>You control the database through Django models. E.g. Add a field to one of the models.</p> <p>Then you can make migrations and migrate and these changes will be replicated in your SQL database by the addition of this field.</p>
1
2016-10-11T11:21:19Z
[ "python", "django" ]
Django Migrations - what benefits do they bring?
39,975,996
<p>I am pretty sure that <a href="https://docs.djangoproject.com/en/1.10/topics/migrations/" rel="nofollow">Django Migrations</a> bring many benefits to the Django platform. I am just having a hard time identifying those benefits.</p> <p>Maybe someone could explain to me in what circumstances Django Migrations can be ...
-3
2016-10-11T11:14:22Z
39,976,321
<p>Just as your code changes over time, so does your database layout. Models get new fields, your App gets new models etc.</p> <p>Your code can be changed and uploaded to your server, replacing old files.</p> <p>Your database however needs to persistent. You cannot just overwrite your database with a different one an...
2
2016-10-11T11:32:50Z
[ "python", "django" ]
Django Migrations - what benefits do they bring?
39,975,996
<p>I am pretty sure that <a href="https://docs.djangoproject.com/en/1.10/topics/migrations/" rel="nofollow">Django Migrations</a> bring many benefits to the Django platform. I am just having a hard time identifying those benefits.</p> <p>Maybe someone could explain to me in what circumstances Django Migrations can be ...
-3
2016-10-11T11:14:22Z
39,977,761
<p>You make some changes to your database, you:</p> <ul> <li>Change the default value of a field</li> <li>You update all user entries so that their "name" field begins with a capital letter</li> <li>You remove a model altogether</li> </ul> <p>So now you need to modify your database schema, get to it!</p> <p>Chances ...
0
2016-10-11T12:55:48Z
[ "python", "django" ]
Python Pillow: Make gradient for transparency
39,976,028
<p>I have code which add gradient on image.</p> <pre><code>def st(path, gradient_magnitude=2.): im = Image.open(path) if im.mode != 'RGBA': im = im.convert('RGBA') width, height = im.size gradient = Image.new('L', (width, 1), color=0xFF) for x in range(width): gradient.putpixel((x, ...
1
2016-10-11T11:16:03Z
39,980,957
<p>Try this. Initial opacity values of 0.9 or 0.95 should give you what you want. I also restructured the code a bit because it was a mess before. Whoever wrote the <a href="http://stackoverflow.com/questions/39842286/python-pillow-add-transparent-gradient-to-an-image/39857434?noredirect=1#comment67230721_39857434">pre...
1
2016-10-11T15:26:43Z
[ "python", "python-imaging-library", "pillow" ]
python continuing a loop from a specific index
39,976,073
<p>I wrote some code that uses enumerate to loop through a list.</p> <pre><code>for index, item in enumerate(list[start_idx:end_idx]) print('index [%d] item [%s]'%(str(index), item)) </code></pre> <p>the item in the list are just strings. Sometimes I do not want to enumerate for the whole list, sometimes I'll sl...
2
2016-10-11T11:19:09Z
39,976,119
<p>You can do:</p> <pre><code>for index, item in enumerate(list[4:]): print(str(index)) </code></pre>
0
2016-10-11T11:21:25Z
[ "python", "loops", "enumerate" ]
python continuing a loop from a specific index
39,976,073
<p>I wrote some code that uses enumerate to loop through a list.</p> <pre><code>for index, item in enumerate(list[start_idx:end_idx]) print('index [%d] item [%s]'%(str(index), item)) </code></pre> <p>the item in the list are just strings. Sometimes I do not want to enumerate for the whole list, sometimes I'll sl...
2
2016-10-11T11:19:09Z
39,976,147
<p>The <code>start</code> parameter of <code>enumerate</code> doesn't have anything to do with what elements of the iterable get selected. It just tells enumerate what number to start with.</p> <pre><code>&gt;&gt;&gt; list(enumerate(range(3))) [(0, 0), (1, 1), (2, 2)] &gt;&gt;&gt; list(enumerate(range(3), 1)) [(1, 0),...
1
2016-10-11T11:23:03Z
[ "python", "loops", "enumerate" ]
python continuing a loop from a specific index
39,976,073
<p>I wrote some code that uses enumerate to loop through a list.</p> <pre><code>for index, item in enumerate(list[start_idx:end_idx]) print('index [%d] item [%s]'%(str(index), item)) </code></pre> <p>the item in the list are just strings. Sometimes I do not want to enumerate for the whole list, sometimes I'll sl...
2
2016-10-11T11:19:09Z
39,976,254
<p>Actually if you got <code>range</code> object it's not a big deal to make a slice from it, because <code>range(n)[:4]</code> is still <code>range</code> object(<em>as @MosesKoledoye mentioned it's Python 3 feature</em>). But if you got a list, for the sake of not creating new list you can choose <a href="https://doc...
2
2016-10-11T11:28:54Z
[ "python", "loops", "enumerate" ]
How do you retrieve the cell row of a changed QComboBox as a QCellWidget of a QTableWidget?
39,976,078
<p>I am trying to get the row and column of a changed combobox in a QTableWidget. Here is how my table is set up. Look at the bottom to see what I am trying to do.</p> <pre><code>def click_btn_mailouts(self): self.cur.execute("""SELECT s.StudentID, s.FullName, m.PreviouslyMailed, m.nextMail, m.learnersDate, m.Res...
1
2016-10-11T11:19:23Z
39,987,228
<p>If I understand correctly, when attaching the signal <code>i</code> will be the value of the row that you want to send (or, maybe <code>i+1</code>?). You can easily send additional data with Qt signals, by using a wrapper function or <code>lambda</code> as follows:</p> <pre><code>for a in range(5): x = QComboBo...
0
2016-10-11T21:41:47Z
[ "python", "pyqt" ]
ssh connection in python
39,976,096
<p>I'm trying to read a text file from a server using ssh from python 3.5. I'm using paramiko to connect to the server but unfortunately, I'm having trouble actually connecting to the server.</p> <p>this is the code I'm using to connect to the server</p> <pre><code>import paramiko ssh = paramiko.SSHClient() ssh.set_m...
0
2016-10-11T11:20:02Z
39,976,380
<p>You should use your <strong>private</strong> key to connect to a remote server. Your <strong>public</strong> key must be already installed in the server side, i.e. it must be listed in <code>~/.ssh/authorized_keys</code>.</p> <p>Try first from the command line, and only then use Python/paramiko. Check the permissio...
2
2016-10-11T11:36:21Z
[ "python", "paramiko" ]
ssh connection in python
39,976,096
<p>I'm trying to read a text file from a server using ssh from python 3.5. I'm using paramiko to connect to the server but unfortunately, I'm having trouble actually connecting to the server.</p> <p>this is the code I'm using to connect to the server</p> <pre><code>import paramiko ssh = paramiko.SSHClient() ssh.set_m...
0
2016-10-11T11:20:02Z
39,977,142
<p>Turns out I simply just forgot to add in the username in the connection string. works perfectly now.</p>
0
2016-10-11T12:21:54Z
[ "python", "paramiko" ]
Find all occurences of inner text in an xml file with etree
39,976,302
<p>I am new to python and trees at all, and have encountered some problems.</p> <p>I have the following dataset structured as:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;graphml xmlns="http://graphml.graphdrawing.org/xmlns"&gt; &lt;node id="node1"&gt; &lt;data key="label"&gt;node1&lt;/data&...
1
2016-10-11T11:32:03Z
39,976,781
<p>You probably forget the namespace. Try something like this:</p> <pre><code>import xml.etree.ElementTree as ET root = ET.fromstring(countrydata) ns = {'graphml': 'http://graphml.graphdrawing.org/xmlns'} for element in root.findall(".//graphml:node[@id]",ns): print(element.attrib['id']) </code></pre>
0
2016-10-11T12:00:57Z
[ "python", "xml", "xpath", "tree", "elementtree" ]
Find all occurences of inner text in an xml file with etree
39,976,302
<p>I am new to python and trees at all, and have encountered some problems.</p> <p>I have the following dataset structured as:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;graphml xmlns="http://graphml.graphdrawing.org/xmlns"&gt; &lt;node id="node1"&gt; &lt;data key="label"&gt;node1&lt;/data&...
1
2016-10-11T11:32:03Z
39,976,806
<p>This does the job on python 2.7 :</p> <pre><code>import xml.etree.ElementTree as ET root = ET.fromstring(data) elts = root.findall('.//*[@key="label"]') for e in elts: print(e.text) </code></pre>
0
2016-10-11T12:02:14Z
[ "python", "xml", "xpath", "tree", "elementtree" ]
Pandas Slow. Want first occurrence in DataFrame
39,976,348
<p>I have a DataFrame of <code>people</code>. One of the columns in this DataFrame is a <code>place_id</code>. I also have a DataFrame of places, where one of the columns is <code>place_id</code> and another is <code>weather</code>. For every person, I am trying to find the corresponding weather. Importantly, many peop...
4
2016-10-11T11:34:07Z
39,976,539
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow"><code>drop_duplicates</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a>, if there is only common ...
2
2016-10-11T11:45:50Z
[ "python", "pandas" ]
Pandas Slow. Want first occurrence in DataFrame
39,976,348
<p>I have a DataFrame of <code>people</code>. One of the columns in this DataFrame is a <code>place_id</code>. I also have a DataFrame of places, where one of the columns is <code>place_id</code> and another is <code>weather</code>. For every person, I am trying to find the corresponding weather. Importantly, many peop...
4
2016-10-11T11:34:07Z
39,976,650
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow"><code>merge</code></a> to do the operation :</p> <pre><code>people = pd.DataFrame([['bob', 1], ['alice', 2], ['john', 3], ['paul', 2]], columns=['name', 'place']) # name place #0 bob 1...
0
2016-10-11T11:52:56Z
[ "python", "pandas" ]
Pandas Slow. Want first occurrence in DataFrame
39,976,348
<p>I have a DataFrame of <code>people</code>. One of the columns in this DataFrame is a <code>place_id</code>. I also have a DataFrame of places, where one of the columns is <code>place_id</code> and another is <code>weather</code>. For every person, I am trying to find the corresponding weather. Importantly, many peop...
4
2016-10-11T11:34:07Z
39,984,155
<p>The map function is your quickest method, the purpose of which is to avoid calling an entire dataframe to run some function repeatedly. This is what you ended up doing in your function i.e. calling an entire dataframe which is fine but not good doing it repeatedly. To tweak your code just a little will significantly...
1
2016-10-11T18:26:06Z
[ "python", "pandas" ]
Django UpdateView create new object
39,976,361
<p>My problem: UpdateView create new object instead of updating previous, i think its happens because in class definition of my view i override get_object method like this:</p> <pre><code>def get_object(self, queryset=None): try: object_get = self.model.objects.get(pk=self.kwargs['pk']) except ObjectDo...
1
2016-10-11T11:35:13Z
39,976,485
<p>In <code>UpdateView</code>, if <code>get_object</code> returns <code>None</code> django will create a new object.So instead of return <code>None</code> do whatever you want.</p> <pre><code>def get_object(self, queryset=None): try: object_get = self.model.objects.get(pk=self.kwargs['pk']) except Obje...
3
2016-10-11T11:43:28Z
[ "python", "django", "django-class-based-views" ]
Trying to iterate through XML : can't get subnode's values
39,976,405
<p>I need to process a huge file with many nodes structured likes this</p> <pre><code>&lt;category name="28931778o.rjpf"&gt; &lt;name&gt;RequestedName&lt;/name&gt; &lt;root&gt;0&lt;/root&gt; &lt;online&gt;1&lt;/online&gt; &lt;description xml:lang="pt-PT"&gt;mydescription &lt;/description&gt; &lt;category-links/&gt; &l...
2
2016-10-11T11:38:23Z
39,982,812
<p>You are right Dopstar ! Many thanks</p> <pre><code>for elem in tree.iterfind('{http://www.cc.com/a}category'): requestedName = elem.find('{http://www.cc.com/a}name').text print requestedName Requestedsortkey = elem.find('{http://www.cc.com/a}custom-attributes/{http://www.cc.com/a}custom-attribute[@name="s...
0
2016-10-11T17:07:14Z
[ "python", "xml-parsing", "lxml", "elementtree" ]
Python Kivy language color property
39,976,475
<p>Does Kivy language support hex color values such as </p> <blockquote> <p><strong>#F05F40</strong></p> </blockquote> <p>Thanks very much in advance! </p>
0
2016-10-11T11:42:46Z
39,977,810
<p>Kivy has <code>utils</code> module with <a href="https://kivy.org/docs/api-kivy.utils.html#kivy.utils.get_color_from_hex" rel="nofollow">get_color_from_hex</a> function that do job:</p> <pre><code>#:import utils kivy.utils &lt;Widget&gt;: canvas.before: Color: rgb: utils.get_color_from_hex...
0
2016-10-11T12:58:27Z
[ "python", "kivy" ]
random circles using SimpleGraphics
39,976,596
<p>I need to make a circle by adjusting conditions on the heights, this program using a lot of random circles but I am unsure where to go from here? I am trying to use the following equation d = (sqrt)((x1 –x2)^2 +(y1 – y2)^2). Right now the program draws many random circles, so adjusting the formula i should be ab...
2
2016-10-11T11:49:14Z
39,977,483
<p>Here's some code that endlessly draws circles. Circles that are close to the centre of the screen will be drawn in red, all other circles will be drawn in white. Eventually, this will create an image similar to the flag of Japan, although the edge of the inner red "circle" will not be smooth.</p> <p>I have not test...
0
2016-10-11T12:41:14Z
[ "python", "python-3.x", "graphics" ]
Python 3.5.2 logger configuration and usage
39,976,715
<p>I'm new to python and trying to setup a logger in my simple app.</p> <p>This is the app structure:</p> <pre><code> - checker - checking - proxy_checker.py - custom_threading - __init__.py - executor_my.py - long_task.py - tests - __init__.py - loggi...
4
2016-10-11T11:57:16Z
39,978,648
<p>My (possibly wrong :-) guess is that you start the script by something like <code>python checker/main.py</code>, thus the logging configuration in <code>__init__.py</code> is not executed.</p> <p>Please, take a look at this answer: <a href="http://stackoverflow.com/questions/7533480/why-is-init-py-not-being-called"...
1
2016-10-11T13:41:04Z
[ "python", "python-3.x", "logging" ]
Deep autoencoder in Keras converting one dimension to another i
39,976,718
<p>I am doing an image captioning task using vectors for representing both images and captions. </p> <p>The caption vectors have a legth/dimension of size 128. The image vectors have a length/dimension of size 2048.</p> <p>What I want to do is to train an autoencoder, to get an encoder which is able to convert text v...
1
2016-10-11T11:57:36Z
39,998,476
<h1>Autoencoders</h1> <p>If you want is to be able to call the <code>encoder</code> and <code>decoder</code> separately, what you need to do is train the whole autoencoder exactly as per the tutorial, with <code>input_shape == output_shape</code> (<code>== 128</code> in your case), and only then can you call a subset ...
1
2016-10-12T12:20:33Z
[ "python", "vector", "neural-network", "keras", "autoencoder" ]
In Python, what's the difference between deepcopy and [each[:] for each in List]
39,976,742
<p>Below is the example code:</p> <pre><code>from copy import deepcopy List = [range(3), range(3), range(3)] a = deepcopy(List) b = [each[:] for each in List] </code></pre> <p>I know the time required to initialize a is slower than b's time, but why does this happen? What's the difference between deepcopy and [each[...
0
2016-10-11T11:58:42Z
39,976,760
<p><code>each[:]</code> creates a <em>shallow</em> copy of each nested list. <code>copy.deepcopy()</code> would make a <em>deep</em> copy.</p> <p>In this specific case, where your nested lists contain immutable integers, this difference doesn't actually matter; <code>deepcopy()</code> returns the integer unchanged whe...
6
2016-10-11T12:00:03Z
[ "python", "list", "copy", "deep-copy" ]
In Python, what's the difference between deepcopy and [each[:] for each in List]
39,976,742
<p>Below is the example code:</p> <pre><code>from copy import deepcopy List = [range(3), range(3), range(3)] a = deepcopy(List) b = [each[:] for each in List] </code></pre> <p>I know the time required to initialize a is slower than b's time, but why does this happen? What's the difference between deepcopy and [each[...
0
2016-10-11T11:58:42Z
39,980,594
<p>As Martijn Pieters said each[:] will perform by creating a shallow copy of each nested list. If your list elements are immutable objects then you can use this, otherwise you have to use deepcopy from copy module.</p> <p>It's possible to completely copy shallow list structures with the slice operator without having ...
1
2016-10-11T15:11:04Z
[ "python", "list", "copy", "deep-copy" ]
How do I shorten this if possible?
39,976,778
<p>Well, here's my code</p> <pre><code>import time import random Dice = input("Would you like to roll the dice?(y/n)") if Dice == "y": roll = random.randint(1,6) print("You have rolled a", roll) again = input("Would you like to roll again?(y/n)") while again == "y": roll2 = random.randi...
-4
2016-10-11T12:00:41Z
39,976,904
<p>I feel like doing someones homework. But here you go, a shortened version of your code (untested).</p> <pre><code>import time import random dice = input("Would you like to roll the dice?(y/n)") while dice == "y": print( "You have rolled a %s" % (random.randint(1,6))) dice = input("would you like to roll a...
2
2016-10-11T12:08:11Z
[ "python", "python-3.x" ]
How do I shorten this if possible?
39,976,778
<p>Well, here's my code</p> <pre><code>import time import random Dice = input("Would you like to roll the dice?(y/n)") if Dice == "y": roll = random.randint(1,6) print("You have rolled a", roll) again = input("Would you like to roll again?(y/n)") while again == "y": roll2 = random.randi...
-4
2016-10-11T12:00:41Z
39,976,968
<pre><code>import random while input('RTD? (y/n) ') == 'y': print('Rolled {}.'.format(random.randint(1, 6))) </code></pre>
4
2016-10-11T12:11:45Z
[ "python", "python-3.x" ]
How do I shorten this if possible?
39,976,778
<p>Well, here's my code</p> <pre><code>import time import random Dice = input("Would you like to roll the dice?(y/n)") if Dice == "y": roll = random.randint(1,6) print("You have rolled a", roll) again = input("Would you like to roll again?(y/n)") while again == "y": roll2 = random.randi...
-4
2016-10-11T12:00:41Z
39,976,981
<pre><code>import time import random while input("Would you like to roll the dice? (y/n) ") == 'y': roll = random.randint(1,6) print("You have rolled a", roll) print("Goodbye") time.sleep(1) </code></pre>
0
2016-10-11T12:12:23Z
[ "python", "python-3.x" ]
How do I shorten this if possible?
39,976,778
<p>Well, here's my code</p> <pre><code>import time import random Dice = input("Would you like to roll the dice?(y/n)") if Dice == "y": roll = random.randint(1,6) print("You have rolled a", roll) again = input("Would you like to roll again?(y/n)") while again == "y": roll2 = random.randi...
-4
2016-10-11T12:00:41Z
39,976,997
<p>Use while loop:</p> <pre><code>import time import random Dice = raw_input("Would you like to roll the dice?(y/n)") while Dice.lower() == "y": roll = random.randint(1, 6) print("You have rolled a ", roll) Dice = raw_input("Would you like to roll again?(y/n)") time.sleep(1) print("Goodbye") </code></pre...
0
2016-10-11T12:13:01Z
[ "python", "python-3.x" ]
Python Selenium IE - Clicking on an anchor does not change the URL
39,976,869
<h2>As Short As Possible</h2> <p>I am trying to do test automation using Python with py.test and Selenium.</p> <p>I have tried two approaches to change the URL by clicking an anchor <code>&lt;a&gt;</code> element, neither of the approaches seems to work - the URL does not change.</p> <p>There are no errors reported,...
2
2016-10-11T12:06:00Z
39,980,754
<p>If you've tried all but nothing get success, you can try using <a href="http://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webdriver.WebDriver.execute_script" rel="nofollow"><code>WebDriver#execute_script()</code></a> as an alternate solution where you can execute some piece of <code>JavaScript...
-1
2016-10-11T15:18:14Z
[ "python", "internet-explorer", "selenium-webdriver", "automated-tests", "anchor" ]
Unable to reliabily Match Base 64 encrypted String from strings stored in a Website: Python Program
39,977,069
<p>I am Rishabh and am a beginner in Python Programming Language.. I have attempted to write a sort of an Authentication Program using Python. </p> <p><strong>Here's What I am doing in my Program:</strong></p> <ol> <li>I get the Username and Password</li> <li>I concatenate the two strings like : ###Username:::Passwor...
3
2016-10-11T12:17:31Z
39,979,998
<p>The problem is because you use <code>re</code> and you have <code>+</code> in <code>encodec</code>. <code>re</code> treats <code>+</code> in special way so ie. <code>1+2</code> is searching <code>12 or 112 or 1112 etc.</code></p> <p>Use <code>html_content.find(encoded)</code> which returns position of <code>encodec...
1
2016-10-11T14:45:18Z
[ "python", "regex", "encryption", "beautifulsoup", "base64" ]
Split and Merge data in a bunch of csv-files in a directory
39,977,119
<p>I have many .csv files in a directory, coming from an energy measurement device that stores its files every two seconds. Each file looks similar to that:</p> <pre><code>Position,Date,Time,V12,Unit,V23,Unit,V31,Unit,A1,Unit,A2,Unit,A3,Unit,P(SUM),Unit,S(SUM),Unit,Q(SUM),Unit,PF(SUM),Unit,PFH,Unit,WH,Unit,SH,Unit,QH,...
-1
2016-10-11T12:20:10Z
39,977,534
<p>The following approach should get you started:</p> <pre><code>from datetime import datetime from collections import defaultdict import csv import glob days = defaultdict(list) for filename in glob.glob('*.csv'): with open(filename, 'rb') as f_input: csv_input = csv.reader(f_input) header = nex...
2
2016-10-11T12:43:46Z
[ "python", "windows", "csv", "scripting" ]
Implement Bhattacharyya loss function using python layer Caffe
39,977,133
<p>Trying to implement my custom loss layer using python layer,caffe. I've used this <a href="https://github.com/BVLC/caffe/blob/master/examples/pycaffe/layers/pyloss.py" rel="nofollow">example</a> as the guide and have wrote the <code>forward</code> function as follow:</p> <pre><code> def forward(self,bottom,top):...
0
2016-10-11T12:21:00Z
40,137,336
<p>Lets say bottom[0].data is p, bottom[1].data is q and Db(p,q) denotes the Bhattacharyya Distance between p and q.</p> <p>The only thing you need to do in your backward function is to compute the partial derivatives of Db with respect to its inputs (p and q) and store them in the respective bottom diff blobs:</p> <...
0
2016-10-19T16:52:48Z
[ "python", "python-2.7", "caffe", "pycaffe" ]
How to read from an excel sheet using pythons xlrd module
39,977,141
<p>I have the following code. What am I trying to do is screenscrape a website and then write the data to an excel worksheet. I can't read the existing data from excel file.</p> <pre><code>import xlwt import xlrd from xlutils.copy import copy from datetime import datetime import urllib.request from bs4 import Beautifu...
0
2016-10-11T12:21:48Z
39,977,418
<p>Is that what you are looking for ? Going through all col.?</p> <pre><code>xl_workbook = xlrd.open_workbook num_cols = xl_sheet.ncols for row_idx in range(0, xl_sheet.nrows): </code></pre>
0
2016-10-11T12:38:03Z
[ "python", "excel", "xlrd", "xlwt" ]
Python: Confusing example of Functions as Objects
39,977,166
<p>When I was reasearching a bit about decorators, I stumbled upon some rather confusing code that i found perplexing in the way that it passes varibles and functions.</p> <pre><code>def get_text(name): return "lorem ipsum, {0} dolor sit amet".format(name) def p_decorate(func): def func_wrapper(name): ...
0
2016-10-11T12:23:03Z
39,977,329
<p>This is a demonstration of how decorators work: They basically wrap the decorated function into another internal function and return its reference.</p> <ol> <li>In your example, the call <code>my_get_text = p_decorate(get_text)</code> calls the function <code>p_decorate</code> with the wrappable function as a param...
2
2016-10-11T12:32:34Z
[ "python", "function", "variables", "python-decorators" ]
What function is func here? Where did it come from?
39,977,187
<p>This is my code:</p> <pre><code>def testit(func, *nkwargs, **kwargs): try: retval = func(*nkwargs, **kwargs) result = (True, retval) except Exception, diag: result = (False, str(diag)) return result def test(): funcs = (int, long, float) vals = (1234, 12.34, '1234',...
-2
2016-10-11T12:24:19Z
39,977,260
<p>Python functions are first-class objects. This means you can assign such an object to a variable and pass it to another function. The very act of executing a <code>def functionname(): ...</code> statement assigns such an object to a name (<code>functionname</code> here):</p> <pre><code>&gt;&gt;&gt; def foo(): retur...
0
2016-10-11T12:28:34Z
[ "python", "function" ]
Why doesn't warp function in Python get executed when I call it?
39,977,254
<p>I have this simple code.</p> <pre><code>def decor(func): def wrap(): print("============") func() print("============") return wrap def print_text(): print("Hello world!") decor(print_text()) </code></pre> <p>Why does this only print "Hello world!" and not the two wrappers? </p>
0
2016-10-11T12:28:19Z
39,977,342
<p>Here you are evaluating <code>print_text</code> (thus printing "Hello World!"), and passing the result to <code>decor</code>:</p> <pre><code>decor(print_text()) </code></pre> <p>Here we are passing <code>print_text</code> to <code>decor</code>, and calling the resulting function which it returns, which is <code>wr...
0
2016-10-11T12:33:07Z
[ "python", "wrap" ]
Why doesn't warp function in Python get executed when I call it?
39,977,254
<p>I have this simple code.</p> <pre><code>def decor(func): def wrap(): print("============") func() print("============") return wrap def print_text(): print("Hello world!") decor(print_text()) </code></pre> <p>Why does this only print "Hello world!" and not the two wrappers? </p>
0
2016-10-11T12:28:19Z
39,977,379
<p>That is because you only return the function wrap - It is not called. If you do call it, either by assigning the result to a variable, or by using <code>decor(print_text)()</code> directly. Note that you should use <code>print_text</code> and not <code>print_text()</code>, as the latter will give the result of the f...
0
2016-10-11T12:35:22Z
[ "python", "wrap" ]
Why doesn't warp function in Python get executed when I call it?
39,977,254
<p>I have this simple code.</p> <pre><code>def decor(func): def wrap(): print("============") func() print("============") return wrap def print_text(): print("Hello world!") decor(print_text()) </code></pre> <p>Why does this only print "Hello world!" and not the two wrappers? </p>
0
2016-10-11T12:28:19Z
39,977,387
<p>You are calling <code>decor</code> with a single argument. That argument is whatever <code>print_text()</code> returns. Well, <code>print_text()</code> prints something and then returns None. So far, your output is just <code>Hello world!</code>. None is now passed to <code>decor</code>, and it returns the <code...
0
2016-10-11T12:35:55Z
[ "python", "wrap" ]
Change value property of Circular gauge
39,977,266
<p>Hi I know this is a old and easy question, but I really dont get it. How can I change the value property of my circular gauge dynamicly from python to the qml file? I tried alot but standing again at the beginning. Because I am very new to QT and Python can somebody explain me how to do? I copied the qml and the emp...
1
2016-10-11T12:28:50Z
40,047,920
<p>I am unfortunately not able to help you with the Python syntax but this is how that would look in C++</p> <pre><code>class Celsius : public QObject { Q_OBJECT Q_PROPERTY(double temperature READ temperature WRITE setTemperature NOTIFY temperatureChanged) public: explicit Celsius(double temperature = 0.6...
0
2016-10-14T16:27:29Z
[ "python", "qt", "pyqt5", "circular", "gauge" ]
Change value property of Circular gauge
39,977,266
<p>Hi I know this is a old and easy question, but I really dont get it. How can I change the value property of my circular gauge dynamicly from python to the qml file? I tried alot but standing again at the beginning. Because I am very new to QT and Python can somebody explain me how to do? I copied the qml and the emp...
1
2016-10-11T12:28:50Z
40,088,966
<p>For anybode having the same problem, I found out, here is the code which seems to go right, thanks a lot for all the helping:</p> <pre><code>class Celsius(QObject): def __init__(self, parent=None): super().__init__(parent) self.temperature = 0.3 @pyqtProperty(int) def temperature(s...
0
2016-10-17T14:24:12Z
[ "python", "qt", "pyqt5", "circular", "gauge" ]
SQLAlchemy: How to properly use Relationship()?
39,977,367
<p>I went through the docs, and <strong>think</strong> I've structured everything correctly, but struggling to implement it. </p> <p>There's two pieces to this: The use case is when I look at a resume, each resume has multiple jobs. Then the sum of all of those jobs determines the value of the entire resume. </p> <p>...
2
2016-10-11T12:34:47Z
39,977,944
<p>I struggled with this in my early days of using sqlalchemy.</p> <p>As stated in the docs:</p> <blockquote> <p>Takes a string name and has the same meaning as backref, except the complementing property is not created automatically, and instead must be configured explicitly on the other mapper. The complementing p...
0
2016-10-11T13:05:59Z
[ "python" ]
how to use for loop to create right angled triangle?
39,977,395
<pre><code>I want to print : 1 12 123 1234 </code></pre> <p>and i have tried:</p> <pre><code>num=int(input("number")) space=int(num) count=1 while count&lt;num: if count==1: print(" "*space,count) count=count+1 space=space-1 while count&gt;=2: for n in range(2,num): print(" "...
-3
2016-10-11T12:36:32Z
39,978,230
<pre><code>print(" "*space,list(range(1,n)) </code></pre> <p>Count the parentheses on this line. One of them isn't closed, which it has to be to work as you intend. </p> <p>Also note that your <code>while</code> loop will never stop running.</p> <p>As a general rule of thumb, whenever you know exactly how many time...
0
2016-10-11T13:19:52Z
[ "python" ]
List dictionaries in documentation with Sphinx
39,977,507
<p>I have a project with a few .py files that only contains a few dictionaries. Like this:</p> <pre><code># My file dictionary = {'key1': 'value1', 'key2: 'value2'} </code></pre> <p>But much larger and longer and I would like to document this with Sphinx but I can't get it to work properly. </p> <p>The files are fou...
0
2016-10-11T12:42:33Z
39,977,606
<p>Sphinx does require extra docstrings for all members that are not classes or methods. You probably don't want to edit <code>autodoc</code> (even though this can come handy for individualization under certain conditions), you can overcome this issue by adding a docstring <strong>below</strong> the variable:</p> <pre...
1
2016-10-11T12:47:34Z
[ "python", "dictionary", "documentation", "python-sphinx", "autodoc" ]
Python TCP socket.error with long messages
39,977,583
<p>I'm trying to send a basic message across my LAN network via TCP in Python. TCPClient.py:</p> <pre><code>import socket, sys, time TCP_IP = "10.0.0.10" TCP_PORT = 5005 BUFFER_SIZE = 1024 running = True while running == True: try: MESSAGE = raw_input("Message: ") s = socket.socket(socket.AF_INE...
0
2016-10-11T12:46:11Z
39,978,067
<p>Here's what happened: </p> <ol> <li>your client sent long line</li> <li>your server got 20 characters of that long line (that's size of your buffer on server side)</li> <li>your server sent back data (20 characters of line) to client</li> <li>your client got data and disconnected from server, causing server to rais...
0
2016-10-11T13:11:50Z
[ "python", "sockets", "tcp" ]
Apply a map to DataFrame rows which are NaN
39,977,656
<p>I want to apply a mapping to a Pandas DataFrame, where some rows in one specific column are <code>NaN</code>. These are left overs from a prior mapping.</p> <pre><code>mymap = defaultdict(str) mymap["a"] = "-1 test" mymap["b"] = "-2 test" mymap["c"] = "-3 test" df[ df["my_infos"].isnull() ] = df["something"].map(l...
2
2016-10-11T12:50:34Z
39,977,771
<p>I think you can select <code>NaN</code> values to both sides and then <code>map</code>:</p> <pre><code>df[ df["my_infos"].isnull() ] = df.ix[ df["my_infos"].isnull(), "something"].map(lambda ip: map_function(ip, mymap)) </code></pre>
1
2016-10-11T12:56:05Z
[ "python", "pandas" ]
Twisted threading and Thread Pool Difference
39,977,750
<p>What is the difference between using</p> <pre><code>from twisted.internet import reactor, threads </code></pre> <p>and just using</p> <pre><code>import thread </code></pre> <p>using a thread pool?</p> <p>What is the twisted thing actually doing? Also, is it safe to use twisted threads?</p>
0
2016-10-11T12:55:11Z
39,982,780
<blockquote> <p>What is the difference</p> </blockquote> <p>With <code>twisted.internet.threads</code>, Twisted will manage the thread and a thread pool for you. This puts less of a burden on devs and allows devs to focus more on the business logic instead of dealing with the idiosyncrasies of threaded code. If you ...
0
2016-10-11T17:04:59Z
[ "python", "multithreading", "security", "threadpool", "twisted" ]
python: grab a specific line after a match
39,977,812
<p>I have have df full of text<br> I would like to define variable <strong>date</strong> which is always three lines after <strong>version</strong>. here is my code</p> <pre><code>with open(input_file1,'r') as f: for i, line in enumerate(f): if line.startswith('Version'): version = line.strip()...
0
2016-10-11T12:58:29Z
39,978,024
<p><code>line</code> is the string contents of the line in the file. <code>i</code> is the incrementally increasing index of the line being parsed. Therefore you want to read line number <code>i+3</code>. You can read three lines ahead easily if you read all the lines into memory with <code>.readlines()</code>.<br> <st...
1
2016-10-11T13:09:56Z
[ "python", "loops", "lines" ]
python: grab a specific line after a match
39,977,812
<p>I have have df full of text<br> I would like to define variable <strong>date</strong> which is always three lines after <strong>version</strong>. here is my code</p> <pre><code>with open(input_file1,'r') as f: for i, line in enumerate(f): if line.startswith('Version'): version = line.strip()...
0
2016-10-11T12:58:29Z
39,978,112
<p>What the error message is telling you is that you cannot add a number to a string.</p> <p>You first need to convert the string to a datetime object, to which you can then add anything you want.</p> <p>Check out the <a href="https://docs.python.org/2/library/datetime.html" rel="nofollow">datetime documentation here...
0
2016-10-11T13:14:13Z
[ "python", "loops", "lines" ]
Nuke Python list of objects order based on other list
39,977,832
<p>I got two lists. First one looks like this:</p> <pre><code>passOrder = [ 'direct_diffuse', 'direct_specular', 'direct_specular_2', 'indirect_diffuse', 'indirect_specular', 'indirect_specular_2', ...
0
2016-10-11T12:59:46Z
39,977,897
<p>I don't know what your class/function definitions look like, so I'm using these stubs to illustrate my solution:</p> <pre><code>class Thing: def __init__(self, value): self.val = value def value(self): return self.val class Nuke: def __init__(self, name): self.n = {"name": Thing...
2
2016-10-11T13:03:39Z
[ "python", "list", "sorting", "object", "nuke" ]
Nuke Python list of objects order based on other list
39,977,832
<p>I got two lists. First one looks like this:</p> <pre><code>passOrder = [ 'direct_diffuse', 'direct_specular', 'direct_specular_2', 'indirect_diffuse', 'indirect_specular', 'indirect_specular_2', ...
0
2016-10-11T12:59:46Z
39,978,014
<p>You can construct a dictionary mapping node names to nodes like this</p> <pre><code>nodes_by_name = {n['name'].value(): n for n in nodes} </code></pre> <p>With this dictionary, it's trivial to retrieve the nodes in the desired order:</p> <pre><code>ordered_nodes = [nodes_by_name[name] for name in passOrder] </cod...
0
2016-10-11T13:09:23Z
[ "python", "list", "sorting", "object", "nuke" ]
Nuke Python list of objects order based on other list
39,977,832
<p>I got two lists. First one looks like this:</p> <pre><code>passOrder = [ 'direct_diffuse', 'direct_specular', 'direct_specular_2', 'indirect_diffuse', 'indirect_specular', 'indirect_specular_2', ...
0
2016-10-11T12:59:46Z
39,978,016
<p>You don't have to code the sort yourself.</p> <pre><code>ordered_nodes = sorted(nodes, key=lambda n: passOrder.index(n["name"].value()) if n["name"].value() in passOrder else len(passOrder)) </code></pre>
1
2016-10-11T13:09:42Z
[ "python", "list", "sorting", "object", "nuke" ]
gcloud.exceptions.Forbidden: 403 Missing or insufficient permissions
39,978,077
<p>I am a new to Google Cloud Platform. I have setup a Google VM Instance. I am facing an authentication issue on Local Machine while running the command:</p> <p><code>python manage.py makemigrations</code></p> <p>Can you please suggest some tips/steps to resolve the same ? </p> <p><strong>Error Trace</strong></p> ...
1
2016-10-11T13:12:16Z
39,981,814
<p>Just ran these two commands:</p> <pre><code> 1. gcloud beta auth application-default login 2. export GOOGLE_APPLICATION_CREDENTIALS='/&lt;path_to_json&gt;/client_secrets.json' </code></pre> <p>from local machine and it started working.</p>
0
2016-10-11T16:08:50Z
[ "python", "django", "google-cloud-storage", "google-cloud-platform", "google-cloud-datastore" ]
gcloud.exceptions.Forbidden: 403 Missing or insufficient permissions
39,978,077
<p>I am a new to Google Cloud Platform. I have setup a Google VM Instance. I am facing an authentication issue on Local Machine while running the command:</p> <p><code>python manage.py makemigrations</code></p> <p>Can you please suggest some tips/steps to resolve the same ? </p> <p><strong>Error Trace</strong></p> ...
1
2016-10-11T13:12:16Z
39,987,101
<p>The behavior for application default credentials has <a href="https://cloud.google.com/sdk/release_notes#12800_20160928" rel="nofollow">changed</a> in <code>gcloud</code> since version 128.</p> <p>One should use</p> <pre><code>gcloud auth application-default login </code></pre> <p>instead. </p> <p>Note that chan...
3
2016-10-11T21:32:10Z
[ "python", "django", "google-cloud-storage", "google-cloud-platform", "google-cloud-datastore" ]
Can read() and readline() be used together?
39,978,085
<p>Is it possible to use both read() and readline() on one text file in python?</p> <p>When I did that, it will only do the first reading function.</p> <pre><code>file = open(name, "r") inside = file.readline() inside2 = file.read() print(name) print(inside) print(inside2) </code></pre> <p>The result shows only the...
2
2016-10-11T13:12:30Z
39,978,203
<p>Yes you can.</p> <p><code>file.readline()</code> reads a line from the file (the first line in this case), and then <code>file.read()</code> reads the rest of the file starting from the <em>seek</em> position, in this case, where <code>file.readline()</code> left off.</p> <p>You are receiving an empty string with ...
1
2016-10-11T13:18:50Z
[ "python" ]
Can read() and readline() be used together?
39,978,085
<p>Is it possible to use both read() and readline() on one text file in python?</p> <p>When I did that, it will only do the first reading function.</p> <pre><code>file = open(name, "r") inside = file.readline() inside2 = file.read() print(name) print(inside) print(inside2) </code></pre> <p>The result shows only the...
2
2016-10-11T13:12:30Z
39,978,214
<p>Reading a file is like reading a book. When you say <code>.read()</code>, it reads through the book until the end. If you say <code>.read()</code> again, well you forgot one step. You can't read it again unless you flip back the pages until you're at the beginning. If you say <code>.readline()</code>, we can cal...
3
2016-10-11T13:19:14Z
[ "python" ]
Python: print ALL argparse arguments including defaults
39,978,186
<p>I want to log the usage of a python program which uses the argparse module. Currently, the logger records the command line usage similar to the answer given in <a href="http://stackoverflow.com/questions/8542725/how-can-i-print-all-arguments-passed-to-a-python-script">this post</a>. However, that only gives the co...
0
2016-10-11T13:17:58Z
39,978,305
<p>I've done something similar in an application, hopefully the below snippets give you what you need. It is the call to vars that gave me a dictionary of all the arguments.</p> <pre><code>parser = argparse.ArgumentParser(description='Configure') .... args = parser.parse_args() ...... options = vars(args) </code></pre...
2
2016-10-11T13:24:09Z
[ "python", "logging", "namespaces", "argparse", "sys" ]
saltstack - execute a state inside a reactor written in python
39,978,293
<p>I am trying to create a reactor in Python + Jinja to react to some event. The documentation has fairly good examples on how to create reactors using the YAML format. However, the documentation for creating a reactor in Python is quite lacking. </p> <p>Here is what I got so far:</p> <pre><code>#!jinja|py """ react...
1
2016-10-11T13:23:25Z
40,038,252
<p>So, it turns out, my way of accessing the context data was wrong. There is no need to wrap the python script in Jinja. Unfortunately this is undocumented at the moment. If you write a state or a returner in Python everything that was inside</p> <pre><code>{{ data }} # in Jinja + YAML </code></pre> <p>Is now availa...
2
2016-10-14T08:15:09Z
[ "python", "salt-stack" ]
Making a String with literal r and variables Python
39,978,308
<p>I'm currently trying to make abstract methods for something like this:</p> <pre><code>preset_create("TaggingAgain", r'{"weight": 0, "precondition": "{\"_tags\":\"tagged\"}"}') </code></pre> <p>In my abstraction the User is able to make Precondition objects within a Preset object which then gets created.</p> <p>It...
0
2016-10-11T13:24:17Z
40,000,949
<p>If anybody else needs this in the future, heres how I've done it (using json which gre_gor posted a link to in a comment to my question).</p> <p>Starting with the string:</p> <pre><code>precon = ("{\"%(n)s\":\"%(v)s\"}" % {"n" : precondition.name,"v" : precondition.value}) </code></pre> <p>Another way to get this...
0
2016-10-12T14:15:21Z
[ "python", "string-literals" ]
Requests lib works in Window and times out in Linux
39,978,321
<p>I have a simple python script to make a POST operation using requests lib. In windows, it works fine with no problem. In <strong>Linux</strong>, it's <strong>not</strong> working <strong><em>even though I can ping</em></strong>. The script gives me in Linux:</p> <pre><code>Traceback (most recent call last): File ...
0
2016-10-11T13:24:49Z
39,984,754
<p>My guess is, the website is not responding to your request, and that's why you are getting a time out error. I will try to solve this by changing the user agent in the header, because some websites might be trying to avoid bots. Maybe try something like this: </p> <pre><code>header = {'User-Agent': 'Mozilla/5.0 (W...
0
2016-10-11T19:00:09Z
[ "python", "linux", "python-2.7", "proxy", "python-requests" ]
how to make a python module or fuction and use it while writing other programs?
39,978,375
<p>There where many instances where i have to write large line of code over and over again in multiple programs. so i was wondering if i could write just one program, save it and then call it in different programs like a function or a module.</p> <p>An elementary example :- I write a program to check if a number is p...
3
2016-10-11T13:27:25Z
39,978,523
<p>You should check out the python documentation. If you still have questions then come back.</p> <p><a href="https://docs.python.org/2/tutorial/modules.html" rel="nofollow">https://docs.python.org/2/tutorial/modules.html</a></p>
1
2016-10-11T13:35:31Z
[ "python", "function", "module" ]
how to make a python module or fuction and use it while writing other programs?
39,978,375
<p>There where many instances where i have to write large line of code over and over again in multiple programs. so i was wondering if i could write just one program, save it and then call it in different programs like a function or a module.</p> <p>An elementary example :- I write a program to check if a number is p...
3
2016-10-11T13:27:25Z
39,978,563
<p>Yes. Let's say you're writing code in a file called <code>palindrome.py</code>. Then in another file, or in the python shell you want to use that code. You would type</p> <pre><code>import palindrome </code></pre> <p>either at the top of the file or just into the shell as a command. Then you can access functio...
0
2016-10-11T13:37:24Z
[ "python", "function", "module" ]
how to make a python module or fuction and use it while writing other programs?
39,978,375
<p>There where many instances where i have to write large line of code over and over again in multiple programs. so i was wondering if i could write just one program, save it and then call it in different programs like a function or a module.</p> <p>An elementary example :- I write a program to check if a number is p...
3
2016-10-11T13:27:25Z
39,978,902
<p>it's easy to write a function in python.</p> <p>first define a function is_palindromic,</p> <pre><code>def is_palindromic(num): #some code here return True </code></pre> <p>then define a function is_prime,</p> <pre><code>def is_prime(num): #some code here return True </code></pre> <p>at last, su...
0
2016-10-11T13:53:22Z
[ "python", "function", "module" ]
how to make a python module or fuction and use it while writing other programs?
39,978,375
<p>There where many instances where i have to write large line of code over and over again in multiple programs. so i was wondering if i could write just one program, save it and then call it in different programs like a function or a module.</p> <p>An elementary example :- I write a program to check if a number is p...
3
2016-10-11T13:27:25Z
39,979,991
<p>It is about writing reusable code. I can suggest you to write reusable code in specific function in separate python file and import that file and function too. For example you need function called sum in other function called "bodmas" then write function called sum in one python file say suppose "allimports.py":</p>...
0
2016-10-11T14:45:07Z
[ "python", "function", "module" ]
String encode/decode issue - missing character from end
39,978,405
<p>I am having <code>NVARCHAR</code> type column in my database. I am unable to convert the content of this column to plain string in my code. (I am using <code>pyodbc</code> for the database connection).</p> <pre><code># This unicode string is returned by the database &gt;&gt;&gt; my_string = u'\u4157\u4347\u6e65\u65...
5
2016-10-11T13:29:13Z
39,981,171
<p>You have a major problem in your database definition, in the way you store values in it, or in the way you read values from it. I can only explain what you are seeing, but neither why nor how to fix it without:</p> <ul> <li>the type of the database</li> <li>the way you input values in it</li> <li>the way you extrac...
1
2016-10-11T15:37:19Z
[ "python", "python-2.7", "encode", "pyodbc", "nvarchar" ]
Is it the circular dependency?
39,978,423
<p>It's said that circular dependencies are bad and anti-patterns. So my question is what's wrong with the code below? Is it an example of circular dependency at all? The code is in python pseudocode but should be understood.</p> <pre><code>class Manager: _handlers = [] def on_config(self): # do somet...
0
2016-10-11T13:30:09Z
39,979,361
<p><a href="http://stackoverflow.com/questions/744373/circular-or-cyclic-imports-in-python">Circular (or cyclic) imports in Python</a>. This answer will help you know more about circular imports in python. </p> <p>This code is not about circular dependency. You can also regard this situation as a trade between bussine...
-1
2016-10-11T14:17:13Z
[ "python", "software-design" ]
How to translate a bson file to a json file with Python?
39,978,504
<p>I have some bson files (I don't have the database they came from, just the files, called file1.bson and file2.bson) and I would like to be able to translate them to json. My code is the following:</p> <pre><code>import json import bson to_convert = ["./file1", "./file2"] for i in to_convert: INPUTF = i + ".b...
2
2016-10-11T13:34:42Z
39,978,874
<p>Actually <a href="http://stackoverflow.com/questions/34320177/python-convert-bson-output-of-mongodump-to-array-of-json-objects-dictionaries?rq=1">this</a> answered my question. Weird how poorly documented is the bson package.</p> <pre><code>import json import bson to_convert = ["./file1", "./file2"] for i in to_c...
0
2016-10-11T13:51:35Z
[ "python", "json", "bson" ]
Simulating UDAF on Pyspark for encapsulation
39,978,527
<p>I'm learning Spark with PySpark, and just hit a wall when trying to make things cleaner.</p> <p>Say a have a dataframe that looks like this. (of course, with way more columns and rows)</p> <pre><code>A | B | C --+---+------ a | 1 | 1.300 a | 2 | 2.500 a | 3 | 1.000 b | 1 | 120.0 b | 4 | 34.20 c | 2 | 3.442 </cod...
3
2016-10-11T13:35:46Z
39,978,829
<p>Function can be defined as a combination of <code>pyspark.sql.functions</code>:</p> <ul> <li><p>YES - go this way. For example:</p> <pre><code>def sum_of_squares(col): return sum(col * col) df.select(sum_of_squares(df["foo"]]) df.groupBy("foo").agg(sum_of_squares(df["bar"]]) </code></pre></li> <li><p>NO - us...
1
2016-10-11T13:49:44Z
[ "python", "apache-spark", "pyspark", "apache-spark-sql", "spark-dataframe" ]
Python: list index out of range (Assigning a 2D list to another 2D list)
39,978,529
<p>I am processing a 2D list and want to store the processed 2D list in a new 2D list with same indexes. But, I am getting error "list index out of range"</p> <p>I have simplified my code to make it easy to understand:</p> <pre><code>a = [ ['a', 'b'], ['c', 'd'] ] print a b = [] for i in range(len(a)): f...
4
2016-10-11T13:35:52Z
39,978,691
<p>Simple, you initialised b to [], so any attempt to access it by index will be out of range. Lists in Python can increase in size dynamically, but this isn't how you do it. You need .append</p>
1
2016-10-11T13:42:43Z
[ "python", "arrays", "list" ]
Python: list index out of range (Assigning a 2D list to another 2D list)
39,978,529
<p>I am processing a 2D list and want to store the processed 2D list in a new 2D list with same indexes. But, I am getting error "list index out of range"</p> <p>I have simplified my code to make it easy to understand:</p> <pre><code>a = [ ['a', 'b'], ['c', 'd'] ] print a b = [] for i in range(len(a)): f...
4
2016-10-11T13:35:52Z
39,979,267
<p>I don't have any idea about your expected output. I just fixed the error. At first <code>append</code> an empty <code>list</code> to <code>b</code> then you can access <code>b[i]</code> and so on. </p> <p>Code:</p> <pre><code>a = [ ['a', 'b'], ['c', 'd'] ] print(a) b = [] for i in range(len(a)): b.ap...
2
2016-10-11T14:12:28Z
[ "python", "arrays", "list" ]
Python: list index out of range (Assigning a 2D list to another 2D list)
39,978,529
<p>I am processing a 2D list and want to store the processed 2D list in a new 2D list with same indexes. But, I am getting error "list index out of range"</p> <p>I have simplified my code to make it easy to understand:</p> <pre><code>a = [ ['a', 'b'], ['c', 'd'] ] print a b = [] for i in range(len(a)): f...
4
2016-10-11T13:35:52Z
39,979,814
<p>At <code>b[i][j]</code> you try to access the jth element of the ith element. However, b is just an empty list, so the ith element doesn't exist, let alone the jth element of that ith element. </p> <p>You can fix this by appending the elements to b. But first, a list (row) should be created (appended to b) for each...
2
2016-10-11T14:37:06Z
[ "python", "arrays", "list" ]
Python databases
39,978,655
<p>I would like run a script that will ping some servers from a database and update a field in a database.</p> <p>My database is sqlite and the layout is:</p> <p><code>name IP last_poll status</code></p> <p>Typically the values will be:</p> <p><code>HQ 192.168.1.1 12:00 2016-01-01 online</code></p> <p>The idea is ...
0
2016-10-11T13:41:16Z
40,022,866
<p>Thank you, I have a list of tuples now achieved with this: </p> <p><code>def read_from_db(): c.execute('SELECT ip FROM sites') data = c.fetchall() hostnames = tuple(sum(data, ()))</code></p> <p><code>for h in hostnames: responses = tuple(os.system('ping -c 1 ' + h) for h in hostnames)</code></p> <p><code>z = ...
0
2016-10-13T13:47:57Z
[ "python", "database", "sqlite" ]
How to make unpaired data in python
39,978,675
<p>My data is in this format</p> <pre><code>ID input_1 input_2 1 'hello' 'greeting' 2 'algorithm' 'computer science' . . . . . . </code></pre> <p>The input_1 and input_2 can be viewed as the pair data, is there a way or ...
-2
2016-10-11T13:42:07Z
39,978,756
<p>You can use the random module - which funnily enough has a shuffle function!</p> <p>random.shuffle(input_1)</p> <p>(note that shuffle operates in place, yuck)</p>
0
2016-10-11T13:45:46Z
[ "python", "pandas" ]
How to make unpaired data in python
39,978,675
<p>My data is in this format</p> <pre><code>ID input_1 input_2 1 'hello' 'greeting' 2 'algorithm' 'computer science' . . . . . . </code></pre> <p>The input_1 and input_2 can be viewed as the pair data, is there a way or ...
-2
2016-10-11T13:42:07Z
39,978,816
<p>I think you can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.permutation.html" rel="nofollow"><code>numpy.random.permutation</code></a>:</p> <pre><code>df.input_1 = np.random.permutation(df.input_1) print (df) ID input_1 input_2 0 1 'algorithm' 'greet...
2
2016-10-11T13:49:12Z
[ "python", "pandas" ]
How to make unpaired data in python
39,978,675
<p>My data is in this format</p> <pre><code>ID input_1 input_2 1 'hello' 'greeting' 2 'algorithm' 'computer science' . . . . . . </code></pre> <p>The input_1 and input_2 can be viewed as the pair data, is there a way or ...
-2
2016-10-11T13:42:07Z
39,978,846
<p>read the data in as a dataframe and then process it using it index <code>df.ix[row_number,column_number]</code> and fetch what ever you want to fetch and process accordingly.</p>
0
2016-10-11T13:50:30Z
[ "python", "pandas" ]
Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force NOT WORKING
39,978,810
<p>I'm trying to setup Node.js and Python on my work laptop.</p> <p>I've installed Node and Python successfully.</p> <p>When I'm trying to update my npm using this command in Windows PowerShell:</p> <pre><code>Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force npm install -g npm-windows-upgrade npm-windows...
0
2016-10-11T13:48:59Z
39,985,038
<p>The error message show the root of error:</p> <pre><code> Window powershell updated your execution policy suceffully, but the setting is overridden by a policy defined at a more specific scope. Due to the override, your shell will retain its current effective execution policy of remoteassigned. </code></pre> ...
0
2016-10-11T19:19:32Z
[ "python", "node.js", "powershell", "executionpolicy" ]
Why does zip change my lists?
39,978,853
<p>I noticed a (to me) very strange behavior, I don't understand: I got a list and an numpy array both with binary values and I want to check the true positives (both==1 at the same time).</p> <pre><code>import numpy as np a = [0,0,1,1] b = np.array([1,0,1,0]) for a,b in zip(a,b): if a==1 and b==1: print "coo...
-1
2016-10-11T13:50:51Z
39,978,894
<p><code>zip</code> did not change your list. You lost the initial references to your lists when you assigned the name <code>a</code> and <code>b</code> to the loop variables in:</p> <pre><code>for a, b in zip(a,b): # ^ ^ </code></pre> <p>A simple fix is to change those names to say, <code>i</code> and <code>j</co...
11
2016-10-11T13:52:48Z
[ "python", "list", "python-2.7", "list-comprehension" ]
Why does zip change my lists?
39,978,853
<p>I noticed a (to me) very strange behavior, I don't understand: I got a list and an numpy array both with binary values and I want to check the true positives (both==1 at the same time).</p> <pre><code>import numpy as np a = [0,0,1,1] b = np.array([1,0,1,0]) for a,b in zip(a,b): if a==1 and b==1: print "coo...
-1
2016-10-11T13:50:51Z
39,978,912
<p>Suppose <code>a</code> is a list, and you write <code>a = a[0]</code>. Now you'd expect <code>a</code> to be not a list, but the first value in the list.</p> <p>Similarly, when you write <code>for a,b in zip(a,b)</code> you re-assign <code>a</code> and <code>b</code> to hold the first element in each iterable. Try:...
1
2016-10-11T13:53:44Z
[ "python", "list", "python-2.7", "list-comprehension" ]
"Error 21: Is a directory" when running a concatenate script
39,979,005
<p>I wrote a program to concatenate some csv files vertically. Here is the program.</p> <pre><code>import os import glob import pandas def concatenate(indir, outfile, colnames): os.chdir(indir) fileList=glob.glob('*.csv') dfList=[] for filename in fileList: print(filename) df=pandas.re...
-1
2016-10-11T13:58:54Z
39,979,094
<p>the error say pretty much everything <code>outfile</code> should be a path to a file, not directory. So instead of this</p> <pre><code>y=str(input("What do you want to name your file?")) concatDf.csv_path = y concatDf.to_csv(outfile,index=None) </code></pre> <p>Do this:</p> <pre><code>y=str(input("What do you wan...
1
2016-10-11T14:03:46Z
[ "python", "csv", "concatenation" ]
sql update set ? = ? where ? = ? (python, sqlite3)
39,979,147
<p>Python, slite3</p> <pre><code>c.execute("UPDATE accounts SET ? = ? WHERE num=?", (db['choise'], db['data'], db['num'])) </code></pre> <p>so i don't know what is wrong with it</p> <p>db is shelve database</p>
0
2016-10-11T14:06:38Z
39,979,176
<p>The column (and table) names <em>cannot be parameterized</em>. Use string formatting for it and query parameterization for the rest of variables:</p> <pre><code>c.execute("UPDATE accounts SET {column} = ? WHERE num = ?".format(column=db['choise']), (db['data'], db['num'])) </code></pre> <p>That said, make sure you...
2
2016-10-11T14:08:20Z
[ "python", "sqlite3" ]
sql update set ? = ? where ? = ? (python, sqlite3)
39,979,147
<p>Python, slite3</p> <pre><code>c.execute("UPDATE accounts SET ? = ? WHERE num=?", (db['choise'], db['data'], db['num'])) </code></pre> <p>so i don't know what is wrong with it</p> <p>db is shelve database</p>
0
2016-10-11T14:06:38Z
39,979,464
<p>Column names cannot be given as arguments. You can try </p> <pre><code>c.execute("UPDATE accounts SET "+str(db['choise'])+" = ? WHERE num=?", (db['data'], db['num'])) </code></pre>
0
2016-10-11T14:21:55Z
[ "python", "sqlite3" ]
fabfile doesn't see remote environment variables
39,979,229
<p>My remote server (192.168.3.68) contains several environment variables set in my ~/.bashrc:</p> <pre><code># For instance export MY_DATABASE_HOST=127.0.0.1 </code></pre> <p>When I put <code>run('echo $MY_DATABASE_HOST')</code> in <code>fabfile.py</code>, it shows:</p> <pre><code>[192.168.3.68] run: echo $MY_DATAB...
2
2016-10-11T14:10:40Z
39,979,563
<p>Each call of <code>run</code> will open up a new shell and any transient commands in the previous invocation of <code>run</code> are thus lost (e.g., such as setting an environment variable). To elide this issue, you can do two things:</p> <p>Write your shell commands thusly:</p> <pre><code>run('source /path/to/....
0
2016-10-11T14:26:29Z
[ "python", "fabric" ]