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 |
|---|---|---|---|---|---|---|
7,800 | 13,372,802 | Parsing Nested XML Data in Python Using ElementTree | <h2>Updates: Towards a Solution</h2>
<p>This code:</p>
<pre><code>tree = ET.parse(assetsfilename)
root = tree.getroot()
assets = {}
def find_rows(rowset, container):
for row in rowset.findall("row"):
singleton = int((row.get('singleton')))
flag = int((row.get('flag')))
quantity = ... | <p>This snippet (somewhat larger) recursively parses the xml structure into nested dictionaries, like you described a possible solution. It works with the sample you provided, but I think it will work with live data anyway. If nothing else, you can use the idea.</p>
<p><strong>UPDATE:</strong> Ok, this updated version... | python|xml|elementtree | 1 |
7,801 | 43,787,083 | How to run in atom a command in the terminal? | <p>I'm doing a school project about changing my wallpaper from python and it works in the terminal perfectly but I need to do it from my text editor, atom, and it doesn't seem to work. I've tried rearranging the apostrophes as maybe it's that, but can't seem to make it work.</p>
<p>This works on the terminal perfectly... | <p>You need to escape those double quotes and remove <code>subprocess</code>:</p>
<pre><code>from subprocess import call
call(["osascript -e 'tell application \"System Events\" to set picture of every desktop to (\"/Users/carlaa/Desktop/DEVf/python/APODkata/apodimage.jpg\" as POSIX file as alias)'", shell=True])
</cod... | python|terminal|atom-editor | 1 |
7,802 | 54,632,981 | Updating loaded data in flask restful api app | <p>I'm looking for the best option to reload data in a deployed app. Best is defined as, must not result in 500s and must update the data (not fail silently), should not block working for too long, but no 500s and update is the priority. </p>
<p>The app is a CPU limited app, which I'm scaling by adding more workers an... | <p>There are different approaches to your task and it depends on what your constrains on how fast workers need to catch up to new values, how you announce them when this value changes and what is your performance requirements. What those solutions share, is that it's easier to control <code>carlist</code> when it's a c... | python|flask|gunicorn|flask-restful | 1 |
7,803 | 54,292,794 | Reverse the order of a data frame columns | <p>Is <code>df.reindex(columns=reversed(df.columns))</code> the fastest way to reverse a <code>pandas.DataFrame</code> by column?</p> | <p>One idea - use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>DataFrame.iloc</code></a> with indexing:</p>
<pre><code>df = df.iloc[:, ::-1]
</code></pre>
<p><strong>Performance</strong>:</p>
<pre><code>np.random.seed(234)
df = pd.DataFra... | python|python-3.x|pandas | 3 |
7,804 | 9,245,845 | serializing datetime with flasks tojson filter | <p>I'm getting this error:</p>
<pre><code>TypeError: datetime.datetime(2012, 2, 12, 0, 47, 6, 542000) is not JSON serializable
</code></pre>
<p>when jinja is trying to parse this line:</p>
<pre><code>var root_node_info = eval({{ nd|tojson|safe }});
</code></pre>
<p>nd contains a bson object from my mongo database. ... | <p>JSON does not handle <code>datetime</code> objects. Standard practice is to encode them as strings in ISO format. This <a href="https://stackoverflow.com/questions/8011081/cannot-serialize-datetime-as-json-from-cherrypy">SO question about JSON</a> provides examples. You will need to <a href="http://flask.pocoo.org/d... | python|serialization|mongodb|flask|jinja2 | 5 |
7,805 | 9,334,259 | Python string as file argument to subprocess | <p>I am trying to pass a file to a program (MolPro) that I start as subprocess with Python.</p>
<p>It most commonly takes a file as argument, like this in console:</p>
<pre><code>path/molpro filename.ext
</code></pre>
<p>Where filename.ex contains the code to execute. Alternatively a bash script (what I'm trying to ... | <p>It seems like your second method should work if you remove <code>StdinCommand</code> from the <code>Popen()</code> arguments:</p>
<pre><code>p = Popen(['/vol/thchem/x86_64-linux/bin/molpro'], shell = False, stdout = None, stderr = STDOUT, stdin = PIPE)
p.communicate(input = StdinCommand)
</code></pre> | python|string|file|subprocess | 8 |
7,806 | 55,342,156 | Redshift queries not working with psycopg2 | <p>I am creating a Python script to interact with schema permissions (and relative tables) on Redshift. As suggested in some other StackOverflow posts I am using psycopg2 library.</p>
<p>When I try to execute some simple <code>SELECT FROM</code> queries I have no problems: I can execute and see results with no issues.... | <p>You have to commit the transaction. </p>
<pre><code>con = psycopg2.connect(conn_string)
sql = "CREATE SCHEMA new_schema"
cur = con.cursor()
cur.execute(sql)
con.commit()
</code></pre> | python|amazon-redshift|psycopg2 | 2 |
7,807 | 52,790,516 | How can I create a pattern from SMS text string? | <p>I have a sample sms "Spent Rs 300.00 at Shop Name from card number XXXX2123". It's like assume any bank sms you receive in mobile after your transaction.</p>
<p>I need to write a robust program in python. </p>
<p>I came up with the following solution thinking about only given string. </p>
<pre><code>def split_str... | <p>The following code works for the sample SMS:</p>
<pre><code>import re
def split_str(s):
print('Spent/Added:',re.sub('.*(Spent|Added).*', '\\1', s))
print('Amount Type:', re.sub('.*?\s+?([a-zA-Z\W]+)\s+?[0-9]+.*', '\\1', s))
print('Amount:',re.sub('.*?[A-Za-z\W]+(.*?)\sat.*', '\\1', s))
print('Locati... | python|python-3.x|python-2.7 | 1 |
7,808 | 47,880,019 | PyQ: How to enumerate symbol column on a splayed table? | <p>I'm trying to create a splayed table with a symbol column using pyq. In q I would set the table by enumerating the symbol column with <code>.Q.en</code>...</p>
<pre><code>:splay/ set .Q.en[`:splay;]([]a:`x`y`z; b:1 2 3)
</code></pre>
<p>I tried a few variations of the following...</p>
<pre><code>q.set(':splay/', ... | <p>First, your q code is incorrect. The function</p>
<pre><code>.Q.en[`:splay;]
</code></pre>
<p>will place the <code>sym</code> file inside the splay table and this is not what you want. Instead, the <code>sym</code> file should be saved in the top database directory (<code>db</code> in the code below) next to the... | python|python-3.x|kdb|pyq | 3 |
7,809 | 47,880,657 | Pandas reorder rows based on smallest to largest values in a column | <p>I want to reorder rows based on column 9 value's in a data-frame (lowest value to largest) in ascending order for large dynamic data.</p>
<p>My data-frame:</p>
<pre><code>1 2 3 4 5 6 7 8 9 #Column values in this row
a b c d e f g h 0
a1 b1 c1 d1 dd1 ef ggg hh 0.5
aaa bbb ccc ... | <p>You need parameter <code>inplace=True</code>:</p>
<pre><code>df1.sort_values('9', inplace=True)
print (df1)
1 2 3 4 5 6 7 8 9
2 aaa bbb ccc ddd eee fff ggg dcx -0.5
0 a b c d e f g h 0.0
1 a1 b1 c1 d1 dd1 ef ggg hh 0.5
3 z b c... | python|python-3.x|pandas|numpy|dataframe | 2 |
7,810 | 37,324,332 | How to find the nearest neighbors for latitude and longitude point on python? | <p><strong>Input:</strong></p>
<pre><code>point = (lat, long)
places = [(lat1, long1), (lat2, long2), ..., (latN, longN)]
count = L
</code></pre>
<p><strong>Output:</strong>
<code>neighbors</code> = subset of <code>places</code> close to the <code>point</code>. (<code>len(neighbors)=L</code>)</p>
<p><strong>Question... | <p>I honestly don't know if using a kd-tree would work correctly, but my hunch says it would be inaccurate.</p>
<p>I think you need to use something like greater circle distance to get accurate distances.</p>
<pre class="lang-py prettyprint-override"><code>
from math import radians, cos, sin, asin, sqrt, degrees, ata... | python|geolocation|scipy|nearest-neighbor|kdtree | 4 |
7,811 | 37,522,508 | How to iterate over GQLQuery objects when an attribute exists for only some of them | <p>So I'm building a basic blog where I've also implemented an IP address API to store the user's location. I've used <a href="http://ip-api.com" rel="nofollow">this website</a>'s API to get the latitude and longitude of the user. This is the <code>Entries</code> class which is used to store each entry - </p>
<pre><co... | <p>I managed to solve the problem. </p>
<p>I used a <code>filter</code> instead of the <code>for</code> loop inside <code>MainPage</code>. </p>
<pre><code>points = filter(None, (e.coords for e in entries))
</code></pre>
<p>This seemed to work and displayed the list of coordinates. (Though I still do not understand w... | python|python-2.7|api|google-app-engine|google-cloud-datastore | 1 |
7,812 | 34,011,544 | plotting a graph from a 9x1064 table in python | <p>I have a text file that contains a table with 9 columns and 1067 rows and I would like to extract the second and sixth columns in order to plot one against the other.
<a href="http://i.stack.imgur.com/sluTj.png" rel="nofollow">This is the first 10 rows of my text file</a> . I would just like to be able to import th... | <p>Use numpy and matplotlib.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt(filename, skiprows = 1)
plt.plot(data[:,5], data[:,1])
plt.show()
</code></pre> | python|text|plot | 0 |
7,813 | 34,286,973 | Prevent multiple logins using the same credentials | <p>I checked previously asked similar Questions, but I am not able to find a suitable answer.</p>
<p>Requirement: On two different machines the same user credentials can't be used to access the application.</p>
<p>What I have implemented, At the time of login, logout from all previous devices used by user.</p>
<pre>... | <p>Django generates a session key and saves it in the db everytime a user logs in. If user logs in from another browser/device Django creates a new session key without deleting the old one.</p>
<p>If you want to log the user out of other devices, you just need to delete his/her previous session key from db.</p>
<p>Sinc... | python|django|python-2.7|django-models | 9 |
7,814 | 72,713,769 | T-SNE for better data visualization | <p>My dataset shape is <code>(248857, 11)</code>
This is how it looks like before StandartScaler. I performed clustering analysis because of those clustering algorithms such as K-means do need feature scaling before they are fed to the algo.
<a href="https://i.stack.imgur.com/9mjn6.png" rel="nofollow noreferrer"><img s... | <p>It seems you need to tune the <code>perplexity</code> hyper-parameter which is:</p>
<blockquote>
<p>a tunable parameter that says (loosely) how to balance attention between local and global aspects of your data. The parameter is, in a sense, a guess about the number of close neighbors each point has. The perplexity ... | python|machine-learning|cluster-analysis|unsupervised-learning|tsne | 1 |
7,815 | 39,701,525 | Export Python-Scopus API results into CSV | <p>I'm very new to Python so not sure if this can be done but I hope it can!</p>
<p>I have accessed the Scopus API and managed to run a search query which gives me the following results in a pandas dataframe:</p>
<pre><code> search-results
entry ... | <p>first you need to get all the results (see comments under question).
The data you need (search results) is inside the "entry" list.
You can extract that list and append it to a support list, iterating until you got all the results. Here i cycle and at every round i subtract the downloaded items (count) from the tota... | python|csv|python-3.5|scopus | 0 |
7,816 | 16,503,341 | Parser in dateutil fails to render hour correctly | <p>Perhaps I am missing something obvious, but does anyone know why the parser from dateutil fails to render the following hour correctly? (The hour should be 20 instead of 0.)</p>
<pre><code>>>> from dateutil import parser
>>> parser.parse("20130501200439+01'00'")
datetime.datetime(2013, 5, 1, 0, 4,... | <p>The parser doesn't seem to accept the form of tz data in the string. Removing the single quotes seems to work:</p>
<pre><code>>>> parser.parse("20130501200439+01'00'".replace("'", ""))
datetime.datetime(2013, 5, 1, 20, 4, 39, tzinfo=tzoffset(None, 3600))
</code></pre> | python|python-dateutil | 1 |
7,817 | 31,690,036 | Python HDF5 Sparse Out of Core Datasets | <p>How do you store sparse NDArrays on disk in Python?</p>
<p>I am answering my own question because I wasted almost a week trying to get sparse out of core matrices. Perhaps this is obvious to some, but not to me and perhaps another poor soul!</p> | <p>Hinted by the accepted answer <a href="https://stackoverflow.com/questions/3545349/sparse-array-support-in-hdf5">here</a> and then tested with datasets made by <a href="http://docs.h5py.org/en/latest/high/dataset.html" rel="nofollow noreferrer">h5py</a>, the following time series test worked.</p>
<pre><code>>>... | python|multidimensional-array|sparse-matrix | 0 |
7,818 | 40,336,475 | things won't install on AWS EC2 because I have pip 8.1.2 instead of 6.1.1 | <p>I have run into this numerous times on my current project and it's driving me crazy. I discover I need to install some module but get an error that pip 6.1.1 isn't installed (server has 8.1.2):</p>
<pre><code>$ sudo pip install djangorestframework
Traceback (most recent call last):
File "/usr/bin/pip", line 5, i... | <p>not sure how to really resolve what I was dealing with, but it turns out the project's <code>virtualenv</code> had a satisfactory version of pip. for people in the future, try to activate the virtual env:</p>
<pre><code>$ source projectenv/bin/activate
</code></pre>
<p>and then install</p>
<pre><code>$ sudo pip ... | python|amazon-web-services|amazon-ec2|pip | 0 |
7,819 | 10,074,808 | Django cms installation in windows 7 | <p>I've got trouble executing a django-cms project in windows (but I've tried and everything is ok in linux and mac)
I've followed the process described in this page
<a href="https://www.django-cms.org/en/documentation/" rel="nofollow">https://www.django-cms.org/en/documentation/</a>
The error I've got is</p>
<pre><c... | <p>Edit the settings.py file and make sure that the ROOT_URLCONF points to the place where you stored your urls. (Maybe "[appname].urls") I usually prefer to keep urls at project-root level anyhow.</p> | python|django-cms | 1 |
7,820 | 10,093,503 | XML data not appearing in HTML page | <p>I'm trying to get XML data to appear on an HTML page. I'm using Django to generate the content in the XML file, and Javascript to ping back every five seconds to see if there have been new posts to load them into the page.</p>
<p>Here is my XML file:</p>
<pre><code><?xml version="1.0" ?>
{% for post in p... | <p>You have a syntax error: </p>
<p><code>request.readState</code></p>
<p>should be</p>
<p><code>request.readyState</code></p>
<p>readState is always not equal to 4.</p> | javascript|python|xml|ajax|django | 0 |
7,821 | 10,114,985 | Cannot upgrade/Install plugins on Eclipse for OS X | <p>I was trying to install the PyDev plugin for Eclipse on OS X and I realized I cannot access the "Find and Install" option. When I go to Help > Software Update both the "Find and Install" and "Manage Configuration" are grayed out.</p>
<p>Since I am running Eclipse 3.6.0 I thought an upgrade to 3.7 might fix it, but ... | <p>Not sure why it's disabled in your case, but anyways, when upgrading to a newer version of Eclipse, don't use the update menu, always grab a new version from Eclipse.org and reinstall the plugins you use (i.e.: to get Eclipse 3.7) -- note: just point to the same workspace you had previously after you update all the ... | python|eclipse|eclipse-plugin|pydev | 1 |
7,822 | 10,158,864 | Running Xvfb and CutyCapt as Python subprocess | <p>I'm an trying to take a screenshot in the background using <a href="http://cutycapt.sourceforge.net/" rel="nofollow">CutyCapt</a></p>
<p>My application is written in python and calls CutyCapt by running a subprocess.</p>
<p>Works locally (windows) just fine, but the CutyCapt.exe for windows does not require an x s... | <p>On Ubuntu 11.10, with the cutycapt and xvfb packages installed, the following works (at least for me...):</p>
<pre><code>import shlex
import subprocess
def url_screengrab(url, **kwargs):
cmd = '''xvfb-run --server-args "-screen 0, 1100x800x24"
/usr/bin/cutycapt --url={u} --out=temp.png '''.format(... | python|subprocess|xvfb|cutycapt | 7 |
7,823 | 60,173,621 | Python: errno13: Permission denied when trying to copy folders | <p>Been through the numerous other '<code>errno13</code>' posts, but found nothing that helps here. </p>
<p>The file directory is as follows: </p>
<pre><code>C:\\Users\\My HP\\Desktop\\Python\\Automate_the_boring_stuff\\Misc\\Eating\\Pie\\carrot.txt
</code></pre>
<p>And here's my code for copying folders: </p>
<pre... | <pre><code>import os
path = r"D:\test"
file_path = r"D:\tmp.txt"
while(True):
print(len(path))
os.mkdir(path)
new_file_path = os.path.join(path,file_path)
os.rename(file_path,new_file_path)
file_path = new_file_path
path = os.path.join(path,"test")
</code></pre>
<p>the above make a longer path ... | python|errno | 0 |
7,824 | 44,115,204 | Count red pixel values and plot histogram in Python | <p>I have a set of images that are located in 3 separate folders, based on their Type. I want to iterate through every Type and count the red pixel values of every image. I have set a limit for red, being in range from 200 to 256. I want to create histograms for each type and later cluster the histogram and discriminat... | <p>This is the solution I came up with. I have taken the liberty to refactor and simplify your code a bit. </p>
<pre><code>import os
import glob
import numpy as np
import matplotlib.pyplot as plt
from skimage import io
root = 'C:\Users\you\imgs' # Change this appropriately
folders = ['Type_1', 'Type_2', 'Type_3']
ex... | python|opencv|numpy|image-processing|scikit-image | 2 |
7,825 | 32,798,426 | How can I render and cache a view programatically in Django? | <p>I have a view in Django that is very slow to render. I'd like to render this view and cache it programmatically but haven't figured out how to do so. Is there any simple way to simply invoke my <code>StatusView</code> and get the markup as a string so I can cache it?</p>
<p>Here's my view with the cache decorator:<... | <p>It took a bit of digging since my Django skills are rusty but I got here:</p>
<pre><code>from django.middleware.cache import UpdateCacheMiddleware
from django.utils.cache import learn_cache_key
from django.http import HttpRequest
from network.views import StatusView
request = HttpRequest()
request.META['SERVER_NAM... | python|django|django-templates|django-views|django-cache | 0 |
7,826 | 14,344,032 | Get 2to3 to Use Spaces not Tabs | <p>I used <code>2to3</code> to convert a folder of python modules. Everything went smooth, but when I went to run some of them it gave me an error about spaces and tabs. My theory: when <code>2to3</code> changes a line it uses tabs and not spaces unlike the rest of the non-changed lines. I was wondering if there was a ... | <p><code>2to3</code> should not replace white space with tabs so I am guessing that you get a <code>TabError</code> because those tabs where already present in the code and python 3 does not allow mixing tabs and spaces within a single file whereas that is fine in python 2.</p>
<p>This can be fixed using the <code>rei... | python|python-2to3 | 6 |
7,827 | 12,077,911 | Long running daemon process on django | <p>I need to run a python script (which is listening to Twitter) which will call various methods on my django app when it gets tweets that match a particular hashtag.</p>
<p>At the moment, I just run the script by hand on the command line but I'd like it to run inside django if possible so that I can control it from t... | <p>You should <a href="http://supervisord.org/" rel="nofollow">Supervisord</a> to run your django application and your script. Making the script a part of the Django project, will let you use <a href="https://docs.djangoproject.com/en/dev/topics/signals/" rel="nofollow">Django signals</a> which you can use to write a c... | python|django|celery|django-celery | 1 |
7,828 | 23,048,468 | New lines/tabulators turn into spaces in generated document | <p>I have problem with <code>\n</code> and <code>\t</code> tags. When I am opening a generated <code>.docx</code> in <em>OpenOffice</em> everything looks fine, but when I open the same document in <em>Microsoft Word</em> I just get the last two tabulators in section <code>"Surname"</code> and spaces instead of newlines... | <p>In Word, what we often think of as a line feed translates to a paragraph object. If you want empty paragraphs in your document you will need to insert them explicitly.</p>
<p>First of all though, you should ask whether you're using paragraphs for formatting, a common casual practice for Word users but one you might... | python|python-docx | 3 |
7,829 | 23,136,443 | Writing to file advice | <p>Here's my code:</p>
<pre><code>import random
ch1=input("Please enter the name of your first character ")
strch1=(((random.randint(1,12)//(random.randint(1,4))))+10)
sklch1=(((random.randint(1,12)//(random.randint(1,4))))+10)
print("The strength value of "+ch1+" is:")
print (strch1)
print("and the skill value of "+... | <p>Use string formatting to get rid of the error:</p>
<pre><code>file.write('Strength: {0}\n'.format(sklch1))
</code></pre>
<p>Obviously you will have to do the same when you write to the file with <code>sklch2</code>.</p> | python|file-io | 5 |
7,830 | 845,276 | How to print the comparison of two multiline strings in unified diff format? | <p>Do you know any library that will help doing that?</p>
<p>I would write a function that prints the differences between two multiline strings in the unified diff format. Something like that:</p>
<pre><code>def print_differences(string1, string2):
"""
Prints the comparison of string1 to string2 as unified di... | <p>This is how I solved:</p>
<pre><code>def _unidiff_output(expected, actual):
"""
Helper function. Returns a string containing the unified diff of two multiline strings.
"""
import difflib
expected=expected.splitlines(1)
actual=actual.splitlines(1)
diff=difflib.unified_diff(expected, act... | python|diff|unified-diff | 29 |
7,831 | 1,153,167 | Simple python / Beautiful Soup type question | <p>I'm trying to do some simple string manipulation with the href attribute of a hyperlink extracted using <a href="http://www.crummy.com/software/BeautifulSoup/" rel="noreferrer">Beautiful Soup</a>:</p>
<pre><code>from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup('<a href="http://www.some-site.com/">... | <p>Python strings do not have an <code>indexOf</code> method.</p>
<p>Use <code>href.index('/')</code></p>
<p><code>href.find('/')</code> is similar. But <code>find</code> returns <code>-1</code> if the string is not found, while <code>index</code> raises a <code>ValueError</code>.</p>
<p>So the correct thing is to u... | python|string|beautifulsoup | 10 |
7,832 | 42,069,650 | python scipy brute optimization | <p>I want to find <code>some_arg</code> value that would minimize the function.</p>
<p>1) imports</p>
<pre><code>from scipy import optimize
import math as m
</code></pre>
<p>2) calculating original 2*sin(t) data</p>
<pre><code>time_steps = list(range(0,20))
def my_sin(time_steps):
sin_data = list()
for ... | <p>If I'm reading this right, you are just trying to recover the scaling factor of <code>2</code> that you applied in your original data.</p>
<p>You can simplify things a bit. Note that the range and args parameters ask for tuples. Note also that the thing you are looking for is what should be the main parameter of th... | python|optimization|scipy|brute-force | 2 |
7,833 | 47,225,215 | error occurred when using cv2.imshow() | <p>The task is, i take pictures from the camera, and i process pictures using cnns, and then display the pic with the result. But there is an error when i use opencv python interface to show the image(the os is the mac os):</p>
<pre><code> while(1):
test_data = []
ret, frame = cap.read()
frame = cv2.imrea... | <p>When you display an image in OpenCV you normally need to set a waitKey and release:</p>
<pre><code>while(1):
test_data = []
ret, frame = cap.read()
frame = cv2.imread('hello.jpg')
h, w, _ = frame.shape
img = copy.deepcopy(frame)
img = pre_process(img)
test_data.append([img])
ret_res ... | python|opencv | 0 |
7,834 | 47,191,226 | Boolean-logical Comparison of Lists Using List Comprehension | <p><strong>Here's what I'm trying to do</strong> (in a single list comprehension):</p>
<p><strong>1.</strong> Compare the the relation of 2 bool-integer lists using logical operators<br>
<strong>2.</strong> Return a list of bool-int values where:<br>
<strong>-</strong> 1 is returned when both a,b values are 1 (1,1... | <p>How's this?</p>
<pre><code>L = [int(y) for x, y in zip(A, B) if int(x)]
</code></pre>
<p>If x is 0, the item is skipped. Otherwise, if y is 1, add 1; if y is 0, add 0.</p> | python|if-statement|list-comprehension|boolean-logic | 0 |
7,835 | 57,496,176 | How to run a scrapy spider in a flask app, from a docker container? | <p>When running my flask app, which uses Python's subprocess to use scrapy within a flask app as specified here (<a href="https://stackoverflow.com/questions/36384286/how-to-integrate-flask-scrapy">How to integrate Flask & Scrapy?</a>), from a Docker Container and calling the appropriate endpoints specified in my f... | <p>Please try it.
.Dockerfile</p>
<pre><code>FROM python:3.6
RUN apt-get update && apt-get install -y wget
WORKDIR /usr/src/app
ADD . /usr/src/app
RUN pip install --no-cache-dir -r requirements.txt
EXPOSE 5000
CMD [ "python", "./server.py" ]
</code></pre> | python|docker|flask|scrapy | 0 |
7,836 | 11,959,953 | Python Persistent TCP client | <p>I need to connect to my server(not http) with a persistent connection, to speed up some things. Could I have an example of how to do this?</p> | <p>You can use <a href="http://docs.python.org/library/socket.html" rel="nofollow">socket</a> library and there are many examples in documentation.</p>
<pre><code>>>> from socket import socket
>>> sock = socket()
>>> sock.connect(("173.194.32.41", 80))
>>> sock.send("Some stuff\r\n\... | python|tcp|connection|telnet|persistent | 2 |
7,837 | 11,670,154 | Displaying LineCollections in matplotlib subplots | <p>When I try to display LineCollections in both subplots, none are displayed. When I display it only in the first, it works. How can I get it to be displayed in both?</p>
<pre><code>import numpy
import matplotlib.delaunay
from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection
# Unique... | <p>You can make a shadow copy of lc_edges by using copy module. Both the lc_edges2 and lc_edges will use the same path list, you can confirm it by: <code>lc_edges._paths is lc_edges2._paths</code>. </p>
<pre><code>import numpy
import matplotlib.delaunay
from matplotlib import pyplot as plt
from matplotlib.collections ... | python|matplotlib | 1 |
7,838 | 58,421,837 | Create new pandas dataframe column containing boolean output from searching for substrings | <p>I'd like to create a new column where if a substring is found in an existing column, it will return True and vice versa. </p>
<p>So in this example, I'd like to search for the substring "abc" in column a and create a Boolean column b whether column a contained the string or not.</p>
<pre><code>a b
zabc True... | <p>This how to do it.</p>
<pre class="lang-py prettyprint-override"><code>df["b"] = df["a"].str.contains("abc")
</code></pre>
<p>Regarding your error.</p>
<p>It's seems that you have np.nan value in your column a, then the method str.contain will return np.nan for those value, as you try to index with an array conta... | python|pandas|dataframe | 5 |
7,839 | 58,547,705 | django 'set' object has no attribute 'items' error | <p>I am trying to deploy my django app on AWS. I create a web-crawler inside my app using bs4 adn requests.I used that to get data from e-commerce sites.it's works perfectly on amazon but it throw this(see at image1) when I try to scrape from newegg. but the same codes works on localhost. first I thought it's the user ... | <p>the headers dict you passed are is rendered as a set and not as a dictionary. Look at the dump in the image. </p> | python|django|amazon-web-services|beautifulsoup|python-requests | 0 |
7,840 | 46,853,901 | Can anyone fix my Python unique password generator? | <p>This is it, the problem is it won't change the values of noun and adjective, and prints 0 for noun, 0 for adjective, and a random number between 10 and 99 for number.</p>
<pre><code>from random import *
print("I get you password.")
i = 0
noun = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
adjective = [0, 0, 0, 0, 0, 0, 0, 0, 0, ... | <p>The cause is because you initialize your noun and adjective lists with ten zeros, so the function choice(noun) has 90% chance of picking zero.</p>
<p>Instead of initializing the list then filling it, do not declare it and just append your nouns and adjectives using, for instance:</p>
<pre><code>curNoun = input( ".... | python|python-3.x | 1 |
7,841 | 47,044,006 | Read Tuple from csv in Python | <p>I am trying to read a row in a csv, which I have previously written.
That written row looks like this when is read: <code>['New York', '(30,40)']</code>
and like this: <code>['New York', '(30,40)']</code> (converts the tuple in a string).</p>
<p>I need to read each item from the tuple to operate with the ints, bu... | <p>You need to use <a href="https://docs.python.org/3/library/ast.html#ast.literal_eval" rel="nofollow noreferrer"><code>ast.literal_eval()</code></a> on you tuple string as:</p>
<pre><code>>>> my_file_line = ['New York', '(30,40)']
>>> import ast
>>> my_tuple = ast.literal_eval(my_file_lin... | python|csv|tuples | 2 |
7,842 | 37,890,256 | OpenCV Python - findHomography with RANSAC | <p>I'm trying to run <a href="http://docs.opencv.org/3.0-beta/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html#Mat%20findHomography(InputArray%20srcPoints,%20InputArray%20dstPoints,%20int%20method,%20double%20ransacReprojThreshold,%20OutputArray%20mask,%20const%20int%20maxIters%20,%20const%20double%20c... | <p>Your error is occurring because you are attempting to specify the <code>method</code> parameter twice; once as a positional argument, and again as a keyword argument. The <code>False</code> argument can be removed to correct your error. If you are trying to use RANSAC to find the homography, the correct call looks l... | python|opencv | 3 |
7,843 | 38,023,521 | SWIG: How to pass list of complex from c++ to python | <p>I have a function in c++ who returns a list of complex:</p>
<pre><code>#include <complex>
std::list< std::complex<double> > func(...);
</code></pre>
<p>what should i do in the '*.i' file ?</p>
<p>Thank you every body.</p>
<p>=================</p>
<p>Following are details:</p>
<p>the function ... | <p>This works:</p>
<pre><code>%include <std_list.i>
%include <std_complex.i>
%template(ComplexList) std::list<std::complex<double> >;
... (your includes / function declarations)
</code></pre>
<p>I think your version (3) should actually also work. Strange that it doesn't. Maybe a SWIG bug.</p> | python|c++|list|swig|complex-numbers | 1 |
7,844 | 37,788,799 | Error in the coding : TypeError : list indices must be integer, not str | <p>Code is importing another file, which is working perfectly.</p>
<p>But, there is a problem in the line where I try to import the csv file, with a column called 'account key', returning the TypeError above.</p>
<pre><code>import file_import as fi
</code></pre>
<p>Function for collectively finding data necessary fr... | <p><code>csv_file["account_key"]</code></p>
<p>Lists expect a numeric index. As far as I know, only dictionaries accept String indices. </p>
<p>I'm not entirely sure what this is supposed to do; I think your logic is flawed. You bind <code>information</code> in the <code>for</code> loop, then never use it. Even if th... | python|csv | 2 |
7,845 | 30,217,133 | Django 1.8: AttributeError at /: 'str' object has no attribute 'copy' | <p>I've been trying out Django 1.8.1. So far it's been good until I tested it. When I go to the address (<code>localhost:8000</code>) where Django is serving the files, I get the error:<br>
<code>
AttributeError at /:
'str' object has no attribute 'copy'
</code></p>
<p>I have one app called <code>fb_auth</code> in Dja... | <p>You should be sure that <a href="https://docs.djangoproject.com/en/1.8/ref/settings/#templates" rel="noreferrer">TEMPLATES</a> on settings is a list.</p>
<p>Quoting django docs:</p>
<blockquote>
<p>TEMPLATES</p>
<p>New in Django 1.8.
Default:: [] (Empty list)</p>
<p>A list containing the settings for... | python|django | 7 |
7,846 | 57,115,352 | how to take input in a function that will be a variable in that function? | <p>I am trying to create a function that will allow me to loop through a user input if it is not an integer but if it is, break. Here, the variable which will take the input cannot be same each time the function is called. </p>
<pre><code>def intry():
global a # intry(b) should change global a to global b
whil... | <p>You are calling your function but you are not storing or using a result of the function, I you really want to do with your code you can do it like:</p>
<pre><code>print (intry()+intry())
</code></pre>
<p>or:</p>
<pre><code>a = intry()
b = intry()
print (a + b)
</code></pre>
<p>output:</p>
<pre><code>23
4
27
<... | python|function | 0 |
7,847 | 43,430,802 | Python 3 How can i take multi digit input and break into each digit | <p>I want to be able to have the user enter a number of multiple digits and be able to take the input apart so I can operate on the individual digits.
I can do it for 2 digits and I guess I could write a loop to take digits out automatically.
Once I have each digit I want to square and sum and repeat until the squares ... | <p>Some corrections may be required in the example. For instance</p>
<blockquote>
<p>23 -> 2^2 + 3^2 = 13 -> 1^2 + 3^2 = 10 -> 1^2 = 1.</p>
</blockquote>
<ol>
<li><p>If you like to refer to the digits of the number you should convert it to string or to list of the digits (as integer numbers on interval [0, 9]).</p>... | python|input | 1 |
7,848 | 36,848,919 | Python Flask html form not displaying - GET instead of POST method? | <p>I'm trying to learn python and some of the Python web frameworks. Currently I'm following following a Flask course, but have run into a problem with an html form that I cannot find a solution to.</p>
<p>The code below is supposed to create a very simple page at '/' where the user can log in using an html form and i... | <p>It looks like your indentation levels are off of the <code>if ...then ...else</code> block in your <code>request.method == 'POST'</code> logic. Indent your <code>else</code> block to match up and give it a try.</p> | python|html|authentication|flask|forms | 0 |
7,849 | 36,847,840 | ImportError: DLL load failed: The specified module could not be found for numpy | <p>I have Python 3.3.2, 64 bit. When I run a script with <code>import numpy</code> I get the following Error: <code>ImportError: DLL load failed: The specified module could not be found.</code>. The traceback is: </p>
<pre><code>Traceback (most recent call last):
File "C:\Users\ZKZJFIO\workspace\FX_FORWARD_FLAG_DETERM... | <p>I had this problem as well after a fresh install of Miniconda and afterwards numpy via <code>conda install numpy</code> in the Anaconda Prompt.</p>
<p>What worked for me was uninstalling via </p>
<p><code>conda uninstall numpy</code> </p>
<p>and install with <code>pip</code> instead:</p>
<pre><code>pip install n... | python|numpy|dll | 1 |
7,850 | 48,558,873 | How to block signals until all other signals are processed? | <p>I'm working on a Qt widget that provides a grid of plots (each one is a QWidget). I want to synchronize the "keepAspectRatio" policy on all my plots.</p>
<p>Each individual plot will emit a <code>sigKeepAspectRatioChanged</code> signal if I call its <code>setKeepDataAspectRatio(bool)</code> method, that broadcasts ... | <p>What you really care for is that the method is not re-entered. The signals and slots are just a conduit for it happening. Thus: protect the relevant methods from recursion. It's more than an order of magnitude more efficient than breaking- and restoring signal-slot connections. Essentially:</p>
<pre><code>def _meth... | python|qt|pyqt | 2 |
7,851 | 48,558,052 | tensorflow Variable Initialization error : Attempting to use uninitialized value Variable | <p>Why is this happening?
<a href="https://i.stack.imgur.com/0rcrd.jpg" rel="nofollow noreferrer">Error message - Attempting to uninitialized Variable Error</a>
here is my source:
<a href="https://i.stack.imgur.com/kxh4c.jpg" rel="nofollow noreferrer">source - Learning .JPG Image in computer using tensorflow</a></p>
<... | <p>You should use <code>tf.global_variables_initializer()</code> and invoke it after you defined all the variables, not before. The simplest thing would be to do simply:</p>
<pre><code>with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
...
</code></pre> | variables|tensorflow|initialization|deep-learning | 1 |
7,852 | 48,600,153 | Python: use dict and list of tuples to create a numpy array | <p>I have five key/value pairs in a python dict object:</p>
<pre><code>dict1 = {0:3, 1:2, 2:2, 3:2, 4:3}
</code></pre>
<p>And I have a list of tuples:</p>
<pre><code>list_of_tuples = [(0, 1), (0, 4), (2, 3)]
</code></pre>
<p>I want a numpy array of shape <code>(5, 5, 2)</code> that contains the value from the dict ... | <p>You can create an array of 4s using <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.full.html" rel="nofollow noreferrer"><code>np.full</code></a> and then populate it:</p>
<pre><code>a = np.full((5, 5, 2), 4)
for x, y in list_of_tuples:
a[x, y] = dict1[x], dict1[y]
</code></pre> | python|python-2.7|numpy | 2 |
7,853 | 48,813,957 | How to check if there is no output in python subprocess? | <p>I use Python 3. This is a part of my script:</p>
<pre><code>proc = subprocess.Popen(["git", "ls-remote", "--heads", "origin", "master"],stdout=subprocess.PIPE)
line = proc.stdout.readline()
if line != '':
print("not empty")
print(line)
else:
pri... | <p>You are getting a binary string as output; many programs do internal decoding and present you with the text string, but <code>subprocess.Popen</code> is not one of them.</p>
<p>But you can easily decode it yourself:</p>
<pre><code>out_bin = b'a5dd03655381fcee94xx4e759ceba7aeb6456\trefs/heads/master\n'
out_txt = ou... | python|subprocess | 4 |
7,854 | 48,671,265 | Optimizing Language Detection code and Lemmatization in Python | <p>I have a data of amazon user reviews in JSON format which i am importing to pandas dataframe and using it to train a model for text classification. I am trying to preprocess the user review text before training a model with that data. I have two questions here:</p>
<p>1) I have written a code to detect it's langua... | <h1>TL;DR</h1>
<pre><code>from nltk import pos_tag, word_tokenize
from nltk.stem import WordNetLemmatizer
wnl = WordNetLemmatizer()
def penn2morphy(penntag):
""" Converts Penn Treebank tags to WordNet. """
morphy_tag = {'NN':'n', 'JJ':'a',
'VB':'v', 'RB':'r'}
try:
return morphy_... | python|pandas|nltk|lemmatization|textblob | 1 |
7,855 | 48,665,261 | Finding potentially problematic string concatationing code by \n | <p>In Python, a string can be replaced with a newline character, so I often get bugs that I can not think of. For example:</p>
<pre><code>numbers = (
'zero',
'one',
'two'
'three',
'four',
'five',
)
</code></pre>
<p>To avoid this difficult problem, I want to check if there is a problem with the... | <p>You are using tuples, perhaps using a different structure ( e.g. the square brackets(a list) or an ordered set) will give you what you want. If I remember the tupling/untupling rules correctly what you are seeing is an effect of unpacking the 6 element tuple into a 1 element variable - python has to do something wit... | python|parsing|abstract-syntax-tree | -1 |
7,856 | 48,557,207 | Convert data into matrix in python | <p>I have the data which is stored as data1.txt, which looks something like this</p>
<pre><code>1,004,-59
1,004,-65
1,004,-69
1,005,-55
1,005,-57
1,006,-53
1,006,-59
1,007,-65
1,007,-69
1,007,-55
1,007,-57
1,008,-53
1,009,-59
1,009,-65
1,009,-69
1,009,-55
1,010,-57
1,010,-53
1,010,-59
1,010,-65
1,011,-69
1,011,-55
1,0... | <p>I would go for a solution where I first collect all the values in a dictionary. In the solution below I assume that the order in which the values appear in the file is important. If not, you can replace the <code>OrderedDict</code> with a normal <code>dict</code>. Note also that in Python version 3.7 the usual <code... | python|numpy|matrix | 0 |
7,857 | 69,578,666 | System cannot find the path specified. (Google chrome - Windows) | <p>This is a voice assistant, I'm trying to apply google maps although. An error appeared -<br />
"The system cannot find the path specified."... I think the problem is the application location.
How can I fix this?</p>
<p>Here is my code:</p>
<pre><code> if "where is" in data:
listening = ... | <pre><code>if "where is" in data:
listening = True
data = data.split(" ")
location_url = "https://www.google.com/maps/place/" + str(data[2])
respond("Hold on Sienan, I will show you where " + data[2] + " is.")
webbrowser.open(location_url)
</code></p... | python | 0 |
7,858 | 51,167,284 | How to integrate the sentiment analysis script with the chatbot for analysing the user's reply in the same console screen? | <p>I want to make a chatbot that uses Sentiment analyser script for knowing the sentiment of the user's reply for which I have completed the Chatbot making.</p>
<p>Now only thing I want to do is to use this Script to analyse the reply of user using the chatbot that I have made.<br>
How should I integrate this <strong>... | <p>Import classes from sentiment analysis script to chatbot script. Then do necessary things according to your requirement. For example. I modified your chatbot script:</p>
<pre><code>from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from sentiment_analysis import Splitter, POSTagger, Dictiona... | python-3.x|importerror|chatbot|sentiment-analysis|nltk-trainer | 1 |
7,859 | 64,310,965 | Extract arbitrary subtotals from 2D numpy array | <p>I have 2D arrays of counts from which I need to extract a sequence of arbitrary subtotals. In this example they are subtotal <em>columns</em>. Each subtotal is the sum of an arbitrary collection of the base columns, represented by a tuple of <em>addend-indices</em>:</p>
<pre><code>>>> A
[[11, 12, 13, 14, 15... | <p>Try <a href="https://numpy.org/doc/stable/reference/generated/numpy.ufunc.reduceat.html" rel="nofollow noreferrer"><code>np.add.reduceat</code></a> :</p>
<pre><code>lens = [len(n) for n in subtotal_addend_idxs]
c = np.concatenate(subtotal_addend_idxs)
output = np.add.reduceat(A[:,c], np.cumsum([0]+lens)[:-1], axis=1... | python|numpy | 1 |
7,860 | 70,568,401 | Plotly.express Area multiple plots data error | <p>This is my code:</p>
<pre><code>import pandas as pd
import plotly.express as px
df={'x':[1,2,3,4,5],'y1':[1,2,3,4,5],'y2':[2,3,4,5,6],'y3':[3,4,5,6,7]}
df=pd.DataFrame(df)
fig = px.area(df, x="x", y=['y1','y2','y3'])
fig.show()
</code></pre>
<p>As you can see my Y data are maximum 7. Why the results in the... | <p><code>plotly.express.area</code> creates a <em>stacked</em> area plot, where each filled area corresponds to one column of the input data: <a href="https://plotly.com/python/filled-area-plots/" rel="nofollow noreferrer">https://plotly.com/python/filled-area-plots/</a></p>
<p>For example, at <code>x = 5</code>, the s... | pandas|plotly|background-image|plotly-python|area | 0 |
7,861 | 69,779,665 | how does the linked list goes to the second node | <p>so I am learning linked lists in python, but I didn't understand how does the linked list goes to the second node as it assigns the next node as the root node, please explain it to me, thanks.
the code</p>
<pre><code>class Node
def __init__(self,d,n=None,p=None):
self.data=d
self.next_node=n
... | <p>In the add function we create a new node that will become our new root aka our new first element. Therefore we first assign the current root as the next_node of our new node. Afterwards we make our new node the new root.</p> | python | 0 |
7,862 | 69,941,733 | h5py error reading virtual dataset into NumPy array | <p>I'm trying to load data from a virtual HDF dataset created with h5py and having some troubles properly loading the data.</p>
<p>Here is an example of my issue:</p>
<pre><code>import h5py
import tools as ut
virtual = h5py.File(ut.params.paths.virtual)
a = virtual['part2/index'][:]
print(virtual['part2/index'][-1]... | <p>Yes, you should get the same values from the Virtual Dataset or an array created from the Virtual Dataset. It's hard to diagnose the error without more details about the data.</p>
<p>I used the h5py example <code>vds_simple.py</code> to demonstrate how this should behave. Most of the code builds the HDF5 files. The ... | python|hdf5|h5py | 0 |
7,863 | 50,084,992 | Joining two df with condition in python | <p>I have two df.
<code>df1</code> has over 2 milion rows and has complete data. I'd like to join data from <code>df2</code>, which has over 70.000 rows but it's structure is a bit complicated.
df1 has for eac row keys <code>KO-STA</code> and <code>KO-PAR</code>.
df2 has in some cases data only on <code>KO-STA</code>, ... | <p>I provide you an example to make sure how you can proceed an what is the reason for the behaviour you observed:</p>
<p>First, let's construct our sample data</p>
<pre><code>df1 = pd.DataFrame(np.random.randint(1,3,size=(3,3)),columns=['a1','x1','x2'])
</code></pre>
<p>Output </p>
<pre><code> a1 x1 x2
0 1 ... | python|pandas|join|merge | 1 |
7,864 | 49,873,914 | disable ssl-certificate verification when installing with pip | <p>I use python for work and often need to install packages using pip but because the IT-department at work is using an https-man-in-the-middle every time i try to install packages while on the internal compagny network it failes with an ssl-certificate verification error.</p>
<p>Until recently I had a colleague (he l... | <p>I was able to get pip working by using <strong>both</strong> the <code>--trusted-host</code> flag and also the <code>--cert</code> flag to point it to the root certificate for the network. The certificate would be installed on any workstation subject to SSL MITM so you can export the certificate yourself or ask you... | python|pip|ssl-certificate | 2 |
7,865 | 66,609,642 | Using Two Pandas Dataframes: Create a column in DF1 that is a count of how many times a combination of values occurs in df2 with conditions | <p>I have two data frames, df2 is a subset of df1. The data represents call center phone calls. df1 is all calls for the time frame, df2 represents calls that abandoned before being picked up.</p>
<p>I want to create multiple new columns in df2 that are counts of how many times the phone number in the row called back a... | <p>This appears to be working, still validating.</p>
<ul>
<li>giant list of phone calls into a contact center</li>
<li>When a call abandons, what percentage of the volume for the day is a result of a callback (if a call abandons, how often do we see that ani again the same day)</li>
<li>If we staff up to prevent x aban... | python|pandas|dataframe | 0 |
7,866 | 66,549,481 | How to get direction from 2 positions in Maya? | <p>Could somebody help me? I am trying to get the direction value in worldSpace based on 2 given positions in Maya. How can I do that in python?
Is it not just subtracting the 2 positions?</p>
<p>thanks a lot!</p> | <p>Indeed, it's the difference of the two position vectors, with pymel it can look like this:</p>
<pre><code>import pymel.core as pm
v = pm.PyNode("locator2").translate.get() - pm.PyNode("locator1").translate.get()
</code></pre>
<p>Open Maya version:</p>
<pre><code>import maya.api.OpenMaya as om... | python|maya|direction | 0 |
7,867 | 64,697,581 | Splitting nd-array to sub nd-array with overlapping | <p>I have the an image represented in nd-array. Let's assume that the shape of it is <code>(256, 256, 3)</code>.</p>
<p>I wish to slice the image to sub arrays each of size <code>(128, 128, 3)</code> with a stride of 64.</p>
<p>I did the following to get the desired indices:</p>
<pre><code>for x1, x2 in (zip(range(0, 2... | <p>you want <code>skimage.util.view_as_windows</code></p>
<pre><code>arr = np.random.rand(256, 256, 3)
out = skimage.util.view_as_windows(arr, window_shape = (128, 128, 3), step = 64).squeeze()
print(out.shape)
Out[]: (3, 3, 128, 128, 3)
</code></pre>
<p>That's a <code>(3, 3)</code> array of your <code>(128, 128, 3)</c... | python|numpy|multidimensional-array|slice | 2 |
7,868 | 63,900,084 | python for loop only updates 2 of 3 variables? | <p>I want to use 3 variables in one for loops.
This is what I tried:</p>
<pre><code>def loop_player_listbox():
global bol_loop, count
bol_loop = True
while True:
time.sleep(1)
str_libo_p = listbox.get(0,tk.END)
str_libo_r = listboxr.get(0,tk.END)
str_libo_price = lis... | <p>Changed from itertools to zip fixed the issue.</p>
<p><code>for i,r,p in zip(str_libo_p, str_libo_r, str_libo_price):</code></p> | python|loops|for-loop|tkinter|listbox | 1 |
7,869 | 63,831,226 | How to set the 'category' data type for a pyarrow Table column? | <p>I understand it is possible to retain <code>category</code> type when writing a pandas <code>DataFrame</code> in a parquet file, using <code>to_parquet</code>.</p>
<p>At the start, in my case, I have already a pyarrow <code>Table</code>.
Can I set one of its column to have the <code>category</code> type?
If yes, how... | <p>In pyarrow, categorical type is called "dictionary type". A pyarrow array can be converted to such a type using the <code>dictionary_encode()</code> method:</p>
<pre class="lang-py prettyprint-override"><code>>>> import pyarrow as pa
>>> table = pa.table({'a': ['A', 'B', 'A']})
>>&g... | python|parquet|pyarrow | 4 |
7,870 | 65,242,853 | Bucketing for histogram in MongoDB | <p>Syntax issue on line #25. Can someone please help me to spot the mistake not sure if the problem is in the code before this line.</p>
<p>File SyntaxError: invalid syntax, line 25</p>
<pre><code>} #25
^
</code></pre>
<p>The line with the syntax is highlighted by #25. Thank you in advance :)</p>
<pre><code>import pand... | <pre><code> 'default': 'Other',
{
'output' : {"average": {"$avg" : '$len_references'}},
}
</code></pre>
<p>That is the problem area. You have a sub-dictionary without a key name.</p>
<p>To illustrate the problem more simply, here is an equivalent dictionary:</... | python|mongodb|mongodb-query|pymongo | 0 |
7,871 | 71,519,173 | Numpy data conversion after txt reading with genfromtxt | <p>Let me say I created a file with this three lines</p>
<pre><code>A\tB\tC
name1\t1\t2
name2\t1.1\t2.2
</code></pre>
<p>where \t corresponds to the delimiter. I read it using this numpy function</p>
<pre><code>data = np.genfromtxt('test.txt', delimiter='\t', dtype=None, encoding='ascii')
</code></pre>
<p>Data is a num... | <p>Your code, showing the results (which you should have done!):</p>
<pre><code>In [1]: txt = """A\tB\tC\t
...: name1\t1\t2\t
...: name2\t1.1\t2.2\t""".splitlines()
In [4]: data = np.genfromtxt(txt, delimiter="\t", dtype=None, encoding="ascii")
In [5]: data
Out[5... | python|numpy|data-conversion|txt|genfromtxt | 0 |
7,872 | 62,848,425 | How to code categorical values in column basis no of occurrences in pandas | <p>I have following dataframe in pandas</p>
<pre><code> id source
1 AS
2 AS
3 AS
4 AT
5 BR
6 BT
7 BR
8 BT
9 AS
10 BE
</code></pre>
<p>What I want to do in above dataframe is whichever source has less than 3 occurrences should be coaded as OTHERS. I have 1 m... | <p>try this,</p>
<pre><code>df.loc[df.groupby('source').transform('count').lt(3)['id'], 'source'] = 'OTHERS'
</code></pre>
<hr>
<pre><code> id source
0 1 AS
1 2 AS
2 3 AS
3 4 OTHERS
4 5 OTHERS
5 6 OTHERS
6 7 OTHERS
7 8 OTHERS
8 9 AS
9 10 OTHERS
</code></pre> | python|pandas | 2 |
7,873 | 62,526,385 | Is it possible to do two consecutive, successful non-blocking reads of stdin in Python? | <p>Apologies for the long code post, but I believe it is useful context.</p>
<p>I am playing around with parsing special keys in raw Python (without curses), but it seems that the <code>select</code> trick for doing non-blocking input is not working in this scenario. In particular, it looks like after reading the first... | <p>If you use low-level I/O, I think it works. <code>select.select</code> will accept numerical file descriptors. I haven't tried to integrate this with your program, but have a play with this. You should get a sequence of characters if you press e.g. left arrow. The original seems not to work with <code>sys.stdin<... | python|python-3.x|linux|select|stdin | 1 |
7,874 | 61,867,058 | Django's ManyToManyField column of model isn't showing in database | <p><strong>I created two models in Django and used 'subcode' as ManyToManyField to create a relation between them.</strong></p>
<p>But after migration the column with ManyToManyField is missing in the database table.</p>
<pre><code>class Subject(models.Model):
Subject_Name = models.CharField(max_length=200)
S... | <p><strong>Short answer</strong>: this is <em>expected</em> behavior.</p>
<p>A <code>ManyToManyField</code> is <strong>not</strong> stored as a column in a relational database. A many-to-many relation is defined as a <em>table</em>. Indeed, a table with two <code>ForeignKey</code>s, one to the "source" model (so <code... | python|django | 5 |
7,875 | 71,307,121 | Python list of dictionaries - access keys | <p>I need to change name of the keys in dictionary using item.replace(" ", "_").lower()
How could I access these keys?</p>
<pre><code>{
"environment": [
{
"Branch Branching": "97/97(100%)",
"Test Status": "TC39",
},
{
... | <p>One way is to use:</p>
<pre><code>dictionary[new_key] = dictionary.pop(old_key)
</code></pre>
<p>In your example:</p>
<pre><code>env = {
"environment": [
{
"Branch Coverage": "97/97(100%)",
"Test Environment": "REGISTERHANDLING",
... | python|json|python-2.7|dictionary|nested | 0 |
7,876 | 63,406,043 | Pulling information about a Tweet using a Tweet ID and the Tweepy API | <p>I am trying to create a list of Tweet IDs from my timeline and then pull information about each Tweet ID, like the username. I am eventually trying to retweet the most "popular" Tweet from my timeline, which I have logic to calculate elsewhere.</p>
<p>This first portion of the code works and creates a list... | <p><a href="https://tweepy.readthedocs.io/en/v3.10.0/api.html#API.statuses_lookup" rel="nofollow noreferrer"><code>API.statuses_lookup</code></a> returns a <code>ResultSet</code> of <code>Status</code> objects. You can use it as a list of <code>Status</code> objects.</p>
<p>This is because <code>API.statuses_lookup</co... | python|twitter|tweepy|attributeerror | 0 |
7,877 | 60,916,520 | Django rest framework, use none in model's field | <p>I have a Django rest framework API, In one of the models, there is a field for GeoLocation's elevation, which defaults its value to None.</p>
<p>The reason for that is that it can be passed in by the user or if left empty, obtained by a call to google's elevation API.</p>
<p>So, I'm trying to use the create functi... | <blockquote>
<p>elevation = models.FloatField...</p>
<p>fields = ('id', 'Name', 'Area', 'Latitude', 'Longitude', 'Elevation')</p>
</blockquote>
<p>field names are case-sensitive, elevation != Elevation. Try using lowercase only.</p> | python|django|django-rest-framework|django-serializer | 1 |
7,878 | 66,293,907 | How To Draw a Triangle-Arrow With The Positions of Detected Objects | <p>I am making a object detection project.</p>
<p>I have my code. And I have written it by following a tutorial. In the tutorial, the guy drew a rectangle in opencv for every single object which is detected.</p>
<p>But I want to change the rectangle to triangle or Arrow.</p>
<p>let me explain with code===></p>
<p>In... | <h2>The easy way</h2>
<p>You can use the <a href="https://docs.opencv.org/4.5.1/d6/d6e/group__imgproc__draw.html#ga0a165a3ca093fd488ac709fdf10c05b2" rel="nofollow noreferrer"><code>cv.arrowedLine()</code></a> function that will draw something similar to what you want. For example, to draw a red arrow above your rectang... | python|opencv | 4 |
7,879 | 68,997,137 | Weird shifting of boxplot in pandas boxplot combining it with seaborn pointplot - what is going on? | <p>Imagine I have the following dataframes</p>
<pre><code>import pandas as pd
import seaborn as sns
import numpy as np
d = {'val': [1, 2,3,4], 'a': [1, 1, 2, 2]}
d2 = {'val': [1, 2], 'a': [1, 2]}
df = pd.DataFrame(data=d)
df2 = pd.DataFrame(data=d2)
</code></pre>
<p>This will give me two dataframes that look the foll... | <p>The problem is that you are plotting categories on the x-axis. Pointplot plots the first item at position 0 while boxplot starts at 1, thus the shift. One possibility is to use an twinned axis:</p>
<pre><code>ax = df.boxplot(column=['val'], by = ['a'])
ax2 = ax.twiny()
sns.pointplot(x='a', y='val', data=df2, ax=ax2)... | python|pandas|dataframe | 1 |
7,880 | 59,162,321 | Exception Handling From Imported Package | <p>I am working with twint to download some twitter followers. Every now and then, twint will throw an error when it cannot find the "more" button. This is described here: <a href="https://github.com/twintproject/twint/issues/340" rel="nofollow noreferrer">https://github.com/twintproject/twint/issues/340</a>.</p>
<p>M... | <p>Since the exception is already caught in the package, you can't catch it a second time. You could modify the package, remove the exception handling and handle it yourself. Or you could add a <a href="https://docs.python.org/3/howto/logging.html#handlers" rel="nofollow noreferrer">logging handler</a> which counts log... | python-3.x|exception|logging|web-scraping|try-except | 0 |
7,881 | 59,418,977 | Select specific dates and calculate values' pct_change in Pandas | <p>For each group <code>city</code> and <code>district</code> in the following dataframe, I want to use <code>price</code> values of <code>2019-03</code> as base values, calculating <code>2019-06</code> and <code>2019-12</code> months' <code>price</code> values percentage changes comparing to the values in <code>2019-0... | <p>You can use <code>isin</code> without <code>groupby</code> and for division of first value use <code>transform</code>:</p>
<pre><code>m = df["date"].isin(['2019-01', '2019-06', '2019-12'])
s = df[m].groupby(["city","district"])['price'].transform('first')
df.loc[m, 'pct1'] = df.loc[m, 'price'].div(s).sub(1)
print ... | python|pandas|dataframe | 2 |
7,882 | 35,683,534 | click() doesn't work in selenium | <p>i am currently using selenium with python and my webdriver is firefox
i tried the click event but it doesn't work </p>
<p>website = www.cloudsightapi.com/api</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from se... | <p>Clicking <em>via javascript</em> worked for me:</p>
<pre><code>element = wait.until(EC.element_to_be_clickable((By.ID, "dropzoneTarget")))
driver.execute_script("arguments[0].click();", element)
</code></pre>
<p>Now, the other problem is that clicking that element would only get you into more troubles. There will ... | python|selenium | 6 |
7,883 | 35,679,090 | How can I use the value from a spin box (or other Tkinter widget) properly in a calculation? | <p>I am writing a program in Python/Tkinter where I need to get the user's inputted value from a spin box and use it in a mathematical calculation (to calculate the cost of an item, more specifically). This is triggered by pressing a button. </p>
<pre><code>from tkinter import *
root = Tk()
root.wm_title("Kiosk")
r... | <p><code>popcorn.get()</code> returns a string you need to convert it to integer using <code>int</code> or float point number using <code>float</code>.</p>
<pre><code>def getvalue():
print(int(popcorn.get()) * 9)
</code></pre> | python|python-3.x|tkinter | 1 |
7,884 | 31,576,967 | Pass values in a Python list values without parentheses to variable | <p>I have a <code>python</code> script which is programmatically loading data from a flat file into a <code>postgresql</code>/<code>Redshift</code> database using the <code>psycopg2</code>. </p>
<p>The script is trying to pass a variable of column names to the copy command, like so: </p>
<pre><code>COPY FROM 's3://.... | <p>This can be done easily with string manipulation.</p>
<pre><code>"(" + ", ".join(column_names) + ")"
</code></pre> | python|postgresql|amazon-redshift | 1 |
7,885 | 60,265,323 | How to return a numpy array with values derived from the source array of max values of different arrays of same shape | <p>I'm have trouble writing this question out so maybe best just to illustrate. In short I have two sets of three arrays of the same shape. Using the first set, for each element, I would like to find which array has the max value in that position and return the value from the second set. While the example has each 3 x ... | <pre><code>import numpy as np
A1 = np.array([[13, 16, 17], [32, 16, 11], [46, 30, 14]], dtype='uint8')
B1 = np.array([[31, 46, 41], [19, 29, 45], [36, 30, 46]], dtype='uint8')
C1 = np.array([[36, 35, 26], [19, 40, 24], [5, 20, 46]], dtype='uint8')
A2 = np.array([[1, 1, 4], [3, 1, 4], [1, 3, 2]], dtype='uint8')
B2 = ... | python|arrays|numpy | 0 |
7,886 | 2,441,661 | What are good Python and/or Django deployment solutions? | <p>For now I use some mix between <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow noreferrer">virtual_env</a>, <a href="http://pypi.python.org/pypi/pip" rel="nofollow noreferrer">pip</a> and <a href="http://docs.fabfile.org/0.9.0/" rel="nofollow noreferrer">Fabric</a>.</p>
<p>This allows to:</p>
<ul>
<... | <p>Fabric is the best solution for you. You can do everything you need using Fabric.</p> | python|deployment | 1 |
7,887 | 67,969,982 | Indexing my choice field with options a,b,c,d | <p>I'm trying to build exam app using django ,i have used the foreign link to connect my choices and question together but I want to add options such as A,B,C in front of my choices please is there any template tags or model field that do such , thanks for helping a newbie</p> | <p>You need to import Django forms library to use radio options. Use this code:</p>
<pre><code>from django import forms
FRUIT_CHOICES= [
('orange', 'Oranges'),
('cantaloupe', 'Cantaloupes'),
('mango', 'Mangoes'),
('honeydew', 'Honeydews'),
]
favorite_fruit= forms.CharField(label='What is your favor... | html|python-3.x|django-models|django-views | 0 |
7,888 | 67,982,013 | How python multithreaded program can run on different Cores of CPU simultaneously despite of having GIL | <blockquote>
<p>In this video, he shows how multithreading runs on physical(Intel or
AMD) processor cores.</p>
<p><a href="https://youtu.be/ecKWiaHCEKs" rel="nofollow noreferrer">https://youtu.be/ecKWiaHCEKs</a></p>
<p>and</p>
<p><a href="https://stackoverflow.com/questions/7542957/is-python-capable-of-running-on-multi... | <p><a href="https://docs.python.org/3/library/math.html" rel="nofollow noreferrer">https://docs.python.org/3/library/math.html</a></p>
<blockquote>
<p>The math module consists mostly of thin wrappers around the platform C math library functions.</p>
</blockquote>
<p>While python itself can only execute a single instruc... | python|python-3.x|multithreading | 2 |
7,889 | 30,739,823 | NoReverseMatch get_absolute_url 0 patterns tried | <p>I get error when i go to <a href="http://127.0.0.1:8000/books/author/" rel="nofollow">http://127.0.0.1:8000/books/author/</a>:</p>
<blockquote>
<p>NoReverseMatch at /books/author/</p>
<p>Reverse for '/books/author/1/' with arguments '()' and keyword
arguments '{}' not found. 0 pattern(s) tried: []</p>
</bl... | <p>You are mixing up two methods, namely:</p>
<p><code>{% url "routing-name" arguments %}</code>
<a href="https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#url" rel="nofollow">https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#url</a></p>
<p>and</p>
<p><code>reverse("routing-name", [arguments]... | python|django | 3 |
7,890 | 67,172,364 | Create new column in dataframe by passing existing pandas column values as argument to API call | <p>I have created a function below, get_lyrics, which I want to pass the Song_Title and Singer_Name column values from an existing dataframe and create a new column in the dataframe.</p>
<p>My code below that attempts to create a column <code>df['Lyrics']</code> gives me this error below and I have no idea why:</p>
<pr... | <p>To apply function on rows, you can use <code>apply()</code> with <code>axis=1</code>.</p>
<pre class="lang-py prettyprint-override"><code>df['Lyrics'] = df.apply(lambda row: get_lyrics(row["Song_Title"], row["Singer_Name"]), axis=1)
</code></pre>
<p>Or with lambda function in one line</p>
<pre cl... | pandas|dataframe|apply | 1 |
7,891 | 72,353,070 | cannot install pyimagej on python | <p>I need to write a code using jupyter notebook but need imagej packages.
I installed pyimagej using several commands</p>
<pre><code>conda install -c conda-forge pyimagej
conda install -c conda-forge/label/cf201901 pyimagej
conda install -c conda-forge/label/cf202003 pyimagej
</code></pre>
<p>But I always get this err... | <p>I tried this and it worked</p>
<pre><code>conda create -n imagej pyimagej
</code></pre> | python|imagej|pyimagej | 0 |
7,892 | 50,829,622 | Why is Python Beautiful Soup stripping parameters from the scraped URL | <p>I'm trying to scrape this website with Python BeautifulSoup. And my code below is first fetching all the links from the page. While fetching the links it is stripping ampersands and parameters from the original link. I wonder why? Would somebody know? I've got the code down here along with the output. </p>
<pre><co... | <p>This issue is about the parser used in Beautifulsoup.</p>
<p>Try with </p>
<pre><code>soup = bs(url.text, 'html.parser')
</code></pre>
<p>or </p>
<pre><code>soup = bs(url.text, 'lxml')
</code></pre>
<p>You might need to install some specific parser, see this <a href="https://www.crummy.com/software/BeautifulSou... | python|web-scraping|beautifulsoup | 1 |
7,893 | 50,926,464 | GraphFactory could not find gremlin.graph property configration | <p><strong>Summary</strong></p>
<p>While trying to start the gremlin server with origindb <code>GraphFactory message: GraphFactory could not find [org.apache.tinkerpop.gremlin.orientdb.OrientEmbeddedFactory]</code> error i got</p>
<p><strong>Detail</strong></p>
<p>I am using the below configuration</p>
<p>Gremlin :... | <p>You are mixing a lot of different versions so it's hard to say what will work. First of all, TinkerPop recommends that you try to match the versions of the server with the version of the client. So that means that if you you use 3.3.1 on the server then you should try to use 3.3.1 of a client (in your case gremlin-p... | python-3.x|orientdb|gremlin|gremlin-server | 1 |
7,894 | 35,232,385 | How do I tell if OpenPGP encryption is symmetric or asymmetric? | <p>Is there a way to tell if things encrypted via the GNU Privacy Guard are symmetric or asymmetric (without decrypting them or already knowing to start with)? How?</p>
<p>Anyway (for those who want to know what I'm doing), I used Python 3.x to program a GUI-based IDE of sorts that can open symmetrically encrypted fil... | <p>OpenPGP is a hybrid cryptosystem, which means messages (or files) are always encrypted symmetrically using a so-called <em>session key</em>. The session key again is encrypted using asymmetric encryption (using a public key) or symmetric encryption again (using a string to key function).</p>
<p>This has technical r... | python-3.x|encryption|gnupg|openpgp | 5 |
7,895 | 26,713,313 | How to print a simple RML report (with no data) in OpenERP7? | <p>I am trying to print a RML report (with no data, just generate the document, to start step by step). But by the moment, I was not able to manage it. I created a new module (<code>res_partner_extended</code>), and a new model (<code>res.partner.link.category</code>). In the main folder of my module, I created the fil... | <p>Remove this,</p>
<pre><code> parser="res_partner_link_category_history"
</code></pre>
<p>And replace with</p>
<pre><code> parser=res_partner_link_category_history
</code></pre>
<p>Just remove the quotes.</p> | python|xml|report|openerp|openerp-7 | 0 |
7,896 | 56,359,196 | Why are total only calculated in one dimension wiht margins=True in pandas.pivot_table? | <p>Examples for <code>pandas.pivot_table</code> show totals being calculated for rows and columns, but for me totals are only calculated for rows.</p>
<p>I can reproduce this behavior with different DataFrames on this setup:</p>
<p>Ubuntu 18.04, Python 3.6.7, Pandas 0.24.2</p>
<pre class="lang-py prettyprint-overrid... | <p>This is a bug in pandas that only looks to occur with numeric columns and <code>margins=True</code>. A workaround is to temporarily cast numeric column names to strings:</p>
<pre><code>In [1]: import pandas as pd; pd.__version__
Out[1]: '0.24.2'
In [2]: df = pd.DataFrame([
...: ["sec", "2019-01", 1],
..... | python|pandas|pivot-table | 0 |
7,897 | 22,739,755 | Add Elements of a List together while Maintaining the Larger List | <p>I have a list in the following format:</p>
<pre><code>[(('ABC','DEF'),2), (('GHI','JKL'), 4) ...]
</code></pre>
<p>I would like to break down to:</p>
<pre><code>[('ABC','DEF', 2), ('GHI','JKL', 4) ...]
</code></pre>
<p>Any suggestions?</p> | <p>You can do that with a simple <em>list comprehension</em>:</p>
<pre><code>L = [(('ABC', 'DEF'), 2), (('GHI', 'JKL'), 4)]
new_list = [e[0] + (e[1],) for e in L]
</code></pre>
<p><strong>Demo:</strong></p>
<pre><code>>>> print new_list
[('ABC', 'DEF', 2), ('GHI', 'JKL', 4)]
</code></pre>
<p><strong>Note:... | python|list|element | 2 |
7,898 | 45,370,775 | PyCharm - Trailing type hints and line width limit | <p>In PyCharm, I typically use trailing <a href="https://www.jetbrains.com/help/pycharm/type-hinting-in-pycharm.html" rel="noreferrer">type hints</a> (not sure of the right way of calling them) for variables such as this:</p>
<pre><code>my_var = my_other_variable # type: MyObject
</code></pre>
<p>However, sometimes ... | <p>I found it very convenient to import the class names directly from the module for the type annotation usage. For example:</p>
<pre><code>from QtWidgets import QVeryLongQtClassName
my_var = my_really_long_variable_name # type: QVeryLongQtClassName
</code></pre>
<p>I have not encountered a problem like yours yet wi... | python|pycharm|type-hinting | 3 |
7,899 | 54,958,036 | sequence item 0: expected str instance, list found | <p>this is part of my code.it reads from an excel file.
I'm getting a type error saying "TypeError: sequence item 0: expected str instance, list found".</p>
<pre><code>text=df.loc[page,["rev"]]
def remove_punct(text):
text=''.join([ch for ch in text if ch not in exclude])
tokens = re.split('\W+', text),
tex = "... | <p>I think the commas at the end of these two lines create a list of the variables you are trying to process.</p>
<pre><code> tokens = re.split('\W+', text), # <---- These commas at the end
tex = " ".join([word for word in tokens if word not in cachedStopWords]), # <----
</code></pre>
<p>It would result in r... | python-3.x|string|nltk | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.