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
Crazy but minor issue in grid-based game
39,030,278
<p>This has been really bugging me. I'm creating a game where a hero moves on a grid and part of it involves a collision check. The collision check stops the hero from moving in a direction if something already occupies the grid there.</p> <p>It works for all directions except down. I can't see why?! It's the same str...
-1
2016-08-19T02:34:36Z
39,049,865
<p>The problem in the <code>CollisionCheck()</code> method for the <code>if Direction == "DOWN":</code> case is that whenever the <code>len(Map.Grid[self.Column][self.Row+1])</code> is less than 2, the method returns <code>None</code> <em>not</em> the <code>False</code> value <code>Move()</code> explicitly checks for, ...
2
2016-08-20T02:20:55Z
[ "python", "python-3.x", "oop", "pygame" ]
How to delete the last item of a collection in mongodb
39,030,332
<p>I made a program with python and mongodb to do some diaries. Like this</p> <p><a href="http://i.stack.imgur.com/8othU.png" rel="nofollow"><img src="http://i.stack.imgur.com/8othU.png" alt="slice diary"></a></p> <p>Sometimes I want to delete the last sentence, just by typing "delete!" But I dont know how to delete ...
0
2016-08-19T02:42:58Z
39,030,354
<p>Be it first or last item, <code>MongoDB</code> maintains unique <code>_id</code> key for each record and thus you can just pass that id field in your delete query either using <code>deleteOne()</code> or <code>deleteMany()</code>. Since only one record to delete you need to use <code>deleteOne()</code> like</p> <pr...
0
2016-08-19T02:46:08Z
[ "python", "mongodb", "collections" ]
NumPy array element not getting updated
39,030,366
<p>I have a NumPy array as follows:</p> <pre><code>supp = np.array([['A', '5', '0'], ['B', '3', '0'], ['C', '4', '0'], ['D', '1', '0'], ['E', '2', '0']]) </code></pre> <p>Now, I want to update the row[2] as row[1]/6. I'm using..</p> <p><code>for row in supp: row[2] = row[1].astype(int) / 6</code></p> <p>But row...
2
2016-08-19T02:47:06Z
39,030,429
<p>The problem is that an <code>np.array</code> has only one type which is automatically assumed to be strings <code>supp.dtype == '|S1'</code> since your input contains only strings of length <code>1</code>. So numpy will automatically convert your updated inputs to strings of length <code>1</code>, <code>'0'</code>s ...
4
2016-08-19T02:55:33Z
[ "python", "arrays", "python-3.x", "numpy" ]
Cython and numpy
39,030,546
<p>Try to run Example 7-11 of <strong>High Performance Python</strong></p> <p><strong>cython_np.pyx</strong></p> <pre><code>#cython_np.pyx import numpy as np cimport numpy as np def calculate_z(int maxiter, double complex[:] zs, double complex[:] cs): cdef unsigned int i, n cdef double complex z, c cdef i...
-1
2016-08-19T03:12:11Z
39,030,954
<p>I think, based on examples in <a href="http://docs.cython.org/en/latest/src/userguide/memoryviews.html" rel="nofollow">http://docs.cython.org/en/latest/src/userguide/memoryviews.html</a></p> <pre><code>double complex[:] zs </code></pre> <p>defines a 1d memoryview with <code>double complex</code> dtype. This is si...
0
2016-08-19T04:08:21Z
[ "python", "numpy", "cython" ]
How can I have my script run certain days / months
39,030,624
<p>I have just created a python script that automatically renews my pass. Is it possible to make the script run like a app or a background program to check if it is a certain day of a month and to run it?</p>
-2
2016-08-19T03:23:09Z
39,030,743
<p>That's just scheduled task.</p> <p>In your task call python.exe, pass your script as an argument and that's it.</p>
0
2016-08-19T03:39:08Z
[ "python", "selenium" ]
CUDA histogram2d not working
39,030,738
<p>Due to a seeming lack of a decent 2D histogram for CUDA (that I can find... pointers welcome), I'm trying to implement it myself with pyCUDA.</p> <p>Here's what the histogram should look like (using Numpy):</p> <p><a href="http://i.stack.imgur.com/ThdCb.png" rel="nofollow"><img src="http://i.stack.imgur.com/ThdCb....
-1
2016-08-19T03:38:14Z
39,040,518
<p>The array being allocated for the output array for the CUDA section used Numpy's default float64 instead of float32, so memory was twice as large as expected. Here's the new histogram output:</p> <p><a href="http://i.stack.imgur.com/whUpm.png" rel="nofollow"><img src="http://i.stack.imgur.com/whUpm.png" alt="New CU...
0
2016-08-19T13:39:35Z
[ "python", "numpy", "cuda", "pycuda", "histogram2d" ]
Accessing dataframes in different notebooks in google data lab
39,030,914
<p>I am using google cloud data lab, and I have several data frames in different notebooks. Is there any way to access all these data frames in one notebook? I use SQL and python for writing the codes.</p> <p>The data frames are the base tables for user engagement in an android app. These base tables are user data, ex...
1
2016-08-19T04:03:08Z
39,039,925
<p>To access functions/variables from other notebooks in Google Cloud Datalab, simply run the other notebooks from your current notebook using the line magic command <code>%run</code></p> <p>For example:</p> <ol> <li>Create a notebook called <code>'notebook_a.ipynb'</code></li> <li>In the notebook, enter the followin...
1
2016-08-19T13:09:55Z
[ "python", "google-cloud-datalab" ]
Unpack a string into an expanded string
39,031,019
<p>I am given a string in the following format: <code>"a{1;4:6}"</code> and <code>"a{1;2}b{2:4}"</code> where the <code>;</code> represents two different numbers, and a <code>:</code> represents a sequence of numbers. There can be any number of combinations of semicolons and colons within the brace.</p> <p>I want to e...
1
2016-08-19T04:15:44Z
39,031,504
<pre><code>import re def expand(compressed): # 'b{2:4}' -&gt; 'b{2;3;4}' i.e. reduce the problem to just one syntax normalized = re.sub(r'(\d+):(\d+)', lambda m: ';'.join(map(str, range(int(m.group(1)), int(m.group(2)) + 1))), compressed) # 'a{1;2}b{2;3;4}' -&gt; ['a{1;2}', 'b{2;3;4}'] elements = re....
4
2016-08-19T05:09:23Z
[ "python" ]
Unpack a string into an expanded string
39,031,019
<p>I am given a string in the following format: <code>"a{1;4:6}"</code> and <code>"a{1;2}b{2:4}"</code> where the <code>;</code> represents two different numbers, and a <code>:</code> represents a sequence of numbers. There can be any number of combinations of semicolons and colons within the brace.</p> <p>I want to e...
1
2016-08-19T04:15:44Z
39,032,210
<p>I tried pyparsing for that and IMHO it produced a pretty readable code (took pack_tokens from the previous answer).</p> <pre><code>from pyparsing import nums, Literal, Word, oneOf, Optional, OneOrMore, Group, delimitedList from string import ascii_lowercase as letters # transform a '123' to 123 number = Word(nums)...
7
2016-08-19T06:12:41Z
[ "python" ]
Unpack a string into an expanded string
39,031,019
<p>I am given a string in the following format: <code>"a{1;4:6}"</code> and <code>"a{1;2}b{2:4}"</code> where the <code>;</code> represents two different numbers, and a <code>:</code> represents a sequence of numbers. There can be any number of combinations of semicolons and colons within the brace.</p> <p>I want to e...
1
2016-08-19T04:15:44Z
39,035,866
<p>Just to demonstrate a technique for doing this using <code>eval</code> (as @ialcuaz asked in the comments). Again I wouldn't recommend doing it this way, the other answers are more appropriate. This technique can be useful when the structure is more complex (i.e. recursive with brackets and so on) when you don't w...
2
2016-08-19T09:43:52Z
[ "python" ]
define a function like numpy transpose and inverse
39,031,127
<p>i would define a function like calculating of inverse <code>np.matrix.I</code>:</p> <pre><code>class matrix: def __init__(self, data): self.data = data self.I = 1.0/data def inv(self): return 1.0/self.data if __name__ == '__main__': m = matrix(10) m.I </code></pre> <p>it is possible to get c...
-1
2016-08-19T04:28:12Z
39,031,323
<p>You could do this with a <code>property</code>:</p> <pre><code>class matrix: def __init__(self, data): self.data = data @property def I(self): return 1.0/self.data if __name__ == '__main__': m = matrix(10) print m.I # 0.1 m.data = 20 print m.I # 0.05 </code></pre> <p>(As an aside, I cal...
2
2016-08-19T04:49:27Z
[ "python", "numpy" ]
Error running socket.io and express-nodejs setup
39,031,156
<p>I was working on nodejs executing python scripts using spawn and socket.io methods. I am getting output on the console. but I am not able to display it on the browser. It is showing error.I have pasted the error below. Can any one please help me in solving this problem. I have got this example from <a href="http://s...
0
2016-08-19T04:31:30Z
39,031,212
<p>You haven't started a web server anywhere or hooked socket.io to it. There are several different ways to do this, but here's one that works:</p> <pre><code>var express = require('express'); var app = express(); var server = require('http').Server(app); var io = require('socket.io')(server); server.listen(80); </c...
2
2016-08-19T04:37:38Z
[ "javascript", "python", "node.js", "express", "socket.io" ]
Import single OBJ files into Maya, moving and rotating it with Python/MEL
39,031,168
<p>Hi I have this code to import OBJ files into maya with Python</p> <p>**</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>import maya.cmds as cmds pathOfFiles = "/Path/...
0
2016-08-19T04:32:41Z
39,060,775
<p>This looks like a fun challenge, so here's my attempt at answering it:</p> <pre><code>import maya.cmds as cmds import glob #1. Import an individual OBJ file at once def importFile(i): cmds.file(i, i=True, groupReference=True, groupName="myobj") #2. Move and rotate the imported file def moveFile(): cmds.se...
0
2016-08-21T04:11:59Z
[ "python", "import", "rendering", "maya" ]
what does "by = lambda x: lambda y: getattr(y, x)" mean?
39,031,255
<p>There is a dataFrame named "subset" and the codes are as follows. pd is the nickname of pandas. I can't figure out the meaning of <code>by = lambda x: lambda y: getattr(y, x)</code>.</p> <pre><code>pivot = pd.pivot_table(subset, values='count', rows=['date'], cols=['sample'], fill_value=0) by = lambda x: lambda y: ...
2
2016-08-19T04:42:01Z
39,031,305
<p><code>by = lambda x: lambda y: getattr(y, x)</code> is equivalent to the following:</p> <pre><code>def by(x): def getter(y): return getattr(y, x) return getter </code></pre> <p><code>getattr(a, b)</code> gets an attribute with the name <code>b</code> from an object named <code>a</code>.</p> <p>So ...
2
2016-08-19T04:47:58Z
[ "python", "pandas", "lambda" ]
Unity - How to reduce time spent in Update and GC
39,031,315
<p>I have script in Unity that is exchanging data with another Python app. It has a while loop that listens for UDP messages as a background thread. Also the script is asking for new data every frame via the Update function.</p> <p>After I receive a message, the script parses it as a string and it needs to split the s...
0
2016-08-19T04:48:56Z
39,035,947
<ol> <li><p>I can see a lot of local variables in your while loop (along with arrays). Local variables cause Garbage collector to run. You should declare all the variables outside of the method.</p></li> <li><p>Moreover, avoid string operations in <code>while/update()</code> as <a href="http://stackoverflow.com/a/42742...
0
2016-08-19T09:48:29Z
[ "c#", "python", "multithreading", "unity3d", "garbage-collection" ]
windows python stdout and stderr to two different files
39,031,332
<p>I would like to output the stdout and stderr to two different log files. i have tried this code but it only outputs the error to error log , but output is not redirected to runtime.log file. </p> <p>the code is being run on windows and mostly robocopy is done in the code. </p> <pre><code>saveerr = sys.stderr ...
0
2016-08-19T04:49:59Z
39,031,459
<p>As mentioned in my comment your code should divert <strong>your</strong> stdout to the file. To get robocopy's stdout to go there too just echo each line to your stdout as shown in this link</p> <p><a href="http://stackoverflow.com/a/28319191/6550457">http://stackoverflow.com/a/28319191/6550457</a></p> <hr> <pre>...
3
2016-08-19T05:05:34Z
[ "python", "windows", "cmd" ]
Spotify - get playlist track names
39,031,363
<p>on <code>search endpoint</code>, one can retrieve <code>playlist</code> data, for instance:</p> <pre><code>def search_playlist(): results = sp.search(q='doom metal', type='playlist') </code></pre> <p>if add this to the code:</p> <pre><code> items = results['playlists']['items'][0]['tracks'] print (ite...
0
2016-08-19T04:54:33Z
39,044,777
<p><a href="https://github.com/plamere/spotipy/blob/master/examples/user_playlists_contents.py" rel="nofollow">https://github.com/plamere/spotipy/blob/master/examples/user_playlists_contents.py</a></p> <pre><code>def show_tracks(results): for i, item in enumerate(tracks['items']): track = item['track'] print("...
0
2016-08-19T17:32:57Z
[ "python", "spotify", "spotipy" ]
Selenium and Javascript
39,031,535
<p>I'm trying to learn how to use selenium. I'm trying to work on creating script to like instagram photos; however, i'm running into a problem where xpath won't detect the image i want to click. I think this is probably due to the fact it's a javascript button.</p> <p>This is a picture of the element i am inspecting....
0
2016-08-19T05:12:13Z
39,032,673
<p>Try <code>driver.find_element_by_xpath("//a[@class='thumb-shadow']/img").c‌​lick()</code></p>
0
2016-08-19T06:45:30Z
[ "python", "selenium" ]
I am thinking Web Crawler but how to start?
39,031,548
<p>I am working at a company that deals with phish and fake Facebook accounts. I want to show my dedication to the "mission". We are unable to passively monitor facebook pages for when they are removed. I am thinking a web crawler but I am curious on how to design one that constant checks a specific link to see if t...
-1
2016-08-19T05:14:35Z
39,031,836
<p>Yes! You can use crawling. However, if you want it to be as fast as possible, crawling may not be the best way to do it. If you're interested this is how I'd do it using HTTPConnection. also, unfortunately, the link has to be <em>completely</em> broken.</p> <p>If you need more information then you will most likely ...
1
2016-08-19T05:42:57Z
[ "python", "facebook" ]
I am thinking Web Crawler but how to start?
39,031,548
<p>I am working at a company that deals with phish and fake Facebook accounts. I want to show my dedication to the "mission". We are unable to passively monitor facebook pages for when they are removed. I am thinking a web crawler but I am curious on how to design one that constant checks a specific link to see if t...
-1
2016-08-19T05:14:35Z
39,032,196
<p>You can send a http request to tell the account is active or not by it's response status, Python has some standard library, you may have a look at <a href="https://docs.python.org/3/library/internet.html" rel="nofollow">Internet Protocols and Support</a>. Personally, I will recommend use requests:</p> <pre><code>im...
0
2016-08-19T06:11:53Z
[ "python", "facebook" ]
I am thinking Web Crawler but how to start?
39,031,548
<p>I am working at a company that deals with phish and fake Facebook accounts. I want to show my dedication to the "mission". We are unable to passively monitor facebook pages for when they are removed. I am thinking a web crawler but I am curious on how to design one that constant checks a specific link to see if t...
-1
2016-08-19T05:14:35Z
39,032,243
<p><a href="https://www.quora.com/How-can-I-build-a-web-crawler-from-scratch/answer/Raghavendran-Balu" rel="nofollow">https://www.quora.com/How-can-I-build-a-web-crawler-from-scratch/answer/Raghavendran-Balu</a> One of the best articles I have read about Crawlers.</p> <p>A web crawler might sound like a simple fetch-p...
0
2016-08-19T06:15:19Z
[ "python", "facebook" ]
How do I change the parsing order of the rules?
39,031,596
<p><a href="https://github.com/EricsonWillians/Lilith" rel="nofollow">I'm developing a programming language</a>, and I'm having trouble dealing with condition statements. Here's the code in my language:</p> <pre><code>x = 4 -&gt; ? 2 &gt; 5 &lt;? x = 7 -&gt; ?&gt; -&gt; [o] &lt;- x -&gt; </code></pre> <p>Here's ...
4
2016-08-19T05:18:38Z
39,032,555
<p>When a production is <em>reduced</em> -- that is, its semantic action is executed -- all of the non-terminals referenced have already been reduced. In other words, children are always reduced before their parents, which is why yacc is called a bottom-up parser.</p> <p>The only practical way to achieve more flexibi...
1
2016-08-19T06:37:29Z
[ "python", "parsing", "yacc", "ply" ]
Is there a better way to work with result from JSON and check whether it's blank or not
39,031,617
<p>I am trying to use the PostCodeAPI (<a href="http://postcodeapi.com.au/" rel="nofollow">http://postcodeapi.com.au/</a>) to get Australian postal information based on postcode. </p> <p>Below would work successfully if a correct postcode is entered in the url (such as 2601.json). </p> <p>I have used try-except to ca...
0
2016-08-19T05:21:07Z
39,031,985
<p>For me if is also required .Still urllib2 is old requests is much simpler for rest api's and web requests.</p> <blockquote> <p>class NoDataException(Exception):<br></p> <blockquote> <p>print("No Data Received ")</p> </blockquote> <p>import requests</p> <p>url='<a href="http://v0.postcodeapi.c...
0
2016-08-19T05:54:32Z
[ "python", "json" ]
Is there a better way to work with result from JSON and check whether it's blank or not
39,031,617
<p>I am trying to use the PostCodeAPI (<a href="http://postcodeapi.com.au/" rel="nofollow">http://postcodeapi.com.au/</a>) to get Australian postal information based on postcode. </p> <p>Below would work successfully if a correct postcode is entered in the url (such as 2601.json). </p> <p>I have used try-except to ca...
0
2016-08-19T05:21:07Z
39,032,062
<p>Unless you absolutely need to use <code>urllib2</code>, I'd suggest using the <a href="http://docs.python-requests.org/en/master/%20requests" rel="nofollow">requests</a> library. It's a more user-friendly HTTP client and does not raise an HTTPError when encountering an HTTP 404. If a 404 is encountered, you shouldn'...
0
2016-08-19T06:01:47Z
[ "python", "json" ]
Is there a better way to work with result from JSON and check whether it's blank or not
39,031,617
<p>I am trying to use the PostCodeAPI (<a href="http://postcodeapi.com.au/" rel="nofollow">http://postcodeapi.com.au/</a>) to get Australian postal information based on postcode. </p> <p>Below would work successfully if a correct postcode is entered in the url (such as 2601.json). </p> <p>I have used try-except to ca...
0
2016-08-19T05:21:07Z
39,032,431
<p>The simplest way I can think of, is this:</p> <pre><code>import requests import json.decoder.JSONDecodeError try: data = requests.get(url, headers=headers).json() except json.decode.DecodeError: print("No data") .. # rest of your code </code></pre> <p>This is similar to your code's <code>try/except</code> ...
0
2016-08-19T06:28:28Z
[ "python", "json" ]
Detecting 'Fold' of a webpage without loading it in a browser
39,031,809
<p>Is it possible to detect <code>Fold</code> of a webpage without actually loading it in Web Browser ?</p> <p>Say I have got 5 URLs, and I wish to know the fold position for these 5 URLs without loading them. More like a batch operation. Can this be done using <code>Java/Javascript/Python ?</code></p>
0
2016-08-19T05:40:05Z
39,032,500
<p>A 'Fold' is more or less a design principle from back in the days, when responsive wasn't a thing yet. Nowadays I wouldn't care too much about the 'fold', but ask yourself the question: 'why bother about the fold?'.</p> <p>A great article you (or your designer) should read: <a href="http://iampaddy.com/lifebelow600...
0
2016-08-19T06:33:45Z
[ "javascript", "java", "python", "html" ]
I can't decode encoded text using python
39,032,019
<pre><code>from base64 import b64decode uio = input("Please enter the text you want to decode...") pu = b64decode(uio.decode()) print("Decode text : ") print(pu) </code></pre> <p>It tells me this : -</p> <pre><code>pu = b64decode(uio.decode()) AttributeError: 'str' object has no attribute 'decode' </code></pre> <p>...
-2
2016-08-19T05:57:38Z
39,032,057
<p>You're trying to <code>decode()</code> a string object. That does not work. simply remove that and it should not raise an error anymore, like so:</p> <pre><code>pu = b64decode(uio) </code></pre> <p>If you're not certain there's always a string object do this:</p> <pre><code>try: pu = b64decode(uio.decode('utf...
1
2016-08-19T06:01:31Z
[ "python", "decode" ]
I can't decode encoded text using python
39,032,019
<pre><code>from base64 import b64decode uio = input("Please enter the text you want to decode...") pu = b64decode(uio.decode()) print("Decode text : ") print(pu) </code></pre> <p>It tells me this : -</p> <pre><code>pu = b64decode(uio.decode()) AttributeError: 'str' object has no attribute 'decode' </code></pre> <p>...
-2
2016-08-19T05:57:38Z
39,032,096
<p>In Python 3, all strings are unicode. Thus, decode is not necessary. (Also, you are supposed to specify an encoding anyways :) ). Example:</p> <pre><code>pu = b64decode(uio.decode("utf-8")) </code></pre>
-1
2016-08-19T06:04:31Z
[ "python", "decode" ]
Generating XML file with proper indentation
39,032,046
<p>I am trying to generate the XML file in python but its not getting indented the out put is coming in straight line.</p> <pre><code>from xml.etree.ElementTree import Element, SubElement, Comment, tostring name = str(request.POST.get('name')) top = Element('scenario') environment = SubElement(top, 'environment') ...
1
2016-08-19T06:00:19Z
39,032,366
<p>You cannot directly parse <code>top</code> which is an <code>Element()</code>, you need to make that into a string (which is why you should import <code>tostring</code> that you are currently not using), and use <code>xml.dom.minidom.parseString()</code> on the result:</p> <pre><code>import xml.dom.minidom xml_p =...
1
2016-08-19T06:24:20Z
[ "python", "xml", "xml-parsing", "xml.etree" ]
How to get cut a few value in to different col in python dataframe?
39,032,119
<p>I have a data frame like following:</p> <pre><code> pop state year value1 value2 value3 0 1.8 Ohio 2000001 3 3 1 1 1.9 Ohio 2001001 3 3 1 2 3.9 Nevada 2002 3 3 1 3 2.9 Nevada 2001003 3 ...
2
2016-08-19T06:06:12Z
39,034,575
<p>You can cast <code>year</code> to take string values followed by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="nofollow"><code>str.extract</code></a> to extract the specific slices corresponding to the values in the 3 columns.</p> <p>You could then replace the e...
2
2016-08-19T08:35:36Z
[ "python", "pandas", "dataframe" ]
Converting Python List to Numpy Array InPlace
39,032,200
<p>I have a python list that's huge (16 GB) and I want to convert it to numpy array, inplace. I can't afford this statement</p> <pre><code>huge_array = np.array(huge_list).astype(np.float16) </code></pre> <p>I'm looking for some efficient ways to transform this <code>huge_list</code> into <code>numpy array</code> wit...
2
2016-08-19T06:12:04Z
39,033,240
<p>As I previously mentioned, the easiest would be to just dump the array to a file and then load that file as a numpy array.</p> <p>First we need the size of the huge list: </p> <pre><code>huge_list_size = len(huge_list) </code></pre> <p>Next we dump it to disk</p> <pre><code>dumpfile = open('huge_array.txt...
2
2016-08-19T07:19:35Z
[ "python", "arrays", "list", "numpy", "in-place" ]
Converting Python List to Numpy Array InPlace
39,032,200
<p>I have a python list that's huge (16 GB) and I want to convert it to numpy array, inplace. I can't afford this statement</p> <pre><code>huge_array = np.array(huge_list).astype(np.float16) </code></pre> <p>I'm looking for some efficient ways to transform this <code>huge_list</code> into <code>numpy array</code> wit...
2
2016-08-19T06:12:04Z
39,034,913
<p><code>np.array(huge_list, dtype=np.float16)</code> will be faster, since it only copies the list once and not twice</p> <hr> <p>You probably don't need to worry about making this copy, because the copy is a lot smaller than the original:</p> <pre><code>&gt;&gt;&gt; x = [float(i) for i in range(10000)] &gt;&gt;&gt...
2
2016-08-19T08:55:13Z
[ "python", "arrays", "list", "numpy", "in-place" ]
Converting Python List to Numpy Array InPlace
39,032,200
<p>I have a python list that's huge (16 GB) and I want to convert it to numpy array, inplace. I can't afford this statement</p> <pre><code>huge_array = np.array(huge_list).astype(np.float16) </code></pre> <p>I'm looking for some efficient ways to transform this <code>huge_list</code> into <code>numpy array</code> wit...
2
2016-08-19T06:12:04Z
39,072,596
<p>You can use <code>numpy</code>'s <code>save</code> and <code>load</code> functions:</p> <p>You can use a normal python list as an argument to <code>np.save</code> and <code>np.load</code> will load directly into a numpy array.</p> <p>Example: </p> <pre><code>from tempfile import TemporaryFile outfile = TemporaryF...
0
2016-08-22T06:28:30Z
[ "python", "arrays", "list", "numpy", "in-place" ]
Merge two dataframes with python
39,032,204
<p>I have two dataframes :dfDepas and df7 ; </p> <pre><code>dfDepas.info() &lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 7 entries, 0 to 6 Data columns (total 4 columns): day_of_week 7 non-null object P_ACT_KW 7 non-null float64 P_SOUSCR 7 non-null float64 depassement 7 non-null float64 dty...
3
2016-08-19T06:12:18Z
39,032,246
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a> and rename column <code>0</code> to <code>day_of_week</code> for matching:</p> <pre><code>merged_df = pd.merge(dfDepas, df7.reset_index().re...
3
2016-08-19T06:15:23Z
[ "python", "pandas", "merge" ]
How do I use a trained Matlab Neural Network to Python for detection purpose
39,032,261
<p>I have trained a Neural Network using a Matlab Neural Network Toolbox, particularly using the command nntool. The detection is basically for traffic sign and I have used a database of 90 traffic images(no-entry,no right and stop signs), each of 30 images of size 8*8 pixels of which no-entry signs are taken positive....
0
2016-08-19T06:17:03Z
39,035,758
<p>First you need to take the weights of your neural network. An example:</p> <pre><code>[x,t] = simplefit_dataset; net = feedforwardnet(20); net = train(net,x,t); wb = getwb(net) </code></pre> <p>Then I also suggest that you read on <a href="http://neuralnetworksanddeeplearning.com/chap1.html" rel="nofollow">ANN str...
1
2016-08-19T09:36:12Z
[ "python", "matlab", "image-processing", "neural-network" ]
Finding the corresponding value in python
39,032,311
<p>I want to find the name of the car which has maximum mpg. I want to print 'Toyota' which has maximum mpg. I want to do this in a Pythonic way. I don't like to use pandas.</p> <p>Here is my code:</p> <pre><code>dataset=[] f= open('auto-mpg-data.csv') csv_f=csv.reader(f) for row in csv_f: dataset.append(row) ...
-1
2016-08-19T06:20:29Z
39,032,410
<p>You mentioned that you don't like <code>pandas</code>, but, for completeness sake, here is how you could have used <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>pandas.read_csv()</code></a> to read the CSV file into a <em>dataframe</em> (which is quite <em>...
0
2016-08-19T06:27:26Z
[ "python", "python-3.x", "csv" ]
Finding the corresponding value in python
39,032,311
<p>I want to find the name of the car which has maximum mpg. I want to print 'Toyota' which has maximum mpg. I want to do this in a Pythonic way. I don't like to use pandas.</p> <p>Here is my code:</p> <pre><code>dataset=[] f= open('auto-mpg-data.csv') csv_f=csv.reader(f) for row in csv_f: dataset.append(row) ...
-1
2016-08-19T06:20:29Z
39,033,002
<p>Here are a couple of ways to improve your code:</p> <ol> <li>When you are working with files, it's always best to <a href="https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects" rel="nofollow"><code>close()</code></a> your file after working with it, or wrap your snippet of code in a <a href="...
0
2016-08-19T07:05:59Z
[ "python", "python-3.x", "csv" ]
Finding the corresponding value in python
39,032,311
<p>I want to find the name of the car which has maximum mpg. I want to print 'Toyota' which has maximum mpg. I want to do this in a Pythonic way. I don't like to use pandas.</p> <p>Here is my code:</p> <pre><code>dataset=[] f= open('auto-mpg-data.csv') csv_f=csv.reader(f) for row in csv_f: dataset.append(row) ...
-1
2016-08-19T06:20:29Z
39,033,415
<p>First, every object that supports iteration, can be converted directly to a list using the <code>list</code> function. Hence instead of</p> <pre><code>for row in csv_f: dataset.append(row) </code></pre> <p>you can do:</p> <pre><code>dataset = list(csv_f) </code></pre> <p>Next, since <code>dataset</code> is a...
0
2016-08-19T07:29:31Z
[ "python", "python-3.x", "csv" ]
Finding the corresponding value in python
39,032,311
<p>I want to find the name of the car which has maximum mpg. I want to print 'Toyota' which has maximum mpg. I want to do this in a Pythonic way. I don't like to use pandas.</p> <p>Here is my code:</p> <pre><code>dataset=[] f= open('auto-mpg-data.csv') csv_f=csv.reader(f) for row in csv_f: dataset.append(row) ...
-1
2016-08-19T06:20:29Z
39,033,651
<p>The simplies way:</p> <pre><code>with open('auto-mpg-data.csv') as fo: reader = csv.reader(fo) next(reader) # skip the header biggest_row = max(reader, key=lambda row: float(row[0])) print(biggest_row[3]) # or whatever the index is </code></pre> <p>Note that if your csv contains an incorrect data then ...
0
2016-08-19T07:43:20Z
[ "python", "python-3.x", "csv" ]
Finding the corresponding value in python
39,032,311
<p>I want to find the name of the car which has maximum mpg. I want to print 'Toyota' which has maximum mpg. I want to do this in a Pythonic way. I don't like to use pandas.</p> <p>Here is my code:</p> <pre><code>dataset=[] f= open('auto-mpg-data.csv') csv_f=csv.reader(f) for row in csv_f: dataset.append(row) ...
-1
2016-08-19T06:20:29Z
39,034,936
<p>Using for loop iterator...</p> <pre><code>&gt;&gt;&gt; mpg = [12,34,40.5,6] &gt;&gt;&gt; idx,maxMpg = 0,0 &gt;&gt;&gt; for n,v in enumerate(mpg): ... if v&gt;maxMpg: idx,maxMpg = n,v ... &gt;&gt;&gt; idx 2 &gt;&gt;&gt; maxMpg 40.5 &gt;&gt;&gt; carnames = ['ford','bmw','toyota','bugatti'] &gt;&gt;&gt; carnames[idx]...
0
2016-08-19T08:56:10Z
[ "python", "python-3.x", "csv" ]
Python High Pass Filter
39,032,325
<p>I implemented an high pass filter in python using this code:</p> <pre><code>from scipy.signal import butter, filtfilt import numpy as np def butter_highpass(cutoff, fs, order=5): nyq = 0.5 * fs normal_cutoff = cutoff / nyq b, a = butter(order, normal_cutoff, btype='high', analog=False) return b, a ...
1
2016-08-19T06:21:30Z
39,032,946
<p>I hope this can help you:</p> <pre><code>import numpy as np import pandas as pd from scipy import signal import matplotlib.pyplot as plt def sine_generator(fs, sinefreq, duration): T = duration nsamples = fs * T w = 2. * np.pi * sinefreq t_sine = np.linspace(0, T, nsamples, endpoint=False) y_sin...
1
2016-08-19T07:02:50Z
[ "python", "signal-processing" ]
Python High Pass Filter
39,032,325
<p>I implemented an high pass filter in python using this code:</p> <pre><code>from scipy.signal import butter, filtfilt import numpy as np def butter_highpass(cutoff, fs, order=5): nyq = 0.5 * fs normal_cutoff = cutoff / nyq b, a = butter(order, normal_cutoff, btype='high', analog=False) return b, a ...
1
2016-08-19T06:21:30Z
39,083,588
<p>Since my reputation is low I am unable to comment on your question - "What is the relationship between cutoff and filter order?" This is not an answer to your original question.</p> <p>For an FIR filter, for a given cutoff frequency, the slope of the impulse response plot (|H(f)| vs f) is steeper for a higher order...
0
2016-08-22T15:37:56Z
[ "python", "signal-processing" ]
Flashing multiple images in python
39,032,376
<p>I am new to python and I am working on flashing (displaying) like 516 images in a go. There have been many questions like this before but none helped me. Here is the code </p> <pre><code>import cv2 import matplotlib import matplotlib.pyplot as plt import matplotlib.image as mpimg for i in range(1,516,1): #a=cv...
-1
2016-08-19T06:24:57Z
39,032,994
<p>Your file path to <code>imread</code> is very likely invalid, so you do not get a proper image in <code>abb</code>, which then of course cannot be displayed, so you get the error about the image size.</p>
0
2016-08-19T07:05:32Z
[ "python", "opencv", "matplotlib" ]
Flashing multiple images in python
39,032,376
<p>I am new to python and I am working on flashing (displaying) like 516 images in a go. There have been many questions like this before but none helped me. Here is the code </p> <pre><code>import cv2 import matplotlib import matplotlib.pyplot as plt import matplotlib.image as mpimg for i in range(1,516,1): #a=cv...
-1
2016-08-19T06:24:57Z
39,035,688
<p>You can use python os module to navigate through directory , and you do not need plotting to flash image .</p> <pre><code>import cv2 import os # import os module path = r"G:\TRAINING\1" img_names = os.listdir(path) # return all image names in given path for name in img_names: im = cv2.imread( os.path....
0
2016-08-19T09:32:39Z
[ "python", "opencv", "matplotlib" ]
Encoding issue with ASCII-safe file with codec header, depending on line count
39,032,416
<p>Here is magical bug of Python 3.5.2 on Windows that killed my day. File below fails on this system:</p> <blockquote> <pre><code>C:\Python35\python.exe encoding-problem-cp1252.py File "encoding-problem-cp1252.py", line 2 SyntaxError: encoding problem: cp1252 </code></pre> </blockquote> <p>Contains almost nothing -...
3
2016-08-19T06:27:40Z
39,033,975
<p>This looks like a regression caused by <a href="http://bugs.python.org/issue20731" rel="nofollow">issue #20731</a>. It looks like the position calculation is assuming there will always be CRLF line endings while your file has only got LF characters, leading to an incorrect offset <a href="https://hg.python.org/cpyth...
3
2016-08-19T08:01:23Z
[ "python", "windows", "python-3.x", "encoding", "python-3.5" ]
Update Cassandra Json Value with python Script
39,032,691
<p>Hi I am quite new to python. I do have following column in my Cassandra table. I need to update a certain value(set displayable to <strong>true</strong>) in it. How do i do this via python script?</p> <pre><code>{ "rowId": "SYSTEM", "status": null, "startDate": null, "endDate": null, "creationDate": 14570...
0
2016-08-19T06:46:29Z
39,033,801
<p>Based on the screenshot you shared, it looks like the <code>value</code> field is simply a <code>text</code> field (if that's not the case you must share the schema of the table), so you'll have to update the complete value stored in that field.</p>
0
2016-08-19T07:51:43Z
[ "python", "cassandra" ]
Formatting Lists into columns of a table output (python 3)
39,032,720
<p>I have data that is collected in a loop and stored under separate lists that hold only the same datatypes (e.g. only strings, only floats) as shown below:</p> <pre><code>names = ['bar', 'chocolate', 'chips'] weights = [0.05, 0.1, 0.25] costs = [2.0, 5.0, 3.0] unit_costs = [40.0, 50.0, 12.0] </code></pre> <p>I have...
3
2016-08-19T06:47:57Z
39,032,993
<p>Here is a small implementation that does what you want in basic python (no special modules). </p> <pre><code> names = ['bar', 'chocolate', 'chips'] weights = [0.05, 0.1, 0.25] costs = [2.0, 5.0, 3.0] unit_costs = [40.0, 50.0, 12.0] titles = ['names', 'weights', 'costs', 'unit_costs'] data = [titles] + list(zip(na...
0
2016-08-19T07:05:25Z
[ "python", "list", "formatting", "columnsorting" ]
Formatting Lists into columns of a table output (python 3)
39,032,720
<p>I have data that is collected in a loop and stored under separate lists that hold only the same datatypes (e.g. only strings, only floats) as shown below:</p> <pre><code>names = ['bar', 'chocolate', 'chips'] weights = [0.05, 0.1, 0.25] costs = [2.0, 5.0, 3.0] unit_costs = [40.0, 50.0, 12.0] </code></pre> <p>I have...
3
2016-08-19T06:47:57Z
39,033,135
<p>After visiting docs.python.org/3/library/functions.html#zip (link provided by cdarke) </p> <p>I managed to find the solution I needed: </p> <p>using the zip method I created a new summary list of the associated data:</p> <pre><code># sort into rows of associated data and convert to list rows = zip(names, weight...
0
2016-08-19T07:13:47Z
[ "python", "list", "formatting", "columnsorting" ]
Formatting Lists into columns of a table output (python 3)
39,032,720
<p>I have data that is collected in a loop and stored under separate lists that hold only the same datatypes (e.g. only strings, only floats) as shown below:</p> <pre><code>names = ['bar', 'chocolate', 'chips'] weights = [0.05, 0.1, 0.25] costs = [2.0, 5.0, 3.0] unit_costs = [40.0, 50.0, 12.0] </code></pre> <p>I have...
3
2016-08-19T06:47:57Z
39,033,695
<p>Some interesting table draw with <code>texttable</code>.</p> <pre><code>import texttable as tt tab = tt.Texttable() headings = ['Names','Weights','Costs','Unit_Costs'] tab.header(headings) names = ['bar', 'chocolate', 'chips'] weights = [0.05, 0.1, 0.25] costs = [2.0, 5.0, 3.0] unit_costs = [40.0, 50.0, 12.0] for ...
1
2016-08-19T07:46:06Z
[ "python", "list", "formatting", "columnsorting" ]
Pyramid debug toolbar serving static content over HTTP instead of HTTPS
39,033,106
<p>On our test servers, we're using the <a href="http://docs.pylonsproject.org/projects/pyramid_debugtoolbar/en/latest/" rel="nofollow">Pyramid debug toolbar</a>, however, it generates <code>http://</code> links to static content (like its CSS and JavaScript files), while the rest of the content is served over HTTPS. T...
2
2016-08-19T07:12:53Z
39,034,219
<p>There might be better/simpler ways to achieve this, but one thing you can do to achieve this add the <code>_scheme='https'</code> parameter to each call to <code>request.static_url()</code>.</p> <p>For that you can of course edit <code>pyramid/url.py</code>, but you can also do this in your projects' <code>__init__...
2
2016-08-19T08:15:26Z
[ "python", "python-3.x", "pyramid", "pylons", "pyramid-debug-toolbar" ]
Pyramid debug toolbar serving static content over HTTP instead of HTTPS
39,033,106
<p>On our test servers, we're using the <a href="http://docs.pylonsproject.org/projects/pyramid_debugtoolbar/en/latest/" rel="nofollow">Pyramid debug toolbar</a>, however, it generates <code>http://</code> links to static content (like its CSS and JavaScript files), while the rest of the content is served over HTTPS. T...
2
2016-08-19T07:12:53Z
39,072,118
<p>Usually you signal your web server to use HTTPS instead of HTTP by passing through <code>X-Forwarded-Proto</code> HTTP header.</p> <p>Example from Nginx:</p> <pre><code> proxy_set_header X-Forwarded-Proto $scheme; </code></pre> <p>However, this is not standard and may depend on your web server configuration. H...
0
2016-08-22T05:49:15Z
[ "python", "python-3.x", "pyramid", "pylons", "pyramid-debug-toolbar" ]
Cython's prange not improving performance
39,033,170
<p>I'm trying to improve the performance of some metric computations with Cython's <code>prange</code>. Here are my codes:</p> <pre><code>def shausdorff(float64_t[:,::1] XA not None, float64_t[:,:,::1] XB not None): cdef: Py_ssize_t i Py_ssize_t n = XB.shape[2] float64_t[::1] hdist = np.ze...
8
2016-08-19T07:15:34Z
39,178,995
<p>I think this the parallelization is working, but the extra overhead of the parallelization is eating up the time it would have saved. If I try with different sized arrays then I do begin to see a speed up in the parallel version</p> <pre><code>XA = np.random.random((900, 2100)) XB = np.random.random((100, 2100, 90)...
3
2016-08-27T08:19:20Z
[ "python", "numpy", "openmp", "cython", "gil" ]
Pygame - Pygame keeps drawing more sprites after moving them
39,033,505
<p><a href="http://i.stack.imgur.com/Y6qT0.png" rel="nofollow">no idea what's wrong</a></p> <p>won't let me post the full code, searched this website and google, but found no answers...</p> <pre><code>DISPLAYSURF=pygame.display.set_mode((width,height),0,32) sprite=pygame.image.load('generic_legionnary.png' def move...
0
2016-08-19T07:34:31Z
39,034,694
<p>Do you clear your screen at the start of each loop ?</p> <p>Why are you loading new sprites each time you move ?</p> <p>Who need only the one loaded before the function, not the others.</p> <p>If you don't clear your screen in each loop, you get this trace. (or your trace might be the old sprites that you have ov...
0
2016-08-19T08:42:06Z
[ "python", "pygame" ]
How to remove duplicates of huge lists of objects in Python
39,033,565
<p>I have gigantic lists of objects with many duplicates (I'm talking thousands of lists with thousands of objects each, taking up to about 10million individual objects (already without duplicates).</p> <p>I need to go through them and remove all the duplicates inside each list (no need to compare between lists, only ...
1
2016-08-19T07:38:22Z
39,033,758
<p>I'd suggest to have a sorted list (if possible), so you can be more precise when you want compare items (like a dictionnary I mean). A hash (or not) list can fulfill that thing.</p> <p>If you have the ability to manage the "add and delete" from your lists, it's better ! Sort the new items each time you add/delete. ...
1
2016-08-19T07:49:07Z
[ "python", "python-3.x" ]
How to remove duplicates of huge lists of objects in Python
39,033,565
<p>I have gigantic lists of objects with many duplicates (I'm talking thousands of lists with thousands of objects each, taking up to about 10million individual objects (already without duplicates).</p> <p>I need to go through them and remove all the duplicates inside each list (no need to compare between lists, only ...
1
2016-08-19T07:38:22Z
39,034,026
<p>A fast, not order preserving solution for (hashable items) is</p> <pre><code>def unify(seq): # Not order preserving return list(set(seq)) </code></pre> <p><strong>Complete Edit</strong></p> <p>I assume, that you have <code>dicts</code> inside a <code>list</code>. And you have many lists. The solution to r...
0
2016-08-19T08:04:24Z
[ "python", "python-3.x" ]
Bs4 select_one vs find
39,033,612
<p>I was wondering what is the difference between performing <code>bs.find('div')</code> and <code>bs.select_one('div')</code>. Same goes for <code>find_all</code> and <code>select</code>. </p> <p>Is there any difference performance wise, or if any is better to use over the other in specific cases.</p>
2
2016-08-19T07:40:56Z
39,033,728
<p><code>select()</code> and <code>select_one()</code> give you a different way navigating through an HTML tree using the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors" rel="nofollow">CSS selectors</a> which has rich and convenient syntax. Though, the CSS selector syntax support in <code...
2
2016-08-19T07:47:28Z
[ "python", "beautifulsoup", "html-parsing", "bs4" ]
Bs4 select_one vs find
39,033,612
<p>I was wondering what is the difference between performing <code>bs.find('div')</code> and <code>bs.select_one('div')</code>. Same goes for <code>find_all</code> and <code>select</code>. </p> <p>Is there any difference performance wise, or if any is better to use over the other in specific cases.</p>
2
2016-08-19T07:40:56Z
39,036,044
<p>select_one is normally much faster than find:</p> <pre><code>In [13]: req = requests.get("https://httpbin.org/") In [14]: soup = BeautifulSoup(req.content, "html.parser") In [15]: soup.select_one("#DESCRIPTION") Out[15]: &lt;h2 id="DESCRIPTION"&gt;DESCRIPTION&lt;/h2&gt; In [16]: soup.find("h2", id="DESCRIPTIO...
1
2016-08-19T09:54:03Z
[ "python", "beautifulsoup", "html-parsing", "bs4" ]
How can I view python library functions in VScode
39,033,652
<p>I can use <kbd>Ctrl</kbd>+left-click in the name of function to view library functions in PyCharm, and I want to do the same in VScode; what should I do?</p> <p>I may not be very clear, so I recorded a gif.</p> <p><a href="http://i.stack.imgur.com/xBAUK.gif" rel="nofollow"><img src="http://i.stack.imgur.com/xBAUK....
0
2016-08-19T07:43:26Z
39,037,438
<p>@cnkl, what you're after is the 'go to definition' feature. You can go to the definition of a symbol by pressing F12. If you press Ctrl and hover over a symbol, a preview of the declaration will appear</p> <p>You can find more details here: <a href="https://code.visualstudio.com/docs/editor/editingevolved#_go-to-...
0
2016-08-19T11:03:38Z
[ "python", "vscode" ]
Are Jupyter notebook executors distributed dynamically in Apache Spark?
39,033,661
<p>I got a question in order to better understand a big data concept within Apache Hadoop Spark. Not sure if it's off-topic in this forum, but let me know.</p> <p>Imagine a Apache Hadoop cluster with 8 servers managed by the Yarn resource manager. I uploaded a file into HDFS (file system) that is configured with 64MB ...
1
2016-08-19T07:44:05Z
39,034,110
<blockquote> <p>Are Jupyter notebook executors distributed dynamically in Apache Spark</p> </blockquote> <p>For the sake of clarity, let's distinguish</p> <ul> <li><p>Jupyter notebooks and their associated kernels - a kernel is the Python process behind a notebook's UI. A kernel executes whatever code you type and ...
3
2016-08-19T08:08:48Z
[ "python", "apache-spark", "pyspark", "jupyter", "jupyter-notebook" ]
Plot confusion matrix sklearn with multiple labels
39,033,880
<p>I am plotting a confusion matrix for a multiple labelled data, where labels look like: </p> <blockquote> <p>label1: 1, 0, 0, 0</p> <p>label2: 0, 1, 0, 0</p> <p>label3: 0, 0, 1, 0</p> <p>label4: 0, 0, 0, 1</p> </blockquote> <p>I am able to classify successfully using the below code. <strong>I only ...
2
2016-08-19T07:56:40Z
39,034,386
<p>I see this is still an open issue in <code>sklearn</code>'s repository:</p> <p><a href="https://github.com/scikit-learn/scikit-learn/issues/3452" rel="nofollow">https://github.com/scikit-learn/scikit-learn/issues/3452</a></p> <p>However there have been some attempts at implementing it. From the same #3452 thread i...
0
2016-08-19T08:24:25Z
[ "python", "machine-learning", "scikit-learn", "confusion-matrix" ]
Minimize delay between two sounds played using winsound.PlaySound
39,033,922
<pre><code>winsound.PlaySound('1.wav', winsound.SND_FILENAME) time.sleep(0.15) winsound.PlaySound('1.wav', winsound.SND_FILENAME) </code></pre> <p><code>1.wav</code> is a sound file of length 01s</p> <p>There is delay of more then a second between the two <code>winsound.PlaySound</code> calls, even if <code>time.slee...
1
2016-08-19T07:58:42Z
39,044,558
<p>The winsound module seems to be unloved. It hasn't adapted to the Python 3 distinction between bytes and strings (<a href="http://bugs.python.org/issue11620" rel="nofollow">http://bugs.python.org/issue11620</a>), so it can't play a .wav file that is stored in memory. </p> <p>You should probably move to a different ...
1
2016-08-19T17:15:42Z
[ "python" ]
Python : Argument based Singleton
39,033,946
<p>I'm following this <a href="http://stackoverflow.com/a/6798042/820410">link</a> and trying to make a singleton class. But, taking arguments (passed while initiating a class) into account so that the same object is returned if the arguments are same.</p> <p>So, instead of storing class name/class reference as a <cod...
2
2016-08-19T07:59:42Z
39,038,020
<p>As theheadofabroom and me already mentioned in the comments, there are some odds when relying on non-hashable values for instance caching or memoization. Therefore, if you still want to do exactly that, the following example does not hide the memoization in the <code>__new__</code> or <code>__init__</code> method. (...
0
2016-08-19T11:33:02Z
[ "python", "dictionary", "arguments", "singleton", "hashable" ]
Python: Date Conversion Error
39,033,982
<p>I'm trying to convert a string into a date format, to be later stored into an SQLite database. Below is the code line at which I'm getting an error.</p> <pre><code>date_object = datetime.strptime(date, '%b %d, %Y %H:%M %Z') </code></pre> <p>And this is the error:</p> <pre><code>File "00Basic.py", line 20, in spid...
0
2016-08-19T08:01:39Z
39,034,769
<p>The problem is located in the <code>%Z</code> (Time zone) part of the format. As the <a href="https://docs.python.org/2/library/datetime.html" rel="nofollow">documentation</a> explains</p> <pre><code>%Z Time zone name (empty string if the object is naive). (empty), UTC, EST, CST </code></pre> <p>It looks like o...
0
2016-08-19T08:47:16Z
[ "python", "sqlite", "date-conversion" ]
Python: Date Conversion Error
39,033,982
<p>I'm trying to convert a string into a date format, to be later stored into an SQLite database. Below is the code line at which I'm getting an error.</p> <pre><code>date_object = datetime.strptime(date, '%b %d, %Y %H:%M %Z') </code></pre> <p>And this is the error:</p> <pre><code>File "00Basic.py", line 20, in spid...
0
2016-08-19T08:01:39Z
39,035,752
<p>You could use <a href="https://pypi.python.org/pypi/pytz?" rel="nofollow"><code>pytz</code></a> for the timezone conversion as shown:</p> <pre><code>from datetime import datetime from pytz import timezone s = "Aug 19, 2016 08:13 IST".replace('IST', '') print(timezone('Asia/Calcutta').localize(datetime.strptime(s.r...
0
2016-08-19T09:35:51Z
[ "python", "sqlite", "date-conversion" ]
Python BeautifulSoup - Scraping Google Finance historical data
39,033,999
<p>I was trying to scrap Google Finance historical data. I was need of to total number of rows, which is located along with the pagination. The following is the div tag which is responsible for displaying the total number of rows:</p> <pre><code>&lt;div class="tpsd"&gt;1 - 30 of 1634 rows&lt;/div&gt; </code></pre> <p...
1
2016-08-19T08:02:46Z
39,034,299
<p>You can just use the python module: <a href="https://pypi.python.org/pypi/googlefinance" rel="nofollow">https://pypi.python.org/pypi/googlefinance</a></p> <p>The api is simple:</p> <pre><code>#The google finance API that we need. from googlefinance import getQuotes #The json handeler, since the API returns a JSON....
0
2016-08-19T08:19:43Z
[ "javascript", "python", "beautifulsoup" ]
Python BeautifulSoup - Scraping Google Finance historical data
39,033,999
<p>I was trying to scrap Google Finance historical data. I was need of to total number of rows, which is located along with the pagination. The following is the div tag which is responsible for displaying the total number of rows:</p> <pre><code>&lt;div class="tpsd"&gt;1 - 30 of 1634 rows&lt;/div&gt; </code></pre> <p...
1
2016-08-19T08:02:46Z
39,037,402
<p>You can easily pass an offset i.e <em>start=..</em> to the url getting 30 rows at a time which is exactly what is happening with the pagination logic:</p> <pre><code>from bs4 import BeautifulSoup import requests url = "https://www.google.com/finance/historical?cid=13564339&amp;startdate=Jan+01%2C+2010&amp;" \ ...
1
2016-08-19T11:01:01Z
[ "javascript", "python", "beautifulsoup" ]
for in a parameter function python - zip dynamic
39,034,136
<p>I have dynamic <code>zip()</code> function call:</p> <pre><code>zip(id, value[0], value[1], value[2], value[3], value[4]) </code></pre> <p>Value has a dynamic length: it could contain 3 or 4 or 7 elements, etc. Is there a way I can make the <code>zip()</code> function dynamic and work with a variable number of ele...
1
2016-08-19T08:10:38Z
39,034,229
<p>Use the <code>*args</code> <em>call</em> syntax:</p> <pre><code>zip(id, *value) </code></pre> <p>Prepending <code>value</code> with <code>*</code> tells Python to apply each entry in <code>value</code> as a separate argument to <code>zip()</code>.</p>
3
2016-08-19T08:16:08Z
[ "python", "python-2.7", "function" ]
Dynamically add columns to Exsisting BigQuery table
39,034,249
<p><strong>Background</strong></p> <p>I am loading files from local machine to BigQuery.Each file has variable number of fields.So,i am using <strong>'autodetect=true'</strong> while running load job.</p> <p><strong>Issue</strong> is,when load job is run for first time and if the destination table doesn't exsist,Bigq...
0
2016-08-19T08:17:12Z
39,035,979
<p>A naive solution would be:</p> <p>1.get the target table schema using </p> <p>service.tables().get(projectId=projectId, datasetId=datasetId, tableId=tableId)</p> <p>2.Generate schema of your data in the file.</p> <p>3.Compare the schemas (kind of a "diff") and then add those columns to the target table ,which ar...
0
2016-08-19T09:50:09Z
[ "python", "google-bigquery", "google-cloud-platform" ]
Dynamically add columns to Exsisting BigQuery table
39,034,249
<p><strong>Background</strong></p> <p>I am loading files from local machine to BigQuery.Each file has variable number of fields.So,i am using <strong>'autodetect=true'</strong> while running load job.</p> <p><strong>Issue</strong> is,when load job is run for first time and if the destination table doesn't exsist,Bigq...
0
2016-08-19T08:17:12Z
39,700,879
<p>You should check schema update options. There is an option named as "ALLOW_FIELD_ADDITION" that will help you.</p>
1
2016-09-26T10:50:37Z
[ "python", "google-bigquery", "google-cloud-platform" ]
cloudsql databases with django on 'new' flexible google app engine
39,034,250
<p>I'm building a django (1.9) app using cloudsql and a 'new' flexible environment. I have this same error: <a href="http://stackoverflow.com/questions/20843817/django-on-google-appengine-with-cloudsql-how-to-connect-database-error-2002-c">Django on Google AppEngine with CloudSQL: How to connect database (Error 2002, C...
0
2016-08-19T08:17:14Z
39,045,983
<p>I've made a PR for the documentation on github, but the key changes that were required in order for me to change my <code>DEBUG</code> flag from <code>True</code> to <code>False</code> are described below. </p> <p>Be aware, that it seems once you change the <code>DEBUG</code> flag, GAE requires that your Cloud SQL ...
0
2016-08-19T18:53:38Z
[ "python", "django", "google-app-engine", "google-cloud-platform", "google-cloud-sql" ]
how to remove blank lines from a csv file created using python
39,034,289
<p>We are creating a subfile from a big csv file. The subfile contains only those rows which have their first column's value as D1:</p> <pre><code>import csv with open('input.csv', 'rb') as csvfile: reader = csv.reader(csvfile, delimiter='|', quotechar='|') writer1 = csv.writer(open('output.csv', 'w'), del...
1
2016-08-19T08:19:13Z
39,034,390
<p>From python csv docs..</p> <blockquote> <pre><code>import csv with open('eggs.csv', 'w', newline='') as csvfile: spamwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) spamwriter.writerow(['Spam'] * 5 + ['Baked Beans']) spamwriter.writerow([...
0
2016-08-19T08:24:38Z
[ "python", "csv" ]
how to remove blank lines from a csv file created using python
39,034,289
<p>We are creating a subfile from a big csv file. The subfile contains only those rows which have their first column's value as D1:</p> <pre><code>import csv with open('input.csv', 'rb') as csvfile: reader = csv.reader(csvfile, delimiter='|', quotechar='|') writer1 = csv.writer(open('output.csv', 'w'), del...
1
2016-08-19T08:19:13Z
39,416,946
<p>This code runs fine:</p> <pre><code>import csv with open('input.csv', 'rb') as csvfile: reader = csv.reader(csvfile, delimiter='|', quotechar='|') writer1 = csv.writer(open('output.csv', 'wb'), delimiter = '|') for row in reader: a = row[0] if (a=='D1'): writer1....
0
2016-09-09T17:35:28Z
[ "python", "csv" ]
How to modify cells in a pandas DataFrame?
39,034,351
<p>I need to change individual elements in a DataFrame. I tried doing something like this, but it doesn't work:</p> <pre><code>for index, row in df.iterrows(): if df.at[row, index] == 'something': df.at[row, index] = df.at[row, index] + 'add a string' else: df.at[row, index] = df.at[row, index]...
2
2016-08-19T08:22:35Z
39,034,468
<p>If need modify all columns in <code>DataFrame</code> use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow"><code>DataFrame</code></...
1
2016-08-19T08:29:08Z
[ "python", "string", "pandas", "dataframe", "condition" ]
How to modify cells in a pandas DataFrame?
39,034,351
<p>I need to change individual elements in a DataFrame. I tried doing something like this, but it doesn't work:</p> <pre><code>for index, row in df.iterrows(): if df.at[row, index] == 'something': df.at[row, index] = df.at[row, index] + 'add a string' else: df.at[row, index] = df.at[row, index]...
2
2016-08-19T08:22:35Z
39,037,148
<p>You can use <code>.ix</code> and apply a function like this:</p> <pre><code>import pandas as pd D = pd.DataFrame({'A': ['a', 'b', 3,7,'b','a'], 'B': ['a', 'b', 3,7,'b','a']}) D.ix[D.index%2 == 0,'A'] = D.ix[D.index%2 == 0,'A'].apply(lambda s: s+'x' if isinstance(s,str) else s+1) D.ix[D.index[2:5],'B'] = D.ix[D.i...
1
2016-08-19T10:48:38Z
[ "python", "string", "pandas", "dataframe", "condition" ]
Risk to overwrite tables via Django Models migrations?
39,034,499
<p>I'm currently trying to update my Django models to incorporate some new functionality but after runnning "makemigrations", the console output makes me worried I'm going to overwrite other tables in the database. </p> <p>Essentially, in my models.py, I have 8 models. One is entirely new, one is merely modified. I wa...
0
2016-08-19T08:30:51Z
39,034,579
<p>Django doesn't interrogate the database itself when making migrations; it builds up a graph based on previous migrations and the current state of the models. So if there are no previous migrations Django will create them from scratch. This won't overwrite your tables, but it won't actually work either, as it will at...
2
2016-08-19T08:35:47Z
[ "python", "django", "python-2.7", "django-models", "django-migrations" ]
Python: "unexpected end of regular expression" during re.compile, empty brackets
39,034,603
<p>To summarize i have <code>re.compile</code> statement like so:</p> <pre><code>markers = ['x'] # some list re.compile(r" *[{}].*(?=\n|$)".format('\\'.join([''] + markers))) </code></pre> <p>For most cases it works fine <strong>unless <code>markers</code> is empty</strong> and RegEx pattern looks like so:</p> <pre>...
0
2016-08-19T08:37:34Z
39,035,409
<p>You may check if the markers list is not empty <em>at the very beginning</em>, then, only escape the characters that must be escaped in the character class: <code>^</code>, <code>\</code>, <code>]</code>, <code>[</code>, <code>-</code>.</p> <p>Note that if the markers list is empty, the pattern becomes <code> *.*</...
1
2016-08-19T09:18:48Z
[ "python", "regex", "python-2.7" ]
Which exception should I throw if a module is not the correct version?
39,034,635
<p>This may have been asked before or I may be overly pedantic, but my own searches have come up empty.</p> <p>Looking through the <a href="https://docs.python.org/2/library/exceptions.html" rel="nofollow">Python 2.x exceptions page</a>, I'm not sure which one I should <code>raise</code> if my script determines that t...
0
2016-08-19T08:39:07Z
39,034,724
<p>You can create you own custom exception if the existing ones don't suffice.</p> <pre><code>class VersionError(Exception): def __init__(self, msg): Exception.__init__(self,msg) </code></pre>
2
2016-08-19T08:44:02Z
[ "python", "exception", "version" ]
Which exception should I throw if a module is not the correct version?
39,034,635
<p>This may have been asked before or I may be overly pedantic, but my own searches have come up empty.</p> <p>Looking through the <a href="https://docs.python.org/2/library/exceptions.html" rel="nofollow">Python 2.x exceptions page</a>, I'm not sure which one I should <code>raise</code> if my script determines that t...
0
2016-08-19T08:39:07Z
39,034,756
<p>You've got a lot of options depending on what you want to do with this exception... Generally, I'd expect the install scripts to handle setting up the appropriate versions of dependencies so I might think of this as a simple runtime assertion -- Therefore <code>AssertionError</code> may be appropriate.</p> <p>This ...
2
2016-08-19T08:46:46Z
[ "python", "exception", "version" ]
Changing Odoo 9 "login title"
39,034,681
<p>I was following this post <a href="http://stackoverflow.com/questions/26974431/odoo-8-how-to-change-page-title/29182681#29182681">Odoo 8 - how to change page title?</a> on how to change Odoo 9 login title . I believe I followed the steps and also restarted the server, but the title didn't change. Any suggestions?</p...
-2
2016-08-19T08:41:07Z
39,038,555
<p>So i figured found a way to do it.</p> <p>1.Click the drop down menu on administrator(In the upper right corner).</p> <p>2.Click the "about" link and activate developer mode.</p> <p>3.Now go to settings,User interface,Views.Type "layout" in search bar.A set of layouts is brought.Click on Web layout.Click edit.In ...
0
2016-08-19T11:58:15Z
[ "python", "odoo-9" ]
Unexpected behaviour when grouping outliers in pandas [Python]
39,034,691
<p>My dataframe is in this format </p> <pre><code>df Count DateTime 2015-01-16 10 2015-01-17 28 2015-01-18 26 2015-01-19 10 2015-01-20 24 2015-01-21 25 </code></pre> <p>Im experimenting with this function to eliminate outliers using groupby</p> <pre><code>def replaceit(group): mean, std = ...
1
2016-08-19T08:42:03Z
39,034,744
<p>Problem is if use <code>df2 = df</code> it is reference to the initial DataFrame. Thus, changing <code>df2</code> will change the initial DataFrame <code>df</code>.</p> <p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.copy.html" rel="nofollow"><code>copy</code></a>:</p> <...
2
2016-08-19T08:45:44Z
[ "python", "pandas", "dataframe" ]
Create a python class with a uniqure feature
39,034,712
<p>I have a bunch of interdependent variables that I want to save in a list of class elements. Now I want it to be sorted according to one of the class features. At the moment, what I am doing is this:</p> <pre><code> class myclass(object): lst_of_A=[] def __init__(self, Attr_A, Attr_B, Attr_C): ...
0
2016-08-19T08:43:13Z
39,036,009
<p>First point, you want to use a <code>dict</code> (or <code>OrderedDict</code> if insertion order matters) instead of a <code>list</code> - this makes for more readable and much faster code. </p> <p>Second point, you want to encapsulate all the handling of this collection (specially the "create or extend" part) so t...
0
2016-08-19T09:51:33Z
[ "python", "list", "class" ]
add exceptions to python function
39,034,718
<p>I have a function that takes an integer as input and returns the number as words, it works as I want with the exception of <code>30,40,50,60,70,80</code> and <code>90</code>, it returns for <code>90 = ninty zero</code>, because the function works by splitting the number, how can I remove the zero being added for the...
0
2016-08-19T08:43:39Z
39,034,802
<p>Just perform an extra pass to correct problems. Sometimes simpler than trying to figure out how to avoid them.</p> <pre><code>print wordify(90).replace(" zero","") </code></pre> <p>or: rename your wordify function into <code>internal_wordify</code>, then define <code>wordify</code> like that:</p> <pre><code>def w...
0
2016-08-19T08:48:55Z
[ "python", "python-2.7", "function" ]
add exceptions to python function
39,034,718
<p>I have a function that takes an integer as input and returns the number as words, it works as I want with the exception of <code>30,40,50,60,70,80</code> and <code>90</code>, it returns for <code>90 = ninty zero</code>, because the function works by splitting the number, how can I remove the zero being added for the...
0
2016-08-19T08:43:39Z
39,034,823
<p>Changing the following line:</p> <pre><code>if n % 100 == 0: return d[n] </code></pre> <p>to</p> <pre><code>if n % 10 == 0: return d[n] </code></pre> <p>solves this issue. Since it will then always use the single word and not add the zero behind it whenever it's a multiple of 10.</p>
2
2016-08-19T08:50:02Z
[ "python", "python-2.7", "function" ]
Heatmap for nonuniformly spaced data
39,034,797
<p>I want to create a heatmap using matplotlib like the one depicted below. The data is not uniformly spaced as you can see from the axes ticks. So suppose we have</p> <pre><code>x = [1, 1.5, 2, 2.5, 3, 3.5, 4, 5, 7] y = [.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5] vals = np.random.rand(len(x), len(y)) </code></pre> <p>How ...
-1
2016-08-19T08:48:41Z
39,035,053
<p>you should interpolate missing data, I used in one of my project following:</p> <pre><code>#create regular grid xi, yi = np.linspace(x.min(), x.max(), 100), np.linspace(y.min(), y.max(), 100) xi, yi = np.meshgrid(xi, yi) #interpolate missing data rbf = scipy.interpolate.Rbf(x, y, z, function='linear') zi = rbf(xi,...
0
2016-08-19T09:02:24Z
[ "python", "matplotlib", "plot", "heatmap" ]
Django signals for models value change condition?
39,034,798
<p>I have a very simple models in my models.py like this :</p> <pre><code>class Music(models.Model): title= models.CharField( max_length=100 ) description = models.TextField( null=True, blank=True ) def __unicode__(self): return self.name class Album(models.Model...
0
2016-08-19T08:48:48Z
39,036,405
<p>So I you want to trigger your signal only when certain field is changed right? You can use a package called <a href="https://github.com/grantmcconnaughey/django-field-history" rel="nofollow">Django Field history</a></p> <p>Something like this:</p> <pre><code>@receiver(post_save, sender=&lt;sender&gt;, dispatch_uid...
0
2016-08-19T10:12:01Z
[ "python", "django", "signals" ]
How to parallelize task in Flask?
39,034,849
<p>I'm sending a XHR request to my Flask server in order to do several pings on a network</p> <h2>Resource</h2> <pre><code>def get(self, site_id): … for printer in printers: hostname = printer['hostname'] response[site_id][hostname] = network_utils.ping(hostname) return response </code>...
1
2016-08-19T08:51:12Z
39,037,917
<p>Make the subprocess asynchronous via <a href="http://www.gevent.org/" rel="nofollow">gevent</a>, for example.</p> <pre><code>from gevent import subprocess import gevent def ping(hostname): command = ['ping', '-c', '1', '-W', '1', '-q', hostname] return subprocess.Popen(command, stdout=subprocess.PIPE) def...
1
2016-08-19T11:27:27Z
[ "python", "flask", "parallel-processing", "ping", "flask-restful" ]
How to parallelize task in Flask?
39,034,849
<p>I'm sending a XHR request to my Flask server in order to do several pings on a network</p> <h2>Resource</h2> <pre><code>def get(self, site_id): … for printer in printers: hostname = printer['hostname'] response[site_id][hostname] = network_utils.ping(hostname) return response </code>...
1
2016-08-19T08:51:12Z
39,037,929
<p>Sounds like the best choice is threading because your issue is <strong>I/O bound</strong>. I'm using <a href="https://docs.python.org/2/library/threading.html#semaphore-objects" rel="nofollow">Semaphore</a> to limit to 5 threads.</p> <p>I'm sending the response dict to the ping dict are thread safe, but you should...
2
2016-08-19T11:27:49Z
[ "python", "flask", "parallel-processing", "ping", "flask-restful" ]
How to parallelize task in Flask?
39,034,849
<p>I'm sending a XHR request to my Flask server in order to do several pings on a network</p> <h2>Resource</h2> <pre><code>def get(self, site_id): … for printer in printers: hostname = printer['hostname'] response[site_id][hostname] = network_utils.ping(hostname) return response </code>...
1
2016-08-19T08:51:12Z
39,052,548
<p>Upvote <a href="http://stackoverflow.com/a/39037929/802365">Or Duan answer</a> as mine is based on his answer:</p> <h3>Resource</h3> <pre><code>class Ping(Resource): def get(self, site_id): site_hostname = mast_utils.list_sites(site_id)['results'][0]['hostname'] printers = mast_utils.list_print...
0
2016-08-20T09:30:00Z
[ "python", "flask", "parallel-processing", "ping", "flask-restful" ]
Python script not getting executed when put on crontab
39,034,905
<p>I have written a python script which is reading some logs and then writing the required info into a csv file.Its working fine if I execute it manually by python <code>myscript.py</code> .However when I m calling it through cron its not working. I have tried:</p> <pre><code>* * * * * python /path/to/myscript.py * * ...
-3
2016-08-19T08:54:22Z
39,035,132
<p>Default shell for cron is not <code>/bin/bash</code>, so you need to give the full path to Python executable.<br> Check the output of <code>which python</code>. On my machine it's <code>/usr/bin/python</code>.<br> Assuming this, your cron job entry should be:</p> <pre><code>* * * * * /usr/bin/python /path/to/myscri...
0
2016-08-19T09:06:40Z
[ "python", "shell", "cron-task" ]
Python script not getting executed when put on crontab
39,034,905
<p>I have written a python script which is reading some logs and then writing the required info into a csv file.Its working fine if I execute it manually by python <code>myscript.py</code> .However when I m calling it through cron its not working. I have tried:</p> <pre><code>* * * * * python /path/to/myscript.py * * ...
-3
2016-08-19T08:54:22Z
39,035,239
<p>Make sure that you do not use any kind of relative paths inside your python script. This can cause your script to exit with an error. </p> <p>So make sure that within your script you do not use <code>../to/something</code>, but instead <code>/path/to/something</code>.</p> <p>ie</p> <pre><code>with open('../file.t...
0
2016-08-19T09:11:16Z
[ "python", "shell", "cron-task" ]
How to print out elements of a class
39,034,964
<p>I just got started with python, now I need to print out the names of elements/objects/instances of a class, this is my code: </p> <pre><code>class Delicious : sweet = 0 sour = 0 apple = Delicious() kiwi = Delicious() litchi = Delicious() bracket = [apple, kiwi, lichi] print(bracket) </code></pre> <p>I ...
-1
2016-08-19T08:57:56Z
39,035,216
<p>The way to get this to work is by grabbing the instances name from <code>globals()</code> and returning it from <code>__str__</code>:</p> <pre><code>class Delicious : sweet = 0 sour = 0 def __str__(self): for k, v in globals().items(): if v == self: return k de...
2
2016-08-19T09:10:06Z
[ "python", "python-3.x" ]
Convert a list of Gene Symbols to UniProt accession numbers using Python
39,035,103
<p>I have a list of gene symbols which represent the intersection of two high throughput data sets. I'm interested in doing some sort of GO annotation and clustering, but in order to do this I need to convert these gene symbols into UniProt accession numbers. My question is, what is the best way to do this using Python...
0
2016-08-19T09:05:12Z
39,299,849
<p>Get some mapping from gene name to PDB ID, like this JSON: <a href="http://www.rcsb.org/pdb/browse/homo_sapiens_download.jsp?rows=100000&amp;page=1&amp;sidx=id&amp;sord=desc" rel="nofollow">http://www.rcsb.org/pdb/browse/homo_sapiens_download.jsp?rows=100000&amp;page=1&amp;sidx=id&amp;sord=desc</a> saving it for exa...
1
2016-09-02T19:55:30Z
[ "python", "converter", "biopython" ]
Run Python program as service on Ubuntu 16.04 inside a virtual environment
39,035,233
<p>I'm trying to get a Flask + SocketIO app running as a service on Ubuntu 16.04, inside a virtual environment. My server is restarted every day at 3 am (outside of my control), so I need it to automatically launch on startup.</p> <p>Running the script by itself works fine:</p> <pre><code>$ python main.py (29539) wsg...
0
2016-08-19T09:11:06Z
39,671,027
<p>I believe that you mistype PYTHON_HOME and than PATH=$VIRTUAL_ENV/bin:$PATH</p> <p>you should use PATH=$PYTHON_HOME/bin:$PATH</p>
0
2016-09-23T23:43:10Z
[ "python", "ubuntu", "flask", "virtualenv", "daemon" ]
How can I get the number of groups to vary depending on the number of lines?
39,035,234
<p>I have this regex: <code>^:([^:]+):([^:]*)</code> which works as in <a href="https://regex101.com/r/qM5nR0/2" rel="nofollow">this regex101 link</a>.</p> <p>Now, in Python, I have this:</p> <pre><code>def get_data(): data = read_mt_file() match_fields = re.compile('^:([^:]+):([^:]*)', re.MULTILINE) fie...
0
2016-08-19T09:11:06Z
39,035,667
<p>To do what you want, you'd need another regex. This is as <code>re.match</code> only matches the last item it matches:</p> <pre><code>&gt;&gt;&gt; re.match(r'(\d)+', '12345').groups() ('5',) </code></pre> <p>Instead of using one regex you'll need to use two. The one that you are using at the moment, and then one t...
1
2016-08-19T09:30:49Z
[ "python", "regex", "python-3.x", "split" ]
How can I get the number of groups to vary depending on the number of lines?
39,035,234
<p>I have this regex: <code>^:([^:]+):([^:]*)</code> which works as in <a href="https://regex101.com/r/qM5nR0/2" rel="nofollow">this regex101 link</a>.</p> <p>Now, in Python, I have this:</p> <pre><code>def get_data(): data = read_mt_file() match_fields = re.compile('^:([^:]+):([^:]*)', re.MULTILINE) fie...
0
2016-08-19T09:11:06Z
39,043,680
<p>You may use a simple trick: after getting the matches with your regex, run a <code>.+\n*</code> regex over the Group 2 value:</p> <pre><code>import re p = re.compile(r'^:([^:]+):([^:]+)', re.MULTILINE) s = ":1:text\ntext\n\n:20:text\n\n:21:text\ntext\ntext\n\n:22: \n\n:25:aa\naa\naaaaa" print([[x.group(1)] + re.fin...
1
2016-08-19T16:20:37Z
[ "python", "regex", "python-3.x", "split" ]
Why do every virtual environment use(point) same python version in pyenv?
39,035,288
<p>I'm using <code>pyenv</code>, <code>virtualenv</code>, 'autoev` for setting my virtual environment.</p> <p>I install <code>Python3.5.1</code>, <code>Python2.7.9</code> and create several project virtual environments.</p> <p>But when I activate each environment and check python version by <code>which python</code>:...
2
2016-08-19T09:13:23Z
39,035,384
<p>To change the <code>PYTHONPATH</code> used in a <code>virtualenv</code>, you will have to add this line to your virtualenv's <code>bin/activate</code> file:</p> <p>`export PYTHONPATH="/correct_path/"</p> <p><br> So in your case it should be <code>export PYTHONPATH="/Users/Chois/.pyenv/versions/chacha_dabang/bin/py...
0
2016-08-19T09:17:41Z
[ "python", "virtualenv", "pyenv" ]
Why do every virtual environment use(point) same python version in pyenv?
39,035,288
<p>I'm using <code>pyenv</code>, <code>virtualenv</code>, 'autoev` for setting my virtual environment.</p> <p>I install <code>Python3.5.1</code>, <code>Python2.7.9</code> and create several project virtual environments.</p> <p>But when I activate each environment and check python version by <code>which python</code>:...
2
2016-08-19T09:13:23Z
39,061,621
<p>No problem</p> <p>When you try to run Python, it first looks for a <code>.python-version</code> in the current directory to decide which version of python to run. If it doesn’t find this file, then it looks for the user-level file <code>~/.pyenv/version</code>.</p> <p>You can use <code>python --version</code> in...
1
2016-08-21T06:57:13Z
[ "python", "virtualenv", "pyenv" ]
fast way to loop over whole python dictionary
39,035,291
<p>I have non-ordered data that sometimes I want to analyse by looking at all the entries and some other time I want to pick just one entry.</p> <p><code> p1 x1 x2 x3 x4 p2 x1 x2 x3 x4 p33 x1 x2 x3 x4 p3 x1 x2 x3 x4 p4 x1 x2 x3 x4 </code></p> <p><code>Dictionary</code> seems a nice format to store the data, ...
0
2016-08-19T09:13:33Z
39,036,018
<p>If its possible use numpy/pandas...</p> <p>For me Python is only for High Level Programming and Low Level is C++... So if possible use existing c++ functions which are in numpy pandas or other libs..</p> <p>Check it out...</p> <pre><code>&gt;&gt;&gt; import numpy as np, pandas as pd &gt;&gt;&gt; p1 = np.arange(10...
0
2016-08-19T09:52:12Z
[ "python", "performance", "dictionary", "bigdata" ]
JoinableQueue join() method blocking main thread even after task_done()
39,035,329
<p>In below code, if I put <code>daemon = True</code> , consumer will quit before reading all queue entries. If consumer is non-daemon, Main thread is always blocked even after the <code>task_done()</code> for all the entries.</p> <pre><code>from multiprocessing import Process, JoinableQueue import time def consume...
0
2016-08-19T09:14:59Z
39,060,824
<p>Let's see what—I believe—is happening here:</p> <ol> <li>both processes are being started.</li> <li>the <code>consumer</code> process starts its loop and blocks until a value is received from the queue.</li> <li>the <code>producer1</code> process feeds the queue 26 times with a letter while the main process fee...
0
2016-08-21T04:24:31Z
[ "python", "multiprocessing" ]
python - Implementing Sobel operators with python without opencv
39,035,510
<p>Given a greyscale 8 bit image (2D array with values from 0 - 255 for pixel intensity), I want to implement the Sobel operators (mask) on an image. The Sobel function below basically loops around a given pixel,applies the following weight to the pixels: <a href="http://i.stack.imgur.com/1N67K.png" rel="nofollow"><i...
2
2016-08-19T09:24:08Z
39,037,728
<p>If using NumPy ans SciPy is not a problem, then a simple solution is to use the SciPy's <a href="http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.signal.convolve2d.html" rel="nofollow"><code>convolve2d()</code></a>.</p> <pre><code>import numpy as np from scipy.signal import convolve2d from scipy.ndi...
0
2016-08-19T11:17:57Z
[ "python", "image", "vision", "sobel" ]