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
listlengths
1
5
I can not access dictionary in my python code
38,446,656
<p>I have written a function that takes code from a sites script element, strips characters, adds double quotes to keys using string replace, and whats returned was what I thought was a dictionary. yet I can't pull values from it. I tried to access values by doing </p> <pre><code>results['file'] </code></pre> <p>and ...
1
2016-07-18T22:00:25Z
38,446,726
<p>The message</p> <pre><code>'str' object has no attribute 'values' </code></pre> <p>tells you that "results" is a string. You can use <a href="https://docs.python.org/3/library/json.html" rel="nofollow">python-json</a> to decode the string to a python object:</p> <pre><code>somevariable = json.loads(results) </cod...
0
2016-07-18T22:08:06Z
[ "python", "json", "django", "dictionary" ]
I can not access dictionary in my python code
38,446,656
<p>I have written a function that takes code from a sites script element, strips characters, adds double quotes to keys using string replace, and whats returned was what I thought was a dictionary. yet I can't pull values from it. I tried to access values by doing </p> <pre><code>results['file'] </code></pre> <p>and ...
1
2016-07-18T22:00:25Z
38,450,843
<p>I suggest you to use yaml in this case, worked pretty well for me.</p> <pre><code>import yaml data = yaml.load(output) print(data['file']) </code></pre> <p>To install yaml</p> <pre><code>$pip install pyyaml </code></pre>
0
2016-07-19T06:18:36Z
[ "python", "json", "django", "dictionary" ]
Print out summaries in console
38,446,706
<p>Tensorflow's <em>scalar/histogram/image_summary</em> functions are very useful for logging data for viewing with tensorboard. But I'd like that information printed to the console as well (e.g. if I'm a crazy person without a desktop environment). </p> <p>Currently, I'm adding the information of interest to the fetc...
1
2016-07-18T22:05:39Z
38,447,138
<p>Overall, there isn't first class support for your use case in TensorFlow, so I would parse the merged summaries back into a tf.Summary() protocol buffer, and then filter / print data as you see fit. </p> <p>If you come up with a nice pattern, you could then merge it back into TensorFlow itself. I could imagine maki...
2
2016-07-18T22:52:04Z
[ "python", "tensorflow", "protocol-buffers", "tensorboard" ]
Copy & Paste Information without f.read?
38,446,741
<p>I am trying to copy and paste information from bytes X to Y from a huge data file to a new file. I got X and Y by using f.readline() and f.tell(). Is there a faster way to do this then the code below.</p> <pre><code>import os a = 300 # Beginning Byte Location b = 208000 # Ending Byte Location def file_split(x,...
-1
2016-07-18T22:09:06Z
38,446,774
<p>You could start with a larger block size than 1 byte? If it's never going to be megabytes worth of data, just go for g.write(f.read(b-a)) and you're done, no need for the loop. If it's going to be megabytes, you may want to do it block by block, making sure the last block is shorter to not exceed b.</p>
0
2016-07-18T22:12:37Z
[ "python", "performance", "file", "copy-paste", "data-management" ]
Save in an array the data from a text file
38,446,756
<p>In Python, if I have the following file:</p> <pre><code>1 10 2 50 3 8 4 9 5 16 6 18 </code></pre> <p>How would I save these data - in two arrays - like so?</p> <pre><code>A = [1 2 3 4 5 6] B = [10 50 8 9 16 18] </code></pre> <p>Thank you </p>
0
2016-07-18T22:10:45Z
38,446,871
<p>We can do this with <a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow"><code>zip()</code></a>.</p> <blockquote> <p>This function returns a list of tuples, where the <code>i</code>-th tuple contains the <code>i</code>-th element from each of the argument sequences or iterables. The retur...
2
2016-07-18T22:22:57Z
[ "python", "python-2.7", "python-3.x" ]
Save in an array the data from a text file
38,446,756
<p>In Python, if I have the following file:</p> <pre><code>1 10 2 50 3 8 4 9 5 16 6 18 </code></pre> <p>How would I save these data - in two arrays - like so?</p> <pre><code>A = [1 2 3 4 5 6] B = [10 50 8 9 16 18] </code></pre> <p>Thank you </p>
0
2016-07-18T22:10:45Z
38,459,232
<p>This pure Python3 code is understandable to a beginner:</p> <pre><code>#!/usr/bin/env python3 first = list() second = list() with open("/tmp/tmp.txt", "r") as data: for a in data.readlines(): _1, _2 = a.split() first.append(int(_1)) second.append(int(_2)) print("A =",first,"\nB =",sec...
1
2016-07-19T12:55:08Z
[ "python", "python-2.7", "python-3.x" ]
Python constructing a class that uses a function from within the same class
38,446,762
<p>I'm trying to get a construct a class that calls a function from within the same class but I'm having trouble doing so. </p> <p>I've had a look at:</p> <p><a href="http://stackoverflow.com/questions/20381904/python-function-pointers-within-the-same-class">Python function pointers within the same Class</a></p> <p>...
0
2016-07-18T22:11:03Z
38,446,790
<pre><code>def prime(self): """The derivative of the sigmoid function""" return self.activation_fn(self.z)*(1-self.activation_fn(self.z)) </code></pre> <p>Or so. note the <code>self.activation_fn</code> instead of just <code>activation_fn</code>.</p>
2
2016-07-18T22:14:07Z
[ "python", "class" ]
Python constructing a class that uses a function from within the same class
38,446,762
<p>I'm trying to get a construct a class that calls a function from within the same class but I'm having trouble doing so. </p> <p>I've had a look at:</p> <p><a href="http://stackoverflow.com/questions/20381904/python-function-pointers-within-the-same-class">Python function pointers within the same Class</a></p> <p>...
0
2016-07-18T22:11:03Z
38,446,807
<p>The comments are correct, you need reference <code>self.</code> because <code>activation_fn</code> is not defined in the scope of the method itself, and your method also doesn't take in any arguments.</p>
1
2016-07-18T22:16:05Z
[ "python", "class" ]
Python constructing a class that uses a function from within the same class
38,446,762
<p>I'm trying to get a construct a class that calls a function from within the same class but I'm having trouble doing so. </p> <p>I've had a look at:</p> <p><a href="http://stackoverflow.com/questions/20381904/python-function-pointers-within-the-same-class">Python function pointers within the same Class</a></p> <p>...
0
2016-07-18T22:11:03Z
38,446,816
<p>It should actually be:</p> <pre><code>def prime(self): """The derivative of the sigmoid function""" return self.activation_fn()*(1-self.activation_fn()) </code></pre> <p>Note that <code>activation_fn</code> does not need to be passed the <code>z</code> value as well - it looks that up from <code>self</code...
4
2016-07-18T22:17:05Z
[ "python", "class" ]
Python constructing a class that uses a function from within the same class
38,446,762
<p>I'm trying to get a construct a class that calls a function from within the same class but I'm having trouble doing so. </p> <p>I've had a look at:</p> <p><a href="http://stackoverflow.com/questions/20381904/python-function-pointers-within-the-same-class">Python function pointers within the same Class</a></p> <p>...
0
2016-07-18T22:11:03Z
38,446,821
<p>So combining both points:</p> <pre><code>def prime(self): """The derivative of the sigmoid function""" return self.activation_fn()*(1-self.activation_fn()) </code></pre> <p><code>activation_fn</code> finds self.z for itself</p>
3
2016-07-18T22:17:35Z
[ "python", "class" ]
Importing theano: AttributeError: 'module' object has no attribute 'find_graphviz'
38,446,771
<p>When I run <code>import theano</code> in Python, I get the following error message:</p> <pre><code>Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import theano Traceback (most recent call last): File "&lt;stdi...
4
2016-07-18T22:12:17Z
38,446,935
<p>For some reason, the Python module <code>pydot</code> was creating the issue:</p> <pre><code>Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; &gt;&gt;&gt; import pydot &gt;&gt;&gt; pydot.find_graphviz() Traceback ...
3
2016-07-18T22:29:19Z
[ "python", "theano" ]
Importing theano: AttributeError: 'module' object has no attribute 'find_graphviz'
38,446,771
<p>When I run <code>import theano</code> in Python, I get the following error message:</p> <pre><code>Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import theano Traceback (most recent call last): File "&lt;stdi...
4
2016-07-18T22:12:17Z
38,455,189
<p>In <code>pydot</code> 1.2.x version,<code>find_graphviz</code> function have been <a href="https://github.com/erocarrera/pydot/issues/126">deprecated</a>. To fix this issue, you should install pydot 1.1.0 version here <a href="https://github.com/erocarrera/pydot/tree/v1.1.0">https://github.com/erocarrera/pydot/tree/...
6
2016-07-19T09:56:00Z
[ "python", "theano" ]
Create dynamically named classes instances in Python
38,446,788
<p>I need to create a new instance of a specific class named from the content of a variable.</p> <p>For example create an instance of the Foo class named whatever the content of the "s" variable is. This is what I tried</p> <pre><code>class Foo: pass s = 'bar' eval(s) = Foo </code></pre> <p>The above code return...
0
2016-07-18T22:14:00Z
38,447,916
<p>This should do it.</p> <pre><code>def make_class(name): class_text = """ global {} # Makes the class object global. class {}: # You put the class here. pass """.format(name, name) # Formats the text. There are a couple different ways to do this. exec(class_text) </code></pre> <p>Example:</p> <pre><cod...
0
2016-07-19T00:41:39Z
[ "python", "python-3.x" ]
python strftime not working with hours minutes and seconds
38,446,854
<p>I am reading the official documentations here</p> <p><a href="https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior" rel="nofollow">https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior</a></p> <p>and it states that I can use </p> <p>%H and %M and %S for hours, minutes an...
1
2016-07-18T22:21:37Z
38,446,896
<p>You are asking for a date, which doesn't include a time. You want a datetime:</p> <pre><code>datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") </code></pre> <p>Example:</p> <pre><code>In [3]: datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") Out[3]: '2016-07-18 18:26:18' </code></pre>
6
2016-07-18T22:25:14Z
[ "python", "datetime" ]
Variables in TestClass when developing in python using VisualStudio
38,446,908
<p>I am learning to develop in python using visual studio. I am implementing a test class. The thing that I got stuck on is where should a variable that will be used across multiple tests be declared. For example in the following code where should calc be declared. </p> <pre><code> class Test_test1(unittest.TestCase):...
0
2016-07-18T22:26:17Z
38,504,843
<p>In the scope of the class level and not in the scope of the function.</p> <p>In the following python example, you can see how to define both:</p> <pre><code>def scope_test(): def do_local(): spam = "local spam" def do_nonlocal(): nonlocal spam spam = "nonlocal spam" def do_global(): global spam ...
1
2016-07-21T12:54:27Z
[ "python", "visual-studio", "unit-testing", "tdd" ]
Testing aiohttp & mongo with pytest
38,446,920
<p>I have a simple coroutine <code>register</code> that accepts login and password as post arguments, then it goes into the database and so on. The problem I have is that I do not know how to test the coroutine.</p> <p>I followed examples from <a href="https://aiohttp.readthedocs.io/en/latest/testing.html" rel="nofol...
1
2016-07-18T22:27:40Z
38,453,868
<p>The root of your problem is <strong>global variable usage</strong>.</p> <p>I suggest the following changes:</p> <pre><code>from aiohttp import web from motor.motor_asyncio import AsyncIOMotorClient from routes import routes def make_app(loop=None): app = web.Application(loop=loop) DBNAME = 'testdb' mo...
1
2016-07-19T08:59:15Z
[ "python", "mongodb", "py.test", "aiohttp" ]
Reshape data into 'closest square'
38,446,984
<p>I'm fairly new to python. Currently using matplotlib I have a script that returns a variable number of subplots to make, that I pass to another script to do the plotting. I want to arrange these subplots into a nice arrangement, i.e., 'the closest thing to a square.' So the answer is unique, let's say I weight num...
2
2016-07-18T22:34:52Z
38,447,157
<p>This what I have done in the past</p> <pre><code>num_plots = 6 nr = int(num_plots**0.5) nc = num_plots/nr if nr*nc &lt; num_plots: nr+=1 fig,axs = pyplot.subplots(nr,nc,sharex=True,sharey=True) </code></pre>
2
2016-07-18T22:54:17Z
[ "python", "matplotlib" ]
Reshape data into 'closest square'
38,446,984
<p>I'm fairly new to python. Currently using matplotlib I have a script that returns a variable number of subplots to make, that I pass to another script to do the plotting. I want to arrange these subplots into a nice arrangement, i.e., 'the closest thing to a square.' So the answer is unique, let's say I weight num...
2
2016-07-18T22:34:52Z
38,447,356
<p>If you have a prime number of plots like 5 or 7, there's no way to do it unless you go one row or one column. If there are 9 or 15 plots, it should work.</p> <p>The example below shows how to</p> <ul> <li>Blank the extra empty plots</li> <li>Force the axis pointer to be a 2D array so you can index it generally eve...
2
2016-07-18T23:20:18Z
[ "python", "matplotlib" ]
Bazel test build fails
38,447,137
<p>I'm using anaconda env. for building magenta, and followed the installation steps as per the <a href="https://github.com/tensorflow/magenta/blob/master/README.md" rel="nofollow">README</a></p> <p>After running the command</p> <pre><code>bazel test //magenta/... </code></pre> <p>it says</p> <blockquote> <p>Exec...
0
2016-07-18T22:51:49Z
38,491,009
<p>The solution (as explained in an <a href="https://github.com/NVIDIA/DIGITS/issues/8#issuecomment-171776188" rel="nofollow">issue</a>)) helped. The error was that the programs were not able to find cuda libraries. So installing <a href="http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1404/x8...
0
2016-07-20T21:17:52Z
[ "python", "tensorflow", "magenta" ]
Why is my python function only populating a dictionary with one line from a file?
38,447,314
<p>I have a file with 11 lines. I'm writing a function that will skip the line containing "XYZ" and return the first and second columns of the rest of the lines in the file. When I run the module, it skips the "XYZ" line, but only returns the first of the remaining lines.</p> <pre><code>def popdict(my_file): for...
1
2016-07-18T23:14:55Z
38,447,327
<p>You return from the outer function the first time you find a line without "XYZ". If you want to wait until end of file, then remove the <strong>return</strong> statement from the loop:</p> <pre><code>def read_to_dict(): for line in my_file: if "XYZ" not in line: x = line.split() ...
0
2016-07-18T23:17:23Z
[ "python", "function", "dictionary" ]
Why is my python function only populating a dictionary with one line from a file?
38,447,314
<p>I have a file with 11 lines. I'm writing a function that will skip the line containing "XYZ" and return the first and second columns of the rest of the lines in the file. When I run the module, it skips the "XYZ" line, but only returns the first of the remaining lines.</p> <pre><code>def popdict(my_file): for...
1
2016-07-18T23:14:55Z
38,447,333
<p>You should <code>return</code> just after the loop over the file finish:</p> <pre><code>def popdict(my_file): for line in my_file: if "XYZ" in line: pass else: x = line.split() a = x[1] b = x[0] d[a] = b return d </code></pre>
0
2016-07-18T23:18:13Z
[ "python", "function", "dictionary" ]
Can I reuse a socket file handle with socket.fromshare?
38,447,361
<p>I'm writing a file cache server to hold copies of static files for a web server. Whenever a thread in the web server needs a static file, it opens a socket connection to the cache server and sends it the result of <code>socket.share()</code> + the name of the file it wants. The cache server uses the result of <code>...
1
2016-07-18T23:21:09Z
38,457,995
<p><a href="https://github.com/python/cpython/blob/master/Modules/socketmodule.c#L2606" rel="nofollow"><code>socket.detach</code></a> only clears the file descriptor field on the <code>PySocketSockObject</code> struct. It does not store the value in any way so that the rest of the module could know that the file descri...
0
2016-07-19T12:01:46Z
[ "python", "windows", "sockets", "python-3.x" ]
Can I reuse a socket file handle with socket.fromshare?
38,447,361
<p>I'm writing a file cache server to hold copies of static files for a web server. Whenever a thread in the web server needs a static file, it opens a socket connection to the cache server and sends it the result of <code>socket.share()</code> + the name of the file it wants. The cache server uses the result of <code>...
1
2016-07-18T23:21:09Z
38,458,160
<p>I'm not sure why:</p> <ol> <li>You're using <code>socket.share</code> and</li> <li>You think it would improve performance.</li> </ol> <p>You say that you're already threading. A web server is going to be IO bound. Most of your time will be spent:</p> <ul> <li>negotiating a TCP/IP connection between client and ser...
0
2016-07-19T12:09:54Z
[ "python", "windows", "sockets", "python-3.x" ]
Why do I need to removeChild form input to call custom GAE API
38,447,406
<p>All I want to do is pass a string to a stupid simple GAE endpoints API that just returns what I sent it. For learning purposes I want to do it without using the Google Javascript libraries or Jinja, Flask, Webapp2, etc. OBTW, yes, I know about the API Explorer. The apparent simplicity of the request there got me won...
1
2016-07-18T23:28:47Z
38,464,583
<p>Sleeping on things helps ... One answer to the second question is to move the text input outside the form. Here's the new HTML:</p> <pre><code>&lt;body&gt; &lt;script&gt; function do_it() { var form1 = document.getElementById('f1'); var input1 = document.getElemen...
0
2016-07-19T17:08:48Z
[ "javascript", "python", "html", "forms", "google-app-engine" ]
Favicon issue with Django - Chrome
38,447,473
<p>I'm having a pretty absurd issue every where EVERY new Django project I create is utilizing an old favicon that I made a long time ago. In other words, all new Django projects have this old favicon and I have no idea how or why its accessing it. </p> <p>Any ideas?</p>
0
2016-07-18T23:38:23Z
38,451,907
<p>There are two points to consider:</p> <p><strong>How you access your sites under development</strong></p> <p>If you use a generic URL such as <code>http://localhost</code>, your browser considers all your sites to be the same one. Thus, you suffer from cross-site caching issues. If so, you can try the well-known s...
0
2016-07-19T07:20:39Z
[ "python", "django", "google-chrome", "favicon" ]
Cannot convert object to str implicitly python
38,447,507
<p>I am very new to python. I have the following code that has a class with three methods problem is at <code>winCMD = 'NET USE '+ host + ' /User:' + self.user + ' ' + self.password</code> line it always complains for <code>self.user</code> and <code>self.password</code> as cannot convert object to int. Any ideas on wh...
0
2016-07-18T23:42:54Z
38,447,553
<p>In <strong>all</strong> your functions you're not actually declaring <code>self</code> <em>as the first parameter</em> and as a result <em><code>host</code> get's assigned to the object instance.</em> When you try to add that to another string with `".. + host + .." you'll get the error you're receiving.</p> <p>Cha...
1
2016-07-18T23:50:49Z
[ "python", "python-3.x" ]
Recursively finding an ID's child and its underlying children
38,447,541
<p>I created a table with two columns, "TOP" and "UNDER". TOP is the parent column with unique IDs, and UNDER contains underlying ID's, separated by ","s. The items in UNDER can also be a parent listed in the "TOP" column.</p> <pre><code>TOP UNDER ---- -------- A B B C,D C E,F D X,Y,Z Z ...
0
2016-07-18T23:49:06Z
38,447,730
<p><strong>EDIT</strong></p> <p>Modified to handle cycles in the graph. ("TOP" and "UNDER" made me think this was a tree, but perhaps that's not a guarantee.)</p> <pre><code>from __future__ import print_function import sqlite3 conn = sqlite3.connect('myTable.db') conn.row_factory = sqlite3.Row c = conn.cursor() def...
2
2016-07-19T00:12:51Z
[ "python", "table", "recursion", "sqlite3", "tree" ]
What is the reason that python is so much slower than C in this instance?
38,447,743
<p>I was solving some problems on project euler and I wrote identical functions for problem 10...</p> <p>The thing that amazes me is that the C solution runs in about 4 seconds while the python solution takes about 283 seconds. I am struggling to explain to myself why the C implementation is so much faster than the py...
4
2016-07-19T00:14:38Z
38,447,955
<p>It's CPython (the implementation) that's slow in this case, not Python necessarily. CPython needs to interpret the bytecode which will almost always be slower than compiled C code. It simply does more work than the equivalent C code. In theory each call to <code>sqrt</code> for example requires looking up that funct...
2
2016-07-19T00:47:31Z
[ "python", "c" ]
Coding noob TypeError: 'str' does not support the buffer interface
38,447,757
<p>I have absolutely no experience with Python and very very little with any other coding languages. However, a few days ago I discovered a tutorial on how to make a "Twitch Plays" stream on twitch.tv. The last step in that process is to mess with some Python code that you copy and paste off of pastebin.com. I'm 99% su...
0
2016-07-19T00:17:06Z
38,448,669
<p>For the first part you're going to want to actually type out your username and Authentication Key (OauthKey). For example, if your username was "User1" and your authentication Key was "AAAA1111", lines 9 and 10 in the first file would look like:</p> <pre><code>username = "User1"; key = "AAAA1111"; </code></pre>...
0
2016-07-19T02:31:56Z
[ "python" ]
dump and load a dill (pickle) in two different files
38,447,815
<p>I think this is fundamental to many people who know how to deal with pickle. However, I still can't get it very right after trying for a few hours. I have the following code:</p> <p><strong>In the first file</strong></p> <pre><code>import pandas as pd names = ["John", "Mary", "Mary", "Suzanne", "John", "Suzanne"]...
-1
2016-07-19T00:28:01Z
38,448,036
<p>Hmm. you need to read it the same way you wrote it -- nesting it inside an open clause:</p> <pre><code>import dill as pickle with open('name_model.pkl' ,'rb') as f: B = pickle.load(f) </code></pre>
1
2016-07-19T00:58:56Z
[ "python", "pandas", "pickle", "dill" ]
dump and load a dill (pickle) in two different files
38,447,815
<p>I think this is fundamental to many people who know how to deal with pickle. However, I still can't get it very right after trying for a few hours. I have the following code:</p> <p><strong>In the first file</strong></p> <pre><code>import pandas as pd names = ["John", "Mary", "Mary", "Suzanne", "John", "Suzanne"]...
-1
2016-07-19T00:28:01Z
38,484,163
<p>Thank you. It looks like the following can solve the problem.</p> <pre><code>import pandas as pd names = ["John", "Mary", "Mary", "Suzanne", "John", "Suzanne"] scores = [80, 90, 90, 92, 95, 100] records = pd.DataFrame({"name": names, "score": scores}) means = records.groupby('name').mean() import dill as pickle ...
0
2016-07-20T14:32:13Z
[ "python", "pandas", "pickle", "dill" ]
How can I list all possibilities of a 3x3 board with 3 different states?
38,448,013
<p>I'm trying to list every possibility of a 3x3 grid, with 3 states: 0, 1, and 2. The board is in the format of a list, so we're listing </p> <pre><code>[0,0,0,0,0,0,0,0,0], [1,0,0,0,0,0,0,0,0], [2,0,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0,0] </code></pre> <p>etc. </p> <p>I have attempted to do this by counting like th...
1
2016-07-19T00:56:03Z
38,448,077
<p>You could use <code>itertools.product</code>:</p> <pre><code>for board in itertools.product([0, 1, 2], repeat=9): ... </code></pre> <p>In your code, you were more or less implementing addition with carrying in base 3. You could represent every single board as an integer between 0 and <code>3^9 - 1 = 19,682</co...
5
2016-07-19T01:05:49Z
[ "python" ]
How can I list all possibilities of a 3x3 board with 3 different states?
38,448,013
<p>I'm trying to list every possibility of a 3x3 grid, with 3 states: 0, 1, and 2. The board is in the format of a list, so we're listing </p> <pre><code>[0,0,0,0,0,0,0,0,0], [1,0,0,0,0,0,0,0,0], [2,0,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0,0] </code></pre> <p>etc. </p> <p>I have attempted to do this by counting like th...
1
2016-07-19T00:56:03Z
38,448,148
<p>Blender's answer is best, it's good to use Python built-ins when you can. But here's one that's more "down and dirty", and you might find enjoyable if you like math. </p> <p>Simply count up in base 3, this will enumerate all your (3x3) possibilities. Zero fill so that each number is 9 digits, then extract the digit...
1
2016-07-19T01:17:25Z
[ "python" ]
Python Pygame: Error detecting collision between bullet and enemy (Space Invaders)
38,448,085
<p>I'm trying to create a basic Space Invaders game in Python. The part that I'm struggling on is detecting when a bullet fired by the player hits the enemy target. I have a <code>Sprite class</code> for both the bullet and enemy that have attributes specifying the bounding rectangle of the sprite, and I have a <code>i...
0
2016-07-19T01:06:34Z
38,448,255
<p>You have to set your sprites rect attributes for each enemy only then you can call the function colliderect.</p> <p>Here is what i mean:</p> <pre><code>enemy.rect.top = some y-value enemy.rect.left = some x-value enemy.rect.bottom = some-height enemy.rect.right = some-width </code></pre>
1
2016-07-19T01:33:47Z
[ "python", "pygame" ]
Conditionally Aggregating Pandas DataFrame
38,448,147
<p>I have a DataFrame that looks like:</p> <pre><code>import pandas as pd df = pd.DataFrame([[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0], [17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0]], columns=['A', 'B', 'C', '...
1
2016-07-19T01:17:21Z
38,448,426
<p>IIUC, you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.expanding.html" rel="nofollow"><code>expanding</code></a> in modern pandas to handle this:</p> <pre><code>&gt;&gt;&gt; cols = ["A","C","D","E"] &gt;&gt;&gt; df[cols] * 2 + df[cols].expanding(axis=1).mean().shift(axis=1...
1
2016-07-19T01:58:49Z
[ "python", "pandas", "dataframe" ]
python array filtering out of bounds
38,448,193
<p>I tried doing this in python, but I get an error:</p> <pre><code>import numpy as np array_to_filter = np.array([1,2,3,4,5]) equal_array = np.array([1,2,5,5,5]) array_to_filter[equal_array] </code></pre> <p>and this results in:</p> <pre><code>IndexError: index 5 is out of bounds for axis 0 with size 5 </code></pre...
4
2016-07-19T01:23:34Z
38,448,251
<p>In the last statement the indices for your array are 1,2,5,5 and 5. Index 5 refers to 6th element in the array while you have only 5 elements. <code>array_to_filter[5]</code> does not exist.</p> <p><code>[i for i in np.unique(equal_array) if i in array_to_filter]</code></p> <p>would return the answer you want. ...
0
2016-07-19T01:33:18Z
[ "python", "arrays", "numpy" ]
python array filtering out of bounds
38,448,193
<p>I tried doing this in python, but I get an error:</p> <pre><code>import numpy as np array_to_filter = np.array([1,2,3,4,5]) equal_array = np.array([1,2,5,5,5]) array_to_filter[equal_array] </code></pre> <p>and this results in:</p> <pre><code>IndexError: index 5 is out of bounds for axis 0 with size 5 </code></pre...
4
2016-07-19T01:23:34Z
38,449,624
<p>If <code>array_to_filter</code> is guaranteed to have unique values, you can do:</p> <pre><code>&gt;&gt;&gt; array_to_filter[np.in1d(array_to_filter, equal_array)] array([1, 2, 5]) </code></pre> <p>From the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html" rel="nofollow">documentation<...
0
2016-07-19T04:31:05Z
[ "python", "arrays", "numpy" ]
Cannot import pandas after pip install pandas
38,448,200
<p>I run the following command to install <code>pandas</code> via <code>pip</code>:</p> <pre><code>sudo pip install pandas --upgrade </code></pre> <p>which outputs</p> <pre><code>Requirement already up-to-date: pandas in /opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages Requirem...
3
2016-07-19T01:24:54Z
38,449,558
<p>Looks like your OS uses pip2 by default. This could be checked by typing:</p> <pre><code>$ pip --version pip 8.1.2 from /usr/local/lib/python2.7/dist-packages (python 2.7) </code></pre> <p>Try to use <code>pip3</code> command like that:</p> <pre><code>sudo pip3 install pandas --upgrade </code></pre>
3
2016-07-19T04:23:14Z
[ "python", "python-3.x", "pandas" ]
Editing the html content of <description> of a KML using lxml
38,448,246
<p>I want to replace the html inside the description tag of a KML with a new, formatted html.</p> <p>My kml has this structure:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;kml xmlns="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="ht...
1
2016-07-19T01:32:37Z
38,448,745
<p>Since KML is a valid XML file, consider <a href="https://www.w3.org/Style/XSL/" rel="nofollow">XSLT</a>, the transformation language used specifically to modify XML documents and Python's lxml can run XSLT 1.0 scripts. </p> <p>Specifically, below the dynamic XSLT is parsed from string, running first the Identity Tr...
0
2016-07-19T02:41:59Z
[ "python", "html", "lxml", "kml", "google-earth" ]
Verifying SAML signature with Python Flask
38,448,264
<p>I have a Python Flask web app. I am integrating OKTA SAML in this app for authentication. </p> <p>I have followed the steps in:</p> <ul> <li><a href="http://stackoverflow.com/questions/21209510/validating-saml-signature-in-python">Validating SAML signature in python</a></li> <li><a href="http://stackoverflow.com/q...
0
2016-07-19T01:34:35Z
38,487,868
<p>I wanted to direct you towards our instructions for Python apps: <a href="http://developer.okta.com/docs/guides/pysaml2" rel="nofollow">http://developer.okta.com/docs/guides/pysaml2</a> In addition, please follow the example for PySAML2 here: <a href="https://github.com/jpf/okta-pysaml2-example" rel="nofollow">https...
0
2016-07-20T18:11:07Z
[ "python", "digital-signature", "saml", "m2crypto", "okta" ]
Verifying SAML signature with Python Flask
38,448,264
<p>I have a Python Flask web app. I am integrating OKTA SAML in this app for authentication. </p> <p>I have followed the steps in:</p> <ul> <li><a href="http://stackoverflow.com/questions/21209510/validating-saml-signature-in-python">Validating SAML signature in python</a></li> <li><a href="http://stackoverflow.com/q...
0
2016-07-19T01:34:35Z
38,512,032
<p>Unless you have a firm grasp of XML parsing, the <a href="https://en.wikipedia.org/wiki/XML_Signature" rel="nofollow">XML Signature</a> specification, cryptographic hashing, and public key encryption, I <em>strongly</em> urge you not to write your own SAML validation routine. </p> <p>For some concrete examples of h...
1
2016-07-21T18:41:30Z
[ "python", "digital-signature", "saml", "m2crypto", "okta" ]
Reverse for 'post_new' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
38,448,270
<p>I get this traceback when browsing to <a href="https://monajalal.pythonanywhere.com/" rel="nofollow">https://monajalal.pythonanywhere.com/</a> and the complete code can be found here <a href="https://github.com/monajalal/FirstDjangoApp" rel="nofollow">https://github.com/monajalal/FirstDjangoApp</a> :</p> <pre><code...
0
2016-07-19T01:35:29Z
38,450,676
<p>Either you need to specify the app name in the url namespace: </p> <p>See this -> <a href="https://docs.djangoproject.com/en/1.9/topics/http/urls/#url-namespaces" rel="nofollow">https://docs.djangoproject.com/en/1.9/topics/http/urls/#url-namespaces</a></p> <p>Or else you need to write your URLs in your html...
0
2016-07-19T06:05:08Z
[ "python", "django", "migration", "url-routing", "manage.py" ]
replacing white part of an image with another image
38,448,281
<pre><code>for i in range(25, 665): for j in range(55, 690): pixel = background[i,j] whitePixel = [255,255,255] if np.array_equal(pixel,whitePixel): background[i,j] = rightsize[i-25,j-55] </code></pre> <p>when I do this code I get an image with ugly edges like this-</p> <p><a href="http://i.stack...
0
2016-07-19T01:36:56Z
38,451,073
<p>It looks like your problem comes from image compression. The borders of your circle are not exactly white. This happens when you load a jpeg image into your program.</p> <p>What you could do is to <a href="http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_thresholding/py_thresholding.html" rel="nofollo...
1
2016-07-19T06:32:25Z
[ "python", "opencv" ]
*Update* Creating an array for distance between two 2-D arrays
38,448,286
<p>So I have two arrays that have x, y, z coordinates. I'm just trying to apply the 3D distance formula. Problem is, that I can't find a post that constitutes arrays with multiple values in each column and spits out an array.</p> <pre><code>print MW_FirstsubPos1 [[ 51618.7265625 106197.7578125 69647.6484375 ] ...
1
2016-07-19T01:37:54Z
38,448,845
<p>Your solutions look good to me. A better idea is to use the linear algebra module in <code>scipy</code> package, as it scales with multiple dimensional data. Here are my codes.</p> <pre><code>import scipy.linalg as LA dist1 = LA.norm(MW_FirstsubPos1 - MW_SecondsubPos1, axis=1) </code></pre>
2
2016-07-19T02:53:51Z
[ "python", "arrays", "numpy" ]
*Update* Creating an array for distance between two 2-D arrays
38,448,286
<p>So I have two arrays that have x, y, z coordinates. I'm just trying to apply the 3D distance formula. Problem is, that I can't find a post that constitutes arrays with multiple values in each column and spits out an array.</p> <pre><code>print MW_FirstsubPos1 [[ 51618.7265625 106197.7578125 69647.6484375 ] ...
1
2016-07-19T01:37:54Z
38,449,406
<p>See if this works, assuming that <code>aaa</code> and <code>bbb</code> are normal python list of lists having the x, y and z coordinates (or that you can convert to such, using <code>tolist</code> or something like that perhaps). <code>result</code> will have the 1-D array you are looking for.</p> <p><strong>Edit:<...
2
2016-07-19T04:03:25Z
[ "python", "arrays", "numpy" ]
*Update* Creating an array for distance between two 2-D arrays
38,448,286
<p>So I have two arrays that have x, y, z coordinates. I'm just trying to apply the 3D distance formula. Problem is, that I can't find a post that constitutes arrays with multiple values in each column and spits out an array.</p> <pre><code>print MW_FirstsubPos1 [[ 51618.7265625 106197.7578125 69647.6484375 ] ...
1
2016-07-19T01:37:54Z
38,452,534
<p>Here's a vectorized approach using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a> -</p> <pre><code>diffs = MW_FirstsubPos1 - MW_SecondsubPos1 dists = np.sqrt(np.einsum('ij,ij-&gt;i',diffs,diffs)) </code></pre> <p>Sample run -</p> <pre><cod...
1
2016-07-19T07:54:08Z
[ "python", "arrays", "numpy" ]
Can not remote debug if there is eventlet.monkey_patch() in code?
38,448,305
<p>I am trying to do remote debug with PyCharm+Pydevd on python code.</p> <p>The code I try to remote debug is below:</p> <pre><code>#!/usr/bin/python import eventlet eventlet.monkey_patch() def main(): import pydevd pydevd.settrace('10.84.101.215', port=11111, stdoutToServer=True, stderrToServer=True) p...
0
2016-07-19T01:40:50Z
38,503,415
<p>Can't help with Pydevd, but there's interactive interpreter backdoor in Eventlet, which allows you to connect and execute any code to analyse state of the system.</p> <pre><code>eventlet.monkey_patch() # add one line eventlet.spawn(backdoor.backdoor_server, eventlet.listen(('localhost', 3000))) </code></pre> <p>Co...
0
2016-07-21T11:45:51Z
[ "python", "pycharm", "pydev", "eventlet", "openstack-neutron" ]
Using Python hidapi to open device with multiple usages
38,448,312
<p>I'm new to the Python hidapi although I've used the C version that it is based on before. The Python library is really different and I can't figure out how to use it from the one example that is provided. Does anyone know of any good documentation for this library?</p> <p>If you're looking for a specific question, ...
0
2016-07-19T01:42:00Z
38,459,575
<p>Although I would still like to find some decent documentation, after using the C hidapi header for reference I found an answer to my original question. In order to specify the usage, you must use <code>open_path()</code> instead of the regular open() method (see below):</p> <pre><code>import hid #Get the list of a...
0
2016-07-19T13:08:42Z
[ "python", "hid", "hidapi" ]
How to speed up the creation of a label tensor from label map in Numpy?
38,448,321
<p>Given a label map of dimensions W X H where each element can take values from {0,..,K-1} I want to output a label tensor of dimensions K X W x H where each element in the K'th map is 1 only if the corresponding value in the labelmap was K. Currently my implementation uses two for loops and is very slow.</p> <pre><...
0
2016-07-19T01:44:17Z
38,448,594
<p>You can use the <code>==</code> operator with broadcasting.</p> <p>For example,</p> <pre><code>In [19]: W = 5 In [20]: H = 8 In [21]: K = 10 </code></pre> <p>Create a <code>p_label</code> for the example:</p> <pre><code>In [22]: p_label = np.random.randint(0, K, size=(W, H)) </code></pre> <p><code>kvals</code...
2
2016-07-19T02:22:51Z
[ "python", "numpy" ]
How to speed up the creation of a label tensor from label map in Numpy?
38,448,321
<p>Given a label map of dimensions W X H where each element can take values from {0,..,K-1} I want to output a label tensor of dimensions K X W x H where each element in the K'th map is 1 only if the corresponding value in the labelmap was K. Currently my implementation uses two for loops and is very slow.</p> <pre><...
0
2016-07-19T01:44:17Z
38,448,652
<pre><code>Label[p_label, np.arange(p_label.shape[0])[:,None], np.arange(p_label.shape[1])] = 1 </code></pre> <p>The 3 index arrays broadcast against each other.</p> <p>==============================</p> <pre><code>lmap = np.arange(12).reshape(3,4) lbl = np.zeros((12,3,4),int) lbl[lmap,np.arange(3)[:,None],np.arange...
1
2016-07-19T02:30:02Z
[ "python", "numpy" ]
Post to Bluemix Retrieve_and_Rank gives status 0, but does not work
38,448,356
<p>I am trying to index some web pages in Bluemix Retrieve and Rank service. So I did crawled my seeds with nutch 1.11, dumped the crawled data(about 9000 URLs) as files, posted those that are possible e.g xml files to my Collection:</p> <pre><code>Post_url = '"https://gateway.watsonplatform.net/retrieve-and-rank/api/...
0
2016-07-19T01:48:55Z
38,514,820
<p>The URL used for posting the converted files have to split the data by /answer_units/ not by /answer_units/id so it should be :</p> <blockquote> <p>Post_converted_url = '"<a href="https://gateway.watsonplatform.net/retrieve-and-rank/api/v1/solr_clusters/%s/solr/%s/update/json/docs?commit=true&amp;split=/answer_u...
0
2016-07-21T21:39:56Z
[ "python", "solr", "ibm-bluemix", "retrieve-and-rank", "solrconfig" ]
ValueError: dict contains fields not in fieldnames even with if statement
38,448,415
<p>I'm trying to pull all of the 2016 NY Times articles that have the word "economy" in them using the Times' API. I get the following error message at the end of my code: </p> <p>ValueError: dict contains fields not in fieldnames: 'abstract'</p> <p>And here is my code:</p> <pre><code>from nytimesarticle import arti...
0
2016-07-19T01:57:14Z
38,448,723
<p>I am not sure what was your problem, but this code creates a file econ-mentions.csv with content.</p> <pre><code>from nytimesarticle import articleAPI def parse_articles(articles): news = [] for i in articles['response']['docs']: dic = {} dic['id'] = i['_id'] if i['abstract'] is not No...
0
2016-07-19T02:39:41Z
[ "python", "web", "screen-scraping" ]
Trying to make a program that returns a predetermined variable via decoding (sorta)
38,448,484
<p>So my goal is to use the module 're' to decode a variable, the following is my code.</p> <pre><code>import re access="password" trial=r"." while True: if trial==access: print(access) break else: trial=trial+r"." </code></pre> <p>The ideal result would be to return 'password', but in...
0
2016-07-19T02:06:27Z
38,448,772
<p>First: an important clarification.</p> <p>The <strong>only</strong> thing the <code>r"…"</code> string syntax does is change the rules for escaping. (Specifically, it mostly disables backslash escape sequences.) <code>r"."</code> means exactly the same thing as <code>"."</code>; it does not create a regular expre...
0
2016-07-19T02:45:22Z
[ "python", "import", "passwords" ]
Output of program for user input giving different length for consonant with user input. input 1 --> abc input2--> 'abc'
38,448,503
<p>""" why this 4 in second user input as 'abc'.ii know that it is counting quotes as python will take input 'abc' as " ' abc ' " hence counting 5 as length how to remove this issue for getting correct answer like other input as shown above n below""" </p> <h1>to get count vowels n consonants</h1> <pre><code> def ...
0
2016-07-19T02:09:05Z
38,448,878
<p>You should judge whether the character is in alphabet first.</p> <pre><code>def get_count(words): words=str(input('Enter:')) vowels = ['a','e','i','o','u'] v_count = 0 c_count = 0 for char in words: if char.isalpha(): if char.lower() in vowels: v_count += 1 ...
0
2016-07-19T02:58:31Z
[ "python", "string", "python-3.x", "string-length" ]
Output of program for user input giving different length for consonant with user input. input 1 --> abc input2--> 'abc'
38,448,503
<p>""" why this 4 in second user input as 'abc'.ii know that it is counting quotes as python will take input 'abc' as " ' abc ' " hence counting 5 as length how to remove this issue for getting correct answer like other input as shown above n below""" </p> <h1>to get count vowels n consonants</h1> <pre><code> def ...
0
2016-07-19T02:09:05Z
38,448,937
<p>Long answer: So your string is <strong>'abc'</strong> which is 5 characters long. python is checking:</p> <ul> <li>if first character <strong>'</strong> is in vowels and it is not so consonant = 0+1 </li> <li>second character is <strong>a</strong>, it is in vowels so vowels = 0+1 </li> <li>third <strong>b</strong> ...
0
2016-07-19T03:06:30Z
[ "python", "string", "python-3.x", "string-length" ]
Join multiline string into an array in Python
38,448,560
<p>In short, my code is supposed to take text from specific tags within a website's HTML (with the help of beautifulsoup4) then load them into an array. </p> <p>I have tried various methods but been unable to join a multiline string into a single array. How would you go about this? Printing <code>productBrands</code> ...
0
2016-07-19T02:18:21Z
38,448,617
<p>If you want to have each line as an element in the array <code>productBrands</code>, then you can create an empty list and use <code>append</code> to add each line to the array.</p> <pre><code>productBrands = [] for item in productData: productBrands.append(item) </code></pre>
0
2016-07-19T02:26:08Z
[ "python", "arrays", "beautifulsoup" ]
Join multiline string into an array in Python
38,448,560
<p>In short, my code is supposed to take text from specific tags within a website's HTML (with the help of beautifulsoup4) then load them into an array. </p> <p>I have tried various methods but been unable to join a multiline string into a single array. How would you go about this? Printing <code>productBrands</code> ...
0
2016-07-19T02:18:21Z
38,448,657
<p>From what I understand, you need to gather the results of <code>get_text()</code> in a list:</p> <pre><code>[product.get_text(strip=True) for product in soup.find_all("div", {"class": "detail"})] </code></pre> <p>Note that there is a shorter way to locate the elements in this case - with a CSS selector:</p> <pre>...
1
2016-07-19T02:30:30Z
[ "python", "arrays", "beautifulsoup" ]
forms.ModelForm does not save ManyToMany fields
38,448,564
<p>I am working with forms (<code>forms.ModelForm</code>) and I have some small inconvenient when I create my form based in the models. My situation such as follow in my <code>models.py</code> file:</p> <p>I have the <code>CorporalSegment</code> model:</p> <pre><code>class CorporalSegment(models.Model): SEGMENTO_...
1
2016-07-19T02:18:43Z
38,495,003
<p><a href="https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method">https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method</a></p> <p>When using commit=False, you have to call save_m2m()</p> <p>m2m relationships require the parent object to be saved first, which you are...
6
2016-07-21T04:40:10Z
[ "python", "django", "django-models", "django-forms" ]
Removing JSON property in array of objects with Python + Inverse
38,448,569
<p>sample data: </p> <p>[{"title": "foo", "imageData": "xyz123"}, {"title": "bar", "imageData": "abc123"}, {"title": "baz", "imageData": "def456"}]</p> <p>this will delete the unwanted key in place, with del, taken from <a href="http://stackoverflow.com/questions/19167485/removing-json-property-in-array-of-objects-w...
0
2016-07-19T02:19:25Z
38,448,686
<p>You could just do this:</p> <pre><code>temp = data['imageData'] data.clear() data['imageData'] = temp </code></pre> <p>The resulting dictionary named <code>data</code> will only contain the key <code>imageData</code> and its associated value</p>
1
2016-07-19T02:34:28Z
[ "python", "json" ]
Removing JSON property in array of objects with Python + Inverse
38,448,569
<p>sample data: </p> <p>[{"title": "foo", "imageData": "xyz123"}, {"title": "bar", "imageData": "abc123"}, {"title": "baz", "imageData": "def456"}]</p> <p>this will delete the unwanted key in place, with del, taken from <a href="http://stackoverflow.com/questions/19167485/removing-json-property-in-array-of-objects-w...
0
2016-07-19T02:19:25Z
38,448,985
<p>You could do that with a list comprehension to create a new list with only the element(s) of interest:</p> <pre><code>import json with open('data.json') as json_data: data = json.load(json_data) new_data = [{'imageData': element['imageData']} for element in data] </code></pre>
1
2016-07-19T03:12:27Z
[ "python", "json" ]
weighted covariance matrix in numpy
38,448,579
<p>I want to compute the covariance <code>C</code> of <code>n</code> measurements of <code>p</code> quantities, where each individual quantity measurement is given its own weight. That is, my weight array <code>W</code> has the same shape as my quantity array <code>Q</code> (<code>n</code> by <code>p</code>). The nativ...
2
2016-07-19T02:21:03Z
38,448,901
<p>After some more experimentation, I found that the following works:</p> <pre><code>A = np.einsum('ki,kj-&gt;ij', Q*W, Q*W) B = np.einsum('ki,kj-&gt;ij', W, W) C = A/B </code></pre>
0
2016-07-19T03:01:25Z
[ "python", "arrays", "numpy", "covariance" ]
weighted covariance matrix in numpy
38,448,579
<p>I want to compute the covariance <code>C</code> of <code>n</code> measurements of <code>p</code> quantities, where each individual quantity measurement is given its own weight. That is, my weight array <code>W</code> has the same shape as my quantity array <code>Q</code> (<code>n</code> by <code>p</code>). The nativ...
2
2016-07-19T02:21:03Z
38,454,780
<p>You can use the very efficient matrix-multiplication with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html" rel="nofollow"><code>np.dot</code></a> -</p> <pre><code>QW = Q*W C = QW.T.dot(QW)/W.T.dot(W) </code></pre>
1
2016-07-19T09:38:52Z
[ "python", "arrays", "numpy", "covariance" ]
translating phone number with letter to all numbers in python. what am i doing wrong?
38,448,584
<p>I keep getting only the first character displayed for the printed translated number</p> <pre><code>phoneNumLetter = str(input("Please enter a phone number that contains letters: ")) def translate(char): if char.upper() == "A" or char.upper() == "B" or char.upper() == "C": number = 2 elif char.upper...
1
2016-07-19T02:22:02Z
38,448,604
<p>While this seems to loop over all the characters,</p> <pre><code>def translateNumber(phoneNumLetter): for char in phoneNumLetter: if char in['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']: result = translate(char) return r...
1
2016-07-19T02:24:06Z
[ "python", "numbers", "phone", "letter" ]
translating phone number with letter to all numbers in python. what am i doing wrong?
38,448,584
<p>I keep getting only the first character displayed for the printed translated number</p> <pre><code>phoneNumLetter = str(input("Please enter a phone number that contains letters: ")) def translate(char): if char.upper() == "A" or char.upper() == "B" or char.upper() == "C": number = 2 elif char.upper...
1
2016-07-19T02:22:02Z
38,448,693
<p>In Python 2.7, an alternative solution that takes much less code is the following.</p> <pre><code>from string import maketrans letter_to_num_table = maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "22233344455566677778889999") phoneNumLetter = str(input("Please enter a phone number that contains letters: ")) def main(): ...
2
2016-07-19T02:35:20Z
[ "python", "numbers", "phone", "letter" ]
translating phone number with letter to all numbers in python. what am i doing wrong?
38,448,584
<p>I keep getting only the first character displayed for the printed translated number</p> <pre><code>phoneNumLetter = str(input("Please enter a phone number that contains letters: ")) def translate(char): if char.upper() == "A" or char.upper() == "B" or char.upper() == "C": number = 2 elif char.upper...
1
2016-07-19T02:22:02Z
38,448,861
<p>You're returning the character as soon as you translate it. You code prints the original phone number. Then, it calls translateNumber. translateNumber goes through the number until it finds an alphabet character. When it does, it translates it to a number and returns it. The 'return' acts as a break - the loop ends....
-1
2016-07-19T02:56:56Z
[ "python", "numbers", "phone", "letter" ]
AttributeError: 'ReturnDict' object has no attribute 'pk'
38,448,603
<p>I am trying to design an api for user login and logout. But I am facing an error of AttributeError: 'ReturnDict' object has no attribute 'pk'. What might be creating this error?</p> <p><a href="http://i.stack.imgur.com/O8nMi.png" rel="nofollow"><img src="http://i.stack.imgur.com/O8nMi.png" alt="enter image descript...
0
2016-07-19T02:24:04Z
38,469,934
<p>Before login you should use authenticate method. Like this:</p> <pre><code>user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) # Redirect to a success page. else: # Return a 'disabled account' error message .....
0
2016-07-19T23:07:29Z
[ "python", "django", "authentication", "django-rest-framework" ]
request() in python seems to block the update of the variable that I want to send in my code
38,448,638
<p>So I have this code that which receives data via RF Receiver constantly.</p> <pre><code>key = 'my api key' ser = serial.Serial('/dev/ttyUSB0',9600) def rfWaterLevel(): rfWaterLevelArray = ser.readline().strip().split() if len(rfWaterLevelArray) == 5: rfWaterLevelVal = float(rfWaterLevelArray[4]) ...
0
2016-07-19T02:28:27Z
38,449,011
<p>The value of <code>rfWaterLevel</code> isn't getting updated because you aren't updating it. Every time you call <code>rfWaterLevel</code> (the function) you execute this statement:</p> <p><code>rfWaterLevel = float(rfWaterLevelTemp[4])</code></p> <p>Then you do something with that value, but you don't show where...
0
2016-07-19T03:15:47Z
[ "python", "python-2.7", "urllib", "httpconnection", "httplib" ]
Using Rblpapi via rpy2
38,448,719
<p>I can successfully use the Rblpapi from R:</p> <pre><code>&gt; library("Rblpapi") &gt; conn &lt;- blpConnect(host='myhost', port=18194) &gt; bds("SPX Index", "INDX_MEMBERS") Member Ticker and Exchange Code 500 XYL UN 501 YHOO UW 502 YUM UN 503 ZBH UN 504 ZION UW </code></pre> <p>However, I can't use it from Pytho...
1
2016-07-19T02:38:14Z
38,448,727
<p>Why? Bloomberg gives you plenty of <a href="http://www.bloomberglabs.com/api/libraries/" rel="nofollow">Python APIs ready-made</a>.</p>
1
2016-07-19T02:40:02Z
[ "python", "rpy2" ]
Using Rblpapi via rpy2
38,448,719
<p>I can successfully use the Rblpapi from R:</p> <pre><code>&gt; library("Rblpapi") &gt; conn &lt;- blpConnect(host='myhost', port=18194) &gt; bds("SPX Index", "INDX_MEMBERS") Member Ticker and Exchange Code 500 XYL UN 501 YHOO UW 502 YUM UN 503 ZBH UN 504 ZION UW </code></pre> <p>However, I can't use it from Pytho...
1
2016-07-19T02:38:14Z
38,461,828
<p>You've misspelled INDX_MEMBERS</p> <pre><code>print r.bds('SPX Index', 'INDX_MEMBERS') </code></pre> <p>works as expected </p>
3
2016-07-19T14:47:32Z
[ "python", "rpy2" ]
Using a RST Document in a ScrollView using Kivy
38,448,755
<p>I am in a bit of a predicament. While working with Kivy's ScrollView Layout and (Current Experimental) reStructuredText renderer module, I ran into a slight problem. Whenever I run my code, my terminal spams me with:</p> <pre><code>[CRITICAL] [Clock] Warning, too much iteration done before the next frame. Check you...
2
2016-07-19T02:43:17Z
38,483,049
<p>Sometimes <code>height: self.minimum_height</code> and similar stuff are like shooting yourself in a foot. Definitely try to comment out these things first, because if you don't do something fancy, the sizing is the issue.</p> <p>Now, why is it an issue? <a href="https://github.com/kivy/kivy/blob/master/kivy/uix/st...
0
2016-07-20T13:44:13Z
[ "python", "kivy" ]
Custom filter field test doesn't work
38,448,832
<p>I have the next test for a <a href="https://github.com/JensAstrup/django-jetpack/blob/master/jet/tests/test_filters.py" rel="nofollow">filter field</a>.</p> <p>Running the test i have this bug:</p> <pre><code>====================================================================== ERROR: test_related_field_ajax_list...
1
2016-07-19T02:52:30Z
38,457,780
<p>Your problem is higher up, in line 30:</p> <pre><code> model_admin = ModelAdmin </code></pre> <p>Here you are not instantiating the object, you simply create another reference to the class itself. Calling a method directly on a class will give the error you see.</p> <p>You need to call the class to instantiate...
0
2016-07-19T11:51:50Z
[ "python", "django", "testing" ]
Couldn't run the python application based on TKinter
38,448,840
<pre><code>import Tkinter as tk from functools import partial pad = [[1, 2, 3], [4, 5, 6], [7, 8, 9], ["C", 0, "S"]] passcode = "" def append_passcode(value): global passcode if len(passcode) == 4: passcode = passcode[1:] passcode += value def clear(): global passcode passcode = "" def s...
1
2016-07-19T02:53:27Z
38,448,896
<p>Here's what you've done wrong:</p> <ul> <li>Misspelled tkinter</li> <li><p>Not included </p> <pre><code>main_window.mainloop() </code></pre></li> </ul> <p>Try this code</p> <pre><code>import tkinter as tk from functools import partial pad = [[1, 2, 3], [4, 5, 6], [7, 8, 9], ["C", 0, "S"]] passcode = "" def app...
1
2016-07-19T03:00:30Z
[ "python", "tkinter" ]
Python shelve file extension on CentOS
38,448,900
<p>When I use python shelve on Ubuntu, it saves to a file without extension. But when I use it on CentOS, 3 files appears with extensions .bac .dat and .dir. What happens here and how to make them consistent?</p>
0
2016-07-19T03:01:20Z
38,632,806
<p><code>shelve</code> uses behind the scene the <code>dbm</code> module, which in turns uses some native <code>dbm</code> bindings depending on the OS.</p> <p>Citing the docs:</p> <blockquote> <p>dbm is a generic interface to variants of the DBM database — dbm.gnu or dbm.ndbm. If none of these modules is install...
1
2016-07-28T09:48:32Z
[ "python", "centos6", "shelve" ]
list of objects python
38,448,914
<p>I am trying to print a list of python objects that contain a list as a property and i am having some unexpected results:</p> <p>here is my code:</p> <pre><code>class video(object): name = '' url = '' class topic(object): topicName = '' listOfVideo = [] def addVideo(self,videoToAdd): ...
9
2016-07-19T03:03:15Z
38,449,719
<p>You have created <code>class variables</code> instead of <code>instance variables</code>, which are different for each instance object. Define your class as follows:</p> <pre><code>class topic(object): def __init__(self): self.topicName = '' self.listOfVideo = [] def addVideo(self,videoToA...
10
2016-07-19T04:42:11Z
[ "python", "python-object" ]
Initiating multiple widgets in Kivy
38,449,006
<p>Imagine this as the main.py:</p> <pre><code>class Widget1(Button): pass class Widget2(ButtonBehavior, Image): pass </code></pre> <p>And inside the .kv file:</p> <pre><code>&lt;Widget1&gt;: Button: &lt;Widget2&gt;: Image: </code></pre> <p>How do I initialize both <code>Widget1</code> and <code>W...
2
2016-07-19T03:14:54Z
38,449,173
<p>Try like this</p> <pre><code>class Widget1(Button) pass class Widget2(ButtonBehavior, Image) pass class MyMain(Widget): pass class MyApp(App): def build(self): return MyMain() MyApp().run() </code></pre> <p>and in your kivy</p> <pre><code>&lt;MyMain&gt;: &lt;Widget1&gt;: Bu...
1
2016-07-19T03:34:45Z
[ "python", "user-interface", "kivy" ]
Initiating multiple widgets in Kivy
38,449,006
<p>Imagine this as the main.py:</p> <pre><code>class Widget1(Button): pass class Widget2(ButtonBehavior, Image): pass </code></pre> <p>And inside the .kv file:</p> <pre><code>&lt;Widget1&gt;: Button: &lt;Widget2&gt;: Image: </code></pre> <p>How do I initialize both <code>Widget1</code> and <code>W...
2
2016-07-19T03:14:54Z
38,482,356
<p>Why would you put another <code>Button</code> and <code>Image</code> inside a widget that <em>inherits</em> it? Seems to me like this:</p> <blockquote> <p>create button → place another button into that button widget</p> </blockquote> <p>You don't want that. And definitely not creating rules inside a rule - som...
0
2016-07-20T13:14:19Z
[ "python", "user-interface", "kivy" ]
IR Kernel dying with fresh install of Jupyter
38,449,025
<p>This is my hardware</p> <blockquote> <pre><code>:~/Downloads$ lscpu Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Byte Order: Little Endian CPU(s): 4 </code></pre> </blockquote> <p>This is my OS</p> <blockquote> <pre><code>uname -a Linux 4.4.0-21-generic #37-Ubunt...
1
2016-07-19T03:17:11Z
39,549,270
<p>Your problem is a version compatibility issue. At this moment, IRkernel has not been upgraded to the most IPython/Jupyter version. If you tried to install <em>de novo</em> in R or RStudio:</p> <pre><code>devtools::install_github('IRkernel/IRkernel') IRkernel::installspec(name = 'ir33', displayname = 'R 3.3') </code...
2
2016-09-17T16:42:58Z
[ "python", "jupyter", "jupyter-notebook" ]
pip install -U pysftp error
38,449,049
<p>I am new to Python, and trying to build a SFTP tool. I installed pysftp already by using "python install.py install" command, but somehow not working.</p> <p>I am using mac os10.11.5, python2.7, pip8.1.2.</p> <p>below is the error when i use "pip install -U pysftp", any thought?</p> <p>thanks.</p> <pre><code>Ins...
1
2016-07-19T03:20:40Z
38,449,224
<p>It look like there's something wrong with your permissions, try <code>sudo pip install -U pysftp</code></p>
0
2016-07-19T03:40:47Z
[ "python", "pysftp" ]
bdist_wheel not working under MSYS2
38,449,052
<p>I'm attempting to build a Python package using under a MSYS2 MINGW64 shell on a Windows 7 VirtualBox VM. The package builds, installs and imports successfully on Linux. </p> <p>I can build a binary wheel under MSYS2...</p> <pre><code>$ python setup.py bdist_wheel running bdist_wheel running build running build_py ...
0
2016-07-19T03:20:55Z
38,449,669
<p>On MSYS2 there is a conflict between with MSYS2 path translation and <code>bdist_wheel</code>. A workaround is to specify an <em>absolute</em> path to a temporary build directory using the <code>--bdist-dir</code> option (should not be "build" since <code>bdist_wheel</code> deletes this directory which means a fresh...
0
2016-07-19T04:36:34Z
[ "python", "python-wheel", "msys2" ]
Add a new field to the sympy symbolic variable
38,449,055
<p>I have a SymPy symbolic variable:</p> <pre><code>from sympy import symbols x=symbols('x') </code></pre> <p>How can I add a new field to the symbolic variable <code>x</code>?</p> <pre><code>x.New_Field=Arbitrary_Value </code></pre>
2
2016-07-19T03:21:13Z
38,453,460
<p>You <em>cannot</em> dynamically add an attribute to a <code>Symbol</code>. </p> <p>It would most likely be a bad idea because SymPy assumes that it can replace expressions which compare as equal. So if you created two symbols and stored an attribute dynamically in one (<em>supposing this were possible</em>)</p> <p...
2
2016-07-19T08:39:49Z
[ "python", "sympy" ]
Validating entries in a csv based on a master csv file with python
38,449,063
<p>I'm currently using Python 2.6. I need to write a script that reads a 'master' csv file and then matches the entries in a second csv file against the master to determine their validity. The master and secondary csv files have the same number of columns with similar values in each. I'm trying to loop through each ent...
0
2016-07-19T03:21:54Z
38,449,218
<p>So looking at your 2 problems parts.<br> Read master into memory. Use a dictionary comprehension to reader the whole master file in with a key of <code>row['ID_A']</code>, e.g.:</p> <pre><code>with open('master.csv') as csvfile: reader = csv.DictReader(csvfile) master = {row['ID_A']: row for row in reader} ...
0
2016-07-19T03:39:43Z
[ "python", "validation", "csv" ]
Validating entries in a csv based on a master csv file with python
38,449,063
<p>I'm currently using Python 2.6. I need to write a script that reads a 'master' csv file and then matches the entries in a second csv file against the master to determine their validity. The master and secondary csv files have the same number of columns with similar values in each. I'm trying to loop through each ent...
0
2016-07-19T03:21:54Z
38,449,382
<p>You could read the master file to a set of <code>(ID_A, ID_C)</code> tuples and when you're validating just check if tuple <code>(ID_C, ID_C)</code> exists in there:</p> <pre><code>import csv class Validator(object): def read_master(self, master): with open(master) as f: reader = csv.DictRe...
0
2016-07-19T04:00:26Z
[ "python", "validation", "csv" ]
xlwings:copy a worksheet, and reproduce it at the end of an existing worksheet
38,449,260
<p>I'm useing xlwings on a Windows.</p> <p>I copy a worksheet and want to reproduce it at the end of an existing worksheet now. In a worksheet to copy, I use a photograph and the figure.</p> <p>I know some sample code to reproduce copy a worksheet.</p> <p>I would appreciate it if you could answer my questions.</p>
0
2016-07-19T03:45:29Z
39,547,092
<p>I was settled with this code:</p> <pre><code>Sheet(1).xl_sheet.Copy(Before=Sheet(1).xl_sheet) </code></pre>
0
2016-09-17T12:57:24Z
[ "python", "copy", "worksheet-function", "xlwings" ]
Why is there no symmetric difference for collections.Counter?
38,449,289
<p>So for sets you can do a symmetric difference (^) which is the equivalent of union minus intersection. Why is ^ an unsupported operand for Counter objects while union and intersection still work? </p>
0
2016-07-19T03:48:54Z
38,449,354
<p>For Counter objects, <code>&amp;</code> and <code>|</code> don't mean intersection and union as they do for sets ... they mean <code>max</code> and <code>min</code>.</p> <blockquote> <p>Several mathematical operations are provided for combining Counter objects to produce multisets (counters that have counts great...
1
2016-07-19T03:56:41Z
[ "python", "python-2.7", "counter" ]
Why is there no symmetric difference for collections.Counter?
38,449,289
<p>So for sets you can do a symmetric difference (^) which is the equivalent of union minus intersection. Why is ^ an unsupported operand for Counter objects while union and intersection still work? </p>
0
2016-07-19T03:48:54Z
38,449,711
<p>Expanding on my comment, turns out it was discussed at time, and rejected.</p> <p>Click the link for the full message (and its thread); I'll just quote the "high order bits" of Raymond Hettinger's reply:</p> <blockquote> <p>It's unlikely that I will add this [symmetric difference] method to the Counter API becau...
2
2016-07-19T04:41:27Z
[ "python", "python-2.7", "counter" ]
Extract dictionary object inside a Div with Beautiful Soup
38,449,310
<p>I have the following sample: </p> <pre><code> [&lt;div class="options__list"&gt; &lt;a href="/link1"&gt; &lt;div class="options__list__item" option-message="closed" data-option='{"id":1,"is_active":true,"name":"Fran","city":{"id":32,"name":"Paris","is_top":null,"url_key":"paris","main_area":{"id":null,"n...
-1
2016-07-19T03:51:12Z
38,449,443
<p>The idea would be to iterate over the links, get the <code>href</code> attribute values, then find the inner option list items and use <a href="https://docs.python.org/3/library/json.html#json.loads" rel="nofollow"><code>json.loads()</code></a> to load the <code>data-option</code> value into the python dictionary:</...
2
2016-07-19T04:07:50Z
[ "python", "web-scraping", "beautifulsoup" ]
Django installed,but "startapp" occured ImportError: No module named 'django'
38,449,323
<p>I uninstalled Django1.9 and install Django1.8.14</p> <p>I successfully installed Django1.8.14 by confirm "import django""django.VERSION" in the python command line. <a href="http://i.stack.imgur.com/29yin.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/29yin.jpg" alt="error report"></a></p> <p>I use python ...
0
2016-07-19T03:52:48Z
38,458,256
<p>Finally,I solved the problem by switching the python35-intel32bit to python35-amd64 and pip install Django1.9. By the way,I run it on Win10-intel-64bit.</p>
0
2016-07-19T12:13:42Z
[ "python", "django" ]
Return Excel file in Flask app
38,449,325
<p>I am creating a Flask application that prompts the user for an Excel file, does some work with it, then returns the file back to the user so that they can download it. (Please ignore any unused imports. I plan on using them later on.)</p> <p>I have my functionality down, i'm just not sure how to send the file back ...
0
2016-07-19T03:53:00Z
38,450,152
<p>It depends if you want to keep the file on your server/computer or not. You could do something like this to keep the files:</p> <pre><code>from flask import send_from_directory def process(): # do what you're doing file_name = 'document_template.xltx' wb = load_workbook('document.xlsx') wb.save(fi...
0
2016-07-19T05:25:40Z
[ "python", "flask" ]
Scrape information about Visit Page and App Name on google play store
38,449,327
<p>I have created the code below to scrape the app name and Visit Page Url from the google play store page. </p> <p> ASOS - Get ASOS (Line 1120) </p> <p> Visit website - Get <a href="http://www.asos.com" rel="nofollow">http://www.asos.com</a> - (q=)(Line 1121 source code)</p> <pre><code>url = 'https://play.goo...
0
2016-07-19T03:53:10Z
38,449,549
<p>BeautifulSoup provides a great deal of functions that you should be taking advantage of.</p> <p>For starters, your script can be cut down to the following:</p> <pre><code>import requests from bs4 import BeautifulSoup url = 'https://play.google.com/store/apps/details?id=com.asos.app' r = requests.get(url) soup = ...
1
2016-07-19T04:21:55Z
[ "python", "html" ]
edit excel sheet cell with python
38,449,353
<p>I am trying to edit excel sheet cell by python. for edit i am using following code:</p> <pre><code>from xlrd import open_workbook from xlutils.copy import copy xl_file = r'D:\path\excel.xls' rb = open_workbook(xl_file) wb = copy(rb) sheet = wb.get_sheet(0) sheet.write(0,2,'New_Data_For_Cell') wb.save(xl_file) </co...
0
2016-07-19T03:56:09Z
38,449,529
<p>To keep the formatting of excel sheet you should use</p> <blockquote> <p>formatting_info=True </p> </blockquote> <p>with open_workbook</p> <p>here is the working code:</p> <pre><code>from xlrd import open_workbook from xlutils.copy import copy xl_file = r'D:\path\excel.xls' rb = open_workbook(xl_file, forma...
1
2016-07-19T04:20:03Z
[ "python", "excel" ]
**ImportError**: unable to load extension module '/home/wyx/pypy3env/site-packages/numpy/core/**multiarray.pypy3-52.so**':
38,449,404
<p>I created a virtualenv of <strong>PyPy 5.2.0-alpha0 with GCC 4.6.3</strong> on Ubuntu 14.04. After that installed numpy (using pip) for pypy successfully, when i do <code>import numpy</code> in the pypy3 intepreter the following error occurrs:</p> <pre><code>ImportError: unable to load extension module '/home/wyx/p...
0
2016-07-19T04:03:07Z
38,454,789
<p>You can't fix this, I'm afraid. <code>pypy3</code> 5.2 does not support <code>numpy</code>.</p>
0
2016-07-19T09:39:17Z
[ "python", "numpy", "pypy" ]
python 3.x need help spliting 1 text file into 4 dictionaries
38,449,484
<p>Can anyone help me with an issue i am having? i am trying to wright some code that will let a user select specific files called diarys then compare it to there current skill levels, each file has a easy, medium, hard, and elite section that i want to put in separate dictionary's, i can get it to print the correct in...
0
2016-07-19T04:13:02Z
38,450,315
<p>I am guessing the only part you struggle is how to fill out four dictionaries given a file with the structure you described.</p> <p>If you are sure that those files will not be altered by anything/anyone other than you, and you are okay with using unsafe &amp; dirty code, you can just do:</p> <pre><code>exec(file_...
0
2016-07-19T05:39:29Z
[ "python", "python-3.x", "dictionary" ]
python 3.x need help spliting 1 text file into 4 dictionaries
38,449,484
<p>Can anyone help me with an issue i am having? i am trying to wright some code that will let a user select specific files called diarys then compare it to there current skill levels, each file has a easy, medium, hard, and elite section that i want to put in separate dictionary's, i can get it to print the correct in...
0
2016-07-19T04:13:02Z
38,450,537
<p>Try this:</p> <pre><code>import os import imp from pprint import pprint # shows all osrs diarys def diary_selection(): diary_options = { 0 : 'ardougne', 1 : 'desert', 2 : 'falador', 3 : 'fremennik', 4 : 'kandarin', 5 : 'lumbridge', 6 : 'morytania', 7 : 'varrock', 8 : 'western', 9 : 'wilderness' } ...
0
2016-07-19T05:54:40Z
[ "python", "python-3.x", "dictionary" ]
Sorting a list of named tuples by field numercially
38,449,581
<p>I'm fairly new to using python. I have a list of namedtuples which I would like to sort numerically by one of the fields. I currently have code that looks something like this:</p> <pre><code>from collections import namedtuple testTuple = namedtuple("test", "name, number") from operator import itemgetter testList ...
0
2016-07-19T04:25:40Z
38,449,591
<p>I think that writing a small lambda function is best you'll be able to do:</p> <pre><code>from collections import namedtuple testTuple = namedtuple("test", ("name", "number")) seq = [testTuple(name = 'abc', number = '123'), testTuple(name = 'xyz', number = '32'), testTuple(name = 'def', number = '32...
3
2016-07-19T04:27:26Z
[ "python", "sorting", "namedtuple" ]
pass user input to festival
38,449,608
<p>So I have a Raspberry Pi unit that is set up to check a gmail account and if new mail appears, it reads it out loud via festival. </p> <p>I interact with Festival via a crude <code>'echo "' + str(message) + '" | festival --tts'</code> call where message is the content of an incoming email.</p> <p>I am guessing th...
1
2016-07-19T04:29:53Z
38,449,880
<p>Is there a reason you have to use the shell to invoke festival?<br> If not, just stay within python and use a lib (e.g. <a href="https://pypi.python.org/pypi/pyfestival/" rel="nofollow">pyfestival</a>) for that as this is probably simpler and you don't have the risk of someone injecting shell code into the message. ...
1
2016-07-19T04:59:13Z
[ "python", "email", "security", "festival" ]
Select column in one row and save as variable using python and mysqldb
38,449,634
<p>first sorry for my bad english. i'm php programmer and I just started a python programming language.</p> <p>Mysql code:</p> <pre><code>SELECT * FROM `datapy` ORDER BY `No` DESC LIMIT 0,1 </code></pre> <p>And show row:</p> <pre><code>++++++++++++++++++ ++ NO +++ nilai ++ ++++++++++++++++++ ++ 12 +++ 100 ++ ++++...
0
2016-07-19T04:32:10Z
38,449,698
<p>you can create a database object like <code>db</code> and use <code>cursor()</code> </p> <pre><code>cur=db.cursor() cur.execute("select nilai from datapy ORDER BY `No` DESC LIMIT 0,1") rows = cur.fetchall() </code></pre>
1
2016-07-19T04:39:42Z
[ "php", "python", "mysql", "mysql-python" ]
Compare adjacent values in numpy array
38,449,670
<p>I have a Numpy one-dimensional array of data, something like this</p> <pre><code>a = [1.9, 2.3, 2.1, 2.5, 2.7, 3.0, 3.3, 3.2, 3.1] </code></pre> <p>I want to create a new array, where the values are composed of the greater of the adjacent values. For the above example, the output would be:</p> <pre><code>b = [2....
-1
2016-07-19T04:36:37Z
38,449,705
<p>You want element-wise maximum of <code>a[1:]</code> and <code>a[:-1]</code>:</p> <pre><code>&gt;&gt;&gt; a array([ 1.9, 2.3, 2.1, 2.5, 2.7, 3. , 3.3, 3.2, 3.1]) &gt;&gt;&gt; a[1:] array([ 2.3, 2.1, 2.5, 2.7, 3. , 3.3, 3.2, 3.1]) &gt;&gt;&gt; a[:-1] array([ 1.9, 2.3, 2.1, 2.5, 2.7, 3. , 3.3, 3....
3
2016-07-19T04:40:48Z
[ "python", "arrays", "numpy" ]
Access the python class from method while defining it
38,449,672
<p>I wanted to access the class on which method is to be defined. This can be used, for example, to create alias for methods with decorator. This particular case could be implemented without using decorator (<code>alias = original_name</code>), but I would like to use decorator, primarily so because the aliasing will b...
2
2016-07-19T04:37:17Z
38,452,335
<p>The short answer is no. The contents of the class body are evaluated before the class object is created, i.e. the function <code>test</code> is created and passed to the decorator without class <code>Test</code> already existing. The decorator is therefore unable to obtain a reference to it.</p> <p>To solve the pro...
0
2016-07-19T07:42:45Z
[ "python", "methods", "reflection" ]
convert roman to number got index out of range error
38,449,741
<p>I am new to python. Trying to convert roman to numbers. Everything works perfect but when I input some roman terms I got index error. Please trace out the error and correct me.</p> <pre><code>def roman(x): x=list(x) print(x) s=0 val=[['I',1],['V',5],['X',10],['L',50],['C',100],['D',500],['M',1000]] ...
1
2016-07-19T04:45:25Z
38,449,939
<p>Can you instead try the roman package:</p> <pre><code>&gt;&gt;&gt; import roman &gt;&gt;&gt; roman.fromRoman('X') 10 &gt;&gt;&gt; roman.fromRoman('IV') 4 &gt;&gt;&gt; roman.fromRoman('V') 5 &gt;&gt;&gt; roman.fromRoman('M') 1000 &gt;&gt;&gt; roman.fromRoman('L') 50 &gt;&gt;&gt; </code></pre> <p>As for the error, ...
2
2016-07-19T05:05:22Z
[ "python", "roman-numerals" ]
Extract specific lines from multiple text files
38,449,795
<p>I want to print certain lines from multiple text files in a folder, depending on the file name. Consider the following text files named from 3 words separated by underscore:</p> <pre><code>Small_Apple_Red.txt Small_Orange_Yellow.txt Large_Apple_Green.txt Large_Orange_Green.txt </code></pre> <p>How can the followin...
1
2016-07-19T04:50:55Z
38,450,446
<p>Try as follow.</p> <p>Use <a href="http://perldoc.perl.org/functions/glob.html" rel="nofollow">glob</a> for to handle the files in a folder. </p> <p>Then use regular expression for check the file name. Here <a href="http://perldoc.perl.org/functions/grep.html" rel="nofollow">grep</a> uses for extract the particula...
0
2016-07-19T05:48:39Z
[ "java", "python", "perl", "awk", "sed" ]