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
Converting list Dict's to DataFrame: Pandas
38,624,151
<p>I'm doing some web-scraping and I'm storing the variables of interest in form of:</p> <pre><code>a = {'b':[100, 200],'c':[300, 400]} </code></pre> <p>This is for one page, where there were two <code>b</code>'s and two <code>c</code>'s. The next page could have three of each, where I'd store them as:</p> <pre><cod...
2
2016-07-27T22:21:25Z
38,625,256
<p>Comprehensions FTW (maybe not the fastest, but can you get any more pythonic?):</p> <pre><code>import pandas as pd list_of_dicts = [{'b': [100, 200], 'c': [300, 400]}, {'b': [300, 400, 500], 'c': [500, 600, 700]}] def extract(key): return [item for x in list_of_dicts for item in x[key]] df =...
1
2016-07-28T00:26:22Z
[ "python", "pandas", "dictionary", "dataframe" ]
Kivy and Matplotlib trying to update plot on button callback
38,624,168
<p>I can generate a 2D surface plot very nicely with Kivy and Matplotlib. I am trying to update the Z values on a button click. How may this be accomplished?</p> <p>I noticed that I can issue a plt.clf() which will clear the plot but doing the plt.gcf() to display the current plot doesn't work.</p> <p>Any suggestions...
0
2016-07-27T22:23:20Z
38,630,095
<p>Line 45 of your code:</p> <pre><code>fig, ax = plt.subplots() </code></pre> <p>creates a new figure and hence a new canvas. This canvas is never added to the <code>BoxLayout</code> and hence never shown. It's probably a better idea to re-use the old canvas. Change the callback function to this:</p> <pre><code>def...
0
2016-07-28T07:45:08Z
[ "python", "matplotlib", "kivy" ]
Kivy and Matplotlib trying to update plot on button callback
38,624,168
<p>I can generate a 2D surface plot very nicely with Kivy and Matplotlib. I am trying to update the Z values on a button click. How may this be accomplished?</p> <p>I noticed that I can issue a plt.clf() which will clear the plot but doing the plt.gcf() to display the current plot doesn't work.</p> <p>Any suggestions...
0
2016-07-27T22:23:20Z
38,642,936
<p>Need to make the fig and ax variables global. Call plt.clf() to clear the current figure and re-plot with appropriate colorbar.</p> <pre><code>import matplotlib matplotlib.use('module://kivy.garden.matplotlib.backend_kivy') from matplotlib.figure import Figure from numpy import arange, sin, pi from kivy.app import ...
0
2016-07-28T17:22:11Z
[ "python", "matplotlib", "kivy" ]
variable that is set to True in if statement never becomes False
38,624,188
<p>I have a list of rectangles coordinates, that I'm iterating over to test for collisions with each one. The list is Like so: <code>self.rectangle_list = [(200, 30, 100, 10), (200, 60, 100, 10), (200, 90, 100, 10), (200, 120, 100, 10), (200, 150, 100, 10)]</code>. My code for the for loop is below.</p> <pre><code> ...
0
2016-07-27T22:25:23Z
38,624,229
<p>Your <code>if</code> statement has a problem:</p> <pre><code>if x &lt;= mouse_x &lt;= x + w and y &lt;= mouse_y &lt;= y + h: self.hovering = True </code></pre> <p>You can't chain less than/greater than as you do in: <code>x &lt;= mouse_x &lt;= x + w</code>. This really gets translated to:</p> <pre...
2
2016-07-27T22:28:58Z
[ "python", "list", "pygame", "iteration" ]
variable that is set to True in if statement never becomes False
38,624,188
<p>I have a list of rectangles coordinates, that I'm iterating over to test for collisions with each one. The list is Like so: <code>self.rectangle_list = [(200, 30, 100, 10), (200, 60, 100, 10), (200, 90, 100, 10), (200, 120, 100, 10), (200, 150, 100, 10)]</code>. My code for the for loop is below.</p> <pre><code> ...
0
2016-07-27T22:25:23Z
38,624,256
<p>You set <code>self.hovering</code> inside the loop for <em>every</em> rectangle in the list. This means, after the loop the value of <code>self.hovering</code> corresponds to the "hovering state" of only the <em>last</em> rectangle.</p> <p>I think you want to set <code>self.hovering = False</code> before the loop a...
4
2016-07-27T22:30:41Z
[ "python", "list", "pygame", "iteration" ]
variable that is set to True in if statement never becomes False
38,624,188
<p>I have a list of rectangles coordinates, that I'm iterating over to test for collisions with each one. The list is Like so: <code>self.rectangle_list = [(200, 30, 100, 10), (200, 60, 100, 10), (200, 90, 100, 10), (200, 120, 100, 10), (200, 150, 100, 10)]</code>. My code for the for loop is below.</p> <pre><code> ...
0
2016-07-27T22:25:23Z
38,624,284
<p>The code is iterating through the list and self.hovering changes after each step. Therefore, the last rectangle determines which value is printed since its the only one influencing it since the print function is called <strong>outside</strong> of the loop.</p> <p><strong>Update</strong>: <br> If you want it to be T...
1
2016-07-27T22:32:44Z
[ "python", "list", "pygame", "iteration" ]
Crop images using dimensions extracted from txt file
38,624,200
<p>I would like to crop multiple images in my folder using PIL or opencv2. But, I have the dimensions in a text file having the same filename as the image. So, let's say my filename is 1_a.jpg, the dimensions (top left.x,width;top left.x,height) are in the 1_a.txt file. So, my program must iterate through every file, ...
0
2016-07-27T22:26:54Z
38,630,346
<p>You would be best to just cycle through all of the PNG files, and for each one attempt to find a matching text file as follows:</p> <pre><code>import glob import os import re faces_folder_path = r"c:\myfiles" for png_file in glob.glob(os.path.join(faces_folder_path, "*.png")): name, ext = os.path.splitext(os....
0
2016-07-28T07:57:59Z
[ "python", "image", "opencv" ]
QFileDialog view folders and files but select folders only?
38,624,245
<p>I'm creating my own custom file dialog using the following code:</p> <pre><code>file_dialog = QtGui.QFileDialog() file_dialog.setFileMode(QtGui.QFileDialog.Directory) file_dialog.setViewMode(QtGui.QFileDialog.Detail) file_dialog.setOption(QtGui.QFileDialog.DontUseNativeDialog, True) </code></pre> <p>The behaviour ...
1
2016-07-27T22:29:44Z
38,643,574
<p>To prevent files being selected, you can install a proxy model which manipulates the flags for items in the file-view:</p> <pre><code>class ProxyModel(QtGui.QIdentityProxyModel): def flags(self, index): flags = super(ProxyModel, self).flags(index) if not self.sourceModel().isDir(index): ...
2
2016-07-28T17:57:02Z
[ "python", "qt", "pyqt", "qfiledialog" ]
What is the difference between metrics.auc and scipy.integrate.quad?
38,624,290
<p>I am getting different values when I calculate the Area Under the Curve when use sklearn.metrics.auc and when I use scipy.integrate.quad. </p> <p>To calculate the AUC, I passing in my data:</p> <pre><code>auc_path = metrics.auc(path,year) auc_sbt = metrics.auc(sbt,year) auc_path = 14929608030 auc_sbt = 1484609864...
0
2016-07-27T22:33:18Z
38,625,120
<p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.auc.html" rel="nofollow"><code>sklearn.metrics.auc</code></a> just estimates the integral for your given pair of <code>x</code> and <code>y</code> vectors using the <a href="https://en.wikipedia.org/wiki/Trapezoidal_rule" rel="nofollow">trapez...
0
2016-07-28T00:06:39Z
[ "python", "excel", "numpy", "scipy", "scikit-learn" ]
What is the difference between metrics.auc and scipy.integrate.quad?
38,624,290
<p>I am getting different values when I calculate the Area Under the Curve when use sklearn.metrics.auc and when I use scipy.integrate.quad. </p> <p>To calculate the AUC, I passing in my data:</p> <pre><code>auc_path = metrics.auc(path,year) auc_sbt = metrics.auc(sbt,year) auc_path = 14929608030 auc_sbt = 1484609864...
0
2016-07-27T22:33:18Z
38,647,387
<p>Based on your description of your data, I get the following plots. For the path data (curr_path and then req_path), I use this function: </p> <pre><code>start = 8549826 def path(year): if year &gt; 23: return start*(cur_path_exp)**23 * req_path_exp**(year-23) else: return start * (cur_path_exp)**year </code...
0
2016-07-28T21:55:54Z
[ "python", "excel", "numpy", "scipy", "scikit-learn" ]
wrap a variable number of instances in a string with parenthesis in python
38,624,332
<p>I have a string that contains variable names separated by 'and's/'or's such as 'x[1] and x[2] or x[3]'. The number of variable names varies as does whether it's an 'and' or 'or' that comes in between them. I want to wrap parenthesis around each stretch of variables separated by 'or's. For example, if the string is '...
0
2016-07-27T22:36:54Z
38,624,461
<p>This might do what you want:</p> <pre><code>import re s = 'x[1] and x[2] or x[3] and x[4] or x[5] or x[6] and x[7]' s = re.sub(r'(\S+(?:\s*or\s*\S+)+)', r'(\1)', s) assert s == 'x[1] and (x[2] or x[3]) and (x[4] or x[5] or x[6]) and x[7]' </code></pre> <hr /> <p>EDIT: A slightly more robust expression and more t...
1
2016-07-27T22:50:31Z
[ "python", "regex", "search", "find", "substitution" ]
wrap a variable number of instances in a string with parenthesis in python
38,624,332
<p>I have a string that contains variable names separated by 'and's/'or's such as 'x[1] and x[2] or x[3]'. The number of variable names varies as does whether it's an 'and' or 'or' that comes in between them. I want to wrap parenthesis around each stretch of variables separated by 'or's. For example, if the string is '...
0
2016-07-27T22:36:54Z
38,624,562
<p>As you already have an answer with a regex method, here is a method that doesn't require a regex:</p> <pre><code>&gt;&gt;&gt; s = 'x[1] and x[2] or x[3] and x[4] or x[5] or x[6] and x[7]' &gt;&gt;&gt; ' and '.join(['(%s)' % w if ' or ' in w else w for w in s.split(' and ')]) 'x[1] and (x[2] or x[3]) and (x[4] or x[...
0
2016-07-27T23:03:00Z
[ "python", "regex", "search", "find", "substitution" ]
Tastypie access resource by parameter other than PK
38,624,446
<p>I am having a hard time figuring out how to ask this question. </p> <p>I have a model <code>User</code>. Currently when I want to access a specific user I go to the url: <code>/api/v1/user/8/</code>. Although, all users have unique usernames, so I would like to go to a specific user by using the url: <code>/api/v1/...
0
2016-07-27T22:49:34Z
38,624,576
<p>You need to use <code>detail_uri_name</code> in your <code>ModelResource</code>'s <code>Meta</code> class (<a href="http://django-tastypie.readthedocs.io/en/latest/resources.html#detail-uri-name" rel="nofollow">documentation</a>) - example resources.py:</p> <pre><code>from django.contrib.auth.models import User fro...
3
2016-07-27T23:04:17Z
[ "python", "django", "api", "tastypie" ]
websockets proxied by nginx to gunicorn over https giving 400 (bad request)
38,624,447
<p>I am having trouble establishing a websocket in my Flask web application.</p> <p>On the client side, I am emitting a "ping" websocket event every second to the server. In the browser console, I see the following error each second</p> <pre><code>POST https://example.com/socket.io/?EIO=3&amp;transport=polling&amp;t=...
1
2016-07-27T22:49:42Z
38,648,638
<p>The problem is that you are running multiple workers on gunicorn. This is not a configuration that is currently supported, due to the very limited load balancer in gunicorn that does not support sticky sessions. Documentation reference: <a href="https://flask-socketio.readthedocs.io/en/latest/#gunicorn-web-server" r...
1
2016-07-29T00:14:27Z
[ "python", "nginx", "websocket", "socket.io", "gunicorn" ]
Python: __add__ and +, different behavior with float and integer
38,624,450
<p>When adding an integer value to a float value, I realized that <code>__add__</code> method is working fine if called on float, such as this:</p> <pre><code>&gt;&gt;&gt; n = 2.0 &gt;&gt;&gt; m = 1 &gt;&gt;&gt; n.__add__(m) 3.0 </code></pre> <p>but not if called on an integer:</p> <pre><code>&gt;&gt;&gt; m.__add__(...
4
2016-07-27T22:49:44Z
38,624,533
<p><code>a + b</code> does not directly translate to <code>a.__add__(b)</code>. It also tries <code>b.__radd__(a)</code> if <code>a.__add__</code> doesn't exist or returns <code>NotImplemented</code>, or if <code>b</code> is an instance of a subtype of <code>a</code>'s type.</p>
6
2016-07-27T22:58:35Z
[ "python", "floating-point", "integer", "add" ]
Python use commands when running script
38,624,456
<p>I'm writing a script in python and I need to do something like this:</p> <p><code>python myscript.py command1 --commandarg1 --commandarg2</code></p> <p><code>python myscript.py --scriptargument1 --scriptargument2 command2 --commandarg1 --commandarg2 --commandarg3</code></p> <p>Is this possible using <code>argpars...
-1
2016-07-27T22:49:55Z
38,630,028
<p>Yes the argparse module is exactly that what you are looking for. </p> <p>visit this page to get the informations how to work with it:</p> <p><a href="https://docs.python.org/3/library/argparse.html" rel="nofollow">https://docs.python.org/3/library/argparse.html</a></p>
1
2016-07-28T07:42:18Z
[ "python" ]
Out of memory with Python but OK with Matlab while displaying the same 2D data as image
38,624,495
<p>I have a 2D array to display as image (it is 500 by 20 000). </p> <p>Python:</p> <pre><code>import numpy as np from matplotlib import pyplot as plt spect_data = np.loadtxt('some_data.txt') plt.figure(figsize=(12,9)) plt.imshow(spect_data,aspect='auto') plt.colorbar() plt.show() </code></pre> <p>Matlab:</p>...
-1
2016-07-27T22:54:36Z
38,624,619
<p>I'm not sure this will solve your problem, but you seem to have the data in memory several times - as a numpy array, as a list of floats, and as a list of strings.</p> <p>If you only need the numpy array, you could use </p> <pre><code>np.loadtxt </code></pre> <p>or </p> <pre><code>np.fromfile </code></pre> <p>i...
2
2016-07-27T23:09:06Z
[ "python", "matlab", "matplotlib" ]
Taking identical 1st element of a list and assigning it as 1st element of the list in python
38,624,557
<p>I am trying to Taking identical 1st element of a list and assigning it as 1st element of the list. I was told it can be done by using defaultdict from collections module but is there a way i can do this without using the Collections library.</p> <p>What i have:</p> <pre><code>mapping = [['Tom', 'BTPS 1.500 625', ...
0
2016-07-27T23:01:16Z
38,624,593
<p>You should use a <em>dict</em>/<a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow">defaultdict</a> to group the data by name, using the first element which is the key as the name, slicing the rest of the data and appending that as a value:</p> <pre><code>from collecti...
1
2016-07-27T23:06:36Z
[ "python" ]
Taking identical 1st element of a list and assigning it as 1st element of the list in python
38,624,557
<p>I am trying to Taking identical 1st element of a list and assigning it as 1st element of the list. I was told it can be done by using defaultdict from collections module but is there a way i can do this without using the Collections library.</p> <p>What i have:</p> <pre><code>mapping = [['Tom', 'BTPS 1.500 625', ...
0
2016-07-27T23:01:16Z
38,624,622
<p>You can loop over the names in mapping and add to dictionary. </p> <pre><code>mapping = [['Tom', 'BTPS 1.500 625', 0.702604], ['Tom', 'BTPS 2.000 1225', 0.724939], ['Max', 'OBL 0.0 421', 0.766102], ['Max', 'DBR 3.250 721', 0.887863]] #using dictionary to store output mapping_dict=dict() for items in mapping: if i...
0
2016-07-27T23:09:11Z
[ "python" ]
Unable to parse function declaration with Python like syntax
38,624,749
<p>I am using <a href="https://fdik.org/pyPEG/index.html" rel="nofollow">pyPEG</a> to parse the declaration of a function. Currently I have this written:</p> <pre><code>from pypeg2 import attr, \ optional, \ csl, \ name, \ List, \ ...
0
2016-07-27T23:23:29Z
39,922,979
<p>Because <code>name()</code> essential attach a matched <code>Symbol</code> to the <code>name</code> attr of the class. In your case the attachment of <code>b</code> overwrites <code>a</code>.</p> <p>The official doc lists the following:</p> <pre><code>class Parameter(object): grammar = attr("typing", Type), na...
0
2016-10-07T17:35:55Z
[ "python", "pypeg" ]
Convert txt files in a folder to rows in csv file
38,624,751
<p>I have 100 txt files in a folder. I would like to create a csv file in which the content of each text file becomes a single row (actually, a single cell in a row) in this csv file. So, the result would be a csv file with 100 rows. </p> <p>I tried the following code:</p> <pre><code>import glob read_files = glob.gl...
0
2016-07-27T23:23:38Z
38,624,876
<p>Try:</p> <pre><code>import glob import csv read_files = glob.glob('neg/*') with open("neg.csv", "wb") as outfile: w=csv.writer(outfile) for f in read_files: with open(f, "rb") as infile: w.writerow([line for line in infile]) </code></pre> <p>That makes each line a cell in the output a...
2
2016-07-27T23:37:56Z
[ "python", "python-2.7" ]
Convert txt files in a folder to rows in csv file
38,624,751
<p>I have 100 txt files in a folder. I would like to create a csv file in which the content of each text file becomes a single row (actually, a single cell in a row) in this csv file. So, the result would be a csv file with 100 rows. </p> <p>I tried the following code:</p> <pre><code>import glob read_files = glob.gl...
0
2016-07-27T23:23:38Z
38,624,881
<p>Before writing each <code>line</code>, first do <code>line.replace('\n',' ')</code> to replace all new line characters with spaces. </p> <p>Obviously, adjust your newline character according to your OS.</p>
0
2016-07-27T23:38:12Z
[ "python", "python-2.7" ]
how to use variable from .yml file to .py file
38,624,773
<p>I have below two files one is .py file and other is .yml file as shown in image. In .py file I am using all variable that define in .yml file. Now I am looking for a solution about How I can pass this .yml file or how I can call or use the variables from .yml file to .py file. I have also marked my question in image...
0
2016-07-27T23:27:03Z
38,625,701
<p>Because of the structure of the YAML document, <code>yaml.load()</code> returns a list of dictionaries:</p> <pre><code>with open('test.yml') as f: var = yaml.load(f) &gt;&gt;&gt; var [{'Username': ['xyz']}, {'Userpassword': ['ubuntu']}, {'Hostname': ['10.0.0.3']}] </code></pre> <p>This is not the most usable ...
1
2016-07-28T01:27:08Z
[ "python", "yaml" ]
how to use variable from .yml file to .py file
38,624,773
<p>I have below two files one is .py file and other is .yml file as shown in image. In .py file I am using all variable that define in .yml file. Now I am looking for a solution about How I can pass this .yml file or how I can call or use the variables from .yml file to .py file. I have also marked my question in image...
0
2016-07-27T23:27:03Z
38,667,100
<h2>what if my .yum file has multiple values in list such as</h2> <pre><code>Username: - asdf - xyz Userpassword: - ubuntu - linux Hostname: - 10.0.0.3 - 10.0.0.4 </code></pre> <p>Then how the code work? because here I am using only single dictionary having multiple values in list.</p>
0
2016-07-29T20:37:08Z
[ "python", "yaml" ]
Nested `ImportError` on Py3 but not on Py2
38,624,810
<p>I'm having trouble understanding how nested imports work in a python project. For example:</p> <pre><code>test.py package/ __init__.py package.py subpackage/ __init__.py </code></pre> <p><code>test.py</code>:</p> <pre><code>import package </code></pre> <p><code>package/__init__.py</code>:</p>...
0
2016-07-27T23:32:10Z
38,624,831
<p>You should use:</p> <pre><code>from . import subpackage </code></pre> <p>in <code>package/package.py</code>.</p>
2
2016-07-27T23:34:38Z
[ "python", "python-2.7", "python-3.x", "import", "packages" ]
Using argparse to overwrite variables depending on flags, use the default values if no args given (python)
38,624,818
<p>I have a program that stores a few important variables as strings that are necessary for the program to operate properly: <code>DeviceNumber</code>, <code>IPAddress</code>, and <code>Port</code>. These variables are stored in a file, which is loaded by the program.</p> <p>For debugging purposes, I would like to be...
0
2016-07-27T23:32:47Z
38,625,043
<p>There's a few ways to define default values for arguments specified by <a href="https://docs.python.org/3/library/argparse.html" rel="nofollow"><code>argparse</code></a>. When adding arguments to your parser, you can specify a default value. Simply:</p> <pre class="lang-py prettyprint-override"><code>import argpars...
2
2016-07-27T23:57:28Z
[ "python", "argparse" ]
Numpy strange behavior - sanity check. How is this possible?
38,624,827
<p>I'm no Python expert by any stretch of the imagination, but this one has me stumped. Either that or I'm missing something completely obvious. It must be one of the two.</p> <p>I have two numpy arrays, <code>a</code> and <code>b</code>. <code>a</code> should be a proper subset of <code>b</code>. To confirm this I pr...
2
2016-07-27T23:33:44Z
38,624,919
<p><code>setdiff1d</code> and your other methods check number for <em>exact</em> equality. Due to floating point errors, it is very possible that your numbers aren't <em>exactly</em> equal. If you want to do floating point comparisons, you should instead use a very small epsilon.</p> <pre><code>if abs(a - b) &lt; 1e-1...
1
2016-07-27T23:42:56Z
[ "python", "arrays", "numpy" ]
Maximum recursion depth exceeded, but only when using a decorator
38,624,852
<p>I'm writing a program to calculate Levenshtein distance in Python. I implemented memoization because I am running the algorithm recursively. My original function implemented the memoization in the function itself. Here's what it looks like:</p> <pre><code># Memoization table mapping from a tuple of two strings to t...
6
2016-07-27T23:36:17Z
38,624,949
<p>Consider the stack frames (function calls) that are happening in your original code. They will look something like:</p> <pre><code>lev(s, t) -&gt; lev(..., ...) -&gt; lev(..., ...) -&gt; lev(..., ...) -&gt; lev(..., ...) </code></pre> <p>In you memoized version they appear as:</p> <pre><code...
7
2016-07-27T23:46:50Z
[ "python", "python-3.x", "recursion", "decorator", "memoization" ]
Maximum recursion depth exceeded, but only when using a decorator
38,624,852
<p>I'm writing a program to calculate Levenshtein distance in Python. I implemented memoization because I am running the algorithm recursively. My original function implemented the memoization in the function itself. Here's what it looks like:</p> <pre><code># Memoization table mapping from a tuple of two strings to t...
6
2016-07-27T23:36:17Z
38,624,952
<p>This <em>looks</em> like an infinite recursion issue, but it's not. You're just recursing really deeply, and the decorator makes it deeper.</p> <p>Instead of directly calling the <code>lev</code> function you defined, every call goes through <code>wrap</code>, and <code>wrap</code> calls <code>lev</code>. That make...
6
2016-07-27T23:47:03Z
[ "python", "python-3.x", "recursion", "decorator", "memoization" ]
Maximum recursion depth exceeded, but only when using a decorator
38,624,852
<p>I'm writing a program to calculate Levenshtein distance in Python. I implemented memoization because I am running the algorithm recursively. My original function implemented the memoization in the function itself. Here's what it looks like:</p> <pre><code># Memoization table mapping from a tuple of two strings to t...
6
2016-07-27T23:36:17Z
38,625,382
<p>Trying to understand your code, I made some modifications. Nothing big, just a matter of preference.</p> <p>I only changed one line:</p> <pre><code>if s[-1] is t[-1]: </code></pre> <p>for this one</p> <pre><code>if s[-1] == t[-1]: </code></pre> <p>As is, your code runs without any recursion problem</p> <p><str...
4
2016-07-28T00:41:31Z
[ "python", "python-3.x", "recursion", "decorator", "memoization" ]
GUI, Buttons not displaying in window
38,624,875
<p>For my homework, I have to create a widget. I'm very new to this. I'm trying to get my buttons to show up. I have tried packing them, but I don't know what I'm doing wrong. Here is what I have.</p> <pre><code>from tkinter import * import turtle main = Tk() main.title("TurtleApp") class turtleApp: def __init_(se...
0
2016-07-27T23:37:50Z
38,624,891
<p>First of all your indentation is off, but once you fix that, you never actually create an instance of your <code>turtleApp</code> class, so none of that code ever gets executed leaving you with an empty GUI.</p> <pre><code># Actually create a turtleApp instance which adds the buttons app = turtleApp() # Enter your...
2
2016-07-27T23:39:23Z
[ "python", "tkinter" ]
401 error python MongoDB connection
38,624,903
<p>I'm trying to set a connection between Python and MongoDB to store tweets. My problem is that I get 401 in each request with <code>Mylistener</code>. Could you please help to fix this ?</p> <pre><code>class MyListener(StreamListener): def __init__(self, start_time, time_limit=60): self.time = start_time...
0
2016-07-27T23:41:40Z
38,625,250
<p>Sounds like you need to authenticate with the database right after creating the new MongoClient instance:</p> <pre><code>client.tweets_db.authenticate('user', 'password') </code></pre> <p>See <a href="https://api.mongodb.com/python/current/examples/authentication.html" rel="nofollow">here</a> for more detailed exa...
0
2016-07-28T00:25:41Z
[ "python", "mongodb" ]
Why are these functions not drawing on the same graph together?
38,624,967
<p>I'd like to be able to click on the two buttons generated in the IPython GUI and then generate a total of 6 points on the same graph. However, right now clicking the two buttons does not create the 6 points, and only creates the graph made by the first button to be clicked. What am I doing wrong?</p> <pre><code>imp...
1
2016-07-27T23:48:51Z
38,625,607
<p>I played around with your code and got it to work by adding %matplotlib notebook and removing calls to plt.show().</p> <pre><code>%matplotlib notebook import matplotlib.pyplot as plt from matplotlib.patches import Rectangle from ipywidgets.widgets import Button from IPython.display import display class Test(object...
1
2016-07-28T01:13:44Z
[ "python", "matplotlib", "ipython" ]
Creating a dictionary from a list of strings
38,625,057
<p>I have a list of strings </p> <pre><code>list = ['2(a)', '2(b)', '3', '3(a)', '1d', '5'] </code></pre> <p>where it is intentional that the 1d, 3, and 5 don't involve parentheses.</p> <p>I would like to create a dictionary which looks like this:</p> <pre><code>dict = {'2': 'a', '2': 'b', '3': 'a', '1': 'd'} </cod...
0
2016-07-27T23:59:40Z
38,625,110
<p>Since a dictionary can't contain duplicate keys, use a <code>defaultdict</code>:</p> <pre><code>import collections l = ['2(a)', '2(b)', '3', '3(a)', '1c', '5'] d = collections.defaultdict(list) for item in l: num = ''.join(c for c in item if c.isdigit()) word = ''.join(c for c in item if c.isalpha()) if...
4
2016-07-28T00:05:42Z
[ "python", "regex", "string", "python-2.7", "dictionary" ]
Creating a dictionary from a list of strings
38,625,057
<p>I have a list of strings </p> <pre><code>list = ['2(a)', '2(b)', '3', '3(a)', '1d', '5'] </code></pre> <p>where it is intentional that the 1d, 3, and 5 don't involve parentheses.</p> <p>I would like to create a dictionary which looks like this:</p> <pre><code>dict = {'2': 'a', '2': 'b', '3': 'a', '1': 'd'} </cod...
0
2016-07-27T23:59:40Z
38,625,225
<p>This is a good time to use <code>setdefault()</code> for a <strong>dictionary</strong> to define the structure of your dictionary. The first part involves capturing the numbers from the elements using a regex that captures all numbers. That <code>list</code> is then concatenated using <code>join()</code>. </p> <p>W...
2
2016-07-28T00:21:48Z
[ "python", "regex", "string", "python-2.7", "dictionary" ]
Change some, but not all, pandas multiindex column names
38,625,102
<p>Suppose I have a data frame with multiindex column names that looks like this:</p> <pre><code> A B '1.5' '2.3' '8.4' b1 r1 1 2 3 a r2 4 5 6 b r3 7 8 9 10 </code></pre> <p>How would I change the just the column names under 'A' from strings to floats...
0
2016-07-28T00:04:06Z
38,626,145
<pre><code># build the DataFrame (sideways at first, then transposed) arrays = [['A','A','A','B'],['1.5', '2.3', '8.4', 'b1']] tuples = list( zip(*arrays) ) data1 = np.array([[1,2,3,'a'], [4,5,6,'b'], [7,8,9,10]]) index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second']) df = pd.DataFrame(data1.T, index=in...
1
2016-07-28T02:24:54Z
[ "python", "pandas" ]
how to search for a text in a string and replace with its value
38,625,104
<p>I need to search for image_bid in string <code>s</code>and if exists need to replace that string with its value <code>DEBUG</code> in this case,I tried the following but doesn't seem to work,can anyone suggest how can I do that?</p> <pre><code>import re s = "cols/sel/Pkg/Bin/LA/${image_bid:DEBUG}/" match = re.sear...
1
2016-07-28T00:04:28Z
38,625,185
<blockquote> <p>The method replace() returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to max.</p> </blockquote> <p>It doesn't seem like the <code>replace</code> method for string support regular expression, use <code>re.su...
0
2016-07-28T00:16:29Z
[ "python" ]
how to search for a text in a string and replace with its value
38,625,104
<p>I need to search for image_bid in string <code>s</code>and if exists need to replace that string with its value <code>DEBUG</code> in this case,I tried the following but doesn't seem to work,can anyone suggest how can I do that?</p> <pre><code>import re s = "cols/sel/Pkg/Bin/LA/${image_bid:DEBUG}/" match = re.sear...
1
2016-07-28T00:04:28Z
38,625,190
<p>You probably want something like</p> <pre><code>final_value = re.sub(r'\$\{image_bid\:(\w+)\}/', r'\1', s) </code></pre>
0
2016-07-28T00:17:15Z
[ "python" ]
Suport Vector machine (SVM) training using multiple features
38,625,115
<p>I am trying to train my svm algorithm with a point dataset extracted from GPS. My data instances (e.g x1, x2, x3,... xn) have a set of attributes (speed, coordinates, etc). I consider the line between two data instances (points) as a segment and I am trying to train my algorithm using more than one features (attribu...
0
2016-07-28T00:06:24Z
38,626,786
<p>after reading reading the description you gave to ali_m , why you choosed SVM? An alternative could be insted of using SVM(supervised learning) , use "anomaly detection"(unsupervised learning) where abnormal in your case would be an anomaly and you could vary the threshold and play with it.</p>
0
2016-07-28T03:50:02Z
[ "python", "svm" ]
Translate row in Python to JavaScript: [(M[i], k // M[i])]
38,625,204
<p>I'm trying to translate the following script into JavaScript. There is one row which I have no idea what it does, I'm suspecting push to the array.</p> <pre><code>def greedyCoinChanging(M, k): n = len(M) result = [] for i in xrange(n - 1, -1, -1): result += [(M[i], k // M[i])] // &lt;-- what the...
1
2016-07-28T00:19:09Z
38,625,237
<p>In JavaScript, you don't have to use a tuple. You can just use an array.</p> <pre><code>result.push([M[i], Math.floor(k/M[i])]); </code></pre> <p>Also, the integer division (<code>//</code>) can become <code>Math.floor(k/M[i])</code>;</p>
1
2016-07-28T00:23:44Z
[ "javascript", "python" ]
Why pandas silently ignores .iloc[i, j] assignment with too many indices?
38,625,223
<p>Why does pandas behave differently when setting or getting items in a series with erroneous number of indexes:</p> <pre><code>df = pd.DataFrame({'a': [10]}) # df['a'] is a series, can be indexed with 1 index only # will raise IndexingError, as expected df['a'].iloc[0, 0] df['a'].loc[0, 0] # will raise nothing, no...
5
2016-07-28T00:21:17Z
38,644,472
<h3>Getting values</h3> <p>If the key is a tuple (as in your example), then the <code>__getitem__</code> method of the superclass for the <code>loc</code> and <code>iloc</code> objects at some point calls <code>_has_valid_tuple(self, key)</code>.</p> <p>This method has the following code</p> <pre><code>for i, k in e...
1
2016-07-28T18:47:58Z
[ "python", "pandas" ]
How to use class based view in Django for html button?
38,625,337
<p>I wrote the following view:</p> <pre><code>class UserDeleteView(TemplateView): template_name = "user/user_delete.html" form_class = UserDeleteForm model = User def delete_my_account(self): user = get_user(self.request).user if user.is_authenticated(): logout(self.reques...
0
2016-07-28T00:36:20Z
38,625,456
<p>It might not be the answer you are looking for, but you can use DeleteView instead of TemplateView which just needs a success url.</p> <p>You can look its default functions methods that can be used here : <a href="https://ccbv.co.uk/projects/Django/1.9/django.views.generic.edit/DeleteView/" rel="nofollow">DeleteVie...
1
2016-07-28T00:53:36Z
[ "python", "django", "python-3.x", "button", "methods" ]
How to use class based view in Django for html button?
38,625,337
<p>I wrote the following view:</p> <pre><code>class UserDeleteView(TemplateView): template_name = "user/user_delete.html" form_class = UserDeleteForm model = User def delete_my_account(self): user = get_user(self.request).user if user.is_authenticated(): logout(self.reques...
0
2016-07-28T00:36:20Z
38,626,827
<p>One way of doing it would be something like this</p> <pre><code>class UserDeleteView(View): def post(self, request, object_id, *args, **kwargs): '''retrieve the object for the given object_id and delete it''' return redirect(url_to_be_redirected_to) </code></pre> <p>This should be sufficient fo...
1
2016-07-28T03:54:44Z
[ "python", "django", "python-3.x", "button", "methods" ]
Correct syntax for calling a group of objects in a list?
38,625,435
<p>I have a list with 1000 items in it but only want to call a certain range of them.</p> <pre><code>class myClass(): def event(self): #do stuff my_list = [myClass(i) for i in range(1000)] #incorrect part: my_list[0 - 10].event() </code></pre> <p>Meaning that I am trying to call "event" for only the f...
-1
2016-07-28T00:50:38Z
38,625,457
<p>Do this:</p> <pre><code>for obj in my_list[:9]: obj.event() </code></pre> <p>Note since you just want the first 9 objects to be called, you need to use indexes 0-8 i.e. 0,1,2,3,4,5,6,7,8</p>
5
2016-07-28T00:53:37Z
[ "python" ]
Correct syntax for calling a group of objects in a list?
38,625,435
<p>I have a list with 1000 items in it but only want to call a certain range of them.</p> <pre><code>class myClass(): def event(self): #do stuff my_list = [myClass(i) for i in range(1000)] #incorrect part: my_list[0 - 10].event() </code></pre> <p>Meaning that I am trying to call "event" for only the f...
-1
2016-07-28T00:50:38Z
38,625,460
<pre><code>[x.event() for x in my_list[:9]] </code></pre> <p>or</p> <pre><code>list(map(lambda x: x.event(), my_list[:9])) </code></pre> <p>or, as @khredos suggests,</p> <pre><code>for obj in my_list[:9]: obj.event() </code></pre> <p>If <code>myClass.event()</code> does return something (and you want to keep t...
3
2016-07-28T00:53:43Z
[ "python" ]
Does python run all computations in double percision?
38,625,448
<p>I know MatLab does everything in double, I heard about the similar thing for python but not quite sure. Can anyone confirm it with reference? Thanks!</p>
0
2016-07-28T00:53:09Z
38,625,477
<p>Well, that's a simplification.</p> <ul> <li><p>The <code>float</code> type in Python is double-precision.</p></li> <li><p>The <code>int</code> type has integer precision, but only limited by memory. Large numbers can have far more significant digits than a double float.</p></li> <li><p>When using NumPy, you may ch...
4
2016-07-28T00:56:47Z
[ "python", "numpy" ]
Python csv reader.next() vs next(reader)
38,625,485
<p>When reading files using the <code>csv</code> module, there are two ways to iterate through the generator returned by <code>csv.reader</code>.</p> <pre><code>with open('foo.csv') as f: reader = csv.reader(f) row1 = reader.next() row2 = next(reader) </code></pre> <p>Is there any difference between how <...
1
2016-07-28T00:58:00Z
38,625,550
<p>In the beginning, the only option was to call <code>iterator.next()</code> on an iterator <code>iterator</code>. Python 2.6 introduced the builtin <code>next(iterator)</code>, which simply called <code>iterator.next()</code> under the hood. In Python 3, <code>next(iterator)</code> calls <code>iterator.__next__()</co...
1
2016-07-28T01:06:08Z
[ "python", "csv" ]
shell multipipe broken with multiple python scripts
38,625,530
<p>I am trying to get the stdout of a python script to be shell-piped in as stdin to another python script like so:</p> <pre><code>find ~/test -name "*.txt" | python my_multitail.py | python line_parser.py </code></pre> <p>It should print an output but nothing comes out of it.</p> <p>Please note that this works:</p>...
1
2016-07-28T01:03:32Z
38,627,080
<p>There's a hint if you run your <code>line_parser.py</code> interactively:</p> <pre><code>$ python line_parser.py a b c line= a line= b line= c </code></pre> <p>Note that I hit ctrl+D to provoke an EOF after entering the 'c'. You can see that it's slurping up all the input before it starts iterating over the li...
3
2016-07-28T04:24:37Z
[ "python", "bash", "shell", "pipe" ]
Python Equivalence of the Scala Code in Spark
38,625,582
<p>I have this piece of code in Scala</p> <pre><code> val file = sc.textFile(filelocation) //Inital edge list that is to be passed to Iterate function var edges : RDD[(Int, Int)] = file.flatMap{ s =&gt; val nodes = s.split("\\s+") Seq((nodes(0).toInt, nodes(1).toInt)) } edges.collect() </...
-3
2016-07-28T01:09:14Z
38,625,774
<p>Change the <code>flatMap</code> to <code>map</code></p> <p>This is going to work!</p>
0
2016-07-28T01:36:27Z
[ "python", "scala", "apache-spark", "pyspark", "databricks" ]
How can I parse a special XML format under Python?
38,625,639
<p>The data format looks like that:</p> <pre><code>&lt;doc&gt; &lt;url&gt;i am url&lt;/url&gt; &lt;docno&gt;01a064132d932277&lt;/docno&gt; &lt;contenttitle&gt;title&lt;/contenttitle&gt; &lt;content&gt;whatever the content is &lt;/content&gt; &lt;/doc&gt; ... &lt;doc&gt; &lt;url&gt;i am another url&lt;/url&gt; &lt;do...
0
2016-07-28T01:17:50Z
38,625,826
<p>You could:</p> <ul> <li>read the file (raw text, unparsed) into a string</li> <li>append "<code>&lt;root&gt;</code>" to the beginning and "<code>&lt;/root&gt;</code>" to the end of the string</li> <li>then have BeautifulSoup parse the resulting string.</li> </ul> <p>Then each of the original <code>&lt;doc&gt;</cod...
3
2016-07-28T01:42:01Z
[ "python", "xml" ]
Using list.index() to find datetime.date object throws an error
38,625,664
<p>I have a list containing datetime.date() objects. I am trying to find the index of a specific date object. </p> <p>I tried this - </p> <pre><code>&gt;&gt; index = date_obj.index(datetime.date(2009, 1, 31)) &gt;&gt; *** TypeError: descriptor 'date' requires a 'datetime.datetime' object but received a 'int' </code><...
0
2016-07-28T01:21:13Z
38,625,675
<p>You imported <code>datetime.datetime</code> as <code>datetime</code></p> <pre><code>from datetime import datetime </code></pre> <p><code>datetime.date</code> is part of the base library, not <code>datetime.datetime</code></p> <p>You should just import <code>datetime</code> and use <code>datetime.datetime</code> a...
2
2016-07-28T01:23:25Z
[ "python", "list", "datetime", "python-datetime" ]
Using list.index() to find datetime.date object throws an error
38,625,664
<p>I have a list containing datetime.date() objects. I am trying to find the index of a specific date object. </p> <p>I tried this - </p> <pre><code>&gt;&gt; index = date_obj.index(datetime.date(2009, 1, 31)) &gt;&gt; *** TypeError: descriptor 'date' requires a 'datetime.datetime' object but received a 'int' </code><...
0
2016-07-28T01:21:13Z
38,625,683
<p>You have probably used</p> <pre><code>from datetime import datetime </code></pre> <p>and the problem is that date is part of the datetime library not from the datetime.datetime module ;)</p>
1
2016-07-28T01:24:43Z
[ "python", "list", "datetime", "python-datetime" ]
In Beautifulsoup4, Get All SubElements of an Element, but Not SubElements of the SubElements
38,625,693
<p>I've got the following html:</p> <pre><code>&lt;div class="what-im-after"&gt; &lt;p&gt; "content I want" &lt;/p&gt; &lt;p&gt; "content I want" &lt;/p&gt; &lt;p&gt; "content I want" &lt;/p&gt; &lt;div class='not-what-im-after"&gt; &lt;p&gt; "con...
1
2016-07-28T01:26:07Z
38,625,694
<p>In the course of writing this question, an approach came to mind which seems to work fine. </p> <p>Basically, I'm checking each <code>&lt;p&gt;</code> element to see if the parent element is <code>&lt;div class="what-im-after"&gt;</code> which, in effect, excludes any <code>&lt;p&gt;</code> tags nested within subel...
0
2016-07-28T01:26:07Z
[ "python", "web-scraping", "beautifulsoup" ]
In Beautifulsoup4, Get All SubElements of an Element, but Not SubElements of the SubElements
38,625,693
<p>I've got the following html:</p> <pre><code>&lt;div class="what-im-after"&gt; &lt;p&gt; "content I want" &lt;/p&gt; &lt;p&gt; "content I want" &lt;/p&gt; &lt;p&gt; "content I want" &lt;/p&gt; &lt;div class='not-what-im-after"&gt; &lt;p&gt; "con...
1
2016-07-28T01:26:07Z
38,626,254
<pre><code>from bs4 import BeautifulSoup htmltxt = """&lt;div class="what-im-after"&gt; &lt;p&gt; "content I want" &lt;/p&gt; &lt;p&gt; "content I want" &lt;/p&gt; &lt;p&gt; "content I want" &lt;/p&gt; &lt;div class='not-what-im-after"&gt; &lt;p&gt; ...
-1
2016-07-28T02:40:16Z
[ "python", "web-scraping", "beautifulsoup" ]
In Beautifulsoup4, Get All SubElements of an Element, but Not SubElements of the SubElements
38,625,693
<p>I've got the following html:</p> <pre><code>&lt;div class="what-im-after"&gt; &lt;p&gt; "content I want" &lt;/p&gt; &lt;p&gt; "content I want" &lt;/p&gt; &lt;p&gt; "content I want" &lt;/p&gt; &lt;div class='not-what-im-after"&gt; &lt;p&gt; "con...
1
2016-07-28T01:26:07Z
38,629,528
<p>What you want is to set <em>recursive=False</em> if you just want the p tags under the <code>what-im-after</code> div that are not inside any other tags:</p> <pre><code>soup = BeautifulSoup(html) print(soup.find('div', class_='what-im-after').find_all("p", recursive=False)) </code></pre> <p>That is exactly the sa...
1
2016-07-28T07:18:13Z
[ "python", "web-scraping", "beautifulsoup" ]
How to distribute python software to users of low technical ability?
38,625,698
<p>I have a python application (3.5) that I’m trying to distribute. It:</p> <ul> <li>Uses no GUI libraries (it runs in the browser)</li> <li>Uses several external packages (Flask, SocketIO, httplib2)</li> <li>maintains saved config and data files inside the main source directory</li> </ul> <p>The target users:</p> ...
0
2016-07-28T01:26:50Z
38,625,772
<p>There are a couple of applications that can help you to distribute a Python Application, for this case you want to take a look on Python freezing tools like <a href="http://www.py2exe.org/" rel="nofollow">py2exe</a> (windows only) or <a href="https://pythonhosted.org/py2app/" rel="nofollow">py2app</a> (MacOs).</p> ...
0
2016-07-28T01:36:21Z
[ "python", "software-distribution" ]
mysql store muptiple alias for one person
38,625,706
<p>One person have one name and multiple alias。 Person can index by name and alias. So I design two table store this relationship: and . Like this:</p> <pre><code>&lt;user table&gt; |user_id | int |name | varchar &lt;alias table&gt; |user_id | int |alias | varchar </code></pre> <p>Two table ...
0
2016-07-28T01:27:19Z
38,625,773
<p>I agree with having a unique constraint, but it should be <code>UNIQUE CONSTRAINT (user_id, alias)</code> on the <code>alias</code> table. But I disagee with the <code>sorted_alias_str</code>. This column will be a hassle to maintain, because it will have to be recomputed each time any user adds or drops an alias....
0
2016-07-28T01:36:21Z
[ "python", "mysql", "database", "web-services" ]
mysql store muptiple alias for one person
38,625,706
<p>One person have one name and multiple alias。 Person can index by name and alias. So I design two table store this relationship: and . Like this:</p> <pre><code>&lt;user table&gt; |user_id | int |name | varchar &lt;alias table&gt; |user_id | int |alias | varchar </code></pre> <p>Two table ...
0
2016-07-28T01:27:19Z
38,625,791
<p>The unique constraint should be on the (user_id, name). This prevents one person (user_id) from having the same alias multiple times.</p>
1
2016-07-28T01:37:33Z
[ "python", "mysql", "database", "web-services" ]
mysql store muptiple alias for one person
38,625,706
<p>One person have one name and multiple alias。 Person can index by name and alias. So I design two table store this relationship: and . Like this:</p> <pre><code>&lt;user table&gt; |user_id | int |name | varchar &lt;alias table&gt; |user_id | int |alias | varchar </code></pre> <p>Two table ...
0
2016-07-28T01:27:19Z
38,625,955
<p>What you have already gives a single user multiple aliases. A composite unique constraint ensures one user will not have the same alias more than once.</p> <pre><code>&lt;user table&gt; |user_id | int (unique) |name | varchar &lt;alias table&gt; |user_id | int (unique, also ref to user.user_id) |alia...
0
2016-07-28T02:00:02Z
[ "python", "mysql", "database", "web-services" ]
Python convert string to datetime for comparison to datetime object
38,625,723
<p>I have a string <code>lfile</code> with a datetime in it (<code>type(lfile)</code> gives <code>&lt;type 'str'&gt;</code>) and a Python datetime object <code>wfile</code>. Here is the code:</p> <pre><code>import os, datetime lfile = '2005-08-22_11:05:45.000000000' time_w = os.path.getmtime('{}\\{}.py' .format('C:\Te...
1
2016-07-28T01:29:24Z
38,625,832
<p><strong>Question 1</strong></p> <p>Python handles microseconds, not nano seconds. You can strip the last three characters of the time to convert it to microseconds and then add <code>.%f</code> to the end:</p> <pre><code>lfile = datetime.datetime.strptime(linx_file_dtime[:-3], '%Y-%m-%d_%H:%M:%S.%f') </code></pre...
2
2016-07-28T01:43:00Z
[ "python", "python-2.7", "datetime", "strptime" ]
Python convert string to datetime for comparison to datetime object
38,625,723
<p>I have a string <code>lfile</code> with a datetime in it (<code>type(lfile)</code> gives <code>&lt;type 'str'&gt;</code>) and a Python datetime object <code>wfile</code>. Here is the code:</p> <pre><code>import os, datetime lfile = '2005-08-22_11:05:45.000000000' time_w = os.path.getmtime('{}\\{}.py' .format('C:\Te...
1
2016-07-28T01:29:24Z
38,626,162
<p>That's right, <code>strptime()</code> does not handle nanoseconds. The accepted answer in the question that you linked to offers an option: strip off the last 3 digits and then parse with <code>.%f</code> appended to the format string.</p> <p>Another option is to use <code>dateutil.parser.parse()</code>:</p> <pre>...
1
2016-07-28T02:26:03Z
[ "python", "python-2.7", "datetime", "strptime" ]
Faster way to partition a Face with Sketch in ABAQUS with scripting
38,625,874
<p>My aim is to obtain a transition mapped quad meshing on a long rectangular region which is a parametrised model. The final mesh can be seen as follows: </p> <p><a href="http://i.stack.imgur.com/P9esm.png" rel="nofollow"><img src="http://i.stack.imgur.com/P9esm.png" alt="Transition Mapped Quad Meshing"></a></p> <p>...
0
2016-07-28T01:48:05Z
39,328,730
<p>It seems you don't have to iterate the process of sketching as in ABAQUS Sketch you can use Linear Pattern to copy/duplicate the initial sketch (first block on the left side). This may make the whole process easier. Thanks.</p> <p>Regards, Longjie</p>
0
2016-09-05T10:34:04Z
[ "python", "scripting", "abaqus" ]
JQuery Ajax call not working in If statement
38,625,945
<p>Is there a reason why my Ajax call will not work inside of an if statement? I may be doing something fundamentally wrong here because I don't have a lot of experience with JS or Ajax. Thanks</p> <p>The working js function is:</p> <pre><code>function filter(varType, varValue) { var $products = $('#products'); ...
0
2016-07-28T01:57:59Z
38,625,971
<p>You closed the curly brace of your <code>if-</code> statement too soon:</p> <pre><code>if (y &gt; x) { $.getJSON($SCRIPT_ROOT + '/filterSize/' + varValue) //} &lt;-- TOO EARLY .success(function (data) { .... }); } &lt;-- SHOULD BE HERE INSTEAD </code></pre> <p>End the <code>if</code> statement ...
1
2016-07-28T02:03:35Z
[ "javascript", "jquery", "python", "ajax" ]
JQuery Ajax call not working in If statement
38,625,945
<p>Is there a reason why my Ajax call will not work inside of an if statement? I may be doing something fundamentally wrong here because I don't have a lot of experience with JS or Ajax. Thanks</p> <p>The working js function is:</p> <pre><code>function filter(varType, varValue) { var $products = $('#products'); ...
0
2016-07-28T01:57:59Z
38,625,972
<pre><code> if (y &gt; x) { $.getJSON($SCRIPT_ROOT + '/filterSize/' + varValue) .success(function (data) { $products.empty(); // clear html from container var elt0 = '&lt;div class="page-content"&gt;&lt;h1 id="shoes"&gt;Shoes&lt;/h1&gt;&lt;/div&gt;'; $products.a...
1
2016-07-28T02:03:59Z
[ "javascript", "jquery", "python", "ajax" ]
Django Rest Framework - adding JOIN endpoints
38,626,017
<p>I'm making a REST API with Django Rest Framework (DRF) which has the following endpoints:</p> <pre><code>/users/ /users/&lt;pk&gt;/ /items/ /items/&lt;pk&gt;/ </code></pre> <p>but I'd like to add the endpoint:</p> <pre><code>/users/&lt;pk&gt;/items/ </code></pre> <p>which would of course return the items that be...
2
2016-07-28T02:08:54Z
39,727,821
<p>Took me a while to figure this out. I've been using view sets, so I'll give this answer within that setting.</p> <p>First, URLConf and registered routes remain unchanged, i.e.,</p> <pre><code>router = DefaultRouter() router.register(r'users', UserViewSet) router.register(r'items', ItemViewSet) urlpatterns = [ ...
0
2016-09-27T14:51:22Z
[ "python", "django", "rest" ]
Trying to convert a CSV into JSON in python for posting to REST API
38,626,039
<p>I've got the following data in a CSV file (a few hundred lines) that I'm trying to massage into sensible JSON to post into a rest api I've gone with the bare minimum fields required, but here's what I've got:</p> <pre><code>dateAsked,author,title,body,answers.author,answers.body,topics.name,answers.accepted 13-Jan...
1
2016-07-28T02:11:16Z
38,626,745
<p>You can use a <code>csv.DictReader</code> to process the CSV file as a dictionary for each row. Using the field names as keys, a new dictionary can be constructed that groups common keys into a nested dictionary keyed by the part of the field name after the <code>.</code>. The nested dictionary is held within a list...
2
2016-07-28T03:45:13Z
[ "python", "json", "csv", "pandas" ]
Why won't this print, when I type in a keyword?
38,626,044
<pre><code>`print"Welcome to Caleb's login script!" loop = 'true' while(loop == 'true'): username = raw_input("Username Please") password= raw_input("Password Please") if(username == "Caleb" and password == "Lamps320"): print 'Logged in as ' + username loop = 'false' loop1 = 'true' while(loop1 == 'true'): co...
-2
2016-07-28T02:11:55Z
38,626,415
<p>Your script is inconsistently indented. It does what you say it does when that is fixed.</p> <pre><code>print"Welcome to Caleb's login script!" loop = 'true' while(loop == 'true'): username = raw_input("Username Please") password= raw_input("Password Please") if(username == "Caleb" and password == "Lamp...
0
2016-07-28T03:00:45Z
[ "python" ]
why list(print(x.upper(), end=' ') for x in 'spam') gets a [None, None, None, None] list?
38,626,055
<p>On page 608 of 《Learning Python 5th》 ,there is a example code: </p> <pre><code>&gt;&gt;&gt; list(print(x.upper(), end=' ') for x in 'spam') S P A M [None, None, None, None] </code></pre> <p>so,why [None, None, None, None] pops up on the last?</p>
1
2016-07-28T02:13:35Z
38,626,086
<p>The <code>print</code> function returns <code>None</code>... Your expression therefore constructs a list <code>[None, None, None, None]</code>. Since you are in the python Read Evaluate Print Loop (REPL), the result of the expression gets printed after it is evaluated... </p> <p>So, the evaluation of the expressio...
4
2016-07-28T02:17:23Z
[ "python", "python-3.x" ]
Store the result of a function as a variable
38,626,087
<p>I'm trying to write an RSA code, but I'm having issues with a simple thing. I want to store the result of a function as a variable, twice in Python. This is my code</p> <pre><code>def random_odd_between(j,k): k1 = (k-1)//2 j1 = j//2 a1 = int(random()*(k1-j1+1))+j1 a = 2*a1 +1 return a # The lis...
0
2016-07-28T02:17:25Z
38,626,102
<p>just replace <code>print '%i' %a</code> with <code>return a</code></p>
3
2016-07-28T02:19:04Z
[ "python", "rsa" ]
Store the result of a function as a variable
38,626,087
<p>I'm trying to write an RSA code, but I'm having issues with a simple thing. I want to store the result of a function as a variable, twice in Python. This is my code</p> <pre><code>def random_odd_between(j,k): k1 = (k-1)//2 j1 = j//2 a1 = int(random()*(k1-j1+1))+j1 a = 2*a1 +1 return a # The lis...
0
2016-07-28T02:17:25Z
38,626,485
<p>I believe you had errors in both your <code>check_if_prime</code> and <code>get_a_prime</code> functions. In the former, <code>ZZ</code> is not defined and the first <code>break</code> should be indented one more level and the last one is redundant. Better yet, just return True or False when needed.</p> <p>In the...
0
2016-07-28T03:11:54Z
[ "python", "rsa" ]
Getting Top N items per group in pySpark
38,626,124
<p>I am using Spark 1.6.2, I have the following data structure:</p> <pre><code>sample = sqlContext.createDataFrame([ (1,['potato','orange','orange']), (1,['potato','orange','yogurt']), (2,['vodka','beer','vodka']), (2,['vodka','beer','juic...
0
2016-07-28T02:21:26Z
38,626,490
<p>If this is working it is probably better to post this to <a href="http://codereview.stackexchange.com/">Code Review</a>.</p> <p>Just as an exercise I did this without the Counter but largely you are just replicating the same functionality.</p> <ul> <li>Count each occurrence of (<code>cat</code>, <code>term</code>)...
1
2016-07-28T03:12:27Z
[ "python", "apache-spark" ]
Misshaped blob in caffe
38,626,234
<p>I'm using the following prototxt:</p> <pre><code>layer { name: "pool2" type: "Pooling" bottom: "conv5" top: "pool2" pooling_param { pool: MAX kernel_w: 2 kernel_h: 1 stride_w: 2 stride_h: 1 pad_h: 0 pad_w: 0 } } </code></pre> <p>The blob shape before is 1x64x1x30, and after ...
1
2016-07-28T02:36:15Z
38,626,737
<p>In general, the max pooling layer accepts an input volume of size W1 x H1 x D1 and requires two hyperparameters -- the stride (S) and kernel size (K). It produces an output volume of size W2 x H2 x D2 where we have W2 = (W1 - K)/S + 1, H2 = (H1 - K)/S + 1, and D2 = D1. Simple computation yields that a kernel size o...
0
2016-07-28T03:44:00Z
[ "python", "deep-learning", "caffe" ]
Why is a generator produced by yield faster than a generator produced by xrange?
38,626,308
<p>I was investigating Python generators and decided to run a little experiment.</p> <pre><code>TOTAL = 100000000 def my_sequence(): i = 0 while i &lt; TOTAL: yield i i += 1 def my_list(): return range(TOTAL) def my_xrange(): return xrange(TOTAL) </code></pre> <p>Memory usage (us...
10
2016-07-28T02:48:00Z
38,626,519
<p>I'm going to preface this answer by saying that timings on this scale are likely going to be hard to measure accurately (probably best to use <code>timeit</code>) and that these sorts of optimizations will almost never make any difference in your actual program's runtime ...</p> <p>Ok, now the disclaimer is done .....
9
2016-07-28T03:16:39Z
[ "python", "python-2.7", "python-3.x", "yield" ]
Why is a generator produced by yield faster than a generator produced by xrange?
38,626,308
<p>I was investigating Python generators and decided to run a little experiment.</p> <pre><code>TOTAL = 100000000 def my_sequence(): i = 0 while i &lt; TOTAL: yield i i += 1 def my_list(): return range(TOTAL) def my_xrange(): return xrange(TOTAL) </code></pre> <p>Memory usage (us...
10
2016-07-28T02:48:00Z
38,626,711
<p>As I mentioned in my comment above, with your generator function and with xrange, you're not actually creating the sequence, merely creating the object. @mgilson's answer covers the calls related to <em>creating</em> them.</p> <p>As for actually doing something with them:</p> <pre><code>&gt;&gt;&gt; TOTAL = 100000...
3
2016-07-28T03:41:32Z
[ "python", "python-2.7", "python-3.x", "yield" ]
how to do a simple calculate in web.py template
38,626,344
<p>in <code>web.py</code>'s template, I can retrieve number like this:</p> <pre><code>$for item in item_list: &lt;td&gt;$item.get("fans_cnt")&lt;/td&gt; </code></pre> <p>and this <code>$item.get("fans_cnt")</code> will get a number, now I want it divided by 1000, but this won't work:</p> <pre><code>$for item in i...
0
2016-07-28T02:52:03Z
38,626,399
<p>From <a href="http://webpy.org/docs/0.3/templetor" rel="nofollow">the docs</a>, under heading Syntax, section <em>Expression Substitution</em>:</p> <blockquote> <p>Special character $ is used to specify python expressions. Expression can be enclosed in () or {} for explicit grouping.</p> </blockquote> <p>So:</p>...
2
2016-07-28T02:58:53Z
[ "python", "templates", "web.py" ]
Python pip installation not working how to do?
38,626,409
<p>I keep trying to install Pip using get-pip.py and only get the wheel file in the scripts folder. Try running "pip" in the command prompt and it just comes out with an error. Running windows 8 incase you need. <em>edit</em> error is 'pip' is not recognized as an internal or external command...</p>
-1
2016-07-28T03:00:06Z
38,627,143
<p>Try navigating to ~/Python[version]/Scripts in cmd, then use <strong>pip[version] [command] [module]</strong> (ie. pip3 install themodulename or pip2 install themodulename)</p>
0
2016-07-28T04:31:37Z
[ "python", "python-2.7", "pip" ]
Python pip installation not working how to do?
38,626,409
<p>I keep trying to install Pip using get-pip.py and only get the wheel file in the scripts folder. Try running "pip" in the command prompt and it just comes out with an error. Running windows 8 incase you need. <em>edit</em> error is 'pip' is not recognized as an internal or external command...</p>
-1
2016-07-28T03:00:06Z
38,627,346
<p>If you are using latest version of Python.</p> <p>In computer properties, Go to Advanced System Settings -> Advanced tab -> Environmental Variables</p> <p>In System variables section, there is variable called PATH. Append c:\Python27\Scripts (Note append, not replace)</p> <p>Then open a new command prompt, try "p...
1
2016-07-28T04:52:26Z
[ "python", "python-2.7", "pip" ]
Pass JSON Data from PHP to Python Script
38,626,423
<p>I'd like to be able to pass a PHP array to a Python script, which will utilize the data to perform some tasks. I wanted to try to execute my the Python script from PHP using shell_exec() and pass the JSON data to it (which I'm completely new to).</p> <pre><code>$foods = array("pizza", "french fries"); $result = she...
3
2016-07-28T03:02:32Z
38,626,631
<p>You can base64 <code>foods</code> to string, then passed to the data to Python and decode it.For example:</p> <pre><code>import sys, base64 if len(sys.argv) &gt; 1: data = base64.b64decode(sys.argv[1]) foods = data.split(',') print(foods) </code></pre>
0
2016-07-28T03:32:31Z
[ "php", "python", "json" ]
Pass JSON Data from PHP to Python Script
38,626,423
<p>I'd like to be able to pass a PHP array to a Python script, which will utilize the data to perform some tasks. I wanted to try to execute my the Python script from PHP using shell_exec() and pass the JSON data to it (which I'm completely new to).</p> <pre><code>$foods = array("pizza", "french fries"); $result = she...
3
2016-07-28T03:02:32Z
38,627,103
<p>If you have the json string: <strong>data = '["pizza","french fries"]'</strong> and <em>json.loads(data)</em> isn't working (which it should), then you can use: <strong>MyPythonList = eval(data)</strong>. <em>eval</em> takes a string and converts it to a python object</p>
0
2016-07-28T04:27:28Z
[ "php", "python", "json" ]
Better Method of Creating Multi Line Text Entry?
38,626,532
<p>I need to create a message box for a user in a GUI with tkinter. For 3/4 of my entries, <code>Entry(master, options. . .,)</code> works. But for a message box, I need a multi line entry. </p> <p>How would I do this? I tried <code>ScrolledText(root).pack()</code>, but it doesn't have the same commands/variables as E...
1
2016-07-28T03:19:48Z
38,628,794
<p>It is not explicitly mentioned in the <a href="http://effbot.org/zone/tkinter-scrollbar-patterns.htm" rel="nofollow">documentation</a>, but even if the <a href="http://effbot.org/tkinterbook/entry.htm" rel="nofollow"><code>tkinter.Entry</code></a> widget's content can be scrolled, it <strong>can only be scrolled hor...
1
2016-07-28T06:39:19Z
[ "python", "python-3.x", "tkinter", "multiline", "entry" ]
Better Method of Creating Multi Line Text Entry?
38,626,532
<p>I need to create a message box for a user in a GUI with tkinter. For 3/4 of my entries, <code>Entry(master, options. . .,)</code> works. But for a message box, I need a multi line entry. </p> <p>How would I do this? I tried <code>ScrolledText(root).pack()</code>, but it doesn't have the same commands/variables as E...
1
2016-07-28T03:19:48Z
38,629,542
<p>Billal is right, however i would recomend simply using a Textbox.</p> <p>go to: <a href="http://www.tutorialspoint.com/python/tk_text.htm" rel="nofollow">http://www.tutorialspoint.com/python/tk_text.htm</a></p> <p>for more information </p>
1
2016-07-28T07:18:28Z
[ "python", "python-3.x", "tkinter", "multiline", "entry" ]
DoesNotExist at /admin/login/ while using userena
38,626,574
<p>I just used userena to create user function and everything works fine except it gives this error when I try to log in at admin page, and I'm using django 1.9.7 and userena 2.0.1. I read some old posts and it says to remove <code>'django.contrib.sites'</code> in INSTALLED_APPS, but userena wouldn't work if I remove i...
1
2016-07-28T03:24:57Z
38,628,132
<p>Probably here's an answer: <a href="http://django-userena.readthedocs.io/en/latest/faq.html#i-get-a-site-matching-query-does-not-exist-exception" rel="nofollow">I get a “Site matching query does not exist.” exception</a></p> <p>Did you forget to set up your SITE_ID setting variable?</p>
1
2016-07-28T05:57:09Z
[ "python", "django", "django-userena" ]
DoesNotExist at /admin/login/ while using userena
38,626,574
<p>I just used userena to create user function and everything works fine except it gives this error when I try to log in at admin page, and I'm using django 1.9.7 and userena 2.0.1. I read some old posts and it says to remove <code>'django.contrib.sites'</code> in INSTALLED_APPS, but userena wouldn't work if I remove i...
1
2016-07-28T03:24:57Z
38,630,170
<p>This error indicates that you do not have and <code>Site</code>s configured in your database. That can be done with your admin. If you visit <a href="http://localhost:8000/admin/sites/site/" rel="nofollow">http://localhost:8000/admin/sites/site/</a> you will see that currently the list is empty.</p> <p>Just add a s...
1
2016-07-28T07:49:14Z
[ "python", "django", "django-userena" ]
form.is_valid() returning false with file attachments
38,626,616
<p>I have a form page which asks for file upload, but in the views.py page, form.is_valid() is always returning 'False'. The following is the forms.py:</p> <p>forms.py</p> <pre><code>from django import forms class Upload_resume(forms.Form): f_name = forms.CharField(label='First Name', max_length=64, required=Tru...
0
2016-07-28T03:30:22Z
38,626,633
<p>The <code>POST</code> request is missing the file. The <code>form</code> tag in your template should have <code>enctype='multipart/form-data'</code> when you are trying to upload a file.</p>
1
2016-07-28T03:32:44Z
[ "python", "django" ]
Convert PIL image to bytearray
38,626,692
<p>In C#, I can use Bitmap.lockbits() to access a bitmap as a byte array. How to do this in PIL? I have tried Image.write() but it wrote a full format image to a stream.</p>
0
2016-07-28T03:38:39Z
38,626,806
<pre><code>from io import BytesIO from PIL import Image with BytesIO() as output: with Image.open(path_to_image) as img: img.save(output, 'BMP') data = output.getvalue() </code></pre>
2
2016-07-28T03:52:08Z
[ "python", "python-imaging-library" ]
python Raspberry pi receive udp data from spesefic port Visual Studio
38,626,698
<p>I currently got my Raspberry Pi 3 working as a File-Sharing device on my local internet. A 5' display is connected to it and I want to be able to send commands to it through udp packets. I know a lot about c#, but I'm totally new to python. I'm programming in Visual Studio. I already have the sending program working...
0
2016-07-28T03:39:51Z
38,627,168
<p>I figured it out. I changed UDP_IP = "192.168.1.11" to UDP_IP = "" Like so:</p> <pre><code>import socket UDP_PORT = 2522 UDP_IP = "" sock = socket.socket(socket.AF_INET, # Internet socket.SOCK_DGRAM) # UDP sock.bind((UDP_IP, UDP_PORT)) while True: data, addr = sock.recvfrom(1024) # buffer size i...
0
2016-07-28T04:35:17Z
[ "python", "visual-studio", "udp", "raspberry-pi", "raspbian" ]
Mapping a list into a reference list
38,626,700
<p>I am trying to make this as clear as I can. Please let me know if I should clarify anything.</p> <p>I have a long list of variables in a list in the following format - </p> <pre><code>L = ["Fruit", "Transportation", "Housing", "Food", "Education"] </code></pre> <p>I would like to map a shorter list into it. The s...
0
2016-07-28T03:40:19Z
38,626,743
<p>By using a list comprehension that takes every value in <code>L</code> and if it is contained inside <code>S</code> it returns a value of <code>1</code>, and, if not, it returns a value of <code>0</code>:</p> <pre><code>m = [1 if subval in S else 0 for subval in L] </code></pre> <p>the result is:</p> <pre><code>[...
1
2016-07-28T03:44:45Z
[ "python", "list", "mapping" ]
Mapping a list into a reference list
38,626,700
<p>I am trying to make this as clear as I can. Please let me know if I should clarify anything.</p> <p>I have a long list of variables in a list in the following format - </p> <pre><code>L = ["Fruit", "Transportation", "Housing", "Food", "Education"] </code></pre> <p>I would like to map a shorter list into it. The s...
0
2016-07-28T03:40:19Z
38,626,744
<p>Try this:</p> <pre><code>[int(x in S) for x in L] </code></pre>
1
2016-07-28T03:45:03Z
[ "python", "list", "mapping" ]
Mapping a list into a reference list
38,626,700
<p>I am trying to make this as clear as I can. Please let me know if I should clarify anything.</p> <p>I have a long list of variables in a list in the following format - </p> <pre><code>L = ["Fruit", "Transportation", "Housing", "Food", "Education"] </code></pre> <p>I would like to map a shorter list into it. The s...
0
2016-07-28T03:40:19Z
38,626,783
<p>You can use python's list comprehension as follow: </p> <pre><code>ans=[1 if x in S else 0 for x in L] </code></pre>
1
2016-07-28T03:49:48Z
[ "python", "list", "mapping" ]
Mapping a list into a reference list
38,626,700
<p>I am trying to make this as clear as I can. Please let me know if I should clarify anything.</p> <p>I have a long list of variables in a list in the following format - </p> <pre><code>L = ["Fruit", "Transportation", "Housing", "Food", "Education"] </code></pre> <p>I would like to map a shorter list into it. The s...
0
2016-07-28T03:40:19Z
38,626,804
<blockquote> <p>I tried map(S, L) but clearly a list is not callable.</p> </blockquote> <p>But its methods are:</p> <pre><code>&gt;&gt;&gt; map(S.count, L) [1, 0, 0, 1, 0] </code></pre> <p>(This one assumes there are no duplicates in S. If that's not the case, you could for example use <code>map(list(set(S)).count...
1
2016-07-28T03:51:45Z
[ "python", "list", "mapping" ]
Filling NaN values in a Pandas DataFrame conditionally on the values of non-NaN columns
38,626,704
<p>I have a question regarding filling <code>NaN</code> values in a Pandas <code>DataFrame</code> conditionally on the values of non-<code>NaN</code> columns. To illustrate:</p> <pre><code>import numpy as np import pandas as pd print pd.__version__ 0.18.1 df = pd.DataFrame({'a': [1, 0, 0, 0, 1], '...
2
2016-07-28T03:40:46Z
38,642,444
<p>You may set <code>a, b, c</code> columns as a multi-index and use pandas <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html#merging-together-values-within-series-or-dataframe-columns" rel="nofollow"><code>combine_first</code></a>.</p> <p>First, you would need a frame of defaults. In your setting it c...
1
2016-07-28T16:54:26Z
[ "python", "pandas" ]
forward expects 1 arguments (0 given)
38,626,750
<pre><code>from turtle import * from Tkinter import * class TurtleApp: def left(self): self.turtle.right(90) def forward(self): self.turtle.forward(self.step) def right(self): self.turtle.right(90) def backward(self): self.turtle.backward(self.step) ...
0
2016-07-28T03:45:44Z
38,626,866
<p>You need to refer to the <code>forward()</code> method defined in your <code>TurtleApp</code> class, not to the <code>turtle.forward()</code> function defined in the <code>turtle</code> module. The latter is being called because <code>from turtle import *</code> places <code>forward()</code> into the global scope an...
1
2016-07-28T03:58:30Z
[ "python", "tkinter", "typeerror", "turtle-graphics" ]
How can I make a button that access a a file in tkinter?
38,626,775
<p>I've been wanting to make a code that would let me open a directory window and select a csv file from a folder. I wanted to make 4 buttons that would do that, and then one button that if pressed it would run a code and write a new file. </p> <p>I've tried it several ways but so far i got not much this is my code:</...
-1
2016-07-28T03:48:25Z
38,626,799
<p>Something along these lines:</p> <pre><code>from Tkinter import * def getFile(): # Get File Code b = Button(text="click me", command=getFile) b.pack() </code></pre> <p>By using <code>command=getFile</code>, Tk knows to call the <code>getFile</code> method when the button is clicked.</p> <p>Good luck!</p>
1
2016-07-28T03:51:26Z
[ "python", "tkinter", "python-3.5" ]
'float' object has no attribute 'astype'
38,626,789
<p>I am trying to find median values in a column of the dataframe. The median value that I am getting is float but I need it in integer format. </p> <pre><code>c_med = round(df['count'].median().astype(int)) c_med = round(df['count'].median()).astype(int) </code></pre> <p>Both the above types give me this error. If ...
-4
2016-07-28T03:50:27Z
38,626,818
<p>You no longer are in the Pandas API after the <code>round</code> function. </p> <p>You have to cast the value like so </p> <pre><code>c_med = int(round(df['count'].median()) </code></pre> <p>I'm not too familiar with Pandas, but you could try </p> <pre><code>c_med = df['count'].median().round().astype(int) </co...
2
2016-07-28T03:53:30Z
[ "python", "pandas", "median" ]
Calling another method to another class
38,626,810
<p>i newbie on python programming, i so confused, why i cant call another method from another class, </p> <p>this is my source- file : 8_turunan lanjut.py</p> <pre><code>class Karyawan(object): 'untuk kelas karyawan' jml_karyawan = 0 # Class variable # constructor def __init__(self, kid, nama, jabatan): self.ki...
0
2016-07-28T03:52:40Z
38,626,932
<p>Your indentation is off in your class. It should read as follows:</p> <pre><code>class Karyawan(object): 'untuk kelas karyawan' jml_karyawan = 0 # Class variable def __init__(self, kid, nama, jabatan): self.kid = kid self.nama = nama self.jabatan = jabatan Karyawan.jml...
1
2016-07-28T04:06:59Z
[ "python", "class", "methods" ]
Missing lines when writing file with multiprocessing Lock Python
38,626,817
<p>This is my code:</p> <pre><code>from multiprocessing import Pool, Lock from datetime import datetime as dt console_out = "/STDOUT/Console.out" chunksize = 50 lock = Lock() def writer(message): lock.acquire() with open(console_out, 'a') as out: out.write(message) out.flush() lock.releas...
1
2016-07-28T03:53:22Z
38,627,411
<p>Since you're running on Windows, <em>nothing</em> is inherited by worker processes. Each process runs the entire main program "from scratch".</p> <p>In particular, with the code as written every process has its own instance of <code>lock</code>, and these instances have nothing to do with each other. In short, <c...
1
2016-07-28T05:00:21Z
[ "python", "python-multiprocessing" ]
how we can get the result export from Arango DB noSQL
38,626,849
<p>I am very new to arango DB nosql I try to get the exported output of arangoDB with shell commands or arangosh commands but I could not find any way. I know serialization to application can definitely help. However, I am looking for cli methods to get it done. </p> <p>There is a way to use pyarango where we can ostr...
0
2016-07-28T03:56:53Z
38,658,305
<p>ArangoDB offers several ways of scripting. You can use <a href="https://docs.arangodb.com/3.0/HTTP/Database/index.html" rel="nofollow">curl as documented with the HTTP-API</a></p> <pre><code>curl --dump - http://localhost:8529/_api/version?details=true </code></pre> <p>The HTTP-API is what all drivers are based on...
1
2016-07-29T12:00:06Z
[ "python", "shell", "nosql", "arangodb" ]
Any ideas how to parse this payload in python?
38,626,883
<p>I am using MQTT to subscribe to a topic and receive messages. I have this code written so far and it works fine subscribing and all but I am having problems determining a way to parse through the payload that I receive from the MQTT broker. I have been trying to obtain the numerical values that I see in the payload ...
0
2016-07-28T04:00:47Z
38,626,955
<pre><code>node_data = {"payload":"dsgsg","fields":{"pressure":34,"temp":35}} data = json.loads(node_data) Press = data['fields']['Pressure'] print Press </code></pre> <p>you have to give the exact location of the filed. In your case <code>pressure</code> is inside the <code>fields</code> dictionary </p>
1
2016-07-28T04:09:43Z
[ "python", "json", "parsing", "data-structures", "iot" ]
Any ideas how to parse this payload in python?
38,626,883
<p>I am using MQTT to subscribe to a topic and receive messages. I have this code written so far and it works fine subscribing and all but I am having problems determining a way to parse through the payload that I receive from the MQTT broker. I have been trying to obtain the numerical values that I see in the payload ...
0
2016-07-28T04:00:47Z
38,628,695
<p>So after a few hours of scratching my head and 'code-ing' away, I managed to achieve my goal. I am not sure if it is the 'prettiest' way or if it's even the best way to do it but here is what I figured out: I was dealing with a 'Dictionary' and I had to select the appropriate key-name 'fields'. This would then enabl...
0
2016-07-28T06:33:41Z
[ "python", "json", "parsing", "data-structures", "iot" ]
Make JSON Object in python
38,626,933
<p>I want make JSON Object in python like this :</p> <pre><code>{ "to":["admin"], "content":{ "message":"everything", "command":0, "date":["tag1",...,"tagn"] }, "time":"YYYYMMDDhhmmss" } </code></pre> <p>This is my code in python :</p> <pre><code>import json cont = [{"mes...
1
2016-07-28T04:07:07Z
38,626,974
<h1>Nested <code>json</code> content</h1> <p><code>json_content</code> is a <code>json</code> string representation returned by the first call to <code>json.dumps()</code>, this is why you get a string version of the content in the second call to <code>json.dumps()</code>. You need to call <code>json.dumps()</code> o...
0
2016-07-28T04:11:30Z
[ "python", "jsonobject" ]