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
7,900
51,813,744
Skipping sound track (pygame.mixer.music)
<p>I am making a snake game with pygame and I want to know something about <code>pygame.mixer.music()</code>.</p> <p>Code:</p> <pre><code>snakebodypos.insert(0, list(snakepos)) if snakepos[0] == foodpos[0] and snakepos[1] == foodpos[1]: pygame.mixer.music.stop() pygame.mixer.music.load(eatsound) pygame.m...
<p>Is there any reason you want to stop the background music while playing the <code>eatsound</code>?</p> <p>Your code does not work because after you load and play <code>eatsound</code>, you immediatly load <code>main</code> again, so <code>eatsound</code> has no time to play.</p> <hr> <p>Usually, you use <code>pyg...
python|python-3.x|pygame|mixer
2
7,901
40,753,561
Print int numpy array with distance
<p>I would like to print int <code>numpy.ndrray</code> with certain distance between elements. For example, for</p> <pre><code>a = np.array([2, 0, -1, -5, 3, 4]) print('a : {}'.format(a)) </code></pre> <p>I have <code>a : [ 2 0 -1 -5 3 4]</code></p> <p>How can I get, for example <code>a : [ 2 0 -1 -5 ...
<p>You can do this with formatting.</p> <pre><code>a = np.array([2, 0, -1, -5, 3, 4]) print(("a :" + " {:&gt;3}"*len(a)).format(*a)) a : 2 0 -1 -5 3 4 </code></pre> <p>The trick is to keep fixed portions separate, then replicate the {} portion by the number of elements in the array. The *a will pass on the...
numpy|int|pretty-print
0
7,902
44,290,877
How can i export csv into 3 columns instead of 2?
<p>I have two columns i am trying to separate, first i am getting rid of anything that has Jr and II, which works, and then i want to seperate the name into a separate tab</p> <p>The 2 tabs i have: Position Number, Name</p> <p>XXX-XXX-XXXX-XXX,"BLOOM, DANIEL ",,</p> <p>Would like the Name to be...
<p>Suppose I have:</p> <pre><code>$ cat file.csv PositionNumber, LastName, FirstName XXX-XXX-XXXX, "BLOOM, DANIEL" </code></pre> <p>You can do:</p> <pre><code>with open('/tmp/file.csv') as csvfile: r=csv.reader(csvfile) for row in r: row=[e.strip().strip('"') for e in row] print(row) ['Positi...
python-3.x|csv
0
7,903
44,305,723
Using MNIST TensorFlow example code for training a network with my own image dataset
<p>I have just begun to use TensorFlow in python. I want to build a binary image classifier using CNN. </p> <p>I found an example code on the internet: <a href="https://github.com/tensorflow/tensorflow/blob/r1.1/tensorflow/examples/tutorials/mnist/mnist_with_summaries.py" rel="nofollow noreferrer">https://github.com/t...
<p>This Get Started is just great to understand line by line and to go "deeper" into neural networks step by step.</p> <p><a href="https://www.tensorflow.org/get_started/" rel="nofollow noreferrer">https://www.tensorflow.org/get_started/</a></p> <p>Try to understand it, it will really help you :)</p>
image|tensorflow|classification|conv-neural-network|mnist
0
7,904
43,417,248
Exchangelib - Monitoring an exchange server mailbox, cannot connect to shared public folder
<p>I am trying to use exchangelib in order to monitor an e-mail address from a dedicated server without requiring an instance of Outlook be installed. </p> <pre><code>import exchangelib from exchangelib import DELEGATE, Account, Credentials, IMPERSONATION from exchangelib.configuration import Configuration credenti...
<p>Its not a direct answer as it didn´t use phyton here, but the following might be the solution for you, so I will post it here.</p> <p>You can access a shared folder via the Exchange Webservices (see the Documentation from Microsoft <a href="https://msdn.microsoft.com/en-us/library/office/jj945067(v=exchg.150).aspx"...
python|exchange-server|exchangewebservices|exchangelib
0
7,905
64,408,751
Python - Error500 trying to POST form using requests (Content-Type: multypart/form-data)
<p>I know this has been asked before here, but none of the solutions seem to work for me, so bare with me.</p> <p>I can post the same request with Curl and it works just fine, if I translate it to Python with <a href="https://curl.trillworks.com/" rel="nofollow noreferrer">https://curl.trillworks.com/</a> the syntax is...
<p>Removing 'Content-Type': 'multipart/form-data;' from the header made it work.</p> <p>I don't understand why it is working using curl with 'Content-Type': 'multipart/form-data;' , but it fails with Python. If anyone knows the reason, please let me know</p> <pre><code>import requests headers = { 'Authorization':...
python-3.x|python-requests
1
7,906
64,580,261
How to speed up python scripts by running simultaneously & sequentially
<p>I have an optimization program (currently a jupyter notebook that outsources the optimization itself to gurobi cloud) that I need to run many iterations of. So far, I've tried running multiple versions of the same script simultaneously overnight. However, this taxes my computer (ie, it's crashed once or twice, and i...
<p>I'm not sure about the file-splitting specifically but here are a couple of other things that could be good to try,</p> <ol> <li><a href="https://www.gurobi.com/documentation/9.0/refman/threads.html#parameter:Threads" rel="nofollow noreferrer">Reduce the number of threads</a></li> <li>Set the solve method=1, <a href...
python|performance|gurobi
0
7,907
70,669,036
Torch Tensor with same shape but different storage size
<p>I'm working on GANs model, the generator creates a tensor with size <code>(3,128,128)</code> which I dumped with the pseudo-code</p> <pre class="lang-py prettyprint-override"><code>import torch image = Generator(noise).clone() tensor = image[0].detach().cpu() torch.save(tensor, save_path) </code></pre> <p>The proble...
<p>It seems like extracting a sub-tensor directly from the original will bring the whole container with it. The function <code>.clone()</code> can solve it. Example:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; import torch &gt;&gt;&gt; tensor = torch.randn(10,3,128,128) &gt;&gt;&gt; sys.getsizeof(tensor.storage...
python|machine-learning|deep-learning|pytorch
0
7,908
69,917,767
numpy array position of each element along one axis
<p>I've got a numpy 2D array, let's say</p> <pre><code>a = np.arange(1,7).reshape(2,3) array([[1, 2, 3], [4, 5, 6]]) </code></pre> <p>and I'd like to have an array with the position of each element of this array along one axis like so:</p> <pre><code>array([[0, 1, 2], [0, 1, 2]]) </code></pre> <p>I need t...
<p>Use <a href="https://numpy.org/doc/stable/reference/generated/numpy.tile.html" rel="nofollow noreferrer"><code>np.tile</code></a>:</p> <pre><code>import numpy as np a = np.arange(1,7).reshape(2,3) n_rows, n_cols = a.shape res = np.tile(np.arange(n_cols), (n_rows, 1)) print(res) </code></pre> <p><strong>Output</str...
python|arrays|numpy
2
7,909
55,864,512
How to use "mesh" in kivy file instead on python file
<p>I am trying to draw a custom shape with kivy using "mesh" in python. I did some research on this but most of the result is just write the code in the python file</p> <p>The code from <a href="https://kivy.org/doc/stable/examples/gen__canvas__mesh__py.html" rel="nofollow noreferrer">here</a> and <a href="https://blo...
<p>You just forgot to put it into a canvas. And I added the <code>triangle_fan</code> mode, to make it into polygon. Just guessing that is what you want.<br> Try this:</p> <pre><code>from kivy.app import App from kivy.lang import Builder KV = """ &lt;MainScreen@Screen&gt;: name: "main" canvas: Mesh:...
python-3.x|kivy|mesh
0
7,910
55,818,276
Groupby and find the difference
<p>I have a pandas DF:</p> <pre><code>df = pd.DataFrame(np.random.randint(1,10,size=(6,2)),columns = list("AB")) df["A"] = ["1111","2222","1111","1111","2222","1111"] df["B"] = ["2001-01-10","2001-01-02","2001-02-11","2001-03-14","2001-02-01","2001-04-14"] df </code></pre> <p>OP:</p> <pre><code> A B 0 ...
<p>This finds the max difference between dates for given group.</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(np.random.randint(1,10,size=(6,2)),columns = list("AB")) df["A"] = ["1111","2222","1111","1111","2222","1111"] df["B"] = ["2001-01-10","2001-01-02","2001-02-11","2001-03-14","2001-02...
python-3.x|pandas|pandas-groupby
1
7,911
73,428,160
How does copying dataframes in different ways affect memory consumption?
<p>I am trying figure out how different ways of copying pandas dataframes affect the memory consumption of a python script using the <a href="https://github.com/pythonprofilers/memory_profiler" rel="nofollow noreferrer">memory_profiler</a> package:</p> <pre class="lang-py prettyprint-override"><code>from copy import de...
<p>i can tell just by inspection that the numbers you got are no where near correct, and you might want to submit an issue to the profiler module creators, anyway, you can request the program consumption from the operating system using <code>psutil</code>, and if you just want to do some simple benchmarking (non produc...
python|pandas|memory-profiling
2
7,912
66,745,103
Find roots of a polynomial function Python Sympy
<p>I try to find the roots of a polynomial function and i use this code:</p> <pre><code>import sympy from sympy import Poly, roots g=sympy.var(&quot;x&quot;) p = Poly(x**25-96*x**12-4*x**3+2, gen=g) print(roots(p)) </code></pre> <p>i don't know why it not works. If i use an easier polynomial function like x**2-1 it wor...
<p>The <code>roots</code> function is for computing roots symbolically in radicals. It is usually not possible to compute roots in radicals for polynomials of degree 5 or more due to the Abel-Ruffini theorem. SymPy's <code>RootOf</code> can represent those roots symbolically e.g.:</p> <pre><code>In [7]: r = RootOf(x**2...
python|sympy|polynomials
2
7,913
66,542,526
How to configure Gcloud Python Pyca library
<p>I am having trouble importing the key to the Google Cloud KMS. How to get the key imported to gcloud KMS?</p> <p>Even if latest version of pyca library is installed then still no attribute 'aes_key_wrap_with_padding' is found. When removing pyca from pip and from ubuntu 20.04 then still the gcloud cli is able to fin...
<p>I think you have to install Pyca cryptography library. In Google Documentation in Importing key section there is <a href="https://cloud.google.com/kms/docs/crypto" rel="nofollow noreferrer">article</a> about it:</p> <blockquote> <p>update the gcloud command-line tool to enable support for automatically wrapping keys...
python|ubuntu|cryptography|gcloud
0
7,914
64,838,325
How to keep track of a changed element in a list
<p>For this program, I am using a list with 4 elements. When I change one, I would like to perhaps put it in a variable to know which element got changed. For example:</p> <p>Original list: ['B', 'B', 'B', 'B'] New list: ['*', 'B', 'B', 'B']</p> <p>So with this, how can I let my program know that element 0 got changed?...
<p>You can make a subclass of <code>collections.UserList</code> and override the methods you will be using to change the list. This will allow you to insert behavior into those methods. If you make sure to call the method on <code>super()</code>, the normal list behavior will stay the same. For example, since we don't ...
python
1
7,915
64,634,755
MRJob: I'm having a client error while using EMR
<p>I'm a newbie in mrjob and EMR and I'm still trying to figure out how things work. So I'm having this error when I'm running my script:</p> <p><code>python3 MovieSimilarities.py -r emr --items=ml-100k/u.item ml-100k/u.data &gt; sims2t.txt</code></p> <pre><code>No configs found; falling back on auto-configuration No c...
<p>the botocore package is actually deprecated, any since that module relies on the botocore package, that module is now broken. Sorry for the inconvenience.</p>
python|amazon-web-services|amazon-emr
0
7,916
64,704,180
Why Python subprocesses won't properly capture signals?
<p>Let's have a tiny little program that is supposed to capture (and ignore) SIGTERM signal:</p> <pre class="lang-py prettyprint-override"><code># nosigterm.py: import signal import time def ignore(signum, frame): print(&quot;Ignoring signal {}&quot;.format(signum)) if __name__ == '__main__': signal.signal(si...
<p>This is a race condition.</p> <p>You are forking and immediately sending the signal, so it's a race for the child process to ignore it before it gets killed.</p> <p>Furthermore, your parent script has a race condition in checking whether the script has died. You signal the script and immediately check if it's dead, ...
python|linux|subprocess|signals|posix
3
7,917
63,970,364
Unable to determine cause of SyntaxError: on line 17, <=100
<p>I am having syntax errors on the below code and can't determine why. Additionally, if I comment out the <code>elif</code> statements, my line 12 does not actually add the variables together.</p> <pre><code>#Define variables and collect inputs points = int(input(&quot;How many points do you have?: &quot;)) years = ...
<p>This is the correct syntax</p> <pre><code>if points &lt;= 50: points_discount = 0.00 elif points &gt; 50 and points&lt;= 100: points_discount = 0.10 elif points &gt;100 and points &lt;=200: points_discount = 0.20 </code></pre>
python
1
7,918
53,211,843
Trying to translate an old pascal script to python: problems with pascal "record"
<p>i'm currently tasked with translating an old pascal script to python. Problem is, i don't have any of experience with pascal... Until now, all went fine (most of the script is pretty self-explanatory), but now i encountered a small snippet of code which i just can't figure out:</p> <pre><code># some other code here...
<p>Pascal's <code>record</code> is like Python's <a href="https://stackoverflow.com/questions/2970608/what-are-named-tuples-in-python"><code>namedtuple</code></a>. One record (namedtuple) is read field by field (hence <code>temp.lambda</code>, <code>temp.value</code>) in <code>readLn</code> function.</p> <p><code>Refl...
python|python-3.x|pascal
1
7,919
65,453,598
How to get multiple keybindings to work simultaniously in turtle graphics?
<p>I am making a game in python called pong.</p> <p>Can I get 2 different turtles in turtle graphics to respond simultaneously to keybindings?</p> <p>Here is the code:</p> <pre><code>import turtle class paddle(turtle.Turtle): def __init__(self, x_cord, keybindings): super().__init__(&quot;square&quot;) ...
<p>This was once a problem I struggled with for a long time, and came to the conclusion that it's not possible <em>(please prove me wrong, as I'm interested in the solution if there is one)</em>.</p> <p>I've analyzed <a href="https://stackoverflow.com/a/47894123/13552470">this</a> great answer that explains how to bind...
python|python-3.x|turtle-graphics|pong|python-turtle
1
7,920
65,360,877
Dynamically create string from pandas column
<p>I have two data frame like below one is df and another one is anomalies:-</p> <pre><code>d = {'10028': [0], '1058': [25], '20120': [29], '20121': [22],'20122': [0], '20123': [0], '5043': [0], '5046': [0]} df = pd.DataFrame(data=d) </code></pre> <p>Basically anomalies in a mirror copy of df just in anomalies...
<p>Try this:</p> <pre><code># first part of the string s = '\n' + 'Metric Name' + '\t' + 'Count' + '\t' + 'Anomaly' # dynamically add the data for idx, val in df.iloc[-1].iteritems(): s += f'\n{idx}\t{val}\t{anomalies[idx][0]}' # for Python 3.5 and below, use this # s += '\n{}\t{}\t{}'.format(idx, val, a...
python|python-3.x|pandas|dataframe|numpy
2
7,921
65,427,310
add a line break ( \n=) in a sorted( list of tuples)
<p>Is there a way to add a line break in the result of a sorted applied to a list of tuples ?</p> <p>my list of tuples :</p> <pre><code>b1 = (&quot;&amp;#20843&quot;, 222, 133, 343) b1a = (&quot;&amp;#20023&quot;, 3001, 61, 0) b2 = (&quot;&amp;#24052&quot;, 610, 33, 281) b3 = (&quot;&amp;#30333&quot;, 287, 70, 838) b4 ...
<p>If you just want one tuple per line, then you can join the reprs with a newline:</p> <pre class="lang-py prettyprint-override"><code>result = sorted(hanzi, key=lambda hanzi: hanzi[2]) print(&quot;\n&quot;.join(repr(x) for x in result)) </code></pre> <p>Or, with <code>sep</code>:</p> <pre class="lang-py prettyprint-o...
python|line-breaks|sortedlist
2
7,922
65,314,107
Python suddenly cannot find files only when I want to rename or copy them
<p>I'm trying to very simply copy a load of files from one directory to another and then rename the files (to replace whitespaces and %20 with _). In my root directory, I have:</p> <ul> <li>optimiser.py (what I use to run the script)</li> <li>Folder (named 'Files to Improve' containing basic text files)</li> <li>Folder...
<p>Change your</p> <pre><code>copyfile(f, finished_files_dir) #error 1 </code></pre> <p>to</p> <pre><code>copyfile(os.path.join(files_to_improve_dir, f), os.path.join(finished_files_dir, f)) </code></pre> <p>and</p> <pre><code>os.rename(f, new_filename) #error 2 </code></pre> <p>to</p> <pre><code>os.rename(os....
python
1
7,923
71,955,178
Reshape DataFrame, 4 columns -> 3, replacing np.nan with value in next column
<p>I have a dataframe with rows containing 2-3 values, spread over 4 columns. How do I reshape the dataframe, so that I only have 3 columns with values.</p> <p>Example dataframe:</p> <pre><code>d = {'col1': [1, 2,np.nan,4], 'col2': ['a',np.nan,'d', 'f'], 'col3': [np.nan,'x',np.nan,'v'], 'col4': ['q','w',...
<p>You can apply <code>dropna</code> and reset the index per row, finally rename the columns to original values:</p> <pre><code>d = dict(enumerate(df.columns)) df2 = (df.apply(lambda s: s.dropna() .reset_index(drop=True), axis=1) .rename(columns=d) ) </code></pr...
python|python-3.x|pandas|dataframe
2
7,924
68,771,119
Wanting to Scrape all "li" elements. Python
<p>I am just a real novice when it comes to python but I am really enjoying the learning process. I am interested in data analysis and all I am trying to do is scrape list elements of a wikipedia page.</p> <p>I have managed to pull the list and prettify it via:</p> <pre><code>music_box = soup.find(class_=&quot;div-col&...
<p>You don't need to use <code>row.find(&quot;li&quot;)</code> to select <code>&lt;li&gt;</code> again, as you have selected them in <code>music_rows = music_box.find_all(&quot;li&quot;)</code>. <code>row.find(&quot;li&quot;)</code> will find <code>&lt;li&gt;</code> in <code>row</code>'s children, not itself. You can t...
python|html|python-3.x|list|beautifulsoup
1
7,925
10,709,986
Broken Python 2.7 GAE installation causing ImportError
<p>Gae sdk was running without errors (using 2.7 and webapp2), but stopped suddenly. Now I cannot even get the example from <a href="https://developers.google.com/appengine/docs/python/gettingstartedpython27/helloworld" rel="nofollow">the getting started page</a> to work. </p> <p>I've done clean installs of both pyth...
<p>I had the same issue and fixed by removing PYTHONPATH from from environment variables. I am installing SimpleCV and the problem come from it.</p> <p>Go to System => Advanced System Parameters => environment variables, then in user variables look for PYTHONPATH and remove it. Restart Google AppEngine and it should w...
python|google-app-engine|windows-7|python-2.7
-1
7,926
4,882,569
Python, splitting strings
<p>I have a large string text file, I would like to split the string every 117 characters and put the next 117 chars on a newline, and so on until the end of the file. </p> <p>I tried this:`s = """ I have removed the string for visibility reasons """ space = """</p> <p>""" file = open('testoutput.txt', 'w') while s: ...
<pre><code>while s: print s[:117] s = s[117:] </code></pre>
python|string|split
6
7,927
62,625,910
Extend list to json file in Python
<p>I've got a array saved in a json file looking like this <code>[4.810,-75.700,0.020,11,5.070,-75.520,0.010,11]</code>. I'm using Python to append new 4-tuples to this array.</p> <pre><code>globe_list = [18.110,-66.170,0.000,11] json_array = json.dumps(globe_list) with open(webgl_file_path + 'tweet_locations.json'...
<p>You could try moving the file pointer to the position of the final &quot;]&quot;, and then writing the additional json, without the initial &quot;[&quot;, like this:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import io &gt;&gt;&gt; with open('example.json', 'rb+') as f: ... f.seek(-1, io.SE...
python|json|python-3.x|file|extend
6
7,928
67,333,855
How to convert 3D Numpy array into greyscale vtkImageData to use in pyQT
<p>I have a 3D numpy array which I am trying to convert into a <code>vtk</code> object to use within pyQT. The code that I have works in that it is showing the volume, but I need the volume to be in greyscale. Can anyone please point me towards what I need to add, or if I am going about this the complete wrong way. Apo...
<p>Why type of greyscale do you want? Unsigned char? Unsigned short? Integer?</p> <p>Whichever type you want set the array_type parameter in the numpy_to_vtk function call. That should get you the grayscale image that you want.</p> <p>Just make sure that the pixel type you choose has the proper range for your input ...
python|pyqt|vtk
0
7,929
67,508,441
Writing to csv file with itertools.product
<p>I have created a script with unique combinations, but I'm stuck on how to go about writing it into a csv file. Right now it's just printing out in my command line and hard to get a good grasp of the data.</p> <p>My code:</p> <pre><code>from itertools import combinations, product crust = ['Thin Crust', 'Hand Tossed'...
<p>Here is the code. It will open the csv file and write it with each iteration of the for loop. You will see one item in each cell as it was given in the terminal.</p> <pre><code>from itertools import combinations, product import csv crust = ['Thin Crust', 'Hand Tossed'] topping = ['Bacon', 'Pepperoni', 'Steak'] sauce...
python-3.x|csv|export-to-csv|itertools
1
7,930
60,736,955
How to connect pydrive with an Service Account
<p>Does anyone have any example or documentation how to connect a Service Account from Google Drive API with <code>pydrive</code>. I managed to do it with auth2 client.</p>
<p>Apparently this should work, but it does not:</p> <pre class="lang-py prettyprint-override"><code>from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from oauth2client.service_account import ServiceAccountCredentials gauth = GoogleAuth() scope = [&quot;https://www.googleapis.com/auth/drive&quo...
python-3.x|pydrive
4
7,931
60,450,783
exclude latest date pandas
<p>I have df that looks like this:</p> <pre><code> Date Value 49 2018-11 6 50 2018-12 8 51 2018-12 2 52 2018-12 5 53 2018-12 2 54 2018-12 14 55 2019-01 8 56 2019-01 20 57 2019-01 5 58 2019-02 2 59 2019-02 5 61 20...
<p>Convert column to datetimes and filter all rows with maximal datetimes by <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> and filter all rows not equal by <a href="http://pandas.pydata.org/pandas-docs/stable/r...
python|pandas
1
7,932
70,302,684
Why does my k-means convergence condition give different results than sklearn?
<p>I've written a function that executes k-means clustering with <code>data</code>, <code>K</code>, and <code>n</code> (number of iterations) as inputs. I can set <code>n=100</code> so that the function calculates Euclidean distance, assigns clusters and calculates new cluster centroids 100 times over before completing...
<p>K-means is a non deterministic algorithm. If you don't have the same initialization than in scikit-learn, you are not sure to find the same clusters. In scikit-learn documentation, it is written :</p> <blockquote> <p>Given enough time, K-means will always converge, however this may be to a local minimum. This is hig...
python|scikit-learn|while-loop|k-means|convergence
1
7,933
70,338,690
wondering about pixel perfect mousepointer collision in the case of a button
<p>I've got a pretty simple code up right now that just moves between two menu screens once the button for each is pressed. I know that you can mask images in pygame to get pixel perfect collision but not sure how I'd go about doing it for the buttons in this code (it's just pretty annoying that you can click slightly ...
<p>To test whether the mouse is on an icon, you need to create a mask from the image (<a href="https://www.pygame.org/docs/ref/surface.html" rel="nofollow noreferrer"><code>pygame.Surface</code></a>) with <a href="https://www.pygame.org/docs/ref/mask.html#pygame.mask.from_surface" rel="nofollow noreferrer"><code> pygam...
python|pygame
1
7,934
11,335,830
Importing another module from another subdirectory of the current directory's parent directory (python)
<p>I'm attempting to write a game. I therefore have lots of different types of code and want to arrange them in a useful hierarchy.</p> <p>I've looked at solutions that involve placing <code>__init__.py</code> in each folder but I'm still somewhat confused, though not as much as the python interpreter. </p> <p>Now su...
<p>It is not possible with the normal import mechanism unless you make <code>Game</code> a package (i.e., by putting an <code>__init__.py</code> inside the <code>Game</code> directory). The python relative import system only works <em>within packages</em>. It is not a general system for referring to arbitrary modules...
python|import|module|path
1
7,935
11,354,171
Writing a thin object proxy by implementing the __get__ descriptor
<p>I'm trying to create a think proxy using the <a href="http://docs.python.org/reference/datamodel.html#object.__get__" rel="nofollow"><code>__get__</code></a> descriptor over a certain type of data so that it can be used conveniently by client code (best shown with an example):</p> <pre><code>class Value(object): ...
<p>You need to add an additional proxy if you want to proxy the array accessor as well. Here's an example using property() for x since it's just an attribute, and an array proxy accessor for y.</p> <p>self._<em>x and self.</em>_y are the internal, private accessors for the true Value's</p> <pre><code>import functools...
python|selenium
2
7,936
11,325,694
How toget a list of "fastest miles" from a set of GPS Points
<p>I'm trying to solve a weird problem. Maybe you guys know of some algorithm that takes care of this.</p> <p>I have data for a cargo freight truck and want to extract some data. Suppose I've got a list of sorted points that I get from the GPS. That's the route for that truck:</p> <pre><code>[ { "lng": "-...
<p>If you have locations and timestamps for when the location data was fetched, you can simply do something like this:</p> <pre><code>def CalculateSpeeds(list_of_points_in_time_order): """Calculate a list of (average) speeds for a list of geographic points.""" points = list_of_points_in_time_order segment_start...
python|algorithm|geolocation
1
7,937
17,824,102
ompi_evesel->dispatch() failed when running OpenMPI process from Java ProcessBuilder
<p>I am trying to create a Java GUI to control and run an MPI process. I can run an MPI process from my command line, but am unable to run via the Java Process Builder.</p> <p>I get the following error immediately after the process starts:</p> <pre><code>[SCI053_VM003:02928] ..\..\openmpi-1.6.4\opal\event\event.c: om...
<p>I suspect that the issue is because you're using Windows. I don't remember when OpenMPI stopped supporting Windows, but at some point it did. You might try using Microsoft's port of MPICH that works on Windows and see if that does what you need. I don't remember the URL offhand, but you can find the port at the MPIC...
java|python|windows|processbuilder|openmpi
0
7,938
17,959,255
python if and else statements calculating employees pay
<p>I'm having a little trouble with this assignment its about calculating the employees pay it goes like Write a Python program that prompts the user for an hourly rate and a number of hours worked and computes a pay amount. Any hours worked over 40 are paid at time and a half (1.5 times the normal hourly rate). Write...
<p>If you need to input both the <em>hours</em> and <em>rate</em> from the user, you can do so like this:</p> <pre><code>hours = int(input('how many hours did you work? ')) rate = int(input('what is your hourly rate? ')) </code></pre> <p>Then once you have those variables, you can start by calculating the overtime.</...
python
3
7,939
61,045,445
tkinter not executing function properly
<p>I'm having a weird issue with the tkinter script below. If the outcommented lines are executed, it is showing the image like intended. When I call the function instead, it doesn't. The main window i opened and nothing else happens. 'Function called' is being printed in the Shell though. Am I missing something basic ...
<p>The photo <code>img</code> gets removed by garbage collection because it is a local variable. To fix this add <code>background_label.img = img</code> at the end of the function, this stops the image from being removed by garbage collection.</p>
python|function|tkinter
0
7,940
66,071,440
Matplotlib not showing one point
<p>I am trying to plot a line x log scale but the first point is not being shown although the scale is correct. The value for x == 0 is 1.57 and the value for x == 10^(-8) is 0.4.</p> <p>How can I correct the plot ?</p> <pre><code> plt.plot(lambdas, errors, &quot;-b&quot;, label = 'Test') plt.plot(lambdas,error...
<p>You can use a <a href="https://matplotlib.org/api/scale_api.html#matplotlib.scale.SymmetricalLogScale" rel="nofollow noreferrer"><code>symlog</code></a> scale and set the linear threshold (minimum value below which the scale changes to a linear scale) as needed:</p> <pre><code>import matplotlib.pyplot as plt plt.pl...
python|matplotlib
2
7,941
72,831,018
How to map virtual environment's Python instead of the global on Windows production server for a django project
<p>I have a Django project running on the production on Windows 10. I am using nginx and waitress.</p> <p>I've been using the global Python on my server (Python 3.9.5). I was wondering how I can use a virtual environment instead of the global on the production server? I can't figure out how I can map my django applicat...
<p>You could use a startup script or a Windows task to automatically activate the virtualenv before running your project. This is a good example for using Waitress: <a href="https://stackoverflow.com/a/27075908/16822178">https://stackoverflow.com/a/27075908/16822178</a> Or like this for a scheduled task at startup: <a ...
python|django|virtualenv|production-environment
0
7,942
72,608,849
torch dataset error -- 'numpy.int32' is not callable
<p>I'm preparing a set of medical imaging volumes and segmentation masks to be input into a multi-label segmentation neural network for training. I am recieving the following error message when I attempt to load my 5D tensors into a torch TensorDataset:</p> <pre><code>Traceback (most recent call last): File (path/pro...
<p><code>size</code> is a tuple, <code>all(tensors[0].size[0] == tensor.size[0] for tensor in tensors),</code></p>
python|numpy|tensorflow|pytorch|dataset
0
7,943
68,034,406
Constructing Binary Tree from Preorder and Inorder Traversal
<p>I'm trying to make the postorder of binary tree from its preorder and inorder traversal. but i don't have any idea how am i suppose to do that and what should be the structure of my code. any help can be useful.</p> <p>for example :</p> <p>input:</p> <p>preorder : 6 2 1 4 3 5 7 9 8</p> <p>inorder : 1 2 3 4 5 6 7 8 ...
<ul> <li>Select first element from preorder list and increment the preorder index.</li> <li>Create a Binary tree node (new_node) and set the value as selected preorder list value.</li> <li>Find the selected element index(inorder_index) in Inorder list.</li> <li>Call recursive function again with left side of inorder_in...
python|data-structures|binary-tree|tree-traversal
0
7,944
68,423,977
Django REST framework TokenAuthentication returns anonymous user
<p>How do I properly implement DRF TokenAuthentication without the request object returning an anonymous user when I try to log in?</p> <p>according to the <a href="https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication" rel="nofollow noreferrer">docs</a>, when authenticated, the <code>Toke...
<p>Since you are using Token authentication, your users will be authenticated with the token in the header, for each request.</p> <p>Django <code>login()</code> is useful in case of SessionAuthentication. Where user is stored in the session object in django, identified by the session cookie.</p> <p>In your view, you do...
python|django|django-rest-framework|django-views|http-token-authentication
1
7,945
59,469,334
Flask-WTF selectfield with UUID
<p>I am using sqlalchemy and use UUID for the primary keys in my database (postgres)</p> <p>Here is my class:</p> <pre class="lang-py prettyprint-override"><code>class EntityType(db.Model): __tablename__ = 'entity_type' id = db.Column(UUID(as_uuid=True), primary_key=True, server_default=db.text('gen_random_u...
<p>Have you tried either converting your database to string so that it play nice with the web:</p> <pre><code>def default_uuid(): return uuid.uuid4().hex class EntityType(db.Model): __tablename__ = 'entity_type' id = db.Column(db.String, primary_key=True, default=default_uuid) </code></pre> <p><strong><e...
python|flask|sqlalchemy|flask-wtforms|wtforms
1
7,946
63,185,073
Convert python signing code to javascript
<p>I'm currently working on a code generator and porting it over to javascript, however I can't seem to get the same results?</p> <p>The code which I've got in Python is the following:</p> <pre class="lang-py prettyprint-override"><code>def sign(self, cs, api): temp_string = &quot;&quot; cs_length = len(cs) ...
<p>Your issue appears to be your conversion from this Python code</p> <pre class="lang-py prettyprint-override"><code>new_char = chr(new_code) </code></pre> <p>To JavaScript</p> <pre class="lang-js prettyprint-override"><code>new_char = new_code.charCodeAt(0); </code></pre> <p>Given that <a href="https://docs.python.or...
javascript|python
2
7,947
35,538,778
Mask Image region for Otsu Threshold with OpenCV
<p>I have images were certain regions are set to 255 to not interfere with the region of interest. When doing an Otsu threshold, these regions offset the threshold value. </p> <p><a href="https://i.stack.imgur.com/JzjM7.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JzjM7.jpg" alt="Image with white...
<p>After following the answer Miki linked, I realized that one can index with conditions in Python. The explicit loop takes a second, the indexing is miliseconds. </p> <pre><code> tempThresImg = img[img != 255] </code></pre>
python|python-2.7|opencv|image-processing
1
7,948
58,795,086
Python: Convert a byte array back to list of int
<p>I can convert a list of ints into a byte array with the following:</p> <pre><code>bytes([17, 24, 121, 1, 12, 222, 34, 76]) Out[144]: b'\x11\x18y\x01\x0c\xde"L' bytes([1, 2, 3]) Out[145]: b'\x01\x02\x03' </code></pre> <p><strong>What I want now is to get the byte array string back to its original list</strong>. Is ...
<p>You can convert the bytearray to a list of ints with <code>list()</code></p> <h3>Test Code:</h3> <pre><code>x = bytes([17, 24, 121, 1, 12, 222, 34, 76]) print(x) print(list(x)) </code></pre> <h3>Results:</h3> <pre><code>b'\x11\x18y\x01\x0c\xde"L' [17, 24, 121, 1, 12, 222, 34, 76] </code></pre>
python|arrays
3
7,949
58,682,842
Why do I get 'Float object is not callable' error
<p>I'm getting this error in my code: </p> <pre><code>Test Failed: 'float' object is not callable. </code></pre> <p>My code is as follows:</p> <pre><code>import math class Person: def __init__(self, name, age): self.name = name self.age = age def std_dev(persons): persons_age = [person.age ...
<p>This simple example reproduces your error:</p> <pre><code>In [101]: x = 1.23 In [102]: x() --------------------------------------------------------------------------- TypeError ...
python
0
7,950
31,280,465
IPython notebook connection failed issue
<p>This is probably very simple; and I am embarrassed to ask; but I spent a long time trying to solve it already. I am trying to use an IPython notebook and on the click to get a Python 3 notebook, I often (but not always) get:</p> <blockquote> <p>Connection failed</p> <p>A connection to the notebook server could not b...
<p>Downgrade <em>Tornado</em> to 5.1.1 from 6.0, that will solve it.<br> Apparently, <em>Tornado</em> 6.0 breaks notebook.</p>
python-3.x
7
7,951
15,588,724
Working locally on web-application
<p>I have been added as developer on application. </p> <p>On Applications Overview this app is shown together with my other app, that I can freely access and change via Google App Engine Launcher.</p> <p>Question is how to get app I'm supposed to work on my computer locally(in other words in GAE), so I can test and c...
<p>You can use the appcfg application (the one that handle uploads) to <a href="https://developers.google.com/appengine/docs/python/tools/uploadinganapp#Downloading_Source_Code" rel="nofollow">download the source code</a>.</p> <p>This only works if the administrator has not disabled it.</p> <p>However, it would be be...
python|google-app-engine|web-applications
0
7,952
15,899,701
Optimise two SQL queries and a list comprehension
<p>I have those two models (simplified):</p> <pre><code>class Place(OrderedModel): name = models.CharField(max_length=100) class Team(models.Model): name = models.CharField(max_length=100) places = models.ManyToManyField(Place, blank=True) </code></pre> <p>Say that there are ten instances of <code>Place<...
<p>You need this SQL query:</p> <pre class="lang-sql prettyprint-override"><code>SELECT P.id, (TP.id IS NOT NULL) AS done FROM myapp_place P LEFT OUTER JOIN myapp_team_places TP ON P.id = TP.place_id AND TP.team_id = %s </code></pre> <p>(You'll also need to add an <code>ORDER BY</code> clause to return the <code>Plac...
python|django|optimization
1
7,953
15,530,071
Scrapy Case : Incremental Update of Items
<p>Please help me solve following case:</p> <p>Imagine a typical classified category page. A page with list of items. When you click on items you land on internal pages.Now currently my crawler scrapes all these URLs, further scrapes these urls to get details of the item, check to see if the initial seed URL as any ne...
<p>Before trying to give you an idea...</p> <p>I must say I would try first your database option. Databases are made just for that and, even if your DB gets really big, this should not do the crawling significantly slow. And one lesson I have learned: "First do the dumb implementation. After that, you try to optimize....
python|screen-scraping|scrapy
2
7,954
59,537,827
Cython: How user-defined conversion of C++-classes can be used?
<p>Cython's <a href="https://cython.readthedocs.io/en/latest/src/userguide/wrapping_CPlusPlus.html#overloading-operators" rel="nofollow noreferrer">documentation</a> seems to be silent about how <a href="https://en.cppreference.com/w/cpp/language/cast_operator" rel="nofollow noreferrer">user-defined conversion</a> can ...
<p>Looking only at the <code>bool</code> case:</p> <ol> <li><p>I'm not convinced <code>print(x)</code> should convert it to bool anyway. <code>print(x)</code> looks for a conversion to a Python object (and OK, <code>bool</code> can be converted to a Python object, but it's somewhat indirect). Python itself uses the <c...
python|c++|cython
2
7,955
49,221,791
Serverless create command not working
<p>I have installed node.js and the serverless framework. If I type: </p> <pre><code>serverless --version </code></pre> <p>Its showing the output as 1.26.1. However if I run the command below:</p> <pre><code>serverless --create --template aws-python3 --name numpy </code></pre> <p>Its throwing the o/p </p> <pre><co...
<p>create should be without hyphens -- </p> <pre><code>serverless create --template aws-python3 --name numpy </code></pre>
node.js|python-3.x|npm|serverless-framework
0
7,956
25,238,740
nested dictionary output from pyparsing
<p>I'm using <a href="http://pyparsing.wikispaces.com/" rel="nofollow">pyparsing</a> to parse an expression of the form:</p> <pre><code>"and(or(eq(x,1), eq(x,2)), eq(y,3))" </code></pre> <p>My test code looks like this:</p> <pre><code>from pyparsing import Word, alphanums, Literal, Forward, Suppress, ZeroOrMore, Cas...
<p>The feature you are looking for is an important one in pyparsing, that of setting results names. Using results names is recommended practice for most pyparsing applications. This feature has been there since version 0.9, as </p> <pre><code>expr.setResultsName("abc") </code></pre> <p>This allows me to access this p...
python|pyparsing|s-expression
10
7,957
71,088,072
Installing geopandas on Apple M1 chip
<p>How do you get <code>geopandas</code> to work in <code>python</code> with the new Apple M1 chip? Using <code>pip</code> does not work. I tried a lot of things and I think I came up with a work around that might be useful to others.</p>
<p>I spent the better part of today figuring out how to get <code>geopandas</code> to work on a new Mac with the M1 chip. According to this <a href="https://github.com/geopandas/geopandas/issues/1816" rel="nofollow noreferrer">closed issue</a>, you have to use conda (<a href="https://docs.conda.io/en/latest/miniconda.h...
python|geopandas|apple-m1
2
7,958
70,967,215
List index out of range in pandas dataframe
<p>I am trying keep the record of time when there is a motion in the camera and when the object leave to store in the csv file. The code works but when I enter the key 'q' I am getting an error <code>IndexError: list index out of range</code> in the line <code>df = df.append({&quot;Start&quot;:times[i],&quot;End&quot;:...
<p>it happen because you try to get index len(times)+1 -&gt; out of the list you can add a if</p> <pre><code>for i in range(0,len(times),2): if i&lt;len(times): df = df.append({&quot;Start&quot;:times[i],&quot;End&quot;:times[i+1]},ignore_index=True) </code></pre>
python|pandas
0
7,959
60,240,026
Printing multiple dictionaries horizontally
<p>I have multiple dictionaries:</p> <pre><code>dict1 = {"Hello": [1, 2, 3], "World": [1,2]} dict2 = {"Hello": [1], "World":[2]} dict3 = {"Test": [1]} </code></pre> <p>I'm trying to print these dictionaries horizontally based on the key and values from each dictionary. It will print a header (Word, Dict1, Dict2, Di...
<p><code>y.keys()</code> does not return a list. Use <code>list(y.keys())</code>. </p>
python|python-3.x|dictionary
1
7,960
60,056,431
Python unicode error in linux but not windows
<p>I followed some guides to piece together this bit of python</p> <pre><code>import requests import sys from bs4 import BeautifulSoup url = requests.get(sys.argv[1]) html = BeautifulSoup(url.content,'html.parser') for br in html.find_all("br"): br.replace_with(" ") for tr in html.find_all('tr'): data = []...
<p>Sorry for wasting your time.</p> <p>I was using...</p> <pre><code>python script.py </code></pre> <p>Which defaults to 2.7</p> <p>What I needed to run is... </p> <pre><code>python3 script.py </code></pre>
python|linux
1
7,961
2,740,026
Why are underscores better than hyphens for file names?
<p>From <a href="http://homepage.mac.com/s_lott/books/python/BuildingSkillsinPython.pdf" rel="nofollow noreferrer">Building Skills in Python</a>:</p> <blockquote> <p>A file name like <code>exercise_1.py</code> is better than the name <code>exercise-1.py</code>. We can run both programs equally well from the command lin...
<p>The issue here is that importing files with the <a href="https://en.wikipedia.org/wiki/Hyphen-minus" rel="noreferrer">hyphen-minus</a> (the default keyboard key <kbd>-</kbd>; <code>U+002D</code>) in their name doesn't work since it represents minus signs in Python. So, if you had your own module you wanted to import...
python|naming
81
7,962
2,946,674
Removing right-to-left mark and other unicode characters from input in Python
<p>I am writing a forum in Python. I want to strip input containing the right-to-left mark and things like that. Suggestions? Possibly a regular expression?</p>
<p>The OP, in a hard-to-read comment to another answer, has an example that appears to start like...:</p> <pre><code>comment = comment.encode('ascii', 'ignore') comment = '\xc3\xa4\xc3\xb6\xc3\xbc' </code></pre> <p>That of course, with the two statements in this order, would be a different error (the first one tries ...
python|unicode|right-to-left
1
7,963
67,847,894
Conv1dTranspose creates the wrong dimensions
<p>I'm trying to build an undercomplete autoencoder for music dimensionality reduction. My Autoencoder class is modular, I can give in input a list of convlayers sizes and it creates me automatically the model. The problem is that when I try to create a model with more than 2 convolutional layers the decoder returns me...
<p>I ended up with a solution on my own. The problem is the stride when the stride is &gt; 1. Setting the stride to be always 1 makes Everything works. An explanation can be found <a href="https://github.com/tensorflow/tensorflow/issues/2118" rel="nofollow noreferrer">here</a></p>
python|keras|deep-learning|tensorflow2.0|autoencoder
0
7,964
67,885,087
Datetime conversion in Python
<p>I have data collected from surveys with a lot of variations in dates:</p> <pre><code> ID Date 0 3786 2020-09-03 21:58:00 1 3785 3/9/2020 21:48 2 3784 2020-09-03 10:46:00 3 3783 2020-09-03 08:31:00 4 3781 2020-09-03 04:20:00 </code></pre> <p>To standardise the date format, I u...
<ul> <li>Just provide <strong>format</strong> and <strong>errors</strong> parameters in this function as described in <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer">this</a></li> </ul>
python|pandas|date|datetime
1
7,965
67,872,477
Row by row calculation
<p>Dumb question, but I am a bit rusty in Python. So I wrote the following code:</p> <pre><code>df = pd.read_csv(mypath ) for index, row in df.iterrows(): if row['Age'] &lt; 2: Total = row['Input'] * 1.2 elif row['Age'] &gt; 8: Total = row['Input'] * 1.1 else: Total = row['Input'] * ...
<p>You can use the apply method</p> <pre><code>def age_total(x): if x &lt; 2: return * 1.2 elif x &gt; 8: return x * 1.1 else: return x * 0.9 df['Total']= df['age'].apply(age_total) </code></pre>
python
4
7,966
30,459,687
how to retrieve specific entries from a csv file in python
<p>I have a CSV file <code>rsvp1.csv</code>:</p> <pre><code> _id event_id comments 1 | x | hello.. 2 | y | bye 3 | y | hey 4 | z | hi </code></pre> <p>My question is:<br> For each event e how can I get the com...
<p>I think it is best to just forget you're working with a csv file and think of it as a normal file in which you can to the following.</p> <pre><code>with open('file.csv', 'r') as f: lines = f.readlines() for line in lines: if not line.startswith('_id'): line_values = line.split(',') with open...
python|csv
0
7,967
30,622,350
How to include a variable name inside a variable name?
<p>Here is what I have:</p> <pre><code>names1 = ['bob', 'jack', 'adam', 'dom' ] num = int(input('Please select a number? ')) # select number 1 for name in names + num: # This is where my problem is print (s) </code></pre> <p>I want the names + num part to refer to the names1 list. How would you do that? </p> ...
<p>There are two options, either you can use, <code>nested list</code> structure or a <code>dictionary</code>.</p> <p><strong>Nested list:</strong></p> <pre><code>parent_list = [['bob', 'jack', 'adam', 'dom'], ["alpha", "beta", "gamma"], ["India", "USA"]] num = int(input('Please select a number? ')) #Checking if the ...
python|variables
3
7,968
42,776,980
ValueError: The two structures don't have the same number of elements
<pre><code>with tf.variable_scope('forward'): cell_img_fwd = tf.nn.rnn_cell.GRUCell(hidden_state_size, hidden_state_size) img_init_state_fwd = rnn_img_mapped[:, 0, :] img_init_state_fwd = tf.multiply( img_init_state_fwd, tf.zeros([batch_size, hidden_state_size])) rnn_outputs2, final_state2 = tf.nn....
<p>Hello I had the same problem, I tried to do this:</p> <pre><code>highest = tf.map_fn(lambda x : (-x, x), indices) </code></pre> <p>This gave me a similar error message:</p> <pre><code>ValueError: The two structures don't have the same number of elements. First structure (1 elements): &lt;dtype: 'int32'&gt; Seco...
tensorflow|recurrent-neural-network|gated-recurrent-unit
26
7,969
43,014,616
Django channels for real time app
<p>I have started working on Django application which should have a WEB UI to run my custom scripts on another server and I need to see the output in the UI in real time. Importent to see step by step script execution. Question is - how to redirect script output (print, logger for python script) to channels and then pu...
<p>I haven't work on Django application but as it's an MVC framework, I suppose my answer would be relevant to your question.</p> <p>You can make ajax call (maybe with jquery) to your controllers, which in turn initiate your scripts. I think there are two ways of doing this. </p> <p>First, is to make serial ajax requ...
python|django|python-3.x
2
7,970
65,835,567
How to separate a string with 2 uppercases and a space with regex in pandas dataframe?
<p>I have a dataframe column, teams, where I am trying to split the team name, 'CubsWhite Sox', into two parts, 'Cubs' and 'White Sox'.</p> <pre><code>import pandas as pd import re data = [{'teams':'CubsWhite Sox','area':'Chicago','league': 'MLB'}, {'teams': 'Red Sox','area':'Boston', 'league': 'MLB'}, {'teams': 'Blue ...
<p>You can use</p> <pre class="lang-py prettyprint-override"><code>df['team'] = df['teams'].str.findall(r'[A-Z][a-z]*(?:\s+[A-Z][a-z]*)?') </code></pre> <p>See the <a href="https://regex101.com/r/zDHgiu/2" rel="nofollow noreferrer">regex demo</a>. <em>Details</em>:</p> <ul> <li><code>[A-Z][a-z]*</code> - an uppercase l...
python-3.x|regex|pandas|dataframe|regex-lookarounds
3
7,971
50,673,501
comparing two columns by if loop in Python
<p>I have made two column of data one of them are 286 number as y-amounts and another is 286 numbers as y1-amounts as function of x. I want to compare this two columns one row by one row and if y is larger than y1 it should be plotted in red else it will be plotted in blue. But I get this error: if yyy > y1: ^ In...
<p>Blocks of code are grouped together by indentation in Python. Any loops, functions, classes, or conditional statements('if' isn't a loop, btw) need to be at an indentation level.</p> <p><a href="https://docs.python.org/2.4/ref/indentation.html" rel="nofollow noreferrer">Reference</a></p> <p><a href="https://repl.i...
python|pandas|numpy|astronomy
1
7,972
50,921,718
iterating through for loop and if condition not satisfied do something. python
<p>I have following condition:</p> <pre><code>a=[] for i in list1: for j in list2: if i==j: a.append(i) </code></pre> <p>I want to add a statement <code>a.append(np.nan)</code> if i!=j after looping through list2. i.e<br> After iterating through inner for loop, if i don't find any i==j then it...
<p>You can easily do that with list comprehension.</p> <p><code>a = [i if j == i else np.nan for i in list1 for j in list2]</code></p> <p>First we assign i if i==j if it is not we assign np.nan. Then we iterate on list1 for i and list 2 for j</p>
python|for-loop|if-statement
1
7,973
50,452,801
Data in text file, like a matrix, with string and number. I want to set a filter, to change some Strings based condition of number by python
<p>For example:</p> <pre><code>300 "FTPAT1 2 " 301 "CHURCH 2 " "01" "Open" "Line" 300 "CHURCH 2 " 301 "GREENL1 1 " "01" "Open" "Line" 400 "FTPAT1 2 " 401 "CHURCH 2 " "01" "Closed" "Line" 400 "CHURCH 2 " 401 "GREENL1 1 " "01" "Closed" "Line" </code></pre> <p>I want to chan...
<p>You can use <code>re.sub</code>:</p> <pre><code>import re with open('filename.txt') as f: with open('new_filename.txt', 'w') as f1: f1.write(re.sub('Open|Closed', '{}', f.read()).format(*['Open' if i == 'Closed' else 'Closed' for i in re.findall('Open|Closed', f.read())])) </code></pre> <p>Output:</p> <pr...
python|text-files
0
7,974
50,241,441
Pass username to Django form
<p>So i have a custom Form where i need to pass in the request.user.username so i can use that to fill out forms.ModelChoiceField based on what user is accessing it. Here is what i have</p> <p>views.py</p> <pre><code>if request.method == 'POST': form = DepartmentForm(request.POST, username=request.user.username) ...
<p>The line <code>Company = forms.ModelChoiceField()</code> is evaluated when the module is loaded. You don't have access to <code>self.username</code> at that point.</p> <p>Instead, you should set the <code>queryset</code> in the form's <code>__init__</code> method:</p> <pre><code>class DepartmentForm(forms.Form): ...
python|django|forms|keyword-argument
3
7,975
61,211,894
Python: Making a function signature with inspect
<p>I'm having trouble figuring out how I should be building a signature manually. The docs say that the <code>parameters</code> argument of <code>inspect.Signature</code> should be an <code>OrderedDict</code>. But that fails for me. </p> <p>Even the <code>parameters</code> in an <code>inspect.Signature</code> instance...
<p>You are missing something important (but not very profound). The documentation for the <a href="https://docs.python.org/3/library/inspect.html#inspect.Signature.parameters" rel="nofollow noreferrer">class attribute <code>parameters</code></a> reads</p> <blockquote> <p>An ordered mapping of parameters’ names to th...
python|python-3.x
2
7,976
57,811,573
Upon prediction, my loaded model is giving me an AttributeError
<p>I'm fairly new to Tensorflow and Machine Learning in general but I know enough that I've built a small model. Although, when loaded and I use <code>model.predict</code>, I get an attribute error: </p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf import numpy as np checkpoint_path = "trai...
<p>Make sure the input you're giving is in the correct format for the model you build. In your case, an <code>Embedding</code> layer expects a 2D tensor. The data should be a numpy array that looks something like this: <code>[[0, 2, 64], [24, 6, 8]]</code>. Each number there represents a word, and each sequence of numb...
python|machine-learning|keras|deep-learning|tf.keras
2
7,977
18,713,043
Parse command line argument using argparse
<p>I have utility which pass multiple argument alongwith require element Could anyone provide some input How can I handle this scenario using argparse. Please find the sample code</p> <pre><code>#! /usr/bin/env python import argparse parser = argparse.ArgumentParser() parser.add_argument("-cdl", dest = "input_file") a...
<p>You can just add options for the arguments you don't need.</p> <pre><code>parser.add_argument("-cdl-sp", dest = "sp", action='store_true') parser.add_argument("-cdl-sk", dest = "sk", action='store_true') </code></pre>
python|argparse
1
7,978
18,481,636
Print string after equals to sign in Python?
<p>I have lots of lines in a text file. One line for example: </p> <pre><code>838: DEBUG, GD, Parameter(Player_Appearance_Model) = GaussianDistribution(0.28, 0.09) </code></pre> <p>Can somebody please tell me how to print all the string after the equals to sign ("="). For instance, in the above case, output should be...
<p>You don't need a regex, just <code>split()</code> it:</p> <pre><code>&gt;&gt;&gt; s = "838: DEBUG, GD, Parameter(Player_Appearance_Model) = GaussianDistribution(0.28, 0.09)" &gt;&gt;&gt; s.split(" = ")[1] 'GaussianDistribution(0.28, 0.09)' </code></pre> <p>or:</p> <pre><code>&gt;&gt;&gt; s.split("=")[1].strip() '...
python|regex|string
8
7,979
69,632,242
conda-forge can't install pwntools due to UnsatisfiableError
<p>I created a new Conda Env with:</p> <pre><code>conda create -n my_env pip python=3.8.8 </code></pre> <p>then, activate my env with</p> <pre><code>conda activate my_env </code></pre> <p>then, as stated in anaconda docs (<a href="https://anaconda.org/conda-forge/pwntools" rel="nofollow noreferrer">here</a>) tried to i...
<p>Using <code>mamba</code>, the issue is more clear (I have added pwntools to the environment creation line:</p> <pre><code>(base) C:\Users\FlyingTeller&gt;mamba create -n my_env -c conda-forge pip python=3.8.8 pwntools __ __ __ __ / \ / \ / \ / \ / ...
python|anaconda|conda|conda-forge|pwntools
2
7,980
55,200,708
How do I make my command line use a specific version of python?
<p>I am getting started on using Zappa. However, I already had installed python 3.7 on my computer while Zappa uses 3.6. I installed python 3.6.8, but when I try to use zappa in the cmd (zappa init) it uses python 3.7 by default. How can I direct zappa to use 3.6 instead?</p>
<p>As mentioned in Zappa <a href="https://github.com/Miserlou/Zappa#installation-and-configuration" rel="nofollow noreferrer">README</a>:</p> <blockquote> <p>Please note that Zappa must be installed into your project's virtual environment. </p> </blockquote> <p>You should use something like <code>virtualenv</code> ...
python|python-3.x|cmd|command-line|zappa
2
7,981
57,549,734
Got only first paragraph from article using selenium python (need all paragraphs)
<p>I want to extract all the paragraphs from this article but I managed to only get the first paragraph using selenium for python. The article link is: <a href="https://nthqibord.com/2019/08/15/pemimpin-pkr-pertahan-tun-mahathir/" rel="nofollow noreferrer">https://nthqibord.com/2019/08/15/pemimpin-pkr-pertahan-tun-maha...
<pre><code>para = [] for p in driver.find_elements_by_xpath("//div[@class='td-ss-main-content']/div[@class='td-post-content']//p"): para.append(p.text) posts = " ".join(para) </code></pre>
python-3.x|selenium|xpath|css-selectors|webdriverwait
0
7,982
57,497,821
how to save data via export in python program?
<p>I want to automate a specific task, and I have a bash file that I want to read data from user arguments by running the script</p> <pre class="lang-sh prettyprint-override"><code>bash my_script.sh /etc/??? path/dst </code></pre> <p>till now, I'm getting the data in my script by access to positional parameters (<cod...
<p>Thanks to <code>@chepner</code>s comment, the solution was using <code>$()</code> instead of using <code>export</code>.</p> <p>As it's mentioned in comments :</p> <blockquote> <p>export only passes information from a parent to a child process, not the other direction.</p> </blockquote> <p>So one of the <strong>corre...
python|linux|python-3.x|bash
1
7,983
42,277,280
Accessing Tensorboard on AWS
<p>I'm trying to access Tensorboard on AWS. Here is my setting :</p> <ul> <li>Tensorboard : <code>tensorboard --host 0.0.0.0 --logdir=train</code> :</li> </ul> <blockquote> <p>Starting TensorBoard b'39' on port 6006 (You can navigate to <a href="http://172.31.18.170:6006" rel="noreferrer">http://172.31.18.170:600...
<p>You can use ssh tunneling technique.</p> <p>In your terminal:</p> <pre class="lang-sh prettyprint-override"><code>ssh -i /path/to/your/AWS/key/file -NL 6006:localhost:6006 user@host </code></pre> <p>where:</p> <ul> <li>user and host: your aws ec2 user and instance specific.</li> <li><code>-N</code>: don't execute a ...
amazon-web-services|amazon-ec2|tcp|tensorflow|tensorboard
21
7,984
65,123,144
docker build error when trying to pip install dict package
<p>I only started getting the error when I moved my docker installation onto ubuntu (things were working fine on windows docker installation).</p> <p>When I run docker build I get the following error when it is trying to install <em>python</em> package <code>dict</code>:</p> <pre><code>#14 1.681 Downloading dict-2020...
<p>You should add <code>--use-feature=2020-resolver</code> to the pip installation command. According this issue: github.com/pypa/pip/issues/8707</p>
python|docker|ubuntu
0
7,985
22,840,348
pandas: how could I order data frame by column name and add empty column
<p>my data frame looks like this</p> <p>df = </p> <pre><code> 1324 1322 1323 1326 1327 1328 1329 278650 2.15 2.15 2.15 2.15 2.15 2.15 535947 2.15 2.15 2.15 2.15 2.15 2.15 </code></pre> <p>And I want to order them like below</p> <pre><code> ...
<p>Try this:</p> <pre><code>df.sort_index(axis = 1,inplace = True) ##Sorts the DataFrame by columns (axis = 1) in place </code></pre> <p>to fix the sorting problem, and try this:</p> <pre><code>import pandas as pd desired_cols = range(1322,1374) for col in desired_cols: if col not in df.columns: df[col] ...
python|pandas
1
7,986
22,750,555
python mock patch top level packages
<p>Using <a href="http://docs.python.org/dev/library/unittest.mock.html" rel="nofollow">mock</a> in python, top level packages (like argparse) cannot be patched outright - presumably because there is no reference to patch. One solution is to patch every individual call into the package (like argparse.ArgumentParser). I...
<pre><code>import unittest.mock as mock mock_argparse = mock.Mock() with mock.patch.dict('sys.modules', argparse=mock_argparse): import argparse print(argparse.ArgumentParser()) # &lt;Mock name='mock.ArgumentParser()' id='140681471282448'&gt; </code></pre> <p>As for mock_open patching:</p> <pre><code>m = mo...
python|unit-testing|mocking|python-mock
4
7,987
22,874,542
Python 3x regular expression syntax
<p>While trying to remove all repeating words in a string in an example below, what should be the correct syntax to check for 1 or more repetition of the word. The following example returns </p> <pre><code>cat cat in the hat hat hat </code></pre> <p>it ignores more than one repetition in the string, only removes "in...
<p>This should print the given sentence with duplicates </p> <pre><code>check_for_repeats = 'cat cat cat in in the the hat hat hat hat hat hat' words = check_for_repeats.split() sentence_array = [] for i in enumerate(words[:-1]): if i[1] != words[i[0] + 1]: sentence_array.append(i[1]) if words[-1:] != wor...
python|regex
1
7,988
45,705,771
How to use activation function on part neurons from one layer in Tensorflow
<p>For example, there is a tensor </p> <pre><code>a=[[1,2,3,4,5], [2,3,4,5,6]] indices =[[1, 0, 1, 0, 0], [0, 1, 0, 0, 0]] </code></pre> <p>I would only like to use activation on the elements (from a) whose index are with value 1 (from b). For example, I only want to use activation function on the elements ...
<p>You can use <a href="https://www.tensorflow.org/api_docs/python/tf/where" rel="nofollow noreferrer">tf.where</a>:</p> <p><code>tf.where(tf.cast(indices, dtype=tf.bool), tf.nn.sigmoid(a), a)</code></p> <p>For your example:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf a = tf.constant...
tensorflow
1
7,989
14,806,396
Blinking an LED with an Arduino and pySerial
<p>I feel really silly for asking this, but I've been shocked at my inability to find the simplest example I can imagine for talking to an Arduino over Serial. I have a connection set up, and I understand how to write both Arduino Code and Python, but I have no idea how to write to an arduino pin using python. Can anyo...
<p>There isn't a direct way to control the Arduino through the serial port, so you would need to have some program running on the Arduino that could respond to serial information and do what you want. There are programs like <a href="http://firmata.org/wiki/Main_Page" rel="nofollow">Firmata</a> that will do this for y...
python|arduino|pyserial|led
4
7,990
56,987,807
h.264 encoding directly from numpy
<p>I want to directly encode videos from numpy arrays of video frames. Open-cv offers such functionality via the <code>cv2.VideoWriter</code>, however I need the h.264 codec which is not available. The best I have so far is using open-cv to write the video and then reencode it via:</p> <pre><code># write video from nu...
<p>scikit-video provides the feature:</p> <pre><code>import skvideo.io outputfile = "/tmp/video.mp4" writer = skvideo.io.FFmpegWriter(outputfile, outputdict={'-vcodec': 'libx264'}) for frame in frames: writer.writeFrame(frame) writer.close() </code></pre>
python|opencv|video|ffmpeg|h.264
3
7,991
57,284,591
How to display all stages (even empty ones) of a selection field in Kanban view in Odoo 10?
<p>I am trying to display stages for a model defined as a <strong>Selection field</strong> in <strong>Kanban view</strong> in <em>Odoo 10</em>. But when I add the stage field in Kanban view, stages with records in it are displayed in kanban view but not all stages. </p> <p>I have a Selection field with 3 stages and a ...
<p>it's working for me in Python File:</p> <pre><code>state = fields.Selection([('en_cours_confirmation', 'En Cours de Confirmation'), ('confirmer', 'Confirmé'), ('annuler', 'Annulé')] , default='en_cours_confirmation', string="Status", group_expand='_expand_states', index=True) def _expand...
python|odoo|odoo-10|kanban
4
7,992
57,128,393
how does itemgetter work? what happens when we initialise it to key
<pre><code>&gt;&gt;&gt; from operator import itemgetter &gt;&gt;&gt; a = [(5, 3), (1, 3), (1, 2), (2, -1), (4, 9)] &gt;&gt;&gt; sorted(a, key=itemgetter(0)) [(1, 3), (1, 2), (2, -1), (4, 9), (5, 3)] </code></pre> <p>How does this work? is key a function as well? i am confused about what goes behind key=itemgetter(0) ?...
<p><a href="https://docs.python.org/3.7/library/operator.html#operator.itemgetter" rel="nofollow noreferrer"><strong><code>itemgetter(..)</code></strong> [python-doc]</a> is a function that constructs a function. This concept is known in computer science as <a href="https://en.wikipedia.org/wiki/Currying" rel="nofollow...
python|sorting
4
7,993
61,811,902
Display y axis from 0 to 100 in Matplotlib plot
<p>I wanted to display my data and wanted to set the y axis to show always from 0 to 100 or from 10 to 60.</p> <p>I used "set_ylim()" and it worked with a small list but then I tried to put my data in that had datetime as x and a int as y and this didn't worked or the list is too long.</p> <p>the data list looks like...
<p>You are plotting strings - change them to ints</p> <pre><code>ax1.plot(data[0],[int(thing) for thing in data[1]],color="red") ax2.plot(data[0],[int(thing) for thing in data[2]],color="blue") </code></pre>
python|matplotlib
0
7,994
23,457,827
flask-security encrypt_password('mypassword') varies every time when i reload the page
<p>I've already configured <code>SECURITY_PASSWORD_SALT</code> and use "bcrypt". But every time i reload the page <code>print encrypt_password('mypassword')</code> will print different values, so i can't verify user input password via <code>verify_password(form.password.data, user.password)</code>.</p> <p>But I can lo...
<p>The fact that <code>encrypt_password()</code> generates a new value is by design. The fact that <code>verify_password()</code> fails is not. It's an already reported <a href="https://github.com/mattupstate/flask-security/issues/229" rel="nofollow">bug in Flask-Security</a>.</p> <p>When you use the login view, a dif...
python|flask-security
2
7,995
24,357,213
Python - combine two lists into a single tuple - for multiprocessing pool.map
<p>I am trying to pass multiple arguments to a function using a single tuple. The reason for this odd approach is that my actual program is following <a href="https://stackoverflow.com/questions/5442910/python-multiprocessing-pool-map-for-multiple-arguments">this example</a> to pass multiple arguments to a <code>multip...
<p>One incremental improvement:</p> <pre><code>def worker(data_to_check, support_data): rowTest, rowProd = data_to_check countRow, precision = support_data </code></pre> <p>Or</p> <pre><code>groups_test = [ 1, 2, 3] groups_prod = [-1,-2,-3] countRows = [0]*4 precisions = [4]*4 groups_combined = zip(groups_te...
python|multiprocessing
0
7,996
24,179,785
how to multithread on a python server
<p>HELP please i have this code </p> <pre><code>import socket from threading import * import time HOST = '' # Symbolic name meaning all available interfaces PORT = 8888 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print ('Socket created') s.bind((HOST, PORT)) print ('So...
<p>The API you're using has moved from <code>thread</code> to <code>_thread</code>, so you'll need to do;</p> <pre><code>import _thread </code></pre> <p>The call is on the _thread module and requires a tuple as a second argument, so the correct line to start the thread would be;</p> <pre><code>_thread.start_new_thre...
python|multithreading|socketserver
2
7,997
14,941,413
Python "in" Comparison of Strings of Different Word Length
<p>I am working through a database of names with possible duplicate entries and attempting to identify which we have two of, unfortunately the formatting is a bit less than optimal and some entries have their first name, middle name, last name or maiden names mashed into one string and some have just first and last.</p...
<p>You need to split the strings and look for the individual words:</p> <pre><code>&gt;&gt;&gt; all(x in 'John Michael Marvulli'.split() for x in 'John Marvulli'.split()) True </code></pre>
python|comparison|string-comparison|comparison-operators
7
7,998
29,738,831
adding conditions when scraping
<p>I'm trying to scrape a webpage, and it seems that each separation has a different <code>div</code>, depending in how much the user pays or the type of page it has.</p> <p>Example:</p> <pre><code>&lt;div class="figuration Web company-stats"&gt; ..information i want to scrap.. &lt;/div&gt; &lt;div class="figuration...
<p>Use a CSS selector:</p> <pre><code>for sel in response.css('div.figuration'): ... </code></pre>
python|web-scraping|scrapy|conditional-statements
2
7,999
46,396,443
Python Requests Complicated Post
<p>I'm trying to use Requests to get to the "next" (right arrow) page of this URL:</p> <p><a href="https://www.sportstats.ca/display-results.xhtml?raceid=43572" rel="nofollow noreferrer">https://www.sportstats.ca/display-results.xhtml?raceid=43572</a>.</p> <p>I used the chrome developer tools to examine the response ...
<p>The website you want to scrap is better suited for selenium.</p> <p>All you need is to get the number of total number of pages from visiting the website, then you loop over the total number of pages and click on the next button once every loop.</p> <p>During every loop you can do the required parsing for each page...
python|beautifulsoup|python-requests
1