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
3,900
58,659,689
Adding custom stopwords to IBM Watson Discovery
<p>I'm trying to add a custom stopwords on a colletion of Watson Discovery, but I only get the error 500 "Error when creating 'stopwords'.". Same on both web and api (curl).</p> <p>I've tried:</p> <ul> <li>file with 99 lines,</li> <li>empty file,</li> <li>and an IBM file (<a href="https://watson-developer-cloud.githu...
<p>I am using python sdk and the following code to upload a custom stopword list, discovery query seems to use the custom stopwords and update the search query results without any error, I did not even need to Delete and create a new collection. </p> <pre><code>authenticator = IAMAuthenticator('&lt;your api key&gt;') ...
python|text-mining|ibm-watson|stop-words|discovery
0
3,901
59,025,973
How to check for the acceptable arguments which a function can accept without reading its code?
<p>Is there a method to check for the possible arguments that a function can accept?</p> <p>e.g.</p> <pre><code>def greet(name,msg): """This function greets to the person with the provided message""" print("Hello",name + ', ' + msg) </code></pre> <p>Output: greet("Monica","Good morning!")</p> <p>The arguments tha...
<p>For this you can use the <a href="https://docs.python.org/3/library/inspect.html" rel="nofollow noreferrer">inspect</a> module - in particular, <a href="https://docs.python.org/3/library/inspect.html#inspect.getfullargspec" rel="nofollow noreferrer">inspect.getfullargspec.</a></p> <p><strong>For your example:</stro...
python|function|arguments
2
3,902
73,463,124
What does -n in python represent?
<pre><code>import argparse parser = argparse.ArgumentParser(description=&quot;Meow like a cat&quot;) parser.add_argument(&quot;-n&quot;, default=1,help=&quot;number of times to meow&quot;, type=int) args = parser.parse_args() for _ in range(arg.n): print(&quot;meow&quot;) </code></pre> <p>I don't really understan...
<p><code>add_argument(&quot;-n&quot;, ...)</code> defines an argument that takes '-n'` as a flag, and is used as with</p> <pre><code>$python your_script -n 1 </code></pre> <p><code>argparse</code> sets that value to the <code>args</code> object.</p> <pre><code>print(args) Namespace(n=1) </code></pre> <p>which is then a...
python|argparse
2
3,903
73,321,370
PANDAS : converting int64 to string results in object dtype
<p>I have a dataframe:</p> <pre><code>df1 = pd.DataFrame({'GL': [2311000200.0, 2312000600.0, 2330800100.0]}) </code></pre> <p>df1.dtypes is float so first I convert it to int64 to removes .0 digitals df1.GL = df1.GL.astype('int64')</p> <p>Then I try to convert it to str but instead I receive object dtype.</p> <p><a hre...
<p>You can force it to use the <code>string</code> dtype by using:</p> <pre><code>&gt;&gt;&gt; df1.GL.astype(&quot;string&quot;) df1.GL 0 2311000200.0 1 2312000600.0 2 2330800100.0 Name: GL, dtype: string </code></pre> <p>However, <code>object</code> dtypes are fine for most string operations. As per the <a ...
python|pandas
1
3,904
73,473,074
Speed up set partition generation by skipping ones with subsets smaller or larger than X, or partitions with more or less than Y subsets
<p>There is a great answer regarding the generation of partition sets:</p> <p><a href="https://stackoverflow.com/questions/19368375/set-partitions-in-python">Set partitions in Python</a></p> <p>(another similar answer with ruby is found here: <a href="https://stackoverflow.com/questions/22519470/calculate-set-partition...
<p>Just use recursion.</p> <p>Note, the arrays returned each time are modified in place for efficiency. If you're going to do anything interesting with them, you probably want to make your own copies.</p> <pre><code>def split_partition (elements, min_size, max_size, partition=None, rest=None, i = 0): if partition ...
python|algorithm|combinations|combinatorics
1
3,905
31,299,542
How to add to arrays such that matching elements become their own arrays
<p>I feel like there is quick way to do this with Numpy but I can't seem to find the function for it.</p> <p>I need to take three arrays:</p> <pre><code>a = [1,2,3] b = [1,2,3] c = [1,2,3] Z = np.somefunction(a,b,c) print Z ([1,1,1],[2,2,2],[3,3,3]) </code></pre>
<p>You can use <code>np.dstack</code> :</p> <pre><code>&gt;&gt;&gt; np.dstack((a,b,c)) array([[[1, 1, 1], [2, 2, 2], [3, 3, 3]]]) </code></pre> <p>Also as says @ Warren Weckesser said in comment since <code>np.dstack</code> returns a 3d array as a better way you can use following way :</p> <pre><code...
python|arrays|numpy
1
3,906
15,752,963
Python Qtconsole: QApp = QCoreApplication.instance() returns None on Linux and a valid QApplication on Windows
<p>I have software which has a GUI interface and a command line interface. What it should do is detect if it is being run in a qtconsole. If it is, it will not create a new QApplication and show the GUI in a non-blocking manner. After the script exists, there will be a cmd object where the user can interact with things...
<p>The problem was I forgot the '--pylab=qt ' argument when I ran </p> <pre><code>ipython qtconsole --pylab=qt --color=Linux -c "%run main.py" </code></pre>
python|pyqt4|ipython|qtconsole
2
3,907
15,817,483
Import png files and save as subplots using matplotlib
<p>I would like to import two png files and stich them into subplots using matplotlib. I am following this <a href="http://matplotlib.org/users/image_tutorial.html" rel="nofollow">tutorial</a> to do this. But when I save the figure with a 2x2 subplot, the resolution is very poor. Is there a better way of doing this?</p...
<p>If the resolution is satisfactory before you save, try using the <code>dpi</code> keyword along with <code>matplotlib.pyplot.savefig()</code> (see docs page for <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig" rel="nofollow">matplotlib.pyplot.savefig</a>). Once you have the plot generat...
python|matplotlib
2
3,908
59,795,511
Dataframe values conditional on multiple values
<p>I have the following df in pandas:</p> <pre><code>person year A B AA 1998 5 AA 1999 10 AA 2000 15 XB 2010 100 CY 1980 3 CY 1981 9 CY 1982 36 CY 1983 72 MJ 2017 120 MJ 2018 240 </code></pre> <p>I'd like to iterate over each <em>person</em> in the ...
<pre><code>dfshift = df.groupby('person')['A'].transform(lambda x: x.shift()) df['B'] = (df['A']/dfshift)*100 df['B'].fillna(0, inplace = True) person year A B 0 AA 1998 5 0.0 1 AA 1999 10 200.0 2 AA 2000 15 150.0 3 XB 2010 100 0.0 4 CY 1980 3 0.0 5 ...
python|pandas|dataframe
3
3,909
49,217,965
odoo-10 How to create journal entries without invoices using custom module ? (Refer below picture)
<p>I want to create a journal entries from my custom module but I don't know which module I must inherit from account.payment or account.move and which steps I have to follow if I will choose one of them , I tried those 2 models but I had nothing the journal entries dos not created , I create order line class with curr...
<p>A new record for any model can be created from python by calling the create function of that model.</p> <p>For example:</p> <pre><code>move = self.env['account.move'].create({'field_1': value, 'field_2': value}) </code></pre> <p>Make sure you pass all required fields in account .move</p>
python|odoo|odoo-10
1
3,910
49,196,881
Getting constant TypeError: fetch_data() missing 1 required positional argument: 'download_dir'
<p>I have been trying to get the following code to work to no avail. I have looked everywhere and I am just not getting what I am doing wrong. I am fairly new to python so here is my code:</p> <pre><code>from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.supp...
<p>You have defined a function, <code>fetch_data()</code>, that takes one argument:</p> <pre><code>def fetch_data(download_dir): ... </code></pre> <p>The last line of the script calls <code>fetch_data()</code>, but with no <code>download_dir</code> argument:</p> <pre><code>fetch_data() </code></pre> <p>That is ...
python|python-3.x|beautifulsoup|peewee
0
3,911
25,083,697
Discrete time-series graph with unknown y range
<p>In a discrete time-series graph, I have tried replacing <code>ax.plot(x,y)</code> by <code>ax.vlines(x,y)</code>:</p> <ul> <li>I get the error: <code>vlines() missing 1 required positional argument: 'ymax'</code></li> </ul> <p>However, I cannot know the <code>ymax</code> value beforehand. How can I avoid this er...
<p>looks to me like you want to have a <code>bar</code> plot.</p> <p><code>ymax</code> is the upper limit for <code>vlines</code>, <code>vlines(0, 0, 1)</code> plots a vertical line at x=0 from y=0 to y=1.</p> <p>This is a working minimal example:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np fro...
python|matplotlib|time-series|timeserieschart
2
3,912
25,193,635
PasswordHash.java not generating matching PBKDF2-HMAC-SHA1 hash
<p>I am writing a Django app that needs to work with an existing Java Play framework app. The Play app uses <a href="https://crackstation.net/hashing-security.htm#javasourcecode" rel="nofollow">PasswordHash.java</a> to store passwords. It stores passwords in a colon separated format. Each hash is stored as <code>iterat...
<p>Try <code>salt = base64.b16decode(salt.upper())</code>.</p> <p>I did and I got the hash in your initial example, albeit uppercased <code>B69139F5...</code></p> <p>Explanation:</p> <p>The hash and salt are both being stored in Base16 (hex) in your initial example. So you decode the salt to use it and then encode t...
java|python|hash|cryptography|pbkdf2
3
3,913
70,839,225
Python Selenium Webscrapping - While log in wrong password Error
<p>Even though my password is <strong>correct</strong>. I can't log in to Instagram and it gives your password is incorrect error. My intention is to enter Instagram and follow some users automatically. However, I am totally stuck at the login screen. Can the language and connection country be a problem?</p> <pre><code...
<p>The <em><strong>login</strong></em> fields on <a href="https://www.instagram.com/accounts/login" rel="nofollow noreferrer">Instagram Login Page</a> are <a href="https://reactjs.org/" rel="nofollow noreferrer">ReactJS</a> elements. So to send a <em>character sequence</em> to those fields you have to induce <a href="h...
python|selenium|web-scraping|instagram
1
3,914
60,104,889
Tokenizer and print it
<p>After tokenizer my list of strings im trying to get the value of the words and its number's associate. f.e: the = 3 how can I do it?? (python) here is the code</p> <pre><code>sentences_train, sentences_test, y_train, y_test = train_test_split(X,y, test_size=0.2, random_state=42) from keras.preprocessing.text i...
<p>Try tokenizer.texts_to_sequences(['the'])</p>
python|printing|tokenize
0
3,915
60,107,956
how to print out WHOLE list of dictionary values of txt file in python
<p>I am trying to print out the </p> <pre><code>exist = False while(exist == False): try: name = input('Please enter a file name: ') myfile = open(name,'r') a = myfile.readline() b = myfile.readlines() count = len(b) exist = True except: print('Error!', name, 'does not exist.') myfile.clos...
<p>You're doing something weird<br> Instead of <br></p> <pre><code>&gt; for i in range(len(lst)): &gt; keylst.append(lst[i][0]) &gt; vallst.append(lst[i][1]) &gt; &gt; dict = {} for i in range(len(lst)): &gt; tempdict = {keylst[i]:vallst[i]} &gt; dict.update(tempdict) </code></pre> <p>just use <code>...
python
0
3,916
3,179,474
Accessing static properties in Python
<p>I am relatively new to Python and was hoping someone could explain the following to me:</p> <pre><code>class MyClass: Property1 = 1 Property2 = 2 print MyClass.Property1 # 1 mc = MyClass() print mc.Property1 # 1 </code></pre> <p>Why can I access Property1 both statically and through a MyClass instance?</p>
<p>The code </p> <pre><code>class MyClass: Property1 = 1 </code></pre> <p>creates a class <code>MyClass</code> which has a dict:</p> <pre><code>&gt;&gt;&gt; MyClass.__dict__ {'Property1': 1, '__doc__': None, '__module__': '__main__'} </code></pre> <p>Notice the key-value pair <code>'Property1': 1</code>. When yo...
python
30
3,917
67,932,279
Break down a complex string into a dictionary in python3
<p>I have a string that look like this:</p> <pre><code>'[0, 1, 2, 4, 8, 16, 32, 64, 128, 256], [200, 78, 570, 259, 85, 12, 8, 1, 0, 0]' </code></pre> <p>Basically the first list is the key, the second is the actual value, so I am trying to break down this string to get the appropriate key and value</p> <p>How do I achi...
<p>If your string is safe and this format (so list, comma, list), you can use <code>ast.literal_eval</code> to get a tuple of two lists.</p> <p>Then, with <code>zip</code>, you can merge elements in order from two iterables.</p> <pre class="lang-py prettyprint-override"><code>import ast s = '[0, 1, 2, 4, 8, 16, 32, 64...
python
4
3,918
68,006,587
Pandas groupby and then find max value per group in another column
<p><a href="https://i.stack.imgur.com/DvGFH.png" rel="nofollow noreferrer">This is not the whole dataset, just .head(10)</a></p> <p>I want a dataframe with 3 columns: groupby user_id</p> <ol> <li><p>’user_id’</p> </li> <li><p>The ‘product_id’ that is most ordered per ‘user_id’ (max in ‘uxp_total_bought' per ‘user_id’)<...
<p>I think the following is gonna work.</p> <pre><code>test = your_dataset.groupby('product_id')['uxp_total_bought'].max() test = test.reset_index() test = your_dataset.loc[uxp.groupby(&quot;user_id&quot;)[&quot;uxp_total_bought&quot;].idxmax()] del test[&quot;uxp_total_bought&quot;] test.rename(columns = {&quot;produc...
pandas|dataframe|pandas-groupby
0
3,919
67,881,962
How can I test my training model using a different dataset in machine learning
<p>Hello I am very new to Python and machine learning and I am running into a issue. After splitting and completing my training and testing models, now I need to test a complete different dataset.</p> <p>Below is how I created my training and test:</p> <p><strong>Using NaiveBayes Classifier model</strong> <code>nb_mode...
<p>Specifically and functionally speaking, your new dataset should have the same number of features.</p> <p>If <code>x_train.shape</code> gives <code>(752, 8)</code>, then you know it has 8 features and 752 samples.</p> <p>After that your model was trained on it, you can be sure that <code>model.n_features</code> will ...
python|machine-learning|testing|training-data|naivebayes
0
3,920
30,565,404
Remove all style, scripts, and html tags from an html page
<p>Here is what I have so far:</p> <pre><code>from bs4 import BeautifulSoup def cleanme(html): soup = BeautifulSoup(html) # create a new bs4 object from the html data loaded for script in soup(["script"]): script.extract() text = soup.get_text() return text testhtml = "&lt;!DOCTYPE HTML&gt;\n...
<p>It looks like you almost have it. You need to also remove the html tags and css styling code. Here is my solution (I updated the function):</p> <pre><code>def cleanMe(html): soup = BeautifulSoup(html, "html.parser") # create a new bs4 object from the html data loaded for script in soup(["script", "style"]):...
python|html|beautifulsoup
26
3,921
66,832,708
Pytorch embedding too big for GPU but fits in CPU
<p>I am using PyTorch lightning, so lightning control GPU/CPU assignments and in return I get easy multi GPU support for training.</p> <p>I would like to create an embedding that does not fit in the GPU memory.</p> <pre><code>fit_in_cpu = torch.nn.Embedding(too_big_for_GPU, embedding_dim) </code></pre> <p>Then when I s...
<p>Lightning will send anything that is registered as a model parameter to GPU, i.e: weights of layers (anything in torch.nn.*) and variables registered using <code>torch.nn.parameter.Parameter</code>.</p> <p>However if you want to declare something in CPU and then on runtime move it to GPU you can go 2 ways:</p> <ol> ...
pytorch-lightning
0
3,922
64,037,148
TypeError: Object of type 'Add' is not JSON serializable - Python Graph
<p>I am working on trying to create a tangent approximation of a function. However, trying to find a way to graph it on top of the graph. Both functions work, but when I graph the functions, I come up with the type error &quot;Object of type 'Add' is not JSON serializable&quot;</p> <pre><code>x = sp.Symbol(&quot;x&quot...
<p>The issue is related to your coefficients (<code>f.subs(x,2).subs(y,2)</code>, <code>fx.subs(x,2).subs(y,2)</code>, and <code>fy.subs(x,2).subs(y,2)</code>). The coefficients are of type <code>&lt;class 'sympy.core.numbers.Float'&gt;</code>, which is not compatible for computations with numpy arrays. You can convert...
python|arrays|json|numpy|sympy
0
3,923
42,625,161
Get value from list in pandas
<p>I have a panda data frame (Python 2.11) containing the time as text in one column (format hh:mm:ss). I want to get the hours (minustes or seconds) only. For that I create a list </p> <pre><code>df.Time.str.split(":") </code></pre> <p>This way I get a list e.g. <code>[10,23,00]</code>. How can I access the first (s...
<p>I think you need parameter <code>expand=True</code> - then output is 3 columns of <code>df</code>:</p> <pre><code>df.Time.str.split(":", expand=True) </code></pre> <p>Sample:</p> <pre><code>df = pd.DataFrame({'Time':['10:23:00', '11:23:00']}) print (df) Time 0 10:23:00 1 11:23:00 df[['hour','minute','s...
python|list|pandas
5
3,924
42,938,354
Wondering about differences between Docker vs Supervisor
<p>They seem to accomplish the same thing of managing processes. What's the difference between Docker and Supervisor?</p>
<p>You can use supervisor in a docker container actually: when you can to make sure that exiting your container will kill <em>all</em> your processes.</p> <p>A Container isolate <em>one</em> main process: as long as that process runs, the container runs.</p> <p>But if your container <em>needs</em> to run several proc...
docker|supervisord|python-daemon
6
3,925
42,708,579
How to merge two count values using one expression with lambda?
<p><strong>In this small dataframe:</strong></p> <pre><code>d1 = pd.read_csv('to_count.mcve.txt', sep='\t') pos M1 M2 F1 F2 23 A,B,A,C,D A,C,B A D 24 A,B,B,C,B A,B,A B D 28 C,B,C,D,E B,C E D </code></pre> <p>I want to count <strong>how many of the values in F1 an...
<p>I would o this; first, make <code>pos</code> the index to eliminate it from all further operations:</p> <pre><code>d1.set_index('pos', inplace=True) </code></pre> <p>You cat <code>reset_index()</code> later if you want. Now, find the counts, convert them to strings, and "add":</p> <pre><code>d1.apply(lambda x: x[...
python|arrays|lambda|count|apply
1
3,926
66,712,435
Unable to resolve host name on AWS Lambda
<p>I am trying to reach an API which is deployed on an EC2 server.</p> <pre><code>req = requests.post(http://xxxxx:10002/scan, json=d) # xxxxx is the EC2 server hostname </code></pre> <p>When I execute the code on my machine it works fine. But when I try it on AWS Lambda it returns this error</p> <pre><code> &quot;erro...
<p>AS @ORP suggested, I only had to check lambda's SG and inbound/outbound rules were not allowing traffic to port 10002</p>
python|amazon-web-services|aws-lambda|python-requests
0
3,927
72,250,879
Can anyone explain that how to print max and min in the code
<ol> <li><p>This is a code</p> </li> <li><p>random is used in the code</p> </li> <li><p>the query is to find max and min value of z</p> <pre><code> import random x = random.randint(2,6) y = random.randint(1,2) z = x + y print(z) </code></pre> </li> </ol>
<p>Okay not a lot to go with but I think this is what you're trying to get:</p> <pre><code>import random x = random.randint(2, 6) y = random.randint(1, 2) z = max(x, y) print(z) </code></pre> <p>This would return the max value between x and y into the variable z</p>
python|random
0
3,928
72,297,419
Trying to find equal amount of characters in same string
<p>I want to see if a string has the same amount of 'x's and 'o's. The method must return a boolean and be case insensitive. The string can contain any chararacter.</p> <p>Examples input/output:</p> <pre><code>XO(&quot;xooxx&quot;) =&gt; false XO(&quot;ooxXm&quot;) =&gt; true XO(&quot;zpzpzpp&quot;) =&gt; true // when ...
<p>Just use <code>collections.Counter</code>.</p> <pre><code>&gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; c = Counter('xooxXo'.lower()) &gt;&gt;&gt; c['x'] == c['o'] True </code></pre> <p>or</p> <pre><code>&gt;&gt;&gt; c = Counter('xooxx'.lower()) &gt;&gt;&gt; c['x'] == c['o'] False </code></pre> <p>Wrap i...
python|python-3.x|append
2
3,929
50,812,654
Why the Line (antialiased) function of openCV2 gives different results on CV_16UC1 and CV_8UC1 without overflow
<pre><code>themap = cv.CreateMat(8,8,cv.CV_8UC1) cv.SetZero(themap) cv.Line(themap,(0,0),(7,7),(10),1,cv.CV_AA) #draw a line print np.asarray(themap[:,:]) #######output [[ 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0] [ 0 2 7 2 0 0 0 0] [ 0 0 3 10 3 0 0 0] [ 0 0 0 3 10 3 0 0] [ 0 0 0 0 ...
<p>Don't use the old, deprecated OpenCV API. Use the cv2 module instead and create your images with Numpy directly. With the following code, the result is as expected and is the same for both 8-bit and 16-bit images.</p> <pre><code>themap = np.zeros((8,8), dtype=np.uint16) ...
python|opencv|line|antialiasing|gaussianblur
1
3,930
3,637,503
What is the best way of running shell commands from a web based interface?
<p>Imagine a web application that allows a logged in user to run a shell command on the web server at the press of a button. This is relatively simple in most languages via some standard library os tools.</p> <p>But if that command is long running you don't want your UI to hang. Again this is relatively easy to deal w...
<p>I haven't heard of any libraries that do this, but you'll need to setup the system command and call out to the system. You will then need to "pump" the sysout and syserr standard inputs and pipe that data back out to your web client.</p> <p>As an example for this style of problem, look into code snippits of how pe...
python|ruby-on-rails|ruby|django|shell
1
3,931
35,329,055
Using Python to check if Telnet is still connected
<p>I'm writing a python program that uses Telnet to send the same few commands once every second, and then reads the output, organizes it into a Dictionary, and then prints to a JSON file (Were it is later read in by a front-end web-gui). The purpose of this is to provide a live-updates of crucial telnet command output...
<p>You can try following code to check if telnet connection is still usable or not.</p> <pre><code> def is_connected(self): try: self.tn.read_very_eager() return True except EOFError: print(&quot;EOFerror: telnet connection is closed&quot;) return False...
python|networking|telnet|telnetlib
2
3,932
61,559,077
Horizontal and vertical scrollview on same screen kivy
<p>I'm trying to create a screen which has a horizontal scrollview at the top of the page, taking up ~25% of the vertical space and a vertical scrollview taking up the rest of the space (and then being able to scroll further down the screen).</p> <p>I've managed to create a horizontal scrollview but can't get the vert...
<p>It took some work to get your MCVE working, but here is the part of your <code>kv</code> that I modified to get scrolling working in both directions with two <code>ScrollViews</code>:</p> <pre><code> ScrollView: #horizontal size_hint_y: 0.25 do_scroll_y: False GridLayout: ...
python|kivy|kivy-language
1
3,933
60,567,391
Docker Unable to connect to Flask
<p>I am trying to move a simple flask application to docker, but my flask application is not accessible from the browser.</p> <p>project tree</p> <pre><code>├───project │ │ dockerfile │ │ requirements.txt │ │ │ └───app │ server.py </code></pre> <p>dockerfile</p> <pre><code>FROM ubuntu:latest ...
<p>Setting this to run in debug mode by setting <code>app.run(debug=True)</code> shows that the host you think you are setting is getting overridden:</p> <pre class="lang-sh prettyprint-override"><code>❰mm92400❙~/test❱✔≻ docker run -it -p 5000:5000 testimage * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) ...
python|docker|flask|dockerfile
2
3,934
56,044,793
How to generate a 3D grid of vectors ? (each position in the 3D grid is a vector)
<p>I want to generate a four dimensional array with dimensions (dim,N,N,N). The first component ndim =3 and N corresponds to the grid length. How can one elegantly generate such an array using python ? </p> <p>here is my 'ugly' implementation:</p> <pre><code>qvec=np.zeros([ndim,N,N,N]) freq = np.arange(-(N-1)/2....
<p>Your implementation looks good enough to me. However, here are some improvements to make it prettier:</p> <pre><code>qvec=np.empty([ndim,N,N,N]) freq = np.arange(-(N-1)/2.,+(N+1)/2.) x, y, z = np.meshgrid(*[freq]*ndim, indexing='ij') qvec[0,...]=x # qvec[0] = x qvec[1,...]=y # qvec[1] = y qvec[2,...]=z ...
python|numpy|vector|grid|numpy-ndarray
0
3,935
57,598,499
Extracting text with selenium by ID
<p>I want to extract text using selenium in Python from an html. My text is under the id tag and when I try to retrieve the text this way gives me error.</p> <p><a href="https://i.stack.imgur.com/l3zum.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l3zum.png" alt="enter image description here"></a>...
<p>To retrieve the text <strong>4/20/2016</strong> you need to induce <em>WebDriverWait</em> for the <code>visibility_of_element_located</code> and you can use either of the followingcan use <a href="https://stackoverflow.com/questions/48369043/official-locator-strategies-for-the-webdriver/48376890#48376890">Locator St...
python|selenium|xpath|css-selectors|webdriverwait
1
3,936
57,498,675
How to check form field value before posting form - Django
<p>I have a form that currently works great with the exception that a user can input any value they want into one of the form fields. I would like to first check the field value when the user presses the submit button, before the form is actually submitted.</p> <p>Where is the best place to do this, I am assuming in t...
<p>you can access customerTag value in your view with:</p> <pre><code>customerTag = request.POST.get('customerTag') </code></pre> <p>and then check if it exists in your database</p> <pre><code># we retrieved customerTag in the code above sample so we pass it to filter params match = CustomUser.objects.filter(custome...
python|django
1
3,937
42,446,505
Incorporating Django's system checks into unit test suite?
<p>I recently deployed some broken code to our staging environment. The new code failed <a href="https://docs.djangoproject.com/en/1.10/topics/checks/" rel="nofollow noreferrer">Django's system checks</a> (error messages reproduced below, though this question is more general). Our unit test suite ran cleanly. My questi...
<p>According to <a href="https://code.djangoproject.com/ticket/25415" rel="nofollow noreferrer">this ticket</a>, not running checks along with the tests was a regression that was introduced in version 1.8, and has recently been fixed.</p> <p>As described there, an easy solution appears to be to create your own <a href...
python|django|unit-testing|testing
1
3,938
59,312,933
'save() prohibited to prevent data loss due to unsaved related object' even when parent object is saved
<p>Having issues with saving an object to DB. I read other similar posts and still can't understand why it fails because I do save the Monitor object before saving State.</p> <p>What am I missing here? </p> <pre><code>monitor = Monitors( hostname=form['hostname'], typ...
<p>Just remove the <code>id</code> field from the <code>Monitors</code> model. Django will create this field automatically and your problem will disappear.</p> <p><a href="https://docs.djangoproject.com/en/3.0/topics/db/models/#automatic-primary-key-fields" rel="nofollow noreferrer">https://docs.djangoproject.com/en/3...
python|django|django-models
1
3,939
58,311,786
Python integration in Qlik on MacOS
<p>I'm very new to using Qlik and at the moment I've only used the cloud via my browser. I would like to integrate python and Qlik such that I can run my code on data in the QlikCloud and visualize using Qlik. I am using a Mac, therefore I can not install the desktop version of Qlik to do the integration. Do you have a...
<h1>Use Data Load Script</h1> <p>When I first started Qlik, I had a very similar situation. My goal was to manipulate data to do calculations in Python, then basically import that into Qlik. What I ended up learning and realizing is that there's a 90% chance what you're trying to calculate outside of Qlik can be done ...
python-3.x|jupyter-notebook|qlikview|qliksense
3
3,940
65,233,291
How can I sort a string list based on edit distance efficiently?
<p>I'm trying to sort a list by edit distance using the levenshtein distance.</p> <pre><code>def suggest(dic, word, distance, maxSugestions=5): list = [] for i in range(1, 200): for word1 in sorted(dic): if distance(word1, word) == i: list.append(word1) if len(list)...
<p>I tried this technique I hope this will work for you</p> <pre><code>def edit_distance(word, string_to_take_distance_with = &quot;someString&quot;): ''' Description: give you the edit distance between 2 words word : String 1 (dynamic) string_to_take_distance...
python
1
3,941
65,211,144
Image Displaying On Mouse Problem Pygame How To Fix?
<p><a href="https://gyazo.com/46ce5c66bd433d4d0829f03cabda2163" rel="nofollow noreferrer">VIDEO</a> what I am trying to do is when my mouse clicks that button and my score is 1 then it should draw the image on the mouse but its only drawing when the mouse clicks on the button even though I added an else statement else ...
<p>Add a state <code>place_tower</code>. Set the state <code>True</code> when you click the button. Draw the tower at the current mouse position if the status <code>place_tower</code> is <code>True</code>:</p> <pre class="lang-py prettyprint-override"><code>place_tower = False run = True while run: for event in p...
python|pygame
1
3,942
28,451,739
start a program from python and not wait for it to exit
<pre><code>os.startfile(r"C:\Users\FZV3H2\Desktop\a.vbs") print("hello") </code></pre> <p>** I want the execution control to go to print("hello") as soon as the execution of "a.vbs" starts , and not wait for "a.vbs" terminate before going to next line . **</p>
<p>You need <a href="https://docs.python.org/2/library/subprocess.html#popen-constructor" rel="nofollow">Popen</a> from subprocess module of python</p> <pre><code>from subprocess import Popen Popen([r"C:\Users\FZV3H2\Desktop\a.vbs"]) </code></pre> <p>If you want it to be executed in a shell environment, give <code>sh...
python|python-2.7|python-3.x
0
3,943
41,645,209
Select largest square chunk for data from numpy array with no data values
<p>I need to select the square section of data within an 2D numpy array with nan's as the no data value. Here is a simplified example:</p> <pre><code>import numpy as np #Fake Data data =np.reshape(np.arange(100,dtype='float64'), (10,10)) extra_cols = np.zeros((1,10), dtype=data.dtype) data = np.concatenate((data,ext...
<p>I am pretty sure I cracked it. A couple of days and too much coffee.</p> <pre><code>import numpy as np def crop_to_data(mask, im): true_points = np.argwhere(mask) top_left = true_points.min(axis=0) # take the largest points and use them as the bottom right of your crop bottom_right = true_points.m...
python|arrays|numpy|image-processing|subset
0
3,944
41,388,130
Sorting a list of tuples by a certain element in a tuple
<pre><code>def insert(key, value, D, hasher = hash): x = hash(key) key_value = (x, key, value) D.append(key_value) sorted(D, key = lambda x:x[0]) return D insert("swag", 100, D, hash) insert("swg", 150, D, hash) print(D) </code></pre> <p>this never seems to be sorted,</p> <p>I want to sort the...
<p>You are sorting the list and immediately throwing the sorted list away. Note that <code>sorted</code> returns a new list so you'll also need to <em>reassign</em> the sorted list to the name <code>D</code>.</p> <pre><code>... return sorted(D, key=lambda x:x[0]) </code></pre> <p>To sort in-place, use the <em>sort</e...
python|python-2.7|python-3.x|tuples|sortedlist
4
3,945
44,650,280
sparse matrix transpose in scipy
<p>I initialized my sparse matrix like this:</p> <pre><code>from scipy.sparse import lil_matrix import numpy as np X = [lil_matrix((3,3)) for i in range(2)] X[0][0,0]=1 X[1][0,0]=1 X[1][0,1]=1 </code></pre> <p>I transposed this matrix like this:</p> <pre><code>elem =[a.toarray() for a in X] elem =np.array(elem) new...
<p>Make your array (with different dimensions to highlight the transpose ambiguity):</p> <pre><code>In [859]: X=[sparse.lil_matrix((3,4)) for i in range(2)] In [860]: X Out[860]: [&lt;3x4 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 0 stored elements in LInked List format&gt;, &lt;3x4 sparse matrix...
python|scipy|sparse-matrix
1
3,946
61,877,953
Eel python: Javascript error eel is not a function
<p>I am using eel to communicate with python. I'm working in dir <code>C:\Users\Desktop\Eel</code> where I have <code>app.py</code> and inside the <code>UI</code> folder I have <code>index.html, myjava.js, style.css, images</code> but nothing called <code>eel.js</code>. I said this because in docs it says to include sc...
<p>It seems that the init statement is written first. What about writing the @eel.expose statement right after the import statement?</p> <p>I'm not good at English, so I'm worried that it will make sense. But I would be happy if I could help.</p>
javascript|python|html|eel
1
3,947
62,015,892
Get object as output instead of List in Django
<p>I'm trying to get output result as an object but i'm getting result as a list.</p> <p>My view:</p> <pre><code>def Expense_with_id(request, id): details = ExSerializer(Cat.objects.filter(id=id).all(), many=True).data return JsonResponse(details, safe=False) Output: [{ "id": 1, "category": 1...
<p><code>ExSerializer(Cat.objects.get(id=id))</code></p> <p>You are doing <code>filter()</code> instead of <code>get()</code>.</p>
python|django|django-models|django-rest-framework|django-views
1
3,948
23,740,922
stream_with_context and stream_template raising a RuntimeError
<p>I am working from the following documentation: <a href="http://flask.pocoo.org/docs/patterns/streaming/" rel="nofollow">http://flask.pocoo.org/docs/patterns/streaming/</a> The following is a good portion of the traceback</p> <pre><code> File "(my template)", line 85, in block "scripts" {{ super() }} File "/u...
<p>I'm not completely familiar with what you're doing in the <code>stream_template</code> method, but based on the example, you need to use <code>stream_with_context</code> on the first argument to <code>Response</code>, not around a template parameter.</p> <p>If you need to stream based on the template, then maybe th...
python|python-2.7|flask
0
3,949
23,689,239
Django REST Framework - Getting params from QueryDict in a PATCH
<p>I curling a PATCH request like so:</p> <pre><code>curl --request PATCH http://api.mycompant.local:8000/v2/foo/15/bar/93923/?param=True </code></pre> <p>However, when I debug, I am finding that I can only access the value of <code>param</code> by using <code>request.GET</code>. <code>request.DATA</code> is empty. T...
<p>You must post some data:</p> <pre><code>curl --request PATCH http://api.mycompant.local:8000/v2/foo/15/bar/93923/ -d "param=True" </code></pre>
python|django|django-rest-framework
1
3,950
24,202,592
AlwaysError when running a testbench on a synchronizer
<p>I encountered this error when running a testbench, together with a synchronizer built on two existing D-FFs.</p> <pre><code>File "/home/runner/design.py", line 28, in Sync @always_seq(clk.posedge, reset=reset) File "/usr/share/myhdl-0.8/lib/python/myhdl/_always_seq.py", line 76, in _always_seq_decorator r...
<p>To model a wire delay, use the "delay" argument in the Signal.</p> <p>change</p> <pre><code>@always_seq(clk.posedge,reset=reset) def SyncLogic(): if reset: F2F.next = 0 dout.next = 0 else: F2F.next = din yield(WIRE_DELAY) dout.next = F2F return SyncLogic </code></pre> <p>to:</p...
python|myhdl
0
3,951
36,028,638
Practical use for matching 0 or more times in regex (*)
<p>I am just beginning with regex in python and am wondering if <code>*</code> i.e. matching something 0 or more times has utility in practical situations or not. Kindly help. Thanks</p>
<p>Imagine you have a substring with fixed start and finish items, which could be separated only with specific separators. For example: <code>"cat-cow"</code>, and you may have many dogs between them, or may not. Like this: <code>cat-dog-dog-cow</code> but you don't want to see another animals between them: <code>cat-h...
python|regex
1
3,952
29,737,521
PyCharm IDE: boto is already installed but got a "No module named boto.cloudfront" importError
<p>I have already got boto installed to my python virtual environment, as shown in the screenshot of my pycharm project.</p> <p><img src="https://i.stack.imgur.com/l3czV.png" alt="enter image description here"></p> <p>However I got an <code>ImportError</code> of boto.cloudfront when I run my script from pycharm</p> ...
<p>My project is a Google App Engine project. So even though boto is installed locally, it is not visible to my code within my Google App Engine project</p> <p>My solution is to copy the boto and all dependency into a <code>lib</code> subdirectory and then add it to the <code>sys.path</code></p>
python-2.7|pycharm
0
3,953
46,302,635
sqlalchemy/postgres: arithmetic on JSON fields?
<p>I am using sqlalchemy on a postgres database, and I'm trying to do arithmetic in a <code>SELECT</code> on two JSON fields which represent floats. However, I have not figured out how to make this work.</p> <p>Assume I have properly defined a table called <code>transactions</code> which contains a JSON column called ...
<p>OK. I finally figured it out. I have to pass each reference through the <code>astext</code> operator before applying <code>cast</code>, as follows ...</p> <pre><code>(transactions.c.cost_data['subtotal'].astext.cast(sqlalchemy.Float) + transactions.c.cost_data['cost'].astext.cast(sqlalchemy.Float)).label('total_cos...
json|python-3.x|casting|sqlalchemy
1
3,954
49,786,443
Delete CRLF in Row ending in CRLF
<p>I have been looking for some python code that will count delimiters in a record but can't seme to find any examples.</p> <p>I have a pipe delimited text file with double quotes for text qualifier with CRLF defining the end of the row. As always some columns have CRLF in the text which confuses the output format.</p...
<p>Maybe the following code is what you are looking for. Unfortunately there is a flaw which, so far, I cannot overcome: if a CRLF appears between 2 double quotes, but immediately after the first one, it is not removed. Apart from that, the code works for me.</p> <pre><code>from pathlib import Path import re regex = ...
python-3.x|csv
0
3,955
21,210,727
Precision of decimals in Python
<p>I don't mean precision as in how many numbers are displayed after the decimal. I mean precision as in the decimal I am trying to use in this pictograph function keeps coming up one tenth shy of what it should be. I have tried using multiple different strategies including importing the decimal module. Here is the fun...
<p>As I tried to explain in comments, the problem is that you're using floating point numbers.</p> <p>For more information on floating point, see <a href="http://en.wikipedia.org/wiki/Floating_point" rel="noreferrer">1</a>, <a href="http://docs.python.org/3/tutorial/floatingpoint.html" rel="noreferrer">2</a>.</p> <p>...
python|decimal|precision
7
3,956
70,068,720
Jupyter shell commands in a function
<p>I'm attempting to create a function to load Sagemaker models within a jupyter notebook using shell commands. The problem arises when I try to store the function in a <code>utilities.py</code> file and source it for multiple notebooks.</p> <p>Here are the contents of the <code>utilities.py</code> file that I am sour...
<p>You can use <code>transform_cell</code> method of IPython's shell to transform the IPython syntax into valid plain-Python:</p> <pre class="lang-py prettyprint-override"><code>from IPython import get_ipython ipython = get_ipython() code = ipython.transform_cell('!ls') print(code) </code></pre> <p>which will show:</p...
python|jupyter-notebook|jupyter|jupyter-lab
3
3,957
53,583,255
Seam insertion coordinates - Seam Carving
<p>I'm having some trouble understanding seam insertion for image enlarging with Seam Carving. AFIK to enlarge an image by k pixels it's necessary to remove k seams, recording their coordinates and using them to reproduce the process backwards, i.e. re-add the deleted seams but duplicating them and applying some kind o...
<p>As pointed out in the cooments, you have to fix indices anyway when inserting even if you can avoid &quot;fixing&quot; in removal part.</p> <p>You can find a full implementation of seam carving and seam insertion in python <a href="https://github.com/andrewdcampbell/seam-carving/blob/master/seam_carving.py" rel="nof...
python|image|algorithm|numpy|seam-carving
0
3,958
45,828,229
Aggregate values on lists of dicts based on key in python
<p>I'm trying to get the aggregation of 2 different lists, where each element is a dictionary with 2 entries, month and value.</p> <p>So the first list looks like this:</p> <pre><code>[{ 'patient_notes': 5, 'month': datetime.date(2017, 1, 1) }, { 'patient_notes': 5, 'month': datetime.date(2017, 2, 1) ...
<p>You can use <code>defaultdict</code> to create a counter. Go through each item in the first list and add the <code>patient_notes</code> value to the dictionary. Then go through the second list and add the <code>employee_notes</code> values.</p> <p>Now you need to encode your new defaultdict back into a list in yo...
python|list|dictionary
3
3,959
46,171,696
python call methods from super class
<p>I am trying to understand python inheritance a little. Here is a use case:</p> <pre><code>class Test: def hello(): print("hello") return "hello" def hi(): print(hello()) print("HI") class Test1(Test): hi() pass x = Test1() x.hello() </code></pre> <p>I don't unde...
<p>I think you are misunderstanding the relationship and definitions of <code>class</code>es and <code>object</code>s. <em>Classes are like blueprints to create objects</em>. By writing methods inside a class, you are essentially defining the behaviors of the object that can be created from the class blueprint. So, wit...
python|inheritance
0
3,960
54,821,361
What happened when user clicked "Upload" from index page?
<p>I'm studying some code from this repository of Liu Lixiang and I'm wondering how it actually works.</p> <p>The source is here: <a href="https://gist.github.com/liulixiang1988/cc3093b2d8cced6dcf38" rel="nofollow noreferrer">https://gist.github.com/liulixiang1988/cc3093b2d8cced6dcf38</a></p> <p>Firstly, when I get t...
<p>the action in the form is redirecting you to a url /upload via POST-Request:</p> <pre><code>&lt;form action="upload" method="post" enctype="multipart/form-data"&gt; </code></pre> <p>Now, the upload.html in the gist has the /upload route defined:</p> <pre><code>@app.route('/upload', methods=['POST']) </code></pre>...
python|html|flask
0
3,961
33,248,994
Run Angular SPA inside Django
<p>We had a standalone frontend server, which just served static AngularJS files. For SEO, we want to use a service such as Prerender, and hence need to run a server which can route URLs.<br> We are planning to Django backend with Prerender middleware for the same(since have a server running Python).</p> <p>I can serv...
<p>My recommendation is to use some kind of URL prefix (<em>STATIC_URL</em>) like "static" in order to clearly distinguish between requests to your Django views and your static files. </p> <p>To serve your static assets you could use <a href="http://whitenoise.evans.io/en/latest/django.html" rel="nofollow">whitenoise<...
angularjs|django|google-app-engine|google-app-engine-python
1
3,962
21,639,701
communicate between python and C++
<p>I want to create a python module which can have its functions called from a C++ class and call c++ functions from that class </p> <p>i have looked at boost however it hasn't seemed to make any sense it refers to a shared library (which i have no idea how to create) and i cant fallow the code they use in examples (...
<p>Python does not know about the C++ file, it will only be aware of the <em>extension module</em> that is compiled from the C++ file. This extension module is an object file, called a shared library. This file has an interface that looks to Python <em>as if it was a normal Python module</em>. </p> <p>This object file...
python|c++|boost|boost-python
4
3,963
41,064,365
pygame detecting mouse cursor over object
<p>I want to print a statement when the mouse cursor hovers over an image I loaded onto the screen, but it only prints when the mouse cursor hovers over the top left portion of the screen even if the image is in the center or bottom right.</p> <pre><code>import pygame, sys from pygame import * def main(): pygame....
<p>The method <code>Surface.get_rect()</code> returns a rectangle of the same size as the image but not at the same position! You'll get a rectangle positioned at (0, 0) which is why it prints when your mouse is in the top left corner. What you can do instead is take the arguments you use to position the surface and pa...
python|pygame
3
3,964
38,241,211
Regular expression in python replace
<p>Is there any way using regular expression in python to replace all the occurrences of <code>,</code> (comma) after the flower braces <code>{</code></p> <p>Data is of the following format in a file - <code>abc.json</code></p> <pre><code>{ "Key1":"value1", "Key2":"value2" }, { "Key1":"value3", "Key2":"value4" }, {...
<p>Test Source: <a href="https://regex101.com/r/wT6uU2/1" rel="nofollow">https://regex101.com/r/wT6uU2/1</a></p> <pre><code>import re p = re.compile(ur'},') test_str = u"{\n\"Key1\":\"value1\",\n\"Key2\":\"value2\"\n},\n\n{\n\"Key1\":\"value3\",\n\"Key2\":\"value4\"\n},\n\n{\n\"Key1\":\"value5\",\n\"Key2\":\"value6\"\...
python|json|regex|jq
1
3,965
38,233,661
set null to None in Python, is it a good practice?
<p>Very often when I deal with input/output that are generated from different languages, I often have to deal with the null values when I get those input/output into Python. As we all know <code>None</code> is the keyword for Python instead of <code>null</code>, so it often creates error when, say, the <code>null</code...
<p>This is not a good idea. It indicates some fuzziness in your program, a blurring of the line between code and input.</p> <p>Any code you write should use <code>None</code>, not a variable set to <code>None</code>. Having a <code>null</code> constant wouldn't help because you could simply write <code>None</code>.</p...
python|null
10
3,966
30,902,632
arcpy: program crashes on intersect
<p>I am writing a program that takes the input of two shape files that were exported with pgsql2shp.exe and does the intersection between them. Here is my code</p> <pre><code>print sys.argv[1], sys.argv[2] intersection = '' arcpy.Intersect_analysis([sys.argv[1], sys.argv[2]], intersection, "ALL") </code></pre> <p>whe...
<p>You've set the name of the output feature class to be an empty string. Try:</p> <pre><code>intersection = "Intersect_Output" </code></pre> <p>The output feature class (here, Intersect_Output) will be written to the geodatabase you're working in.</p>
python|python-2.7|gis|arcpy
1
3,967
31,072,395
Reversed IP localisation in python
<p>I have an old project in python : Get the IP corresponding to a location. I know we can get IP from a location (I've read <a href="https://stackoverflow.com/questions/2543018/what-python-libraries-can-tell-me-approximate-location-and-time-zone-given-an-ip">this</a>), and I would like to know if it's possible to reve...
<p>There are <a href="https://pypi.python.org/pypi/GeoIP/" rel="nofollow">Python bindings</a> for the <a href="http://dev.maxmind.com/geoip/" rel="nofollow">GeoIP</a> library.</p> <p>Also their databases are downloadable.</p> <p><a href="https://github.com/maxmind/geoip-api-python/tree/master/examples" rel="nofollow"...
python|ip
0
3,968
40,294,493
Setting up a login with python requests for indeed.com
<p>I'm trying to write a resume searcher for www.indeed.com (there's no API for resumes unfortunately). Specifically, I need to provide login details (to get names from resumes). The login page is here:</p> <p><a href="https://secure.indeed.com/account/login" rel="nofollow">https://secure.indeed.com/account/login</a>...
<p>You're missing multiple data fields.</p> <p>This worked for me</p> <pre><code>import requests data = { 'action':'Login', '__email':'Your Email', '__password':'Your password', 'remember':'1', 'hl':'en', 'continue':'/account/view?hl=en', } response = requests.p...
python|authentication
1
3,969
58,838,943
Find the "n" largest elements in a Python 'list' with duplicate values
<p>Suppose I have a list as shown:</p> <pre class="lang-py prettyprint-override"><code>test= [19, 2, 8, 12, 8] </code></pre> <p>I sorted it as:</p> <pre class="lang-py prettyprint-override"><code>print(sorted([(val, idx) for (idx, val) in enumerate(test)], reverse = True)) </code></pre> <p>Output is:</p> <pre clas...
<p>To get four largest numbers from a list you can use:</p> <pre><code>sorted(sorted(set(test), key=test.index), reverse=True)[:4] #[19, 12, 8, 2] </code></pre> <p><strong>EDIT</strong></p> <p>This will give you the desired output:</p> <pre><code>[i[::-1] for i in sorted(enumerate(test), key=lambda x: x[::-1], reve...
python|list
1
3,970
52,205,994
Queries in query set group in to one query using Django
<p>I have a query set like the below.</p> <pre><code>&lt;QuerySet[{'user':'xyz','id':12,'home':'qwe','mobile':1234}, {'user':'xyz','id':12,'home':'qwe','mobile':4321}, {'user':'abc','id':13,'home':'def','mobile':1233}, {'user':'abc','id':13,'home':'def','mobile':1555},]&gt; </code></pr...
<p>You can use the function which you have written, only change is required is need to order the values based on id. So before taking the values from the objects, <code>order_by('id')</code>, then take your required values and pass it to your function to merge the values.</p> <p>Eg.</p> <pre><code>query_set = Mymode...
mysql|django|python-3.x|orm|django-queryset
1
3,971
59,484,773
Plot a directed graph in Python?
<p>I am trying to make a directed graph or Sankey diagram (any would work) for customer state migration. Data looks like below, count means the number of users migrating from the current state to next state.</p> <pre><code>**current_state next_state count** New Profile Initiated ...
<p>For directed graphs, <code>graphviz</code> would be my tool of choice instead of Python.</p> <p>The following script <code>txt2dot.py</code> converts your data into an input file for graphviz:</p> <pre><code>text = '''New Profile Initiated 37715 Profile Initiated End 3...
python|plotly|directed-graph
10
3,972
19,114,052
'ascii' codec can't encode character '\xeb' in position 25: ordinal not in range(128) with urlopen(req).read()
<p>I am trying to retrieve automatically the image link of a news article and I wrote a python module <strong><em>imageprocessor</em></strong> with the <strong><em>getimage</em></strong> function, which identifies for a news article the image link:</p> <pre><code>req = Request('http://top-channel.tv/artikull.php?id=26...
<p>Seems like you have to decode your string first. Try this:</p> <pre><code>img = urllib.urlopen(link).read() img = img.decode(&lt;source encoding&gt;) img = unicode_str.encode("utf8") </code></pre> <p>An example could be:</p> <pre><code>img= '\xa0' img = img.decode("windows-1252") img = img.encode("utf8") </code><...
python|character-encoding|django-views
0
3,973
18,837,921
Python - How to insert blank line at certain directory level when doing directory walk?
<p>I know how to do a directory walk (using os.walk) and print out all files in a certain directory. What I want to do further is to insert a blank line after the contents of a directory are printed for all directories at a certain level. To illustrate, suppose I have these files:</p> <pre><code>/level1/level2a/file...
<p>You can try something like the following. It checks if the <code>root</code> path has more than the number of directory levels indicated in the argument variable (hard-coded in the example). In that case save it in <code>d</code> variable and the previous different one in <code>prev_d</code>. Then <code>print</code>...
python
0
3,974
69,186,756
dataframe lookup using another dataframe as column reference
<p>I have DF A with 3 columns (L,M,N) and n rows as:</p> <pre><code>L M N 1 2 3 4 5 6 7 8 9 </code></pre> <p>And DF B with 2 columns (X and Y) and n rows as:</p> <pre><code> X Y 'L' NaN 'M' 'N' 'N' 'L' </code></pre> <p>And I want a DF with n rows like:</p> <pre><code>1 NaN 5 6 9 7 </code></pre> <p>Basica...
<p>Bit hacky but one way using <code>pandas.Series.reset_index</code>:</p> <pre><code>def getloc(index): try: return df.loc[index[0], index[1]] except KeyError: return np.nan new_df = df2.apply(lambda x: x.reset_index().apply(tuple, axis=1)).applymap(getloc) print(new_df) </code></pre> <p>Outpu...
python|pandas
0
3,975
67,495,715
Python separating string into list at symbols
<p>I have a string that contains numbers and math symbols, such as: <code>data = &quot;1678-156&quot;</code> or <code>data = &quot;354+45&quot;</code>. How can I turn this into a list like so: <code>dataList = [&quot;1678&quot;,&quot;-&quot;,&quot;156&quot;]</code> or <code>dataList = [&quot;354&quot;,&quot;+&quot;,&qu...
<p>You could use <code>re.findall</code>:</p> <pre class="lang-py prettyprint-override"><code>data = &quot;1678-156&quot; parts = re.findall(r'[*/+-]|\d+(?:\.\d+)?', data) print(parts) ['1678', '-', '156'] </code></pre> <p>This answer assumes that the only components of your formula would be either basic arithmetic sy...
python|string|list
0
3,976
67,234,118
Why does my Morse Code decoding tool not find any subsequent characters?
<p>I am working on a Morse Code encoding/ decoding tool. I have completed the encoder, and I'm working on the decoder. Currently the decoding function &quot;<em>MorseCodeDecoder(MSG)</em>&quot; can decode a single letter at a time. It does this by checking every character in a string one by one and copying them to the ...
<p>Instead of blundering about with appending to strings and picking out each character from your encoded string to form a morse-code letter, you can just use <a href="https://docs.python.org/3.9/library/stdtypes.html?highlight=join#str.join" rel="nofollow noreferrer"><code>str.join()</code></a> and <a href="https://do...
python|python-3.x|morse-code
2
3,977
63,719,972
Fastest way to swap bytes of big file in Python
<p>For a project I need to swap 4 byte words in a fast way. I need to switch every word(4Bytes) of a big file(2mb) before I can use a other calculation algorithm.</p> <pre><code>def word_swaper(data): buf_swaped_data = b&quot;&quot; number_of_words = int(len(data) / 4) for word in range(number_of_words): ...
<p><del>Using two <code>io.BytesIO()</code>s benchmarks to be more than 3x as fast on my box</del> but <a href="https://docs.python.org/3.8/library/array.html#array.array.byteswap" rel="nofollow noreferrer">there's a built-in method for this</a> that's 550 times faster...</p> <pre><code>import timeit import os import i...
python|python-3.x
2
3,978
19,400,721
Reading through file 4 lines at a time
<pre><code>import os filePath = "C:\\Users\\siba\\Desktop\\1x1x1.blb" BrickName = (os.path.splitext(os.path.basename(filePath))[0]) import sys def ImportBLB(filePath): file = open(filePath) line = file.readline() while line: if(line == "POSITION:\n"): POS1 = file.next() POS...
<p>Replace your logic with this:</p> <pre><code>with open(file_path) as f: while True: try: line = next(f) except StopIteration: break # stops the moment you finish reading the file if not line: break # stops the moment you get to an empty line if...
python|file|while-loop|lines
1
3,979
13,326,667
Handling POST JSON Error in Flask
<p>I am writing an API and expecting data in JSON. My function works well and stores data in SQLite as follows:</p> <pre><code>if request.method == 'POST': if request.headers['Content-Type'] == 'application/json': db = get_db() data = json.loads(request.data) row = (data['lat'], data['long'...
<p>The moment you load data from JSON with <code>data = json.loads(request.data)</code> you have a python structure.</p> <p>If at that time it is <em>not</em> a dictionary, then whatever the request sent you did not hold the correct JSON structure (could be a list, for example).</p> <p>I'd use a <code>try</code> / <c...
python|http|flask
10
3,980
17,043,170
Python Bottle how to pass parameter as json
<p>I created an api for openerp using bottle</p> <p>It works well while access using browser</p> <p>I don't know how to pass it as json parameters</p> <p>The Problem is </p> <p>how can i call using api and pass json parameters like</p> <pre><code>http://localhost/api?name=admin&amp;password=admin&amp;submit=Submit...
<p><a href="http://bottlepy.org/docs/dev/api.html#bottle.BaseRequest.forms" rel="nofollow"><code>request.forms</code></a> is used for POST or PUT requests. The form in your code uses GET, not POST, so you should use <a href="http://bottlepy.org/docs/dev/api.html#bottle.BaseRequest.query" rel="nofollow"><code>request.qu...
python|json|wsgi|bottle
2
3,981
54,633,670
Python analog to C++ pointer to class member
<p>Is it possible to create pointer to Python class member (not method)?</p> <p>I want something like this:</p> <pre><code>class PClass: def __init__(self): self.a = 123 def foo(self, a): self.a = a # this works def bar(pointer_to_method): py_ex = PClass() pointer_to_method(py_ex, 321...
<p>Python is totally different from C++ when it comes to memory model and what "variables" really are, so your question doesn't really make sense. <a href="https://nedbatchelder.com/text/names.html" rel="nofollow noreferrer">I strongly suggest you read this</a> to understand why the mere concept of "pointer" doesn't ap...
python|c++
2
3,982
71,238,482
How do I avoid crashes when using xlwings? It crashes on xw.App()
<p>Im trying to make a simple sheet calculating the summation of two numbers: A3 = A1 + A2. I use the script below.</p> <pre><code>import xlwings as xw app = xw.App(visible=False) wb = xw.Book(r'C:/Data/xlwings/testxlwings.xlsx') sh = wb.sheets[&quot;Sheet1&quot;] sh.range(&quot;A1&quot;).value = 683 sh.range(&quot;...
<p>This is not really an answer to solve the problem, but new lines are not allowed in comments, therefore I write this as answer.<br /> I would check if python has access to excel (by using the COM interface). Therefore, open a excel workbook on your virtual machine and execute the following code in python:</p> <pre><...
python|excel|xlwings
0
3,983
9,281,742
How can I import hbase in python?
<p>I'm trying to play around with hbase in python and I am using the cloudera repository to install the hadoop/hbase packages. It seems to work as I can access and work on the database using the shell but its not fully working within python.</p> <p>I know to communicate with hbase I need thrift so I downloaded and co...
<p>Have a look at HappyBase (see <a href="https://github.com/wbolster/happybase" rel="nofollow">https://github.com/wbolster/happybase</a> for info). It is the modern way to interact with HBase from Python. It covers the complete Thrift API but wraps it in a much better interface.</p>
python|hbase|cloudera
3
3,984
9,210,731
What is the proper way to write to the Google App Engine blobstore as a file in Python 2.5
<p>I am currently exceeding the soft memory limit when I try to do simple writes to the Google App Engine blobstore. What is the proper way to write this code so that it does not leak memory? </p> <pre><code>from __future__ import with_statement from google.appengine.api import files from google.appengine.api import b...
<p>Unfortunately python's garbage collector is not perfect. Every write you do creates lots of small objects (via protocol buffer creation) that is not collected by python on the fly for some reason. I found that in mapreduce library I have to do</p> <pre><code>import gc gc.collect() </code></pre> <p>from time to tim...
python|google-app-engine
3
3,985
39,416,083
Automate webpage tasks without having to have a browser open?
<p>I know about tampermonkey/greasemonkey and have used it a fair bit, but now my task is to write a program that runs in the background and automates mundane tasks (clicking buttons, typing into input fields etc.) on a specific webpage. Running a browser in the background takes too much RAM and processing power, so I'...
<p>It depends on whether you want a script that interacts with a web UI, or a script that automates web requests. Do you <em>really</em> need to click buttons and type into input fields? Presumably, the data from those buttons and input fields is eventually sent to a web server. You could skip the entire UI and just...
python|selenium|automation
0
3,986
39,090,495
a python library that accepts some text, and replaces phone numbers, names, and so on with tokens
<p>I need a python library that accepts some text, and replaces phone numbers, names, and so on with tokens. Example:</p> <p>Input: Please call Robert on 0430013454 to discuss this further.</p> <p>Output: Please call <em>NAME</em> on <em>PHONE</em> to discuss this further.</p> <p>In other words I need to take a sent...
<p>As Harrison pointed out, nltk has named entity recognition, which is what you want for this task. <a href="https://gist.github.com/onyxfish/322906" rel="nofollow">Here</a> is a good sample to get you started.</p> <p>From the site:</p> <pre><code>import nltk sentences = nltk.sent_tokenize(text) tokenized_sentence...
python|python-2.7|pyparsing
1
3,987
55,326,468
Save ImageField in UpdateView Django
<ul> <li>I have an image field in profile model.</li> <li>I am not able to save the image from template.</li> <li>Tried saving image using django admin, it successfully saves the image and display the image in the update view.</li> </ul> <p>How do I save the image from frontend not from django admin?</p> <p><strong>M...
<p>Change image widget to <code>FileInput</code> </p> <pre><code>widgets = { 'image' : forms.FileInput(attrs={'class': 'input-image-control'}), ... </code></pre>
javascript|python|html|django
1
3,988
52,749,959
How to use Boto to self-terminate instance its running on?
<p>I need to terminate an instance from an AutoScalingGroup as the policies ASG has are leaving the scaled out instances running longer than desired. I need to terminate said instance after its done running a python process.</p> <p>The code already uses Boto to access other AWS services, so I'm looking to leverage Bot...
<p>An instance can be removed from an Auto Scaling Group by using <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/autoscaling.html#AutoScaling.Client.detach_instances" rel="nofollow noreferrer"><code>detach_instances()</code></a>:</p> <blockquote> <p>Removes one or more instances ...
python|amazon-web-services|amazon-ec2|boto
0
3,989
47,768,406
Extract Uniques and loop
<p>I have a dataframe that looks like this: </p> <pre><code> A B C 0 1 2 PRODUCT_1 1 3 2 PRODUCT_2 2 3 2 PRODUCT_4 3 3 2 PRODUCT_5 4 5 2 PRODUCT_1 5 3 2 PRODUCT_3 </code></pre> <p>I want to, for each unique product, perform a model prediction with A and B columns, and store the correspon...
<p>Starting with - </p> <pre><code>df = pd.DataFrame(...) # your data df A B C 0 1 2 PRODUCT_1 1 3 2 PRODUCT_2 2 3 2 PRODUCT_4 3 3 2 PRODUCT_5 4 5 2 PRODUCT_1 5 3 2 PRODUCT_3 </code></pre> <p>Find uniques first, using </p> <pre><code>uniques = df.C.unique() uniques array(['PRODUCT_1...
python|pandas|group-by|unique
0
3,990
47,865,986
Numpy TypeError for function
<p>I have been implementing an algorithm that requires I take the average of vectors from a specific point to a set of other points and "unitise" it. As such, I use this function:</p> <pre><code>import numba import numpy def dist(a,b): return ((a[0]-b[0])**2+(a[1]-b[1])**2)**0.5 @jit def point_average(o, points)...
<p><code>points</code> is a <code>list</code> of <code>arrays</code>, not a 2D <code>array</code>. Hence you cannot do</p> <pre><code>points[i, 0] </code></pre> <p>you could only do</p> <pre><code>points[i][0] </code></pre> <p>Also, if you consequently use NumPy arrays instead of lists and arrays, you don't need Nu...
python|numpy
0
3,991
37,553,882
Web Scrape in Python
<p>So I am trying to web scrape <a href="https://en.wikipedia.org/wiki/FIFA_World_Rankings" rel="nofollow">https://en.wikipedia.org/wiki/FIFA_World_Rankings</a> and scrape the first table on the page, but it has not worked and I get an error 'NoneType' object is callable. </p> <p>Here is my code: </p> <pre><code>from...
<p>You are missing the <code>findAll</code> (or <code>find_all</code>, if you want to be Pythonic) function to search for all tags under an element. </p> <p>You may also want to do a check on the data to make sure you don't get an IndexError like so. </p> <pre><code>for row in soup('table', {'class': 'wikitable'})[0]...
python|beautifulsoup
2
3,992
66,298,468
OSError: Label: File 'Gilroy-light.ttf' not found
<p>I m trying to add font file in my app but it is showing</p> <pre><code>OSError: Label: File 'Gilroy-light.ttf' not found </code></pre> <p>I have added <code>.ttf</code> at include ext. Line but then also this error is showing Include ext. Line:</p> <pre><code>source.include_exts = py,png,jpg,kv,atlas,ttf </code></pr...
<p>There isn't a lot of info to give a proper answer. But this is what I believe is going wrong.</p> <p>The answer depends on whether you are executing your program on your system or on your android device. But since you have added a line from the buildozer.spec file I will assume you are either attempting to compile t...
python|android|kivy|buildozer|kivymd
0
3,993
72,609,565
Logging source code before output in Spyder console
<p>When you run code in RStudio, it logs both the code and the output in the console (see <a href="https://r4epis.netlify.app/images/RStudio_overview.PNG" rel="nofollow noreferrer">here</a>). Is it possible to do the same in Spyder?</p>
<p>(<em>Spyder maintainer here</em>) You can run cells and get their contents printed on the console by going to the menu</p> <pre><code>Tools &gt; Preferences &gt; Editor &gt; Run code </code></pre> <p>and enabling the option called <code>Copy full cell contents to the console when running code cells</code>.</p>
python|spyder
1
3,994
72,547,478
Keras to Pytorch -> troubles with layers and shape
<p>I am in the process of converting a Keras model to PyTorch and would need your help.</p> <p>Keras Code:</p> <pre class="lang-py prettyprint-override"><code>def model(input_shape): input_layer = keras.layers.Input(input_shape) conv1 = keras.layers.Conv1D(filters=16, kernel_size=3, padding=&quot;same&quot;)(in...
<p>My Current Code is:</p> <pre class="lang-py prettyprint-override"><code>class Net(nn.Module): def __init__(self): super(Net,self).__init__() self.conv1 = nn.Conv1d(256,128,1) self.batch1 = nn.BatchNorm1d(128) self.avgpl1 = nn.AvgPool1d(1, stride=1) self.fc1 = nn.Linear(128...
python|tensorflow|keras|pytorch|conv-neural-network
1
3,995
39,798,473
Data Validation Using Functions
<p>How do I create a function that validates the following?</p> <pre><code>def get_order(): order=int(input("Select an item number: ")) return order </code></pre> <p>I tried this:</p> <pre><code>def validate_order(order_choice): order_choice=get_order() return order_choice while order_choice &lt;...
<p>I'm going to assume you want to validate that the order number is indeed an integer.</p> <p>To do this we will use the <code>isinstance()</code> function. Which accepts a variable and a type and returns <code>True</code> or <code>False</code> depending on whether or not it matches the second argument.</p> <p>In yo...
python|function|validation
0
3,996
16,079,185
My script returns an error when the test isn't corresponding to the Regex: 'NoneType' object has no attribute 'group'
<p>My script down here is supposed to return a result in this format </p> <pre><code>[ {'heure':xxxx,'mid': xxxx,'type message': "e.g SMS.Message ", "Origine":xxx,"Destination":xxxx}] </code></pre> <p>Well it works but without the Type message I've just added this so I think that the regex isn't correct. :/ It al...
<p>Change your extraire function to this, as you are trying to access properties on <code>ms</code> even when there are no matches. And when there are no matches, <code>ms</code> is None :</p> <pre><code>def extraire(data): ms = re.match(r'(\S+).*mid:(\d+).*(R:NVS:\w+)', data) # heure &amp; mid ...
python|regex|exception|python-2.x
1
3,997
16,056,082
Def function python: raw_input not store
<p>I'm newbie in python. I'm study hard to know well how python work since I starting study in 2013 at college. Sorry, if little messy. </p> <p>Let me showing my problem below. I have some def function looks like:</p> <pre><code>def thread_1(): a = input('Value UTS (100) = ') if a &...
<p>The variables a,b and c you are using on thread_1, thread_2 an thread_3 are only defined inside those functions. 'a' is only defined inside thread_1, b inside thread_2 and c inside thread_3, but theay are not global variables of the main program. The statement </p> <pre><code>return a </code></pre> <p>returns onl...
python|input|raw-input
0
3,998
38,938,938
Playing drum sounds in Python Music21 library
<p>It's been a couple of weeks since I started reading the book "Making music with computers: creative programming in Python" and now i'm stucked while trying to play drum sounds with this library. I'm using Mit's music21 library, as the one proposed by the book didn't work for me (it's called simply "music"). This is ...
<p>Hi Julian I made it work on my Mac with a minor change. I hope that would help! I basically changed only one line of your code and now it works on my Mac. When I say it works I mean it is creating the <code>mid</code> file correctly but fail to open it.</p> <p>The reason it fails to open it is that the default pla...
python|audio|midi|music21|midi-instrument
1
3,999
40,732,212
Occurence of a multiple symbol in a string-Python
<pre><code>string='I love #Snorlax he is a beast #op#letsgo' for item in string.split(): if item.startswith('#'): print(item) </code></pre> <p>The problem with my code is that the output i get is:</p> <pre><code>#Snorlax #op#letsgo </code></pre> <p>The output should be</p> <pre><code>#Snorlax #op </code...
<p>Try this:</p> <pre><code>string='I love #Snorlax he is a beast #op#letsgo' for item in string.split(): if item.startswith("#"): print("#" + item.split("#")[1]) </code></pre>
python-3.x
2