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
returning the element in one list based on the index and maximum value of an element in another list
38,953,807
<p>I have a list of lists which I converted into a numpy array:</p> <pre><code>lsts = ([[1,2,3], ['a','b','a']], [[4,5,6,7], ['a','a','b','b']], [[1,2,3],['b','a','b']]) np_lsts = np.array(lsts) </code></pre> <p>I want to return the largest element in the first list where a 'b' occurs in the second ...
0
2016-08-15T10:58:47Z
38,954,333
<p>This should be a lot more efficient than the current solutions if the sublists have a lot of elements, since it is vectorized over those sublists:</p> <pre><code>import numpy_indexed as npi results = [npi.group_by(k).max(v) for v,k in lsts] </code></pre>
0
2016-08-15T11:37:10Z
[ "python", "numpy" ]
Azure Bottle web app and numpy
38,953,826
<p>after publishing Bottle web app where I use NumPy library it says</p> <blockquote> <p>The page cannot be displayed because an internal server error has occurred.</p> </blockquote> <p>in local host it works. I used virtual environment as described in </p> <blockquote> <p><a href="http://stackoverflow.com/quest...
-1
2016-08-15T11:00:37Z
38,967,461
<p>@Mr.Green, Per my experience, first, my suggestion is that you can refer to the tutorial <a href="https://azure.microsoft.com/en-us/documentation/articles/web-sites-python-create-deploy-bottle-app/" rel="nofollow">Creating web apps with Bottle in Azure</a> to be sure your webapp with Bottle has been deployed correct...
0
2016-08-16T05:51:35Z
[ "python", "azure", "numpy", "azure-web-sites", "bottle" ]
Failed to coerce slice entry of type TensorVariable to integer
38,953,854
<p>I was following the code on one of the books about deep learning, where the author uses theano as a library for this kind of networks. When I try to run the code: </p> <pre><code>i = T.lscalar() # mini-batch index train_mb = theano.function( [i], cost, updates=updates, givens={ ...
0
2016-08-15T11:02:46Z
39,064,585
<p>it looks like the same problem as I did,<br> please visit <a href="http://stackoverflow.com/a/39064543/6740140">http://stackoverflow.com/a/39064543/6740140</a><br> Hope it can help you.</p>
0
2016-08-21T13:13:26Z
[ "python", "theano" ]
pip install from specific setup.py
38,953,855
<p>I created a python 3.3 app on RedHat's Openshift cloud service. By default it has setup.py for my project. I'm learning Udemy course called "Build a SaaS app with Flask" (<a href="https://github.com/nickjj/build-a-saas-app-with-flask" rel="nofollow">source code</a>) Now I wanted to use python-click, as recommended ...
1
2016-08-15T11:02:52Z
38,957,066
<p>it seems that you can't do anything about it :-) - It's hard coded in pip source code :-)</p> <p>if you try to use this command: <code>pip install -e .</code></p> <p>it will call a method named <a href="https://github.com/pypa/pip/blob/master/pip/req/req_install.py#L1115" rel="nofollow">parse_editable</a> which wi...
1
2016-08-15T14:28:33Z
[ "python", "pip", "setup.py" ]
Python TypeError: sequence item 0: expected string, list found in message body of email code
38,953,859
<p>I am trying to send some data in my email code in the body part of the email message. I am calling 2 functions which returns a list. I would like to include these into the email body part of the message. I am getting the error TypeError: sequence item 0: expected string</p> <pre><code> Traceback (most recent cal...
-1
2016-08-15T11:03:02Z
38,954,045
<p>Your function extract_testcases_from_report_htmltestrunner returns a tuple, not a single value. So basically, you might end up with something like this:</p> <pre><code>'\n'.join([('a','b'), ('c', 'd')] </code></pre> <p>And this does simply not work in python.</p>
0
2016-08-15T11:15:21Z
[ "python", "python-2.7" ]
Python TypeError: sequence item 0: expected string, list found in message body of email code
38,953,859
<p>I am trying to send some data in my email code in the body part of the email message. I am calling 2 functions which returns a list. I would like to include these into the email body part of the message. I am getting the error TypeError: sequence item 0: expected string</p> <pre><code> Traceback (most recent cal...
-1
2016-08-15T11:03:02Z
38,954,071
<p>Both <code>extract_only_header_from_summary_from_report_htmltestrunner()</code> and <code>extract_testcases_from_report_htmltestrunner()</code> produce sequences of sequences (the first a list of lists, the other a generator yielding tuples). Neither are suitable for <code>str.join()</code>, which can only take a se...
2
2016-08-15T11:17:39Z
[ "python", "python-2.7" ]
List and Numpy array in Python
38,953,903
<p>I was trying to hot-encode data. Data is list of vocabulary_size = 17005207.</p> <p>To hot-encode, I made a list of inputs of num_labels = 100. Following code:</p> <pre><code>inputs = [] for i in range(vocabulary_size): inputs.append(np.arange(num_labels) == data[i]).astype(np.float32) </code></pre> <p>Throws m...
1
2016-08-15T11:06:07Z
38,954,023
<p>Not sure whether I've understood correctly what you're asking for, but if what you want is a oneliner, you could transform you're already working code into this:</p> <pre><code>inputs = np.array([np.arange(num_labels) == data[i] for i in range(vocabulary_size)], dtype=np.float32) </code></pre>
0
2016-08-15T11:14:13Z
[ "python", "numpy" ]
Identify 90'degree projection between two points
38,953,938
<p>In <code>python</code> I have two points, A and B in 2D. </p> <p>I have a user who is traveling between these 2 points (now a vector?). </p> <p>These points are arbitrarily far apart.</p> <p>I want to calculate 2 projections(?) at half way between these 2 points 100m away from the original line, one projection at...
0
2016-08-15T11:08:15Z
38,954,994
<p>Consider the direction vector from A to B:</p> <pre><code>ab = (x2 - x, y2 - y) </code></pre> <p>Then, the vector that is orthogonal to this line is:</p> <pre><code>orth = (y - y2, x2 - x) </code></pre> <p>The length of this vector (and of the direction vector) is:</p> <pre><code>l = sqrt((x2-x)^2 + (y2-y)^2) <...
1
2016-08-15T12:22:25Z
[ "python", "math", "vector", "projection" ]
Pk fields always ends up in resulting query GROUP BY clause
38,953,962
<p>I have my model hierarchy defined as follows:</p> <pre><code>class Meal(models.Model): created_at = models.DateTimeField(auto_now_add=True) discount_price = models.DecimalField(blank=False, null=False, decimal_places=2, max_digits=4) normal_price = models.DecimalField(blank=True, null=True, decimal_plac...
0
2016-08-15T11:09:36Z
38,969,218
<p>To make it work I had to do the following:</p> <pre><code>qs.filter(created_at__range=[date_start, date_end])\ .annotate(created_at_date=TruncDate('created_at'))\ .values('created_at_date')\ .annotate(price=Sum(F('items__meal__discount_price') * F('items__amount'), output_field=Decima...
0
2016-08-16T07:43:48Z
[ "python", "sql", "django", "django-orm", "postgresql-9.3" ]
Python - find closest position and value
38,954,251
<p>I m trying to find the closest point for a couple X and Y given as to access to its values. In my case, in X directions (np.arrange(0,X.max(),1), i would like to extract the closest values from Y = 0 to obtain its values in "values array" :</p> <pre><code>import numpy as np import matplotlib.pyplot as plt #My coord...
-1
2016-08-15T11:30:05Z
38,954,411
<p>You can use something faster than a <code>for</code> loop:</p> <pre><code>import numpy as np def find_nearest(array, value): ''' Find nearest value is an array ''' idx = (np.abs(array-value)).argmin() return idx haystack = np.arange(10) needle = 5.8 idf = find_nearest(haystack, needle) print haystack...
2
2016-08-15T11:42:07Z
[ "python", "numpy", "indexing" ]
Match everything until optional string (Python regex)
38,954,311
<p>I've pounded my head against this issue, and it just seems like I am missing something uber-trivial, so apologies in advance. I have a url, which may, or may not, contain some POST values. I want to match the the entire url UNTIL this optional part (not inclusive). So for example:</p> <pre><code>import re myurl = r...
1
2016-08-15T11:35:26Z
38,954,408
<p>you may want to take a look at <a href="https://docs.python.org/2/library/urlparse.html" rel="nofollow">https://docs.python.org/2/library/urlparse.html</a></p> <p>the order in which parameters are passed may change:</p> <pre><code>?pageNum=41&amp;cat=ThisPartChanges </code></pre>
3
2016-08-15T11:41:43Z
[ "python", "regex" ]
Match everything until optional string (Python regex)
38,954,311
<p>I've pounded my head against this issue, and it just seems like I am missing something uber-trivial, so apologies in advance. I have a url, which may, or may not, contain some POST values. I want to match the the entire url UNTIL this optional part (not inclusive). So for example:</p> <pre><code>import re myurl = r...
1
2016-08-15T11:35:26Z
38,954,476
<p>I'd recommend you to avoid regular expressions when it comes to url parsing, use this <a href="https://docs.python.org/2/library/urlparse.html" rel="nofollow">module</a> instead, here's a working example for your problem:</p> <pre><code>import urlparse myurl = 'http://myAddress.com/index.aspx?cat=ThisPartChanges&a...
2
2016-08-15T11:46:56Z
[ "python", "regex" ]
Match everything until optional string (Python regex)
38,954,311
<p>I've pounded my head against this issue, and it just seems like I am missing something uber-trivial, so apologies in advance. I have a url, which may, or may not, contain some POST values. I want to match the the entire url UNTIL this optional part (not inclusive). So for example:</p> <pre><code>import re myurl = r...
1
2016-08-15T11:35:26Z
38,954,483
<p>In your case, this could do:</p> <pre><code>^[^&amp;]+ </code></pre> <p>More robust:</p> <pre><code>^[^?]+\?cat=[^&amp;]+ </code></pre> <p><strong>Example:</strong></p> <pre><code>In [40]: s = 'http://myAddress.com/index.aspx?cat=ThisPartChanges&amp;pageNum=41' In [41]: re.search(r'^[^&amp;]+', s).group() Out[...
1
2016-08-15T11:47:18Z
[ "python", "regex" ]
How to make django form field without validation in administration
38,954,322
<p>I am learning django, currently I am working on django 1.9. I have made a model named <code>experience</code>, which contains:</p> <pre><code>from __future__ import unicode_literals from django.db import models # Create your models here. class Experience(models.Model): designation = models.CharField(max_len...
1
2016-08-15T11:36:09Z
38,954,378
<p>Simply change it to <code>ending_date = models.DateField(null=True, blank=True)</code></p>
1
2016-08-15T11:39:33Z
[ "python", "django", "django-models", "django-forms", "django-admin" ]
Python loop inserting last row only in cassandra
38,954,357
<p>I typed a small demo loop in order to insert random values in Cassandra but only the last record is persisted into the database. I am using cassandra-driver from datastax and its object modeling lib. Cassandra version is 3.7 and Python 3.4. Any idea what I am doing wrong?</p> <pre><code>#!/usr/bin/env python impor...
0
2016-08-15T11:38:21Z
38,954,463
<p>You need to use the method save.</p> <pre><code>... row = TestTable(type=type, value=value) row.save() ... </code></pre> <p><a href="http://cqlengine.readthedocs.io/en/latest/topics/models.html#cqlengine.models.Model.save" rel="nofollow">http://cqlengine.readthedocs.io/en/latest/topics/models.html#cqlengine.models...
0
2016-08-15T11:46:11Z
[ "python", "cassandra" ]
Python loop inserting last row only in cassandra
38,954,357
<p>I typed a small demo loop in order to insert random values in Cassandra but only the last record is persisted into the database. I am using cassandra-driver from datastax and its object modeling lib. Cassandra version is 3.7 and Python 3.4. Any idea what I am doing wrong?</p> <pre><code>#!/usr/bin/env python impor...
0
2016-08-15T11:38:21Z
38,963,611
<p>The problem is in the definition of the key column:</p> <pre><code>key = columns.UUID(primary_key=True, default=uuid.uuid4()) </code></pre> <p>For the default value it's going to call the <code>uuid.uuid4</code> function once and use that result as the default for all future inserts. Because that's your primary ke...
1
2016-08-15T21:51:33Z
[ "python", "cassandra" ]
Error when using round() for a variable
38,954,362
<p>I never coded before and started with Python-3.5 a few days ago. After some exercise i try to play around myself. Last time I wanted to create a script which stores the input as a variable and rounds it to three decimals. Unfortunately I get an error when I try to do that:</p> <pre><code>round (spam, 3) TypeError: ...
0
2016-08-15T11:38:27Z
38,954,390
<p>The difference is that in the second case you supply the value of <code>spam</code> using a float literal (that is, <code>spam = 3.666666</code>) while, in the first case you get it from calling <code>input()</code> which isn't exactly the same.</p> <p>The function <code>input()</code> returns a <code>str</code> i...
2
2016-08-15T11:40:20Z
[ "python", "python-3.x", "variables", "rounding", "typeerror" ]
Python SQLite Return Default String For Non-Existent Row
38,954,369
<p>I have a DB with ID/Topic/Definition columns. When a select query is made, with possibly hundreds of parameters, I would like the fetchall call to also return the topic of any non-existent rows with a default text (i.e. "Not Found").</p> <p>I realize this could be done in a loop, but that would query the DB every ...
0
2016-08-15T11:39:05Z
38,955,706
<p>To get data like <code>wd2</code> out of a query, such data must be in the database in the first place. You could put it into a temporary table, or use a <a href="http://www.sqlite.org/lang_with.html" rel="nofollow">common table expression</a>.</p> <p>To include rows without a match, use an <a href="https://en.wiki...
0
2016-08-15T13:09:11Z
[ "python", "sqlite" ]
Defining 500 intial random positions of an rotating object in 2-D by Python
38,954,401
<p>I have edited my question. Now I don't want to use loop in my function. The function is for defining initial position of an rotating object in 2-D. I would like to get the output format like this: </p> <p><code>theta1 theta2 theta3 phi1 phi2 phi3 eta1 eta2 eta3</code></p> <p>The definition of e inside the functi...
0
2016-08-15T11:41:10Z
38,954,512
<p>So if we make your function return a tuple:</p> <pre><code>def randpos(): theta = 2*pi* rand()-pi if rand() &lt; 12: if phi &lt; pi: phi += pi else: phi -= pi eta = 2*pi*rand()-pi return (theta, phi, eta) </code></pre> <p>then call it 500 times and pu...
0
2016-08-15T11:49:11Z
[ "python", "numpy", "rotation", "2d" ]
Defining 500 intial random positions of an rotating object in 2-D by Python
38,954,401
<p>I have edited my question. Now I don't want to use loop in my function. The function is for defining initial position of an rotating object in 2-D. I would like to get the output format like this: </p> <p><code>theta1 theta2 theta3 phi1 phi2 phi3 eta1 eta2 eta3</code></p> <p>The definition of e inside the functi...
0
2016-08-15T11:41:10Z
38,954,542
<p>you can use list comprehension for this, for your case:</p> <pre><code>def randpos(N=500): # your function code here ... desired = 500 init_positions = [randpos() for i in range(desired)] </code></pre>
0
2016-08-15T11:50:43Z
[ "python", "numpy", "rotation", "2d" ]
Defining 500 intial random positions of an rotating object in 2-D by Python
38,954,401
<p>I have edited my question. Now I don't want to use loop in my function. The function is for defining initial position of an rotating object in 2-D. I would like to get the output format like this: </p> <p><code>theta1 theta2 theta3 phi1 phi2 phi3 eta1 eta2 eta3</code></p> <p>The definition of e inside the functi...
0
2016-08-15T11:41:10Z
38,954,677
<p>So, you've defined your function f(x) called randpos, it seems this function doesn't accept any input. N is the variable you'll use to iterate over this function, you got few options here:</p> <p>You can store your values in some list like this:</p> <pre><code>N = 10 random_positions = [randpos() for i in range(N)...
0
2016-08-15T11:59:16Z
[ "python", "numpy", "rotation", "2d" ]
Defining 500 intial random positions of an rotating object in 2-D by Python
38,954,401
<p>I have edited my question. Now I don't want to use loop in my function. The function is for defining initial position of an rotating object in 2-D. I would like to get the output format like this: </p> <p><code>theta1 theta2 theta3 phi1 phi2 phi3 eta1 eta2 eta3</code></p> <p>The definition of e inside the functi...
0
2016-08-15T11:41:10Z
38,958,341
<p>What about using a random numpy array ?</p> <p>Something like that:</p> <pre><code>import numpy as np N=500 #we create a random array 3xN r = np.random.rand(3,N) #tetha is row 0, phi row 1, eta row 2 #we apply the same treatment that is in the question to get the right range #also note that np.pi is just a predef...
0
2016-08-15T15:44:47Z
[ "python", "numpy", "rotation", "2d" ]
Cache busting with Django
38,954,505
<p>I'm working on a website built with Django.<br> When I'm doing updates on the static files, the users have to hard refresh the website to get the latest version.<br> I'm using a CDN server to deliver my static files so using the built-in static storage from Django.<br> I don't know about the best practices but my id...
0
2016-08-15T11:48:47Z
38,954,600
<p>Django's built-in contrib.staticfiles app already does this for you; see <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/staticfiles/#manifeststaticfilesstorage" rel="nofollow">ManifestStaticFilesStorage</a> and <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/staticfiles/cachedstaticfilessto...
0
2016-08-15T11:54:14Z
[ "python", "django", "caching", "static", "cdn" ]
Cache busting with Django
38,954,505
<p>I'm working on a website built with Django.<br> When I'm doing updates on the static files, the users have to hard refresh the website to get the latest version.<br> I'm using a CDN server to deliver my static files so using the built-in static storage from Django.<br> I don't know about the best practices but my id...
0
2016-08-15T11:48:47Z
38,956,967
<p>Here's my work around : </p> <p>On deployment (from a bash script), I get the shasum of my css style.<br> I put this variable inside the environment. </p> <p>I have a context processor for the template engine that will read from the environment.</p>
0
2016-08-15T14:23:55Z
[ "python", "django", "caching", "static", "cdn" ]
How to have catagorical factor variables in python
38,954,525
<pre><code> age income student credit_rating Class_buys_computer 0 youth high no fair no 1 youth high no excellent no 2 middle_aged high no fair yes 3 senior medium no fair yes 4 senior low yes fair yes 5 senior low yes excellent no 6 ...
1
2016-08-15T11:49:37Z
38,954,579
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow"><code>astype</code></a> with parameter <code>category</code>:</p> <pre><code>cols = ['age','income','student'] for col in cols: df[col] = df[col].astype('category') print (df.dtypes) age ...
1
2016-08-15T11:52:58Z
[ "python", "pandas", "dataframe", "categorical-data" ]
Tensorflow: How can I extract image features from a specific layer of a pre-trained CNN?
38,954,598
<p>I have a pre-trained CNN model as a .pb file. I can load the model and extract the final vector from the last layer for all images. Now I would like to extract the vector coming from a specific layer and not the final for my images. I am using an import_graph_def function to load the model and I don't know the names...
1
2016-08-15T11:54:09Z
38,958,002
<p>One approach other than what was mentioned by Peter Hawkins, to use tf.Graph.get_operations() in the comments is to use tensorboard to find the name of the layer you would like to extract from. </p> <p>From there you can just use </p> <pre><code>graph.get_tensor_by_name("import/layer_name") </code></pre> <p>to ex...
1
2016-08-15T15:21:40Z
[ "python", "machine-learning", "neural-network", "tensorflow", "conv-neural-network" ]
functional field odoo type float , new api
38,954,686
<p>I'm trying to make an operation * on a field , i have tried functional fields but it didn't work , now i'm trying this @api.depends api , does it work with odoo 8 ? it still not work </p> <pre><code>class fleuret(osv.Model): _inherit = "mrp.bom.line" _columns = { 'unit_price' : fi...
1
2016-08-15T12:00:04Z
38,954,894
<pre><code>from openerp import models,fields,api import openerp.addons.decimal_precision as dp class fleuret(models.Model) _inherit = "mrp.bom.line" @api.one @api.depends('product_qty') def _compute_price(self): self.amount =(self.unit_price * self.product_qty) unit_price = fields....
2
2016-08-15T12:15:13Z
[ "python", "api", "openerp", "field", "odoo-8" ]
functional field odoo type float , new api
38,954,686
<p>I'm trying to make an operation * on a field , i have tried functional fields but it didn't work , now i'm trying this @api.depends api , does it work with odoo 8 ? it still not work </p> <pre><code>class fleuret(osv.Model): _inherit = "mrp.bom.line" _columns = { 'unit_price' : fi...
1
2016-08-15T12:00:04Z
38,955,268
<pre class="lang-py prettyprint-override"><code>from openerp import models, fields, api import openerp.addons.decimal_precision as dp class fleuret(models.Model) _inherit = "mrp.bom.line" unit_price = fields.Float( string='unit price', related='product_id.lst_price', store=True, readonly=True...
0
2016-08-15T12:40:19Z
[ "python", "api", "openerp", "field", "odoo-8" ]
functional field odoo type float , new api
38,954,686
<p>I'm trying to make an operation * on a field , i have tried functional fields but it didn't work , now i'm trying this @api.depends api , does it work with odoo 8 ? it still not work </p> <pre><code>class fleuret(osv.Model): _inherit = "mrp.bom.line" _columns = { 'unit_price' : fi...
1
2016-08-15T12:00:04Z
38,955,338
<pre><code>from openerp.osv import osv, fields from openerp import models,api, _ import openerp.addons.decimal_precision as dp class fleuret(osv.Model): _inherit = "mrp.bom.line" _columns = { 'unit_price' : fields.float(string='unit price', related='product_id.lst_price', store=True, ...
1
2016-08-15T12:44:00Z
[ "python", "api", "openerp", "field", "odoo-8" ]
Python request.py syntax error
38,954,852
<p>I am new to Python 3.4.5 which I am learning online by watching videos with some good knowledge of C. I am trying to download an image via Python which I am unable to do because of this error.</p> <p>Code:</p> <pre>import random import urllib.request def img(url): full='name'+'.jpeg' urllib.request.urlretrie...
0
2016-08-15T07:09:56Z
38,954,853
<p>Try,</p> <p>def img(url): full='name'+'.jpeg';urllib.urlretrieve(url,full)</p> <p>urllib.request does not exist in python 2.x, which seems to be your case<br> so don't try to import that in second line of your code</p> <p>plus you made a type(forgot semicolon) which works as a statement separator while writing in...
0
2016-08-15T07:22:39Z
[ "python" ]
PyDev debugging: do not open "_pydev_execfile" at the end
38,955,017
<p>I am new to both Python and Eclipse.</p> <p>I am debugging a module file with Eclipse/PyDev. When I click "Step over" or "Step return" at the last line of the file, Eclipse opens the file "_pydev_execfile" where I have to click "Step over" or "Step return" again, before the debugging is terminated. </p> <p>Does th...
9
2016-08-15T12:23:34Z
39,012,273
<p>In general, you can put <code># @DontTrace</code> at the end of lines that define functions to ignore these functions in the traceback. </p> <p>In the particular case described in the question, this works as follows: Change the definition of execfile() in _pydev_execfile.py to:</p> <pre><code>def execfile(file, gl...
2
2016-08-18T07:28:44Z
[ "python", "eclipse", "debugging", "pydev" ]
cannot access simple http server
38,955,047
<p>I created a simple Simple http server using </p> <p>python -m SimpleHTTPServer</p> <p>I can access it via my laptop or through my phone but when it is acessed through another location it shows Webpage not available or when I try to access it through my browser's VPN it also gives an ERROR: Requested url could not ...
-2
2016-08-15T12:25:25Z
38,955,088
<p>IPv4 addresses starting with 192.168 are part of the local network block. You cannot access them outside your local network.</p> <p>See also: <a href="http://xkcd.com/742" rel="nofollow">http://xkcd.com/742</a></p>
0
2016-08-15T12:27:54Z
[ "python", "simplehttpserver" ]
Downloading thousands of files using python
38,955,052
<p>I'm trying to download about 500k small csv files (5kb-1mb) from a list of urls but it is been taking too long to get this done. With the code bellow, I am lucky if I get 10k files a day.</p> <p>I have tried using the multiprocessing package and a pool to download multiple files simultaneously. This seems to be eff...
0
2016-08-15T12:25:39Z
38,955,902
<p>You are re-coding the wheel!</p> <p>How about that :</p> <pre><code>parallel -a urls.file axel </code></pre> <p>Of course you'll have to install <code>parallel</code> and <code>axel</code> for your distribution.</p> <p><code>axel</code> is a multithreaded counterpart to <code>wget</code></p> <p><code>parrallel<...
-1
2016-08-15T13:21:47Z
[ "python", "web-scraping", "urllib2", "python-multiprocessing" ]
numpy.subtract performs subtraction wrong on 1-dimensional arrays
38,955,074
<blockquote> <p>I read the post <a href="http://stackoverflow.com/questions/588004/is-floating-point-math-broken">is-floating-point-math-broken</a> and get Why it happens, but I couldn't find a solution that could help me..</p> <p>How can I do the correct subtraction?</p> </blockquote> <p>Python version 2.6.6...
-1
2016-08-15T12:27:07Z
38,959,017
<p>You might add your Python and numpy versions to the question.</p> <p>Differences can arise from <code>np.float32</code> v <code>np.float64</code> dtype, the default Python float type, as well as display standards. <code>numpy</code> uses different display rounding than the underlying Python.</p> <p>The subtractio...
0
2016-08-15T16:27:45Z
[ "python", "arrays", "numpy" ]
Python replace oneliner without using regexp
38,955,140
<p>I have my code here:</p> <pre><code>a = u"\n".join(my_array).replace(u"\n\n", u"\n") </code></pre> <p>The problem is that if there are <code>"\n\n\n\n"</code> you are left with <code>"\n\n"</code> and I just want <strong>one</strong> <code>"\n"</code></p> <p>So I've come up with:</p> <pre><code>a = u"\n".join(my...
1
2016-08-15T12:31:11Z
38,955,240
<p>perhaps this can help:</p> <pre><code>u"\n".join(s.replace(u'\n', '') for s in my_array)) </code></pre>
0
2016-08-15T12:38:36Z
[ "python" ]
Python replace oneliner without using regexp
38,955,140
<p>I have my code here:</p> <pre><code>a = u"\n".join(my_array).replace(u"\n\n", u"\n") </code></pre> <p>The problem is that if there are <code>"\n\n\n\n"</code> you are left with <code>"\n\n"</code> and I just want <strong>one</strong> <code>"\n"</code></p> <p>So I've come up with:</p> <pre><code>a = u"\n".join(my...
1
2016-08-15T12:31:11Z
38,955,503
<p>If you really want to do this in one line and without using regular expression, one way to reduce all the sequences of multiple <code>\n</code> to single <code>\n</code> would to be first <code>split</code> by <code>\n</code> and then <code>join</code> all the non-empty segments by a single <code>\n</code>.</p> <pr...
3
2016-08-15T12:54:29Z
[ "python" ]
Python replace oneliner without using regexp
38,955,140
<p>I have my code here:</p> <pre><code>a = u"\n".join(my_array).replace(u"\n\n", u"\n") </code></pre> <p>The problem is that if there are <code>"\n\n\n\n"</code> you are left with <code>"\n\n"</code> and I just want <strong>one</strong> <code>"\n"</code></p> <p>So I've come up with:</p> <pre><code>a = u"\n".join(my...
1
2016-08-15T12:31:11Z
38,955,521
<p>To convert sequences of newlines to single newlines you can split the string on newlines and then filter out the empty strings before re-joining. Eg,</p> <pre><code>mystring = u"this\n\nis a\ntest string\n\nwith embedded\n\n\nnewlines\n" a = u'\n'.join(filter(None, mystring.split(u'\n'))) print '{0!r}\n{1!r}'.forma...
2
2016-08-15T12:55:51Z
[ "python" ]
Python replace oneliner without using regexp
38,955,140
<p>I have my code here:</p> <pre><code>a = u"\n".join(my_array).replace(u"\n\n", u"\n") </code></pre> <p>The problem is that if there are <code>"\n\n\n\n"</code> you are left with <code>"\n\n"</code> and I just want <strong>one</strong> <code>"\n"</code></p> <p>So I've come up with:</p> <pre><code>a = u"\n".join(my...
1
2016-08-15T12:31:11Z
38,955,712
<p>Using <code>reduce</code> should work:</p> <pre><code>reduce(lambda x,y: (x+y).replace('\n\n', '\n'), x) </code></pre> <p>However, regular expressions would be more elegant:</p> <pre><code>re.sub('\n+', '\n', x) </code></pre>
1
2016-08-15T13:09:48Z
[ "python" ]
Is there a way to register Jupyter Notebook Progress Bar Widget instead of Text Progress Bar in Dask/Distributed?
38,955,163
<p>I know that there is a way to globally register <code>dask.diagnostics.ProgressBar</code>, and while it is quite nice, it breaks my cell outputs. I have also seen a nice <code>distributed.diagnostics.progress</code> function, which can present the execution progress with Jupyter Notebook Progress Bar widget, but it ...
2
2016-08-15T12:32:43Z
38,955,284
<p>The short answer today is "no". This is possible to build, but would require some effort on your part.</p> <p>The <code>distributed.diagnostics.progress</code> function operates in the event loop, and so it stops updating when notebook is busy running a cell. There is no way to both have a synchronous dask.comput...
2
2016-08-15T12:41:15Z
[ "python", "dask" ]
reading names with genfromtxt missing hyphen
38,955,168
<p>I am trying to read the following file and I tried to use numpy to load data:</p> <pre><code>#Frame HIE_21@O-PHE_32@N-H THR_20@O-PHE_32@N-H HIE_21@ND1-PHE_32@N-H 1 0 0 0 2 1 0 0 3 ...
0
2016-08-15T12:33:06Z
38,955,478
<p>Use the argument <code>deletechars=''</code>:</p> <pre><code>In [15]: f1 = np.genfromtxt('hyphens.txt', dtype=None, names=True, deletechars='') In [16]: f1 Out[16]: array([(1, 0, 0, 0), (2, 1, 0, 0), (3, 0, 0, 0), (4, 0, 0, 0), (5, 0, 0, 0)], dtype=[('Frame', '&lt;i8'), ('HIE_21@O-PHE_32@N-H', '&lt;i8'), (...
2
2016-08-15T12:52:49Z
[ "python", "numpy", "names", "genfromtxt" ]
top n columns with highest value in each pandas dataframe row
38,955,182
<p>I have the following dataframe:</p> <pre><code> id p1 p2 p3 p4 1 0 9 1 4 2 0 2 3 4 3 1 3 10 7 4 1 5 3 1 5 2 3 7 10 </code></pre> <p>I need to reshape the data frame in a way that for each id it will have the top 3 columns with the highest values. The result woul...
0
2016-08-15T12:33:56Z
38,955,314
<p>You can use:</p> <pre><code>df = df.set_index('id').apply(lambda x: pd.Series(x.sort_values(ascending=False) .iloc[:3].index, index=['top1','top2','top3']), axis=1).reset_index() print (df) id top1 top2 top3 0 1 p2 p4 p3 1 2 p4 p3 p2 2 3 p3 p4 p2 3 4 p2 p3 p4 4 5 ...
2
2016-08-15T12:42:43Z
[ "python", "pandas", "dataframe", "data-analysis" ]
top n columns with highest value in each pandas dataframe row
38,955,182
<p>I have the following dataframe:</p> <pre><code> id p1 p2 p3 p4 1 0 9 1 4 2 0 2 3 4 3 1 3 10 7 4 1 5 3 1 5 2 3 7 10 </code></pre> <p>I need to reshape the data frame in a way that for each id it will have the top 3 columns with the highest values. The result woul...
0
2016-08-15T12:33:56Z
38,955,365
<p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html" rel="nofollow"><code>np.argsort</code></a> to find the indices of the <em>n</em> largest items for each row:</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame({'id': [1, 2, 3, 4, 5], 'p1': [0, 0, 1...
6
2016-08-15T12:46:05Z
[ "python", "pandas", "dataframe", "data-analysis" ]
Pass the QAction object which calls triggered.connect() as a parameter in the function that is triggered after i click on QAction
38,955,281
<p>i am creating list of QAction objects using for loop like this:</p> <pre><code>class some_class: self.tabs = [] for self.i in range(0,10): self.tabs[self.i] = QtGui.QAction("New", self) self.tabs[self.i].triggered.connect(self.some_function) def some_function(self): print self.i </code></pre> <...
0
2016-08-15T12:41:09Z
38,955,762
<p>Cache the index as a default argument:</p> <pre><code>for index in range(0, 10): action = QtGui.QAction("New", self) action.triggered.connect( lambda checked, index=index: self.some_function(index)) self.tabs.append(action) ... def some_function(self, index): action = self.tabs[index] ...
1
2016-08-15T13:13:23Z
[ "python", "python-2.7", "pyqt4", "signals-slots" ]
Python append json object in file, guard if object does not exist
38,955,307
<p>I am reading in a json file using python, and then appending in an array within an object, the shape of this being </p> <pre><code>"additional_info": {"other_names": ["12.13"] </code></pre> <p>I am appending the array as follows:</p> <pre><code>data["additional_info"]["other_names"].append('13.9') with open('json...
0
2016-08-15T12:42:25Z
38,955,538
<p>Usually I would use nested <code>try-except</code> to check for each missing key or a <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a>, but in this case I think I would go with 2 <code>if</code> statements for the sake of simplicity:</p>...
1
2016-08-15T12:57:03Z
[ "python", "json" ]
Function works once, not the second time around
38,955,325
<p>in my program I start with this...</p> <pre><code>def start(): acu.cont acu.php input('Welcome... ( Press Enter )') acga.Game.game() start() </code></pre> <p>This works fine and start the game normally the first time around. When I finish the game I have this..</p> <pre><code>again = '1' print...
-2
2016-08-15T12:43:26Z
38,955,463
<p>Try changing the <code>while</code> in</p> <pre><code>while again == '1': </code></pre> <p>to <code>if</code>.</p>
-3
2016-08-15T12:52:04Z
[ "python", "python-3.x" ]
Property behaviour (getter and setter) for a column, instead of normal attribute behaviour
38,955,334
<p>Does SQLAlchemy support something like this:</p> <pre><code>class Character(Base): __tablename__ = 'character' id = Column(Integer, primary_key=True) level = Column(Integer) @ColumnProperty(Integer) def xp(self): return self._xp @xp.setter def xp(self, value): self._xp = value ...
0
2016-08-15T12:43:44Z
38,955,426
<p>Just add a <code>_xp</code> column definition, that maps to the <code>xp</code> column in the table, and use a regular <code>@property</code> object to implement your setter logic:</p> <pre><code>class Character(Base): __tablename__ = 'character' id = Column(Integer, primary_key=True) level = Column(Int...
2
2016-08-15T12:49:22Z
[ "python", "python-3.x", "properties", "sqlalchemy" ]
Select a particular element in a webpage from list using selenium python
38,955,339
<p>I am trying to automate through selenium python to select a particular element from a list of element in a webpage. That is in the first page of the webpage I am selecting one list item from 5 items displayed, later I need to deselect them in the next page of the website where all the five numbers are listed. How ca...
0
2016-08-15T12:44:01Z
38,957,011
<p>I'm not sure which webdriver you are using, but the snippet I'm including here has worked for me with the Firefox, Chrome, and CasperJS drivers.</p> <p>To click an option in a drop down list, you'll want to use something like the following, using one of your XPATH attributes above:</p> <pre><code>opt_button = driv...
1
2016-08-15T14:26:01Z
[ "python", "python-2.7", "selenium", "selenium-webdriver" ]
Tricky wide to long conversion in Pandas with multi-index columns
38,955,407
<p>I have a dataframe that looks like</p> <pre><code>stock date type1 type2 volume_A qtit_A volume_B qtit_B 'ABC' '2013-01-01' 1 2 1000 5 2500 6 'ABC' '2013-01-02' 1 3 4000 10 2500 0 </code></pre> <p>and I would like to reshape it as follows:</p> <pre><code>stock ...
0
2016-08-15T12:48:05Z
38,955,534
<pre><code>pd.lreshape(df.assign(type_A=['A']*len(df), type_B=['B']*len(df)), {'volume': ['volume_A', 'volume_B'], 'qtit': ['qtit_A', 'qtit_B'], 'type': ['type_A', 'type_B']}) Out: date stock type1 type2 qtit type volume 0 '2013-01-01' 'ABC' 1 2 ...
3
2016-08-15T12:56:39Z
[ "python", "pandas" ]
Tricky wide to long conversion in Pandas with multi-index columns
38,955,407
<p>I have a dataframe that looks like</p> <pre><code>stock date type1 type2 volume_A qtit_A volume_B qtit_B 'ABC' '2013-01-01' 1 2 1000 5 2500 6 'ABC' '2013-01-02' 1 3 4000 10 2500 0 </code></pre> <p>and I would like to reshape it as follows:</p> <pre><code>stock ...
0
2016-08-15T12:48:05Z
38,955,716
<p>If you set <code>['date','stock','type1','type2']</code> as the <code>index</code>, then you can split the remaining column labels on <code>'_'</code>, create a MultiIndex from these tuples, and then move the <code>A</code>,<code>B</code> labels into the <code>index</code> using <code>stack</code>. <code>reset_index...
2
2016-08-15T13:10:09Z
[ "python", "pandas" ]
django post request is not showing javascript blob object in terminal
38,955,447
<p>I've been banging my head on the wall for hours with this. I am trying to use <code>recorder.js</code> using the source from this example <a href="https://webaudiodemos.appspot.com/AudioRecorder/" rel="nofollow">https://webaudiodemos.appspot.com/AudioRecorder/</a></p> <p>Now I want to modify it so that the user wil...
0
2016-08-15T12:51:00Z
38,955,664
<p>As Daniel Roseman wrote, uploaded files end up in <code>request.FILES</code>. One more thing - from jQuery documentation:</p> <blockquote> <p>As of jQuery 1.6 you can pass false to tell jQuery to not set any content type header.</p> </blockquote> <p>and Django documentation states:</p> <blockquote> <p>Note th...
1
2016-08-15T13:06:15Z
[ "javascript", "jquery", "python", "django", "post" ]
How to add a duplicate csv column using pandas
38,955,564
<p>I have a <code>CSV</code> that has just one column with <code>domains</code>, similar to this:</p> <pre><code>google.com yahoo.com cnn.com toast.net </code></pre> <p>I want to add a duplicate column and add the headers <code>domain</code> and <code>matches</code> so my <code>csv</code> will look like:</p> <pre><c...
1
2016-08-15T12:58:46Z
38,955,609
<p>You can add parameter <code>name</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a>:</p> <pre><code>import pandas as pd import io temp=u"""google.com yahoo.com cnn.com toast.net""" #after testing replace io.StringIO(temp) to file...
1
2016-08-15T13:02:07Z
[ "python", "csv", "pandas", "dataframe" ]
TensorFlow GPU Epoch Optimization?
38,955,736
<p>So this code works, and it gives me a 2x boost over CPU only, but I think its possible to get it faster. I think the issue boils down to this area...</p> <pre><code>for i in tqdm(range(epochs), ascii=True): sess.run(train_step, feed_dict={x: train, y_:labels}) </code></pre> <p>I think what happens is that eve...
0
2016-08-15T13:11:30Z
38,956,678
<p>The overhead of <code>session.run</code> is around 100 usec, so if you do 10k steps, this overhead adds around 1 second. If this is significant, then you are doing many small iterations, and are incurring extra overhead in other places. IE, GPU kernel launch overhead is 5x larger than CPU (5 usec vs 1 usec).</p> <...
1
2016-08-15T14:08:30Z
[ "python", "tensorflow" ]
formset validation not working as intended django
38,955,756
<p>I have a formset and I want to check each form to make sure my reading object isn't greater than my target object. For some reason I can't get this to work correctly because if the reading is larger than the target it still saves, also my form errors are not showing up as well. How can I check each form to validate ...
0
2016-08-15T13:12:50Z
38,974,680
<p>I figured it out I had to change reading to an int as well as my target then presto it worked like a charm.</p> <pre><code>class BaseInspecitonFormSet(BaseInlineFormSet): def clean(self): #if any(self.errors): # return reading = [] target = [] for form in self.forms: dim_i...
0
2016-08-16T12:13:14Z
[ "python", "django" ]
Missing letter č in ReportLab pdf created with Python 3.4
38,955,791
<p>A couple of days ago I started to use ReportLab with Python34. It's pretty nice package but I have one big problem that I don't know how to overcome.</p> <p>Could someone check my code and help me get over this? The problem is connected with letter č in Slovenian language. In the title there is no problem, but lat...
1
2016-08-15T13:14:49Z
39,016,389
<p>The problem is that in the title you are using <code>Vera</code> as the font, in the text you are using the default font used by Reportlab which is <code>Times-Roman</code> (if I remember correctly). </p> <p>The blackboxes you're seeing indicate that the current font (<code>Times-Roman</code>) doesn't have a symbol...
0
2016-08-18T10:54:20Z
[ "python", "python-3.x", "pdf-generation", "reportlab" ]
Separate process for my time consuming task (flask application)
38,955,792
<p>I am having a problem similar to the one in <a href="http://stackoverflow.com/questions/18127128/time-out-issues-with-chrome-and-flask">this question</a>. I have a flask application that takes input from the user (sometimes multiple thousand addresses), then processes it (cleans/geocodes), then returns a results pag...
-1
2016-08-15T13:14:52Z
38,956,739
<p>Using celery leaves out a bit- it allows you to kick off a background process, but does not help your problem of things timing out! My recommended solution is to use something like redis or your database to store the results... when someone visits the "kick off this job" url they get back a message "starting the pr...
0
2016-08-15T14:11:06Z
[ "python", "flask" ]
Separate process for my time consuming task (flask application)
38,955,792
<p>I am having a problem similar to the one in <a href="http://stackoverflow.com/questions/18127128/time-out-issues-with-chrome-and-flask">this question</a>. I have a flask application that takes input from the user (sometimes multiple thousand addresses), then processes it (cleans/geocodes), then returns a results pag...
-1
2016-08-15T13:14:52Z
38,957,047
<p>You're not running the task in the background. Use <code>delay</code> or <code>apply_async</code> to run the task in the background. Calling it directly executes it synchronously.</p> <pre><code>task = cleanAddress.delay(address) return jsonify(task.id) </code></pre> <p>Respond with the task's id, then poll its ...
1
2016-08-15T14:27:43Z
[ "python", "flask" ]
Local binding of "self" to another variable in instance methods acceptable?
38,955,807
<p>Is it acceptable according to the standards of best practice to locally bind <em>self</em> in a instance method to another variable? It comes in handy, especially when testing the method. I would also like to like know whether this approach is more efficient if instance attributes are retrieve within loops. Here is ...
1
2016-08-15T13:15:40Z
38,955,891
<p>This generally offers no benefits, it is actually counter-intuitive in that it confuses readers as to what your intentions are (<code>self</code> is arguably the most recognizable name in Python). </p> <p>The only up-side of doing this (albeit, a bit differently) is if you want to eliminate the attribute look-up on...
3
2016-08-15T13:21:06Z
[ "python", "python-2.7", "python-3.x" ]
Preserve index and column order when combining DataFrames
38,955,825
<p>Say we have the following DataFrames:</p> <pre><code>import pandas as pd import numpy as np df1_column_array = [['foo', 'bar'], ['A', 'B']] df1_column_tuple = list(zip(*df1_column_array)) df1_column_header = pd.MultiIndex.from_tuples(df1_column_tuple) df1_index_array = [['one','two'], ['0'...
1
2016-08-15T13:16:40Z
38,955,953
<p>You can use <code>hack</code> - first concat and get <code>Multiindex</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a> output of second <code>concat</code>:</p> <pre><code>idx = pd.concat([df1,df2]).index df_joined ...
1
2016-08-15T13:25:14Z
[ "python", "pandas" ]
Python/Biopython: How to search for a reference sequence (string) in a sequence with gaps?
38,955,872
<p>I am facing the following problem and have not found a solution yet:</p> <p>I am working on a tool for sequence analysis which uses a file with reference sequences and tries to find one of these reference sequences in a test sequence.</p> <p>The problem is that the test sequence might contain gaps (for example: <c...
0
2016-08-15T13:19:42Z
38,955,920
<p>You could do this: </p> <pre><code>import re a = 'TGTAACGAACGG' b = 'ACCTTGT--CGAA-GGAGT' temp_b = re.sub(r'[\W_]+', '', b) #removes everything that isn't a number or letter if a in temp_b: #do something </code></pre>
0
2016-08-15T13:23:08Z
[ "python", "regex", "biopython", "string-search", "sequence-analysis" ]
Python/Biopython: How to search for a reference sequence (string) in a sequence with gaps?
38,955,872
<p>I am facing the following problem and have not found a solution yet:</p> <p>I am working on a tool for sequence analysis which uses a file with reference sequences and tries to find one of these reference sequences in a test sequence.</p> <p>The problem is that the test sequence might contain gaps (for example: <c...
0
2016-08-15T13:19:42Z
38,956,003
<p>There's good news and there's bad news...</p> <p>Bad news first: What you are trying to do it not easy and regex is really not the way to do it. In a simple case regex could be made to work (maybe) but it will be inefficient and would not scale.</p> <p>However, the good news is that this is well understood problem...
0
2016-08-15T13:28:53Z
[ "python", "regex", "biopython", "string-search", "sequence-analysis" ]
Import variable from parent directory in python package
38,955,895
<p>I'm a bit new to python and I'm trying to learn Flask.</p> <p>My project structure looks like this:</p> <pre><code>project/ __init__.py views/ __init__.py profile.py </code></pre> <p>My <code>project/__init__.py</code> looks like this:</p> <pre><code>from flask import Flask from views.profile...
0
2016-08-15T13:21:23Z
38,974,217
<p>Finally I found an answer which works:</p> <p>In my profile.py I put this:</p> <pre><code>import sys, os.path sys.path.append(os.path.abspath('../')) from ccs import app </code></pre>
0
2016-08-16T11:52:24Z
[ "python", "import" ]
How to convert tuple to a list
38,955,931
<p>Following one of the accepted solutions to <a href="http://stackoverflow.com/questions/1815316/why-cant-i-join-this-tuple-in-python">this SO question</a>, I tried to convert a tuple into a list by doing this</p> <pre><code>mylist = list(mytuple) </code></pre> <p>However, I am getting a <code>Tuple object is not it...
-4
2016-08-15T13:23:42Z
38,955,982
<p>You could use</p> <pre><code>mylist = [x for x in mytuple] </code></pre>
-1
2016-08-15T13:26:56Z
[ "python" ]
How to convert tuple to a list
38,955,931
<p>Following one of the accepted solutions to <a href="http://stackoverflow.com/questions/1815316/why-cant-i-join-this-tuple-in-python">this SO question</a>, I tried to convert a tuple into a list by doing this</p> <pre><code>mylist = list(mytuple) </code></pre> <p>However, I am getting a <code>Tuple object is not it...
-4
2016-08-15T13:23:42Z
38,956,546
<p>You don't have a <code>tuple</code>. You have an <a href="https://docs.python.org/2/library/ast.html#node-classes" rel="nofollow"><code>ast.Node</code> subclass</a>. This <em>does matter</em>, AST nodes represent a parse tree, and although <code>ast.Tuple</code> may, in running Python code, result in a <code>tuple()...
1
2016-08-15T14:01:03Z
[ "python" ]
Connecting Two Models and Only Displaying in Template When they have a relationship
38,955,938
<p>I'm working on a site in Django where I have two models (players and seasons). I would like to display the players on a season page, but only when they are part of that season. Currently, this is what I have in my models file:</p> <p>models.py</p> <pre><code>from django.db import models class Player(models.Model)...
0
2016-08-15T13:24:12Z
38,956,024
<p>PxS is the through table in a many-to-many relationship. You should define that relationship explicitly:</p> <pre><code>class Season(models.Model): ... players = models.ManyToManyField('Player', through='PxS') </code></pre> <p>Now, in your <code>season</code> view, rather than sending all players explicitl...
1
2016-08-15T13:30:22Z
[ "python", "django" ]
Elementwise and in python list
38,955,954
<p>I have two <code>python lists</code> <code>A</code> and <code>B</code> of equal length each containing only boolean values. Is it possible to get a third list <code>C</code> where <code>C[i] = A[i] and B[i]</code> for <code>0 &lt;= i &lt; len(A)</code> without using loop?</p> <p>I tried following </p> <p><code>C =...
0
2016-08-15T13:25:21Z
38,956,148
<p>I'd recommend you use numpy to use these kind of predicates over arrays. Now, I don't think you can avoid loops to achieve what you want, but... if you don't consider mapping or enumerating as a form of looping, you could do something like this (C1):</p> <pre><code>A = [True, True, True, True] B = [False, False, Tr...
2
2016-08-15T13:37:17Z
[ "python", "python-2.7" ]
Elementwise and in python list
38,955,954
<p>I have two <code>python lists</code> <code>A</code> and <code>B</code> of equal length each containing only boolean values. Is it possible to get a third list <code>C</code> where <code>C[i] = A[i] and B[i]</code> for <code>0 &lt;= i &lt; len(A)</code> without using loop?</p> <p>I tried following </p> <p><code>C =...
0
2016-08-15T13:25:21Z
38,956,162
<p>You can do it without an explicit loop by using <code>map</code>, which performs the loop internally, at C speed. Of course, the actual <code>and</code> operation is still happening at Python speed, so I don't think it'll save much time (compared to doing essentially the same thing with Numpy, which can not only do ...
2
2016-08-15T13:38:15Z
[ "python", "python-2.7" ]
Elementwise and in python list
38,955,954
<p>I have two <code>python lists</code> <code>A</code> and <code>B</code> of equal length each containing only boolean values. Is it possible to get a third list <code>C</code> where <code>C[i] = A[i] and B[i]</code> for <code>0 &lt;= i &lt; len(A)</code> without using loop?</p> <p>I tried following </p> <p><code>C =...
0
2016-08-15T13:25:21Z
38,956,381
<p>Simple answer: you can't.</p> <p>Except in the trivial way, which is by calling a function that does this for you, using a loop. If you want this kind of nice syntax you can use libraries as suggested: map, numpy, etc. Or you can write your own function. </p> <p>If what you are looking for is syntactic convenience...
0
2016-08-15T13:52:35Z
[ "python", "python-2.7" ]
Elementwise and in python list
38,955,954
<p>I have two <code>python lists</code> <code>A</code> and <code>B</code> of equal length each containing only boolean values. Is it possible to get a third list <code>C</code> where <code>C[i] = A[i] and B[i]</code> for <code>0 &lt;= i &lt; len(A)</code> without using loop?</p> <p>I tried following </p> <p><code>C =...
0
2016-08-15T13:25:21Z
38,956,709
<blockquote> <p>Is it possible to get a third list <code>C</code> where <code>C[i] = A[i] and B[i]</code> for <code>0 &lt;= i &lt; len(A)</code> without using loop?</p> </blockquote> <p>Kind of:</p> <pre><code>class AndList(list): def __init__(self, A, B): self.A = A self.B = B def __getitem...
0
2016-08-15T14:09:36Z
[ "python", "python-2.7" ]
Reduce running time in Texture analysis using GLCM [Python]
38,955,970
<p>I am working on 6641x2720 image to generate its feature images (Haralick features like contrast, second moment etc) using a moving GLCM(Grey level Co-occurrence matrix ) window. But it takes forever to run. <strong>The code works fine, as I have tested it on smaller images.</strong> But, I need to make it run faster...
1
2016-08-15T13:26:15Z
38,960,020
<p>Fill a GLCM is a linear operation: you just go through all the pixels on your image/window and you fill the matching matrix case. Your issue is that you perform the operation for each pixel, and not just for an image. So in your case, if the image dimensions are Width x Height and the window dimensions are NxN, then...
0
2016-08-15T17:37:18Z
[ "python", "image-processing", "textures", "skimage" ]
Spike centered on zero in fast Fourier transform
38,956,089
<p>I have time associated data that I would like to perform a Fourier transform on. Data is located at <a href="http://pastebin.com/2i0UGJW9" rel="nofollow">http://pastebin.com/2i0UGJW9</a>. The problem is that the data is not uniformly spaced. To solve this, I attempted to interpolate the data and then perform the Fas...
0
2016-08-15T13:34:31Z
38,956,777
<p>As I don't have enough reputation to post a comment, I'll post my suggestions as an answer and hope one of them does lead to answer.</p> <h2>Interpolation</h2> <p>It's probably wiser to interpolate onto a grid that is quite a bit finer than what you are doing. Otherwise your interpolation will smooth the noisy dat...
3
2016-08-15T14:13:30Z
[ "python", "numpy", "scipy", "fft" ]
Single Frame Stalling in Pygame
38,956,240
<p>I've been building a game and a lengthy way through I noticed movement wasn't absolutely smooth and jittered randomly. I created a mockup program that reproduces this: </p> <pre><code>import pygame import sys pygame.init() clock = pygame.time.Clock() screen = pygame.display.set_mode((800,400)) def create_lines()...
2
2016-08-15T13:43:22Z
38,957,450
<p>Not sure if I've understood correctly, but what about if you tweak these 2 lines?</p> <p><code>self.rect.x += 1</code> instead <code>self.rect.x += 2</code></p> <p><code>clock.tick(60)</code> instead <code>clock.tick(30)</code></p> <p>Also, you could try making your animation time-based, for example:</p> <pre><c...
0
2016-08-15T14:50:32Z
[ "python", "pygame" ]
How to find index of an exact word in a string in Python
38,956,274
<pre><code>word = 'laugh' string = 'This is laughing laugh' index = string.find ( word ) </code></pre> <p>index is 8, should be 17. I looked around hard, but could not find an answer.</p>
0
2016-08-15T13:45:27Z
38,956,318
<p>Strings in code are not separated by spaces. If you want to find the space, you must include the space in the word you are searching for. You may find it would actually be more efficient for you to split the string into words then iterate, e.g:</p> <pre><code>str = "This is a laughing laugh" strList = str.split(" "...
0
2016-08-15T13:48:58Z
[ "python", "find", "word" ]
How to find index of an exact word in a string in Python
38,956,274
<pre><code>word = 'laugh' string = 'This is laughing laugh' index = string.find ( word ) </code></pre> <p>index is 8, should be 17. I looked around hard, but could not find an answer.</p>
0
2016-08-15T13:45:27Z
38,956,342
<p>You should use regex (with word boundary) as <code>find</code> returns the <em>first</em> occurrence. Then use the <code>start</code> attribute of the <code>match</code> object to get the starting index.</p> <pre><code>import re string = 'This is laughing laugh' a = re.search(r'\b(laugh)\b', string) print(a.start...
2
2016-08-15T13:50:21Z
[ "python", "find", "word" ]
How to find index of an exact word in a string in Python
38,956,274
<pre><code>word = 'laugh' string = 'This is laughing laugh' index = string.find ( word ) </code></pre> <p>index is 8, should be 17. I looked around hard, but could not find an answer.</p>
0
2016-08-15T13:45:27Z
38,956,495
<p>Here is one approach without regular expressions:</p> <pre><code>word = 'laugh' string = 'This is laughing laugh' words = string.split(' ') word_index = words.index(word) index = sum(len(x) + 1 for i, x in enumerate(words) if i &lt; word_index) =&gt; 17 </code></pre> <p>This splits the string int...
0
2016-08-15T13:58:44Z
[ "python", "find", "word" ]
How to find index of an exact word in a string in Python
38,956,274
<pre><code>word = 'laugh' string = 'This is laughing laugh' index = string.find ( word ) </code></pre> <p>index is 8, should be 17. I looked around hard, but could not find an answer.</p>
0
2016-08-15T13:45:27Z
38,956,536
<p>try this:</p> <pre><code>word = 'laugh' string = 'This is laughing laugh'.split(" ") index = string.index(word) </code></pre> <p>This makes a list containing all the words and then searches for the relevant word. Then I guess you could add all of the lengths of the elements in the list less than index and find...
0
2016-08-15T14:00:43Z
[ "python", "find", "word" ]
How to save multiple data sets with the sio.savemat function?
38,956,278
<p>I have created a code in python that reads multiple files (reads specific parts of them) and my goal is to save all these data points to matlab format. This is my 'main program' (all the functions are defined before):</p>
0
2016-08-15T13:45:42Z
38,957,123
<p>This <a href="http://stackoverflow.com/questions/29040276/how-to-append-to-mat-file-using-scipy-io-savemat">question</a> is about how to append data using savemat. It looks like that asker says you can only append data to the existing dictionary key though, so it may not solve your problem.</p> <p>What I recommend ...
2
2016-08-15T14:32:27Z
[ "python", "matlab", "loops", "scipy", "save" ]
IP Spoofing in python 3
38,956,401
<p>Is it possible to send a spoofed packet with another ip source? I've searched on the net and I found out that I need to use scapy library. I have this script that I found:</p> <pre><code>import sys from scapy.all import * if len(sys.argv) != 4: print ("Usage: ./spoof.py &lt;target&gt; &lt;spoofed_ip&gt; &lt;po...
0
2016-08-15T13:53:40Z
39,053,296
<p>solved on my own using scapy library:</p> <pre><code>from scapy.all import * A = "192.168.1.254" # spoofed source IP address B = "192.168.1.105" # destination IP address C = RandShort() # source port D = 80 # destination port payload = "yada yada yada" # packet payload while True: spoofed_packet = IP(src=A, d...
0
2016-08-20T10:52:24Z
[ "python", "python-3.x", "ip", "spoofing" ]
django rest change json response design
38,956,403
<p>I'm working with the Django rest tutorial and I see that all the responses are return only the models fields, for example:</p> <pre><code>[ { "id": 1, "title": "", "code": "foo = \"bar\"\n", "linenos": false, "language": "python", "style": "friendly" }] </code></pre> <p>My question is h...
0
2016-08-15T13:53:49Z
38,957,641
<p>From what I can tell, you are using the following code, which I have modified to do what you have requested. However, I would suggest that unless you have very good reason to do so, to not modify how the response is given. It leads to complications in creating multiple objects in the future for ModelViewSets, and al...
0
2016-08-15T15:01:25Z
[ "python", "django", "django-views", "django-rest-framework", "django-serializer" ]
Extract name entities from web domain address
38,956,512
<p>I am working on an NLP problem (in Python 2.7) to extract the location of a news report from the text inside the report. For this task I am using the Clavin API which works well enough. </p> <p>However I've noticed that the name of the location area is often mentioned in the URL of the report itself and I'd like to...
1
2016-08-15T13:59:29Z
38,957,790
<p>Check - <a href="http://nbviewer.jupyter.org/url/norvig.com/ipython/How%20to%20Do%20Things%20with%20Words.ipynb" rel="nofollow">Word Segmentation Task</a> from <a href="http://norvig.com/" rel="nofollow">Norvig</a>'s work.</p> <pre><code>from __future__ import division from collections import Counter import re, nlt...
0
2016-08-15T15:09:08Z
[ "python", "string", "machine-learning", "nlp" ]
Shared hosting setup for on Apache for Django 1.10
38,956,640
<p>We're looking for a clean and isolated way to host several Django sites on a single Apache with vhosts on Ubuntu 14.04.</p> <p>Following the docs <a href="https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/modwsgi/#using-mod-wsgi-daemon-mode" rel="nofollow">https://docs.djangoproject.com/en/1.10/howto/dep...
1
2016-08-15T14:05:49Z
39,414,058
<p>To summarize Graham Dumpleton's answer</p> <ul> <li>mod_wsgi 4.5.4 was broken with Python3. 4.5.5 fixed it.</li> <li>It's possible to setup a Python virtualenv for the virtualhosting (with package <code>mod_wsgi</code>) but is recommended to setup a Python virtualenv using <code>python-home</code> option and not <c...
0
2016-09-09T14:35:47Z
[ "python", "django", "apache", "mod-wsgi", "shared-hosting" ]
How to automatically call for a next iterator inside a loop
38,956,684
<p>I recently started scripting and am having difficulties with nested loops. I'm not getting the first iterator object from the first loop as an input to the second to run properly.</p> <p>The problem itself is quite simple. I would like to change the second item (‘20’) on row 1 in my data to a number from the ra...
1
2016-08-15T14:08:37Z
38,958,573
<p>It seems you are trying to concatenate a string to a list. <code>nline = nline[:2] + str(y)+ nline[3:]</code>. This will yield in a type error.</p> <p>Also <code>nline[:2]</code> gets the first 2 parts of the list, so you want to split <code>nline[:1]</code> to <code>nline[2:]</code></p> <p>Try something along the...
1
2016-08-15T16:00:03Z
[ "python", "loops", "iteration" ]
Object detection and segmentation Using Python
38,956,745
<p>I am an undergraduate student. I am new to image processing and python.</p> <p>I have many images of plants samples and their description(called labels which are stuck on the sample) as shown in the below Figure. I need to Automatically segment only those labels from the sample.</p> <p>I tried thresholding based o...
-2
2016-08-15T14:11:20Z
38,957,099
<p>You can try a template matching with a big white rectangle to identify the area where information is stored.</p> <p><a href="http://docs.opencv.org/3.1.0/d4/dc6/tutorial_py_template_matching.html#gsc.tab=0" rel="nofollow">http://docs.opencv.org/3.1.0/d4/dc6/tutorial_py_template_matching.html#gsc.tab=0</a></p> <p>W...
0
2016-08-15T14:30:49Z
[ "python", "opencv", "image-processing", "ocr", "image-segmentation" ]
Object detection and segmentation Using Python
38,956,745
<p>I am an undergraduate student. I am new to image processing and python.</p> <p>I have many images of plants samples and their description(called labels which are stuck on the sample) as shown in the below Figure. I need to Automatically segment only those labels from the sample.</p> <p>I tried thresholding based o...
-2
2016-08-15T14:11:20Z
38,972,226
<p>Why using color threshold? I tried this one with ImageJ and get nice results. I just converted the image to 8bit and <a href="http://i.stack.imgur.com/5uKTg.png" rel="nofollow">binarise</a> using a fixed threshold (166 in this case). You can choose the best threshold from the image <a href="http://i.stack.imgur.com/...
0
2016-08-16T10:15:04Z
[ "python", "opencv", "image-processing", "ocr", "image-segmentation" ]
Find channel name of message with SlackClient
38,956,760
<p>I am trying to print the channel a message was posted to in slack with the python SlackClient. After running this code I only get an ID and not the channel name.</p> <pre><code>import time import os from slackclient import SlackClient BOT_TOKEN = os.environ.get('SLACK_BOT_TOKEN') def main(): # Creates a slack...
0
2016-08-15T14:12:04Z
38,970,310
<p>I'm not sure what you are outputting. Shouldn't "channels" be "channel" ? Also, I think this output is the "user" field. The "Channel" field should yield an id starting with C or G (<a href="https://api.slack.com/events/message" rel="nofollow">doc</a>). </p> <pre><code>{ "type": "message", "channel": "C2147...
0
2016-08-16T08:44:16Z
[ "python", "python-2.7", "slack-api", "slack" ]
Find channel name of message with SlackClient
38,956,760
<p>I am trying to print the channel a message was posted to in slack with the python SlackClient. After running this code I only get an ID and not the channel name.</p> <pre><code>import time import os from slackclient import SlackClient BOT_TOKEN = os.environ.get('SLACK_BOT_TOKEN') def main(): # Creates a slack...
0
2016-08-15T14:12:04Z
39,075,937
<p>This will always produce a channel id and not channel name. You must call <strong>channels.info</strong> to get the channel name.</p> <pre><code>import time import os from slackclient import SlackClient BOT_TOKEN = os.environ.get('SLACK_BOT_TOKEN') def main(): # Creates a slackclient instance with bots token sc =...
0
2016-08-22T09:31:59Z
[ "python", "python-2.7", "slack-api", "slack" ]
Pandas add new columns based on splitting another column
38,956,778
<p>I have a pandas dataframe like the following:</p> <pre><code>A B US,65,AMAZON 2016 US,65,EBAY 2016 </code></pre> <p>My goal is to get to look like this:</p> <pre><code>A B country code com US.65.AMAZON 2016 US 65 AMAZON US.65.AMAZON 2016 US 6...
2
2016-08-15T14:13:31Z
38,956,805
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow"><code>split</code></a> with parameter <code>expand=True</code> and add one <code>[]</code> to left side:</p> <pre><code>df[['country','code','com']] = df.A.str.split(',', expand=True) </code></pre...
2
2016-08-15T14:15:24Z
[ "python", "pandas", "dataframe", "split", "multiple-columns" ]
Pandas add new columns based on splitting another column
38,956,778
<p>I have a pandas dataframe like the following:</p> <pre><code>A B US,65,AMAZON 2016 US,65,EBAY 2016 </code></pre> <p>My goal is to get to look like this:</p> <pre><code>A B country code com US.65.AMAZON 2016 US 65 AMAZON US.65.AMAZON 2016 US 6...
2
2016-08-15T14:13:31Z
38,957,891
<p>For getting the new columns I would prefer doing it as following:</p> <pre><code>df['Country'] = df['A'].apply(lambda x: x[0]) df['Code'] = df['A'].apply(lambda x: x[1]) df['Com'] = df['A'].apply(lambda x: x[2]) </code></pre> <p>As for the replacement of <strong>,</strong> with a <strong>.</strong> you can use the...
0
2016-08-15T15:14:33Z
[ "python", "pandas", "dataframe", "split", "multiple-columns" ]
Wagtail/Django block doesn't render content properly from custom/nested StructBlock template
38,956,897
<p>I have a block in the head of my base template that will render "extra" CSS. This CSS will be customized from fields coming in from a Wagtail CMS instance.</p> <p>So, in the <code>base.html</code> template I have:</p> <pre><code>&lt;head&gt; {% block extra_css %}{% endblock %} &lt;/head&gt; &lt;body&gt; {% blo...
0
2016-08-15T14:20:16Z
38,972,874
<p>This is a limitation in the way custom templates for StreamField blocks work. (There's a similar limitation in Django templating in general too, though - the <code>{% block %}</code> mechanism only works in conjunction with <code>{% extends %}</code>, not <code>{% include %}</code>.) The HTML content for the block i...
1
2016-08-16T10:46:52Z
[ "python", "css", "django", "templates", "wagtail" ]
IndexError: index out of range in python
38,956,910
<p>i am tying to solve the following question on a competitive coding website where i have to convert '->' to '.' only in the code section but not in the comments. <a href="https://www.hackerearth.com/problem/algorithm/compiler-version-2/" rel="nofollow">https://www.hackerearth.com/problem/algorithm/compiler-version-2/...
-1
2016-08-15T14:21:06Z
38,957,085
<ol> <li><code>if string</code> is the same as <code>if string != ""</code></li> <li><code>temp_list</code> is a list so you can loop over it in a more pythonic way <code>for i in temp_list</code></li> <li><code>string</code> is a variable of type <code>str</code> so you cann't index it like this: <code>string[i][j]</c...
-1
2016-08-15T14:29:51Z
[ "python", "python-3.x" ]
Python & MySQL - non GCC module?
38,956,942
<p>Are there any MySQL modules that are written purely in Python and don't require GCC to be compiled? MySQLdb is great but it just requires too much for what I'm working with right now.</p> <p>Thanks</p>
0
2016-08-15T14:22:26Z
38,957,681
<p>This does the trick. All python, no gcc.</p> <p><a href="https://github.com/mysql/mysql-connector-python" rel="nofollow">https://github.com/mysql/mysql-connector-python</a></p>
0
2016-08-15T15:03:21Z
[ "python", "mysql", "database" ]
Python splitting of text
38,956,950
<p>I have a text file (.txt) with different lines of words For example: </p> <pre><code>1,2,3,4,5 11,12,13,14,15 </code></pre> <p>How can I use the <code>file.read().split()</code> command to just get the 2nd column...so 2 and 12 for example of the text?</p>
1
2016-08-15T14:22:51Z
38,956,991
<p>Assuming no spaces around <code>,</code>:</p> <pre><code>with open('file.txt') as f: for line in f: print(line.split(',')[1]) </code></pre> <p>If there could be whitespaces, use <code>re.split()</code>:</p> <pre><code>with open('file.txt') as f: for line in f: print(re.split(r'\s?,\s?', li...
4
2016-08-15T14:25:05Z
[ "python" ]
Python splitting of text
38,956,950
<p>I have a text file (.txt) with different lines of words For example: </p> <pre><code>1,2,3,4,5 11,12,13,14,15 </code></pre> <p>How can I use the <code>file.read().split()</code> command to just get the 2nd column...so 2 and 12 for example of the text?</p>
1
2016-08-15T14:22:51Z
38,957,009
<p>First you have to split the file into lines (easily done simply by iterating over it), than you have to extract the 2nd column from each line.</p> <p>Simple example:</p> <pre><code>with open("myfile.txt") as myfile: for line in myfile: print(line.split(",")[1]) # indexing starts at 0 </code></pre> <p>...
2
2016-08-15T14:25:58Z
[ "python" ]
Python filter a DBF by a range of date (between two dates)
38,956,992
<p>I'm using the <a href="https://pypi.python.org/pypi/dbf/0.96.8" rel="nofollow">dbf</a> library with python3.5. The DBF table has a column with only dates without time and another just with time. Want to retrieve records from the last five minutes.</p> <p>I'm new to this module and currently see just two approaches ...
1
2016-08-15T14:25:06Z
38,960,067
<p>The simplest way is to have a filter function that only tracks matching records:</p> <pre><code># lightly tested def last_five_minutes(record, date_field, time_field): now = dbf.DateTime.now() record_date = record[date_field] try: # if time is stored as HH:MM:SS record_time = dbf.DateTim...
0
2016-08-15T17:40:14Z
[ "python", "dbf" ]
Python Pandas Drop Duplicates keep second to last
38,957,036
<p>What's the most efficient way to select the second to last of each duplicated set in a pandas dataframe?</p> <p>For instance I basically want to do this operation:</p> <pre><code>df = df.drop_duplicates(['Person','Question'],take_last=True) </code></pre> <p>But this:</p> <pre><code>df = df.drop_duplicates(['Pers...
6
2016-08-15T14:27:19Z
38,957,387
<p>With groupby.apply:</p> <pre><code>df = pd.DataFrame({'A': [1, 1, 1, 1, 2, 2, 2, 3, 3, 4], 'B': np.arange(10), 'C': np.arange(10)}) df Out: A B C 0 1 0 0 1 1 1 1 2 1 2 2 3 1 3 3 4 2 4 4 5 2 5 5 6 2 6 6 7 3 7 7 8 3 8 8 9 4 9 9 (df.groupby('A', as_index=False)...
5
2016-08-15T14:46:50Z
[ "python", "pandas" ]
Python Pandas Drop Duplicates keep second to last
38,957,036
<p>What's the most efficient way to select the second to last of each duplicated set in a pandas dataframe?</p> <p>For instance I basically want to do this operation:</p> <pre><code>df = df.drop_duplicates(['Person','Question'],take_last=True) </code></pre> <p>But this:</p> <pre><code>df = df.drop_duplicates(['Pers...
6
2016-08-15T14:27:19Z
38,957,404
<p>Starting with this: </p> <pre><code> Person Question 1 0 0 2 1 1 3 2 2 4 3 3 5 4 4 6 0 0 7 1 1 8 2 2 9 3 3 10 4 4 </code></pre> <p>Try this: For last..... </p> <p...
-2
2016-08-15T14:47:56Z
[ "python", "pandas" ]
Python Pandas Drop Duplicates keep second to last
38,957,036
<p>What's the most efficient way to select the second to last of each duplicated set in a pandas dataframe?</p> <p>For instance I basically want to do this operation:</p> <pre><code>df = df.drop_duplicates(['Person','Question'],take_last=True) </code></pre> <p>But this:</p> <pre><code>df = df.drop_duplicates(['Pers...
6
2016-08-15T14:27:19Z
38,965,036
<p>You could <code>groupby/tail(2)</code> to take the last 2 items, then <code>groupby/head(1)</code> to take the first item from the tail:</p> <pre><code>df.groupby(['A','B']).tail(2).groupby(['A','B']).head(1) </code></pre> <p>If there is only one item in the group, <code>tail(2)</code> returns just the one item.</...
2
2016-08-16T00:45:19Z
[ "python", "pandas" ]
Why does not django delete one to one relationship?
38,957,082
<p>I have the following simple relationship:</p> <pre><code>class User(models.Model): fields here class UserProfile(models.Model): user = models.OneToOneField(User) </code></pre> <p>I did the following in the shell:</p> <pre><code>user = User.objects.create(...) profile = UserProfile.objects.create(user=use...
1
2016-08-15T14:29:47Z
38,957,230
<p>You can reload the user from the database:</p> <pre><code>user = User.objects.get(pk=user.pk) </code></pre> <p>That will refresh all its attributes including the userprofile.</p>
3
2016-08-15T14:38:40Z
[ "python", "django", "django-models", "django-queryset", "one-to-one" ]
extend python not extending correctly
38,957,127
<p>I have a list <code>indexlist</code> with the value:</p> <p><code>[8, 11, 4, 3]</code></p> <p>This is in the middle of a function, so other relevant values are <code>i=0</code> and <code>endsorted = sorted(indexlist[i+1:])</code></p> <p>Then I call</p> <p><code>indexlist[:i+1].extend(endsorted)</code></p> <p>wh...
0
2016-08-15T14:32:48Z
38,957,259
<p>Look on that code:</p> <pre><code># Init indexlist = [8, 11, 4, 3] # Your setup i = 0 endsorted = sorted(indexlist[i+1:]) # Extending the right list object new_index_list = indexlist[:i+1] new_index_list.extend(endsorted) </code></pre> <p>The new_index_list value is <code>[8, 3, 4, 11]</code>.</p> <p>Since I ex...
0
2016-08-15T14:40:04Z
[ "python" ]
Sanitizers in Python native module
38,957,154
<p>I would like to use GCC's sanitizers for a native module.</p> <p>I use the link options:</p> <pre><code>-static-libasan -static-libtsan -static-liblsan -static-libubsan -fsanitize=address -lasan -lubsan </code></pre> <p>When I load the native module it prints the error message:</p> <pre><code>ASan runtime does n...
0
2016-08-15T14:34:05Z
39,309,254
<p>For some reason linking in <code>-lasan</code> didn't work either. However, <code>LD_PRELOAD</code> worked fine.</p> <p>Try <code>LD_PRELOAD</code>, if that is feasible for you.</p>
0
2016-09-03T16:51:53Z
[ "python", "python-3.x", "gcc", "address-sanitizer" ]
Extract all single {key:value} pairs from dictionary
38,957,159
<p>I have a dictionary which maps some keys to 1 or <strong>more</strong> values. </p> <p>In order to map to more than 1 value, I'm mapping each individual key to a list. How can I get the number of the single pairs? Is there a quick pythonic way to do this?</p> <p>My dict looks something like this:</p> <pre><code>&...
0
2016-08-15T14:34:25Z
38,957,246
<p>You could try something like</p> <pre><code>len([_ for v in d.values() if len(v) == 1]) </code></pre> <p>where <code>d</code> is the name of your dictionary (you should avoid using identifiers such as <code>dict</code>, incidentally).</p> <p>Depending on your interpreter version, you might need to use <code>iterv...
1
2016-08-15T14:39:22Z
[ "python", "dictionary" ]