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,200
50,786,798
Parse DateTime from Object with Pandas
<p>I would like to parse the year column to datetime.</p> <pre><code> name id nametype recclass mass (g) fall year 0 Aachen 1 Valid L5 21.0 Fell 01/01/1880 12:00:00 AM ... reclat reclong GeoLocation ... 50.77500 6.08333 (50.775000, 6....
<p>I think need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a>:</p> <pre><code>df = pd.DataFrame({'year':['01/01/1880 12:00:00 AM']}) df['year'] = pd.to_datetime(df['year']) print (df) year 0 1880-01-01 </code></pr...
python|pandas|csv
2
9,201
35,104,827
Deploying Flask App using Python 3.5 and Scipy on Heroku
<p>I'm try to use create a flask web app on Heroku that uses python 3.5, scipy and flask.</p> <p>It's well known I suppose that Heroku (still) can't install scipy on its platform. I'm wondering if anyone knows how to push a Flask app to Heroku that can use scipy. I know there are buildpacks that exist (like this one <...
<p><strong>EDIT</strong> I had to make a new buildpack that I will maintain since the one that I had previously was changed and now only supports <em>Python 2.7</em>. Mine supports <em>Python 3</em>.</p> <p>Here's step by step what you should do.</p> <p>1) Add this <a href="https://github.com/arose13/conda-buildpack....
python|heroku|scipy|buildpack
2
9,202
61,243,879
Entity recognition based on context
<p>Is there a way to get the probability of a word belonging to an entity based on context of the sentence. For example (entity : server_name)</p> <p>"I want to check mogo server" And the result would be for example:</p> <blockquote> <p>Mogo : server_name , 0.5688999</p> </blockquote> <p>"Check status of server mo...
<p>Try using <a href="https://sklearn-crfsuite.readthedocs.io/en/latest/api.html#module-sklearn_crfsuite" rel="nofollow noreferrer">CRF</a> classifier. For each of the words in the sentence, you can get the probability scores.</p> <p><a href="https://sklearn-crfsuite.readthedocs.io/en/latest/api.html#module-sklearn_cr...
python|nltk|spacy|rasa-nlu|named-entity-recognition
1
9,203
42,546,221
Bokeh linked brushing with custom index
<p>Say I have a table with columns: id, x1, y1, x2, y2. I want to plot x1 vs y1 and x2 vs y2 side by side, and have linked brushing by id. The Bokeh documentation on linked brushing <a href="http://bokeh.pydata.org/en/latest/docs/user_guide/interaction/linking.html" rel="nofollow noreferrer">here</a> only shows example...
<p>Using the same example, is this not what you want? each plot with a different x and y, but still linked?</p> <pre><code>from bokeh.io import output_file, show from bokeh.layouts import gridplot from bokeh.models import ColumnDataSource from bokeh.plotting import figure output_file("brushing.html") x = list(range(...
python|data-visualization|bokeh
0
9,204
53,900,119
Can't grab all the pdf links within a table from a webpage
<p>I've written a script in python in combination with selenium to scrape different <strong><em><code>pdf</code></em></strong> links generated upon clicking on the different numbers, as in <code>110015710</code>, <code>110015670</code> etc located within a table from a webpage. </p> <p><strong><em><a href="https://www...
<p>when you click the element it will doing XHR to request for pdf links, add delay after every click.</p> <pre><code>for item in wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,"tr.Iec"))): driver.execute_script("arguments[0].click();",item) time.sleep(1) </code></pre>
python|selenium|selenium-webdriver|web-scraping
0
9,205
58,190,500
creating custom legend / guide for alpha level
<p>I'm trying to plot gene expression levels. Essentially for each gene I draw a "pyplot.arrow" and color it by alpha=expression_level. expression levels are normalized to values between 0 and 1. Now I want to create a legend based on the alpha, which shows what level of alpha corresponds to what expression level.</p> ...
<p>Here is how I ended up doing this if anyone in the future has a similar problem.</p> <p>Get the axes you are working on using plt.gca() then create another axes that will be plotted inside it using axes.inset_axes(). instead of using alpha to color different expression values, use a matplotlib colormap like "YlOrRd...
python|matplotlib|plot
0
9,206
44,743,897
Training an InceptionV3 network not working (Tensorflow)
<p>I have installed Tensorflow, bazel both latest version.</p> <p>To train a model from scratch I have to run the following command on this link <a href="https://github.com/tensorflow/models" rel="nofollow noreferrer">https://github.com/tensorflow/models</a>:</p> <pre><code>bazel-bin/inception/imagenet_train --num_gp...
<p>Original answer:</p> <blockquote> <p>You have to build <code>imagenet_train</code> first, what is the output when you run <code>bazel build //inception:imagenet_train</code>?</p> <p><code>bazel-bin</code> is a symbolic link to a directory.</p> </blockquote> <p>Based on your comment below (<code>~/models#</c...
tensorflow|bazel|imagenet
1
9,207
41,154,340
how to fill missing values with a tuple
<p>consider <code>df</code></p> <pre><code>np.random.seed([3,1415]) df = pd.DataFrame(np.random.choice([(1, 2), (3, 4), np.nan], (10, 10))) df </code></pre> <p><a href="https://i.stack.imgur.com/f0jv8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/f0jv8.png" alt="enter image description here"></a></p> <p>...
<p>You can do with <code>.applymap</code>:</p> <pre><code>import numpy as np import pandas as pd np.random.seed([3,1415]) df = pd.DataFrame(np.random.choice([(1, 2), (3, 4), np.nan], (10, 10))) df.applymap(lambda x: (0,0) if x is np.nan else x) </code></pre> <p>This will work for a <code>pd.Series</code> if you us...
python|pandas|numpy
8
9,208
47,103,266
i am trying to create a programme which calculates the tax for a gym membership and there is an error which i can not fix
<pre><code>def tax(): tax == 10 membership = {'social' , 'sport'} membership = input("please enter the type of membership") months = input("please enter number of months overdue") if membership == 'sport': cost = months * 100 * 100/tax print ("the penalty is £",cost) elif member...
<p>You're using tax for both the method name and the tax rate. Python cannot figure out which one you want when you call <code>cost = months * 100 * 100/tax</code>.</p> <pre><code>def calculate_tax(): tax = 10 membership = {'social' , 'sport'} membership = input("please enter the type of membership") ...
python-3.x
2
9,209
64,244,741
Combine for iterators to avoid duplicates in python
<p>I have 2 <code>for</code> loops that work well. The problem is that I want to combine them in order to avoid to append duplicates in my <code>data2</code> dataframe. In other words, I want the <code>for value in Dic[&quot;synonyms.0&quot;].values:</code> loop to happen only when no there is no <code>value in line :<...
<p>You just need to add a boolean value that determines how the first iteration went</p> <pre><code>found_value = False for value in Dic[&quot;label&quot;].values: if (value != None) : if value in line : data2.append([value, line.count(value), len(value),dosage]) found_value = True i...
python|for-loop|duplicates
2
9,210
69,842,541
Why do I see more threads at OS level than are spawned by my code?
<p>Python programs generates threads on some conditions with the following code:</p> <pre><code>thread1 = threading.Thread(target=foo, args=(arg1,)) thread1.start() </code></pre> <p>The problem is that I see too many threads at OS level:</p> <pre class="lang-none prettyprint-override"><code>$ ps -efL | grep myscript.py...
<p>It is weird, but there is posibility that those 4000 threads are all threads from your PC, for example right now i have 3840 active Threads, and python should not give you all tasks from your pc. In python if you have only MainThread you should see 1 after typing <code>threading.active_count()</code>, or more if you...
python|multithreading
0
9,211
73,177,586
Extract all Images from PDF with Python, and retain their transparency
<p>I see a number of solutions on the web and here for extracting images from a PDF with PyMuPDF, PyPDF2, and others, but none them successfully retain transparency information, are using deprecated code that no longer works, or the questions have gone unanswered. The examples I try show a black background where the tr...
<p>PDF Images are not what you seem to expect. So lets take one sample, but all inserts can be done differently (otherwise there would be no need for different extraction apps). PDF was not designed for splitting retrospectively, many objects were simplified for toner ink for transfer on usually white paper, thus trans...
python|pypdf2|pymupdf
3
9,212
55,619,761
Remove outliers from Pandas pivot_table rows
<p>I am currently working on a problem that entails looking at a number of purchased parts and determining if we are successful in our endeavors to reduce our cost.</p> <p>I am hit by a few issues though. Since our purchaser can choose to enter an order in any given number of Unit Of Measures (UOM), but does not alway...
<p>One way you can do that is to filter on columns that have an extreme value (>10%) in this case, but by changing low and high you can set the bounds of the extreme value. After that you can replace those values with low and high with nan, and then take the subset of columns that are outliers in this case as a separat...
python|pandas|lambda|pivot-table
1
9,213
55,741,962
Tkinter OptionMenu disabled but expandable
<p>Is there any solution of write-protecting a <code>tkinter</code> <code>OptionMenu</code> while retaining the possibility to inspect the available Options?</p> <p>Background: I have a tkinter <code>OptionMenu</code> containing a selection of files that the user can "quick-load" into the application. However it migh...
<p>You can disable each entry of the menu instead of disabling the optionmenu totally using <code>menu.entryconfigure(&lt;index&gt;, state='disabled')</code>. The menu of an optionmenu is stored in the 'menu' property:</p> <pre><code>import tkinter as tk root = tk.Tk() var = tk.StringVar(root) opmenu = tk.OptionMenu(...
python|python-3.x|tkinter
2
9,214
55,865,916
How to measure in Python the time lapse between keystrokes?
<p>I'm trying to create a python program that measures trill velocity of pianists. Trills are a musical ornament consisting of a rapid alternation between two adjacent keys on the piano, so I think this can be simulated with two keys of the pc keyboard, like "K" and "O". Keys would be pressed at a frequency of 10 beats...
<p>Modifying keyboard library's pressed_keys example, as follows, I have achieved what I was attempting. However, for some reason, times are printed twice on the screen for each keystroke. Why does this happen? How could it be fixed?</p> <pre><code>""" Prints the scan code of all currently pressed keys. Updates on eve...
python
0
9,215
73,505,035
Insert a single cell of string above header row in python pandas
<p>I have my dataframe ready to be written to an excel file but I need to add a single cell of string above it. How do I do that?</p> <p><a href="https://i.stack.imgur.com/42xS7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/42xS7.png" alt="enter image description here" /></a></p>
<pre><code>import pandas as pd df = pd.DataFrame({'label':['first','second','first','first','second','second'], 'first_text':['how is your day','the weather is nice','i am feeling well','i go to school','this is good','that is new'], 'second_text':['today is warm','this is cute','i am feel...
python|pandas|dataframe
0
9,216
66,611,794
Python SQL - Trouble inserting into database. (NO error)
<pre class="lang-py prettyprint-override"><code>USER_ROBLOX_ID = 114678641 author_id = 257073333273624576 date_today = datetime.today().strftime('%Y-%m-%d') await self.bot.db.execute(&quot;&quot;&quot; INSERT INTO user_data (roblox_id, discord_id, verified_at, verify_code) VALUES ($1, $2, $3, $4); &quot;&quot;&quot;, U...
<p>strptime() transform a datetime to a string. As you can see your error is about your str not having 'toordinal' attribute</p> <p>strptime() is the opposite function, allow you to transform a string to a datetime.</p> <p>As your column is set up to be a datetime, it will contain a full datetime object and you can't f...
python|sql|postgresql|discord|asyncpg
1
9,217
66,367,692
Automatic page refresh stops working (Flask App)
<p>I created a Flask app that displays the latest pictures on an HTML website. The website is set to automatically refresh every 10 seconds using a meta tag</p> <pre><code>&lt;meta http-equiv=&quot;refresh&quot; content=&quot;10&quot; /&gt; </code></pre> <p>it all works great when the server and website run on a local ...
<p>You could just use javascript for this. Just put the code below in your html file somewhere or in a seperate javascript file named <code>script.js </code> and link that javascript file like <code>&lt;script src=&quot;/Path/To/File.js&quot;&gt;&lt;/script&gt;</code></p> <pre><code>&lt;script&gt; window.setTimeout(fun...
python|html|flask|page-refresh
0
9,218
64,809,914
Import an exported grafana csv file into python pandas that makes sense?
<p>The title of this question could probably use some work. But here is what I'm wanting to do. I have exported data from a grafana dashboard. It turns out to be something like</p> <pre><code> Series Time Value 0 A 2020-11-11 21:00:00-05:00 0.003020 1 A 2020-11-11 21:00:30-05:00 0.050300 2 A 2020...
<p>With some additional searching I finally found the answer <a href="https://stackoverflow.com/questions/43453162/python-pandas-convert-rows-to-columns-where-multiple-columns-exist">here</a>.</p> <p>Using the pivot_table made it easy.</p> <pre class="lang-py prettyprint-override"><code>table.pivot_table(index=['Time']...
python|pandas|grafana
1
9,219
63,818,820
Is there a way to add a new attribute with a value to an element using selenium python?
<p>Here's the HTML</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;img src="//www.shahidpro.tv/uploads/articles/220cc817.jpg" width="408" height="605" vspace="" hspace=...
<p>Let's say you can find <code>element</code> that you want to change. You can add new attribute using js:</p> <pre><code>driver.execute_script(&quot;arguments[0].setAttribute('style', 'display: block; margin-left: auto; margin-right: auto;');&quot;, element) </code></pre>
javascript|python|selenium|selenium-webdriver|setattribute
1
9,220
53,280,140
Round a number in Python
<p>I have a very simple problem. I want to break an interval from <code>1e-6</code> to <code>10e-6</code> into ten values and append them to a list. For this reason, I made the program below,</p> <pre><code>start_value = 1e-6 stop_value = 10e-6 step_value = 10 step = (stop_value-start_value)/(step_value-9) current_li...
<p>You could take a look at the <code>fractions</code> module:</p> <pre><code>import fractions start_value = fractions.Fraction(1, 1000000) stop_value = fractions.Fraction(10, 1000000) step_value = 10 step = fractions.Fraction(stop_value-start_value, (step_value - 1)) current_list = [] for i in range(step_value): ...
python|python-3.x
1
9,221
52,986,062
Replace variables in text template
<p>So my text file says something like this:</p> <pre><code>Dear $name, \n\n Thank you for participating in our study on working memory and musical training! \n\n You are receiving this email because you said that you were interested in receiving your results of the tests that you took on your musical and non-musical ...
<p>Create a "template", then fill in the placeholders <code>{name}</code> using the values stored in a dictionary.</p> <pre><code>text="""Dear {name}, Thank you for participating in our study on working memory and musical training! You are receiving this email because you said that you were interested in receiving y...
python|string|templates
2
9,222
53,227,976
Attribute in django django dispatch method
<p>Below is the dispatch method in django view class </p> <pre><code>def dispatch(self, request, *args, **kwargs): # Try to dispatch to the right method; if a method doesn't exist, # defer to the error handler. Also defer to the error handler if the # request method isn't on the approved list. if re...
<p>It's defined as a part of the Django <a href="https://docs.djangoproject.com/en/2.1/ref/request-response/#attributes" rel="nofollow noreferrer">request object</a>.</p> <blockquote> <p><strong>HttpRequest.method</strong></p> <p>A string representing the HTTP method used in the request. This is guaranteed to b...
python|django
4
9,223
71,883,160
Why does subprocess.Popen run in parallel but subprocess.run does not
<p>I would like to perform an expensive IO operation in parallel in a subprocess. However, when I execute the following code, it runs sequentially and takes forever to complete:</p> <pre class="lang-py prettyprint-override"><code>import subprocess import csv processes = [] with open(f'identifiers.csv', 'r', newline='...
<p>This is clearly documented; <code>subprocess.run</code> blocks and waits for the subprocess to finish. If you want to run a parallel subprocess, you need <code>Popen</code>; but then you also need to do the required management of the subprocess object which <code>run</code> takes care of for you behind the scenes. (...
python|python-3.x|parallel-processing|subprocess
1
9,224
68,783,366
can pycuda parse float as unsigned char array as C++/CUDA does?
<p>I'm trying to do base64 using pycuda for data transfer on network. I need to convert float to byte or unsigned char and I did it just by cudamemcpy after I found memcpy works well on CPU. I mean, I just do cuda mem copy some float values and take those values in the kernel by &quot;unsigend char* &quot; to treat it ...
<p>First of all this import:</p> <pre><code>import pycuda.driver as drv </code></pre> <p>doesn't match the rest of your code. To match the rest of your code, that should be:</p> <pre><code>import pycuda.driver as cuda </code></pre> <p>On to your question. The parameter that pycuda is complaining about is parameter 0 (...
python|c++|casting|cuda
2
9,225
10,609,965
Python - Simplest method of stripping the last byte from a file?
<p>I want to make a script that will take a file, strip off the last byte of a file. The file can be anything, not just text. </p> <p>I have been playing around with the seek() and tell() methods, but I can't find a way of dealing with the file that allows me to do this. </p> <p>I figured it should be relatively triv...
<p>Seek one byte from the end, and truncate.</p> <pre><code>f = open(..., 'r+') f.seek(-1, os.SEEK_END) f.truncate() f.close() </code></pre>
python|file|truncate
13
9,226
61,715,151
If I delete a row with pandas, it remains in Excel
<p>If I delete a row with pandas, it remains in Excel</p> <pre><code>def sort_wickelfalzrohr(d): # Filter settings filt_with_isolation = (df_read['KZ'] == 'R-R') &amp; (df_read['D'] == d) &amp; (df_read['IsoOf'].isna() == False) filt_without_isolation = (df_read['KZ'] == 'R-R') &amp; (df_read['D'] == d) &...
<p>Yes. When you read from a file, you create a copy of the file in computer's memory. All the changes you make are in the memory, which will be deleted after you close the program. If you want to apply the changes to the file you should save your dataframe back to the file using <code>df.to_excel</code> or <code>df.to...
python|excel|pandas|save
1
9,227
67,516,373
concurrent.futures raises TypeError?
<p>In case someone else see's this same problem:</p> <pre><code>## The params should have been sent as a tuple data = [] for file in files: data.append((file, loc, symbol, under_df)) with concurrent.futures.ProcessPoolExecutor() as executor: r = [executor.submit(process_file, data) for data in data] </code></pr...
<p>You didn't show <code>files</code> and I think <code>file</code> might be something else than you expect.</p> <pre><code>from concurrent.futures.process import ProcessPoolExecutor def print_int(el: int): print(el**2) lst = list(range(10)) with ProcessPoolExecutor() as executor: r = [executor.submit(print...
python|multiprocessing|concurrent.futures
0
9,228
60,692,703
How to write a matrix/ 2D-array to a text file python
<h3>Scenario</h3> <p>Using Python, I need to write a 2d matrix into a file in order to allow the following command to easily read it:</p> <pre class="lang-py prettyprint-override"><code>with open("matrix.txt") as textFile: matrix = [line.split() for line in textFile] </code></pre> <h3>Problem</h3> <p>I have tri...
<p>You can convert individual rows of your matrix into strings separated by spaces and write those into a text file. </p> <pre><code>matrix = [[1, 2, 3,],[4, 5, 6],[7, 8, 9]] with open('matrix.txt', 'w') as testfile: for row in matrix: testfile.write(' '.join([str(a) for a in row]) + '\n') </code></pre>
python
4
9,229
70,654,731
How to apply a function to sub selections in a pandas DataFrame object efficiently?
<p>I have a dataframe of people's addresses and names. I have a function that processes names that I want to apply. I am creating sub selections of people with matching addresses and applying the function to those groups.</p> <p>To this point I have been using <code>.loc</code> to as follows</p> <pre><code>for x in df[...
<p>Try using</p> <pre><code>df.groupby('address').apply(lambda x: function(x['names'])) </code></pre> <p><strong>Edited:</strong> Check this example. I've used a dataframe from another StackOverflow question</p> <pre><code>import pandas as pd df = pd.DataFrame({ &quot;City&quot;:[&quot;Delhi&quot;,&quot;Delhi&quo...
python|pandas|performance|pandas-groupby
0
9,230
56,785,517
What should be the correct approach to pass in primary key into URL?
<p>Right now I am using Class-based delete view, and my URL contains two arguments which are the primary keys of my 2 models: <code>Post</code> and <code>Lesson</code>. However, I am encountering an <code>Attribute Error: Generic detail view LessonDeleteView must be called with either an object pk or a slug in the URLc...
<p>As you are deleting <code>Lesson</code>, you don't need to provide <code>Post</code> ID. You can simply use <code>Lesson</code> ID here. So try like this:</p> <pre><code># url path('post/lesson_uploaded/&lt;int:pk&gt;/', LessonDeleteView.as_view(), name='lesson_delete'), # using pk instead of lession_id, it will r...
python|django
2
9,231
60,994,784
How to convert CURL command with python requests and retrieve results via API
<p>I'm new to python and encountered problems passing the parameters below that I want to request from the server via API.</p> <p>I'm using flask as I want this to be web based. Step1: go to index.html and pass teamID <code>teamID = request.form['teamID']</code>. Step2: Authenticate user via API &amp; find data by tea...
<p>Thanks to <a href="https://curl.trillworks.com/" rel="nofollow noreferrer">TrillWorks</a>, we have now an online curl to python converter.<br> So for:</p> <pre><code>curl -X POST -H \"Content-Type: application/json\" -H \"accessToken:" &amp; authToken &amp; "\" \"" &amp; serverURL &amp; "teamID/" &amp; teamID &amp;...
python|curl|flask|python-requests|flask-restful
1
9,232
66,124,968
Drop Pandas dataframe rows if geocoordinates outside country shapefile
<p>I'm working on a script that will filter and drop any rows containing coordinates outside a specific country shapefile.</p> <p>Here's what I have so far</p> <pre><code>import pandas as pd import shapefile from shapely.geometry import Point from shapely.geometry import shape df = pd.read_stata(r'C:PathtoDataFrame'...
<p>To avoid the TypeError, try replacing the code for creation of dataframe copy as follows:</p> <pre><code>df_copy = df.apply(lambda x: InCountry(x.geopointlongitude, x.geopointlatitude), axis=1) </code></pre>
python|pandas|dataframe|anaconda|data-science
1
9,233
66,237,058
How to find matching items in a list with a condition
<p>the given data set :</p> <pre><code>P = {&quot;alice&quot;: &quot;R&quot;, &quot;bob&quot;: &quot;D&quot;, &quot;carol&quot;: &quot;D&quot;} V = {&quot;alice&quot;: [True, True, False, True, None], &quot;bob&quot;: [True, False, None, True, True], &quot;carol&quot;: [False, False, False, None, None]} </co...
<p>There a lot of methods to do this. This is the method I used,<br/> First, you need to reverse <code>p</code> because it is the easiest way as I think. I used the following code for that:</p> <pre><code>p_r = {} for a, b in p.items(): if p_r.get(b): p_r[b] += [a] else: p_r[b] = [a] </code></p...
python|loops|dictionary
0
9,234
66,026,365
How to scrape pdf to local folder with filename = url and delay within iteration?
<p>I scraped a website (<code>url =</code> &quot;http://bla.com/bla/bla/bla/bla.txt&quot;) for all the <strong>links</strong> containing <strong>.pdf</strong> that were important to me. These are now stored in <code>relative_paths</code>:</p> <pre><code>['http://aa.bb.ccc.com/dd/ee-fff/gg/hh99/iii/3333/jjjjj-99-0065.pd...
<p>give this a shot:</p> <pre><code>import time count_downloads = 25 #&lt;--- wait x seconds after every 25 downloads time_delay = 60 #&lt;--- wait 60 seconds after every y downloads for idx, link in enumerate(relative_paths): if idx % count_downloads == 0: print ('Waiting %s seconds...' %time_delay) ...
python|pdf|web-scraping|beautifulsoup|filenames
0
9,235
68,172,763
Making python as windows service
<p>I have created python file which intern call PowerShell Script. I want to make this as windows service. can anyone of you help me with that. I'm trying by using NSSM. when I started running service, getting error as &quot;PowerShell is not recognized as internal or external Windows command&quot;</p>
<p>you can use <a href="https://pypi.org/project/pyinstaller/" rel="nofollow noreferrer">PyInstaller</a> for create python as a service</p> <p>Once you install it using</p> <pre><code>pip install PyInstaller </code></pre> <p>then you can create exe file using</p> <pre><code>pyinstaller -F --hidden-import=win32timezone ...
python|powershell|nssm
0
9,236
63,246,167
Why does zip() of list of lists output such?
<p>Let's take:</p> <pre><code>a = zip([[1,2],[2,3]]) </code></pre> <p>where a is the zipped variable of list of lists [[1,2],[2,3]] the output for <code>print(list(a))</code>is</p> <pre><code>[([1, 2],), ([2, 3],)] </code></pre> <p>meaning the zip was a tuple containing ([1, 2],), ([2, 3],)? Why is that? For example, w...
<p>&quot;The zip() function takes iterables (can be zero or more), aggregates them in a tuple, and return it.&quot;</p> <p>Basically it mean that you can do sometime like that:</p> <pre><code>list1 = [1,2,3,4] list2 = [&quot;h&quot;, &quot;b&quot;, &quot;s&quot;] for num, char in zip(list1, list2): print(num, char...
python|list|zip
0
9,237
62,920,925
Django passing user ID to filter models
<p>I have trying to filter objects in a model to avoid people putting events in their calendars which over lap. I found the below link which helped (<a href="https://stackoverflow.com/questions/13026689/django-form-field-clean-to-check-if-entered-date-is-in-a-stored-range">Django form field clean to check if entered da...
<p>You can make use of the <code>manage_id</code> of the <code>Event</code> object wrapped in the form:</p> <pre><code>class EventForm(ModelForm): # &hellip; def clean(self): form_start_time = self.cleaned_data.get('start_time') form_end_time = self.cleaned_data.get('end_time') between...
python|django
1
9,238
62,217,514
DjangoFilterBackend: Filtering on a primary key results in "Select a valid choice. That choice is not one of the available choices."
<p>I have two models (Product &amp; Category) which every product has a linked category.</p> <p>I have installed <code>DjangoFilterBackend</code> which the hope of filtering on the <code>category</code> field to return a list of products in that category. </p> <p>However, whenever I send the query in Postman. I recei...
<p>Ah-ha!</p> <p>I changed the model to:</p> <pre><code>class Product(models.Model): name = models.CharField(max_length=250, unique=True, blank=False) photo = models.ImageField(upload_to=product_photo_path) **category = models.ForeignKey(Category, to_field='name', on_delete=models.CASCADE)** quantity ...
python|django|django-rest-framework
1
9,239
58,712,529
Get child element value from xml file using Python
<p>I need to extract/modify a child element from a .xml file using Python. For this, I am using the xml.etree.ElementTree but I don't get the desired output from my code. I need to extract the element "name" just under "deployment"(in this case xyz1000_Test_v1) from the .xml file:</p> <pre><code>&lt;?xml version="1.0"...
<p>All elements in the document are bound to the same namespace, and the <code>network</code> element is not an immediate child of the root.</p> <p>With <code>findall()</code>, use this:</p> <pre><code>for network in root.findall('.//{http://www.test.com/esc/esc}network'): name = network.find('{http://www.test.co...
python|xml|elementtree
1
9,240
58,878,133
Is there a function to add WOE, calculated on Training data, to the whole data set? (python)
<p>I am working on some python code to predict Default rate of loans handed out by a bank. </p> <p>I have calculated the WOE and information value (IV) on the training set (using the following code: <a href="https://github.com/Sundar0989/WOE-and-IV/blob/master/WOE_IV.ipynb?fbclid=IwAR1MvEfyGsdyTre0uPJC5WRl91dfue_t0vH...
<p>Thanks for asking this question. Here is the code to do the required transformation which is shown in the notebook as well.</p> <pre><code>transform_vars_list = df.columns.difference(['target']) transform_prefix = 'new_' # leave this value blank to replace the original column #apply transformations for var in trans...
python|training-data
1
9,241
59,591,971
Seaborn line style from colum-name
<p>I have the dataframe:</p> <pre><code> Blau_Loch Blau_Scheibe Rot_Loch Rot_Scheibe 0 0.4190 0.4120 0.420 0.4110 1 0.4180 0.4130 0.421 0.4170 2 0.4200 0.4150 0.421 0.4140 3 0.4180 0.4100 0.422 0.4140 4 0.419...
<p>You don't write many details about how you call the functions. You can set colors to <code>relplot</code> with <code>palette=</code> and markers with <code>markers=</code>. If you don't set them, you get default values. I'm not sure how to get a hollow circle using this setup; markers can be chosen from <a href="htt...
python|seaborn
1
9,242
49,335,353
How to get py-scrypt's "simple password verifier" example functions to work?
<p>I am using the <a href="https://bitbucket.org/mhallin/py-scrypt/src" rel="nofollow noreferrer">example script</a> provide by <code>py-scrypt</code> to build a <strong>simple password verifier</strong>. Below is my test script.</p> <p><strong>Test Script:</strong></p> <pre><code>#!/usr/bin/python3 # -*- coding: utf...
<h1>Explanation for UnicodeDecodeError Exception</h1> <h2>Reason 1</h2> <p>I think I understand why Scrypt is issuing a <code>UnicodeDecodeError</code>. Quoting <a href="https://wiki.python.org/moin/UnicodeDecodeError" rel="nofollow noreferrer">Python's UnicodeDecodeError </a>:</p> <blockquote> <p>The UnicodeDecod...
python|scrypt
0
9,243
60,240,983
Scrapy: Selector for text between two HTML elements..?
<p>I am currently using scrapy to scrape a website. The Website is a list of profiles. So the Spider click on every link in the list (which is one profile) and then extract the data, comes back and clicks on the next one etc. This is how I structured it:</p> <pre><code>class Profiles(scrapy.Spider): name = 'profil...
<p>This might be a case that you have to fallback to a regular expression.</p> <p>Without knowing the full structure of the page it is hard to give you exactly what you need, but here is an example using the snippet you gave</p> <pre class="lang-py prettyprint-override"><code>import scrapy sel = scrapy.Selector(text=&...
python|xpath|scrapy|web-crawler
2
9,244
67,636,662
H2O GAM train: parameter "fold_column" not working
<p>I can not make the parameter &quot;fold_column&quot; work with the H2OGeneralizedAdditiveEstimator, using Python.</p> <p>I need to create folds outside H2O, and read the finished Pandas DataFrame into a H2OFrame. In the H2OFrame there is a column &quot;fold_number&quot;. I can loop through the folds and train models...
<p>I was able to reproduce the error and indeed it's not working (neither <code>nfolds</code> nor <code>fold_column</code> seem to be working). We will fix this ASAP. Here's the Jira ticket: <a href="https://h2oai.atlassian.net/browse/PUBDEV-8163" rel="nofollow noreferrer">https://h2oai.atlassian.net/browse/PUBDEV-816...
python|h2o|gam
3
9,245
67,966,862
How do I use pd.NA by default in pandas DataFrame.from_records?
<p>pd.NA and related pandas array dtypes are solving some of the most annoying issues with missing data in pandas. How do I use pd.NA by default when creating a DataFrame like this?</p> <pre><code>import pandas as pd pd.DataFrame.from_records([ {'a': 1, 'b': 'x'}, {'b': 'y', 'c': 1.7}, ]) # Pandas 1.2 output ...
<p>Like mentioned @sammywemmy in comments, possible solution is add code after <code>from_records</code>, e.g. <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.convert_dtypes.html" rel="nofollow noreferrer"><code>DataFrame.convert_dtypes</code></a>:</p> <pre><code>df = pd.DataFrame.f...
python|pandas|dataframe
1
9,246
67,890,299
Find all occurrences of a key in nested dictionaries and lists - with path
<p>I read the answers to how to get all occurrences of a key within nested dicts and lists here:</p> <p><a href="https://stackoverflow.com/questions/9807634/find-all-occurrences-of-a-key-in-nested-dictionaries-and-lists">Link to question</a></p> <p>Apart from getting the value of the key, I would like to be able to dis...
<p>After some experimenting I found the below code to solve my problem.</p> <pre><code>def gen_dict_location_extract(key, value, path=None): if path is None: path = [] if hasattr(value, &quot;items&quot;): for k, v in value.items(): if k == key: # recursive exit point ...
python|python-3.x
0
9,247
30,675,501
Matplotlib/Genfromtxt: Multiple plots against time, skipping missing data points, from .csv
<p>I've been able to import and plot multiple columns of data against the same x axis (time) with legends, from csv files using genfromtxt as shown in this link:</p> <p><a href="https://stackoverflow.com/questions/30423052/matplotlib-import-and-plot-multiple-time-series-with-legends-direct-from-csv/30673995">Matplotli...
<p>I think if you set <code>usemask =True</code> in your <code>genfromtxt</code> command, it will do what you want. Probably don't want <code>filling_values</code> set either </p> <pre><code>arr = np.genfromtxt('DemoData.csv', delimiter=',', dtype=None, missing_values='', usemask=True) </code></pre> <p>you can then...
python|csv|matplotlib|plot|genfromtxt
2
9,248
64,124,305
Look for repeated values inside row arrays of Pandas Dataframe
<p>I was looking for this question but I didn't find something similar.</p> <p>So, as an example I have a df like this:</p> <pre><code> GROUP CATEGORY ONE [pretty, intuitive, new, expensive, imported] TWO [new, small, expensive, useful] TH...
<p>I think the solution is this. My approach might be old school but it works.</p> <pre><code>import pandas as pd df = pd.DataFrame({'group': ['ONE', 'TWO', 'THREE'], 'category': [[&quot;pretty&quot;, &quot;intuitive&quot;, &quot;new&quot;, &quot;expensive&quot;, &quot;imported&quot;], [&quot;new&quot;, &q...
python-3.x|pandas|dataframe
2
9,249
66,717,746
efficient way to do multi threaded calls from python to mysql server deployed on AWS?
<p>Is there a way to use threads to simultaneously perform the SQL queries so I can cut down on fetching and processing time of my code below? Is there a better method to perform the same result faster? Given the size of the data sets, it's taking &gt;22 seconds to get the result and likely to increase. Can I use multi...
<p>Something like this may work. I'm not positive if you can use the same connection across multiple threads, so you <em>may</em> need to create the SSH tunnel inside of each thread. Under the assumption that you can use the same connection object:</p> <pre class="lang-py prettyprint-override"><code>from multiprocessin...
python|mysql
0
9,250
72,243,463
how to align sliding window to extract features from multi modal timeseries data?
<p>I have two datasets that are collected at different frequencies at the same time. One is recorded at 128Hz and another one is recorded at 512 Hz. I am trying to extract some features using the moving window technique but I have some problems.</p> <ol> <li>Frequencies of both datasets are different.</li> <li>the time...
<p>yes there is a valid solution called pyphisio <a href="https://github.com/MPBA/pyphysio" rel="nofollow noreferrer">https://github.com/MPBA/pyphysio</a></p> <p>Hope it helps!</p>
python|machine-learning|statistics|data-science|feature-extraction
1
9,251
72,414,157
Finding the season of the highest temperature amplitude
<p><a href="https://i.stack.imgur.com/oDt4V.png" rel="nofollow noreferrer">enter image description here</a></p> <p>I was being disqualified from an interview test from a &quot;top&quot; freelance website because they found similarities in my answers from online. But I also would like to share my own solutions to this q...
<p>The question gives an &quot;example&quot; for T. If you study the question closely, there is an implication that the length of T will be a multiple of 4 - i.e., not necessarily just 8 but maybe 12, 16 etc. So you need a more generic solution. Something like this:</p> <pre><code>class Solution: SEASONS = ['WINTER...
python|amplitude
0
9,252
3,367,706
Ascending/descending ordering of Django QuerySet when one attribute is a model method
<p>I have a QuerySet of teams ordered by school name. One of the attributes is a model method that keeps track of the team's winning percentage. I want to order the teams from highest winning percentage to lowest. If teams have the same winning percentage, I want them to be ordered alphabetically by school. How do I ge...
<p>Do it in two steps, not bad since sorts are stable:</p> <pre><code>from operator import attrgetter sorted_team_list = sorted(team_list, key=attrgetter('school')) sorted_team_list = sorted(sorted_team_list, key=attrgetter('win_pct'), reverse=True) </code></pre>
python|django|sorting
1
9,253
3,376,867
How do I set up rpy2?
<p>Hi I just download rpy2 and Python 2.6. When I try to run some of example code I found on the internet, I got this error. Can anyone explain why this is happening and how can I fix it? Thanks.</p> <pre><code>import rpy2.robjects as RO Traceback (most recent call last): File "&lt;pyshell#0&gt;", line 1, in &lt;mo...
<blockquote> <p>This might be because R.exe is nowhere in your Path</p> </blockquote> <p>This sounds like a big clue. Check the value of <code>%PATH%</code> in your Windows environment. I'd expect this to contain the location of <code>R.EXE</code> (probably something like <code>C:\Programs\R\R-2.8.0\bin</code>).</...
python|r
1
9,254
3,470,208
How to link one table to itself?
<p>I'm trying to link one table to itself. I have media groups which can contain more media group. I created a relation many to many:</p> <pre><code>media_group_groups = Table( "media_group_groups", metadata, Column("groupA_id", Integer, ForeignKey("media_groups.id")), C...
<p>SQLAlchemy can't figure out which columns in your link table to join on. Try this for the <code>relationship</code>:</p> <pre><code>mediaGroup = relationship("MediaGroup", secondary=media_group_groups, order_by="MediaGroup.title", backref=backref('media_groups', sec...
python|sqlalchemy
1
9,255
26,914,633
Text-to-speech for Python 2.7
<p>How can I use text-to-speech in Python 2.7? With that I mean that someone can write a text, and this text will then be spoken with a voice by the program. With the voice it should be something like in the google translator and it should be compatible with Tkinter 2.7. Are there any modules or ways to manage this? Th...
<p>You may be interested in <strong>pyttsx</strong>, it's cross-platforms too. You can read more about this from pypi <a href="https://pypi.python.org/pypi/pyttsx" rel="nofollow">HERE</a>.</p> <p>And the doc <a href="http://pyttsx.readthedocs.org/en/latest/" rel="nofollow">pyttsx - Text-to-speech x-platform</a></p>
python|python-2.7|module|tkinter|text-to-speech
1
9,256
45,192,259
Check if variable is defined using a function
<p>I need to check, whether variable is defined or not. If it is not, then this variable should be created as empty string. I want to do it by <code>try</code> and it works fine:</p> <pre><code>try: ident except: ident = '' </code></pre> <p>But I need to do that using a function, coz I will do that many, many...
<p>If you want a one-liner, you can perhaps go with:</p> <pre><code>ident= ident if ident else ' ' </code></pre> <p>EDIT: This also worked for me:</p> <pre><code>f=lambda x: x if x else ' ' c=8 f(c) # output: 8 f(d) # NameError: name 'd' is not defined </code></pre>
python|python-2.7
0
9,257
61,472,293
How to purge all celery subtasks from parent task?
<p>In my <code>sharedtask</code> I call several <code>subtasks(...).apply_async()</code>. Thus, both the parent task and the subtasks have their own task_id.</p> <p>When I cancel the entire operation, I call the revoke of all active tasks and it works correctly. But as soon as cores are released, the queue moves on, e...
<p>You could try the following:</p> <pre><code>app.control.revoke(task_id, terminate=True) </code></pre> <p>and start the task with:</p> <pre><code>task_id = subtasks(...).apply_async() </code></pre> <p>I'm not sure if it works with subtasks to save the task id in this way, but with normal tasks it works well, so it is...
python-2.7|celery|celery-task
0
9,258
61,316,025
Weird path behavior when using os.path and pathlib Mac OSX Catalina
<p>I have an image called <code>image1.png</code> its real path on my macbook is : </p> <blockquote> <p>/Users/emadboctor/Desktop/images/image1.png </p> </blockquote> <p>and the image is found by calling:</p> <blockquote> <p><code>images = os.listdir('/Users/emadboctor/Desktop/images/image1.png')</code></p> </bl...
<p>Use the function <code>resolve</code>.</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; from pathlib import Path &gt;&gt;&gt; &gt;&gt;&gt; Path.cwd() WindowsPath('d:/Docs/Notes/Notes') &gt;&gt;&gt; p = Path('../../test/lab.svg') &gt;&gt;&gt; p WindowsPath('../../test/lab.svg') &gt;&gt;&gt; p.absolut...
python-3.x|python-os|pathlib
0
9,259
60,712,771
Attribute error: module 'requests' has no attribute 'Session' in pandas-DataReader
<p>I am trying to follow <a href="https://kylelix7.github.io/Efficient-Frontier-Explained-with-SciPy/" rel="nofollow noreferrer">this</a> tutorial. However the line:</p> <pre class="lang-py prettyprint-override"><code>portfolio = web.DataReader(name=symbol, data_source='quandl', start=start, end=end) </code></pre> <p...
<p>check your spelling.</p> <p>It should have been <code>requests.session()</code> not <code>requests.Session()</code></p>
python|pandas|python-requests|pandas-datareader
0
9,260
56,186,906
The logic and Code sample for conversion of Osm:Relation to GeoJson
<p>I just want to convert <code>osm</code> data to <code>geojson</code> where it is pretty simple with node and way tags of <code>osm</code> data, but relation which is giving complex can't find the logic to convert <code>osm</code> relation to <code>geojson</code> format especially how to form coordinates parameter of...
<p>The <a href="https://wiki.openstreetmap.org/wiki/GeoJSON" rel="nofollow noreferrer">GeoJSON</a> page in the OSM Wiki lists various tools for converting OSM data to GeoJSON:</p> <blockquote> <ul> <li><a href="https://wiki.openstreetmap.org/wiki/Ogr2ogr" rel="nofollow noreferrer">ogr2ogr</a> – General tool for co...
java|python|geometry|openstreetmap|geojson
0
9,261
18,572,379
Multiple kernels in Enthought Canopy
<p>I previously worked with the EPD Python distribution using its Qt-console, where one of the most useful features was easily having multiple kernels in multiple tabs, when doing several calculations simultaneously.</p> <p>I recently got the "new" Enthought Canopy, which somehow tries to emulate MatLab, which might n...
<p>The <em>Canopy GUI application</em> does not yet support multiple kernels. However, just like with EPD, you can run QtConsole, including using its multiple kernel capabilities, from a Canopy User Python command line.</p> <p>To do this quickly:</p> <p><code> ~/Enthought/Canopy_64bit/User/bin/ipython qtconsole </cod...
python|linux|kernel|enthought|canopy
2
9,262
57,455,119
Add environment variable in app.yaml file during Google Build
<p>I'm using Google Cloud Build with <code>cloudbuild.yaml</code> to download an <code>app.yaml</code> file that includes environment variables for my <code>Python</code> based app. The <code>app.yaml</code> version used for the initial deployment does not contain the environment variables for security protection.</p> ...
<p>When you run <code>gcloud app deploy</code>, the deployment process won't take the <code>cloudbuild.yaml</code> file into account and will deploy your app along with your <em>unpopulated</em> <code>app.yaml</code> file.</p> <p>To run a custom build step, you'll need to create a cloudbuild.yaml file as you did, defi...
python|google-app-engine|yaml|google-cloud-build
1
9,263
57,350,806
Nested for loops with ranges defined by files
<p>I'm trying to code a nested for loop where the ranges are defined by two input files, the content of the files is not really relevant for this problem. The files are passed to the program as arguments. </p> <p>For each line of file A(which as an example contains numbers) the for loop should iterate through each of ...
<p>Typically with opening files and reading the stream from them you want to do a while loop until it reaches the end of the file. If the files are passed in as arguments I'm not sure having a loop reading the first file then an inner loop reading the second file makes sense. If you need to combine the data it probably...
python|python-3.x
0
9,264
42,517,109
Output squares using a while loop
<p>Im trying to accomplish taking an input number, for ex 8 and have it output all of the squares up to 64. so 1,4,9,16,25,36,49,64. I want to do it without using the exponent operator. I have run into a problem where my loop is just jumping straight to 64 and skipping the other squares. </p> <pre><code>limit = input(...
<p>Your counter(<code>ctr</code>) increment part is wrong. When you do <code>ctr = (square) + 1</code>, you are making it more then the limit in the first iteration itself. For example, lets say the limit is 8, which means square is 64.</p> <p>Now you want your loop to run while ctr is less than equal to limit.</p> <...
python|python-3.x
0
9,265
59,153,084
How to Append data in While loop into Empty DataFrame
<p>I have dataframe which has 5 columns.</p> <pre><code>Df = pd.DataFrame(columns=['userId','movieId','rating','timestamp','genres']) </code></pre> <p>I have this function</p> <pre><code>def Main(): flag = 0 while(flag &lt;=99): data1 = pickRandomMovies() data2 = usersToMovies(data1) ...
<p>change your code to</p> <pre><code>def Main(): flag = 0 while(flag &lt;=99): data1 = pickRandomMovies() data2 = usersToMovies(data1) if len(data2) &lt; 6: data2 = data1 else: flag +=1 data3 = commonUsers(data2) #append all valu...
python|pandas
1
9,266
59,327,507
Accessing list in pandas dataframe from within DataFrame.loc
<p>I'm working with a database that contains the column 'tchname' with each entry containing a string such as 'John Smith' or 'Mr John Adam Smith', where the first or second word (depending on if there's an honorific) of each string is the first name and the final word is the surname.</p> <p>What I wish to do is creat...
<p>Thanks to Alexander Cécile for his suggestion on using regex. I tried to avoid this due to the poor performance of regex, however here's a solution based on it:</p> <pre><code>import numpy as np import pandas as pd # Typical data example: data = {'tchname': ['MISS NANDA DEVI', 'RAJIK HUSSAIN-III', ...
python|python-3.x|pandas|dataframe
0
9,267
53,926,231
Python: average and standard deviation of specific columns among multiple files and plot the average with standard deviation bar
<p>I have input data which look like below, where I want to average the 6th column and standard deviation of that column. I also need a graph where the 1st column will be in x-axis and average will be in the y-axis with error bar.</p> <p>I have attached the script which can only plot the 1st column vs 6th column. I ha...
<p>If I understood you correctly, you want to plot the observations in the first file, the corresponding observation in the second file and then the average between these two for all observations. A good way to do this is to first define a function that reads any of the files and format the data to numerical values usi...
python|matplotlib|average|standard-deviation
0
9,268
53,894,803
sqlalchemy onupdate inconsistent behavior for Query.update()
<p>I'm implementing a restful POST API with Flask, using sqlalchemy to update resource in PostgreSQL, say MyResource:</p> <pre><code>class MyResource(db.Model): __tablename__ = 'my_resource' res_id = Column(Integer, primary_key=True) &lt;other columns&gt; time_updated = Column(TIMESTAMP(timezone=True)...
<p>Similar problem is also observed for the other timestamp field to be populated with <code>default</code>, say... a record was inserted yesterday, but all records inserted today end up having the same <code>time_created</code> value as yesterday's value.</p> <pre><code>time_created = Column(TIMESTAMP(timezone=True),...
python|postgresql|sqlalchemy|flask-sqlalchemy
1
9,269
58,278,783
Using bqplot tooltip with a dataframe
<p>Use widget to display snippets from a csv file/dataframe and feed to tooltip attribute of bqplot</p> <p>I am trying to display certain info (statistics such as age group, income, obesity levels etc.) for each state in the US using bqplot. I am able to plot the US map using examples provided on bqplot github. But th...
<p>For Point 2:</p> <p>In your <code>hover_handler</code> code, you need to capture the information being passed through to the function, and use it to filter your master dataframe (<code>df</code>). Try changing your <code>hover_handler</code> code to the below, and see what info is being passed to the function. Then...
python|dictionary|tooltip|ipywidgets|bqplot
1
9,270
65,408,242
Pandas groupby multiple column then subplot
<p>I have a simple issue that I would appreciate if someone can help me with</p> <p>I'm grouping a dataframe by two columns to create a multiindex dataframe. Then, I want to create a bar plot for each each group:</p> <pre><code>df.groupby(['Teacher_name','Class_name'], sort = True).Student_ID.count() </code></pre> <p>H...
<p>You should install plotly and use the wonderful plotly express like this :</p> <pre class="lang-py prettyprint-override"><code>import plotly.express as px fig = px.histogram(df, x=&quot;Class_name&quot;, facet_col=&quot;Teacher_name&quot;) fig.update_layout(autosize=False, width=600, height=300) # resize figure fig....
python|pandas|group-by|pandas-groupby|subplot
2
9,271
45,649,856
pycrypto encrypt/decrypt, losing part of encrypted string when decrypting
<p>I am trying to encrypt/decrypt with pycrypto in python. for the most part things have worked smooth but I am getting an odd problem when decrypting data.I have tried to encrypt/decrypt some jpgs for testing and although they encrypt/decrypt without issue, the decrypted files cannot be opened/are corrupted. To try to...
<p>You have at least three issues:</p> <ul> <li><p>You probably mean <code>hashlib.sha256(encPW.encode('UTF-8')).digest()</code> instead of <code>hashlib.sha256(encPW.encode('UTF-8').digest())</code> (the closing brace is at the wrong position)</p></li> <li><p>You're encoding the ciphertext with Base64 before writing ...
python|encryption|pycrypto
1
9,272
28,638,813
How to make a short and long version of a required argument using Python Argparse?
<p>I want to specify a required argument called <code>inputdir</code> but I also would like to have a shorthand version of it called <code>i</code>. I don't see a concise solution to do this without making both optional arguments and then doing my own check. Is there a preferred practice for this that I'm not seeing or...
<p>For <em>flags</em> (options starting with <code>-</code> or <code>--</code>) pass in options <em>with</em> the flags. You can specify multiple options:</p> <pre><code>parser.add_argument('-i', '--inputdir', help="Specify the input directory") </code></pre> <p>See the <a href="https://docs.python.org/2/library/argp...
python|command-line-arguments|argparse
80
9,273
14,426,749
Python - Threading - Can I make a list of thread Queues?
<p>I'm making a threaded chat server and I need a way to send a message to all the clients. I could use a global queue but then only one of the threads handling the clients would be able to send the message. So I was wondering if its possible to create a separate queue object within each of the client threads and appen...
<p>Your approach is just fine. The only thing I would change is making <code>clientqueues</code> a <a href="https://stackoverflow.com/questions/3506150/static-class-members-python">static member</a> of <code>ClientThread</code> rather than a global variable.</p>
python|multithreading|list|queue
3
9,274
6,879,788
pexpect returning windows style end of line
<p>If anyone has used <code>pexpect</code> on linux have you notice that <code>pexpect</code> returns the window style end of line when using its <code>readline()</code> function? Do you know a way to get rid of this?</p>
<p>It's not only readline() that returns \r\n, all captured text returned by pexpect contains \r\n line endings.</p> <p>The documentation has the following explanation:</p> <blockquote> <p><strong>readline(self, size=-1)</strong></p> <p>This reads and returns one entire line. A trailing newline is kept i...
python|pexpect
2
9,275
57,235,908
Cannot create menu AttributeError: 'Frame' object has no attribute 'tk_menuBar'
<p>I am using the following snippet from a tutorial of Tkinter to create a Gui with a menu Bar. I copied exactly how it was in the tutorial: </p> <pre><code>from tkinter import * from tkinter import Menu from tkinter import Menubutton def new_file(): pass def open_file(): pass def stub_action(): pass ...
<p>You can still do the following</p> <p>if <strong>name</strong> == "<strong>main</strong>":</p> <pre><code>root = Tk() mBar = Frame(root, relief=RAISED, borderwidth=2) mBar.pack(fill=X) cmdBtn = makeCommandMenu() casBtn = makeCascadeMenu() chkBtn = makeCheckbuttonMenu() radBtn = makeRadiobuttonMenu() noMenu = makeD...
python|tkinter|menu
1
9,276
44,372,048
Python pandas Timestamp.week returns 52 for first day of year
<p>The code below returns <code>52 52</code>: how come?</p> <pre><code>import pandas as pd ts = pd.Timestamp('01-01-2017 12:00:00') print(ts.weekofyear, ts.week) </code></pre>
<p>This is correct, that's <a href="https://en.wikipedia.org/wiki/ISO_week_date" rel="noreferrer">ISO week date</a>.</p> <blockquote> <h3>Last week</h3> <p>The last week of the ISO week-numbering year, i.e. the 52nd or 53rd one, is the week before week 01. This week’s properties are:</p> <ul> <li>It has ...
python|pandas|datetime
16
9,277
61,671,227
How to call JS file/React code within Flask project? getting errors
<p>I'm currently trying to put together a Flask + React project. Just a simple Flask project, with some react code for the js part. </p> <p>I have had some difficulty getting the js file (which contains the react code) to run at all in the project.</p> <p>This is my project structure, standard for flask: <a href="htt...
<pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;title&gt;nstem&lt;/title&gt; &lt;link rel= "stylesheet" href= "{{ url_for('static',filename='css/nstem.css') }}"&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="indexBox1"&gt;&lt;/div&gt; &l...
javascript|python|reactjs|flask
-1
9,278
61,768,249
Scraping sitemap index URLs for status code with Beautiful Soup
<p>I'm trying to write a script given the following instruction:</p> <blockquote> <p>Scrape all the URLs into a sitemap index and store the information into an Excel file, specifying for each URL the corresponding status code.</p> </blockquote> <p>I managed to scrape all URLs and store them into a file, by the way,...
<pre class="lang-py prettyprint-override"><code>import requests from bs4 import BeautifulSoup import csv def main(url): with requests.Session() as req: r = req.get(url) soup = BeautifulSoup(r.content, 'html.parser') links = [item.text for item in soup.select("loc")] with open("data...
python|web-scraping|beautifulsoup|xml-sitemap
1
9,279
20,685,944
How to write select statement in sqlachemy
<p>I want to do the select statement in sqlachemy like</p> <pre><code>select user.id from user where user.name = 'test' </code></pre> <p>I loaded user table by:</p> <pre><code>User = Table('user',metadata,autoload=True) Result = session.query(User.c.id).filter_by(name='test').first() </code></pre> <p>I got an error...
<p>Solved:</p> <pre><code>r =session.query(statSoftware.c.id).filter(statSoftware.c.name=='Apache').first() </code></pre> <p>Using <code>filter()</code> instead of <code>filter_by()</code>, Allows to get all needed columns .</p>
python|sqlalchemy
1
9,280
35,849,217
Can't send E-Mails with Python
<p>I have this code as I am trying to send E-Mails using Python.</p> <pre><code>def Mail(): import smtplib import textwrap SERVER = "localhost" FROM = "fromemail" TO = ["toemail"] SUBJECT =(input('What is the subject of your E-Mail')) TEXT =(input('What do you want the E-Mail to say?')) me...
<p>The 'Connection unexpectedly closed' shows that the server is probably ON but unable to create a connection to smtplib.</p> <p>You could check the status of the port 25 smtp service to verify that,</p> <p><code># netstat -an | grep -i :25 tcp 0 0 127.0.0.1:25 0.0.0.0:* LIST...
python|email|smtp|smtplib
1
9,281
15,086,674
IronPython XML-Reader in .Net 2.0
<p>I created a XML-Reader that creates a pretty stupid formated List, the script thats goint to use it needs it this way though.</p> <pre><code>import xml.etree.ElementTree as ET PATH_IN = "&lt;Path&gt;\sweep.xml" tree = ET.parse(PATH_IN) root = tree.getroot() Input = [] for project in root: for design in proj...
<p>The basic issue here is that ElementTree uses expat for xml parsing, but expat (a C library made available to Python via a CPython wrapper) cannot be used from IronPython.</p> <p>However, ElementTree can use a different tree builder driven by a different parser, e.g. the XMLReader parser in .NET. A search for "xmlr...
python|xml|ironpython
1
9,282
15,106,584
Substring search for multiword strings - Python
<p>I want to check a set of sentences and see whether some seed words occurs in the sentences. but i want to avoid using <code>for seed in line</code> because that would have say that a seed word <code>ring</code> would have appeared in a doc with the word <code>bring</code>. </p> <p>I also want to check whether multi...
<p>Consider using a regular expression:</p> <pre><code>import re pattern = re.compile(r'\b(?:' + '|'.join(re.escape(s) for s in seed) + r')\b') pattern.findall(line) </code></pre> <p><code>\b</code> matches the <em>start</em> or <em>end</em> of a "word" (sequence of word characters).</p> <p>Example:</p> <pre><code...
python|string|nlp|mwe
3
9,283
15,408,933
Terminating generator expression
<p>I'm having a mental block, is there a usual python 1-liner for terminating a list comprehension or genex based on some condition? Example usage:</p> <pre><code>def primes(): # yields forever e.g. 2, 3, 5, 7, 11, 13 ... [p for p in primes() if p &lt; 10] # will never terminate, and will go onto infinite loop co...
<p>You can use <a href="http://docs.python.org/2/library/itertools.html#itertools.takewhile" rel="nofollow noreferrer"><code>itertools.takewhile</code></a>:</p> <pre><code>itertools.takewhile(lambda x: x &lt; 10, primes()) </code></pre> <p>or… if you want to avoid lambda:</p> <pre><code>itertools.takewhile((10.).__g...
python|generator
10
9,284
29,519,548
matlab equivalent of python sklearn train_test_split function?
<p>How can I get in matlab the equivalent of the python code</p> <p><code>x_train, x_test, y_train, y_test = sk.cross_validation.train_test_split(X,y)</code></p> <p>The train and test dataset should be randomly sampled because I will repeat this procedure more times to perform bootstrap.</p>
<p>Say you have 150 samples that you want to split into 100 samples for training and 50 samples for testing. You could just do:</p> <p>Python:</p> <pre><code>import numpy as np idx = np.random.permutation(range(len(y))) X_train, y_train = X[idx[:100]], y[idx[:100]] X_test, y_test = X[idx[100:]], y[idx[100:]] </code>...
python|matlab|scikit-learn|cross-validation
2
9,285
29,658,608
Inconsistent results from Django ORM
<p>Can anyone shed some light on this unusual behavior? I'm debugging a Django manager, and it seems to be the case that the ORM is changing the results it returns for the same query. Look at the following series of commands (run in the debugger during a test):</p> <p>The first line is a command which should return th...
<p>I was able to solve the issue by changing the <code>order_by('knz_updated_at)</code> clause to <code>order_by('knz_updated_at', 'id')</code>.</p> <p>It seems that, in cases where both objects were updated in the same second, the ORM can be ambiguous about what value it returns (since Django <code>DateTimeField</cod...
python|mysql|django|orm|django-orm
1
9,286
46,474,620
TemplateDoesNotExist at /accounts/register/ accounts/register.html
<p>why i still getting this error even though i already create register.html? i already read about this error and i already try to put in settings.py : <code>TEMPLATES_DIRS [ os.path.join(BASE_DIR, '/profiles/accounts/templates')]</code> and still nothing have changed .</p> <p>i try to create my own customize registra...
<p>This should help you out,</p> <blockquote> <p><a href="https://devdoodles.wordpress.com/2009/02/16/user-authentication-with-django-registration/" rel="nofollow noreferrer">https://devdoodles.wordpress.com/2009/02/16/user-authentication-with-django-registration/</a></p> </blockquote> <p>and you should define TEMP...
python|django|python-2.7|python-3.x|django-templates
0
9,287
61,173,101
I am trying to read a folder path but I am getting the 'str' has no attribute 'dir' error message
<pre><code>if __name__ == '__main__': args = "C:\Users\Ankuran Das\Desktop\Pyhton\holiday_100" working_folder = args.dir gmm = load_gmm(working_folder) if args.loadgmm else generate_gmm(working_folder, args.number) fisher_features = fisher_features(working_folder, gmm) classifier = train(gmm, fisher_features)...
<p>Your variable <strong>args</strong> is a simple string variable not an object with some attribute <strong>dir</strong>. Just change the line: <strong>working_folder = args.dir</strong> with <strong>working_folder = args</strong> and it should point to your desired directory.</p>
python
0
9,288
61,172,069
Extract polygon name if the geo-point is inside polygon?
<p>Extract polygon name if the geo-point is inside polygon ?. I have two dataset one with polygon name and polygon and other with location name and latitude and longitude.</p> <p>Data 1 (Geopandas Dataframe)</p> <pre><code>COMMUNITY NAME POLYGON New York MULTIPOLYGON (((55.1993358199345 25.20971347951325, ...
<p>Here is the answer to the above question. </p> <pre><code>Install these two packages to avoid the "Error" #!pip install rtree #conda install -c conda-forge libspatialindex Polygon Data (GeoDataFrame) data_poly = gpd.read_file("data.geojson") # Readonly the required columns # Drop NAN Location Data (Geo...
python|python-3.x|gis|geopandas|shapely
1
9,289
49,436,598
How do I print the variable values that result in the maximum of a function?
<p>I want to compute the maximum value of a function in python, then print the maximum value, as well as values of the variables at that maximum.</p> <p>I think I have gotten pretty far. In my example below, the function is just the values from <code>x</code> multiplied by the values from <code>y</code> multiplied by...
<p>The easiest way to do it would be to keep track of the values in the same way that you keep track of the current maximum:</p> <pre> def f(x,y,z): maximum = 0 for a in x: for b in y: for c in z: if a*b*c > maximum: maximum = a*b*c <b...
python|python-3.x|function|math|max
3
9,290
21,202,244
Fourier transform a trig function in Sympy returns unexpected result
<p>I think Sympy makes a mistake in calculating the <a href="http://docs.sympy.org/dev/modules/integrals/integrals.html#sympy.integrals.transforms.fourier_transform" rel="noreferrer">Fourier transform</a> of a trig function. For example:</p> <pre><code>from sympy import fourier_transform, sin from sympy.abc import x, ...
<p>SymPy computes the Fourier transform by literally computing the integral. I would consider this to be a bug, so feel free to open <a href="https://github.com/sympy/sympy/issues" rel="noreferrer">an issue</a> for it. </p>
python|integration|sympy|continuous-fourier
6
9,291
20,989,890
pyinotify can not watch current dir
<p>I put a script using pyinotify under my home dir (/home/name) and run it. While I can not make the script watch my home dir (/home/name) or dirs that contain my home dir, like root (/) and /home/. All other dirs are OK, like /var, /boot, /home/name/Documents.</p> <p>Let me describe it in a clean way:</p> <pre><cod...
<p>Think you need to specify a watch to your home dir.</p> <pre><code>wm.add_watch('/home', pyinotify.ALL_EVENTS, rec=True) </code></pre>
python|pyinotify
1
9,292
62,760,029
Trying to run simple script at python prompt but getting an error
<p><strong>Trying to run simple python file in python prompt but giving an error:</strong></p> <p><em>content of test.py</em></p> <pre><code>print(&quot;Trying to print this using .py file on anaconda prompt&quot;) </code></pre> <p><em>Running file from python prompt</em></p> <pre class="lang-none prettyprint-override"...
<p>You are trying to run it within the python interpreter. So just exit that and run the command on the terminal.</p>
python
0
9,293
54,975,541
Get Python turtle to face in direction of line being plotted
<p>I'm trying to get the turtle shape to follow the direction of a line.</p> <p>I have a simple parabola and I want the turtle shape to follow the direction of the line - when the graph goes up, the turtle faces up and when the graph comes down, the turtle faces down.<br> I am using <code>goto()</code> for the positio...
<p>I agree with @NicoSchertler that the arc tangent of the derivative is the way to go mathematically. But if it's just for good visuals, there's a simpler way. We can combine turtle's <code>setheading()</code> and <code>towards()</code> methods, constantly setting the turtle's heading towards the next position just ...
python|graphics|turtle-graphics
1
9,294
54,962,716
Bundle Python.exe with Jar
<p>I have created a Java application that executes a Python script using a runtime. I was wondering if there is a way to include the python.exe with the necessary libraries with the Jar file?</p>
<p>You should check whether it is the best option to bundle the windows specific python executable into your .jar file or if you want to use something like <a href="https://www.jython.org/" rel="nofollow noreferrer">jython</a> to execute python script from java.</p> <p>But to answer your question this mainly depends o...
java|python
0
9,295
21,616,839
Python/Pygame: Drawing graph origin mathematically?
<p>I am working on a graphing program that I am calling PyGraph. It allows you to create a graph of any size and draw on it, and later in development I will provide coordinates and things, but for now I have one question: How can I draw a intersecting lines through the center to represent the origin?</p> <p>Here is wh...
<p>The problem is that you draw the grid using the top left corner as your anchor. That is, all your grid rectangles have one corner in the top left. This becomes a problem when the distance between the center line and the screen edge is not divisible by the size - you can't divide a line of 640 units into even divisio...
python|math|graph|pygame
1
9,296
21,494,489
What does numpy.random.seed(0) do?
<p>What does <a href="https://numpy.org/doc/stable/reference/random/generated/numpy.random.seed.html" rel="noreferrer"><code>np.random.seed</code></a> do?</p> <pre><code>np.random.seed(0) </code></pre>
<p><code>np.random.seed(0)</code> makes the random numbers predictable</p> <pre><code>&gt;&gt;&gt; numpy.random.seed(0) ; numpy.random.rand(4) array([ 0.55, 0.72, 0.6 , 0.54]) &gt;&gt;&gt; numpy.random.seed(0) ; numpy.random.rand(4) array([ 0.55, 0.72, 0.6 , 0.54]) </code></pre> <p>With the seed reset (every ti...
python|numpy
792
9,297
24,898,459
Python: save a page with a lot of graphics as a .html file
<p>I want to save a visited page on disk as a file. I am using a urllib and URLOpener. I choose a site <a href="http://emma-watson.net/" rel="nofollow noreferrer">http://emma-watson.net/</a>. The file is saved correctly as .html, but when I open the file I noticed that the main picture on top which contains bookmarks ...
<p>What you're trying to do is create a very simple web scraper (that is, you want to find all the links in the file, and download them, but you don't want to do so recursively, or do any fancy filtering or postprocessing, etc.).</p> <p>You could do this by using a full-on web scraper library like <a href="http://scra...
python|python-2.7|beautifulsoup|urllib|urlopen
2
9,298
41,001,516
Create a aggregated matrix using Pandas
<p>I have the following <code>areaId</code> and <code>areaNo</code> information. I am trying to create a matrix with their aggregated values</p> <pre><code>areaId areaNo a1 01 a1 02 a1 02 b1 ...
<p>You could use <code>pd.crosstab</code></p> <pre><code>In [82]: df Out[82]: areaId areaNo 0 a1 1 1 a1 2 2 a1 2 3 b1 3 4 b1 3 5 b2 1 6 b2 3 In [83]: pd.crosstab(df['areaId'], df['areaNo']) Out[83]: areaNo 1 2 3 areaId a1 1 2 0 b1 ...
pandas|matrix|aggregate|divide
1
9,299
41,038,477
How to pass multiple arguments in os.system() in python 2.7 (Python Script).
<p>I am creating a python script where i needed to pass 2-3 arguments in os.system(). Suppose those commands/arguments are a,b. here A should execute first then B. Is there any solution for this ?</p>
<p>I don't really see the problem, you can just use the same commands as you would do on the command line. For instance:</p> <pre><code>import os os.system("ls -l &amp;&amp; echo \"hello\"") </code></pre> <p>Or if you want to execute the second command even though the first one failed:</p> <pre><code>import os os.sy...
python|python-2.7|os.system
1