Unnamed: 0
int64
0
1.91M
id
int64
337
73.8M
title
stringlengths
10
150
question
stringlengths
21
64.2k
answer
stringlengths
19
59.4k
tags
stringlengths
5
112
score
int64
-10
17.3k
5,400
13,784,713
What good are Python function annotations?
<p>I have gone through the first couple of sections in PEP 3107, but I still don't get what good they do for the language. It seems to me that you can add metadata to functions using decorators. e.g.</p> <pre><code>def returns(return_type): f.return_type = return_type # &lt;- adding metadata here return f @retur...
<p>As you mentioned, the relevant PEP is <a href="http://www.python.org/dev/peps/pep-3107/" rel="noreferrer">3107</a> (linked for easy reference in case others encountering this question haven't read it yet).</p> <p>For now, annotations are kind of an experiment, and kind of a work in progress. There is actually a rec...
python|python-3.x
33
5,401
13,270,888
Why is startswith slower than slicing
<p>Why is the implementation of <a href="http://docs.python.org/2/library/stdtypes.html#str.startswith" rel="noreferrer"><code>startwith</code></a> slower than slicing?</p> <pre><code>In [1]: x = 'foobar' In [2]: y = 'foo' In [3]: %timeit x.startswith(y) 1000000 loops, best of 3: 321 ns per loop In [4]: %timeit x[:...
<p><em>Some</em> of the performance difference can be explained by taking into account the time it takes the <code>.</code> operator to do its thing:</p> <pre><code>&gt;&gt;&gt; x = 'foobar' &gt;&gt;&gt; y = 'foo' &gt;&gt;&gt; sw = x.startswith &gt;&gt;&gt; %timeit x.startswith(y) 1000000 loops, best of 3: 316 ns per ...
python|startswith
43
5,402
43,812,444
encoding string that has been decoded with %' to unicode
<p>html POST method decoded my string like this:</p> <blockquote> <p>Ostrołęka => Ostro%C5%82%C4%99ka</p> </blockquote> <p>How do I encode it into readable form in Python?</p> <p>Sorry for possible duplicate. </p> <p>EDIT: Solution in 'possible duplicate' doesn't solve above problem</p>
<p>Python 2:</p> <pre><code>from urllib import unquote x = unquote('Ostro%C5%82%C4%99ka') </code></pre> <p>Python 3:</p> <pre><code>from urllib.parse import unquote x = unquote('Ostro%C5%82%C4%99ka') </code></pre>
python|unicode
0
5,403
71,429,930
How can I count how many rows have a value equal to 3 in each column and store them in a new column
<p>I am new to python. So I am trying to sum the total of each row/column with a value &quot;3&quot;, and store it in a new column in my dataframe.</p> <p>my data looks like this:</p> <pre><code> [A] [B] [C] [D] [E] [F] ID1 1 2 2 3 1 1 ID2 3 1 2 3 1 1 ID3 1 1 2 1 1 2 ID4 3 2 2 ...
<p>Use:</p> <pre><code>df['G'] = df.eq(3).sum(axis=1) print(df) # Output A B C D E F G ID1 1 2 2 3 1 1 1 ID2 3 1 2 3 1 1 2 ID3 1 1 2 1 1 2 0 ID4 3 2 2 3 1 1 2 ID5 1 1 2 3 1 3 2 </code></pre>
python|pandas|dataframe
2
5,404
9,265,413
comparing/extracting data from matrices using python (2.6.1)
<p>I have two .csv files containing correlation matrices exported from R. One file contains the P-values and one contains the r-values. The row and column headers match exactly between the two files. </p> <p>I am trying to extract the r-values and corresponding row and column header for pairs only when the P-value ...
<p>To read the data, you should be able to use numpy.genfromtext. See the documentation, there is a ton of functionality within this function. To read your example above, you might do:</p> <pre><code>from numpy import genfromtxt rdata = genfromtxt('AllcorrR.csv', skip_header=1)[:,1:] Pdata = genfromtxt('AllcorrP.csv...
python|matrix|correlation
1
5,405
39,201,892
Django display data in a table -- Sort of a table within a table (nested forloop?). Data needs to link as well
<p>I'm not sure the best way to explain it so I created an example picture and made up some data:</p> <p><a href="https://i.stack.imgur.com/HclH8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HclH8.jpg" alt="Table"></a></p> <p>I looked at this post and know I need to use some forloop template stu...
<blockquote> <p>"A 'related manager' is a manager used in a one-to-many or many-to-many related context." <a href="https://docs.djangoproject.com/en/1.10/ref/models/relations/" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/models/relations/</a></p> </blockquote> <p>I can't see how your relation betw...
python|django
0
5,406
39,009,204
aws boto3 s3 put_object error handling/testing
<p>How should errors be handled/tested for python AWS <a href="https://boto3.readthedocs.io/en/latest/" rel="nofollow">boto3</a> s3 put_object? For example:</p> <pre><code>import boto3 s3 = boto3.resource('s3') bucket = s3.Bucket('foo') bucket.put_object(Key='bar', Body='foobar') </code></pre> <p>Are the errors tha...
<p>AWS s3 does not restrict uploads based on requests. The restriction is only for size: For Example: 1 POST request will upload files upto 5GB 2 PUT can upload upto 160 GB of size</p> <p>The errors you are trying or expecting to handle are nothing but client/browser restriction while uploading multiple files ...
python|amazon-web-services|amazon-s3|error-handling|boto3
0
5,407
55,143,626
Valid authentication credential for Android Management API
<p>I'm learning to work with api and now I try to get a list of devices runing a python script from the console. Client Library for Python installed.</p> <p><strong>sample.py</strong></p> <pre><code>import pprint import sys from apiclient.discovery import build import json api_key = 'AIzaSyBNv8k-zm_TkytbBMJVkR7_wjc...
<p>Having drawn conclusions from the tips <strong>@tehhowch</strong>, I found a solution for my question.</p> <p>Instead ApiKey need using OAuth2ServiceAccount. More informations at this <a href="https://developers.google.com/identity/protocols/OAuth2ServiceAccount" rel="nofollow noreferrer">page</a>. Sample code for ...
android|python|google-api|google-api-python-client|android-management-api
4
5,408
52,745,431
Conditional Subtract Dates
<p>Lets say i have the pandas dataframe below. How can i subtract one month from Var2 when Var0 is equal to b. I would like to do this conditionally, rather than creating a new data-set with just the var0 b values,subtracting and then re-merging. Var2 is in pandas datetime.</p> <pre><code>Var0 Var1 Var2 x 76....
<p>Using <code>DateOffset</code></p> <pre><code>df.Var2=pd.to_datetime(df.Var2,format='%Y-%m') df.loc[df.Var0=='b','Var2']=df.Var2-pd.DateOffset(months=1) df.Var2=df.Var2.dt.strftime('%Y-%m') df Out[24]: Var0 Var1 Var2 0 x 76.27 2018-05 1 x 93.38 2018-06 2 a 73.00 2018-05 3 a 74.33 20...
python|python-3.x|pandas
2
5,409
52,802,329
How can i get Alexa Slot Value in ASK-SDK lambda function?
<p>I want to access the slot value '{cityName}' in my Lambda Function. I am using ASK-SDK. What is the python code or syntax to do so?</p> <p><a href="https://i.stack.imgur.com/YesnQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YesnQ.png" alt="My Alexa Console Picture"></a></p>
<p>If the <code>WeatherApiCallIntent</code> is triggered with a <code>CityName</code> slot value, the request JSON will look like this:</p> <pre><code>"request": { "type": "IntentRequest", "requestId": "amzn1.echo-api.request.xxxxx-xxx-xxx-xx-xxxxxxx", "timestamp": "2018-09-12T13:35:25Z", ...
python-2.7|alexa|alexa-skills-kit|alexa-slot
1
5,410
34,232,042
PySpark 1.5 How to Truncate Timestamp to Nearest Minute from seconds
<p>I am using PySpark. I have a column ('dt') in a dataframe ('canon_evt') that this a timestamp. I am trying to remove seconds from a DateTime value. It is originally read in from parquet as a String. I then try to convert it to Timestamp via</p> <pre><code>canon_evt = canon_evt.withColumn('dt',to_date(canon_evt.dt))...
<p><strong>Spark &gt;= 2.3</strong></p> <p>You can use <code>date_trunc</code></p> <pre><code>df.withColumn(&quot;dt_truncated&quot;, date_trunc(&quot;minute&quot;, col(&quot;dt&quot;))).show() ## +-------------------+-------------------+ ## | dt| dt_truncated| ## +-------------------+-----------...
python|datetime|apache-spark|apache-spark-sql|pyspark
23
5,411
34,228,599
Getting SSLError: [Errno 8] _ssl.c:510: EOF occurred in violation of protocol
<p>I am using tornado framework and doing certificate authentication but I am getting following error :</p> <p>SSLError: [Errno 8] _ssl.c:510: EOF occurred in violation of protocol</p> <p>I am using below code:</p> <pre><code>http_server = tornado.httpserver.HTTPServer(HomeHandler() ,ssl_options=dict( ...
<p>I have upgraded tornado version to 4.3 and no ssl error I am getting now.</p>
python-2.7|ssl-certificate|tornado
0
5,412
72,637,167
pandas df are being read as dict
<p>I'm having some trouble with <code>pandas</code>. I opened a .xlsx file with <code>pandas</code>, but when I try to filter any information, it shows me the error</p> <pre><code>AttributeError: 'dict' object has no attribute 'head' #(or iloc, or loc, or anything else from DF/pandas)# </code></pre> <p>So, I did some r...
<p>if its a <code>dict</code> of <code>DataFrames</code> try...</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; dict_df = {&quot;a&quot;:pd.DataFrame([{1:2,3:4},{1:4,4:6}]), &quot;b&quot;:pd.DataFrame([{7:9},{1:4}])} &gt;&gt;&gt; dict_df {'a': 1 3 4 0 2 4.0 NaN 1 4 NaN 6.0, 'b': 7 ...
excel|pandas|dataframe|dictionary
0
5,413
16,363,622
django haystack not returning results according to expectations
<p>I have configured Django haystack with Elasticsearch Search Engine using <code>QueuedSignalProcessor</code> with <code>redis</code> Queue backend. Everything working except now I have some issue. I have two objects in db whose title is <code>code fixes</code> and <code>code fixess</code> (with extra <code>s</code> a...
<p>The reason is because Haystack is configured to use the <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/analysis-snowball-analyzer.html" rel="nofollow">Snowball analyzer</a></p> <p>This looks for known (English) word endings, such as the <code>es</code> in <code>fixes</code> and stori...
python-2.7|elasticsearch|django-haystack|django-1.4
0
5,414
16,201,548
Python: TypeError: 'file' object has no attribute '__getitem__'
<p>I have a .gpx file which is cut off int the middle of the file. When I try to parse it using the <a href="https://github.com/tkrajina/gpxpy" rel="nofollow">gpxpy library</a> I run into the following error.</p> <pre><code>Parsing points in track.gpx ERROR:root:expected '&gt;', line 3125, column 29 Traceback (most re...
<p>This appears to be a bug in <code>gpxpy</code>'s error handling.</p> <p>Looking at the source to <a href="https://github.com/tkrajina/gpxpy/blob/master/gpxpy/__init__.py#L17" rel="nofollow"><code>parse</code></a>, when the parser fails without raising an exception, it tries to raise an exception with this:</p> <pr...
python|parsing|exception|typeerror|gpx
2
5,415
40,474,822
Combine queues for async io with auto enqueue in tensorflow
<p>I have multiple csv files which contain features. One feature is the filename of an image. I want to read the csv files line by line, push a path to the corresponding image into a new queue. Both queues should be processed in parallel.</p> <p><a href="https://i.stack.imgur.com/qiiWN.jpg" rel="nofollow noreferrer"><...
<pre><code>filenames = ['./cs_disp_train.txt', './cs_limg_train.txt'] txt_queue = tf.train.string_input_producer(filenames) # txt_queue = tf.FIFOQueue(10, tf.string) # init_txt_queue = txt_queue.enqueue_many(filenames) enqueue_ops = [] image_queues = tf.FIFOQueue(100, tf.string) num_reader = len(filenames) for i in r...
queue|tensorflow|pipeline
1
5,416
60,071,998
Breaking out of loop - Python
<p>I've tried googling and searching on SO, but I cant figure out why my break on the second to last line is not heading out of the while loop. Better yet, I cant figure out why the loop is not continuing either. My intention is to give the user the possibiltiy to head to the main menu after the last choice (basically ...
<p><a href="https://stackoverflow.com/a/41065563/12841609">This</a> will help you I think. Break only breaks from current loop. If you want to go up on levels you need to break from each loop separately.</p> <p>A <a href="https://stackoverflow.com/q/189645/12841609">suggestion</a> is to turn a loop into a function and...
python|while-loop|break
1
5,417
63,180,610
Issue sorting enumerated list by position
<p>I'm having some difficulty sorting my enumerated list by position.</p> <p>I've searched other posts, and I think it could be because the values are not converted to integers.</p> <p>However, I'm not sure how to do that in this context.</p> <p>For example:</p> <pre><code>lst = ['blue', 'red', 'green', 'black', 'yello...
<p>One way to to create a list of tuples, not a list of strings. The list comprehension that creates <code>lst_pos</code> becomes:</p> <pre><code>lst_pos = [(i, v) for i, v in enumerate(lst)] lst_sort = sorted(lst_pos, key = lambda x:x[0]) lst_sort [(0, 'blue'), (1, 'red'), (2, 'green'), (3, 'black'), (4, 'yellow...
python
1
5,418
32,352,884
Python intersection of 2 UNICODE tuple/List
<p>I am trying to search words from a file and appending resulting words from each line to a Tuple. And then I want to find intersecting words from the two tuples list_1 and list_2. But i get error- </p> <p>TypeError: unhashable type: 'list'</p> <pre><code># -*- coding: utf-8 -*- </code></pre> <p>import re</p> <p>l...
<p>There you have list inside list. fix it.</p> <pre><code>result = set(list_1).intersection(list_2) </code></pre> <p>set([]) = Ok set([[],[]]) = Failed because list can't be hashed</p>
python|list|unicode|intersection
0
5,419
54,914,096
Why is the mysql Insert command not working for me in python?
<p>The query is correct but I do not understand why it cannot be added into my database. Please help me thanks. I am a beginner and I can hardly debug this one.</p> <pre><code> def callback(channel): print("\nflame detected\n") GPIO.add_event_detect(channel, GPIO.BOTH, bouncetime=300)#pin if HIGH or LOW GPIO.a...
<p>You can try ...</p> <pre><code>sql = "INSERT INTO res(celsius,fahrenheit,humidity,flame) VALUES(%s,%s,%s,%s)" data = (cel, far, hum, fla) </code></pre> <p>Specifying the need values and making it clearer, also you're missing the <code>db.commit()</code> </p> <p><code>cur.execute(sql, data)</code> with this you ha...
python|mysql
0
5,420
44,108,173
Python: how to check if an element is not in a list?
<p>I'm a newbie in python &amp; using python 3.4.3 in PyCharm in windows. Suppose that i have a list in python in which (0,2,4)th elements are names(string) and (1,3,5)th elements are theirs' rolls(int) </p> <pre><code>list = ['a',12,'b',16,'c',20] </code></pre> <p>if i want to prompt the user to enter a roll number...
<p>You can use a simple <code>if-else</code> pair for this:</p> <pre><code>l = ['a',12,'b',16,'c',20] roll = int(input()) if roll in l: del (l[l.index(roll) - 1: l.index(roll) + 1]) print("Succes! Your list is ",l) else: print("Number not in list.") </code></pre> <p>If the number one enters is <code>12</c...
python|python-3.x
3
5,421
14,102,796
python os.path.expanduser() Is this always true
<p>Resolution: As Thomas pointed out below, the task I have been given is near to impossible to achieve, and the data must be on the fly determined since the template structure used by ANY OS can be overridden fairly easily, and there is NEVER a way to guarantee that a pre-built template can be correctly applied. My ...
<p>This is not even true on Linux. Just have a look at <code>/etc/adduser.conf</code>:</p> <ul> <li><code>GROUPHOMES=yes</code> would let <code>adduser</code> create homes such as: <code>/home/groupname/user.</code></li> <li><code>LETTERHOMES=yes</code> would create ones looking like: <code>/home/u/user</code>.</li> <...
python|windows|macos|python-2.7
5
5,422
13,984,461
Python pandas resample added dates not present in the original data
<p>I am using pandas to convert intraday data, stored in <code>data_m</code>, to daily data. For some reason <code>resample</code> added rows for days that were not present in the intraday data. For example, 1/8/2000 is not in the intraday data, yet the daily data contains a row for that date with NaN as the value. Dat...
<p>What you are doing looks correct, it's just that pandas gives NaN for the mean of an empty array.</p> <pre><code>In [1]: Series().mean() Out[1]: nan </code></pre> <p><a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.resample.html?highlight=resample#pandas.DataFrame.resample" rel="nofollo...
python|pandas
6
5,423
34,444,711
How to use pip on a python by path?
<p><a href="https://stackoverflow.com/questions/6220274/install-python-module-to-non-default-version-of-python-on-mac">This question</a> shows how to use pip for different python versions. However, I have the same version of python installed in two different paths. Let's not ask why, if I remove one, things break.</p...
<p>For two python installations you can have two pips. </p> <p>Install a pip for the other python:</p> <pre><code>sudo /usr/bin/python -m easy_install pip </code></pre> <p>Execute pip as a module:</p> <pre><code>/usr/bin/python -m pip install --user your_package </code></pre> <p>Recommend to symlink them to separ...
python|macos|pip
1
5,424
27,116,402
Python gdal undefined symbol GDALRasterBandGetVirtualMem
<p>I'm trying to use <a href="https://pypi.python.org/pypi/GDAL" rel="nofollow noreferrer">Python GDAL bindings</a>. When naively installing bindings through pip, installation fails with <a href="https://gis.stackexchange.com/q/21269/4904">error: 'VSIFTruncateL' was not declared in this scope</a>, probably due to a mi...
<p>If a gdal version is already installed, this problem will occur even if you have linked against the version installed in <code>~/.local</code>.</p> <p>A solution is given at <a href="http://fr.planet.mysql.com/entry/?id=683010" rel="noreferrer">a Planet MYSQL post here</a>:</p> <blockquote> <p>In this case, we c...
python|gdal
9
5,425
27,285,358
python for each match in a string copy to an array
<p>I'm doing some queries against a database that's going to return something like the following - </p> <pre><code>string = 'T=1 ID=56494759 DID=583887 O=N M=N J=76732 R=0 P=1 S=101 WR=N T=1 ID=56494760 DID=418400 O=N M=N J=48064 R=14780471 P=1 S=101 WR=N T=1 ID=56494761 DID=583889 O=N M=N J=76733 R=0 P=1 S=101 WR=N '...
<p>Somethign like this:</p> <pre><code>string = 'T=1 ID=56494759 DID=583887 O=N M=N J=76732 R=0 P=1 S=101 WR=N T=1 ID=56494760 DID=418400 O=N M=N J=48064 R=14780471 P=1 S=101 WR=N T=1 ID=56494761 DID=583889 O=N M=N J=76733 R=0 P=1 S=101 WR=N ' import re print(re.findall(r'\sID=(\d+)', string)) </code></pre> <p>Res...
python|python-2.7
1
5,426
27,033,146
How to use mapreduce in mongodb?
<p>I have the following code in python:</p> <pre><code>from pymongo import Connection import bson c = Connection() db = c.twitter ids = db.users_from_united_states.distinct("user.id") for i in ids: count = db.users_from_united_states.find({"user.id":i}).count() for u in db.users_from_united_states.find({"us...
<pre><code>[ { "$group": { "_id": "$user.id", "my_fitness_data": { "$push": "$text" } } }, { "$project": { "UserId": "$_id", "TweetsCount": { "$size": "$my_fitness_data" }, ...
python|mongodb|mapreduce
1
5,427
27,158,537
A simple timeout after waiting for input
<p>I would like to be able to time out a script in python 3 after 10 seconds or so if there hasn't been any input from the keyboard. I've researched using the signal, time, and thread modules and they are all getting complicated to me. Preferably, I would just like to use the time module being that I'm already using it...
<p>This will work, the highest answer wont run on Windows, but scroll down an answer and it will show you how to fix for Windows: <a href="https://stackoverflow.com/questions/3471461/raw-input-and-timeout">raw_input and timeout</a> </p>
python-3.x|timer|python-3.4
-1
5,428
12,413,826
Remote_api configuration with App Engine
<p>Using Python, I'm trying to connect to my AppEngine app's remote_api handler, but I keep getting an error. What I want to do is set up the remote_api stubs to route database calls through that and access my app's datastore directly. So, first, I import the remote_api libraries, then call the ConfigureRemoteApi on...
<p>assuming you are using high replication datastore now...</p> <p>Your app_id is probably wrong, and you also need to pass the address parameter. I whipped this up a while back while reading the oreilly book for appengine(book is severely out of date and not recommended)</p> <pre><code>def attach_to_app(app_id, user...
python|google-app-engine|remoteapi
6
5,429
12,181,207
I am using your ftputil within a python script
<p>I am using your ftputil within a python script to get last modification/creation date of files in directory and I am having few problems and wondered if you could help.</p> <pre><code> host.stat_cache.resize(200000) recursive = host.walk(directory, topdown=True, onerror=None) for root,dirs,files in recursiv...
<p>You've put <code>name</code> in quotes. So Python will always be checking for the literal filename "name", which presumably doesn't exist. You mean:</p> <pre><code> if host.path.isfile(name): mtime1 = host.stat(name) mtime2 = host.stat(name).mtime </code></pre>
python|ftputil
1
5,430
22,974,915
How do I read in lines from a text file and search through all rows and tables in a database for matching strings?
<p>My project involves using Python to extract forensic data from a Windows image file. I have now written programs that carry out the extraction and saved the data to a SQLite Database for analysis. I have a keyword text file that I would like to read in line by line and search all the tables in my database for the ...
<pre><code>condition = ' OR '.join(["field LIKE ?" for k in keywords]) sql = "SELECT * FROM {t} WHERE {c}".format(c=condition, t=tablename) args = ['%{k}%'.format(k=k) for k in keywords] cursor.execute(sql, args) </code></pre>
python|sqlite
1
5,431
23,320,260
Can the strings be changed into variables?
<pre><code>import numpy as np data1 = np.array([1,2,np.nan,4,5,6,7],dtype=float) data2 = np.array([11,np.nan,9,4,5,6,71],dtype=float) data3 = np.array([17,np.nan,13,4,15,6,17],dtype=float) result1 = data1/data2 result2 = data1/data3 result3 = data3/data2 </code></pre> <p>For every results, I want to convert the np....
<p>To iterate over variable in module scope you can use globals(), it contain all variable from module. globals() return dictionary with structure: {"var_name": var, ...}, i.e.:</p> <pre><code>x = 10 y = 10 print globals() </code></pre> <p>Among "service" module variables our <code>x</code> and <code>y</code> will b...
python|numpy
2
5,432
7,926,364
Printing number pairs (two numbers) in python3
<p>I'm trying to get used to the new formatting options in python-3.</p> <p>Is there simpler way of printing sequence of number pairs (two numbers) in python3 ? </p> <pre><code>for x in range(0,n): # [0, n-1] print("{} {}".format(x, x*x)); </code></pre> <p>If this is the shortest and simplest way, please, could ...
<pre><code>for x in range(0,n): print(x, x*x) </code></pre>
python-3.x
2
5,433
1,294,272
How do I install PyGTK / PyGobject on Windows with Python 2.6?
<p>I have an application which depends on PyGTK, PyGobject, and PyCairo that I built to work on Linux. I want to port it over to windows, but when I execute <code>import gobject</code> I get this:</p> <pre><code>Traceback (most recent call last): import gobject File "C:\Python26\lib\site-packages\gtk-2.0\gobject...
<p>I have it working fine, and it didn't give me much trouble, so we know it can be done...</p> <p>Keep in mind you will probably need all of the following installed on your Windows machine:</p> <ul> <li><p>PyCairo ( <a href="http://ftp.gnome.org/pub/GNOME/binaries/win32/pycairo/" rel="noreferrer">http://ftp.gnome.or...
python|pygtk|mingw|pygobject
10
5,434
42,072,721
"ValueError: max_features must be in (0, n_features] " in scikit when using random forest
<p>I have a dataset of 20 features and 840 rows. I have already optimized the classifier (random forest). My parameters are n_estimators=100 and max_features=5. I want to do a classification for each feature. I mean with each of the features I want to know the prediction accuracy. But when I use my code I get an error....
<p>So I managed to solve the problem!!! :) In <a href="http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html" rel="noreferrer">scikit page</a> says:</p> <p>*If float, then max_features is a percentage and int(max_features * n_features) features are considered at each split.*</p>...
python-3.x|optimization|machine-learning|scikit-learn|random-forest
15
5,435
41,819,114
how do i open a file in python with variable name?
<p>I am trying to open a file that has a random time date stamp as part of its name. Most of the filename is known eg <code>filename = 2017_01_23_624.txt</code> is my test name. The date and numbers is the part I am trying to replace with something unknown as it will change. My question relates to opening an existing f...
<p>You can't open a file with a partial filename containing a wildcard for it to match. What you would have to do it look at all the files in your directory and pick the one that matches best.</p> <p>Simple example:</p> <pre><code>import os filename = "filename2017_" # known section direc = r"directorypath" matches...
python-3.x
1
5,436
47,217,837
python dictionary for students records
<p>i am trying to create a program in python 3 where it will ask the user to input the students name(name) and his/hers ID numbers(ID) all in one go separated by comma. Then present all the dictionary values in the following format eg: Name:John ID:123 Name:Mary ID:234 Name:Eve ID:345 the program will run forever un...
<p>Couple months late and I am pretty new to coding myself but here's something I put together that might help. I used a lot of comments throughout the code so you know what I'm attempting to do.</p> <pre><code># Initilize values i = 0 StuName = None ID = None students = {} # Loop structure that says "While this is t...
python-3.x
0
5,437
11,479,064
Multiple linear regression in Python
<p>I can't seem to find any python libraries that do multiple regression. The only things I find only do simple regression. I need to regress my dependent variable (y) against several independent variables (x1, x2, x3, etc.).</p> <p>For example, with this data:</p> <pre><code>print 'y x1 x2 x3 ...
<p><a href="http://scikit-learn.org/stable/modules/linear_model.html#ordinary-least-squares" rel="noreferrer"><code>sklearn.linear_model.LinearRegression</code></a> will do it:</p> <pre><code>from sklearn import linear_model clf = linear_model.LinearRegression() clf.fit([[getattr(t, 'x%d' % i) for i in range(1, 8)] fo...
python|numpy|statistics|scipy|linear-regression
111
5,438
11,728,230
reading/count character in the line?
<p>I am trying to read / count the character on the file (which is located in line 2)</p> <p>all the even line of the file looks similar to this: </p> <p>---------------LL---NE--HVKTHTEEK---PF-ICTVCR-KS----------</p> <p>here is my code so far but I got the error saying:</p> <p>for character in len[(line2)]: TypeErr...
<p><code>line2</code> is a string, and <code>len(line2)</code> is an integer (number of characters in <code>line2</code>). Square brackets are used for indexing (or slicing) sequences, so for example you could get the first character of <code>line2</code> using <code>line2[0]</code>, or the last character using <code>...
python|count|character
0
5,439
33,815,013
Iterate over jinja array
<p>I have the following jinja array:</p> <pre><code>{'e34': ['120'], 'e24': ['50']} </code></pre> <p>I want to find if a word contains <code>e2</code>, and take it to another function.</p> <p>I did the following:</p> <pre><code>{% set result = 'default' %} {% for item, value in jinjaarray.items() %} {% if 'e2' i...
<p>Instead using <a href="https://docs.python.org/3.5/library/stdtypes.html#dict.items" rel="nofollow"><code>.items()</code></a> like Python3, jinja2 uses Python2-fashioned <a href="https://docs.python.org/2/library/stdtypes.html#dict.iteritems" rel="nofollow"><code>.iteritems()</code></a> as stated in the <a href="htt...
python|jinja2
2
5,440
46,655,873
Why do scipy.linalg's methods run slower on 9x9 matrices?
<p>I'm comparing runtimes for various ways to solve linear systems, and I've found an odd pattern. The solution methods I'm testing are <code>la.solve()</code>, <code>la.inv()</code>, and <code>la.lu_factor_solve()</code>.</p> <pre><code>import scipy.linalg as la import numpy as np from time import time from matplotli...
<p>I've tried your code examples with <a href="https://github.com/nschloe/perfplot" rel="nofollow noreferrer">perfplot</a> (a small project of mine, essentially a wrapper around timeit) and found no such peculiarities. One <em>can</em> recognize the exhaustion of the level-1-cache though:</p> <p><a href="https://i.sta...
python|numpy|matrix|scipy
2
5,441
37,947,365
Pylint import check when directories are not the same than the import
<p>I've an unusual question, and I don't find the answer because no one is doing like that :p</p> <p>I want to use PyLint in order to resolve errors before running the script, especially calling methods from other modules and heritage.</p> <p>Thing is, my python scripts are not organized the same way than the import....
<p>There are possibly multiple solutions to this. First, you can try to write a failure import hook, using astroid's API, which might look as this: <a href="https://github.com/PyCQA/astroid/blob/master/astroid/brain/brain_six.py#L273" rel="nofollow">https://github.com/PyCQA/astroid/blob/master/astroid/brain/brain_six.p...
python|import|pylint
0
5,442
37,676,731
TypeError: create() takes 2 positional arguments but 4 were given
<p>Here is my code file with name is CreateNode.py</p> <pre><code>#!/usr/bin/python import py2neo from py2neo import Graph, Node def createNodeWithLabelProperties(): print("Start Create label with prperties") py2neo.authenticate ("localhost:7474", "neo4j", "XXXXXXX") graph = Graph("http://loc...
<p>In py2neo v3, the <code>create</code> method (and all similar methods) take only a single argument, which can be any graphy object (see the <a href="http://py2neo.org/v3/types.html" rel="nofollow">manual page on types</a>). You can therefore create multiple nodes by unioning them into a subgraph to pass as the argum...
python|neo4j|py2neo
3
5,443
37,761,093
Capitalizing words in (Python)?
<p>I was trying to write something to capitalize each word in a sentence. And it works fine, as follows:</p> <pre><code>print " ".join((word.capitalize() for word in raw_input().strip().split(" "))) </code></pre> <p>If the input is 'hello world', the output would be :</p> <pre><code> Hello World </code></pre> <p...
<p>The problem in your code is that strings are immutable and you are trying to mutate it. So if you wont to work with loop you have to create new variable.</p> <pre><code>s = raw_input().strip().split(' ') new_s = '' for word in s: new_s += s.capitalize() print new_s </code></pre> <p>Or, It would work if you use...
python|string|python-2.7|capitalization
4
5,444
30,212,006
Can I save and load a heterogenous list of polymorphic types in MongoEngine?
<p>I want to save and load a heterogenous list of polymorphic types in MongoEngine. What I ideally want would look like:</p> <pre><code>from mongoengine import Document, EmbeddedDocument, IntField, StringField class BaseEmbedded(EmbeddedDocument): meta = {'abstract': True} class FooEmbedded(BaseEmbedded): an_i...
<p>Mapping JSON to classes is what Mongoengine does and is also supported for embedded documents. You need to set allow_inheritance=True in the embedded document's meta.</p>
python|mongodb|mongoengine
1
5,445
61,556,843
Define function and it's parameter based on configuration in python
<p>I have to written a python script with class and its function. The function parameters shall be varied based on configuration. In 'C' language it can achieved using #ifdef or #if Macro</p> <pre><code>#ifdef MULTIPLE_APPLICATION uint8 check_actions(int machine, int application_instance, int error_limit) { ...
<p>python is an pure OOP language! There is no #if macros. the consipt is totaly diffrent here. you can solve it in many ways. one of the simple ways is to define outer function and 2 nested inner functions and call one of the inner functions coresponding to var that you pass to the outer functions. see below:</p> <pr...
python|python-3.x
2
5,446
27,845,372
Django filter datetime field by time, irrespective of date
<p>I have a datetime field in Django, and I want to filter this based on time. I don't care about the particular date, but I want to find all transactions before 7:30, for example.</p> <p>I know I can filter by hour and minute such as:</p> <pre><code>Q(datetime__hour=7) &amp; \ Q(datetime__minute=30) </code></pre> <...
<p>Just split the datetime field into a date and a time field. Than you can filter on time only:</p> <pre><code>from datetime import combine class MyModel(models.Model): start_date = models.DateField() start_time = models.TimeField() class Meta: ordering = ['start_date', 'start_time'] def st...
python|django|datetime
1
5,447
65,527,938
Why Is 'user_input' Always A String?
<pre><code>def user_input_checker(user_input): if isinstance(user_input, int): print('user_input is an integer.') if isinstance(user_input, float): print('user_input is a float point.') if isinstance(user_input, str): print('user_input is a string') print('What is your input?') user_input = ...
<p>In your code, <code>user_input</code> is always a <code>string</code> because the <code>input()</code> function always returns <code>string</code> values. <a href="https://docs.python.org/3/library/functions.html#input" rel="nofollow noreferrer">This is described in Python's documentation</a> (emphasis mine):</p> <b...
python|python-3.x|string
3
5,448
66,910,131
How do I access a dataframe value only if a certain column exists?
<p>How do I make it so that if there is no term 'Short Long Term Debt' in the dataframe then <code>short_long_term_debt = 0</code>, but if there is then use the final line?</p> <pre><code>import pandas_datareader.data as web import pandas as pd import datetime import requests pd.set_option('display.max_rows', 500) pd.s...
<p>You can check if <code>Short Long Term Debt</code> is in <code>balance.columns</code>:</p> <pre class="lang-py prettyprint-override"><code>if 'Short Long Term Debt' in balance.columns: short_long_term_debt = balance['Short Long Term Debt']['2020'].iloc[0] else: short_long_term_debt = 0 </code></pre>
python|pandas|dataframe|contains|yfinance
0
5,449
67,168,990
vectorization of framewise Binary accuracy calculation
<p>I am working of customizing the standard model.fit() method to calculate frame-wise accuracy of each sample during validation. Sample dimension is 512 time frames and 128 frequency bins. As of now I am calculating frame wise binary accuracy by looping through each frame of the sample but this is taking more time (~ ...
<p>Assuming <code>y_pred</code> is a 4-tuple where each <code>y_pred[i]</code> has shape <code>(8, 512, 6)</code> like <code>y</code>, I think you can do something like this:</p> <pre class="lang-py prettyprint-override"><code>def test_step(self, data): x, y = data # Unpack the data x: (8, 512, 128, 1) y: (8,...
python|machine-learning|keras|deep-learning
1
5,450
4,393,153
Sandbox IronPython?
<p>Is it possible to run an IronPython interpreter inside my .Net application, but inside a sandbox? I want to deny the IP script access to the filesystem while still allowing the app itself access. </p> <p>Would this involve running the scripting engine in a second AppDomain? How would I handcuff it so it can't do...
<p>Here's an article explaining how to <a href="http://msdn.microsoft.com/en-us/library/bb763046.aspx" rel="noreferrer">create an AppDomain and execute code in a sandbox</a>. Just create the AppDomain and handcuff the code that runs inside it.</p>
.net|ironpython|appdomain|sandbox
12
5,451
69,532,812
Adding Disjunctive constraints in google ortools
<p>I'm trying to add an optional vehicle meeting state in google-ortools.</p> <p>I am trying to ensure that vehicle 1 can only go to the meeting node if vehicle 2 also visits the meeting node.</p> <p>The below code compiles, but it does not prevent the first vehicle one from visiting first_vehicle_meet, while second_ve...
<p>In the routing library, it you want to add (x == 2) || (y == 3)</p> <p>First query the solver</p> <pre><code> solver = routing.solver() </code></pre> <p>Then create one Boolean variable per equality</p> <pre><code> x2 = solver.IsEqualCstVar(x, 2) # You can use x2 == (x == 2).Var() y3 = solver.IsEqualCstVar(y, 3...
python|or-tools|vehicle-routing
2
5,452
69,385,863
Pivot / Reshape pandas dataframe
<p>Mock pandas dataframe to pivot:</p> <pre><code>df = pd.DataFrame({'id': ['A','B','C'], 'year': [2012, 2014, 2016], 'val1': [1,2,3], 'val2': [5,6,7], 'val3': [9,10,11]}) </code></pre> <p>I'd to pivot pandas dataframe to obtain following shape...
<p>Try this, It is just a quick and dirty way to do it. Not the best.</p> <pre><code>#Transpose Year and other columns df1 = df[[&quot;year&quot;, &quot;val1&quot;, &quot;val2&quot;, &quot;val3&quot;]].T #Set first row as header new_header = df1.iloc[0] df1 = df1[1:] df1.columns = new_header df1.reset_index(inplace=T...
python|pandas
1
5,453
51,443,683
Greater than not working in Pygame
<p>I'm making a game that involves platforms. I want it to be that you cannot land on a platform unless you land on it from above. However, this doesn't seem to be working.</p> <pre><code>for platform in hits: if(object.rect.bottom &gt; platform.rect.top): object.vy = 0 object.rect.bottom = platfor...
<p>I found the answer! After many failed attempts of trial and error I found that </p> <pre><code>if(object.rect.bottom &lt; platform.rect.bottom): </code></pre> <p>works!</p>
python-3.x|pygame
0
5,454
51,401,989
Is there a way to send audio files to a Flask server?
<p>I am really new to programming Flask APIs. Is there any way to send a audio file which is recorded on an android device to my flask server? Should I send audio file byte by byte or is there a way to send it directly ?</p>
<p>Save the audio and use multipart</p> <p>In your flask script</p> <pre><code>@app.route('/uploadfile',methods=['GET','POST']) def uploadfile(): if request.method == 'PUT': f = request.files['file'] filePath = "./somedir/"+secure_filename(f.filename) f.save(filePath) return "succe...
android|python|audio|flask
1
5,455
51,165,295
add another options in action button in tree view odoo 10
<p>I want to add another options in action button on tree view. Moreover in export and delete, i want to add "Confirm" options. I don't know how, please help me. Thanks</p> <p><a href="https://i.stack.imgur.com/iJ62R.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iJ62R.png" alt="enter image descrip...
<pre><code> &lt;record id="action_id" model="ir.actions.server"&gt; &lt;field name="name"&gt;name&lt;/field&gt; &lt;field name="model_id" ref="module_name.model_object_name" /&gt; &lt;field name="code"&gt; action = model.function_name() ...
python-2.7|button|treeview|odoo-10
1
5,456
51,412,000
Running AppleScript inside of Python script
<p>I'm trying to run the AppleScript inside of my Python script but it does not work. When I run the same AppleScript in the AppleScriptEditor it works perfectly!</p> <p>This is my code:</p> <pre><code>script = ''' tell application "System Events" set position of first window of applicatio...
<p>Most likely the Python process is not allowed to touch the window. Manipulating Windows of other processes is a privileged operation that require your app to be whitelisted. See <a href="https://apple.stackexchange.com/questions/291574/osascript-is-not-allowed-assistive-access-1728">https://apple.stackexchange.com/...
python|macos|accessibility
1
5,457
17,587,160
Drawing text in python
<p>I have the following code (derived from <a href="https://stackoverflow.com/a/17556210/35070">this answer</a>) with my attempt to add the text drawing of numbers. It doesn't work. It doesn't create an image and the cmd prompt is too fast to see which error it is throwing.</p> <pre><code>#!/usr/bin/env python impor...
<p>You can open a command line window by pressing <kbd>Win</kbd>+<kbd>r</kbd><kbd>cmd</kbd> <kbd>Enter</kbd>. Once in there, you execute your program and still see its output. Another option would be to wrap the <code>generate_montage</code> call, like this:</p> <pre><code>try: generate_montage(sys.argv[1:], filen...
python|image|text|drawing
1
5,458
17,632,342
Extract string between characters from a txt file in python
<p>I have a txt file that I want python to read, and from which I want python to extract a string specifically between two characters. Here is an example:</p> <pre><code>Line a Line b Line c &amp;TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTEST...
<p>This works:</p> <pre><code>data=[] flag=False with open('/tmp/test.txt','r') as f: for line in f: if line.startswith('&amp;'): flag=True if flag: data.append(line) if line.strip().endswith('!'): flag=False print ''.join(data) </code></pre> <p>If yo...
python|character|extract
4
5,459
70,543,635
Django - Listing first model field values in second model createView form field for logged in user
<p>I am trying to add a transaction (2nd model) for a specific account (1st model) based on the logged in user, either by listing the available account in the transaction <code>creatView</code>, or by clicking on the account name on the rendered HTML page.</p> <pre class="lang-py prettyprint-override"><code>class Accou...
<pre><code> class Transaction(genric.creatView): user=Account.objects.filter(account_holder_name=self.request.user.username) tran_create=Transaction.object.create(account_name=user,**Kwargs) tran_create.save() </code></pre>
python|python-3.x|django|django-views
0
5,460
72,916,388
Find exact match between strings
<p>I am trying to create a function to get certain strings of a df column, only if there is an exact match with a string in a list. Here is an example:</p> <pre><code>my_list = ['Lys', 'Lysol', 'Cla', 'Clarins'] def test(row): for i in my_list: if i in row['Product']: return i else: re...
<p>This should work, no matter how long your list is and how you sort things:</p> <pre><code>def find_str(row, list_): words = row.split(' ') for elem in words: for search_str in list_: if search_str in elem: return elem return row df['Exact_match'] = df['Product']....
python|pandas|string|function|exact-match
1
5,461
55,774,631
Pyinstaller Python3 Windows10 - App will not start from .bat script
<p>Using Python3 and Pyinstaller on Windows 10... I created an app that runs fine when double clicking on it or when running it directly from the command line. However, it only works with the command line from inside of the working directory (its home directory). I want to use Windows scheduler to launch the app period...
<p>You should include <code>pic.jpeg</code> as part of your <code>my.exe</code> bundle. Try adding:</p> <pre><code>datas=[('pix.jpeg', '.')], </code></pre> <p>under the <code>Analysis</code> part of your <code>.spec</code> file. Also, make sure you are producing a <code>onefile</code> bundle.</p>
python|windows|batch-file|pyinstaller
0
5,462
73,434,988
Input Layer for Conv1D in Keras
<p>Let me explain my problem and the dataset a bit. In my dataset, i have hourly measurements of a variable <code>x</code> and 7 more columns representing the day of the week that that measurment was taken as dummy variables. So, it is something like this:</p> <pre><code>DateTime x Mon Tue Wed Thur Fri Sat S...
<p>in this case you are trying to solve a sequence problem, so if i got it true, you would need only the output values, Make a list of values which are the outputs and then by</p> <pre><code>dataset = tf.data.Dataset.from_tensor_slices(list_of_values) </code></pre> <p>take the list of values, you said you would need tw...
python|keras|conv-neural-network|conv1d
0
5,463
49,848,175
Fill forms using selenium or requests
<p>I'm trying to enter <a href="https://www.santandertotta.pt/pt_PT/Particulares.html" rel="noreferrer">this site</a> to retrieve my bank account, first I tried with selenium, but only filled username (maybe because it has 2 forms):</p> <pre><code>from selenium import webdriver driver = webdriver.Firefox() driver.get...
<p>You cannot get access to Password field because it's not present on main page. To handle Password field you have to click Login button to get to Login page. Also you need to switch to iframe which contains authentication form</p> <pre><code>from selenium.webdriver.support.ui import WebDriverWait as wait from seleni...
python|python-3.x|selenium|web-scraping|python-requests
8
5,464
64,794,913
How to get data of a variable from one class into another class in python?
<p>so I am writing code where I generate certain data in a class and save it in a dictionary. I want to use that data in the second class . The first class is as fellows:</p> <pre><code>class DataAnalysis(): def __init__(self,matfile=None): '''Constructor ''' self.matfile= matfile def g...
<p>The <code>get_alldata()</code> method in the <code>DataAnalysis</code> class you defined is returning a <code>bodedata_dict</code> which isn't defined anywhere. It's like printing the content of a variable without defining it first.</p> <p>EDIT: Looking further into it, <code>bodedata_dict</code>in the first example...
python-3.x|class
0
5,465
64,674,808
Pytesseract not detecting a digit which might be a picture within a picture
<p>I'm trying to extract the number from the image string given below</p> <img src="https://i.stack.imgur.com/hy3aJ.png" width="100" /> <p>I have no problem in extracting digits from normal text, but the digit in the above strip seems to be a picture within a picture. This is the code I'm using to extract the digit.</p...
<p>First you need to apply <code>adaptive-thresholding</code> with <code>bitwise-not</code> operation to the image.</p> <p>After <code>adaptive-thresholding</code>:</p> <p><a href="https://i.stack.imgur.com/JvMcD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JvMcD.png" alt="enter image description ...
python|ocr|python-tesseract
0
5,466
63,960,435
How to convert current date time to a specific format
<p>I have a date column in pandas and it has dates like this:</p> <pre><code>Fri Sep 18 2020 21:57:21 GMT+0500 (Pakistan Standard Time) </code></pre> <p>How do I convert it to a format like this :</p> <pre><code>2020-09-18 21:57:21 </code></pre>
<p>Let's try stripping the unnecessary text:</p> <pre><code>pd.to_datetime(df['text'].str.extract('^(.*) GMT')[0]) </code></pre> <p>Output:</p> <pre><code>0 2020-09-18 21:57:21 Name: 0, dtype: datetime64[ns] </code></pre>
python|pandas|datetime
2
5,467
63,828,437
How to setup a layer that takes grayscale image and ouputs ARGB making one of the grayscale color transparent?
<p>I started with DeepLabV3+ mlmodel that outputs 2D Multiarray (Segmented). Successfully added a layer that takes this as an input and outputs GRAYSCALE image.</p> <p>Now, I would like to take this GrayScale image as input and output ARGB, in which I would like to make either one of the color transparent.</p> <p>How t...
<p>It looks like your output has shape (1, 513, 513). The first number, 1, is the number of channels. Since this is 1, Core ML can only turn the output into a grayscale image. A color image needs 3 channels, or a shape of (3, 513, 513).</p> <p>Since this is DeepLab, I'm assuming your grayscale image doesn't really have...
python|machine-learning|image-segmentation|coreml|mlmodel
0
5,468
52,994,010
How can I remove HTML tag in Python from HTML file?
<p><strong>Summary:</strong> What regex string would I use to remove tags in a HTML document? Although, this may be a duplicate from a previous answer: <a href="https://stackoverflow.com/questions/11412758/how-to-remove-only-html-tags-in-a-string">How to remove only html tags in a string?</a> and <a href="https://stac...
<p>If <code>regex</code> is not required and to get the job done you can check existing implementations.</p> <h2>Django's <code>strip_tags</code>:</h2> <p><a href="https://github.com/django/django/blob/master/django/utils/html.py#L183" rel="nofollow noreferrer">https://github.com/django/django/blob/master/django/util...
python|html|regex|python-3.x|python-3.4
0
5,469
68,682,755
calculate effective time of a process by subtracting non-working-time
<p>I have a pandas dataframe with over 100 timestamps that defines the non-working-time of a machine:</p> <pre><code>&gt;&gt;&gt; off_time date (index) start end 2020-07-04 18:00:00 23:50:00 2020-08-24 00:00:00 08:00:00 2020-08-24 14:00:00 16:00:00 2020-09-04 00:00:00 23:59:59 2020-10-05 18...
<p><em>Set up sample data</em> (I added a couple of rows to your samples to include some edge cases):</p> <pre><code>######### OFF TIMES off = pd.DataFrame([ [&quot;2020-07-04&quot;, dt.time(18), dt.time(23,50)], [&quot;2020-08-24&quot;, dt.time(0), dt.time(8)], [&quot;2020-08-24&quot;, dt.time(1...
python|pandas|dataframe|datetime|timestamp
1
5,470
67,211,934
File transfer from one server to other server in Airflow
<p>I have a file(file.txt) present in server1 with userid as &quot;username1&quot; in the path ( /home/A/file1.txt) and want to transfer this file to other server &quot;server2&quot; with userid as &quot;username2&quot; and want to place the file in the path (/home/B/). I have written below code and its not working as ...
<p>I think your mistake is on the <code>bash_file_transfer</code> declaration. Should be <code>scp</code>, not <code>cp</code>.</p>
python|unix|airflow
1
5,471
60,556,962
Web Crawling/Web Scraping
<p>I am trying to learn how to web crawl/web scrape and need some help. I am currently in the process of web scraping from the following website: <a href="http://books.toscrape.com/" rel="nofollow noreferrer">http://books.toscrape.com/</a>. I am, however, having difficulty web scraping the price, rating, and cover url ...
<p>Try the below code</p> <pre><code>from lxml import html import requests page = requests.get('http://books.toscrape.com/') tree = html.fromstring(page.content) product_name = tree.xpath('//article[@class="product_pod"]/h3/a/text()') product_price=tree.xpath('//div[@class="product_price"]/p/text()[1]') cover_image=t...
python|web-scraping|web-crawler
1
5,472
63,533,705
List of Counts in the Correct Order
<p>For the list:</p> <pre><code>names=['fred', 'fred', 'fred', 'bill', 'bill', 'ted', 'ted', 'ted', 'ted'] </code></pre> <p>I would like to return a list of counts for each name:</p> <pre><code>desired_list=[3,2,4] </code></pre> <p>Note the count of each name is in the same order as in the list 'names'.</p> <p>Code I h...
<p>Use <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow noreferrer"><code>collections.Counter</code></a></p> <pre><code>from collections import Counter names = ['fred', 'fred', 'fred', 'bill', 'bill', 'ted', 'ted', 'ted', 'ted'] print(list(Counter(names).values())) </code...
python|list|count|compression
2
5,473
56,470,306
How to update elements on display after passed time?
<p>I got a program in Pygame which allows me to show up elements from the list <code>list</code>. Each 3 seconds, it updates and displays the next element from <code>list</code>. My problem is that elements are overlapping on screen, but I want to update it each time 3 seconds have passed. I already used:</p> <pre><co...
<p>Here's something that updates what's displayed every three seconds:</p> <pre><code>import sys import time import pygame from pygame.locals import * pygame.init() FPS = 30 WINDOWWIDTH = 640 WINDOWHEIGHT = 480 BLACK = (0, 0, 0) WHITE = (255, 255, 255) clock = pygame.time.Clock() font = pygame.font.SysFont("comicsan...
python|list|pygame|display
1
5,474
56,786,959
QPainter in pyqt5 is not painting anything when calling repaint() in a loop. How do I fix this?
<p>I am totally new to PyQt. I want to do animation using PyQt5 .This is a simple test I am doing , so I am just trying to move a rectangle from top to the bottom of the window. Here's a gist of what I am doing to achieve this.</p> <ol>1. I have put whatever I wanted to paint inside paintEvent() method. I have painted...
<h3>Problem:</h3> <p>Having a continuous loop does not allow the GUI to perform tasks such as painting, interaction with the OS, etc. Each GUI provides a way to make animations in a way that does not block the window.</p> <hr> <p>Qt provides various classes that allow you to implement the animation as:</p> <ul> <li...
python|python-3.x|animation|pyqt|pyqt5
2
5,475
66,240,853
How to get best audio quality on music bot using discord.py?
<p>I've built a discord music bot in discord.py but for some reason, it doesn't play music in as high quality as Fredboat or Rythm(so I don't think voice chat's bitrate is the problem). I've tried a couple of things online.</p> <p>The only thing that improved quality a little bit was downloading the song before playing...
<p>I was also stuck in this quality issue. But I found a work around this.</p> <p>You can also test this , I got same quality as that of streaming with no issues.</p> <pre><code>FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'} YDL_OPTIONS = {'format': '...
python|ffmpeg|discord|discord.py
0
5,476
66,079,371
does not let me use f or f1 as a command for the discord bot
<p>Im trying to use specifically &quot;f1&quot; as the command to pass to the discord bot but I end up getting the error</p> <pre><code>Ignoring exception in command None: discord.ext.commands.errors.CommandNotFound: Command &quot;f1&quot; is not found </code></pre> <p>It's weird, since it wasnt complaining when I used...
<p>You haven't defined a command for &quot;f1&quot;, Hence the error.</p>
python|discord
0
5,477
72,803,383
Scatter plot in python
<p>I have a vector X of size 100x2 and the corresponding binary labels in a vector y ={1, -1} of length 100. I would like to plot the scattered data with s.t. I get the features on the axis and the color of the data point corresponds to a label e.g. red is -1, yellow is 1 for a given data point.</p> <p>I've been lookin...
<p>You can do this easily using <code>seaborn</code> (or matplotlib as well). Below is the code.</p> <ol> <li>I am creating a random array of size 100x2 and calling it X. I am creating a random array of 0s and 1s of size 100x1 and calling it Y</li> </ol> <pre><code>&gt;&gt; import numpy as np &gt;&gt; X = np.random.ran...
python|scatter
1
5,478
68,346,736
Some of Pandas subplots is blank or not displayed correctly
<p>I am trying to create subplots using a Pandas DataFrame but some of them are blank and not displayed correctly. I don't know where I made a mistake. Pandas Data Reader sometimes gives an error when receiving data from FRED, when I convert subplots to seaborn scatterplots in such errors, the problem is solved, but wh...
<p>Your <code>for</code> loop should be like this instead.</p> <pre class="lang-py prettyprint-override"><code>for ax, col in zip(axes.flatten(), df.columns): ... </code></pre> <p>You need to flatten the <code>axes</code> grid, making in one dimensional, otherwise the <code>zip</code> function won't work properly, h...
pandas|dataframe|matplotlib|seaborn|pandas-datareader
0
5,479
59,207,470
In a Pandas Dataframe Groupby.agg() to combine mulitple columns as arguments to a lambda function
<p>I want to be able to create an aggregate groupby column that is created from an aggregate function that depends on more than just one column of the original dataframe. For example (in this case), I want to compute the exponentially weighted mean of a list of assets with a given half life.</p> <p>Here is an example ...
<p>Your approach on <code>stats2</code> is close. Try to use <code>apply</code> instead of <code>agg</code>. Then assign it back to the columns <code>'ewm'</code> of <code>stats</code> to combine the result.</p> <pre class="lang-py prettyprint-override"><code>stats2 = df.groupby('ASSET').apply(lambda x: (np.exp(k * x[...
dataframe|lambda|aggregate|pandas-groupby|multiple-columns
0
5,480
62,986,339
how can I call a class without passing driver?
<p>I'm trying to create a callable class that clicks on an element and waits until a new element appears. this is what I have:</p> <pre><code>class ButtonElementAndWaitNewElement: driver = None def __init__(self, locator, element_to_appear): self.locator = locator self.element_to_appear = element_to_appear de...
<p>Give <code>driver</code> a default value of <code>None</code>, then change a <code>None</code>-valued argument to <code>self.driver</code>.</p> <pre><code>def __call__(self, driver=None): if driver is None: driver = self.driver WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, se...
python|selenium|webdriver
0
5,481
59,697,485
How to obtain pagination for the Mongo Aggregate
<p>I have been using flask-paginate for pagination and Mongo DB as database:</p> <p>In view.py page</p> <pre><code>from flask_paginate import Pagination, get_page_args @app.route('/test',methods=['GET','POST']) def searchindex(): page, per_page, offset = get_page_args() pipeline = [{ '$match': { "...
<p>It's recommended to apply <code>$sort</code> operator for correct pagination.</p> <p>Probably you are getting different result for every execution.</p> <p>Try MongoDB way. Just add as last stages <code>$skip</code> and <code>$limit</code> to aggregation pipeline (imagine you have >1M records) and calculate total r...
python|mongodb|flask|pymongo
1
5,482
49,161,846
More efficient approach of creating class instances of different classes?
<p>Let's say we have a function <code>classes_init</code>. It takes in lists or other types of information which it uses to initialize many instances of different types of classes, such as:</p> <pre><code>["spam", 24] ["eggs", 10] ["bacon", 20] ... </code></pre> <p>Index 0 of those lists indicates what type of class ...
<p>Use a dictionary to map string to class:</p> <pre><code>class_map = { 'spam': Spam, 'eggs': Eggs, 'bacon': Bacon, } def classes_init(xlists): classlist = [class_map[name](argument) for name, argument in xlists] </code></pre> <p>The class map could be created from the class names, if all the string...
python|python-3.x|class|oop|initialization
7
5,483
49,319,900
Django Ceilometer get events for all projects
<p>I have a problem for getting all events for all tenants/projects in Ceilometer. When I get the event list I always get only the list of events related to project that my user assigned. The user is admin in openstack. </p> <p>Explaining in more detail:</p> <p><strong>Here is my sample code:</strong></p> <pre><cod...
<p>You need to make a filtering query using <code>all_tenants eq True</code> as documented on the bottom of the <a href="https://docs.openstack.org/panko/latest/webapi/v2.html" rel="nofollow noreferrer">API docs</a>.</p> <blockquote> <p>2) Specify the ‘all_tenants=True’ query parameter to get all events for all proj...
python|django|openstack|ceilometer
1
5,484
60,240,402
Issue with a skiping of first row
<p>I understand that it skips the first row in the file because of header, but how can I avoid it? The syntax must be exactly the same as it is below.</p> <p>File contains: <code>Rabbit, Pig, Dog, Horse, Bird</code></p> <pre><code>try: file = open("file.txt") line = file.readline() animals = [] for...
<p>The problems is the line variable, it reads a line and it is never used. You should consider using another name for the variable file because it is a keyword. Also it is good practice to open files in this format:</p> <pre><code>with open("file.txt") as f: f.read() </code></pre> <p>This should work.</p> <pre><co...
python|list
1
5,485
66,770,718
Class Attribute value does not change
<p>I am learning python and part of my excercise is to introduce betting into an already working code of Black Jack game. Now I have surprsing worked the solution out but the issue is after the first round is finished, the value of the Pot(Player Pot) stays the same, ie the Pot of the Black jack player. If the player ...
<p>Instead of setting <code>self.Bet</code> to the value that the player won/lost depending on the result (<code>self.wins</code>/<code>self.loses</code>) you do the other way around and set <code>self.wins</code>/<code>self.loses</code> to the value of <code>self.Bet</code>.</p> <p>Change <code>self.loses=self.Bet</co...
python|python-3.x
0
5,486
66,872,421
Matplotlib subplot axes change size after plotting data
<p>I have a fairly lengthy program that I've been working on to do some data analysis at my lab. It takes a csv file and calculates a limit of detection for one or more gene targets based on a range of concentrations of input DNA (RNA, actually, but it's irrelevant in this case).</p> <p>Since the number of targets to b...
<p>Inside <code>drawplots()</code> about line 82 in your code, try using <code>ax.set_aspect('auto')</code> (you currently have it set to <code>ax.set_aspect('equal')</code>) Setting it to <code>'auto'</code> produced the graphs you are looking for: <a href="https://i.stack.imgur.com/Y46RZ.png" rel="nofollow norefer...
python|pandas|numpy|matplotlib
1
5,487
42,727,667
Creating dummy variables by grouping
<p>I have a DataFrame representing player, team and win. What I would like to do is create a new DataFrame where team is the index and whether player x was in that team is represented, and if that team won.</p> <pre><code>pd.DataFrame(data=[['Team A', 1], ['Team B', 0], ['Team B', 0], ['Team A', 1]], columns=['TEAM', ...
<p>IIUC you can use <code>pivot_table()</code> method:</p> <pre><code>In [96]: df.reset_index().pivot_table(index='TEAM', columns='index', values='WIN', fill_value=0) Out[96]: index Player 1 Player 2 Player 3 Player 4 TEAM Team A 1 0 0 1 Team B 0 0 0 ...
pandas|machine-learning|dummy-variable
2
5,488
56,016,521
No such file or directory: 'B.npz' while compiling 'pose_estimation.py' to draw 3d cube using Opencv
<p>I want to draw 3D coordinate axis (X, Y, Z axes) on a chessboard’s first corner using Opencv and python.</p> <p>But when I run this following code, </p> <pre><code>import cv2 import numpy as np import glob def draw(img, corners, imgpts): corner = tuple(corners[0].ravel()) img = cv2.line(img, corner, tupl...
<p>In order to generate the <code>B.npz</code> file, you should add <code>np.savez()</code> with some parameters (<code>mtx</code>, <code>dist</code>, <code>rvecs</code> and <code>tvecs</code>) after <code>cv.calibrateCamera()</code> in the <a href="https://docs.opencv.org/master/dc/dbb/tutorial_py_calibration.html" re...
python|python-2.7|opencv|opencv3.0
2
5,489
54,124,065
Pandas: Conditional column creating
<p>I'm trying to <strong>create column C</strong>, based on the values in columns A and B given the following conditions:</p> <pre><code>if A &lt; 5000: C = A * B else: C = A </code></pre> <p>The following gives a syntax error:</p> <pre><code>df['C'] = df.apply(lambda x (x['A'] * x['B)'] if x['A'] &lt; 5000 else x =...
<p>Use vectorized <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow noreferrer"><code>numpy.where</code></a>:</p> <pre><code>df['C'] = np.where(df['A'] &lt; 5000, df['A'] * df['B'], df['A']) </code></pre> <p><strong>Performance</strong>:</p> <pre><code>np.random.seed(2019)...
python|pandas|conditional
4
5,490
53,664,727
Calculating if ordered quantity is not equal to package
<p>In my case, I'm selling the product's in packages. 1 package is 24 products if I order 30 than it is more than 1 package but less then 2 so I'm raising an error for a user to know that he is ordering more than one package and less then two. But the problem is that this warning should not appear when he is ordering 4...
<pre><code>product_qty = 30 packaging_qty = 24 def check_unpacking_allowence(self): if product_qty % packaging_qty != 0: raise UserError('You cant break packaging') </code></pre>
python
2
5,491
73,666,971
django-safedelete 1.3.0 - Cannot migrate
<p>I built an internal app that used django-safedelete. I was working fine for months, until i recently upgraded my distro, and tried to add a field to my model. I also upgraded my python modules, everything is up-to-date, and no errors during the upgrade.</p> <p>Now I cannot migrate anymore:</p> <ul> <li><p>if I &quot...
<p>It's a wonder how I can actually look for answers for hours, then post on this site, and a few minutes later, I actually find the answer ...</p> <p>Anyway. It looked like I was mistaken on the meaning of the second error message. It failed because a previous migration already create the deleted_by_cascade field in a...
python|mysql|django|django-models|django-migrations
0
5,492
52,069,592
How to take the resulting object of a function called from another module?
<p>The idea is this - say I have a function in <code>module2.py</code> called <code>def run(example):</code> which has a data-frame object as the result of running it, let's call it <code>df_1</code>. If I call <code>module2.run(example)</code> inside <code>module1.py</code> will I be able to continue to use the result...
<p>Yes, you can do exactly the way you have said, in module1.py, you just have to import module2.py like "import module2" or if the function is inside a class, you can import it like "from module2 import classname" Then you can create the object of the class and then call the method. You need to return the dataframe o...
python|pandas
1
5,493
47,986,068
How to remove whitespace at specfic position/index of Python string
<p>I am trying to remove whitespace at a specific position within a Python string.</p> <p>For example, I have the following string: <code>time = "Year 1.2 Quarter 4"</code> </p> <p>Since I want Quarter to be abbreviated, I replaced the word using this: </p> <pre><code>time = time.replace('Quarter','Q') ##Output: ...
<p>Avoid using <code>time</code> as variable name as it might conflict with <code>time</code> package.</p> <p>You can use <code>replace()</code> as following:</p> <pre><code>time_str = "Year 1.2 Quarter 4" time_str = time_str.replace("uarter ", "") print(time_str) </code></pre> <p>output:</p> <pre><code>Year 1.2 Q...
python|python-3.x
1
5,494
39,600,006
building simple terminal pyqt4 and pyserial how to update textbrowser
<p>I have followed a simple tutorial on creating a basic gui using qt designer and have incorporated that into python. I then made a simple python script that just continuously reads newlines from the serial port and prints them to the terminal. I want to combine them but I'm afraid my understanding of how pyqt4 works ...
<p>For anyone that has a similar issue. I found a solution by implementing a timer and creating a new function in the class:</p> <pre><code>self.my_timer = QtCore.QTimer() self.my_timer.timeout.connect(self.print_serial) self.my_timer.start(10) # milliseconds def print_serial(self): if ser...
python|pyqt|pyserial
0
5,495
32,185,232
How to avoid/fix django's DatabaseTransactionError
<p>I have the following (paraphrased) code that's subject to race conditions:</p> <pre><code>def calculate_and_cache(template, template_response): # run a fairly slow and intensive calculation: calculated_object = calculate_slowly(template, template_response) cached_calculation = Calculation(calculated=cal...
<p>The Django docs on <a href="https://docs.djangoproject.com/en/1.8/topics/db/transactions/#controlling-transactions-explicitly" rel="nofollow">controlling transactions explicitly</a> have an example of catching exceptions in atomic blocks.</p> <p>In your case, you don't appear to be using the <code>atomic</code> dec...
python|django|django-orm
1
5,496
64,548,932
I want to export all the entries to an excel file
<pre><code>#bll import pickle import pandas as pd class Customer: cuslist=[] def __repr__(self): return(str(self)) def __init__(self): self.id=0 self.age=0 self.name=0 self.dateofBirth = 0 self.address = 0 self.phoneNumber = 0 self.amount = 0 ...
<p>Look into openpyxl.</p> <p>It's a python module that lets you do stuff like this:</p> <pre><code>from openpyxl import Workbook book = Workbook() sheet = book.active sheet['A1'] = &quot;name&quot; sheet['A2'] = customer1.name sheet['A3'] = customer2.name sheet['B1'] = &quot;age&quot; sheet['B2'] = customer1.age she...
python|pandas|dataframe
1
5,497
64,364,946
Are "Iterable", "Iterator" examples of types in python?
<p>This is a question about how python's (dynamic) type system works. I have read articles online saying that to define a class to be &quot;an iterable&quot;, we need to define a <code>__iter__</code> function for it. We don't in fact have to explicitly state that that class &quot;is an iterable&quot;. I would have gue...
<p>A <code>type</code> is what python calls any object that's been defined via a <code>class</code> statement. Using Java as a reference point, <code>type</code> is akin to <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html" rel="nofollow noreferrer"><code>java.lang.Class</code></a> - the class tha...
python
5
5,498
64,431,264
django ValueError Cannot query "abcd@gmail.com": Must be "object" instance
<p>i am trying to make an app for student but i'm getting this error, as you can see for convenient i wanted to use like that one i showed bellow but it doesn't work, should i keep using like before? or i could use like that ? what would be best way ?</p> <p><strong>ValueError at /student/program_structure/ Cannot quer...
<p>The <code>user</code> field of the <code>Course</code> refers to the <code>Student</code> object, not a <code>User</code> object, so you can not user <code>request.user</code> for this.</p> <p>You can however query for a <code>Course</code> where the <code>user</code> is a <code>Student</code> where the <code>user</...
python|django|django-models|django-views|django-templates
1
5,499
69,696,228
String Concatenation Issue with the If Else Logic in Python
<p>I have this table:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>name</th> <th>address</th> <th>city</th> <th>Result</th> <th>Required Result</th> </tr> </thead> <tbody> <tr> <td>Sara</td> <td>abc</td> <td>NY</td> <td>Sara, abc, NY</td> <td>Sara, abc, NY</td> </tr> <tr> <td></td> <td>d...
<p>Try this</p> <pre class="lang-py prettyprint-override"><code>return ', '.join([i.strip() for i in [name, address, city] if i.strip()]) </code></pre> <p>instead of all that if else statements</p> <p>This pretty much does the same, just using some in-built functions and methods in Python</p> <pre class="lang-py pretty...
python
2