Unnamed: 0
int64
0
1.91M
id
int64
337
73.8M
title
stringlengths
10
150
question
stringlengths
21
64.2k
answer
stringlengths
19
59.4k
tags
stringlengths
5
112
score
int64
-10
17.3k
9,400
58,122,950
Can Django template tags be used like Django Template callables?
<p>I'm using the the Django Template Language to call into a model's method to create dynamic ids according to product-specific logic.</p> <p>JSON files hold product-specific configuration information. I use the Django Template Language in strings in the JSON files so each product has their own logic for creating prod...
<p>No that is not at all how it works. A template tag cannot be a method on a model. If you want to define a template tag, it needs to go in a file inside the <code>templatetags</code> directory of your app, and you need to call it with the tag syntax <code>{% ... %}</code>. Of course because of that it can't accept <c...
python|django
1
9,401
69,331,450
Passing variables to html from Python
<p>I have a function which sends a mail to a user, like this:</p> <pre><code>import os import smtplib import imghdr from email.message import EmailMessage EMAIL_ADDRESS = email EMAIL_PASSWORD = password msg = EmailMessage() msg['Subject'] = 'Email Title' msg['From'] = EMAIL_ADDRESS msg['To'] = ANOTHER_EMAIL_ADDRESS ...
<p>In <code>email.html</code> change <code>{{userEmail}}</code> to <code>{userEmail}</code>. Then you should be able to use <a href="https://docs.python.org/3/tutorial/inputoutput.html#the-string-format-method" rel="nofollow noreferrer">Python string formatting</a> to add the <code>userEmail</code> variable.</p> <pre><...
python|html
3
9,402
54,139,705
Find perticular value from mongodb collection
<p>I am writing <strong>Python3</strong> code to get values from <strong>MongoDB</strong>. I have one collection which has only 2 records. </p> <pre><code>{ "_id" : ObjectId("5c35b8aa04f44540cbea189d"), "BTCBlockNumber" : 1708 } { "_id" : ObjectId("5c3711d47095538174d342b6"), "ETHBlockNumber" : 1 } </code></pre> <p>N...
<p><strong>Follow these below Code:</strong></p> <pre><code>getcheckblocknumber = self.col.find({},{item:1, _id: 0}) </code></pre>
python-3.x|mongodb
0
9,403
28,685,036
handle Python exception/errors in PHP
<p>I am running some python script from within a PHP script using PHP's <code>exec($cmd, $output)</code> function. </p> <p>The <a href="http://php.net/manual/en/function.exec.php" rel="nofollow">documentation</a> states that the all output of the program is written to the <code>$output</code> array. This works fine, h...
<p>Redirect stderr to stdout</p> <pre><code>$ret_val = exec('python run_python.py 2&gt;&amp;1', $output); </code></pre>
php|python|error-handling
3
9,404
49,367,499
How do i format the response from watson conversation to show user?
<p>i am working in pycharm and just doing a simple interaction with the watson conversation service where you ask it a questione and it responds, however the response from watson sends all sorts of other info as well that i don't want to display, i only want to display the answer and then let the user enter another que...
<p>The result is in <code>response</code>, which is an object.</p> <p>You can access the text from Watson with:</p> <pre><code>print('\n'.join(response['output']['text'])) </code></pre>
python-2.7|watson-conversation
0
9,405
24,480,358
How to set the values of a dataframe given a series of indices and corresponding column names?
<p>Assume I have a dataframe df1:</p> <pre><code> A B C D E Date 2009-01-30 NaN NaN NaN NaN NaN 2009-02-02 NaN NaN NaN NaN NaN 2009-02-03 NaN NaN NaN NaN NaN 2009-02-04 NaN NaN NaN NaN NaN 2009-02-05 NaN NaN NaN NaN NaN 2009-02-06 NaN Na...
<pre><code>import numpy as np import pandas as pd df1 = pd.DataFrame(np.nan, columns=list('ABCDE'), index=pd.to_datetime( ['2009-01-30', '2009-02-02', '2009-02-03', '2009-02-04', '2009-02-05', '2009-02-06', '2009-02-09', '2009-02-10'])) ser = pd.Series(list('AE'), index=pd.to_datetime(['2009-02-04', '2009-02-0...
python|pandas|indexing
1
9,406
38,473,175
Make return of a method/instance become an attribute
<p>I have a class A() include some method:</p> <pre><code>class A(self): def __init__ (self, x1, x2): self.x1 = x1 self.x2 = x2 def plus(self): X3 = self.x1 + self.x2 return X3 </code></pre> <p>How can I make X3 become an attribute which I can access by "self.X3" to use it for ...
<p>One way would be to simply make <code>X3</code> an attribute by prepending <code>self.</code>. For example:</p> <pre><code>class A(self): def __init__ (self, x1, x2): self.x1 = x1 self.x2 = x2 def plus(self): self.X3 = self.x1 + self.x2 return self.X3 </code></pre> <p>I'm n...
python|class|methods|attributes
2
9,407
54,650,277
Auto row-adjust in excel, python
<p>with cells containing text of different fontsizes, how can we adjust the row height automatically using openpyxl in python so that the text inside any cell can be seen properly.</p>
<p>Use <code>wrap_text</code> property of openpyxl:</p> <pre><code>for row in ws.iter_rows(): for cell in row: cell.style.alignment.wrap_text=True </code></pre>
python|excel|openpyxl
-1
9,408
54,677,154
Is there a way to send "User is typing..." status in telethon?
<p>I wanted to send an update to an entity that will show up as "X is typing..." (X being me) on their (recipient's) side. I've looked through the docs (especially under the <a href="https://telethon.readthedocs.io/en/latest/telethon.client.html" rel="nofollow noreferrer"><code>telethon.client</code></a> package) and c...
<p>The function you are looking for is <code>SetTypingRequest</code>. Read more about it here:</p> <p><a href="https://lonamiwebs.github.io/Telethon/methods/messages/set_typing.html" rel="nofollow noreferrer">https://lonamiwebs.github.io/Telethon/methods/messages/set_typing.html</a></p> <p>Example:</p> <pre><code>fr...
python|telegram|telethon
3
9,409
52,856,935
Replace values based on index pandas
<p>I'm working with a dataset, from which a subset has initial values and final values. I created an <code>id</code> that lets me identify those observations, so after applying this:</p> <pre><code>df['aux']=df.duplicated(subset=['id'], keep=False) df_dup=df_dup[df_dup.aux==True] df_dup.sort_values(by='id').reset_ind...
<p>Without <code>groupby</code> and base on your <code>drop_duplicates</code></p> <pre><code>df.value=df.id.map(df.drop_duplicates('id',keep='last').set_index('id').value) df Out[436]: index id status value 0 88 1 'initial' 12 1 95 1 'final' 12 2 63 2 'initial' 13 3 52 ...
pandas|indexing|replace
2
9,410
39,870,398
Django Factory Boy iterate over related parent
<p>I have a project with Clients, Draftschedules, LineItems and Servers.</p> <ul> <li><p>Each client has a single DraftSchedule, each Draftschedule has many Lineitems</p></li> <li><p>Each Client has many Servers</p></li> <li><p>Each LineItem has a Single Server</p></li> </ul> <p><a href="https://i.stack.imgur.com/JPR...
<p>You could try using a <a href="http://factoryboy.readthedocs.io/en/latest/reference.html#id6" rel="nofollow">lazy_attribute_sequence</a> :</p> <pre><code>@factory.lazy_attribute_sequence def servers(obj, seq): all_servers = obj.draftschedule.client.servers.all() nb_servers = all_servers.count() return a...
python|django|fixtures|factory-boy
3
9,411
44,058,868
sort list of dicts by different keys in python
<p>here is the list of dict I have:</p> <pre><code>[{'title': 'C'}, {'contentTitle':'B'}, {'title': 'A'}] </code></pre> <p>In python, is it possible to write a comparator to sort the list, which would first look value under <code>title</code> and if there is no <code>title</code>, use the value under <code>contentTit...
<p>You can use <a href="https://docs.python.org/3.6/library/stdtypes.html#dict.get" rel="nofollow noreferrer"><code>dict.get()</code></a> to look up a key without raising an exception:</p> <pre><code>&gt;&gt;&gt; lst = [{'title': 'C'}, {'contentTitle':'B'}, {'title': 'A'}] &gt;&gt;&gt; sorted(lst, key=lambda x: x.get(...
python
3
9,412
41,756,726
subprocess VS function VS Parallel programs in /etc/profile
<p>I have made 3 python codes. I am using a Raspberry Pi</p> <ul> <li>Code 1 - Prints Barcode on a button press</li> <li>Code 2 - Sends Barcode to Server</li> <li>Code 3 - Runs in background to record data in case of network failure and resend data once internet comes on.</li> </ul> <p>Note: All these codes are running...
<p>Option 1 is the most universal. That's how this type of programs works -- they work in different processes, maybe even on different machines or containers and work with each other via a network/ipc API.</p> <p>Option 2 is almost the same, but it doesn't make sense. <a href="https://askubuntu.com/questions/247738/wh...
python|parallel-processing
0
9,413
30,168,126
user registration in django rest framework
<p>I am creating a server side for android application in DRF which will require user registration and login\logout endpoints. also obviously different permissions when a user logged in.</p> <p>I followed the rest framework tutorial here - <a href="http://www.django-rest-framework.org/tutorial/1-serialization/" rel="n...
<p>I've copied it from Django documentation as an answer for your first question.</p> <blockquote> <p>One of the most powerful parts of Django is the automatic admin interface. Best thing is that you can customise it easily.</p> <p>If logged in as a superuser, you have access to create, edit, and delete any...
android|python|django|rest|django-rest-framework
0
9,414
64,474,768
Clear search bar using selenium
<p>Im using selenium to check if FB pages exist. When i enter the page title in the search bar it works fine but after the second loop the name of the page gets attached to the preview search and i cant find a way to clear the previous search.</p> <p>For example it looks for xyz for the first time then it looks for xyz...
<p>You can use WebElement.clear();//to clear the previous search item WebElement.sendkeys(abc);//to insert the new search</p> <p>Also I guess you have a sticky search in your application hence I recommend you to use this method everytime you insert something in the searchbox</p>
python|python-3.x|selenium|selenium-webdriver
1
9,415
73,121,342
Celery in python to build microservices
<p>First, thanks for reading this. I want to break down a project to small microservices. I've been thinking of different tools like gRPC, but I think celery might be a better option for me. Please if I'm wrong and celery is not a good choice, tell me why.</p> <h3>What exactly I want to do?</h3> <ul> <li>For example, I...
<p>This particular error indicates that using <code>result.get()</code> within a task is a bad practice that could lead to deadlocks.</p> <p>If you know what you are doing you can try <a href="http://docs.celeryproject.org/en/latest/_modules/celery/result.html" rel="nofollow noreferrer">allow_join_result</a> but that c...
python|python-3.x|celery|microservices|celerybeat
0
9,416
55,857,242
Comparison of list to list of lists and return the other element from the list of list
<p>I have a list - answers:</p> <pre><code>[0,1] </code></pre> <p>and another list of list - questions: </p> <pre><code>[[0,ABC], [1,DEF], [3,XYZ]] </code></pre> <p>How can I compare the 2 and return</p> <pre><code> ABC, DEF </code></pre> <p>based on the comparison of all elements in answers to first elements i...
<p>You can use a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow noreferrer">list comprehension</a> and keep the second items in <code>questions</code> if the first item is contained in <code>answers</code> :</p> <pre><code>answers = set([0,1]) [i[1] for i in questio...
python|list|tuples
2
9,417
53,308,099
how to cycle in python?
<p>I have the code to retrieve the parameters from the photo. I would need to put it in the loop so it would load all of my photos from the folder and write them down in Python`enter code here</p> <pre><code>import requests BASE_URL = 'https://westeurope.api.cognitive.microsoft.com/face/v1.0/detect' headers = { 'Oc...
<p>I guess you want <code>os.listdir</code></p> <pre><code>for fname in os.listdir(basepath): if fname[-3:] in ["jpg","gif","png"]: print("this is an image:",os.path.join(basepath,name)) </code></pre>
python|python-2.7|cycle
0
9,418
52,978,434
Is it possible to use StratifiedKFold from sklearn in multi input Neural Networks?
<p>I have a dataset that can be passed to a multi input neural network in the shape of a python <em>dictionary</em> or a <em>list</em>:</p> <p><strong>Example</strong>:</p> <pre><code>#dict {'input1': X1, 'input2': X2, 'input3': X3}, {'output': Y} #list [ X1, X2, X3], y </code></pre> <p>Now I would like to use <stro...
<p>skf.split() returns you indices and it depends only on Y:</p> <pre><code>for train_index, test_index in skf.split(X, y): ... print("TRAIN:", train_index, "TEST:", test_index) ... X_train, X_test = X[train_index], X[test_index] ... y_train, y_test = y[train_index], y[test_index] </code></pre> <p>So you can...
python|scikit-learn|neural-network|keras|cross-validation
2
9,419
71,992,945
Telling me that I need flask but I already have it?
<p>every time I try to run ./startup .sh, I get the error ModuleNotFoundError: No module named 'flask', but I already did pip install flask multiple time!!! im using startup.sh script from <a href="https://github.com/malwaredllc/byob/tree/master/web-gui" rel="nofollow noreferrer">https://github.com/malwaredllc/byob/tre...
<p>If you are using Linux then there is 2 version of python which comes with it. If you have more then one then use</p> <p><code>pip3 install flask</code></p> <p><strong>or</strong></p> <p><code>python3 -m pip install flask</code></p> <p>Tell me if you still have problem</p>
python|pip
-1
9,420
10,346,336
List of lists into numpy array
<p>How do I convert a simple list of lists into a numpy array? The rows are individual sublists and each row contains the elements in the sublist.</p>
<p>If your list of lists contains lists with varying number of elements then the answer of Ignacio Vazquez-Abrams will not work. Instead there are at least 3 options:</p> <p>1) Make an array of arrays:</p> <pre><code>x=[[1,2],[1,2,3],[1]] y=numpy.array([numpy.array(xi) for xi in x]) type(y) &gt;&gt;&gt;&lt;type 'nump...
python|list|numpy
271
9,421
62,569,780
access only first 80% columns of a data frame
<p>I want to access only the first 80% columns of my dataframe and store it into new data frame whereas store the remainig 20% in another data frame. Here is something I tried:</p> <pre><code>ratings_df=ratings_df.iloc[:,:int(ratings_df.shape()[1]*0.8)-1] </code></pre> <p>however this gave an error:</p> <pre><code>Tra...
<p>You should remove the brackets. You only need df.shape[1]. By the way for more readability, I suggest you use rather</p> <pre><code>shape_80 = int(df.shape[1]*0.8)-1 ratings_df=ratings_df.iloc[:,:shape_80] </code></pre> <p>Or something like that</p>
python|pandas|numpy|dataframe|recommendation-system
2
9,422
61,989,827
Is there a way to use apply() to create two columns in pandas dataframe?
<p>I have a function returning a tuple of values, as an example:</p> <pre><code>def dumb_func(number): return number+1,number-1 </code></pre> <p>I'd like to apply it to a pandas DataFrame</p> <pre><code>df=pd.DataFrame({'numbers':[1,2,3,4,5,6,7]}) test=dumb_df['numbers'].apply(dumb_func) </code></pre> <p>The re...
<pre><code>df[['number_plus_one', 'number_minus_one']] = pd.DataFrame(zip(*df['numbers'].apply(dumb_func))).transpose() </code></pre> <p>To understand, try taking it apart piece by piece. Have a look at <code>zip(*df['numbers'].apply(dumb_func))</code> in isolation (you'll need to convert it to a list). You'll see how...
python|pandas|apply
1
9,423
61,688,764
Keras CNN: Incompatible shapes [batch_size*2,1] vs. [batch_size,1] with any batch_size > 1
<p>I am Fitting a Siamese CNN with the following structure: </p> <pre><code>def get_siamese_model(input_shape): """ Model architecture """ # Define the tensors for the three input images A_input = Input(input_shape) B_input = Input(input_shape) C_input = Input(input_shape) # C...
<p>Mentioning the solution in this (Answer) section even though it is present in the Comments section, for the benefit of the community.</p> <p>For the above code, with <code>batch_size &gt; 1</code>, it is resulting in error, </p> <pre><code>InvalidArgumentError: Incompatible shapes: [4,1] vs. [2,1] [[node los...
python-3.x|tensorflow|image-processing|keras|conv-neural-network
0
9,424
64,341,791
Why does this dict.get() throw this error?
<p>I have the following code (probably self-explanatory):</p> <pre><code>def main(): print(&quot;Please input 2 numbers to operate on: &quot;) value1 = int(input()) value2 = int(input()) print(&quot;Please input an operator: &quot;) operator = str(input()) result ={ '+': lambda x, y: x+y...
<p>You're putting the parenthesis in the wrong place- <code>.get(operator(value1, value2), &quot;Error&quot;)</code> calls <code>operator</code> with <code>value1</code> and <code>value2</code>.</p> <p>What you probably meant was <code>.get(operator, &quot;Error&quot;)(value1, value2)</code> which correctly calls the r...
python|python-3.x
2
9,425
10,866,199
How to make editable install of Python package from vcs into specific directory using pip?
<p>By default pip installs <em>editable</em> packages into <code>src</code> subdirectory of the directory where Python is installed. </p> <p>I'd like to install a package from version control to a directory of my choosing using pip's support for checking out a package from source control, for example:</p> <pre><code>...
<p><code>pip help install</code> says:</p> <pre><code>--src=DIR, --source=DIR, --source-dir=DIR, --source-directory=DIR Check out --editable packages into DIR </code></pre> <p>For example:</p> <pre><code>pip install -e git+https://github.com/kennethreitz/requests.git@355b97165c#egg=requests-org...
python|version-control|pip
8
9,426
70,539,584
Python script to find error code 404 from URL list
<pre><code>from pandas import DataFrame import csv import requests urllist_404 = [] resplist = [] code_list = [] count = 0 with open('cmsURl.csv1.csv', 'r') as file: reader = csv.reader(file) for row in reader: urls = row[1] request = requests.get(urls) request_code = request.status_code count =...
<pre><code>from pandas import DataFrame import csv import requests import openpyxl urllist_404 = [] resplist = [] code_list = [] count = 0 with open('urlpages1.csv', 'r') as file: reader = csv.reader(file) for row in reader: print(row) urls = row[0] response = requests.get(urls) ...
python-3.x
0
9,427
56,863,136
Get Percent change where axis equals columns in python pandas?
<p>I have the following dataset:</p> <pre><code>import pandas as pd w = pd.Series(['EY', 'EY', 'EY', 'KPMG', 'KPMG', 'KPMG', 'BAIN', 'BAIN', 'BAIN']) x = pd.Series([2020,2019,2018,2020,2019,2018,2020,2019,2018]) y = pd.Series([100000, 500000, 1000000, 50000, 100000, 40000, 1000, 500, 4000]) z = pd.Series([10000, 10000...
<p>just specify <code>periods=-1</code> and pick column <code>[actual_cost]</code> as follows:</p> <pre><code>df['actual_budget_pct_diff'] = df.pct_change(periods=-1, axis='columns',fill_method='ffill')['actual_cost'] Out[160]: actual_cost budgeted_cost actual_budget_pct_diff consultant fisc...
python|python-3.x|pandas|group-by
3
9,428
69,758,364
How to use a var in multiple methods in python
<p>I have a few files in my code that speak to the database</p> <p>This might look something like this:</p> <pre><code>def addUser(): # some code def verifyUser(): # some code def addStuffToDB(): # some code </code></pre> <p>In all of the above I need to use a variable - let's call it <code>db</code> - that hol...
<p>If you have all this functions inside the same file, it is enough to just define variable <code>db</code> outside any function (this will make it global). Now all functions will be able to see <code>db</code> variable. But if you change <code>db</code> inside a function it will not change outside the function.</p> <...
python|python-3.x|variables
2
9,429
69,969,042
Python open("file", "w+") not creating a nonexistent file
<p>Similar questions exist on Stack Overflow. I have read such questions and they have not resolved my problem. The simple code below results in a File Not Found Error. I am running Python 3.9.1 on Mac OS X 11.4</p> <p>Can anyone suggest next steps for troubleshooting the cause of this?</p> <pre><code>with open(&quot;...
<p>**sometimes the compiler can't find any path like that you insert in open() function. at that time as possible you can save by default in the folder where your programs were saved by IDE. the followed syntax may be helpful for you **</p> <pre><code>with open('test.txt', 'w+') as f: f.write(&quot;xyz&quot;) </c...
python|macos|file|file-io|with-statement
0
9,430
66,192,403
How to get time values as strings, during read_excel execution?
<p>i have to parse ODF-format turnstile's data file. In the file are employees entry/out time values in HH:MM:SS (like a 141:59:30).<br /> <a href="https://drive.google.com/file/d/1j0EEraI-JbfXKoaliXi_LV85S3_nIAk5/view?usp=sharing" rel="nofollow noreferrer">link to sample file on GoogleDrive</a></p> <p>My attempts to o...
<p>You can pass a dictionary to the dtype parameter where you input your column name as the key, and the data type as the value.</p> <p>Could look something like this :</p> <pre><code>df = pd.read_excel(filename, engine=&quot;odf&quot;, skiprows=3, dtype={'time_col':str}) </code></pre> <p><strong>UPDATE</strong></p> <p...
python|pandas|datetime|ods
0
9,431
72,733,784
Converting Month Number to Month Name in Python
<p>I am trying to convert the current month number to the month name. I have read similar threads, but I am getting an error when I try the conventional method and I don't know what is causing the error. Here is my code:</p> <pre><code>month_name = datetime.now().month month_name.strftime(&quot;%B&quot;) </code></pre>...
<p>You need to store the date corresponding to the month you are getting from <code>datetime.now()</code>:</p> <pre><code>from datetime import datetime date = datetime.now() month_number = date.month print(date.strftime(&quot;%B&quot;), month_number) </code></pre> <p><strong>Output:</strong></p> <pre><code>June 6 </c...
python|date
0
9,432
68,273,927
OSError: no library called "cairo" was found
<p>I've been trying to figure out why I'm getting this error only when I'm running this in a docker container, but when I run my program locally, it works fine. I have looked at other posts on StackOverflow that had issues similar like this, but unfortunately they all seem to have problems running their programs locall...
<p>The resolution to my problem is exactly as many people described; the libcairo.so2 library is not included in the python library. To add it into a docker container, you just had to edited the dockerfile like so...</p> <pre><code> FROM python:3.8-slim-buster ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 # I...
python|docker-compose|dockerfile
3
9,433
63,070,451
Tkinter Entry returns blank when called from another script but works fine by its self
<p>The is going to work like this: Launcher with buttons to run different functions on other scripts. However when I try launching the &quot;New Account&quot; a new window pops up as it should but the entry field prints blank.</p> <p>Launcher:</p> <pre><code>import Setup as s import Stock as t from tkinter import * imp...
<p>It is because you have used multiple instances of Tk(). Either change Tk() to Toplevel() inside setep() function or change self.searched = StringVar() to self.searched = StringVar(window) inside App.<strong>init</strong>()</p>
python|tkinter
0
9,434
58,840,462
Indexing numpy.ndarrays periodically
<p>I am trying to access (read/write) <code>numpy.ndarrays</code> periodically. In other words, if I have <code>my_array</code> with the shape of <strong>10*10</strong> and I use the access operator with the inputs:</p> <p><code>my_arrray[10, 10]</code> or <code>acess_function(my_array, 10, 10)</code></p> <p>I can ha...
<p>I think this does what you want but I'm not sure whether there's something more elegant that exists. It's probably possible to write a general function for an Nd array but this does 2D only. As you said it uses modular arithmetic.</p> <pre><code>import numpy as np def access(shape, ixr, ixc): """ Returns a s...
python|numpy|numpy-ndarray
1
9,435
15,922,382
Trying to parse source IP's from apache access log and write the output to a file but only 1 ip is written
<p>I'm trying to read an apache access log and pull all source ip's from there to an output file. I'm new to python so i'm not sure i'm doing it right, but it has to be in python.</p> <pre><code>#! python for line in open('/var/log/apache2/access.log'): ip = line.split(' ')[0] print ip </code></pre> <p>I know...
<p>You missed indent:</p> <pre><code>#! python for line in open('/var/log/apache2/access.log'): ip = line.split(' ')[0] print ip </code></pre> <p>And to write to file you can use something like this:</p> <pre><code>#! python f = open("ip.txt", "w") for line in open('/var/log/apache2/access.log'): ...
python|apache|parsing
4
9,436
59,804,824
Python, Matplotlib: How to set the axis range when x is time?
<p>I am doing my school Arduino project at home, and the teacher asks me to visualize my data for him. On my x-axis, I have more than 20K time points need to show, and I try to set a range for it.</p> <p>The graph I am trying to achieve: <img src="https://i.stack.imgur.com/i3OSc.png" alt="desired graph"></p> <p>What ...
<p>Here an example of how you can plot your data using <code>r</code>:</p> <p>As you did not provide a reproducible example, I created a fake one using my understanding of your code. Basically, it looks that you have a file with 4 columns: Days, Temperature, Humidity and Light_levels. Here, I only create two columns. ...
python|r|matplotlib|range|axis
0
9,437
59,848,703
Python tkinter how can I copy information from a Text widget to a Canvas widget?
<p>To put it simple, i want to write stuff in the text widget and then have it copied onto a canvas widget on the same coordinates (in the code below the Text widget size is the same as the canvas one)</p> <p><a href="https://i.stack.imgur.com/X1zQ7.png" rel="nofollow noreferrer">here is an image of the code</a></p> ...
<p>It looks like you're trying to show some text to display only. If that's the case, set it's <code>state</code> property to disabled <strong>after</strong> updating it.</p> <p><code>text_editor.configure(state='disabled')</code></p> <p>However, if you really want to replace it with a canvas with the same information,...
python-3.x|canvas|tkinter|text|widget
1
9,438
49,305,174
fast way to stack vectors into a matrix in Python
<p>I want to stack 100k vector of the same lentgh (500) into a single matrix in python but it takes too much time.</p> <p>here is my code:</p> <pre><code>stacked = all_vectors[0] for i in range(1,100000): stacked = np.column_stack((stacked ,all_vectors[i])) </code></pre> <p>Do you know how to make this quicker?<...
<p>You should get the answer you want with</p> <pre><code>stacked = np.column_stack(all_vectors[:100000]) </code></pre> <p>There appears to be no difference between that and</p> <pre><code>stacked = np.array(all_vectors[:100000]).transpose() </code></pre> <p>as you can see from this interactive session:</p> <pre><...
python|loops|numpy|matrix|vector
3
9,439
24,944,780
py2exe error: "Error in atexit._run_exitfuncs:Error in sys.exitfunc:"
<p>I am trying to wrap my pyqt application into a windows executable using py2exe. I was able to generate the exe just fine but on running it, it gives an error which I have no clue about. </p> <p>Here's my setup.py:</p> <pre><code>from distutils.core import setup import py2exe setup(name="dcm", version="0.1",...
<p>For posterity:</p> <p>The problem was that there were few "print" statements in my scripts that I was using for debugging (the app was developed on Linux). But evidently these cause the above mentioned error on windows. When I got rid of all those print statements my app started working.</p> <p><strong>Update</str...
python|windows|pyqt4|py2exe
1
9,440
60,324,369
How to initialize a session in Flask?
<p>Upon any incoming connection, so whenever a new computer or a browser connects and a new session cookie is created, I want to initialize a couple of session variables. If I do this:</p> <pre><code>session[&quot;authorized&quot;] = False session[&quot;client_id&quot;] = None session[&quot;client_secret&quot;] = None ...
<p>Try this method works for me</p> <pre><code>if not session.get('authorized'): session['authorized'] = False if not session.get('client_id'): session['client_id'] = None if not session.get('client_secret'): session['client_secret'] = None if not session.get('go_idt'): session['go_id'] = None if not se...
python|flask|web-applications
1
9,441
3,195,781
Find n greatest numbers in a sparse matrix
<p>I am using sparse matrices as a mean of compressing data, with loss of course, what I do is I create a sparse dictionary from all the values greater than a specified treshold. I'd want my compressed data size to be a variable which my user can choose.</p> <p>My problem is, I have a sparse matrix with alot of near-z...
<p><code>scipy.stats.scoreatpercentile(arr,per)</code> returns the value at a given percentile:</p> <pre><code>import scipy.stats as ss print(ss.scoreatpercentile([1, 4, 2, 3], 75)) # 3.25 </code></pre> <p>The value is interpolated if the desired percentile lies between two points in <code>arr</code>.</p> <p>So if y...
python|numpy|sparse-matrix
2
9,442
2,391,788
Models in database speed vs static dictionaries speed
<p>I have a need for some kind of information that is in essence static. There is not much of this information, but alot of objects will use that information.</p> <p>Since there is not a lot of that information (few dictionaries and some lists), I thought that I have 2 options - create models for holding that informat...
<p>If they're truly never, ever going to change, then feel free to put them in your <code>settings.py</code> file as you would declare a normal Python dictionary.</p> <p>However, if you want your information to be modifiable through the normal Django methods, then use the database for persistent storage, and then make...
python|django|dictionary
2
9,443
66,939,886
Python Requests Proxy 'str' object has no attribute 'get'
<p><strong>I am trying to do a request using a Proxy.</strong></p> <p>My Code:</p> <pre><code>import requests proxies = {'http' '1.1.1.1:1234'} r = requests.get('https://httpbin.org/ip', proxies=proxies) print(r.text) </code></pre> <p>The Error:</p> <pre><code> no_proxy = proxies.get('no_proxy') if proxies is not No...
<p>You missed a <code>:</code> in your dictionary:</p> <pre><code>proxies = {'http': '1.1.1.1:1234'} </code></pre> <p>If you have <code>proxies = {'http' '1.1.1.1:1234'}</code>, then <code>proxies</code> is actually a <code>set</code> with the single value of <code>'http1.1.1.1:1234'</code>, hence the error.</p>
python|python-3.x|http|proxy|python-requests
0
9,444
66,986,109
Why is Python loading numpy 1.20.0 in my dask env when conda says 1.20.1 is installed?
<p>Why is Python loading numpy 1.20.0 in my dask env when conda says 1.20.1 is installed?</p> <pre><code>(dask) ➜ dask: conda list -n dask | grep numpy numpy 1.20.1 py38h18fd61f_0 conda-forge (dask) ➜ dask: python Python 3.8.8 | packaged by conda-forge | (default, Feb 20 2021, 16:22:...
<p>This might happen because by default, python packages installed in the so-called user site (<code>pip install --user package</code> or in newer pip versions automatically when the prefix directory is not writable for the current user) are still considered first in the <code>PYTHONPATH</code>.</p> <p>You can deactiva...
python-3.x|numpy|conda
1
9,445
43,011,405
Change bar color based on value
<p>I am currently using plotly to generate some simple graphs in python. The graphs represent the predicted energy consumption of a large area each hour. What i want to do is change the color of each individual bar if the predicted energy consumption of that area is high to red, and if it is low to green. The high- an...
<p>Seemed like a fun task to practice plotly and python on.</p> <p>Here is a plotly plot using some faked up data:</p> <pre><code>import plotly.plotly as py import plotly.graph_objs as go import random import datetime # setup the date series # we need day of week (dow) and if it is a weekday (wday) too sdate = date...
python|bar-chart|plotly
4
9,446
35,230,506
multiple figures in matplotlib
<p>I am actually new here and i just started python for my master thesis project. I try to plot multiple figures but i can't. i have looked many same questions and answers but still, i can't get a result. </p> <pre><code>plt.figure(1) plt.draw() plt.axis([14,55, 3, 5]) plt.xlabel('doy') plt.ylabel('amplitudes of L1 &a...
<p>I strongly suggest using the OO interface as much as possible (instead of the pyplot 'state machine' API). What you want is something like:</p> <pre><code>fig1, ax1 = plt.subplots() fig2, ax2 = plt.subplots() ax1.plot(x, y, 'ro') ax2.plot(x, y, 'go') </code></pre> <p>Running these commands an ipython session (a...
python|matplotlib|plot
0
9,447
35,079,359
Python cryptography fails with "Expected interface of CipherAlgorithm"
<p>I'm trying to use the cryptography python module (<a href="https://cryptography.io" rel="nofollow">cryptography.io</a>) but cannot implement a working example. <a href="https://cryptography.io/en/latest/hazmat/primitives/symmetric-encryption/" rel="nofollow">From example in documentation</a>.</p> <p>This code:</p> ...
<p>You are passing <code>default_backend</code> as the backend argument, but that's actually a function. Call it with <code>default_backend()</code> and it will return a backend object you can pass in.</p> <p>The non-hazmat layer does contain a symmetric encryption recipe (known as <a href="https://cryptography.io/en/...
python|cryptography
2
9,448
26,736,419
How to write Flask decorator with request?
<p>I am not sure why following decorator[validate_request] doesn't work. What is correct way to write such validation decorator?</p> <pre><code>def validate_request(req_type): if req_type is 'json' and not request.json: abort(400) def decorator(func): @functools.wraps(func) def wrapped...
<p>This is how your decorator should look like</p> <pre><code>def validate_request(f): @functools.wraps(f) def decorated_function(*args, **kwargs): # Do something with your request here data = flask.request.get_json() if not data: flask.abort(404) return f(*args, **kwargs) return decorated_...
python|flask|python-decorators
35
9,449
45,025,590
Python transparent weak referencing
<p>Python 3.6</p> <p>How would I go about creating a 'transparent' <code>weakref.ref</code>.</p> <p>So I don't have to use the <code>__call__()</code> method?</p> <p>I can just use <code>y.value</code></p> <pre><code>class integer(): def __init__(self,value): self.value = value x = integer(5) y = weakr...
<p>You would use:</p> <pre><code>class integer(): def __init__(self,value): self.value = value x = integer(5) y = weakref.proxy(x) print(y.value) </code></pre> <p>outputs:</p> <pre><code>5 </code></pre>
python
0
9,450
45,196,233
Python Matplotlib: Create normal colorbar with white interval at specific values
<p>I have Sea Ice Concentration data around Antarctica that range between -40 and +40 (see attached Figure) but I would like for the values between +10 and -10 to appear white in my map and colorbar because they do not represent sea ice concentration (they appear light green and light blue in the current Figure).</p> ...
<p>I assume you have read the <a href="https://stackoverflow.com/questions/41806285/how-to-change-colorbars-color-in-some-particular-value-interval">linked question</a> and it's answer. It clearly states</p> <blockquote> <p>Colormaps are always ranged between 0 and 1.</p> </blockquote> <p>and further explains how ...
python|matplotlib|intervals|colorbar
3
9,451
45,059,510
Spyder in python will not run scripts
<p>I have a very bizzare problem with the spyder editor for python 2.7</p> <p>I cannot run some scripts, some run, some don't.</p> <p>A script of no more than:</p> <p>print "test"</p> <p>Does not work in spyder, but runs in a windows console.</p> <p>while the same script, but written on a different machine and tra...
<p>For me the issue started happening after I encrypted my disk due to company compliance requirements. The test program was working with python in command prompt but not in spyder. I reset the spyder environment using commands:</p> <ol> <li><code>spyder --reset</code></li> <li><code>spyder --defaults</code></li> </ol>...
python-2.7|spyder
2
9,452
64,685,888
Python- using sum in for loop with an error
<p>Why should I write this program like this(first way) :</p> <pre><code>sum = 0 for i in range(1, 10): if (i % 3 == 0) or (i % 5 == 0): sum = sum + i print(sum) </code></pre> <p>Why cant I write like this?(second way) :</p> <pre><code>for i in range(1, 10): if (i % 3 == 0) or (i % 5 == 0): ...
<p>As <a href="https://docs.python.org/3/library/functions.html#sum" rel="nofollow noreferrer">the doc</a> says, the first argument to the builtin function <code>sum()</code> needs to be an iterable.</p> <p>Lists and tuples are examples of iterables. An int is not an iterable.</p> <p>Now, in your first approach, <code>...
python|sum
0
9,453
71,612,207
Problem extracting table from pdf from web page with tabula (Web Scraping in Python)
<p>when I extract a table from a page, I manage to extract without problems, but the data is out of order. There is data from one column that appears as the title of another column for example, how can I fix this? My code:</p> <pre><code>from tabula import read_pdf url='https://becas.osinergmin.gob.pe/seccion/centro_d...
<p>I found the solution: Use tabula program to find coordinates. We just need upload the program: <a href="https://tabula.technology/" rel="nofollow noreferrer">https://tabula.technology/</a> and dowload the JSON file to see the coordinates. We need to put it in &quot;area&quot; argument of read_pdf function in this or...
python|web-scraping|tabulate|tabula-py
0
9,454
69,601,193
Negamax Not Working For Python Chess Engine
<p>I'm making a very simple Python chess engine using the standard Python chess library with a very simple evaluation function; the sum of the total black piece weights (positive) plus the sum of the total white piece weights (negative). The engine always plays as black.</p> <p>I used the Negamax Wikipedia page for gui...
<p>Just based on a first glance, I would say you may be missing a &quot;quiescence search&quot; (meaning a search for quietness). Also called &quot;captures only search&quot;.</p> <p><a href="https://www.chessprogramming.org/Quiescence_Search" rel="nofollow noreferrer">https://www.chessprogramming.org/Quiescence_Search...
python|algorithm|chess|negamax
-2
9,455
55,483,456
How do I match a list of strings to a list of of filenames so I can save those files into one master file?
<p>I have a list of barcodes. I want to read and append files from a folder that match the barcode, but of course the barcodes are not a 1-to-1 match.</p> <p>Example of the Barcode is <code>07002991H3</code> and an Example of the File Name is <code>07002991H3001</code>.</p> <p>I am able to match the barcodes with a ...
<p>You need to give pandas the file path as well as the file name; try </p> <pre class="lang-py prettyprint-override"><code>df = pd.read_csv(os.path.join('//FolderThatContainsFiles', file)) </code></pre>
python|pandas|dataframe|string-matching
0
9,456
55,405,948
Processing each row in column
<ol> <li>I'm trying to go through each row in column 'birth' </li> <li>Check if the last part of the string separated by "," ends in two characters 2.a. If it does, I will append "US" to it.</li> </ol> <p>So, "Los Angeles, Ca" would be "Los Angeles, Ca, US" And "Bisacquino, Sicily, Italy" would stay the same</p> <p>I...
<p>We can use the <code>str</code> methods provided by <code>pandas</code> to solve for this. Let's use the following dataframe that I define below.</p> <pre><code>print(df) place 0 Los Angeles, Ca 1 Bisacquino, Sicily, Italy 2 New York, NY condition = df.place.str.sp...
python|pandas|bigdata
0
9,457
57,621,975
Cant remove file using os.remove
<p>Having some problems with os.remove() at the moment. The file is not open, I have full permissions to edit and remove the file (and can do so outside of python) however access is denied from inside python itself. Is there something wrong with the code or could it be an issue within spyder itself?</p> <p>EDIT: Updat...
<p>Change the permissions first.</p> <pre><code>os.chmod(filePath, 0777) os.remove(filePath) </code></pre>
python-3.x|operating-system|file-management
0
9,458
59,173,175
converting a random string into date in python raises REdefinition of group name 'm'
<p>I have been trying to parse some very old data to structure and store them in a database. I have some random strings that contain dates.</p> <p><code>YEAR:1999 DATE:09/1999</code></p> <p><code>DATE:09/1996</code></p> <p><code>DATE:1993</code></p> <p><code>YEAR:2006 DATE:15/05/06</code></p> <p><code>YEA...
<p>This is a very verbose parser for the format(s) you provided. Output is given as a list of [year, month, day], where each entry is only present if found in the date.</p> <pre><code>import datetime dates = ['YEAR:1999 DATE:09/1999', 'DATE:09/1996', 'DATE:1993 ', 'YEAR:2006 DATE:15...
python|string|datetime|parsing|nlp
1
9,459
54,144,408
Repeatedly execute same code before/after statements/code blocks
<p>I am filtering some data in a <code>pandas.DataFrame</code> and want to track the rows I loose. So basically, I want to</p> <pre><code>df = pandas.read_csv(...) n1 = df.shape[0] df = ... # some logic that might reduce the number of rows print(f'Lost {n1 - df.shape[0]} rows') </code></pre> <p>Now there are multipl...
<p>You could write a "wrapper-function" that wraps the filter you specify:</p> <pre><code>def filter1(arg): return arg+1 def filter2(arg): return arg*2 def wrap_filter(arg, filter_func): print('calculating with argument', arg) result = filter_func(arg) print('result', result) return result w...
python|python-3.x|pandas
0
9,460
53,809,815
TypeError: unsupported operand type(s) for Sub: 'str' and 'int' on line 8
<p>Why do I keep getting this answer? <strong>TypeError: unsupported operand type(s) for Sub: 'str' and 'int' on line 8</strong></p> <pre><code>#Define payment, knowing that up to 40 hours it is normal rate, and above that every hour is paid at 150%. totalHours = input("Enter the total amount of worked hours:\n") hour...
<p>You need to add <code>int</code> convertation.</p> <pre><code>totalHours = int(input("Enter the total amount of worked hours:\n")) hourlyWage = int(input("Enter the payrate per hour:\n")) </code></pre> <p>As from <code>input</code> you get <code>str</code> and not <code>int</code> so you cant do math operations wi...
python|python-3.x
0
9,461
54,059,953
I can't adapt my dataset to VGG-net, getting size mismatch
<p>I’m trying to implement the pre-trained VGG net to my script, in order to recognize faces from my dataset in RGB [256,256], but I’m getting a “size mismatch, m1: [1 x 2622], m2: [4096 x 2]” even if i'm resizing my images it doesn't work, as you can see my code work with resnet and alexnet.</p> <p>I've tryed resizin...
<p>The error comes from this line:</p> <pre><code>model_conv.fc = nn.Linear(4096, 2) </code></pre> <p>Change to:</p> <pre><code>model_conv.fc = nn.Linear(2622, 2) </code></pre>
python-3.x|pytorch|vgg-net|transfer-learning
0
9,462
58,289,062
Prevent pip from caching a package
<p>Is there a way to tell pip never to create a wheel cache of my package?</p> <h1>Background</h1> <p>I wrote a package for in-house use that sets up some symbolic links when installed using <code>cmdclass</code> in the <code>setup.py</code>. These post-install and post-develop triggers run fine if I install the sdi...
<p>There is no <em>clean</em> way of doing this that I know of. You can take your chances and play <em>dirty</em>.</p> <p>Inspired by this <a href="https://discuss.python.org/t/pep-517-and-projects-that-cant-install-via-wheels/791/6" rel="nofollow noreferrer">comment</a>, you could try with a <code>setup.py</code> scr...
python|python-3.x|pip|setuptools
2
9,463
58,455,610
Scraper problems with ASP.NET locating objects - Selenium
<p>Im new into python, and im trying to make a scraper into a ASPX website. I got two types of results in this page, the empty ones and the results, My code can get the empty ones but i cant get the results when they exist, I try all the kinds of paths and still cant get the result,</p> <p>Can someone help me?</p> <p>t...
<p>To looking at the table the data you are trying to get is the second row not the first row.</p> <p>Try this one.</p> <pre><code>results = wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "table[id*='ContentPlaceHolder1_gvwProfissional'] &gt; tbody &gt; tr"))) if "ContentPlaceHolder1_gvwProfission...
python|asp.net|selenium|xpath
0
9,464
45,341,480
How to assess object variables and methods from non-member function pointer
<p>I created an object and assigned non-member function as a pointer to one of its methods. Now is it possible to access the variables and invoke methods of the object from the non-member function?</p> <pre><code> def process_event(): # How to assess a and b variables and invoke # foo method specific to ...
<p>You can bind the <code>process_event</code> to an instance using <code>types.MethodType</code>, but in effect you are dynamically creating a new member function, e.g.:</p> <pre><code>import types def process_event(instance): return instance.foo() class Testing(object): def __init__(self, a, b, process_even...
python|python-2.7|python-3.x
1
9,465
45,335,993
compare string got error ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
<p>I am trying to use <code>if</code> condition to update some values in a column using the following code:</p> <pre><code>if df['COLOR_DESC'] == 'DARK BLUE': df['NEW_COLOR_DESC'] = 'BLUE' </code></pre> <p>But I got the following error:</p> <pre><code>ValueError: The truth value of a Series is ambiguous. Use a.e...
<p>To answer your immediate question, the problem is that the expression <code>df['COLOR_DESC'] == 'DARK BLUE'</code> results in a Series of booleans. The error message is telling you that there is no one unambiguous way to convert that array to a single boolean value as <code>if</code> demands.</p> <p>The solution is...
python|pandas
1
9,466
45,363,935
index error, while executing python
<p>I am a beginner in python, currently executing a piece of code but it throws the following error.I tried my best to solve but could't do it. Please help me. The code is as follows.</p> <pre><code> continue num_snps_skipped += 1 samp_id = sline[id_index] ref_allele = sline[ref_allele_index] tum_al...
<p>More than likely your <code>ref_trinuc</code> string has one or zero characters. That's why <code>if not ref_trinuc[1] == snp[0]:</code> is giving an index error, because it's trying to grab the second character. </p> <p>Before that line try printing ref_trinuc to see what it holds.</p> <p>If it is normal that ref...
python|index-error
0
9,467
28,823,234
Python loading 'utf-16' file can't decode '\u0153'
<p>I have a text file encoded as <code>utf-16</code> which throws an exception for the following character: <code>'\u0153'</code>.</p> <blockquote> <p>UnicodeEncodeError: 'charmap' codec can't encode character '\u0153' in position</p> </blockquote> <p>I'm using a very simple script to load the file, and I also trie...
<p>The exception that originally stumped you is because you're running Python inside a terminal emulator (or possibly "console window" is a more familiar term?) that can't display all of the characters in Unicode. To fix that you need to get yourself a Unicode-capable terminal emulator, and then ensure Python <em>know...
python|character-encoding
10
9,468
14,854,174
Get arguments from commandline, then from file, then from default values
<p>I have a python program that runs depending on some parameters. Let's say, one of the parameters is <code>C</code> with a default value of <code>3</code>. So when I run it without any arguments, it does</p> <pre><code>$ python parsing.py C=3 </code></pre> <p>When I load a file for my initial data, it can get some ...
<p>Assuming you use the <a href="http://docs.python.org/2/library/argparse.html" rel="noreferrer"><code>argparse</code> module</a>, simply don't set a default argument when you add the argument. Then the attribute will be <code>None</code> if the argument was not present, and you can check for that instead of parsing a...
python|argparse
5
9,469
14,736,766
Why does gevent.socket break multiprocessing.connection's auth
<p>I have an application that uses both <code>grequests</code> and <code>multiprocessing.managers</code> for a combination of IPC communication and Asynchronous RESTful communications over HTTP.</p> <p>It seems that <code>grequests</code>, in using <code>gevent.monkey</code>'s <code>patch_all()</code> method, breaks t...
<p>If you don't patch the socket module, <code>gevent</code>'s ability to not block on network operations won't be available, and thus most of the benefit of using <code>gevent</code> in the first place won't be available.</p> <p><code>gevent</code> and <code>multiprocessing</code> aren't really designed to play nicel...
python|connection|multiprocessing|gevent|monkey
6
9,470
68,595,424
Doing Contrast Enhancement Using A Map
<p>So I've had a go at different way of manipulating the current image. I have the following image and subsequent mask for the image:</p> <p><a href="https://i.stack.imgur.com/15rRW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/15rRW.png" alt="enter image description here" /></a></p> <p><a href="ht...
<p>Here is the hard light composition in Python/OpenCV using an intensity modified saliency map. You can adjust the arguments in the rescale_intensity to adjust as desired.</p> <p>Image:</p> <p><a href="https://i.stack.imgur.com/VMLR3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VMLR3.png" alt="en...
python|opencv|image-processing|contrast|image-enhancement
1
9,471
56,999,614
Remove the background noise for OCR with opencv
<p>I'm trying to do OCR with tesseract, to get a better result, I'd like to remove the background noise before sending it to tessseract.</p> <p>I already knew the text has the fixed color and use cv2.inrange to remove the noise background, but the problem is the background noise has the similar color to the text color...
<p>Starting with your first result you could remove noise that is:</p> <ul> <li><p>too large or too small to be letters</p></li> <li><p>not vertically centered with the rest of the text</p></li> </ul> <pre><code>import cv2 as cv import numpy as np im = cv.imread('ocr.png') imgray = cv.cvtColor(im, cv.COLOR_BGR2GRAY)...
python|opencv
4
9,472
57,223,014
calculate relative performance in python on daily stock price data
<p>DataFrame 'MasterFile' includes</p> <pre><code>##Index, Date, CompanyA, CompanyB, Company C ##0, 2019-07-26, 100, 25, 38 ##1, 2019-07-25, 99, 24, 37 </code></pre> <p>I have 6 records (-5 workdays in the excel) and the Company A, B and C datapoints represent daily closing stock prices</p> <p>My goal is to create a...
<p>I use example with dates as strings so it may need changes</p> <pre><code>df = pd.DataFrame([ ['2019-07-26', 100, 25, 38], ['2019-07-25', 99, 24, 37], ['2019-07-24', 100, 50, 50], ['2019-07-19', 5, 2, 2], ], columns=['Date', 'Company A', 'Company B', 'Company C']) print(df) </code></pre> <hr>...
python
0
9,473
61,908,916
Where does flask store token for password recovery?
<p>I need to provide password recovery token in order to test it's functionality with integration test. But I can't trace the place its stored.</p>
<p>Apparently it doesn't. <a href="https://github.com/mattupstate/flask-security/blob/3e15d06ee82a728d5cc53059fb28406c7bc6e7aa/flask_security/recoverable.py#L55" rel="nofollow noreferrer">It hashes the user's current password [hash] and their id</a> and sends that as token. Which is entirely reasonable, since that's al...
python|flask|flask-security
2
9,474
61,948,171
what is the most efficient way of getting digit sum?
<p>I have to find the digit sum until its in single digit. if input is -9999 then output should be -9<br> <code>(-(9+9+9+9))==-9)</code></p> <p>if input is 9012 then output should be 3 <code>(+(9+0+1+2)==1+2==3))</code></p> <p>ps: i have solved this but the negative inputs are giving wrong output.I am using the divi...
<p>just a simple recursion should help, add this to your code</p> <pre class="lang-py prettyprint-override"><code>if n &lt; 0: return - digSum(abs(n)) </code></pre>
python|math
3
9,475
23,580,176
Missing module when compiling python to exe
<p>I am getting an error when compiling python to exe. the error is showing a missing module but when I install, the pip cannot find it. How can I install those modules?</p> <blockquote> <p>The following modules appear to be missing: ['_scproxy', 'email.Encoders', 'email.MIMEBase', 'win32evtlog', 'win32evtlogutil'...
<p>modified from the example at the bottom here : <a href="http://www.py2exe.org/index.cgi/ListOfOptions" rel="nofollow">http://www.py2exe.org/index.cgi/ListOfOptions</a></p> <pre><code>from distutils.core import setup from py2exe.build_exe import py2exe setup( windows=['yourscript.py'], options={ ...
python
0
9,476
24,235,276
Beautifulsoup css data extraction
<p>I am attempting to extract css data from an html document. the data points are a variable number of circle x-y coordinates generated by the user onto an image and exported into the html as follows:</p> <pre><code>#shapes a#rage_circle1{ top: 248px; left: 231px; width: 18px; height: 18px; border:...
<p>I think <a href="https://pythonhosted.org/cssutils/" rel="nofollow">cssutils</a> is the right choice for your problem. The following snippet will simply output the values of all <code>top</code> and <code>left</code> attributes.</p> <pre><code>import cssutils css = cssutils.parseFile('index.html') for rule in css.c...
python|css|beautifulsoup
1
9,477
24,417,090
prudentia path weirdness: Can't find box using path relative to the current directory
<p>Prudentia cannot find the box I defined. I am quite sure that the box is there. And when I use an absolute path it complains about the <code>$prudentia_dir</code> in Ansible.</p> <p>Here's my directory tree:</p> <pre><code>deployment/ |-- Readme.md |-- boxes | |-- common_vars.yml | |-- dev.yml | |-- dev_vars...
<p>Take a look inside your <code>staging.yml</code>. Paths there should be specified in this format:</p> <p><code>"{{prudentia_dir}}/tasks/common-setup.yml"</code></p> <p>rather than:</p> <p><code>$prudentia_dir/tasks/common-setup.yml</code></p> <p>Probably you're using box file from previous versions with newer pr...
python|ansible|prudentia
2
9,478
36,016,942
Getting values OF a set in Python
<p>I have 6 arrays, let's say <code>a,b,c1,d1,c2,d2</code>. </p> <p>Arrays <code>a and b</code> have some common pairs of <code>c1,c2</code> and <code>d1,d2</code>. I find these common pairs, <strong>i.e. those <code>a and b</code> which have the same <code>c1,d1</code> and <code>c2,d2</code> like this:</strong></p> ...
<p>Still not 100% what you are asking. As I understand the question, you want the elements of <code>a</code> and <code>b</code> at those positions where the elements of <code>c1</code> and <code>d1</code> are the same as those of <code>c2</code> and <code>d2</code> respectively.</p> <p>In this case, using <code>set</c...
python|python-2.7|set|counter|multiple-conditions
1
9,479
21,303,339
Why is the output "cbe" rather than "bce" in this python program?
<pre><code>getDifference=lambda string1, string2: reduce((lambda character1, character2: character1+character2), (set(string1)-set(string2))) print getDifference('abcde','adf') </code></pre> <p>In the first line, I defined a lambda expression that finds the difference between string1 and string2. I assume the output...
<p>A set is an unordered collection of unique elements - so the order of the characters is not kept through the sets operation. Check here for more:</p> <p><a href="http://docs.python.org/2/tutorial/datastructures.html#sets" rel="nofollow">http://docs.python.org/2/tutorial/datastructures.html#sets</a></p>
python
4
9,480
62,742,380
how to extract year in date field of date of birth and calculate age of person in django views.py?
<p>I am trying to do this in views.py</p> <pre><code>ExtractYear(date_of_birth) - today.year </code></pre> <p>But it gives error to use int, and i tried like:</p> <pre><code>int (ExtractYear(date_of_birth) )- int(today.year) </code></pre> <p>and it gives error of int() argument must be a string, a bytes-like object or ...
<p>The age of a person does not only depends on the year. For example, if a person is born on the first of February, then the first of January, he/she is one year younger than the first of March.</p> <p>You can annotate your person with:</p> <pre><code>from django.db.models.functions import ExtractYear MyModel.objects...
python|django|django-models|django-views|django-templates
1
9,481
62,754,767
TF.Keras SparseCategoricalCrossEntropy return nan on GPU
<p>Tried to train UNet on GPU to create binary classified image. Got nan loss on each epoch. Testing of loss function always produces nan-return.</p> <p>Test case:</p> <pre><code>import tensorflow as tf import tensorflow.keras.losses as ls true = [0.0, 1.0] pred = [[0.1,0.9],[0.0,1.0]] tt = tf.convert_to_tensor(true)...
<p>I had the same issue. My loss was a real number if I trained on CPU. I tried upgrading the TF version, but it didn't fix the problem. I finally fixed my issue by reducing the y dimension. My model output was a 2D array. When I reduced it to 1D, I managed to get a real loss on GPU.</p>
python|tensorflow|keras
2
9,482
45,752,866
Geopy location error (in python)
<p>I have a list of coordinates, for which I use geopy geolocator's function to get the related country. But at certain lines I get the following error:</p> <p>KeyError: 'country'</p> <p>My programline is this:</p> <pre><code>cim = location.raw['address']['country'] </code></pre> <p>It returns the country related t...
<p>It's basically saying that there's no <code>'country'</code> key for whichever address you're providing.</p> <p>Are the coordinates always in countries, or can they be in the sea/ocean? Can the coordinates be on the border of two (or more) countries?</p> <p>If 'yes' to any of these questions, check how <code>geopy...
python|location|geopy
0
9,483
45,876,059
Python websocket create connection
<p>I have this server</p> <p><a href="https://github.com/crossbario/autobahn-python/blob/master/examples/twisted/websocket/echo_tls/server.py" rel="nofollow noreferrer">https://github.com/crossbario/autobahn-python/blob/master/examples/twisted/websocket/echo_tls/server.py</a></p> <p>And I want to connect to the serve...
<p>This works</p> <pre><code>import asyncio import websockets import ssl async def hello(): async with websockets.connect('wss://127.0.0.1:9000',ssl=ssl.SSLContext(protocol=ssl.PROTOCOL_TLS)) as websocket: data = 'hi' await websocket.send(data) print("&gt; {}".format(data)) respon...
python|ssl|websocket|autobahn
6
9,484
33,399,561
Writing to different columns in CSV
<p>I know this question has been asked a few times but I have tried everything and nothing seems to work I think I just need a 2nd set of eyes to tell me what I am doing wrong. </p> <p>I am currently able to write to my CSV file like this</p> <pre><code>Row 1: Date Row 2: User_Name Row 3: Text etc.. </code></pre> <p...
<p>You need to either call <a href="https://docs.python.org/2/library/csv.html#csv.csvwriter.writerow" rel="nofollow"><code>.writerow()</code></a> inside the loop:</p> <pre><code>for item in r: screen_name = item['user']['screen_name'].encode('utf-8') created_at = item['created_at'].encode('utf-8') tweet =...
python|csv
2
9,485
33,127,950
Class constructor able to init with an instance of the same class object
<p>Can python create a class that can be initialised with an instance of the same class object?</p> <p>I've tried this:</p> <pre><code>class Class(): def __init__(self,**kwargs): print self self = kwargs.get('obj',self) print self if not hasattr(self,'attr1'): pri...
<p>Not sure what you're trying to achieve, but technically your error is here:</p> <pre><code> self = kwargs.get('object',self) </code></pre> <p>There's nothing magic with <code>self</code>, it's just a function argument, and as such a local variable, so rebinding it within the function will only make the local n...
python|class|init|self
1
9,486
73,791,808
For loops through pandas dataframes for state and country
<p>I am trying to get the state location from zip codes when they are in the US. The code below is what I am using importing a csv with zip codes and country. I am getting repeating state for the first zip code in the dataframe. I tried .append on the state, country but am still just getting the return of the first row...
<pre><code>df['state']=state df['country']=country </code></pre> <p>overwrite the whole column.</p> <p>You can use .apply() instead. Put your code in a function and you can do something like that:</p> <pre><code>def zip_to_state_country(zip_code): # your logic here return zip_code[0], zip_code[1] # returns jus...
python|pandas|dataframe|geopy
0
9,487
12,839,106
scp between 2 remote hosts - without password
<p>I use paramiko module and I can simply put and get files to and from remote host. Is there the way I can copy the file between 2 remote hosts? I have pem file on my local host so I can establish ssh to both hosts. Is there the way I can do it without (if possible) additional configuration on remote hosts - using SS...
<p>Hey Francheska,</p> <p> The following python pseudo code may help you... Replace dest_server, source_file, dest_file with your appropriate... It is tested and working one...</p> <pre><code>import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('dest_server...
python|ssh|paramiko
3
9,488
21,495,032
Error in sepia effect opencv python
<p>I'm trying to create a filter which will create a sepia look for all pictures. But I get some spots in my filtered image which are blue and cyan. I think it might be overflow but I tried to account for that and it didnt give me the affect I was looking for. I'm not sure whats wrong. The link to original is at <a hre...
<p>In my opinion problem is with types. Python thinks that after operation you want to integer. Each channel has 8 bits. After calculation when you will get value 256 (100000001) python will read only first 8 bits (00000001). Because of that you have a little bit strange image. In my case works this code:</p> <pre><co...
python|opencv
2
9,489
38,416,671
Python Injection - is there such a thing?
<p>I've been doing some penetration testing on my own site and have been doing a lot of research on common vulnerabilities.</p> <p>SQL injection comes up a lot but I was wondering, could there possibly be such a thing as python injection? Say for example that a web form submitted a value that was entered in a dictiona...
<p>This depends entirely on what you <em>do</em> with the input from the webform. In normal use the form gets encoded as <code>x-www-form-urlencoded</code> or <code>json</code> -- Both formats which <em>can</em> be deserialized into a python dictionary completely safely. Of course, they <em>could</em> be deserialized...
python|code-injection
1
9,490
31,025,392
Crontab, python script fails to run
<p>I have a bash script to automate few things I do. The bash calls 2 python scripts, If I run the bash script normally, everything runs, no errors what so ever. I set up a cron job to Automate this and when I checked the logs I noticed the python scripts don't run at all. It gives me the following error.</p> <p><code...
<p>The working directory of the cron is different from the directory you run the script directly.</p> <ul> <li><p>Make your bash script to use absolute path for python script files.</p></li> <li><p>Or make the bash script to change directory to where you run the script directly.</p></li> </ul>
python|bash|unix|crontab
4
9,491
30,827,790
Connecting Python Backend to Android APP
<p>How to use python as a backend for an Android App that is built using C#? The Python Backend is written using the Flask framework. The Android app is built using xamarin.</p>
<p>No matter what type of technology your server or the client use if they can communicate with each other using some sort of standard "protocol".</p> <p>There are many ways to communicate both sides (client and server) like sockets, xml, json, etc. They just need to understand each other.</p> <p>In your particular c...
python|xamarin
2
9,492
39,997,410
need only link as an output
<p>I have multiple html tag I want to extract only content of 1st href="..." for example this single line of data.</p> <pre><code>&lt;a class="product-link" data-styleid="1424359" href="/tops/biba/biba-beige--pink-women-floral-print-top/1424359/buy?src=search"&gt;&lt;img _src="http://assets.myntassets.com/h_240,q_95,w...
<p>If you need a single "product link", just use <code>find()</code>:</p> <pre><code>soup2.find('a', attrs={'class': 'product-link'})["href"] </code></pre> <p>Note that you can use a <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors" rel="nofollow">CSS selector</a> location technique as we...
python|python-2.7|beautifulsoup|data-cleaning
0
9,493
28,917,832
How to execute Python script from Java code in Android
<p>I'm trying to make an standard Android application execute a python script that could return values to Java, but I'm facing a lot of issues.</p> <p>Jython doesnt support this in the Android environment, SL4A is a dead project, Kivi seems to be an full stack framework that do not use Java at all and QPython is SL4A ...
<p>I don't think any of thoses projects will help. For example, Kivy drive the Python execution, even it it's started from Java.</p> <p>If you have an application in Java, but want to start a Python Interpreter, i guess solution using <a href="https://code.google.com/p/android-python27/" rel="nofollow">https://code.go...
android|jython|kivy|sl4a|qpython
1
9,494
8,409,194
Unable to deserialize PyMongo ObjectId from JSON
<p>I'm seemingly unable to deserialize my MongoDB JSON document with the BSON <a href="http://api.mongodb.org/python/current/api/bson/json_util.html" rel="noreferrer">json_util</a>. </p> <p>The json.loads function is choking on the <code>ObjectId()</code> string. I had understood json_util capable of handling MongoDB'...
<p>I think your string form actually looks like the python representation...</p> <pre><code>s = '{"_id": {"$oid": "4edebd262ae5e93b41000000"}}' u = json.loads(s, object_hook=json_util.object_hook) print u # Result: {u'_id': ObjectId('4edebd262ae5e93b41000000')} s = json.dumps(u, default=json_util.default) print s...
python|json|mongodb|pymongo|bson
20
9,495
58,664,914
How do I split multiple columns?
<p>I would like to split each of columns in dataset.</p> <p>The idea is to split the number between "/" and string between "/" and "@" and put this values to the new colums.</p> <p>I tried sth like this :</p> <pre><code>new_df = dane['1: Brandenburg'].str.split('/',1) </code></pre> <p>and then creating new columns...
<p>As I understood, you want to extract <strong>two parts</strong> from each cell. E.g. from <em>ES-NL-10096/1938/X1@hkzydzon.dk/6749</em> there should be extracted:</p> <ul> <li><em>1938</em> - the number between slashes,</li> <li><em>X1</em> - the string between the second slash and <em>@</em>.</li> </ul> <p>To to ...
python|pandas|split
1
9,496
58,801,456
how to get class details recursively in selenium python
<p>I have got a python script based on selenium to do some automation and getting stock market data.</p> <p><a href="https://i.stack.imgur.com/e9u2R.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e9u2R.jpg" alt="enter image description here"></a></p> <p>I can individually access elements, but I wa...
<p>You can locate the dates and use them to locate the corresponding numbers</p> <pre><code>all_dates = driver.find_elements_by_xpath('//td[@class="date"]') for date in all_dates: numbers = date.find_elements_by_xpath('.//following-sibling::td[@class="number"]') print(date.text) for number in numbers: ...
python|selenium|selenium-webdriver
2
9,497
58,717,095
How to send data between two clients
<p>I am making a simple game with multiplayer mode in it. I need to somehow send data between one player and other. I can't find a way to transfer data between two clients. Is there a way to forward them through the server?</p> <p>I'm using the <code>socketserver</code> library to accept connections. Here is the way I...
<p>From the 90s playbook: one of the clients can be a server; other clients (on the same LAN) connect to it. </p> <p>It won't work well outside a LAN, because of NAT.</p> <p>Normally you would need to run a dedicated server somewhere that would let users connect, and would route messages between them.</p> <p>Natural...
python|python-3.x|sockets|networking|socketserver
1
9,498
52,132,072
Invaild Syntax Python Inside print 2.7.11
<p>Ok so is inside the print function is an error. And I can't seem to get rid of is here is my code: </p> <pre><code>def chaselect(): print ''' Now you must choose your race ''' while player.race == None: ace = raw_input(''' 1. Human 2. Elf 3. Dwarf 4. Orc ''')) if ace == '1': p...
<p>Try this:</p> <pre><code>def chaselect(): print 'Now you must choose your race ' while player.race == None: ace = raw_input('1. Human \n2. Elf \n3. Dwarf \n4. Orc\n') if ace == '1': print 'You chose human are you sure?' con = raw_input('\n1. Confirm Race\n2. Read Lo...
python|python-2.7|error-handling|syntax
0
9,499
51,613,359
How to iterate through cursor after mysql select * query in python?
<p>I am querying all the fields of a mysql table like this - </p> <pre><code>query = """select * from %s where %s=%s;""" % (tableName,key,value) cursor.execute(query) </code></pre> <p>Now, I would like to iterate over the results. I do not want to specify the column names which I would like to fetch as I would like t...
<p>MySQLdb conforms to <a href="https://www.python.org/dev/peps/pep-0249/" rel="nofollow noreferrer">PEP-249</a>.</p> <p>Therefore,<code>execute</code> must return an iterator. You can just do:</p> <pre><code>for tupl in cursor.execute(query): pass </code></pre> <p>where <code>tupl</code> is a tuple.</p> <hr> ...
python|mysql
2