Unnamed: 0 int64 0 1.91M | id int64 337 73.8M | title stringlengths 10 150 | question stringlengths 21 64.2k | answer stringlengths 19 59.4k | tags stringlengths 5 112 | score int64 -10 17.3k |
|---|---|---|---|---|---|---|
5,900 | 49,719,673 | Why can a subprocess still write to stdout after it's been closed? | <p>I found this piece of code in the <a href="https://docs.python.org/3/library/subprocess.html#replacing-shell-pipeline" rel="noreferrer"><code>subprocess</code> documentation</a>, where one process's stdout is being piped into another process:</p>
<pre><code>p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hd... | <p>Closing a file decriptor just means decrementing a reference count (inside the operating system kernel). The descriptor number becomes invalid, but nothing happens to the object it refers to unless the reference count hits zero.</p>
<p>Inside the <code>Popen</code> calls, operations are taking place which duplicate... | python|subprocess|pipe | 4 |
5,901 | 62,618,511 | Why are Python issues preceded by `bpo-`? | <p>I've raised two python issues, but can't work out why the issue numbers are referred to as <code>bpo-xxxxxx</code> where <code>xxxxxx</code> is the issue number.</p>
<p>What is the etymology for this, or what is <code>bpo</code> an acronym for?</p>
<p>Why is it generally written in lowercase?</p> | <p>The Python Developer's Guide's <a href="https://devguide.python.org/tracker/" rel="noreferrer">Issue Tracking</a> page says:</p>
<blockquote>
<p>The issue tracker is also commonly referred to as <em>bugs.python.org</em> and <em>bpo</em>.</p>
</blockquote> | python|issue-tracking | 6 |
5,902 | 62,661,312 | Apply the lambda function for replacing number in pandas pivot table | <p>What's the good way to replace the number into pandas pivot table?</p>
<p>I used this code but always invalid syntax. What's the syntax should be? for replacing number in pivot.</p>
<p><a href="https://i.stack.imgur.com/ZG8un.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZG8un.png" alt="enter im... | <p>You can try:</p>
<pre><code>(pivot_table > 2.5).astype(int)
</code></pre> | python|python-3.x|pandas|pivot-table | 0 |
5,903 | 53,479,514 | How to uninstall Anaconda even without Anaconda Uninstall.exe? | <p>I had several issue with Jupyter and thought of uninstalling anaconda and reinstalling it. But when I uninstall, it says successfully uninstalled but anaconda is still there.</p> | <p>To uninstall Anaconda open a terminal window and remove the entire anaconda install directory: <code>rm -rf ~/anaconda</code>. You may also edit <code>~/.bash_profile</code> and remove the anaconda directory from your <code>PATH</code> environment variable, and remove the hidden .condarc file and .conda and .continu... | python|anaconda | -1 |
5,904 | 53,509,168 | Extract Year, Month and Day from datetime64[ns, UTC], Python | <p>I have this column in a df:</p>
<pre><code> > df["time"]
0 2007-02-01 22:00:00+00:00
1 2007-02-01 22:00:00+00:00
2 2007-02-01 22:00:00+00:00
3 2007-02-01 22:00:00+00:00
4 2007-02-01 22:00:00+00:00
</code></pre>
<p>I want to create three new columns with day, month, and... | <p>In order to not modify your existing <code>time</code> column, create a separate datetime series using <code>pd.to_datetime</code> and then use the <code>dt</code> accessor:</p>
<pre><code># obtain datetime series:
datetimes = pd.to_datetime(df['time'])
# assign your new columns
df['day'] = datetimes.dt.day
df['mo... | python|pandas|datetime|time|datetime64 | 7 |
5,905 | 53,754,542 | Changing values for ndarray based on condition upon another ndarray of the same shape | <p>So I have two ndarray
one is containing ndvi values the other one is containing temperature</p>
<p>The condition is that the for all the pixel with temperature that is above the 25% of all temperatures, its pixel's ndvi value has to be changed to np.nan.</p>
<p>So I am currently using:
temp[temp > T_25]=np.nan (w... | <p>Your line <code>temp[temp > T_25] = np.nan</code> is almost correct. You just have to change the array that you're indexing to be <code>ndvi</code>:</p>
<pre><code>ndvi[temp > T_25] = np.nan
</code></pre>
<p>Should do what you want.</p>
<p>You can also fold the calculation of <code>T_25</code> into the same... | python|numpy|landsat | 0 |
5,906 | 53,551,620 | how to filter multiple filed with python Regular expression | <p>May I know how should I design the filter to get multiple match for a filed? Here is an example, I need to fitler the all uplinkVolume from below paragraph to summary the all uplink volume.</p>
<p>How can I do that with Python Regular expression? </p>
<blockquote>
<p>{ extensionType:{1} length:{48} serviceList:{... | <p>This expression finds all uplinkVolume fields and places the values of the found fields into a group. Values equal to " - " are not included in the sample.</p>
<pre><code>r"uplinkVolume:{(\d+)}"
</code></pre>
<p>Example of use:</p>
<pre><code>import re
json_text = "YOUR_JSON_TEXT_FROM_THE_EXAMPLE_ABOVE"
field_va... | python|expression | 1 |
5,907 | 53,600,059 | Replacing values from one dataframe to another | <p>I'm trying to fix discrepancies in a column from one df to a column in another.
The tables are not sorted as well.
How can i do this using python. Example:</p>
<p>df1</p>
<pre><code>Age Name
40 Sid Jones
50 Alex, Bot
32 Tony Jar
65 Fred, Smith
24 Brad, Mans
</code></pre>
... | <p>Create a column in <code>df1</code> with commas removed from the <code>Name</code> column</p>
<pre><code>df1['Name_nocomma'] = df1.Name.str.replace(',', '')
</code></pre>
<p>merge <code>df1</code> to <code>df2</code> using <code>Name_nocomma</code> & <code>Name</code> to get the <em>corrected</em> <code>Name</... | python|pandas|dataframe | 2 |
5,908 | 53,572,551 | Relisting a stack | <pre><code>class Stack:
def __init__(self):
self.container = []
def isEmpty(self):
return self.size() == 0
def push(self, item):
self.container.append(item)
def peek(self) :
if self.size()>0 :
return self.container[-1]
else :
r... | <p>Add a <a href="https://docs.python.org/3/reference/datamodel.html#object.__str__" rel="nofollow noreferrer"><code>__str__</code></a> method to the class that will construct the list then just print the instance</p>
<pre><code>class Stack:
...
def __str__(self):
return '\n'.join('{} - {}'.format(n, t... | python|stack | 0 |
5,909 | 46,058,324 | Counting the real number of arguments in python | <p>Is there any way to count the <strong>real</strong> number of arguments passed to a function in python, even when some defaults values are set? I'm trying to write a function, which replaces a certain range of a text file with 0 (or an offset value), but it doesn't work because python returns the number of arguments... | <p>Just use <code>None</code> as the default for <code>end</code>:</p>
<pre><code>def substitute_with(FILE, start, end=None, offset=0):
...
if end is None:
end = length_Z
...
</code></pre> | python|parameters|arguments|signature | 2 |
5,910 | 55,010,130 | Python function using loops | <p>I need help going through this problem</p>
<blockquote>
<p>print the list elements in reverse order using a loop</p>
</blockquote>
<p><code>def reverse():
nums = [3,7,5,0,-4,1,0,-7,34,5,-87,43,1,76]</code></p>
<p>we cannot use reverse command and must use loops.</p> | <pre><code>nums = [3,7,5,0,-4,1,0,-7,34,5,-87,43,1,76]
for i in range(len(nums)-1, -1, -1):
print(nums[i])
</code></pre>
<p>This basically starts with 1 less than <code>len(nums)</code>, goes until you get to just before -1, in increments of -1.</p> | python | 0 |
5,911 | 33,258,754 | Run $Path command in Terminal in a python script | <p>i use ipython notebook and I want to call a terminal command:
<code>fft <in> <out></code></p>
<p>my "fft" is in my $PATH so using a terminal, this would work. </p>
<p>How can I run this command in my ipython notebook?</p>
<hr>
<p>the problem is that my fft executable is in my $PATH folder, and pytho... | <p>Found the solution:</p>
<pre><code>import os
os.system("xterm -e 'bash -c \"fft -i 3 AddedK AddedK_ifft; exit -f exec bash\"' ")
</code></pre>
<p><code>xterm</code> opens a new terminal</p>
<p><code>fft ...;</code> calls the function fft </p>
<p><code>exit -f</code> closes the terminal</p> | python|terminal|ipython|ipython-notebook | 0 |
5,912 | 12,771,659 | Django variable that is true when testing | <p>I want to have <strong>a single</strong> settings.py file that will behave differently when running the application</p>
<pre><code>./manage.py runserver
</code></pre>
<p>and when testing</p>
<pre><code>./manage.py test myapp
</code></pre>
<p>So, I can change the test db to sqlite for example, with something like... | <p>If you need this condition just for Django unit test purposes, the following line in the <code>settings.py</code> file should work:</p>
<pre><code>if 'test' in sys.argv:
DATABASES['default']['ENGINE'] = 'django.db.backends.sqlite3'
SOUTH_TESTS_MIGRATE = False # if you're using south
</code></pre>
<p>This a... | python|django|testing | 6 |
5,913 | 30,841,734 | How to find exact place for given value in python dictionary? | <p>I have one dictionary with key and value. Key is row name and values is the last seat number. I would like to find the row number based on the input value.</p>
<pre><code>seats_dict={'A':10,'B':'20':'C':30}
</code></pre>
<p><strong>Input:</strong></p>
<p>seat_num =16</p>
<p><strong>Output:</strong>
Should be <st... | <p>It seems to me that the <code>seats_dict</code> does not hold a full map for seats and sections, but only the end number of each section.</p>
<blockquote>
<p><code>seats_dict={'A':10,'B':'20':'C':30}</code></p>
<p>Input:</p>
<p>seat_num =16 ## Note: I don't see 16 in the dict</p>
<p>Output: Should be 'B'</p>
</block... | python|dictionary | 2 |
5,914 | 40,229,543 | return total on python | <p>im having trouble with modular python on returning the total and then printing it in the output. lend a hand?</p>
<pre><code>def main():
Monday = int(input("Enter the store sales for Monday: "))
Tuesday = int(input("Enter the store sales for Tuesday: "))
Wednesday = int(input("Enter the store sales for ... | <p>You have to pass the required information to your function. You have five input parameters. When you call the function, you have to give it five values.</p>
<pre><code>total = totalSales(Monday, Tuesday, Wednesday, Thursday, Friday)
</code></pre>
<p>... in your <strong>main</strong> should fix the problem.</p>
... | python | 0 |
5,915 | 8,610,172 | Capturing Scapy function output in Python | <p>I am trying to capture the output of a scapy function (traceroute) to a string in a python script. I understand I need to pipe this function to stdout (as you do with subproces.call() but unsure how to do this using scapy, is anybody able to provide any assistance? I am new to Python.</p>
<p>Relevent code below.</p... | <p>You can also call traceroute like this:</p>
<pre><code>trace, _ = traceroute("www.example.org", verbose=0)
# trace.get_trace() returns a rather impractical format, so we need
# to convert it. First, we only want the first trace available
hosts = trace.get_trace().values()[0]
# hosts will be in the format { 1: ("1.... | python|scapy | 2 |
5,916 | 8,922,118 | Use of M2M Table and relationship to get specific data in sqlalchemy | <p>I have Table</p>
<pre><code># File : MyRelations.py
ACC_ADD_TABLE = Table('acc_add_rel', METADATA,
Column('acc_id', ForeignKey('acc.id'),
nullable=False),
Column('add_id', ForeignKey('address.id'),
nullable=False),
PrimaryKeyConstraint('add_id', 'acc_id'),
)
# File : Addr... | <p>This works without requiring an import:</p>
<pre><code>default_address = relationship('Address',
secondary=ACC_ADD_TABLE,
primaryjoin="acc.c.id==acc_add_rel.c.acc_id",
secondaryjoin="and_(address.c.id==acc_add_rel.c.add_id, address.c.type=='defaul... | python|orm|sqlalchemy|relation | 4 |
5,917 | 52,036,396 | python; reading file path error | <p>i have a directory structure;</p>
<p><code>DIR1:
----outerPyFile.py
----DIR2:
--------innerPyFile.py
--------DIR3:
------------fileToRead.csv
</code></p>
<hr>
<p>I'm reading fileToRead.csv in <strong>innerPyFile</strong>: <code>pd.read_csv('DIR3/fileToRead.csv')</code>
<em>works fine if i run innerPyFile.py indiv... | <p>Try this:</p>
<p><strong>innerPyFile.py</strong></p>
<pre><code>import os
script_path = os.path.abspath(__file__) # i.e. /path/to/dir/foobar.py
script_dir = os.path.split(script_path)[0] #i.e. /path/to/dir/
rel_path = "DIR3/fileToRead.csv"
abs_file_path = os.path.join(script_dir, rel_path)
pd.read_csv(abs_file_pa... | python|path|absolute-path|os.path|pathlib | 1 |
5,918 | 51,659,259 | Add SQLAlchemy foreign key ID to another table based on the value | <p>I have two tables:</p>
<pre><code> class User(db.Model):
__tablename__ = 'user'
id = db.Column(INT, primary_key=True)
name = db.Column(db.String(16), nullable=False)
uid = db.Column(db.String(16), unique=True)
department_id = db.Column(INT, db.ForeignKey('department.id'),... | <p>There's no way around the fact that you'll have to get the department id, if you don't have it. The usual way:</p>
<pre><code>dep = Department.query.filter_by(name=name).one()
usr = User(..., department_id=dep.id)
</code></pre>
<p>You could also use a scalar subquery in place of the id, if you really want to avoid... | python|database|sqlalchemy|flask-sqlalchemy | 2 |
5,919 | 51,664,225 | PyCharm: regex string intentions for function arguments | <p>I have a function that takes a string argument that will be compiled into a regular expression, like so:</p>
<pre><code>class Pattern:
def __init__(self, pattern, **kwargs) -> None:
self.re = re.compile(pattern)
self.extras = dict(**kwargs)
... more methods ...
</code></pre>
<p>When I i... | <p>I found one way but it works not so smoothly as I expected.</p>
<p><code>File - Settings - Editor - Language Injections - Add</code>:</p>
<ul>
<li><code>Generic Python</code></li>
<li>ID: <code>RegExp</code></li>
<li>Places Patterns:</li>
</ul>
<p><code>+ pyLiteralExpression().and(pyMethodArgument("Pattern", 0, "... | python|regex|pycharm | 2 |
5,920 | 59,493,009 | Why is Flask ignoring Cache-Control? | <p>I am running a Flask application that includes an hourly process which updates a json variable in memory, and includes that variable in its response template. I've encountered the following unexpected behavior:</p>
<ol>
<li>Initial visits to the web page show the data that was instantiated when the server was initi... | <p>This right way to set cache-control for your case is:</p>
<pre><code>@app.after_request
def add_header(r):
r.headers["Cache-Control"] = "no-store max-age=0"
return r
</code></pre>
<p><code>no-store</code> will only prevent new resource from being cached, but it will not prevent the cache... | python|flask|cache-control | 0 |
5,921 | 56,093,625 | Pandas Mask on multiple Conditions | <p>In my dataframe I want to substitute every value below 1 and higher than 5 with nan. </p>
<p>This code works</p>
<pre><code>persDf = persDf.mask(persDf < 1000)
</code></pre>
<p>and I get every value as an nan but this one does not:</p>
<pre><code>persDf = persDf.mask((persDf < 1) and (persDf > 5))
</cod... | <p>Use the <code>|</code> operator, because a value cant be <code>< 1</code> AND <code>> 5</code>:</p>
<pre><code>persDf = persDf.mask((persDf < 1) | (persDf > 5))
</code></pre>
<p>Another method would be to use <code>np.where</code> and call that inside <code>pd.DataFrame</code>:</p>
<pre><code>pd.DataF... | python|pandas|nan|mask | 9 |
5,922 | 67,407,010 | How to Execute the script only under specific conditions using python | <p>I have been working on a script where performing a cleaning script for various columns.</p>
<p>I have to process those script if it undergoes an specific condition.</p>
<p><strong>For Eg.</strong></p>
<pre><code>if flag = 'Not feasible':
"Process the remaining steps"
</code></pre>
<p><strong>Input Data... | <p>In order to save you effort on amending large number of scripts for cleaning various columns, you do it in these steps:</p>
<ol>
<li>firstly extract those not for processing into another dataframe,</li>
<li>re-define <code>df</code> with the extracted rows for processing with a copy</li>
<li>run your cleaning script... | python|pandas | 1 |
5,923 | 13,246,764 | How to add a library to to my Google App Engine project? | <p>In response to <a href="http://code.google.com/p/googleappengine/issues/detail?can=2&start=0&num=100&q=&colspec=ID%20Type%20Component%20Status%20Stars%20Summary%20Language%20Priority%20Owner%20Log&groupby=&sort=&id=2749" rel="nofollow">this bug at Google</a> I am planning to replace the w... | <p>Typically you just copy the folder (e.g. /webob) to the root of your application directory, and as the version is not supported directly as yet don't include it in the app.yaml. </p> | python|google-app-engine | 2 |
5,924 | 16,831,413 | Django HTML-how to make the title of an object 'clickable' and direct to detail display page after clicking | <p>Sorry if this question is a bit general, I am learning web development in django and trying to figure out how the html functions & interacts.</p>
<p>Now,there is a simple page display.html,taking a set of objects(e.g book) and display the title of the book.</p>
<p>Normally,the title of each book would be a lin... | <p>The <em>usual</em> way I approach this in Django is to implement the <a href="https://docs.djangoproject.com/en/dev/ref/models/instances/#get-absolute-url" rel="nofollow"><code>get_absolute_url()</code></a> function for the particular model class, i.e. <code>Book</code> in your case.</p>
<p>Resulting template code ... | python|html|django | 1 |
5,925 | 16,705,343 | How to watch a file for modifications OS X and Python | <p>I'm working on a small game with a physical interface that requires me to write a character to the serial port with python every time a particular file in a directory is modified. The file in question is going to be modified probably every 20 - 30 seconds or so while the game is being played. </p>
<p><strike>What i... | <p>I've used all of the Python interfaces for notify/fsevents on OSX and at this point I think python-watchdog is the best. Pythonic design, simple to use. No wrestling with weird filesystem masks. It comes with a useful CLI app if you have a bash script too if you're feeling lazy.</p>
<p><a href="https://pypi.python.... | python|serial-port|arduino|game-maker | 1 |
5,926 | 54,443,986 | Using Python 2 and 3 but it cant find python 2 packages | <p>I have been using python 2.7.14 for awhile and have started using python 3. I installed python 3.7.2 and the py launcher so I know how to switch versions using</p>
<pre><code>py -2
py -3
</code></pre>
<p>When I run some of my python 2 files it cant find the modules, I get the the <code>No module named ___</code>... | <p>Due to many incompatibilities, the Python community agreed to have the two versions use distinct paths.</p>
<p>It seems like the module for Python2 is missing or mislocated on your computer. Try running <code>pip install pytube</code> to fix this.</p> | python|python-3.x|python-2.7 | 0 |
5,927 | 54,262,938 | Understanding how does a decorator really work | <p>I'm starting studying decorators and I already hit an obstacle. First here is my code.</p>
<pre><code> def deco (f):
def coucou():
print("this is function{}".format(f))
return f()
return coucou
@deco
def salut():
print("salut")
def hi():
return salut()
</code></pre>
<p>I will tr... | <p>The <code>f</code> in <code>coucou</code> is the <em>undecorated</em> (original) version of <code>salut</code>.</p> | python|python-3.x|decorator | 2 |
5,928 | 54,543,096 | How to obtain the index of the certain data type in a list? | <p>I have a list containing string, int, and float data.</p>
<p>For example:</p>
<pre><code>a = ['a', 'b', 1, 2, 3.5, 4.6]
</code></pre>
<p>I want to have the float data index such as <code>[4,5]</code> from the example above.</p>
<p>How can I do that?</p> | <p>Keep it simple:</p>
<pre><code>[i for i, x in enumerate(a) if isinstance(x, float)]
</code></pre> | python|python-3.x|list|indexing | 3 |
5,929 | 39,403,002 | Manually set package as installed in Python/pip | <p>I'm installing the <code>openbabel</code> package, and it can automatically generate the necessary Python libraries during compilation. This saves a good chunk of time, since installing from source via <code>pip</code> takes a few minutes, and that time can be rolled into the initial compilation.</p>
<p>I've listed... | <p>Create an empty .egg-info file in your site-packages directory. </p>
<p>For example, on my machine I did <code>touch /usr/lib64/python3.6/site-packages/GLWindow-1.8.0-py3.6.egg-info</code> to trick pip3 into thinking that I've installed <code>GLWindow</code>. </p> | python|pip | 0 |
5,930 | 55,437,306 | Break line in the text file into several columns for CSV | <p>I have a text file which something like this. I want to break the lines such that I can get individual columns for me to be able to put up a graph.</p>
<pre><code>node name | requested bytes | total execution time | accelerator execution time | cpu execution time
prefix/up23/conv2d_transpose 37.75MB (100.00%, 1... | <p>In your case you can do:</p>
<pre><code>with open('test.txt','r') as inp:
for f in inp.readlines():
print(f.split())
</code></pre>
<p>Which prints:</p>
<pre><code>['node', 'name', '|', 'requested', 'bytes', '|', 'total', 'execution', 'time', '|', 'accelerator', 'execution', 'time', '|', 'cpu', 'execut... | python|csv|readlines | 1 |
5,931 | 55,369,069 | "bool is not subscriptable" error when not indexing into a bool - Python | <p>I have the following function:</p>
<pre><code> def in_loop(i):
global loop_started
if i == '[':
loop_started = True
return [True, 'loop starting']
if loop_started:
if i == ']':
loop_started = False
return [True, 'loop ove... | <p>The problem is that when the characters like '+' or '-' are reached you are essentially returning boolean but are accessing <code>if in_loop(i)[1] == 'loop starting':</code> nonetheless.</p>
<p>You must return a consistent return type for the 2nd for-loop code to work. For ex, look at the comments below to your cod... | python|boolean | 2 |
5,932 | 52,565,404 | Keras not importing | <p>import tensorflow as tf
Traceback (most recent call last):</p>
<pre><code> File "<ipython-input-30-64156d691fe5>", line 1, in <module>
import tensorflow as tf
</code></pre>
<blockquote>
<p>File "E:\Users\Rajesh\Anaconda3\lib\site-packages\tensorflow__init__.py", line 22, in
from tensorflow... | <p>Is it keras or tensorflow ?</p>
<p>for making both work, uninstall both</p>
<pre><code>conda remove tensorflow
conda remove keras
</code></pre>
<p>Remove it from local env as well</p>
<pre><code>python3 -m pip uninstall tensorflow
python3 -m pip uninstall keras
</code></pre>
<p>From global env too</p>
<pre><co... | python|tensorflow | 0 |
5,933 | 52,896,183 | bin directory missing from anaconda envs in Windows 10 | <p>Encountered the following error after a recent <code>conda update --all</code> and anaconda update on windows 10. This happens when trying to use a python3.6 kernel in jupyter:</p>
<pre><code>['C:/Users/user/AppData/Local/Continuum/anaconda3/envs/sos/bin/python', '-m', 'ipykernel_launcher', '-f', 'C:\\Users\\user\\... | <p>The same thing happened to me on Win10 after a recent "conda update --all".
I removed the "/bin/" between the environment name and the "/python" in my "kernel.json" file to get it running again. </p> | python-3.x|windows-10|anaconda | 0 |
5,934 | 52,472,993 | Available options in the spark.read.option() | <p>When I read other people's python code, like, <code>spark.read.option("mergeSchema", "true")</code>, it seems that the coder has already known what the parameters to use. But for a starter, is there a place to look up those available parameters? I look up the apche documents and it shows parameter undocumented. </p>... | <p>Annoyingly, the documentation for the <code>option</code> method is in the docs for the <code>json</code> method. The docs on that method say the options are as follows (key -- value -- description):</p>
<ul>
<li><p>primitivesAsString -- true/false (default false) -- infers all primitive values as a string type</p>
... | python|python-3.x|apache-spark | 10 |
5,935 | 52,582,834 | Python Scrapy crawling takes too much time using xpath element selection with selenium in chrome | <h3>Problem:</h3>
<p>My problem is that I wrote few selenium Scrapy web spiders just for school task purposes and I wanted to crawl politely (DOWNLOAD_DELAY = 5 *per page), but I even don't have to, because it take too much time to crawl one page. <strong>For finding all elements in one page I wait even 30 seconds</str... | <p>You're probably using implicit_wait of 5 seconds. Because of that, when find_element doesn't find anything it waits for 5 seconds to give it a chance to appear...</p> | python|selenium|selenium-webdriver|xpath|scrapy | 1 |
5,936 | 47,977,653 | How can I get the custom nested data in Django? | <p>I have four model as bellow:</p>
<pre><code>class AModel(models.Model):
name = models.CharField(max_length=11)
class BModel(models.Model):
name = models.CharField(max_length=11)
a = models.ForeignKey(AModel, related_name="bs")
class CModel(models.Model):
name = models.CharField(max_length=11)
... | <p>It is not the actual code but pseudo code which will give you the idea.</p>
<pre><code>data_of_C_in_D = D.C_set # gives all value of C in D
Data_of_B_in_C = for i in data_of_C_in_D:
B.i_set #gives all value of C in B
</code></pre>
<p><strong>....</strong></p>
<p>Similarly you can go from D --... | python|django|algorithm | 0 |
5,937 | 47,812,785 | Remove empty partitions in Dask | <p>When loading data from CSV some CSVs cannot be loaded, resulting in an empty partition. I would like to remove all empty partitions, as some methods seem to not work well with empty partitions. I have tried to repartition, where (for example) <code>repartition(npartitions=10)</code> works, but a value greater than t... | <p>I've found that filtering a Dask dataframe, e.g., by date, often results in empty partitions. If you're having trouble using a dataframe with empty partitions, here's a function, based on MRocklin's guidance, to cull them:</p>
<pre><code>def cull_empty_partitions(df):
ll = list(df.map_partitions(len).compute())... | python|dask | 11 |
5,938 | 47,915,560 | simple math not adding up in python For loop | <p>Here's my code:</p>
<pre><code>x = 20
for i in range(1,7):
y = x/i
print(i) # These lines are just to show what
print(y) # the code is doing. I know it's not elegant.
print(i*y) # And is not my final solution
print('\n')
</code></pre>
<p>Here's my output:</p>
<pre><code>1
20.0
20.0
... | <p>In Python 2.x <code>/</code> performs integer division, leading to what you expect:</p>
<pre><code>$ python
Python 2.7.12 (default, Nov 20 2017, 18:23:56)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x=20
>>> [x/i for i in range(1,7)]
[... | python|python-3.x | 1 |
5,939 | 37,374,206 | Django-Channels - /admin/ portal not displaying new models created | <p>I have a implemented django-channels. Earlier I was using Apache to serve the django application, but now Channels uses Daphne(server) to serve my application. After adding two new models to the models.py file, I migrated the changes to database. I also registered the models in the admin.py file.</p>
<p>Even so, th... | <p>As mentioned by knbk, restarting the worker processes made it reflect the changes on my Admin portal. That was the only thing I hadn't tried. </p> | python|django|django-models|django-channels | 1 |
5,940 | 34,020,161 | python apscheduler - skipped: maximum number of running instances reached | <p>I am executing a function every second using Python apscheduler (version 3.0.1)</p>
<p><strong>code</strong>:</p>
<pre><code>scheduler = BackgroundScheduler()
scheduler.add_job(runsync, 'interval', seconds=1)
scheduler.start()
</code></pre>
<p>It's working fine most of the time but sometimes I get this warning:</... | <p>It means that the task is taking longer than one second and by default only one concurrent execution is allowed for a given job. I cannot tell you how to handle this without knowing what the task is about.</p> | python|cron|scheduler|apscheduler | 28 |
5,941 | 7,553,470 | problem with deserialization xml to objects - unwanted split by special chars | <p>I try to deserialize xml to objects, and i met a problem with encoding of various items in xml tree.</p>
<p><strong>XML example:</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<results>
<FlightTravel>
<QuantityOfPassengers>6</QuantityOfPassengers>
<Id>N... | <p>The problem is that the <code>data</code> method of your target class may be called more than once per element. This may happen if the feeder crosses a block boundary, for example. Looks like it can also happen when it hits a non-ASCII character. This is ancient legend. I can't find where this is documented. However... | python|xml|encoding|deserialization | 1 |
5,942 | 7,349,678 | Port a multi-version python application to Windows | <p>I have written a program in Python 3 that relies on another program in Python 2.7 for some core tasks. It works seamlessly on gnunux since most distribution have already 2.7 installed, I just have to require Python 3, and it's all good.</p>
<p>But now I want to port the bundle to Windows, and I don't know how to ma... | <p>How about using PyInstaller? Never used it myself but:</p>
<blockquote>
<p>PyInstaller is a program that converts (packages) Python programs into stand-alone executables, under Windows, Linux, and Mac OS X.</p>
</blockquote>
<p><a href="http://www.pyinstaller.org/" rel="nofollow">http://www.pyinstaller.org/</a><... | python|windows | 1 |
5,943 | 72,717,967 | Convert the str to list of tuple | <p>I call the oxidation states of A and B in AB compounds from list1 ('CaFe', 'BaSi', 'SeOs', 'BaGeO', 'CdCe'):</p>
<pre><code>dfA = pd.read_csv("oxi_state.csv",index_col=0, header =0)
A1 = []
A2 = []
final = []
for i in range(len(list1)):
A1 = dfA['OS'][list1[i][0]]
A2 = dfA['OS'][list1[i][1]]
A = (... | <p>you may have to loop through all of the items. Using</p>
<pre><code>list('2,3,4')
</code></pre>
<p>will return</p>
<pre><code>['2',',','3',',','4']
</code></pre>
<p>You can then go through and remove the commas and convert the str to int</p> | python|dataframe | 0 |
5,944 | 31,794,159 | Django mongodb auth with mongoengine error | <p>I try to extend basic user document from mongo and normally i would do it like this:</p>
<pre><code>from mongoengine.django.auth import User
class Account(User):
field1=something1
field2=something2
</code></pre>
<p>etc.</p>
<p>Somehow i just can't import django.auth from mongoengine.
It just says:
Impor... | <p>Problem solved.</p>
<p>Just for anyone that will be struggling with this.</p>
<p>django.auth or even mongoengine.django is not included in mongoengine 0.10 as it seems but it is in 0.9 so i downgraded it.</p>
<p>Also to get connection working properly i needed to update pymongo from 2.7.1 to 2.8.1 and now it all ... | python|django|mongodb|authentication|mongoengine | 0 |
5,945 | 38,936,287 | Returning False to Break out of a loop | <p>I am trying to break out of this loop. I have returned False and added a break if the character in the word is not on the hand, which is a dictionary with integer values per letter, based on Scrabble letter scores. This is part of a larger game but this particular function checks to see if the word I've entered is... | <p>There are several problems in your code, I have refactored it to make it clearer (and fixed it, that was the point :))</p>
<p><em>minor issues</em>:</p>
<ul>
<li>not optimal: first check if word is in word_list (you'd better use a <code>set</code> rather than a list, would be much faster), then test for available ... | python|loops|return | 0 |
5,946 | 52,786,362 | How to upgrade/install a package without pip | <p>I have pip2 and pip3 in my environment.</p>
<ul>
<li><p>pip 1.5.4 from /usr/lib/python2.7/dist-packages (python 2.7)</p></li>
<li><p>pip 18.0 from /usr/local/lib/python3.4/dist-packages/pip (python 3.4)</p></li>
<li><p>Python 2.7.6</p></li>
<li><p>Python 3.4.3</p></li>
</ul>
<p>This is what I'm getting when I try ... | <p>Try download <code>geopy</code> package from <a href="https://pypi.org/project/geopy/" rel="nofollow noreferrer">https://pypi.org/project/geopy/</a>
and run </p>
<pre><code>python setup.py install
</code></pre> | python|python-3.x|python-2.7|pip | 0 |
5,947 | 40,484,995 | Why doesn't Python write to the file? | <p>I have programmed a small password generator where you can save the password and its service on a file named "password.txt". Everytime I run the program, the file remains blank. When I delete the file and run the program again, the file "password.txt" is created but is still blank.</p>
<pre><code>import random
let... | <p>Just a small indentation error</p>
<pre><code>import random
letters = "1 2 3 4 5 6 7 8 9 Q W E R T Z U I O P A S D F G H J K L Y X C V B N M q w e r t z u i o p a s d f g h j k l y x c v b n m : ; , . 0".split()
def checkNumb(string):
for i in string:
x = i.isdigit()
if x == True:
... | python|python-3.x | 1 |
5,948 | 9,750,971 | Why doesn't Python raise an error on namespace collision? | <p>The following Python code executes normally without raising an exception:</p>
<pre><code>class Foo:
pass
class Foo:
pass
def bar():
pass
def bar():
pass
print(Foo.__module__ + Foo.__name__)
</code></pre>
<p>Yet clearly, there are multiple instances of <code>__main__.Foo</code> and <code>__main_... | <p>In Python everything is an object - instance of some type. E.g. <code>1</code> is an instance of type <code>int</code>, <code>def foo(): pass</code> creates object <code>foo</code> which is an instance of type <code>function</code> (same for classes - objects, created by <code>class</code> statement are instances o... | python|namespaces|python-3.x | 6 |
5,949 | 68,292,347 | Fastest way to modify columns value iterating on pandas dataframe | <p>Im using a csv file that has the lap number on a column, where each row contain data about that lap (last number is the lap), like this:
value1, value2, 1
value3, value4, 1
...
valueN, valuex, 99</p>
<p>I have a subset of this data, so i have a range from lapX to lapY, and i want to rearrange it, where lapX is 1 and... | <p>Based on the expected dataframe, it looks like you just want to re-number the laps incrementally, even if they are not consecutive laps. So 5, 6, 9 becomes 1, 2, 3.</p>
<p>For that, take the unique values of <code>Lap</code> and sort them. Then zip it with a <a href="https://docs.python.org/3/library/itertools.html#... | python|pandas|dataframe | 1 |
5,950 | 68,170,708 | Counting consecutive days of temperature data | <p>So I have some sea surface temperature anomaly data. These data have been filtered down so that these are the values that are below a certain threshold. However, I am trying to identify cold spells - that is, to isolate events that last longer than 5 consecutive days. A sample of my data is below (I've been working ... | <p>I think rather than filtering your original data you should try to do it the pandas way which in this case means obtain a series with true false values depending on your condition.</p>
<p>Your data seems not to include temperatures so here is my example:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd... | python|pandas|numpy|python-xarray | 2 |
5,951 | 26,258,905 | The view didn't return an HttpResponse object. It returned None instead | <p>I have the following simple view. Why is it resulting in this error?</p>
<p><code>The view auth_lifecycle.views.user_profile didn't return an HttpResponse object. It returned None instead.</code></p>
<pre><code>"""Renders web pages for the user-authentication-lifecycle project."""
from django.shortcuts ... | <p>Because the view must <em><strong>return</strong></em> <code>render</code>, not just call it. Change the last line to</p>
<pre><code>return render(request, 'auth_lifecycle/user_profile.html',
context_instance=RequestContext(request))
</code></pre> | python|django|django-views | 105 |
5,952 | 26,101,567 | Can't load module after pip install | <p>I am attempting to use a snapchat module in Python, but the problem I'm having is after I run</p>
<pre><code>pip install snapchat
</code></pre>
<p>... I copy the code to test, and get an error:</p>
<pre><code>Traceback (most recent call last):
File "./snapchat.py", line 2, in <module>
from snapchat import S... | <p>Unfortunately, the current behaviour is a bug, which has been reported at <a href="http://github.com/niothiel/snapchat-python/issues/2" rel="nofollow">http://github.com/niothiel/snapchat-python/issues/2</a>. Hopefully it will be fixed soon.</p> | python|pip | 1 |
5,953 | 1,648,537 | How to split a string by commas positioned outside of parenthesis? | <p>I got a string of such format: </p>
<pre><code>"Wilbur Smith (Billy, son of John), Eddie Murphy (John), Elvis Presley, Jane Doe (Jane Doe)"
</code></pre>
<p>so basicly it's list of actor's names (optionally followed by their role in parenthesis). The role itself can contain comma (actor's name can not, I strongly ... | <p>One way to do it is to use <code>findall</code> with a regex that greedily matches things that can go between separators. eg:</p>
<pre><code>>>> s = "Wilbur Smith (Billy, son of John), Eddie Murphy (John), Elvis Presley, Jane Doe (Jane Doe)"
>>> r = re.compile(r'(?:[^,(]|\([^)]*\))+')
>>>... | python|regex|split | 20 |
5,954 | 44,090,240 | How to display current time in realtime with flask and moment.js? | <p>I want to display the current time on a webpage with Flask.
At the moment I have this code which displays the current time but does not update unless the user explicitly refresh the page.</p>
<pre><code><div id="datetime">
<h2>{{ moment().format('HH:mm', refresh=True)}}</h2>
<h2>{{ m... | <p>The best way to write this would be going the JavaScript route as @tyteen4a03 said. Take a look at this question for help: <a href="https://stackoverflow.com/questions/28415178/how-do-you-show-the-current-time-on-a-web-page">How do you show the current time on a web page?</a> </p>
<p>Like you mentioned in the quest... | python|flask|momentjs | 0 |
5,955 | 33,029,129 | Make a numpy upper triangular matrix padded with Nan instead of zero | <p>I generate a matplotlib 3d surface plot. I only need to see the upper-triangular half of the matrix on the plot, as the other half is redundant. </p>
<p>np.triu() makes the redundant half of the matrix zeros, but I'd prefer if I can make them Nans, then those cells don't show up at all on the surface plot. </p>
... | <p>You can use <code>numpy.tril_indices()</code> to assign the <code>NaN</code> value to lower triangle, e.g.:</p>
<pre><code>>>> import numpy as np
>>> m = np.triu(np.arange(0, 12, dtype=np.float).reshape(4,3))
>>> m
array([[ 0., 1., 2.],
[ 0., 4., 5.],
[ 0., 0., 8.],
... | python|numpy|matplotlib | 24 |
5,956 | 13,872,827 | templategs "not a valid tag library", fails to load models | <p>While trying to load custom templtetags, I got error</p>
<pre><code>'myapp' is not a valid tag library: ImportError raised loading myapp.templatetags.myapp: No module named models
</code></pre>
<p>The problem is in templatetags/myapp.py is not been able to load model -> "myapp: No module named models". Why followi... | <p>Django is probably confused because of same name. Try to rename the file myapp.py to something else.
Also, You need to add the template tag app to the Installed apps and make sure the template tag has the <code>__init__.py</code> file. More information could be find <a href="https://docs.djangoproject.com/en/dev/how... | python|django | 1 |
5,957 | 34,818,228 | How to count number of repeated keys in several dictionaries? | <p>Let's say I have huge number of dictionaries (it could be 10'000 dictionaries). I would like to count number of each key in all dictionaries. I.e. if I have 3 dictionaries: </p>
<ul>
<li><code>{1: 'url1', 3: 'url2', 7: 'url3', 5: 'url4'}</code></li>
<li><code>{1: 'url1', 7: 'url3'}</code></li>
<li><code>{5: 'url4',... | <p>If you can accept slightly different output, this might work for you:</p>
<pre><code>from collections import Counter
dicts = [
{1: 'url1', 3: 'url2', 7: 'url3', 5: 'url4'},
{1: 'url1', 7: 'url3'},
{5: 'url4', 10: 'url5'},
]
result = Counter()
for d in dicts:
result.update(d.keys())
print dict(res... | python|dictionary|count|key | 2 |
5,958 | 34,826,133 | UDP broadcast and automatic server discovery in python, TCP socket unavailable | <p>I'm developing a reverse shell application in python, and right now I'm trying to implement an autodiscovery feature. It should work as follows:</p>
<ol>
<li>The server broadcasts the IP/port it listens for connections on, and waits for a client. If no client tries to connect in a few seconds, it broadcasts again (... | <p>Change <code>sckt.settimeout(None)</code> to <code>sock.settimout(None)</code> in the server code.</p>
<p>You want to have the <strong>accepted</strong> socket in blocking mode and not the <strong>accepting</strong> one.</p>
<p>This ensures that the <code>sckt.recv</code> waits for an incoming message from the cli... | python|sockets|networking|broadcast | 1 |
5,959 | 27,194,436 | How to access an item in a tuple when the tuple is inside a list? | <p>My data looks like this:</p>
<pre><code>>>> print nattach[:10]
[PPAttachment(sent=u'1', verb=u'is', noun1=u'chairman', prep=u'of', noun2=u'N.V.', attachment=u'N'), PPAttachment(sent=u'2', verb=u'named', noun1=u'director', prep=u'of', noun2=u'conglomerate', attachment=u'N'), PPAttachment(sent=u'3', verb=u'... | <p>Obviously <code>PPAttachment</code> is not a tuple, nor is it apparently a <code>namedtuple</code>. To get the third element, you'll probably want to access the value by name:</p>
<pre><code>[attach.noun1 for attach in nattach]
</code></pre> | python|list|tuples | 3 |
5,960 | 27,112,087 | Using SST framework, how do you click a link by css class or xpath? | <p>I am testing a website that has buttons that are not discernible by element or id. However, I am able to identify it by <code>xpath</code> or <code>css</code> class. How do you click on a button using one of those two attributes. I'm able to assert the button is there using <code>get_element_by_xpath;</code> however... | <p>If this answer is helpful to someone else. We we able to solve the issue with the following solutions.</p>
<pre><code>click_element(get_element_by_xpath('your xpath'), wait=True)
click_link(get_element_by_xpath('your xpath'), wait=True)
click_button(get_element_by_xpath('your xpath'), wait=True)
</code></pre>
<p><... | python|selenium|xpath|css-selectors | 1 |
5,961 | 23,127,660 | Python's equivalent Java's function wait(), notify(), synchronized | <p>I have to write a class in Python 2.7 and I have some problems.
I come from a java background and learned python quite recently</p>
<p>Here is what I would write if i have to do in java</p>
<pre><code>public class CommandSender extends Thread {
private boolean isTimeOut;
private boolean running;
privat... | <p>First of all, you should be aware of Python's <a href="https://wiki.python.org/moin/GlobalInterpreterLock" rel="nofollow">global interpreter lock</a> will not allow more than one thread to run Python code at the same time (though threads can run e.g. C code, for example using native code modules if they release the ... | python|multithreading|sync | 3 |
5,962 | 53,428 | What are some good Python ORM solutions? | <p>I'm evaluating and looking at using CherryPy for a project that's basically a JavaScript front-end from the client-side (browser) that talks to a Python web service on the back-end. So, I really need something fast and lightweight on the back-end that I can implement using Python that then speaks to the PostgreSQL D... | <p>If you're looking for lightweight and are already familiar with django-style declarative models, check out peewee:
<a href="https://github.com/coleifer/peewee">https://github.com/coleifer/peewee</a></p>
<p>Example:</p>
<pre><code>import datetime
from peewee import *
class Blog(Model):
name = CharField()
cla... | python|orm | 128 |
5,963 | 57,492,869 | Python: Trying to understand import io | <p>I currently try to understand the import <code>io</code>.</p>
<p>1) What I still didn't figure out what happens in the variable <code>buffer_2</code>. Why is that step necessary?</p>
<p>2) I couldn't figure out what the default <code>delimiter</code> is for <code>csv.writer</code>. Is it necessary to set this para... | <p>I don't know where this code comes from, so I may only guess. I'd say that the author needed a binary buffer - a buffer of <code>bytes</code> which acts like a binary file. This is the <code>io.BytesIO</code> instance. But <code>csv.writer()</code> works with text and expects a text file. The <code>io.StringIO</... | python | 3 |
5,964 | 33,522,706 | Interchanging between different scipy ode solvers | <p>I have a made a solver which can interchange between <code>scipy.integrate.ode</code> and <code>scipy.integrate.odeint</code>. Here is the code.</p>
<pre><code>def f(y,s,C,u,v):
y0 = y[0] # u
y1 = y[1] # u'
y2 = y[2] # v
y3 = y[3] # v'
dy = np.zeros_like(y)
dy[0] = y1
dy[2] = y3
C =... | <blockquote>
<p>Why is this occurring, and how I can I fix this?</p>
</blockquote>
<p>It is occurring because of an unfortunate API design decision made years ago. <code>odeint</code> and the <code>ode</code> class require different signatures for the system to be solved.</p>
<p>You can fix it by adding a wrapper ... | python|scipy | 6 |
5,965 | 46,899,376 | Create a file to import all modules that are contained within said file | <p>Is there a way I can import a list of modules that are contained within a single file just by using one statement without building some sort of method?</p>
<p>E.g. </p>
<p>large_import_file.py</p>
<pre><code>import x,y,z
</code></pre>
<p>main.py</p>
<pre><code>import large_import_file
x.do_this()
y.do_this()
z... | <p>If you want to bring in all of methods and imports for large_import_file to the current file's namespace, you'd just do.</p>
<pre><code>from large_import_file import *
</code></pre>
<p>As silent mentioned in his answer this is covered in
<a href="https://docs.python.org/3/tutorial/modules.html#more-on-modules" re... | python|import|module | 0 |
5,966 | 37,754,828 | What is the advantage of doing a Multi-GPU training in TensorFlow? | <p>In <a href="https://www.tensorflow.org/versions/r0.9/tutorials/deep_cnn/index.html" rel="nofollow">this TensorFlow tutorial</a>, you can use N number of GPUs to distribute N mini-batches (each containing M training samples) to each GPU and calculate the gradients concurrently.</p>
<p>Then you average the gradients ... | <p>The main purpose for multi-GPU learning is to enable you train on large data set in shorter time. It is not necessarily better with larger mini-batch, but at least you can finish learning in a more feasible time. </p>
<p>More precisely, those N mini-batches are not trained in a synchronized way if you use Asynchron... | optimization|gpu|tensorflow|multi-gpu | 2 |
5,967 | 57,218,012 | import nested json into pandas dataframe | <p><strong>JSON STR:</strong></p>
<pre><code>{
"PurchaseId": "Pur-001",
"Orders": [{
"id": "154",
"isOnline": false,
"Store_location": {
"Order-Date": "2019-06-04T07:35:00"
},
"Store_Network": [{
"Network_Domain": "Food_Processing"
}]
}],
"Sales": [{
"id": "1856",
"Sales... | <p>This is pretty long, but gets the job done. Hopefully someone answers with a better solution and less verbose. </p>
<pre><code>a = {
"PurchaseId": "Pur-001",
"Orders": [{
"id": "154",
"isOnline": False,
"Store_location": {
"Order-Date": "2019-06-04T07:35:00"
},
"Store_Network": [{
"N... | python|json|pandas | 1 |
5,968 | 43,449,372 | Remove char/str in one col as a condition for removing different str from another col - DF Pandas | <p>I have a Dataframe (let's call it <strong>my_df</strong>) with two columns. </p>
<p>initiating an example:</p>
<pre><code>my_df = pd.DataFrame({'first_col':['theTable','aChair','Lamp','intheCup','aBottle','theGlass'],'second_col':['itisBig','isSmall','itisBright','itisDark','isRed', 'itisWhite']})
</code></pre>
<... | <p>You were on the right track. Basically you just need to create a boolean filter about which rows you want to modify and then apply those modifications to only those rows.</p>
<pre><code>import pandas as pd
my_df = pd.DataFrame({'first_col':['theTable','aChair','Lamp','intheCup','aBottle','theGlass'],'second_col':[... | python|string|pandas|parsing|dataframe | 3 |
5,969 | 43,168,438 | How IDA will load DLL at constant memory segment at debug process? | <p>Each time TEST_DEBUG.EXE loaded at 0x04000000 base in IDA-Modules, but
TEST_DEBUG.DLL file loaded at any randoms base like 0x0C120000, 0x0C710000 , 0x0ABC0000
How i say to IDA debugger, load TEST_DEBUG.DLL every time at 0x0ABC0000 BASE ?</p>
<p>PS:
TEST_DEBUG.EXE load many DLLS, and one of them is TEST_DEBUG.D... | <p>NO ONE KNOW ?
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\x86_arm>EDITBIN /REBASE:BASE=0x61000000 mydll.dll</p> | python|debugging|reverse-engineering|ida | 0 |
5,970 | 48,836,596 | How does using '?' for object information work? | <p>I stumbled upon the following syntax in <a href="https://stackoverflow.com/questions/48746567/python-decorator-to-keep-signature-and-user-defined-attribute">Python decorator to keep signature and user defined attribute</a>:</p>
<pre><code>> def func():
... return "Hello World!"
...
> func?
Signature: func... | <p>The reasons using the <code>?</code> character in the pre-packaged Python IDLE shell fails, is because using the <code>?</code> is specific to <a href="https://ipython.org/ipython-doc/stable/interactive/reference.html#dynamic-object-information" rel="nofollow noreferrer"><em>IPython</em></a>:</p>
<blockquote>
<p>... | python|function|ipython | 2 |
5,971 | 48,784,564 | Python file does not recognise library installed in virtual environment | <p><strong>Explanation</strong></p>
<p>I had a previous post but I deleted it due to it being meandering and coming to the wrong conclusions.</p>
<p>The command I'm running below doesn't make sense on its own, but it's the file that is ultimately causing problems when other scripts I have run this file down the code ... | <p>I had a similar issue while working with my venv. However the error I received was "reportMissingModuleSource" and the code would break during runtime.</p>
<p>Here was my solution:
I've checked what version of python was running on global and ran the same code surprisingly it worked.
Figured it may be some... | python|python-3.x|pip|virtualenv | 0 |
5,972 | 66,862,626 | Unable to write to cloudwatch logs despite correct permissions | <p>Despite using correct permissions,
and trying to both print, and to log
to cloudwatch, I am unable to see any output.</p>
<p>Here is my lambda handler:</p>
<p>version 1</p>
<pre class="lang-py prettyprint-override"><code>def handler(event, context):
print('here 1')
for request in event['Records']:
# ... | <p>Without seeing the <code>serverless.yml</code> file, here is the best answer I can provide.</p>
<p>A quick way to verify if your function has the required permissions to log to cloudwatch.</p>
<ul>
<li>Go to the AWS Lambda console</li>
<li>Find your function</li>
<li>Select <code>Monitor</code></li>
</ul>
<p>If your... | python|aws-lambda|amazon-cloudwatch|serverless-framework | 0 |
5,973 | 67,180,958 | Python Pandas Series.to_sql() with index | <p>I'm using pandas great library but this operation seems not be working.
I just want to convert a simple pandas Series into a SQL table with <code>to_sql()</code> method.</p>
<pre><code>my_series = pd.read_json("some_path", typ="series")
my_series.to_sql(**{
"name": "atc... | <p>@Pibiche @eshirvana.
My series has an index. It's not a row number. It's a string: ["A", "A01", "A01A"].
I just wanted to use that index as a column named <code>code_atc</code> in my table.
Somehow I succeeded in doing it using the following workaround:</p>
<pre><code> serie = pd.rea... | python|sql|pandas|indexing | 0 |
5,974 | 48,264,085 | Is it possible to use python string format method with matplotlibs latex capabilities? | <p>With matplotlib, it is possible to use latex to label axes and plots. i.e.</p>
<pre><code>import matplotlib.pyplot as plt
data = pandas.DataFrame({'A': [1, 2, 3, 4, 5],
'B': [6, 7, 8, 9, 10],
'C': [11, 12, 13, 14,15]})
data['A/B'] = data['A']/data['B']
plt.plot(dat... | <p>You need three braces:</p>
<pre><code>plt.title(r'$\\frac{{{}}}{{{}}}$'.format(new_name1, new_name2))
</code></pre>
<p>The inner pair <code>{}</code> will be formatted using the given variables, and the outer <code>{{</code> and <code>}}</code> are <a href="https://docs.python.org/3.4/library/string.html#format-st... | python|matplotlib | 3 |
5,975 | 48,207,687 | Change default backend for matplotlib in Jupyter Ipython | <p>Right now the default backend for matplotlib is <code>'module://ipykernel.pylab.backend_inline'</code> </p>
<p>I want to switch that to <code>TkAGG</code>. I edited the <code>matplotlibrc</code> file in </p>
<p><code>~/anaconda2/lib/python2.7/site-packages/matplotlib/mpl-data/matplotlibrc/</code> </p>
<p>to add... | <p>The question is similar to <a href="https://stackoverflow.com/questions/21176731/automatically-run-matplotlib-inline-in-ipython-notebook">Automatically run %matplotlib inline in IPython Notebook</a>, except that you want to automatically use TK backend instead of inline backend. </p>
<p>So the idea is to locate you... | python|matplotlib|jupyter | 8 |
5,976 | 17,420,973 | sorted function takes 4 arguments? | <p>I've got some code which works. The problem is, the output numbers aren't in order. I looked at the sorted() function and believe that's what I need to use, but when I use it, it says that sorted can only take 4 arguments, I have 6-7.</p>
<pre><code>print "Random numbers are: "
for _ in xrange(10):
print rn(),rn... | <p>Put the numbers in a sequence, which is what <code>sorted()</code> works with:</p>
<pre><code>s = sorted([rn(), rn(), rn(), rn(), rn(), rn()])
</code></pre>
<p>then pick values from <code>s</code> when writing:</p>
<pre><code>f.write("%d,%d,%d,%d,%d,%d\n" % tuple(s))
</code></pre>
<p>Note that since <code>s</cod... | python | 3 |
5,977 | 69,927,478 | Exit with code 1 due to network error: ProtocolUnknownError | <pre><code>from flask import Flask, render_template, make_response
import pdfkit
app = Flask(__name__)
@app.route('/<Customer_Full_Name>/<Customer_adress>/<customerID_number>/<CurrentDate>/<Digital_Signature>')
def pdf_template(Customer_Full_Name, C... | <p>You should try to add this option:</p>
<pre><code>"enable-local-file-access": ""
</code></pre>
<p>to your options dict</p>
<p>Stephane</p> | flask|pdf-generation|aws-api-gateway|python-3.7 | 3 |
5,978 | 50,229,676 | How to shutdown celery node | <p>My celery log is showing this error:</p>
<pre><code>UserWarning: A node named celery@postr is already using this process mailbox!
Maybe you forgot to shutdown the other node or did not do so properly?
Or if you meant to start multiple nodes on the same host please make sure
you give each node a unique node name!
... | <p>Assuming you are on a unix, you can see the running processes with:</p>
<pre><code>ps aux | grep celery
</code></pre>
<p>This will show you as list of the running process ids, eg. 1111, 2222 and 3333. You can then shut down the celery processes by sending the <code>TERM</code> signal:</p>
<pre><code>kill -TERM 1111 ... | python|django|rabbitmq|celery|supervisord | 1 |
5,979 | 66,601,300 | Convert subprocess output to requests url | <p>I'm trying to get the hostname by subprocess:</p>
<pre><code> hostname = str(subprocess.run(['hostname'], stdout=subprocess.PIPE).stdout.decode('utf-8'))
</code></pre>
<p>and then, use the hostname to create a new GET resust via requsts:</p>
<pre><code>url=f"{server_url+str(host)}"
result = requests.get(ur... | <p>It's worked for me after using:</p>
<pre><code>url=f"{server_url+str(host).rstrip()}"
</code></pre> | python | 0 |
5,980 | 64,105,254 | Processing .txt file using wholeTextFiles & wanting to extract filename | <p>I am reading a .txt file using <code>wholeTextFiles()</code> in python spark. I know that after reading <code>wholeTextFiles()</code>, the resultant rdd will be of format (filepath, content). I have multiple files to read. I want to cut the file name from the filepath and save to a spark dataframe and a part of the ... | <p>Here a <strong>Scala version</strong> that is easily convertible to pyspark by your good self:</p>
<pre><code>import org.apache.spark.sql.functions._
import org.apache.spark.sql.types.StringType
val files = sc.wholeTextFiles("/FileStore/tables/*ZZ.txt",0)
val res1 = files.map(line => (line._1, line._... | python|pyspark|rdd | 0 |
5,981 | 61,853,401 | Retrieving information from wiki table using XPath in Python | <p>I'm trying to retrieve the name of the country out of the capital city wiki page, specifically from the main information table of the city, using xpath.</p>
<p>For example I want to retrieve "Spain" from <a href="https://en.wikipedia.org/wiki/Barcelona" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Barcel... | <p>The <code>tr</code> contains the <code>th</code> and the <code>td</code> as siblings so move the <code>th</code> check into a predicate:</p>
<pre><code>//table[@class='infobox geography vcard']//tr[@class = 'mergedtoprow'][th = 'Country']/td//a//text()
</code></pre>
<p>When I run</p>
<pre><code>import requests
im... | python-3.x|xpath | 0 |
5,982 | 60,437,391 | Why does python only shows the first half of the list in tkinter? | <p>I tried to write a program, which shows a list of integers in a table in a new tkinter window by pressing a button. Than I run it, only the first half of the list was showed, but no errors was indicated. I tried to double the body of the for-loop, but one at uneven number of integers of the list and two at a even we... | <p>Because when you pop off one of the numbers the list that <code>i</code> is iterating through gets shorter, that's why it terminates early. Also instead of using <code>x</code> as a separate variable to keep track of the iterations, you can use <code>enumerate</code>. Doing this, and not popping off the number, just... | python|list|tkinter | 1 |
5,983 | 60,626,683 | Display name along with the count in descending order in Django | <p>I have two models within my models.py file as described below:</p>
<pre><code>class Company(models.Model):
company_name = models.CharField(max_length=100)
def __str__(self):
return f"{self.company_name}"
Class Jobs(models.Model):
job_title = models.CharField(max_length=100)
job_company = models.Foreig... | <p>You can use Django's <code>Count</code> <a href="https://docs.djangoproject.com/en/3.0/topics/db/aggregation/" rel="nofollow noreferrer">aggregation</a> on a queryset to accomplish this. In your <code>Views.py</code> do something like this:</p>
<pre class="lang-py prettyprint-override"><code>from django.db.models i... | python|django|django-models|django-views|django-templates | 0 |
5,984 | 63,456,530 | How to solve a Formatting Error in Pandas Dataframe - Length issue or formatting? | <p>I am experiencing the error on the last line:</p>
<pre><code>ValueError: Must have equal len keys and value when setting with an iterable
</code></pre>
<p>I am not quite sure how to correct this error. I tried using different datetime formulas, but I think I may be mixing things up.</p>
<p>Here is a sample of my df:... | <pre><code>df.loc[df['Blank'] == 'ENDING MY', 'Marketing Year'] = df['Calendar Year'].astype(int) - 1
</code></pre>
<p>left out 'marketing year' as identifier. Fixed.</p> | python|pandas | 0 |
5,985 | 61,110,188 | How to display a GIF in jupyter notebook using google colab? | <p>I am using google colab and would like to embed a gif. Does anyone know how to do this? I am using the code below and it is not animating the gif in the notebook. I would like the notebook to be interactive so that one can see what the code animates without having to run it. </p>
<p>I found many ways to do so that ... | <p>For external gif, you can use Jupyter's display as @knoop's answer.</p>
<pre><code>from IPython.display import Image
Image(url='https://upload.wikimedia.org/wikipedia/commons/e/e3/Animhorse.gif')
</code></pre>
<p>But for a local file, you need to read the bytes and display it.</p>
<pre><code>!wget https://upload.... | python|matplotlib|jupyter-notebook|gif|google-colaboratory | 23 |
5,986 | 65,934,959 | Remove specific duplicates from df/list of lists | <p>I have the following pandas df (dummy df, original has around 50'000 rows).</p>
<pre><code>columns = ['question_id', 'answer', 'is_correct']
data = [['1','hello','1.0'],
['1','hello', '1.0'],
['1','hello', '1.0'],
['2', 'dog', '0.0'],
['2', 'cat', '1.0'],
['2', 'dog', '0.0'],
... | <p>Since you don't want any duplicates for the correct answers, use drop_duplicates() before selecting the 2 correct answers to remove any duplicates in the correct answers. 2 answers selected from these will be unique. Then somehow select (up to) 2 answers and similarly for the wrong answers.</p>
<p>After selecting co... | python|pandas | 1 |
5,987 | 69,150,260 | Geoviews FilledContours: keeping filled colours but removing countour lines | <p>I would like to plot something that resembles a kdeplot using <a href="https://geoviews.org/gallery/bokeh/filled_contours.html" rel="nofollow noreferrer">geoviews</a> without actually plotting the contour lines. The <a href="https://residentmario.github.io/geoplot/plot_references/plot_reference.html" rel="nofollow n... | <p>The argument you have to use is <code>line_color</code> and in your case you want to set it to <code>None</code>.</p>
<p>Applying the change to this line of code</p>
<pre><code>kde_plot = gv.FilledContours((Y, X, Z)).opts(cmap='PuBu', fill_alpha=0.5, line_color=None)
</code></pre>
<p>you will get this plot as a retu... | python|plot|kernel-density|geoviews | 1 |
5,988 | 68,882,724 | python pandas dataframe calculation | <p>I have a dataframe with two numeric columns <strong>item_cnt_day</strong> and <strong>item_price</strong>.<br />
I want to create a new column called <strong>rev</strong> in my dataframe which is calculated by (<strong>item_cnt_day * item_price</strong>). However, I want to add the condition <strong>rev = item_cnt_d... | <p>You can use loc accessor with boolean masking:</p>
<pre><code>df['rev']=0
df.loc[df['item_cnt_day'].ge(0),'rev']=df['item_cnt_day'].mul(df['item_price'])
</code></pre>
<p>OR</p>
<p>You can use <code>where()</code>:</p>
<pre><code>df['rev']=df['item_cnt_day'].mul(df['item_price']).where(df['item_cnt_day'].ge(0),0)
#d... | python-3.x|pandas|dataframe | 0 |
5,989 | 59,115,203 | I have a problem with classes and inputs in Python | <p>I just started learning about classes and am trying to build a calculator
that tells people how much they need to tip the waiter as a small project
but instead of entering myself the information i want that a user will do it himself so it will suit hes needs.
now i think i built it right, the computer accepts the i... | <p>The problem is with the indentation:</p>
<pre><code>class tip_calculator:
def __init__(self, bill, amount_of_diners, precent):
self.bill = bill
self.amount_of_diners = amount_of_diners
self.precent = precent
def return_answer(self):
print(
"The amount you need to... | python-3.x|class|oop | 2 |
5,990 | 59,750,422 | Crossbar.io close router when guest worker is down | <p>I am playing with crossbar.io for quite a while and I faced with some sync issue.
Problem:
I'm running my python backend as guest worker and wants to exit router when that python guest worker is down. I've set controller.options.shutdown for "shoutdown_on_worker_exit" but seems to have no effect if just python proce... | <p>I have run this worker in/with container. Following <a href="https://crossbar.io/docs/Container-Configuration/" rel="nofollow noreferrer">this</a> and <a href="https://github.com/crossbario/crossbar-examples/blob/master/sharedregs/python/.crossbar/config.json" rel="nofollow noreferrer">this</a></p> | python|wamp|autobahn|crossbar | 0 |
5,991 | 59,617,356 | Pandas column value arrangement | <p>I have a data about google play statistic and the Insatalls column values make me failed.It is like 10.000+ and I want to get rid of "+" for all values. What can I do ? Is there any pandas trick ? </p> | <p>Use this code to strip '+' on right ends</p>
<pre><code>df['Installs'] = df['Installs'].str.rstrip('+')
</code></pre> | python|pandas|data-science | 2 |
5,992 | 67,905,483 | To update the dataframe - what is difference between df.columns.get_loc vs df['colname']? | <p>iloc supports only integers and not names. So the following code is valid:</p>
<pre><code>for row in range(0, len(df)):
df.iloc[row, df.columns.get_loc('ColName')] = 3
</code></pre>
<p>Following code is invalid because it uses column name rather than integer:</p>
<pre><code>for row in range(0, len(df)):
df.i... | <p>Setting a value with .iloc is not a problem. It can become a problem when you make a copy with an iloc slice.</p>
<p>Are you aware of .loc? That is used for slicing with labels. Perhaps this is just an example code but you can very easily do:</p>
<pre><code>for row in df.index:
df.loc[row, 'ColName'] = 3
</code>... | python|pandas | 0 |
5,993 | 67,040,264 | Python - Interger / Variable issues. New programmer | <p>i am extremely new to the coding world. Started Python last week and had been following the website and video titled "Automate the boring stuff" and some other websites that ive been following along at the same time. I only made it to lesson five because i started writing up my own program to see what i le... | <p>It's coming from this line:</p>
<pre><code>age = int(input(age))
</code></pre>
<p>The parameter to <code>input</code> is the prompt it should print when reading from the keyboard. So, that's what prints the "26". It then waits for you to enter another number. That new number then gets stored in <code>ag... | python|variables|integer | 1 |
5,994 | 72,464,123 | Exclude tests files from setuptools find packages | <p>I'm trying to build a lib without the test files, as described here <a href="https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html" rel="nofollow noreferrer">https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html</a>. In the <code>pyproject.toml</code>, I got:</p>
<pre><code>[tool.setupt... | <p>It looks like you're using regex syntax. But this is a glob/wildmatch pattern, not regex.</p>
<p>Try this:</p>
<pre><code>[tool.setuptools.packages.find]
include = ['lib*']
exclude = ['lib*tests']
</code></pre> | python-3.x|setuptools|packaging|pyproject.toml | 1 |
5,995 | 56,310,244 | how to grab a csv url | <p>I have run into this problem before and still don't know what I can do, so I figured I would ask here. </p>
<p>Say I have a website like: <a href="https://www.macrotrends.net/stocks/charts/AAPL/apple/stock-price-history" rel="nofollow noreferrer">https://www.macrotrends.net/stocks/charts/AAPL/apple/stock-price-hist... | <p>It sounds like you are looking for the url for this specific case, and not a general solution for similar cases, if that is the case, I think this is the url you are looking for: </p>
<p><a href="http://download.macrotrends.net/assets/php/stock_data_export.php?t=AAPL" rel="nofollow noreferrer">http://download.macro... | python|r | 2 |
5,996 | 56,427,051 | Slot filling in RASA form with ambiguous user uput | <p>Playing around with RASA for the first time, I went into the case that I need to fill slots in a form where it is not possible to distinguish some of them based on the users input. Given the <a href="https://github.com/RasaHQ/rasa/tree/master/examples/formbot" rel="nofollow noreferrer">formbot-example</a> imagine a ... | <p>You have two options:</p>
<ul>
<li>Either use a common slot, e.g. <code>number</code> for both or </li>
<li>Use a common entity <code>number</code> and use a custom action to set the correct slot based on the last intent.</li>
</ul> | python|rasa-nlu|rasa-core | 0 |
5,997 | 55,172,499 | How to use OR or AND in fnmatch.filter? | <p>How do you apply OR or AND in the fnmatch filter?</p>
<pre><code>pattern = "*2006*|*2005*"
fnmatch.filter(list,pattern)
</code></pre> | <p><code>fnmatch</code> does not support that (in the general case), the syntax is quite limited - same as shell-style wildcards. You'll have to use <a href="https://docs.python.org/3/library/re.html#module-re" rel="nofollow noreferrer">regular expressions</a>, or call filter twice and union the results (for OR) or int... | python|python-3.x | 3 |
5,998 | 42,366,008 | Passing multiple arguments to SOAP webservice using SUDS | <p>There is a PHP SOAP webservice I want to use, that requires authentication. However username and password are not required to be passed in HTTP header but as SOAP arguments. I only have a PHP (working) example of running a query:</p>
<pre><code>$soap_client->getCurrentOrderCustomers(array("user" => 'root', "p... | <p>I think - the SOAP service WSDL tells us how to pass parameters to SOAP method.
I tried following following code Python and SOAP call using suds works fine for me.</p>
<p>Line number 4 - print client shows all the soap methods with parameters </p>
<pre><code>from suds.client import Client
url="http://www.dneonlin... | python|soap | 1 |
5,999 | 53,834,184 | Import and parse .data file | <p>there is a file I tried to import and safe as pandas df. At a first sight looks like it's already columns and rows ordered, but finally I had to do a bunch of stuff to create pandas df. Could you please check if there is much faster way to manage it? </p>
<p>url = '<a href="https://archive.ics.uci.edu/ml/machine-le... | <p>When you replaced <code>\t</code> to blankspace, you can use <code>read_csv</code> to read it. But you need to wrap up your text, because the first parameter in <code>read_csv</code> is <code>filepath_or_buffer</code> which needs object with a read() method (such as a file handle or StringIO). Then your question can... | python-3.x|pandas|python-requests | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.