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
Calculation occurance random numbers in csv file
37,697,154
<p>I have a csv file with the columns: recipe_name (index), apple, citrus, banana, melon, ... (and more columns with fruits). For each recipe there is a row with the weight percentages of each fruit. But not all recipes contain all fruits. These are empty spaces in the csv file. It looks like this: </p> <blockquote>...
1
2016-06-08T08:29:32Z
37,697,523
<p>You can try something like this</p> <pre><code>import csv with open(yourFileName, 'rU') as f: data = {row[0]:len([x for x in row[1:] if x]) for row in csv.reader(f, yourDialect)[1:]} </code></pre> <p>this will give you a dictionary with keys as recipe names and values their fruit count!</p>
1
2016-06-08T08:45:15Z
[ "python", "excel", "csv", "pandas" ]
how to merge two data frames based on particular column in pandas python?
37,697,195
<p>i have to merge two dataframes</p> <p>df1</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>company,standard tata,A1 cts,A2 dell,A3</code></pre> </div> </div> </p> <p>df2</p> <p>...
-2
2016-06-08T08:31:55Z
37,697,279
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a>:</p> <pre><code>print (pd.merge(df1, df2, on='company')) </code></pre> <p>Sample:</p> <pre><code>print (df1) company standard 0 tata A1 1 cts A2 2 dell A3 prin...
0
2016-06-08T08:35:23Z
[ "python", "python-2.7", "pandas" ]
Django pytest database access for data migration
37,697,215
<p>I'm using <code>Django (1.9.6)</code>, <code>pytest (2.9.2)</code> and <code>pytest-django (2.9.1)</code></p> <p>I have a data migration that looks like this:</p> <pre><code># -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-06-07 09:56 from __future__ import unicode_literals from django.db import migrat...
1
2016-06-08T08:32:52Z
37,704,920
<p>I found the solution thanks to @HÃ¥ken Lid and the <a href="https://code.djangoproject.com/ticket/23422" rel="nofollow">Django issue</a> he provided. The problem is that Django creates the ContentTypes receiving a signal emitted when all the migrations complete. That's why it didn't find the permissions but it let m...
0
2016-06-08T14:09:35Z
[ "python", "django", "py.test", "pytest-django" ]
manage.py not generated when using "django-admin startapp mysite"
37,697,225
<p>I'm trying to setup a webapp using the django framework. Following the tutorial, when I use "django-admin startapp {project-name}", django-admin correctly generates: </p> <pre><code>06/08/2016 10:21 AM &lt;DIR&gt; . 06/08/2016 10:21 AM &lt;DIR&gt; .. 06/08/2016 10:21 AM 63...
0
2016-06-08T08:33:12Z
37,697,401
<p><code>manage.py</code> is included in projects not apps. To create a new project, you should do:</p> <pre><code>django-admin startproject {project-name} </code></pre> <p>Projects are a collection of apps. So to create an app, <code>cd</code> into the project directory you've just created and do:</p> <pre><code>dj...
3
2016-06-08T08:40:05Z
[ "python", "django" ]
python numpy strange boolean arithmetic behaviour
37,697,280
<p>Why is it, in python/numpy:</p> <pre><code>from numpy import asarray bools=asarray([False,True]) print(bools) [False True] print(1*bools, 0+bools, 0-bools) # False, True are valued as 0, 1 [0 1] [0 1] [ 0 -1] print(-2*bools, -bools*2) # !? expected same result! :-/ [0 -2] [2 0] print(-bools) ...
3
2016-06-08T08:35:28Z
37,698,296
<p>Numpy arrays are homogenous—all elements have the same type for a given array, and the array object stores what type that is. When you create an array with <code>True</code> and <code>False</code>, it is an array of type <code>bool</code> and operators behave on the array as such. It's not surprising, then, that y...
0
2016-06-08T09:19:48Z
[ "python", "numpy", "boolean" ]
python numpy strange boolean arithmetic behaviour
37,697,280
<p>Why is it, in python/numpy:</p> <pre><code>from numpy import asarray bools=asarray([False,True]) print(bools) [False True] print(1*bools, 0+bools, 0-bools) # False, True are valued as 0, 1 [0 1] [0 1] [ 0 -1] print(-2*bools, -bools*2) # !? expected same result! :-/ [0 -2] [2 0] print(-bools) ...
3
2016-06-08T08:35:28Z
37,707,121
<p>Its all about operator order and data types.</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; B = np.array([0, 1], dtype=np.bool) &gt;&gt;&gt; B array([False, True], dtype=bool) </code></pre> <p>With numpy, boolean arrays are treated as that, boolean arrays. Every operation applied to them, will first ...
2
2016-06-08T15:41:55Z
[ "python", "numpy", "boolean" ]
'ascii' codec can't encode character error when saving list of tuples to file
37,697,373
<p>I have a list of tuples, which I would like to save to a file. I normally solve this error with <code>.encode('utf-8')</code> but as I do have a tuple with integers in it, this does not seem to work. </p> <p>My data looks like this:</p> <pre><code>lis=[[(0, u'good', 19, u'quality', 1), (1, u'smells', 13, u'produ...
1
2016-06-08T08:39:11Z
37,697,769
<p>You have the call order backwards; you want</p> <pre><code>str(x).encode('utf-8') </code></pre> <p>... though the <code>str()</code> will probably bump into the same error if you are passing it things which may or may not be Unicode, and encoding a <code>str</code> isn't necessarily well-defined anyway; you should...
1
2016-06-08T08:56:30Z
[ "python", "encoding", "utf-8" ]
'ascii' codec can't encode character error when saving list of tuples to file
37,697,373
<p>I have a list of tuples, which I would like to save to a file. I normally solve this error with <code>.encode('utf-8')</code> but as I do have a tuple with integers in it, this does not seem to work. </p> <p>My data looks like this:</p> <pre><code>lis=[[(0, u'good', 19, u'quality', 1), (1, u'smells', 13, u'produ...
1
2016-06-08T08:39:11Z
37,697,910
<ol> <li>use <code>str(x).encode('utf-8')</code> and not str(x.encode('utf-8'))</li> <li>use <code>for k in lis</code> instead of <code>for k in range(0, len(lis))</code></li> <li>use <code>for line in k</code> instead of <code>for line in lis[k]</code></li> <li>most likely you have syntax error in <code>" ".join(str(x...
0
2016-06-08T09:02:15Z
[ "python", "encoding", "utf-8" ]
'ascii' codec can't encode character error when saving list of tuples to file
37,697,373
<p>I have a list of tuples, which I would like to save to a file. I normally solve this error with <code>.encode('utf-8')</code> but as I do have a tuple with integers in it, this does not seem to work. </p> <p>My data looks like this:</p> <pre><code>lis=[[(0, u'good', 19, u'quality', 1), (1, u'smells', 13, u'produ...
1
2016-06-08T08:39:11Z
37,698,464
<p>Assuming that you use Python2, you can do the following:</p> <ul> <li>convert anything to a unicode string</li> <li><p>encode the unicode string obtained</p> <pre><code>... strs=str(k)+" "+" ".join(unicode(x).encode('utf-8') for x in line) ... </code></pre></li> </ul>
0
2016-06-08T09:26:12Z
[ "python", "encoding", "utf-8" ]
'ascii' codec can't encode character error when saving list of tuples to file
37,697,373
<p>I have a list of tuples, which I would like to save to a file. I normally solve this error with <code>.encode('utf-8')</code> but as I do have a tuple with integers in it, this does not seem to work. </p> <p>My data looks like this:</p> <pre><code>lis=[[(0, u'good', 19, u'quality', 1), (1, u'smells', 13, u'produ...
1
2016-06-08T08:39:11Z
37,702,417
<p>You're getting the <code>'ascii' codec can't encode character</code> error because you're calling <code>str()</code> on a Unicode string that has non-ASCII chars in it.</p> <p>In Python 2.x, <code>str()</code> will try to encode the Unicode to bytes using the ASCII codec. Therefore, you should never use <code>str()...
0
2016-06-08T12:23:46Z
[ "python", "encoding", "utf-8" ]
Pycharm update reference automatically
37,697,438
<p>I'm a new Pycharm's user, and in my project, I need to turn a python file in a directory. This file contains a lot of functions and so i would like reorder my project creating a new directory that contains new python files with the functions cited previously. So my question is: Is there a pycharm functionality that ...
1
2016-06-08T08:41:48Z
37,698,048
<blockquote> <p>go to File >> Settings >> Project >> Project Interpreter</p> </blockquote> <p>select the setting icon there and click on more</p> <p>here click in last option (Interpreter Paths).</p> <p>add your modules directory location here.</p> <blockquote> <p>restart Pycharm</p> </blockquote>
1
2016-06-08T09:08:33Z
[ "python", "reference", "pycharm" ]
python unittest for argparse
37,697,502
<p>I have a function inside a module that creates an <code>argparse</code>:</p> <pre><code>def get_options(prog_version='1.0', prog_usage='', misc_opts=None): options = [] if misc_opts is None else misc_opts parser = ArgumentParser(usage=prog_usage) if prog_usage else ArgumentParser() parser.add_argumen...
1
2016-06-08T08:44:12Z
37,708,095
<p>Your error message stack is hard to read because it is in quoted form rather than code. But I think the <code>-v</code> argument is producing a <code>sys.exit</code>. <code>version</code> is like <code>help</code> - it's supposed to display a message and then exit. The <code>-v</code> is used by <code>unittest</c...
2
2016-06-08T16:31:24Z
[ "python", "python-2.7", "unit-testing", "argparse" ]
python unittest for argparse
37,697,502
<p>I have a function inside a module that creates an <code>argparse</code>:</p> <pre><code>def get_options(prog_version='1.0', prog_usage='', misc_opts=None): options = [] if misc_opts is None else misc_opts parser = ArgumentParser(usage=prog_usage) if prog_usage else ArgumentParser() parser.add_argumen...
1
2016-06-08T08:44:12Z
37,711,448
<p>I prefer explicitly passing arguments instead of relying on globally available attributes such as <code>sys.argv</code> (which <code>parser.parse_args()</code> does internally). Thus I usually use <code>argparse</code> by passing the list of arguments myself (to <code>main()</code> and subsequently <code>get_options...
2
2016-06-08T19:37:08Z
[ "python", "python-2.7", "unit-testing", "argparse" ]
df.first_valid_index() returns an index which raises a KeyError?
37,697,617
<p>I'm trying to group a <code>pd.DataFrame</code> by month and apply a custom function <code>ultimo(x)</code>:</p> <pre><code>def ultimo(x): if x.first_valid_index() is None: return np.nan else: return x[x.first_valid_index()] </code></pre> <p>I've got this from another <a href="http://stacko...
1
2016-06-08T08:49:37Z
37,697,981
<p>This is because in your previous question, the input (and hence <code>x</code>) is a series, so <code>x[index]</code> works as expected. For a dataframe, <code>x[index]</code> expects a column name. In order to access the row indexed by the index, you need <code>x.loc[index]</code>. See <a href="http://pandas.pydata...
2
2016-06-08T09:05:45Z
[ "python", "python-3.x", "pandas", "dataframe" ]
TfidfVectorizer.fit_transform giving type error
37,697,654
<p>I am new to scikit-learn. I need to calculate the tf-idf vectors for a large corpus. But before beginning on that, I tried coding for a few small documents consisting of not more than 5-6 words each. The specific code that I wrote is as given below:</p> <pre><code>from sklearn.feature_extraction.text import TfidfV...
1
2016-06-08T08:51:06Z
37,732,660
<p>I think this is related to a faulty installation of numpy, reported <a href="https://github.com/scikit-learn/scikit-learn/issues/4691%20here" rel="nofollow">here</a>.</p> <p>You may run the test and check that (nose required):</p> <pre><code>pip install nose nosetests -v numpy nosetests -v sklearn </code></pre> <...
0
2016-06-09T17:32:02Z
[ "python", "scikit-learn", "tf-idf" ]
python Reportlab two items in the same row on a Paragraph
37,697,686
<p>I would like to align two text in the same row, on the left and on the right:</p> <p>TEXT1 TEXT2</p> <p>and in the same line left align an image and center a text:</p> <p>IMAGE TEXT</p> <p>How is it possible?</p> <p>That's my code:</p> <pre><code>Story=[] styles=getSampleSt...
0
2016-06-08T08:52:30Z
37,705,137
<p>Use a <code>Table</code>. The table can have its own style and the items (<code>Paragraph</code>, <code>Image</code>, ...) can also have their own style, that way you can have differently aligned items within the table cells</p> <pre><code>from reportlab.lib.pagesizes import A4 from reportlab.platypus import Simple...
0
2016-06-08T14:19:27Z
[ "python", "django", "python-3.x", "pdf-generation", "reportlab" ]
Neo4j unable to connect to graph database server
37,697,695
<p>I am using an example script to connect to the neo4j server and after that run a query. But I am getting this error: </p> <blockquote> <p>C:\cygwin\lib\python2.7\site-packages\neo4j\v1\session.py:94: UserWarning: Bolt over TLS is only available in Python 2.7.9+ and Python 3.3+ so communications are not secure...
1
2016-06-08T08:52:47Z
37,697,845
<p>The driver only support Bolt, so no http possible.</p> <p>Your connection uri mixes the two protocols, change to this :</p> <pre><code>driver = GraphDatabase.driver("bolt://localhost",auth=basic_auth("neo4j", "neo")) session = driver.session() </code></pre> <p>Normally, by just following the example in the reposi...
4
2016-06-08T08:59:24Z
[ "python", "python-2.7", "neo4j" ]
How to convert earth-coordinates to astronomical coordinates ?
37,697,822
<p>How can I calculate position (ra, dec) of star observed at some station (longitude, latitude) on specific date and time (in julian format)? I have made some detections in specific days at a specific station, I'd like to convert my earth coordinates to astronomical ones in order to have a map of the sky section I obs...
-3
2016-06-08T08:58:38Z
37,698,495
<p>Regarding Astropy documentation, <a href="http://docs.astropy.org/en/stable/api/astropy.coordinates.SkyCoord.html#astropy.coordinates.SkyCoord" rel="nofollow">skycoord</a> seem to perform what you need.</p> <p>obstime argument is of type <a href="http://docs.astropy.org/en/stable/api/astropy.time.Time.html#astropy....
0
2016-06-08T09:27:33Z
[ "python", "coordinates", "astropy", "julian-date" ]
How to remove % symbol for particular column in dataframeusing python pandas?
37,697,934
<p>My data frame have following data:</p> <pre><code>company,standard,returns aaa,b1,10% bbb,b2,20% </code></pre> <p>I have to remove <code>%</code> from <code>returns</code> column.</p>
-3
2016-06-08T09:03:18Z
37,697,951
<p>First remove last value of each string by <a href="http://pandas.pydata.org/pandas-docs/stable/text.html#indexing-with-str" rel="nofollow">indexing with str</a> and then cast to <code>int</code> or <code>float</code>:</p> <pre><code>#if int values print (df['returns'].str[:-1].astype(int)) #if flaot values print (...
1
2016-06-08T09:04:07Z
[ "python", "python-2.7", "pandas", "dataframe" ]
How to remove % symbol for particular column in dataframeusing python pandas?
37,697,934
<p>My data frame have following data:</p> <pre><code>company,standard,returns aaa,b1,10% bbb,b2,20% </code></pre> <p>I have to remove <code>%</code> from <code>returns</code> column.</p>
-3
2016-06-08T09:03:18Z
37,697,955
<p>Use vectorized <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html#pandas.Series.str.replace" rel="nofollow"><code>str.replace</code></a>:</p> <pre><code>In [225]: df['returns'] = df['returns'].str.replace('\%','') df Out[225]: company standard returns 0 aaa b1...
0
2016-06-08T09:04:22Z
[ "python", "python-2.7", "pandas", "dataframe" ]
Backward lookup in order_by
37,698,047
<p>Here is example model:</p> <pre><code>class Sample(models.Model): group = models.ForeignKey(SampleSet) type = models.IntegerField() code = models.IntegerField() class SampleSet(models.Model): some_text = models.TextField() </code></pre> <p>Is there any ways to use backward lookups in order_by? Nee...
0
2016-06-08T09:08:31Z
37,698,088
<p>How about:</p> <pre><code>SampleSet.objects.filter(sample__type=0).order_by('sample__code') </code></pre>
0
2016-06-08T09:10:21Z
[ "python", "django", "django-models" ]
Backward lookup in order_by
37,698,047
<p>Here is example model:</p> <pre><code>class Sample(models.Model): group = models.ForeignKey(SampleSet) type = models.IntegerField() code = models.IntegerField() class SampleSet(models.Model): some_text = models.TextField() </code></pre> <p>Is there any ways to use backward lookups in order_by? Nee...
0
2016-06-08T09:08:31Z
37,698,089
<p>You need to filter first before you order</p> <pre><code>SampleSet.objects.filter(sample__type=0).order_by('sample__code') </code></pre> <p>If you still need the all samples as well then I'd suspect you need to order by type first, then by code.</p> <pre><code>SampleSet.objects.order_by('sample__type', 'sample__c...
0
2016-06-08T09:10:22Z
[ "python", "django", "django-models" ]
Continuous deployment using travis and heroku - preserving some kind of state
37,698,058
<h3>The problem</h3> <p>I'm currently in the process of setting up Travis to run our tests and deploy if the tests are successfull. Which is pretty straight forward, but I don't want to deploy when these conditions are met:</p> <pre><code> - The time is between 07:00 and 22:00 (workdays) - During the deploy the data...
2
2016-06-08T09:09:12Z
38,738,432
<p>Ok with the awesome help of the folks over at Travis I came up with the following solution:</p> <ol> <li><p>I've activated the <a href="https://docs.travis-ci.com/user/cron-jobs/" rel="nofollow">CronJobs</a> and set them to run daily. At the time of writing this you can't specify a time the crons run, instead they ...
0
2016-08-03T08:33:18Z
[ "python", "django", "heroku", "travis-ci", "continuous-deployment" ]
Find a character in multiple places python
37,698,138
<p>How would one go about finding the positions of a certain character that appears multiple times in python.</p> <p>E.G:</p> <p>If I input the string "Lots of foxes" how would I find each of the positions of "O" and display them independently</p> <p>Thanks for your help</p>
-1
2016-06-08T09:12:35Z
37,698,237
<p>You can use <a href="https://docs.python.org/2/library/re.html#re.finditer" rel="nofollow"><code>re.finditer</code></a>:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; [match.start() for match in re.finditer('o', 'Lots of foxes')] [1, 5, 9] </code></pre> <p>Or, if you want case insensitive search:</p> <pre><...
2
2016-06-08T09:16:42Z
[ "python", "string", "python-3.x", "character" ]
Find a character in multiple places python
37,698,138
<p>How would one go about finding the positions of a certain character that appears multiple times in python.</p> <p>E.G:</p> <p>If I input the string "Lots of foxes" how would I find each of the positions of "O" and display them independently</p> <p>Thanks for your help</p>
-1
2016-06-08T09:12:35Z
37,698,320
<p>You can do it without regexp:</p> <pre><code>for idx, val in enumerate("Lots of foxes"): if val == "O": print(idx) </code></pre> <p>If you want the match to be case insesitive, just change the line <code>val == "O"</code> with <code>val.upper() == "0"</code>.</p>
0
2016-06-08T09:20:47Z
[ "python", "string", "python-3.x", "character" ]
Find a character in multiple places python
37,698,138
<p>How would one go about finding the positions of a certain character that appears multiple times in python.</p> <p>E.G:</p> <p>If I input the string "Lots of foxes" how would I find each of the positions of "O" and display them independently</p> <p>Thanks for your help</p>
-1
2016-06-08T09:12:35Z
37,698,332
<p>You could accomplish that with a simple <code>for</code> loop like so:</p> <pre><code>def find_position(astring, acharacter): positions = [] for c in range(len(astring)): if astring[c] == acharacter: positions.append(c) return positions </code></pre> <p>And test it:</p> <pre><code>...
0
2016-06-08T09:21:18Z
[ "python", "string", "python-3.x", "character" ]
Save one-hot-encoded features into Pandas DataFrame the fastest way
37,698,228
<p>I have a Pandas DataFrame with all my features and labels. One of my feature is categorical and needs to be one-hot-encoded.</p> <p>The feature is an integer and can only have values from <code>0 to 4</code></p> <p>To save those arrays back in my DataFrame I use the following code</p> <pre><code># enc is my OneHo...
1
2016-06-08T09:16:25Z
37,699,550
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/version/0.13.1/generated/pandas.get_dummies.html" rel="nofollow">pd.get_dummies</a>:</p> <pre><code>&gt;&gt;&gt; s 0 a 1 b 2 c 3 a dtype: object &gt;&gt;&gt; pd.get_dummies(s) a b c 0 1 0 0 1 0 1 0 2 0 0 1 3 1 0 0 </code></pre> ...
3
2016-06-08T10:11:55Z
[ "python", "pandas", "machine-learning", "scikit-learn" ]
UTF-8 text in HDInsight cluster with spark result encoding error 'ascii' codec can't encode characters in position: ordinal not in range(128)
37,698,276
<p>Trying to work with Hebrew characters UTF-8 TSV file in HDInsight cluster with spark on Linux and I get encoding error, any recommendations? </p> <p>There's my pyspark notebook code:</p> <pre><code>from pyspark.sql import * # Create an RDD from sample data transactionsText = sc.textFile("/people.txt") header = tr...
0
2016-06-08T09:19:10Z
37,739,117
<p>If you run the following code with the hebrew text:</p> <pre><code>from pyspark.sql import * path = "/people.txt" transactionsText = sc.textFile(path) header = transactionsText.first() # Create a schema for our data Entry = Row('id','name','age') # Parse the data and create a schema transactionsParts = transact...
2
2016-06-10T02:41:23Z
[ "python", "encoding", "ascii", "pyspark", "hdinsight" ]
Passing a dict of dict with Ajax
37,698,371
<p>I'm working on a website running on Django. I need to pass data from the Javascript to my Python code with Ajax.</p> <p>Here's my code:</p> <pre><code>// Javascript file function myFunc() { {...} // Generate var 'values' which is a dict of dict {{},{}...} console.log(JSON.stringify(values)); ...
2
2016-06-08T09:23:10Z
37,701,514
<p>jquery will breaks your js dict(it's called object in js) into multiple variables before sending via ajax so there is no dict on the python side , basically you can't pass a dictionary from js to python via ajax ... however they both understand json . </p> <p>so you need to json encode your dict before sending the...
1
2016-06-08T11:40:06Z
[ "javascript", "jquery", "python", "ajax", "django" ]
Python UT - Mocking a function local veriable
37,698,554
<p>I have a function as follows</p> <h2>Function</h2> <pre><code> def foo(arg1, arg2, arg3): # all the method code.... parent = arg1.get_item(larg1) if larg2 not in parent.children: # do stuff </code></pre> <p>I want to mock <code>parent</code> in the method, so that when I call <...
0
2016-06-08T09:29:52Z
37,700,408
<p>Mock the <code>arg1.get_item</code> method and return your expected value. If you want to return an object,you can also mock it as such.</p> <h2>fix</h2> <pre><code>@mock.patch( 'foo.bar.foo.get_item', mock.Mock(return_value=mock.Mock(children=[])) ) </code></pre>
0
2016-06-08T10:49:50Z
[ "python", "unit-testing", "mocking" ]
Create partial index with SqlAlchemy and Alembic
37,698,555
<p>I have the following model with the index: </p> <pre><code>class User(TableMixin, Base): username = Column(String, nullable=False, unique=False) password = Column(String, nullable=False, unique=False) Index('ix_active_username', "active", username, unique=True, postgresql_where=("a...
0
2016-06-08T09:29:55Z
37,699,906
<p>The complete solution:</p> <pre><code>class User(TableMixin, Base): username = Column(String, nullable=False, unique=False) password = Column(String, nullable=False, unique=False) class TableMixin(): id = Column(Integer, primary_key=True) active = Column(Boolean, nullable=False, default=True) Inde...
1
2016-06-08T10:27:05Z
[ "python", "sqlalchemy", "alembic" ]
Capture the URL in get request in Python
37,698,661
<p>I am writing python code to automate testing to download files. I have downloaded the file by clicking the download icon. What I am trying now is to assert that correct file was downloaded in the background. For this purpose, I need to extract the get request and parameters within. This parameters and URL will conta...
-1
2016-06-08T09:34:03Z
37,701,253
<p>I see two ways you can do that.</p> <ol> <li><p>Like I mentioned in the comment, you could simply check the 'href' attribute of the download link, instead of clicking it.</p></li> <li><p>Once the program has clicked the link, use:</p> <p>driver.implicitly_wait(5) #just to be on the safe side</p> <p>print driver.c...
0
2016-06-08T11:29:13Z
[ "python", "python-3.x" ]
Python: linear algebra package with domain checks
37,698,834
<p>Does it exists a (possibly efficient) linear algebra package that uses some form of domain check before performing linear operations?</p> <p><code>numpy</code> performs already some kind of domain check before linear operations: if dimensions don't match, it raises a <code>ValueError</code>. I would like to identif...
1
2016-06-08T09:41:35Z
37,759,406
<p>You can roll your own vector spaces by <a href="http://docs.scipy.org/doc/numpy-1.10.1/user/basics.subclassing.html#slightly-more-realistic-example-attribute-added-to-existing-array" rel="nofollow">subclassing numpy arrays</a>. I managed to come up with a simple subclass that is essentially a <code>numpy.ndarray</co...
1
2016-06-11T02:37:44Z
[ "python", "numpy", "linear-algebra" ]
Regexp for matching executable version number
37,698,919
<p>I'm trying to write a regular expression for matching executable version number.<br> It can be provided in two ways:</p> <ul> <li><code>MAJOR.MINOR.TINY</code></li> <li><code>MAJOR.MINOR.TINY.BUILD_NUMBER</code></li> </ul> <p>I do not need to parse these values, just check for match. So, I can: <code>^\d+[\.\d+]*$...
0
2016-06-08T09:44:51Z
37,699,149
<p>The regex should be like <code>re.compile(r'^\d+(\.\d+){2,3}$')</code></p>
4
2016-06-08T09:53:50Z
[ "python", "regex" ]
Regexp for matching executable version number
37,698,919
<p>I'm trying to write a regular expression for matching executable version number.<br> It can be provided in two ways:</p> <ul> <li><code>MAJOR.MINOR.TINY</code></li> <li><code>MAJOR.MINOR.TINY.BUILD_NUMBER</code></li> </ul> <p>I do not need to parse these values, just check for match. So, I can: <code>^\d+[\.\d+]*$...
0
2016-06-08T09:44:51Z
37,699,232
<p>Please check this <a href="http://regexr.com/3dj41" rel="nofollow">regex</a></p> <p><code>^((\d+\.){2,3}\d+)$</code></p>
0
2016-06-08T09:57:20Z
[ "python", "regex" ]
Plotting multi-line charts in python and embedding in HTML
37,698,928
<p>I am doing some data analysis in python. I have a time series data (for continuous dates) and I want to plot something like :</p> <p><img src="http://i.stack.imgur.com/G9NKm.png" alt="Image"></p> <p>I have plotted single line chart using matplotlib and embedded it to HTML using base64 encoding. But the concern is ...
0
2016-06-08T09:45:22Z
37,699,283
<p>You will need some Javscript to have animated graphs in HTML. You may consider using Bokeh, a Python wrapper to the D3.js library:</p> <p><a href="http://bokeh.pydata.org/en/latest/" rel="nofollow">http://bokeh.pydata.org/en/latest/</a></p>
0
2016-06-08T09:59:53Z
[ "python", "matplotlib" ]
Best way to prevent a main thread from completing it's execution
37,698,995
<p>An application, completely scheduled and monitored by some Job Monitor, implements a JMSMessageListener... now what is the best way to prevent this main thread (which is registering itself on JMS Queue) not to finish it's execution. Otherwise Job monitor will mark this job as completed while on message event thead w...
1
2016-06-08T09:47:56Z
37,702,750
<p>Neither will affect the CPU significantly. The python reactor is based off the <a href="https://en.wikipedia.org/wiki/Reactor_pattern" rel="nofollow">ractor pattern</a>, at it's core is an event loop with blocks until an event arrives and then handles it. In the trivial case there are no events provided so no work i...
0
2016-06-08T12:38:36Z
[ "python", "python-2.7", "jms", "twisted.internet" ]
Accessing a variable of the another program in C
37,699,120
<p>In python, you can learn memory location of variables by using id function, so:</p> <pre><code>X = "Hello world!" print(id(X)) # Output is equal to 139806692112112 (0x7F27483876F0) </code></pre> <p>I'm tried to access to variable with pointers in C (Surely the other program still alive):</p> <pre><code>#include &...
5
2016-06-08T09:52:43Z
37,699,496
<p>Doing something like this is more and more impossible these days. With features like address space layout randomization you can't really tell where a given program, let alone variable will load in actual memory.</p> <p>Best bet is to use some type of message passing. Not sure why all the downvotes on your questio...
3
2016-06-08T10:09:14Z
[ "python", "c++", "c" ]
Setting variables with Django signals without using globals
37,699,186
<p>In Django 1.9 I construct a list of forms based on a database table corresponding to <code>TheModel</code> in my <code>forms.py</code>. When the database table changes I want the forms to change as well. Therefore I set up a Django signal to listen to the change and update the forms. My problem is now that nothing c...
-1
2016-06-08T09:55:07Z
37,700,705
<p>As @Jerzyk pointed out, caching the forms will only work in a single-threaded environment and will most likely fail in production. The signal is only sent and handled in the thread where the save/delete happened. Other processes will be unaware of the change.</p> <p>Instead, store the query used to build the form i...
0
2016-06-08T11:03:25Z
[ "python", "django", "django-signals" ]
Separate text from URL in Excel column
37,699,245
<p>What I have is a column in Excel with a list of URLs like this:</p> <ul> <li><a href="http://www.example.com/1" rel="nofollow">first link</a></li> <li><a href="http://www.example.com/2" rel="nofollow">second link</a></li> <li>...</li> </ul> <p>What I would like is to separate the "text" from the "URL" like this:</...
3
2016-06-08T09:57:59Z
37,699,696
<p>Three steps simple solution (for Google Sheets):</p> <ul> <li><p>just copy and '<em>paste values only</em>' to get the text (or use concatenate-with-nothing)</p></li> <li><p>check this <a href="http://webapps.stackexchange.com/questions/89557/extract-the-link-text-and-url-from-a-hyperlinked-cell">answer</a> for a c...
3
2016-06-08T10:18:06Z
[ "python", "excel", "libreoffice-calc" ]
Scrapy, how to limit time per domain?
37,699,528
<p>I have been searching for an answer and there is no answer on this forum although several questions have been asked. One answer is the it is possible to stop spider after certain time but that is not suitable for me because I usually launch 10 websites per spider. So my challenge is that I have spider for 10 website...
0
2016-06-08T10:10:50Z
37,714,568
<p>Just use <code>scrapyd</code> to schedule 2000 single web-site crawls. Set <code>max_proc</code> = 10 [<a href="http://scrapyd.readthedocs.io/en/stable/config.html#max-proc" rel="nofollow">1</a>] to run 10 spiders in parallel. Set spider's <code>CLOSESPIDER_TIMEOUT</code> [<a href="http://doc.scrapy.org/en/latest/to...
1
2016-06-08T23:27:17Z
[ "python", "time", "scrapy" ]
Python Pandas CSV import / Unicode woes
37,699,684
<p>I am working with message board posts (contained in <code>CSV</code> files), trying to clean data/etc, before training classification models. </p> <p>Things were going well, until I got:</p> <blockquote> <p>TypeError: 'float' object is not iterable</p> </blockquote> <p>in response to the line:</p> <pre><code>l...
2
2016-06-08T10:17:40Z
37,700,696
<p>I think you need check <code>NaN</code> values in your <code>DataFrame</code>, which is created from <code>csv</code>. You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isnull.html" rel="nofollow"><code>isnull</code></a> with <a href="http://pandas.pydata.org/pandas-docs/sta...
1
2016-06-08T11:02:30Z
[ "python", "csv", "pandas", "classification" ]
Extract json fields and write them into a csv with python
37,699,691
<p>I've got a very big json with multiple fields and I want to extract just some of them and then write them into a csv.</p> <p>Here is my code:</p> <pre><code>#!/usr/bin/python3 # -*- coding: utf-8 -*- import json import csv data_file = open("book_data.json", "r") values = json.load(data_file) data_file.close() ...
2
2016-06-08T10:17:53Z
37,699,983
<p>You need to encode the data:</p> <pre><code>wr.writerow([key.encode("utf-8"), value.encode("utf-8")]) </code></pre> <p>The difference is equivalent to:</p> <pre><code>In [8]: print u'\u2019'.encode("utf-8") ’ In [9]: print str(u'\u2019') -------------------------------------------------------------------------...
3
2016-06-08T10:31:03Z
[ "python", "json", "csv" ]
Python regex: return the whole sentence with a certain word in it from period to period
37,699,760
<p>Below is the sentence I want to process. It consists of IDs which start with two hashes at the front (<code>##2312435</code>) plus remaining text. I need a regular expression that would find sentences with word <code>likely</code> in them and would retrieve the whole sentence plus the ID. </p> <p>Sentence:</p> <bl...
1
2016-06-08T10:20:45Z
37,700,454
<p>So it's very ugly, and works only in case if there only one sentence with word <code>likely</code>:</p> <pre><code>re.findall(r'##(\d+)(?:[^#]*\.)*([^#.]*?likely[^#.]*?)\.', text, re.IGNORECASE) # Output: #[('2312435', ' John is likely to come home after midnight'), # ('2233442', ' Mark is likely to have a beer to...
2
2016-06-08T10:51:45Z
[ "python", "regex", "text-analysis" ]
Python regex: return the whole sentence with a certain word in it from period to period
37,699,760
<p>Below is the sentence I want to process. It consists of IDs which start with two hashes at the front (<code>##2312435</code>) plus remaining text. I need a regular expression that would find sentences with word <code>likely</code> in them and would retrieve the whole sentence plus the ID. </p> <p>Sentence:</p> <bl...
1
2016-06-08T10:20:45Z
37,700,750
<pre><code>p = re.compile(r'^##\d+.*likely.*$') res = p.match(t).group().replace('##','') </code></pre> <p>For example,</p> <pre><code>&gt;&gt;&gt; t = '##2312435 Jon is not home. John is likely to come home after midnight. Another not related sentence. ##2233442 Mark is very angry. Mark is likely to have a beer toni...
0
2016-06-08T11:06:05Z
[ "python", "regex", "text-analysis" ]
Python regex: return the whole sentence with a certain word in it from period to period
37,699,760
<p>Below is the sentence I want to process. It consists of IDs which start with two hashes at the front (<code>##2312435</code>) plus remaining text. I need a regular expression that would find sentences with word <code>likely</code> in them and would retrieve the whole sentence plus the ID. </p> <p>Sentence:</p> <bl...
1
2016-06-08T10:20:45Z
37,700,811
<p>Any regex for this task will look ugly, but we can make it at least efficient.</p> <p>The basic regex is to match the <code>##</code> + digits, capture these digits, then match any text that is not <code>##</code> + digit, then <code>likely</code>, then again any text that is not <code>##</code> + digit.</p> <pre>...
0
2016-06-08T11:08:32Z
[ "python", "regex", "text-analysis" ]
Recursive traversal of xml tags is not printing the value of the (sub tags) Ref.tail
37,699,859
<h1>Xml Document</h1> <p>We have the following xml file:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;doc id="ENG_DF_000170_20150219_F0010008Z"&gt; &lt;post id="p10" author="Kosh" datetime="2015-02-19T21:33:00"&gt; &lt;quote orig_author="Luddly Neddite"&gt; &lt;quote orig_author="zeke"&gt; &lt;quot...
0
2016-06-08T10:25:15Z
37,701,368
<p>Because only the first text node in each element would be stored as <code>text</code> of the element. Text nodes that preceded by other child element would be stored as <code>tail</code> of the corresponding child element. You can use the following logic to get all direct child text nodes given a parent element. It ...
1
2016-06-08T11:34:27Z
[ "python", "xml", "recursion" ]
Building a simple operattion type calculator for two digits? stuck at error
37,699,987
<pre><code>print("Welcome to MusCalculator") print("For adding two no type add") print("for mutiplying type multiply") print("for subtraction type subtract") print("for dividing type divide") def add_numbers(x, y): if input == "addition": addition = x + y print addition if input == "multiply":...
-3
2016-06-08T10:31:24Z
37,700,882
<p>There are some problems in your code. Some are mentioned below. Addition variable is used in your main code, you might want to try different name or declare addition as a global variable.</p> <p>under or above your print statements: addition = 0</p> <p>Also you are setting the received operation into variable name...
0
2016-06-08T11:11:47Z
[ "python" ]
Using findAll to retrieve date with no class and id
37,700,282
<p>So I have following HTML. </p> <pre><code>&lt;div class="media-body"&gt;&lt;i class="" style="text-shadow:1px 1px 0px #dcdcdc;"&gt;29 May 2016 &lt;/i&gt;&lt;a href="http://www.sharesansar.com/events/opening-day-of-auction-of-tinau-development-bank-limited-21903-32-units-ordinary-unclaimed-right-share/"&gt;&lt;h4 ...
1
2016-06-08T10:44:27Z
37,701,106
<p>Remember to increase your <code>page counter</code>. With a simple modification to your code and without error checking (it up to you) it works just fine:</p> <pre><code>import requests from bs4 import BeautifulSoup def events_log(max_pages): page = 1 while page &lt;= max_pages: url = 'http://www.s...
1
2016-06-08T11:23:16Z
[ "python", "web-scraping", "beautifulsoup" ]
How to limit the choice of the Fields.Selection in python
37,700,340
<p>I have a fields types selection with the following values:</p> <pre><code>_CATEGORY_SELECT = [ ('tap','Finished products'), ('nvl','Materials'), ('lik','Components'), ('hth','Item consumption'), ('dlk','workwear Supplies perio...
0
2016-06-08T10:47:03Z
37,700,446
<pre><code>[x for x in _CATEGORY_SELECT if x[0] in ['dlx','dlk']] </code></pre>
0
2016-06-08T10:51:22Z
[ "python", "openerp" ]
How to limit the choice of the Fields.Selection in python
37,700,340
<p>I have a fields types selection with the following values:</p> <pre><code>_CATEGORY_SELECT = [ ('tap','Finished products'), ('nvl','Materials'), ('lik','Components'), ('hth','Item consumption'), ('dlk','workwear Supplies perio...
0
2016-06-08T10:47:03Z
37,701,344
<p>You can also use <code>filter()</code></p> <p><code>filter(lambda x: x[0] in ['dlx','dlk'], _CATEGORY_SELECT)</code></p>
0
2016-06-08T11:33:27Z
[ "python", "openerp" ]
Check if <sqlalchemy.engine.result.ResultProxy> object is empty
37,700,387
<p>I'm downloading some data from a SQL Server database through a library that leverages <code>pymssql</code> in the back-end. The result of a <code>curson.execute("""&lt;QUERY BODY&gt;""")</code> is a <code>sqlalchemy.engine.result.ResultProxy</code> object. How can I check if the result of the query was empty, so the...
0
2016-06-08T10:49:01Z
37,700,970
<p>The <code>ResultProxy</code> object does not contain any rows yet. Therefore it has no information about the total amount of them, or even whether there are any. <code>ResultProxy</code> is just a "pointer" to the database. You get your rows only when you explicitly fetch them via <code>ResultProxy</code>. You can d...
0
2016-06-08T11:16:36Z
[ "python", "sqlalchemy" ]
Searching a text file for a line of text matching the text inputted from a user Python
37,700,475
<p>When the user enters a phrase, key words out of the phrase needs to be matched to text in a text file and then the line out of the text file can be printed back to the user.</p> <p>e.g. when a user types in "my phone screen is blank" or "the display screen is blank" there should be the same solution outputted to th...
1
2016-06-08T10:52:37Z
37,700,792
<p>You can use <a href="https://docs.python.org/2/library/functions.html#raw_input" rel="nofollow">raw_input</a></p> <p>Here is the working code:</p> <pre><code>search_file = open(r"D:\phone.txt", "r") question = raw_input(" Welcome to the phone help center, What is the problem?") if question in ["screen", "display"...
0
2016-06-08T11:07:51Z
[ "python", "arrays", "string", "search" ]
Searching a text file for a line of text matching the text inputted from a user Python
37,700,475
<p>When the user enters a phrase, key words out of the phrase needs to be matched to text in a text file and then the line out of the text file can be printed back to the user.</p> <p>e.g. when a user types in "my phone screen is blank" or "the display screen is blank" there should be the same solution outputted to th...
1
2016-06-08T10:52:37Z
37,703,014
<p>First these 2 lines do not work as per your requirement:</p> <pre><code>question = raw_input(" Welcome to the phone help center, What is the problem?") if question in ["screen", "display", "blank"]: </code></pre> <p>If user types <em>my phone screen is blank</em>, as the full sentence is not member of the list, th...
0
2016-06-08T12:50:09Z
[ "python", "arrays", "string", "search" ]
Python GDAL does not install on Mac OSX El Capitan
37,700,484
<p>I am having several issues when installing pygdal in my Mac OSX El capitan. The procedure is the folowing:</p> <ol> <li>Install GDAL Libraries from <a href="http://www.kyngchaos.com/software/frameworks#gdal_complete" rel="nofollow">http://www.kyngchaos.com/software/frameworks#gdal_complete</a></li> <li><code>pip in...
1
2016-06-08T10:53:09Z
37,707,062
<p>I finally (with a little help from <a href="http://stackoverflow.com/users/5389320/cam-aust">Cam_Aust</a>) solved the problem !!! </p> <p>Here is what I did:</p> <ol> <li>Find the cp_port.h file in your system: <code>sudo find / -name cpl_port.h</code>, My output was:</li> </ol> <p><code>/Library/Frameworks/GDAL....
1
2016-06-08T15:39:16Z
[ "python", "osx", "osx-elcapitan", "gdal" ]
Want to open a tkinter window simultaneously with a matplotlib window?
37,700,488
<p>'''My code opens the matplotlib window and the tkinter but tkinter window opens after quitting the matplotlib window. I want both of them to pop up at the same time.'''</p> <pre><code>from pylab import * import matplotlib.pyplot as plt from matplotlib import style import numpy as np import pylab style.use('seaborn-...
2
2016-06-08T10:53:38Z
37,703,246
<p>just put everything before <code>show()</code>:</p> <pre><code>... root=Tk() w=Label(root, text="hello") w.pack() #root.mainloop() # Don't use this grid() show() </code></pre>
1
2016-06-08T12:59:52Z
[ "python", "matplotlib", "tkinter" ]
python: receive indentation error for unknown reason
37,700,538
<p>I don't understand why the following code work:</p> <pre><code>if trend == 1: maeName = tempMae.dif.idxmax() else: maeName = tempMae.dif.abs().idxmin() </code></pre> <p>While the following code:</p> <pre><code>if trend == 1: maeValue = tempMae.dif.max() maeName = tempMae.dif.idxmax() else: mae...
-3
2016-06-08T10:55:32Z
37,700,787
<p>It is possible you have mixed tabs and spaces. They do look alike.</p>
4
2016-06-08T11:07:33Z
[ "python" ]
python: receive indentation error for unknown reason
37,700,538
<p>I don't understand why the following code work:</p> <pre><code>if trend == 1: maeName = tempMae.dif.idxmax() else: maeName = tempMae.dif.abs().idxmin() </code></pre> <p>While the following code:</p> <pre><code>if trend == 1: maeValue = tempMae.dif.max() maeName = tempMae.dif.idxmax() else: mae...
-3
2016-06-08T10:55:32Z
37,701,091
<p>You may run your script with an options like this:</p> <pre><code>python script_file.py -tt </code></pre> <p>to read docs what exactly its doing you may <a href="https://docs.python.org/2.7/using/cmdline.html#cmdoption-t" rel="nofollow">here</a></p>
2
2016-06-08T11:22:33Z
[ "python" ]
Pandas Python. Top 3 recommended items in a column
37,700,808
<p>I am new to Pandas and I was given a task: for every product find three other products that are most viewed together in the same session</p> <p>Data frame <code>viewed.products</code> looks like:</p> <pre><code>session products 00b3a43caf4209d2/10 1536 00b3a43caf4209d2/10 42 00b3a43caf4209d2/10 395 00b...
0
2016-06-08T11:08:29Z
37,700,856
<p>I think you can use first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a> column <code>products</code> on <code>session</code> and then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofoll...
1
2016-06-08T11:10:10Z
[ "python", "pandas" ]
How to return a dataframe value from row and column reference?
37,700,960
<p>I know this is probably a basic question, but somehow I can't find the answer. I was wondering how it's possible to return a value from a dataframe if I know the row and column to look for? E.g. If I have a dataframe with columns <code>1-4</code> and rows <code>A-D</code>, how would I return the value for <code>B4</...
0
2016-06-08T11:16:16Z
37,700,990
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#different-choices-for-indexing" rel="nofollow"><code>ix</code></a> for this:</p> <pre><code>In [236]: df = pd.DataFrame(np.random.randn(4,4), index=list('ABCD'), columns=[1,2,3,4]) df Out[236]: 1 2 3 4 ...
2
2016-06-08T11:17:45Z
[ "python", "pandas", "indexing", "dataframe", "scalar" ]
How to return a dataframe value from row and column reference?
37,700,960
<p>I know this is probably a basic question, but somehow I can't find the answer. I was wondering how it's possible to return a value from a dataframe if I know the row and column to look for? E.g. If I have a dataframe with columns <code>1-4</code> and rows <code>A-D</code>, how would I return the value for <code>B4</...
0
2016-06-08T11:16:16Z
37,700,999
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.at.html" rel="nofollow"><code>at</code></a>, if rows are <code>A-D</code> and columns <code>1-4</code>:</p> <pre><code>print (df.at['B', 4]) </code></pre> <p>If rows are <code>1-4</code> and columns <code>A-D</code>:</p> <pre><cod...
0
2016-06-08T11:18:09Z
[ "python", "pandas", "indexing", "dataframe", "scalar" ]
shutil copy a tempfile to overwrite another
37,701,055
<pre><code>import tempfile import shutil tmp_f = tempfile.NamedTemporaryFile(delete=False) tmp_f.write("hello world") shutil.copy(tmp_f.name, "/etc/exports") </code></pre> <p>when I read "/etc/exports", it is a completely empty file. what is wrong?</p>
0
2016-06-08T11:20:43Z
37,701,385
<p>You need to close the file:</p> <pre><code>tmp_f.write("hello world") tmp_f.close() </code></pre>
1
2016-06-08T11:35:09Z
[ "python", "temporary-files", "shutil" ]
python3 and RO package and DS9
37,701,200
<p>How to get RO package working in Python 3? I managed to get it to work in Python 2.7, but when I install it manually as <code>python3 setup.py install</code> and then do <code>import RO.DS9</code> I get this:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File ...
0
2016-06-08T11:27:09Z
37,701,370
<p>In Python 3, <a href="https://docs.python.org/3/library/collections.html?highlight=userstring#collections.UserString" rel="nofollow"><code>UserString</code> is part of the <code>collections</code> module</a>.</p> <p>As you can see on <a href="https://pypi.python.org/pypi/RO" rel="nofollow">the RO page</a>, this lib...
1
2016-06-08T11:34:38Z
[ "python", "python-3.x" ]
How can I rename multiple columns with numbers in python?
37,701,373
<p>I have a data frame with ~2400 columns and I would like to rename all the columns from <code>1</code> to <code>2400</code>.<br /> My current columns names are numbers and almost all of them are duplicated.</p> <p>I was trying something like that but it doesn't work :</p> <pre><code># An example import pandas as pd...
3
2016-06-08T11:34:43Z
37,702,816
<p>IIUC you can just do</p> <pre><code>df.columns = pd.Index(np.arange(1,len(df.columns)+1).astype(str) </code></pre> <p>So this just overwrites the columns with a new <code>Index</code> object generated from <code>np.arange</code> and we cast the dtype to <code>str</code> using <code>astype</code></p> <p>Example:</...
1
2016-06-08T12:41:00Z
[ "python", "dictionary", "pandas", "rename", "multiple-columns" ]
How can I rename multiple columns with numbers in python?
37,701,373
<p>I have a data frame with ~2400 columns and I would like to rename all the columns from <code>1</code> to <code>2400</code>.<br /> My current columns names are numbers and almost all of them are duplicated.</p> <p>I was trying something like that but it doesn't work :</p> <pre><code># An example import pandas as pd...
3
2016-06-08T11:34:43Z
37,702,920
<p><code>np.arange</code> certainly works, but you could also just use a <code>list</code> comprehension:</p> <pre><code>df.columns = [i for i in range(len(df.columns))] </code></pre> <p>If you want them as strings, use <code>[str(i) for i in range(len(df.columns))]</code></p>
1
2016-06-08T12:46:33Z
[ "python", "dictionary", "pandas", "rename", "multiple-columns" ]
scrapy - item loader - mysql
37,701,691
<p>I am starting to learn scrapy. I want to use an item loader and write some data to MySQL. The code below works perfectly fine when I use argument "TakeFirst()" for the output processor in items.py. However, I need to get all the entries to MySQL, not only the first. When I use argument "MapCompose()" instead, I get ...
0
2016-06-08T11:49:45Z
37,703,080
<p>You need to pass <code>string</code> values to mysql, that's why <code>TakeFirst()</code> works, because it transforms the list that you get inside your loader, and only gets the first element (this is the normal procedure, because it normally gets staff like <code>['myvalue']</code> on which case is perfectly ok to...
2
2016-06-08T12:53:09Z
[ "python", "mysql", "scrapy" ]
scrapy - item loader - mysql
37,701,691
<p>I am starting to learn scrapy. I want to use an item loader and write some data to MySQL. The code below works perfectly fine when I use argument "TakeFirst()" for the output processor in items.py. However, I need to get all the entries to MySQL, not only the first. When I use argument "MapCompose()" instead, I get ...
0
2016-06-08T11:49:45Z
37,705,024
<p>You need to create an item per entry in the listing, something like this:</p> <pre><code>import scrapy from scrapy.loader import ItemLoader from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor class TestCrawlSpider(CrawlSpider): name = "test_crawl" allowed_domains =...
1
2016-06-08T14:14:47Z
[ "python", "mysql", "scrapy" ]
Splitting bracket delimited text which can contain quoted strings
37,701,766
<p>I am trying to split some text. Basically I want to separate level-1 brackets, like <code>"('1','a',NULL),(2,'b')"</code> => <code>["('1','a',NULL)", "(2,'b')]"</code>, but I need to be aware of possible quoted strings inside. It needs to at least satisfy the following py.tests:</p> <pre><code>from splitter import ...
3
2016-06-08T11:53:51Z
37,703,026
<p>I cooked this and it works on given tests.</p> <pre><code>tests = ["('1'),('2')", "(1),(2),(3)", "('1','a'),('2','b')", "('1','a',NULL),(2,'b')", "('\\'1','a'),('2','b')", "('1','a,c'),('2','b')", "('1','a)c'),('2','b')", "('1','a),(c'),('2','b')", "('1','a\\'),(c'),('2','b')"] for text in tests: tmp = '' ...
0
2016-06-08T12:50:34Z
[ "python", "regex", "pyparsing", "finite-state-machine" ]
Splitting bracket delimited text which can contain quoted strings
37,701,766
<p>I am trying to split some text. Basically I want to separate level-1 brackets, like <code>"('1','a',NULL),(2,'b')"</code> => <code>["('1','a',NULL)", "(2,'b')]"</code>, but I need to be aware of possible quoted strings inside. It needs to at least satisfy the following py.tests:</p> <pre><code>from splitter import ...
3
2016-06-08T11:53:51Z
37,705,415
<p>One way would be to use the newer <a href="https://pypi.python.org/pypi/regex" rel="nofollow"><strong><code>regex</code></strong></a> module which supports the <code>(*SKIP)(*FAIL)</code> functionality:</p> <pre><code>import regex as re def split_text(text): rx = r"""'.*?(?&lt;!\\)'(*SKIP)(*FAIL)|(?&lt;=\)),(?...
3
2016-06-08T14:30:32Z
[ "python", "regex", "pyparsing", "finite-state-machine" ]
Splitting bracket delimited text which can contain quoted strings
37,701,766
<p>I am trying to split some text. Basically I want to separate level-1 brackets, like <code>"('1','a',NULL),(2,'b')"</code> => <code>["('1','a',NULL)", "(2,'b')]"</code>, but I need to be aware of possible quoted strings inside. It needs to at least satisfy the following py.tests:</p> <pre><code>from splitter import ...
3
2016-06-08T11:53:51Z
37,724,529
<p>This is the regular expression which seems to work and passes all the tests. Running it on real data it is about 6x faster than finite state machine implemented in Python.</p> <pre><code>PATTERN = re.compile( r""" \( # Opening bracket (?: # String (?:'(?: ...
0
2016-06-09T11:20:10Z
[ "python", "regex", "pyparsing", "finite-state-machine" ]
Scrapy selector not working on Splash response
37,701,774
<p>I'm trying to scrape some dynamic content using Scrapy. I have succesfully set up Splash to work along with it. However, the selectors of the following spider yield empty results:</p> <pre><code># -*- coding: utf-8 -*- import scrapy from scrapy.selector import Selector from scrapy_splash import SplashRequest cla...
2
2016-06-08T11:54:20Z
37,703,312
<p>I've tried that <code>SplashRequest</code> and ran into the same problem as you did. After messing around I tried executing a LUA script instead.</p> <pre><code>script = """ function main(splash) local url = splash.args.url assert(splash:go(url)) assert(splash:wait(0.5)) return { html = ...
2
2016-06-08T13:02:38Z
[ "python", "web-scraping", "scrapy", "splash" ]
Scrapy selector not working on Splash response
37,701,774
<p>I'm trying to scrape some dynamic content using Scrapy. I have succesfully set up Splash to work along with it. However, the selectors of the following spider yield empty results:</p> <pre><code># -*- coding: utf-8 -*- import scrapy from scrapy.selector import Selector from scrapy_splash import SplashRequest cla...
2
2016-06-08T11:54:20Z
37,706,589
<p>Your spider works fine with me, with Scrapy 1.1, Splash 2.1 and no modification of the code in your question, just using settings suggested in <a href="https://github.com/scrapy-plugins/scrapy-splash" rel="nofollow">https://github.com/scrapy-plugins/scrapy-splash</a></p> <p>As other have mentioned, your <code>parse...
3
2016-06-08T15:17:50Z
[ "python", "web-scraping", "scrapy", "splash" ]
Scrapy selector not working on Splash response
37,701,774
<p>I'm trying to scrape some dynamic content using Scrapy. I have succesfully set up Splash to work along with it. However, the selectors of the following spider yield empty results:</p> <pre><code># -*- coding: utf-8 -*- import scrapy from scrapy.selector import Selector from scrapy_splash import SplashRequest cla...
2
2016-06-08T11:54:20Z
38,693,397
<p>I don't have enough reputations to add a comment, so I have to make an answer here.</p> <p>I am facing a similar issue with Splash 2.1 returning "malformed"(uncompressed gziped actually speeking ) html content if I set <code>'Accept-Encoding': 'gzip'</code> for a SplashRequest.</p> <p>Finally, I found the solution...
1
2016-08-01T07:42:12Z
[ "python", "web-scraping", "scrapy", "splash" ]
How would one go about "un-importing" a SINGLE module?
37,701,838
<p>Just out of curiosity, how would one go about <em><code>un-importing</code></em> a module?</p> <p>For example, you import a couple of modules like this:</p> <pre><code>import x, y, z </code></pre> <p>Then say for some reason you don't want and / or need module <code>y</code> to be included anymore, how would you ...
2
2016-06-08T11:56:43Z
37,702,213
<p>From the docs:</p> <blockquote> <p>Import statements are executed in two steps: (1) find a module, and initialize it if necessary; (2) define a name or names in the local namespace (of the scope where the import statement occurs). </p> </blockquote> <p>If you need a module temporarily and you are concerned about...
2
2016-06-08T12:14:51Z
[ "python", "python-3.x", "import", "module", "python-import" ]
Django-tables2 column total
37,701,875
<p>I'm trying to sum up all values from column using this <a href="https://github.com/bradleyayers/django-tables2/blob/master/docs/pages/column-headers-and-footers.rst" rel="nofollow">documentation</a>, but footer doesn't show up. I'm I missing something?</p> <p><strong>models.py</strong></p> <pre><code>class Mokejim...
0
2016-06-08T11:58:51Z
37,744,112
<p>Your screenshot shows that django-tables2 correctly assumes there is a footer on your table (yay!) but it seems that nothing is returned from the lambda. You can try to replace it by something like this to see what's going on:</p> <pre><code>def suma_footer(table): try: s = sum(x['suma'] for x in table....
0
2016-06-10T09:01:07Z
[ "python", "django", "django-tables2" ]
Removing an element from a parsed XML tree disrupts iteration
37,702,011
<p>I want to parse an xml file, then process the result tree by removing selected elements. My problem is that removing an element disrupts the loop that iterates over the elements.</p> <p>Consider the following xml data:</p> <pre><code>&lt;results&gt; &lt;group&gt; &lt;a /&gt; &lt;b /&gt; ...
2
2016-06-08T12:05:45Z
37,779,451
<p>The issue is you are removing elements from something you are iterating over, when you remove an element the remaining elements get shifted so you can end up removing the incorrect elements: </p> <p>A simple solution is to iterate over a copy of the tree or use <em>reversed</em>:</p> <p>copy:</p> <pre><code> de...
1
2016-06-12T21:57:13Z
[ "python", "xml" ]
Migration for model inherited from Django
37,702,032
<p>We're using <code>CustomFlatPage</code> model derived from <code>django.FlatPage</code> model in our application. It works fine, but the <code>FlatPage</code> changed in Django 1.9, which triggers the migration for our <code>CustomFlatPage</code>. But we'd like to have a clean migrations, that is state where <code>m...
0
2016-06-08T12:06:47Z
37,811,571
<p>Based on my investigation and on comments provided, it looks like there is no solution for the moment.</p>
0
2016-06-14T12:07:08Z
[ "python", "django", "django-models", "django-migrations" ]
Can you give a method an attribute created by another method in the same class in pygame?
37,702,235
<p>I have some code where I am trying to animate a sprite. However, I need to use an attribute (direction) defined in a method (walk) in my method (animate). Is this possible?</p> <pre><code>class character(): </code></pre> <p>init and animate are here</p> <pre><code> def walk(self, x, y, direction): if e...
0
2016-06-08T12:16:09Z
37,704,120
<p>Sure,</p> <p>You can initialise the attribute in <code>__init__</code>,</p> <p>change it in <code>walk</code>,</p> <p>and call it using <code>Character.animate(Character.direction)</code></p> <p>an example:</p> <pre><code>class Character(): def __init__(self): self.direction = 0 def walk(self, ...
0
2016-06-08T13:37:36Z
[ "python", "class", "pygame" ]
Comparing one list to see in which position it appears in another
37,702,245
<p>Here's my Python code which doesn't work. One list is called <code>sentencelist</code>the other is called <code>noduplicateslist</code>. For each word in <code>sentencelist</code>, I want to find that word's index in <code>noduplicateslist</code>.</p> <p>For example, sentencelist may be THE CAT SAT ON THE MAT and n...
0
2016-06-08T12:16:24Z
37,705,465
<p>You most likely would benefit from reading about list.index(), as described <a href="https://docs.python.org/3/tutorial/datastructures.html" rel="nofollow">here</a>.</p> <p>Example usage which produces your desired output:</p> <pre><code>for word in sentencelist: print(noduplicateslist.index(word)) </code>...
2
2016-06-08T14:32:19Z
[ "python", "list", "compare" ]
Alternative to batch importer for neo4j for large datasets
37,702,298
<p>I am trying to import a large dataset to neo4j.I created a python script to write the cypher queries into a .cql file after reading a .xls file and then I ran them using the neo4j-shell.This worked for a small dataset.But on increasing the size of dataset my system crashed for the same.I have seen few suggestions to...
0
2016-06-08T12:18:39Z
37,703,338
<p>You could try the Neo4J <strong>Load CSV</strong> tool / cypher command. It is very flexible and can be used with the <strong>USING PERIODIC COMMIT </strong> to process very large datasets by making periodic commits to prevent buffer overflow problems and optimize the process further.</p> <p>The only prerequisite i...
1
2016-06-08T13:04:00Z
[ "python", "groovy", "neo4j", "large-data", "neo4j-batch-inserter" ]
Python script to extract all subdirectories according to filename
37,702,301
<p>My directory contains several folders, each with several subdirectories of their own. I need to move all of the files that contain 'Volume.csv' into a directory called Volume. </p> <pre><code>Folder1 |---1Area.csv |---1Circumf.csv |---1Volume.csv Folder2 |---2Area.csv |---2Circumf.csv |---2Volume.csv Volume </cod...
0
2016-06-08T12:18:41Z
37,702,998
<pre><code>import os import shutil </code></pre> <p>Setup your source and destination directories</p> <pre><code>source_dir = "/Users/nenad/Documents/Python Files/Random Tests" dest_dir = "/Users/nenad/Documents/Python Files/Random Tests/volume" </code></pre> <p>This set will now hold paths of all files matching you...
0
2016-06-08T12:49:33Z
[ "python" ]
Python script to extract all subdirectories according to filename
37,702,301
<p>My directory contains several folders, each with several subdirectories of their own. I need to move all of the files that contain 'Volume.csv' into a directory called Volume. </p> <pre><code>Folder1 |---1Area.csv |---1Circumf.csv |---1Volume.csv Folder2 |---2Area.csv |---2Circumf.csv |---2Volume.csv Volume </cod...
0
2016-06-08T12:18:41Z
37,703,470
<p>You can use <code>glob</code> for this. It returns a list of path names matching the expression you give it. </p> <pre><code>import glob import shutil dest = 'testfiles/' files = glob.glob('*/*test.csv') for file in files: shutil.move(file, dest) </code></pre> <p>I used relative paths but you can also use a...
2
2016-06-08T13:10:16Z
[ "python" ]
Removing unwanted parts of picture
37,702,389
<p>I have a group of pictures, that I want to recognize the characters.I wrote the code that recognize the numbers and characters with Neural Networks, In the picture there are some other parts like Logo and the name of Company which they're not necessary. what approach should I use to remove these things? As the name ...
0
2016-06-08T12:22:47Z
37,717,880
<p>I'd suggest you first segment out the characters and then you pass it on to your neural net for recognition. If you have the information of the unwanted characters beforehand (i.e. if you know that only this particular Logo and dash is going to repeat) then you can have a template of it, threshold it, and find the c...
0
2016-06-09T05:54:10Z
[ "python", "image", "opencv", "image-processing" ]
How can I see contents of gzip file with paramiko?
37,702,408
<p>Once I connect to a remote server as follows, </p> <pre><code>transport.connect(username=username, password=password) sftp = paramiko.SFTPClient.from_transport(transport) </code></pre> <p>I can do <code>sftp.listdir()</code> and see that there are some gzip files on the remote server, like <code>example.gz.2016</c...
0
2016-06-08T12:23:23Z
37,702,799
<p>Your question has two parts:</p> <ol> <li>How to view the content of a zip file from the command line</li> <li>How to execute remote commands and get the output using python&amp;paramiko</li> </ol> <p><strong>First</strong> things first: How to list the content of a zip file on the console. <a href="https://superu...
1
2016-06-08T12:40:17Z
[ "python", "bash", "networking", "gzip", "paramiko" ]
Draw half infinite lines?
37,702,642
<p>I use pyqtgraph for data acquisition and I have to represent some thresholds on the graphics view. For example to represent a high voltage limit, etc. I used the class <code>InfiniteLine</code> from pyqtgraph, but now, I have to take into account some possible changes on the threshold value during the acquisition. ...
1
2016-06-08T12:34:07Z
37,836,348
<p>Your approach looks good and is mostly what <code>pyqtgraph.InfiniteLine</code> is doing. I examined <a href="https://github.com/pyqtgraph/pyqtgraph/blob/master/pyqtgraph/graphicsItems/InfiniteLine.py" rel="nofollow">the source of InfiniteLine</a> and extracted those parts which are absolutely necessary and added th...
1
2016-06-15T13:06:13Z
[ "python", "pyqt", "pyqtgraph" ]
Draw half infinite lines?
37,702,642
<p>I use pyqtgraph for data acquisition and I have to represent some thresholds on the graphics view. For example to represent a high voltage limit, etc. I used the class <code>InfiniteLine</code> from pyqtgraph, but now, I have to take into account some possible changes on the threshold value during the acquisition. ...
1
2016-06-08T12:34:07Z
37,922,685
<p>thanks you for you very complete answer ! Your code works very well. I made some modifications on your class InfiniteLineWithBreak in order to set multiple threshold transitions. I modified the <strong>init</strong> and the paint methods only:</p> <pre><code>def __init__(self, listOfcouplesOfThresholdAndItsDate, ...
1
2016-06-20T12:32:06Z
[ "python", "pyqt", "pyqtgraph" ]
Periodic List in Python
37,702,651
<p>I’m trying to create a circular list in Python. I.e., a list where <code>list[x]</code> is equal to <code>list[x - len(list)]</code> if <code>x</code> > <code>len(list)</code>.</p> <p>Here is the code below:</p> <pre><code>class Circ(list): def __getitem__(self, idx): while (idx &gt; len(self)): ...
0
2016-06-08T12:34:25Z
37,702,762
<p>You have an off-by-one error. Python list indices start at <em>zero</em>, so valid indices are 0, 1 and 2. Since <code>3</code> is equal to <code>len(self)</code> however, you never reduce it.</p> <p>Test if <code>idx</code> is greater than <strong>or equal to</strong> the length:</p> <pre><code>while idx &gt;= le...
4
2016-06-08T12:39:04Z
[ "python", "list" ]
Periodic List in Python
37,702,651
<p>I’m trying to create a circular list in Python. I.e., a list where <code>list[x]</code> is equal to <code>list[x - len(list)]</code> if <code>x</code> > <code>len(list)</code>.</p> <p>Here is the code below:</p> <pre><code>class Circ(list): def __getitem__(self, idx): while (idx &gt; len(self)): ...
0
2016-06-08T12:34:25Z
37,702,831
<p>Recall that list indices are 0-based; hence, you want <code>while (idx &gt;= len(self)):</code>.</p> <p>Good test case!</p>
0
2016-06-08T12:41:55Z
[ "python", "list" ]
Periodic List in Python
37,702,651
<p>I’m trying to create a circular list in Python. I.e., a list where <code>list[x]</code> is equal to <code>list[x - len(list)]</code> if <code>x</code> > <code>len(list)</code>.</p> <p>Here is the code below:</p> <pre><code>class Circ(list): def __getitem__(self, idx): while (idx &gt; len(self)): ...
0
2016-06-08T12:34:25Z
37,702,843
<p>The problem is your condition:</p> <pre> while (idx <b>&gt;</b> len(self)): idx -= len(self) </pre> <p>You should replace it with:</p> <pre> while (idx <b>&gt;=</b> len(self)): idx -= len(self) </pre> <p>although this is far from efficient. A more efficient way is to use modulo (<code>%</code>):</p> <pr...
0
2016-06-08T12:42:34Z
[ "python", "list" ]
How can I extrat a specific src url format using regex?
37,702,704
<p>My string:</p> <pre><code>Russia's National Settlement Depository discusses why it believes the biggest blockchain opportunities have yet to be uncovered.&lt;img alt="" height="1" src="http://feeds.feedburner.com/~r/CoinDesk/~4/rvoQUj-KDaw" width="1" /&gt;|One of the co-founder of digital currency startup Stellar a...
0
2016-06-08T12:36:50Z
37,702,924
<p>You are missing the <code>~</code> character in your regex:</p> <p><code>http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&amp;+~]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+</code></p> <p>btw: <a href="http://python-regex.com/" rel="nofollow">this</a> is a super way to test regex in Python!</p>
0
2016-06-08T12:46:41Z
[ "python", "regex", "url", "extract", "src" ]
How can I extrat a specific src url format using regex?
37,702,704
<p>My string:</p> <pre><code>Russia's National Settlement Depository discusses why it believes the biggest blockchain opportunities have yet to be uncovered.&lt;img alt="" height="1" src="http://feeds.feedburner.com/~r/CoinDesk/~4/rvoQUj-KDaw" width="1" /&gt;|One of the co-founder of digital currency startup Stellar a...
0
2016-06-08T12:36:50Z
37,702,937
<p>try this script :</p> <pre><code>text1="""Russia's National Settlement Depository discusses why it believes the biggest blockchain opportunities have yet to be uncovered.&lt;img alt="" height="1" src="http://feeds.feedburner.com/~r/CoinDesk/~4/rvoQUj-KDaw" width="1" /&gt;|One of the co-founder of digital currency s...
0
2016-06-08T12:47:10Z
[ "python", "regex", "url", "extract", "src" ]
How can I extrat a specific src url format using regex?
37,702,704
<p>My string:</p> <pre><code>Russia's National Settlement Depository discusses why it believes the biggest blockchain opportunities have yet to be uncovered.&lt;img alt="" height="1" src="http://feeds.feedburner.com/~r/CoinDesk/~4/rvoQUj-KDaw" width="1" /&gt;|One of the co-founder of digital currency startup Stellar a...
0
2016-06-08T12:36:50Z
37,702,975
<p>try this :</p> <pre><code>(?:src=)(".*?") </code></pre> <p>and get group \1</p> <p><a href="https://regex101.com/r/eI3bF2/2" rel="nofollow">DEMO</a></p>
0
2016-06-08T12:48:24Z
[ "python", "regex", "url", "extract", "src" ]
How can I extrat a specific src url format using regex?
37,702,704
<p>My string:</p> <pre><code>Russia's National Settlement Depository discusses why it believes the biggest blockchain opportunities have yet to be uncovered.&lt;img alt="" height="1" src="http://feeds.feedburner.com/~r/CoinDesk/~4/rvoQUj-KDaw" width="1" /&gt;|One of the co-founder of digital currency startup Stellar a...
0
2016-06-08T12:36:50Z
37,702,982
<p>where is this data coming from ? I'd suggest using an html parser instead of trying to extract with regex. you can pull out the full values from within the tags there if that's coming from html</p> <p>below i put your string in test.html (for python using beautifulsoup as example)</p> <pre><code>&gt;&gt;&gt; from ...
2
2016-06-08T12:48:41Z
[ "python", "regex", "url", "extract", "src" ]
Select values from a set of arrays according to an array of permutations
37,702,825
<p>I have 3 numpy arrays of shape 2xN (with N large, a few millions), call them a1, a2, a3. Then I have another array of shape Nx3 whose row values refer to one of the arrays a1, a2, a3, call it permutations. This permutations array looks like: [[0, 1, 2], [1,2,0], [1,0,2], ... up to N rows ]</p> <p>I want to create ...
3
2016-06-08T12:41:37Z
37,703,512
<p>With <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#combining-advanced-and-basic-indexing" rel="nofollow"><code>fancy-indexing</code></a>, you could do -</p> <pre><code>bb = aa[:,np.arange(N),permutations.T] </code></pre> <p>Please note that this would be of shape <code>(2,3,N)</code>. So,...
1
2016-06-08T13:11:55Z
[ "python", "numpy", "vectorization" ]
list python-dev as install_requires in setup.py
37,702,938
<p>Is there a way to tell python in the setup.py file that "python-dev" (which cannot be installed with pip because is a OS package) is necessary and therefore should be installed?</p> <p>How to install it automatically? </p>
1
2016-06-08T12:47:11Z
37,703,300
<p>No. For one thing, the <code>python-dev</code> package is specific to Debian-like distributions; there is no guarantee that other distributions will have a package with the same name that fulfills the desired role. For another, the user installing your Python package may have permission to install Python modules (...
1
2016-06-08T13:02:07Z
[ "python", "lxml", "setup.py" ]
Can a column's server_defaults be different for different dialects in SQLAlchemy?
37,702,968
<p>I'm using SQLAlchemy to configure my database schemas, and I want to set up a <code>Column</code> with a <code>server_default</code> that is different depending on the database dialect. One database function call for PostgreSQL and another for SQLite. Can this be done? How?</p> <pre><code>from sqlalchemy import Col...
0
2016-06-08T12:47:58Z
37,702,969
<p>Use the <code>@compiles</code> decorartor, as described in <a href="http://docs.sqlalchemy.org/en/latest/core/compiler.html?highlight=compiles#dialect-specific-compilation-rules" rel="nofollow">the docs</a>:</p> <pre><code>from sqlalchemy.ext.compiler import compiles from sqlalchemy.sql.functions import FunctionEle...
1
2016-06-08T12:47:58Z
[ "python", "postgresql", "sqlite", "sqlalchemy" ]
1st digit before taking modulo(10**9 + 7)
37,703,061
<p>I am multiplying many large numbers and finally taking modulo of it. To optimise this I am using MOD at each step. But I also want the 1st digit of the final answer. Is there any way to know that even after using MOD?</p> <p>Or is there any other efficient way to do huge multiplication many times, get the final ans...
0
2016-06-08T12:52:22Z
37,703,548
<p>take 10 based logarithms, sum them up and take the fractional part of the sum.</p> <p>think about scientific notation of large numbers.</p>
0
2016-06-08T13:13:51Z
[ "python", "math", "multiplication" ]
How can I create a Decimal with a large exponent in Python 3?
37,703,071
<p>Python 3 seems to have some arbitrary limit to Decimal sizes that Python 2 does not. The following code works on Python 2:</p> <pre><code>Decimal('1e+100000000000000000000') </code></pre> <p>But on Python 3 I get:</p> <pre><code>decimal.InvalidOperation: [&lt;class 'decimal.InvalidOperation'&gt;] </code></pre> <...
3
2016-06-08T12:52:40Z
37,703,528
<p>It would appear that <code>Decimal</code>s actually <em>can't</em> hold arbitrarily long numbers: </p> <pre><code>&gt;&gt;&gt; d = Decimal('10') ** Decimal('100000000000000000000') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; decimal.Overflow: [&lt;class 'decimal.Overflow'&gt...
1
2016-06-08T13:12:52Z
[ "python", "python-3.x" ]
How to access a List of Objects from outside a class in python
37,703,220
<p>Hope you can help me on this one. I have created a list of objects because the program that I use creates lots of agents and it is easier to keep track.I want to access that information from outside the class, so I need to call that list and call in the agent number(which is created from the simulator). I have put a...
-1
2016-06-08T12:58:54Z
37,704,273
<p>You're not actually storing anything inside the <code>Machine</code> class. The only thing that you <em>are doing</em> is storing values in the (confusingly named) <code>carObject</code>:</p> <pre><code>from StoreCar import * carObject = [] class Machine: def calculation(): VehicleID = 2 # this is genar...
1
2016-06-08T13:43:28Z
[ "python", "class", "object", "dictionary", "access" ]
Use python to reduce number of hits in tabular blast output file
37,703,222
<p>I have a large blast files in tabular format, for which the number of target sequences weren't limited, so it takes a long time to parse. I want to reduce the number of hits for each query sequence to the first 10. My python is basic but here's what I have so far</p> <pre><code>import sys blastfile = open(sys.argv...
1
2016-06-08T12:58:55Z
37,703,908
<p>This one-pass version prints the first 10 of each title in the order they occur in the file:</p> <pre><code>import sys NUM_TO_PRINT=10 # good practice - use names rather than raw numbers blastfile = open(sys.argv[1],"r") titles={}; # an empty dictionary. # This will map titles to counts of how many times...
1
2016-06-08T13:28:11Z
[ "python", "string", "search", "blast" ]