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 |
|---|---|---|---|---|---|---|---|---|---|
Python Import Text Array with Numpy | 39,229,830 | <p>I have a text file that looks like this:</p>
<pre><code>...
5 [0, 1] [512, 479] 991
10 [1, 0] [706, 280] 986
15 [1, 0] [807, 175] 982
20 [1, 0] [895, 92] 987
...
</code></pre>
<p>Each column is tab separated, but there are arrays in some of the columns. Can I import these with <code>np.genfromtxt</co... | 0 | 2016-08-30T14:10:19Z | 39,236,239 | <p>As an alternative to <code>genfromtxt</code> you might try <code>fromregex</code>. You basically set up an analogy between regular expression groups and the fields of a numpy structured dtype.</p>
<p>In this example, I parse out all numbers without worrying about whether they are single numbers or arrays. Then I ... | 0 | 2016-08-30T20:07:30Z | [
"python",
"arrays",
"numpy",
"genfromtxt"
] |
How to open remote MySQL connection at a LAMP(Python) stack | 39,229,914 | <p>I am developing a django application where my MySQL database is present.
My django application and database setup is on one machine.</p>
<p>Now I have 2 other machines running a script which need to remotely connect to my MySQL database present in my main machine.</p>
<p>So in my main machine. I have done this:</p... | 0 | 2016-08-30T14:13:24Z | 39,230,020 | <p>The setup you did to allow remote connections looks good (though you didn't mention restarting mysql, but I'll assume that was done). Also I'm assuming there's no NAT and all machines involved are directly connected to the internet (ifconfig shows a WAN ip).</p>
<p>I'd recommend trying to connect with the mysql com... | 1 | 2016-08-30T14:17:33Z | [
"python",
"mysql",
"linux",
"django",
"database"
] |
How to open remote MySQL connection at a LAMP(Python) stack | 39,229,914 | <p>I am developing a django application where my MySQL database is present.
My django application and database setup is on one machine.</p>
<p>Now I have 2 other machines running a script which need to remotely connect to my MySQL database present in my main machine.</p>
<p>So in my main machine. I have done this:</p... | 0 | 2016-08-30T14:13:24Z | 39,230,038 | <p>instead of doing machine ip address, allow any host 'user'@'%' and see if it works.</p>
<p>If it does, check the logs to see what your hostname is displayed to your server as.</p>
<p>Changing bind address is not necessary. </p>
| 1 | 2016-08-30T14:18:33Z | [
"python",
"mysql",
"linux",
"django",
"database"
] |
Can I use a builtin name as a method name of a Python class? | 39,229,951 | <p>I have a class that performs some simple data manipulation, I need three methods: set, add, sub:</p>
<pre><code>class Entry(): # over-simplified but should be enough for the question
def __init__(self, value):
self.set(value)
def set(self, value):
self.value=value
def add(self, value):
... | 5 | 2016-08-30T14:14:32Z | 39,230,013 | <p>You are fine. You just don't want to overwrite the built-ins if they are a built-in method <em>__init__</em> <em>__iter__</em> etc unless you are implementing the functionality expected by those methods.</p>
<p>You are "overwriting" a built in <em>function</em> as a class method, which means you aren't really over... | 1 | 2016-08-30T14:17:20Z | [
"python",
"pep8"
] |
Can I use a builtin name as a method name of a Python class? | 39,229,951 | <p>I have a class that performs some simple data manipulation, I need three methods: set, add, sub:</p>
<pre><code>class Entry(): # over-simplified but should be enough for the question
def __init__(self, value):
self.set(value)
def set(self, value):
self.value=value
def add(self, value):
... | 5 | 2016-08-30T14:14:32Z | 39,230,029 | <p><a href="https://www.python.org/dev/peps/pep-0020/" rel="nofollow">Namespaces are one honking great idea</a> - same in this case, name <code>set</code> defined but it exists only in namespace limited to <code>Entry</code> class and does not clash with built-in function name.</p>
| 1 | 2016-08-30T14:18:02Z | [
"python",
"pep8"
] |
Can I use a builtin name as a method name of a Python class? | 39,229,951 | <p>I have a class that performs some simple data manipulation, I need three methods: set, add, sub:</p>
<pre><code>class Entry(): # over-simplified but should be enough for the question
def __init__(self, value):
self.set(value)
def set(self, value):
self.value=value
def add(self, value):
... | 5 | 2016-08-30T14:14:32Z | 39,234,005 | <p>The whole thing about not shadowing builtin names is that you don't want to stop your self from being able to use them, so when your code does this:</p>
<pre><code>x.set(a) #set the value to a
b = set((1,2,3)) #create a set
</code></pre>
<p>you can still access the builtin <code>set</code> so there is no conflict,... | 2 | 2016-08-30T17:49:26Z | [
"python",
"pep8"
] |
Transform 1D List | 39,229,972 | <p>I'm new to python and I need to transform a list of number(0,1,2,3) into a 2D array. Basically, they both have the same row number however the value in the 1D list indicates it's column number in the 2D array. The value in the 2D list is marked with a 1. For example, a sample 1D list </p>
<pre><code>list_1d = [1,0,... | -1 | 2016-08-30T14:15:15Z | 39,230,293 | <p>assuming the wanted result in the question is not exact, you could do something like this:</p>
<pre><code>list_1d = [1,0,3,2,0]
x_size = max(list_1d) + 1
y_size = len(list_1d)
matrix = []
for y in range(y_size):
line = []
for x in range(x_size):
line.append(1 if x == list_1d[y] else 0)
matrix.... | 0 | 2016-08-30T14:30:02Z | [
"python",
"arrays",
"list",
"numpy",
"transform"
] |
Transform 1D List | 39,229,972 | <p>I'm new to python and I need to transform a list of number(0,1,2,3) into a 2D array. Basically, they both have the same row number however the value in the 1D list indicates it's column number in the 2D array. The value in the 2D list is marked with a 1. For example, a sample 1D list </p>
<pre><code>list_1d = [1,0,... | -1 | 2016-08-30T14:15:15Z | 39,230,363 | <p>Here's a one liner</p>
<pre><code>>>> np.array([[ 1 if i == n else 0 for i in range(4)] for n in list_1d])
array([[0, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 0],
[1, 0, 0, 0]])
</code></pre>
<p>It uses a nested couple of comprehensions to do what you need. The width of... | 1 | 2016-08-30T14:32:52Z | [
"python",
"arrays",
"list",
"numpy",
"transform"
] |
Transform 1D List | 39,229,972 | <p>I'm new to python and I need to transform a list of number(0,1,2,3) into a 2D array. Basically, they both have the same row number however the value in the 1D list indicates it's column number in the 2D array. The value in the 2D list is marked with a 1. For example, a sample 1D list </p>
<pre><code>list_1d = [1,0,... | -1 | 2016-08-30T14:15:15Z | 39,230,521 | <blockquote>
<p>"I wanted to optimize code by not using a for loop since my list has millions of elements."</p>
</blockquote>
<p>In that case, use numpy:</p>
<pre><code>>>> list_1d = [1,0,3,2,0]
>>> mat = np.zeros((len(list_1d),4))
>>> mat[range(len(list_1d)), list_1d] = 1
>>> ma... | 5 | 2016-08-30T14:39:13Z | [
"python",
"arrays",
"list",
"numpy",
"transform"
] |
Transform 1D List | 39,229,972 | <p>I'm new to python and I need to transform a list of number(0,1,2,3) into a 2D array. Basically, they both have the same row number however the value in the 1D list indicates it's column number in the 2D array. The value in the 2D list is marked with a 1. For example, a sample 1D list </p>
<pre><code>list_1d = [1,0,... | -1 | 2016-08-30T14:15:15Z | 39,230,711 | <pre><code>list_1d = [1,0,3,2,0]
</code></pre>
<p>How tall should the matrix be?</p>
<blockquote>
<p><code>height</code> is the number of elements in the 1d list.</p>
</blockquote>
<pre><code>height = len(list_1d)
</code></pre>
<p>How wide should the matrix be?</p>
<blockquote>
<p><code>width</code> is the num... | 0 | 2016-08-30T14:48:04Z | [
"python",
"arrays",
"list",
"numpy",
"transform"
] |
Python: Correct Way to refer to index of unicode string | 39,230,021 | <p>Not sure if this is exactly the problem, but I'm trying to insert a tag on the first letter of a unicode string and it seems that this is not working. Could these be because unicode indices work differently than those of regular strings?</p>
<p>Right now my code is this:</p>
<pre><code>for index, paragraph in enu... | 3 | 2016-08-30T14:17:36Z | 39,230,141 | <p>The behavior you're seeing suggests you have a byte string instead of a unicode string - your code should work if it was a unicode string, unicode string indexes work the same way as 'normal' ascii strings. In python 3, at least.</p>
| 2 | 2016-08-30T14:23:10Z | [
"python",
"unicode",
"python-2.x"
] |
Python: Correct Way to refer to index of unicode string | 39,230,021 | <p>Not sure if this is exactly the problem, but I'm trying to insert a tag on the first letter of a unicode string and it seems that this is not working. Could these be because unicode indices work differently than those of regular strings?</p>
<p>Right now my code is this:</p>
<pre><code>for index, paragraph in enu... | 3 | 2016-08-30T14:17:36Z | 39,233,084 | <p>You are right, indices work over each <code>byte</code> when you are dealing with <em>raw bytes</em> i.e <code>String</code> in <em>Python(2.x)</em>.</p>
<p>To work seamlessly with Unicode data, you need to first let <em>Python(2.x)</em> know that you are dealing with <code>Unicode</code>, then do the string manipu... | 5 | 2016-08-30T16:53:13Z | [
"python",
"unicode",
"python-2.x"
] |
Python: Correct Way to refer to index of unicode string | 39,230,021 | <p>Not sure if this is exactly the problem, but I'm trying to insert a tag on the first letter of a unicode string and it seems that this is not working. Could these be because unicode indices work differently than those of regular strings?</p>
<p>Right now my code is this:</p>
<pre><code>for index, paragraph in enu... | 3 | 2016-08-30T14:17:36Z | 39,237,624 | <p>You should use Unicode strings. Byte strings in UTF-8 use a variable number of bytes per character. Unicode use one (at least those in the BMP on Python 2...the first 65536 characters):</p>
<pre><code>#coding:utf8
s = u"××§×××"
t = u'<b>'+s[0]+u'</b>'+s[1:]
print(t)
with open('out.htm','w',encodin... | 3 | 2016-08-30T21:48:44Z | [
"python",
"unicode",
"python-2.x"
] |
passing a dictionary to all templates using context_processors | 39,230,053 | <p>I want to show my notification to all my templates. In my settings I have:</p>
<pre><code>TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_proc... | 1 | 2016-08-30T14:19:13Z | 39,230,408 | <p>Your <code>TEMPLATES</code> setting looks ok. In your context processor, you don't need to use <code>RequestContext</code>. Just return a dictionary. If you are using Django 1.9 or earlier, you <strong>must</strong> call the method <code>request.user.is_authenticated()</code> otherwise <code>request.user.is_authenti... | 2 | 2016-08-30T14:34:56Z | [
"python",
"django",
"python-3.x",
"django-1.9"
] |
Get file's links with google-drive-api python | 39,230,197 | <p>I've worked with <code>Google Drive</code> <code>Api</code> some time and I can't find the way to get the link for file's view on Drive pragramatically.<br>
There is <code>function</code> which creates folder and returns its id, however additionally I need to return a <code>link</code> for <code>view</code> only.
T... | 0 | 2016-08-30T14:25:53Z | 39,253,486 | <p>So, create folder and return a View link is possible by adding "webViewLink" to fields in method files().create(). The function will be the next:</p>
<pre><code>def create_folder(parent_id, folder_name='no_name', ):
data = {'name': folder_name,
'mimeType': 'application/vnd.google-apps.folder',
'pare... | 0 | 2016-08-31T15:23:18Z | [
"python",
"google-drive-sdk"
] |
openpyxl module does not have attribute '__version__' when imported by pandas | 39,230,220 | <p>My traceback from running pandas takes me to: <br/>
<code>site-packages\pandas\io\excel.py line 58, in get_writer
AttributeError: 'module' object has no attribute '__version__'</code></p>
<p>I found this link to a git issue in the PyInstaller repo
<a href="https://github.com/pyinstaller/pyinstaller/issues/1890" rel... | 2 | 2016-08-30T14:26:36Z | 39,396,636 | <p>Edits were not making an impact because the process was compiled into an exe that these modules were running through. Exported the sections I needed outside of my anaconda environment and now the process works without a hitch. </p>
| 1 | 2016-09-08T17:05:22Z | [
"python",
"pandas",
"openpyxl",
"conda"
] |
Retrieve geocodes from Google API and append to original table - python | 39,230,230 | <p>I am trying to retrieve the geocodes of a bunch of addresses through the Google geocoding API and append them to my table with addresses.</p>
<p>After spending two days reviewing the internet I coulnd´t find any simple way of doing while it shouldn´t be that hard. I am specially having problems parsing the json o... | -1 | 2016-08-30T14:26:57Z | 39,230,823 | <p>I use <a href="https://pypi.python.org/pypi/geopy" rel="nofollow">this package</a> to do my geocoding, which takes care of parsing the JSON file.</p>
<pre><code>from geopy.geocoders import GoogleV3
googleGeo = GoogleV3('googleKey')
# create a geocoded list containing geocode objects
geocoded = []
for address in m... | 1 | 2016-08-30T14:54:09Z | [
"python",
"google-maps",
"geocoding"
] |
Send a syn packet through http proxy in python 3 | 39,230,310 | <p>I'm able to send a tcp syn packet through a socks, but what about HTTP proxies? Is it possible?</p>
<p>This is the code with sock (it works):</p>
<pre><code>p = bytes(IP(dst="DESTINATIONIP")/TCP(flags="S", sport=RandShort(), dport=80))
while True:
try:
socks.setdefaultproxy(sock... | 0 | 2016-08-30T14:30:51Z | 39,258,534 | <p>I presume when you say "send a SYN packet" you mean "make a connection", since you can't send any bare IP-level packets via SOCKS, only make connections and send TCP / UDP payload.</p>
<p>For http proxy, it's similar, you just use the http tunneling command "CONNECT", e.g. you send</p>
<pre><code>CONNECT somewhere... | 0 | 2016-08-31T20:33:10Z | [
"python",
"sockets",
"python-3.x",
"scapy",
"http-proxy"
] |
Looping over a dictionary to make multiple dictionaries | 39,230,401 | <p>I have a dictionary, dict1, and I am wanting to find a way to loop through it to isolate all the values for shepherds, collies, and poodles. I apologize a head of time if my syntax is off. I am still learning about dictionaries!</p>
<pre><code>dict1 = {
'Bob VS Sarah': {
'shepherd': 1,
'collie': 5,
'poo... | 0 | 2016-08-30T14:34:44Z | 39,230,481 | <pre><code>dict_shepherd = {'shepherd': []}
for name in dict1:
dict_shepherd['shepherd'].append(dict1['shepherd'])
</code></pre>
<p>It's worth noting that standard dictionaries don't enforce any ordering of their contents, so looping through the items might not yield them in the same order as they are listed in yo... | 2 | 2016-08-30T14:37:41Z | [
"python",
"dictionary"
] |
Looping over a dictionary to make multiple dictionaries | 39,230,401 | <p>I have a dictionary, dict1, and I am wanting to find a way to loop through it to isolate all the values for shepherds, collies, and poodles. I apologize a head of time if my syntax is off. I am still learning about dictionaries!</p>
<pre><code>dict1 = {
'Bob VS Sarah': {
'shepherd': 1,
'collie': 5,
'poo... | 0 | 2016-08-30T14:34:44Z | 39,230,598 | <p>You can solve it in general case for a variable number of keys in sub-dicts with a <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict(list)</code></a>:</p>
<pre><code>from collections import defaultdict
from pprint import pprint
dict1 = # your dict... | 2 | 2016-08-30T14:43:03Z | [
"python",
"dictionary"
] |
Looping over a dictionary to make multiple dictionaries | 39,230,401 | <p>I have a dictionary, dict1, and I am wanting to find a way to loop through it to isolate all the values for shepherds, collies, and poodles. I apologize a head of time if my syntax is off. I am still learning about dictionaries!</p>
<pre><code>dict1 = {
'Bob VS Sarah': {
'shepherd': 1,
'collie': 5,
'poo... | 0 | 2016-08-30T14:34:44Z | 39,230,649 | <p>You can also get all the lists in one line using dictionary and list comprehensions:</p>
<pre><code>ds = {type: [val[type] for val in dict1.values()] for type in ['shepherd', 'collie', 'poodle']}
# {'collie': [2, 7, 8, 5, 2, 6, 5, 2, 2, 2, 2, 8, 9, 2, 2, 7],
# 'poodle': [2, 2, 1, 8, 2, 3, 8, 5, 4, 1, 2, 2, 2, 4, ... | 2 | 2016-08-30T14:45:23Z | [
"python",
"dictionary"
] |
Looping over a dictionary to make multiple dictionaries | 39,230,401 | <p>I have a dictionary, dict1, and I am wanting to find a way to loop through it to isolate all the values for shepherds, collies, and poodles. I apologize a head of time if my syntax is off. I am still learning about dictionaries!</p>
<pre><code>dict1 = {
'Bob VS Sarah': {
'shepherd': 1,
'collie': 5,
'poo... | 0 | 2016-08-30T14:34:44Z | 39,230,844 | <p>You can user defaultdict as follow</p>
<pre><code>from collections import defaultdict
dict1 = {'Bob VS Sarah': {'shepherd': 1,'collie': 5,'poodle': 8},
'Bob VS Ann': {'shepherd': 3,'collie': 2,'poodle': 1},
'Bob VS Jen': {'shepherd': 3,'collie': 2,'poodle': 2},
'Sarah VS Bob': {'shepherd': 3,'collie': 2,'poodle... | 1 | 2016-08-30T14:54:58Z | [
"python",
"dictionary"
] |
Python List : Index out of Range | 39,230,444 | <p>I've been trying to create a program that has to read in a file, find the unique words and punctuation, put those to a list and then get the positions of each word and store them in a list. Then, using the lists the program will recreate the file. This is my code:</p>
<pre><code>import time
import re
words = open('... | 0 | 2016-08-30T14:36:31Z | 39,230,696 | <p>The problem is that you are incrementing every element of <code>positions</code> so that it displays as 1-indexed, then using that array when python is expecting 0-indexed. Try using:</p>
<pre><code>recreated = " ".join([uniquewords[i-1] for i in positions])
</code></pre>
<p>instead</p>
| 1 | 2016-08-30T14:47:49Z | [
"python"
] |
Python List : Index out of Range | 39,230,444 | <p>I've been trying to create a program that has to read in a file, find the unique words and punctuation, put those to a list and then get the positions of each word and store them in a list. Then, using the lists the program will recreate the file. This is my code:</p>
<pre><code>import time
import re
words = open('... | 0 | 2016-08-30T14:36:31Z | 39,230,759 | <p>Please check the below code. I changed bit for recreating string to solve space issue along with the indexing problem you were facing.</p>
<pre><code>import time
import re
words = open("val.txt",'r')
sentence = words.readline()
uniquewords = []
positions = []
punctuation = re.findall(r"[\w']+|[.,!?;]", sentence)
fo... | 0 | 2016-08-30T14:50:31Z | [
"python"
] |
Turning a list of key/value pairs into a pandas dataframe stored in a HDFStore | 39,230,446 | <p>There are questions similar to this, but none of them handle the case where my dataframe is inside an HDFStore.</p>
<p>I need to turn a list of timestamp/key/value items into dataframes and store it as several dataframes each indexed on the timestamp, and then save it in an HDFStore.</p>
<p>Example code:</p>
<pre... | 0 | 2016-08-30T14:36:35Z | 39,235,820 | <p>I'd comment to get some clarification, but I don't have the rep yet. Without some more context, it's hard for me to say whether your approach is wise, but I'd inclined to say no in almost all cases. Correct me if I'm wrong, but what you're trying to do is:</p>
<ul>
<li>Given a list of iterables: <code>[(timeA, key1... | 0 | 2016-08-30T19:39:23Z | [
"python",
"pandas",
"hdf"
] |
Plot google map as background | 39,230,459 | <p>I want to display Google map and I use this code :</p>
<pre><code>url = "http://maps.googleapis.com/maps/api/staticmap?center=-30.027489,-51.229248&size=800x800&zoom=14&sensor=false"
im = Image.open(cStringIO.StringIO(urllib2.urlopen(url).read()))
plt.imshow(im)
plt.show()
</code></pre>
<p>this gives m... | 0 | 2016-08-30T14:37:04Z | 39,252,096 | <p>Take a look at the <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.imshow" rel="nofollow">documentation of <code>imshow()</code></a> and specifically its <code>origin</code> argument which determines where the [0,0] index of the array is located in the plot.</p>
<p>The line needs to be:</p>
<p... | 1 | 2016-08-31T14:16:26Z | [
"python",
"image",
"google-maps",
"url"
] |
Why my Element not in view when page scrolls by itself in selenium? | 39,230,460 | <p>Now, suppose my page have 10 clickable links with same class, one below another at some distance, such that only 1st 3 links are shown in current view, others are seen when i scroll down. Now, i have written a code to click on all of them. It clicks on first 3 and then selenium scrolls my page to show link 5 to 7, p... | 0 | 2016-08-30T14:37:06Z | 39,234,449 | <p>Figured out the solution, by adding this code after every click.</p>
<pre><code>self.driver.execute_script("window.scrollBy(0, 150);")
</code></pre>
| 0 | 2016-08-30T18:15:11Z | [
"python",
"selenium"
] |
Why my Element not in view when page scrolls by itself in selenium? | 39,230,460 | <p>Now, suppose my page have 10 clickable links with same class, one below another at some distance, such that only 1st 3 links are shown in current view, others are seen when i scroll down. Now, i have written a code to click on all of them. It clicks on first 3 and then selenium scrolls my page to show link 5 to 7, p... | 0 | 2016-08-30T14:37:06Z | 39,254,311 | <p>Try calling <code>x.location_once_scrolled_into_view</code> before you do x.click(). That should cause the element to scroll into view to be clicked.</p>
| 0 | 2016-08-31T16:05:47Z | [
"python",
"selenium"
] |
Having a special character such as a period in a python key | 39,230,604 | <p>I'm trying to generate sql insert statements using sqlalchemy like this.</p>
<pre><code>def get_sql(self):
"""Returns SQL as String"""
baz_ins = baz.insert().values(
Id=self._id,
Foo.Bar=self.foo_dot_bar,
)
return str(baz_ins.compile(dialect=mysql.dialect(),
... | 0 | 2016-08-30T14:43:27Z | 39,234,745 | <p>There's an alternate form of <a href="http://docs.sqlalchemy.org/en/latest/core/dml.html#sqlalchemy.sql.expression.ValuesBase.values" rel="nofollow"><code>.values</code></a> where you pass in a <code>dict</code> instead:</p>
<pre><code>baz.insert().values({
"Id": self._id,
"Foo.Bar": self.foo_dot_bar,
})
</... | 0 | 2016-08-30T18:33:31Z | [
"python",
"sqlalchemy"
] |
Having a special character such as a period in a python key | 39,230,604 | <p>I'm trying to generate sql insert statements using sqlalchemy like this.</p>
<pre><code>def get_sql(self):
"""Returns SQL as String"""
baz_ins = baz.insert().values(
Id=self._id,
Foo.Bar=self.foo_dot_bar,
)
return str(baz_ins.compile(dialect=mysql.dialect(),
... | 0 | 2016-08-30T14:43:27Z | 39,234,824 | <p>In your query, <code>values</code> can be <a href="http://docs.sqlalchemy.org/en/latest/core/dml.html#sqlalchemy.sql.expression.Insert.values" rel="nofollow">assigned with dictionary</a>. So you can do something like:</p>
<pre><code>baz_ins = baz.insert().values({"Id": self._id, "Foo.Bar": self.foo_dot_bar})
</code... | 0 | 2016-08-30T18:38:19Z | [
"python",
"sqlalchemy"
] |
Numpy vectorized zero-order interpolation | 39,230,757 | <p>I have an array</p>
<pre><code>p = [[0.9, 0.95, 0.99],
[0.89, 0.94, 0.98],
[0.9, 0.95, 0.99],
[0.91, 0.96, 0.97],
]
</code></pre>
<p>and a uniform random number for each row</p>
<pre><code>r = [0.5,
0.9,
0.3,
0.99]
</code></pre>
<p>I want to know the last column index where p ... | 2 | 2016-08-30T14:50:27Z | 39,230,923 | <p>Here's one vectorized solution using <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> -</p>
<pre><code>mask = (p > r[:,None])
out = np.where(mask.any(1),mask.argmax(1),p.shape[1])
</code></pre>
<p>Sample run -</p>
<pre><code>In [50]: p
Out[50]... | 3 | 2016-08-30T14:58:45Z | [
"python",
"numpy",
"optimization",
"vectorization"
] |
How do i return the position of a word that appears twice in a string? | 39,230,787 | <p>I'm writing a program where the user has to enter a set of string characters. They then pick a keyword that may or may not be in the string. If it is then the program will run through the string and see how many times the keyword appear and it will print this to the screen. I have done this so it does it but if the ... | 0 | 2016-08-30T14:51:50Z | 39,230,960 | <p>You could use <a href="https://docs.python.org/2/library/re.html#re.finditer" rel="nofollow">re.finditer</a>, here's a little example out of your example:</p>
<pre><code>import re
sentence = input("Enter a set of string characters:")
keyword = input("Enter a keyword that we can tell you the position of:")
for m i... | 1 | 2016-08-30T14:59:56Z | [
"python",
"string"
] |
How do i return the position of a word that appears twice in a string? | 39,230,787 | <p>I'm writing a program where the user has to enter a set of string characters. They then pick a keyword that may or may not be in the string. If it is then the program will run through the string and see how many times the keyword appear and it will print this to the screen. I have done this so it does it but if the ... | 0 | 2016-08-30T14:51:50Z | 39,230,984 | <p>using <code>enumerate()</code> in an example where "een" is the keyword, <code>line</code> the input :</p>
<pre><code>keyword = "een"
line = "een aap op een fiets"
for index, word in enumerate(line.split()):
if word == keyword:
print(index)
</code></pre>
| 4 | 2016-08-30T15:00:43Z | [
"python",
"string"
] |
How do i return the position of a word that appears twice in a string? | 39,230,787 | <p>I'm writing a program where the user has to enter a set of string characters. They then pick a keyword that may or may not be in the string. If it is then the program will run through the string and see how many times the keyword appear and it will print this to the screen. I have done this so it does it but if the ... | 0 | 2016-08-30T14:51:50Z | 39,231,002 | <p>The <code>index</code> method, as you found, returns just the first match:</p>
<pre><code>>>> words = 'This is the time that the clock strikes'.split()
>>> words.index('the')
2
</code></pre>
<p>This list comprehension will return the locations of all matches:</p>
<pre><code>>>> [i for i... | 1 | 2016-08-30T15:01:25Z | [
"python",
"string"
] |
How do i return the position of a word that appears twice in a string? | 39,230,787 | <p>I'm writing a program where the user has to enter a set of string characters. They then pick a keyword that may or may not be in the string. If it is then the program will run through the string and see how many times the keyword appear and it will print this to the screen. I have done this so it does it but if the ... | 0 | 2016-08-30T14:51:50Z | 39,231,024 | <p>You can use the regex method <a href="https://docs.python.org/2/library/re.html#re.finditer" rel="nofollow"><code>finditer()</code></a></p>
<pre><code>>>> keyword = 'fox'
>>> s = 'The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.'
>>> from re impor... | 1 | 2016-08-30T15:02:21Z | [
"python",
"string"
] |
Add a value to the end of a pandas index object | 39,230,854 | <p>I have a pandas index object and I'd like to add a single value to the end of it. The .append() method doesn't seem to work like one would expect, and since I'm trying to add an element, I can't insert at the location of -1 because that puts the value in the second-to-last position. For example</p>
<pre><code>impor... | 1 | 2016-08-30T14:55:36Z | 39,231,155 | <p>The method <code>append</code> takes another index as input, but <a href="http://pandas.pydata.org/pandas-docs/stable/api.html#combining-joining-set-operations" rel="nofollow"><code>union</code></a> will work if you simply pass an array-like object: </p>
<pre><code>indx.union([20])
</code></pre>
<p>Note that index... | 2 | 2016-08-30T15:09:12Z | [
"python",
"pandas"
] |
Add a value to the end of a pandas index object | 39,230,854 | <p>I have a pandas index object and I'd like to add a single value to the end of it. The .append() method doesn't seem to work like one would expect, and since I'm trying to add an element, I can't insert at the location of -1 because that puts the value in the second-to-last position. For example</p>
<pre><code>impor... | 1 | 2016-08-30T14:55:36Z | 39,231,251 | <p>You need to pass a collection of index values as parameter while appending to the given <code>index</code> object.</p>
<pre><code>indx.append(pd.Index([20])) # Pass the values inside the list
Int64Index([11, 12, 13, 14, 15, 20], dtype='int64')
</code></pre>
| 2 | 2016-08-30T15:13:43Z | [
"python",
"pandas"
] |
Add a value to the end of a pandas index object | 39,230,854 | <p>I have a pandas index object and I'd like to add a single value to the end of it. The .append() method doesn't seem to work like one would expect, and since I'm trying to add an element, I can't insert at the location of -1 because that puts the value in the second-to-last position. For example</p>
<pre><code>impor... | 1 | 2016-08-30T14:55:36Z | 39,231,255 | <p>You may want to try these two options:</p>
<pre><code>import pandas as pd
import numpy as np
ser.append(pd.Series([np.nan], index = [20]))
# 11 1.0
# 12 2.0
# 13 3.0
# 14 4.0
# 15 5.0
# 20 NaN
# dtype: float64
ser.set_value(20, np.nan)
# 11 1.0
# 12 2.0
# 13 3.0
# 14 4.0
# 15 5.0... | 2 | 2016-08-30T15:13:58Z | [
"python",
"pandas"
] |
Predefined module aliases in Python? | 39,231,138 | <p>I'm developing a library of Python modules that is fairly deeply nested, e.g.:</p>
<pre><code>\MyTools
__init__.py
\HydroTools
__init__.py
\bin
\Code
__init__.py
hydro.py
\TerraTools
__init__.py
\bin
\Code
__init__.py
... | 1 | 2016-08-30T15:08:38Z | 39,231,445 | <p>You want to push these nested packages on top of your module namespace.</p>
<p>In <code>MyTools/__init__.py</code> add:</p>
<pre><code>from .HydroTools.Code import hydro
from .TerraTools.Code import terra
</code></pre>
| 3 | 2016-08-30T15:21:31Z | [
"python"
] |
How do I pass grants with boto3's upload_file? | 39,231,148 | <p>I have a command using the AWS CLI</p>
<pre><code>aws s3 cp y:/mydatafolder s3://<bucket>/folder/subfolder --recursive --grants read=uri=http://policyurl
</code></pre>
<p>The first part is easy to do in python, I can use <code>os.walk</code> to walk the folders and get the files and upload the file using th... | 0 | 2016-08-30T15:08:58Z | 39,237,239 | <p>In your <code>upload_file</code> call you will need to pass <code>GrantRead</code> in <code>ExtraArgs</code>. Generally speaking you can pass in any arguments that <a href="http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Client.put_object" rel="nofollow"><code>put_object</code></a> would take thi... | 0 | 2016-08-30T21:18:22Z | [
"python",
"python-2.7",
"boto3"
] |
python dictionary iteration for data frame filtering with multiple conditions | 39,231,176 | <p>I am basically trying to build basic search engine that returns results based on a parsed query.</p>
<p>I have a dictionary that is user generated based on parsed input from their string:</p>
<pre><code>input = {âcolorâ: [âblackâ], âmakeâ: [âhondaâ], âtypeâ: [ââ]}
</code></pre>
<p>I am the... | 0 | 2016-08-30T15:10:04Z | 39,233,351 | <p>Let <code>d</code> be your dict, then:</p>
<pre><code>cond = [df[k].apply(lambda k: k in v if v != [''] else True) for k, v in d.items()]
cond_total = functools.reduce(lambda x, y: x & y, cond)
print(df[cond_total])
</code></pre>
<p>Output:</p>
<pre><code> make type color mpg year
2 honda suv black ... | 1 | 2016-08-30T17:09:42Z | [
"python",
"pandas",
"dictionary"
] |
creating admin restricted urls | 39,231,178 | <p>so in my urls.py (outside django default admin section ) i want to restrict some urls only to admin so if i have this for logged users </p>
<pre><code> from django.contrib.auth.decorators import login_required
urlpatterns = [
url(r'^a1$',login_required( views.admin_area1 ), name='a1'),
url(r'... | 2 | 2016-08-30T15:10:15Z | 39,231,312 | <p>You can use the decorator returned by <code>user_passes_test(lambda u: u.is_superuser)</code> in the same way that you use <code>login_required</code>:</p>
<pre><code>urlpatterns = [
url(r'^a1$', user_passes_test(lambda u: u.is_superuser)(views.admin_area1), name='a1'),
]
</code></pre>
<p>If you want to restri... | 7 | 2016-08-30T15:15:59Z | [
"python",
"django",
"django-1.9"
] |
reading csv file from panda and plotting | 39,231,188 | <p>I have 1000 files in which the data is stored in comma separation.
The description of a file is given below:</p>
<p>The values are comma separated, <code>-9999</code> values should be ignored and
if it can be read, all the values of row and column should be stored in numbers,
as it has to used in plotting.
The shap... | 0 | 2016-08-30T15:10:44Z | 39,231,415 | <p>I never used plot ,but following would be useful for the first question
input the list of values to na_values and those will be considered as NA by pandas</p>
<pre><code>pd.read_csv(File, sep=',',na_values=['-9999'],keep_default_na=False)
</code></pre>
<p>Also <a href="http://pandas.pydata.org/pandas-docs/stable/g... | 1 | 2016-08-30T15:20:34Z | [
"python"
] |
reading csv file from panda and plotting | 39,231,188 | <p>I have 1000 files in which the data is stored in comma separation.
The description of a file is given below:</p>
<p>The values are comma separated, <code>-9999</code> values should be ignored and
if it can be read, all the values of row and column should be stored in numbers,
as it has to used in plotting.
The shap... | 0 | 2016-08-30T15:10:44Z | 39,233,336 | <p>Once you've read the data in (Shijo's method looks good) the <a href="https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.pairplot.html" rel="nofollow">Seaborn library's pairplot</a> should generate the plot you want.</p>
| 0 | 2016-08-30T17:09:04Z | [
"python"
] |
Finding a pattern in python using re (reggae) | 39,231,204 | <p>I'm trying to build a regular expression:</p>
<pre><code>mystring = /some/path/with/%variable%/%inside%/%it%/
re.findall("[^\s%]+", allocine_spec[key])
</code></pre>
<p>And this return the following:</p>
<pre><code>['/some/path/', 'variable', '/', 'inside', '/', 'it']
</code></pre>
<p>But I would like only:</p>
... | 2 | 2016-08-30T15:11:54Z | 39,231,290 | <p>You need a much simpler regex:</p>
<pre><code>%([^%]+)%
</code></pre>
<p>See the <a href="https://regex101.com/r/iP1gV6/1">regex demo</a></p>
<p>This will match a <code>%</code>, then capture 1+ chars other than <code>%</code> into Group 1 and then will match a trailing <code>%</code>. If your strings only contai... | 5 | 2016-08-30T15:14:57Z | [
"python",
"regex",
"python-2.7"
] |
Compute y-value based on x-value and function - Python | 39,231,282 | <p>I'm currently trying to teach myself how to plot functions with matplotlib in Python, and I'm stuck on a rather simple task: <strong>Given a function f(x) = 2x +3, plot the coordinates in matplotlib.</strong> </p>
<p>I have solved this the hard way, through <em>manual</em> calculation, creating a list of both the x... | -1 | 2016-08-30T15:14:43Z | 39,231,408 | <p>The <code>lambda</code> function would be very useful in this situation. You can declare your function using <code>f = lambda x: 2*x + 3</code>. The <code>map</code> function would be a good way to obtain all of your <code>y</code> values in a simple way: <code>y = map(f, x)</code>.</p>
<p>Here is the documentation... | 0 | 2016-08-30T15:20:07Z | [
"python",
"function",
"matplotlib",
"range",
"coordinates"
] |
Compute y-value based on x-value and function - Python | 39,231,282 | <p>I'm currently trying to teach myself how to plot functions with matplotlib in Python, and I'm stuck on a rather simple task: <strong>Given a function f(x) = 2x +3, plot the coordinates in matplotlib.</strong> </p>
<p>I have solved this the hard way, through <em>manual</em> calculation, creating a list of both the x... | -1 | 2016-08-30T15:14:43Z | 39,231,458 | <p>Here's an easy way to plot your function within a certain range <code>[A,B]</code>:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
def graph(formula, x_range):
x = np.array(x_range)
y = formula(x)
plt.plot(x, y)
plt.show()
def f(x):
return 2 * x + 3
A, B = -10, 10
graph(f... | 0 | 2016-08-30T15:21:51Z | [
"python",
"function",
"matplotlib",
"range",
"coordinates"
] |
Ignoring Time gaps larger than x mins Matplotlib in Python | 39,231,410 | <p>I get data every 5 mins between 9:30am and 4pm. Most days I just plot live intraday data. However, sometimes I want a historical view of lets says 2+ days. The only problem is that during 4pm and 9:30 am I just get a line connecting the two data points. I would like that gap to disappear. My code and an example of w... | 0 | 2016-08-30T15:20:15Z | 39,235,253 | <p>So it looks like you're using a pandas object, which is helpful. Assuming you have filtered out any time between 4pm and 9am in <code>data['Date_Time']</code>, I would make sure your index is reset via <code>data.reset_index()</code>. You'll want to use that integer index as the under-the-hood index that matplotlib ... | 1 | 2016-08-30T19:04:44Z | [
"python",
"matplotlib",
"time-series",
"graphing",
"timeserieschart"
] |
What is the best way to quote unquoted strings while leaving already quoted strings alone? | 39,231,418 | <p>I have a large block of text that is almost JSON, but is not quite. I need to make it JSON so that I can process it. Specifically, it is the "marks" object in the code at the following page: <a href="https://en.wikipedia.org/wiki/Module:Syrian_Civil_War_detailed_map" rel="nofollow">https://en.wikipedia.org/wiki/Modu... | 0 | 2016-08-30T15:20:36Z | 39,231,760 | <p>This looks for any lines that does not already have any <code>"</code> characters. For those lines have an alphabetic character or an underline after the equal sign, then the quantity after the equal sign is placed in quotes:</p>
<pre><code>$ sed -E '/"/!s/= +(.*[[:alpha:]_].*),/= "\1",/' file
marks = {
lat = ... | 0 | 2016-08-30T15:36:24Z | [
"python",
"json",
"regex",
"string",
"sed"
] |
What is the best way to quote unquoted strings while leaving already quoted strings alone? | 39,231,418 | <p>I have a large block of text that is almost JSON, but is not quite. I need to make it JSON so that I can process it. Specifically, it is the "marks" object in the code at the following page: <a href="https://en.wikipedia.org/wiki/Module:Syrian_Civil_War_detailed_map" rel="nofollow">https://en.wikipedia.org/wiki/Modu... | 0 | 2016-08-30T15:20:36Z | 39,231,885 | <p>Process each line of text separately (assumes items do not span across lines)</p>
<p>Strip off the trailing comma</p>
<p>Split each line at the first equals sign</p>
<p>For each sub-item produced by splitting:</p>
<ul>
<li>Strip off leading/trailing spaces</li>
<li>If it's equal to <code>{</code> or <code>}</cod... | 0 | 2016-08-30T15:42:12Z | [
"python",
"json",
"regex",
"string",
"sed"
] |
What is the best way to quote unquoted strings while leaving already quoted strings alone? | 39,231,418 | <p>I have a large block of text that is almost JSON, but is not quite. I need to make it JSON so that I can process it. Specifically, it is the "marks" object in the code at the following page: <a href="https://en.wikipedia.org/wiki/Module:Syrian_Civil_War_detailed_map" rel="nofollow">https://en.wikipedia.org/wiki/Modu... | 0 | 2016-08-30T15:20:36Z | 39,231,926 | <p>With a regex as</p>
<pre><code>(^[^\n\S]*|=\s*)(?![\d\s])(\w+[^,\s]*)
</code></pre>
<p>and a replacement of</p>
<pre><code>\1"\2"
</code></pre>
<p>you would get <a href="https://regex101.com/r/mQ9rI9/1" rel="nofollow">these results</a>. You can switch from Python to any other flavor, if you think you will be usi... | 1 | 2016-08-30T15:43:51Z | [
"python",
"json",
"regex",
"string",
"sed"
] |
What is the best way to quote unquoted strings while leaving already quoted strings alone? | 39,231,418 | <p>I have a large block of text that is almost JSON, but is not quite. I need to make it JSON so that I can process it. Specifically, it is the "marks" object in the code at the following page: <a href="https://en.wikipedia.org/wiki/Module:Syrian_Civil_War_detailed_map" rel="nofollow">https://en.wikipedia.org/wiki/Modu... | 0 | 2016-08-30T15:20:36Z | 39,235,114 | <pre><code>$ cat tst.awk
/=/ {
lhs = rhs = $0
sub(/[[:space:]]*=.*/,"",lhs)
sub(/^[^=]+=[[:space:]]*/,"",rhs)
sub(/[^[:space:]]+/,"\"&\"",lhs)
if ( rhs !~ /^([0-9]+\.?[0-9]*|".*"),?$/ ) {
sub(/,?$/,"\"&",rhs)
rhs = "\"" rhs
}
$0 = lhs " = " rhs
}
{ print }
$ awk -... | 0 | 2016-08-30T18:56:09Z | [
"python",
"json",
"regex",
"string",
"sed"
] |
Error with Fibonacci sequence in python | 39,231,469 | <p>Edit - All fixed thank you </p>
<pre><code>fib=[0,1]
for i in range(0,700):
fib.append(fib[len(fib)-2]+fib[len(fib)-1])
print(fib[len(fib)-1])
print('Do you want a range of numbers or single?')
answer=input()
if answer=='single':
print('Which number?')
number=int(input())
fib[number]
elif ans... | 0 | 2016-08-30T15:22:22Z | 39,231,936 | <pre><code>fib=[0,1]
for i in range(0,700):
fib.append(fib[len(fib)-2]+fib[len(fib)-1])
print(fib[len(fib)-1])
answer=input('Do you want a range of numbers or single?')
if answer=='single':
number=int(input('Which number?[index]: '))
print(fib[number])
elif answer=='range':
firstNumber=int(input('Fr... | 2 | 2016-08-30T15:44:36Z | [
"python"
] |
How to debug Protocol.dataReceived in Twisted | 39,231,472 | <p>I'm new to twisted and I'm having trouble to debug my code within the <code>dataReceived</code> method of the <code>twisted.internet.protocol.Protocol</code> object.</p>
<p>Given some code like this</p>
<pre><code>class Printer(Protocol):
def dataReceived(self, data):
print data # Works perfectly
... | 0 | 2016-08-30T15:22:28Z | 39,234,703 | <p>You can't catch errors from <code>dataReceived</code> directly since that function isn't a <code>deferred</code> user's generally have control over. You can only call <code>addErrback</code> on <code>deferred</code> objects. Here is an example of how to catch errors:</p>
<pre><code>from twisted.internet.protocol ... | 1 | 2016-08-30T18:31:04Z | [
"python",
"asynchronous",
"twisted"
] |
__init__() missing 1 required positional argument: 'quantity' | 39,231,476 | <p>I am getting the error as shown in the question, and I can't figure out why. Even when trying other stackoverflow methods of fixing this it doesn't work.</p>
<p>Thanks all :)</p>
<pre><code>class Item(object):
def __init__(self, name, style, quantity):
self.name = name
self.style = style
... | 0 | 2016-08-30T15:22:46Z | 39,231,533 | <p>Change </p>
<pre><code>Item.__init__(name, style, quantity,)
</code></pre>
<p>for</p>
<pre><code>super().__init__(name, style, quantity)
</code></pre>
| 4 | 2016-08-30T15:25:25Z | [
"python",
"python-3.x"
] |
__init__() missing 1 required positional argument: 'quantity' | 39,231,476 | <p>I am getting the error as shown in the question, and I can't figure out why. Even when trying other stackoverflow methods of fixing this it doesn't work.</p>
<p>Thanks all :)</p>
<pre><code>class Item(object):
def __init__(self, name, style, quantity):
self.name = name
self.style = style
... | 0 | 2016-08-30T15:22:46Z | 39,231,593 | <p>Simply use <code>super</code> for inheritance in Python (read <a href="http://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods">here</a> for more details):</p>
<pre><code>class Weapon(Item):
def __init__(self, name, style, quantity = 1):
super(Weapon, self).__init__(name... | 0 | 2016-08-30T15:28:49Z | [
"python",
"python-3.x"
] |
__init__() missing 1 required positional argument: 'quantity' | 39,231,476 | <p>I am getting the error as shown in the question, and I can't figure out why. Even when trying other stackoverflow methods of fixing this it doesn't work.</p>
<p>Thanks all :)</p>
<pre><code>class Item(object):
def __init__(self, name, style, quantity):
self.name = name
self.style = style
... | 0 | 2016-08-30T15:22:46Z | 39,231,704 | <p>You're missing <strong><code>self</code></strong> in the <code>Item._init__()</code>. You can either </p>
<ol>
<li><p>Add self:</p>
<pre><code>class Weapon(Item):
def __init__(self, name, style, quantity = 1):
Item.__init__(self, name, style, quantity)
</code></pre></li>
<li><p>Use super: </p>
<pre><code>clas... | 1 | 2016-08-30T15:34:02Z | [
"python",
"python-3.x"
] |
__init__() missing 1 required positional argument: 'quantity' | 39,231,476 | <p>I am getting the error as shown in the question, and I can't figure out why. Even when trying other stackoverflow methods of fixing this it doesn't work.</p>
<p>Thanks all :)</p>
<pre><code>class Item(object):
def __init__(self, name, style, quantity):
self.name = name
self.style = style
... | 0 | 2016-08-30T15:22:46Z | 39,231,705 | <p>Calling <code>Item.__init__</code> directly means you need to pass <code>self</code> as the first argument. Simply doing <code>Item.__init__(name, style, quantity)</code> means it thinks that <code>name</code> is the Item instance (self) and style is the name, quantity is the style and quantity is missing.</p>
<p>... | 1 | 2016-08-30T15:34:05Z | [
"python",
"python-3.x"
] |
How do I run one def function inside of a different def function in python? | 39,231,512 | <p>I'm trying to run a timer inside of a function of my code. I need to start the timer slightly before the user starts typing, then stop the timer when the user has entered the alphabet correctly.
Here is my code:</p>
<pre><code>import time
timec = 0
timer = False
print("Type the alphabet as fast as possible.\nYou M... | 0 | 2016-08-30T15:24:31Z | 39,231,641 | <pre><code>import time
start = time.time()
attempt = input("Start typing now: ")
finish = time.time()
if attempt == "abcdefghijklmnopqrstuvwxyz":
print "Well done, that took you %s seconds.", round(finish-start, 4)
else:
print "Sorry, there where errors."
</code></pre>
| 2 | 2016-08-30T15:31:24Z | [
"python",
"function",
"time",
"timer"
] |
How do I run one def function inside of a different def function in python? | 39,231,512 | <p>I'm trying to run a timer inside of a function of my code. I need to start the timer slightly before the user starts typing, then stop the timer when the user has entered the alphabet correctly.
Here is my code:</p>
<pre><code>import time
timec = 0
timer = False
print("Type the alphabet as fast as possible.\nYou M... | 0 | 2016-08-30T15:24:31Z | 39,231,733 | <p>Think carefuly about that you are dong</p>
<ol>
<li>You ask for a user-entered string</li>
<li>While <code>timer</code> equals <code>True</code>, you sleep for one second and increase the count. In this loop, you do not change the <code>timer</code>.</li>
</ol>
<p>Obviously, once user stopped entering the alphabet... | 2 | 2016-08-30T15:35:04Z | [
"python",
"function",
"time",
"timer"
] |
How do I run one def function inside of a different def function in python? | 39,231,512 | <p>I'm trying to run a timer inside of a function of my code. I need to start the timer slightly before the user starts typing, then stop the timer when the user has entered the alphabet correctly.
Here is my code:</p>
<pre><code>import time
timec = 0
timer = False
print("Type the alphabet as fast as possible.\nYou M... | 0 | 2016-08-30T15:24:31Z | 39,232,098 | <p>you could do something like: </p>
<pre><code>import datetime
alphabet = 'abcdefghijklmnopqrstuvwxyz'
print('Type the alphabet as fast as possible.\nYou MUST be accurate!\nYou will be timed"')
init_time = datetime.datetime.now()
success_time = None
while True:
user_input = input('The timer has started!\nType ... | 0 | 2016-08-30T15:53:19Z | [
"python",
"function",
"time",
"timer"
] |
Python XML Parsing issue | 39,231,535 | <p>I have an XML as attached below and using python minidom to parse the build.xml. I am trying below python code to parse and retrieve the "name" and "value" tag. I am trying to retrieve the values for "SE_CONFIG","SE_ARCH","PREBUILDID" which have respective value install-csu,macosx,prebuild_7701.</p>
<p>Having foll... | 0 | 2016-08-30T15:25:26Z | 39,231,907 | <p>Since you asked if there is another way, you can try using <strong>xml.etree.ElementTree</strong>. </p>
<p>There is a cool example in the following link, the tags can be defined in the for loop:</p>
<p><a href="http://chimera.labs.oreilly.com/books/1230000000393/ch06.html#_solution_96" rel="nofollow">http://chimer... | 3 | 2016-08-30T15:43:07Z | [
"python",
"xml",
"minidom"
] |
Python XML Parsing issue | 39,231,535 | <p>I have an XML as attached below and using python minidom to parse the build.xml. I am trying below python code to parse and retrieve the "name" and "value" tag. I am trying to retrieve the values for "SE_CONFIG","SE_ARCH","PREBUILDID" which have respective value install-csu,macosx,prebuild_7701.</p>
<p>Having foll... | 0 | 2016-08-30T15:25:26Z | 39,243,890 | <p>Get it done through ElementTree</p>
<pre><code> doc =xml.etree.ElementTree.parse('build.xml')
for node in doc.iter('hudson.model.StringParameterValue'):
print str(node.find('name').text) + '\t' + str(node.find('value').text)
</code></pre>
| 1 | 2016-08-31T07:59:26Z | [
"python",
"xml",
"minidom"
] |
Cosine similarity yields 'nan' values pt.II | 39,231,600 | <p>This is the other side of this question: <a href="http://stackoverflow.com/questions/33651788/cosine-similarity-yields-nan-values">Cosine similarity yields 'nan' values</a> .
In that topic, auther coded the metrics by himself, but iam using scipy's cosine: (<code>ratings</code> is 71869x10000)</p>
<pre><cod... | 1 | 2016-08-30T15:29:04Z | 39,232,797 | <p>The cosine distance is not defined if one of the input vectors is all 0. <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cosine.html" rel="nofollow"><code>scipy.spatial.distance.cosine</code></a> returns <code>nan</code> in that case:</p>
<pre><code>In [70]: a
Out[70]: array([0,... | 1 | 2016-08-30T16:35:22Z | [
"python",
"numpy",
"scipy"
] |
ConnectionError with Messenger bot | 39,231,607 | <p>I'm using messenger bot with pymessenger (here the link <a href="https://github.com/davidchua/pymessenger" rel="nofollow">https://github.com/davidchua/pymessenger</a> ).
Sometimes, when I try to send messages to the user using the bot.send_text_message() or one of the other functions to send messages of the python p... | 0 | 2016-08-30T15:29:47Z | 39,232,489 | <p>try to catch the HTTPSConnectionPool exception and look into its args to see the details I mean something like</p>
<pre><code>except HTTPSConnectionPool as e:
e.args
</code></pre>
| 0 | 2016-08-30T16:16:48Z | [
"python",
"bots",
"facebook-messenger"
] |
Dynamic Variable Naming for tree[Python] | 39,231,687 | <p>I have made a tree structure for preorder traversal.
And I can manually name all the variables.</p>
<p>Is there a way to make a variable. I need a tree structure as follows:</p>
<pre><code> 0
1 2
3 4 5 6
7 8 9 10 11 12 13 14
...
</code></pre>
<p>and so on.</p>
<pre><code>import time
c... | -1 | 2016-08-30T15:33:23Z | 39,231,948 | <p>It seems that you are going from left-to-right on the tree. If we represent the path in binary, the leftmost branch (on the forth layer down) as <code>0000</code> (<code>.left.left.left.left</code>) then then next number would be <code>0001</code> (<code>.left.left.left.right</code>). Then it would be <code>0010</co... | 0 | 2016-08-30T15:45:16Z | [
"python",
"variables",
"dynamic",
"tree",
"traversal"
] |
Python: I have a string and a list of lists of varying lengths and I want to return the letters in groups as they correspond to the list | 39,231,826 | <p>Imagine that I have a string that is 5 letters long, say 'ABCDE'. I also have a list of lists of the different way to split the list i.e. [[5], [4, 1], [3, 2], ... [1, 1, 1, 1, 1]]. How could return all the different ways to split the list, like below. The problem I am having is setting up a loop with uneven numb... | 3 | 2016-08-30T15:39:15Z | 39,232,117 | <p>That is a classic brute force problem. You have to generate all options of where you can split the string. You can either split it between each two letters or not. </p>
<p>For string of length n there are n - 1 places you can possibly split it</p>
<pre><code>a b c d e
^ ^ ^ ^
</code></pre>
<p>Thus, each binary (... | 3 | 2016-08-30T15:54:37Z | [
"python",
"string",
"list"
] |
Python: I have a string and a list of lists of varying lengths and I want to return the letters in groups as they correspond to the list | 39,231,826 | <p>Imagine that I have a string that is 5 letters long, say 'ABCDE'. I also have a list of lists of the different way to split the list i.e. [[5], [4, 1], [3, 2], ... [1, 1, 1, 1, 1]]. How could return all the different ways to split the list, like below. The problem I am having is setting up a loop with uneven numb... | 3 | 2016-08-30T15:39:15Z | 39,232,152 | <p>If you want to apply that configuration list of lists containing possible "slices" of a string, here is a way to do it - basically, we take a slice and pass the rest of the string to the next step:</p>
<pre><code>s = 'ABCDE'
c = [[5], [4, 1], [3, 2], [1, 1, 1, 1, 1]]
for item in c:
result = []
s_copy = s
... | 3 | 2016-08-30T15:56:27Z | [
"python",
"string",
"list"
] |
Python: I have a string and a list of lists of varying lengths and I want to return the letters in groups as they correspond to the list | 39,231,826 | <p>Imagine that I have a string that is 5 letters long, say 'ABCDE'. I also have a list of lists of the different way to split the list i.e. [[5], [4, 1], [3, 2], ... [1, 1, 1, 1, 1]]. How could return all the different ways to split the list, like below. The problem I am having is setting up a loop with uneven numb... | 3 | 2016-08-30T15:39:15Z | 39,232,303 | <p>The previous answer is correct, but Python allows us to write this in much more compact fashion:</p>
<pre><code>def my_split(string, config):
return [string[sum(config[:i]):sum(config[:i+1])] for i in range(len(config))]
</code></pre>
<p>To get the result for all configurations, you simply need to loop over th... | 0 | 2016-08-30T16:04:50Z | [
"python",
"string",
"list"
] |
How to write a txt with the following list using pandas? | 39,231,865 | <p>Hello I am using pandas to process a excel file my code looks as follows:</p>
<pre><code>df = xl.parse("Sheet1")
important_Parameters="bash generate.sh --companyCode"+" "+df[u'Company Code '].astype(str)+" "+"--isaADD"+df[u'TP Interchange Address '].astype(str)+" "+"--gsADD"+" "+df[u'TP Functional Group Address ']... | 2 | 2016-08-30T15:41:17Z | 39,231,987 | <p>Panda dataframes have more than a few methods for saving to files. Have you tried <code>important_Parameters.to_csv("important.csv")</code>? I'm not certain what you want the output to look like.</p>
<p>If you want it tab-separated, you can try:
<code>important_Parameters.to_csv("important.csv", sep='\t')</code... | 2 | 2016-08-30T15:47:09Z | [
"python",
"pandas"
] |
How to get the absolute url in python | 39,231,900 | <p>I am currently working on a http server in python. I have subclassed BaseHttpRequestHandler to handler a get/post request. As per documentation, BaseHttpRequestHandler has an instance variable path, but how do i get the full request url</p>
<p>Example <a href="http://www.cnn.com/index.html" rel="nofollow">http://w... | 0 | 2016-08-30T15:42:54Z | 39,232,224 | <p>You can get the server name (and port, if the server is on a specific port) via <code>self.server.server_name</code> and <code>self.server.server_port</code>. Then just concatenate them - assuming you have a port, and that the server name doesn't include a trailing '/' (can't check at the moment, myself):</p>
<pre>... | 0 | 2016-08-30T15:59:39Z | [
"python",
"python-2.7",
"http",
"http-headers"
] |
Sympy coeff not consistent with as_independent | 39,231,911 | <p>I have the following snippet of code</p>
<pre><code>import sympy
a = sympy.symbols('a')
b = sympy.symbols('b')
c = sympy.symbols('c')
print((a*b).coeff(c,0))
print((a*b).as_independent(c)[0])
</code></pre>
<p>I don't understand why the two print statements print different output. According to the documentation o... | 2 | 2016-08-30T15:43:21Z | 39,399,240 | <p>It's a bug. I have a pull request fixing it <a href="https://github.com/sympy/sympy/pull/11590" rel="nofollow">here</a>. </p>
| 1 | 2016-09-08T19:58:47Z | [
"python",
"sympy"
] |
Django AUTH_USER_MODEL not registering custom User class | 39,231,917 | <p>I've got this setup in my models</p>
<p>from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.db import models</p>
<pre><code>class AccountManager(BaseUserManager):
def create_user(self, email, password=None, **kwargs):
. . .
def create_superuser(self, email, password... | 0 | 2016-08-30T15:43:27Z | 39,232,666 | <p>Explicitly specify the manager inside your custom user model:</p>
<pre><code>class Account(AbstractBaseUser):
objects = AccountManager()
....
</code></pre>
| 0 | 2016-08-30T16:28:07Z | [
"python",
"django"
] |
What's the correct way to access methods of a member variable in a class pointing to an object? | 39,231,932 | <p>What's the correct way to define/access methods of a member variable in a class pointing to an object?</p>
<p>For example, I have a class <code>Foo</code> that has a method <code>foo_method</code>:</p>
<pre><code>class Foo:
def foo_method(self):
return 'bar'
</code></pre>
<p>Now, in another class <cod... | 0 | 2016-08-30T15:44:15Z | 39,237,874 | <p>There are no real guidelines, but if you make a <code>bar_method()</code> that explicitly calls <code>foo.bar()</code> and does nothing in between it's the exact same coupling and less convenient.</p>
<p>Python's idioms include "<a href="http://docs.python-guide.org/en/latest/writing/style/#we-are-all-responsible-u... | 2 | 2016-08-30T22:12:16Z | [
"python",
"design-patterns",
"python-3.5",
"composition"
] |
keras: multiple w_constraints | 39,231,977 | <p>I want a set of weights to be constrained to have a fixed norm (as in <code>unitnorm</code>) and non-negative values (as in <code>nonneg</code>). This pair of constraints is useful in some kinds of optical modeling.</p>
<p>I'm not a Python expert, so I tried <code>W_constraint = nonneg(), W_constraint = maxnorm(1)... | 0 | 2016-08-30T15:46:38Z | 39,259,405 | <p>If you look at the topology.py file in the keras source code it has a property:</p>
<pre><code> @property
def constraints(self):
cons = {}
for layer in self.layers:
for key, value in layer.constraints.items():
if key in cons:
raise Exception('Received multiple constrai... | 1 | 2016-08-31T21:37:12Z | [
"python",
"constraints",
"keras"
] |
How to map results of `dask.DataFrame` to csvs | 39,231,984 | <p>I create a dataframe with <code>df=dask.DataFrame.read_csv('s3://bucket/*.csv')</code>. When i execute a <code>df[df.a.isnull()].compute</code> operation, i get a set of rows returned that match the filter criteria. I would like to know which files do these returned rows belong in so that i could investigate why suc... | 1 | 2016-08-30T15:46:53Z | 39,232,198 | <p>If your CSV files are small then I recommend creating one partition per file</p>
<pre><code>df = dd.read_csv('s3://bucket/*.csv', blocksize=None)
</code></pre>
<p>And then computing the number of null elements per partition:</p>
<pre><code>counts = df.a.isnull().map_partitions(sum).compute()
</code></pre>
<p>You... | 0 | 2016-08-30T15:58:43Z | [
"python",
"dask"
] |
Extracting tables using pandas read_html function? | 39,232,013 | <p>This is an unusual problem. I am trying to extract a table from certain website(link cant be given because of security). The problem is that the site will load the table when accessed through website but when we use <code>inspect element</code> on any values/tables on that table it is not visible. It just show <code... | 0 | 2016-08-30T15:48:33Z | 39,232,261 | <p>When data scraping off a secure website, the website can be using Java to load the tables so you never see the HTML-styled code. This could be why BeautifulSoup is not returning anything. </p>
<p>Does the "scripts and links inside" look like Java? </p>
<p>Maybe have a look at <a href="http://selenium-python.readth... | 0 | 2016-08-30T16:01:55Z | [
"python",
"html",
"pandas",
"web-scraping"
] |
Smartsheet API failure to recognize number values when creating row objects | 39,232,147 | <p>I need help adding numbers to a row update using the Smartsheet Python SDK. I am attempting to update/add specific cell values programmatically via a Python script. An example of the code I am using is:</p>
<pre><code>import smartsheet
smartsheet = smartsheet.Smartsheet(TokenString)
row = smartsheet.models.Row(... | 0 | 2016-08-30T15:56:11Z | 39,257,507 | <p>Trying this out myself I experienced the same thing. Only representing the value as a string did it enter into my sheet, otherwise it was a null/blank row. I have reported this as an issue on Github for the <a href="https://github.com/smartsheet-platform/smartsheet-python-sdk/issues/49" rel="nofollow">Python SDK</a>... | 1 | 2016-08-31T19:24:02Z | [
"python",
"smartsheet-api"
] |
Python speech recognition error converting mp3 file | 39,232,150 | <p>My first try on audio to text. </p>
<pre><code>import speech_recognition as sr
r = sr.Recognizer()
with sr.AudioFile("/path/to/.mp3") as source:
audio = r.record(source)
</code></pre>
<p>When I execute the above code, the following error occurs,</p>
<pre><code><ipython-input-10-72e982ecb706> in <mod... | 0 | 2016-08-30T15:56:19Z | 39,232,767 | <p><code>Speech recognition</code> supports WAV file format.
Here is a sample WAV to text program using <code>speech_recognition</code>:</p>
<h3>Sample code (Python 3)</h3>
<pre><code>import speech_recognition as sr
r = sr.Recognizer()
with sr.AudioFile("woman1_wb.wav") as source:
audio = r.record(source)
try:
... | 2 | 2016-08-30T16:33:52Z | [
"python",
"speech-recognition",
"speech-to-text"
] |
Extending Flask class as main App | 39,232,166 | <p>I'm learning Flask and am a bit confused about how to structure my code. So I tried to extend Flask main class as follows:</p>
<pre><code>from flask import Flask, ...
class App(Flask):
def __init__(self, import_name, *args, **kwargs):
super(App, self).__init__(import_name, *args, **kwargs)
</code></pre... | 1 | 2016-08-30T15:57:10Z | 39,232,991 | <p>Doing this doesn't make sense. You would subclass <code>Flask</code> to change its internal behavior, not to define your routes as class methods.</p>
<p>Instead, you're looking for <a href="http://flask.pocoo.org/docs/0.11/blueprints/" rel="nofollow">blueprints</a> and the <a href="http://flask.pocoo.org/docs/0.11... | 3 | 2016-08-30T16:46:32Z | [
"python",
"flask"
] |
handle errors in Python ArgumentParser | 39,232,167 | <p>I want to manually handle the situation where <code>parse_args()</code> throws an error in case of a unknown value for an argument. For example:
If I have the following python file called <code>script.py</code>:</p>
<pre><code>argp = argparse.ArgumentParser(description='example')
argp.add_argument('--compiler', cho... | 2 | 2016-08-30T15:57:11Z | 39,233,308 | <p>The whole point to defining choices is to make the parser complain about values that are not in the list. But there are some alternatives:</p>
<ul>
<li><p>omit choices (include them in the help text if you want), and do your own testing after parsing. <code>argparse</code> doesn't have to do everything for you. I... | 2 | 2016-08-30T17:07:17Z | [
"python",
"python-2.7",
"python-3.x",
"argparse"
] |
Is my model underfitting, tensorflow? | 39,232,176 | <p>My loss first decreased for few epochs but then started increasing and then increased up to a certain point and then stopped moving. I think now it has converged. Now, can we say that my model is underfitting? Because my interpretation is that (slide 93 <a href="http://cs231n.stanford.edu/slides/winter1516_lecture5.... | 0 | 2016-08-30T15:57:25Z | 39,234,296 | <p>So, to summarize, the loss on the training data:</p>
<ul>
<li>first went down</li>
<li>then it went up again</li>
<li>then it remains at the same level</li>
<li>then the learning rate is decayed</li>
<li>and the loss doesn't go back down again (still stays the same with decayed learning rate)</li>
</ul>
<p>To me i... | 2 | 2016-08-30T18:06:19Z | [
"python",
"machine-learning",
"neural-network",
"tensorflow",
"deep-learning"
] |
Emit socket.io message with Python using nodejs as server | 39,232,231 | <p>I need a bit of help.</p>
<p>I'm doing tests to learn how to build a realtime web, so I use node.js with socket.io. All works fun but if I try to publish some message in the channel that is listening node with a different source that isn't node or javascript it crashes.</p>
<p>Server side: (node that fails when a ... | 0 | 2016-08-30T15:59:54Z | 39,232,668 | <p><code>socket.io-redis</code> uses <a href="https://github.com/socketio/socket.io-redis/blob/40c6d284e5e3beff680bc289c393f562192a5328/index.js#L140" rel="nofollow"><code>msgpack</code></a> on top of Redis to pub/sub messages, so you can't just push regular strings to it and expect it to work. The client you're using ... | 0 | 2016-08-30T16:28:14Z | [
"python",
"node.js",
"redis",
"socket.io",
"msgpack"
] |
How to get a uuid with python requests | 39,232,293 | <p>I am attempting to log into a web page using the python requests module but the Post data on the website that I want to log into includes a uuid tag.</p>
<pre><code>pass: ********
user: ********
uuid: ********
</code></pre>
<p>I have thoroughly searched for any mention of this anywhere in most requests documentati... | 1 | 2016-08-30T16:04:10Z | 39,233,039 | <p>You can parse it from the source:</p>
<pre><code>In [29]: from bs4 import BeautifulSoup
In [30]: import re
In [31]: patt = re.compile("document.cplogin.uuid.value=\"(.*?)\"")
In [32]: with requests.Session() as s:
....: page = s.get('http://myneu.neu.edu/cp/home/displaylogin').content
....: ... | 2 | 2016-08-30T16:49:57Z | [
"python",
"http",
"post",
"login",
"python-requests"
] |
ATLAS on a python virtualenv in Fedora for numpy/scipy/scikit-learn | 39,232,482 | <p>I am struggeling to let python find and use the installed ATLAS libraries from my distribution when using virtualenv.</p>
<p>This is on Fedora 21, atlas, atlas-devel, blas, blas-devel are installed. Outside of a virtualenv, the command <code>python -c 'import numpy; numpy.show_config()'</code> shows that I have ATL... | 1 | 2016-08-30T16:16:29Z | 39,233,754 | <p>You need to tell numpy's setup.py where to find your ATLAS libraries.</p>
<p>Try creating a <code>.numpy-site.cfg</code> file in your home folder before running <code>pip install</code>. <a href="https://github.com/numpy/numpy/blob/master/site.cfg.example" rel="nofollow">Here's</a> the template for this file. </p>
... | 1 | 2016-08-30T17:34:53Z | [
"python",
"numpy",
"virtualenv",
"blas",
"atlas"
] |
How to seperate a python file to couple files, making a real game with files | 39,232,492 | <p>I made a little game with python/pygame. It's in one folder and it's 300+ lines. I want to develop this little game. I'm seeing lots of games
made by pygame, and I'm seeing they have folders like <code>main.py</code> , <code>classes.py</code> and <code>setup.py</code>.</p>
<p>But I only know the python language an... | -2 | 2016-08-30T16:16:57Z | 39,237,042 | <p>To import a file called <em>script.py</em> from the same directory as your main file:</p>
<pre><code>import script
</code></pre>
<p>To import a file called <em>script.py</em> from a sub directory called <em>app</em>:</p>
<pre><code>import sys
sys.path.insert('app')
import script
</code></pre>
<p>To import a file... | 1 | 2016-08-30T21:02:17Z | [
"python",
"pygame"
] |
needs to find \t in the middle of a string | 39,232,555 | <p>I have a json file with two variables:</p>
<pre><code>\t\t"ROW_ID" : 475895,
\t\t"TEXT" : "TITLE:\tCardiology Consult\n\t24 Hour Events:\n\tPatient without any further...
</code></pre>
<p>I need to find the tabs (<code>\t</code>) in the middle of <code>TEXT</code> (because I cannot load this into python correctly... | 0 | 2016-08-30T16:20:49Z | 39,238,316 | <p>Simple. With a negative lookbehind, you can make sure you're not unnecessarily removing the tabs that come right after newlines.</p>
<pre><code>(?<!\n)\t+
</code></pre>
<p>If you're worried that <code>\n</code> will match the character <code>n</code> instead of a newline on some regex engines, use <code>\x0A</c... | 0 | 2016-08-30T22:57:54Z | [
"python",
"json",
"regex"
] |
create 2d array with lists as entries | 39,232,625 | <p>I want to create a 2d numpy array that contains python lists as entries.
The mainprogram will append IDs to each entry. In the end I need to search for the entry with the most appended IDs. I will need these IDs later on and because of this a simple 2d array with integer entries, that just get incremented, won't sol... | 0 | 2016-08-30T16:24:28Z | 39,244,240 | <p>You can try to create an empty numpy array of object type and then assign lists to array entries, you have to adapt your code as such</p>
<pre><code>evaluatelist = np.empty(image.shape, dtype=object)
for x in xrange(evaluatelist.shape[0]):
for y in xrange(evaluatelist.shape[1]):
evaluatelist[x,y] = []
<... | 0 | 2016-08-31T08:17:52Z | [
"python",
"arrays",
"list",
"numpy"
] |
Why can't I define a class in main()? | 39,232,627 | <p>I'm trying to define a class in my main() method but when I run the code the console states 'g' is not defined. If I put the definition of g anywhere else it seems to work fine. What is wrong?</p>
<pre><code>class graph(object):
def __init__(self):
self.nodes = []
self.edges = []
self.gr... | -2 | 2016-08-30T16:24:33Z | 39,232,654 | <p>You have defined <code>g</code>. However, you defined it inside your <code>main()</code> function scope. In the console, you are outside this scope, so you can't refer to <code>g</code> anymore.</p>
| 1 | 2016-08-30T16:26:57Z | [
"python",
"class",
"main"
] |
Why can't I define a class in main()? | 39,232,627 | <p>I'm trying to define a class in my main() method but when I run the code the console states 'g' is not defined. If I put the definition of g anywhere else it seems to work fine. What is wrong?</p>
<pre><code>class graph(object):
def __init__(self):
self.nodes = []
self.edges = []
self.gr... | -2 | 2016-08-30T16:24:33Z | 39,232,657 | <p>The variable <code>g</code> is <em>local</em> and exists only inside <code>main()</code>, while you're trying to access it outside <code>main()</code>.</p>
<p>The following tutorial explains the difference between local and global variables: <a href="http://www.python-course.eu/global_vs_local_variables.php" rel="n... | 4 | 2016-08-30T16:27:15Z | [
"python",
"class",
"main"
] |
Why can't I define a class in main()? | 39,232,627 | <p>I'm trying to define a class in my main() method but when I run the code the console states 'g' is not defined. If I put the definition of g anywhere else it seems to work fine. What is wrong?</p>
<pre><code>class graph(object):
def __init__(self):
self.nodes = []
self.edges = []
self.gr... | -2 | 2016-08-30T16:24:33Z | 39,232,829 | <p>A way you can do this is using <a href="https://ipython.org/install.html" rel="nofollow">IPython</a>. <a href="http://ipython.readthedocs.io/en/stable/api/generated/IPython.terminal.embed.html#IPython.terminal.embed.embed" rel="nofollow"><code>IPython.embed(<strong><em>**kwargs</em></strong>)</code></a> will start t... | 0 | 2016-08-30T16:37:04Z | [
"python",
"class",
"main"
] |
Loop over multiple columns in dataframe | 39,232,632 | <p>I have a dataframe from a CSV file that has 61 columns and 1mil rows. 25 of those columns <code>(Flag_1, Flag_2, ..., Flag_25)</code> have <code>True/False</code> as values for each row of the dataframe.</p>
<p>What I'm trying to do is loop through each column to determine if there is a True for that entire row wit... | 2 | 2016-08-30T16:24:58Z | 39,232,739 | <p>Please try:</p>
<pre><code>data2['FLAG_ALL'] = data2.any(axis=1,bool_only=True).values
</code></pre>
<p>More info on <strong>any()</strong> <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.any.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFram... | 0 | 2016-08-30T16:31:53Z | [
"python",
"pandas",
"for-loop",
"dataframe"
] |
Loop over multiple columns in dataframe | 39,232,632 | <p>I have a dataframe from a CSV file that has 61 columns and 1mil rows. 25 of those columns <code>(Flag_1, Flag_2, ..., Flag_25)</code> have <code>True/False</code> as values for each row of the dataframe.</p>
<p>What I'm trying to do is loop through each column to determine if there is a True for that entire row wit... | 2 | 2016-08-30T16:24:58Z | 39,232,823 | <p>Given an example dataframe of:</p>
<pre><code>df = pd.DataFrame({
'flag_1': [False, False, True],
'flag_2': [False, False, False],
'flag_3': [True, False, False]})
</code></pre>
<p>You can use <code>df.filter</code> to get the appropriate columns (those starting with flag, an underscore and then digits... | 4 | 2016-08-30T16:36:49Z | [
"python",
"pandas",
"for-loop",
"dataframe"
] |
How to call Amazon API gateway with Groovy | 39,232,661 | <p>I am going to call API gateway from M2M cloud that uses limited version of Groovy inside and I can't use external SDK.
So I have checked for the description of the implementation and for some code samples.</p>
<ul>
<li>I found documentation - <a href="http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canoni... | -1 | 2016-08-30T16:27:27Z | 39,267,020 | <p>I have solved this issue. </p>
<p>I did the number of mistakes related to host, service, endpoint and request parameter. It is boring to describe each of them so I just add correct script below.</p>
<pre><code>import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import java.security.InvalidKeyException
i... | 0 | 2016-09-01T08:57:07Z | [
"python",
"amazon-web-services",
"groovy",
"amazon-api",
"amazon-api-gateway"
] |
pandas ordering columns misses values | 39,232,736 | <p>Not sure on the right title for this. But I have a need to take out a column from a dataframe, and show the top five results. The column is a mix of integers and n/a results. As an example I create a basic dataframe:</p>
<pre><code>regiona col1
a n/a
a 1
a 200
b 208
b 400
b 560
b 600
c 800
c 1120
... | 2 | 2016-08-30T16:31:46Z | 39,232,878 | <p>Check your dataframe's <code>dtypes</code>, now it is <code>object</code>. So first make sure <code>col1</code>'s datatype is numeric.
Use <code>na_values</code> at <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>pd.read_csv()</code></a> and your function wi... | 5 | 2016-08-30T16:40:34Z | [
"python",
"pandas"
] |
pandas ordering columns misses values | 39,232,736 | <p>Not sure on the right title for this. But I have a need to take out a column from a dataframe, and show the top five results. The column is a mix of integers and n/a results. As an example I create a basic dataframe:</p>
<pre><code>regiona col1
a n/a
a 1
a 200
b 208
b 400
b 560
b 600
c 800
c 1120
... | 2 | 2016-08-30T16:31:46Z | 39,232,940 | <p>You could also do:</p>
<pre><code>df['col1'] = pd.to_numeric(df['col1'], errors='coerce')
df.dropna().sort_values(['col1'], ascending=False).head(5)
regiona col1
10 c 1680.0
9 c 1200.0
8 c 1120.0
7 c 800.0
6 b 600.0
</code></pre>
| 3 | 2016-08-30T16:43:52Z | [
"python",
"pandas"
] |
Numpy Vectorization of sliding-window operation | 39,232,790 | <p>I have the following numpy arrays:</p>
<pre><code>arr_1 = [[1,2],[3,4],[5,6]] # 3 X 2
arr_2 = [[0.5,0.6],[0.7,0.8],[0.9,1.0],[1.1,1.2],[1.3,1.4]] # 5 X 2
</code></pre>
<p><code>arr_1</code> is clearly a <code>3 X 2</code> array, whereas <code>arr_2</code> is a <code>5 X 2</code> array. </p>
<p>Now without loo... | 4 | 2016-08-30T16:35:09Z | 39,232,977 | <p>We can use <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>NumPy broadcasting</code></a> to create those sliding windowed indices in a vectorized manner. Then, we can simply index into <code>arr_2</code> with those to create a <code>3D</code> array and perform element-wis... | 4 | 2016-08-30T16:45:47Z | [
"python",
"arrays",
"numpy",
"matrix-multiplication",
"sliding-window"
] |
Numpy Vectorization of sliding-window operation | 39,232,790 | <p>I have the following numpy arrays:</p>
<pre><code>arr_1 = [[1,2],[3,4],[5,6]] # 3 X 2
arr_2 = [[0.5,0.6],[0.7,0.8],[0.9,1.0],[1.1,1.2],[1.3,1.4]] # 5 X 2
</code></pre>
<p><code>arr_1</code> is clearly a <code>3 X 2</code> array, whereas <code>arr_2</code> is a <code>5 X 2</code> array. </p>
<p>Now without loo... | 4 | 2016-08-30T16:35:09Z | 39,238,064 | <p>This is a nice case to test the speed of <code>as_strided</code> and Divakar's broadcasting.</p>
<pre><code>In [281]: %%timeit
...: out=np.empty((L,W,arr1.shape[1]))
...: for i in range(L):
...: out[i]=np.multiply(arr1,arr2[i:i+W,:])
...:
10 loops, best of 3: 48.9 ms per loop
In [282]: %%ti... | 3 | 2016-08-30T22:29:38Z | [
"python",
"arrays",
"numpy",
"matrix-multiplication",
"sliding-window"
] |
Python - How to add the location of each object in the image? | 39,232,820 | <p>I have tracked more than one objects in the image and now my final step is to add the location of each object in the image here is the <a href="http://i.stack.imgur.com/guyKa.png" rel="nofollow">image</a></p>
<p>Another question is when I am printing the x, y, and radius of each object, I found that the locations a... | -1 | 2016-08-30T16:36:43Z | 39,254,610 | <p>Without seeing all of your code, it's hard to suggest a solution, but it looks like you are at least iterating over your objects. If not, you can put them in a list like so:</p>
<pre><code>obj_list = [obj1, obj2, obj3]
</code></pre>
<p>Then you can add their coordinates to a list like this:</p>
<pre><code>obj_co... | 0 | 2016-08-31T16:24:31Z | [
"python",
"python-2.7",
"opencv",
"computer-vision"
] |
Tornado templates setting value field | 39,232,936 | <p>I have a python array:</p>
<pre><code>a=["a","b","c","d","e","f"]
</code></pre>
<p>I pass this as a value to tornado render:</p>
<pre><code> self.render("index.html", a=a)
</code></pre>
<p>In my html I have the following:</p>
<pre><code> <input type="hidden" id="xxx" value="
{% for c in a %}
{{c}}
... | 0 | 2016-08-30T16:43:28Z | 39,232,971 | <p>Just join the list in the backend itself.</p>
<pre><code> self.render("index.html", a=' '.join(a))
</code></pre>
<p>And use,</p>
<pre><code><input type="hidden" id="xxx" value="{{ a }}" />
</code></pre>
<p>in template</p>
| 1 | 2016-08-30T16:45:37Z | [
"python",
"html",
"tornado"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.