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
pygame.error: Couldn't open mp3
38,647,923
<p>Here's the code for something I was testing out to put in a game I'm creating. I made this code to try to make the music loop over and over again. Here:</p> <pre><code>from pygame import mixer mixer.init() mixer.music.load('C:\\Users\\owner-\\Dropbox\\Programming\\Zelpha808\\music.mp3') def play(): timer = 1 ...
0
2016-07-28T22:44:37Z
38,648,259
<p>Try just putting the mp3 in the same directory as your .py file. And about the music looping, if you have a loop that is keeping your window open, you should call <code>pygame.mixer.music.play(loops=-1)</code> before the loop. This tells pygame to keep looping the music contentiously. As the pygame.mixer.music doc s...
0
2016-07-28T23:22:23Z
[ "python", "pygame", "mp3", "python-3.5" ]
pygame.error: Couldn't open mp3
38,647,923
<p>Here's the code for something I was testing out to put in a game I'm creating. I made this code to try to make the music loop over and over again. Here:</p> <pre><code>from pygame import mixer mixer.init() mixer.music.load('C:\\Users\\owner-\\Dropbox\\Programming\\Zelpha808\\music.mp3') def play(): timer = 1 ...
0
2016-07-28T22:44:37Z
38,648,977
<p>It turns out that the music file is a .wav file... The original file was a .mp3, and it had like 10 seconds of silence at the beginning of it. So I put it in audacity, and cut it out, and I guess it changed it to a .wav file. I feel so stupid hahaha. But that did it, I did mixer.music.load('C:/Users/owner-/Dropbox/P...
0
2016-07-29T01:03:30Z
[ "python", "pygame", "mp3", "python-3.5" ]
Sum list of list elements in python like sql group by
38,647,928
<p>I have a list of lists (string,integer)</p> <p>eg:</p> <pre><code>my_list=[["apple",5],["banana",6],["orange",6],["banana",9],["orange",3],["apple",111]] </code></pre> <p>I'd like to sum the same items and finally get this:</p> <pre><code>my2_list=[["apple",116],["banana",15],["orange",9]] </code></pre>
0
2016-07-28T22:45:02Z
38,647,985
<pre><code>from collections import defaultdict my_list= [["apple",5],["banana",6],["orange",6],["banana",9],["orange",3],["apple",111]] result = defaultdict(int) for fruit, value in my_list: result[fruit] += value result = result.items() print result </code></pre> <p>Or you can keep result as dictionary</p>
2
2016-07-28T22:51:25Z
[ "python", "list" ]
Sum list of list elements in python like sql group by
38,647,928
<p>I have a list of lists (string,integer)</p> <p>eg:</p> <pre><code>my_list=[["apple",5],["banana",6],["orange",6],["banana",9],["orange",3],["apple",111]] </code></pre> <p>I'd like to sum the same items and finally get this:</p> <pre><code>my2_list=[["apple",116],["banana",15],["orange",9]] </code></pre>
0
2016-07-28T22:45:02Z
38,647,993
<p>You can use <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a> on the <em>sorted</em> list:</p> <pre><code>from itertools import groupby my_list=[["apple",5],["banana",6],["orange",6],["banana",9],["orange",3],["apple",111]] my_list2 = []...
2
2016-07-28T22:51:47Z
[ "python", "list" ]
Sum list of list elements in python like sql group by
38,647,928
<p>I have a list of lists (string,integer)</p> <p>eg:</p> <pre><code>my_list=[["apple",5],["banana",6],["orange",6],["banana",9],["orange",3],["apple",111]] </code></pre> <p>I'd like to sum the same items and finally get this:</p> <pre><code>my2_list=[["apple",116],["banana",15],["orange",9]] </code></pre>
0
2016-07-28T22:45:02Z
38,647,998
<pre><code>from itertools import groupby [[k, sum(v for _, v in g)] for k, g in groupby(sorted(my_list), key = lambda x: x[0])] # [['apple', 116], ['banana', 15], ['orange', 9]] </code></pre>
0
2016-07-28T22:52:13Z
[ "python", "list" ]
Sum list of list elements in python like sql group by
38,647,928
<p>I have a list of lists (string,integer)</p> <p>eg:</p> <pre><code>my_list=[["apple",5],["banana",6],["orange",6],["banana",9],["orange",3],["apple",111]] </code></pre> <p>I'd like to sum the same items and finally get this:</p> <pre><code>my2_list=[["apple",116],["banana",15],["orange",9]] </code></pre>
0
2016-07-28T22:45:02Z
38,648,218
<p>Using Pandas and <code>groupby</code>:</p> <pre><code>import pandas as pd &gt;&gt;&gt; pd.DataFrame(my_list, columns=['fruit', 'count']).groupby('fruit').sum() count fruit apple 116 banana 15 orange 9 </code></pre>
0
2016-07-28T23:17:45Z
[ "python", "list" ]
Sum list of list elements in python like sql group by
38,647,928
<p>I have a list of lists (string,integer)</p> <p>eg:</p> <pre><code>my_list=[["apple",5],["banana",6],["orange",6],["banana",9],["orange",3],["apple",111]] </code></pre> <p>I'd like to sum the same items and finally get this:</p> <pre><code>my2_list=[["apple",116],["banana",15],["orange",9]] </code></pre>
0
2016-07-28T22:45:02Z
38,653,442
<p>If you dont want the order to preserved, then plz use the below code.</p> <pre><code>my_list=[["apple",5],["banana",6],["orange",6],["banana",9],["orange",3],["apple",111]] my_dict1 = {} for d in my_list: if d[0] in my_dict1.keys(): my_dict1[d[0]] += d[1] else: my_dict1[d[0]] = d[1] my_list2 = [...
0
2016-07-29T07:56:34Z
[ "python", "list" ]
How to quickly fetch all documents MongoDB pymongo
38,647,962
<p>Currently I fetch documents by iterating through cursor in pymongo, for example:</p> <pre><code>for d in db.docs.find(): mylist.append(d) </code></pre> <p>For reference, performing a fetchall on the same set of data (7m records) takes around 20 seconds while the method above takes a few minutes.</p> <p>Is the...
2
2016-07-28T22:49:20Z
38,661,360
<p>using the $natural sort will bypass the index and return the documents in the order in which they are stored on disk, meaning that mongo doesn't have to thrash around with random reads on your disk.</p> <p><a href="https://docs.mongodb.com/manual/reference/method/cursor.sort/#return-natural-order" rel="nofollow">ht...
1
2016-07-29T14:30:25Z
[ "python", "mongodb", "nosql", "pymongo" ]
Celery, RabbitMQ, Redis: Celery message enters exchange, but not queue?
38,647,974
<p>I'm using Python 2.7 (sigh), celery==3.1.19, librabbitmq==1.6.1, rabbitmq-server-3.5.6-1.noarch, and redis 2.8.24 (from redis-cli info).</p> <p>I'm attempting to send a message from a celery producer to a celery consumer, and obtain the result back in the producer. There is 1 producer and 1 consumer, but 2 rabbitm...
0
2016-07-28T22:50:14Z
38,662,361
<p>It appears that using the following task stub in the producer solved the problem:</p> <pre><code>@CELERY_RESULT.task(name='ZipUp', queue='cognition.workflow.ZipUp_%s' % INTERNAL_VERSION) def ZipUp(directory): # pylint: disable=invalid-name """ Task stub """ _unused_directory = directory raise NotImpleme...
0
2016-07-29T15:24:10Z
[ "python", "redis", "rabbitmq", "celery" ]
eglInitialize failure using ANGLE dll from python 64 bits
38,648,125
<p>I've been using the ANGLE dlls for a while to run OpenGLES2.0 code on windows from 32 bit python (pi3d module) However I can't get it to work with 64 bits. I have <a href="https://github.com/paddywwoof/pi3d_windll" rel="nofollow">compiled the libraries</a> and at one stage, on a different laptop to which I don't hav...
0
2016-07-28T23:04:06Z
38,654,764
<p>Probably a 32-bit integer is given as an argument or expected as the type for the returned value instead of a 64-bit unsigned integer. This happens commonly for pointer values (handles) since 64-bit windows has 32-bit integers and 64-bit pointers. Defining <code>argtypes</code> and <code>restypes</code> attributes m...
1
2016-07-29T09:04:31Z
[ "python", "dll", "opengl-es", "ctypes" ]
Keras low accuracy classification task
38,648,195
<p>I was playing around with Keras and a dummy dataset. I wanted to see how much better a neural network would do compared to a standard SVM with a RBF kernel. The task was simple: predict the class for a 20-dim vector in the set {0,1,2}. </p> <p>I noticed that the neural network does horribly. The SVM gets around 90%...
1
2016-07-28T23:14:15Z
38,672,367
<p>After several tries of your example, I figured out that accuracy fluctuates between 0.3 and to 0.9 regardless of learning technique. I believe that this happening because of random and meaningless data – it’s hardly possible to recognize any features inside white noise</p> <p>I suggest using meaningful datasets...
0
2016-07-30T09:24:07Z
[ "python", "neural-network", "gpu", "theano", "keras" ]
Problems converting string to integer splitting two variables in Python 3
38,648,216
<p>Using Python 3.4 in Idle. Why am I getting this error message... </p> <pre><code>ValueError: invalid literal for int() with base 10: '4 4' </code></pre> <p>when converting my input statement into an integer. I'm trying to put <code>int</code> in my input statement vs using </p> <pre><code>num1 = int(num1) num2 ...
0
2016-07-28T23:17:19Z
38,648,281
<p>Your second way is trying to convert <code>4 4</code> into an <code>int</code> which it can't do, you need to apply <code>int</code> to each individual number as a string, so your code becomes:</p> <pre><code>num1, num2 = map(int, input('Enter 2 numbers: ').split()) </code></pre> <p>On a side note - by calling you...
0
2016-07-28T23:25:18Z
[ "python", "python-3.4" ]
How to call a function for every for iteration of a zip of two lists?
38,648,220
<p>I have two lists: <code>a=[1,2,3]</code>, <code>b=[a,b,c]</code></p> <p>I want for each <code>zip</code> of those two to call a function, but not to do it in a trivial way inside a for loop. Is there a pythonic way? I tried with a <code>map</code>:</p> <p><code>map(func(i,v) for i,v in zip(a,b))</code></p> <p>but...
0
2016-07-28T23:18:10Z
38,648,247
<p>A list comprehension is almost always faster or equivalent to <code>map</code>. If you append the results of the comprehension to a list (as in the example), then a comprehension is also faster than a <code>for loop</code>:</p> <pre><code>a = [1, 2, 3] b = ['a', 'b', 'c'] c = [] def foo(x, y): global c re...
1
2016-07-28T23:20:53Z
[ "python", "dictionary", "iterator" ]
How to call a function for every for iteration of a zip of two lists?
38,648,220
<p>I have two lists: <code>a=[1,2,3]</code>, <code>b=[a,b,c]</code></p> <p>I want for each <code>zip</code> of those two to call a function, but not to do it in a trivial way inside a for loop. Is there a pythonic way? I tried with a <code>map</code>:</p> <p><code>map(func(i,v) for i,v in zip(a,b))</code></p> <p>but...
0
2016-07-28T23:18:10Z
38,648,272
<p>The pythonic way <em>is</em> the for loop:</p> <pre><code>for i, v in zip(a, b): func(i, v) </code></pre> <p>Clear, concise, readable. What's not to like?</p>
5
2016-07-28T23:24:24Z
[ "python", "dictionary", "iterator" ]
How to call a function for every for iteration of a zip of two lists?
38,648,220
<p>I have two lists: <code>a=[1,2,3]</code>, <code>b=[a,b,c]</code></p> <p>I want for each <code>zip</code> of those two to call a function, but not to do it in a trivial way inside a for loop. Is there a pythonic way? I tried with a <code>map</code>:</p> <p><code>map(func(i,v) for i,v in zip(a,b))</code></p> <p>but...
0
2016-07-28T23:18:10Z
38,648,493
<p><strong>If</strong> the function <code>func</code> doesn't return anything, you could use:</p> <pre><code>any(func(i, v) for i,v in zip(a, b)) </code></pre> <p>Which will return <code>False</code> but not accumulate the results.</p> <p>This would not be considered "Pythonic" by many since <code>any()</code> is be...
0
2016-07-28T23:54:17Z
[ "python", "dictionary", "iterator" ]
In Jupyter Lab, execute editor code in Python console
38,648,286
<p>In <a href="https://github.com/jupyter/jupyterlab" rel="nofollow">Jupyter Lab</a>, I want to send code from the editor to the Python console for execution, preferably with a keyboard shortcut. The documentation doesn't seem to offer a way to do this, but it's such a fundamental aspect of an IDE that I imagine it's p...
0
2016-07-28T23:25:48Z
39,419,764
<p>This is planned as a feature for the 1.0 release. See <a href="https://github.com/jupyter/jupyterlab/issues/450" rel="nofollow">https://github.com/jupyter/jupyterlab/issues/450</a> </p>
0
2016-09-09T21:11:40Z
[ "python", "anaconda", "jupyter", "jupyter-notebook" ]
In JavaScript code how to get data from a Python JSON variable
38,648,316
<p>The following code in Python:</p> <pre><code>jsVar = (json.dumps(jsPass)) </code></pre> <p>produces this output: </p> <pre><code>{ "TT1004": [ [1004, 45.296109039999997, -75.926546579999993, 66.996664760000002, 150, false ] ], "TT1001": [ [1001, 45.296471220000001, -75.923881289999997, 64....
1
2016-07-28T23:29:38Z
38,649,347
<p><strong>From your original post</strong>:<br></p> <blockquote> <p>Python: <code>jsVar = (json.dumps(jsPass))</code></p> <p>JavaScript code: <code>var myVar2 = jsVar;</code></p> </blockquote> <p><strong>Q:</strong> How to access Python JSON variable from Javascript code?</p> <p><strong>A:</strong> Python an...
0
2016-07-29T01:56:47Z
[ "javascript", "python", "json" ]
Pulling Data from App Annie API - Python
38,648,328
<p>I need to pull some data from App Annie's API using Python. However I am unable to connect. I double checked my API key and the "documentation". Does anyone know how I can connect through their API? I keep getting a 401 unauthorized access error.</p> <p><a href="https://support.appannie.com/hc/en-us/articles/2...
0
2016-07-28T23:32:17Z
38,648,409
<p>You need to specify your api key in the HTTP header:</p> <pre><code>response = requests.get(url, headers={'Authorization':'bearer b7e26.........'}) </code></pre>
0
2016-07-28T23:43:10Z
[ "python", "appannie" ]
Can I call a dict of python objects from with a method of another class?
38,648,355
<p>I've created a class called Emp has attributes like employee number, department number, employee type etc. I've used this class to populate a dictionary called emp_dict.</p> <p>I've done a similar thing for Dept with details of the department, now I want to create a method in the department class to measure the nu...
2
2016-07-28T23:34:51Z
38,648,361
<p>The <code>contractor_count</code> variable is never touched again. You have: </p> <pre><code>contractor_count_= 1 </code></pre> <p>Did you mean this?</p> <pre><code>contractor_count += 1 </code></pre> <p>I would also recommend using a variable name that is different from the method name, to avoid possible confu...
2
2016-07-28T23:36:08Z
[ "python" ]
Can I call a dict of python objects from with a method of another class?
38,648,355
<p>I've created a class called Emp has attributes like employee number, department number, employee type etc. I've used this class to populate a dictionary called emp_dict.</p> <p>I've done a similar thing for Dept with details of the department, now I want to create a method in the department class to measure the nu...
2
2016-07-28T23:34:51Z
38,648,451
<p>It seems like you have a spelling error, and hit <code>_</code> instead of <code>+</code>:</p> <p>your code should be:</p> <pre><code>class Dept(): def __init__(self,deptno, deptname): self.deptno = deptno def contractor_count(self,qtr,emp_dict): contractor_count = 0 if qtr in ['FY14Q1A','FY14Q2A','FY...
0
2016-07-28T23:49:12Z
[ "python" ]
OpenCV Hough Circle Transform needs 8-bit image
38,648,387
<p>I am working with Hough Circle Transform with my RaspberryPi and when I take a ROI to check for circle like this:</p> <pre><code>for (x,y,w,h) in trafficLights: cv2.rectangle(image,(x,y),(x+w,y+h),(0,0,255),2) roi = image[y:y+h,x:x+w] roi = cv2.medianBlur(roi,5) circles = cv2.HoughCircles(roi,cv2.H...
0
2016-07-28T23:39:50Z
38,660,785
<p>Thank you Miki and bpachev for the help!</p> <p>The first error means that you need to convert it to grayscale like this</p> <pre><code>gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) </code></pre> <p>And the NoneType error means that no circles were found so to advoid the error you can add this if statement </p>...
0
2016-07-29T14:00:45Z
[ "python", "opencv", "numpy", "channel", "hough-transform" ]
Creating a polling bot
38,648,468
<pre><code>import requests dados = {"action": "polls", "view":"process", "poll_id":"2", "poll_2":"6", "poll_2_nonce":"e29cc82a53"} url = "http://soulegal.byethost7.com/wp/wp-admin/admin-ajax.php" requests.post(url, data=dados) </code></pre> <p>The site URL is : <a href="http://s...
1
2016-07-28T23:51:17Z
38,648,532
<p>Wordpress creates an IP/PC/Mac address and sever side keys (similiar to the PHP session id) which is used for loading. As well you might want to check what cookies are going back and forth between your browser and the voting poll page. </p>
0
2016-07-29T00:00:33Z
[ "python", "python-requests" ]
Creating a polling bot
38,648,468
<pre><code>import requests dados = {"action": "polls", "view":"process", "poll_id":"2", "poll_2":"6", "poll_2_nonce":"e29cc82a53"} url = "http://soulegal.byethost7.com/wp/wp-admin/admin-ajax.php" requests.post(url, data=dados) </code></pre> <p>The site URL is : <a href="http://s...
1
2016-07-28T23:51:17Z
38,648,557
<p>So you need to do a few things:</p> <ol> <li><p>You need to use a <code>requests.Session</code> instance so it can track cookies for you, including the cookie that Wordpress uses to allow you to vote from your poll page (which you have to make a get request to first).</p></li> <li><p>You need to get the nonce value...
1
2016-07-29T00:03:36Z
[ "python", "python-requests" ]
How do I read buffers from Gamemaker Studio in Python 3?
38,648,502
<p>I want to write a server in Python 3, I haven't used Python before and I have an idea on how the syntax works. But if I sent data like this through Gamemaker Studio</p> <pre><code> var buffer = buffer_create(1024,buffer_grow,1); buffer_seek(buffer,buffer_seek_start,0); buffer_write(buffer,buffer_s32,5); ...
2
2016-07-28T23:55:05Z
39,183,856
<p>Yo can read buffer using <code>struct.unpack</code> on python. here is the documentation <a href="https://docs.python.org/3.1/library/struct.html" rel="nofollow">https://docs.python.org/3.1/library/struct.html</a></p>
0
2016-08-27T17:25:43Z
[ "python", "game-maker" ]
Optimise python function fetching multi-level json attributes
38,648,535
<p>I have a 3 level json file. I am fetching the values of some of the attributes from each of the 3 levels of json. At the moment, the execution time of my code is pathetic as it is taking about 2-3 minutes to get the results on my web page. I will be having a much larger json file to deal with in production. </p> <p...
1
2016-07-29T00:01:02Z
38,648,809
<p>Ok, caching. So what we're going to do is start returning values to the user instantly based on data we already have, rather than generating new data every time. This means that the user might get slightly less up to date data than is theoretically possible to get, but it means that the data they do receive they rec...
0
2016-07-29T00:37:24Z
[ "python", "json", "python-2.7", "flask", "flask-restful" ]
Open .exe file through .bat file in Flask
38,648,550
<p>I am trying to open an .exe file (e.g. Paint) with a html button using Flask, so I wrote a small .bat file that runs it properly when I run it through Python, but does not seem to work when I open it through Flask.</p> <p>The Python is:</p> <pre><code>@app.route('/assemblies', methods=['GET', 'POST']) def assembli...
0
2016-07-29T00:02:43Z
38,652,272
<p>Found a solution after changing:</p> <pre><code>filepath="/static/run.bat" p = subprocess.Popen(filepath, shell=True, stdout = subprocess.PIPE) stdout, = p.communicate() </code></pre> <p>for:</p> <pre><code>subprocess.call(["static/myFile.exe"]) </code></pre> <p>and now it works. I am bypassing the bat file, bu...
0
2016-07-29T06:51:39Z
[ "python", "html", "windows", "batch-file", "flask" ]
Numpy trouble vectorizing certain kind of aggregation
38,648,561
<p>I am having difficulty in vectorizing the below operation:</p> <pre><code># x.shape = (a,) # y.shape = (a, b) # x and y are ordered over a. # Want to combine x, y into z.shape(num_unique_x, b) # Below works and illustrates intent but is iterative z = np.zeros((num_unique_x, b)) for i in range(a): z[x[i], y[i,...
0
2016-07-29T00:03:54Z
38,649,161
<p>Your use of <code>num_unique_x</code>, and the size of <code>z</code> suggests that this is a case where <code>x</code> and <code>y</code> have repeats, and that some of the <code>z</code> will be larger than 1. In which case we need to use <code>np.add.at</code>. But to set that up I'd have review its documentati...
1
2016-07-29T01:29:26Z
[ "python", "numpy" ]
Is there a workaround for "try: input() except KeyboardInterrupt:"
38,648,691
<p>I've searched this topic to no avail for hours.</p> <p>Is it possible to do something along the lines of:</p> <pre><code>try: input_var = input('&gt; ') except KeyboardInterrupt: print("This will not work.") </code></pre> <p>But when I try this and do CTRL-C, it just does nothing. </p> <p>Is there any ot...
1
2016-07-29T00:20:50Z
38,648,900
<p>It sounds like you would be interested in the signal module. </p> <p><a href="http://stackoverflow.com/a/1112350/4171411">This Answer</a> demonstrates how to use the signal module to capture Ctrl+C, or SIGINT.</p> <p>For your use case, something along the lines of the following would work :</p> <pre><code>#!/usr/...
1
2016-07-29T00:51:31Z
[ "python", "powershell", "windows-10", "python-3.5", "try-except" ]
mysql query failing due to "\" at the of one of string value
38,648,696
<p>I am generating queries using excel sheet in python and then executing the query using <code>conn.execute(query)</code>. </p> <p>However one query is failing because it has <code>\</code> at the end of one of the value string. Look for <code>VALUES ("test", "ABCD\"</code> in the query below:</p> <pre><code>INSERT ...
0
2016-07-29T00:21:24Z
38,648,736
<p>You specified 12 columns in your <code>INSERT</code> statement, but you only included values for 11 columns:</p> <pre><code>INSERT INTO S_account(Sub, AccName, AccTeam, Terr, AccOwner, Level1, GAccount, Customer, City, State, EndCusName, AccID) VALUES ("test", "ABCD\", "test", "test", "test", ...
1
2016-07-29T00:28:17Z
[ "python", "mysql" ]
Scipy.optimize minimize is taking too long
38,648,727
<p>I am running a constrained optimization problem with about 1500 variables and it is taking over 30 minutes to run....</p> <p>If I reduce the tolerance to 1 the minimization will complete in about five minutes, but that doesn't seem like a good way to speed things up. </p> <pre><code>from scipy.optimize import mini...
1
2016-07-29T00:26:15Z
38,656,480
<p>Here's what I'd do:</p> <ul> <li>profile the minimization. From your output it seems that evaluating the function is the bottleneck. Check if it's so. If it is, then:</li> <li>see if you can compute the jacobian with paper and pencil or a CAS system. Use it instead of finite differences.</li> <li>see if you can spe...
2
2016-07-29T10:25:59Z
[ "python", "optimization", "scipy", "minimize" ]
Scipy.optimize minimize is taking too long
38,648,727
<p>I am running a constrained optimization problem with about 1500 variables and it is taking over 30 minutes to run....</p> <p>If I reduce the tolerance to 1 the minimization will complete in about five minutes, but that doesn't seem like a good way to speed things up. </p> <pre><code>from scipy.optimize import mini...
1
2016-07-29T00:26:15Z
38,657,261
<p>Your tolerance should be set to whatever tolerance you need. Setting it higher just tells the optimiser to stop sooner and doesn't actually speed it up. That being said, allowing it to go to a greater tollerence might be a waste of your time if not needed.</p> <p>Possible ways to reduce the time required are as fol...
1
2016-07-29T11:05:29Z
[ "python", "optimization", "scipy", "minimize" ]
Why does numpy least squares result diverge from using the direct formula?
38,648,730
<p>I want to calculate the least squares estimate for given data.</p> <p>There are a few ways to do this, one is to use numpy's least squares:</p> <pre><code>import numpy np.linalg.lstsq(X,y)[0] </code></pre> <p>Where X is a matrix and y a vector of compatible dimension (type float64). Second way is to calculate the...
8
2016-07-29T00:26:27Z
38,648,835
<p>While those two formulas are mathematically equivalent, they <strong>are not</strong> numerically equivalent! There are better ways to solve a system of linear equations Ax = b than by multiplying both sides by A^(-1), like <a href="https://en.wikipedia.org/wiki/Gaussian_elimination">Gaussian Elimination</a>. <code>...
5
2016-07-29T00:42:04Z
[ "python", "numpy" ]
Color between the x axis and the graph in PyPlot
38,648,770
<p>I have a graph that was plotted using datetime objects for the x axis and I want to be able to color beneath the graph itself (the y-values) and the x axis. I found this post <a href="http://stackoverflow.com/questions/28091290/matplotlibs-fill-between-doesnt-work-with-plot-date-any-alternatives">Matplotlib&#39;s fi...
2
2016-07-29T00:32:38Z
38,664,967
<p>I've yet to determine what went wrong in your original code but I got it working with <a href="http://pandas.pydata.org/" rel="nofollow">pandas</a>:</p> <pre><code>import pandas as pd, matplotlib.pyplot as plt, matplotlib.dates as mdates df = pd.read_csv('/path/to/yourfile.csv') df['date'] = df['%YEAR'].astype(str...
1
2016-07-29T18:04:26Z
[ "python", "matplotlib" ]
Sorting with lambda in Python with an additional function
38,648,814
<p>I'm baffled by why this doesn't work.</p> <p>I have a function called <code>value(word)</code> which returns an integer value for any string, e.g.: <code>value('chicken') = 53</code>.</p> <p>Can <code>value()</code> be used within a lambda expression as a key to sort a list. In other words, can we do:</p> <pre><c...
-4
2016-07-29T00:37:54Z
38,648,821
<p>To get the order you expect, you need to sort in reverse order since the default is ascending order. You can use the <code>reverse</code> key word argument to do so. Also you can remove the <code>lambda</code> since <code>value</code> is <em>already</em> a function</p> <pre><code>def value(word): return sum(ord...
0
2016-07-29T00:39:30Z
[ "python", "python-3.x" ]
Sorting with lambda in Python with an additional function
38,648,814
<p>I'm baffled by why this doesn't work.</p> <p>I have a function called <code>value(word)</code> which returns an integer value for any string, e.g.: <code>value('chicken') = 53</code>.</p> <p>Can <code>value()</code> be used within a lambda expression as a key to sort a list. In other words, can we do:</p> <pre><c...
-4
2016-07-29T00:37:54Z
38,648,868
<p>Your function is working correctly:</p> <pre><code>sorted(words, key=lambda x: value(x)) </code></pre> <p>The issue is likely either with your <code>value</code> function or the sorting order. For instance, if your function is:</p> <pre><code>def value(s): return len(s) </code></pre> <p>then <code>sorted</co...
1
2016-07-29T00:47:53Z
[ "python", "python-3.x" ]
Bokeh Range Set Only 1 Bound
38,648,896
<p>I would expect the following code to set only the upper bound of the plot y range, however the lower bound is also inexplicably set to 0:</p> <pre><code>import bokeh.plotting as bkp import numpy as np bkp.output_file("/tmp/test_plot.html") fig = bkp.figure(y_range=[None, 100]) # plot y range: 0-100 # fig = bkp.fig...
0
2016-07-29T00:51:04Z
38,649,535
<p>The <code>Range1d(start=None, end=100)</code> (as you are also referring to in your comments) is only defining your initial view. It doesn't make sense for a Range to not have both a starting point and an ending point, so if you give it <code>start=None</code>, it will just use its default value which is <code>0</co...
0
2016-07-29T02:17:01Z
[ "python", "visualization", "bokeh" ]
Bokeh Range Set Only 1 Bound
38,648,896
<p>I would expect the following code to set only the upper bound of the plot y range, however the lower bound is also inexplicably set to 0:</p> <pre><code>import bokeh.plotting as bkp import numpy as np bkp.output_file("/tmp/test_plot.html") fig = bkp.figure(y_range=[None, 100]) # plot y range: 0-100 # fig = bkp.fig...
0
2016-07-29T00:51:04Z
38,650,362
<p>You are replacing the auto-ranging default <code>DataRange1d</code> with a "dumb" (non-auto ranging) <code>Range1d</code>. Set the <code>end</code> value of the default range that the plot creates, without replacing the entire range. Or alternatively, replace with a new <code>DataRange1d</code>. </p>
1
2016-07-29T04:08:23Z
[ "python", "visualization", "bokeh" ]
All rows within a given column must match, for all columns
38,648,940
<p>I have a Pandas DataFrame of data in which all rows within a given column must match:</p> <pre><code>df = pd.DataFrame({'A': [1,1,1,1,1,1,1,1,1,1], 'B': [2,2,2,2,2,2,2,2,2,2], 'C': [3,3,3,3,3,3,3,3,3,3], 'D': [4,4,4,4,4,4,4,4,4,4], 'E': [5,...
3
2016-07-29T00:57:32Z
38,648,975
<p>You can use <code>apply</code> to loop through columns and check if all the elements in the column are the same:</p> <pre><code>df.apply(lambda col: (col != col[0]).any()) # A False # B False # C False # D False # E False # dtype: bool </code></pre>
2
2016-07-29T01:03:16Z
[ "python", "pandas" ]
All rows within a given column must match, for all columns
38,648,940
<p>I have a Pandas DataFrame of data in which all rows within a given column must match:</p> <pre><code>df = pd.DataFrame({'A': [1,1,1,1,1,1,1,1,1,1], 'B': [2,2,2,2,2,2,2,2,2,2], 'C': [3,3,3,3,3,3,3,3,3,3], 'D': [4,4,4,4,4,4,4,4,4,4], 'E': [5,...
3
2016-07-29T00:57:32Z
38,648,997
<p>Given your example dataframe:</p> <pre><code>df = pd.DataFrame({'A': [1,1,1,1,1,1,1,1,1,1], 'B': [2,2,2,2,2,2,2,2,2,2], 'C': [3,3,3,3,3,3,3,3,3,3], 'D': [4,4,4,4,4,4,4,4,4,4], 'E': [5,5,5,5,5,5,5,5,5,5]}) </code></pre> <p>You can use the f...
4
2016-07-29T01:06:27Z
[ "python", "pandas" ]
All rows within a given column must match, for all columns
38,648,940
<p>I have a Pandas DataFrame of data in which all rows within a given column must match:</p> <pre><code>df = pd.DataFrame({'A': [1,1,1,1,1,1,1,1,1,1], 'B': [2,2,2,2,2,2,2,2,2,2], 'C': [3,3,3,3,3,3,3,3,3,3], 'D': [4,4,4,4,4,4,4,4,4,4], 'E': [5,...
3
2016-07-29T00:57:32Z
38,649,007
<p>You can compare the entire DataFrame to the first row like this:</p> <pre><code>In [11]: df.eq(df.iloc[0], axis='columns') Out[11]: A B C D E 0 True True True True True 1 True True True True True 2 True True True True True 3 True True True True True 4 True True True Tr...
4
2016-07-29T01:07:06Z
[ "python", "pandas" ]
Tastypie detail_uri_name with forignkey's attribute
38,648,946
<p>I have a extended the <code>User</code> Django class with my own user class in django:</p> <pre><code>class MyUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='my_user') theme = models.IntegerField(default=0) tags = TaggableManager() </cod...
0
2016-07-29T00:58:22Z
38,650,463
<p>You cannot use other class attribute as a <code>detail_uri_name</code>.</p> <p>But, in theory:</p> <pre><code>class MyUserResource(ModelResource): class Meta: queryset = User.objects.all().select_related('user') allowed_methods = ['get'] detail_uri_name = 'user__username' def get_b...
2
2016-07-29T04:22:10Z
[ "python", "mysql", "django", "api", "tastypie" ]
Tkinter calculator fails to update label
38,649,048
<p>I tried making a simple integer sign calculator using tkinter. It has a class with two different functions. The second function is supposed to be initiated when the user presses the "Enter" button. When I run the code the window comes up just as it is supposed to. But when I type and hit "Enter" the second funct...
0
2016-07-29T01:13:48Z
38,649,216
<p>To set the value of a StringVar you need to use the <code>set</code> method. Right now all you did was re-assign the variable. You can also set a stringvar's (default) value by giving it a value when you first initialize it. e.g. - <code>var = tk.StringVar(value="some value")</code></p> <p>Edit: Didn't see that you...
1
2016-07-29T01:38:38Z
[ "python", "user-interface", "tkinter", "label", "calculator" ]
Tkinter calculator fails to update label
38,649,048
<p>I tried making a simple integer sign calculator using tkinter. It has a class with two different functions. The second function is supposed to be initiated when the user presses the "Enter" button. When I run the code the window comes up just as it is supposed to. But when I type and hit "Enter" the second funct...
0
2016-07-29T01:13:48Z
38,649,249
<p>The first problem: in your constructor you initialize a variable named self.statement to a StringVar and then initialize again to a Label. After that second initialization, you have no way of accessing the first object. You need to use two different names.</p> <p>The second problem: in your event handler, <code>c...
1
2016-07-29T01:44:02Z
[ "python", "user-interface", "tkinter", "label", "calculator" ]
How to get the type of a varible
38,649,081
<p>I created a function that took a list as a parameter and removed either a space or a number. Code below: </p> <pre><code>def cleaner(List, filter_out=' '): if filter_out == ' ': for i in List: if i == ' ': List.remove(' ') if filter_out == 'int': for i in List: ...
1
2016-07-29T01:18:35Z
38,649,138
<p>This would be a proper way to do it for medium sized lists</p> <pre><code> def cleaner(lst,filter_item = ' '): if filter_item == ' ': for i in list(lst): if i == ' ': lst.remove(' ') elif filter_item == 'int': for i in list(lst): ...
1
2016-07-29T01:26:33Z
[ "python", "list", "function", "types" ]
How to get the type of a varible
38,649,081
<p>I created a function that took a list as a parameter and removed either a space or a number. Code below: </p> <pre><code>def cleaner(List, filter_out=' '): if filter_out == ' ': for i in List: if i == ' ': List.remove(' ') if filter_out == 'int': for i in List: ...
1
2016-07-29T01:18:35Z
38,649,167
<p>Removing items from a list while iterating it results in bad consequences:</p> <pre><code>&gt;&gt;&gt; nums = [1, 2, 3, 4] &gt;&gt;&gt; for x in nums: ... print x ... nums.remove(x) ... 1 3 </code></pre> <p>You start at index 0. You print <code>nums[0]</code>, <code>1</code>. You then remove it. The ne...
4
2016-07-29T01:30:18Z
[ "python", "list", "function", "types" ]
import all future features
38,649,099
<p>Just curious, I tried <code>from __future__ import *</code>, but I received this error:</p> <pre class="lang-none prettyprint-override"><code> File "&lt;stdin&gt;", line 1 SyntaxError: future feature * is not defined </code></pre> <p>Well, that makes sense. A <code>__future__</code> import is a little special an...
3
2016-07-29T01:20:54Z
38,649,110
<p>You can't, and that's by design. This is because more <code>__future__</code> features might be added in the future, and those can break your code.</p> <p>Imagine that in 2.x, the only <code>__future__</code> feature was <code>division</code>. Then in 2.y, a new <code>__future__</code> feature, <code>print_function...
4
2016-07-29T01:22:48Z
[ "python", "import" ]
Importerror: cannot import name Split
38,649,129
<p>I am very new to python and need some help here. I think it comes from PATH,but I have no clue about fixing it. Please help.</p> <p><a href="http://i.stack.imgur.com/QDSqq.png" rel="nofollow">Once I type in import split and it keeps popping up</a></p> <blockquote> <p>runfile('/Users/zhihaowang/Desktop/untitled1...
-1
2016-07-29T01:25:06Z
39,029,544
<p>split is part of standard string method not from string module. Without importing also you could just apply split method. your_str.split()</p>
0
2016-08-19T00:47:50Z
[ "python", "importerror" ]
Django CORS X-FirePHP-Version
38,649,170
<p>I am getting the following error message when I try to access my endpoints.</p> <pre><code>Request header field X-FirePHP-Version is not allowed by Access-Control-Allow-Headers in preflight response. </code></pre> <p>This is how my settings.py file looks</p> <pre><code>INSTALLED_APPS = [ 'django.contrib.admin...
1
2016-07-29T01:30:42Z
38,649,283
<p>If you have additional headers that are going to be in your requests to a CORS enabled server, you should specify those in the <code>CORS_ALLOW_HEADERS</code> <a href="https://github.com/ottoyiu/django-cors-headers" rel="nofollow">django-cors</a> setting. This should solve it, but I would double check to make sure t...
1
2016-07-29T01:48:04Z
[ "python", "django", "cors", "django-cors-headers" ]
Decided the order of the groupby output?
38,649,415
<p>After the groupby, the output order of the group is pre-decided. In the following case, the order is A, AAA, B, BBB. </p> <p>Is there a way to customize this order? I want to order to be AAA,A,BBB,B. I might want it in other orders as well.</p> <pre><code>import pandas as pd import matplotlib as mpl import matplo...
0
2016-07-29T02:04:36Z
38,649,483
<p><code>sort=False</code> just means that it's not guaranteed to be sorted (it may be ordered). My recollection is that this is in the "seen order", but again that's no guaranteed.</p> <p>To sort the output of a groupby, just do the sort after (by the index):</p> <pre><code>In [11]: t.sort_index() Out[11]: Rating A ...
0
2016-07-29T02:11:26Z
[ "python", "pandas", "group-by" ]
Decided the order of the groupby output?
38,649,415
<p>After the groupby, the output order of the group is pre-decided. In the following case, the order is A, AAA, B, BBB. </p> <p>Is there a way to customize this order? I want to order to be AAA,A,BBB,B. I might want it in other orders as well.</p> <pre><code>import pandas as pd import matplotlib as mpl import matplo...
0
2016-07-29T02:04:36Z
38,649,484
<p>You can't change the order returned by groupby/mean (save what's possible with the <code>sort</code> parameter). However, it easy to change the order after the fact using <code>reindex</code>:</p> <pre><code>In [24]: data.groupby('Rating', sort=False)['Score'].mean().reindex(['AAA', 'A', 'BBB', 'B']) Out[24]: Rati...
2
2016-07-29T02:11:32Z
[ "python", "pandas", "group-by" ]
__init__ file doesn't work as expected in python
38,649,482
<p>I have some folders and <code>.py</code> files in the following structure:</p> <pre><code>parent/ __init__.py test.ipynb code/ __init__.py common.py subcode/ __init__.py get_data.py </code></pre> <p>In the <code>__init...
4
2016-07-29T02:11:23Z
38,649,808
<p>The problem is that you are importing another module named <code>code</code> that is installed on your system rather than your own module. You can verify this by checking the module file path in <code>code.__file__</code> after you <code>import code</code>.</p> <p>The first thing to do is change the name of your mo...
3
2016-07-29T02:52:51Z
[ "python", "init" ]
__init__ file doesn't work as expected in python
38,649,482
<p>I have some folders and <code>.py</code> files in the following structure:</p> <pre><code>parent/ __init__.py test.ipynb code/ __init__.py common.py subcode/ __init__.py get_data.py </code></pre> <p>In the <code>__init...
4
2016-07-29T02:11:23Z
38,649,865
<p>You're on Python 3. You need to perform relative imports explicitly:</p> <pre><code>from . import code </code></pre> <p>The <code>code</code> module you're currently getting is the standard library <a href="https://docs.python.org/3/library/code.html" rel="nofollow"><code>code</code></a> module.</p>
1
2016-07-29T02:59:50Z
[ "python", "init" ]
Python: determine if a string contains math?
38,649,496
<p>Given these strings:</p> <pre><code>"1 + 2" "apple,pear" </code></pre> <p>How can I use Python 3(.5) to determine that the first string contains a math problem and <strong>nothing else</strong> and that the second string does not?</p>
1
2016-07-29T02:12:48Z
38,649,579
<p>Simply use split(), then iterate through the list to check if all instance are either numerical values or operational values. Then use eval.</p> <pre><code>input = "1 + 2" for i in input.split(): if i in ['+','-','*','%','.'] or i.isdigit(): pass # do something else: pass # o...
0
2016-07-29T02:22:40Z
[ "python", "python-3.x", "math", "python-3.5" ]
Python: determine if a string contains math?
38,649,496
<p>Given these strings:</p> <pre><code>"1 + 2" "apple,pear" </code></pre> <p>How can I use Python 3(.5) to determine that the first string contains a math problem and <strong>nothing else</strong> and that the second string does not?</p>
1
2016-07-29T02:12:48Z
38,649,713
<p>Here is a way to do it:</p> <pre><code>import ast UNARY_OPS = (ast.UAdd, ast.USub) BINARY_OPS = (ast.Add, ast.Sub, ast.Mult, ast.Div, ast.Mod) def is_arithmetic(s): def _is_arithmetic(node): if isinstance(node, ast.Num): return True elif isinstance(node, ast.Expression): ...
7
2016-07-29T02:38:38Z
[ "python", "python-3.x", "math", "python-3.5" ]
Python: determine if a string contains math?
38,649,496
<p>Given these strings:</p> <pre><code>"1 + 2" "apple,pear" </code></pre> <p>How can I use Python 3(.5) to determine that the first string contains a math problem and <strong>nothing else</strong> and that the second string does not?</p>
1
2016-07-29T02:12:48Z
38,649,905
<p>You can use a parsing library such as <a href="https://fdik.org/pyPEG/" rel="nofollow">pyPEG</a>, although there is room for improvment do more than this you could define a grammar like this:</p> <pre><code>from pypeg2 import optional, List, Namespace import re number = re.compile(r'\d+') binop = re.compile(r'\+|\...
0
2016-07-29T03:05:15Z
[ "python", "python-3.x", "math", "python-3.5" ]
Labeling boxplot in seaborn with median value
38,649,501
<p>How can I label each boxplot in a seaborn plot with the median value?</p> <p>E.g.</p> <pre><code>import seaborn as sns sns.set_style("whitegrid") tips = sns.load_dataset("tips") ax = sns.boxplot(x="day", y="total_bill", data=tips) </code></pre> <p>How do I label each boxplot with the median or average value?</p>
3
2016-07-29T02:13:10Z
38,649,932
<p>Can I just say that I love it when people include sample datasets. A healthy +1 to you!</p> <pre><code>import seaborn as sns, numpy as np sns.set_style("whitegrid") tips = sns.load_dataset("tips") ax = sns.boxplot(x="day", y="total_bill", data=tips) medians = tips.groupby(['day'])['total_bill'].median().values me...
2
2016-07-29T03:09:31Z
[ "python", "matplotlib", "seaborn" ]
acess class attribute in another file
38,649,575
<p>I'm new to python.</p> <p>I have a question about accessing attribute in class</p> <p>t1.py</p> <pre><code>#!/usr/bin/python import t2 class A: flag = False if __name__ == "__main__": t2.f() print(A.flag) </code></pre> <p>t2.py</p> <pre><code>#!/usr/bin/python import t1 def f(): ...
1
2016-07-29T02:21:38Z
38,649,902
<p>Yeah, I can see how this can be a little confusing but it is basically a question of namespaces along with the distinction that the <code>__main__</code> namespace is not considered as part of the list of imported modules. This allows the file that is the point of execution (and thus occupying the <code>__main__</co...
-1
2016-07-29T03:04:55Z
[ "python" ]
acess class attribute in another file
38,649,575
<p>I'm new to python.</p> <p>I have a question about accessing attribute in class</p> <p>t1.py</p> <pre><code>#!/usr/bin/python import t2 class A: flag = False if __name__ == "__main__": t2.f() print(A.flag) </code></pre> <p>t2.py</p> <pre><code>#!/usr/bin/python import t1 def f(): ...
1
2016-07-29T02:21:38Z
38,649,937
<p>They are indeed two different objects (explained very well in <a href="http://stackoverflow.com/a/38649968/5827958">user2357112's answer</a>). If you want <code>t2</code> to use the same object, you need to tell Python that you are actually importing the same module that is importing <code>t2</code>. To do that, i...
0
2016-07-29T03:10:05Z
[ "python" ]
acess class attribute in another file
38,649,575
<p>I'm new to python.</p> <p>I have a question about accessing attribute in class</p> <p>t1.py</p> <pre><code>#!/usr/bin/python import t2 class A: flag = False if __name__ == "__main__": t2.f() print(A.flag) </code></pre> <p>t2.py</p> <pre><code>#!/usr/bin/python import t1 def f(): ...
1
2016-07-29T02:21:38Z
38,649,968
<p>When you do</p> <pre><code>./t1.py </code></pre> <p>you're executing the <code>t1.py</code> file, but it's not executed as the <code>t1</code> module. It's considered to be the <code>__main__</code> module. (This is what that <code>if __name__ == '__main__'</code> line checks for.) That means that when this line:<...
2
2016-07-29T03:14:02Z
[ "python" ]
acess class attribute in another file
38,649,575
<p>I'm new to python.</p> <p>I have a question about accessing attribute in class</p> <p>t1.py</p> <pre><code>#!/usr/bin/python import t2 class A: flag = False if __name__ == "__main__": t2.f() print(A.flag) </code></pre> <p>t2.py</p> <pre><code>#!/usr/bin/python import t1 def f(): ...
1
2016-07-29T02:21:38Z
38,650,415
<p>You can find this out yourself:</p> <h1>t1.py</h1> <pre><code>#!/usr/bin/python import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) logger.debug('t1 has started') logger.debug('t2 is being imported') import t2 logger.debug('A is being "compiled"') class A: flag = False...
0
2016-07-29T04:15:35Z
[ "python" ]
Keep one method constantly running and another method executing every certain period
38,649,612
<p>So currently I am these two method where one reads the RF Data from another device constantly and another method sends that data every so often.</p> <p>How could I do this? I need the RF Data incoming to be constantly updated and received while the sendData() method just grabs the data from the global variable when...
0
2016-07-29T02:27:02Z
38,651,243
<p>I can't give you a full solution but I can guide you into the right direction.</p> <p>Your code has three problems.</p> <ol> <li><p><code>Process</code> starts (as the name suggests) a new process and not a new thread. A new process cannot share data with the old process. You should use mutlithreading instead. Hav...
1
2016-07-29T05:41:25Z
[ "python", "multithreading", "multiprocessing", "raspberry-pi2" ]
facet_grid not working in ggplot for python?
38,649,657
<p>I want to create plots based upon summary statistics rather than letting ggplot aggregate for me. After trying and failing with geom_violin() I finally settled on calculating percentiles and creating barplots. Even so I can't seem to produce them. </p> <p>In R this works:</p> <pre><code>library(dplyr) library(ggpl...
1
2016-07-29T02:31:46Z
38,710,623
<p>It looks like it's fixed now in 0.11.1.</p> <p><a href="https://github.com/yhat/ggplot/issues/515" rel="nofollow">https://github.com/yhat/ggplot/issues/515</a></p>
0
2016-08-02T01:48:52Z
[ "python", "ggplot2", "python-ggplot" ]
Can the Kivy language access inherited layouts and widgets?
38,649,664
<p>Can the kivy language access inherited layouts and widgets? I want to create one basic BoxLayout that contains the styling and title Label for my widget. I want to be able to inherit from this widget and add additional widgets in different positions.</p> <pre><code>from kivy.app import App from kivy.lang import Bui...
7
2016-07-29T02:32:28Z
39,183,012
<p>With simple kv no, because if you put something in the widget (e.g. <code>Label: ...</code>), it'll call <code>&lt;widget&gt;.add_widget()</code> method and when such a method is called without <a href="https://kivy.org/docs/api-kivy.uix.widget.html#kivy.uix.widget.Widget.add_widget" rel="nofollow">additional</a> pa...
1
2016-08-27T15:56:11Z
[ "python", "kivy", "kivy-language" ]
Can the Kivy language access inherited layouts and widgets?
38,649,664
<p>Can the kivy language access inherited layouts and widgets? I want to create one basic BoxLayout that contains the styling and title Label for my widget. I want to be able to inherit from this widget and add additional widgets in different positions.</p> <pre><code>from kivy.app import App from kivy.lang import Bui...
7
2016-07-29T02:32:28Z
39,196,128
<p>Here's a fun thing: you don't need to specify all classes used in kv lang in the lang itself - you can also add them using <code>Factory.register</code> method later in code. Here's an example:</p> <pre><code>from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label from kiv...
1
2016-08-28T21:52:16Z
[ "python", "kivy", "kivy-language" ]
How would I create a new line in Python?
38,649,755
<p>I am using Python 2.7 and this is what I am working with </p> <pre><code>print( "Massa: ", line.count("massa")) # trying to create a new line between these two lines print( "Lorem: ",line.count("lorem")+1) </code></pre> <p>I tried this </p> <pre><code>print( "Massa: ", line.count("massa"))\n( "Lorem: ", line.c...
0
2016-07-29T02:45:34Z
38,649,811
<p>I think you can just use:</p> <pre><code>print "" </code></pre> <p>to print a newline</p>
0
2016-07-29T02:53:02Z
[ "python", "python-2.7", "newline" ]
How would I create a new line in Python?
38,649,755
<p>I am using Python 2.7 and this is what I am working with </p> <pre><code>print( "Massa: ", line.count("massa")) # trying to create a new line between these two lines print( "Lorem: ",line.count("lorem")+1) </code></pre> <p>I tried this </p> <pre><code>print( "Massa: ", line.count("massa"))\n( "Lorem: ", line.c...
0
2016-07-29T02:45:34Z
38,649,825
<p>If you mean that you want to print it with a single print statement, this will do it. </p> <pre><code>print "Massa: ", line.count("massa"), "\n", "Lorem: ", line.count("lorem")+1 </code></pre> <p>Since you are using Python 2.7 I removed the enclosing brackets, otherwise the strings are treated as elements of a tup...
1
2016-07-29T02:54:17Z
[ "python", "python-2.7", "newline" ]
How would I create a new line in Python?
38,649,755
<p>I am using Python 2.7 and this is what I am working with </p> <pre><code>print( "Massa: ", line.count("massa")) # trying to create a new line between these two lines print( "Lorem: ",line.count("lorem")+1) </code></pre> <p>I tried this </p> <pre><code>print( "Massa: ", line.count("massa"))\n( "Lorem: ", line.c...
0
2016-07-29T02:45:34Z
38,650,849
<p><code>\n</code> creates a line break. You can pass it as a single string and use <a href="https://docs.python.org/2.7/library/string.html#formatstrings" rel="nofollow"><code>format</code></a> to place your parameters.</p> <pre><code>print("Massa: {0}\nLorem: {1}".format(line.count("massa"), line.count("lorem")+1))...
0
2016-07-29T05:04:48Z
[ "python", "python-2.7", "newline" ]
NOT NULL constraint failed: stores_store.merchant_id
38,649,975
<p>I am using djano rest framework for designing an API for store listing, and creation. The concept of my app is a linkage between merchant and buyer. A merchant can have multiple store of various categories.I have a model of Merchant which contains about merchant information,product which contains a list of product o...
1
2016-07-29T03:15:14Z
38,675,642
<p>there is problem with StroreCreateSerializer. your are trying to create instance of Store without merchant thats why you are getting error. If you want to create store without merchant you need to make merchant foreign key Null true. I hope this help.</p> <p>Moreover you are using add() with foreign key. add() meth...
0
2016-07-30T15:36:22Z
[ "python", "django", "api", "python-3.x", "django-rest-framework" ]
How to Prevent Triplicates in Pandas DataFrame
38,649,993
<p>I have the following code:</p> <pre><code>stim_df = pd.concat([block1,block2,bloc3,block4], axis=0, ignore_index=True).sample(frac=1).reset_index(drop=True) stim_df.columns = ["Word","Condition"] #Check for triplicates: for j in xrange(len(stim_df)): if j == 0 or j == 1: pass else: if sti...
-1
2016-07-29T03:17:56Z
38,664,855
<p>Are you looking to generate a sequence with no repetitions, or just remove the a sequence like <code>2,2,2</code>?</p> <p>If you're looking for the latter, try using <code>diff</code> to remove repeating sequences.</p> <pre><code>df[~(df.Condition.diff() == 0)] Condition Word 0 1 neut 1 2 ...
0
2016-07-29T17:57:49Z
[ "python", "pandas", "random", "dataframe" ]
How to speed up wait wake-up from notify_all?
38,650,008
<p>Platform: Python 2.6 on CentOS 6</p> <p>I've got 2 threads using the same object. Thread 1 feeds the object data and when the correct data is found, it does a <code>threading.Condition.notify_all()</code>.</p> <p>Thread 2, via the object, calls <code>threading.Condition.wait()</code> on the same condition variable...
0
2016-07-29T03:19:55Z
38,650,021
<p>To speed the wake up from <code>notify_all</code>, hold the lock for less time after <code>wait</code> returns. It's the lock that's preventing the other thread from making progress.</p> <p>If this doesn't make the solution to your problem obvious, there's a very good chance that you are misusing conditions. If so,...
0
2016-07-29T03:21:44Z
[ "python", "multithreading", "multiprocessing" ]
the assertionerror when run py-faster-rcnn
38,650,014
<p>When I tried to run the py-faster-rcnn followed the README.md in Github: ./experiments/scripts/faster_rcnn_alt_opt.sh 0 VGG_CNN_M_1024 pascal_voc</p> <p>And it stuck in stage like this: AssertionError: Path does not exist: /home/jiaxin/py-faster-rcnn/data/VOCdevkit2007/VOC2007/ImageSets/Main/trainval.txt</p> <pr...
0
2016-07-29T03:20:49Z
38,927,839
<p>I just googled the solution for the second error. The credit comes from @faschinj <a href="https://github.com/rbgirshick/py-faster-rcnn/issues/132" rel="nofollow">https://github.com/rbgirshick/py-faster-rcnn/issues/132</a>. </p> <p>Make sure there are no spaces after the commas otherwise they are parsed as separate...
0
2016-08-12T23:46:02Z
[ "python", "github" ]
web crawler in python (multiple website )
38,650,034
<p>I used <code>requests</code> and <code>bs4</code>. In the circle, I found that it's only the last 'soup' is right when i get every 'soup'.the other 'soup' is different with HTML source. Please help me. Thanks.</p> <pre><code>for eachLine in files: addr = 'http://neuromorpho.org/neuron_info.jsp?neuron_name='+eac...
1
2016-07-29T03:23:07Z
38,650,130
<p>The request object has content parameter which has all content of the site and you can parse it using BS4</p> <pre><code>for eachLine in files: addr = 'http://neuromorpho.org/neuron_info.jsp?neuron_name='+eachLine r2 = requests.get(addr) content = r2.content soup2 = bs4.BeautifulSoup(content) pr...
0
2016-07-29T03:37:06Z
[ "python", "html", "web-crawler" ]
Google Trends "An error has been detected"
38,650,126
<p>I have the following code which I used a code sample from dominolab:</p> <pre><code>from pytrends.pyGTrends import pyGTrends import time from random import randint from IPython.display import display from pprint import pprint import urllib import sys import os google_username = "myusername" google_password = "mypa...
0
2016-07-29T03:36:38Z
38,650,265
<p>I think the problem is the date query, <code>date = "01/2014 65m"</code>, you're asking it for 65 months after January 2014 ... but that's in the future!</p> <p>Hence this is the correct format for date:</p> <pre><code>connector.request_report(keyword_string, geo="US", date="01/2014 5m") </code></pre>
2
2016-07-29T03:55:43Z
[ "python", "csv", "ipython", "jupyter", "google-trends" ]
Python how to implement code to GUI
38,650,139
<p>Im very new to making GUI in python and I have searched everywhere but cant find what im looking for. I simply want to have a program where the user inputs a radius and the program prints out the area of that radius in a label with the help of either a button click or enter. Thanks in advance :)</p> <pre><code>impo...
-1
2016-07-29T03:38:39Z
38,650,560
<p>I have modified your code little bit. Now code will display area on the label as you mentioned.Check the code.If I am wrong let me know.</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-html lang-html prettypr...
1
2016-07-29T04:33:38Z
[ "python", "python-2.7", "user-interface", "tkinter" ]
Call a child variable in a mother class python
38,650,235
<p>I'm trying to access the "Table_Name variable" of the Child class to make the "Load_Data" method do different stuff depending on the child who cast the parent Class.<br> Also, is there method to know the child who summoned the parent class? </p> <pre><code>class DataBaseClass(obj): .. def Load_Data(): ...
0
2016-07-29T03:52:04Z
38,650,426
<p>Just implement the <code>load_data</code> on child classes. Something like this:</p> <pre><code>class Child1(Base): ... def load_data(): # CHILD1's OWN LOGIC class Child2(Base): ... def load_data(): # CHILD2's OWN LOGIC </code></pre> <hr> <p>(Update as per your comment.)</p> <...
0
2016-07-29T04:17:27Z
[ "python", "class" ]
Call a child variable in a mother class python
38,650,235
<p>I'm trying to access the "Table_Name variable" of the Child class to make the "Load_Data" method do different stuff depending on the child who cast the parent Class.<br> Also, is there method to know the child who summoned the parent class? </p> <pre><code>class DataBaseClass(obj): .. def Load_Data(): ...
0
2016-07-29T03:52:04Z
38,650,446
<p>The correct way to achieve this functionality is <a href="http://stackoverflow.com/questions/3724110/practical-example-of-polymorphism">polymorphism</a></p> <p>You need to override the <code>Load_data</code> method in the child classes</p> <pre><code>class DataBaseClass(object): def Load_Data(self): ra...
1
2016-07-29T04:20:02Z
[ "python", "class" ]
Call a child variable in a mother class python
38,650,235
<p>I'm trying to access the "Table_Name variable" of the Child class to make the "Load_Data" method do different stuff depending on the child who cast the parent Class.<br> Also, is there method to know the child who summoned the parent class? </p> <pre><code>class DataBaseClass(obj): .. def Load_Data(): ...
0
2016-07-29T03:52:04Z
38,650,511
<p>I think what you are trying to do is something like this:</p> <pre><code>class BaseClass(object): @classmethod def load_data(cls): try: return some_external_load_function(cls.DATA_FILE_NAME) except AttributeError: raise NotImplementedError( 'It seems ...
1
2016-07-29T04:27:38Z
[ "python", "class" ]
How to Compare Values of two Dataframes in Pandas?
38,650,273
<p>I have two dataframes <code>df</code> and <code>df2</code> like this</p> <pre><code> id initials 0 100 J 1 200 S 2 300 Y name initials 0 John J 1 Smith S 2 Nathan N </code></pre> <p>I want to compare the values in the <code>initials</code> columns found in (<code>df</code> and <code>df2</c...
1
2016-07-29T03:56:12Z
38,650,318
<p>How about?:</p> <pre><code>df3 = df.merge(df2,on='initials', how='outer').drop(['initials'],axis=1).dropna(subset=['id']) &gt;&gt;&gt; df3 id name 0 100.0 John 1 200.0 Smith 2 300.0 NaN </code></pre> <p>So the 'initials' column is dropped and so is anything with <code>np.nan...
1
2016-07-29T04:01:46Z
[ "python", "pandas", "dictionary", "dataframe" ]
How to Compare Values of two Dataframes in Pandas?
38,650,273
<p>I have two dataframes <code>df</code> and <code>df2</code> like this</p> <pre><code> id initials 0 100 J 1 200 S 2 300 Y name initials 0 John J 1 Smith S 2 Nathan N </code></pre> <p>I want to compare the values in the <code>initials</code> columns found in (<code>df</code> and <code>df2</c...
1
2016-07-29T03:56:12Z
38,654,434
<pre><code>df1 id initials 0 100 J ...
1
2016-07-29T08:48:28Z
[ "python", "pandas", "dictionary", "dataframe" ]
Django: How to use FilePathField to get file size
38,650,340
<p>I work in a postproduction company, we have our media files on a server. Through the site running on a second server, the user would point to a file, perform some operations (calculating checksums for example) and save the results in the database.</p> <p>I'm looking for a "best practices" example on how to use Fil...
1
2016-07-29T04:04:12Z
38,650,487
<p>In your FilePathField give the correct path name </p> <pre><code>FilePathField(path="/home/simon/",..) </code></pre> <p><code>cleaned_data</code> of <code>FilePathField</code> will give you the exact path so using that to get the file name and file size of it... </p> <pre><code>form = AssetTestForm(request.POST) ...
1
2016-07-29T04:25:10Z
[ "python", "django" ]
How to rename a bunch of files using python?
38,650,533
<p>I am a complete beginner in python. I need to rename a bunch of files with dates in the name. The names all look like:</p> <ul> <li><code>front 7.25.16</code></li> <li><code>left 7.25.16</code></li> <li><code>right 7.25.16</code></li> </ul> <p>I would like them to start with the date rather then <em>front</em>, <e...
2
2016-07-29T04:30:01Z
38,650,794
<p>Check this example to rename file as per your need.</p> <pre><code>import os filenames = ["front 7.25.16.jpg", "left 7.25.16.jpg", "right 7.25.16.jpg"] for file_name in filenames: x = file_name.split(' ')[0] y = file_name.split(' ')[1] new_name = '{} {}{}'.format(os.path.splitext(y)[0], x, os.path.spl...
1
2016-07-29T04:59:28Z
[ "python" ]
Media List in Python VLC
38,650,544
<p>I need to write a program in Python that will play video files from a folder in the VLC player, using the Linux OS. These files must be in the playlist. Code:</p> <pre><code>import vlc mrl1 = '....1.3gp' mrl2 = '....2.3gp' Instance = vlc.Instance('--input-repeat=-1', '--fullscreen', '--mouse-hide-timeout=0') Med...
0
2016-07-29T04:31:13Z
38,651,007
<p>Use while/for loop which will iterate through media list one by one. May be in this case pointer is pointing to only first video.</p> <p>Edit 1:</p> <p>[Use of For Loop] (<a href="http://stackoverflow.com/questions/28440708/python-vlc-binding-playing-a-playlist">Python VLC binding- playing a playlist</a>) Refer an...
0
2016-07-29T05:21:04Z
[ "python", "vlc", "libvlc" ]
Media List in Python VLC
38,650,544
<p>I need to write a program in Python that will play video files from a folder in the VLC player, using the Linux OS. These files must be in the playlist. Code:</p> <pre><code>import vlc mrl1 = '....1.3gp' mrl2 = '....2.3gp' Instance = vlc.Instance('--input-repeat=-1', '--fullscreen', '--mouse-hide-timeout=0') Med...
0
2016-07-29T04:31:13Z
38,654,205
<p>You should to put it into a loop, which waits for each song to finish playing. For example, try this code</p> <pre><code>import vlc import time mrl1 = '....1.3gp' mrl2 = '....2.3gp' song_list=[mrl1,mrl2] Instance = vlc.Instance('--input-repeat=-1', '--fullscreen', '--mouse-hide-timeout=0') for song in song_list: ...
0
2016-07-29T08:36:01Z
[ "python", "vlc", "libvlc" ]
Can't get y-axis on Matplotlib histogram to display probabilities
38,650,550
<p>I have data (pd Series) that looks like (daily stock returns, n = 555):</p> <pre><code>S = perf_manual.returns S = S[~((S-S.mean()).abs()&gt;3*S.std())] 2014-03-31 20:00:00 0.000000 2014-04-01 20:00:00 0.000000 2014-04-03 20:00:00 -0.001950 2014-04-04 20:00:00 -0.000538 2014-04-07 20:00:00 0.000764 20...
1
2016-07-29T04:31:41Z
38,657,671
<p>There is no easy way (that I know of) to do that using <code>plt.hist</code>. But you can simply bin the data using <code>np.histogram</code> and then normalize the data any way you want. If I understood you correctly, you want the data to display the probability to find a point in a given bin, NOT the probability d...
1
2016-07-29T11:26:51Z
[ "python", "matplotlib", "histogram", "probability-density" ]
lambda,map on object arrays in python - Return List of objects
38,650,558
<p>How to return a list of objects and not list here. I want to return a list of test objects and not a list of str..</p> <pre><code>class test: val = "" def __init__(self,v): self.val = v def tolower(self,k): k = k.val.lower() return k def test_run(): tests_lst = [] tests...
0
2016-07-29T04:33:20Z
38,651,037
<p>The question is unclear. I'll answer by what I understand.</p> <p>What I understand is that you are trying to create a new list of test objects, with the values as lower case.</p> <p>You can do this either by changing the state of each of the objects in a for loop (changing state is usually not recommended):</p> ...
0
2016-07-29T05:23:24Z
[ "python", "python-2.7" ]
passing the output of one .py script to another in GDB
38,650,566
<p>How to pass the output of one .py script which I executed in GDB using below command:</p> <pre><code>(gdb)source myfilename.py </code></pre> <p>to another .py script myfilename2.py</p> <p>E.g: On running myfile myfilename.py in GDB I get the below results</p> <pre><code>(gdb)source myfilename.py (gdb)print $fun...
2
2016-07-29T04:34:11Z
38,708,157
<p>You cannot use contents of GDB variable $1 for your program input, since program launch is performed by shell, not by gdb. </p> <p>You can store your script output in file, launch gdb for your executable and use command</p> <pre><code>(gdb)run &lt;outputfile </code></pre> <p>Or use a named pipe, as suggested <a h...
0
2016-08-01T21:08:42Z
[ "python", "gdb" ]
passing the output of one .py script to another in GDB
38,650,566
<p>How to pass the output of one .py script which I executed in GDB using below command:</p> <pre><code>(gdb)source myfilename.py </code></pre> <p>to another .py script myfilename2.py</p> <p>E.g: On running myfile myfilename.py in GDB I get the below results</p> <pre><code>(gdb)source myfilename.py (gdb)print $fun...
2
2016-07-29T04:34:11Z
38,722,335
<p>I'm not sure if you can run other python programs output to another in gdb, but of course you can pass output of a command like this.</p> <pre><code> (gdb) run "`python -c 'print "\xff\xff\xff\xff"'`" </code></pre> <p>May be you can try passing the second .py file instead of the command for its output to be pass...
2
2016-08-02T13:49:05Z
[ "python", "gdb" ]
django rest framework add user and create data in db
38,650,611
<p>every one,I now using django rest framework(3.4) on my project(django 1.8+),I can create new user but I can not use new user to create data in db(I can do it in forms ok), however,I can create data in db by admin. I have to make the new user to create data in db,how can I do that?thanks for any one who reply. </p> ...
0
2016-07-29T04:39:28Z
38,652,489
<p>I changed the <code>settings.py</code> then it can work</p> <blockquote> <p>settings.py</p> </blockquote> <pre><code>...... REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', #'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ] } </co...
1
2016-07-29T07:04:22Z
[ "python", "django", "django-rest-framework" ]
django rest framework add user and create data in db
38,650,611
<p>every one,I now using django rest framework(3.4) on my project(django 1.8+),I can create new user but I can not use new user to create data in db(I can do it in forms ok), however,I can create data in db by admin. I have to make the new user to create data in db,how can I do that?thanks for any one who reply. </p> ...
0
2016-07-29T04:39:28Z
38,656,076
<p>I think from admin portal you need to provide permissions to user you have created for each method PUT,POST,GET or provide AllowAny permission(Which will give access to all your created user for any request). For more details refer <a href="http://www.django-rest-framework.org/api-guide/permissions/" rel="nofollow">...
1
2016-07-29T10:06:46Z
[ "python", "django", "django-rest-framework" ]
sending dynamic html email containing javascript via a python script
38,650,665
<ol> <li>at the first place, I could not help myself with the correct search terms on this.</li> <li>secondly, I couldnt pretty much make it working with standard smtplib or email package in python.</li> </ol> <p>The question is, I have a normal html page(basically it contains a that is generated from bokeh package i...
0
2016-07-29T04:43:51Z
38,650,801
<p>Sorry, but you'll not be able to send an email with JavaScript embedded. That is a security risk. If you're lucky, an email provider will strip it before rendering, if you're unlucky, you'll be sent directly to spam and the provider will distrust your domain.</p> <p>You're better off sending an email with a link to...
1
2016-07-29T05:00:15Z
[ "javascript", "python", "email", "bokeh", "smtplib" ]
I want to append 4 text variables into a variable called job and print the text of job variable
38,650,679
<p>I am currently scraping Linkedin Job directory using selenium in python shell</p> <p>from selenium import webdriver</p> <p>from selenium.webdriver.common.keys import Keys</p> <p>driver = webdriver.Firefox()</p> <pre><code>driver.get('https://www.linkedin.com/jobs/search? locationId=sg%3A0&amp;f_TP=1%2C2&amp;orig...
1
2016-07-29T04:45:26Z
38,652,931
<pre><code>for e in range(55): for g in a: print(g.text) job.append(g) for h in b: print(h.text) job.append(h) for i in c: print(i.text) job.append(i) for j in d: print(j.text) job.append(j) </code></pre> <p>Maybe you should get job list like this.</p...
0
2016-07-29T07:27:47Z
[ "python", "selenium" ]
I want to append 4 text variables into a variable called job and print the text of job variable
38,650,679
<p>I am currently scraping Linkedin Job directory using selenium in python shell</p> <p>from selenium import webdriver</p> <p>from selenium.webdriver.common.keys import Keys</p> <p>driver = webdriver.Firefox()</p> <pre><code>driver.get('https://www.linkedin.com/jobs/search? locationId=sg%3A0&amp;f_TP=1%2C2&amp;orig...
1
2016-07-29T04:45:26Z
40,101,749
<p>i am not really understand your question. maybe u can get some ideas from enumerate(list)</p> <p>for example:</p> <pre><code>word_list=['go','have', 'fun', 'good'] name_list=['1.txt','2.txt','3.txt','4.txt'] for i, word in enumerate(word_list): print i ### it is the position of each element print word ### i...
0
2016-10-18T07:09:16Z
[ "python", "selenium" ]
Is it better to derive from Gtk.Widget or directly from a specific widget?
38,650,893
<p>When I create a UI class for my app, I often wonder if it's better to derive my class from <code>Gtk.Widget</code> and then add explicitly the widgets I need or to derive directly from a specific widget.</p> <p>Here is two examples, which one is the best?</p> <pre class="lang-py prettyprint-override"><code>class M...
1
2016-07-29T05:08:11Z
38,678,401
<p>I fail to see why you think the first is better. Just Subclass what you actually want. A Gtk.Box <em>is</em> a Gtk.Widget so wherever you can use the latter you can use the former.</p>
0
2016-07-30T20:53:43Z
[ "python", "gtk" ]
Is it better to derive from Gtk.Widget or directly from a specific widget?
38,650,893
<p>When I create a UI class for my app, I often wonder if it's better to derive my class from <code>Gtk.Widget</code> and then add explicitly the widgets I need or to derive directly from a specific widget.</p> <p>Here is two examples, which one is the best?</p> <pre class="lang-py prettyprint-override"><code>class M...
1
2016-07-29T05:08:11Z
38,818,000
<p>It depends on the abstraction in your mind. Ask yourself: is your component merely a customised <em>box</em> or something <em>more</em>?</p> <p>Moreover, do you <em>actually</em> need inheritance here? Perhaps you can just do away with a free factory-function that creates a group of Gtk.Widgets to your liking.</p>
1
2016-08-07T19:59:23Z
[ "python", "gtk" ]
How do I add multiple markers to a stripplot in seaborn?
38,650,895
<p>I would like to know how I could get multiple markers in the same strip plot.</p> <pre><code>tips = sns.load_dataset("tips") coldict={'Sun':'red','Thur':'blue','Sat':'yellow','Fri':'green'} markdict={'Sun':'x','Thur':'o','Sat':'o','Fri':'o'} tips['color']=tips.day.apply(lambda x: coldict[x]) tips['marker']=tips.d...
1
2016-07-29T05:08:20Z
38,651,415
<p>Caution it's a little hacky but here ya go:</p> <pre><code>import sns tips = sns.load_dataset("tips") plt.clf() thu_fri_sat = tips[(tips['day']=='Thur') | (tips['day']=='Fri') | (tips['day']=='Sat')] colors = ['blue','yellow','green','red'] m = sns.stripplot('size','total_bill',hue='day', marker...
1
2016-07-29T05:53:53Z
[ "python", "pandas", "matplotlib", "seaborn" ]
Decoding ISO-8859-1 and Encoding to UTF-8 before MySQL query
38,650,968
<p>I'm kinda stuck if I'm doing it right. </p> <p>I have a file which is ISO-8859-1 (pretty certain). My MySQL db is in utf-8 encoding. Which is why I want to convert the file to UTF-8 encoded characters before I can send it as a query. For instance, First I rewrite every line of the <strong>file.txt</strong> into <st...
0
2016-07-29T05:16:23Z
38,651,095
<p>Try this instead:</p> <pre><code>line = line.decode('ISO-8859-1').encode('utf-8-sig') </code></pre> <p>From the docs:</p> <blockquote> <p>As UTF-8 is an 8-bit encoding no BOM is required and any U+FEFF character in the decoded string (even if it’s the first character) is treated as a ZERO WIDTH NO-BREAK S...
1
2016-07-29T05:28:35Z
[ "php", "python", "mysql", "utf-8", "character-encoding" ]
Decoding ISO-8859-1 and Encoding to UTF-8 before MySQL query
38,650,968
<p>I'm kinda stuck if I'm doing it right. </p> <p>I have a file which is ISO-8859-1 (pretty certain). My MySQL db is in utf-8 encoding. Which is why I want to convert the file to UTF-8 encoded characters before I can send it as a query. For instance, First I rewrite every line of the <strong>file.txt</strong> into <st...
0
2016-07-29T05:16:23Z
38,651,661
<p>Welcome to the wonderful world of unicode and windows. I've found this site very helpful in understanding what is going wrong with my strings <a href="http://www.i18nqa.com/debug/utf8-debug.html" rel="nofollow">http://www.i18nqa.com/debug/utf8-debug.html</a>. The other thing you need is a hex editor like <a href="...
1
2016-07-29T06:11:48Z
[ "php", "python", "mysql", "utf-8", "character-encoding" ]
Decoding ISO-8859-1 and Encoding to UTF-8 before MySQL query
38,650,968
<p>I'm kinda stuck if I'm doing it right. </p> <p>I have a file which is ISO-8859-1 (pretty certain). My MySQL db is in utf-8 encoding. Which is why I want to convert the file to UTF-8 encoded characters before I can send it as a query. For instance, First I rewrite every line of the <strong>file.txt</strong> into <st...
0
2016-07-29T05:16:23Z
38,653,078
<p>Alright guys, so my encoding was right. The file was getting encoding to utf-8 just as needed. All the queries were right. It turns out that the other dataset that was in Arabic was in ISO-8859-1. Therefore, only 1 of them was working. No matter what I did.</p> <p>The Hexeditors did help. But in the end I just used...
0
2016-07-29T07:36:02Z
[ "php", "python", "mysql", "utf-8", "character-encoding" ]
Decoding ISO-8859-1 and Encoding to UTF-8 before MySQL query
38,650,968
<p>I'm kinda stuck if I'm doing it right. </p> <p>I have a file which is ISO-8859-1 (pretty certain). My MySQL db is in utf-8 encoding. Which is why I want to convert the file to UTF-8 encoded characters before I can send it as a query. For instance, First I rewrite every line of the <strong>file.txt</strong> into <st...
0
2016-07-29T05:16:23Z
38,665,348
<p>You should <em>not</em> need to do any explicit encode or decode. <code>SET NAMES ...</code> should match what the <em>client</em> encoding is (for <code>INSERTing</code>) or should become (for <code>SELECTing</code>).</p> <p>MySQL will convert between the client encoding and the columns's <code>CHARACTER SET</cod...
0
2016-07-29T18:28:42Z
[ "php", "python", "mysql", "utf-8", "character-encoding" ]
XPath not working as I'd expect it to
38,651,048
<p>Hopefully, you don't need the entire set of code here, but I have an issue where I'm parsing HTML, using XPath and I'm not getting what I'd expect:</p> <pre><code># here is the current set of tags I'm interested in html = '''&lt;div style="padding-top: 10px; clear: both; width: 100%;"&gt; &lt;a href="http:...
2
2016-07-29T05:24:45Z
38,660,682
<p>With the URL you provided, the following Python code:</p> <pre><code>url = "http://www.amazon.com/gp/cdp/member-reviews/ARPJ98Y7U8K5H?ie=UTF8&amp;display=public&amp;page=3&amp;sort_by=MostRecentReview" from lxml import etree parser = etree.HTMLParser(encoding="utf-8") tree = etree.parse(url, parser) for e in tree...
0
2016-07-29T13:55:26Z
[ "python", "python-2.7", "xpath", "python-requests", "lxml" ]