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 |
|---|---|---|---|---|---|---|
3,700 | 31,620,161 | custom nagios script with nrpe resulting in non-zero exit status 1 | <p>I am trying to run a python script using nrpe to monitor rabbitmq. Inside the script is a command 'sudo rabbiqmqctl list_queues' which gives me a message count on each queue. However this is resulting in nagios giving htis message: </p>
<pre><code>CRITICAL - Command '['sudo', 'rabbitmqctl', 'list_queues']' returned... | <p>The "non-zero exit code" error is often associated with <code>requiretty</code> being applied to all users by default in your sudoers file.</p>
<p>Disabling "requiretty" in your sudoers file for the user that runs the check is safe, and may potentially fix the issue. </p>
<p>E.g. (assuming nagios/nrpe are the use... | python|rabbitmq|nagios|nrpe|rabbitmqctl | 3 |
3,701 | 15,734,582 | Advice with a file program asking for the largest number | <p>the assignment this time around deals with using files. "Assume that a file containing a series of integers is named numbers.dat and exists on the computer's disk. Design a program that determines the largest number stored in the file. The instructor told us not to use array based implementations, and include a vari... | <p>Imagine you have a sheet of paper with hundreds of numbers on it. Using nothing but your brain and eyes, read those numbers and find the largest one.</p>
<p>How would you do this?</p>
<p>Now, how would you tell the computer to do it the same way?</p> | file-io|python-3.x | 0 |
3,702 | 59,827,370 | Python Curses addwstr() returned ERR when adding lines to screen | <p>Suppose I am adding a large number of lines to a curses screen. </p>
<p>Minimal non-working example:</p>
<pre><code>import curses
class MyApp(object):
def __init__(self, stdscreen):
self.screen = stdscreen
for i in range(0,100):
self.screen.addstr(str(i) + '\n')
sel... | <p>It occurred to me that I could use <code>try</code>/<code>except</code> to determine the maximum number of lines that can be printed on the screen to avoid this error:</p>
<pre><code>import curses
class MyApp(object):
def __init__(self, stdscreen):
self.screen = stdscreen
maximum = self.maxl... | python|curses | 0 |
3,703 | 25,263,508 | Download from private GitLab without API | <p>I need to download a file from a private GitLab.</p>
<p>I already saw this post:
<a href="https://stackoverflow.com/questions/24463229/download-from-a-gitlab-private-repository">Download from a GitLab private repository</a></p>
<p>But I cannot use the API, since I dont have the needed IDs to download the files... | <p>First generate a Personal Access Token from your settings page: <code>/profile/personal_access_tokens</code>. Make sure it has the <strong>read_repository</strong> scope.</p>
<p>Then you can use one of two methods, replacing <code>PRIVATETOKEN</code> with the token you acquired:</p>
<ol>
<li><p>Pass a <code>Priva... | python|session|authentication|cookies|gitlab | 0 |
3,704 | 70,823,496 | reset cumulative sum base on condition pandas and return other cumulative sum | <p>I have this dataframe -</p>
<pre><code> counter duration amount
0 1 0.08 1,235
1 2 0.36 1,170
2 3 1.04 1,222
3 4 0.81 1,207
4 5 3.99 1,109
5 6 1.20 1,261
6 7 4.24 1,068
7 8 3.07 1,098
8 9 ... | <p>I would first go through the 2 columns once for their cumulative sums.</p>
<pre><code>cum_amount = df['amount'].cumsum()
cum_duration = df['duration'].cumsum()
</code></pre>
<p>Get a list ready for the results</p>
<pre><code>results = []
</code></pre>
<p>Then loop through each index (equivalent to counter)</p>
<pre>... | python|pandas|dataframe|cumsum | 0 |
3,705 | 2,383,121 | Change Node Display Size in Networkx | <p>I am not using GraphViz because I am having problems with making it play nice with Networkx. I know this is weird, but I've tried many suggestions to fix this problem, but I just seem to have some of the worst luck in the world. Therefore the problem that I have must be solved withing Networkx without using GraphViz... | <p>Try <a href="http://networkx.lanl.gov/reference/generated/networkx.draw.html#networkx.draw" rel="noreferrer"><code>nx.draw(G, node_size=size</code>)</a>, where <code>size</code> can be a scalar or an array of length equal to the number of nodes.</p> | python|networkx | 31 |
3,706 | 5,659,680 | Twisted XML-RPC error | <p>I get an exception on both client and server side when I run the first example at <a href="http://buildbot.twistedmatrix.com/builds/sphinx-html/291-15849/projects/web/howto/xmlrpc.html" rel="nofollow">http://buildbot.twistedmatrix.com/builds/sphinx-html/291-15849/projects/web/howto/xmlrpc.html</a>. The server code I... | <p>Looks like you have an old version of xmlrpclib?</p>
<p>What version of python are you using?
Where is the xmlrpclib coming from that your xmlrpc server is using, and what version is it?</p>
<pre><code>$ python -v
>>> import xmlrpclib
# /usr/lib/python2.6/xmlrpclib.pyc matches /usr/lib/python2.6/xmlrpclib... | python|twisted|xml-rpc | 2 |
3,707 | 6,162,258 | Boost.python error in hello world example | <p>I keep getting the error when I try to compile the hello world example with bjam. Everything in Jamroot file ran ok, except the last line (when I commented this line, no error happens):</p>
<pre><code>run-test hello : hello_ext hello.py ;
</code></pre>
<p>The error is:</p>
<pre><code>capture-output bin/hello.test... | <p>I had encountered similar problem during building adobe asl library. The problem was the version of installed from ubuntu repositories bjam (3.1.16). After installing latest bjam from sourceforge (3.1.18), everything worked as it should.
<br/><br/>PS. OS is Ubuntu 11.04</p> | c++|python|boost | 0 |
3,708 | 67,929,554 | Unable to click on next button with Selenium | <p>I've been at this for hours and haven't made any progress. I'm trying to click on the next button on this page <a href="https://www.govinfo.gov/app/collection/uscourts/district/alsd/2021/%7B%22pageSize%22%3A%22500%22%2C%22offset%22%3A%220%22%7D" rel="nofollow noreferrer">here</a></p>
<p>Here's my code:</p>
<pre><cod... | <p>1 Your XPATH does not work because it uses dynamic class name <code>collapseOne1690</code>, as was mentioned earlier.
Also, it's not very stable even if you used a part of this class name.
If you prefer XPaths, I'd suggest this one: <code>//span[@class='custom-paginator']//li[@class='next fw-pagination-btn']/a</code... | python|selenium|selenium-webdriver|web-scraping|xpath | 2 |
3,709 | 67,735,936 | Plotting a 3D graph in Python | <p>I have 3 vectors "x1", "x2" and "targets" of shape (1000,1) each and I want to plot this on a 3D graph.</p>
<p>While using the code</p>
<pre><code>targets = targets.reshape(observations,)
fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')
ax.plot(x1,x2,targets)
ax.set_xlabe... | <p>To my understanding, plot requires 3 vectors with one dimension each. If you just extract one column of data from you arrays you be fine I think. See the example below:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
x1 = np.random.random((1000,1))
x2 = np.random.random((1000,1))
targets = np.rand... | python|matplotlib|plot | 1 |
3,710 | 66,949,282 | how to get PIL for python | <p>I am trying to run a python code which uses <code>tensorflow 1.15</code>, <code>keras 2.2.4</code> and <code>PIL 7.2.0</code>. I do not have PIL on my conda virtual environment running with Python 3.6. None of the following works for me-</p>
<pre><code>conda install PIL
conda install PIL=7.2
pip install PIL
pip ins... | <p>For installing the PIL Library, you have to run the command <code>pip install Pillow</code>. Refer <a href="https://pypi.org/project/Pillow/" rel="nofollow noreferrer">here</a></p> | python|python-imaging-library | 0 |
3,711 | 67,101,524 | Making test data for full length of definition uisng Python? | <p>Thanks for your replies to my threads.</p>
<p>I am looking to make a test data to satisfy the full length of field definition using Python Script</p>
<p>For instance, with this data structure:</p>
<pre><code>Name varchar (10)
Business Name varchar (15)
Address Varchar (20)
Amount number (10,2)
..........
............. | <p>Assuming this is coming as a list of tuples (or list of lists) <code>[(10, 'x'), (15, 'u'), (20, 'p'), (10, 9)]</code>, you can do this:</p>
<pre><code>final_string = ''
for length, character in data:
final_string += length * str(character) + ' | '
print(final_string)
</code></pre>
<p>and the output is:</p>
<p... | python | 1 |
3,712 | 66,759,486 | OSError: [Errno 30] Read-only file system | <p>I am trying to run my flask app to lambda. It deploy successfully (using serverless framework) but when I'm testing I get this error :</p>
<p><code>OSError: [Errno 30] Read-only file system</code></p>
<p>Part of the code that trigger the error :</p>
<pre><code>with open("tmp/some-file.zip", "wb")... | <p>In the provided example, you're using relative path to <code>tmp</code>, unless you're working dir is <code>/</code>, it will try to open a file in an invalid (not available for write) path. When trying to write to a file in <code>/tmp</code> (which is writable for Lambdas), ensure you're providing proper, ideally a... | python|python-3.x|flask|aws-lambda|serverless-framework | 0 |
3,713 | 72,269,805 | Replacing data in python returns old and new values | <p>I am having some issues with the following code:</p>
<pre><code> def string(self):
vars = []
string = """
test = "Hello"
print(test)
OK = "Hello"
print(OK)
"""
pieces = string.split("\n")
for b in pieces:
... | <p>You can first extract the vars and then replace the matches as whole words with a single <code>re.sub</code> like this:</p>
<pre class="lang-py prettyprint-override"><code>def string_replace(self):
text = """test = "Hello"
print(test)
OK = "Hello"
print(OK)"""
... | python|regex|string | 0 |
3,714 | 72,169,890 | Code that works, but makes little sense to me: if str1.find("not") | <p>New to coding/Python and doing codingbat challenges. Really basic stuff.</p>
<p><a href="https://codingbat.com/prob/p189441" rel="nofollow noreferrer">https://codingbat.com/prob/p189441</a></p>
<p>^ This problem can be solved writing:</p>
<pre><code>def not_string(str1):
if str1.find("not"):
re... | <p><code>str1.find("not")</code> returns the index of the substring, if it is found; and -1 if it is not found.</p>
<p>If you use it as a condition:</p>
<pre><code>if str1.find("not"):
</code></pre>
<p>then it will only be falsey if <code>str1.find("not")</code> returns zero, because all i... | python | 1 |
3,715 | 50,955,960 | How can I map 2 numpy arrays with same indices | <p>I am trying to map 2 numpy arrays as [x, y] similar to what zip does for lists and tuples.</p>
<p>I have 2 numpy arrays as follows:</p>
<pre><code>arr1 = [1, 2, 3, 4]
arr2 = [5, 6, 7, 8]
</code></pre>
<p>I am looking for an <code>output as np.array([[[1, 5], [2, 6], [3, 7], [4, 8]]])</code></p>
<p>I tried this b... | <p>You are looking for <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.dstack.html" rel="nofollow noreferrer"><strong><code>np.dstack</code></strong></a></p>
<blockquote>
<p>Stack arrays in sequence depth wise (along third axis).</p>
</blockquote>
<pre><code>np.dstack([arr1, arr2])
array... | python|numpy | 2 |
3,716 | 50,603,662 | Function takes another function as an argument and calls it twice inside its body | <pre><code>def apply_twice(func, arg):
return func(func(arg))
def add_five(x):
return x + 5
print(apply_twice(add_five, 10))
</code></pre>
<p><strong>I am not able to figure out how/why the output is 20!!</strong></p>
<p>For me, the flow for above code is like this: </p>
<pre><code>de... | <p>why not 20?</p>
<p>10+5=15
15+5=20</p>
<p>the last step should return 15+5</p> | python-3.x|function | 0 |
3,717 | 26,723,937 | plot the bars from starttime not from zero | <p>for example i have the values</p>
<pre><code>starTime1 = 1.5
starTime2 = 3
starTime3 = 2.3
</code></pre>
<p>and i have three bars horizantal, for example with name:
bar1
bar2
bar3</p>
<p>i have "x" scale = 24 hours(range0,24)</p>
<p>So how to plot the bars from values "startTime", not from zero.</p>
<p>There is... | <p>You can use the <code>left</code> keyword to <code>barh</code> (or the <code>bottom</code> keyword for vertical bars) to change the starting position of a bar. You'll have to subtract the same amount from the bar length though.</p>
<p>Example:</p>
<pre><code>pylab.barh( [1,2,3], [10,20,30], left=20 )
</code></pre... | python | 2 |
3,718 | 26,889,296 | Python list of lists from CMD output | <p>Trying to parse the values of SSID, BSSID and Signal from CMD output by using python. The thing that confuses me is how to get those three values each time to store it in a list of lists. I could do it for every single line like so..</p>
<pre><code>import subprocess, re
cmd = subprocess.Popen('netsh wlan show netw... | <p>Here is how you could parse the output into a list of dictionaries:</p>
<pre><code>import subprocess
ssid = {}
ssids = []
cmd = subprocess.Popen('netsh wlan show networks mode=BSSID',
shell=True, stdout=subprocess.PIPE)
for line in cmd.stdout:
l = map(lambda x: x.strip(), line.strip().s... | python|windows|cmd|wifi|netsh | 2 |
3,719 | 44,874,061 | Comparing cell values with a integer in pandas giving typeerror | <p>I have been trying to compare values of each cell in a row with an integer like so:</p>
<pre><code>df.loc[df['A'] <= 14, 'A']
</code></pre>
<p>All rows whose values are less than or equal to 14, but it shows an error like:</p>
<blockquote>
<pre><code>TypeError : '<=' is not supported between instances of st... | <p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html" rel="nofollow noreferrer"><code>replace</code></a> <code>,</code> to empty space and convert to <code>int</code>:</p>
<pre><code>df = pd.DataFrame({'A':['1,473','1,473','1,4', '1,2'],
'B':[2,4,... | python|pandas | 1 |
3,720 | 57,738,373 | Ansible: XML module to read an attribute value and access it | <p>I am using Ansible playbook to extract a specific attribute value from an XML file, as prescribed in <a href="https://docs.ansible.com/ansible/2.4/xml_module.html" rel="nofollow noreferrer">the Ansible XML module page</a>, but getting an error "Xpath /business/website/validxhtml does not reference a node".</p>
<p>X... | <p>It's because neither <code>validxhtml</code> element exist nor <code>attribute</code> in sample xml. First of all XML like HTML has Elements & Attributes, both are different things <a href="https://www.w3schools.com/xml/xml_attributes.asp" rel="nofollow noreferrer">Ref</a></p>
<p>So you need to either add <code... | python|xml|linux|ansible | 1 |
3,721 | 18,414,045 | Append os.listdir neatly | <p>With this code in a TextCtrl I get:</p>
<pre><code>os.listdir(self.dirname)
self.bottomview.AppendText(str(os.listdir(self.dirname)))
>>>[u'a.txt', u'b.txt', u'c.txt']
</code></pre>
<p>How would you append os.listdir so that it lists like:</p>
<pre><code>a.txt
b.txt
c.txt
</code></pre> | <p>I have tried it in normal python and the below command works - </p>
<pre><code>print "\n".join(os.listdir(self.dirname))
</code></pre>
<p>See if this works well in <code>wxpython</code> also.</p> | operating-system|wxpython | 0 |
3,722 | 55,313,363 | D3 Visualization of network data (nodes and links) via json file | <p>I would like to visualize network data that consists nodes and links in json file. I'm looking how D3 could be utilized. I haven't tried D3 but seems its good to visualize network data.</p>
<p>Lot of example visualization of data using D3 but I observed the link in json file example always based on source and targe... | <blockquote>
<p>If you want to refer to a property of nodes as opposed to the index
(which is the default) you can use the function link.id().</p>
<p>For reference, see: <a href="https://github.com/d3/d3-force#link_id" rel="nofollow noreferrer">https://github.com/d3/d3-force#link_id</a></p>
</blockquote>
<p>I... | javascript|python|json|d3.js|data-visualization | 2 |
3,723 | 55,371,933 | Same for_loop code, print different results the second time run | <p>Here is my code :</p>
<pre><code>for i in range (x):
print(i)
x=5
</code></pre>
<p>I use Spyder 3.3.2 on a Windows 10 platform. When I tried the for loop with the code I've written above I found an interesting problem.
The first time I clicked the green Run file(F5) button it printed:</p>
<pre><code>0
1... | <p>You need to define the loop variable x outside</p>
<pre><code>x=5
for i in range (x):
print(i)
0
1
2
3
4
</code></pre> | python|for-loop | 0 |
3,724 | 58,198,749 | How to avoid integrity errors occuring because of concurrent creations/updates? | <p>So let's say there's a model A which looks like this:</p>
<pre><code>class A(model):
name = char(unique=True)
</code></pre>
<p>When a user tries to create a new A, a view will check whether the name is already taken. Like that:</p>
<pre><code>name_taken = A.objects.get(name=name_passed_by_user)
if name_taken:... | <p>The only thing you can do is to set the appropriate <a href="https://www.postgresql.org/docs/9.1/transaction-iso.html#XACT-REPEATABLE-READ" rel="nofollow noreferrer"><em>transaction isolation</em></a> directly to postgres. Neither python nor the ORM can do anything about it. <em>serialized</em> level will most likel... | python|django|database|postgresql|sqlalchemy | 1 |
3,725 | 58,473,700 | is there a way to combine multiple columns with comma separated | <p>I have a dataframe with 1 million+ records and I am looking to combine two columns to one row with a separator, anyone help me how to do it ?</p>
<pre><code>def chunk_results(df):
n =0
for i in range(len(df)):
data_frame = df.iloc[n:n+5]
# code for combie
n=n+5
My Dataframe:
ID Val... | <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>groupby</code></a> whatever the rows you want and just aggregate them</p>
<pre><code>chunksize = 5
df.astype(str).groupby(df.index // chunksize).agg(','.join)
</code></pre>
<p><strong>... | python-3.x|pandas | 2 |
3,726 | 58,363,920 | how to fix code not hashing every line in file | <p>Im trying to hash each line in a txt file but it will only hash the first line</p>
<p>I tried redirecting print</p>
<pre class="lang-py prettyprint-override"><code>import hashlib
with open('hash.txt','r+') as f:
for line in f:
line = line.strip()
f.write(f'{line} -> {hashlib.sha3_256(line.e... | <p>You are writing to the same file you are reading from. Try creating new file and writing your result in it</p>
<pre><code>with open('hash.txt','r+') as f:
with open('result.txt', 'w+') as r:
for line in f:
line = line.strip()
r.write(f'{line} -> {hashlib.sha3_256(line.encode()... | python | 2 |
3,727 | 58,272,709 | How to parse a value next to a specific substring in Python | <p>I have a log file containing lines formatted as shown below. I want to parse the values right next to the substrings <code>element=(string)</code>, <code>time=(guint64)</code> and <code>ts=(guint64)</code> and save them to a list that will contain separate lists for each line:</p>
<pre><code>0:00:00.336212023 62327... | <p>Regex was meant for this:</p>
<pre><code>lines = """
0:00:00.336212023 62327 0x55f5ca5174a0 TRACE GST_TRACER :0:: element-latency, element-id=(string)0x55f5ca532a60, element=(string)rawvideoparse0, src=(string)src, time=(guint64)852315, ts=(guint64)336203035;
0:00:00.336866520 62327 0x55f5ca5176d0 TRACE... | python|regex|string | 1 |
3,728 | 65,224,489 | Compare multiprocessing outputs using queue (Python) | <p>I need to run command1 and command2 at the same time(in parallel) until output of them matches.
For Example the while loop in consumer should break in the third iteration where command1 = 9 and command2 = 9.<br />
I have the above code using multiprocessing. What I am doing wrong ? Any help is appreciated.</p>
<p>ED... | <p>You've got an infinite loop because you read from the queues <em>outside</em> the infinite loop, and never reassign <code>result1</code>/<code>result2</code>. You want:</p>
<pre><code>def consumer(q1,q2):
while True:
result1 = q1.get() # Reading inside the loop
result2 = q2.get()
if resu... | python|multiprocessing | 0 |
3,729 | 45,536,045 | Python receiver won't accept more than 1 message per client | <p>I wrote this with the intent of sending data collected on one server being sent to an external server. The issue seems to be with c2.py as the mailer.py has no issue with sending the data but c2.py will only output 1 message sent to it from a unique IP.</p>
<p>mailer.py (Sends data to the c2.py sitting on another s... | <p>You can't reopen the same socket and your your server is closing the connection (<code>conn.close()</code>) after receiving all the data you get an error. Move <code>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)</code> into the function and open a new socket:</p>
<pre><code>import socket
from time import sl... | python-2.7|sockets | 1 |
3,730 | 28,863,853 | Minimum element from the matrix column | <p>I need to find minimum over all elements from the column which has the maximum column sum.
I do the following things:</p>
<p>Create random matrix</p>
<pre><code>from numpy import *
a = random.rand(5,4)
</code></pre>
<p>Then calculate sum of each column and find index of the maximum element</p>
<pre><code>c = a.s... | <p>You can extract the minimum value of a column as follows (using the variables you have indicated):</p>
<pre><code>e=a[:,d].min()
</code></pre>
<p>Note that using</p>
<pre><code>a=min(a[:,d])
</code></pre>
<p>will break you out of Numpy, slowing things down (thanks for pointing this out @SaulloCastro).</p> | python|numpy|matrix|minimum | 5 |
3,731 | 28,665,367 | How to continue editing project with git / heroku? | <p>I'm following <a href="https://devcenter.heroku.com/articles/getting-started-with-django" rel="nofollow">this tutorial</a> which initializes a project from scratch, and goes on. But I couldn't find how to continue editing. I mean, I wrote some of the code, uploaded it with <code>git push heroku master</code>, then t... | <p>Yes, you should do it exactly as you did today. Mind you, you must've committed your changes before you did </p>
<pre><code>git push heroku master
</code></pre>
<p>Quite possibly, what you did was this</p>
<pre><code>$ git add .
$ git commit -m "my django app"
$ git push heroku master
</code></pre>
<p>Tomorrow, ... | python|django|git|heroku|heroku-toolbelt | 1 |
3,732 | 14,411,481 | "Sourcing" a Python file from another | <p>I have a service where users upload egg files. The problem is that a <code>settings.py</code> file needs to be extracted by me and I should only accept some of the values in that file. The file consists of regular Python variables like:</p>
<pre><code>VAR1 = 'Hello'
VAR2 = ['my.list']
VAR3 = {
'a': 'b'
}
</code... | <p>If you just do <code>import settings</code> all the variables will be available like <code>settings.VAR1</code> <code>settings.VAR2</code> etc.</p> | python | 8 |
3,733 | 14,371,883 | python import csv lists | <p>I want to import a CSV into multiple dictionaries in python</p>
<pre><code>queryInclude,yahoo,value1
queryInclude,yahoo,value2
queryInclude,yahoo,value3
queryExclude,yahoo,value4
queryExclude,yahoo,value5
queryInclude,google,value6
queryExclude,google,value7
</code></pre>
<p>My ideal result would have row[0]=dicti... | <p>Using <code>defaultdict</code> prevents having to account for the first element added to a dictionary. It declares the default type when the key is not present and must be a callable that creates the default object:</p>
<pre><code>#! python3
import csv
from io import StringIO
from collections import defaultdict
fr... | python|csv|dictionary|import | 4 |
3,734 | 41,589,655 | What's the difference between python3.<x> and python3.<x>m | <ul>
<li>What does the <strong><code>m</code></strong> stand for in <code>python3.6m</code> ? </li>
<li>How does it differ to non <strong><code>m</code></strong> version?</li>
<li>In which case would I prefer to use <code>python3.6m</code> rather than <code>python3.6</code>?</li>
</ul> | <blockquote>
<p>What does the <code>m</code> stand for in <code>python3.6m</code>?</p>
</blockquote>
<p>It signifies that Python was configured <code>--with-pymalloc</code> which enables a specialized implementation for allocating memory that's faster than the system <code>malloc</code>.</p>
<blockquote>
<p>How d... | python|python-3.x|python-3.6 | 68 |
3,735 | 41,659,309 | Got `bad character range` in regex when using comma after dash but not reverse | <p>I have tried this command in python console:</p>
<pre><code>re.match('^\<.+\>([\w\s-,]+)\<.+\>$', 'Carrier-A')
</code></pre>
<p>and I got:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/re.py", line 141, in match
retur... | <p>A dash <code>-</code>, when used within square brackets <code>[]</code>, has a special meaning: it defines a range of characters. E.g., <code>[\s-,]</code> means "any character from <code>\s</code> to <code>,</code>" (which is not possible). <em>However</em>, the dash does not have the special meaning if it is eithe... | python|regex|python-2.7 | 9 |
3,736 | 41,317,905 | adding sequential values in list to target value | <p>The idea is for each number to add the next sequential numbers to try to reach the target value. If for each starting value (for i...) if adding the next sequential numbers exceeds the target then i has failed and move onto the next. </p>
<p>I'm getting some values slipping through and some duplicating.</p>
<p>If ... | <p>You could use two markers that move through the list and keep track of sum of values between them. While current sum is less than target (13) and first marker is not at the end of the list move it forward and add value to current sum. Once first marker has been moved check if the current sum matches the target and u... | python | 1 |
3,737 | 57,037,252 | Updating column in for loop using merge | <p>Hi, </p>
<p>I have two dataframes and I want to loop through subsets of my first DF and merge values to my second DF. </p>
<p>My data looks like: </p>
<pre><code> DF1
product survey_id
X1 survey_1
x2 survey_1
x3 survey_2
x4 survey_3
x5 survey_3
... | <p>I hope this works. The idea is that having DF1, you could create a data frame (keys) with just the last survey ids and based on that populate DF2.</p>
<pre><code>dict1 = {'product':['x1','x2','x3','x4','x5', 'x1', 'x2', 'x3', 'x4', 'x5'],
'survey_id':['survey_1','survey_1','survey_2', 'survey_3', 'surve... | python|sql|pandas|numpy|merge | 0 |
3,738 | 25,493,242 | UNIQUE constraint failed in SQLAlchemy | <p>I have two simple classes for SQLAlchemy:</p>
<pre><code>papers2authors_table = Table('papers2authors', Base.metadata,
Column('paper_id', Integer, ForeignKey('papers.id')),
Column('author_id', Integer, ForeignKey('authors.id'))
)
class Paper(Base):
__tablename__ = "papers"
id = Column(Integer, pri... | <p>I found a solution that I don't like, but it works. Replace this:</p>
<pre><code> try:
self.s.begin_nested()
author = Author(name=v)
except IntegrityError:
print("Duplicate author")
self.s.rollback()
author = self.s.query(Author).filter(Auth... | python|sql|sqlalchemy | 5 |
3,739 | 44,616,922 | Matplotlib ignore negative values in 3D plot | <p>I have to plot a 3d function which has meaningless negative values (they should not appear in the plot). The function which has to be plot is like:</p>
<pre><code>def constraint_function(x, y):
return min(
(1800 - 0.3 * x - 0.5 * y) / 0.4,
(500 - 0.1 * x - 0.08 * y) / 0.12,
(200 - 0.06 *... | <p>First, your z-value array axes are reversed; it should be <code>zs[iy][ix]</code> not <code>zs[ix][iy]</code>. Because of this your plot is flipped left-for-right.</p>
<p>Second, building your z array by iterating in Python is much slower; you should instead delegate to numpy, like so:</p>
<pre><code>import numpy ... | python|python-3.x|matplotlib | 1 |
3,740 | 61,875,790 | speed up a Pandas fillna by subcatagory mean (how to replace a for loop) | <p>My data contains several sub categories coded in the column "RID", I'm filling by the mean of each sub category. The code I've been using is very slow. Looking for a better method that gets rid of the for loop.</p>
<pre><code>filled = mergedf.copy()
for c,v in enumerate(mergedf.RID.unique()):
filled.loc[filled.... | <p>Let's try the following, using <code>groupby</code> with <code>transform</code>:</p>
<pre><code>filled['FDG'].fillna(filled.groupby('RID')['FDG'].transform('mean'))
</code></pre>
<p>or </p>
<pre><code>fill4 = filled.fillna(filled.groupby('RID').transform('mean'))
</code></pre> | pandas|dataframe|pandas-groupby|fillna | 0 |
3,741 | 23,833,708 | Accessing request headers in flask-restless preprocessor | <p>I'm building an API with Flask-Restless that requires an API key, that will be in the <code>Authorization</code> HTTP header.</p>
<p>In the Flask-Restless example <a href="http://flask-restless.readthedocs.org/en/latest/index.html" rel="nofollow">here</a> for a preprocessor:</p>
<pre><code>def check_auth(instance_... | <p>In a normal Flask request-response cycle, the <a href="https://flask.readthedocs.org/en/latest/reqcontext/"><code>request</code> context</a> is active when the Flask-Restful preprocessors and postprocessors are being run.</p>
<p>As such, using:</p>
<pre><code>from flask import request, abort
def check_auth(instan... | python|flask|flask-restless | 7 |
3,742 | 24,333,156 | Creating a shortcut to a network path in Python | <p>I need to create a shortcut to a network drive in Python. We have a network drive that is mapped to various letters on different PCs (i.e.: I:\ or R:\) so I can't place a letter in front of the path because it various by user. Instead, I directly use the network path but when I try to run the following code, I get a... | <p>Network paths usually start with two backslashes, for example <code>\\server\share</code> to access the share called <code>share</code> on <code>server</code>. As such, when specifying the path to that share, you will have to use four backslashes if you want to escape it:</p>
<pre><code>'\\\\xxxxxxx.xx.xx.xxx.com\\... | python|win32com | 1 |
3,743 | 24,425,337 | Converting text in Matplotlib when exporting .eps files | <p>I'd like to be able to save Matplotlib plots and add them directly as vector graphics in Microsoft Word documents. However, the only format supported by Word and Matplotlib both is .eps, and the axis text is completely missing in Word if I try. I'll show you:</p>
<p>Here's a minimal working example script:</p>
<pr... | <p>As sebacastroh points out, one can save the matplotlib figure as <code>svg</code> using <code>plt.savefig()</code> and then use Inkscape to do the conversion between <code>svg</code> and <code>emf</code>. Enhanced Meta files (emf) are easily read by any Office programm.<br>
This can be automated, like so</p>
<pre><... | python|matplotlib|eps | 3 |
3,744 | 20,701,715 | How to install python-evdev on Mac OS? | <p>Is there any way to install the <code>python-evdev</code> library on Mac OS? When I try to install it, Mac says that <code>The linux/input.h header file is missing.</code> (of course). Is it possible to install it under Mac? Or do you know any other alternative?</p>
<p>I have an application that reads the Wacom inp... | <p>I'm afraid that this isn't possible, since the evdev interface is specific to the Linux kernel. Even if you managed to install it, it would not work as there are no <code>/dev/input/*</code> devices from which events can be read on MacOS.</p>
<p>If you're looking for a portable solution, you may want to look into a... | python|macos|wacom|evdev | 6 |
3,745 | 72,046,021 | Save multiple dataframes to the same file, one after the other | <p>Lets say I have three dfs</p>
<pre><code>x,y,z
0,1,1,1
1,2,2,2
2,3,3,3
a,b,c
0,4,4,4
1,5,5,5
2,6,6,6
d,e,f
0,7,7,7
1,8,8,8
2,9,9,9
</code></pre>
<p>How can I stick them all together so that i get:</p>
<pre><code>x,y,z
0,1,1,1
1,2,2,2
2,3,3,3
a,b,c
0,4,4,4
1,5,5,5
2,6,6,6
d,e,f
0,7,7,7
1,8,8,8
2,9,9,9
</code></pre>... | <p>If you want to save all your dataframes in the <strong>same file</strong> one after the other, use a simple loop with <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_csv.html" rel="nofollow noreferrer"><code>to_csv</code></a> and use the file append mode (<strong>a</strong>):</p>
<pre class... | python|pandas|dataframe | 2 |
3,746 | 71,834,176 | How can I make a live counter that counts the passwords generated from a txt file in python? | <pre><code>import random
chars = "abcdefghijklmnopqrstuvwxyz"
numbers = "123456789"
while 1:
password_len = int(input(" What length for the passwords: "))
password_count = int(input(" How many passwords would you like to generate: "))
txtfile = open('passwords.txt... | <p>This prints the count every 1,000 lines:</p>
<pre><code>for x in range(password_count):
password = ""
for _ in range(password_len):
password += random.choice(chars + numbers)
if x % 1000 == 0:
print(x,end='\r')
txtfile.write(password + '\n')
</code></pre>
<p>For 100,000 passwords, it only t... | python|counter | 0 |
3,747 | 46,618,781 | Python convert specific dataframe columns to integer | <p>I have a dataframe of 8 columns and I would like to convert last six columns to integer. The dataframe contains also NaN values and I don't want to remove them.</p>
<p><a href="https://i.stack.imgur.com/tdGG1.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tdGG1.jpg" alt="enter image description ... | <p>Thanks to MaxU I'm adding this option with nan = -1:</p>
<blockquote>
<p>Reason: nan values are float values and can't coexist with integers.
So either nan values and floats or the option to think of -1 as nan</p>
</blockquote>
<p><a href="http://pandas.pydata.org/pandas-docs/version/0.20/generated/pandas.to_n... | python|dataframe|integer|type-conversion | 4 |
3,748 | 62,537,608 | 'django' is not recognized as an internal or external command in PyCharm's virtual environment | <p>New to PyCharm and Django, I've looked through online for this solution for a few hours already, nothing seems to work.</p>
<p>The usual: <code>python -m django-admin startproject mysite</code> does not seem to work if my cmd directory is at <code>C:\Users\...\PycharmProjects\</code></p>
<p>On the other hand, if I u... | <p>You have to add python to your system path variable <a href="https://datatofish.com/add-python-to-windows-path/" rel="nofollow noreferrer">this is a quick tutorial on how to do so</a></p> | python|django|pycharm | 0 |
3,749 | 70,168,752 | could not convert string to float: '2,550,000,000' | <p>I'm trying to fit a module to my dataframe but im getting <code>could not convert string to float: '2,550,000,000'</code> error. please take a look at my codes below:</p>
<pre><code>import tensorflow as tf
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.compose import make_column_transformer
from sk... | <p>You can specify the thousands separator when you read the file like this:</p>
<pre><code>houseprice = pd.read_csv('houseprice.csv', thousands=',')
</code></pre> | python|pandas | 3 |
3,750 | 53,444,507 | Get text of an element when it has more elements with text | <p>I am using Selenium in Python and Firefox and I would want to get the text "TextB" in the next portion of HTML, I have tried with <code>element.get_attribute('textContent')</code> but it takes "TextA" too, is there any form of getting ONLY that text?</p>
<pre><code><p class="class_name" id="id_name">
<... | <p>Try to get text content of the last child only</p>
<pre><code>element = driver.find_element_by_id('id_name')
driver.execute_script('return arguments[0].lastChild.textContent', element)
</code></pre> | html|python-3.x|selenium | 3 |
3,751 | 53,459,046 | Pandas dataframe change all value if greater than 0 | <p>I have a dataframe</p>
<pre><code>df=
A B C
1 2 55
0 44 0
0 0 0
</code></pre>
<p>and I want to change values to 1 if the value is >0.</p>
<p>Is this the right approach:
df.loc[df>0,]=1</p>
<pre><code>to give:
A B C
1 1 1
0 1 0
0 0 0
</code></pre> | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.clip_upper.html" rel="nofollow noreferrer"><code>clip_upper</code></a>:</p>
<pre><code>df = df.clip_upper(1)
print (df)
A B C
0 1 1 1
1 0 1 0
2 0 0 0
</code></pre>
<p>Numpy alternative:</p>
<pre><code>df = pd.DataFra... | pandas|dataframe | 6 |
3,752 | 45,978,058 | Return NaN from indexing operation on a pandas series | <pre><code>a = pd.Series([0.1,0.2,0.3,0.4])
>>> a.loc[[0,1,2]]
0 0.1
1 0.2
2 0.3
dtype: float64
</code></pre>
<p>When a non existent index is added to the request along with existing ones, it returns NaN (which is what I need).</p>
<pre><code>>>> a.loc[[0,1,2, 5]]
0 0.1
1 0.2
2 0.3... | <p>Try <code>pd.Series.reindex</code> instead.</p>
<pre><code>out = a.reindex([0,1,2, 5])
print(out)
0 0.1
1 0.2
2 0.3
5 NaN
dtype: float64
</code></pre>
<hr>
<pre><code>out = a.reindex([5])
print(out)
5 NaN
dtype: float64
</code></pre> | python|pandas|indexing|nan|series | 5 |
3,753 | 33,155,448 | Python split not the expected result | <p>I'm trying to cut a string into pieces in Python with the following code:</p>
<p><code>re.split("[A-Z][a-z]?[0-9]*","CO2")</code></p>
<p>I expect some result like this:</p>
<pre><code>["C","O2"]
</code></pre>
<p>however I get:</p>
<pre><code>['','','']
</code></pre> | <p>Since you have no capturing groups in your re, the things you split on are not part of the result. What you're getting is the empty string before the 'C', the empty string between 'C' and 'O2' and the empty string after 'O2'.</p>
<p>If you use</p>
<pre><code>re.split("([A-Z][a-z]?[0-9]*)","CO2")
</code></pre>
<p>... | python|regex | 1 |
3,754 | 73,616,449 | Pandas.read_csv stops at 50 characters | <p>i've got some finance data stored in a csv. The problem comes when loading my bids and asks, which are lists of lists, stored in a csv. My goal now is to load the csv into normal lists i can zip and map to whatever i need. Currently have found a way using .to_string() to create a string representation of my list of ... | <p>thanks everyone! with your help my solution wound up being simpler, using .at[]
.at[] returns a string instead of any kind of object which i can use with literal_eval to convert it to list!</p>
<pre><code>df = pandas.read_csv('C:/Users/Ethan/Desktop/csv/test.csv', names=['E','ID','Bids','Asks'])
df2 = df.at[0,'Bids'... | python|pandas|csv | 2 |
3,755 | 12,905,984 | How to make my user input allow for variables in it in python? | <p>My problem is that my program will not recognize the user input for the sides of the equation includes a variable in it (x) which I am using a trial and error method for finding. It sees x as a string, seperate from the defined variable x. So, if the user put in for the right side of the equation 16 and x*x for the ... | <p>You can use <a href="http://docs.python.org/library/functions.html#eval" rel="nofollow"><code>eval()</code></a> to evaluate arbitrary Python code. It is generally a Very Bad Idea to use this in real world code as it is extremely dangerous to allow users to execute unknown code, even if you try to restrict what they ... | python|string|variables|input | 2 |
3,756 | 38,131,592 | No module name _tkinter windows python 2.7 | <p>I have been searching for hours reading over various suggestions for this topic so please do not downvote me too fast. The closest thing i could find to a solution is here: <a href="https://stackoverflow.com/questions/5459444/tkinter-python-may-not-be-configured-for-tk">Tkinter: "Python may not be configured fo... | <p>Your title says python2.7 but your error message says python2.5 ... I'm guessing you are accidentally running the wrong python installation. </p> | python|windows|python-2.7|tkinter | 0 |
3,757 | 40,140,067 | Python-Counting element frequency in a 2D list | <p>I want to know if there is a way to count element frequencies in a 2D python list.
For 1D lists, we can use</p>
<pre><code>list.count(word)
</code></pre>
<p>but what if I have a list:</p>
<pre><code>a = [ ['hello', 'friends', 'its', 'mrpycharm'],
['mrpycharm', 'it', 'is'],
['its', 'mrpycharm'] ]
</... | <p>Assuming I understand what you want,</p>
<pre><code>>>> collections.Counter([x for sublist in a for x in sublist])
Counter({'mrpycharm': 3, 'its': 2, 'friends': 1, 'is': 1, 'it': 1, 'hello': 1})
</code></pre>
<p>Or,</p>
<pre><code>>>> c = collections.Counter()
>>> for sublist in a:
... ... | python | 6 |
3,758 | 39,968,806 | "oauth2client.transport : Refreshing due to a 401" what exactly this log mean? | <p>I setup a job on google cloud dataflow, and it need more than 7 hours to make it done. My Job ID is 2016-10-10_09_29_48-13166717443134662621. It didn't show any error in pipeline. Just keep logging out "oauth2client.transport : Refreshing due to a 401". Is there any problem of my workers or there is something wrong.... | <p>As a general approach, you should try running the pipeline locally, using the <code>DirectPipelineRunner</code> on a small dataset to debug your custom transformations.</p>
<p>Once that passes, you can use the Google Cloud Dataflow UI to investigate the pipeline state. You can particularly look at <code>Elements Ad... | python|google-cloud-dataflow | 2 |
3,759 | 8,841,227 | Browser charsets order of precedence | <p>Client browsers are sending the header <code>HTTP_ACCEPT_CHARSET: ISO-8859-1,utf-8;q=0.7,*;q=0.3</code>. I only serve webpages as utf8 with the correct header but browsers are posting data from forms encoded with the ISO-8859-1 charset. My question is, will a browser always prefer charsets in the order of its ACC... | <p>The request header <code>Accept-Charset</code> (which may get mapped to <code>HTTP_ACCEPT_CHARSET</code> server-side) expresses the client’s preferences, to be used when the server is capable to serving the resource in different encodings. The server may ignore it, and often will.</p>
<p>If your page is UTF-8 encod... | python|html|character-encoding | 2 |
3,760 | 8,859,504 | django form dropdown list of numbers | <p>i am new to django and i want to make a simple form, according to the doc i can make a form using forms module from django</p>
<pre><code>from django import forms
class CronForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField(required=False, label='Your e-mail address')
mes... | <p>You're looking for a <code>ChoiceField</code> which renders as a <code>select</code> html element by default.
<a href="https://docs.djangoproject.com/en/dev/ref/forms/fields/#choicefield" rel="noreferrer">https://docs.djangoproject.com/en/dev/ref/forms/fields/#choicefield</a></p>
<pre><code>class CronForm(forms.For... | python|django|linux | 61 |
3,761 | 52,013,284 | chromedriver building from source not working | <p>I am on Mac (OSX-13.13) , I am following the instructions here.</p>
<ul>
<li><a href="https://chromium.googlesource.com/chromium/src/+/master/docs/mac_build_instructions.md" rel="nofollow noreferrer">https://chromium.googlesource.com/chromium/src/+/master/docs/mac_build_instructions.md</a></li>
</ul>
<p>args confi... | <p>Figured out myself, basically I had set <code>is_component_build = false</code> which is why the binary is split into one chromedriver and several other dylibs. Those dylibs will also have to be copied to the same folder which explain why it was small. To get it correct either the path containing dromedriver with al... | python|selenium|selenium-webdriver|selenium-chromedriver | 0 |
3,762 | 52,388,933 | Pandas: Mark values between flags from another column | <p>The workflow is as below:</p>
<ol>
<li>Groupby LineNum then</li>
<li>Mark values in LWS column greater than 50 as 'start'</li>
<li>Mark values in Text column containing ':'(colon) as 'end'</li>
<li>Mark values between start and end as 1 in 'ExpectedFlag'</li>
</ol>
<p><strong>I have finished upto step 3 i.e upto c... | <p>You can write and apply a function to do this:</p>
<pre><code>def proc():
started = False
def inner(b):
nonlocal started
if started:
if b == 1:
started = False
return 1
else:
if b == 1:
started = True
... | python|pandas|data-science | 1 |
3,763 | 59,646,219 | Test set accuracy of 1. How to debug | <p>I am trying to create a simple neural network using tensorflow as a learning exercise. These are the details of the NN I created.. </p>
<pre><code>def multilayer_perceptron(x, weights, biases, keep_prob):
layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
layer_1 = tf.nn.relu(layer_1)
layer_1 =... | <p>There can be multiple reasons for it, first, let's look at the hyperparameter you are defining. </p>
<p><strong>Learning rate:</strong></p>
<p>There are multiple ways to select a good starting point for the learning rate. A naive approach is to try a few different values and see which one gives you the best loss w... | python|tensorflow|machine-learning|deep-learning|neural-network | 0 |
3,764 | 36,269,908 | how to not install package with pip to anaconda | <p>I have problem about pip.</p>
<p>When I want to install some package, for instance flask, It wants to install it to /anaconda3. </p>
<pre><code>juldou@juldou-machine:~$ pip install flask
Requirement already satisfied (use --upgrade to upgrade): flask in ./anaconda3/lib/python3.5/site-packages
</code></pre>
<p>I k... | <p>The command <code>pip</code> belongs to whatever python environment it was installed in. The exact binary that is executed when you run a command are determined by your PATH environment variable and whatever executable is found first is executed. In your case your Anaconda environment is in your PATH before your sys... | python|linux|installation|pip|anaconda | 6 |
3,765 | 16,978,806 | How to run scrapy server as a daemon | <p>I am trying to run scrapy server as a daemon. I have tried <a href="http://scrapyd.readthedocs.org/en/latest/" rel="nofollow">this link</a> but i getting error
whenever i run this command:</p>
<pre><code>sudo apt-get install scrapyd-0.14
Reading package lists... Done
Building dependency tree
Reading state ... | <p>You need to add the Ubuntu repository first. Run the following commands under root permission: </p>
<pre><code>$ curl -s http://archive.scrapy.org/ubuntu/archive.key | sudo apt-key add -
$ echo "deb http://archive.scrapy.org/ubuntu precise main" >> /etc/apt/sources.list
$ apt-get update
$ apt-get install scra... | python|scrapy|scrapyd | 9 |
3,766 | 52,736,989 | How to print the first letter from a list of random names | <p>How to print the first letter from a list of random names?<br>
This is what I have done so far and I can print the names randomly but need to print the first letter and not the whole name.</p>
<pre><code>import random
names = ['Ed Sheeran', 'Beyonce', 'Adele', 'Rhianna']
secure_random = random.SystemRandom()
print... | <p>Randomize the list and then print the first character-</p>
<pre><code>import random
names = ['Ed Sheeran', 'Beyonce', 'Adele', 'Rhianna']
random_names = random.sample(names, len(names))
#If you are okay with mutating the original list then look into "shuffle"
for name in random_names:
print(name[0])
</code></pr... | python | 1 |
3,767 | 52,808,344 | Get number of seconds until the start of the next hour | <ul>
<li>I'm currently using a REST API that only allows 1000 queries per hour</li>
<li>Once the 1000 queries are used up, you then have to wait until the beginning of the next hour for the counter to be reset</li>
<li>My aim is to determine the number of seconds that I have to wait until the start of the next hour</li... | <p>Think <code>datetime.timedelta</code> will help you in this case. Something like this:</p>
<pre><code>import datetime
delta = datetime.timedelta(hours=1)
now = datetime.datetime.now()
next_hour = (now + delta).replace(microsecond=0, second=0, minute=2)
wait_seconds = (next_hour - now).seconds
</code></pre>
<p... | python|datetime|timedelta | 10 |
3,768 | 37,200,909 | Declaring uninterpreted polyadic functions with Z3Py | <p>Using Z3Py, I'm trying to write a function <code>decl_func(fname, arity)</code> which takes in two arguments : <code>fname</code>, the name of the function to be declared, and <code>arity</code>, its number of arguments, and returns the corresponding (uninterpreted) Z3 function over integers. The problem is that the... | <p>This question is about <a href="http://rosettacode.org/wiki/Variadic_function#Python" rel="nofollow">variadic functions in Python</a>.</p>
<blockquote>
<p>You can use the same "*" syntax to apply the function to an existing list of arguments: </p>
</blockquote>
<p>Therefore, something like this <em>should</em> w... | python-3.x|z3|z3py | 1 |
3,769 | 37,456,131 | Sorting in sparse matrix (Python 2.*) | <p>I'm solving a task in coursera and get stuck with sorting in sparse matrix.
The problem is: i make a support vector classification (<code>sklearn.svm.SVC</code>) </p>
<pre><code> clf = SVC(C=1, kernel='linear', random_state=241)
clf.fit(X, y)
</code></pre>
<p>and as a result got a matrix <code>clf.coef_</co... | <p>Since by calling <code>argsort</code> you get the sorted indices instead of the sorted array, you can use the result of <code>argsort</code> directly as feature indices.</p>
<p>So if you have an array <code>[1.5, 2.5, 0.5]</code>, the result of <code>argsort</code> is <code>[2, 0, 1]</code>, representing that eleme... | python|scikit-learn|sparse-matrix|python-2.x | 0 |
3,770 | 37,553,343 | No such File or Directory Exception | <p>I am a relative newbie to Python, and I have searched and while there are many posts regarding the error, none appear to address my requirement.</p>
<p>Briefly, I am writing code to hourly reports. I intend to have 4 days of reports archived in the folder. At the beginning of my code I have one line that deletes al... | <p>If the file it wants to delete is not in the directory, I want that to be okay and the program to continue processing the next command instead of aborting the process. In short I want to check to see if the file is there and if it isn't skip the rm code and process the rest of the script.</p> | python|exception | 2 |
3,771 | 37,351,871 | Gui with button to open port scanner | <p>I am making a GUI with tkinter that allows me to click a button that will run a port scan. I have a script for a port scan that functions correctly, I have managed to open the port scanner through the button on the GUI but then I receive an error that I otherwise don't receive when running the port scanner alone. </... | <p>The problem is with your <code>exec</code> statement. You're opening your other <code>.py</code> file named <code>port_scanner.py</code> and then calling <code>exec(open("./port scanner.py))</code>.</p>
<p>This just isn't going to work.</p>
<p><strong>Why this doesn't work:</strong></p>
<p>When you do <code>exec(... | python|user-interface|port | 1 |
3,772 | 34,418,545 | (Flask) Faking request.environ['REMOTE_USER'] for testing | <p>I am deploying a Flask app on IIS and using its Windows Authentication, which sets request.environ['REMOTE_USER'] to your windows username if authenticated successfully. Now when writing test cases, how do I fake request.environ['REMOTE_USER']? The test cases are run independent of the IIS server. </p>
<p>My attemp... | <p>Figured out the answer to my own question from <a href="https://stackoverflow.com/questions/15278285/setting-mocking-request-headers-for-flask-app-unit-test">Setting (mocking) request headers for Flask app unit test</a>. There is an <code>environ_base</code> parameter that you can pass request environment variables ... | python|iis|flask|wsgi | 7 |
3,773 | 66,020,301 | Discord.py creating embeds without subtitles | <p>I'm a newbie to python and Stackoverflow in general so please let me know if this is out of place.</p>
<p><strong>Question:</strong> How do I create an embed in discord with discord.py without having to add a sub-title to the embed?</p>
<p>For example, here is a simplified version of my embed function:</p>
<pre><cod... | <p>It's a strange area where Discord.py doesn't make sense, it at least cannot be avoided or left empty, however there are some ways to circumvent the problem</p>
<p>In this example, you can just use the bold decorator in the field you don't want, you can also use the unicode blank character which would also appear as ... | python|discord|discord.py | 3 |
3,774 | 72,660,765 | Why os.path.realpath doesn't work properly | <p>i just downloaded a file called "N_PR_8705_004A_.doc" in my "Downloads" folder and i want to put it into my "Stage NLP" folder using os. I know how to do it without os but i'd like that shit to work it's faster and it simply doesnt. First i tried to get the path of my file doing this:</... | <p>I think I have a possible answer to your question. Neither <code>realpath</code> nor <code>abspath</code> require their arguments to name existing files. In particular, the <a href="https://docs.python.org/3/library/os.path.html#os.path.abspath" rel="nofollow noreferrer">documentation</a> for <code>abspath()</code> ... | python|operating-system | 0 |
3,775 | 39,562,222 | Python save captcha image from url? Error 401 | <p>I have a problem to save captcha as png.
Here is my code so far</p>
<pre><code>import requests
url_login = "https://www.hackthis.co.uk/?login"
r_login = requests.post(url_login, {'username': 'darkcyber', 'password': 'secr3tp4s5'})
print r_login.status_code
if "Invalid login details" in r_login.text:
print "... | <p>You need download image and save to local as new file. </p>
<p>Here's the sample code:</p>
<pre><code>import requests
r = requests.get('http://url.com/captcha.php')
f = open('yourcaptcha.png', 'wb')
f.write(r.content)
f.close()
</code></pre>
<p><strong>UPDATE after your comments:</strong></p>
<pre><code>import... | python|python-requests | 4 |
3,776 | 39,644,885 | Generic binary operation in a class definition? | <p>I am writing a tiny linear algebra module in Python 3, and there are a number of binary operators to define. Since each definition of a binary operator is essentially the same with only the operator itself changed, I would like to save some work by writing a generic binary operator definition only once.</p>
<p>For ... | <p>You could use a class decorator to mutate your class and add them all in with the help of a factory function:</p>
<pre><code>import operator
def natural_binary_operators(cls):
for name, op in {
'__add__': operator.add,
'__sub__': operator.sub,
'__mul__': operator.mul,
'__truediv... | python|class | 3 |
3,777 | 16,574,470 | Out of memory when using numpy's multivariate_normal random sampliing | <p>I tried to use numpy.random.multivariate_normal to do random samplings on some 30000+ variables, while it always took all of my memory (32G) and then terminated. Actually, the correlation is spherical and every variable is correlated to about only 2500 other variables. Is there another way to specify the spherical c... | <p>If your correlation is spherical, that is the same as saying that the value along each dimension is uncorrelated to the other dimensions, and that the variance along every dimension is the same. You don't need to build the covariance matrix at all, drawing one sample from your 30,000-D multivariate normal is the sam... | python|memory|numpy | 1 |
3,778 | 31,907,613 | Test function appends NONE during end of unittest | <p>I've been working on some code to practice unit testing. The original is supposed to get all file names in a directory, and list the number of files with the same extension. When I run the same function using unittest, the test appends a <code>None</code> at the end, breaking the test.</p>
<pre><code>#!/usr/local/b... | <p>Your function doesn't use a <code>return</code> statement, so Python returns <code>None</code> (the default). You are printing that value. Note that your test isn't broken by it, your test is actually not testing anything, only running the code.</p>
<p>Simply remove your <code>print()</code> call:</p>
<pre><code>d... | python|unit-testing|python-3.x | 0 |
3,779 | 38,826,816 | boost.python caching wrapped class members | <p>I have a trivial classes dependency:</p>
<pre><code>class A {
... // constructor is omitted
public:
const std::string str1;
};
class B {
public:
std::shared_ptr<A> a;
}
BOOST_PYTHON_IMPORT(wrapped) {
class_<A, std::shared_ptr<A>>("APy")
.def_readonly("str1", &A::str1);
... | <p>The <code>APy</code> wrappers are temporaries because <code>s1, s2</code> are strings. Once <code>s1</code> is created, Python doesn't care if the setup that created it could also be used to create <code>s2</code>. Most likely <code>b.a</code> gets discarded because it isn't stored.
Does the same thing happen when ... | c++|boost|boost-python | 0 |
3,780 | 40,721,451 | Ride history prices on UBER API | <p>I am trying the UBER API using the python library. My goal is to make a simple project where I export my rides history to an excel file and this will help automate the creation of expenses reports I have to make for the company I work for.</p>
<p>Everything is working fine, except that I can`t find in the documenta... | <p>You could retrieve this data through the <a href="https://developer.uber.com/docs/riders/references/api/v1.2/requests-request_id-receipt-get" rel="nofollow noreferrer">receipts endpoint</a>, although this would require that all the Uber requests in your company were made from your application, as stated in this endp... | python|uber-api | 3 |
3,781 | 40,346,336 | Call Dictionary With Randomly Chosen Value as Name - TypeError | <p>I am using a function that assigns a variable to equal the value of a randomly chosen key. Here the type is string and print works.</p>
<pre><code>def explore():
import random
random_key = random.choice(explore_items.keys())
found_item = explore_items[random_key]
print type(found_item)
print fou... | <p>You can use a variable via its name as string using <code>exec</code>:</p>
<pre><code>dic1 = {'k': 'dic2'}
dic2 = {'key_1': 'value'}
exec('print ' + dic1['k'] + "['key_1']")
</code></pre> | python|dictionary|call | 0 |
3,782 | 40,717,835 | Python: install some packages | <p>I need to advice:
I have 2 versions of Python: 2 and 3.
How Can I install some package through the <code>pip</code> to especially version? What should I use?</p> | <p>For Python 2.x: In <code>C:\Python27\Scripts</code> folder you will have some executables like <code>pip2.7.exe</code> or <code>pip2.exe</code>
similarly for Python 3.x.</p>
<p><code>cmd> pip install <module></code>
instead of just <code>pip</code> you can use the respected version of <code>pip</code>.</p... | python|package|pip | 0 |
3,783 | 32,336,287 | Python3 & Tkinter, list.sort list of objects made of StringVar | <p>I have an Python3 app that uses a tkinter interface to collect & edit info stored in a MySQL database. The data consist of several tables, and each table row is represented by a Class (called 'Action' here) made of several StringVar(), which are sometimes displayed with buttons to remove or insert new rows. Clas... | <p>You didn't quite get the syntax right for the lambda. You need an argument and a colon. Try:</p>
<pre><code>list.sort(Action._registry, key=lambda item: item.__dict__['date'].get())
</code></pre>
<hr>
<p>Additional style tip: it is idiomatic to call <code>sort</code> as a method of the object you're sorting, rath... | python|sorting|python-3.x|tkinter | 1 |
3,784 | 27,964,159 | python 2.7 check if argument has been passed from command prompt | <p>kind of stuck in a problem. I need to check if a certain parameter has been passed via command prompt while executing a python script. </p>
<p>I execute the python file as <code>python run.py -ip 127.0.0.1 -trigger 1</code></p>
<p>While on my python script I used <code>argparse</code> as</p>
<pre><code>parser = a... | <p>Add a <code>--trigger</code> argument to your parser</p>
<pre><code>parser = argparse.ArgumentParser()
parser.add_argument('-ip', '--ip')
parser.add_argument('-t','--trigger', nargs='*')
args = parser.parse_args()
</code></pre>
<p>If <code>--trigger</code> is absent, <code>args.trigger</code> should be the default... | python|python-2.7|argparse | 3 |
3,785 | 13,913,117 | Tweepy OAuth - HTTP Error 404: Not Found | <p>I'm using the <a href="https://github.com/tweepy/tweepy" rel="nofollow">Tweepy library</a> to implement 'Signin with Twitter' on my website. </p>
<p>As shown in the <a href="https://github.com/tweepy/examples/blob/master/appengine/oauth_example/handlers.py" rel="nofollow">Tweepy examples</a>, I'm doing: </p>
<p><c... | <p>You're not returning in the <code>except</code> handler, so the code proceeds to try and create the request token before it redirects. Put a return there, so it will only proceed if there is no error.</p> | python|google-app-engine|twitter|tweepy | 0 |
3,786 | 34,530,587 | How to get "subsoups" and concatenate/join them? | <p>I have a HTML document I need to process. I'm using 'beautifoulsoup' for that. Now I would like to retrieve a few "subsoups" from that document and join them into one soup so I can later use it as a parameter for a function that expects a soup object.</p>
<p>If it's not clear, I'll give you an example...</p>
<pre>... | <p><a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/#parsing-only-part-of-a-document" rel="noreferrer"><code>SoupStrainer</code></a> would do exactly what you are asking about and, as a bonus, you'll get a performance boost since it would parse exactly what you want it to parse - not the complete document ... | python|html|beautifulsoup|html-parsing | 8 |
3,787 | 27,234,280 | How to parse sentences based on lexical content (phrases) with Python-NLTK | <p>Can Python-NLTK recognize input string and parse it not only based on white space but also on the content? Say, "computer system" became a phrases in this situation. Can anyone provide a sample code?</p>
<hr>
<p><strong>input String</strong>: "A survey of user opinion of computer system response time"</p>
<p><str... | <p>The technology you're looking for is called multiple names from multiple sub-fields or sub-sub-fields of linguistics and computing.</p>
<ul>
<li><strong>Keyphrase Extraction</strong>
<ul>
<li>From Information Retrieval, mainly use for improving indexing/querying for sear</li>
<li>Read this recent survey paper: <a... | python|nltk|lexical | 18 |
3,788 | 23,258,111 | write python script for UNIX command lines | <p>Hey there I have an assignment next week benchmark using compiler and the professor wants us to write an script actually the command lines. I am new on python and writing scripts on UNIX.
How do you write a script on Python?
I need tutorials or any advice</p>
<p>Thanks </p>
<p>We have to write these steps</p>
<p>... | <p>subprocess.Popen, os.listdir, os.chdir and time.time() should help. These are all python commands. You can get the subprocess module with "import subprocess", and the os module with "import os", for examples.</p>
<p>To create a Python script, just edit a text file (named "the-script" for this example) with your ... | python|unix | 3 |
3,789 | 7,744,695 | Create custom number data type within range? | <p>In Ada, you can define a custom data type such as this</p>
<pre><code>type Day_Of_Month is range 1 .. 31;
</code></pre>
<p>So now you can create a <code>Day_Of_Month</code> variable that can only hold an int between 1 and 31. This is nice because we don't have to keep doing conditional checks when want to update t... | <p>If this datatype is going to get used often, it might be worth creating a class for it and overwriting operators so it works more seamlessly. That way, all the exception handling is still internal to the datatype, and it gives you plenty of flexibility to define things like, for your example, differences in the numb... | python|types | 1 |
3,790 | 8,050,502 | Python's nonlocal depends on level of hierarchy? | <p>This question is a follow-up on <a href="https://stackoverflow.com/q/370357/923794">a question about Python variable scope</a>. Additional questions <a href="https://stackoverflow.com/q/1261875/923794">q1</a>, <a href="https://stackoverflow.com/q/1414304/923794">q2</a> and <a href="https://stackoverflow.com/question... | <p><code>global</code> and <code>nonlocal</code> are not meant to be combined. They mean different things:</p>
<ul>
<li><code>global</code> means the name exists at the module level</li>
<li><code>nonlocal</code> means the name exists in an outer lexical function scope</li>
</ul>
<p>The reason you are getting the or... | python|python-3.x|scope|closures | 22 |
3,791 | 7,905,380 | Testing Equivalence of xml.etree.ElementTree | <p>I'm interested in equivalence of two xml elements; and I've found that testing the tostring of the elements works; however, that seems hacky.</p>
<p>Is there a better way to test equivalence of two etree Elements? </p>
<p>Comparing Elements directly:</p>
<pre><code>import xml.etree.ElementTree as etree
h1 = etree... | <p>This compare function works for me:</p>
<pre><code>def elements_equal(e1, e2):
if e1.tag != e2.tag: return False
if e1.text != e2.text: return False
if e1.tail != e2.tail: return False
if e1.attrib != e2.attrib: return False
if len(e1) != len(e2): return False
return all(elements_equal(c1, c... | python|python-3.x|elementtree | 39 |
3,792 | 42,080,231 | python regular expression to match anything not containing some word, in between 2 characters | <p>In Fortran, a data statement begins with the word "data", followed by the name of the array, then followed by the values of the array, sandwiched between two forward slashes "/". </p>
<pre><code>pattern_data = r'''
( data [^/]+ / [^/]+ / )
'''
c = "data plevel = /4.56, 234., 1e-45/ data tlayer / -5.6, +290.098/"
... | <p>Your attempt would prohibit <code>data</code> being immediately before the first slash, which is not what you want. This tests whether <code>data</code> is anywhere between the slashes:</p>
<pre><code>( data [^/]+ / (?! [^/]* data ) [^/]+ / )
</code></pre> | python|regex | 0 |
3,793 | 70,824,293 | How to remove all pixels that aren't connected to at least 10 another pixels in python | <p>Is there a way to remove all pixels that aren't connected to at least 10 other pixels?
I want this</p>
<p><img src="https://i.stack.imgur.com/ypBGu.png" alt="image" /></p>
<p>to look something like</p>
<p><img src="https://i.stack.imgur.com/lcPyk.png" alt="this" />.</p> | <p>I'm sure that can be done with some KNN manipulation, but i suggest <a href="https://www.geeksforgeeks.org/erosion-dilation-images-using-opencv-python/" rel="nofollow noreferrer">erosion and dilation</a> to get rid of the noisy dots, using openCV for example.</p> | python | 0 |
3,794 | 70,906,116 | Calculating the tangent on a transition point of a black and white image | <p>I would like to calculate the angle of the tangent on a given white to black transition point on an image that consists entirely of black and white pixels and displays simple shapes such as squares, circles or triangles.</p>
<p>Zooming in on an image like that would look like this:</p>
<p><a href="https://i.stack.im... | <p>Such a measurement is highly inaccurate on binary images, if not unusable.</p>
<p>If you measure on two neighboring pixels, the angle will be one of 0° or ±45°, so the angular resolution is very poor !</p>
<p>You can compute on several pixels to improve that resolution (five pixels correspond to like 11°), but now y... | python|c++|math|image-processing|calculus | 0 |
3,795 | 11,807,034 | How do I generate a set of four specific characters? | <p>New to coding, having fun with an adventure game. I want the character to be able to run away from a monster and in doing so, the game will generate a random character that must be one of the following four characters:</p>
<p>N S W E</p>
<p>I am having trouble doing so, currently I have </p>
<pre><code>import ran... | <p>Just use <code>random.choice('NSEW')</code>.</p> | python|string|character|generator | 7 |
3,796 | 11,718,852 | sum over values in python dict except one | <p>Is there a way to sum over all values in a python dict except one by using a selector in </p>
<pre><code>>>> x = dict(a=1, b=2, c=3)
>>> np.sum(x.values())
6
</code></pre>
<p>?
My current solution is a loop based one:</p>
<pre><code>>>> x = dict(a=1, b=2, c=3)
>>> y = 0
>>... | <p>You could loop over the dict to create a generator for the <code>sum</code> method:</p>
<pre><code>np.sum(value for key, value in x.iteritems() if key != 'a')
</code></pre> | python|dictionary|numpy|sum | 8 |
3,797 | 11,687,953 | Operations on rows in scipy sparse matrix of csr format | <p>I would like to multiply single rows of a csr matrix with a scalar. In numpy I would do</p>
<pre><code>matrix[indices,:] = x * matrix[indices,:]
</code></pre>
<p>For csr this raises an exception in scipy.</p>
<p>Is there a way to do this similarily with csr matrixes?</p> | <p>No, there's no way to this directly, because although you can compute <code>row * x</code>, you can't assign to a row in a CSR matrix. You can either convert to DOK format and back, or work on the innards of the CSR matrix directly. The <code>i</code>'th row of a CSR matrix <code>X</code> is the slice</p>
<pre><cod... | python|numpy|scipy | 12 |
3,798 | 58,279,548 | Using split-apply-combine to remove some values with a customized function and combine what's left | <p>So this isn't the dataset I need to work with but it's a template for a huge one I'm working with (~1.8 million data points) for a cancer research project, so I figured if I could get this to work with a smaller one, then I can adapt it for my large one! So as a sample, let's say I have the following data set:</p>
... | <p>EDIT: more general solution</p>
<p>First, it would help to make a <code>closure</code> to define your configurations. This is under the assumption that you will have more configurations in the future:</p>
<pre><code>def create_num_to_delete(p, alpha):
"""Create a num_to_delete function given p and alpha."""
... | python|pandas|split-apply-combine | 2 |
3,799 | 37,697,934 | How to remove % symbol for particular column in dataframeusing python pandas? | <p>My data frame have following data:</p>
<pre><code>company,standard,returns
aaa,b1,10%
bbb,b2,20%
</code></pre>
<p>I have to remove <code>%</code> from <code>returns</code> column.</p> | <p>First remove last value of each string by <a href="http://pandas.pydata.org/pandas-docs/stable/text.html#indexing-with-str" rel="noreferrer">indexing with str</a> and then cast to <code>int</code> or <code>float</code>:</p>
<pre><code>#if int values
print (df['returns'].str[:-1].astype(int))
#if flaot values
print... | python|python-2.7|pandas|dataframe | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.