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
5,300
40,695,874
Why int() method does not work and string is not converted into interger?
<p>I have a following piece of code:</p> <pre><code>if (sum(L) % 3) == 0: biggest_list = [] for i in range(len(L)): biggest_list.append(max(L)) L.remove(max(L)) string_l = [] for i in range(len(biggest_list)): string_l.append(str(biggest_l...
<p><a href="https://i.stack.imgur.com/H2m7w.png" rel="nofollow noreferrer">I think it's int</a></p> <p>I don't get your question in fact</p>
python|integer
0
5,301
9,788,501
Direct link to comments that are being loaded asynchronously?
<p>I am playing around with change.org and trying to download a couple of comments on a petition. For this, I would like to know where the comments are being pulled from when the user clicks on "load more reasons" For an example, look here: </p> <p><a href="http://www.change.org/petitions/tell-usda-to-stop-using-pin...
<p>They must be validating the source of the request. If you go to the site open the console and run this:</p> <pre><code>$.get('http://www.change.org/petitions/tell-usda-to-stop-using-pink-slime-in-school-food/opinions?page=2&amp;role=comments',{},function(data){console.log(data);}); </code></pre> <p>You will see th...
python|jquery|xmlhttprequest|screen-scraping|web-scraping
1
5,302
10,256,675
How do you make use of a counter with recursion in Python?
<p>I'm trying to write a simple "password" program in Python that allows 3 attempts at "logging in" with a recursive function. I can't figure out why it's not working though... (And yes, Jurassic Park inspired)</p> <pre><code>def magicWord(count): int(count) answer = raw_input("What is the password? ") if ...
<p>You were very close. There were just a couple minor fix-ups:</p> <pre><code>def magicWord(count): answer = raw_input("What is the password? ") if answer == 'lucas': print 'ACESS GRANTED' else: count += 1 if count &gt; 2: print "na na na you didn\'t say the magic word...
python|recursion|counter
2
5,303
26,169,673
Making pandas play nice with scikit-learn
<p>This is somewhat of a theoretical question. I know SO doesn't like code that isn't easily replicated, but please bear with me!</p> <p>I've got a pandas DataFrame that I want to run a Lasso regression on. To do so, the best way I know of is getting the features into a numpy array:</p> <pre><code> features = df[l...
<p>You can make a dictionary which maps <code>cols</code> to <code>coef</code>s like this:</p> <pre><code>dict(zip(cols, coef)) </code></pre> <p>This is a <a href="https://stackoverflow.com/q/209840/190597">common pure Python idiom</a>.</p>
numpy|pandas|scikit-learn
4
5,304
60,216,759
SOLVED:How can i get a decimal like 0.9 to be a percentage so the number i have goes up by 0.9 percent?
<p>I'm doing a school project and we ask the user for a population in millions and we also ask for a growth rate. The rate is a percentage, for example if the number is 0.9 the population should go up by 0.9 percent or if it was 4.31, it would go up by 4.31 percent. I am having trouble converting 0.9(decimal) to 0.9(p...
<p>You can try this.</p> <p>Let's understand what <em>x%</em> means. <em>x%</em> is <em>x parts/100parts</em>. So, 50% is 50/100. Think of it this way. Find out 50% of the given population can be written as <em>50/100=X/given_population</em>.</p> <p><em>X=(50/100)*given_population</em> here <em>X</em> is 50% of the g...
python|percentage
1
5,305
1,637,961
Deciphering Python word unscrambler
<p>I'm currently trying to dig deep into python and I have found a challenge on (hackthissite.org) that I'm trying to crack. I have to unscramble 10 words that are found in the provided wordlist. </p> <pre><code>def permutation(s): if s == "": return [s] else: ans = [] for an in permuta...
<p>The pseudocode for that looks something like:</p> <pre><code>Load the word list (dictionary) Input the words to unscramble For each word: Find every permutation of letters in that word (permutation) For each permutation: Add this permutation to the solution list if it exists in the dictionary Print the solu...
python
3
5,306
2,311,533
Empty list in App Engine Datastore: Java vs Python
<p>I have the following java model class in App Engine:</p> <pre><code>public class Xyz ... { @Persistent private Set&lt;Long&gt; uvw; } </code></pre> <p>When saving an object <em>Xyz</em> with an <strong>empty</strong> set <em>uvw</em> in Java, I get a "<strong>null</strong>" field (as listed in the appengin...
<p>It should work if you assign a default value to your Python property:</p> <pre><code>uvw = db.ListProperty(int, default=[]) </code></pre>
java|python|google-app-engine|datanucleus
2
5,307
63,009,238
Azure Functions (python) adal authentication timeout
<p>I am trying out Azure Functions with Python (linux app service plan). I have written a basic code that will authenticate my function with Azure. It uses Service principal details (set in AppSettings) via ADAL authentication. I have deployed the function via Visual Studio Code. When I run the function it runs forever...
<p>Take a look on Azure AD if you've granted the permissions for the Service Principal to retrieve the token.</p>
python|python-3.x|azure|azure-functions
0
5,308
44,222,049
ImageTk and PIL do not display png image correctly
<p>I am currently trying to write some kind of mapping tool in python using both the PIL and Tkinter module. So far almost everything works quite fine. During the setup process of the ui a virtual image is created (based upon several input png files), which also seems to have worked well. However, when trying to displa...
<p>For anyone that cares, it seems that the image was not just correctly anchored but instead fixed in the middle of the canvas.</p>
python|image|canvas|tkinter|python-imaging-library
0
5,309
32,707,560
Return result of uneven np.array multiplication and print ValueError
<p>My desired output is essentially replicating how R handles uneven vectors. Below, R proceeds to complete the operation and reports back the error.</p> <pre><code>&gt; x &lt;- c(1,2,3) &gt; y &lt;- c(4,5,6) &gt; xy &lt;- x * y &gt; xy [1] 4 10 18 &gt; y &lt;- c(4,5,6,7) &gt; xy &lt;- x * y Warning message: In x * y...
<p>This task is known as 'exception handling'. You do it in Python like so:</p> <pre><code>def vector_multiply(v, w): try: answer = np.array(v) * np.array(w) except ValueError: print "Warning: shapes didn't match" answer = #whatever you want instead return answer </code></pre>
python|r|numpy
0
5,310
32,893,568
Python breaks parsing json with characters \"
<p>I'm trying to parse json string with an escape character (Of some sort I guess)</p> <pre><code>{ "publisher": "\"O'Reilly Media, Inc.\"" } </code></pre> <p>Parser parses well if I remove the character <code>\"</code> from the string,</p> <p>the exceptions raised by different parsers are,</p> <p><strong>json<...
<p>You almost certainly did not define properly escaped backslashes. If you define the string properly the JSON parses <em>just fine</em>:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; json_str = r''' ... { ... "publisher": "\"O'Reilly Media, Inc.\"" ... } ... ''' # raw string to prevent the \" from being ...
python|json|parsing|ujson
9
5,311
34,815,193
cx_Oracle Giving DLL load failed exception
<p>I have </p> <ul> <li><strong>Oracle 11g client</strong> installed, </li> <li>64 bit Windows 7 machine,</li> <li>Python 3.4, </li> <li>cx_Oracle 64 bit installed. </li> </ul> <p>Still facing the exception <code>ImportError: DLL load failed: The specified procedure could not be found.</code> during run time.</p>
<p>First, make sure that the Oracle client, the Python installation and the cx_Oracle installation all match with each other. In your case you need to make sure they are all 64-bit and also all 11g. Second, if all of that is correct and you are still getting that error, you'll need to find out what dependency is missin...
python|cx-oracle
0
5,312
34,462,889
List index out of range while sorting in python
<p>I am trying to read a CSV file into a list and then sort it based on the first two columns of the list (first by first column and then by second column if the first column is the same). This is what I am doing:</p> <pre><code>def sortcsvfiles(inputfilename,outputfilename): list1=[] row1=[] with open(inp...
<p>You have probably an empty line in your file. Perhaps the last one. For example, you can just ignore empty lines:</p> <pre><code>def sortcsvfiles(inputfilename,outputfilename): with open(inputfilename,'rt') as csvfile: reader = csv.reader(csvfile) header = next(reader) data = [row for ro...
python|sorting|csv
3
5,313
34,844,886
scikit TfidfVectorizer.transform() returns varying results for same document
<p>I'm fairly new to <code>sckit-learn</code> and am confused because the <code>TfidVectorizer</code> is sometimes returning a different vector for the same document.</p> <p>My corpus contains >100 documents. </p> <p>I'm running:</p> <pre><code>vectorizer = TfidfVectorizer(ngram_range=(1, 2), token_pattern=r'\b\w+\b...
<p>As mentioned in a comment, it's very likely a rounding error and it's probably not worth <em>worrying</em> about.</p> <p>However I think it's worth trying to understand the phenomenon.</p> <p>What's probably happening is a rounding error. These errors sometimes happen because numbers on your computer are not of in...
python|scikit-learn
0
5,314
27,403,865
Python Scrapy unexpected indent error
<p>We're trying to crawl items such as 'product', 'price', etc. but we keep getting a indentation error.</p> <p>The code we're using (crawlproduct.py):</p> <pre><code>from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from productcrawl.items import ProductCrawlItem class MySpider(Base...
<p>With the following indentation, this is probably what you intended:</p> <pre><code>from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from productcrawl.items import ProductCrawlItem class MySpider(BaseSpider): name = "crawlproduct" allowed_domains = ["yorcom.nl"] f = ope...
python|scrapy
-1
5,315
27,029,020
Too many values to unpack using NLTK and Pandas in Python
<p>I am trying out different things to make the NLTK's naive bayes work using the NLTK and Pandas modules, but I am getting the "too many values to unpack" error.</p> <pre><code>import pandas as pd from pandas import DataFrame, Series import numpy as np import re import nltk ### Remove cases with missing name or miss...
<p>I suspect you are trying to do something bigger than name classification when using <code>panadas.DataFrame</code> because the <code>DataFrame</code> object is normally used when you have limited RAM and wants to makes use of diskspace as you iterate through the data to extract features:</p> <blockquote> <p>a 2-d...
pandas|python-2.7|machine-learning|nlp|nltk
4
5,316
23,368,941
How to unhide and show a process created with subprocess.popen()?
<p>I am trying to create a simple command-line process and show it to the user (I do NOT want the process to be hidden):</p> <pre><code>import subprocess import win32con kwargs = {} info = subprocess.STARTUPINFO() info.dwFlags |= subprocess.STARTF_USESHOWWINDOW info.wShowWindow = win32con.SW_SHOWMAXIMIZED ExecuteStr...
<p>For Windowed applications, you simply need to use the <code>SW_HIDE</code> constant instead of <code>SW_SHOWMAXIMIZED</code>.</p> <p>If you also want to cover console applications that start up a terminal window, I'm guessing that you would want to run something like this:</p> <ol> <li>start the process;</li> <li>...
python|windows|python-2.7|subprocess
0
5,317
8,260,502
Python multiple threads/ multiple processes for reading serial ports
<p>I'm trying to write a python class utilizing parallel processing/threading for reading two serial ports(/dev/ttyS1 and /dev/ttyS2). Both of these ports are running at a 19200 baud rate and are constantly active. I used pySerial for this purpose.</p> <p>Both of the read operations need to be run continuously and con...
<p>I'm not an expert on the subject in any way, but I keep on finding that the amount of additional subtleties that using <code>threading</code> requires is not worth the effort if I can parallelise via processes instead.</p> <p>A third module that you did not mention among the alternatives is <a href="http://docs.pyt...
python|multithreading|concurrency|multiprocessing
2
5,318
47,184,102
Collapse result of join's two columns into one column
<p>I'm trying to figure out a time efficient way to collapse two tables, which we commonly join together, into a single table. The tables contain readings, where table A is the table that contains the type of reading it is, and table B contains a FK to table A with the actual reading's value. Both of these tables are a...
<p>Combining (data from) two separate rows into one is what <code>JOIN</code>s are for, whether those rows come from different tables or from the same one. You can write a relatively straightforward query that produces the rows you want, such as</p> <pre><code>select a1.id as id, a1.fk_id as fk_id, a1.timestamp...
python|mysql|pivot|mariadb
2
5,319
71,087,420
Adding values in a new column conditionally in pandas dataframe
<p>I have a DataFrame like below:</p> <pre><code>ds = pd.DataFrame({'Name' : ['A','A','B','B','C', 'C', 'C', 'C'], 'Year': ['2021','2020','2020','2019','2021','2020','2020','2019' ]}) </code></pre> <p>I want to add a new column 'Breached'. The value of &quot;Breached&quot; for column Name 'A' should be 1 if the ye...
<p>Seems like you could <code>groupby</code> + transform <code>max</code> + <code>ne</code> to get a boolean Series that is True if the year is the not latest year for each group, False otherwise. Then convert this Series to int dtype:</p> <pre><code>ds['Breached'] = ds.groupby('Name')['Year'].transform('max').ne(ds['Y...
python|pandas|dataframe
1
5,320
11,644,713
Multiple consumers, is it possible to clone a queue (gevent)?
<p>I'd like to do something like that (1 queue, and multiple consumers):</p> <pre><code>import gevent from gevent import queue q=queue.Queue() q.put(1) q.put(2) q.put(3) q.put(StopIteration) def consumer(qq): for i in qq: print i jobs=[gevent.spawn(consumer,i) for i in [q,q]] gevent.joinall(jobs) </cod...
<p>I suggest you to create a greenlet to dispatch the work to consumers. Example code:</p> <pre><code>import gevent from gevent import queue master_queue=queue.Queue() master_queue.put(1) master_queue.put(2) master_queue.put(3) master_queue.put(StopIteration) total_consumers = 10 consumer_queues = [queue.Queue() for...
python|queue|gevent
2
5,321
46,901,128
Implement a 'trending' algorithm to sort a queryset of Posts
<p>I have a <code>Post</code> model for user posts, and also a <code>PostScore</code> model to track the score of that <code>Post</code> in order to sort the queryset by <code>trending</code>, similar to reddit's 'hot':</p> <pre><code>class PostScore(models.Model): user = models.ForeignKey(User, blank=True, null=T...
<p>I think it could be a good idea to use extra methods of Managers in such situations. (<a href="https://docs.djangoproject.com/en/1.11/topics/db/managers/#adding-extra-manager-methods" rel="nofollow noreferrer">https://docs.djangoproject.com/en/1.11/topics/db/managers/#adding-extra-manager-methods</a>)</p>
python|django|algorithm
0
5,322
46,714,151
Python Django Load Images based on Tab Clicked
<p>I am using bootstrap with nav-tabs to hopefully select filtered images based on the tab clicked. I can do an AJAX call to the view that I created that filters out the images based on category and returns an <code>items.html</code> template file. </p> <p>Is there a way to load the partial template without having to ...
<p>Just make ajax calls to the view and return only the required content from the server and and on ajax <strong>success</strong> replace using <strong>.html()</strong> method.</p>
javascript|jquery|python|ajax|django
0
5,323
46,666,067
Python: Dict reading did not always succeed
<p>I'm making a python script that must read a dictionary of this type</p> <pre><code>{'error': [], 'result': {'XXBTZEUR': [[1507633993, '4074.00000', '4074.90000'], [1507633994, '4074.00000', '4075.00000'], [1507634006, '4074.50000', '4075.00000'], ...
<p>The 'last' entry is not stored in the array in the 'XXBTZEUR' entry, it's it's own entry in the dictionary stored in 'result'.</p> <pre><code>result['result']['XXBTZEUR'] </code></pre> <p>gives the array as expected, to get the 'last' entry you'd have to do </p> <pre><code>result['result']['last'] </code></pre> ...
python|dictionary
0
5,324
37,895,449
How to find documents from the list by term in the query (if atleast one query term exists in the documents of list)
<p>I've list of queries and list of documents like this</p> <pre><code>queries = ['drug dosage form development Society', 'new drugs through activity evaluation of some medicinally used plants', ' Evaluation of drugs available on market for their quality, effectiveness'] docs = ['A Comparison of Urinalysis Technologie...
<p>Your code(<code>for i in query:</code>) is searching for sentence not words. To search for words, first you have to split query sentence into words.</p> <pre><code>for q in queries: for word in q.strip().split(" "): print word </code></pre> <p>Complete code:</p> <pre><code>for q in queries: for wo...
python
0
5,325
37,644,690
Enumerate list to make a new list of indices?
<p>I'm trying to make a new list of indices by enumerated a previous list. Basically, what I want is:</p> <p>To enumerate a list of elements to obtain indices for each element. I coded this:</p> <pre><code>board = ["O","O","O","O","O"] for index,y in enumerate(board): print(index,end=" ") </code></pre> <p>which ...
<p>You should probably just make a range of the right length:</p> <pre><code>board = ["O","O","O","O","O"] indices = list(range(len(board))) print(indices) &gt; [0, 1, 2, 3, 4] </code></pre>
python|enumerate
1
5,326
37,629,142
Python - My frequency function is inefficient
<p>I'm writing a function that returns the number of times appeared of a word that appeared the most in the list of words.</p> <pre><code>def max_frequency(words): """Returns the number of times appeared of the word that appeared the most in a list of words.""" words_set = set(words) words_list = word...
<p>To prevent multiple passes of your list for each unique word, you can simply iterate over it once and update dictionary values for each count. </p> <pre><code>counts = {} for word in words: counts[word] = counts.get(word, 0) + 1 </code></pre> <p><strong>Outputs</strong>:</p> <pre><code>&gt;&gt;&gt; print(max(...
python|performance|python-3.x|frequency|coding-efficiency
3
5,327
30,068,089
Getting path string from Excel in IronPython
<p>I am trying to set working directory through IronPython. Its basically for ANSYS Workbench. I am getting the directory path from excel and i am storing it in a variable in IronPython.</p> <pre class="lang-py prettyprint-override"><code>dirpath = worksheet.range["E25"].value </code></pre> <p>and I am giving this ...
<p>Assuming you are using <a href="https://msdn.microsoft.com/en-us/library/Microsoft.Office.Interop.Excel.aspx" rel="nofollow">Microsoft.Office.Interop.Excel</a> you could use one of the following statements:</p> <pre class="lang-py prettyprint-override"><code>dirpath = worksheet.Range["E25"].Text </code></pre> <p...
excel|ironpython
0
5,328
61,447,877
Python split list into several lines of code
<p>I have a list in Python which includes up to 50 elements. In order for me to easily add/subtract elements, I'd prefer to either code it vertically (each list element on one Python code line) or alternatively, import a separate CSV file?</p> <pre><code>list_of_elements = ['AA','BB','CC','DD','EE','FF', 'GG'] ...
<p>The first line should contain the first element, like this: </p> <pre><code>list_of_elements = ['AA', 'BB', 'CC', 'DD', 'EE', 'FF', 'GG'] </code></pre> <p>or as Naufan Rusyda Faikar commented: <code>Put backslash next to = Or put the left bracket next to =</code>.</p> <pre><code>list_of_elements = \ ['AA', 'BB',...
python|code-formatting
5
5,329
27,734,207
Flask with Heroku, Import Error: No module named Flask
<p>So I'm trying to create an app with Flask and Heroku. I can run it with Foreman just fine, but after deploying to Heroku, the application error comes up and the heroku logs show:</p> <pre><code>heroku[web.1]: State changed from crashed to starting heroku[web.1]: Starting process with command `python app.py` app[web...
<p>You probably need to add Flask (and any other external dependencies) to a requirements.txt and include it in your repo.</p> <p>You can use 'pip freeze > requirements.txt" to create it with what ever packages you have installed in your environment at the moment.</p>
python|heroku|flask
1
5,330
72,365,497
How to count rows where condition is false Pandas?
<p>I have a <code>NUM</code> column, I try to filter rows where column <code>NUM</code> is valid (true) and:</p> <ol> <li>Update current dataframe</li> <li>Insert count of wrong rows into dict <code>report</code></li> </ol> <p>I try this:</p> <pre><code>report[&quot;NUM&quot;] = dataset['NUM'].apply(~isValid).count() ...
<p>If you want to count the rows where <code>isValid</code> outputs False:</p> <pre><code>(~dataset['NUM'].apply(isValid)).sum() </code></pre> <p>output: <code>0</code></p> <h4>edit</h4> <pre><code>m = dataset['NUM'].apply(isValid) report[&quot;NUM&quot;] = (~m).sum() dataset2 = dataset[m] </code></pre>
python|pandas
1
5,331
43,106,573
Not sure why my loss values are increasing across epochs (linreg in tensorflow)
<p>I know, TF is overkill for this sort of problem but this is just my way of introducing myself to the syntax and TFs training process.</p> <p>Here is the code:</p> <pre><code>data = pd.read_excel("/Users/madhavthaker/Downloads/Reduced_Car_Data.xlsx") train = np.random.rand(len(data)) &lt; 0.8 data_train = data[tr...
<p>I think it is due to the shape of your cost function. Actually it can happen that the cost increases, see the answer there for a mathematical explanation: <a href="https://datascience.stackexchange.com/questions/15962/why-is-learning-rate-causing-my-neural-networks-weights-to-skyrocket">https://datascience.stackexch...
python|tensorflow|linear-regression
0
5,332
36,854,086
(String formatting) Is this what you call right justified and how do I get number to align "right justified"? Python 3.4
<pre><code>print(''' a b a**b 1 2 1 2 3 8 3 4 81 4 5 1024 5 6 15625\n''') </code></pre> <p>Alright so in the code above, if you look at the third column, the numbers are aligned by let's say a left mar...
<h2>Here is a simple fix using the <code>%</code> operator:</h2> <p>using the <code>%</code> to format a string, if you place a <code>-</code> after the <code>%</code> it will signify a left align. for your code, this would look like:</p> <pre><code>a = 1 b = 2 i = 0 for i in range(0,5): print(&quot;%10i%9i%-9i&qu...
python-3.x
1
5,333
36,808,696
Python Telegram bot too slow?
<p>I've just started to make a telegram bot in python, and I've noticed one thing with the small piece of code I did: The bot takes too long to respond. Once I send a message to my bot, it takes almost 6-8 seconds to get a reply, which is just too long in a realistic situation. I'm sure it's not my internet being too s...
<p>The problem with your code is there is no <code>timeout</code> period for your <code>getUpdates</code> method. Try setting a <code>timeout</code> of 10 seconds so that the <code>urlopen</code> will wait 10 seconds for a new update before sending another request. </p> <p>Below is the edited code.</p> <pre><code>fro...
python|bots|telegram|telegram-bot
1
5,334
48,848,919
file cannot be executed in command line using Python
<p>I am a beginner to python and I have a txt file which contains list of URLs, and when I want to scan the txt file, I got error in the last which says KeyboardInterrupt. This is my code<br> if <strong>name</strong> == "<strong>main</strong>":</p> <pre><code># Directory that contains panafapi.py SCRIPT_DIRECTORY ...
<p>I think the issue is you redirect output to a path which doesn't exist</p> <pre><code>/Users/kiya/Desktop/result/result767_http://blogimg.goo.ne.jp/.json </code></pre> <p>try a simple filename like</p> <pre><code>/Users/kiya/Desktop/result/result767_blogimg.goo.ne.jp.json </code></pre>
python|data-analysis
0
5,335
48,881,901
Dataframe to Time Series when minutes are repeated
<p>I'm working with clinical data and want to make predictions of patients' waiting time at every minute, and the data (simplified) looks something like this: </p> <pre class="lang-none prettyprint-override"><code>Time(minutes) PatientSerial RemainingTime(minutes) 420 1 5 420...
<p>For clarity: This is not an answer but asking how the result should look like (not able to show the view in comment underneath question). This may help to get a better understanding how this question should be solved. <strong>Edit1: Coded answer is below</strong>.</p> <p>@Ted:</p> <p>I would like to know if the re...
python|dataframe|machine-learning
0
5,336
48,655,518
How to use the RST module in Kivy?
<p>I'm creating a fitness/nutrition app in Kivy. The problem is that most of the screens involve text for the viewer to read and I don't want the text to be just plain old text like that of a .txt file. I tried looking for something and I found there is a RST rendering module that will make my text look good but after ...
<h1>How to use RST Document in Kivy?</h1> <p>Rreference: <a href="https://kivy.org/docs/api-kivy.uix.rst.html" rel="nofollow noreferrer">reStructuredText renderer</a></p> <h2>Reading text from an input File:</h2> <h3>1. Create an input File - inFile.txt</h3> <p>Create a file called "inFile.txt" with the following t...
python|kivy|kivy-language
0
5,337
67,108,896
Python web scraping, using html-requests to find a specific element and extract text
<p>I am using python for webscraping (new to this) and am trying to grab the brand name from a website. It is not visible on the website but I have found the element for it:</p> <p><code> &lt;span itemprop=&quot;Brand&quot; style=&quot;display:none;&quot;&gt;Revlon&lt;/span&gt;</code></p> <p>I want to extract the &quot...
<p>Here is a working solution with Selenium:</p> <pre><code>from seleniumwire import webdriver from webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(ChromeDriverManager().install()) website = 'https://www.boots.com/revlon-colorstay-makeup-for-normal-dry-skin-10212694' driver.get(website...
python|html|web-scraping|python-requests
3
5,338
67,054,516
How could I install Tensorflow Object Detection on a Mac?
<p>I'm a bit stuck I'm following a tutorial for object detection and I couldn't install Tensorflow Object Detection on my virtual environnement I tried this code without success. There is probably a better solution but I didn't find a way to solve my problem.</p> <pre><code>!move protoc-3.15.8-osx-x86_64.zip {paths['PR...
<p>I was finally able to install it with another method found on Medium <a href="https://medium.com/@viviennediegoencarnacion/how-to-setup-tensorflow-object-detection-on-mac-a0b72fbf470a" rel="nofollow noreferrer">https://medium.com/@viviennediegoencarnacion/how-to-setup-tensorflow-object-detection-on-mac-a0b72fbf470a<...
python|macos|tensorflow|computer-vision|object-detection
1
5,339
48,048,072
PYTHON PACKAGE ISSUES: Can't import __init__.py
<p>My hierarchy is this:</p> <pre><code>Main_Directory/ Package/ __init__.py a.py(containing class a) b.py(containing class b) path.py test.py </code></pre> <p><strong>__init__.py</strong></p> <pre><code>print(IN init) from a import a from b import b print(DONE) </code...
<p>Add a dot before each module in <code>__init__.py</code>'s import statements. This specifies relative import:</p> <pre><code>from .a import a from .b import b </code></pre> <p>Alternatively specify an absolute import using the package name:</p> <pre><code>from package.a import a from package.b import b </code></p...
python|python-3.x
0
5,340
48,117,803
Hack python code
<p>I always heard that python was a language that was friendly to monkey patching... well now i need to monkey patch and know not what to do.</p> <p>I specifically need to disable the 'raising' of a parsing exception to see if a iso parsing library behaves. It's not so simple, because i'm using libmirage (which is a c...
<p>Well since there is no way to do this without forking i guess the best way is to either clone the repo with git and use pip -e ~/fork to install a modified version (or maybe just copy the repo to the local dir since it's pure python) or convince the upstream to be more permissive during parsing.</p> <p>I did both....
python|exception|monkeypatching
0
5,341
64,379,460
Can I use webhooks to create a log of when certain actions were taken?
<p><strong>Problem</strong>: Habitica is a habit-tracking app, but its personal data logs are not as detailed as I want. I want to create a local log of when I mark off habits/todo's in the app. Habitica offers certain webhooks that trigger when habits/todo's are checked off, which seems perfect for what I want, but ho...
<p>Creating the Habitica webhook as Flask application is a good approach.<br /> Heroku supports Python/Flask very nicely however the file system is ephemeral, hence it gets wiped out at every application restart.</p> <p>In order to persist data you can look at various options:</p> <ul> <li>save the file to <a href="htt...
python|heroku
0
5,342
69,801,005
Failing to match the required number of dimensions for Keras LSTM model
<p>I have tried to set up a bare minimum example for building a neural network. I got 5 prices for a car over 5 different dates. No matter how I rearrange my data, I get 1 out of 2 types of errors.</p> <p>Either</p> <pre><code>ValueError: Input 0 of layer sequential is incompatible with the layer: expected ndim=3, foun...
<p>As explained in the <a href="https://keras.io/api/layers/recurrent_layers/lstm/" rel="nofollow noreferrer">keras documentation</a> the required input shape is <code>(batch, timesteps, features)</code>. In your case this is <code>(5, 1, 1)</code> since <code>batch=5</code>, <code>timesteps=1</code> and <code>features...
python|tensorflow|keras|lstm|recurrent-neural-network
0
5,343
72,890,339
Using pandas to concatenate strings of multiple row by column?
<p>I want use the first 5 rows of my data frame and concentrate the string to form a new index.</p> <p>Doing some research i think groupby with agg and lambda will work. What would be the best way to accomplish this? I am new to python.</p> <p>For example my current data frame:</p> <p>Dataframe (df):</p> <div class="s-...
<p>you don't need to use <code>.groupby()</code> or <code>lambda</code>. Simply use <code>.agg(sum)</code> on the first n-th rows to get concatenate the strings.</p> <p>first step, get the slice:</p> <pre><code>slc = df.iloc[:4,:] </code></pre> <p>use <code>.agg(sum)</code> to aggregate the strings in one row.</p> <pre...
python|pandas|dataframe
1
5,344
66,570,323
How to simplify GPIO configuration of esp32 in python?
<p>Another simplify question. How can I simplify this. I was searching in the internet for the machine module but there wasn't shown that I can configure more than one GPIO per line. I think it should be possible to configure all the GPIOs in one line but I just don't know how. The GPIOs are from an esp32. And don't bl...
<p>You can try this in a module:</p> <pre><code>import sys module = sys.modules[__name__] for idx, pin in enumerate([15, 2, 4]): setattr(module, 'GND_%s' % idx, Pin(pin, Pin.OPEN_DRAIN)) </code></pre>
python|esp32|simplify
0
5,345
64,957,662
CPython Memory Heap Corruption Issue
<p>I have a <code>Windows fatal exception: code 0xc0000374</code> - yes there's multiprocessing (wait for the but...). Google says that the exception code 0xc0000374 indicates a heap corruption. Yes, multiprocessing is a must-have. It's apart of the framework I'm working in, as each bot has the potential to have its ow...
<p>The bug is most likely in this line of <code>method_ground_shot_is_viable</code>:</p> <pre><code> return (shot_viable) ? Py_True : Py_False; </code></pre> <p>Functions registered using <code>PyMethodDef</code> must return a <a href="https://docs.python.org/3/c-api/intro.html#reference-count-details" rel="nofollow...
python|c|python-3.x|cpython
3
5,346
63,872,899
How do I display a matching element equal to a given value in a dataframe with pandas?
<p>I am trying to display the name of a country by searching for the biggest difference between the amount of Gold in &quot;Gold&quot; and the amount of Gold in &quot;Gold.1&quot;. Now I am unsure how to display the name of the country (column 1) when calculating this difference.</p> <pre><code>def answer_two(): for co...
<p>Here's an example that would assist in answering your question. This (<code>idxmax()</code>) will return the index of the greatest value in a Series, which as you can see in this case is the difference between columns <code>one</code> and <code>two</code>.</p> <pre class="lang-py prettyprint-override"><code>import p...
python|pandas|dataframe
0
5,347
63,787,301
Is there a way to create combinations that preserve the order of elements in a list?
<p>I have a function that supplies me with a list of lists. The length of the list corresponds to the length of the combination, while the length of the sublist corresponds to the different letters that can be used in that position. So, for instance the expected combinations for this list <code>[['W'], ['I'], ['C', 'J'...
<p>I think what you're looking for is product (short for Cartesian product) which is in the itertools module. You can read about it <a href="https://docs.python.org/2/library/itertools.html#itertools.product" rel="nofollow noreferrer">here.</a></p> <p>Here is the sample code:</p> <pre><code>import itertools as it data ...
python-3.x|combinations
1
5,348
65,379,269
python else statement confusion
<p>I am new to python programming. I am a little confused in the below code, how else statements work without corresponding if statement. Could anyone please explain to me the below code. Program is Prime number between two intervel.</p> <pre><code>start=int(input(&quot;Enter Number: &quot;)) stop=int(input(&quot;E...
<p>In Python, <a href="https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops" rel="nofollow noreferrer">loops can have an <code>else</code> statement</a>. However, think more of a try-except statement than a if clause.</p> <p>An example:</p> <pre><code>for item in c...
python|if-statement
0
5,349
62,810,395
how to convert timeseries ranking table to individual rank table in pandas dataframe python
<p>for example, ranktable is</p> <pre><code>time/rank 1 2 3 1 a b c 2 b c a </code></pre> <p>and I want convert this to individual rank by time</p> <pre><code>time/individual a b c 1 1 2 3 2 3 1 2 </code></pre> <p>with pandas dataframe, code is below..</p> <pre...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.melt.html" rel="nofollow noreferrer"><code>DataFrame.melt</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html" rel="nofollow noreferrer"><code>DataFrame.pivot</code></a>:...
python|pandas|dataframe|time-series
1
5,350
62,661,961
how can i click the button if the xpath has changed somehow
<p>here is the code: Gen_enemy = driver.find_element_by_class_name('kt-callout__action')</p> <pre><code>for i in range(5): time.sleep(y) Gen_enemy.click() time.sleep(y) driver.find_element_by_xpath('/html/body/div[6]/div/div[3]/button[1]').click() time.sleep(b) driver.find_element_by_xpath...
<p>I've had this problem once and the solution for me was to declare the object again, because the class was updated.</p> <p>Here is the solution I've used.</p> <pre><code>campo_de_comentário = driver.find_element_by_class_name(&quot;Ypffh&quot;) campo_de_comentário.click() campo_de_comentário = driver.find_element_by_...
python|python-3.x|selenium|selenium-webdriver|selenium-chromedriver
0
5,351
71,345,394
Save, Recover, and Continue Updating Learning Curves while Training a CNN if Server Crashes Suddenly
<p>I am training a deep learning model with TensorFlow on a remote server. The problem is that I am only allocated 2 hours of training at a time and the server may crash at any points for various reason.</p> <p>I know the training of my model will take me at least 48 hours to complete. I would like to be able after the...
<p><strong>Tensorboard is automatically archeive</strong> or you can <strong>reset</strong> it but you can do logging file with the text format where these values indicates or using summary.</p> <ol> <li><p><strong>history</strong> = model.fit(batched_features, epochs=1 ,validation_data=(batched_features) callbacks=[cu...
python|tensorflow|deep-learning|custom-training
0
5,352
56,755,288
How to append values to existing comma delimited csv (excel) file
<p>I have an existing CSV-file with 4 columns (comma delimited, so all values in one column in excel) <a href="https://i.stack.imgur.com/olOB6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/olOB6.png" alt="enter image description here"></a></p> <p>How do I write a code to add for example the value...
<p>Because of the mixed type of the array, you need to specify the formatter when flushing into a file:</p> <p>Try:</p> <pre><code>np.savetxt("testfile.csv", combined, fmt='%s',delimiter=",") </code></pre> <p>Every entry gets casted as a string before writing.</p> <p>To solve the issue in the comments:</p> <pre>...
python|excel|xlsxwriter|openxlsx
0
5,353
60,879,962
Add object to an existing lattice deformer Maya
<p>I’m currently stuck with as silly problem.</p> <p>I’m writing a re-build script for one of the characters and I need to write a command in python Maya to add a model to already existing lattice deformer. Is there a way to do this? I know that if I were to do it manually, I could add new object via deformer set, are...
<p>here you go :</p> <pre><code>mySel = ['objectName'] deformer = 'latticeName' myLatticeSet = cmds.listConnections( deformer, type=&quot;objectSet&quot; ) cmds.sets( mySel, add= myLatticeSet[0] ) </code></pre>
python|maya|lattice|pymel
1
5,354
68,368,700
Filter | Groupby | Aggregate
<p>I am doing some task in pandas python.</p> <p>I have a data like this:</p> <pre><code>col1 |col2 |col3 |col4 |col5 | col6 delhi |assam |&quot;f&quot; |78.3 |87.1 | B2C delhi |goa |&quot;f&quot; |78.3 |87.1 | B2C delhi |goa |&quot;f&quot; |78.3 |87.1 | B2C delhi |assam |&quot;f&quot; |78.3 |87.1 | B2C up ...
<p>IIUC, here's one way:</p> <pre><code>df = df.groupby(['col1', 'col2', 'col3','col6'], sort=False).sum().reset_index() </code></pre> <p><em>NOTE:</em> If you just wanna perform aggregation where value in <code>col6</code> is eq <code>('B2C')</code> :</p> <pre><code>df = pd.concat([df[df.col6.eq('B2C')].groupby(['col1...
python|pandas|pandas-groupby|aggregate
3
5,355
59,223,108
How to initialize or change a dataframe according to my index length?
<p>I have an index that looks like:</p> <pre><code>MyIndex 11 12 13 </code></pre> <p>and a dataframe which might be longer than my index: (they could be equal under some situations)</p> <pre><code>OldIndex c1 0 00 1 01 2 02 3 03 4 04 </code></pre> <p>I want to fit the dataframe in...
<p>simple way to do it would just be this...</p> <p>assuming you have: </p> <pre><code>df1 = pd.DataFrame(index=[0,1,2]) df2 = pd.DataFrame({'c1':[1,2,3,4,5]},index=[0,1,2,3,4]) df1['c1'] = df2['c1'].values[:len(df1.index)] </code></pre> <p>output:</p> <pre><code>&gt;&gt;&gt; df1 c1 0 1 1 2 2 3 </code></pr...
python|pandas
0
5,356
25,027,093
Django, REST: Serialize a text or image file to post via HTTP in JSON
<p><strong>Running</strong>:Windows 7, Python 3.3. Django 1.6</p> <p><strong>Background</strong>: I'm created an app in Django using the REST framework, that accepts HTTP 'POST' requests with JSON descriptions of objects in the body and creates records in a SQL databse from those 'POST' requests. Most of the fields o...
<p>Yeah you could encode the images using base64 and just post them in the request but it's a bit of a hack. If you just save the base64 to the database then you will end up with a huge database which is bad. </p> <p>There is a snippet here that uses base64 on the wire but saves as an ImageField: </p> <p><a href="htt...
python|json|django|rest|serialization
3
5,357
42,659,307
Pyspark calculate custom distance between all vectors in a RDD
<p>I have a RDD consisting of dense vectors which contain probability distribution like below</p> <pre><code>[DenseVector([0.0806, 0.0751, 0.0786, 0.0753, 0.077, 0.0753, 0.0753, 0.0777, 0.0801, 0.0748, 0.0768, 0.0764, 0.0773]), DenseVector([0.2252, 0.0422, 0.0864, 0.0441, 0.0592, 0.0439, 0.0433, 0.071, 0.1644, 0.0405...
<p>As far as I know there isn't a function for doing cosine similarities between rows. So you will have to be a little tricky to get where you want.</p> <p>First create pairs of rows in a column format by using <a href="http://spark.apache.org/docs/2.1.0/api/python/pyspark.html?highlight=cartesian#pyspark.RDD.cartesia...
python|pyspark|rdd|similarity
6
5,358
65,727,371
Get all documents from mongo collection using a nested list comprehension in Python
<p>I have a python list of mongo documents called <code>id_list</code> which contains a field called <code>userId</code>, and a mongo collection of user transactions called <code>collection</code>. I want to retrieve all the transactions in the collection for each user by passing the id of each user in <code>id_list</c...
<p>I finally got it by doing this:</p> <pre><code>[doc for doc in collection.find({'userId': {'$in': id_list}, 'site': SITE, 'operator': OPERATOR, 'isTrue': {'$exists': True}})] </code></pre> <p>Instead of passing each id in the list one by one to the mongo query, i used the <code>$in</code>operator, and passed it the ...
python|mongodb|list|python-2.7|list-comprehension
0
5,359
51,106,763
County boarders in Cartopy
<p>How do you plot US county borders in Cartopy?</p> <p>It's very straight forward to plot state and country boundaries</p> <pre><code>ax.add_feature(cfeature.BORDERS.with_scale('50m')) ax.add_feature(cfeature.STATES.with_scale('50m')) </code></pre> <p>But I can't seem to find a similar method to add county boundari...
<p>Given cartopy's ability to draw shapefiles, this question essentially boils down to "where can I find US county outlines?".</p> <p>A similar question was asked on the Natural Earth forum at <a href="http://www.naturalearthdata.com/forums/topic/u-s-county-shape-file/" rel="noreferrer">http://www.naturalearthdata.com...
python|cartopy
11
5,360
61,431,090
How to get all the questions asked by a specific user from the Stack Exchange API?
<p>I'm trying to get all the questions with details from Stack Exchange API for a given user ID using following code:</p> <pre><code>response = requests.get("http://api.stackexchange.com/2.2/users/2593236/questions?") </code></pre> <p>However, I receive this error message.</p> <pre><code>{"error_id":400,"error_messa...
<p>To download all questions or answers from a specific user and stack, you can use:</p> <pre><code>import requests, traceback, json all_items = [] user = 2593236 stack = "stackoverflow.com" qa = "questions" # or answers page = 1 while 1: u = f"https://api.stackexchange.com/2.2/users/{user}/{qa}?site={stack}&amp...
python-3.x|python-requests|stackexchange-api
1
5,361
69,606,879
Trouble scraping with scrapy
<p>Here is my code guys, to explain first of all I scraped listing links, then I yielded response to go through every link of a listing and then parse some info e.g name,address,price,number. While running it in terminal I get some errors such as (price = response.css('div.article_right_price::text').get().strip() ...
<p>The error you are getting is not <code>scrapy</code> related. You are calling method <code>strip()</code> on a <code>None</code> object. Your selectors are returning <code>None</code> instead of the string value you are expecting. Check your selectors again and also consider using <a href="https://docs.scrapy.org/en...
python|web|scrapy
0
5,362
54,136,086
Convert list to dictionary by setting fixed length
<p>I have a list <code>data=['CDs', 1, 'J12345','Rainbow', None, 'Styles', 2, 'J12345', 'Rainbow', None, 'Folk', 3, 'J12345', 'Rainbow', None]</code> I would like to convert it to a pandas dataframe with fixed number of columns. </p> <p>The result expected to be like:</p> <pre><code>category | num | series | title...
<p><strong><em>Setup</em></strong></p> <pre><code>num_cols = 5 cols = ['category', 'num', 'series', 'title', 'brand'] </code></pre> <hr> <h3><code>numpy.reshape</code></h3> <pre><code>d = np.reshape(data, (-1, num_cols)) pd.DataFrame(d, columns=cols) </code></pre> <p></p> <pre><code> category num series ti...
python|pandas|list|dictionary|dataframe
4
5,363
28,839,182
Sorting dictionary by value and lexicographical
<p>I have a dictionary : {'a':10,'b':20,'c':5,'d':5,'e':5} and want to get that</p> <pre><code> b 20 a 10 c 5 d 5 e 5 </code></pre> <p>sorting by value and if i have a equality by value - it must be sorting lexicographically. </p> <p>Note: using python 2</p>
<p>To match the actual output you want you have to use two keys to sort negating the int value with <code>-</code>:</p> <pre><code>d = {'a':10,'b':20,'c':5,'d':5,'e':5} for k,v in sorted(d.items(),key=lambda x:(-x[1],x[0])): print("{} {}".format(k,v)) </code></pre> <p>Output:</p> <pre><code>b 20 a 10 c 5 d 5 e ...
python|sorting
5
5,364
57,084,723
Enumerating columns of large data using NumPy
<p>I have a large data, and I want to name the columns, for instance '1', '2', ... . For a small data, I can do</p> <pre><code>np.random.randint(5, size=(50, 2)) # synthesis data A = A.ravel().view([('1','i8'),('2','i8'),]).astype([('1','i4'),('2','i8'),]) </code></pre> <p>and then call an individual column using</...
<p>Extending from your work, you can use a list comprehension to accomplish this. It will automatically create the required number of columns with the proper labels:</p> <pre><code>A = np.random.randint(5, size=(10, 10)) B = A.ravel().view([ (str(x),'i4') for x in range(1, len(A[0])+1) ]) </code></pre> <p>Then you ca...
python|numpy
3
5,365
40,815,617
how do you add up the output of the first integers in every lists?
<p>I have these five lists in which i want to get the values of each place added up. For example, if my list is:</p> <pre><code>[0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1] [0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0] [1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1] [1, 1, 1...
<p>Put them into a 2D list, transpose it with <code>zip</code>, <code>map</code> it to <code>sum</code>, and send it to <code>list</code> to evaluate that lazy object (<code>list()</code> call not needed in Python 2, as it returns a list already).</p> <pre><code>&gt;&gt;&gt; l = [[0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0...
python|list|python-3.x|indexing
4
5,366
38,159,745
Indentation affecting program in Sage
<pre><code>k=10 l=1 o=2 F=IntegerModRing(k) R.&lt;t&gt;=F[] K.&lt;x&gt;=R.quotient(t^o-1) poly=((x+l)^k)-(x^k)-l m=poly.list() if(m!=0): print k </code></pre> <p>This gives output 10 as it should</p> <pre><code>k=10 o=2 l=1 F=IntegerModRing(k) R.&lt;t&gt;=F[] K.&lt;x&gt;=R.quotient(t^o-1) poly=((x+l)^k)...
<p>The 'if' statement should not be indented. It won't run in the second example. In Python, there are strict rules in indentation. You can only indent if a new code block is started. The statement before the 'if' statement needs to be a loop statement, a conditional statement, or a function/class definition.</p>
python|sage
1
5,367
36,489,284
GAE cron retry parameters
<p><a href="http://i.stack.imgur.com/vsIdV.png" rel="nofollow">GAE page</a></p> <p>As suggested by GAE, I have added the retry parameter as(copied from the GAE website):</p> <pre><code> - retry_parameters min_backoff_seconds: 2.5 max_doublings: 5 </code></pre> <p>But when I'm trying to deploy my pr...
<p>Remove the hyphen from <code>retry_parameters</code>. Also, the parameters to <code>retry_parameters</code> should be indented by one more level.</p> <pre><code>cron: - description: daily reports and exports url: /admin/reports/reportsdaily schedule: every 10 mins retry_parameters: min_backoff_seconds: 2....
python|google-app-engine|cron
3
5,368
19,648,263
Why does Emacs get my literal Unicode strings wrong?
<p>As far as I know, these should be equivalent in a system that uses UTF-8 as the default encoding:</p> <pre><code>pattern1 = 'Wörterbuch Wortformen'.decode('utf8') pattern2 = u'Wörterbuch Wortformen' </code></pre> <p>However, when I send these lines from an Emacs buffer to the Python process (<code>M-x python-shell...
<p>It turns out that it was a <a href="http://lists.gnu.org/archive/html/help-gnu-emacs/2013-10/msg00488.html" rel="nofollow">bug</a> in <code>python.el</code>.</p>
python|emacs|unicode
1
5,369
54,288,421
Classifier for time based data to binary label
<p>I have access to a dataframe of 100 persons and how they performed on a certain motion test. This frame contains about 25,000 rows per person since the performance of this person is kept track of (approximately) each centisecond (10^-2). We want to use this data to predict a binary y-label, that is to say, if someon...
<p>Yes it definitely is feasible and also very common. Search for any document classification tasks (e.g. sentiment) for examples of this kind of tasks.</p>
python|machine-learning|neural-network|recurrent-neural-network
1
5,370
34,056,184
Attaching a location value to a list when printed
<p>So i have a adventure game and i created a list of locations</p> <pre><code>rooms = [ "You are in the garden. Darkness everywhere.", "You are in the bathroom. You sound some noise.", "You are in the hall. You almost fall. Stairs east", "You are in the kitchen. You can hear voices.", ...
<p>Use the <code>enumerate</code> function.</p> <pre><code>for i,description in enumerate(rooms): print(i, description) </code></pre>
python|python-3.x
1
5,371
34,103,338
issue in writing data from 2 RDDs (one with unicode data and one with normal )into a csv file in PySpark?
<p>I have two <code>RDD's</code>:</p> <p><strong>RDD1:</strong> data in <code>RDD1</code> is in unicode format</p> <pre><code>[[u'a',u'b',u'c'],[u'c',u'f',u'a'],[u'ab',u'cd',u'gh']...] </code></pre> <p><strong>RDD2:</strong></p> <pre><code>[(10.1, 10.0), (23.0, 34.0), (45.0, 23.0),....] </code></pre> <p>Both the <...
<p>If by local you mean driver file system then you can simply <code>collect</code> or convert <code>toLocalIterator</code> and write:</p> <pre><code>import csv import sys if sys.version_info.major == 2: from itertools import izip else: izip = zip rdd1 = sc.parallelize([(10.1, 10.0), (23.0, 34.0), (45.0, 23.0...
python|csv|apache-spark|pyspark|rdd
2
5,372
27,091,167
Show viewMap until user close it
<p>I would like to start a common intent ( <code>android.viewMap()</code> ) with waiting until the user close the activity. I cannot determine the correct parameters to these functions:</p> <pre><code>mapIntent = droid.makeIntent("android.intent.action.RUN", droid.viewMap(dic["latitude"]+","+dic["longitude"])) droid.s...
<p>I managed to solve the problem.</p> <pre><code>mapIntent = droid.makeIntent("android.intent.action.PACKAGE_FIRST_LAUNCH", str(droid.viewMap(dic["latitude"]+","+dic["longitude"]))) droid.startActivityIntent(mapIntent, True) </code></pre>
python|android-intent
0
5,373
48,802,454
How to use class and self here to get two different entries?
<p>With my current code, it does not matter whether I click on "Input Folder" - Change or "JukeBox" change the result always gets displayed in "JukeBox" entry. This is incorrect, using class and self how can I change the code to display result from "Input Folder" - Change in "Input Folder" entry and the result from "Ju...
<p>Your code has both:</p> <pre><code>entry = Entry(frametop, width=50, textvariable=inPut_dir) entry.grid(row=5,column=4,padx=2,pady=2,sticky='we',columnspan=20) </code></pre> <p>and</p> <pre><code>entry = Entry(frametop, width=50, textvariable=jukeBox_dir) entry.grid(row=6,column=4,padx=2,pady=2,sticky='we',column...
python|class|tkinter|self
1
5,374
46,368,027
convert list of keys to nested dictionary
<p>I'm trying to figure out how to create, for example, a dictionary that looks like this: <code>d[keys[0]][keys[1]][keys[2]]</code> from a list like this : <code>keys = ["key1", "key2", "key3"]</code> ... </p> <p>I've tried the following: </p> <pre><code> keys = ["key1", "key2", "key3"] d = {} d_ref= d for ke...
<p>Just a simple for-loop should do the trick</p> <pre><code>&gt;&gt;&gt; d = {} &gt;&gt;&gt; for k in reversed(keys): ... d = {k: d} ... &gt;&gt;&gt; d {'key1': {'key2': {'key3': {}}}} </code></pre> <p>(<strong><em>edit</strong>:</em> <em>OP changed the question after posting</em>) Should you want a list ...
python|dictionary
7
5,375
46,472,809
Python: Binning based on 2 columns in Pandas
<p>Looking for a quick and elegant way to bin based on 2 columns in Pandas. </p> <p>Here's my data frame</p> <pre><code> filename height width 0 shopfronts_23092017_3_285.jpg 750.0 560.0 1 shopfronts_200.jpg 4395.0 6020.0 2 shopfronts_25092017_eateries_...
<p>You can use dual <code>pd.cut</code> i.e </p> <pre><code>bins = [0,400,640,800,np.inf] df['group'] = pd.cut(df['height'].values, bins,labels=["g1","g2","g3",'g4']) nbin = [0,300,480,600,np.inf] t = pd.cut(df['width'].values, nbin,labels=["g1","g2","g3",'g4']) df['group'] =np.where(df['group'] == t,df['group'],'ot...
python|pandas|pandas-groupby|binning
8
5,376
46,224,384
Error message "Nontype object has no get attribute"
<p>I retrieved some data using API and tried extracting the country code using this python script but got an error message:</p> <blockquote> <p>Nonetype object has no get attribute. </p> </blockquote> <p>The data is in a JSON file. Here is my code:</p> <pre><code>country_code=[data.get("sys").get("country") for da...
<p>If you <code>.get('key-x')</code> from a dict that does not contain <code>'key-x'</code> None will be returned. You can change this behaviour by specifying <code>.get('key-x', default_return_value)</code> where <code>default_return_value</code> is a variable whose value you would like to return from the invocation g...
python|json|dictionary
1
5,377
49,560,664
Error when opening .mat file in python
<p>I'm trying to open a MATLAB file which is an 'array of structures'. When using scipy.io.loadmat to open the file, I get the following error:</p> <pre><code>File "&lt;ipython-input-15-0951b80baef6&gt;", line 1, in &lt;module&gt; data = sio.loadmat('C:\Users\Martin\Desktop\Biophysics PhD\Results\180321_agonists_s...
<p>This error is most likely happening because <code>scipy.io.loadmat</code> cannot find the file of interest. Because you're using Windows, the path you're defining is not quite correct. You need to delineate the directory separator <code>\</code> with two backslashes: <code>\\</code>.</p> <p>In other words:</p> <...
python|matlab|io|scipy
7
5,378
49,393,805
Get random items from range of list
<p>Let's say I have a unsorted set of items:</p> <pre><code>input = set([45, 235, 3, 77, 55, 80, 154]) </code></pre> <p>I need to get random values from this input but in a specific range. E.g. when I have </p> <pre><code>ran = [50, 100] </code></pre> <p>I want it to return either 77 or 55 or 80. What's the fastest...
<p>Using a <code>set</code> for this isn't the right way because elements aren't sorted. This would lead to a <code>O(N)</code> solution to test each element against the boundaries.</p> <p>I'd suggest to turn the data into a sorted list, then you can use <code>bisect</code> to find start &amp; end indexes for your bou...
python|algorithm|random
6
5,379
49,357,552
Generate k random list from a list of elements possibly containing sublist
<p>I have a list <code>l</code> in the following form. I need to randomly generate <code>k</code> (six in this example) number of lists from this list so that only one element is selected from the sublists at a time. </p> <pre><code>l = [1,2,3,[11,22,33,44], 4,5,6, [22,33,44], 5, [99,88]] Result: 1,2,3, 22, 4,5,6, ...
<p>The key function to use is <code>choice</code> from the <code>random</code> module, which randomly selects a value from any iterable object with a known size. All such objects have a <code>__getitem__</code> method as well as a <code>__len__</code> method (both of which are needed to apply the <code>choice</code> fu...
python|random
1
5,380
53,546,330
attributeError: 'list' object has no attribute.....
<p>I am getting attributeError, but I don't understand.... </p> <pre><code>class User(): def __init__(self, first, last, age): self.first = first self.last = last self.age = age self.login_attempt = 0 class Admin(User): def __init__(self, first, last, age): super().__...
<p>You're assigning a list to <code>sarah.privilages</code>, so it surely does not have a <code>show_privilages</code> method. You should make the <code>__init__</code> method of <code>Admin</code> take a list of privileges as a parameter, so it can pass on to the <code>__init__</code> method of <code>Privilages</code>...
python|list|attributeerror
3
5,381
46,096,074
Regex to Match Horizontal White Spaces
<p>I need a regex in Python2 to match only horizontal white spaces not newlines.</p> <p><strong><code>\s</code></strong> matches all whitespaces including newlines.</p> <pre><code>&gt;&gt;&gt; re.sub(r&quot;\s&quot;, &quot;&quot;, &quot;line 1.\nline 2\n&quot;) 'line1.line2' </code></pre> <p><strong><code>\h</code></st...
<p>I ended up using <strong><code>[^\S\n]</code></strong> instead of specifying all Unicode white spaces.</p> <pre><code>&gt;&gt;&gt; re.sub(r&quot;[^\S\n]&quot;, &quot;&quot;, u&quot;line 1.\nline 2\n\u00A0\u200A\n&quot;, flags=re.UNICODE) u'line1.\nline2\n\n' &gt;&gt;&gt; re.sub(r&quot;[\t ]&quot;, &quot;&quot;, u&q...
regex|python-2.7|unicode|python-unicode
14
5,382
54,954,141
Pandas - remove rows based on two conditions
<p>I have a pandas dataframe like this -</p> <pre><code>ColA ColB ColC Apple 2019-03-02 18:00:00 Saturday Orange 2019-03-03 10:00:00 Sunday Mango 2019-03-04 09:00:00 Monday </code></pre> <p>I am trying to remove rows from my dateframe based on ce...
<p>Seems it is harder than what I thought </p> <pre><code>s1=df.ColB.dt.hour.between(9,17,inclusive=False) df.loc[s1|df.ColC.isin(['Saturday','Sunday'])] ColA ColB ColC 0 Apple 2019-03-02 18:00:00 Saturday 1 Orange 2019-03-03 10:00:00 Sunday </code></pre> <hr> <p>Or using </p> <pre><...
python|pandas
2
5,383
54,706,007
Pandas: fill in a dataframe column with a serie starting at a specifc index
<p>My dataframe looks like this:</p> <pre><code> time price 0 2019-02-01 00:07:00 0.00234135 1 2019-02-01 00:10:15 0.0023541 2 2019-02-01 00:13:30 0.00235838 3 2019-02-01 01:03:00 0.00236977 4 2019-02-01 01:07:00 0.00237751 </code></pre> <p>What I did after was to compute...
<p>Converting to <code>Series</code> with not defined index is not good idea, because possible not aligment between new <code>Series</code> and old index:</p> <pre><code>df.loc[18:, 'macd'] = macd[18:] </code></pre> <p>Solution with <code>pd.Series</code>:</p> <pre><code>df.loc[18:, 'macd'] = pd.Series(macd, index=d...
python|pandas
0
5,384
73,605,563
Infinite loops in multiprocessing python
<p>How do I get the notworking() to work in mulitprossesing. My console is only logging whyisthis(). I am new to multiprosessing, and I am just not getting this, so I hope someone will give an easy solution.</p> <pre><code>from multiprocessing import Process def whyisthis(): while True: print(f'Why is this'...
<p>The problem with your code lies here:</p> <pre><code>p1 = Process(target=whyisthis(), daemon=False, name=&quot;Why is this&quot;) </code></pre> <p>the target should be a funcion but in your code you <strong>execute</strong> the function here with brackets. That is like normal function calling so that's why your prog...
python|while-loop|python-multiprocessing
0
5,385
13,149,663
Efficient way to store comments in Google App Engine?
<p>With Google App Engine, an entity is limited to 1 MB in size. Say I have a blog system, and expect thousands of comments on each article, some paragraphs in lengths. Typically, without a limit, you'd just store all the comments in the same entity as the blog post. But here, there would be concerns about reaching the...
<p>If comments are threaded, storing them as separate entities might make sense.</p> <p>If comments can be the target of voting, storing them as separate entities makes sense.</p> <p>If comments can be edited, storing them as separate entities reduces contention, and avoids having to either do pessimistic locking on ...
python|google-app-engine
2
5,386
21,732,449
python- how to unpack a text or set of strings
<p>How can I unpack them separately?? I want to get back the length of the strings(used) and the strings itself from txt? Any help?</p> <pre><code>dataType = struct.pack('H', gvrDatatype) varName = struct.pack('B' + str(len(gvrVarname)) + 's', len(gvrVarname), gvrVarname) txt = struct.pack('B' + str(len(gvrTxt)) + 's'...
<p>I think the first question to answer is: Why are you packing strings like this in the first place? Unless you are passing this as a data structure to a library that accepts the format you created above, you should not need to do that: store strings as text in text files - not as binary. If it is the case that you ne...
python|struct|unpack
3
5,387
21,675,161
Why OrderedDict has this behavior
<p>In Python 2.7 I am having this behavior with OrderedDict</p> <pre><code>from collections import * id(OrderedDict()) 42101904 id(OrderedDict()) 42071680 id(OrderedDict()) 42071680 id(OrderedDict()) 42071680 id(OrderedDict()) 42071680 </code></pre> <p>Why?</p>
<p>That's not specific to <code>OrderedDict()</code>, Python is <em>reusing</em> freed memory to store the new object.</p> <p>From the <a href="http://docs.python.org/2/library/functions.html#id" rel="nofollow"><code>id()</code> function documentation</a>:</p> <blockquote> <p>Return the “identity” of an object. Thi...
python|python-collections
4
5,388
41,144,086
Typing problems in PyCharm
<p>I have the following function:</p> <pre><code>def clock(dimS: Tuple[int] =(0)) -&gt; Generator[Tuple[int], None, None]: """ Produce coordinates """ itr = 0 dim = len(dimS) maxItr = np.prod(dimS) if (dim &lt; 1): raise ValueError( 'function clock expected positive number of d...
<p><code>mypy</code> accepts your sample input without issue. This is an issue with PyCharm from what it seems. </p> <p>Scaning through the bug tracker for JetBrains, I found an issue that deals with what you're experiencing, see <a href="https://youtrack.jetbrains.com/issue/PY-20709" rel="nofollow noreferrer">Return ...
python|python-3.x|pycharm|typing|type-hinting
2
5,389
40,282,669
onHotEncoding and lists in a pandas dataFrame
<p>I have a pandas dataframe:</p> <pre><code>import pandas as pd d={'col1':[[1,2,3],[4,5,6]],'col2':[[7,8,9],[10,11,12]]} df=pd.DataFrame(d) </code></pre> <p>which results in:</p> <p><a href="https://i.stack.imgur.com/lG2dc.png" rel="nofollow"><img src="https://i.stack.imgur.com/lG2dc.png" alt="result of comman ...
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a> for creating <code>Series</code>, then cast <code>list</code> to <code>string</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.as...
list|pandas|dataframe|multiple-columns|one-hot-encoding
2
5,390
40,312,013
check type within numpy array
<p>I have different types of data. most of them are <code>int</code> and sometimes <code>float</code>. The <code>int</code> is different in size so 8/ 16/ 32 bits are the sizes.<br> For this situation I'm creating a numerical type converter. therefore i check the type by using <code>isinstence()</code>. This because I ...
<p>An array is an object of type <code>np.ndarray</code>. Its values or elements are stored in a data buffer, which can be thought of as a contiguous block of memory bytes. The bytes in the data buffer do not have a type, because they are not Python objects.</p> <p>The array has a <code>dtype</code> parameter, which...
python-3.x|numpy|isinstance
38
5,391
29,042,182
Creating a 4d matrix full of zeros in python, numpy
<p>I am trying to create a 4 dimensional matrix in python using the following code;</p> <pre><code>import numpy as np rho=np.zeros(2,2,2,2) </code></pre> <p>But I get the following error;</p> <pre><code> rho=np.zeros(2,2,2,2) TypeError: function takes at most 3 arguments (4 given) </code></pre> <p>This seems to ...
<p>Instead of passing 4 arguments, pass one argument, a tuple of four elements:</p> <pre><code>&gt;&gt;&gt; rho=np.zeros((2,2,2,2)) &gt;&gt;&gt; rho array([[[[ 0., 0.], [ 0., 0.]], [[ 0., 0.], [ 0., 0.]]], [[[ 0., 0.], [ 0., 0.]], [[ 0., 0.], [ 0., ...
python|matlab|numpy
13
5,392
58,934,489
Loop and fetch values from Json script using Python
<p>I have a JSON script in which I need to fetch out series of values using loops in Python. Sample Json snippet is shown below,</p> <pre><code>{ 'ResponseMetadata': { 'RetryAttempts': 0, 'HTTPStatusCode': 200, 'RequestId': 'aaaaaaaaaaaa', 'HTTPHeaders': { 'date': 'Tue, ...
<p>I am not sure if I understand your task correct: </p> <pre><code>[y.get("DestinationPrefixListId") for x in data["RouteTables"] for y in x["Routes"] if y.get("DestinationPrefixListId")] </code></pre> <p>Will return:</p> <pre><code>['pl-234234', 'pl-2342344'] </code></pre>
python|boto3|amazon-vpc
1
5,393
58,678,545
how to convert a str variable likes "xe4\xb8\xad" to Chinese?
<p>I have some str variables, having the form of 'Nov 3, 2019 16:13:05.882679000 \xe4\xb8\xad\xe5\x9b\xbd\xe6\xa0\x87\xe5\x87\x86\xe6\x97\xb6\xe9\x97\xb4', and I want to convert the unicode part '\xe4\xb8\xad\xe5\x9b...' to Chinese, here they mean "中国标准时间". I have tried this method : </p> <pre><code>t.encode('raw...
<p>This is UTF-8 incorrectly decoded as latin-1. <a href="https://en.wikipedia.org/wiki/Mojibake" rel="nofollow noreferrer">Mojibake</a>. To reverse it, undo the incorrect decoder and apply the correct decoder:</p> <pre><code>&gt;&gt;&gt; s = '\xe4\xb8\xad\xe5\x9b\xbd\xe6\xa0\x87\xe5\x87\x86\xe6\x97\xb6\xe9\x97\xb4' &...
python|unicode|character-encoding|mojibake
0
5,394
51,842,741
Modifying HTTPS response packet on the fly with mitmproxy
<p>I am trying to implement an mitmproxy addon script, in order to tamper with a particular https packet data - which is by the way decrypted on the fly through mitmproxy's certificate injection.</p> <p>I am following this <a href="https://stackoverflow.com/a/29914515/5500552">Stack Overflow answer</a> to a rather sim...
<p>Have you tried to use <code>pretty_url</code> attribute ?<br> Something like :</p> <pre><code>if flow.request.pretty_url == "https://api.example.com/api/v1/user/info": .... </code></pre> <p><code>pretty_url</code> attribute handles full <em>domain name</em> whereas <code>url</code> only deals with correspondin...
python|linux|packet-capture|mitmproxy|tampering
1
5,395
59,481,247
Basemap Invalid Syntax for mapping EPSG
<p>I have a doubt related to Basemap Background Map because my code is working in some cases and other not. I have a region to plot, so I apply the following code.</p> <pre><code>import os import csv import numpy as np from obspy import read from mpl_toolkits.basemap import Basemap from matplotlib import pyplot as plt...
<p>@Jason To solve the problem I re write the code and use an IDLE (under Ubuntu) for some weird reason the simple text editor (under Ubuntu) missed the spaces and then the mistake I reported </p> <blockquote> <p>SyntaxError: invalid syntax</p> </blockquote> <p>I will show you all the code I am working (fast bullet...
python-3.x|matplotlib-basemap
0
5,396
18,836,547
Dynamic FormWizard
<p>I made a project that works like <a href="https://ifttt.com/" rel="nofollow">ifttt.com</a> does.</p> <p>To do so I use <code>FormWizard</code>.</p> <p>Actually, that works fine with the only 2 services which are <code>RSS</code> and <code>Evernote</code></p> <p>I could set the <code>FORMS</code> and <code>TEMPLAT...
<p>here is how I finished to handle it </p> <p>first, <strong>urls.py</strong> :</p> <pre><code>url(r'^service/create/$','django_th.views.get_form_list', name='create_service'), </code></pre> <p>then in <strong>views.py</strong> :</p> <p>I did :</p> <pre><code>def get_form_list(request, form_list=None): if for...
python|django|evernote
5
5,397
69,035,662
Calculate distance between two points with ZIP CODE alone
<p>I have a dataset as follows;</p> <pre><code> Group Zip 1 30079 1 30059 1 30049 1 30024 2 30061 2 30031 2 30043 2 30130 </code></pre> <p>Within each group, is there a way to calculate the distance between each successive zip using Z...
<p>I would try the geopy package:</p> <pre><code>I stole these examples from the blog post linked below: from geopy.geocoders import Nominatim geocoder = Nominatim(user_agent = 'your_app_name') # after initiating geocoder location = geocode(address) # returns location object with longitude, latitude and altitude ins...
python|pandas|numpy
1
5,398
56,203,148
Convert an existing NumPy array into a ctype array to be shared among multiprocessing
<p>Let's say I have an existing array that we don't want to make any changes to, but like to be converted to a ctype array and be shared among all the multiprocessing later on.</p> <p>The actual array I want to be shared is of shape 120,000 x 4, which is too large to type all out here, so let's pretend such an array i...
<p>The workaround I found months ago requires flattening the array into a 1-dimensional array first, even though I only understand half of what is under the hood. </p> <p>The gist of the solution is to:</p> <p>1) make a RawArray of the same size and same dtypes as the array we are trying to share</p> <p>2) create a...
python|arrays|numpy|multiprocessing|ctypes
0
5,399
13,590,647
Increment list based on number pattern
<p>I have a list of zeros and ones that looks like this:</p> <pre><code>lst = [0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1] </code></pre> <p>How can I transform this lst into this:</p> <pre><code>transformed_lst = lst = [0, 1, 1, 1, 1, 0, 0, 0, 2, 2, 0, 0, 0, 3, 0, 4, 4] </code></pre> <p>Basically, at each oc...
<p>You basically have two states - "reading <code>0</code>s" and "reading <code>1</code>s" - and when you switch between then (namely from ones to zeroes) the delta to be applied for subsequent <code>1</code>s change:</p> <pre><code>reading_zeroes = True delta = 0 for x in input: if x: reading_zeroes = Fa...
python|list
6