Unnamed: 0 int64 0 1.91M | id int64 337 73.8M | title stringlengths 10 150 | question stringlengths 21 64.2k | answer stringlengths 19 59.4k | tags stringlengths 5 112 | score int64 -10 17.3k |
|---|---|---|---|---|---|---|
9,700 | 19,213,724 | Is there a dedicated milli-sec precision timestamp data structure in python pandas? | <p>For instance, in q, there is a dedicated time struct, such as 11:59:59.999, which I can use in a table as a column. Is there anything like this in pandas?</p>
<p>I read the doc and there seems to be quite comprehensive examples for timestamp on a daily resolution, which is good for fund managers, I guess. Is there ... | <h1>Yes there is!</h1>
<h2>It's called <code>Timestamp</code>!</h2>
<p><code>pandas</code> has support for up to <strong>nanosecond</strong> resolution using its own <code>Timestamp</code> class which is a subclass of <code>datetime.datetime</code>:</p>
<pre><code>In [6]: pd.Timestamp('now') + np.timedelta64(100, 'n... | python|pandas | 3 |
9,701 | 36,440,016 | Python Matplotlib scatter plot adding x-axis labels | <p>I have this following code in order to generate scatterplots</p>
<pre><code> import matplotlib.pyplot as plt
line = plt.figure()
plt.plot(xvalue, yvalue)
plt.grid(True)
plt.savefig("test.png")
plt.show()
</code></pre>
<p>and here... | <p>Here is my answer. You target was to plot the datetime as xticklabel.<br>
I always do something like this. Code like this: </p>
<pre><code>## For example, I have 9 daily value during 2013-04-01 to 2014-04-10
start = datetime.datetime.strptime("01-04-2013", "%d-%m-%Y")
end = datetime.datetime.strptime("10-04-20... | python|python-3.x|matplotlib|scatter-plot | 6 |
9,702 | 36,538,722 | Sum of Values in a file, negatives? | <p>I have a file I'm working with that has an integer per line and no commas are separating the numbers. When I go to get the sum of the numbers in that file, it only works for positive integers. What I have doesn't work for negative numbers in the file. Any way of being able to accomplish that? My code in question:</p... | <p>The problem is that those methods require all characters be a digit, and <code>-</code> is not; see <a href="https://docs.python.org/2/library/stdtypes.html" rel="nofollow noreferrer">https://docs.python.org/2/library/stdtypes.html</a></p>
<pre><code>>>> "234".isalnum()
True
>>> "-234".isalnum()
F... | python|file|sum|addition | 1 |
9,703 | 19,678,641 | Build an approximately uniform grid from random sample (python) | <p>I want to build a grid from sampled data. I could use a machine learning - clustering algorithm, like k-means, but I want to restrict the centres to be roughly uniformly distributed.</p>
<p>I have come up with an approach using the scikit-learn nearest neighbours search: pick a point at random, delete all points wi... | <p>I'm not sure from the question exactly what you are trying to do. You mention wanting to create an "approximate grid", or a "uniform distribution", while the code you provide selects a subset of points such that no pairwise distance is greater than <code>r</code>.</p>
<p>A couple possible suggestions:</p>
<ul>
<l... | python|machine-learning|cluster-analysis|scikit-learn | 4 |
9,704 | 19,805,402 | Python List of classes | <p>I'm trying to design a "Time Tracker" device. I want to be able to define a class line like:</p>
<pre><code>class line():
def __init__(self, course, weekHours, hoursTotal, comment)
self.course = course
self.weekHours = weekHours
self.hoursTotal = hoursTotal
self.comment = comment... | <p>You can store class instances in a list:</p>
<pre><code>lines = []
lines.append(line('Math', '3', '12', 'Hello World!'))
...
</code></pre>
<p>To get the i'th line, you'd just do:</p>
<pre><code>lines[i]
</code></pre>
<p>Note that there really isn't a good reason to have a class here. a python <code>dict</code> ... | python|list|class | 2 |
9,705 | 22,320,705 | how to run local python script on remote machine | <p>I have a python script on my local machine.Is there any way to run this script on remote machine.I mean python script should on the local machine but execution should happen on remote machine and get the output back to the local machine.</p> | <p>The <code>pathos</code> package has tools that make it easy to interact with remote machines, all directly from python… and you can also easily capture <code>stdout</code> or other piped responses and return them to your calling script.</p>
<p>So, let's say you have a local script <code>hello.py</code> that looks l... | python | 7 |
9,706 | 43,484,395 | Efficient way to avoid for loops in Pandas DataFrame | <p>I'm converting an Excel spreadsheet to Python so as to automate and speed up several tasks. I need to add several columns to the DataFrame and add data to them based on values in a previous column. I've got it working using two nested for loops, but it's really slow and I know Pandas is not designed for cell-by-cell... | <p>This would do the job:</p>
<pre><code>import pandas as pd
results = pd.DataFrame({'scores':[78.5, 91.0, 103.5], 'outcomes':[1,0,1]})
thresholds = [103.5, 98.5, 93.5, 88.5, 83.5, 78.5]
for threshold in thresholds:
results[str(threshold)] = results[['scores','outcomes']].apply(lambda x: x['outcomes'] if x['sco... | python|pandas | 3 |
9,707 | 9,143,509 | iPhone Sensor Data app ploting in Streaming mode | <p>Im using the <a href="http://wavefrontlabs.com/Wavefront_Labs/Sensor_Data.html" rel="nofollow">Sensor Data app</a> to access the data from the iPhone's accelerometer. I want to use the steaming option to stream the data to my MacBook in real time. For this I would like some sort of a script that collects this data a... | <p>In order to gain full control over the plots, you would probably have to install a plotting library in your computer. <a href="http://sourceforge.net/projects/matplotlib/files/matplotlib/matplotlib-1.1.0/" rel="nofollow">Matplotlib</a> is an open-source python library that will help you to solve this situation. If y... | iphone|python|real-time|accelerometer|sensors | 0 |
9,708 | 9,495,279 | urllib2 HTTPPasswordMgr not working - Credentials not sent error | <p>The following python curl call has the following successful results:</p>
<pre><code>>>> import subprocess
>>> args = [
'curl',
'-H', 'X-Requested-With: Demo',
'https://username:password@qualysapi.qualys.com/qps/rest/3.0/count/was/webapp' ]
>>> xml_output = subproc... | <p>From <a href="https://stackoverflow.com/questions/2407126/python-urllib2-basic-auth-problem">Python urllib2 Basic Auth Problem</a></p>
<blockquote>
<p>The problem [is] that the Python libraries, per HTTP-Standard, first send an unauthenticated request, and then only if it's answered with a 401 retry, are the corr... | python|curl|urllib2|httplib | 3 |
9,709 | 9,206,627 | getting python 2.4.5 out of my environment variables | <p>major noob question:
when I run python on the windows command line, it says I have 2.4.5... however, it's not in my PATH environment variable (or anywhere in my environment variables), and, Python27 IS in PATH! Anyone know how I can get Python27 up and running in windows cmd?</p> | <p>Trying running WHERE PYTHON (or WHERE PYTHON.EXE) to figure out where the python executable is at.</p>
<p>It may be that python v2.4.5 is as part of another program. </p> | python | 0 |
9,710 | 39,342,838 | Running Jupyter kernel and notebook server on different machines | <p>I'm trying to run an iPython/ Jupyter kernel and the notebook server on two different Windows machines on a LAN.</p>
<p>From most of the links that I found on the internet, they offer advice on how we can access a remote kernel + server setup from a web browser, but no information on how to separate the kernel and ... | <p>I ended up using this <a href="https://github.com/jupyter/kernel_gateway_demos/tree/master/nb2kg" rel="nofollow">demo</a> which pretty much did this job for me. </p> | python|ipython|jupyter|jupyter-notebook | 2 |
9,711 | 55,306,127 | how to upload a file and send it to someone Tkinter | <p>I have made a chatroom where users can messages to each other but I want to add a upload file feature, I have found how to do this:</p>
<pre><code>import tkinter as tk
from tkinter import filedialog
def UploadAction(event=None):
filename = filedialog.askopenfilename()
print('Selected:', filename)
root = t... | <p>Although this subject is <a href="https://stackoverflow.com/help/on-topic">out of topic</a> (this question is actually about sockets and not tkinter), not asked correctly (see <a href="https://stackoverflow.com/help/how-to-ask">how to ask</a>), and possibly a duplicate of <a href="https://stackoverflow.com/questions... | python|python-3.x|tkinter | 0 |
9,712 | 52,693,436 | How to hash a dictionary? | <p>I wanted to know if you could hash a dictionary? Currently playing around with Blockchain! Here's the code I would like to hash:</p>
<pre><code>def add_transactions():
transaction = {
"previous_block_hash": previous_block_hash() ,
"index": increase_index(),
"item": item(),
"timestam... | <p>Dictionary is unhashable data type in python. So you cannot hash a dictionary object. But, if you need to have some check sum you can serialize dictionary and then calculate its hash (just a workaround that can help). </p>
<p>For example using <code>jsonpickle</code> and <code>hashlib</code>:</p>
<pre><code>import... | python | 6 |
9,713 | 37,168,052 | Python: What is returned when I use requests.get('url') and print r.text? | <p>I'm trying to scrape <a href="http://www.machinefinder.com/ww/en-US/categories/used-drawn-planters" rel="nofollow">this webpage</a>. This code works: </p>
<pre><code>import requests
header = {
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:32.0) Gecko/20100101 Firefox/32.0',
}
r = requests.get('h... | <pre><code>>>>>type(r.text)
<type 'unicode'>
</code></pre>
<p>Looks to be the html for the page. You could use Beautiful soup to parse it
:<a href="https://www.crummy.com/software/BeautifulSoup/bs3/documentation.html" rel="nofollow">https://www.crummy.com/software/BeautifulSoup/bs3/documentation.ht... | python|json|python-requests | 0 |
9,714 | 37,366,544 | List to csv in python with header | <p>I have written a script which gives the list like below as an output.</p>
<pre><code>['red', '361', '0']
['blue', '1', '0']
['orange', '77', '0']
['cream', '660', '73']
['ivory', '159', '0']
</code></pre>
<p>This list is very huge and I want to write the output contents to a csv with header on top like below.</p>
... | <p>Code -</p>
<pre><code>import csv
arr = [['red', '361', '0'],
['blue', '1', '0'],
['orange', '77', '0'],
['cream', '660', '73'],
['ivory', '159', '0']]
with open('output.csv','w') as f:
writer = csv.writer(f)
writer.writerow(['color', 'total', 'fail'])
writer.writerows(arr)
</co... | python|csv|export-to-csv | 13 |
9,715 | 34,339,648 | Python - TypeError: unbound method beamDeflection() must be called with beam instance as first argument (got list instance instead) | <p>In Python, I am trying to run a function in a class and get the following error:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:/Users/X/Downloads/beamModel.py", line 58, in getTotalDeflection
beam.beamDeflection(loadsList, x)
TypeError: unbound met... | <p>The problem could be because you are calling <code>beamDeflection()</code> not on an instance of <code>beam</code> but on the static <code>beam</code> class itself. </p>
<p>Assuming that is the problem, you could probably rewrite your <code>getTotalDeflection</code> method like so:</p>
<pre><code>def getTotalDefle... | python | 1 |
9,716 | 72,560,823 | The @login_required decoration is not working in Django (user not authenticated?) | <p>I am trying to set up a login page and I am trying to use the <code>@login_required</code> decoration. However, whenever I try and log in with valid credentials I am re-directed to the 'login' page (set to re-direct unauthenticated users). I am not sure if the problem is in the @login_required decoration or perhaps ... | <p>You need to correctly authenticate the user before logging in.</p>
<pre><code>from django.contrib.auth import authenticate, login
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
</... | python|django|django-models|django-views|django-forms | 1 |
9,717 | 31,957,936 | How to iterate and print the list of dictionaries in xls using python | <p>I want to read data from database and convert it into list of dictionaries to put it in to a XLS File for reporting.</p>
<p>I tried python code for report since it's easier for me write code with minimum programming knowledge</p>
<p>I want to Write the list of dictionaries within list of dictionaries to an XLS Fi... | <p>I think it's because you have</p>
<pre><code>m += 1
</code></pre>
<p>inside your inner for loop. So, for every element in c, you are putting it down one more row. (Your commented out line at the end was right.)</p>
<p>By the way, it's better to use meaningful variable names than just letters for variables (e.g... | python|dictionary|xls|xlwt | 0 |
9,718 | 31,892,673 | Creating SQL Table with variable name from Python | <p>I'm trying to create and write a DataFrame to a SQL table using Python. The table should be named after a variable, specifically <code>table_name</code> (<code>table_name</code> will change as I run my code). Below is the relevant part of my code to try to set this up:</p>
<pre><code>con = sql.connect(r'/Users/lin... | <p>Why don't you use:</p>
<pre><code>cur.execute('CREATE TABLE IF NOT EXISTS {tab} (Date, Morning1, Day1, Evening1, Night1, Morning3, Day3, Evening3, Night3)'
.format(tab=table_name))
</code></pre> | python|sql|pandas|dataframe | 3 |
9,719 | 38,662,209 | How to update a PySpark RDD of dictionaries based on some condition | <p>Firstly I understand the concept of persistent data structures and immutability with regards to RDD's.. update is the only word I could think of :)</p>
<p>My question is:</p>
<p>Given an RDD of dictionaries (or Row objects) how can I loop/map across and apply some transformation login on that RDD and receive back ... | <ul>
<li><code>update_virtual_cash_balance</code> doesn't return anything so you get <code>None</code></li>
<li><code>update</code> method doesn't return anything so you would get <code>None</code> even if <code>update_virtual_cash_balance</code> returned value</li>
<li>you shouldn't modify data in place. RDD is immuta... | python|pyspark | 1 |
9,720 | 38,883,202 | Python Reportlab insert image base64 colors are being inverted | <p>I am trying to add a base64 image on a pdf using ReportLab. I am able to add the image successfully. However, the colors for the image are being inverted. </p>
<p>To confirm that it wasn't the base64 code that had the colors inverted, I manually converted the base64 online to make sure the colors were correct.</p... | <p>The following works for me. Can you try putting <code>mask='auto'</code> parameter?</p>
<pre><code>image64 = signature
p.drawImage(image64, 110, 25 ,mask='auto')
</code></pre> | python|base64|reportlab | 0 |
9,721 | 40,598,513 | Parsing Through Dictionary with multiple keys correctly | <p>I've wrote the function to parse through my created Dictionary of abbreviations and meanings. But It wont work for longer abbreviations. I think it's finding the first instance of piece and spitting that out. I want it to take the whole input and return the value that responds to that. Single letters and double lett... | <p>abbrev is a string, when you turn it into a list, you're getting a list of each letter:</p>
<pre><code>>>> abbrev = 'one, two, three'
>>> list(abbrev)
['o', 'n', 'e', ',', ' ', 't', 'w', 'o', ',', ' ', 't', 'h', 'r', 'e', 'e']
</code></pre>
<p>You may want something like this instead:</p>
<pre><... | python|parsing|dictionary | 0 |
9,722 | 10,115,126 | Python-Requests close http connection | <p>I was wondering, how do you close a connection with Requests (python-requests.org)?</p>
<p>With <code>httplib</code> it's <code>HTTPConnection.close()</code>, but how do I do the same with Requests?</p>
<p>Code:</p>
<pre><code>r = requests.post("https://stream.twitter.com/1/statuses/filter.json", data={'tr... | <p>I think a more reliable way of closing a connection is to tell the sever explicitly to close it in a way <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html" rel="noreferrer">compliant with HTTP specification</a>:</p>
<blockquote>
<p>HTTP/1.1 defines the "close" connection option for the sender to
... | python|http|urllib2|httplib|python-requests | 75 |
9,723 | 60,111,082 | Django passing data to html | <p>Ok, I'm stuck and I don't know what I'm doing wrong. I have database and i need to fetch data from it and render it in HTML. I've watched few tutorials and it doesn't seem hard but it's not working for me.
this is my view:</p>
<pre><code>def get_all_subjects(request):
all_subjects = Predmeti.objects.all()
r... | <p>as return do this:</p>
<pre><code>return render(request, 'home.html', locals())
</code></pre>
<p>then in html:</p>
<pre><code>{% for predmet in all_subjects %}
{{ predmet.ime }}
{% endfor %}
</code></pre> | python|django|django-templates | 1 |
9,724 | 32,293,455 | How to change logging level in google app engine python production server? | <p>I have tried to search answers for this question online, but in vain. I do see the answer for "<a href="https://stackoverflow.com/questions/7811493/how-to-change-the-logging-level-of-dev-appserver">How do set the log level in google app engine python dev server</a>", which is useful to know - but if I understand cor... | <p>As Paul Collingwood said in his comment, it is easy to set a filter in the Developer Console, in order to reduce visual clutter.</p>
<p>If there are cases in which you do not wish to have the debug logs recorded at all (e.g. while in production), you might like to write a little wrapper function for the logging cal... | python|google-app-engine | 0 |
9,725 | 32,597,390 | open url from pythonanywhere | <p>This code works well on my local machine, but when I upload and run it on pythonanywhere.com it gives me this error.
<br>
My Code:</p>
<pre><code>url = "http://www.codeforces.com/api/contest.list?gym=false"
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271... | <p>Free accounts on PythonAnywhere are restricted to a <a href="https://www.pythonanywhere.com/whitelist/" rel="noreferrer">whitelist</a> of sites, http/https only, and access goes via a proxy. There's more info here:</p>
<p><a href="https://www.pythonanywhere.com/wiki/403ForbiddenError" rel="noreferrer">PythonAnywhe... | python|urllib2|pythonanywhere | 6 |
9,726 | 28,113,266 | Tweepy include_rts not working | <p>I am trying to retreive the statuses of the users without his retweets.</p>
<pre><code>total_pages = 17
for page_count in range(1,total_pages+1):
statuses = api.user_timeline(screen_name, count = 200, page = page_count, include_rts=False)
for tweet in statuses:
if tag.lower() in tweet.text.lower():
... | <p>Tweepy uses <code>'false'</code> or <code>0</code>, not <code>False</code>, and <code>true</code>, <code>t</code> or <code>1</code>, not <code>True</code>.</p> | python|twitter|tweepy | 0 |
9,727 | 43,991,120 | Why is numpy faster at finding non-zero elements in a matrix? | <pre><code>def nonzero(a):
row,colum = a.shape
nonzero_row = np.array([],dtype=int)
nonzero_col = np.array([],dtype=int)
for i in range(0,row):
for j in range(0,colum):
if a[i,j] != 0:
nonzero_row = np.append(nonzero_row,i)
nonzero_col = np.appen... | <p>There are 2 reasons why NumPy functions can outperform Pythons types:</p>
<ul>
<li>The values inside the array are native types, not Python types. This means NumPy doesn't need to go through the abstraction layer that Python has.</li>
<li>NumPy functions are (mostly) written in C. That actually only matters in some... | python|performance|numpy | 1 |
9,728 | 13,818,081 | Hexadecimal regular expression string matching does not work (python) | <p>I have a hexadecimal string as follows (for example)</p>
<pre><code>'0x100x200x3f0x2d0x300x330xd0xa'
</code></pre>
<p>and I want to extract all the stuff between the header</p>
<pre><code>'0x100x200x3f0x2d'
</code></pre>
<p>and the tail</p>
<pre><code>'0xd0xa'
</code></pre>
<p>In the example given above the ex... | <blockquote>
<p>So one should never have two [] nested?</p>
</blockquote>
<p>A <code>[</code> nested within a character group will make the outer character group include the <code>[</code> character. The character <code>]</code> will close the first character group, making the second <code>]</code> a static characte... | python|regex|hex | 2 |
9,729 | 27,250,709 | pass integers into array from argv in Python | <p>I want to pass some integer values into an array via sys.argv, but I get a TypeError.
how can I pass integers into my array, from the argv list? Must I do an explicit conversion?</p>
<pre><code>#!/usr/bin/python
from array import array
import serial, sys
ser = serial.Serial('/dev/ttyACM0', 9600)
a=array('i',(0 for... | <p>Replace:</p>
<pre><code>a.append(sys.argv[1])
a.append(sys.argv[2])
a.append(sys.argv[3])
</code></pre>
<p>with:</p>
<pre><code>a.append(int(sys.argv[1]))
a.append(int(sys.argv[2]))
a.append(int(sys.argv[3]))
</code></pre>
<p>and this:</p>
<pre><code>print(a.range(0-2))
</code></pre>
<p>with:</p>
<pre><code>p... | python|arrays | 2 |
9,730 | 27,125,946 | Constantly being unable to deploy app on app engine | <p>Using google app engine launcher, I can't seem to deploy my app due to this:
email=martinchua99@gmail.com', '--passin', 'update', 'C:\Users\admin\Desktop\school work\customtinywebdb']"
Usage: appcfg.py [options] update | [file, ...]</p>
<p>appcfg.py: error: Error parsing C:\Users\admin\Desktop\school work\customti... | <p>Yaml files are sensitive to white spaces. Also you are missing key words and new lines. Give this a try:</p>
<pre><code>application: camel-cars
version: 1
runtime: python27
api_version: 1
threadsafe: false
handlers:
- url: /images
static_dir: images
- url: .*
script: main.py
</code></pre> | python|google-app-engine | 0 |
9,731 | 23,236,611 | Difference of decimal numbers with another base | <p>I am using Python. I have several pairs of numbers and I want to find their difference, but their base is on 42. For example,</p>
<pre><code>5.39->5.40->5.41->5.42->6.00
</code></pre>
<p>So, 10.38 with 10.24 has 0.14, but 10.41 with 11.02 has 0.03</p>
<p>Is there any way to do this with Python? The on... | <p>Like this? Subtracts A from B using 0.42 as cap for decimal part.</p>
<pre><code>base = 42
a = (5,10)
b = (4,39)
if a > b:
b, a = a, b
overflow = int(b[1] < a[1])
c = (b[0]-a[0]-overflow, b[1]+base*overflow-a[1])
print(c)
</code></pre>
<p>Question is not very clear. Also I used tuples to avoid parsing.... | python | 0 |
9,732 | 7,998,436 | float has no attribute int , in python 3.2 | <p>I have this one error that says ,"float has no attribute int" error.
The question is to write a function that takes a parameter as image and draws two vertical lines to img, one red line from (50,0) to (50,300) and one made up of randomly colored pixels from (150,50) to (150,250). For some reason the random part, wh... | <p><code>random.random()</code> returns a random floating point in the range [0.0,1.0). If you wanted an integer of it, you'd have to do:</p>
<pre><code>int(RandomColor) # would be 0 because random() is < 1.0
int(RandomColor * 256) # to get 0-255
</code></pre>
<p>You want a random number between 0-255, so couldn'... | python|random | 6 |
9,733 | 41,943,015 | What could be wrong in this body function? | <p>I am developing a function for a game and I am getting stuck in a function that must return if a word is included in a board. Python's shell returns me a False condition when it suppose to be True.
This is my body funtion:</p>
<pre><code>def board_contains_word(board, word):
""" (list of list of str, str) ->... | <p>You have a loop, but you're ignoring the loop counter. You set the value in each iteration into the <code>word_index</code> variable; you should use that inside your loop.</p>
<p>Your other issue is that you always return after the first iteration. Your second <code>return</code> should be <em>outside</em> the loop... | python|function | 0 |
9,734 | 57,545,934 | You may need to add u'127.0.0.1' to ALLOWED_HOSTS | <p>I am getting the following error when I am trying to start my Django server</p>
<pre><code>python manage.py runserver 0.0.0.0:8000
Performing system checks...
System check identified no issues (0 silenced).
August 18, 2019 - 20:47:09
Django version 1.11, using settings 'config.settings'
Starting development serv... | <p>This happens just because <code>localhost</code> of your host machine is not localhost of your host server. You can either do </p>
<pre><code>ALLOWED_HOSTS=['<your host ip address>',]
</code></pre>
<p>or </p>
<pre><code>ALLOWED_HOSTS=['*',]
</code></pre>
<p>although wildcard is not recommended, but useful ... | python|django | 5 |
9,735 | 33,842,584 | Sorting list in Python causes error | <p>I'm having a problem sorting list in Python here's my code:</p>
<pre><code>lista = [ 1, .89, .65, .90]
for x in lista.sort():
print (x)
</code></pre>
<p>Error is:</p>
<pre><code>TypeError: 'NoneType' object is not iterable
</code></pre> | <p>The <code>sort</code> method sorts the list in-place; it always returns <code>None</code>.
What you can do:</p>
<pre><code>lista = [ 1, .89, .65, .90]
lista.sort()
for x in lista:
print (x)
</code></pre>
<p>Or, as @Delgan pointed out, you can use the <code>sorted</code> function, which returns the sorted list... | python|list | 7 |
9,736 | 33,640,673 | ImportError igraph: undefined symbol | <p>After installing python-igraph with pip, I still can't import it. I've encountered such error around the internet but most solutions I've found were about reinstalling the module, which I already did. Any suggestions on how to fix this would be greatly appreciated. Thanks</p>
<pre><code>>>> import igraph
T... | <p>Uninstalling everything through pip and then installing python-igraph community repo package for arch linux did it. Didn't realize there was one. Suggested by Tamás.</p> | python|import|igraph|undefined-symbol | 1 |
9,737 | 47,029,772 | How to embed JyNI in a jar | <p>I'm developing an application in java, and in this one, I use <a href="https://mvnrepository.com/artifact/org.python/jython-standalone/2.7.1" rel="nofollow noreferrer">jython-standalone</a> (Jython for untold reasons, its goal being to ease some scripting within the application).</p>
<p>I would like to have access ... | <p>You should be able to start the live interpreter by executing the class org.python.util.jython.</p>
<p>On Linux, OSX:</p>
<pre><code>java -cp jython.jar:build/JyNI.jar org.python.util.jython
</code></pre>
<p>On Windows:</p>
<pre><code>java -cp jython.jar;build\JyNI.jar org.python.util.jython
</code></pre>
<p>Al... | java|maven|numpy|jar|jython | 0 |
9,738 | 46,869,864 | Calculating percentage/fraction from sum in python sql query | <p>I have a query that grabs the counts of complaints for a city.</p>
<pre><code>query = '''
select ComplaintType as complaint_type, City as city_name,
count(ComplaintType) complaint_count
from data
where city in ({})
group by city_name, complaint_type
order by city_name
'''.format(strs_to_arg... | <p>Well, one method is to summarize in a subquery and join the results in:</p>
<pre><code>query = '''
select d.ComplaintType as complaint_type, d.City as city_name,
count(*) as complaint_count,
count(*) * 1.0 / max(cc.cnt) as ratio
from data d cross join
(select d.city, count(*)... | python|mysql|sql | 1 |
9,739 | 27,760,555 | how count by 2 with python? | <p>Hello I am extremely new to python and I am trying to create a program where the end-user will input a number and my program will count to that number skipping by 2. for example:</p>
<pre><code>enter a number: 10
you entered: 10
4
6
8
10
</code></pre>
<p>How can I count by 2 with python, I tried doing this:</p>
<... | <p>Your var, <code>number</code>, is of the type <code>string</code>. You have to convert it to a 'number' like type, like <code>float</code> or <code>int</code> before you can calculate with it. To do this, wrap <code>int()</code> around your <code>raw_input()</code> call and change your while loop to check for <code>... | python|counting | 1 |
9,740 | 43,159,697 | Stuff isn't appending to my list | <p>I'm trying to create a simulation where there are two printers and I find the average wait time for each. I'm using a class for the printer and task in my program. Basically, I'm adding the wait time to each of each simulation to a list and calculating the average time. My issue is that I'm getting a division by ... | <p>I think your problem stems from an empty <code>waitingtimes</code> on the first iteration or so. If there is no print job in the queue, and there has never been a waiting time inserted, you are going to reach the bottom of the loop with <code>waitingtimes==[]</code> (empty), and then do:</p>
<pre><code>sum(waitingt... | python|queue | 0 |
9,741 | 48,530,006 | Taskkill Taskmgr.exe Python | <p>I was wondering if there was a way to kill the Taskmgr.exe process with python.</p>
<p>I am currently working on a revision program designed to close all applications that I could use to close said program or distract me from revision in the first place. Each time coming up with a unique message to guide me back to... | <p>I have found a way to close taskmgr.exe (task manger) and without admin perms.</p>
<pre><code>import os
os.system('wmic process where name="taskmgr.exe" call terminate')
</code></pre>
<p>It works for me every time.</p> | python|module|operating-system|taskkill | 2 |
9,742 | 19,895,363 | Google App Engine: Permalink generation | <p>I am currently working my way through the Web Development course from Udacity, and as I was going through one of their sample source codes regarding generation of a permalink for every individual post in a blog, I encountered a doubt. Now here's the code where I am stuck:</p>
<pre><code>class PostPage(BlogHandler):... | <p>Couple of posts on the forums that you might find useful - </p>
<ol>
<li><a href="http://forums.udacity.com/questions/6012751/permalinks/6013385" rel="nofollow noreferrer">http://forums.udacity.com/questions/6012751/permalinks/6013385</a></li>
<li><a href="http://forums.udacity.com/questions/6014750/a-couple-helpfu... | python|database|google-app-engine|key|gql | 2 |
9,743 | 19,865,224 | Custom output XML (with attributes) with TastyPie? | <p>I apologize in advance if this is not the correct area to post this, but I can't seem to find any help in the docs or on Stack Overflow. TastyPie is awesome, and I've been able to get very close to the desired XML output. However, the problem arises when I want to have a custom attribute on a node. I can't seem to... | <p>Well I got my answer, but not on my own. Thanks to Omelyanyk Andrey in Poland for this working code...this got me to where I need to be and allows me to further customize now that I have working code to learn from.</p>
<pre><code>class MySerializer(Serializer):
def format_datetime(self, data):
return u... | python|xml|django|tastypie | 1 |
9,744 | 4,474,690 | implement an object that holds x seats in y rows | <p>What is the best way to implement an object that holds x rows with y seats? Would it be to use a dictionary object, such as</p>
<pre><code>object={'row1:"2", "row2:"2","row3":"4"}
</code></pre>
<p>And then reference each row if I where to update number of seats?
Or are there any better way of implementing this?</p... | <p>If all you're doing is tracking rows and seats, you could do it with a simple array:</p>
<pre><code>rows = [2,2,4]
</code></pre>
<p>Row 1 is <code>rows[0]</code> with 2 seats, Row 3 is <code>rows[2]</code> with 4 seats, and so on.</p> | python|dictionary | 6 |
9,745 | 69,528,708 | How can I get numbers after and before decimal point? | <p>I have number f = 93.7415</p>
<p>How can I get numbers after and before decimal point (<code>.</code>) using % opretor (I mean how to get 3 and 7)</p>
<p>I've tried something like this</p>
<pre><code>f=float(input("Number: "))
print(f%10)
</code></pre> | <p>With positive numbers, ,odulo with powers of 10 gives you the part of the number that is <em>after</em> that place. Integer division gives you the part that is <em>before</em></p>
<pre><code>>>> f = 93.7415
>>> int(f % 10 // 1)
3
>>> int(f % 1 // 0.1)
7
</code></pre> | python | 1 |
9,746 | 51,249,848 | How to compute local 3x3 range in a larger 2D matrix? | <p>For an image processing workflow, I need to be able to apply a kernel to an image to create a new matrix as follows:</p>
<p>Iterate over an input 10x10 matrix, and at each location, determine the range (difference between maximum and minimum value) in a 3x3 neighborhood of the matrix element, and store this range a... | <p>The minimum value in a neighborhood is given by the morphological erosion, and the maximum value by the dilation. These can be computed by just about any image processing toolbox, including <a href="https://docs.opencv.org/2.4/modules/imgproc/doc/filtering.html#dilate" rel="nofollow noreferrer">OpenCV</a>, <a href="... | python|numpy|image-processing|matrix | 1 |
9,747 | 73,045,313 | how to repeat each row n times in pandas so that it looks like this? | <p>I want to know how to repeat each row n times in pandas in this fashion</p>
<p>I want this below result(With <code>df_repeat = pd.concat([df]*2, ignore_index=False)</code> I can't get expected result ):</p>
<p>Original Dataset:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>index</th>
<... | <p>You can <a href="https://pandas.pydata.org/docs/reference/api/pandas.Index.repeat.html" rel="nofollow noreferrer"><code>repeat</code></a> the index:</p>
<pre><code>df_repeat = df.loc[df.index.repeat(2)]
</code></pre>
<p>output:</p>
<pre><code> index value
0 0 x
0 0 x
1 1 x
1 1 x... | python|pandas|dataframe | 0 |
9,748 | 55,823,557 | Converting Darknet53 gives "nan" results in Tensorflow 2.0 | <p>I am trying to convert Yolo v3 to tensorflow 2.0
I wrote the Darknet53 network layers and I am able to run it on both test inputs as well as actual images but the result in both cases is 'nan'</p>
<p>I already tried scaling the code up and down. First by dividing the image by 255 to scale between 0 and 1 as in the... | <p>Since tensorflow 2.1.0rc0, which is soon to be released as the final 2.1.0, there is a new API specifically designed to help users find out the root cause of such numerical issues liek this, namely <code>tf.debugging.enable_check_numerics()</code>. </p>
<p><code>tf.debugging.enable_check_numerics()</code> is the su... | python|tensorflow|yolo|tensorflow2.0 | 2 |
9,749 | 55,737,589 | How to remove some dots from a string in python | <p>I'm extracting an int from a table but amazingly comes as a string with multiple full stops.
This is what I get:</p>
<pre><code>p = '23.4565.90'
</code></pre>
<p>I would like to remove the last dots but retain the first one when converting to an in.
If i do</p>
<pre><code>print (p.replace('.',''))
</code></pre>
... | <p>What about <code>str.partition</code>?</p>
<pre><code>p = '23.4565.90'
a, b, c = p.partition('.')
print(a + b + c.replace('.', ''))
</code></pre>
<p>This would print:
<code>23.456590</code></p>
<p>EDIT: the method is <code>partition</code> not <code>separate</code></p> | python-3.x | 5 |
9,750 | 50,164,417 | How does GPU utilization work in the context of neural network training? | <p>I am using an AWS <a href="https://aws.amazon.com/ec2/instance-types/p3/" rel="nofollow noreferrer">p3.2xlarge</a> instance with the <a href="https://aws.amazon.com/marketplace/pp/B077GCH38C" rel="nofollow noreferrer">Deep Learning AMI</a> (DLAMI). This instance has a single <a href="https://www.nvidia.com/en-us/dat... | <p>The power of GPUs over CPUs is to run many operations at the same time. However archiving this high level of parallelization is not always easy. Frameworks like Tensorflow or PyTorch do its best to optimise everything for GPU and parallelisation, but this is not possible for every case.</p>
<p>Computations in LSTM... | amazon-ec2|neural-network|nvidia|pytorch|tensor | 2 |
9,751 | 64,848,470 | How to format python text for POS Printer | <p>I have been able to write python code that prints a bunch of text using receipt style.</p>
<p>On a regular full size printer I get the print out as expected with correct formatting and it looks like so.</p>
<p><a href="https://i.stack.imgur.com/63ssK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com... | <p>It seems that the printer only supports a limited line length, and auto-wraps long lines.</p>
<p>If <a href="http://www.bilkur.com/products/Palmx_ZJ-8330.htm" rel="nofollow noreferrer">this</a> is the printer in question, it has a print width of 72 mm, and three (I assume monospaced) fonts, with letter widths of 3 m... | python | 1 |
9,752 | 65,017,523 | How to apply cross_val_score to cross valid our own model | <p>Usually, we apply <code>cross_val_score</code> to the <code>Sklearn</code> models by doing the following way.</p>
<pre><code>scores = cross_val_score(clf, X, y, cv=5, scoring='f1_macro')
</code></pre>
<p>Now I have my own models that I wish to perform cross validation. How should I approach it?</p>
<pre><code>tf.ker... | <p>We cannot directly integrate Keras model in sklearn pipeline. So if you are looking for evaluation of your Keras model using cross_val_score you need to use the wrapper module <strong>tf.keras.wrappers.scikit_learn</strong> for using the sklearn API with Keras models. For eg,</p>
<pre><code>from tf.keras.wrappers.sc... | python|tensorflow|machine-learning|scikit-learn | 2 |
9,753 | 64,817,171 | Filter rows in child table using parent table having one to many relationship sqlalchemy | <p>I have two tables having one to many relationship.</p>
<p>I want to find all rows of child where type is "abc"</p>
<pre><code>class Parent(base):
__tablename__ = "parent"
id = Column("id", String, primary_key=True)
parent = relationship("Child", back_populates=&quo... | <p>This would do what you want:</p>
<pre><code>from sqlalchemy.orm import contains_eager
q = (session.query(Parent)
.join(Child)
.options(contains_eager(Parent.parent))
.filter(Child.type == 'abc'))
for p in q:
print(p.id, [c.name for c in p.parent])
</code></pre>
<p>The <a hre... | python|python-3.x|sqlalchemy|flask-sqlalchemy|marshmallow-sqlalchemy | 2 |
9,754 | 53,015,474 | Get result from a website using post through web scraping | <p>Here is the link to the website from which I want to get my data
<a href="http://ipindiaonline.gov.in/tmrpublicsearch/frmmain.aspx" rel="nofollow noreferrer">Puplic Search of Trademarks</a></p>
<p>In order to do so, I need to fill a form but I want to fill that form using the Python <code>requests</code> library. I... | <p>The post requires a few more values for it to work. These can be obtained by first requesting the page without a search (probably only needed once if you are doing multiple searches). For example:</p>
<pre><code>from bs4 import BeautifulSoup
import requests,json
def returnJson(wordmark, page_class):
url = "htt... | python|web-scraping|beautifulsoup|python-requests | 0 |
9,755 | 65,184,367 | ML Decision Tree classifier is only splitting on the same tree / asking about the same attribute | <p>I am currently making a Decision tree classifier using Gini and Information Gain and splitting the tree based on the the best attribute with the most gain each time. However, it is sticking the same attribute every time and simply adjusting the value for its <a href="https://i.stack.imgur.com/xAzVm.png" rel="nofollo... | <p>The working solution i have was to change the split function as follows. To be completly honest i amnt able to see whats wrong but it might be obvious
The working function is as follows</p>
<pre><code>def split(r):
max_ig = 0
max_att = 0
max_att_val = 0
# calculates gini for the rows provided
curr_gini = gini_index... | python|machine-learning|classification|decision-tree|c4.5 | 0 |
9,756 | 72,066,693 | how to calculate Manhattan distance (or L1/ cityblock) for two 2D array? | <p>For 1D vector/array it's easier. For example:</p>
<pre><code>array1 = [1, 2, 3]
array2 = [1, 1, 1]
</code></pre>
<p>manhattan distance will be: (0+1+2) which is 3</p>
<pre><code>import numpy as np
def cityblock_distance(A, B):
result = np.sum([abs(a - b) for (a, b) in zip(A, B)])
return result
</code></pre>... | <p>You can modify your code to calculate the desired result by comparing each list in the 2d array in turn (using your code for the 1D case) and then summing the result:</p>
<pre><code>def cityblock_distance(A, B):
result = np.sum([np.sum([abs(a - b) for (a, b) in zip(C, D)]) for C, D in zip(A, B)])
return resu... | python|arrays|distance|numpy-ndarray|euclidean-distance | 0 |
9,757 | 68,719,842 | Extracting using Pandas | <p>I want to extract the year from this column :</p>
<p><img src="https://i.stack.imgur.com/KxN2R.jpg" alt="enter image description here" /></p>
<p>what I know is I split it by <code>,</code> into a list using</p>
<pre><code>df['yearcorrect'] = df['released'].astype(str).str.split(',')
</code></pre>
<p>I can not go on ... | <p>You can try this :</p>
<pre><code>import pandas as pd
df=pd.DataFrame({"t":["te,1723(hd k)","683, 7939(jod ls)"]})
df["year"]=df.t.str.split(r"[,(]",expand=True)[1]
print(df)
"""
t year
0 te,1723(hd k) 1723
1 683, 7939(j... | python|pandas | 0 |
9,758 | 68,681,725 | TypeError: 'Value' object is not iterable : iterate around a Dataframe for prediction purpose with GCP Natural Language Model | <p>I'm trying to iterate over a dataframe in order to apply a predict function, which calls a Natural Language Model located on GCP. Here is the loop code :</p>
<pre><code> model = 'XXXXXXXXXXXXXXXX'
barometre_df_processed = barometre_df
barometre_df_processed['theme'] = ''
barometre_df_... | <p>I think you are not iterating correctly.
The way to iterate through a dataframe is:</p>
<pre><code>for index, row in df.iterrows():
print(row['col1'])
</code></pre> | pandas|loops|google-cloud-platform|typeerror | 0 |
9,759 | 61,695,431 | Can't remove instances of a class | <p>I starting to code in python and using pyzero to make a simple game. After the end of the game, I want to delete all the existing instances of certain types of classes, to allow the game to start again. I have a list of all the instances of that class, but using remove(self) seems to cause a problem in the logic tha... | <p>Actually you remove objects from a list while you iterate through the list. Read <a href="https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating">How to remove items from a list while iterating?</a>, for more information about this topic.</p>
<p>Create a shallow copy of the list... | python|list|class|pygame|pgzero | 0 |
9,760 | 61,652,088 | Trying to find Mean returns for following stocks from yahoo finance | <pre><code>tickers = ['BIOCON.NS', 'HDFCBANK.NS', 'RELIANCE.NS', 'RADICO.NS', 'LTI.NS', 'TCS.NS', 'DRREDDY.NS','BAJFINANCE.NS']
pfolio_data = pd.DataFrame()
for t in tickers:
pfolio_data[t] = wb.DataReader(t, data_source='yahoo', start ='2017-1-1')['Adj Close']
pfolio_data_returns= (pfolio_data/pfolio_data.shift... | <p>What does the data in pfolio_data_returns look like ?<br>
Maybe this is what you are looking for:<br>
<a href="https://stackoverflow.com/questions/34923728/type-error-unhashable-type-list-while-selecting-subset-from-specific-columns">Type error: unhashable type 'list' while selecting subset from specific col... | python | 0 |
9,761 | 63,561,584 | Bayesian Optimisation via HParams and Tensorboard | <p>I'm currently using HParams to instigate a grid search hyperparameter optimisation session, which works fine, and is outputting logs to my tensorboard HParams plugin, and I can see the various different runs and the Parallel Co-Ordinates view. The code is structured like so, although it might not be necessary to rev... | <p>This is a long-time <a href="https://github.com/tensorflow/tensorboard/issues/2351" rel="nofollow noreferrer">open feature request</a> and is unfortunately still not currently implemented with the <code>HPARAMS</code> section but <code>Keras-tuner</code> will allow you to log the results of each run. Encoding the hy... | python|tensorflow|tensorboard|hyperparameters | 0 |
9,762 | 63,410,938 | Building a custom array from zeros and a given 1-d array | <p>I have a list that I want to build a kernel from <code>[90,50,10]</code></p>
<p>What I want to do is to get a kernel that looks like -</p>
<pre><code>[[90,0,0]
[50,0,0]
[10,0,0]
[0,90,0]
[0,50,0]
[0,10,0]
[0,0,90]
[0,0,50]
[0,0,10]]
</code></pre>
<p>I can implement this using a loop, AND I tried doing somet... | <p>you could do:</p>
<pre><code>s = np.array([90,50,10])
size = s.size
o = np.zeros((size ** 2, s.size))
o[np.arange(size**2), np.repeat(np.arange(size), size)] = np.tile(s, size)
print(o)
</code></pre>
<pre><code>[[90. 0. 0.]
[50. 0. 0.]
[10. 0. 0.]
[ 0. 90. 0.]
[ 0. 50. 0.]
[ 0. 10. 0.]
[ 0. 0. 90.]
... | python|numpy | 2 |
9,763 | 60,769,273 | How to convert hex values to floating point number in python | <p>I have hex value <code>4396 eccd</code>. If I convert it to floating point number using some <a href="https://gregstoll.com/~gregstoll/floattohex/" rel="nofollow noreferrer">online calculator</a>, I get value as <code>301.85</code> which is correct. </p>
<p>But when I convert it using python, I get some different v... | <p>For understanding what <code>fromhex()</code> do, you can refer this : <a href="https://python-reference.readthedocs.io/en/latest/docs/float/fromhex.html" rel="nofollow noreferrer">https://python-reference.readthedocs.io/en/latest/docs/float/fromhex.html</a></p>
<p>Instead of using <code>fromhex()</code> for hex st... | python-3.x|floating-point|hex | 2 |
9,764 | 68,920,889 | Integrate multiple mapped fields with spark | <p>I have a dataset that looks something like this:</p>
<pre><code>+-------+-----------------+-----------------+
| ID | mapCol1| mapCol2|
+-------+-----------------+-----------------+
| 1234 |Map(1m -> 1, |Map(1m -> 5, |
| | 3m -> 2, | 3m -> 6, |
| ... | <p>It can be done using map_zip_with function.
An example written in python:</p>
<pre><code>import pyspark.sql.functions as F
df = spark.createDataFrame([(1234, {"1m": 1, "2m": 2, "6m": 3, "9m": 4}, {"1m": 5, "2m": 6, "6m": 7, "12m": 8})],... | python|apache-spark|pyspark | 2 |
9,765 | 69,111,732 | Substring each element of an array column in PySpark 2.2 | <p>I would like to substring each element of an array column in PySpark 2.2. My df looks like the one below, which is
similar to <a href="https://stackoverflow.com/questions/63749555/parse-through-each-element-of-an-array-in-pyspark-and-apply-substring">this</a>, although each element in my df has the same length befor... | <p>Your udf approach works for me. Besides you can use <code>transform</code> with <code>substring</code>:</p>
<pre><code>import pyspark.sql.functions as f
df.withColumn('new_column', f.expr('transform(col1, x -> substring(x, 0, 5))')).show()
+--------------------+--------------------+
| col1| ... | python|arrays|pyspark|apache-spark-sql | 0 |
9,766 | 69,120,295 | Python: How can I populate rows between dates for each ID? | <p><strong>Objective:</strong> I want to plot out the current and leaving members each month.</p>
<p>So I have two dataframes (see below): <strong>Dataframe A</strong> has an ID, date they joined the club, and dates YTD as a row. <strong>Dataframe B</strong> has a start date, end date and membership type for each ID.</... | <p>First, you should ensure all the dates needed is in datetime format.</p>
<p>Next, get the join date and leave date for unique ID.</p>
<p>Merge them together and create columns then filter with the condition.</p>
<p>Sample code:</p>
<pre><code>df_a["Date"] = pd.to_datetime(df_a["Date"], errors = '... | python|sql|pandas|dataframe|date | 0 |
9,767 | 72,580,810 | Function modifies Pandas dataframe but can't access the modifed datarame | <p>I previously posted a question and code to SO about flattening JSON data that in retrospect was too convoluted so I've tried to simplify and post a new question (original question: <a href="https://stackoverflow.com/q/72413031/11620388">How to flatten a pandas dataframe with some columns as json? follow-up</a>).</p>... | <p>I suppose you didn't run the function correctly.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import numpy as np
def drop_col(df_in):
print(f"original shape: {df_in.shape}")
df_out = df_in.drop(['B'], axis=1)
print(f"final shape: {df_out.shape}")
return... | python|pandas|dataframe | 0 |
9,768 | 68,087,722 | Creating multiple data frames using for loop with conditions | <p>I have two data frames.</p>
<pre><code>DF1
col1 col2
price($) price(#)
dimension(m) dimension(inch)
color1 color2
</code></pre>
<pre><code>DF2
toyname price($) price(#) dimension(m) dimension(inch) color1 color2
t1 2 12 11 ... | <p>Assuming each row represents a different toy. Try with <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.set_index.html#pandas-dataframe-set-index" rel="nofollow noreferrer"><code>set_index</code></a> + <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.iterrows.html#pandas-d... | python|python-3.x|pandas|dataframe | 1 |
9,769 | 59,441,338 | combine pandas rows based on condition of columns (vectorized) | <p>I have this dataframe</p>
<pre><code>import pandas as pd
df = pd.DataFrame({"a":[None, None, "hello1","hello2", None,"hello4","hello5","hello6", None, "hello8", None,"hello10",None ] , "b": ["we", "are the world", "we", "love", "the", "world", "so", "much", "and", "dance", "every", "day", "yeah"]})
a b
0 N... | <p>First, create a Series which describes the groups:</p>
<pre><code>grouping = df.a.notnull().cumsum()
</code></pre>
<p>Then, for column a we can use the first element and for column b we want to concatenate all elements:</p>
<pre><code>df.groupby(grouping).agg({'a': 'first', 'b': ' '.join})
</code></pre>
<p>This ... | python|pandas|text|vectorization | 2 |
9,770 | 62,327,496 | eb config and .ebextensions/ - .ebextensions/ not working | <p>It is my understanding that editing the config via <code>eb config</code> and via <code>.ebextensions/</code> both do the same thing. Using <code>eb config</code> directly changes the config were using <code>.ebextensions/</code> changes the config but is scripted, thus repeatable.</p>
<p><strong>Is this correct?</... | <p>Here is what I did to fix this issue.</p>
<p><code>eb config</code></p>
<p>delete <em>WSGIPath: application</em></p>
<p>save and wait for reload</p>
<p><code>eb deploy</code></p>
<p>save and wait for reload</p>
<p><code>eb config</code></p>
<p>verify the changes from the file are made!</p> | python|django|amazon-elastic-beanstalk|ebcli | 0 |
9,771 | 58,990,153 | How to write a program that lives for a configurable period of time? | <p>I have written a script that runs for a certain amount of duration and this duration can be updated and the program should terminate after running for the updated duration.
For eg:
If I start a program that runs for 60 seconds and later before these 60 seconds have passed, I update the duration of the program to run... | <p>Use a global variable <code>extension</code> and update it when you get the new <code>time_interval</code>.</p>
<pre><code>def killer(sleep_time):
while sleep_time:
print ("sleeping - %s" % i)
time.sleep(1)
sleep_time += extension-1
extension = 0
</code></pre> | python|asynchronous | 0 |
9,772 | 58,847,248 | Increasing the loop speed | <p>I have 1 million loops to make. Is there anyway of processing this (and python loops in general) faster?</p>
<pre><code>import numpy
#in a population of 1000 individuals of the same species, one individual has an advantageous mutation
#before, the average quantity of newborns per each 2 individuals per generation w... | <p>There are two ways in general to make a loop faster:</p>
<ol>
<li>Make the thing you're doing inside the loop faster, so that the computer is doing less work to achieve the same result. This only works if you're able to find inefficiencies in your code and fix them.</li>
<li>Run more than one loop at the same time... | python|performance|loops | 0 |
9,773 | 31,288,739 | What is KeyError: 'string' in import? | <p>Does anyone can explain why it is happening? I have module that includes sale, now when i import product an error pops up saying:</p>
<pre><code> File "/opt/openerp/custom_server70_addons/extra-addons/base_import/models.py", line 220, in parse_preview
fields = self.get_fields(cr, uid, record.res_model, contex... | <p>It seems one of your field does not have string.</p>
<p>Ex:</p>
<pre><code>'my_field': fields.char(string='my string')
</code></pre>
<p>Check your all the fields and add string label in your field and try to import the records again.</p> | python-2.7|openerp|openerp-7 | 0 |
9,774 | 60,297,705 | Spark dataFrame taking too long to display after updating its columns | <p>I have a dataFrame of approx. 4 million rows and 35 columns as input.</p>
<p>All I do to this dataFrame is the following steps:</p>
<ul>
<li>For a list of given columns, I calculate a sum for a given list of group features and joined it as new column to my input dataFrame</li>
<li>I drop each new column sum right ... | <p>This happens due to the inner workings of Spark and its lazy evaluation.</p>
<p>What Spark does when you call <code>groupby</code>, <code>join</code>, <code>agg</code>, it attaches these calls to the plan of the <code>df</code> object. So even though it is not executing anything on the data, you are creating a larg... | python|dataframe|pyspark | 5 |
9,775 | 60,245,789 | Mutli indexing using pandas | <p>df</p>
<pre><code>ITEM CATEGORY COLOR
48684 CAR RED
54519 BIKE BLACK
14582 CAR BLACK
45685 JEEP WHITE
23661 BIKE BLUE
</code></pre>
<p>I tried using the below code </p>
<pre><code>df.groupby(['CATEGORY', 'COLOR']).size().unstack(f... | <p>I believe you need <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html" rel="nofollow noreferrer"><code>DataFrame.set_index</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_index.html" rel="nofollow noreferrer"><co... | python|pandas | 1 |
9,776 | 72,311,674 | subtracting time intervals from column dates in dataframes Pandas Python | <p>How would I be able to subtract 1 second and 1 minute and 1 month from <code>data['date']</code> column?</p>
<pre><code>import pandas as pd
d = {'col1': [4, 5, 2, 2, 3, 5, 1, 1, 6], 'col2': [6, 2, 1, 7, 3, 5, 3, 3, 9],
'label':['Old','Old','Old','Old','Old','Old','Old','Old','Old'],
'date': ['2022-01-24... | <p>Your <code>date</code> column is of type string. Convert it to <code>pd.Timestamp</code> and you can use <code>pd.DateOffset</code>:</p>
<pre class="lang-py prettyprint-override"><code>pd.to_datetime(data["date"]) - pd.DateOffset(months=1, minutes=1, seconds=1)
</code></pre> | python|python-3.x|pandas|numpy|datetime | 1 |
9,777 | 50,473,617 | How to authorize colab with Github? | <p>When selecting option on Google colab "Save a copy on Github" I receive message : </p>
<p><a href="https://i.stack.imgur.com/Sypkh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Sypkh.png" alt="enter image description here"></a></p>
<p>From reading <a href="https://medium.com/tensorflow/colab-a... | <p>Saving notebook to github in colab is a simple two step process. Just click <code>Save a copy in github</code> and <code>authorize googlecolab for git</code>.</p>
<p><strong><em>The first popup :</em></strong>
<a href="https://i.stack.imgur.com/4yCPg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.co... | github|tensorflow|google-colaboratory | 3 |
9,778 | 50,407,526 | Deformable convolution in tensorflow | <p>I tried to use the <code>tensorlayer</code> in python 3.5 to run a simple code. I have this error::</p>
<pre><code>[TL] DeformableConv2d ab: n_filter: 32, filter_size: (3, 3) act:relu
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/anaconda3/lib/python3.5/site-pack... | <p>A bug fix has been implemented, however we have not released it yet.
If you wish to install TL from sources, you can do the following:</p>
<pre><code>pip uninstall tensorlayer
pip install --upgrade tensorflow # if you do not use GPU support
pip install --upgrade tensorflow-gpu # if you use GPU support
pip ins... | python|tensorflow | 3 |
9,779 | 44,823,426 | pip install mysql-connector-python installation error | <p>I'm getting an error after installing MySQL Connector for Python 2.7.9 in Linux OS.</p>
<blockquote>
<p>Command /usr/bin/python -c "import setuptools,
tokenize;<strong>file</strong>='/tmp/pip-build-5nxFZ_/mysql-connector-python-rf/setup.py';exec(compile(getattr(tokenize,
'open', open)(<strong>file</strong>).r... | <p>try this ,</p>
<pre><code>pip install MySQL-python==1.2.5 # version specified
</code></pre>
<p>or </p>
<pre><code>pip install MySQL-python
</code></pre> | python|mysql | 2 |
9,780 | 55,192,603 | How do I get a program to calculate the pay raise for each employee from a file? | <p>Here is the problem I am trying to solve for my introduction to programming course:</p>
<p>The trustees of a small college are considering voting a pay raise for their faculty
members. They want to grant a 7 percent raise for those earning more than $50,000.00,
a 4 percent raise for those earning more than $60,000.... | <p>For now i will avoid looking at how you display the pay raises of each employees as your print statements appear to do that already? Without your 'program7.txt' file i cant see what is actually being produced though so perhaps you can edit the question to describe your current and desired outputs.</p>
<p>Instead I'... | python|file | 0 |
9,781 | 55,426,411 | How can I fix my integrated vscode termnial | <p>So i'm trying to set up my <code>vscode</code> to run python, it works but the issue is I set it up in a way that when I type <code>./helloworld.py</code> in the integrated terminal, it opens up <code>pycharm</code> and I don't want that. I want it to open up python shell or output <code>"hello world"</code> in the ... | <p>The best way to run your file is to open your files in the editor window and then move your cursor to the editor window and right click. You get a pane that looks like so.</p>
<p><a href="https://i.stack.imgur.com/ndTzi.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ndTzi.jpg" alt="enter image d... | python|visual-studio-code | 0 |
9,782 | 53,938,985 | Flask render_template where HTML is in S3 | <p>Can I have templates stored in S3 send to render_template ?</p>
<pre><code>application_root = config.get_application_root()
static_folder = os.path.join(application_root, 'static')
template_folder = os.path.join(application_root, 'templates')
app = Flask(__name__, static_url_path='/static', static_folder=static_fol... | <p>Use <code>render_template_string</code> instead of <code>render_template</code>:</p>
<p><a href="http://flask.pocoo.org/docs/1.0/api/#flask.render_template_string" rel="nofollow noreferrer">http://flask.pocoo.org/docs/1.0/api/#flask.render_template_string</a></p> | python|amazon-s3|flask | 0 |
9,783 | 57,250,384 | how to sort a datatable frame in descending order | <p>I'm trying to apply a sort on one field(total product ratings per each country) in a Frame, and here ascending is worked out, all the products are displayed in an ascending order </p>
<p>I have looked for it(sort options) in documentation, however its info is not written down/available.</p>
<p>a[:,:,sort("totals")... | <p>In order to sort a column in descending order, you can put a <code>-</code> sign in front of that column. This works both for numeric and for string columns. For example:</p>
<pre class="lang-py prettyprint-override"><code>>>> import datatable as dt
>>> from datatable import f, sort
>>> A... | python|datatable | 3 |
9,784 | 24,292,200 | What are the differences between HoughCircles in EmguCV and OpenCV? | <p>I'm trying to detect the circles in this image using EmguCV 2.2 with C#, but not having any luck.</p>
<p><img src="https://i.stack.imgur.com/Ndh3z.png" alt="enter image description here"></p>
<p>Using OpenCV with the cv2 python package the following code correctly finds the 8 circles in the above image:</p>
<pre>... | <p>I used the following code for finding Hough Circles </p>
<pre><code>Image<Bgr, byte> Img_Result_Bgr = new Image<Bgr, byte>(Img_Source_Gray.Width, Img_Source_Gray.Height);
CvInvoke.cvCvtColor(Img_Source_Gray.Ptr, Img_Result_Bgr.Ptr, Emgu.CV.CvEnum.COLOR_CONVERSION.CV_GRAY2BGR);
Gray cannyThreshold = new ... | c#|python|opencv|emgucv | 5 |
9,785 | 24,006,430 | python error in get trending topic using tweepy | <p>I am trying to get top 20 trending topic through twitter api based on the Tweepy library. </p>
<p>Here is my python code: </p>
<pre><code>import tweepy
import json
import time
today = time.strftime("%Y-%m-%d")
CONSUMER_KEY = ""
CONSUMER_SECRET = ""
ACCESS_KEY = ""
ACCESS_SECRET = ""
auth = tweepy.OAuthHandler... | <p>I believe that you're using tweepy version 1 which is <a href="https://dev.twitter.com/docs/api/1/get/trends/daily" rel="nofollow">no longer supported</a>: <a href="https://api.twitter.com/1/trends/daily.json" rel="nofollow">https://api.twitter.com/1/trends/daily.json</a></p>
<p>Try to re-install (version 1.1), for... | python|tweepy | 2 |
9,786 | 24,388,528 | Abaqus Python script to open several odb files by variable name | <p>I have a txt-file called "odbList.txt" which contains the names of several odb-files.</p>
<pre><code>plate_2mm.odb
plate_4mm.odb
plate_6mm.odb
</code></pre>
<p>Now I wrote a Python Script, where I want to open each of these files in a loop.</p>
<pre><code> # list of ODB-Files
odbList = [ ]
f = file( 'W... | <p>Have you tried entering your string as a raw string like this<code>odb = openOdb(path = r'W:/someDirectory/' + case)</code> or usining the os.sep character like this: <code>odb = openOdb(path = 'W:someDirectory' + os.sep + case)</code></p> | python | 0 |
9,787 | 45,879,045 | binascii.Error: Incorrect padding, even when string length is multiple of 4 | <p>I am trying to convert base64 string to image by python code, but I am getting <strong>binascii.Error: Incorrect padding</strong> I have gone through with my <a href="https://stackoverflow.com/a/9807138">solution</a> but they only suggest check string length is divisible 4, if not make it divisible by 4 by adding '... | <p>by checking your link, your string has 200000 bytes all right, <em>but</em> it contains the header:</p>
<pre><code>strOne = b"data:image/png;base64,iVBORw0KGgoAAAANSU...
</code></pre>
<p>This is part of MIME message or something. You have to strip this first.</p>
<pre><code>strOne = strOne.partition(",")[2]
</cod... | python|python-2.7|base64 | 10 |
9,788 | 41,104,802 | Plotting of a Dataframe - Python | <p>I am pretty sure you can help. I am just writing my thesis in social media mining and I am pretty new to this kind of stuff so please be patient with me ;)</p>
<p>I am doing a opinion mining on twitter, for that I have streamed a lot of tweets. i have then clustered the tweets for certain periods, for example: all ... | <p>If you have your data stored as a dictionary I would recommend that you just put it in a pandas DataFrame using pandas.DataFrame.from_record. You can then just plot the data using DataFrame.plot. Below is an example that creates a multi-index pandas DataFrame, resets the level and then plots the opinion vs datetime.... | python|datetime|twitter|plot|dataframe | 0 |
9,789 | 38,699,927 | Django: Know when a file is already saved after usign storage.save() | <p>So I've a Django model which has a FileField. This FileField, contains generally an image. After I receipt the picture from a request, I need to run some picture analysis processes. </p>
<p>The problem is that sometimes, I need to rotate the picture before running the analysis (which runs in celery, loading the mod... | <p>No magic solution here. You have to manage states on your model, specially when working with celery tasks. You might need another field called <code>state</code> with the states: <code>NONE</code> (no action is beeing done), <code>PROCESSING</code> (task was sent to celery to process) and <code>DONE</code> (image wa... | python|django|amazon-web-services|amazon-s3 | 0 |
9,790 | 40,370,800 | Insert result of sklearn CountVectorizer in a pandas dataframe | <p>I have a bunch of 14784 text documents, which I am trying to vectorize, so I can run some analysis. I used the <code>CountVectorizer</code> in sklearn, to convert the documents to feature vectors. I did this by calling:</p>
<pre><code>vectorizer = CountVectorizer
features = vectorizer.fit_transform(examples)
</code... | <p>Return term-document matrix after learning the vocab dictionary from the raw documents.</p>
<pre><code>X = vect.fit_transform(docs)
</code></pre>
<p>Convert sparse csr matrix to dense format and allow columns to contain the array mapping from feature integer indices to feature names.</p>
<pre><code>count_vect_df... | python|pandas|machine-learning|scikit-learn | 34 |
9,791 | 26,072,087 | Pandas: number of days elapsed since a certain date | <p>I have a dataframe with a 'date' column with ~200 elements in the format yyyy-mm-dd.</p>
<p>I want to compute the number of days elapsed since 2001-11-25 for each of those elements and add a column of those numbers of elapsed days to the dataframe.</p>
<p>I know of the to_datetime() function but can't figure out h... | <p>Assuming your time values are in your index, you can just do this:</p>
<pre><code>import pandas
x = pandas.DatetimeIndex(start='2014-01-01', end='2014-01-06', freq='30T')
df = pandas.DataFrame(index=x, columns=['time since'])
basedate = pandas.Timestamp('2011-11-25')
df['time since'] = df.apply(lambda x: (x.name.... | python|date|pandas|dataframe | 10 |
9,792 | 32,805,937 | how do I import an array containing dictionary from a text file? | <p>I have a text file with cookies inside. It looks like this: </p>
<pre><code>[{"key":"value", "key":"value", "key":"value"},
{"key":"value", "key":"value", "key":"value"},
{"key":"value", "key":"value", "key":"value"},
{"key":"value", "key":"value", "key":"value"}]
</code></pre>
<p>I store it into a string varia... | <p>Since your input seems formatted as JSON, look into the <code>json</code> module. It will do the parsing for you: <a href="https://docs.python.org/3.4/library/json.html" rel="nofollow">https://docs.python.org/3.4/library/json.html</a></p>
<pre><code>import json
with open(filename,'r') as f:
data = json.load(f)
... | python|arrays|python-3.x|dictionary | 3 |
9,793 | 36,796,495 | odoo ValueError("Expected singleton: %s" % self) | <p>I got error in odoo when I select 2 reports and push "print_report" button:</p>
<pre><code> 2016-04-22 14:04:34,682 2656 ERROR talm openerp.http: Exception during JSON request handling.
Traceback (most recent call last):
File "/opt/odoo/openerp/http.py", line 643, in _handle_exception
... | <p>problem is in <code>stock_write_off</code>.py</p>
<pre><code> File "/ksi/addons/talm/wizard/stock_write_off.py", line 20, in print_report
data['report_ids'] = self.report_ids.id
</code></pre>
<p>just use <strong>self.report_ids.ids</strong> instead of self.report_ids.id</p>
<p>this will be correct syntax:
da... | python-2.7|openerp|odoo-9 | 3 |
9,794 | 48,855,921 | Can't get my program to animate circles in 2D in matplotlib | <p>I am trying to animate <code>n</code> circles in 2D with <code>matplotlib</code>, but when run, my code only shows one circle, stationary, regardless of what I make <code>n</code>. Does anyone know how to fix it, and what is wrong with it?</p>
<pre><code>%matplotlib notebook
import numpy as np
from matplotlib impor... | <p>Two problems:</p>
<ol>
<li>The indentation is wrong. You need to return from the function not from within the loop.</li>
<li>You need to return an iterable of artists, not a single artist, because you want all artists to update.</li>
</ol>
<p>Complete code:</p>
<pre><code>import numpy as np
from matplotlib import... | python|animation|matplotlib|plot | 1 |
9,795 | 70,426,256 | How to schedule a production python script to trigger a function to run at a specified time every Day | <p>I am trying to schedule a python script(function) that get's data from a database (source DB) and dump them into an S3 bucket(destination DB). This would be used in production and I want a schedule that triggers this job to run at a particular time every day without human intervention. Please how do I go about this.... | <p>Do you need this script to work on Windows or use less than a minute intervals? If not, then it's easier to set up a <em>cron job</em> to call your script when needed. The script then contains only the task itself:</p>
<pre><code>#!/usr/bin/env python3
from datetime import datetime
if __name__ == '__main__':
p... | python|scheduled-tasks|scheduler | 0 |
9,796 | 49,824,899 | Can't get a GET response in DJango Rest | <p>I'm trying to learn DJango Rest so I made a litte test to see if I could obtain some things from the database, but I'm getting some problems.</p>
<p>Here's my models.py:</p>
<pre><code>from django.db import models
# Create your models here.
class Stock(models.Model):
ticker = models.CharField(max_length=10)... | <p>You need to remove <code>self</code>.</p>
<p>Remember you are using functions not clases. </p>
<pre><code>@api_view(['GET', 'POST'])
def stock_list(request, format=None):
if request.method == 'GET':
stocks = Stock.objects.all()
serializer = StockSerializer(stocks, many=True)
return Res... | python|django|django-rest-framework | 0 |
9,797 | 66,491,482 | Rotations Matrix | <p>You are given a square matrix A of dimensions NxN. You need to apply the below given 3 operations on matrix A.</p>
<p>Rotation: It is represented as R S where S is an integer in {90, 180, 270, 360, 450, ...} which denotes the number of degrees to rotate. You need to rotate matrix A by angle S in the clockwise direct... | <p>You are very close. Of course you knew that. :)</p>
<p>The problem you are having is that you are not explicitly following the instruction for the Update action. It says you should apply the update to the <em>original matrix</em> and then re-rotate it. You are applying the update to the <em>already rotated matri... | python|python-3.x|matrix | 2 |
9,798 | 64,874,882 | Add rows for missing hourly data in a pandas dataframe | <p>I have a pandas dataframe with 2 columns: <code>Created'(%Y-%m-%d %H)</code> and <code>Count</code> which is an integer.</p>
<p>It is counting the amount of "tickets" registered per hour.</p>
<p>The problem is that there are many hours in the day that there are not registered any tickets.</p>
<p>I would li... | <p>You can resample with:</p>
<pre><code>import datetime
import pandas as pd
df = pd.DataFrame({
'Created': ['2020-10-26 10', '2020-10-26 08','2020-10-26 09','2020-10-26 07','2020-10-26 06'],
'count': [11, 10,14,16,20]})
df['Created'] = pd.to_datetime(df['Created'], format='%Y-%m-%d %H')
df.sort_values(by=['Created... | python|pandas|dataframe | 0 |
9,799 | 53,212,335 | Python regex get all matches all with findall | <p>Suppose I have this string:</p>
<pre><code>string = 'start asf[2]+asdfsa[0]+fsad[1]'
</code></pre>
<p>I would like to extract the integers above into an array in the order in which they appear in the string:</p>
<pre><code>[2, 0, 1]
</code></pre>
<p>I've tried findall but it doesn't work:</p>
<pre><code>print r... | <p>Here is one approach</p>
<pre><code>>>> regex = re.compile("(?<=\[)([0-9]){1}?(?=\])")
>>> string = 'start asf[2]+asdfsa[0]+fsad[1]'
>>> re.findall(regex, string)
['2', '0', '1']
</code></pre>
<p><strong>DEMO</strong></p>
<pre><code>>>> import re
>>> def get_all_int... | python|regex | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.