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,100
67,283,145
FileNotFoundError: [Errno 2] No such file or directory for logging in multiprocess(gunicorn) environment python
<p>I have using gunicorn to create my server and logging my file using python logging package. But when I am running gunicorn with 100 worker nodes with RotatingfileHandler I am seeing following error.</p> <pre><code>--- Logging error --- Traceback (most recent call last): File &quot;/usr/local/lib/python3.7/logging/...
<p><code>logging.config.dictConfig(config)</code> - it doesnt create a directory. Please check, do you have this /tmp/log/ directory?</p>
python|logging
-1
7,101
67,588,980
installing matplotlib ERROR: Command errored out with exit status -4
<p>I'm trying to install matplotlib in my Python env (rosnav) but I keep getting the same error:</p> <pre><code>(rosnav) ➜ ~ pip install matplotlib Collecting matplotlib Using cached matplotlib-3.3.4.tar.gz (37.9 MB) ERROR: Command errored out with exit status -4: command: /home/vis2020/python_env...
<ul> <li>This issue is related to a numpy issue: <ul> <li>NumPy 1.19.5 was being installed and it appears that there is an issue with OpenBLAS <ul> <li><a href="https://github.com/numpy/numpy/issues/18131" rel="nofollow noreferrer">https://github.com/numpy/numpy/issues/18131</a></li> </ul> </li> <li><a href="https://gi...
python|numpy|matplotlib|pip
4
7,102
60,501,663
get name of loss function used in keras model
<p>I want to save the name of the loss function I used in my keras model. I looked into the <a href="https://keras.io/models/about-keras-models/" rel="nofollow noreferrer">documentation</a> but haven't found a way to get this name. If possible I also want to save this name in case I use a custom loss function. Or at le...
<p>The loss is saved as an attribute inside the <code>model</code> object. I was not able to find it in the docs, I found it using <code>dir(model)</code>. You can retrieve from the attribute the name of the loss function, a <code>tf.keras.losses.Loss</code> instance or a custom callable.</p> <pre><code>model.compile(l...
python|keras|loss-function
0
7,103
70,204,652
Why does the Keras (Tensorflow 2.0) model does not include the variables of matrix multiplication, when plotted?
<p>I am using the following code to build a deep learning model in Keras (Tensorflow 2.0).</p> <pre><code>import tensorflow as tf keras = tf.keras from keras.layers import Input, Dense from keras.models import Model a = Input(shape=(138,7), name='inputP') b = Input(shape=(138,7), name='inputQ') c = tf.transpose(b, [0,...
<p>To make <code>plot_model</code> works properly, replace all those tensorflow operations like <code>tf.transpose</code> and <code>tf.matmul</code> with lambda layers such that every node in the functional API is a keras layer, i.e.,</p> <pre><code>import tensorflow as tf a = tf.keras.Input((138,7), name='inputP') b ...
keras|tensorflow2.0
2
7,104
65,945,874
Display Multiple Non Empty Dataframes on HTML Email
<p>I'm trying to display multiple dataframes in the body of an email to end users. There are 100 end users and each df is filtered to display only their entries. Some dataframes could be empty, depending on the records created by the end user. My code looks like this:</p> <pre><code>email_body = &quot;&quot;&quot;\ &lt...
<p>Looks like I've got a solution. I've set the curly brackets in the email body to reference index numbers.</p> <pre><code>email_body = &quot;&quot;&quot;\ &lt;html&gt; &lt;head&gt;&lt;/head&gt; &lt;body&gt; &lt;br&gt;{0}&lt;br&gt; &lt;br&gt;{1}&lt;br&gt; &lt;br&gt;{2}&lt;br&gt; ...
python|html|pandas
0
7,105
68,986,940
python3.7 & pandas - use column value in row as lookup value to return different column value
<p>I've got a tricky situation - tricky for me since I'm really new to python. I've got a dataframe in pandas and I need to logic my way through building a new column that will be used later in a data match from a difference source. Basically, the picture tells what I can't figure out.</p> <p>For any of the LOW label...
<p>Chosing a similar example as you did:</p> <pre><code>df = pd.DataFrame({&quot;a&quot;:[&quot;1&quot;,&quot;1.1&quot;,&quot;1.1.1&quot;,&quot;1.1.2&quot;,&quot;2&quot;],&quot;b&quot;:range(5)}) df[&quot;c&quot;] = np.nan mask = df.a.apply(lambda x: len(x.split(&quot;.&quot;)) &lt; 3) df.loc[mask,&quot;c&quot;] = df....
python-3.x|pandas|dataframe
1
7,106
68,192,949
Remove keywords which are not bigram or trigram (Yake)
<p>I am using Yake (Yet Another Keyword Extractor) to extract keywords from a dataframe. I want to extract only bigrams and trigrams, but Yake allows only to set a max ngram size and not a min size. How do you would remove them?</p> <p>Example df.head(0):</p> <p>Text: 'oui , yes , i mumbled , the linguistic transition ...
<p>If your problem is that the keywords list contains some monograms, you can simply do a filter that ignores words without spaces and create a new list. I'll give you an example:</p> <pre><code>keywords_without_unigrams = [] for kw in keywords: if(' ' in kw[0]): keywords_without_unigrams.append(kw) for ...
python|dataframe|keyword|n-gram
3
7,107
63,237,728
Finding row in pandas df and performing a diff relative to that row location
<p>I have a database object that returns my query outputs as a pandas df.</p> <p>One of my queries generates a list of dates (<strong>df1</strong>):</p> <pre><code> data_interestDate 0 2020-07-15T00:00:00 1 2020-06-11T00:00:00 2 2020-05-14T00:00:00 3 2020-04-14T00:00:00 </code></pre> <p>The other query returns...
<p>I found myself doing some formatting to get you to where you wanted your format to be, but:</p> <p>Query DF 1 (df1):</p> <pre><code>df1.head() data_interestDate 0 2020-07-15T00:00:00 1 2020-06-11T00:00:00 2 2020-05-14T00:00:00 3 2020-04-14T00:00:00 </code></pre> <p>Query DF 2 (df2):</p> <pre><code>df2.head(...
python|pandas|dataframe
1
7,108
62,277,715
Does deleting intermediate tensors affect the computation graph in PyTorch?
<p>To free up memory, I was wondering if it was possible to remove intermediate tensors in the forward method of my model. Here's a minimalized example scenario:</p> <pre><code>def forward(self, input): x1, x2 = input x1 = some_layers(x1) x2 = some_layers(x2) x_conc = torch.cat((x1,x2),dim=1) x_con...
<p>PyTorch will store the <code>x1, x2</code> tensors in the computation graph if you want to perform automatic differentiation later on. Also, note that deleting tensors using <code>del</code> operator works but you won't see a decrease in the GPU memory. Why? Because the memory is freed but not returned to the device...
pytorch
3
7,109
35,653,713
Is there a Python Isomap module that accepting distance matrix as well as original vectors?
<p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.manifold.Isomap.html" rel="nofollow">Isomap in well-known scikit-learn</a> only accepts plain vectors as input. But I only have a distance matrix. Is there any other Python module handling this?</p>
<p>Isomap is a two step process:</p> <p>1a. Given the original data points, find nearby neighbors. 1b. Compute a distance matrix D based on distances between points when you are only allowed to hop between nearby neighbors.</p> <ol start="2"> <li>Run Multidimensional Scaling on the distance matrix D. </li> </ol> <p...
python|machine-learning|visualization
4
7,110
58,693,802
How to convert columns from CSV file to json such that key and value pair are from different columns of the CSV using python?
<p>I have a CSV file with which contains labels and their translation in different languages:</p> <pre><code>name en_GB de_DE ----------------------------------------------- ElementsButtonAbort Abort Abbrechen ElementsButtonConfirm Confirm Bestätigen ElementsButtonDelete ...
<p>Say your data is as such:</p> <pre><code>import pandas as pd df = pd.DataFrame([["ElementsButtonAbort", "Abort", "Arbrechen"], ["ElementsButtonConfirm", "Confirm", "Bestätigen"], ["ElementsButtonDelete", "Delete", "Löschen"], ["ElementsButtonEdit", "Edit",...
python|json|csv|raspberry-pi3
0
7,111
49,067,263
Frame swapping is not working
<p>I want to switch the frame, but not able to do it</p> <p>1st Page(frame) should have red background color and "Hello" button and Frame size should have 900x650 as window size. When press "Hello" button it should swap to 2nd frame</p> <p>2nd page (frame) should have green background color and "Hello" button and Fra...
<p>Since you are using <code>pack()</code>, the second frame is placed <strong>below</strong> the first frame. You can check that by dragging the bottom part of the window. You'll see that there are 2 frames created with the red on the top, and the green on the bottom.</p> <p>You can use <a href="http://effbot.org/tki...
python|tkinter
2
7,112
48,915,796
finding a string in pandas dataframe column and cell
<p>I have a dataframe as below and I want to find how many times value from the column <code>Jan</code> occurs in the column <code>URL</code> and corresponding cell of the column <code>URL</code>. </p> <p>I want to create 3 columns - <code>found in cell</code> and <code>found in column</code> and <code>distinct finds<...
<p>Here is one way.</p> <pre><code>df['found_inCell'] = df.apply(lambda row: row['URL'].count(row['Jan']), axis=1) df['found_in_column'] = df['Jan'].apply(lambda x: ''.join(df['URL'].tolist()).count(x)) df['distinct_finds'] = df['Jan'].apply(lambda x: sum(df['URL'].str.contains(x))) # Feb Jan ...
python|pandas|search|text
2
7,113
25,234,996
Getting standard error associated with parameter estimates from scipy.optimize.curve_fit
<p>I am using <code>scipy.optimize.curve_fit</code> to fit a curve to some data i have. The curves, for the most part, seem to fit very well. For some reason, pcov = inf when i print it off.</p> <p>What i really need is to calculate the error associated with the parameters i'm fitting, and am not sure how exactly to d...
<p>The variance of parameters are the diagonal elements of the variance-co variance matrix, and the standard error is the square root of it. <code>np.sqrt(np.diag(pcov))</code></p> <p>Regarding getting <code>inf</code>, see and compare these two examples:</p> <pre><code>In [129]: import numpy as np def func(x, a, b, ...
python|scipy|mathematical-optimization|curve-fitting
14
7,114
25,024,313
How to customize QTreeWidget header's font
<p>Using:</p> <pre><code>tree=QtGui.QTreeWidget() tree.setHeaderLabels(['Column 1','Column 2','Column 3']) tree.setColumnWidth(0, 48) tree.setColumnWidth(1, 48) tree.setColumnWidth(2, 48) </code></pre> <p><code>QTreeWidget</code> is created. Its column headers are given names. And headers horizontal sizes are s...
<p>Assuming you want the font to be the same for the entire header, you should be able to do:</p> <pre><code>tree.header().setFont(font) </code></pre>
python|pyqt
1
7,115
72,317,872
Comparing two Numpy Arrays and keeping non-equal vectors in a third array
<p>I have two 2D arrays filled with vectors. I want to compare all the vectors of A to all the vectors in B and keep all the vectors of B that are unequal to the vectors in A. Like this on a small scale:</p> <p>A = [[0,1,0], [1,1,0], [1,1,1]]</p> <p>B = [[0,0,0], [1,0,0], [0,1,0], [1,1,0], [1,1,1]]</p> <p>Result = [[0,...
<p>If both arrays have a decent size, you can use broadcasting:</p> <pre><code>A = np.array([[0,1,0], [1,1,0], [1,1,1]]) B = np.array([[0,0,0], [1,0,0], [0,1,0], [1,1,0], [1,1,1]]) out = B[(A!=B[:,None]).any(2).all(1)] </code></pre> <p>Output:</p> <pre><code>array([[0, 0, 0], [1, 0, 0]]) </code></pre> <p>Altern...
python|arrays|numpy|compare
2
7,116
50,709,437
json-ld alias not parsing
<p>I am trying to learn json-ld and I am having some problems with aliases. </p> <p>When I use the JSON-ld playground with the following context and document:</p> <pre><code>{ "@context": { "url": "@id", "a": "@type", "name": "http://schema.org/name", "schema": "http://schema.org/" }, "url": "ht...
<p>The two examples are not the same. The problem with the Python example is that the input doc does not have a context. The processor first expands the data and will result in unknown terms that are dropped. You can see the problem if you print out the expanded data:</p> <pre class="lang-py prettyprint-override"><...
python|json|schema.org|json-ld
2
7,117
4,028,625
querying relation does not give back related object in sqlalchemy
<p>I have a very simple table(mapped as AuthToken class), consisting of a string ('token'), and a userid (foreign key to another table), with 'user' as relation ( = class User)</p> <p>session.query(AuthToken.user).one() gives back the token, and the userid (as a tuple), but not the user object.</p> <p>Does anybody kn...
<p>You should query mapped classes, not their attributes, if you want to receive objects.</p> <pre><code>token = Session.query(AuthToken).options(eagerload('user')).filter(...).one() user = token.user </code></pre>
python|orm|sqlalchemy
0
7,118
56,424,745
How to return the last element of a list with a for loop
<p>I need to extract the last character from each line based on this list:</p> <pre><code>lst = [ '-ae-' , '-ap-' , '-vn-' , '-au-' , '-aw-' , '-be-' , '-bp-' , '-br-' , '-dz-' ] </code></pre> <p>Here a sample of the <code>df['CN']</code> :</p> <pre><code>1: aes-sof-mar-goo-wh-en-ap-bro-sear-vn-loc 2: aes-br-mar-goo...
<p>Use <code>rfind</code> to find the rightmost occurence. Use <code>max</code> to find the rightmost rightmost occurence. This code assumes at least one <code>lst</code> member will be found; if none are found, it will return a <code>lst</code> member anyway.</p> <pre><code>def param(df): lst = ['-ae-','-ap-','-v...
python|python-3.x|pandas|jupyter
1
7,119
56,238,988
iteratively recalculating value of a column in pandas based on row value
<p>I have a Pandas dataframe <code>df</code>:</p> <pre><code>import pandas as pd df = pd.DataFrame({'item':[1,1,1,1,1,1,2,2,2,2,2,2], 'date':['2017-03-27','2017-04-03','2017-04-10','2017-04-17','2017-04-24','2017-05-01', '2017-03-27','2017-04-03','2017-04-10','2017-04-17','2017-04-24','2017-05-01'], ...
<p>A quick solution:</p> <pre><code>df['stock'] -= (df.groupby('item').stock .transform(lambda x: x.min() if x.min()&lt;0 else 0) </code></pre>
python|pandas
1
7,120
55,364,688
Python & Beautifulsoup 4 - Unable to filter classes?
<p>I'm trying to scrape shoe sizes from this URL: <a href="http://www.jimmyjazz.com/mens/footwear/jordan-retro-13--atmosphere-grey-/414571-016?color=Grey" rel="nofollow noreferrer">http://www.jimmyjazz.com/mens/footwear/jordan-retro-13--atmosphere-grey-/414571-016?color=Grey</a></p> <p>What I'm trying to do is get onl...
<p>What is you are asking for is to get the <code>a</code> tags with a specific class <code>box</code> and no other classes. This can be accomplished via <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#a-function" rel="nofollow noreferrer"><em>passing a custom function as filter</em></a> to <em>find_all...
python|web-scraping|beautifulsoup
1
7,121
57,379,849
Emulate one attribute of class instance for all operations
<p>I'd like for an instance of my class to always be treated as though it is one of its attributes, unless other attributes are specifically requested. For instance, suppose my class is: </p> <pre><code>class Value: def __init__(self, value, description): self.value = value self.description = desc...
<p>The "simple solution" is your second answer - subclass whatever the value is you're trying to act as. You can still override <code>__init__</code> and add whatever entities you need (though you also have to overwrite <code>__new__</code> as well - see <a href="https://stackoverflow.com/questions/35943789/python-can-...
python|class|attributes|instance
1
7,122
58,485,440
Using excel tables as a source for Bokeh plot
<p>How can I use an existing data table (e.g. Excel sheet) as a source for Bokeh data plot? </p>
<p>Pandas natively supports reading from Excel sheets in to DataFrames with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html" rel="nofollow noreferrer"><code>read_excel</code></a>:</p> <pre><code>df = pd.read_excel(...) </code></pre> <p>And Bokeh can adapt Pandas DataFrames d...
python|pandas|bokeh
2
7,123
25,519,163
Error: `gyp` failed with exit code: 1 while installing jugglingdb-postgres
<p>I am getting this error while installing jugglingdb-postgres in my ubuntu.help me to sort out this problem.Using Python 2.7.4 in my ubuntu.</p> <pre><code>gyp: Call to 'pg_config --libdir' returned exit status 1. gyp ERR! configure error gyp ERR! stack Error: `gyp` failed with exit code: 1 gyp ERR! stack at Ch...
<p><code>pg_config</code> isn't on your <code>PATH</code>.</p> <p>Adjust your <code>PATH</code> then make sure that running:</p> <pre><code>pg_config --version </code></pre> <p>works, and reports the correct PostgreSQL version, then try again.</p> <p>To locate <code>pg_config</code>:</p> <pre><code>locate */pg_con...
python|postgresql|ubuntu|npm|jugglingdb
0
7,124
46,285,185
Strassen's multiplication--> TypeError: 'int' object has no attribute '__getitem__'
<p>I'm writing a program for Strassen's matrix multiplication and I'm getting the following error: </p> <pre><code> Traceback (most recent call last): File "StrassensMult_v01.py", line 130, in &lt;module&gt; cMatrix = matrixMul(aMatrix, bMatrix) File "StrassensMult_v01.py", line 92, in matrixMul...
<p>The problem is in handling of the corner case in <code>matrixMul</code>, for order of matrix <code>A</code>, n = 1.</p> <pre><code>def matrixMul(A, B): n = getOrder(A) if n != 1: # ... else: C = [] C.append(A[0][0] * B[0][0]) return C </code></pre> <p>Notice you <strong>retu...
python|typeerror|strassen
0
7,125
46,567,188
How to uncheck all radio buttons from another class
<p>I want to uncheck some radio buttons in <code>class A</code> by pushing a button in <code>class B</code>.</p> <p>My example codes are as below:</p> <pre><code>import sys, os import PyQt4 from PyQt4.QtCore import * from PyQt4.QtGui import * class Widget1(QWidget): def __init__(self, bridge, parent=None): ...
<p>The buttons don't show up because you have not added the grid layouts to any of the widgets. So for <strong>all three</strong> grid layouts, do either this:</p> <pre><code> self.grid = QGridLayout() self.setLayout(self.grid) </code></pre> <p>or this:</p> <pre><code> self.grid = QGridLayout(self) </code>...
python|layout|pyqt4|signals-slots
0
7,126
21,174,913
greuests alternative - python
<p>I am developing a program that downloads multiple pages, and I used grequests to minimize the download time and also because it supports requests session since the program requires a login. grequests is based on gevent which gave me a hard time when compiling the program (py2exe, bbfreeze). Is there any alternative ...
<p>Sure, there are plenty of alternatives. There's absolutely no reason you have to use <code>gevent</code>—or greenlets at all—to download multiple pages.</p> <p>If you're trying to handle thousands of connections, that's one thing, but normally a parallel downloader only wants 4-16 simultaneous connections, and any ...
python|concurrency|compilation
4
7,127
54,837,314
Add relationship to three tables with data and strange column names
<p>I have a Postgres database with 3 tables with data and their models in Django. I do not have control over how these tables are filled. But I need to add relationships to them.</p> <p>It would not be a problem for me in MsSQL, Oracle or MySql. But Im confused here.</p> <pre><code>class Keywords(models.Model): ...
<p>Finally, I found a solution:</p> <pre><code>class Mapping(models.Model): id = models.AutoField(primary_key=True) video = models.ForeignKey(Videos, to_field='videoid', db_column='videoid', on_delete=models.DO_NOTHING,blank=False,null=True,) keyword = models.ForeignKey(Keywords, to_field='keyword', db_col...
python|django|postgresql
0
7,128
54,965,304
Finding only superstrings in collection
<p>While trying to help answer <a href="https://stackoverflow.com/q/54964548/225020">this</a> question I figured numpy would be a great alternative to python loops, although I can't seem to figure out how to do it and it's now become a mind puzzle I want to figure out but can't. I don't want to be credited with asking ...
<p>I don't think numpy is a good way to do this, why not a list comprehension like:</p> <pre><code>print([i for i in data if any([x in i and x!=i for x in data])]) </code></pre> <p>Output:</p> <pre><code>['testing', 'foobar', 'applepie'] </code></pre> <p>I think that's very good already, you answered it right, but ...
python|numpy
0
7,129
29,324,418
function doesn't continue to loop
<p>My function is acting a little bit weird.</p> <pre><code>def cow_latinify_sentence(sento): ''' Converting English to Cow Latin ''' alpha = list("bcdfghjklmnpqrstvwxyz") finale = [] worda = "" for word in sento.split(): finale.append(word) for i in finale: if i[0].lower() in alpha...
<p>When you <code>return worda</code>, you return the first word and then the function stops executing. Thus, it won't return anything else.</p> <p>In Python, I would suggest you use something called <em>list comprehension</em>. For details on how it works, please search Google. I will give you an example of how to ap...
loops|iteration|python-3.3
2
7,130
52,270,892
In Tensorflow, when use dataset.shuffle(1000), am I only using 1000 data from my whole dataset?
<p>When using the following code to train my network:</p> <pre><code>classifier = tf.estimator.Estimator( model_fn=my_neural_network_model, model_dir=some_path_to_save_checkpoints, params={ some_parameters } ) classifier.train(input_fn=data_train_estimator, steps=step_num) </code></pre> <p>wh...
<p>With <code>shuffle_buffer=1000</code> you will keep a buffer in memory of 1000 points. When you need a data point during training, you will draw the point randomly from points 1-1000. After that there is only 999 points left in the buffer and point 1001 is added. The next point can then be drawn from the buffer.</p>...
python|tensorflow
1
7,131
51,963,780
Using data from payload globally in python
<p>I need to use user's setup configuration in a Flask APP. The user will post certain data ( id, age etc) and I have to use this configuration in other methods as well. Now this is what I have tried which is not working</p> <pre><code>data_config = {} @app.route('/api/data', methods=['POST']) def check(): payloa...
<p>There is <code>global</code> missing. Try this:</p> <pre><code>data_config = {} @app.route('/api/data', methods=['POST']) def check(): global data_config payload = request.get_json() data_config = payload print(data_config) return jsonify(data_config) </code></pre> <hr> <p>BTW your solution l...
python|flask
3
7,132
43,484,307
Big oh Analysis
<p>Code 1:</p> <p>I my opinion this code is O(n^3) since the outer loop runs n^2 times and the inner loop runs n times. According to my prof this code is not O(n^3). Could someone please explain why? I am really confused. </p> <pre><code>i, j, sum = 1, 1, 0 while i &lt; n**3: while j &lt; n: sum = sum + i ...
<pre><code>i, j, sum = 1, 1, 0 while i &lt; n**3: while j &lt; n: sum = sum + i j += 1 i = i + n </code></pre> <p>Note that the inner loop is executed only during the first pass of the outer loop, because <code>j</code> is not reinitialized as in <code>for</code> loop. It is pretty obvious that the runn...
python-3.x|big-o
0
7,133
47,675,094
Implement perceptual loss with pretrained VGG using keras
<p>I am relatively new to DL and Keras.</p> <p>I am trying to implement perceptual loss using the pretrained VGG16 in Keras but have some troubles. I already found that <a href="https://stackoverflow.com/questions/43914931/vgg-perceptual-loss-in-keras">question</a> but I am still struggling :/</p> <p><strong>A short ...
<h2>Number of channels</h2> <p>Well, the first problem is significant. </p> <p>VGG models were made to color images with 3 channels... so, it's quite not the right model for your case. I'm not sure if there are models for black &amp; white images, but you should search for them.</p> <p>A workaround for that, which I...
tensorflow|keras|deep-learning|vgg-net
18
7,134
28,009,929
Python Non-Blocking Reading of Commands
<p>I'm trying to read command outputs from hcitools in Linux (it scans for bluetooth devices).</p> <p>I just need to read the first line that it returns, as sometimes this tool has an error. The issue is that this tool continues to run in a infinite loop, which locks up the rest of my Python script. The script is run ...
<p>It seems to me you cannot possibly join a thread, after you have just terminated it on the line above.</p> <p>Your particular issue about doing an lescan is probably better solved with the solution from mikerr/btle-scan.py - <a href="https://gist.github.com/mikerr/372911c955e2a94b96089fbc300c2b5d" rel="nofollow nor...
python|linux|bluetooth
0
7,135
47,089,821
Error when retrieving Date from datetime.date object in Python
<p>I want to retrieve date in the format of "May 01 2009" from datetime.date object. I have a table stored in MySQL database. It has Date column, and Time Column separately. Date in table is of the format,</p> <pre><code>2009-05-01 </code></pre> <p>I have connected to MySQL server using PyMySQL module,</p> <pre><cod...
<p><code>strftime</code> is a instance method of <code>date</code> objects, not a separate function:</p> <pre><code>print(row[0].strftime("%b %d %Y")) </code></pre> <p>The error message is trying to tell you that you're calling the uninstanced method (descriptor) from the <code>date</code> class directly, without pas...
python|mysql|anaconda|pymysql
0
7,136
29,921,407
4 dimensional array of zeros in python
<p>I want to make an 4 dimensional array of zeros in python. I know how to do this for a square array but I want the lists to have different lengths.</p> <p>Right now I use this:</p> <pre><code>numpy.zeros((200,)*4) </code></pre> <p>Which gives them all length 200 but I would like to have lengths <code>200,20,100,2...
<p>You can use <code>np.full</code>:</p> <pre><code>&gt;&gt;&gt; np.full((200,20,10,20), 0) </code></pre> <blockquote> <p><strong>numpy.full</strong></p> <p>Return a new array of given shape and type, filled with fill_value.</p> </blockquote> <p>Example :</p> <pre><code>&gt;&gt;&gt; np.full((1,3,2,4), 0) arr...
python|arrays|numpy
7
7,137
29,971,535
Reportlab Unordered List not showing bullets
<p>Whenever users input unordered lists using TinyMCE and it will look like this under source code</p> <pre><code>&lt;ul&gt; &lt;li&gt;item 1&lt;/li&gt; &lt;li&gt;item 2&lt;/li&gt; &lt;li&gt;item 3&lt;/li&gt;&lt;/ul&gt; </code></pre> <p>When it renders to PDF using reportlab, it shows up without bullets all on the...
<p>This worked.</p> <pre><code>{{ for note in notes }} {{script}} notesWithBullets = rml( note.body.replace('&lt;li&gt;', '&amp;bull; ').replace('&lt;/p&gt;','&lt;br&gt;').replace('&lt;/ul&gt;','&lt;br&gt;').replace('&lt;/li&gt;', '&lt;br&gt;')) {{endscript}} &lt;tr&gt;&lt...
python|tinymce|pdf-generation|reportlab|rml
0
7,138
70,624,272
Data-frame using values from different rows while iterating
<p><em>updated info at bottom</em> I have a group from a df.groupby that looks like this:</p> <pre><code> stop_id stop_name arrival_time departure_time stop_sequence 0 87413013 Gare de Le Havre 05:20:00 05:20:00 0.0 1 87413344 Gare de B...
<p>Convert your time columns to <code>Timedelta</code> with <code>to_timedelta</code></p> <pre><code>df['arrival_time'] = pd.to_timedelta(df['arrival_time']) df['departure_time'] = pd.to_timedelta(df['departure_time']) </code></pre> <p>Now use <code>itertools.combinations</code> to generate all combinations:</p> <pre><...
python|pandas|dataframe|pandas-groupby|nested-loops
1
7,139
70,022,866
how to make the snake go beyond the screen, it will return to the other side of the screen
<p>hey guys i just programmed the snake game but i want when x=0(my snake is in position 0) then immediately x=600 like it doesn't have a collision wall getting in its way, how can i do it?</p> <p>programming language: Python</p> <p>the library i use is pygame</p> <p>this is my code</p> <pre><code>import pygame, time ...
<p>Use the <code>%</code> (modulo) operator. The module operator computes the remainder of an integral division:</p> <pre class="lang-py prettyprint-override"><code>x = (x + x1_change) % 600 y = (y + y1_change) % 600 </code></pre> <hr /> <p>The actual problem in your code is that you set <code>x = 600</code>, but you t...
python|pygame
2
7,140
55,733,045
how to loop on all sub lists and compare each element with python
<p>How to compare multiple list items with each other and provide results?</p> <pre><code>X = [10 20 50 100 500 400] Y = [30 20 60 70 90 490] </code></pre> <p>Compare <code>X[0]</code> which is 10 with <code>Y[0]</code> which is 30 and check which list has greater number after comparing each element.</p> <p>How can...
<p>You might want to try something like the code below:</p> <pre><code>&gt;&gt;&gt; x = 10, 20, 50, 100, 500, 400 &gt;&gt;&gt; y = 30, 20, 60, 70, 90, 490 &gt;&gt;&gt; for index, (x_value, y_value) in enumerate(zip(x, y)): sign = '&gt;' if x_value &gt; y_value else '&lt;' if x_value &lt; y_value else '==' ...
python-3.x
2
7,141
66,649,027
Building randomized multiple choice quiz in Python. How to pull up additional questions?
<p>I am a new programmer working on my very first Python program ever.</p> <p>I am building a little quiz game in Python. The code contains ten possible quiz questions. In order to win, the user must get four of them correct in a row. To make the game more playable, I've set the questions to be assigned to a random num...
<p>Put:</p> <pre><code>while user_score &lt; 4: </code></pre> <p>On the line right above</p> <pre><code>computer_action = random.choice(question_list) </code></pre> <p>And then take every line below the <code>while</code> and tab it out once to put all of that in the while loop. (If you're using a decent text editor, y...
python|random
0
7,142
64,971,608
How to write `height : self.minimum_height` for BoxLayout in .py file -- kivy
<p>I am struck with a problem. I have a BoxLayout whose height was set to self.minimum_height in .kv file . However i was getting an error that <code>Nonetype Object has no attribute 'add_widget'</code> where <code>Nonetype</code> basically refers to the BoxLayout . The problem arised when i started using Screens. Howe...
<p>Of the several questions and answers on this topic, I didn't find one that showed how to get relative sizing in a scrollview application without using size_hint. I started from the example shown in the answer below, but rather than bind a callback to each of the individual widgets of the child layout of the scrollvi...
python|kivy
0
7,143
64,715,007
ModuleNotFoundError and import errors in Docker container
<p>When importing python modules locally, I am able to successfully do so, however I'm having difficulty doing so when dockerising the app. It seems as though I get the opposite behaviour locally to how I get in the docker app... any thoughts?</p> <p>I have the following directory structure</p> <pre><code>| app | ...
<p>I've just come across another thread on StackOverflow which seems to have resolved my issue. I can leave the import statements as I indicated above in my question, and by setting the PYTHONPATH in the docker container correctly, I am able to get the imports working correctly in docker.</p> <p><a href="https://stacko...
python|docker|dockerfile
4
7,144
63,844,935
Get exact formula used by Pytorch autograd to compute gradients
<p>I am implementing a custom CNN with some custom modules in it. I have implemented only the forward pass for the custom modules and left their backward pass to autograd. I have manually computed the correct formulae for backpropagation through the parameters of the custom modules, and I wished to see whether they mat...
<p>I don't believe there is such a feature in pytorch, even because it would be quite unreadable. What you can do is to implement a custom <a href="https://discuss.pytorch.org/t/defining-backward-function-in-nn-module/5047/2" rel="nofollow noreferrer">backward</a> method for your layer with the formula you derived, the...
pytorch|backpropagation|autograd
0
7,145
52,936,436
In the following question I implemented the Jacobi iteration method
<p>I used Latex for the math formatting.</p> <p><a href="https://i.stack.imgur.com/0jtrm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0jtrm.png" alt="enter image description here"></a></p> <p>My code: </p> <pre><code>import numpy as np from pprint import pprint from numpy import array, zeros, ...
<p>First, you need to write code to calculate <code>||A||</code> for a matrix <code>A</code>. Save the old matrix in <code>x_old</code>; after you iterate,subtract the old and new matrices and calculate that error figure. Compare it to 10^(-15).</p> <pre><code>x_old = x error = 1.0 # Dummy value iter_ct = 0 whil...
python
1
7,146
65,138,738
Multiple Output Prediction (Machine Learning)
<p>I'm on the newer side of learning about machine learning (keras/tensorflow) and am curious about how one might set up a network for taking in some input (an &quot;image&quot; with x channels/features) and be able to predict more than one value based off of this input. I've seen regression models, but the ones I've s...
<p>I'm not sure if you're talking about the design of models with the ability to predict multiple labels or just a problem of implementation.</p> <p>You can just simply sort the scores of the model's output, and take the top-N highest as the predictions. But if you're talking about how to design a model, there're lots ...
python|tensorflow|machine-learning|keras
0
7,147
68,539,734
Celery Crontab in not Picking the tasks
<p>I have added crontab for every 1 minute in the celery beat schedule. Migrations also done properly. can I miss anything in this code ?Is the crontab format will be correct.<br /> Thanks in advance . the crontab for minutes will work</p> <pre><code>settings.py INSTALLED_APPS = [ 'app1', 'django_celery_beat', ] CELERY...
<p>Change</p> <pre><code>*'schedule': crontab(minute=1),* </code></pre> <p>into</p> <pre><code>'schedule': crontab(minute='*/1'), </code></pre> <p>It should work.</p>
python|django|rabbitmq|celery|django-celery-beat
0
7,148
10,453,103
Methods to control environment when starting a lettuce test suite
<p>I'm building a test framework that will have a top level Gherkin interface backed by Python/Lettuce. We want to build it in to our continuous integration infrastructure (Hudson) as well as have the same tests be easily runnable on any environment (dev-int, qa-int, stage, etc). Since you can't pass parameters throu...
<p>Not sure what lettuce was like back then, but there is the <code>world</code> object <a href="http://lettuce.it/reference/terrain.html#world" rel="nofollow">(outlined here)</a>. The author admits that this is a little un-pythonic, but you can do something like this:</p> <pre><code>from lettuce import Runner, world ...
python|hudson|lettuce
0
7,149
5,486,049
issues when using pycassa with uwsgi
<p>We are using pycassa with uwsgi. There are about 16 uwsgi processes.</p> <p>It is strange that one process can get the data which is queried by another process. e.g. there is one row in column family A, looks like:</p> <p>{row_key, {'column_a': 1, 'column_b': 2}}</p> <p>process 1 run: get(row_key, columns=['colum...
<p>Open a connection for every worker using the uwsgi.post_fork_hook api function</p> <pre><code>import uwsgi def myconnect(...): global_connection = ... uwsgi.post_fork_hook = myconnect </code></pre>
python|cassandra|connection-pooling|uwsgi|pycassa
2
7,150
61,837,810
Cannot play the video in VideoCapture in python
<p>I have tried the video capture program using opencv in python. The code is given below</p> <pre><code>from cv2 import * a=VideoCapture(0) while(True): b,c=a.read() imshow("video",c) if(waitKey()==ord('s')): break a.release() destroyAllWindows() </code></pre> <p>For the above code,my webcam is ...
<pre><code>import numpy as np import cv2 cap = cv2.VideoCapture(0) while(True): ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('frame',gray) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() </code></pre>
python|opencv
2
7,151
62,007,270
how to search in google from python?
<p>i'm trying to make a script and for that script i need python to search in google for me is there a way to do that? like i'm telling python to search coffee and he will find it on google and open a tab the in that tab the search word is coffee? i've tried the serpapi but it didn't work is there any other way? this i...
<p>you can use module <a href="https://pypi.org/project/google/" rel="nofollow noreferrer">google</a>. </p> <p>Example:</p> <pre><code>from googlesearch import search query = "Apple" for res in search(query, tld="co.in", num=10, stop=10, pause=2): print(res) </code></pre>
python
0
7,152
67,237,081
Python threading does not execute properly
<p>I have a <em><strong>thread_function(ticker)</strong></em> which basically takes in a stock symbol as a string, checks if it meets the condition and if it does, appends it to a list. <em><strong>capitulation(ticker, df)</strong></em> function returns either stock symbol or nothing at all. As I loop through 5000+ tic...
<p>When using threading or multiprocessing your functions are going to have their own copy of these variables inside of the thread and will not update the variable in your main script. This is why that variable is empty.</p> <p>You should look at the Multiprocessing library, specifically the Pool and apply_async functi...
python|multithreading|queue|python-multithreading|python-3.8
1
7,153
67,259,042
problems with a portscanner in python
<p><strong>There's a cybersecurity course, and one of the exercises is to make a port scanner. I think mine works but still the instant feedback doesn't give me the points. Here's the exercise:</strong></p> <pre><code>import sys import socket def get_accessible_ports(address, min_port, max_port): found_ports = []...
<p>You're silenced all possible exceptions instead of specific ones (related to a connection problems) without any output:</p> <pre><code>try: ... except: ... </code></pre> <p>That's why you missed the problem with address: socket.connect() accepting a tuple of <code>(host, port)</code>. It's a <strong>single</s...
python|security
1
7,154
67,347,011
I wanted to print something when given two numbers gives remainder 0 in python. The following code is to demonstrate what I want but it didn't worked
<pre><code>A = '4' B = '2' while True: if A % B == 0: print(&quot;True&quot;) </code></pre>
<p>It'll not gonna work as <code>A</code> and <code>B</code> are of string data-type. You can't just evaluate the <code>%</code> operator on string values you need to convert the values in suitable data types 1st.</p> <pre><code>A = '4' B = '2' while True: if int(A) % int(B) == 0: print(&quot;True&quot;) <...
python
2
7,155
67,341,970
One line einsum functions with "interleaved" output indexing impossible to recreate using tensordot?
<p>The similarities and differences between NumPy's <code>tensordot</code> and <code>einsum</code> functions are well documented and have been extensively discussed in this forum (e.g. <a href="https://stackoverflow.com/questions/51989572/how-does-numpy-tensordot-function-works-step-by-step">[1]</a>, <a href="https://s...
<p>As I stress in my earlier answers, <code>tensordot</code> is an extension of <code>np.dot</code>, allowing us to specify which dimensions are used in the sum-of-products. The <code>dot</code> default is last of A, 2nd to the last of B.</p> <p>This illustrates how <code>dot</code> handles dimensions greater than 2:<...
python|arrays|numpy|numpy-einsum|tensordot
1
7,156
60,601,757
Importing edges to networkx library in Python
<p>I am working on a social network analysis problem where I have a directed graph. I get an issue when I import the edges to my graph file, which for some reason makes it undirected, making it impossible to measure centralities such as in/out degree etc.</p> <h1>importing edge and node pandas dataframe</h1> <pre><co...
<p>You need to specify in the <a href="https://networkx.github.io/documentation/stable/reference/generated/networkx.convert_matrix.from_pandas_edgelist.html" rel="nofollow noreferrer"><code>from_pandas_edgelist</code></a> the <code>create_using</code> parameter. So replace</p> <pre><code>G = nx.from_pandas_edgelist(ed...
python|networkx|sna
1
7,157
60,607,644
WhatsApp Web Automation with Python Selenium (unable to locate element)
<p>I am using python and selenium to send a message to a target.</p> <p>I can successfully open whatsapp web but after that I cannot open the inbox of the contact to whom I want to send the message.</p> <p>Here is the code so far. The first part is common where I have to open the web page. It happened without any pro...
<p>Finally, I got the answer.</p> <p>I realize there is no point in opening the search box. Typing name in the search box only brings the name appear on top, it cannot select any of the contacts.</p> <p>We should find the name of the contact from the center-left side of the screen.</p> <p>For that use:</p> <pre><co...
python|selenium|selenium-webdriver|selenium-chromedriver|webautomation
2
7,158
60,555,153
How do I make two different things happen at the same time in Python?
<p>I'm used to multiprocessing, but now I have a problem where <code>mp.Pool</code> isn't the tool that I need.</p> <p>I have a process that prepares input and another process that uses it. I'm not using up all of my cores, so I want to have the two go at the same time, with the first getting the batch ready for the ...
<p>You should be able to use <code>Pool</code>. If I understand it correctly, you want one worker to prepare the input for the next worker which runs and does something more with it, given your example functions, this should do just that:</p> <pre><code>pool = mp.Pool(2) for i in range(4): next_input = pool.apply(...
python|concurrency|parallel-processing
0
7,159
63,375,098
move mouse relatively in Linux
<p>I want to move my mouse relatively to the right. I already installed</p> <ul> <li>Python (3.8.2 (default, Jul 16 2020, [GCC 9.3.0])</li> <li>inside AutoKey 0.95.10.</li> </ul> <p>My prototype (below) can do absolutely move. Is that possible with autopilot.input or do I have to try something different?</p> <pre><code...
<p>it moves the mouse relatively using <code>autopilot.input</code>.</p> <p>to install:</p> <p><code>sudo apt-get install python3-autopilot</code></p> <pre><code>from autopilot.input import Mouse mouse = Mouse.create() x, y = mouse.position() mouse.move(x + 100, y + 100) </code></pre>
python-3.x|autokey
1
7,160
63,563,041
Selenium how to click over elements stored in a list
<p>I am trying to get all elements by partial link text then after that click on each of them and from the following page get some info. My idea was I should click on each link then back to the previous page then repeat the process for the other links. I saw this post <a href="https://stackoverflow.com/questions/491616...
<p>stale elements are not clickable. It means that you have navigated to another page. If you want to click all those link again, you can go back to that page and reload the list. Another way is to use driver.get for the the URL's (the link you want to click)</p> <p><a href="https://seleniumbyexamples.github.io/navget"...
python|selenium|selenium-webdriver|web-scraping
1
7,161
63,417,786
Animated scatterplot with colorcoding looses color (Python/ Plotly)
<p>I have a 4D dataset with 3 dimensions describing the data and the fourth a time-index. Plotting the dataset as a scatterplot with colorcoding for the 3rd dimension works fine. When I try to animate it using the fourth dimension the color coding stops to work. As the chart should be easy to read, plot.ly is used for ...
<p>May i suggest adding point size as another dimension instead of animation.</p> <pre><code>fig = px.scatter( df, x=&quot;2.Value&quot;, y=&quot;3.Value&quot;, color=&quot;4.Value&quot;, size=&quot;1.Value&quot;, range_x=[0,20], range_y=[0,20] ) fig.show() </code></pre> <p><a href="https...
python|animation|plotly
0
7,162
56,701,139
Model-logging for "hybrid models" (e.g. SKlearn Pipeline including KerasWrapper) possible?
<p>I have wrapped my keras-tf-model into a Sklearn Pipeline, which also does some pre- and postprocessing. I want to serialize this model and capture its dependencies via MLflow.</p> <p>I have tried <code>mlflow.keras.save_model()</code>, which seems not appropriate. (it's not a "pure" keras model and as no <code>save...
<p>You can add extra dependencies when you save your model, for example if you have a keras step in your pipeline you can add keras &amp; tensorflow:</p> <pre><code> conda_env = mlflow.sklearn.get_default_conda_env() conda_env["dependencies"] = ['keras==2.2.4', 'tensorflow==1.14.0'] + conda_env["dependencies"] ml...
python|keras|scikit-learn|mlflow
3
7,163
56,502,490
Producing some output if an item is present in one list, not in other list
<p>I have two lists of dates. I want to produce an output if a date is present, another if not. My code is:</p> <pre><code>main_list = ['2019-01-24', '2019-01-25', '2019-01-26', '2019-01-27', '2019-01-28', '2019-01-29', '2019-01-30'] result_list = ['2019-01-24', '2019-01-26', '2019-01-27', '2019-01-30'] </code></pre>...
<p>In your case </p> <pre><code>list(map(int,[x in result_list for x in main_list])) [1, 0, 1, 1, 0, 0, 1] </code></pre>
python
1
7,164
56,757,043
Sum two dataframes with different indexing
<p>I have two dataframes with different indexing that I want to sum the same column from the two dataframes. Based on a suggestion, I tried the following but removes disregards other columns like <code>cat</code></p> <pre class="lang-py prettyprint-override"><code>df = df.set_index('date') tmp = tmp.set_index('date')...
<p>Try <code>update</code>:</p> <pre><code>df.Anomaly.update(df.Anomaly+tmp.Anomaly) </code></pre> <p>Output:</p> <pre><code> cat Anomaly date 2018-12-06 a 0 2019-01-07 b 1 2019-02-06 a 1 2019-03-06 a 0 2019-04-06 b 0 </code></pre>
python|pandas
1
7,165
17,856,674
How to set-up this Python data structure in R
<p>I have the following data structure in Python that I would like to set-up in R. What is the correct way to achieve this that's most akin to the Python set-up.</p> <pre><code>testing = [ [[12,14], [4]], [[2,1], [5]], [[42,11], [13]] ] </code></pre> <p><strong>EDIT 1</strong></p> <p>Base...
<p>This is not an answer but maybe a general method to convert structure from python to R. Why not to use an intermediate format to transform your python structure to R structure. for example, through <code>json</code> format.</p> <h3>python</h3> <pre><code>import json testing = [ [[12,14], [4]], [[2,1], [5]]...
python|r
3
7,166
61,153,278
Avoid overlapping bounding boxes in Tensorflow Object Detection API
<p>I am using the Tensorflow Object Detection API to train my own numberplate detector. I used <code>ssd_mobilenet_v3_small_coco</code> as feature extractor. When I tested my model using the Object detection tutorial, I found that same object is detected multiple times. After some searching, I found that tensorflow use...
<p>You can refer it here <a href="https://www.tensorflow.org/api_docs/python/tf/image/non_max_suppression" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/image/non_max_suppression</a></p> <p>When you run your model on one image it spits out an output dictionary ie output_dict</p> <p>Set you thr...
python|tensorflow|object-detection|bounding-box|object-detection-api
0
7,167
60,979,672
InfluxDB - query working on Grafana but not in Python
<p>I'm trying this query from Grafana and it works perfectly: SELECT * FROM "x" WHERE time > '2020-03-31' AND time &lt; '2020-04-02'</p> <p>The problem is, in python I have to format the query as a string, and I run into the following problems:</p> <p>1) if I use double quotes around the whole line, I get invalid syn...
<p>I'm not sure it can work but you could try to use <strong>triple quotes</strong>. The questions of mixing single and double quotes was asked <a href="https://stackoverflow.com/a/7487171/13187605">here</a>.</p> <p>Example:</p> <pre><code>print(""" I'm "Bob" """) </code></pre> <p>Use spaces around the triple space ...
python|python-3.x|database|influxdb|influxdb-python
0
7,168
61,160,295
How can I use for loop to build a dictionary that can reads values from a list?
<p>The first number is the student id, the second is the code of the course.</p> <pre class="lang-py prettyprint-override"><code>course = ["001, aly6015", "002, aly6050", "001, aly6020", "003, aly6070", "001, aly6140"] dict = {} for i in course: </code></pre> <p>I want to build a dictionary like the following: when...
<pre><code>from collections import defaultdict d = defaultdict(list) for item in course: sid, cid = item.split(', ') d[sid].append(cid) </code></pre>
python|python-3.x
1
7,169
66,177,097
Python Shared Memory using mmap and empty files
<p>I'm trying to make a fast library for interprocess communication between any combination of Python and C/C++ processes. <code>(i.e. Python &lt;-&gt; Python, Python &lt;-&gt; C++, or C++ &lt;-&gt; Python)</code></p> <p>In the hopes of having the fastest implementation, I'm trying to utilize shared memory using mmap. ...
<p>To answer the questions directly as best I can:</p> <ul> <li><p>The file needs to be sized appropriately before it can be mapped. If you need more space, there are different ways to do it ... but most portable is likely unmap the file, resize the file on disk, and then remap the file. See: <a href="https://stackov...
python|c++|ipc|shared-memory
3
7,170
72,659,589
how to append multiple columns of a huge dataset in a csv file to a data frame
<p>I have a dataset in a csv file and I need to append some of its columns to a list. the dataset is very huge and its length is 2222678 rows.Here is my code to append its columns to list. However it gets stuck and my computer runs slowly. I appreciate if anyone can tell me is there a way to append that huge data into ...
<p>It seems you are appending your column data line by line, hence the large amount of time. I would suggest transforming those columns into lists like so:</p> <pre><code>input_data_x = list(dataset[&quot;pos_x&quot;]) input_data_y = list(dataset[&quot;pos_y&quot;]) </code></pre> <p>If you want tuples of x and y you ca...
python
1
7,171
68,059,129
request.user.is_authenticated is false on certain HTML on certain pages but not in views
<p>Most pages on this website I'm creating for practice <code>{% if request.user.is_authenticated %}</code> go through as true. But there is one page that always returns this as false (I've pasted that section of code below). Even though in views.py the function that controls that page, show when I run</p> <p><code>pri...
<p>When you create a django project there is such a thing as template context processor, context processor makes available variables, that we create in our code in templates.</p> <p>'django.contrib.auth.context_processors.auth', sets the request user variable, and makes it available in every django template.</p> <p>In ...
python|django|authentication
2
7,172
59,092,497
python glob exclude pattern in the file name
<p>This should be simple but I could not get it working. I would like to list the files in a directory by excluding files containing a certain pattern using glob.glob in python.</p> <p>The files in my directory are:</p> <p><code>lh.Hip.nii, lh.IPL.nii, lh.LTC.nii, rh.Hip.nii, rh.IPL.nii, rh.LTC.nii</code></p> <p>an...
<p>try this : </p> <pre><code>result = [] files = glob.glob('*') for f in files : if 'Hip' not in f : result.append(f) </code></pre> <p>The result in your case is : <code>['lh.IPL.nii', 'lh.LTC.nii', 'rh.IPL.nii', 'rh.LTC.nii']</code></p>
python|glob
0
7,173
62,999,309
why does ~(True ^ False) return -2
<p>I tried the following command line in python</p> <pre><code>In[1]: ~(True ^ False) </code></pre> <p>and it returned :</p> <pre><code>Out[1]: -2 </code></pre> <p>Could someone explain this to me please?</p> <p>Thanks in advance</p>
<p>It's because of how python handles booleans:</p> <p><code>True</code> is represented as 1, (See <code>True==1</code>)</p> <p><code>False</code> is represented as 0. (See <code>False==0</code>)</p> <p>Without syntactic sugar and abstractions:</p> <pre><code>x=~(1 ^ 0) x=~1 x=-2 </code></pre>
python|bit-manipulation|bitwise-operators|boolean-logic|boolean-operations
1
7,174
62,246,318
Flask-PyMongo. How to display all entries from python to html?
<p>one entry contains: title, link, time, text. How to display all entries from python to html? I tried a lot of options, but I couldn't find the correct syntax. Last try:</p> <p>App.py:</p> <pre><code>from flask import Flask, render_template, jsonify from flask_pymongo import PyMongo app = Flask(__name__) app.conf...
<p>Please consider my comment.</p> <blockquote> <p>You are querying it wrong, the first argument to the <code>find</code> is the filter, second is projection.</p> </blockquote> <p>I think you need to do like this:</p> <p><strong>app.py:</strong></p> <pre class="lang-py prettyprint-override"><code>@app.route('/', ...
python|mongodb|flask|pymongo|flask-pymongo
0
7,175
62,442,259
How to match a string after colon on Regex
<pre><code>text = Bounding box for object 1 "PASpersonWalking" (Xmin, Ymin) - (Xmax, Ymax) : (160, 182) - (302,431) </code></pre> <p>I need only : <code>(160, 182) - (302,431)</code> from the text</p>
<pre class="lang-py prettyprint-override"><code>rgx = r'^.+:(.+)$' re.search(rgx, text).group(1) </code></pre> <p><code>^</code>: Start at beginning of string</p> <p><code>.+:</code>: Allow any characters until a colon</p> <p><code>(.+)$</code>: Capture all characters until the end of the string</p> <p>To put it in...
python|regex
1
7,176
62,267,084
How to insert value/key from a dict in a list in postgres
<p>im creating a db and want to insert links from a value/key dictionary in a list, looks loke this:</p> <pre><code>"images": [{ "link": "https://images-url.com/images/I/61lYKVLbPZL0._AC_SL1500_.jpg", "variant": "MAIN" }, { "link": "https://images-url.com/images/I/7165NDvwSKL0._AC_SL1500_.j...
<p>i solve in this way: data = </p> <pre><code>{ "product": { "images": [{ "link": "https://images-url.com/images/I/61lYKVLbPZL0._AC_SL1500_.jpg", "variant": "MAIN" }, { "link": "https://images-url.com/images/I/7165NDvwSKL0._AC_SL1500_.jpg", "varia...
python|json|database|postgresql-9.4
0
7,177
58,733,756
Remove Puncuation From JSON File Only Inside Quotation Marks
<p>I have multiple JSON files filled with strings that can get up to several hundred lines. I'll only have three lines in my example of the file, but on average there are about 200-500 of these "phrases":</p> <pre><code>{ "version": 1, "data": { "phrases":[ "A few words that's it.", ...
<p>This should work.</p> <pre><code>import re import json with open('C:/test/data.json') as json_file: data = json.load(json_file) for idx, v in enumerate(data['data']['phrases']): data['data']['phrases'][idx] = re.sub(r'-',' ',data['data']['phrases'][idx]) data['data']['phrases'][idx] = re.sub(r'[^\w\...
python|json|python-2.7
4
7,178
73,480,017
Handle blank/empty CSV cells
<p>I have two sets of geolocation data as lat/long in a csv file. The first two columns (0 and 1) comprise the latitude and longitude of the first set, and the next two columns (2 and 3) comprise the second set. The first set contains about 100 entries and the second set contains about 75. I want to plot both sets onto...
<p>From the docs <a href="https://numpy.org/doc/stable/reference/generated/numpy.loadtxt.html#numpy-loadtxt" rel="nofollow noreferrer"><code>numpy.loadtxt</code></a></p> <blockquote> <p>This function aims to be a fast reader for simply formatted files. The genfromtxt function provides more sophisticated handling of, e....
python|numpy|csv
0
7,179
70,871,669
Interpretation of counts for `numpy.unique` when applied on a matrix
<p><code>numpy.unique</code> has an optional argument <code>return_counts</code>. From the docs:</p> <blockquote> <p>return_counts bool, optional If True, also return the number of times each unique item appears in ar.</p> <p>New in version 1.9.0.</p> </blockquote> <p>Which is straightforward for a 1-D array. However, ...
<p>When you specify an axis, <code>np.unique</code> returns unique subarrays indexed along this axis. To see is better, assume that one of the rows repeats:</p> <pre><code>m_sample = np.array([ [1, 2, 1], [2, 2, 2], [3, 3, 3], [1, 4, 5], [1, 2, 1] ]) </code></pre> <p>In such case <code>np.unique(m_s...
python|numpy
0
7,180
59,948,234
Flask - Multi user access with OOP
<p>I created an app with flask but I'm having a problem with multi-user access bcs of the <strong>global variables</strong>. Whenever I run the script (it might take minutes) and someone else is trying to access the page and run a script there too a collision appear and data by both users mix. </p> <p>I truly understa...
<p>Your problem has absolutely nothing to do with OO - it's only the result of using gobal variables. </p> <p>Your flask server process will serve all incoming requests, one after the other. So what happens in a multi-user scenario is:</p> <p>1/ user A posts to <code>index</code>. This assigns values to your globals ...
python|oop|flask|global-variables
1
7,181
67,176,001
Additional columns added to saved CSV
<p>I have following code which generate features from csv</p> <pre><code>def gen_features_per_id(file_name, label): df = pd.read_csv(file_name, delimiter=',') df['dt'] = pd.to_datetime(df['datetime'], unit='s') row = [] column_names = ['group_timestamp', 'label', 'x_mean', 'x_me...
<p>There is problem for each loop in <code>groupby</code> is necessary append values to <code>row</code> list and then append to <code>rows</code> outside loop for nested lists, so possible pass to <code>DataFrame</code> cosntructor in last step:</p> <pre><code>#added for nested lists (outside loops) rows = [] df['dt'...
python|pandas
1
7,182
63,984,555
Fetch in JavaScript for FastApi in localhost
<p>How can you use my Api made with FastAPI, from my localhost, from an external html, for example, it is my simple implementation of test:</p> <p>main.py:</p> <pre><code>from fastapi import FastAPI app = FastAPI() @app.get(&quot;/&quot;) async def main(): return {&quot;message&quot;: &quot;Hello World&quot;} </c...
<p>You have to enable CORS in your API:</p> <pre><code>from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() origins = [ &quot;http://localhost&quot;, &quot;http://localhost:8000&quot; &quot;http://localhost:8080&quot;, ] app.add_middleware( CORSMiddleware, ...
javascript|python|fastapi
3
7,183
42,914,365
How can I get the length of an array in a nested JSON object returned by Python requests?
<p>I'm trying to port some code from Perl to Python. The code performs an HTTP GET request with non-default headers. The response is a JSON document. The top level element is an object that has a key named <code>queryResponse</code>. The value of that element is also an object, and it has a key named <code>entity</code...
<pre><code>use JSON::XS qw( decode_json ); my $response_json = '{ "queryResponse": { "entity": [ "a", "b", "c" ] } }'; my $response = decode_json($response_json); my $count = @{ $response-&gt;{queryResponse}{entity} }; </code></pre> <p>is equivalent to</p> <pre><code>import json response_json = '{ "queryResponse": { ...
python|python-2.7|python-requests
2
7,184
66,535,070
I need help resolving a Runtime.ImportModuleError in AWS Lambda
<p>I am new to AWS Lambda, and I am trying to run a simple print('hello') statement in a test scenario of a Lambda function written in Python. However, I keep getting a Runtime.ImportModuleError. Here is my code:</p> <pre><code>import boto3 def handler(event, context): s3 = boto3.client('s3') csvfile = s3.get_...
<p>I figured it out...I hadn't hit &quot;Deploy Changes&quot; with the correct handler name. Doing so resolved the error.</p>
python|aws-lambda|boto3
1
7,185
66,713,727
Pyqt5 QWidget.show() Not Working On Other Thread
<p>Look There Are My Qwidget Object And If I Am Working This Object On Main Thread No Problem Qwidget .show is Working but If I Run On Other Thread(threading.Thread) program freezes and shuts down.</p> <p>WHAT CAN I DO ?</p>
<p>In a word: don’t do it. It doesn’t even have to do with threads, everything to do with separation of the UI and the “business” logic.</p> <ol> <li><p>Put the code that you had running in a thread into a QObject.</p> </li> <li><p>Have that object emit signals and provide slots for interaction with UI. It should not b...
python|qt|pyqt|pyqt5|pyqt6
0
7,186
72,447,409
Error running "up" script with openvpn under windows
<p>I created an ovpn configuration under windows and I actually wanted it to run a Powershell script after the connection is estabilshed.</p> <p>The last lines of the ovpn-file are as follows</p> <pre><code>script-security 3 up test.py </code></pre> <p>The content of the test.py is very simple and I tried both</p> <p>a...
<p>Okay I found a solution now but I am everything but not happy with it. So looking for s.o. to provide a better solution.</p> <p>Apparently there seems to be two issues here.</p> <ul> <li>The python or powershell script is not executed at all</li> <li>Admin permissions are required to run the script in question</li> ...
python|powershell|openvpn
0
7,187
65,680,262
curses.getstr with pre-populated value
<p>Having some issues with Python <code>curses</code>'s <code>getstr</code>.</p> <p>First, left arrow behaves as delete. How can I set it simply to act as left?</p> <p>Second, I want the <code>getstr</code> to be pre-populated with some default value. How can I achieve this?</p> <p>Thanks in advace!</p>
<p>I was able to achieve this using a Textbox instead of getstr. When setting a Textbox to a single line, it accepts the ENTER key for submission. Here is my solution which displays a centered single line input field, which prepopulates the input value and uses the arrow keys to move around.</p> <pre><code>def get_stri...
python|curses
0
7,188
50,735,538
Interdependence of 2 classes with type hint in Python
<p>I want to defined 2 classes and use type hints in Python 3.4+, but with some dependence between them.</p> <p>This is the code I have</p> <pre><code>class Child(): def __init__(self, name:str, parent:Parent) -&gt; None: """Create a child Args: name (str): Name of the child ...
<p>It is a case of forward declaration.</p> <p>To make it work, you can us string <code>'Parent'</code> instead of class Name <code>Parent</code> for the function <code>Child.__init__</code> (and optionally <code>Parent.give_life</code> to make it symmetric).</p> <p>The resulting code is the following:</p> <pre><cod...
python-3.x|type-hinting
2
7,189
51,073,813
Pandas groupby count with conditions
<h3>Example Data</h3> <p>Given the following data frame: </p> <pre><code>| feature | gene | target | pos | | 1_1_1 | NRAS | AATTGG | 60 | | 1_1_1 | NRAS | TTGGCC | 6 | | 1_1_1 | NRAS | AATTGG | 20 | | 1_1_1 | KRAS | GGGGTT | 0 | | 1_1_1 | KRAS | GGGGTT | 0 | | 1_1_1 | KRAS | G...
<p>Okay, I figured it out. If there is a more efficient way to to do this, I'm all ears!</p> <pre><code> # flag targets that are multi-mapped and add flag as new column matches['multi_mapped'] = np.where(matches.groupby(["FeatureID", "gene", "target"]).pos.transform('nunique') &gt; 1, "T", '') # separate m...
python|pandas|pandas-groupby
0
7,190
4,028,681
How do I run a python file that is read into a std::string using PyRun
<p>I am embedding Python into my C++ program, and have used PyRun_SimpleString quite effectively but now am having trouble.</p> <p>What I have done is loaded a python.py file a std::string but am now having troubles running it. PyRun_SimpleFileEx didn't seem to do the trick either so some help would be great!</p> <pr...
<p>I solved my problem by using a string vector and reading each line of the file into the vector, then executing each one using PyRun_SimpleString.</p> <p>Here's the finished code, no error checking though. std::vector string_vector; std::string content; if(python_script.empty()) r...
c++|python
0
7,191
3,419,512
Minimize to gnome panel
<p>I have an application written in python, I would like it to be able to "minimize" to the gnome panel, much like how gnome's rhytmbox minimizes to the panel. Is it easily possible to do this? </p> <p>I've run the examples from <a href="http://ubuntuforums.org/showthread.php?t=496185" rel="nofollow noreferrer">here</...
<p>The examples linked show how to write panel applets, which have been somewhat discouraged for a while now. Instead, you probably want to create a <a href="http://library.gnome.org/devel/pygtk/stable/class-gtkstatusicon.html" rel="nofollow noreferrer">gtk.StatusIcon</a>. Status icons require the user to have a system...
python|applet|gnome
3
7,192
3,804,149
Using regex in python
<p>i have the following problem. I want to escape all special characters in a python string.</p> <pre><code>str='eFEx-x?k=;-' re.sub("([^a-zA-Z0-9])",r'\\1', str) 'eFEx\\1x\\1k\\1\\1\\1' str='eFEx-x?k=;-' re.sub("([^a-zA-Z0-9])",r'\1', str) 'eFEx-x?k=;-' re.sub("([^a-zA-Z0-9])",r'\\\1', str) </code></pre> <p>I ...
<p>Use <code>r'\\\1'</code>. That's a backslash (escaped, so denoted <code>\\</code>) followed by <code>\1</code>.</p> <p>To verify that this works, try:</p> <pre><code>str = 'eFEx-x?k=;-' print re.sub("([^a-zA-Z0-9])",r'\\\1', str) </code></pre> <p>This prints:</p> <pre><code>eFEx\-x\?k\=\;\- </code></pre> <p>whi...
python|regex
7
7,193
56,542,705
Could not upload csv file to test.pypi.org
<p>I am trying to upload a simple python package to PypI. For testing this I first uploaded to <a href="https://test.pypi.org/" rel="nofollow noreferrer">test.pypi.org</a>. When I install this package with pip and use it, I get the error <code>FileNotFoundError: [Errno 2] File b'../data/spam_collection.csv' does not ex...
<p>Try this:</p> <pre><code>packages=['spamclassifier'], package_dir={'spamclassifier': 'spamclassifier'}, package_data={'spamclassifier': ['data/*']}, include_package_data=True </code></pre> <p>Keep everything else constant. Hope it helps</p>
python|csv|pypi
0
7,194
56,530,292
Using split function for multiple data
<p>so for my problem, I have to create a program that takes a users input, and then prints it like a list. For example, if the user inputs "I like doing this activity, the program should return it as.</p> <pre><code>I like doing this activity. </code></pre> <p>But these should work with any scenario that the user inp...
<p>Print the list like this:</p> <pre class="lang-py prettyprint-override"><code>print('\n'.join(my_list_of_data)) </code></pre>
python|python-3.x
2
7,195
56,696,011
Control Flow issue: Python function called but not executed
<p>I have the strangest problem I have ever met in my life.</p> <p>I have a part of my code that looks like this:</p> <pre><code> class AzureDevOpsServiceError(Exception): pass skip = ["auto"] def retrieve_results(): print(variable_not_defined) ... # some useful implementation if not "results" in sk...
<p>As highlighted by @gmds, it was a problem of cache.</p> <p>Deleting the <strong>.pyc</strong> file didn't do much.</p> <p>However, I have found a solution:</p> <ol> <li>Renaming the function (e.g. adding <code>_</code>)</li> <li>Running the program</li> <li>Renaming back (i.e. removing <code>_</code> in the previ...
python|control-flow
0
7,196
61,596,650
Output not displayed as expected in <li> tag
<p>html code :</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"&gt;&lt;/script&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script&gt; ...
<p>This is happening because your socket design is a bit faulty. The <code>name</code> and <code>text</code> values are being returned from separate <code>socket</code> broadcasts while you expect them to be together. I see that your <code>name</code> &amp; <code>text</code> values are available together in html, so yo...
javascript|html|flask|python-3.8
1
7,197
57,977,486
How do I only keep files in a directory that contain a specific string?
<p>I am trying to open all the HTML files in a directory, read the HTML files, and only keep the HTML files that contain the phrase "apples and oranges."</p> <p>I tried opening every file in the directory, then applying the BeautifulSoup function on it.</p> <pre><code>import os import fnmatch from pathlib import Path...
<p>I belive the issue is you aren't actually reading in the file. In <code>soup = BeautifulSoup(files, 'html.parser')</code>, <code>files</code> is not an string.</p> <p>You need to read that in first, then pass that into BeautifulSoup:</p> <pre><code>import os import fnmatch from pathlib import Path from bs4 import ...
python|os.walk
1
7,198
58,036,125
Expand column containing key value pairs into their own columns
<p>I have a pandas dataframe that looks like this:</p> <pre><code>df = pd.DataFrame({'x':['''[{"key":"Gender","value":["Men"]}, {"key":"Shoe Size","value":["M"]}, {"key":"Shoe Category","value":["Men's Shoes"]}, {"key":"Color","value":["Multicolor"]}, {"key":"Manufacturer Part Number","value":["8190-W-NAVY-7.5...
<p>Here is a possible solution. However, you have to find out all the possible key values beforehand. I guess, it could be done programmatically, but I have hard-coded them here. Also, if there are multiple items in value, it will take the first one.</p> <pre><code>import pandas as pd import json # original dataframe...
python|pandas
1
7,199
56,127,592
AttributeError: module 'tensorflow' has no attribute 'ConfigProto'
<p>I import tensorflow (version 1.13.1) and need <code>ConfigProto</code>:</p> <pre><code>import tensorflow as tf config = tf.ConfigProto(intra_op_parallelism_threads=8, inter_op_parallelism_threads=8, allow_soft_placement=True,device_count = {'CPU' : 1, 'GPU' : 1}) </code></pre> <p>I get this error:</p> <pre>...
<p>ConfigProto disappeared in tf 2.0, so an elegant solution is: </p> <pre><code>import tensorflow as tf </code></pre> <p>and then replace:</p> <p><code>tf.ConfigProto</code> by <code>tf.compat.v1.ConfigProto</code></p> <p>In fact, the compatibility built in 2.0 to get tf 1.XX: <code>tf.compat.v1</code> is really h...
python|tensorflow
106