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
500
72,985,072
Memory Error when applying spacy model to large log file
<p>I am currently working on tokenizing a large log file that contains 39296844 characters. I am using the <code>nlp = spacy.load('en_core_web_sm')</code> model for this text file. Additionally I established the <code>nlp.max_length = 100000000000</code> so that I can read very large files. However, when I run the code...
<p>I don't see the point of processing ~40m characters as a single string. Do lines separated by <code>\n</code> form logical units? In this case read the string line by line and process each line using <code>pipe()</code>.</p> <pre><code>text = df.iloc[161][1] lines = text.split('\n') processed_lines = nlp.pipe(lines,...
python|nlp|spacy
1
501
55,791,341
Persistent storage of data?
<p>My use case needs to store the data on a disk immediately when the data is available. I'm using Raspberry PI and few lasers. Once the laser is activated/deactivated timestamp is taken and it should be stored on the disk. Data is only stored when lasers are "armed". They can also be in "idle" state (they're still wor...
<p>Sounds like python?</p> <p>If so, you can write to your file using <code>with</code>:</p> <blockquote> <p><code>with open('/path', 'w') as f: f.write('stuff')</code></p> </blockquote> <p>and the file descriptor will close automatically when execution exits the block.</p> <p>However, regarding your other ...
python-2.7|persistence
0
502
73,468,846
Django: typehinting backward / related_name / ForeignKey relationships
<p>Let's say we have the following models:</p> <pre><code>class Site(models.Model): # This is djangos build-in Site Model pass class Organization(models.Model): site = models.OneToOneField(Site) </code></pre> <p>And if I use this somewhere in some other class:</p> <pre><code>organization = self.site.organi...
<p>Django adds backwards relations at runtime which aren't caught by <code>mypy</code> which only does static analysis.</p> <p>To make <code>mypy</code> happy (and to make it work with your editor's autocomplete) you need to add an explicit type hint to <code>Site</code>:</p> <pre class="lang-py prettyprint-override"><...
python|django|type-hinting|django-stubs
1
503
49,833,144
Efficient way of replacing values from a data set with values from another one
<p>I have this code:</p> <pre><code>for index, row in df.iterrows(): for index1, row1 in df1.iterrows(): if df['budget'].iloc[index] == 0: if df['production_companies'].iloc[index] == df1['production_companies'].iloc[index1] and df['release_date'].iloc[index].year == df1['release_year'].iloc[...
<p>Get rid of all of the loops, you can accomplish this efficiently with a merge. Here I provided some example data, since none of the data you provided will actually merge. You want to make sure <code>release_date</code> in <code>df</code> is a datetime, if it isn't already. </p> <pre><code>import pandas as pd import...
python|performance|pandas|numpy|dataframe
1
504
53,287,108
pass wx.grid to wx.frame WX.python
<p>All im trying to do is have 2 classes </p> <p>1- creates a grid</p> <p>2- takes the grid and puts it into a wx.notebook </p> <p>so basically one class makes the grid the other class takes the grid as parameter and add it to the wx.notebook</p> <p>but I keep getting an error that says</p> <pre><code> self.m_g...
<p><code>wx.grid.Grid(self)</code> here <code>self</code> must be a wx.Window (or subclass) type. In your code it's <code>reportGrid</code> type.</p> <p>But <code>reportGrid</code> is not a wx.Window nor a subclass of wx.Window.</p> <p>If you have a page "pagegrid" (for example, of type wx.Panel or subclass) of the w...
python|python-3.x|wxwidgets|wxpython
1
505
65,361,807
select the rows of a table according to an id that is in a JSON in a column of the table
<p>I need to select the rows of a table according to the id In a JSON In one of the columns using Pandas.</p> <p>example :</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">column_a</th> <th style="text-align: center;">column_b</th> <th style="text-align: left;">co...
<p>If you have already loaded this into pandas it is probably now a dictionary which can be accessed by key similar to the dataframe so you are looking to filter like this:</p> <pre><code>df[df['column_c']['id'] == 'cc'] </code></pre>
python|json|pandas|dataframe
0
506
71,780,524
How to change decimal separator from dot to coma in Pandas when column have NaN values?
<p>When I try to open my ready files in Excel, it changes my decimals number to data. I try to change dot to coma in decimals numbers, and it work. I used this code to change it:</p> <pre class="lang-py prettyprint-override"><code>def convert_df(df): return df.to_csv(sep=';',decimal=',').encode('utf-8') </code></pr...
<p>Here is one way to do it:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame( { &quot;col1&quot;: [1.1, 1.2, 1.3], &quot;col2&quot;: [1.1, pd.NA, 1.3], } ) print(df) # Toy dataframe col1 col2 0 1.1 1.1 1 1.2 &lt;NA&gt; 2 1.3 1.3 </code>...
python|pandas
1
507
62,687,732
Linking two files by ID, and then removing data values from one file by referencing the other in Python using DataFrames
<p>I don't think this problem is that complex, I'm just dumb and I'm not sure how to word my search.</p> <p>I have two files, and they are linked by a common ID. One file (FileA), there is an upper year and a lower year listed out in each row. In the other file (FileB), there is a range of years. I don't need the years...
<p>I added some 2341 references in your file_b example to show that they would be filtered out:</p> <pre><code>import pandas as pd file_a = pd.DataFrame( data=[[2341, 2005, 1995], [2341, 2013, 2010]], columns=[&quot;id&quot;, &quot;uyear&quot;, &quot;year&quot;] ) file_b = pd.DataFrame( data=[[4321, 199...
python-3.x|pandas
0
508
62,021,220
is there a way to make python type in google without getting into anything?
<p>so im trying to make a code that you copy what you want then you press the hotkey and i want python to open google and type there "what is the meaning of (what ever word you want) in Hebrew" and then close python after the code is complete is there a way to do that? this is the code:</p> <pre><code>from pynput.keyb...
<p>If you simply need to open the browser and execute a search you can use this. </p> <pre class="lang-py prettyprint-override"><code>import webbrowser def search_google(subject): webbrowser.open("https://www.google.com/search?q=What is the meaning of " + subject + " in H...
python
1
509
60,672,863
Biopython PDBIO assembly chain IDs
<p>I am using Bio.PDB to parse structures in mmCIF and PDB format. I realised that PDBIO does not deal well with two-character chain identifiers (like ‘AA’ or ‘AB’) found in <strong>assembly</strong> structures. I have made a slight change to the code that fits me. Attached you will find the modified PDBIO module. What...
<p>Stackoverflow is a site to ask questions. What you are proposing is a change to BioPython software. Luckily, BioPython is open-source, so you create a <a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-requests" rel="nofollow noreferrer">pull request</a> so that your ch...
biopython|pdb
0
510
60,608,693
Django, get value of the ChoiceField form
<p>I have a form which contain a choicefield of items on my database. My question is How can I get the selected value of my choicheField?</p> <p>forms.py</p> <pre><code>class list_data(forms.Form): message = forms.CharField(widget=forms.Textarea) def __init__(self, author, *args, **kwargs): super(li...
<p>In case of a POST request, you pass <code>request.POST</code> as first parameter, and thus as <code>author</code>, and not as data. You can rewrite the view to:</p> <pre><code>def sms(request): if request.method == 'POST': form2 = <b>list_data(request.user, data=request.POST)</b> if form2.is_val...
python|django|forms
2
511
60,779,818
Set conditional constraint, Pulp
<p>First time using pulp and I am trying to set a conditional constraint on a production problem I am working on. Unfortunately I cannot find any examples in the documentation as to how to do so either. </p> <p>The objective function is to maximise revenue by informing monthly plant production on which product to pro...
<p>Introduce a set of binary variables which are indexed by {plant, product, month}, which determine whether plant <code>i</code> is being used to make product <code>j</code> during month <code>k</code>. Variable will be <code>1</code> when this is true, and <code>0</code> otherwise.</p> <p>You'll then need to add con...
python|linear-programming|pulp
0
512
66,042,721
pandas grouping and visualization
<p>I have to do some analysis using Python3 and pandas with a dataset which is shown as a toy example-</p> <pre><code>data ''' location importance agent count 0 London Low chatbot 2 1 NYC Medium chatbot 1 2 London High human 3 3 London Low human ...
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot_table.html" rel="nofollow noreferrer"><code>DataFrame.pivot_table</code></a>, added <code>aggfunc=sum</code> for aggregate if duplicates and then use <a href="http://pandas.pydata.org/pandas-docs/stable/referen...
python|pandas
2
513
72,510,330
How to get first element of a list inside dictionary and add to Pandas Dataframe column in Python?
<p>I have a dictionary like this:</p> <pre><code>dict = {&quot;key 1&quot;: [&quot;val 1&quot;, &quot;val 2&quot;], &quot;key 2&quot;: [&quot;val 3&quot;, &quot;val 4&quot;, &quot;val 5&quot;], &quot;key 3&quot;: [&quot;val 6&quot;, &quot;val 7&quot;], ... } </code></pre> <p>I also have a panda...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>dct = { &quot;key 1&quot;: [&quot;val 1&quot;, &quot;val 2&quot;], &quot;key 2&quot;: [&quot;val 3&quot;, &quot;val 4&quot;, &quot;val 5&quot;], &quot;key 3&quot;: [&quot;val 6&quot;, &quot;val 7&quot;], } df[&quot;first_key&quot;] = df[&quot;key&...
python|pandas|list|dataframe|dictionary
2
514
63,192,438
Unbound local error does not occur consistently
<p>I am trying to add data to my SQlite3 table which runs on a function that takes two arguments to find a city and a neighbourhood <code>def scrapecafes(city, area)</code> Strangely, this works well with some of the arguments I am entering but not with others. For example if I run <code>scrapecafes(melbourne, thornbur...
<p>The problem is <code>geopy</code> doesn't have co-ordinates for <code>Carlton</code>. Hence, you should change your table schema and insert <code>null</code> in those cases.</p> <p>When <code>geopy</code> doesn't have data, it returns <code>None</code> and when try to call something on <code>None</code> it throws ex...
python|sqlite|beautifulsoup|geopy
1
515
67,814,858
Canno't create a PySimpleGui table with my data
<p><strong>My table does not accept data in format, that I put in var <strong>dataT</strong></strong></p> <pre class="lang-py prettyprint-override"><code>import PySimpleGUI as sg dataT = [[''], [''], [''], [''], [''], [''], [''], [''], ['']] def edit(): sg.theme('Light Green 1') headings = ['CPF', 'NAME', '...
<p>There are 9 columns for headings,</p> <pre class="lang-py prettyprint-override"><code>headings = ['CPF', 'NAME', 'ENDEREÇO', 'CITY', 'STATE', 'GENDER', 'EMAIL', 'BIRTH', 'FAQ'] </code></pre> <p>Here table data means 9 rows and each one only with one row.</p> <pre class="lang-py prettyprint-override"><code>dataT = [[...
python|pysimplegui
0
516
67,845,221
Webscraping with beautiful soup 4, class not working
<p>I'm trying to webscrape, as a personal excersie, the players data from this page: <a href="https://sofifa.com/players" rel="nofollow noreferrer">https://sofifa.com/players</a> So I want to grab the players ID which is in this kind of line of HTML:</p> <pre><code>&lt;td class = &quot;col col-pi&quot; data-col=&quot;p...
<p>I went to the site and inspected the source. I copied your code and grabbed all the <code>td</code> elements but I did not find any with <code>class=&quot;col col-pi&quot;</code>.</p> <pre class="lang-py prettyprint-override"><code>soup = soup_making(url) tags = soup.find_all('td') all_td_classes = set() for tag in ...
python|html|web-scraping|beautifulsoup|css-selectors
0
517
67,019,451
Is it possible to choose at runtime to import uic compiled files or dynamically load the ui with QUiLoader()?
<p>As stated in the <a href="https://doc.qt.io/qtforpython/tutorials/basictutorial/uifiles.html" rel="nofollow noreferrer">official documentation</a> there are 2 ways of importing <code>.ui</code> files in your code:</p> <ul> <li><a href="https://doc.qt.io/qtforpython/tutorials/basictutorial/uifiles.html#option-a-gener...
<p>In the case of Qt for Python the option is to use <a href="https://doc.qt.io/qtforpython/PySide6/QtUiTools/loadUiType.html" rel="nofollow noreferrer"><code>loadUiType</code></a>:</p> <pre class="lang-py prettyprint-override"><code>ui_class, qt_class = loadUiType(&quot;filename.ui&quot;) class FooWidget(QFooWidget):...
python|qt|pyside2
2
518
42,936,464
How to read into a pandas dataframe the wollowing json?
<p>I have the following json:</p> <pre><code>[ [ { "A": "2017-02-02T11:57:41+0000", "B": "agent", "C": "hi how are you son." }, { "A": "2017-02-01T22:19:58+0000", "B": "user2", "C": "M contestan" }, { ...
<pre><code>In [17]: import json </code></pre> <p>Assuming you have the following JSON string:</p> <pre><code>In [18]: s Out[18]: '[[{"A": "2017-02-02T11:57:41+0000", "B": "agent", "C": "Hola Alex, si no has realizado la modificacin de los datos afiliados, por favor confrmanos tu DNI, celular y operador para revisarlo...
python|json|python-3.x|pandas
1
519
69,513,415
Python Selenium: extraction of rating given by individual reviewer
<p>I am trying to extract google reviews of a resturant using Python Selenium. I tried to extract the reviews posted by each reviewers. Here is my code:</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriv...
<p>You are using a wrong XPath locator.<br /> Instead of</p> <pre class="lang-py prettyprint-override"><code>rating = person.find_element_by_xpath(&quot;./span&quot;).get_attribute('aria-label') </code></pre> <p>Try using</p> <pre class="lang-py prettyprint-override"><code>rating = person.find_element_by_xpath(&quot;./...
python|python-3.x|selenium|selenium-webdriver|xpath
1
520
69,373,046
How do I extract a specific column from a dataset using pandas that's imported from a HTML file?
<pre><code>import requests import os import pandas as pd from bs4 import BeautifulSoup #Importing html df = pd.read_html(os.path.expanduser(&quot;~/Documents/HTMLSpider/HTMLSpider_test/spotgamma.html&quot;)) print (df['Latest Data']) </code></pre> <p>All of the documentation I can find online states that extracting a ...
<p>Note that</p> <pre><code>df = pd.read_html(os.path.expanduser(&quot;~/Documents/HTMLSpider/HTMLSpider_test/spotgamma.html&quot;)) </code></pre> <p>will return a <strong>list of</strong> dataframes, not a single one.</p> <p>See: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_html.html...
python|pandas|beautifulsoup
3
521
42,170,046
Python serial port returing null string
<p>Reading data from the serial port: readline() in the below code return the null vector, the reading data from the serial port is hexadecimal number like AABB00EF the putty gives me the output means the communication is working but nothing works via python here is the code:</p> <pre><code>#!/usr/bin/python import s...
<p>readline will try to read until the end of the line is reached, if there is no <code>\r</code> or <code>\n</code> then it will wait forever (if you have a timeout it might work...) instead try something like this</p> <pre><code>ser.setTimeout(1) result = ser.read(1000) # read 1000 characters or until our timeout oc...
python|pyserial
0
522
54,154,770
When does it make sense to use a public package as a Submodule in Python vs installing using pip?
<p>I am working on a python project that has many open sourced dependencies that may not be regularly maintained. I tried using packages as submodules by adding them with Git; but then I get an error saying the module I want is not available when I try to use the submodule; when I install the package with pip it works ...
<p><code>git</code> is a development tool; you use it during development but not deployment. <code>pip</code> is a deployment tool; during development you use it to install necessary libraries; during deployment your users use it to install your package with dependencies.</p> <p>Use submodules when you need something ...
python|git
7
523
23,656,404
Error on downloading scrapy image
<p>i have a <code>scrapy spider</code> to fetch images and content from some ecommerce sites. Now i want to download images, i write a few codes but i got this error :</p> <pre><code>.. File "/usr/lib/python2.7/pprint.py", line 238, in format return _safe_repr(object, context, maxlevels, level) ...
<p>Try change recursion limit for <code>sys.setrecursionlimit(10000)</code> in spyder. My python interpreter gave 900 recursions before "RuntimeError"</p>
python|scrapy|web-crawler
1
524
53,686,899
Firestore updates using python api are not persisting
<p>I have the following code. </p> <pre><code>from firebase_admin import firestore db = firestore.client() collection = db.collection('word_lists') word_list = collection.get() for item in word_list: item_dict = item.to_dict() print item_dict['next_practice_date'] item.reference.update({'next_practice_da...
<p>I did not find the solution to the problem but instead switched <code>from firebase_admin import firestore</code></p> <p>to <code>from google.cloud import firestore</code> and everything works well now.</p>
python|firebase|google-cloud-firestore|firebase-admin
0
525
55,060,950
Sparse matrix hstack getting error regarding subscriptability
<p>Would someone please explain why this does not work?</p> <pre><code>from scipy.sparse import coo_matrix, hstack row = np.array([0,3,1,0]) col = np.array([0,3,1,2]) data = np.array([4,5,7,9]) temp = coo_matrix((data, (row, col))) temp_stack = coo_matrix([0, 11,22,33], ([0, 1,2,3], [0, 0,0,0])) temp_res = hstack(tem...
<p>First note that the first argument of <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.hstack.html" rel="nofollow noreferrer"><code>hstack</code></a> is expected to be a tuple containing the arrays to be stacked, so you should call it with <code>hstack((temp, temp_stack))</code>.</p> <p>Ne...
python|scipy
1
526
33,303,067
How to assign project category to a project using JIRA rest apis
<p>How to assign project category to a project using JIRA rest apis.<br> My Jira server version is 6.3.13</p>
<p>All the following is using python!</p> <p>If you are creating a new issue you can do it in two different ways, the first being a dict:</p> <pre><code> issue_dict = { 'project': {'id': 123}, 'summary': 'New issue from jira-python', 'description': 'Look into this one', 'issuetype':...
jira-rest-api|python-jira
-1
527
40,797,026
How to make multiple update in django?
<p>I'm trying to make multiple update in django by checking in checkbox then push the update button. </p> <p>This is my view.py</p> <pre><code>def update_kel_stat(request, id, kelid): if request.method == "POST": cursor = connection.cursor() sql = "UPDATE keluargapeg_dipkeluargapeg SET KelStatAppr...
<p>were you looking for <a href="https://docs.djangoproject.com/en/1.10/ref/request-response/#django.http.QueryDict.getlist" rel="nofollow noreferrer">getlist</a>?</p> <blockquote> <p>QueryDict.getlist(key, default=None)<br> Returns the data with the requested key, as a Python list. Returns an empty list if the ...
javascript|python|django|web
2
528
19,085,274
Open New Thunderbird Email Using Python
<p>I'm trying to open just a new Thunderbird email and attach a file to it for me to fill out the recipient email addresses' instead of hardcoding it. I'm using Windows 7, Python 2.7 and the latest version of Thunderbird.</p> <p>I noticed some other questions like this but they all involved writing a Thunderbird plug...
<p>Thunderbird and other programs from Mozilla don't use <code>win32com</code>. Instead, they use <code>xpcom</code>. See [<a href="http://kb.mozillazine.org/Calling_Thunderbird_from_other_programs" rel="nofollow">http://kb.mozillazine.org/Calling_Thunderbird_from_other_programs</a>. </p> <p>There is a python module, ...
python|email|python-2.7|thunderbird
2
529
19,299,168
Why child class doesn't overwerite the fields from based class in python and how deal with that
<p>I create based abstract class in python which is based class for all child classes and implement some functions which will be redundant to write each time in every child class.</p> <pre><code>class Element: ###SITE### __sitedefs = [None] def getSitedefs(self): return self.__sitedefs class SR...
<p>Your problem's is due to name mangling. See eg: <a href="https://stackoverflow.com/questions/1301346/the-meaning-of-a-single-and-a-double-underscore-before-an-object-name-in-python">What is the meaning of a single- and a double-underscore before an object name?</a>.</p> <p>If you change all the <code>__sitedefs</co...
python
7
530
41,719,006
What type of field do I have to use in order to associate related parent object in serializer
<p>I have two models with one to many relation. I will use the default example.</p> <pre><code>class Album(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) album_name = models.CharField(max_length=100) artist = models.CharField(max_length=100) class Track(models.M...
<p>You can even try this</p> <pre><code>album = serializers.SlugRelatedField( queryset=models.Album.objects.all(), slug_field='uuid' ) </code></pre> <p>It will accept you model uid to get the object.</p> <pre><code>{ "album": "ed79716c-ba5d-4d3f-bb96-2685b38139e5", "title": "Eleanor Rigby...
python|django|serialization|django-rest-framework
1
531
27,829,259
Organize subplots using matplotlib
<p>I am trying to plot the content of a json file. The script should generate 64 subplots. Each subplot consists of 128 samples (voltage levels). "ElementSig" is a "key" in that json file for a list of 8192 samples. I am taking 128 samples at a time and generate a subplot of it as you see in my following script:</p> <...
<p>I got a better figure when I saved it as .png file. </p> <pre><code>fig = plt.figure(figsize=(20, 222)) plt.subplots_adjust(top=.9, bottom=0.1, wspace=0.2, hspace=0.2) for i in range(1, 65): print 'E', i, ':' plt.subplot(64, 2, i) plt.ylabel('E%s' % str(i)) i += 1 print E[0+j:127+j] plt....
python|matplotlib
0
532
48,646,779
TypeError: cupcake_flour() missing 1 required positional argument: 'cu_flour'. What am I doing wrong?
<p>This is my first time taking python and i'm having a hard time understanding what I've done wrong to receive this error? This code is supposed to change grams to cups for a cupcake recipe and this is just the first step converting the flour. The input function works but after that I get the above error.</p> <pre><c...
<p>You have defined your function <code>cupcake_flour</code> to take an argument, but you are not providing one when you are calling <code>cupcake_flour()</code>. You probably want to pass the user input to the function and then print the amount of flour needed like so:</p> <pre><code>def cupcake_flour(cookies): cu_...
python|python-3.x
1
533
64,291,796
subset a python dataframe by conditions
<p>I trying to select the name row with count&gt;250, which is called effective here. So we will try to find the mean of its rate</p> <pre><code>t3=dfnew.groupby('name')['ratings'] t4=t3.count() t5=t4[t4.values&gt;250] t6=t3.mean() t6[(t6.index==t5.index)] </code></pre> <p>Obviously the problem is in last row of my cod...
<pre><code>t3=dfnew.groupby('name')['ratings'].agg(['count','mean']) t5=t3[t3['count']&gt;250] t5 </code></pre> <p>It works fine when I aggregate two functions at the same time.</p>
python|pandas|numpy
0
534
64,462,917
"view_as_windows" from skimage but in Pytorch
<p>Is there any Pytorch version of <code>view_as_windows</code> from skimage? I want to create the view while the tensor is on the GPU.</p>
<p>I needed the same functionality from Pytorch and ended up implementing it myself:</p> <pre class="lang-py prettyprint-override"><code>def view_as_windows_torch(image, shape, stride=None): &quot;&quot;&quot;View tensor as overlapping rectangular windows, with a given stride. Parameters ---------- ima...
python|pytorch|scikit-image
1
535
70,578,538
literal_eval and boolean Logic in Python
<pre><code>&gt;&gt;&gt; from ast import literal_eval &gt;&gt;&gt; H = {&quot;('a','b')&quot;:1} &gt;&gt;&gt; x = ('a','b') &gt;&gt;&gt; str(x) &quot;('a', 'b')&quot; &gt;&gt;&gt; list(H.keys())[0] &quot;('a','b')&quot; &gt;&gt;&gt; str(x) == list(H.keys())[0] False </code></pre> <p>Why do I get a False statement? Howev...
<p>In my tests, <code>str(x)</code> is <code>&quot;('a', 'b')&quot;</code>. Do you notice the space after the comma?</p> <p>That is enough to explain why the strings are different (one contains a space while the other does not), while the tuples are equal.</p>
python|boolean
1
536
70,546,285
How can I find the second smallest output for my function?
<p>I used this function to find the biggest pullback $ wise for my data frame column with stock prices. I need help to figure out how to get the X following output. Basically the plan is to join those outputs into a new data frame to get the X biggest pullbacks within my data frame.</p> <p><strong>Main question:</stron...
<p>The strategy u can use is to first find the biggest pullback, then exclude that range where that pullback is and then calculate the biggest pullback for all valid ranges that are left.</p> <p>I made my own <code>maxdrop</code> function that works in a similar fashion as yours, except it only looks within specified b...
python|pandas|function|format
1
537
72,948,512
Is there any method to replace selectROI with auto selection?
<p>I have finished detecting faces through videos and generating a bounding box if detected by Haar Cascade classifier. And now I only want to analyze the particular part of the face such as foreheads or cheeks, but I could just choose the place manually through selectROI in OpenCV. Is there any method to revise my cod...
<p>there can be different ways you can go around for detecting and analysing facial regions, I am listing a few:</p> <ul> <li>you can use <a href="http://dlib.net/face_landmark_detection.py.html" rel="nofollow noreferrer"><code>Dlib's Landmark Detector</code></a> to detect facial landmarks and classify the facial regio...
python|opencv|face-detection
1
538
64,801,774
AttributeError: module 'numexpr' has no attribute '__version__'
<p>Trying to import some modules written below:</p> <pre><code>import numpy as np import os.path import pandas as pd import math import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D </code></pre> <p>However I get an AttributeError: module 'numexpr' has no attribute '<strong>version</strong>' which I ...
<p>I experienced the same problem a while back and solved it by doing the following thing in <code>Ananconda</code>:</p> <pre><code>pip uninstall -y numpy pip uninstall -y setuptools pip install setuptools pip install numpy </code></pre> <p>If you are using Anaconda3 try the same thing using <code>pip3</code>.</p>
python|pandas
0
539
65,008,711
What is the optimal way to create a new column in Pandas dataframe based on conditions from another row?
<p>I have a Pandas dataframe, <code>week1_plays</code> in the following format:</p> <p><a href="https://i.stack.imgur.com/18A4N.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/18A4N.png" alt="enter image description here" /></a></p> <p>What I want to do is add a column <code>week1_plays['distance_fro...
<p>You are looking for a <code>merge</code> or <code>join</code> operation. Try something like this:</p> <pre><code>df = pd.DataFrame({'gameId':[1,1,1,1,1,1],'playId':[1,1,1,1,1,1], 'frameId':[1,1,1,2,2,2], 'position':['A','B','WR','C','WR','D'], 'x':[87,56,45,34,45,67], 'y':[25,36...
python|pandas|dataframe
2
540
64,810,833
Python 3.8 sort - Lambda function behaving differently for lists, strings
<p>Im trying to sort a list of objects based on frequency of occurrence (increasing order) of characters. Im seeing that the sort behaves differently if list has numbers versus characters. Does anyone know why this is happening?</p> <p>Below is a list of numbers sorted by frequency of occurrence.</p> <pre><code># Sort ...
<p>Sorting uses stable sort - that means if you have the same sorting criteria for two elements they keep their <em>relative</em> order/positioning (here it being the amount of 2 for both of them).</p> <pre><code>from collections import Counter # Sort list of characters based on increasing order of frequency alp = ['l'...
python-3.x
3
541
63,857,586
How do I fix a value error when using scipy.integrate odeint function?
<p>I'm an engineering student and I'm trying to figure out how to use the odeint function from the scipy.integrate module (I've only ever used ode45 in MATLAB). I'm attempting to numerically solve a simple second order mass, spring, dashpot system. Below is the code I've written (specifically I'm using Jupyter Notebook...
<p><code>f</code> is an array of numbers, and therefore so is <code>f -b/m*x[1] - k/m*x[0]</code>, so the return value of your function <code>translational</code> is not correct.</p> <p>Instead of attempting to precompute the values of <code>f</code>, what you should do is use the expression for the function in <code>t...
python|numpy|scipy
0
542
53,291,663
How to build a dictionary that map nodes to its degree in networkx2.1,python3?
<p>what I try is here :</p> <pre><code>def comm_deg(G): nodes = G.nodes() A=nx.adj_matrix(G) deg_dict = {} n = len(nodes) degree= A.sum(axis = 1) for i in range(n): deg_dict[nodes[i]] = degree[i,0] return deg_dict </code></pre> <p>it shows that KeyError: 0, I find both using <code>n...
<p>So there's several issues here.</p> <p>First, there's a better way to create a dict than what you're doing. In fact it's basically already built in. <code>G.degree</code> is already a dict-like object so that <code>G.degree[node]</code> will give the degree of <code>node</code>.</p> <p>If you really want it to ...
python|python-3.x|networkx
2
543
72,091,852
Pandas datetime filter
<p>I want to get subset of my dataframe if date is before 2022-04-22. The original df is like below</p> <p>df:</p> <pre><code> date hour value 0 2022-04-21 0 10 1 2022-04-21 1 12 2 2022-04-21 2 14 3 2022-04-23 0 10 4 2022-04-23 1 12 5 2022-04-23 2 ...
<p>You most likely still have some string dates in one of your rows thus the first element might be ok but a complete comparison of all values using &quot;&lt;&quot; will fail.</p> <p>Either you use timegeb's answer in the comments.</p> <pre><code>df['date'] = pd.to_datetime(df['date']) </code></pre> <p>or you convert ...
python|pandas|dataframe|datetime
1
544
68,581,994
How to get the "element name" for selenium?
<p>I have (found) a python script whose purpose is to click a certain button on a certain web page. This is the script:</p> <pre><code>from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(ChromeDriverManager().install()) url = &quot;https://url&quot; driver....
<p>What you're looking for is called the developer tools. If you're using Chrome, <a href="https://nira.com/chrome-developer-tools/#:%7E:text=From%20the%20Chrome%20menu%3A,web%20page%20you%27re%20on." rel="nofollow noreferrer">here's</a> a good tutorial. Most browsers have a very similar layout.</p> <p>Essentialy you w...
python|selenium
1
545
10,583,640
Is this a correct implementation for a curried operator.add function?
<p>This <a href="http://www.uncarved.com/blog/not_currying.mrk" rel="nofollow">blogpost</a> proposed this implementation of a curried addition function:</p> <pre><code>def addN(n): return lambda x: x + n def plus(a, b): addA=addN(a) return addA(b) </code></pre> <p>I believe my version is more correct bec...
<p>Your <code>plus</code> function is identical to the <code>addN</code> function from the blog post. The only differences are:</p> <ol> <li>You used a <code>lambda</code> where the blog post used a <code>def</code>.</li> <li>For some reason you used <code>operator.add(a,b)</code> instead of simply <code>a+b</code>.</...
python|functional-programming
5
546
5,394,474
Django: Edit Function while not changing the Image data
<p>I have an edit function that I want the user to be able to edit the Picture object (tags), while keeping the old image. The form is looking for a photo but I do want the user to be able to change the image - just the other information. </p> <p>How do you pass the original image data from the picture object into the...
<p>I think this thread should give you a clue how to make existing fields readonly: <a href="https://stackoverflow.com/questions/324477/in-a-django-form-how-to-make-a-field-readonly-or-disabled-so-that-it-cannot-be">In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?</a></p> <p>...
python|django-forms|django-views
0
547
5,484,900
Does local GAE read and write to a local datastore file on the hard drive while it's running?
<p>I have just noticed that when I have a running instance of my GAE application, there nothing happens with the datastore file when I add or remove entries using Python code or in admin console. I can even remove the file and still have all data safe and sound in admin area and accessible from code. But when I restart...
<p>How the datastore reads and writes its underlying files varies - the standard datastore is read on startup, and written progressively, journal-style, as the app modifies data. The SQLite backend uses a SQLite database.</p> <p>You shouldn't have to care, though - neither backend is designed for robustness in the fac...
python|google-app-engine|local-storage
3
548
5,313,513
Is there any python implement of edonkey/emule
<p>I want deploy a project in google appengine to search edonkey/emule, Is there any python implement of edonkey/emule or ed2k protocol library ?</p>
<p>After 20 minutes of googling all combinations of python and edonkey/emule/ed2k and visiting all sites of all clients listed under the "eDonkey network" Wikipedia page I can say with near certainty that the answer is "No."</p>
python|p2p
1
549
61,848,676
Is there a way to label the mean and median in matplotlib boxplot legend?
<p>I have the following box plot which plots some values with different mean and median values for each box; I am wondering if there is any way to label them so that they appear on the graph legend (because the current box plot plots an orange line for the median and a blue dot for the mean and it is not so clear which...
<p>Its a bit late, but try this:</p> <pre><code> bp = plt.boxplot([x_5_diff[k] for k in keys], positions=keys) # You can access boxplot items using ist dictionary plt.legend([bp['medians'][0], bp['means'][0]], ['median', 'mean']) </code></pre>
python|matplotlib|boxplot
5
550
61,801,990
Tensorflow 2.0 : AttributeError: module 'tensorflow' has no attribute 'matrix_band_part'
<p>While running the code tf.matrix_band_part , i get the following error</p> <pre><code>AttributeError: module 'tensorflow' has no attribute 'matrix_band_part' </code></pre> <p>My tensorflow version : 2.0</p> <p>Any solution for this problem is needed.</p>
<p>I have found the answer. So i would like to share.</p> <p>Compatible version for the function for tensorflow 2.0 is</p> <pre><code>tf.compat.v1.matrix_band_part </code></pre> <p>Ref : <a href="https://www.tensorflow.org/api_docs/python/tf/linalg/band_part" rel="nofollow noreferrer">https://www.tensorflow.org/api_...
tensorflow2.0|attributeerror
1
551
61,789,921
Cant See Data Inside of Section Tag with Selenium
<p>I am trying to count how many buttons are on a page. And then later press them. However to access these buttons I have to go through an iframe, some generic (div) layers, and a region (section) layer.</p> <p>I'm able to get through the iframe layer with</p> <p><code>driver.switch_to.frame("iframeID")</code></p> <...
<p>It is simple to achieve with Beautiful Soup:</p> <pre><code>from bs4 import BeautifulSoup soup = BeautifulSoup(driver.page_source, 'html.parser') len(soup.find_all('button', {'type' : 'button'})) </code></pre> <p>Hope this helps.</p>
python|selenium|selenium-webdriver|webdriver
0
552
67,538,117
Python Countdown but in Year, Month, Week, Days, Hours, Minutes, Sec
<p>I would like to have my lifetime displayed in the form of a countdown. Unfortunately, Python datetime only allows days. And couldn't program a conversion</p> <p>this is what i tried:</p> <pre><code>#!/usr/bin/env python3 import time import datetime from dateutil.relativedelta import relativedelta from datetime impo...
<p>Here's how I'd do it. Note that &quot;months&quot; is approximate, assuming 30 days per month. Using only &quot;weeks&quot; would be more accurate.</p> <pre><code>import time import datetime from datetime import timedelta lebenszeit = datetime.datetime(2085,7,6) - datetime.datetime.now() alldays = lebenszeit.days ...
python|datetime|countdown
1
553
71,257,349
Linear discriminant Analysis Sklearn
<p>I’m running LDA on a dataset and the outcome was good across all metrics. However I can’t seem to extract the top features or loadings like I can for PCA.</p> <p>Is anyone familiar with extracting top features / loadings from LDA when using sklearn python3?</p>
<p>try this:</p> <pre><code>import numpy as np from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA X = training_input y = training_label.ravel() clf = LDA(n_components=1) clf.fit(X, y) clf.coef_ beste_Merkmal = np.argsort(clf.coef_)[0][::-1][0:25] print('beste_Merkmal =', beste_Merkmal) ...
python|python-3.x|lda|linear-discriminant
0
554
70,326,423
Python: Large float arithmetic for El Gamal decryption
<h2>Context</h2> <p>The decryption math formula for the El Gamal method is the following:</p> <pre><code>m = ab^(-k) mod p </code></pre> <p>Specifically in Python, I want to compute the following equivalent:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; m = (b**(-k) * a) % p </code></pre> <p>The issu...
<p>Very easily: just multiply the two, and do an explicit mod:</p> <pre><code>&gt;&gt;&gt; p = 262643 &gt;&gt;&gt; pow(15653, -3632, p) 86669 &gt;&gt;&gt; 86669 * 923 % p 152015 </code></pre> <p>Done!</p>
python|math|cryptography|precision|elgamal
2
555
11,237,527
I have a set of points along the oval. How do I create a filled binary mask
<p>I am trying to get an filled binary mask of a contour of this image. <img src="https://i.stack.imgur.com/rp469.png" alt="The contour of the image"></p> <p>I took a look this question <a href="https://stackoverflow.com/questions/3654289/scipy-create-2d-polygon-mask">SciPy Create 2D Polygon Mask</a>; however it does ...
<p>I'm not sure what you're plotting at the end, but your example works for me:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from matplotlib.nxutils import points_inside_poly from itertools import product, compress pv = [(1,1),(5,1),(5,9),(3,2),(1,1)] x, y = np.meshgrid(np.arange(10),np.arange(1...
python|image-processing|numpy|matplotlib
2
556
10,966,006
Django Middleware - How to edit the HTML of a Django Response object?
<p>I'm creating a custom middleware to django edit response object to act as a censor. I would like to find a way to do a kind of search and replace, replacing all instances of some word with one that I choose.</p> <p>I've created my middleware object, added it to my <code>MIDDLEWARE_CLASSES</code> in settings and ha...
<p>You can simply modify the <code>response.content</code> string:</p> <pre><code>response.content = response.content.replace("BAD", "GOOD") </code></pre>
python|html|django
9
557
56,617,528
Keras model doest not provide same results after converting into tensorflow-js model
<p>Keras model performs as expected in python but after converting the model the results are different on the same data.</p> <p>I tried updating the keras and tensorflow-js version but still the same issue.</p> <p>Python code for testing:</p> <pre><code> import keras import cv2 model = keras.models.load_model("keras...
<p>It has to do with the image used for the prediction. The image needs to have completely loaded before the prediction.</p> <pre><code>imEl.onload = function (){ const pred = model.predict(preprocessing_img(imgEl)).dataSync() const class_index = tf.argMax(pred); } </code></pre>
javascript|python|keras|tensorflowjs
1
558
69,730,687
Is there a way to make Class[key] work to extract from a static container?
<p>I'm trying to build a class that maintains an internal list of all objects of that class and can look them up by ID. While I could use <code>myClass.get(objectID)</code> to get the objects, I would really prefer to use <code>myClass[objectID]</code> but this throws <code>TypeError: 'type' object is not subscriptable...
<p>With respect to your <strong>EDIT</strong> that uses a metaclass, I'd suggest using a <code>dict</code> instead of a <code>set</code> for the <code>bucket</code> attribute since it makes things easier and more succinct:</p> <pre><code>class MetaBucket(type): def __init__(cls, name, bases, dct): cls.bucke...
python|class
0
559
17,737,914
Unable to iterate over the "tr" element of a table using beautiful soup
<pre><code>from bs4 import BeautifulSoup import re import urllib2 url = 'http://sports.yahoo.com/nfl/players/5228/gamelog' page = urllib2.urlopen(url) soup = BeautifulSoup(page) table = soup.find(id='player-game_log-season').find('tbody').find_all('tr') for rows in tr: data = raws.find_all("td") print data...
<p>There's no <code>tbody</code> in the table under <code>div#player-game_log-season</code>. And your code has some typos.</p> <ul> <li><code>raws</code> -> <code>rows</code></li> <li><code>table</code> -> <code>tr</code></li> </ul> <hr> <pre><code>... tr = soup.find(id='player-game_log-season').find_all('tr') for ...
python|web-scraping|beautifulsoup
1
560
60,895,313
Pandas Dataframe: New Column that uses Country if Province is empty, else use the Province
<p>The meat of what I'm trying to do can be seen at the bottom. Here's the dataset I'm using: <a href="https://github.com/CSSEGISandData/COVID-19/blob/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv" rel="nofollow noreferrer">https://github.com/CSSEGISandData/COVID-19/blob/m...
<p>This worked:</p> <pre><code>def names_column(frame, lst): #Makes a new column called Name for i in range(len(frame)): if type(frame['Province/State'][i]) is str: lst.append(frame['Province/State'][i]) else: lst.append(frame['Country/Region'][i]) frame['Name'] = df(lst...
python|pandas|dataframe
-1
561
72,775,645
in class, pass from method to method the values of local variables
<p>I have a problem to pass from method to method the values of local variables. I didn't put them in the constructor because I would like some processing to be done in the methods</p> <pre><code>class Myclass: def __init__(self,nbr1,nbr2): self.nbr1 = nbr1 self.nbr2 = nbr2 def ope...
<p>You need to actually call <code>operation1()</code> somewhere</p> <pre><code>def operation2(self): nbr3 = self.operation1() nbr3 *= 2 return nbr4, nbr3 </code></pre> <p>Or set the instance variable</p> <pre><code>def operation1(self): self.nbr3 = self.nbr1 + self.nbr2 def operation2(self): nbr4...
python|oop
0
562
68,110,565
Does Google Drive API search responds not only files/folder metadata but also the matched content w.r.t query in the search response?
<pre><code>response = DRIVE.files().list(q=&quot;fullText contains 'what is python?',spaces='drive',fields='*',pageToken=page_token).execute() </code></pre> <p>from the above sample Python code,what extra param that I can pass or extract to get the files with the matched content as well with them?</p> <p>Example respon...
<p>The <a href="https://developers.google.com/drive/api/v2/search-shareddrives" rel="nofollow noreferrer">q</a> parameter for file.list method allows you to search for things like files with a specific title, or file type</p> <p>The google drive api is just a file storage system it does not have the power to open a fil...
python|google-api|google-drive-api|google-api-python-client
0
563
59,411,587
Python - find items with multiple occurences and replace with mean
<p>For df:</p> <pre><code>sample type count sample1 red 5 sample1 red 7 sample1 green 3 sample2 red 2 sample2 green 8 sample2 green 8 sample2 green 2 sample3 red 4 sample3 blue 5 </code></pre> <p>I would like to find items in "type" with multiple occurences and repla...
<p>I believe you can simplify solution to <code>mean</code> per all groups, because mean by value is same like this value:</p> <pre><code>df = df.groupby(["sample","type"], as_index=False, sort=False)["count"].mean() print (df) sample type count 0 sample1 red 6 1 sample1 green 3 2 sample2 re...
python|pandas
1
564
35,619,831
Iterating to produce a unique list
<p>This is the initial code:</p> <pre><code>word_list = ['cat','dog','rabbit'] letter_list = [ ] for a_word in word_list: for a_letter in a_word: letter_list.append(a_letter) print(letter_list) </code></pre> <p>I need to modify it to produce a list of unique letters.</p> <p>Could somebody please advise how ...
<p>Only problem that I can see is that you have not checked if the letter is already present in list or not. Try this:</p> <pre><code>&gt;&gt;&gt; word_list= ['cat', 'dog', 'rabbit'] &gt;&gt;&gt; letter_list= [] &gt;&gt;&gt; for a_word in word_list: for a_letter in a_word: if a_letter not in letter_list: ...
python|list|for-loop|char|unique
2
565
73,484,500
useEffect fires and print statements run but no actual axios.post call runs reactjs
<p>I have a useEffect function that is firing due to <code>yearsBackSettings</code> changing and the console.log statements inside useEffect fire too:</p> <pre><code>useEffect(() =&gt; { console.log(&quot;something changed&quot;) console.log(yearsBackSettings) if (userId) { const user_profile_api_url ...
<p>The issue is somewhere in your python server code, in your console you can see that you are actually logging a response object with a 200 response code, meaning your server doesn't crash during the actual request.</p> <p>There might be a problem in your server side logging causing the request to not show up, I would...
javascript|python|reactjs|django
5
566
71,090,728
Optimization variables of a neural network model with simulated annealing
<p>I implement an MLP neural network model on the data, for optimization 4 variables a function base on the MLP model is defined, and simulated annealing run on this function. I don't know why I get this error (attached below).</p> <p>Neural network code:</p> <pre><code># mlp for regression from numpy import sqrt from ...
<p>it's for your input shape, in MLP neural network your input shape is [none,14], but in your function's input id [14,1], so you need transpose it.</p> <pre><code>def objective_function(X): wob = X[0] torque= X[1] RPM = X[2] pump = X[3] input=[wob,torque,RPM, 0.00017,0.027,pump,0,0.5,0.386,0.026,0.0119,...
python|function|optimization|mlp|simulated-annealing
0
567
70,984,483
Issue with load_img- Error- FileNotFoundError: [Errno 2] No such file or directory:
<pre><code>for i in os.listdir(&quot;D:/Deep Learning/vgg16_images&quot;): print(i) image=[] for i in os.listdir(r'D:\Deep Learning\vgg16_images'): img = load_img(i,target_size=(224, 224)) img=img_to_array(img) img = img.reshape((1, img.shape[0], img.shape[1], img.shape[2])) # prepare the image for the...
<p>my apologies..this question should not have been there in the first place, realized it later..those days when the brain stops working completely</p> <p>The mentioned directory and load_img paths are different. load_imp was working for all images other than the bus.jpg was because those images were there in both the ...
python|image
0
568
70,840,179
pandas pivot data Cols to rows and rows to cols
<p>I am using python and pandas have tried a variety of attempts to pivot the following (switch the row and columns)</p> <p>Example: A is unique</p> <pre><code> A B C D E... (and so on) [0] apple 2 22 222 [1] peach 3 33 333 [N] ... and so on </code></pre> <p>And I would l...
<p>Think you're wanting <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.transpose.html" rel="nofollow noreferrer">transpose</a> here.</p> <pre><code>df = pd.DataFrame({'A': {0: 'apple', 1: 'peach'}, 'B': {0: 2, 1: 3}, 'C': {0: 22, 1: 33}}) df = df.T print(df) 0 1 A apple peach B...
python|pandas|pivot
1
569
60,030,104
how to convert a pandas dataframe to a list of dictionaries in python?
<p>I have a dataframe like this:</p> <pre><code>data = {'id': [1,1,2,2,2,3], 'value': ['a','b','c','d','e','f'] } df = pd.DataFrame (data, columns = ['id','value']) </code></pre> <p>I want to convert it to a list of dictionary like:</p> <pre><code>df_dict = [ { 'id': 1, 'value':['a','b'] }, { 'id': 2, 'va...
<p>You can groupby and then use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html" rel="nofollow noreferrer">to_dict</a> to convert it to a dictionary.</p> <pre><code>&gt;&gt;&gt; df.groupby(df['id'], as_index=False).agg(list).to_dict(orient="records") [{'id': 1, 'value'...
python|pandas|dataframe|dictionary
3
570
60,235,937
How do I extract the information from the website?
<p>I am trying to gather information of all the vessels from this website: <a href="https://www.marinetraffic.com/en/data/?asset_type=vessels&amp;columns=flag,shipname,photo,recognized_next_port,reported_eta,reported_destination,current_port,imo,ship_type,show_on_live_map,time_of_latest_position,lat_of_latest_position,...
<p>Instead of clicking each vessel to open up the details, you can get the information you're searching for from the results page. This will get each vessel, pull the info you wanted and click to the next page if there are more vessels:</p> <pre><code>import selenium.webdriver as webdriver url = "https://www.marinet...
python|selenium|web-scraping|beautifulsoup
1
571
2,814,450
How to make Django work with MySQL Connector/Python?
<p>Has anyone made Django work with myconnpy?</p> <p>I've checked out <a href="http://github.com/rtyler/connector-django-mysql" rel="nofollow noreferrer">http://github.com/rtyler/connector-django-mysql</a> but the author said it's very outdated and not supported.</p> <p>If you've managed to make Django work with myco...
<p>I needed something similar, so I forked the project you linked to and updated it to work (for small values of) with Django 1.2's newer database backend API.</p> <p>It should be noted that my use case is very simple (read access to a single table on a single database) and I have not tested it with anything more than...
python|mysql|django|mysql-connector|django-database
1
572
6,016,937
Writing a string to the last line in a file, Python
<p>I'm attempting to make a function that writes a string to the last line in a file. However, what I currently have (below) only writes to the first line. So if I call the function more than once, it simply overwrites the first line. I'd like it to instead write the string to a new line; how would I go about this? </...
<p>Open the file in append mode (<code>'a'</code> instead of <code>'w'</code>). Opening in <code>'w'</code> mode truncates your file (you're now writing into an empty file)</p>
python|string|file|io
16
573
5,660,549
Google AppEngine tells me that my int is not an int
<p>The relevant part of the code:</p> <pre><code>pk = int(pk) logging.info('pk: %r :: %s', pk, type(pk)) instance = models.Model.get_by_id(int(pk)) </code></pre> <p>The output from the log message above</p> <pre><code>pk: 757347 :: &lt;type 'int'&gt; </code></pre> <p>The stacktr...
<p>Does your model have a property 'pk', which is now an IntegerProperty(), but was previously a StringProperty(), and the entity with id 757347 was saved with the old version of the model?</p>
python|google-app-engine|google-cloud-datastore
5
574
67,803,117
How to edit "view on site" url on django admin?
<p>How in the modern version of Django edit the &quot;view on site&quot; url on django admin?</p>
<p>in your model implement <code>get_absolute_url</code> method like this</p> <pre><code> def get_absolute_url(self): return reverse('model_record_view',args=[self.id]) </code></pre> <p>where model_record_view is the name of the view and it is id as a paramter</p>
python|django
0
575
67,986,807
Create Pandas DataFrame from a list and list of lists
<p>I have two python lists</p> <pre><code>messages = ['message1', 'message2', 'message3'] labels = [[1,0,1,3,1], [1,1,2,0,3], [0,0,2,1,0]] </code></pre> <p>I am creating dataFrame which will take <strong>messages</strong> as first column and <strong>labels</strong> as <strong>cat_1, cat_2, cat_3, cat_4, cat_5</strong>...
<p>If no problem with starting by <code>0</code> for new columns names use <code>DataFrame</code> constructors with <code>join</code>:</p> <pre><code>df = pd.DataFrame({'message': messages}).join(pd.DataFrame(labels).add_prefix('cat_')) print (df) message cat_0 cat_1 cat_2 cat_3 cat_4 0 message1 1 0...
python|python-3.x|pandas|list|dataframe
4
576
67,686,642
RedisCluster MGET with pipeline
<p>I am trying to perform an MGET operation on my Redis with the pipeline to increase performance. I have tried doing MGET in one go as well as as a batch flow</p> <pre><code>from rediscluster import RedisCluster ru = RedisCluster(startup_nodes=[{&quot;host&quot;: &quot;somecache.aws.com&quot;, &quot;port&quot;: &quot;...
<p>Turns out we can not use MGET with the pipeline, below is m final solution</p> <pre><code>from rediscluster import RedisCluster def redis_multi_get(rc: RedisCluster, keys: list): pipe = rc.pipeline() [pipe.get(k) for k in keys] return pipe.execute() if __name__ == '__main__': rc = RedisClus...
python|redis|pipeline|redis-cluster
0
577
67,639,397
Combine two rows in csv using python
<p>I need to combine two rows removing the space between them. What I need is:</p> <p>My csv with single column:</p> <pre><code>&quot;2021-05-13&quot;|&quot;test&quot;|&quot;perfect line&quot; &quot;2021-05-13&quot;|&quot;test&quot;| &quot;imperfect line&quot; &quot;2021-05-13&quot;|&quot;test&quot;|&quot;perfect...
<p>You can use a <a href="https://regex101.com/r/se0wbY/2" rel="nofollow noreferrer">regex</a> to reconstruct the line in the proper format:</p> <pre><code>import re with open(your_file, 'r') as f: s=re.sub(r'^([^|]*\|)([^|]*\|)\n\s*([^|\n]*\n)',r'\1\2\3', f.read(), flags=re.M) print(s) </code></pre> <p>Print...
python|csv
0
578
30,345,832
osm file, parsing, memory error even with clearing elements.
<p>I want to take an osm file, clean it, and then save it as a json file. The xml file is about 1 gb big.</p> <pre><code>def audit(): osm_file = open('c:\Users\Stephan\Downloads\los-angeles_california.osm', "r") with open('lala.txt', 'w') as outfile: for event, elem in ET.iterparse(osm_file, events=("s...
<pre><code>osm_file = open('c:\Users\Stephan\Downloads\los-angeles_california.osm', "wr") </code></pre> <p>if you want to clean it, it should be writable</p>
python|json|memory|openstreetmap
0
579
30,344,045
Ordering a string by its substring numerical value in python
<p>I have a list of strings that need to be sorted in numerical order using as a int key two substrings. Obviously using the <code>sort()</code> function orders my strings alphabetically so I get 1,10,2... that is obviously not what I'm looking for.</p> <p>Searching around I found a key parameter can be passed to the ...
<p>Try the following</p> <pre><code>In [26]: import re In [27]: f = lambda x: [int(x) for x in re.findall(r'\d+', x)] In [28]: sorted(strings, key=f) Out[28]: ['test1txtfgg2', 'test1txtfgf10', 'test2txtsdsd1', 'test2txffdt3'] </code></pre> <p>This uses regex (the <a href="https://docs.python.org/3/library/re.html" ...
python|string|sorting
4
580
66,788,463
How to move specific data from one column to a new column on Pandas?
<p>I have a set of data with 2 columns: Column1 = Hex Code and Column2= Current (A).</p> <p>The data in Column1 is Hex Code, 27 different codes which repeats and for each Hex Code have Current (A) value on Column2.</p> <p>I want to pick a set of 27 data points from Column1 &amp; Column2 and place them into Coulmn3 &amp...
<p>I am going tho show you my code. But I want to tell that you can not have repeating columns names. We suppose data is the name of your original dataset:</p> <pre><code>import pandas as pd col_name1=data.columns.values[0] col_name2=data.columns.values[1] two_columns = data[[col_name1,col_name2]][0:27].values two_c...
python|excel|pandas|dataframe
0
581
43,010,622
Unable to click element on page Selenium python
<p>I am trying to move to page 2 and beyond of this page (pagination) with python selenium and spent a few hours on this. I am getting this error, and would be thankful of any help..Error from chromedriver</p> <pre><code>is not clickable at point(). Other element would receive the click </code></pre> <p>My code so f...
<p>What if instead you would locate the "Next" button <em>by link text</em>, scroll into it's view and then click:</p> <pre><code>next_button = self.driver.find_element_by_link_text("Next") self.driver.execute_script("arguments[0].scrollIntoView();", next_button) next_button.click() </code></pre> <p>I would also maxi...
python|selenium|web-scraping
2
582
42,590,529
How can I track all SQL query timings and counts in Django?
<p>I'd like to have a Django application record how much time each SQL query took.</p> <p>The first problem is that SQL queries differ, even when they originate from the same code. That can be solved by normalizing them, so that</p> <pre><code>SELECT first_name, last_name FROM people WHERE NOW() - birth_date &lt; int...
<p>Django debug toolbar has a panel that shows "SQL queries including time to execute and links to EXPLAIN each query" <a href="http://django-debug-toolbar.readthedocs.io/en/stable/panels.html#sql" rel="nofollow noreferrer">http://django-debug-toolbar.readthedocs.io/en/stable/panels.html#sql</a></p>
python|django
0
583
42,936,110
None value in python numerical integration function
<p>I'm trying to write a code that calculates integrals using the rectangular rule and also allows the user to input the integral limits and number of divions(rectangles). I've written the function, but for certain values it just returns "None". Any idea why?</p> <p>Here's my code so far:</p> <pre><code>def integral(...
<pre><code>for i in range(1, N-1): result += h * f(a + i*h) return result </code></pre> <p>If <code>N = 2</code> then <code>for i in range(1, 1)</code> is not going to execute, thus <code>integral</code> returns <code>None</code>.</p> <p>But even if <code>N &gt; 2</code>, having <code>return</code> inside the...
python|numerical-integration
2
584
72,454,208
How to pass a variable as a column name with pyodbc?
<p>I have a list that has two phone numbers and I'd like to put each phone number into its own column in an Access database. The column names are Phone_Number1 and Phone_Number2. How do I pass that to the INSERT statement?</p> <pre class="lang-py prettyprint-override"><code>phone_numbers = ['###.218.####', '###.746.###...
<p>If you want to insert both numbers in the same row, remove the for loop and adjust the <code>INSERT</code> to consider the two columns:</p> <pre class="lang-py prettyprint-override"><code>phone_numbers = ['###.218.####', '###.746.####'] # ... column_names = [f&quot;PhoneNumber{i}&quot; for i in range(1, len(phone_nu...
python|pyodbc
1
585
65,828,379
How to blit from the x and y coordinates of an image in Pygame?
<p>I'm trying to lessen the number of files I need for my pygame project by instead of having a folder with for example 8 boots files, I can make 1 bigger image that has all of them 8 pictures put next to each other and depending on animation tick, that specific part of the image gets blitted.</p> <p>Currently, I utili...
<p>You can define a subsurface that is directly linked to the source surface with the method <a href="https://www.pygame.org/docs/ref/surface.html#pygame.Surface.subsurface" rel="nofollow noreferrer"><code>subsurface</code></a>:</p> <blockquote> <p><code>subsurface(Rect) -&gt; Surface</code></p> <p>Returns a new Surfac...
python|pygame
2
586
65,623,839
Why I am getting None in place of int from if block inside a method called by another method in the class
<p>Here is the code, I am trying to get a binary search result using a method inside the class. The class has more functions but only this function is giving the wrong output (<code>None</code> in place an integer). The <code>if</code> part from line number 10 to 15 is causing the problem.</p> <pre><code>class Solution...
<p>Short answer to your question: include the &quot;return&quot; in raw 21,23.</p> <ol start="20"> <li> <pre><code> elif x&gt;nums[i]: </code></pre> </li> <li> <pre><code> return self.binary_search(nums, i+1, end, x) </code></pre> </li> <li> <pre><code> else: </code></pre> </li> <li> <pre><code> return ...
python|python-3.x
0
587
51,019,885
Using Rasa NLU model with python API instead of HTTP server
<p>Is there a way to use <a href="https://nlu.rasa.com" rel="nofollow noreferrer">https://nlu.rasa.com</a> model without the HTTP server ? I want to use it as a python library/module. </p>
<p>Yes, and this is documented in there docs at nlu.rasa.com specifically <a href="https://nlu.rasa.com/python.html" rel="nofollow noreferrer">this section</a>.</p> <p>As of version 0.12.3:</p> <p><strong>Training</strong></p> <pre><code>from rasa_nlu.training_data import load_data from rasa_nlu.config import RasaNL...
python|rasa-nlu
4
588
50,444,618
Python - MySQL "Column count doesn't match value count at row 1"
<pre><code>name = form.name.data email = form.email.data username = form.username.data password = sha256_crypt.encrypt(form.password.data) cursor = mysql.connection.cursor() cursor.execute("Insert into users(name,email.username,password) values(%s,%s,%s,%s)",(name,email,username,password)) mysql.connection.commit() ...
<pre><code>cursor.execute("Insert into users(name,email.username,password) </code></pre> <p>You have a "." instead of a "," between email and username. It should be</p> <pre><code>cursor.execute("Insert into users(name,email,username,password) </code></pre>
python|mysql|database
4
589
50,411,346
Update an Excel sheet in real time using Python
<p>Is there a way to update a spreadsheet in real time while it is open in Excel? I have a workbook called Example.xlsx which is open in Excel and I have the following python code which tries to update cell B1 with the string 'ID': </p> <pre><code>import openpyxl wb = openpyxl.load_workbook('Example.xlsx') sheet = w...
<p>I have actually figured this out and its quite simple using xlwings. The following code opens an existing Excel file called Example.xlsx and updates it in real time, in this case puts in the value 45 in cell B2 instantly soon as you run the script. </p> <pre><code>import xlwings as xw wb = xw.Book('Example.xlsx')...
python|excel|openpyxl
21
590
26,644,810
In Python how to strip dollar signs and commas from dollar related fields only
<p>I'm reading in a large text file with lots of columns, dollar related and not, and I'm trying to figure out how to strip the dollar fields ONLY of $ and , characters.</p> <p>so say I have:</p> <pre><code>a|b|c $1,000|hi,you|$45.43 $300.03|$MS2|$55,000 </code></pre> <p>where a and c are dollar-fields and b is no...
<p>Unless you are really tied to the idea of using a regex, I would suggest doing something simple, straight-forward, and generally easy to read:</p> <pre><code>def convert_money(inval): if inval[0] == '$': test_val = inval[1:].replace(",", "") try: _ = float(test_val) except: ...
python|regex
4
591
61,342,267
Removing the rows that columns don't match with the same values
<p>I have a data frame that looks like this.</p> <p>This is what I have:</p> <pre><code> V1 V2 V3 hello 0 0 nice 0 1 meeting 1 1 you 1 0 </code></pre> <p>I want to make it look like...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a> with inverted logic - get all rows with same values in both columns:</p> <pre><code>df = df[df.V2 == df.V3] </code></pre> <p>Alternative with <a href="http...
python|pandas|merge
3
592
61,196,837
Azure Blob Bindings with Azure Function (Python)
<p>I currently have a process of reading from sql, using pandas and pd.Excelwriter to format the data and email it out. I want my function to read from sql (no problem) and write to a blob, then from that blob (using SendGrid binding) attach that file from the blob and send it out. </p> <p>My question is do I need bot...
<blockquote> <p>do I need both an in (attaching for email) and an out (archiving to the blob) binding for that blob?</p> </blockquote> <p>Firstly I don't think you could bind the blob in and out simultaneously if the not existed. If you have tried you will find it will return error. And I suppose you could send th...
python|azure|azure-functions|azure-blob-storage
0
593
58,112,337
Python: Mysql Escape function generates corrupted query
<p>Python mysql default escape function, corrupts the query. Original Query string is following. It works fine and does add records to database as desired</p> <pre><code>INSERT IGNORE INTO state (`name`, `search_query`, `business_status`, `business_type`, `name_type`, `link`) VALUES ("test_name1", "test", "test_status...
<p>You can't escape <em>the entire query!</em> You can't construct a query by randomly concatenating strings and then wave a magic wand over it and make it "injection secure". You need to escape every individual value <strong>before</strong> you put it into the query. E.g.:</p> <pre><code>"INSERT ... VALUES ('%s', ......
python|mysql|python-3.x
1
594
56,265,046
error attributing items from scrapy into a database
<p>am trying to insert items scraped through scrapy into a MySQL database (create a new database if none is present before), I followed an online tutorial since I have no idea how to do this but an error keeps happening.</p> <p>am trying to store an item that contains 5 text fields into a database</p> <p>here's my pi...
<p>You defined the constructor as <code>_init_</code> instead of <code>__init__</code></p>
python|mysql|scrapy
1
595
69,568,033
How to plot lines from a dataframe with column headers as the x-axis
<p>I figure I need to do some sort of data sorting/display it differently in order to plot the graph but I'm not sure how. I have tried transposing the data set but that doesn't seem to do the trick either.</p> <p>This is my data after slicing and I need to plot W values as x axis vs the R values as y1, y2, y3, y4 and ...
<p>For each graph you need two arrays or lists x and y.</p> <p>Since x values are the same for every graph you can reuse them. You could get them from the keys of your DataFrame (assuming they are integers) like this:</p> <pre><code>x = [key for key in df.keys() if type(key) == int] </code></pre> <p>Next you need the y...
python|pandas|matplotlib|plot
2
596
55,292,876
Autostart a python program in RaspberryPi
<p>I am making a project related to RaspberryPi and Xbee, where it is essential that python program should start when i give power to RaspberryPi.</p> <p>I saw a techniqe on a udemy lecture, where it was said- sudo crontab -e A file will open. Go at the end of the file and then type @reboot sudo python3 /home/pi/mycod...
<pre><code>sudo nano /home/pi/.bashrc </code></pre> <p>Go to the last line of the script and add:</p> <pre><code>echo Running at boot sudo python /home/pi/sample.py </code></pre> <p>There are various other ways in this blog <a href="https://www.dexterindustries.com/howto/run-a-program-on-your-raspberry-pi-at-startu...
python|raspbian
1
597
57,364,349
Optionally passing parameters onto another function with jit
<p>I am attempting to jit compile a python function, and use a optional argument to change the arguments of another function call. </p> <p>I think where jit might be tripping up is that the default value of the optional argument is None, and jit doesn't know how to handle that, or at least doesn't know how to handle i...
<p>If you see the documentation <a href="https://numba.pydata.org/numba-doc/dev/reference/types.html#optional-types" rel="nofollow noreferrer">here</a>, you can specify the <code>optional</code> type arguments explicitly in Numba. For example (this is the same example from documentation):</p> <pre><code>&gt;&gt;&gt; @...
python-3.x|jit|numba
3
598
57,419,527
Why flask session didn't store the user info when making different posts to it from react?
<p>I wrote several APIs using Flask-RESTful and several react modules for testing purposes. Ideally, if I stored some info in session through a request, python should be able to detect whether there is such session even in other API entries with code, like</p> <pre class="lang-py prettyprint-override"><code>if session...
<p><code>fetch</code> does not supports cookie by default, you need to enable it using <code>credentials: 'include'</code></p> <pre><code>makePostRequest = (e: any) =&gt; { e.preventDefault() const payload = { 'email': this.state.email, 'password': this.state.password } ...
python-3.x|session|web|flask|flask-restful
0
599
57,710,512
How to store .format() print output to a var for reuse
<p>I have a list of dictionaries which i want to display using Tkinter. So far i only managed to print the desired result.</p> <p>Example code:</p> <pre><code>for x in list: for key, value in x.items(): print("{}: {}".format(key, value)) &gt;&gt;&gt;key: value key: value key: value </code></pre> <p...
<p>Looks like you need.</p> <pre><code>out = "" for x in list: for key, value in x.items(): out += "{}: {}\n".format(key, value)) print(out) </code></pre>
python|dictionary|format
2