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
2,400
67,653,157
Python Requests/Selenium hard scraping tables
<p>website is: <a href="https://www.jao.eu/auctions#/" rel="nofollow noreferrer">https://www.jao.eu/auctions#/</a></p> <p>I need to get/scrape and save the tables ('AUCTION SPECIFICATIONS &amp; RESULTS') present in jao.eu/auctions# that come after I operate selections in the OUT AREA, IN AREA, TYPE, AUCTION ID, etc., ...
<p>To get the data you can simulate Ajax request with <code>requests</code> module. For example:</p> <pre class="lang-py prettyprint-override"><code>import json import requests url = &quot;https://www.jao.eu/api/v1/auction/calls/getauctions&quot; payload = { &quot;corridor&quot;: &quot;AT-CH&quot;, &quot;from...
python|selenium-webdriver|web-scraping|python-requests
1
2,401
42,783,508
Rename key field in all documents: duplicate key error
<p>I have 4000 of documents I need to change the one key of whole documents what I have tried is </p> <pre><code>db.qa_opportunities.updateMany({},{$rename :{"tx_date":"review_date"}}) </code></pre> <p>but it is created two one is tx_date and another is review_date some of the values are moved to tx_date and some...
<p>You currently have an index which includes the tx_date field (among others), and because the index is configured to be <em>unique</em>, when you remove the tx_date field you end up with duplicate index keys.</p> <p>I would try the following:</p> <ol> <li>Analyse all your indexes, and make a note of any which refer...
mongodb|python-2.7|python-3.x
1
2,402
50,746,971
Call a python script with parser arguments in .NET
<p>Sorry if this is a duplicate question but I could not find clear answer.</p> <p>I am trying to call a python script (dnstwist.py) from within .NET using IronPython. </p> <pre><code>public static void runDNSTwistPython(string url) { var ipy = Python.CreateRuntime(); dynamic test = ipy.UseFile("dnstwist-mast...
<p>@jacob-hall you can use C# Process class and pass the command line to be executed this class documentation can be found here <a href="https://msdn.microsoft.com/pt-br/library/system.diagnostics.process.start(v=vs.110).aspx" rel="nofollow noreferrer">Process</a></p> <p>and you code will be something like this:</p> ...
c#|python|.net
0
2,403
26,908,480
bin data depending on values of a separate column
<p>I have a dataset which looks somehow like this toy example:</p> <pre><code>s1 = pd.Series(np.random.rand(5)) s2 = pd.Series(np.random.rand(5) * 10) cat1 = pd.Series(['s1'] * 5) cat2 = pd.Series(['s2'] * 5) s = s1.append(s2).reset_index(drop=True) c = cat1.append(cat2).reset_index(drop=True) data = pd.DataFrame({'ca...
<p>You're probably losing out on the vectorization speedup</p> <p>Try this:</p> <pre><code>buckets = dict(s1=s1_buckets, s2=s2_buckets) data['Buckets'] = data.groupby(['cat']).apply(lambda df: np.digitize(df.s, buckets[df.cat.irow(0)])) </code></pre>
python|pandas|categories|dataframe|binning
1
2,404
57,989,381
How to return void in python
<h1>This is the famous coin change dp problem - given some coins return possible amount 11=2+2+2+5</h1> <pre><code>arr=[2,5] def Recur(amount,seq): if amount==0: print(seq) return if amount&lt;0: return for coin in arr: seq+=str(coin) Recur(amount-coin,seq) Recur(1...
<pre><code>arr=[2,5] def Recur(amount,seq): if amount==0: print(seq) return if amount&lt;0: return for coin in arr: seq+=str(coin) # error is in this line since you are #trying to update seq which persist across the method stack due ...
python|recursion|dynamic-programming
0
2,405
69,590,183
How do I get this command to work in different places at the same time?? discord.py
<p>I want this command to work in different places at the same time. When I run it on one channel, and my friend runs it on another channel, the command starts to be duplicated when one of us presses the button. I don't click anything, but if my friend clicks on the button in his channel, the message will be sent in bo...
<p>The while loop isn't the problem here (though it's a separate problem).</p> <p>What's happening is that <code>await bot.wait_for(&quot;button_click&quot;)</code> doesn't care what button is pressed. This means that when the command is run twice, then a button is clicked, both messages respond.</p> <p>You'll want to ...
python|discord.py
0
2,406
25,861,323
ORM works, Declarative doesn't. Why?
<p>This should be self explanatory. I am able to expose a database through the Object Relational approach (ORM), but not through the Declarative approach. Am I failing to instantiate the class? What is the missing step here?</p> <pre><code>from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import ...
<p>Try this:</p> <pre><code>class MyClass(Base): __table__ = my_table int_col = Column(Integer, primary_key=True) str_col = Column(String) </code></pre> <p>Declarative creates table for each mapper, so 'my_table' in declarative is other table. You may also use database reflection:</p> <pre><code>metadata...
python|sqlalchemy
1
2,407
20,618,010
numpy function IOError
<p>On my macbook air running OSX Mavericks (I'm almost certain this wasn't happening the other day on a PC running Windows 7 running virtually identical code) the following code gives me the following error.</p> <pre><code>import numpy as np massFile='Users/BigD/Dropbox/PhD/PPMS/DATA/DB/HeatCap/HeatCapMass.txt' print...
<p>The path you're supplying in <code>massFile</code> is relative to the directory you're executing the script in.</p> <p>To see where you are, just type <code>pwd</code> in your shell. In your case, it will return <code>/Users/BigD/Dropbox/PhD/PPMS/</code>. So this value is silently prepended to your path:</p> <pre>...
numpy|genfromtxt
4
2,408
33,276,615
update python module while it is active
<p>Is it possible to update a python module while it is used in a running script?</p> <p>The situation is the following: 1) I have a script running using pandas 0.15.2. It is a long data processing task and should continue running for at least another week. 2) I would like to run, on the same machine, another script, ...
<p>If the script is still running, it's likely that replacing the dependency will not affect it at all - the code will already be in memory.</p> <p>Still, it's better to be safe than sorry. I would install the other script inside a virtualenv, in which you can install whichever versions of modules you want without af...
python|module
3
2,409
36,641,616
Can't successfully convert to int/float within average calculation in python
<p>Here is my code, without the last part it splits the name and score. I'm trying to work out the average by using sum/len. I need to convert the score to float somewhere, whenever I try I get the following message:</p> <pre><code>for name in sorted(user_scores): # get the highest score in the list. average ...
<p>Your average calculation is wrong. It should be </p> <pre><code>average = sum(user_scores[name]) / len(user_scores[name]) </code></pre> <p>(Probably this was some kind of copy-paste error. With <code>len[name]</code> you are using <code>name</code> as an index to <code>len</code>, not as a parameter (hence the <co...
python|input|average
1
2,410
54,272,036
Error using python built in function **abs** in pyspark-2.3
<p>I was trying to convert negative number to positive by using python built in <strong>abs</strong> function in pyspark shell-2.3.</p> <pre><code>numb = -2 print(abs(numb)) </code></pre> <p>Its throwing me a weird error:</p> <pre><code>py4j.protocol.Py4JError: An error occurred while calling z:org.apache.spark.sql....
<p>That's not how you use <a href="https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#module-pyspark.sql.functions" rel="nofollow noreferrer"><code>pyspark.sql.functions</code></a>. There are not designed to be evaluated outside <a href="https://spark.apache.org/docs/2.3.2/sql-programming-guide.html#untyp...
python|apache-spark|pyspark|pyspark-sql
2
2,411
34,297,966
problems in read/write program with python
<p>so I have an archive were there is a number, say 1, and I want to do a program that reads that 1, then add 1 so 1+1=2 and then print in the archive 2, so now there is only a 2 in the archive. What I did is this </p> <pre><code>outfile = open('text.txt', 'r') m=outfile.readline() g=m+1 outfile.close() outfile = o...
<p>When you read <code>m</code>, it is a string. You need to cast it to <code>int</code> before adding 1.</p> <pre><code>with open("text.txt") as inf: m = inf.read() g = int(m) + 1 with open("text.txt", "w") as outf: outf.write(str(g)) </code></pre>
python|rewrite|add
1
2,412
47,460,973
Are there any pros to having a convolution layer using a filter the same size as the input data?
<p>Are there any pros to having a convolution layer using a filter the same size as the input data (i.e. the filter can only fit over the input one way)?</p>
<p>A filter the same size as the input data will collapse the output dimensions to <code>1 x 1 x n_filters</code>, which could be useful towards the end of a network that has a low dimensional output like a single number for example.</p> <p>One place this is used is in sliding window object detection, where redundant...
tensorflow|neural-network|conv-neural-network|convolution
1
2,413
64,554,404
How to use emmet for Python in Vs code
<p>How can i use emmet in for python in Vs code?</p> <p><a href="https://i.stack.imgur.com/86CfJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/86CfJ.png" alt="enter image description here" /></a></p> <p>What item and value should I enter to add emmet for python and other languages?</p>
<p>in <code>.vscode</code> folder &gt; <code>setting.json</code> add this:</p> <pre><code>{ &quot;emmet.includeLanguages&quot;: { &quot;javascript&quot;: &quot;javascriptreact&quot;, &quot;razor&quot;: &quot;html&quot;, &quot;plaintext&quot;: &quot;pug&quot;, &quot;django-html&quot;:&quot;html...
python|visual-studio-code
1
2,414
73,116,893
Label not updating in tkinter
<p>I have asked a very similar question I believe 2 days ago and it got closed as a mod told me to look at other similar questions but none of the solutions worked. Does anyone have any idea how to fix the error. Here is the code at the moment all it does is print and display the first number in the sequence:</p> <pre>...
<p>There are few issues in your code:</p> <ul> <li>it is not recommended to use console <code>input()</code> in a GUI application</li> <li>the for loop will be blocked by <code>tk.mainloop()</code> until the root window is closed. However the next iteration will raise exception since the root window is destroyed. Actu...
python|tkinter
1
2,415
73,490,014
assigning a json dictionary key value to a variable
<p>I have a json with the following structure.</p> <pre><code>{ &quot;source&quot;: { &quot;excelsheetname&quot;: { &quot;convert_to_csv&quot;: &quot;True&quot;, &quot;tgt_folder&quot;: &quot;archieve/datetime=&quot;, &quot;brand&quot;: &quot;chicken&quot;, &q...
<p>First, you want to parse the JSON into a Python dictionary:</p> <pre class="lang-py prettyprint-override"><code>import json config_str = &quot;&quot;&quot; { &quot;source&quot;: { &quot;excelsheetname&quot;: { &quot;convert_to_csv&quot;: &quot;True&quot;, &quot;tgt_folder&quot;: &...
python|json
2
2,416
73,427,549
Convert Pandas Dataframe Strings to Decimal (Inc. Empty Strings)
<p>I have written a utility function that will convert strings to decimals- it also returns a zero decimal if the string is empty.</p> <pre><code>from decimal import * def convert_string_to_decimal(some_string): return Decimal('0.00') if (some_string == '' or some_string.isspace()) else Decimal(some_string) </cod...
<p>There is no need for new function, you can do it with astype...</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd data = {'id': ['A', 'B', 'C', 'D', 'E'], 'debit': ['1.11','', '2.22', '3.33', ' '], 'credit': ['1.2345', '2.3456', '3.00', '4', '5']} df = pd.DataFrame(data) print(df) ''' id deb...
python|pandas|decimal
1
2,417
66,634,900
Schedule an event for a certain unix timestamp in Python
<p>How to implement the following?</p> <pre><code>def thirty_seconds_in(): print('meow') at_time( time() + 30, thirty_seconds_in ) </code></pre> <p>Do I need my own thread/runloop with a <code>sleep(.01)</code> in it?</p>
<p>The first solution is, like you said, to implement your own loop.</p> <p>The second solution is to use some given library functions like <a href="https://docs.python.org/3/library/sched.html" rel="nofollow noreferrer">sched</a>.</p> <p>But in fact you need a runtime loop that will perform a check.</p>
python|scheduler
2
2,418
63,901,851
How to convert a datetime ('2019-06-05T10:37:29.353+0100') to UTC timestamp using Python3?
<p>I want to convert <code>datetime</code>, i.e. <code>2019-06-05T10:37:29.353+0100</code>, to UTC timestamp in Python3.</p> <p>I understand that <code>+0100</code> represents the timezone. Why do <code>+0100</code>, <code>+0200</code>, and <code>+0300</code> all convert to the same timestamp?</p> <p>How can I convert ...
<p>here's some more explanations (see comments) how to convert back and forth between timestamps as strings with UTC offset and POSIX timestamps.</p> <pre><code>from datetime import datetime, timezone s = '2019-06-05T10:37:29.353+0100' # to datetime object dt = datetime.strptime('2019-06-05T10:37:29.353+0100', '%Y-%m-...
python|python-3.x|datetime
2
2,419
65,451,939
How does Tensorflow or Keras handle model weight inititialization and when does it happen?
<p>After reading the <a href="https://stackoverflow.com/q/47995324/3577783">answer to this question</a> I am a bit confused as to <em>when exactly TensorFlow initializes the weight and bias variables</em>. As per the answers, Compile defines the <strong>loss function</strong>, the <strong>optimizer</strong> and the <st...
<p>The weights are initialized when the model is created (when each layer in model is initialized), i.e before the <code>compile()</code> and <code>fit()</code>:</p> <pre><code>import tensorflow as tf from tensorflow.keras import models, layers inputs = layers.Input((3, )) outputs = layers.Dense(units=10, ...
tensorflow|keras|neural-network|transfer-learning
3
2,420
65,185,733
How to apply average pooling at each time step of lstm output?
<p>I'm trying to apply average pooling at each time step of lstm output, please find my architecture as below</p> <pre><code>X_input = tf.keras.layers.Input(shape=(64,35)) X= tf.keras.layers.LSTM(512,activation=&quot;tanh&quot;,return_sequences=True,kernel_initializer=tf.keras.initializers.he_uniform(seed=45),kernel_re...
<p>I am not sure this is the most efficient way, but you can try this :</p> <pre><code>X = tf.keras.layers.Reshape(target_shape=(64,256,1))(X) X = tf.keras.layers.TimeDistributed(tf.keras.layers.GlobalAveragePooling1D())(X) X = tf.keras.layers.Reshape(target_shape=(64,))(X) </code></pre> <p>instead of :</p> <pre><code>...
tensorflow|keras|deep-learning|lstm
1
2,421
68,842,822
How to unify date format from HTML timestamps
<p>I am scraping the publish date of articles from a number of publishers' websites using a python script. This data is found in HTML attributes or tags identified variously by &quot;time&quot;, &quot;timestamp&quot;, and &quot;published_date&quot;, among others, and provides the time in, for example, the following for...
<p>The <a href="https://github.com/scrapinghub/dateparser" rel="nofollow noreferrer">dateparser</a> python library looks like the best solution to my needs.</p> <ul> <li>Support for almost every existing date format: absolute dates, relative dates (&quot;two weeks ago&quot; or &quot;tomorrow&quot;), timestamps, etc.</l...
python|html|date|beautifulsoup|tags
0
2,422
71,504,192
400 Bad Request POST request
<p>I'm programing in Python some API application, using POSTMAN, and a Bearer token. I already receive the token, and to some GET with success response.</p> <p>But when doing a insert of a record I got 400 Bad request error, this is the code I'm using for adding the record</p> <pre><code>def add_identity(token, accoun...
<p>data have to be a dict ,, you can try import json and data=json.dumps(newIdentity) , and if it keeps returning 400 , check well that all the parameters are accepted by the api by recreating the request with Postman or any request editor, and if the api uses any web interface check what is the reason for that 400 . ...
python|api|request|token
1
2,423
62,801,781
Unable to consume a .NET WCF service in Python
<p>I am trying to access a .NET WCF web service from Python and am getting the following error - would anyone be able to let me know what I am doing wrong:</p> <pre><code>File &quot;C:\temp\anaconda3\lib\site-packages\suds\mx\literal.py&quot;, line 87, in start raise TypeNotFound(content.tag) suds.TypeNo...
<p>Create ResponseData object, the type is defined in wsdl, if there are multiple schemas, you need to add a prefix, such as ns0, ns1, etc.</p> <pre><code>ResponseData = client.factory.create('ns1:ResponseData') ResponseData.token = &quot;Test&quot; </code></pre> <p>Make sure that the properties of the object you creat...
python|.net|web-services|wcf|soap
1
2,424
61,928,007
How to split row in multiple rows and add new column also in pandas?
<p>I am trying to split row into multiple rows but I need to add one more column when the split will happen. Can you please help me how to do this?</p> <p>Example:</p> <pre><code>df1: rule_id priority_order comb_fld_order R162 2.3 1 R162 2.3.1 1 R162 ...
<p>No need for the lambdas function. You can just explode and call the column name:</p> <pre><code>import pandas as pd df1 = pd.DataFrame({ 'rule_id': ['R162', 'R162', 'R162', 'R162', 'R162'], 'priority_order': ['2.3', '2.3.1', '2.6', '2.6.1', '3.0.4'], 'comb_fld_order': ['1', '1', '2', '2', ('3.2', '3.1'...
python|python-3.x|pandas|dataframe
0
2,425
60,361,617
Reverse for 'new_entry' with arguments '('',)' not found. 1 pattern(s) tried: ['new_entry/(?P<topic_id>[0-9]+)/$']
<p>I'm new learning Django and I want a study tracker web app with Django. The error came up when I was creating the function and template for <strong>new entries</strong> - this will allow a user write a detailed note about a topic they are currently learning about but whenever I run the template I get an error messag...
<p>You passed your template <em>topic_list</em> variable but in your template you used <em>topic</em>. I think you would set a loop. Because you have no any variable named <em>topic</em>. If you changed them, it will work.</p>
python|django|django-templates
1
2,426
60,745,841
Inheriting from BaseException vs Exception
<p>I know what is difference between <code>Exception</code> and <code>BaseException</code> in <code>Python</code>. I wonder what is a good practice and more <em>pythonic</em>: Should my exceptions inherit from <code>BaseException</code> or <code>Exception</code>?</p>
<p>By default, all user-defined exceptions should inherit from <code>Exception</code>. This is <a href="https://docs.python.org/3/library/exceptions.html#Exception" rel="nofollow noreferrer">recommended in the documentation</a>:</p> <blockquote> <p>exception <code>Exception</code></p> <p>All built-in, non-syste...
python-3.x
5
2,427
60,479,568
Dimension in Tensorflow / keras and sparse_categorical_crossentropy
<p>I cannot understand how to use tensorflow dataset as input for my model. I have a X as (n_sample, max_sentence_size) and a y as (n_sample) but I cannot match the dimension, I am not sure what tensorflow do internaly.</p> <p>Below you can find a reprroducible example with empty matrix, but my data is not empty, it is...
<p>this works for me in Tensorflow 2.0. </p> <pre><code>import numpy as np # Prepare for tensorflow BUFFER_SIZE = 10000 BATCH_SIZE = 64 VOCAB_SIZE = 5354 X_train = np.zeros((16,6760)) y_train = np.zeros((16,1)) # This is changed train = tf.data.Dataset.from_tensor_slices((X_train, y_train)) train = train.shuffle(...
tensorflow|keras|nlp|cross-entropy
1
2,428
60,385,080
how to import django variable to html?
<p>I have to send data from the rs232 port and display it in a graph, use java script <a href="https://canvasjs.com/html5-javascript-dynamic-chart/" rel="nofollow noreferrer">https://canvasjs.com/html5-javascript-dynamic-chart/</a></p> <p>I need help importing the views.py variable in my html</p> <pre><code>views.py ...
<p>write this on your views and point a url to it</p> <pre><code>from django.shortcuts import render def indexw(request): context_variable = '' context = {"context_variable": context_variable} return render(request,'index.html', context) </code></pre>
python|html|django|serial-port
0
2,429
63,710,517
K-fold cross-validation in keras with single output for binary class
<p>I am working with a convolutional neural network that i am using to classify cats and dogs, that has just one output for two classes. I need to use k-fold cross validation to find which set or pets breeds gives the best validation accuracy. The closest answer to my problem is in this question: <a href="https://stack...
<p>You won't be able to use <code>ImageDataGenerator</code> because according to the documentation, <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.cross_val_score.html" rel="nofollow noreferrer">cross_val_score</a> expects an array of shape <code>(n_samples, features)</code>.</p> <p>...
python|python-3.x|tensorflow|machine-learning|keras
0
2,430
63,447,689
Converting pandas groupby values to numpy array
<p>I <strong>tried multiple solutions</strong> but none of them gives the desired output.</p> <p>I have a DataFrame:</p> <pre><code> tag value 'A' 3.7 'A' 1.5 'E' 9.7 'E' 2.9 'B' -1.2 'B' 0.8 </code></pre> <p>My <strong>expected output</strong> is a Numpy Array:</p> <pre><code>array([[3....
<p>If there is always same number of values per groups is possible create nested lists and pass to <code>np.array</code>, also for same order of groups add <code>sort=False</code> parameter to <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><co...
python|python-3.x|pandas|numpy|pandas-groupby
3
2,431
63,435,697
Cross validation inconsistent numbers of samples error (Python)
<p>I am trying to make a classification using cross validation method and SVM classifier. In my data file, the last column contains my classes (which are 0, 1, 2, 3, 4, 5) and the rest (except first column) is the numeric data that I want to use to predict these classes.</p> <pre><code>from sklearn import svm from skle...
<p>You are misunderstanding the output from <code>cross_val_score</code>. As per the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.cross_val_score.html" rel="nofollow noreferrer">documentation</a> it returns &quot;array of scores of the estimator for each run of the cross validation...
python|numpy|scikit-learn
1
2,432
63,330,244
Apply median from a subset to entire column, Python /Pandas
<p>first time posting here. I have a credit risk model data set that has 38K accounts. 25K accounts are training data. The other 13K are OOT (out of time validation). All the 200 columns have the same definitions between training and OOT. Just the data has two parts.</p> <p>I need to impute missing data. 37 columns of ...
<p>Consider converting the <em>trainmedian</em> (i.e., Series) to a data frame with same dimensions using the <code>DataFrame()</code> constructor on list of series.</p> <pre><code>whole_median = pd.DataFrame([trainmedian for _ in range(whole.shape[0])]) </code></pre> <hr /> <p>To demonstrate with random 500-row data a...
pandas|group-by|median|imputation|fillna
0
2,433
56,718,204
amixer: invalid command
<p>I am trying to change the volume of my RaspberryPi using this small code snippet:</p> <pre><code>import os def setVolume(vol,prefix): cmd = "amixer -q -M set PCM " + vol + "%" print(prefix+"Changing volume to " + vol + "%") print(prefix+str(os.system(cmd))) </code></pre> <p>I am using this function i...
<p>This should be very easy for you to narrow down, as the problem ultimately has little to do with Python. Your python code is just constructing a command string that is then executed by the operating system. </p> <p>First of all, I'd suggest printing or logging the full command you are executing so that you know j...
python|raspberry-pi|amixer
1
2,434
69,823,218
How to extract link from href using beautifulsoup
<p>I am try to extract url from the href but they will give me the empty list</p> <pre><code> import requests from bs4 import BeautifulSoup headers ={ 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36' } r =reques...
<p>Just one alternativ approach, you can use <a href="https://selenium-python.readthedocs.io/getting-started.html" rel="nofollow noreferrer"><code>selenium</code></a>.</p> <h3>Example</h3> <pre><code>from bs4 import BeautifulSoup from selenium import webdriver driver = webdriver.Chrome('YOUR PATH TO CHROMEDRIVER') dri...
python|web-scraping|beautifulsoup
0
2,435
61,088,160
Example using geospatial indexing with pymongo
<p>I have been looking at using MongoDB instead of a custom geospatial database, however I am having difficulty at understanding how pymongo works with spherical coordinates. Specifically I am not sure the $maxDistance (and similar have any effect). For example if I execute this code:</p> <pre><code>db = pymongo.Mongo...
<p>You are using the older form of query where the distance is specified in radians. If you change to the <a href="https://docs.mongodb.com/manual/reference/operator/query/nearSphere/" rel="nofollow noreferrer">new format</a> the <code>maxDistance</code> is specified in meters. </p> <p>Also for reasons lost in the mis...
python|mongodb|pymongo
2
2,436
60,837,858
Can't install Scrapy
<p>I would like to install the Scrapy package. I tried with <code>pip install Scrapy</code> but it didn't work, a lot of errors are displayed but I think this is the main error : <code>Building wheel for Twisted (setup.py) ... error</code>.</p> <p>I searched on this forum and found something : try to install it with ...
<p>try this. Works for me in pycharm.</p> <pre><code>pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org Scrapy </code></pre>
python|pip|scrapy
-1
2,437
61,131,969
Stuck in loop help - Python
<p>The second 'if' statement midway through this code is using an 'or' between two conditions. This is causing the issue I just don't know how to get around it. The code is going through a data file and turning on the given relay number at a specific time, I need it to only do this once per given relay. If I use an 'an...
<p>Try printing all used variables, check if everything is, what you think it is. On top of that, sometimes whietespaces characters causes problem with comparison. </p>
python|loops|if-statement
0
2,438
69,278,418
How do I get Pillow ImageOps.contain to work when inside VS Code?
<p>I have VS Code on a Mac. Pillow is installed and version verified as 8.3.2 via Pip list in the terminal window of VS Code. I have confirmed via the pillow docs that the <a href="https://pillow.readthedocs.io/en/stable/reference/ImageOps.html#PIL.ImageOps.contain" rel="nofollow noreferrer">ImageOps.contain()</a> is ...
<p>This turns out to be a problem with what I can only call nested environments and/or a conflict between Anaconda and Workspaces. I'm not really sure but when I used the _version import to figure out a) what VS Code thought and then b) figured out the environment Pip was reporting on, I deactivated up one level, upgr...
python|python-imaging-library
0
2,439
72,610,283
Why does my graph not plot the points generated by linspace? (animation)
<p>When I remove linspace and plot points by typing them into a list by hand they are plotted just fine. However switch to linspace, and the points on the graph come up blank. What am I missing here? Printing the linspace lists show they are generating the values, but they don't seem to make the graph</p> <pre><code>im...
<p>It seems like you are facing a problem because of <code>Position = [P]</code> and <code>Time = [T]</code>.</p> <p>Because <code>numpy.linspace</code> already returns an array, you don't need additional <code>[]</code>.</p> <p>Here is a working example that is referenced from <a href="https://matplotlib.org/stable/ap...
python|numpy|matplotlib|animation
0
2,440
72,520,699
After chrome update, Message: target frame detached
<p>I have this error :</p> <pre><code>selenium.common.exceptions.WebDriverException: Message: target frame detached (Session info: chrome=102.0.5005.63) </code></pre> <p>which is often displayed after running my program, since the update of chrome. I suppose it's due to the fact that the version of chrome and chromed...
<p>I recently faced same issue, please check the accepted answer here : <a href="https://stackoverflow.com/questions/71323442/this-version-of-chromedriver-only-supports-chrome-version-99-current-browser-ver">This version of ChromeDriver only supports Chrome version 99 Current browser version is 98.0.4758.102</a></p> <p...
python|selenium|selenium-webdriver
1
2,441
72,505,074
Out of memory Error while training Rasa/LaBSE
<p>I want to train <code>rasa/LaBSE</code> from the <code>LanguageModelFeaturizer</code>. I have followed the steps in the docs and did not change the default training data.</p> <p>My config file looks like:</p> <pre><code># The config recipe. # https://rasa.com/docs/rasa/model-configuration/ recipe: default.v1 # Conf...
<p>Running the same code using google colab (Using 16GB GPU memory) works fine. The model uses around 6.5-7GB of memory.</p>
python|tensorflow|rasa|rasa-nlu|rasa-sdk
0
2,442
68,385,728
Installing pyarrow: can't copy 'build/lib.macosx-11-arm64-3.9/pyarrow/include/arrow': doesn't exist or not a regular file
<p>I am trying to install pyarrow with the following command*:</p> <pre><code>OPENSSL_ROOT_DIR=/opt/homebrew/opt/openssl@1.1/ pip install &quot;pyarrow==4.0.1&quot; --no-use-pep517 </code></pre> <p>However, it looks like the compilation fails as I get the following message at the end:</p> <pre><code> Moving built C-...
<p>UPDATE</p> <p>You can use the nightly install of pyarrow which now supports M1</p> <p><code>pip install --extra-index-url https://pypi.fury.io/arrow-nightlies/ --prefer-binary --pre pyarrow</code></p> <p>PRE-UPDATE</p> <p>The bad news is I think this is the fault of pyarrow rather than yourself.</p> <p>The good news...
cmake|pip|apple-m1|pyarrow|python-3.9
1
2,443
59,095,426
retrun sources in Bokeh javascript callback
<p>Imagine <a href="http://docs.bokeh.org/en/1.3.2/docs/user_guide/interaction/callbacks.html#customjs-for-model-property-events" rel="nofollow noreferrer">this</a> example in Bokeh docs:</p> <pre class="lang-py prettyprint-override"><code># modified to by used in a notebook from bokeh.layouts import column from boke...
<p>If you want full synchronization between the Python runtime and the JS output, you would have to embed a Bokeh server application in the notebook. (The Bokeh server is <em>specifically the thing whose job is to keeps things in sync.</em>) Otherwise all output in a Jupyter noteboook is uni-directional only, Python ->...
python|bokeh
0
2,444
59,213,368
Python Q-learning implementation not working
<p>I implemented a small simulation based on the sugarscape model in python. I have three classes in the program and when I try run the Q-learning algorithm I wrote the model converges into a single state and never changes where as when I run the model without the q-learning algorithm then the states are always differe...
<p>More questions than answers. I don't know where the problem is exactly, but here is list of unclear things in the code, which, if corrected, may probably get you to the desired result:</p> <ul> <li>is it an intention in <code>_regeneration</code> to seed entire field with same amount of sugar? You randomly pick val...
python|testing|machine-learning|agent|q-learning
0
2,445
59,091,328
Implementing hierarchy for Enum members
<p>I would like to establish a hierarchy for the members of my Enum. My (simplified) enum aims at representing different types of food. Of course, everyone knows a burger is "superior" to a pizza and my enum needs to convey this idea:</p> <pre><code>from functools import total_ordering from enum import IntEnum, unique...
<p>You get a recursion error because in order to determine the <code>index</code> the list elements need to compared for equality, which in turn will invoke <code>__eq__</code>. </p> <p>Alternatively you could use a mapping from the enum members to some ordering, e.g.:</p> <pre><code>FoodType.FOOD_HIERARCHIES = [ ...
python|enums
2
2,446
63,253,955
Reshaping a messy dataset using Pandas
<p>I got this messy dataset from a csv-file that contains multiple entries in the same cell. This is how it looks:</p> <pre><code>file = ('messy.csv') df = pd.read_csv(file) df.head() Folders Files aa; bb; aa.src aa.xml ; bb.src bb.war ; cc; ...
<p><strong>Turning it into a json/dict</strong></p> <p>Ok so probably not the most efficient solution but it works:</p> <pre><code>import pandas as pd # Recreating the dataframe df = pd.DataFrame({'Folders':[&quot;aa; bb;&quot;, &quot;cc&quot;, &quot;dd; ee; ff;&quot;], 'Files':['aa.src aa.xml ; bb.src bb.war ;', 'cc....
pandas|dataframe|reshape
1
2,447
73,329,351
How can I split a string into a list by sentences, but keep the \n?
<p><strong>I want to split text into sentences but keep the \n such as:</strong></p> <blockquote> <p>Civility vicinity graceful is it at. Improve up at to on mention perhaps raising. Way building not get formerly her peculiar.</p> <p>Arrived totally in as between private. Favour of so as on pretty though elinor direct....
<p>You can use <code>(?&lt;=...)</code> to retain separator followed by what you want to remove by the split:</p> <pre><code>import re s='Civility vicinity graceful is it at. Improve up at to on mention perhaps raising. Way building not get formerly her peculiar.\n\nArrived totally in as between private. Favour of so ...
python|python-re|moviepy
1
2,448
49,294,333
RuntimeError: populate() isn't reentrant
<p>I got a legacy project based on Django as backend and Angularjs on the front. It's deployed and working, but I got no docs at all so I had to guess everything out of how to deploy it in local, how the system works and that.</p> <p>Now, I've been asked to set it up in a pre-production environment, and so I tried to ...
<p> I had a similar error out of a simple <code>$ python manage.py shell</code> in my case. I couldn't find any help out of searching for <em>RuntimeError("populate() isn't reentrant")</em>, so I finally set about poking through it in the debugger.</p> <p>In my case, it turned out to be that Oracle wasn't happy over m...
django|python-3.x|virtualhost
0
2,449
49,320,238
How to print list items as if they're contents of print in python?
<p>words_list = ['who', 'got', '\n', 'inside', 'your', '\n', 'mind', 'baby']</p> <p>I have this list of words stored as a list element. I wanted to use the elements as contents of the print function. Ex.</p> <pre><code>print(words_list[0] + words_list[1] + words_list[2]...words_list[n]) </code></pre> <p>My desired o...
<p>In Python 3 you can do:</p> <pre><code>print(*words_list) </code></pre> <p>because print is just a function and the <code>*</code> operator in this context will <a href="https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists" rel="nofollow noreferrer">unpack elements of your list and put them...
python|string|python-3.x|list
1
2,450
49,200,074
Write a list of dictionaries row by row on a file
<p>I need to append dictionaries to a file row by row. At the end I will have a list of dictionary in the file.</p> <p>My naive attempt is:</p> <pre><code>with open('outputfile', 'a') as fout: json.dump(resu, fout) file.write(',') </code></pre> <p>But it does not work. Any suggestion?</p>
<p>If you need to save a number of dictionaries in a particular order, why not first put them in a list object and use json to serialize the whole thing for you?</p> <pre><code>import json def example(): # create a list of dictionaries list_of_dictionaries = [ {'a': 0, 'b': 1, 'c': 2}, {'d': ...
python|json|file
1
2,451
49,144,225
uWSGI will not run in mixed Python environment in order to operate correctly with nginx and run Django app
<p><strong>Environment:</strong> Ubuntu 16.04 (with system Python at 2.7.12) running in Vagrant/Virtualbox on Windows 10 host</p> <p><strong>Python Setup:</strong> System python verified by doing python -V with no virtualenv's activated. Python 3.5 is also installed, and I've done <code>pipenv --three</code> to cre...
<p>It might be the problem with your virtual environment. Try the following</p> <pre><code>rm -rf /root/.local/share/virtualenvs/my_site-gmmiTMID virtualenv -p python3 /root/.local/share/virtualenvs/my_site-gmmiTMID source /root/.local/share/virtualenvs/my_site-gmmiTMID/bin/activate pip install -r requirements.txt </c...
python|django|nginx|uwsgi
-1
2,452
60,110,944
Replace a word in a sentence with words from a list and copying the new sentences in a column
<p>I have a dataframe that contains sentences in one column, specific words I have extracted from the column, and a third column containing a list of synonyms for the words in the second column:</p> <pre><code>data= {"sentences":["I am a student", "she is my friend", "that is the new window"], "words": ["studen...
<p>That is not a direct dataframe manipulation, but you can still try it :</p> <pre><code>import pandas as pd data= {"sentences":["I am a student", "she is my friend", "that is the new window"], "words": ["student","friend", "window"], "synonyms":[["pupil"],["comrade","companion"],["brand new","up-to-date","latest"]]...
python|pandas|list|replace
0
2,453
6,025,758
What's the pythonic way to set class variables?
<p>perhaps I'm asking the wrong question. I have code like this:</p> <pre><code>class ExpressionGrammar(Grammar): def __init__(self, nonterminals, terminals, macros, rules, precedence, nonterminal_name = '_expr'): self.nonterminals = nonterminals self.terminals = terminals self.rules = rules self.ma...
<p>You can avoid doing that with something like:</p> <pre><code>class C(object): def __init__(self, x, y, z, etc): self.__dict__.update(locals()) </code></pre> <p>then all these arguments become members (including the self argument). So you may remove it with: <code>self.__dict__.pop('self')</code></p> <...
python
9
2,454
30,468,920
Python-linkedin Return URL?
<p>I am trying to use <a href="https://github.com/ozgur/python-linkedin" rel="nofollow">https://github.com/ozgur/python-linkedin</a> </p> <p>The steps I am taking are as follows:</p> <ul> <li>Register my application on linkedin to get the secret and api key.</li> <li>Put the return URI as localhost:8080/code.</li> <l...
<p>Since the last changes in LinkedIn API you have no longer access to the following member permissions:</p> <p>r_fullprofile, r_network, r_contactinfo, rw_nus, rw_groups, w_messages</p> <p><a href="https://developer.linkedin.com/support/developer-program-transition" rel="nofollow">https://developer.linkedin.com/supp...
python|api|oauth|linkedin
0
2,455
43,016,425
How to count the number of faces detected in live video by openCV using python?
<p>I need to count the number of faces in a video taken from webcam. For example, if I am standing in front of the camera then count=1, now if any other person is detected then count=2, if another person is detected then the count should be 3.</p> <p>I am using frontal_face_haarcascade.xml by opencv in python. I can d...
<pre><code>import numpy as np import cv2 faceCascade = cv2.CascadeClassifier(cascPath) video_capture =cv2.VideoCapture(0) while(True): idx=0 ret, frame = video_capture.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale( gray, scaleFactor=1.1, ...
python|opencv
-1
2,456
72,158,437
Error while working on chatbot-universal-sentence-encoder
<p>I am trying &quot;chatbot.py&quot; and I am getting below error.</p> <p>Traceback (most recent call last): File &quot;chatbot.py&quot;, line 11, in embeddings = model(df[&quot;MESSAGE&quot;].values)[&quot;outputs&quot;] IndexError: only integers, slices (<code>:</code>), ellipsis (<code>...</code>), numpy.newaxis (...
<p><code>model(df[&quot;MESSAGE&quot;].values)</code> already returns the embeddings as a numpy array. Omitting <code>[&quot;outputs&quot;]</code> should make it work.</p>
python|pandas|numpy|tensorflow-hub
0
2,457
65,514,146
Netmiko TEXTSFM Windows 10 issues
<p>I am running Python 3 on a Windows 10 computer.<br /> When I run this it works fine. When I add the <code>use_textfsm=True</code> to the results, I get a permission error where the templates are at.<br /> Permissions seem to be fine. I would like to try copy the template folder to a new location but I am not sure h...
<p>I already experienced the same issue in this environment.</p> <p><strong>Environment</strong></p> <pre class="lang-py prettyprint-override"><code>Python 3.9.4 testfsm==1.1.0 netmiko==3.4.0 </code></pre> <p>The error message you got is the solution but you may have misinterpreted it. You should do the following:</p> ...
python-3.x|netmiko
0
2,458
50,864,786
Pandas read_html misses table with several rows
<p>I'm scraping a website and in order to get the table I'm using <code>pd.read_html</code>.</p> <p>I get the node doing this:</p> <pre><code>table=WebDriverWait(browser,10).until(EC.presence_of_element_located(( By.XPATH,'//tbody[ancestor::div[contains(@id,"cornerOddsDiv")]]'))) newt=pd.read_html(table.get_attribut...
<p>I finally found the answer. The node is of a structure like the following</p> <pre><code>&lt;div&gt; &lt;div&gt; &lt;table&gt; &lt;tbody&gt; &lt;tr&gt;..&lt;/tr&gt; &lt;tr&gt;..&lt;/tr&gt; ... &lt;/tbody&gt; Etc </code></pre> <p>The key is, instead of passi...
python-3.x|pandas|html-table
0
2,459
50,899,548
PyTorch 0.4 LSTM: Why does each epoch get slower?
<p>I have a toy model of a PyTorch 0.4 LSTM on a GPU. The overall idea of the toy problem is that I define a single 3-vector as an input, and define a rotation matrix R. The ground truth targets are then a sequence of vectors: At T0, the input vector; at T1 the input vector rotated by R; at T2 the input rotated by R...
<p>Short answer: Because we did not detach the hidden layers, and therefore the system kept backpropagating farther and father back through time, taking up more memory and requiring more time.</p> <p>Long answer: This answer is meant to work without teacher forcing. "Teacher forcing" is when all inputs at all time-...
python-3.x|pytorch
1
2,460
50,534,397
Pyenv not shows all version when used as sudo
<p>I installed <code>3.5.2</code> and <code>3.5.3</code> version using pyenv.</p> <pre><code># pyenv versions * system (set by /usr/local/pyenv/version) 3.5.2 3.5.3 </code></pre> <p>But, when I run this command as <code>sudo</code> (not login as <code>root</code>) it not gives me all versions.</p> <pre><code>$ s...
<pre><code>$ export PYENV_ROOT=/usr/local/pyenv/ $ sudo /usr/local/pyenv/bin/pyenv versions </code></pre> <p>This doesn't work because <code>PYENV_ROOT</code> won't be passed to the environment in sudo. Try this:</p> <pre><code>$ sudo PYENV_ROOT=/usr/local/pyenv/ /usr/local/pyenv/bin/pyenv versions </code></pre> <p>...
python|centos|pyenv
1
2,461
26,600,185
Paramiko Expect - Tailing
<p>I am trying to tail a log file, and it works. But I need to also be able to analyze the output and log for errors and such. I am using the base example on the Paramiko-expect github page and I can not figure out how to do this.</p> <pre><code>import traceback import paramiko from paramikoe import SSHClientInteracti...
<p>I'm the author of paramiko-expect.</p> <p>I've implemented a new feature in 0.2 of my module just now which will allow you to specify a callback to the tail method so that you can process the current line as you like. You may use this to grep the output or process it further before displaying it. It is expected t...
python|logging|ssh|paramiko|tail
6
2,462
45,243,444
Django Postgres django.db.utils.ProgrammingError
<p>I know similar questions have been asked many times, but none of those solutions have worked. </p> <p>Recently I have been trying to connect to an AWS RDS database. However, now whenever I try to run a server through manage.py migrate my database I always get the following:</p> <pre><code>Traceback (most recent ca...
<p>You're calling your <code>get_func_names()</code> function, which queries the EmployeeProfile model, at class level in your EmployeeFilter class. This means it is called at import time. Since the views are imported on startup, your migrations have not yet had a chance to run.</p> <p>You should not call any code tha...
python|django|postgresql
0
2,463
44,895,094
marisa trie suffix compression?
<p>I'm using a custom Cython wrapper of <a href="https://github.com/s-yata/marisa-trie" rel="noreferrer">this marisa trie</a> library as a key-value multimap.</p> <p>My trie entries look like <code>key 0xff data1 0xff data2</code> to map <code>key</code> to the tuple <code>(data1, data2)</code>. <code>data1</code> is ...
<p>As I suspected, it's caused by padding.</p> <p>in <code>lib/marisa/grimoire/vector/vector.h</code>, there is the following function:</p> <pre><code>void write_(Writer &amp;writer) const { writer.write((UInt64)total_size()); writer.write(const_objs_, size_); writer.seek((8 - (total_size() % 8)) % 8); } </code...
python|c++|trie
6
2,464
44,919,669
folium.GeoJson (style function) not working as i want
<pre><code>import folium ,pandas ,json df=pandas.read_csv('Volcanoes_2.txt') def colors(elev): minimum=int(min(df['ELEV'])) step=int(max((df['ELEV'])-min(df['ELEV']))/3) if elev in range (minimum,minimum+step): col= "green" elif elev in range(minimum+step,minimum+step*2): col= "orange"...
<p>You were very close. I was able to get it to work by changing <code>fillcolor</code> to <code>fillColor</code> in your style function</p> <p><code>lambda x :{'fillColor':'green' if \ x['properties']['POP2005']&lt;10000000 \ else 'orange' if 10000000 &lt;x['properties']['POP2005']&gt;20000000 else 'red'}</...
json|python-3.x|folium
8
2,465
61,274,904
Python string format with incorrect values
<p>I have a string that I'd like to format but the values I'm using to format may or may not be proper values (<code>None</code>, or <code>''</code>). In any event that one of these improper values is passed, I still want the string to format, but ignoring any values that will not work. For example:</p> <pre><code>mys...
<p>You could write your own formatter and override <a href="https://docs.python.org/3/library/string.html#string.Formatter.format_field" rel="nofollow noreferrer"><code>format_field()</code></a> to catch these errors and just returns empty strings. Here's the basics (you might want to edit to only catch certain errors)...
python|python-3.x
3
2,466
60,659,801
Python iteration wont change
<p>I want to "reset" my for loop so i thought i have to set my iterator i on 0, but it will continue with 1 etc. How do "reset" my for loop? I tried to set i on 0 but in the next step my for loop just continues with 1 and so on. g is just a list with 2 items and S is a String, ignore all that. Its just this iteration t...
<p>you can use a while loop:</p> <pre><code>S='1112' g=['1', '2'] i = 0 output = 0 while i &lt; len(g): if g[i] in S: S = S.replace(g[i], "", 1) print(S) i = 0 output += 1 else: i += 1 print('Is S empty?', S=='') </code></pre> <p>output:</p> <pre><code>112 12 2 Is ...
python|python-3.x|loops|for-loop|range
1
2,467
57,753,346
How do I extract two things using Regex in Python?
<p>I have a string that has two things, which is the name of the petitioner and the advocate.</p> <p>I wanna separate the petitioner names and the advocate names.</p> <p>All petitioner names start with a number <code>(1-)</code> and the advocate name start with <code>Advocate-</code>.</p> <blockquote> <p>1) RAM PR...
<p>If you want to find two distinct things and plan to use regular expressions, it is almost always a good idea to use two distinct expressions instead of one. For example</p> <pre class="lang-py prettyprint-override"><code>petitioner_re = re.compile(r"\d+\) ([A-Z ]+)") # matches petitioners advocate_re = re.compil...
python|regex
1
2,468
58,141,628
Adding labels in scatter plot legend
<p>I am trying to add legend labels to my scatter plot for my physics lab report. It seems to only display the first word (in this case: "Actual") and nothing else. The plot also saves and empty file.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np IndexofR=[1.33, 1.443, 1.34] #Actual, Pfund's Metho...
<p>Try doing something like this:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np IndexofR=[1.33, 1.443, 1.34] #Actual, Pfund's Method, Snell's Law Colors = ['red', 'blue', 'green'] Labels = ['Actual','Pfund\'s Method', 'Snell\'s Law'] for i, c, l in zip(IndexofR, Colors, Labels): plt.scatter(i...
python|matplotlib
1
2,469
56,243,362
Is there a way to zoom into the next node in the 'setSelected' list?
<p>In The Foundry NukeX I'm trying to find list of nodes of same kind and zoom into each node one after the other of the <code>.setSelected</code> nodes. </p> <p>To be clear I'm trying to create a Python code thats behind <code>Edit</code> -> <code>Search...</code> menu or hotkey <kbd>/</kbd> in NUKE.</p> <p>With ...
<p>You need a <strong>nested <code>for-in</code></strong> loop to make iterations inside a desired class. </p> <p>Here's a how your code should look like:</p> <pre><code>import nuke for node in nuke.allNodes('Grade'): node.setSelected(True) for id in nuke.selectedNodes(): xCoord = id.xpos() + id.scr...
python|nuke
1
2,470
56,199,754
Regex: string between a mix of constant and variable characters
<p>I have a string (fulltext). It's made of a part that is the name of a built-in function and of a second part that is the description. I want to extract the description.</p> <p>i.e. I want to extract the part of the text that is between <code>\rPython *function_name*()\r</code> and this <code>\r</code> so the outco...
<p>We can try using <code>re.findall</code> here:</p> <pre><code>input = "\rPython classmethod()\rreturns class method for given function\r" matches = re.findall(r'\rPython\s+[^()]+\(\)\r(.*)\r', input) print(matches) </code></pre> <p>This prints:</p> <pre><code>['returns class method for given function'] </code></p...
python|regex|python-3.x
3
2,471
18,532,519
How to use webservices with https in python
<p>I have used below python code for web services but here my site url is include https. so if i use http then it gives "Method Not Found" error at the time web services runing and if i use https then this code is not working.</p> <p>Anyone let me know how to resolve this issue with https.</p> <pre><code>import urlli...
<p>filmor have right. Try to use requests. An example of function : </p> <pre><code>def http_get(url, user=None, password=None, proxies=None, valid_response_status[httplib.OK], **kwargs): """ Performs a http get over an url @param url: the url to perfom get against @type url: str @param user: user if authentication re...
python|web-services
0
2,472
18,564,745
can't pip install mysql-python
<p>I'm trying to get django/pip/mysql working and i can't seem to figure out how to install mysql-python. this is the error i receive when trying to install mysql-python</p> <pre> pip install mysql-python Downloading/unpacking mysql-python Downloading MySQL-python-1.2.4.zip (113kB): 113kB downloaded Running setup...
<p>try downloading python-dev through software manager:</p> <pre><code>sudo apt-get install python-dev </code></pre>
python|django|pip
53
2,473
71,562,054
local variable assigned in enclosing line referenced before assignment
<p>I have this bit of code</p> <pre class="lang-py prettyprint-override"><code>health = 12 manager_health = 10 def manager_boss_fight_used_for_backup(): sleep(1) print(&quot;manager health is &quot;,manager_health) print(&quot;your health is &quot;,health) sleep(1) print(&quot;the boss get...
<p>Whenever you make an assignment to <code>health</code> inside the <code>manager_fight_used_for_backup()</code> function, Python attempts to assign a new variable called <code>health</code> by default.</p> <p>The fastest fix is to use the <code>global</code> keyword at the beginning of the function body, to make it c...
python|variables|subroutine
0
2,474
69,433,514
Test Intel Extension for Pytorch(IPEX) in multiple-choice from huggingface / transformers
<p>I am trying out one huggingface sample with SWAG dataset <a href="https://github.com/huggingface/transformers/tree/master/examples/pytorch/multiple-choice" rel="nofollow noreferrer">https://github.com/huggingface/transformers/tree/master/examples/pytorch/multiple-choice</a></p> <p>I would like to use Intel Extension...
<p>First you have to understand, which factors actually increases the running time. Following are these factors:</p> <ol> <li>The large input size.</li> <li>The data structure; shifted mean, and unnormalized.</li> <li>The large network depth, and/or width.</li> <li>Large number of epochs.</li> <li>The batch size not co...
performance|intel|huggingface-transformers|intel-python|intel-pytorch
2
2,475
55,233,040
Many to many LSTM with attention at each time step
<p>I am working on time series image classification, where I need to output a classification at each time step (many to many). </p> <p>My Tensorflow graph takes [Batch size, Time step, Image] and implements a deep CNN-LSTM, which currently goes to a time distributed dense layer before classification. </p> <p>In my pr...
<p>Seems that this code worked fine. The error was downstream. If anyone uses this code to implement many-to-many attention, note that it will take a very long time to train as you are learning two additional weight matrixes for each time step.</p>
python|tensorflow|deep-learning|many-to-many
1
2,476
57,460,861
Detect text only inside detected objects
<p>I'm very new to Computer Vision, I'm tryind to build a CV model which will detect and recognize price tags and extract info from it. I've already trained model that can detect price tags using YOLO. But I also want to teach my system to detect and recognize text which only written inside these price tags. Than parse...
<p>Well, the first one that pops into my mind would be to crop the objects detected with YOLO and then run the OCR on that image. After running OCR, you'll have to do some postprocessing to classify each line of text to a specific category (price, name etc.)</p>
python|opencv|yolo
2
2,477
58,505,602
How to create windowed multivariate dataset from SequenceExample TFRecord
<p>I am trying to set up a Tensorflow pipeline using tf.data.datasets in order to load some TFRecord into a Keras model. These data are multivariate timeseries.</p> <p>I am currently using Tensorflow 2.0</p> <p>First I get my dataset from the TFRecord and parse it :</p> <pre class="lang-py prettyprint-override"><cod...
<p>Providing the solution here (Answer Section), even though it is present in the question section, for the benefit of the community.</p> <p>Converting dictionary to a tensor with shape <code>(None,11)</code> using <code>tf.stack</code> in the <strong><em>parse_function</em></strong> has resolved the problem.</p> <p>...
python-3.x|tensorflow-datasets|tensorflow2.0|tf.keras
0
2,478
58,365,726
Subtract products through two tables
<p>It turns out that I am achieving a stock system, however, I managed to make it increase every time a product enters my warehouse but I can't make it subtract every time I leave. </p> <p>The tables I work are <code>product</code> and <code>document_ detail</code>. In the document <code>detail_table</code> I have an ...
<p>I don't know if I have understood you OK.</p> <p>I think that each one of your products has a list of document details. Each one of these details has a <code>cantity_deb</code> and a <code>quantity_to_have</code>. And the quantity available of each product is the sum of the <code>cantity_deb</code> minus the sum of...
python|odoo
0
2,479
58,584,001
How to make a scatter plot with a 3rd variable separating data by color?
<p>My problem is very similar to the one in: <a href="https://stackoverflow.com/questions/39612054/python-scatter-plot-with-dates-and-3rd-variable-as-color">python - scatter plot with dates and 3rd variable as color</a></p> <p>But I want the colors to vary acording to 3 set of values inside my 3rd variable. </p> <p>f...
<p>I think what you should do is:</p> <ol> <li>create an empty <code>list</code> which later will be passed to 'c' in the scatter function.</li> <li>iterate over your data and do a 'switch like' sequence of if statements to add 1,2 or 3 to the list, according to the discretization you mention. These numbes will repres...
python|matplotlib|scatter|astronomy
0
2,480
22,591,266
reading data from a file and storing them in a list of lists Python
<p>I have a file data.txt containing following lines : </p> <p><img src="https://i.stack.imgur.com/rJ0QG.jpg" alt="enter image description here"><br> I would like to extract the lines of this file into a list of lists, each line is a list that will be contained within ListOfLines wich is a list of lists. When there is...
<p>Well, sharing your sample data in an image don't make easy to working with it. Like this I don't even bother and I assume others do the same.</p> <p>However, <code>data = file.readlines()</code> forces the content of the file into a list first, and then you iterate through that list. You could do that instantly wit...
python-3.x
1
2,481
45,487,717
Custom command to upload photo to Photologue from within Django shell?
<p>I have successfully employed Photologue to present <a href="https://ace.scisat.ca/dataplots/gallerylist/" rel="nofollow noreferrer">galleries of regularly-created data plot images</a>. Of course, now that the capability has been established, an obscene number of data plots are being created and they need to be shar...
<p>On just one part of your question: the <code>slug</code> column is empty when the <code>Photo</code> is saved.</p> <p>It <em>should</em> automatically be populated when the <code>Photo</code> is saved - as your copy-and-paste of the Photologue source code above <code>if self.slug is None: self.slug = slugify(self.t...
python|django|photologue|django-shell|django-commands
1
2,482
28,429,512
Python parsing date and find the correct locale_setting
<p>I have the following date string: '3 févr. 2015 14:26:00 CET'</p> <pre><code>datetime.datetime.strptime('03 févr. 2015 14:26:00', '%d %b %Y %H:%M:%S') </code></pre> <p>Parsing this failed with the error:</p> <pre><code>ValueError: time data '03 f\xc3\xa9vr. 2015 14:26:00' does not match format '%d %b %Y %H:%M:%S'...
<p>To parse localized date/time string using <a href="http://userguide.icu-project.org/formatparse/datetime" rel="nofollow noreferrer">ICU date/time format</a>:</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- from datetime import datetime import icu # PyICU import pytz # $ pip install pytz tz = icu.ICUt...
python|datetime|internationalization|locale|datetime-parsing
3
2,483
28,856,137
Triangular indices for multidimensional arrays in numpy
<p>We know that <code>np.triu_indices</code> returns the indices of the triangular upper part of a matrix, an array with two dimensions.</p> <p>What if one wants to create indices as in the following code?</p> <pre><code>indices = [] for i in range(0,n): for j in range(i+1,n): for k in range(j+1,n): ...
<p>In general you can get a list of indexes that follow the logic of the code you put with</p> <pre><code>from itertools import combinations ndim = 3 # number of dimensions n = 5 # dimension's length (assuming equal length in each dimension) indices = list(combinations(range(n), r=ndim) </code></pre> <p>or if you wa...
python|numpy|numerical-methods
3
2,484
14,634,444
Pyramid app: How can I pass values into my request.route_url?
<p>I have this in my views.py file as the view config for my home page:</p> <pre><code>@view_config(route_name='home_page', renderer='templates/edit.pt') def home_page(request): if 'form.submitted' in request.params: name= request.params['name'] body = request.params['body'] page=Page(name,...
<p>I think your form should submit to "/", ie.</p> <pre><code>&lt;!-- where your home_page route is waiting for the POST --&gt; &lt;form action="/" method="post"&gt; </code></pre> <p>With the prior answers this now looks correct:</p> <pre><code>return HTTPFound(location=request.route_url('view_page', pagename=name))...
python|routing|pyramid
5
2,485
68,535,827
Slicing first and last two inputs not working when inputs are taken
<p>If I run the code from the commented <code>#c_list</code>, it works. But if I run it from the <code>a_list</code> that takes input, I get an empty list. How do I solve it?</p> <pre><code>a_list = [input('Enter input for list: ')] #c_list = [10,20,24,25,26] length = len(a_list) if length&gt;3: b_list = a_list[2...
<p>As <a href="https://stackoverflow.com/users/2648811/green-cloak-guy">Green Cloak Guy</a> mentioned, <code>input()</code> always returns a single string.</p> <p>In Python 3.x, if you want multiple inputs you can use the <code>.split()</code> method and a list comprehension:</p> <pre><code>input_list = [int(x) for x i...
python|python-3.x
1
2,486
41,250,880
Stop trial from advancing based on user input in PsychoPy
<p>I'm coding an experiment for an EyeTracker machine using PsychoPy.</p> <p>As suggested in PsychoPy's google group, I've used the Builder View to create the basic structure of the experiment, compiled the script and then added modifications on the Coder View, so the way to handle user's input is the standard generat...
<p>You haven't included the critical part, which is the loop around your first code snippet. This loop is probably something like</p> <pre><code>while continueRoutine: # Your code here </code></pre> <p>... which runs the code until continueRoutine is set to <code>False</code> which happens when the user presses...
python|psychopy
1
2,487
41,252,840
list returns None, omits value
<p>I am attempting to return values and positions of letters. Running this as a plain for loop works just fine. It's when I turned it into a function that it started to look wonky.</p> <p>Here it is along with its output:</p> <pre><code>dict = {'a': 1, 'b': 2 ... 'z': 26} list1 = [] list2 = [] def plot(word): c...
<p>I think that the issue is that your are trying to map a capital letter. I would simply change the for loop to iterate over the lowercase.</p> <pre><code>for i in word.lower(): y = dict.get(i) list1.append(y) #keeps printing None for the first letters counter += 1 x = counter list2.append(x) </co...
python|list|dictionary
2
2,488
6,960,895
Conditional addition in Python
<p>I have been struggling with a text file to perform conditional appending/extending certain text using Python. My apologies in advance if this is too basic and already been discussed here in someway or the other :(</p> <p>Concerning the code (attached), I need to add statement "mtu 1546" under the statement containi...
<p>The basic answer to your question is very simple. Strings are immutable, so you can't <code>append</code> to or <code>extend</code> them. You have to create a new string using concatenation. </p> <pre><code>&gt;&gt;&gt; print i interface Vlan2286 description mgmt_SNMA_Rs no ip address xconnect 22.93.94.86 2286 e...
python
1
2,489
57,134,770
How to integrate Lambda, Alexa, and my code (Python - Tweepy)?
<p>I am trying to tweet something by talking to Alexa. I want to put my code on AWS Lambda, and trigger the function by Alexa.</p> <p>I already have a Python code that can tweet certain string successfully. And I also managed to create a zip file and deploy it on Lambda (code depends on the "tweepy" package). However,...
<p>Alexa ASK_SDK Psuedo Code: This is pseudo code of the new ASK_SDK, which is the predecessor to the ALEXA_SDK. Also note I work in NodeJS but the structure is likely the same</p> <ul> <li>Outer Function with Call Back - Lambda Function Handler <ul> <li>CanHandle Function <ul> <li>Contains logic to determine if thi...
python|handler|alexa|alexa-skills-kit
0
2,490
56,949,488
Run script with subprocess.run() in Python, blocking all file read/write attempts
<p>I have a web server running Apache 2 on Raspbian Stretch. It is going to be a programming contest website, where users can send code via a HTML form, that sends their source code to PHP via a POST request. PHP then runs (using <code>exec()</code>) a Python script with arguments such as the submitted code path. The s...
<p>doing this securely, to put it simply, is difficult. it's relatively easy to escape even a chroot jail if you're not really careful about how you set it up. basically the Unix security model isn't built to make this sort of thing easy and it's assumed that things are mostly cooperative</p> <p>docker would probabl...
php|python|linux
1
2,491
25,785,243
Understanding time.perf_counter() and time.process_time()
<p>I have some questions about the new functions <code>time.perf_counter()</code> and <code>time.process_time()</code>.</p> <p>For the former, from the documentation:</p> <blockquote> <p>Return the value (in fractional seconds) of a performance counter, i.e. <strong>a clock with the highest available resolution</st...
<p>There are two distincts types of 'time', in this context: absolute time and relative time.</p> <p>Absolute time is the 'real-world time', which is returned by <code>time.time()</code> and which we are all used to deal with. It is usually measured from a fixed point in time in the past (e.g. the UNIX epoch of 00:00:...
python|python-3.x
134
2,492
44,446,491
Editable console listview in python
<p>I'm trying to find a way to make an editable listview in python to be used in a terminal. </p> <p>Basically each line of that listview will have a single word and I would like to be able to check or uncheck some words in the listview. Then, once I'm done editing I want to be able to close the listview and continue ...
<p>The curses library is a good way to do this. It allows you to write strings to the screen in a specific position instead of just constantly scrolling down like a typical Python program. And it has the ability to grab key inputs so you could use arrow keys and space bar to select individual lines. </p> <p>Because y...
python|listview|terminal|console
1
2,493
20,869,711
Features in sklearn logistic regression
<p>I have some problem with adding own features to sklearn.linear_model.LogisticRegression. But anyway lets see some example code:</p> <pre><code>from sklearn.linear_model import LogisticRegression, LinearRegression import numpy as np #Numbers are class of tag resultsNER = np.array([1,2,3,4,5]) #Acording to resultNE...
<p>Not quite sure about your question, but few thing that might help you:</p> <ul> <li><p>You can use <code>predict_proba</code> function to estimate probabilities for each class:</p> <pre><code>&gt;&gt;&gt; logit.predict_proba(xPP) array([[ 0.1756304 , 0.22633999, 0.25149571, 0.10134168, 0.24519222]]) </code></p...
python|machine-learning|nlp|logistic-regression|scikit-learn
1
2,494
71,919,693
PySimpleGuiWeb change ip address
<p>I have a python script that uses PySimpleGuiWeb. I want to host it on my server and connect to it from another computer. But the script is running on 127.0.0.1. Can I somehow change this, or is there another way?</p>
<p>From the host device running the pysimplegui python script, you can likely load the gui via 127.0.0.1:###### through a browser (where ##### is your port). This is because it's hosted and being accessed from the same device.</p> <p>Accessing from another device on the same network: try using the IP of the device host...
python|pysimplegui
0
2,495
35,833,011
How to add if condition in a TensorFlow graph?
<p>Let's say I have following code:</p> <pre><code>x = tf.placeholder("float32", shape=[None, ins_size**2*3], name = "x_input") condition = tf.placeholder("int32", shape=[1, 1], name = "condition") W = tf.Variable(tf.zeros([ins_size**2*3,label_option]), name = "weights") b = tf.Variable(tf.zeros([label_option]), name ...
<p>You're correct that the <code>if</code> statement doesn't work here, because the condition is evaluated at graph construction time, whereas presumably you want the condition to depend on the value fed to the placeholder at runtime. (In fact, it will always take the first branch, because <code>condition &gt; 0</code>...
python|if-statement|tensorflow
104
2,496
35,983,072
Mass invoices duplicate Odoo8
<p>Is there anyway to duplicate, or create, a bunch of invoices with xml-rpc?</p> <p>I try with the copy method of the Odoo ORMApi</p> <pre><code>invoices = call('account.invoice','search_read', [('type','ilike',"out_invoice")]) for invoice in invoices: inv = invoice.copy() </code></pre> <p>How can I insert the new...
<p>Try erppeek, it's a python library that makes this much easier</p> <pre><code>client = erppeek.Client(SERVER, DATABASE, USERNAME, PASSWORD) invoices=client.search('account.invoice',[('type','ilike',"out_invoice")]) for i in range(len(invoices)): client.copy('account.invoice',invoices[i-1]) </code></pre>
python|xml-rpc|odoo-8
0
2,497
15,047,008
Use Python re to get rid of links
<p>Say I have a string looks like <code>&lt;a href="/wiki/Greater_Boston" title="Greater Boston"&gt;Boston–Cambridge–Quincy, MA–NH MSA&lt;/a&gt;</code></p> <p>How can I use <code>re</code> to get rid of links and get only the <code>Boston–Cambridge–Quincy, MA–NH MSA</code> part?</p> <p>I tried something like <code>ma...
<pre><code>re.sub('&lt;a[^&gt;]+&gt;(.*?)&lt;/a&gt;', '\\1', text) </code></pre> <p>Note that parsing HTML in general is <a href="https://stackoverflow.com/a/1732454/216074">rather dangerous</a>. However it seems that you are parsing MediaWiki generated links where it is safe to assume that the links are always simila...
python|regex
3
2,498
29,723,449
Python declaring a numpy matrix of lists of lists
<p>I would like to have a numpy matrix that looks like this [int, [[int,int]]] I receive an error that looks like this "ValueError: setting an array element with a sequence."</p> <p>below is the declaration</p> <pre><code>def __init__(self): self.path=np.zeros((1, 2)) </code></pre> <p>I attempt to assign a value...
<p>Do you want a higher dimensional array, say 3d, or do you really want a 2d array whose elements are Python <code>lists</code>. Real lists, not numpy arrays?</p> <p>One way to put lists in to an array is to use <code>dtype=object</code>:</p> <pre><code>In [71]: routes=np.zeros((1,2),dtype=object) In [72]: routes[0...
python-3.x|numpy
2
2,499
46,629,681
How to find recursively all links from a webpage with beautifulsoup?
<p>I have been trying to use some code I found <a href="https://stackoverflow.com/questions/20198934/how-to-get-all-links-from-website-using-beautiful-soup-python-recursively">in this answer</a> to recursively find all links from a given URL:</p> <pre><code>import urllib2 from bs4 import BeautifulSoup url = "http://f...
<p>Your recursiveUrl tries to access a url link that is invalid like: /webpage/category/general which is the value your extracted from one of the href links. </p> <p>You should be appending the extracted href value to the website's url and then try to open the webpage. You will need to work on your algorithm for recur...
python|recursion|beautifulsoup
3