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
9,500
51,855,169
dialogflow: 403 IAM permission 'dialogflow.sessions.detectIntent'
<p>After hours of reading docs and resources, I am asking for your help.</p> <p>I have a dialog flow agent on API V2 project "xxx1"</p> <p>I have created a service account for "xxx1" and attached role "Dialogflow API Client"</p> <p>I downloaded the JSON file with credentials.</p> <p>I create the session in python w...
<p>I faced the same issue while integrating Dialogflow with external client.</p> <p>The root cause for my case was that even though I created the service account for my external client, I forgot to add the service account and give "Dialogflow API Admin' Role.</p> <p>How I resolve: In GCP project, go to IAM > click th...
python|dialogflow-es
2
9,501
59,799,890
utf-8 and skipinitialspace within a line
<p>I'm recently using pandas to read dataframe from a CSV file. Upon calling the reading the Csv file I also have to include 'utf-8' in order to not get the following error</p> <pre><code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0x84 in position 19: invalid start byte </code></pre> <p>So I go and modify th...
<p>I had a similair problem when working with lots of diferent <code>txt</code> files, I developed a small program to parse 50 lines of my file and detect the encoding using chardet.</p> <p>it's bettter to use more lines as suggested by anky_91 so use 1000 or more.</p> <pre><code>from pathlib import Path import chard...
python|pandas|utf-8
1
9,502
62,161,909
get the minimum column between columns values pyspark
<p>i have a dataframe with x,y,z columns and with 3 X columns and 3 Xd columns and i want to get the minimum Xd column with his X in a new column called id.</p> <pre><code>df: x y z a ad b bd c cd 4 8 1 1 2 2 8 3 5 7 5 6 1 6 2 3 3 1 7 3 5 1 9 2 4 3 7 result: x y z id 4 8 1 1 7 ...
<p>Try this, using <strong><code>arrays_zip</code></strong>, higher order function <strong><code>filter</code></strong>, and <strong><code>array_min</code></strong>.</p> <pre><code>from pyspark.sql import functions as F df.withColumn("zip", F.arrays_zip(F.array('a','b','c'),F.array('ad','bd','cd')))\ .withColumn("i...
python|dataframe|pyspark|minimum
2
9,503
56,164,489
Selenium Chromedriver not navigating to url
<p>What I have now is:</p> <pre><code>chrome_options = Options() chrome_options.add_extension(r"C:\Users\x\OneDrive\Desktop\pp\crxSolver.crx") driver = webdriver.Chrome(r'C:\Users\x\OneDrive\Desktop\chromedriver.exe', options=chrome_options) driver.get("https://www.google.com") </code></pre> <p>I am able to open the ...
<p>Try upgrading to chrome 75, your issue should resolve. Seems to be some issue with the machine and your browser compatibility.</p>
python|selenium
5
9,504
36,427,596
Freeze the first column in Treeview pygtk
<p>I am using a <strong>pygtk</strong> application and I have added a <em>Treeview</em> inside a <em>ScrolledWindow</em>. Now I want to freeze the <strong>first column</strong> (fix the column position), so that when scrolling the <em>Treeview</em> horizontally the column position is fixed and still visible (as it's do...
<p>The closest I've been able to get is a bit of a kludge. I use Perl, not Python, so I'll just describe my technique.</p> <p>Connect to the treeview's scroll-event signal and watch for direction=left/right (or smooth with get_scroll_deltas() returning non-zero for the X axis). Be sure to return FALSE for vertical s...
python|gtk|pygtk|gtktreeview
0
9,505
36,272,334
Can i use a wildcard in os.path.ismount() in python
<p>i Would like to check if there are any /decrypt* mount points.Using wildcard with os.path.ismount() was my best guess, but it doesn't work. What can I do then</p>
<p>You can use <a href="https://docs.python.org/2/library/glob.html" rel="nofollow"><code>glob.glob(pattern)</code></a> to expand the wildcard into a list of candidates to pass to <code>os.path.ismount</code>.</p> <pre><code>for path in glob.glob(pattern): if os.path.ismount(path): print(path) # Or do wha...
python-2.7
0
9,506
36,541,007
ImportError from python-fitbit
<p>I'm trying to use the python-fitbit package with Python 3.4 to get information from Fitbit (<a href="https://github.com/orcasgit/python-fitbit" rel="nofollow">https://github.com/orcasgit/python-fitbit</a>). </p> <p>Whenever I run it, I get the following error. Right now oauthlib is installed, and I've tried unins...
<p>Where in your file system did you install oauthlib?</p> <p>Please make sure that oauthlib is in your python path. In order to check your python path you can execute:</p> <pre><code>import sys; print sys.path </code></pre>
python
0
9,507
17,128,914
Get max keys of a list of dictionaries
<p>If I have:</p> <pre><code>dicts = [{'a': 4,'b': 7,'c': 9}, {'a': 2,'b': 1,'c': 10}, {'a': 11,'b': 3,'c': 2}] </code></pre> <p>How can I get the maximum keys only, like this:</p> <pre><code>{'a': 11,'c': 10,'b': 7} </code></pre>
<p>Use <a href="http://docs.python.org/2/library/collections.html#counter-objects" rel="noreferrer"><code>collection.Counter()</code> objects</a> instead, or convert your dictionaries:</p> <pre><code>from collections import Counter result = Counter() for d in dicts: result |= Counter(d) </code></pre> <p>or even:...
python|list|dictionary
8
9,508
58,072,185
Pytorch:Apply cross entropy loss with custom weight map
<p>I am solving multi-class segmentation problem using u-net architecture in pytorch. As specified in <a href="https://arxiv.org/abs/1505.04597" rel="nofollow noreferrer">U-NET</a> paper, I am trying to implement custom weight maps to counter class imbalances.</p> <p>Below is the opertion which I want to apply - <a h...
<p>Your <code>final_train_loader</code> provides you with an input image <code>data</code> and the expected pixel-wise labeling <code>target</code>. I assume (following pytorch's conventions) that <code>data</code> is of shape B-3-H-W and of <code>dtype=torch.float</code>.<br> More importantly, <code>target</code> is o...
deep-learning|pytorch|image-segmentation|semantic-segmentation|unet-neural-network
2
9,509
43,747,614
How to get legend location in matplotlib
<p>I'm trying to get the legend location in matplotlib. It seems like Legend.get_window_extent() should provide this, but it returns the same value regardless of where the legend is located. Here is an example:</p> <pre><code>from matplotlib import pyplot as plt def get_legend_pos(loc): plt.figure() plt.plot...
<p>You would need to replace <code>plt.draw()</code> by </p> <pre><code>plt.gcf().canvas.draw() </code></pre> <p>or, if you have a figure handle, <code>fig.canvas.draw()</code>. This is needed because the legend position is only determined when the canvas is drawn, beforehands it just sits in the same place. </p> <p...
python|matplotlib|legend
3
9,510
54,291,425
Accessing keyword argument of decorated function inside the decorator fails in Python 3
<p><code>kwargs</code> is empty in the following code. How to access timeout keyword arg of the decorated function?</p> <pre><code>import functools def retriable(func): @functools.wraps(func) def wrapper(*args, **kwargs): timeout = kwargs['timeout'] criteria_satisfied = func(*args, **kwargs) ...
<p>The solution was to make decorator with arguments. Which would return another decorator over the function and would populate the created closure with the argument value. </p> <pre><code>import functools def retriable_with_arg(timeout): def retriable(func): @functools.wraps(func) def wrapper(*arg...
python|python-3.5|python-decorators|functools
0
9,511
54,618,012
Show edges and faces of markers in legend
<p>I have the attached plot, and I like the symbols as plotted with </p> <pre><code>ax.errorbar('mjd', 'aperMag3Ab', label='', fmt='o', color='k', ms=ms*1.4) ax.errorbar('mjd', 'aperMag3Ab', label='WFCAM Y', fmt='o', color='y', ms=ms) </code></pre> <p>basically repeated eight times in total. The legend I cur...
<p>I don't have access to your data but if you explicitly set the <code>fmt</code>, <code>markeredgewidth</code> and <code>markeredgecolor</code> in the plot, it should show up in the legend as well.</p> <p>As a minimal working example:</p> <pre><code>import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.error...
python|matplotlib|plot|label|legend
2
9,512
71,252,199
Tricky distance matrix calculation and how to cleverly avoid out of bounds
<p>I have the layout of a warehouse with racks and aisles where items are picked from locations on the racks while traversing the aisles:</p> <p><a href="https://i.stack.imgur.com/5EPFv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5EPFv.png" alt="" /></a></p> <p>I want to compute a distance matrix...
<p>In your comment, you stated that the last point is (330,31), which is inconsistent with your linspace. The biggest mistake is that you are iterating over the individual axes, whilst you should iterate over all combinations of the coordinates. I separated out the distance calculation and the matrix generation, becaus...
python|numpy
1
9,513
71,285,719
Python loop to run after n minutes from start time
<p>I am trying to create a while loop which will iterate between 2 time objects, <code>while datetime.datetime.now().time() &lt;= datetime.datetime.now() +relativedelta(hour=1):</code> but on every n minutes or second interval. So if the starting time was 1:00 AM, the next iteration should begin at 1:05 AM with n being...
<p>This can be achieved with a manual implementation.</p> <p>Essentially, you would need to loop continuously until you reach the &quot;active&quot; time window. Once there, you basically execute your function and refuse to run again until the specified execution interval has passed. The main loop does not need to be e...
python|datetime|scheduled-tasks|python-datetime
3
9,514
39,037,663
Python - Basic vs extended slicing
<p>When experimenting with slicing I noticed a strange behavior in Python 2.7:</p> <pre><code>class A: def __getitem__(self, i): print repr(i) a=A() a[:] #Prints slice(0, 9223372036854775807, None) a[::] #prints slice(None, None, None) a[:,:] #prints (slice(None, None, None), slice(None, None, None)) </cod...
<p>For Python 2 <code>[:]</code> still calls <a href="https://docs.python.org/2/reference/datamodel.html#object.__getslice__" rel="noreferrer"><code>__getslice__(self, i, j)</code></a> (deprecated) and this is documented to return a slice <code>slice(0, sys.maxsize, None)</code> when called with default parameters:</p>...
python|python-2.7
10
9,515
55,562,098
Unable to connect Google App Engine to CloudSQL Postgres (via SQLAlchemy) in cloud shell
<p>Running a small web app on Google App Engine (Flexible) using Python 3, Flask, SQLAlchemy, the psycopg2-binary package, and CloudSQL Postgres. The app connects to CloudSQL properly in my local dev environment (I use the proxy), but it won't seem to connect when deployed in the cloud.</p> <p>Worked fine the first t...
<p>For those reading this via search in the future, I had previously skipped the <code>export SQLALCHEMY_DATABASE_URI=postgresql+psycopg2://[USER]:[PW]@127.0.0.1:5432/[DB_NAME]</code> because I didn't particularly care about the cloud shell environment and assumed it wouldn't make a difference for deployment. Apparent...
python|google-app-engine|sqlalchemy|google-cloud-sql
3
9,516
52,601,904
I am trying to create a new column to bin values of a time column of a dataframe in python based on time range
<p>Time column values: 09:11:00,10:11:00...NAT</p> <pre><code>pd.cut(df_master['time_colum`enter code here`n'],bins= ['09:11:00','11:44:00','13:55:00','16:28:00'], labels= ['Morning','Afternoon','Evening']) TypeError Traceback (most recent call last) &lt;ipython-input-102-c66025f961bf&gt; in &lt;module&gt;(...
<p>You just have to convert your string time to time delta value </p> <pre><code> time 0 09:31:00 1 12:04:00 2 14:15:00 3 16:48:00 df1['time'] = pd.to_timedelta(df1['time'] pd.cut(df1['time'],bins=pd.to_timedelta(['09:11:00','11:44:00','13:55:00','16:28:00']), labels=['Morning','Afternoon','Evening']) </co...
python|pandas
1
9,517
37,234,063
subpattern filter
<p>I'd like to generate a pattern for a python script, where any number of three words must exist in a specified pattern?</p> <p>for example, given a sequence:</p> <pre><code>ATG GTC TGA CGA CGG CAG TAA AAA AAA GGG TGG GCA GCC TTT GAA GCC TTT </code></pre> <p>I'd like to find all occurrences of <strong>19-21mers</st...
<p>I don't think regex is expressive enough to handle this with the length requirement.</p> <p>However, you can break down this problem by using a window iterator to simulate an open read frame:</p> <pre><code># From http://stackoverflow.com/questions/6822725/rolling-or-sliding-window-iterator-in-python: from iterto...
python|regex|bioinformatics
1
9,518
33,997,369
after.each_scenario hook is not working(not available) in aloe_django
<p>I wanted to do some operations(clear cookies, clear database etc) after each scenario in one feature, but the after.each_feature is not available in aloe_django. How did you deal with this problem. Any suggestions to handle this. The following hook is not available in aloe_django. </p> <p><code>@before.each_scenari...
<p>I have used before/after.each_example() hook available in Aloe_django. You put this piece of code into your terrain.py file. </p> <p><code>@before.each_example def before_each_example(scenario,outline,steps): call_command(#your command#)</code> </p>
django|python-3.x|bdd|lettuce
1
9,519
34,393,353
Login to a website using script
<p>I am actually writing a windows script which on clicking will open my default web browser , open a page , enter my login details and then submit the form. </p> <p>All I could do so far was open the browser with this:</p> <pre><code>explorer http:\\outlook.com\website.com </code></pre> <p>Since I could not find an...
<p><strong>IEC</strong></p> <p>For me the easiest to use option for controlling a browser from Python is <a href="http://www.mayukhbose.com/python/IEC/" rel="nofollow noreferrer">IEC</a>. I find very easy to use for simple things like you describe.</p> <blockquote> <p>IEC is a python library designed to help you automa...
python
6
9,520
72,682,621
how can we calculate the area of root image?
<p>in my project i need to calculate the area of small plant root image.</p> <p><a href="https://i.stack.imgur.com/1wfGV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1wfGV.png" alt="rootimage" /></a></p> <p>i have used the following two codes but i still doubt these:</p> <pre><code>import cv2 imag...
<p>If your thresholded image has no noise, then <code>countNonZero</code> is fine.</p> <p>But if after threshold you still have some noise, which is usually small black dots scattered here and there, then better to filter them out.</p> <p>One of possible ways is to apply <em>morphological opening</em>, see <a href="htt...
python|image|opencv|root|area
0
9,521
39,645,899
Can I prevent the Cmd dialogue from popping up when using SymPy preview?
<p>I have written some code in Python 2.7 that will read a string from a .ini file and generate a .png image of the string in LaTeX format using <code>sympy.preview</code>. The idea is to use this script to generate the images in the background while I am typing them out. The problem is that even when I run the script ...
<p>I solved my own problem. If I ran the Python script from a previously-existing cmd instance, the windows didn't pop up. My solution then was to start a hidden instance of cmd and send the path location to the hidden cmd window. This enabled the Python code to be executed without the annoying popups from <code>latex....
python|latex|command-prompt|sympy
1
9,522
39,574,474
Run Length Encoding in python
<p>i got homework to do "Run Length Encoding" in python and i wrote a code but it is print somthing else that i dont want. it prints just the string(just like he was written) but i want that it prints the string and if threre are any characthers more than one time in this string it will print the character just one tim...
<p>Three remarks:</p> <ol> <li>You should use the existing method <code>str.count</code> for the <code>encode</code> function.</li> <li>The <code>decode</code> function will print <code>count</code> times a character, not the character and its counter.</li> <li>Actually the <code>decode(encode(string))</code> combinat...
python
0
9,523
38,657,109
How to call a Python script with arguments from Java class
<p>I am using <em>Python 3.4</em>.</p> <p>I have a Python script <code>myscript.py</code> :</p> <pre><code>import sys def returnvalue(str) : if str == "hi" : return "yes" else : return "no" print("calling python function with parameters:") print(sys.argv[1]) str = sys.argv[1] res = returnvalue...
<p>Have you looked at these? They suggest different ways of doing this:</p> <p><a href="https://stackoverflow.com/questions/27235286/call-python-code-from-java-by-passing-parameters-and-results">Call Python code from Java by passing parameters and results</a></p> <p><a href="https://stackoverflow.com/questions/938190...
java|python|python-3.4
6
9,524
40,394,874
How to find common elements inside a list
<p>I have a list l1 that looks like [1,2,1,0,1,1,0,3..]. I want to find, for each element the indexes of elements which have same value as the element.</p> <p>For eg, for the first value in the list, 1, it should list out all indexes where 1 is present in the list and it should repeat same for every element in the lis...
<p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html" rel="nofollow noreferrer"><code>numpy.unique</code></a>, which can return the inverse too. This can be used to reconstruct the indices using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel...
python|pandas|dataframe
1
9,525
40,677,389
Python: How to get the updated dictionary in 1 line?
<p>In python, I have a dictionary named dict_a : </p> <pre><code>dict_a = {'a':1} </code></pre> <p>and I want to get a new dictionary <code>dict_b</code> as the update of <code>dict_a</code>,at the same time I don't want to change the <code>dict_a</code>, so I used this:</p> <pre><code>dict_b = copy.deepcopy(dict_a)...
<p>What about:</p> <pre><code>&gt;&gt;&gt; a = {'a':1} &gt;&gt;&gt; update = {'b': 1} &gt;&gt;&gt; b = dict(a.items() + update.items()) &gt;&gt;&gt; b {'a': 1, 'b': 1} </code></pre> <p><code>update</code> - is your value that need to update(extend) dict <code>a</code></p> <p><code>b</code> - is a new resulting dict...
python|dictionary
0
9,526
40,456,206
Importing a module in Python as part of a package *as well* as in a way that works stand-alone
<p>Note: This is Python 3.5</p> <p>Given some project <code>thing</code> such that:</p> <pre><code> thing/ top.py (imports bar) utils/ __init__.py (empty) bar.py (imports foo; has some functions and variables) foo.py (has some functions and variables) </code></pre> <p...
<p>Its typical to have all your entrypoints outside the module, than all imports can be relative. For example</p> <pre><code>thing/ app.py thing/ __init__.py top.py utils/ __init__.py bar.py foo.py </code></pre> <p>And app.py can look like</p> <pre...
python|python-import|python-3.5
3
9,527
68,060,054
Why Python Gensim LDA model is slower when using multicore comparing when using single-core (post shows comparisions)?
<p>I'm using a i5 8600 (6 cores and no multithreading).</p> <p>I'm comparing some topic modelling with LDA inside Gensim and I have no idea why I have these variatons <strong>shown below</strong>. I need to understand it so I can select and apply on a big data. <strong>Someone have a clue what's happening here?</strong...
<p>As gojomo and rchurch4 aptly pointed out above, there are multiple factors that can contribute to this situation:</p> <ol> <li>Memory pressure / swapping.</li> <li>Overhead for managing parallelism (e.g. splitting the job among parallel threads and combining the results).</li> </ol> <p>Please note though that <code>...
python|performance|gensim|multicore|lda
1
9,528
26,338,633
Twisted mail server with TLS - no portal?
<p>So thanks to a couple of users here, I now have a (almost) working SMTP Server that supports switching from plain text to TLS connection as required. Basic server code is:</p> <pre><code>from twisted.internet import ssl, protocol, defer, task, endpoints from twisted.protocols.basic import LineReceiver from twisted....
<p>So I've found what seems to be a simple answer - simply create overloaded definitions for ValidateFrom and ValidateTo in our custom ESMTP class! Works nicely enough... but I'm not 100% convinced this is the most "correct" solution - I can now submit my ehlo, mail from, and rcpt to... but when I try to submit "data":...
python|smtp|twisted
0
9,529
1,603,076
How to trim the longest match from beginning of a string (using python)
<p>In recent bash versions, I can do this:</p> <pre><code>$ string="Universe.World.Country.State.City.Street" $ echo $string Universe.World.Country.State.City.Street $ newString="${string##*.}" $ echo $newString Street </code></pre> <p>Using Python, what is a succinct way to doing the same? I am interested in the las...
<pre><code>&gt;&gt;&gt; 'Universe.World.Country.State.City.Street'.rpartition('.')[2] 'Street' </code></pre>
python|string
3
9,530
1,679,384
Converting Dictionary to List?
<p>I'm trying to convert a Python dictionary into a Python list, in order to perform some calculations.</p> <pre><code>#My dictionary dict = {} dict['Capital']="London" dict['Food']="Fish&amp;Chips" dict['2012']="Olympics" #lists temp = [] dictList = [] #My attempt: for key, value in dict.iteritems(): aKey = key...
<pre><code>dict.items() </code></pre> <p>Does the trick.</p>
python|list|dictionary
540
9,531
32,344,725
Tk Python - .trace leaves reference to object and doesnt allow the object to be garbage collected
<p>the basics of my problem is this, I have an object which gets created and destroyed fine (i.e. garbage collected) until I introduce the below line:</p> <pre><code>self.variableA.trace("w", self.printSomeStuff) </code></pre> <p>variableA is a stringVar and is set up as shown below</p> <pre><code>self.variableA = t...
<p>You can try to delete the callback(s) using <code>trace_vdelete()</code>. Hopefully that will remove the reference(s) to the tk variable.</p> <pre><code>def cb(*args): print args v = StringVar() v.trace('r', cb) v.trace('w', cb) v.set(10) # cb called # ('PY_VAR5', '', 'w') v.get() # cb called # ('PY_VAR5...
python|tkinter|trace
1
9,532
54,806,726
Flatten nested dictionary using Pandas
<p>I would like to flatten a nested dictionary. A solution for such a problem was suggested here: <a href="https://stackoverflow.com/a/41801708/8443371">https://stackoverflow.com/a/41801708/8443371</a>. Problem: I would like to obtain a keys identical to the keys in the last layer only. For an input:</p> <pre><code>d ...
<p>Here's my solution in pure python for the dictionary you've provided:</p> <pre><code>d = {'a': 1, 'c': {'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]} def flatten_dict(dic): result = {} for key in dic.keys(): if isinstance(dic[key], dict): result.update(flatten_dic...
python|pandas|python-2.7
2
9,533
27,931,532
Install Tkinter on python 2.6 and 2.7
<p>So we are trying to deploy a python module called Tkinter in a large multi-user environment under RHEL. It seems to be installed in python 2.6 but not 2.7. We tied yum install but it seems to only do it under python 2.6. How can we deploy under 2.7?</p>
<p>Try downloading Tkinter then using python 2.7 to run <code>python setup.py install</code></p>
python-2.7|tkinter|redhat|tk
0
9,534
27,996,106
Python Connect 4 check for winners (processing 2)
<p>So I'm trying to make a simple Python connnect 4 game on Processing 2, and now I'm trying to make the critical algorithm to check for the winner of a single round. It's not like tic-tac-toe, so I'm not sure where to start. If I should ask somewhere else, tell me as well.</p> <p>Basically, every time a player places...
<p>Here, I believe, is the function I think you're missing (needs to be checked out more carefully, maybe with <code>print</code> statements &amp;c, but though there may be off-by-one's &amp;c I think it's the right general idea):</p> <pre><code>def fours(fourthings): asaset = set(fourthings) return asaset.pop...
python|processing
0
9,535
44,319,380
max method of a list consisting of strings
<p>I am wondering why the result is '4' if I write the following code:</p> <pre><code>lists = ['1','2','3','4'] print(max(lists)) lists.append(5) print(max(lists)) </code></pre> <p>I suppose that the max method of lists converts from <code>str</code> to <code>int</code> first and then gives me the max of <code>int</c...
<p>Your list contains strings and you are appending an integer.</p> <p>lists = ['1', '2', '3', '4', 5]</p> <pre><code>TypeError: '&gt;' not supported between instances of 'str' and 'int' </code></pre> <p>If you had only strings or only int's max will do the comparison as the '>' operator will work. You need to conve...
python
1
9,536
12,295,834
Export a website to an XML Page
<p>I need to export a website(.html page) to a XML file. The website contains a table with some data which i require for using in my web project. The table in the website is formed using some javascript, so i cannot get the data by getting the page source. Please tell me how I can export the table in the website to a X...
<p>You could try to reverse engineer the javascript code. Maybe it's making an ajax request to a service, that delivers the data as json. Use your browsers developer tools/network tab to see what's going on.</p>
php|javascript|python|xml|perl
4
9,537
23,241,987
Find the index of an item in a list that starts with a user defined input
<p>Given a list such as:</p> <pre><code>lst = ['abc123a:01234', 'abcde123a:01234', ['gfh123a:01234', 'abc123a:01234']] </code></pre> <p>is there a way of quickly returning the index of all the items which start with a user-defined string, such as <code>'abc'</code>? </p> <p>Currently I can only return perfect matche...
<p>You can accomplish that using the following script/method (which I admit is quite primitive):</p> <pre><code>lst = ['abc123a:01234', 'abcde123a:01234', ['gfh123a:01234', 'abc123a:01234']] user_in = 'abc' def get_ind(lst, searchterm, path=None, indices=None): if indices is None: indices = [] if pat...
python|list
2
9,538
8,125,968
How to build wxPython trunk with mingw on Windows?
<ul> <li>I checked out wxPython and wxWidgets into two directories <code>C:\dev\wx\wxPtyhon</code> and <code>C:\dev\wx\wxWidgets</code>:</li> </ul> <pre> mkdir /D c:\dev\wx\ cd c:\dev\wx git clone https://github.com/wxWidgets/wxPython.git git clone https://github.com/wxWidgets/wxWidgets.git </pre> <ul> <li>I successf...
<p>On Linux I got what seemed like an identical error. I removed the error in this manner:</p> <ol> <li>I used the find command to get a list of wx-config programs</li> <li>From the list, I chose a wx-config that seemed right &amp; used its full path for WX_CONFIG</li> </ol>
wxpython|wxwidgets
1
9,539
41,752,309
Single legend item with two lines
<p>I'd like to generate a custom <code>matplotlib</code> legend which, for each entry has two lines for each label as shown in this example:</p> <p><a href="https://i.stack.imgur.com/PiAhd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PiAhd.png" alt="enter image description here"></a></p> <p>From...
<p>In the matplotlib legend guide there is a chapter about <a href="http://matplotlib.org/users/legend_guide.html#legend-handlers" rel="noreferrer">custom legend handlers</a>. You could adapt it to your needs, e.g. like this:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np from matplotlib.legend_hand...
python|matplotlib
12
9,540
41,847,337
Converting strings separated by comma in text files to JSON
<p>I am having problems converting strings in a text file to JSON format. Right now I have 3 text files, and in each file, there are many rows of object in the file that I would like to convert to JSON format.</p> <p>The strings are separated by a semicolon, as seen below:</p> <pre><code>mary; 24; female;1993; studen...
<p>Your text file is not in <a href="http://json.org/example.html" rel="nofollow noreferrer">JSON</a> format, so <code>json.loads()</code> won't work. Something like this could help convert it into JSON:</p> <pre><code>$ cat a.txt mary; 24; female;1993; student john; 21; male; 1982; student luke; 22; male; 1988; stude...
python|json|string|parsing
4
9,541
70,995,571
How to add a int and a str to print out after it calculates the numbers? I keep trying and it doesnt work?
<p>Im still VERY NEW to programming and python...Any help would be GREATLY appreciated..</p> <p>I am doing a BMI calculator in my python class.. I actually got it working the way the instructor wanted but I wanted to just improve it slightly and I had no idea it was going to be this difficult. My original code that act...
<p>Well, it's good that you are providing more information to the user than just printing out the BMI. But in this case, your test wants only a single number as output for validation.</p> <p>Your code is correct but. A few improvements which you can make in your code:</p> <pre><code>height = input(&quot;enter your heig...
python|calculator
3
9,542
46,903,963
Python, numpy, piecewise answer gets rounded
<p>I have a question with regards to the outputs of numpy.piecewise.</p> <p>my code:</p> <pre><code>e=110 f=np.piecewise(e,[e&lt;120,e&gt;=120],[1/4,1]) print(f) </code></pre> <p>As a result i get: 0 and not the desired 0.25</p> <p>Can someone explain me why piecewise seems to be rounding my answer? Is there a way ...
<p>From the <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.piecewise.html" rel="nofollow noreferrer"><code>np.piecewise</code> docs</a>:</p> <blockquote> <p>The output is the same shape and type as x</p> </blockquote> <p>Integer in, integer out. If you want a floating-point output, you n...
python|numpy|piecewise
0
9,543
29,887,159
Python/tkinter: elapsed time in label/updating a label constantly?
<p>So im trying to write code to display the playback time of an audio file, by constantly looping and updating the label text from pyglet's elapsed time method. I can get the time to appear, but it does not update. was wondering how to update the label on the GUI to show the elapsed time? The loop for time is near the...
<p>Instead of updating it with a loop, we're going to have that function tell the root <code>tkinter</code> instance (<code>app</code>) to call it again after a certain amount of time, with the <code>after()</code> method. In this way, it'll run indefinitely with the specified frequency. This is similar to recursion, b...
python|loops|audio|tkinter|label
1
9,544
65,531,067
Django: NameError: Slug is not defined
<p>Can anyone advise on how to query the `total_likes of a post to be shown in my HTML, I tried, but was given this error:</p> <pre><code>NameError: Slug is not defined </code></pre> <p>An expert has suggested me to use generic class views which i am not familiar with, is there any other ways i can query the correct po...
<p>I will give you a solution that uses class based views, to show you how clearer they are (no boilerplate code)</p> <p><code>urls.py</code></p> <pre class="lang-py prettyprint-override"><code>from .views import LikeView, PostDetailView, HomeFeedView urlpatterns = [ ... path(&quot;home/&quot;, HomeFeedView.as...
python|django
0
9,545
72,363,664
Embedding Python to C++ Segmentation fault
<p>I am trying to track the execution of python scripts with C++ Threads (If anyone knows a better approach, feel free to mention it)</p> <p>This is the code I have so far.</p> <pre><code>#define PY_SSIZE_T_CLEAN #include &lt;/usr/include/python3.8/Python.h&gt; #include &lt;iostream&gt; #include &lt;thread&gt; void la...
<p>After testing and debugging the program for about 20 minutes I found that the <strong>problem is</strong> caused because in your example you've created the second <code>std::thread</code> named <code>second</code> before calling <code>join()</code> on the <code>first</code> thread.</p> <p>Thus, to <strong>solve</str...
python|c++|c|multithreading
1
9,546
36,806,745
Data transformation for machine learning
<p>I have dataset with SKU IDs and their counts, i need to feed this data into a machine learning algorithm, in a way that SKU IDs become columns and COUNTs are at the intersection of transaction id and SKU ID. Can anyone suggest how to achieve this transformation.</p> <p>CURRENT DATA</p> <pre><code>TransID SKUID...
<p>In <code>R</code>, we can use either <code>xtabs</code></p> <pre><code>xtabs(COUNT~., df1) # SKUID #TransID 31 32 33 34 # 1 1 2 1 0 # 2 2 0 0 -1 </code></pre> <p>Or <code>dcast</code></p> <pre><code>library(reshape2) dcast(df1, TransID~SKUID, value.var="COUNT", fill=0) # TransID 31 32 33 ...
r|python-2.7|numpy|pandas|graphlab
4
9,547
48,733,108
How to configure 4 spaces per tab in komodo for python?
<p>I am using komodo-edit (Komodo Edit, version 8.5.0, build 13638, platform macosx) to write python code. Whenever I press the 'tab' key I want the editor to insert 4 spaces. The preference looks like this:</p> <p><a href="https://i.stack.imgur.com/beyae.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur....
<p>Install komodo-edit 11. Seems to be a bug in version 8.5</p>
python|komodo
0
9,548
19,992,559
Decimals in python 3
<p>So i've been trying to code a section in my cash-register class. Im trying to make it so that it keeps track of the total price as an integer. so for example 18.66 would be 1866. But i still want it to be considered as 18.66 if that makes sense. this is so that it avoids the accumulation of roundoff errors. But i do...
<p>You should keep the data as is.</p> <p>You can achieve what you want by mean of formatting. If i were you i will add a new function like this:</p> <pre><code>def getTotalAsString(self): return "%d" % (self._totalPrice * 100) </code></pre> <p>This approach will give you more flexibility in the future</p>
python|python-3.x
0
9,549
66,809,707
Invalid syntax using regular expression in python 3.6.8
<p>regular expression working in mac but giving error in linux. Linux has all python package but version is different</p> <p>Mac python version = 3.7.9</p> <p>linux python version = 3.6.8</p> <pre><code>line 99 pattern = re.compile(rb&quot;neighbor \d+\.\d+\.\d+\.\d+&quot;) ...
<p>As mentioned in existing comments, it seems likely you are using the wrong version of python</p> <pre><code>$ python2 -c 'rb&quot;&quot;' File &quot;&lt;string&gt;&quot;, line 1 rb&quot;&quot; ^ SyntaxError: invalid syntax $ </code></pre> <pre><code>$ python3 -c 'rb&quot;&quot;' $ </code></pre> <p>What ...
python|python-3.x
0
9,550
66,894,046
Inserting separate dictionary into list of dictionaries
<p>I'm working with an api that returns json formatted as a list (of a list) of dictionaries similar to this:</p> <pre><code>list_of_dictionaries = [ [{'key1':0},{'key2':1}], [{'key1':2},{'key2':3}], [{'key1':4},{'key2':5}], [{'key1':6},{'key2':7}], [{'key1':8},{'key2':9}] ] </code></pre> <p>I also ...
<p>Use <code>zip()</code> to process the two lists together.</p> <pre><code>for coord, d_list in zip(coordinates_list, list_of_dictionaries): d_list.append({'x': coord.x, 'y': coord.y}) </code></pre>
python|list|dictionary
1
9,551
69,482,458
Am I mislabeling my data in my neural network?
<p>I'm working on an implementation of EfficientNet in Tensorflow. My model is overfitting and predicting all three classes as just a single class. My training and validation accuracy is in the 99% after a few epochs and my loss is &lt;0.5. I have 32,000 images between the three classes (12, 8, 12).</p> <p>My hypothesi...
<p>Well first off you are writing more code than you need to. In train_ds and val_ds you did not specify the parameter label_mode. By default it is set to 'int'. Which means your labels will be integers. This is fine if your compile your model using loss=tf.keras.losses.SparseCategoricalCrossentropy. If you had set</p>...
python|tensorflow|deep-learning|neural-network|multilabel-classification
1
9,552
51,348,980
Python virtual environment suddenly lost all libraries and modules
<p>I was running Jupyter Notebook in my Python venv.</p> <p>I made a new venv in a completely unrelated folder, but figured I don't need it. I move back to my original venv folder, ran my notebook files, just to find that <strong>it lost Python3 AND ALL the modules and libraries</strong> like numpy, matplotlib, beauti...
<p>When you use an environment, you only create that once (third line) and then you need to execute <code>source bin/activate</code> each time inside the directory. The problem you describe maybe is related with recreate the environment. </p>
python|jupyter-notebook|python-venv
0
9,553
51,217,030
Python can't find Pygame module on Mac
<p>Using home-brew I have installed pygame as homebrew says this </p> <blockquote> <p>"Requirement already satisfied: pygame in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages (1.9.1release)"</p> </blockquote> <p>but when I run idle3 and import pygame, python says this</p> <pre><...
<p>Add <code>/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages</code> to your system path so Python knows to search here for libraries.</p> <p>Here's a tutorial <a href="https://www.architectryan.com/2012/10/02/add-to-the-path-on-mac-os-x-mountain-lion/#.Uydjga1dXDg" rel="nofollow noreferre...
python|macos|pygame
2
9,554
51,480,882
Using Pathlib to search for a matching file?
<p>I have the following method:</p> <pre><code>def file_search(self, fundCodes, type): funds_string = '_'.join(sorted(fundCodes)) files = set(os.listdir(self.unmappedDir)) file_match = 'citco_unmapped_{type}_{funds}_{start}_{end}.csv'.format(type=type, funds=funds_string, start=self.startDate, end=self.end...
<p>I ended up re-writing it as so:</p> <pre><code>def file_search(self, fundCodes, dataType): funds_string = '_'.join(sorted(fundCodes)) file_match = 'citco_unmapped_{type}_{funds}_{start}_{end}.csv'.format(type=dataType, funds=funds_string, ...
python
0
9,555
70,688,451
Why do I get an old data set in one case after a GET request, and an up-to-date data set in the other
<p>I make a POST request, enter the data into the table, but after that I do a Get and get the old data in this case</p> <pre><code>def get_queryset(self): transaction.commit() if self.action not in ['retrieve', 'list', 'create', 'selector']: res = self.queryset.filter(is_editable=True) else: ...
<p>QuerySets cache the value. That means that if you directly return <code>self.queryset</code>, it will run the query <em>once</em>, and store the values in memory.</p> <p>If you add <code>.all()</code>, you make a <em>copy</em> of the <code>QuerySet</code> <em>without</em> the cache, and you thus force making a new q...
python|django
1
9,556
55,619,581
Getting total memory and cpu usage for one python instance
<p>I'm using keras to make and test different types of Neural Nets and need data to compare them. I need data on the cpu and memory used during the training and testing. This is in python and as I looked around I found lot of suggestions for psutil. However everything I see seems to grab the current usage. </p> <p>Wha...
<p>psutil is a good recommendation to collect that type of information. If you incorporate this code into your existing keras code, you can collect information about the cpu usage of your process at the time the cpu_times() method is called</p> <pre><code>import psutil process = psutil.Process() print(process.cpu_tim...
python|tensorflow|keras|psutil
1
9,557
50,210,177
In SQLite3, how to select with match to any item of a list?
<p>I use 'sqlite3' to access a database in a Python program. I have a list of keywords, for example, </p> <pre><code>fruit=['banana','apple','orange'] #the total number is 50. </code></pre> <p>If I have following table:</p> <pre><code>Col 1 | Col 2 'this is a desk' | something el...
<p>Use the <strong>OR</strong> operator for selecting rows with different values.</p> <pre><code>SELECT "Col 1" FROM table WHERE "Col 1" LIKE '%banana%' OR "Col 1" LIKE '%apple%' OR "Col 1" LIKE '%orange%' </code></pre>
python-3.x|sqlite
0
9,558
53,030,737
Alias an sqlalchemy.text object
<p>Im trying to allow users to input query in the UI and then add it to the FROM clause of my sqlalchemy. After seeing the <code>from_self</code> function on the query object in the <a href="https://docs.sqlalchemy.org/en/latest/orm/query.html" rel="nofollow noreferrer">docs</a>, I tried:</p> <pre><code>Query.from_sta...
<p>After a lot of hassling, found a way to do so like this:</p> <pre><code>alias(TextAsFrom(text("SELECT * FROM test_table"), columns), name='some_name') </code></pre> <p>This is possible due to the TextAsFrom that can be found deep in the docs <a href="https://docs.sqlalchemy.org/en/latest/core/selectable.html?highl...
python|sql|sqlalchemy
2
9,559
53,086,026
pandas to_datetime couldn't parse string into dates and return strings
<p>I have a <code>Series</code> <code>s</code> as</p> <pre><code>10241715000 201709060 11202017 112017 111617 102417 110217 1122018 </code></pre> <p>I tried the following code to convert <code>s</code> into <code>datetime</code>;</p> <pre><code>pd.to_datetime(s.str[:7], format='%-m%d%Y',...
<p>It should be -7 not 7 for <code>str</code> slice </p> <pre><code>pd.to_datetime(s.astype(str).str[-7:], format='%m%d%Y', errors='coerce') Out[189]: 0 NaT 1 NaT 2 2017-01-20 3 2017-01-01 4 NaT 5 NaT 6 NaT 7 2018-11-02 Name: a, dtype: datetime64[ns] </code></pre> <...
python-3.x|pandas|strftime|string-to-datetime
2
9,560
71,810,031
Password reset django-allauth and django-rest-auth
<p>I cannot wrap my head around this problem. Read a lot of solutions but cannot seem to find the correct combination that works for me.</p> <p>I want to initiate a users password reset flow from within my (android/iOS) app. I think I need <code>django-rest-auth</code> for this to expose an API endpoint something like ...
<p><strong>UPDATE:</strong> I just saw django-allauth is no longer maintained and that you should switch to: dj-rest-auth. Now the process starts all over again...</p> <p>Ok, the following works, posting for reference because I have lost an awful lot of time on this.</p> <p>Pipfile:</p> <pre><code>[packages] django = &...
python|django|django-allauth|django-rest-auth
0
9,561
68,621,692
How to get custom user status from discord
<p>I'm trying to get custom user status from discord gateway but it only prints one status from one user, I want all of them.</p> <pre><code>payload = { 'op': 2, &quot;d&quot;: { &quot;token&quot;: TOKEN, &quot;intents&quot;: 513, &quot;properties&quot;: { &quot;$os&quot;: &q...
<p>You could start using discord.py documentation.</p> <p>I would do something like this:</p> <pre><code>async def customstatus(): guild = client.get_guild(* GUILD ID *) for member in guild.members: # Do some stuff </code></pre> <p>More information regarding CustomActivity :</p> <p><a href="htt...
python|discord
0
9,562
61,809,719
Python3 Print on Same Line - Numbers in 7-Segment-Device Format
<p>I'm new to Python and having difficulty getting the output to print on one line. </p> <p>This is pertaining to the online Python class Learning Python Essentials Lab 5.1.10.6 and printing to a 7-segment-device. If you are unfamiliar with a 7-segment-device, see <a href="https://en.wikipedia.org/wiki/Seven-segment_...
<p>Your problem is that you are printing each number before the next, but you need to print each <em>row</em> before the next. As a simplified example:</p> <pre><code>dict1 = { '0':('###','# #','# #','# #','###'), '1':(' ##','###',' ##',' ##',' ##'), '2':('###',' #','###','# ','###'), '3':('###',' #...
python|python-3.x|printing|seven-segment-display
1
9,563
67,426,438
Pandas - How can I group by one numeric column and filter rows from each group by the median of each group?
<p>I have a dataset consisting of one ID, one categorical variable &quot;A&quot; and one numerical variable &quot;B&quot;.<br /> I want to group by &quot;A&quot; and filter the rows <strong>from each group</strong> to get only the rows that are avobe or equal to the median of &quot;B&quot; (the median should be calcula...
<pre><code>out = df[df.groupby(&quot;A&quot;)[&quot;B&quot;].transform(lambda x: x &gt;= x.median())] print(out) </code></pre> <p>Prints:</p> <pre class="lang-none prettyprint-override"><code> ID A B 0 1 Category 1 0.5 3 4 Category 1 0.6 4 5 Category 2 0.4 </code></pre>
python|pandas|pandas-groupby|data-science
4
9,564
67,243,869
Sort with respect to multi-level key where the order is different for each level
<p>I have a collection of items with multiple attributes which are represented by tuples:</p> <pre class="lang-py prettyprint-override"><code>items = [(a11, a12, ..., a1N), (a21, a22, ..., a2N), ...] </code></pre> <p>Now I want to sort these items, however the order may vary for each level (e.g. <code>aX1</code> ascend...
<p>Assuming all items in the tuple are string characters, you can encode them into hex string where a character <code>c</code> will be set to be <code>format(ord(c), 'x')</code> if <code>reverse</code> is not <code>True</code> and <code>format(127 - order(c), 'x')</code> if <code>reverse</code> is <code>True</code>. No...
python|python-3.x|string|sorting
1
9,565
70,139,937
How to randomly fill X of rows in a pandas dataframe?
<p>How to randomly fill the rows of a dataframe by setting a number? For example:</p> <p>Given a pandas dataframe with 10 elements:</p> <pre><code>col1 a b c d e f g h i j </code></pre> <p>How to fill randomly with <code>1</code> and the rest with <code>0</code> in the rows of another column. For example, I would like ...
<p>This should do the trick. For each row, set the col2 to a random int between 0 and 1</p> <pre><code>df[&quot;col2&quot;] = df.apply(lambda x: randint(0,1), axis=1) </code></pre> <p>If you need n random values to exist and the rest to be set, you can try this:</p> <pre><code>n = 4 df[&quot;col2&quot;] = 0 df_to_updat...
python|pandas|dataframe
1
9,566
63,574,330
How do I keep elements in a frame justified to the right while keeping the entire frame coloured, regardless of the size of the window?
<p>I'm new to tkinter so I'm a little lost in terms of grid layout. What I'm trying to do is have a logo sit in the bottom right corner of the window, and always be in that position no matter how big the window is. I have managed to position the logo no problem, but when I justify to the right, the frame becomes white ...
<p>First you need to change <code>btmFrame.grid(row=2, sticky='e')</code> to <code>btmFrame.grid(row=2, sticky='ew')</code>, so that the frame fills all the space horizontally.</p> <p>Then add <code>btmFrame.columnconfigure(0, weight=1)</code> to push the <code>powered</code> and <code>sLogoLabel</code> to the right of...
python|tkinter
1
9,567
61,155,823
From minidom/getElementsByTagName to lxml/xpath
<p>I'm trying to parse a lot of different xml/gpx files to get lat/lon pairs that are an attribute of the node trkpt. I have a working minidom version, but i want to try and have a similar version using lxml and xpath to check if it is faster.</p> <p>Here is sample xml:</p> <pre><code>xml = '''&lt;gpx xmlns:xsi="http...
<p>Use <a href="https://lxml.de/tutorial.html#elements-carry-attributes-as-a-dict" rel="nofollow noreferrer"><code>elem.get()</code></a> to get the value of an attribute.</p> <pre><code>lxtree = etree.fromstring(xml) trkpt = lxtree.xpath('dft:trk/dft:trkseg/dft:trkpt', namespaces={'dft': 'http://www.topografix.com/GPX...
python|xpath|lxml|minidom
0
9,568
69,287,385
How do I place text in a button in multiple columns
<p>I'm working on inserting a button that will span 6 columns with the labels being self-generating, but I want to split these labels into columns. In my head the code would look like this:</p> <pre class="lang-py prettyprint-override"><code>from tkinter import * root = Tk() Testbtn = Button(root, text=&quot;Column0&q...
<p>You can't split the text of a single button across multiple columns. You can add multiple labels inside the button, but then the button will not work like a proper button anymore, and the text won't align with columns outside of the button.</p>
python-3.x|tkinter|button
0
9,569
62,898,236
Documenting member functions exclusively starting with "test_"
<p><strong>How can I document my tests, only my tests?</strong></p> <p>I document my unittest with Sphinx.</p> <p>My setup is as followed:</p> <pre><code>class MyTestWrapper1(unittest.Testcase) def test_general_setup() class MyTestWrapper2(MyTestWrapper1) def test_general_tear_down() class TheUsedTest1(MyTest...
<p>I haven't tested this, but you could try to check for the type of the object to skip:</p> <pre class="lang-py prettyprint-override"><code>def maybe_skip_member(app, what, name: str, obj, skip, options): import inspect if inspect.isclass(obj) or name.startswith('test_'): return False return True <...
python|python-sphinx|python-unittest
0
9,570
59,788,022
check if string has .pdf extension
<p>I am very new to scraping. I have 2 problems. first one is that I need to scrap a particular section of the website which contains anchor tags. I need to get the anchor tags pdf links only along with their titles but unfortunately, anchor tags have normal links also.this is my first problem</p> <p>the second proble...
<p>Some titles in your case have <code>\n</code> in body - you should try this:</p> <pre><code>title = link.text.strip().replace('\n', '') </code></pre> <p>So your final code with <code>.pdf</code> filtering will look like this:</p> <pre><code>section = soup.find("section", {"class": "news_content"}) for link in se...
python|web-scraping|beautifulsoup
1
9,571
60,240,552
Pandas DataFrame to Dict with (Row, Column) tuple as keys and int value at those location as values
<p>I am trying to make the following DataFrame</p> <pre><code> A B C D E A 0 7324 11765 6937 10424 B 7324 0 17791 3532 5902 C 11765 17791 0 17184 20608 D 6937 3532 17184 0 6550 E 10424 5902 20608 6550 0 </code></pre> <p>to look something...
<p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html" rel="nofollow noreferrer"><code>stack</code></a> and then convert to dict:</p> <pre><code>df.stack().to_dict() </code></pre> <hr> <pre><code>{('A', 'A'): 0, ('A', 'B'): 7324, ('A', 'C'): 11765, ('A', 'D'): 6937, ('...
pandas|dataframe|tuples
1
9,572
67,743,868
Convert multiple csv to another csv format
<p>I am trying to convert my old CSV files to another format and a new name (<code>_new.csv</code>). All files are in the folder with the date stamp. e.g <code>Filename_05_08_2021.csv</code>. Almost I have 63 files from today date to back. The problem is I have to provide each file name one by one while call function. ...
<p>Just iterate within the directory. You can use glob:</p> <pre><code>import glob def new_csv(file_path): c = csv.reader(open(file_path)) c_list = [] c_list.extend(c) out_csv = open(file_path.replace('.csv','_new.csv'), &quot;w&quot;) for line in c_list: if len(line) == 10: out_...
python|csv
1
9,573
67,659,218
VSCodium not importing modules in Python
<p>I wanted to make a voice assistant importing SpeechRecognition on Python; I installed PyAudio and SpeechRecognition with the following commands: <code>pip install PyAudio</code> <code>pip install SpeechRecognition</code> on Linux, but when I try to import SpeechRecognition with <code>import speech_recognition as sr<...
<p>I think its main reason is on Linux pip is for python 2 while pip3 is for python 3. If you are using py3 using pip3 may help. Other reasons may include a virtual environment you are on.If vscodium does not automatically activate it or whatever extension you are using do not run in the virtual environment it may not ...
python|linux|visual-studio-code
0
9,574
42,920,741
[Python][Selenium]Unable to use webdriver with Chrome
<p>I'm a beginner in Python and Selenium, and I dont know what is the error in my code or environment...</p> <pre><code># encoding: utf-8 import time from selenium import webdriver from bs4 import BeautifulSoup driver = webdriver.Chrome(executable_path=r'C:/Python27/Scripts/chromedriver') time.sleep(3) driver.get('h...
<p>Try to download <a href="https://chromedriver.storage.googleapis.com/index.html?path=2.28/" rel="nofollow noreferrer">latest version of <code>chromedriver</code></a> and put it to <code>C:/Python27/Scripts/</code> instead of outdated one</p>
python|selenium
1
9,575
72,195,219
pyplot.scatter() plots points but has no meaningful axes?
<p>I am trying to make a simple scatterplot with Matplotlib. I am passing an Numpy array for x and another one for y:</p> <pre class="lang-py prettyprint-override"><code>df = df.to_numpy() # this was originally a pandas DataFrame print(df) plt.scatter(df[:,1], df[:,2]) plt.show() </code></pre> <p>The print outputs:...
<p>As you can see from your prints, <code>df</code> contains only strings. <code>matplotlib</code> has no idea what to do with them.</p> <p>Change:</p> <pre><code>plt.scatter(df[:,1], df[:,2]) </code></pre> <p>With:</p> <pre><code>plt.scatter(df[:,1].astype(float), df[:,2].astype(float)) </code></pre> <p>What it does i...
python|matplotlib
0
9,576
50,352,091
XMLHttpRequest endpoint blocked while signing S3 request because no HTTPS, eventhough everything is on HTTPS
<p>I am trying to sign a huge video upload, because I want to upload it directly to S3. It works on localhost, but on my live site it fails to sign the request because of:</p> <pre><code>Mixed Content: The page at 'https://www.example.com/profile' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoin...
<p>After many hours of researching I decided to rebuild this function and use AJAX get, which I am more familiar with. I also changed the way I pass/recieve the query string arguments to the best way, which is actually used in flask/python.</p> <pre><code>function getSignedRequest(file) { $.ajax({ url : "/sign_s3/...
javascript|python|ssl|xmlhttprequest
0
9,577
56,195,878
How to select a certain element with beautiful soup
<p>I want to write some code that grabs a solution from slader (just screwing around with the library). Trying to use the <code>.find()</code> method to a select a certain div with a certain class, but I end up just getting None as a result. This is my first asked question on stack overflow, please comment if you need ...
<p>You have to do this <code>solution = soup.find("div", {'class': 'solution-content'})</code>. However incase of the url that you wanted to fetch data from, the div is loaded lazily. Meaning it is loaded after some time via ajax. So when you fetch the resp the content is not available. It is better if you could do som...
python|beautifulsoup
0
9,578
18,534,255
Python unicode error
<p>Can someone explain me why in example below, <code>print a</code> raises exception, while <code>a.__str__()</code> doesn't?</p> <pre><code>&gt;&gt;&gt; class A: ... def __init__(self): ... self.t1 = "čakovec".decode("utf-8") ... self.t2 = "tg" ... def __str__(self): ... return self.t1 + self.t2 ... ...
<p>In Python 2 <code>str</code> must return an ASCII string. When you call <code>__str__</code> directly you're skipping the step of Python converting the output of <code>__str__</code> to an ASCII string (you could in fact return whatever you want from <code>__str__</code>, but you shouldn't). <code>__str__</code> sho...
python|python-unicode
6
9,579
18,531,480
pythonic equivalent this sed command
<p>I have this awk/sed command </p> <pre><code>awk '{full=full$0}END{print full;}' initial.xml | sed 's|&lt;/Product&gt;|&lt;/Product&gt;\ |g' &gt; final.xml </code></pre> <p>to break an XML doc containing large number of tags such that the new file will have all contents of the product node in a single line</p> <...
<p>Something like this?</p> <pre><code>from __future__ import print_function import fileinput for line in fileinput.input('initial.xml'): print(line.rstrip('\n').replace('&lt;/Product&gt;','&lt;/Product&gt;\n'),end='') </code></pre> <p>I'm using the <code>print</code> function because the default <code>print</cod...
python|sed
1
9,580
54,101,593
Conditional Batch Normalization in Keras
<p>I'm trying to implement Conditional Batch Normalization in Keras. I assumed that I will have to create a custom layer, hence, I extended from the <a href="https://github.com/keras-team/keras/blob/master/keras/layers/normalization.py" rel="nofollow noreferrer">Normalization</a> source code from Keras team. </p> <p>T...
<p>I would use <a href="https://www.tensorflow.org/api_docs/python/tf/case" rel="nofollow noreferrer">tf.case</a> to express your conditional statements: </p> <pre class="lang-py prettyprint-override"><code>normed_training, mean, variance = \ tf.case({ c1: lambda: K.normalize_batch_in_train...
python|tensorflow|machine-learning|keras|keras-layer
2
9,581
56,916,504
Adanet running out of memory
<p>I tried training an AutoEnsembleEstimator with two DNNEstimators (with hidden units of 1000,500, 100) on a dataset with around 1850 features (after feature engineering), and I kept running out of memory (even on larger 400G+ high-mem gcp vms). </p> <p>I'm using the above for binary classification. Initially I had t...
<p>Three hypotheses:</p> <ol> <li><p>You might have too many DNNs in your ensemble, which can happen if <code>max_iteration_steps</code> is too small and <code>max_iterations</code> is not set (both of those are constructor arguments to <code>AutoEnsembleEstimator</code>). If you want to train each DNN for <code>N</co...
python|tensorflow|tensorflow-estimator|adanet
1
9,582
21,285,948
Using certain attributes of an object to make other objects in a different class
<p>For a program that creates a timetable for a doctor(specialist) I want to use certain attributes of an object created by a different class to be used in the class that makes the timetable for the doctor.</p> <pre><code>class makePatient(object): def __init__(self,name,room): self.name = name self.room...
<p>I think another approach would be better; you can put the <em>whole <code>makePatient</code> object</em> into the timetable for the specialist:</p> <pre><code>specialist1 = makeSpecialist("Dr. John", "Hematology", [patient1]) </code></pre> <p>Now you can access the names and other attributes of the patients in a s...
python|class|variables|object
2
9,583
21,060,995
Submatrix in scipy
<p>I have a sparse matrix A and a column vector a,</p> <pre><code>In[1]: A Out[1]: &lt;256x256 sparse matrix of type '&lt;type 'numpy.float64'&gt;' with 512 stored elements (blocksize = 2x2) in Block Sparse Row format&gt; In[2]: len(a) Out[2]: 70 </code></pre> <p>I would to write a submatrix. The code I wrote for th...
<p>csr matrices have fast row slicing; csc matrices have fast column slicing. Conversions between most sparse types are well optimized, so I would suggest trying to use the appropriate type for the kind of slice to be performed.</p> <p>Sub = A.tocsr()[a,:].tocsc()[:,a]</p>
python|scipy|sparse-array|submatrix
1
9,584
53,608,653
How to select all but the 3 last columns of a dataframe in Python
<p>I want to select all but the 3 last columns of my dataframe.</p> <p>I tried :</p> <pre><code>df.loc[:,-3] </code></pre> <p>But it does not work</p> <p>Edit : title</p>
<p>Select everything <strong>EXCEPT the last 3 columns</strong>, do this using <code>iloc</code>: </p> <pre><code>In [1639]: df Out[1639]: a b c d e 0 1 3 2 2 2 1 2 4 1 1 1 In [1640]: df.iloc[:,:-3] Out[1640]: a b 0 1 3 1 2 4 </code></pre>
python|pandas|dataframe
38
9,585
46,029,657
forking once and getting different pid values
<pre><code>import os, time def counting(count): for i in range(count): time.sleep(1) print("[{}] =&gt; {}".format(os.getpid(), i)) for i in range(5): pid = os.fork() if pid != 0: print("Process {} parent".format(pid)) else: counting(5) os._exit(0) print("e...
<p>The process ID <em>is</em> the same for any individual process, it's just that your output is mixed up because those processes are running concurrently.</p> <p>You'll see this if you count the number of each process/sequence pair. You'll find there are five distinct process IDs and that <em>each</em> of them has al...
python|python-3.x
2
9,586
55,101,223
Replace value in dictionary with nested values
<p>I have two dictionaries with same keys and nested lists as values:</p> <pre><code>dict_1 = {'PickMeterEquipment': [['value', 'PB:PRICELIST', 'list', 'LeaseAccountingContracts'],['value', 'PICK_SKU10', 'propval', '._sku']],'GenericPickRule': [['propval', '_amEntitled', 'literal', '0'], ['propval', '_sku', 'value',...
<p>Try this:</p> <pre><code>dict_1 = {'PickMeterEquipment': [['value', 'PB:PRICELIST', 'list', 'LeaseAccountingContracts'],['value', 'PICK_SKU10', 'propval', '._sku']],'GenericPickRule': [['propval', '_amEntitled', 'literal', '0'], ['propval', '_sku', 'value', 'PICK_SKU1'], ['propval', '_sku', 'value', 'PICK_SKU2']]...
python|python-3.x
0
9,587
52,356,185
How to import matplotlib.pyplot in Ubuntu
<p>I am using <code>MEEP</code> by Python3 in Ubuntu. After activate <code>MEEEP</code>, once I <code>import matplotlib.pyplot as plt</code>. Then it shows error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/tim/anaconda3/envs/meep/lib/python3.6/site...
<p>I found installing python3-pyqt5 fixed the issue:</p> <pre><code>apt-get install python3-pyqt5 </code></pre>
ubuntu|python-3.6|meep
0
9,588
37,431,469
Multiline strings in Jupyter notebook
<p>How do I split thE <code>sql</code> string <code>x</code>, in the following snippet, onto several lines - this is in a <code>Jupyter</code> notebook?</p> <pre><code>import pandas as pd import pyodbc as p def s(sqlString): cnxn = p.connect(driver='{SQL Server}', server='SERVERNAME', database='OURDBNAME', uid='m...
<p>Use Python's <a href="https://docs.python.org/3.2/tutorial/introduction.html#strings" rel="noreferrer">triple quote notation</a> to define a multi-line string:</p> <pre class="lang-py prettyprint-override"><code>x = """\ Select * FROM OURDBNAME.dbo.vw_DimFoo """ print(x) </code></pre> <p>results in</p> <pre><co...
python-3.x|jupyter
20
9,589
38,514,984
JSON formatted string to pandas dataframe
<p>OK, I have been beating my head against the wall with this one all afternoon. I know that there are many similar posts, but I keep getting errors and am probably making a stupid mistake. </p> <p>I am using the <code>apyori</code> package found here to do some transaction basket analysis: <a href="https://pypi.pytho...
<p>I would suggest reading up on StackOverflow's guidelines on producing a <a href="https://stackoverflow.com/help/mcve">Minimal, Complete, and Verifiable example</a>. Also, statements like "I keep getting errors" are not very helpful. That said, I took a look at your code and the source code for this <code>apyori</co...
python|json|apriori
2
9,590
40,390,068
Python pandas: Find values in one column that fall within range in another column
<p>I have a pandas dataframe that contains payroll information from the years 2013 through 2016. Each row describes the amount of money the employee earned in a single year. It looks like this:</p> <p><strong>Name, Year, Amount</strong></p> <p>"Bill Smith", "2014", "$20,000"</p> <p>"John Jones", "2014", "$10,000"</p...
<p>This should work:</p> <pre><code>workers = df[df.Year&lt;2015].Name.unique() mew_workers_data = df[~df.Name.isin(workers)] </code></pre>
python|pandas
0
9,591
44,282,757
How do I get the value of an entry and enter it in Ssol.txt?
<pre><code>from tkinter import * from tkinter import ttk win = Tk() win.title("hello") win.geometry('510x50+200+100') Block = IntVar() def x(): k = open("Ssol.txt", 'w') Entry(win, width=5, textvariable=Block).grid(column=1, row=0,sticky=(N,W,E)) ttk.Button(win, text="실행", command=x).grid(column=0, row=1,sticky=...
<p>You need to use <code>.get()</code> to access the value of your <code>IntVar</code>:</p> <pre><code>from tkinter import * win = Tk() Block = IntVar() def Block_to_file(): contents = str(Block.get()) with open("Ssol.txt", 'w') as f: f.write(contents) Entry(win, width=15, textvariable=Block).grid(c...
python|python-3.x|tkinter|pygame
1
9,592
32,751,512
Renaming columns in pandas dataframe using regular expressions
<pre><code> Y2010 Y2011 Y2012 Y2013 test 0 86574 77806 93476 99626 2 1 60954 67873 65135 64418 4 2 156 575 280 330 6 3 1435 1360 1406 1956 7 4 3818 7700 6900 5500 8 </code></pre> <p>Is there a way to rename the columns of this dataframe from Y2010... to 2010.. i.e. removi...
<p>I'd use map:</p> <pre><code>In [11]: df.columns.map(lambda x: int(x[1:])) Out[11]: array([2010, 2011, 2012, 2013]) In [12]: df.columns = df.columns.map(lambda x: int(x[1:])) In [13]: df Out[13]: 2010 2011 2012 2013 0 86574 77806 93476 99626 1 60954 67873 65135 64418 2 156 575 280 330...
python|pandas
13
9,593
32,759,369
How can I customize the format of Python output?
<p>I know basically nothing about <code>python</code> (I did know about it before but never took the time to try it out). I've started using <code>python</code> because I'm doing an A level course in computer science.</p> <p>I wanted to know how to center align the output ?</p> <p>What I've done to "center" align is:...
<p>The method center() returns centered in a string of length width. Padding is done using the specified fillchar. Default filler is a space.</p> <p><strong>SYNTAX</strong></p> <pre><code>str.center(width[, fillchar]) </code></pre> <p>You could refer to the links below.</p> <p><a href="http://www.tutorialspoint.com...
python
1
9,594
51,183,430
GitHub : API name/identity inside webhook payload?
<p>I'm writing a Github API client and a webhook.</p> <p>Is there any way to distinguish if an event (i.e assignment, issue open, etc etc) is trigered by API or by user directly (i.e via git's web ui) ?</p> <p>I read what payload github will send on it's webhook call, but could not find one.</p> <p>sincerely -bino-<...
<p>I'm not sure what it looks on the server side, but at least when using the UI, the POST payload seems to be form-data, and with API it is JSON-formatted.</p> <p>From my tests with UI:</p> <pre><code>... Content-Disposition: form-data; name="issue[user_assignee_ids][]" 28 ------ </code></pre> <p>and from GitHub A...
python|python-3.x|github|webhooks
0
9,595
73,049,456
Apply the nested shape of one list on another flat list
<p>I have two lists:</p> <p>A: <code>[[0, 1], [2, [3]], 4]</code></p> <p>B: <code>[5, 6, 7, 8, 9]</code></p> <p>I wish list B could have the same shape with list A: <code>[5, 6, 7, 8, 9]</code> =&gt; <code>[[5, 6], [7, [8]], 9]</code></p> <p>So list A and list B have the same dimension/shape:</p> <p>A: <code>[[0, 1], [...
<p>A one-line variant of @Mozway's idea, using a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="noreferrer">list comprehension</a>:</p> <pre><code>A = [[0, 1], [2, [3]], 4] B = [5, 6, 7, 8, 9] def un_flatten(t, d): return [un_flatten(e, d) if isinstance(e, list) else nex...
python|arrays|list|algorithm|nested
6
9,596
55,680,066
Why tkinter canvas xview_moveto() does not work properly?
<p>I'm trying to make movement of the canvas automatic, i.e. moving plot along with charts drawn on the canvas, for that I'm using xview_moveto() function, but for some reason it only moves canvas 1 time, the second time view returns to initial view, do not know why, could some one help to understand?</p> <p>here is p...
<p>The method <code>xview_moveto</code> takes a fraction between zero and one. Anything larger than one will be treated as one. From the canonical tcl/tk documentation:</p> <blockquote> <p>Adjusts the view in the window so that fraction of the total width of the canvas is off-screen to the left. Fraction must be a f...
python|tkinter
0
9,597
49,802,727
sum occurrences of a string in pandas dataframe
<p>I have to count and sum totals over a dataframe, but with a condition:</p> <pre><code>fruit days_old apple 4 apple 5 orange 1 orange 5 </code></pre> <p>I have to count with the condition that a fruit is over 3 days old. So the output I need is</p> <p>2 apples and 1 orange</p> <p>I thought I would have to use an ...
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow noreferrer"><code>value_counts()</code></a>:</p> <pre><code>In [120]: df[df.days_old &gt; 3]['fruit'].value_counts() Out[120]: apple 2 orange 1 Name: fruit, dtype: int64 </code></pre>
python|pandas|dataframe
3
9,598
66,586,702
Python 3.8 key press detection in a while loop, when running SSH on a virtual machine
<p>I have a very simple Python3.8 script that is checking something in a while loop. I'd like to be able to press a key to stop that. The script was running on WSL2 Ubuntu 20.04, it's now running on a Ubuntu 20.04 AWS EC2 instance. I've tried tkinter &amp; pynput, but they don't work for me on virtual Linux while using...
<p>Would using Ctrl+C count? You can detect this event as a KeyboardInterrupt in a try/except.</p> <pre><code>import time try: for i in range(1000): print(f&quot;Processing item {i}&quot;) time.sleep(1) except KeyboardInterrupt: print(f&quot;\nI got to {i} before I was interrupted&quot;) </code...
python|keypress
0
9,599
64,934,859
VS Code Python debugger - parameter values during return
<p>I am using VS code's Python debugger to monitor function returns.</p> <pre><code>Python: 3.7.3 VS Code: 1.51.0 Python Extension: v2020.11.371526539 MACOS: 10.15.7 (19H2) </code></pre> <p>I can inspect the variables before they are returned, and they are correct, but after the return, they assume previously held val...
<p>I had a breakpoint at the return line in the function and a breakpoint at the function call/assignment after the return.</p> <pre><code> def align_bb(self, bbs2) ... # the variables are correct at this point return update_obj, new_obj, stale_obj # I had a breakpoint here update_obj, new_obj, stale_...
python|vscode-debugger
0