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,200 | 48,369,984 | data-frame remove duplicate indexed rows | <p>I have a DataFrame (df)</p>
<pre><code> mark
snap_time
140000 8250.0
140000 8250.0
141000 8252.0
141000 8252.0
142000 8249.0
</code></pre>
<p>I'm trying to remove any rows with the same snap_time index</p>
<p>I've tried:</p>
<pre><code>df.drop_duplicates(subset=None, keep=... | <p>try explicitly telling which columns to check for matching duplicates</p>
<pre><code>df.drop_duplicates(subset=['snap_time', 'mark'], keep=False)
</code></pre> | python|pandas|dataframe | 0 |
3,201 | 48,049,922 | I need help visualising the font metrics in Wand | <p>Normally when I write a sentence in Wand using <code>draw.text</code> the letter spacing is taken care of, however I need to write one letter at a time to build frames for a text animation. The problem with this is that by moving the left offset (here is the <a href="http://docs.wand-py.org/en/0.4.4/wand/drawing.htm... | <p>I figured out that <code>y2</code> is height of the letters from the origin. It is the bearingY in documentation.</p>
<p><code>y1</code> is height below the origin.</p>
<p><a href="https://i.stack.imgur.com/aATDz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aATDz.png" alt="enter image descripti... | python|typography|wand | 0 |
3,202 | 48,312,420 | How to convert a list to dict? | <p>I have lists like this:</p>
<pre class="lang-none prettyprint-override"><code>['7801234567', 'Robert Post', '66 Hinton Road']
['7809876543', 'Farrukh Ahmed', '101 Edson Crest']
['7803214567', 'Md Toukir Imam', '34 Sherwood Park Avenue']
['7807890123', 'Elham Ahmadi', '8 Devon Place']
['7808907654', 'Rong Feng', '32... | <p>Use <code>zip</code> to associate the keys with their values by index</p>
<pre><code>keys = ('tel', 'name', 'address')
values = ['7801234567', 'Robert Post', '66 Hinton Road']
d = dict(zip(keys, values))
# {'tel': '7801234567', 'name': 'Robert Post', 'address': '66 Hinton Road'}
</code></pre>
<p>Edit: </p>
<p>Ob... | python|python-3.x|dictionary | 2 |
3,203 | 51,488,941 | Python: Why does interpreter search for variable assignment in a function below the line being executed? | <p><strong>Context</strong></p>
<p>I am relatively new to python / computer programming and trying to wrap my head around some basic concepts by playing around with them.</p>
<p>In my understanding, python is an interpreted language i.e. it evaluates the line of code as it is being executed.</p>
<p><strong>Question<... | <blockquote>
<p>In my understanding, python is an interpreted language i.e. it evaluates the line of code as it is being executed.</p>
</blockquote>
<p>No.<sup>1</sup> Python compiles a module at a time. All function bodies are compiled to bytecode, and the top-level module code is compiled to bytecode. That's what ... | python|variables|global|local|interpreter | 2 |
3,204 | 73,804,813 | Python installed in multiple paths, is this bad? | <p>I am newish to python and Mac and may have messed up when installing python. Will this cause future errors?</p>
<p>Also why are some paths listed multiple times?</p>
<pre><code>~ % where python3
/opt/homebrew/bin/python3
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
/opt/homebrew/bin/python3
/usr/loc... | <p>First, what are these?</p>
<ol>
<li><p>/opt/homebrew/bin/python3 — this was installed by Homebrew.</p>
</li>
<li><p>/Library/Frameworks/<em>whatever</em> — This was <em>probably</em>
installed by an installation package from the Python website.</p>
</li>
<li><p>/usr/bin/python3 — this one probably came with Xcode.</... | python|macos|homebrew | 2 |
3,205 | 64,427,360 | Why all these decimals with sympy.solve? | <p>I have this system to solve:</p>
<p>(<em>y</em>-1) <em>x</em> = 0<br />
(<em>x</em>-1) (1/2-<em>x</em>) <em>y</em> = 0</p>
<p>I want to use Sympy's <code>solve</code>, but it gives me:</p>
<pre><code>[(0.0, 0.0), (0.500000000000000, 1.00000000000000), (1.00000000000000, 1.00000000000000)]
</code></pre>
<p>Why all th... | <p>Try to modify the expression below</p>
<pre><code>...
Y = -y*(1-x)*((1-x-x)/2
...
</code></pre>
<p>and wonder why the outcome is now <em>what you want</em>.</p> | python|decimal|sympy|symbols | 0 |
3,206 | 64,272,117 | astropy.io.fits: How to append new cards to a header of a fits file? | <p>I'm trying to insert/append new cards to an existing header (the PRIMARY header) of a FITS file. With the code I have below, I can see on the terminal that I am 'successful' in performing this action. But when I open the FITS file in DS9 and check the header info, my new card is not present. So my action is not bein... | <p>Indeed with your code you're not saving the updated file. You must use the update mode and call <code>.flush()</code>:</p>
<pre><code>from astropy.io import fits
with fits.open('my.fits', mode='update') as hdul:
hdr = hdul[0].header
hdr.append(('NEWCARD', 'value', 'A comment.'), end=True)
hdul.flush() ... | python|header|astropy|fits | 1 |
3,207 | 64,509,621 | sum of as many pairwise distinct positive integers | <p>Task. The goal of this problem is to represent a given positive integer as a sum of as many pairwise distinct positive integers as possible. That is, to find the maximum such that can be written as 1 + 2 + · · · + where 1, . . . , are positive integers and ̸= for a</p>
<p>Sample 1.</p>
<p>Input:</p>
<p>6</p>
... | <p>Using a greedy algorithm which selects the smallest available number is a good approach you chose.</p>
<pre><code>n = 17 # The input
x = 0 # The running total
for k in range(1, n): # The maximum number is bounded above by n
x += k
if n - x < k + 1: # The next number is too big
print(k) # Print k
... | python|arrays|list|sum|greedy | 0 |
3,208 | 71,955,662 | concatenate specific columns on Pandas dataframes | <p>I've been trying to add a multiples sets of data but can't seem to make it work.</p>
<p>Say, I have three 3x9 dataframes</p>
<p>dfA:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: left;"></th>
<th style="text-align: left;">A: Wave height</th>
<th style="text-align: l... | <p>You can't have duplicated index values using pd.concat</p>
<p>But you can try with merge and parameter 'outer' :</p>
<pre><code>pd.merge(dfA, dfB, on="name_of_colum_index", how="outer")
</code></pre>
<p>Set index name before.</p> | python|pandas|dataframe | 0 |
3,209 | 60,444,979 | Django how to compute the Percentage using annotate? | <p>I want to compute the total average per grading categories and multiply it by given number using annotate</p>
<p>this is my views.py </p>
<pre><code>from django.db.models import F
gradepercategory = studentsEnrolledSubjectsGrade.objects.filter(grading_Period = period).filter(Subjects = subject).filter\
(Gr... | <p>You can do this using <a href="https://docs.djangoproject.com/en/3.0/ref/models/expressions/#f-expressions" rel="nofollow noreferrer">F Expresisons</a></p>
<p>From the Docs:</p>
<pre><code>Reporter.objects.all().update(stories_filed=F('stories_filed') + 1)
</code></pre>
<p>So your example would be something like:... | python|django | 0 |
3,210 | 59,399,903 | How to get the list of available encode/decode codecs? | <p>The documentation for <code>open</code> states:</p>
<pre><code>encoding is the name of the encoding used to decode or encode the
file. This should only be used in text mode. The default encoding is
platform dependent, but any encoding supported by Python can be
passed. See the codecs module for the list of suppor... | <pre><code>help(codecs)
</code></pre>
<p>list the help for encode() as well.</p>
<p>The following docs page also lists out the supported encodings.
<a href="https://docs.python.org/3/library/codecs.html" rel="nofollow noreferrer">https://docs.python.org/3/library/codecs.html</a></p> | python | 1 |
3,211 | 59,149,754 | pandas multindex choose/drop rows based on second column | <p>Copying the example from this <a href="https://stackoverflow.com/questions/53927460/select-rows-in-pandas-multiindex-dataframe">question</a>, consider the following dataframe:</p>
<pre class="lang-py prettyprint-override"><code>mux = pd.MultiIndex.from_arrays([
list('aaaabbbbbccddddd'),
list('tuvwtuvwtuvwtu... | <p>use <code>head(2)</code> with groupby</p>
<pre><code>df.groupby('one').head(2)
Out[246]:
col
one two
a t 0
u 1
b t 4
u 5
c u 9
v 10
d w 11
t 12
</code></pre> | python|pandas|dataframe | 3 |
3,212 | 63,036,359 | Python: how can i replace the header by the first row of a web scraped table | <pre><code>import pandas as pd
url = "http://hkureis.versitech.hku.hk/data.php"
table = pd.read_html(url)[0]
print(table)
table.to_excel("Reis.xlsx")
</code></pre>
<p>How can I get rid of the first row and the first column. Replacing them by the next row and column in python?</p>
<p><a href="https:/... | <p>Try it with the .to_string(index=False, header=False) method:</p>
<pre class="lang-py prettyprint-override"><code>print(table.to_string(index=False, header=False))
</code></pre>
<p>Result:</p>
<p><a href="https://i.stack.imgur.com/7SqN6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7SqN6.png" al... | python|html|excel | 0 |
3,213 | 49,078,880 | Does pre-processing run in parallel via dask? | <p>I am loading many netCDF4 files like so:</p>
<pre><code>theDataset=xr.open_mfdataset(input_files,
concat_dim='time',
preprocess=preprocess_dims,
chunks={'time':chunk_size})
</code></pre>
<p>The preprocessing function subsets the... | <p>According to the docstring for <code>open_mfdataset</code> it should do if you pass <code>parallel=True</code>.</p>
<p><a href="https://github.com/pydata/xarray/issues/1981" rel="nofollow noreferrer">Here</a> is the github pull request where parallel opening and preprocessing in <code>open_mfdataset</code> was impl... | python-xarray | 0 |
3,214 | 65,891,595 | Create a list from a char and remove an element in Python? | <p>I have written the following function that gets a char, creates a list by a specified length of a char from it, and finally removes an element from the newly created list.</p>
<pre><code>def create_list_from_char(char, remove_elem):
n = int(len(remove_elem))
my_list = [char[i:i+n] for i in ra... | <p>use this:</p>
<pre><code>def create_list_from_char(char, remove_elem):
n = int(len(remove_elem))
my_list = [char[i:i+n] for i in range(0, len(char), n)]
print("Created list is: ", my_list)
print(remove_elem in my_list)
my_list.remove(re... | python|list | 1 |
3,215 | 50,542,765 | screen looks like pushed toward left and up when rotating it in OpenCV | <p>Window have empty space in right and bottom about 3cm. It looks like the screen had pushed away. I rotate my screen to reference <a href="https://www.tutorialkart.com/opencv/python/opencv-python-rotate-image/" rel="nofollow noreferrer">this page</a>.</p>
<p>Here is picture</p>
<p><img src="https://i.stack.imgur.co... | <p>The problem lies in the line <code>img = cv2.warpAffine(img, M, (h, w))</code> where <code>h</code> and <code>w</code> must be interchanged. </p>
<p>The function <code>cv2.warpAffine()</code> creates a new image with the rotation matrix <code>M</code>. But since <code>w</code> and <code>h</code> have been interchan... | python|opencv | 2 |
3,216 | 61,376,931 | How do I call an entry on tkinter? | <p>I'm new to Python and I'm struggling to figure out what's wrong with my code. </p>
<pre><code>import tkinter as tk
r = tk.Tk()
r.title('PROJECT')
def file_entry():
global ent
tk.Label(r, text = "ENTRY").grid(row = 2)
ent = tk.Entry(r).grid(row = 2, column = 1)
b_ent = tk.Button(r, text="OK", width ... | <p>It appears that chaining the grid to the entry widget is not acceptable. </p>
<p>If you put it on a separate line, the <code>ent</code> variable get properly assigned and get the inputted value as opposed to not working and being assigned None.</p>
<p>Try this:</p>
<pre class="lang-py prettyprint-override"><code>... | python|tkinter | 0 |
3,217 | 61,535,029 | Why is Index being graphed and not country? Using Matplotlib Horizontal Bar Graph | <p>I'm pretty new to all of this. I've been looking online how to change my y-ticks to represent a column that I wanted to initially graph.</p>
<p>Anyway, I have a dataframe that I created by using a SQL command...it's called eastasia_pac. The columns are <code>index</code> (although apparently it's not really a colum... | <p>By default, <code>matplotlib</code> plots according the index of a specified <code>dataframe</code>. You can solve this by either setting the index of the data or by overwriting the values.</p>
<p><strong>Overwrite method:</strong></p>
<pre><code># I'm assuming this is what's creating your plot
eastasia_pac.plot.b... | python|pandas|matplotlib | 0 |
3,218 | 54,163,902 | Adding value to Maximum Value in a dataframe column | <p>I have a dataframe:</p>
<pre><code>Region | A | B | C | Total
===============================================================
Africa | 100.10 | 20.135 | 10.02 | 130.255
---------------------------------------------------------------
Europe | 200.35 | 5... | <p>Using <code>mul</code> with bool mask</p>
<pre><code>df=df.set_index('Region')
df+=(df==df.max()).mul(df.loc['Unknown'])
df=df.drop('Unknown',axis=0)
df.Total=df.iloc[:,:-1].sum(1)
df
A B C Total
Region
Africa 100.1 20.135 10.02 130.255
Europe 20... | python|pandas | 2 |
3,219 | 54,972,425 | In Google Colab, I created a file with Pickle Library but I can't find it in Google Drive | <pre><code>#Saving the best model with Pickle (Neural %83.43)
import pickle
pickle.dump(classifier, open("NeuralNews", 'wb'))
loading = pickle.load(open("NeuralNews", 'rb'))
predictionPickleNeural = loading.predict(testResult2)
predictionPickleNeural = (predictionPickleNeural > 0.5)
acScorePickleNeural =
accurac... | <p>Its inside the current directory of Google Cloud VM. You can try:</p>
<pre><code>import os
os.listdir('.')
</code></pre>
<p>If you get some output like,</p>
<pre><code>['.config', 'sample_data']
</code></pre>
<p>then you can even get listing by issuing the command like below,</p>
<pre><code>!ls sample_data
</co... | python|deep-learning|google-colaboratory | 1 |
3,220 | 41,061,048 | Tensorflow: Building graph and label files form checkpoint file | <p>I want to build the graph and labels file from <strong>inception-resnet-v2.ckpt</strong> file. I have already downloaded the check point file form
<code>wget http://download.tensorflow.org/models/inception_resnet_v2_2016_08_30.tar.gz</code>.</p>
<p>I want to replace the <strong>inception5h</strong> model in <strong... | <p>Not sure, what the label file is, but to convert a checkpoint into a .pb file (which is binary protobuf), you have to <a href="https://www.tensorflow.org/versions/r0.10/how_tos/tool_developers/index.html#freezing" rel="nofollow noreferrer">freeze the graph</a>. Here is a script I use for it:</p>
<pre><code>#!/bin/b... | android|tensorflow|deep-learning | 1 |
3,221 | 38,073,629 | Show fewer pages in Django pagination | <p>I am working on a Django application and on one of the pages we use pagination. I have around 200 pages and if I am somewhere in the middle then it has links from page 1 - 4, displays the 4 pages behind the page I am on, 3 after the page I am on and the last 4 pages. Looking like <a href="http://i.stack.imgur.com/7U... | <p>You seem to be using the <a href="https://pypi.python.org/pypi/django-pagination" rel="nofollow">django-pagination</a> app. It has a setting for the number of items left and right of the current page</p>
<ul>
<li><code>PAGINATION_DEFAULT_WINDOW</code> The number of items to the left and to the right of the current ... | python|django|pagination | 1 |
3,222 | 51,765,581 | Save a raw html form django | <p>I am trying to save some user data from a raw html form in django.<br>
My code looks like this: </p>
<pre><code># This is the view -->
if request.method == 'POST':
name = request.POST['name']
email = request.POST['email']
age = request.POST['age']
password = request.POST['password']
# Some v... | <p>I recommend you to follow <a href="https://docs.djangoproject.com/fr/2.0/topics/forms/modelforms/" rel="nofollow noreferrer">Django's official documentation - model forms</a></p> | python|django|forms | 1 |
3,223 | 40,584,140 | maximum recursion depth exceeded when using a class descriptor with get and set | <p>I have been playing with my code and I ended up with this:</p>
<pre><code>class TestProperty:
def __init__(self,func):
self.func = func
def __set__(self,instance,value):
setattr(instance,self.func.__name__,value)
def __get__(self,instance,cls):
if instance is None:
r... | <p>Don't use <code>getattr()</code> and <code>setattr()</code>; you are triggering the descriptor again there! The descriptor handles all access to the <code>TestProp</code> name, using <code>setattr()</code> and <code>getattr()</code> just goes through the same path as <code>p.TestProp</code> would.</p>
<p>Set the at... | python | 2 |
3,224 | 27,224,063 | Read innermost value in multiple tuple in python | <p>I want to <strong>read</strong> in the <strong>innermost value in tuple</strong>.</p>
<pre><code>Input - (((False, 2), 2), 2)
Output - False
</code></pre>
<p>I want to <strong>read</strong> only <strong>False</strong> value. The <strong>size of tuple</strong> goes vary but I want to read only the most <strong>inne... | <p>You can flatten the tuple using a generator function and return the first item:</p>
<pre><code>from collections import Iterable
def solve(seq):
for x in seq:
if isinstance(x, Iterable) and not isinstance(x, basestring):
for y in solve(x):
yield y
else:
yi... | python|tuples | 1 |
3,225 | 70,366,271 | How build two graphs in one figure, module Matplotlib | <p>How to build two graphs in one figure from the equations below</p>
<ol>
<li>y = (x+2)^2</li>
<li>y = sin(x/2)^2</li>
</ol>
<p>There is my code:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
from math import sin
y = lambda x: sin(x / 2) ** 2
y1 = lambda x: (x + 2) ** 2
fig = plt.subplots()
x = ... | <p>Use <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplots.html" rel="nofollow noreferrer"><code>supplots</code></a> to make 2 Axes in your Figure:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
fig, (ax1,ax2) = plt.subplots(nrows=2)
x = np.linspace(-3, 3, 100)
ax1.plot(x... | python|python-3.x|numpy | 0 |
3,226 | 45,777,023 | Pandas plot multiple series but only showing legend for one series | <p>I'm using an ipython notebook (python 2) and am plotting both a barchart and a line plot on the same plot. There are two series (NPS and Count Ratings). However, when I try to display the legend, it only shows a legend for the second series. </p>
<p>Below is my code: </p>
<pre><code>ax=nps_funding_month[35:][nps_... | <p>The following code </p>
<pre><code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df=pd.DataFrame({"x" : np.arange(5),
"a" : np.exp(np.linspace(3,5,5)),
"b" : np.exp(-np.linspace(-1,0.5,5)**2)})
ax=df.plot(x="x", y="a", kind='line',color='green',label='NPS... | python|pandas|matplotlib|plot | 2 |
3,227 | 45,881,057 | Extract first 3 words from string | <p>I am looking for a script code to search for the first 3 words of a string.</p>
<p>Example : </p>
<pre><code>words = 'I am confused looking for 3 words from the front'
</code></pre>
<p>Expected results:</p>
<pre><code>'I am confused'
</code></pre> | <p>You can split the string into a list using the .<code>split()</code> method. Once you've done this you can extract the first 3 words from the sentence using a list slice (<code>[:3]</code>). Finally you'll want to join the result back together into a new string using <code>.join()</code>:</p>
<pre><code>words = 'I ... | python|string|python-2.7|split|python-2.x | 25 |
3,228 | 45,757,363 | reaching python with R | <p>I am trying to install tensorflow in <code>Rstudio</code>, when I run <code>install_tensorflow()</code>, I get</p>
<pre><code>Error: Prerequisites for installing TensorFlow not available.
Execute the following at a terminal to install the prerequisites:
$ sudo pip install --upgrade virtualenv
</code></pre>
<p>Bu... | <p>try:</p>
<pre><code>install_tensorflow("virtualenv", envname="myenv")
</code></pre>
<p>this will create a new python virtualenv environment.</p> | python|r|tensorflow|rstudio | 0 |
3,229 | 24,560,203 | Don't understand error message on SQLalchemy | <p>I've got three tables: users, funds, and fund types. Each fund has a fund type, each user has a list of funds, and each user can also have a list of fund types that they have created.</p>
<p>Schema:</p>
<pre><code>class Fund(Base):
__tablename__ = 'fds_funds'
fds_fund_id = Column(Integer, primary_key=True)... | <p>I'm not really sure what fixed it, but I did some rearranging and messing with the references. For posterity, this works:</p>
<pre><code>user_funds = Table('usf_user_funds', Base.metadata,
Column('usf_usr_user_id', Integer, ForeignKey('usr_users.usr_user_id')),
Column('usf_fds_fund_id', Integer, ForeignKey(... | python|sqlalchemy|pyramid | 0 |
3,230 | 31,190,367 | django deploying separate web & api endpoints on heroku | <p>I have a web application with an associated API and database. </p>
<p>I'd like to use the same Django models in the API, but have it served separately by different processes so I can scale it independently. </p>
<p>I also don't need the API to serve static assets, or any of the other views. </p>
<p>The complicati... | <p>As Daniel said you could just use two settings files, with a shared base. If you want to serve a subset of the urls you should just also create separate url definitions in the <code>ROOT_URLCONF</code> setting. </p>
<p>So your project structure would be something like this:</p>
<pre><code>project/
project/
... | python|django|heroku|procfile | 2 |
3,231 | 39,962,977 | How to import CSV file to django models | <p>I have Django models like this</p>
<pre><code>class Revo(models.Model):
SuiteName = models.CharField(max_length=255)
Test_Case = models.CharField(max_length=255)
FileName = models.CharField(max_length=255)
Total_Action = models.CharField(max_length=255)
Pass = models.CharField(max_len... | <p>You can use the built in <a href="https://docs.python.org/3/library/csv.html" rel="nofollow">csv module</a> to turn your csv file into a <a href="https://docs.python.org/3/library/csv.html#csv.DictReader" rel="nofollow">dict like object</a>:</p>
<pre><code>import csv
with open('import.csv') as csvfile:
reader ... | python|django|csv|graph | 3 |
3,232 | 40,180,737 | How to get data from pickle files into a pandas dataframe | <p>I'm working on a social media sentiment analysis for a class. I have gotten all of the tweets about the Kentucky Derby for a 2 month period saved into pkl files.</p>
<p>My question is: how do I get all of these pickle dump files loaded into a dataframe?</p>
<p>Here is my code:</p>
<pre><code>import sklearn as sk... | <p>You can use </p>
<ol>
<li><code>pd.read_pickle(filename)</code></li>
<li>add it to a list</li>
<li>then <code>pd.concat(thelist)</code></li>
</ol> | python|pandas|twitter|pickle | 10 |
3,233 | 29,257,995 | Attach label information when averaging predictions across users | <p>I have 3 datasets that contains predictions, usernames and labels, respectively. Using the code below I average the predictions across users (based on help from Jaime and ali_m from <a href="https://stackoverflow.com/questions/29243982/average-using-grouping-value-in-another-vector-numpy-python">Average using groupi... | <p>You can do this by passing <code>return_index=True</code> to <code>np.unique</code>. From <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html" rel="nofollow noreferrer">the docs</a>:</p>
<blockquote>
<p>return_index : bool, optional</p>
<p>If True, also return the indices of <em>ar</em> th... | python|numpy | 1 |
3,234 | 8,829,874 | Unexplained paramiko error | <p>When using ssh with paramiko to execute the command on remote system. When executing it gives error</p>
<pre><code>def execute(self,command):
to_exec = self.transport.open_session()
to_exec.exec_command(command)
stdout.write("\r%s" % "Executed")
stdout.flush()
get_co... | <p>You haven't got a <code>Transport</code> stream object. Maybe try creating one with <code>self.transport = self.get_transport()</code> like this:</p>
<pre><code>def execute(self,command):
self.transport = self.get_transport()
to_exec = self.transport.open_session()
to_exec.exec_command(comma... | python | 1 |
3,235 | 52,282,037 | Issue installing Virtualenvwrapper on Ubuntu 18.04? | <p>Fresh Ubuntu 18.04 install. Following <a href="https://virtualenvwrapper.readthedocs.io/en/latest/" rel="nofollow noreferrer">these instructions</a> here are the commands I've run so far.</p>
<pre><code>sudo apt update
sudo apt upgrade
python3 -V
sudo apt install python3-pip
sudo apt install build-essential libssl... | <p>on Ubuntu 18.04 I had to add this to my .bash_profile</p>
<pre><code># virtualenv and virtualenvwrapper
export WORKON_HOME=$HOME/.virtualenv
export VIRTUALENVWRAPPER_LOG_DIR="$WORKON_HOME"
export VIRTUALENVWRAPPER_HOOK_DIR="$WORKON_HOME"
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
source ~/.local/bin/virtualen... | python-3.6|ubuntu-18.04|virtualenvwrapper | 2 |
3,236 | 52,424,068 | If I have a starting and an ending IP, how can I find the subnet? | <p>I need to block some IPs from some countries but I'm only given the starting IP and the ending IP like this:</p>
<pre><code>11.22.33.44 - 11.22.35.200
</code></pre>
<p>I'd like to calculate the subnet to have it like this:</p>
<pre><code>(not accurate)
11.22.33.44/14
</code></pre>
<p>How can I determine the sub... | <p>I haven't spent much time networking recently, but here's how I think you can do this most efficiently.</p>
<p>First of all, it's important to recognize that not all IP ranges can be represented as a single subnet. Let's take a look at a common subnet like</p>
<pre class="lang-none prettyprint-override"><code>192.... | python|routing|ip|subnet | 4 |
3,237 | 51,572,034 | nested loop to display all data from models django | <p>I need to display all data from models in Django </p>
<p>I have two list one has all rows and another has all columns, what is want to do something like </p>
<pre><code>{{student.username }}
</code></pre>
<p>I am trying to use nested loop to get all data, I know this "row.{{column}} " is wrong but did not find th... | <p>You can query the <code>student</code> and fetch only the required <code>columns</code> using <code>values_list</code> </p>
<p><strong>Ex:</strong></p>
<pre><code>student = student.objects.values_list('column_1', 'column_2')
</code></pre>
<p>Then in your template</p>
<pre><code> {% for column in student %}
&... | python|django | 3 |
3,238 | 56,385,548 | django formset not saving | <p><strong>EDIT:</strong> Turns out my form was not validating. I added print(formset.errors) as an else in my view, which revealed that I had a required field not being completed.</p>
<p>I am trying to manually render formset fields in a template, but the fields are not being saved when I submit. </p>
<p>My method ... | <p>Turns out my form was not validating. I added print(formset.errors) as an else in my view, which revealed that I had a required field not being completed.</p> | python|django | 0 |
3,239 | 56,052,010 | How to retrieve data from an irregularly formatted text database in Python? | <p>I'm working on code to calculate various thermodynamic properties of a given set of molecules. To do so, I have to plug in 9 coefficients into a set of equations to get the desired values. These coefficients, which vary from molecule to molecule, are retrieved from the NASA Thermobuild database, which has the foll... | <p>I'll address the question of extracting the data you want from a record in your text database.</p>
<p>Once you find a record you are interested in (<code>if species_name in line:</code>) you need to advance to the seventh and eighth lines of that record and extract the coefficients. </p>
<p>The <a href="https://w... | python|regex|database|search | 1 |
3,240 | 13,297,016 | Define multiple bluetooth dongles in python-bluez (scan from specific device) | <p>I'm building a bluetooth application in Python, using python-bluez (under linux)</p>
<p>But my computer has 2 bluetooth adapters (one built in, one usb dongle)
How can I choose which one to scan from, because now it randomly picks one.</p>
<p>The code right now is pretty basic ;)</p>
<pre><code>nearby_devices = b... | <pre><code> #Automatic selection:
nearby_devices = discover_devices(lookup_names=True, device_id=-1)
#First adapter
nearby_devices = discover_devices(lookup_names=True, device_id=0)
#Secon adapter
nearby_devices = discover_devices(lookup_names=True, device_id=1)
#..etc
</code></pre> | python|bluetooth|bluez | 0 |
3,241 | 22,359,827 | WLST execute stored variable "connect()" statement | <p>So, I am passing a environment variable from bash to python;</p>
<pre><code>#!/usr/bin/env python2
import os
#connect("weblogic", "weblogic", url=xxx.xxx.xxx.xxx:xxxx)
os.environ['bash_variable']
</code></pre>
<p>via wlst.sh I can print exported bash_variable, but how do I execute stored variable? Basically, I a... | <p>Question though, why wouldn't you called the script with the variable as an argument and use sys.argv[] ?</p>
<p>By example something like this.</p>
<pre><code>import os
import sys
import traceback
from java.io import *
from java.lang import *
wlDomain = sys.argv[1]
wlDomPath = sys.argv[2]
wlNMHost = sys.argv[... | python|weblogic|wlst | 1 |
3,242 | 16,789,439 | Can a form class of ModelForm change the attributes? | <p>I've read a few posts in StackOverflow about the <code>forms.Form</code> vs <code>forms.ModelForm</code>.</p>
<p>It seems that when there is already a table in database for the form, it is better to use <code>ModelForm</code> so that you don't have to declare all the attribute again as they already exist in the cor... | <p>It seems like "validation" would be kind of a big answer to 3 - it's usually a major feature of web frameworks. As for not using HTML tags, there's the <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel="nofollow">DRY principle</a>: if you're already defining what the fields of a form are (for valida... | python|django|forms | 2 |
3,243 | 43,553,149 | On Windows, running “import tensorflow” generates No module named '_pywrap_tensorflow_internal' error | <p>This is a different error than <a href="https://stackoverflow.com/questions/42011070/on-windows-running-import-tensorflow-generates-no-module-named-pywrap-tenso">On Windows, running "import tensorflow" generates No module named "_pywrap_tensorflow" error</a> as it points on <code>_pywrap_tensorfl... | <p><strong>For cpu I found the solution and it worked</strong></p>
<ul>
<li><p>Run below command it will clear all dependencies and then update it or remove and install the latest version of tensor flow </p>
<pre><code> `pip install tensorflow==1.5`
</code></pre></li>
</ul> | windows|tensorflow|python-import | 1 |
3,244 | 43,501,234 | Using Python Subprocess module to run a Batch File with more than 10 parameters | <p>I'm using this code:</p>
<p>test.py:</p>
<pre><code>cmd_line = str('C:\mybat.bat') + " "+str('C:\')+" "+str('S:\Test\myexe.exe')+" "+str('var4')+" "+str('var5')+" "+str('var6')+" "+str('var7')+ " "+str('var8') + " "+str('var9')+ " "+ str('var10')
process = subprocess.Popen(cmd_line, stdin=PIPE, stderr=None, stdo... | <p>Batch file supports only <code>%1</code> to <code>%9</code>. To read 10th parameter (and the next and next one) you have to use the command (maybe more times)</p>
<pre><code>shift
</code></pre>
<p>which shifts parameters:</p>
<p><code>10th</code> parameter to <code>%9</code>, <code>%9</code> to <code>%8</code>, e... | python|subprocess | 2 |
3,245 | 43,671,458 | Django CRUD update object with many to one relationship to user | <p>I followed along the awesome tutorial <a href="https://simpleisbetterthancomplex.com/tutorial/2016/11/15/how-to-implement-a-crud-using-ajax-and-json.html" rel="nofollow noreferrer">How to Implement CRUD Using Ajax and Json</a> by Vitor Freitas. For my project I have an object with a many to one relationship with th... | <p>After a lot of trial and error I found a solution. I had been using inline formsets because I kept finding answers that pointed that direction, but I would rather do it manually if possible and I had been trying, but how I had been doing this did not work in this instance for some reason. </p>
<p>I had been tryin... | python|django|crud | 0 |
3,246 | 54,678,513 | Can I only log when some variable is set to true in python? | <p>I want my code to only log debug level messages when some variable is set to true. Is it possible? Here is my config for the logging module. Right now, I have to comment and uncomment at different places in my code to enable or disable the logging...</p>
<pre><code>formatter = logging.Formatter('%(asctime)s; %(leve... | <p><code>if my_var: logger.setLevel('Warning')</code> <a href="https://docs.python.org/3/howto/logging.html" rel="nofollow noreferrer">check the doc</a></p> | python | 1 |
3,247 | 71,325,207 | How to add duplicates in python text file? | <p>I have this text file which is ppe.txt where it contains this</p>
<pre><code>GH,FS,25
KH,GL,35
GH,FS,35
</code></pre>
<p>how do I identify GH as they appeared twice and add the values so it becomes</p>
<pre><code>GH,FS,60
KH,GL,35
</code></pre>
<p>is it possible to do this?</p> | <p>Open the file for reading. Split each line into 3 tokens. Form a tuple from the first 2 tokens and use that as the key to a dictionary (<em>result</em>). Append the int value of the 3rd token to the value of the tuple/key.</p>
<p>Finally, iterate over the dictionary's items and print the result.</p>
<pre><code>resul... | python|python-3.x|python-3.8 | 0 |
3,248 | 9,308,670 | Difference between two types of class properties definition? | <p>Is there a difference between</p>
<pre><code>class Foo(object):
bar = 1
def __init__(self):
... etc.
</code></pre>
<p>and</p>
<pre><code>class Foo(object):
def __init__(self):
... etc.
Foo.bar = 1
</code></pre>
<p>In both cases <code>bar</code> is a property of the class and it is sam... | <p>I'd say that the only difference is that in the second case, <code>Foo.bar</code> doesn't exist until the <code>Foo.bar = 1</code> statement is executed while in the first case is already available when the class object is created.</p>
<p>That's probably a small difference without any effect in your code (unless th... | python|class | 4 |
3,249 | 34,213,362 | How to delete rows using a key word from columns in Pandas | <p>How we can delete the whole row taking a keyword in any column of that row? I have 250 such rows and 28 columns and I want to delete all rows having "income" as a key string in any column from a data frame using pandas </p> | <p>Say for instance you wanted to drop any row that had 'c' in a column</p>
<pre><code>In [5]: import pandas as pd
In [7]: data = [['a', 'b'], ['a', 'c'], ['c', 'd']]
df = pd.DataFrame(data, columns=['col1', 'col2'])
In [9]: df
Out[9]:
col1 col2
0 a b
1 a c
2 c d
In [10]: df.loc[~(df == '... | python-3.x|pandas|row|dataframe|multiple-columns | 2 |
3,250 | 72,654,707 | How to split by newline and ignore blank lines using regex? | <p>Lets say I have this data</p>
<pre><code>data = '''a, b, c
d, e, f
g. h, i
j, k , l
'''
</code></pre>
<p>4th line contains one single space, 6th and 7th line does not contain any space, just a blank new line.</p>
<p>Now when I split the same using <code>splitlines</code></p>
<pre><code>data.splitlines()
</code>... | <h2>List comprehension approach</h2>
<p>You can add elements to your list if they are not empty strings or whitespace ones with a condition check.</p>
<p>If the element/line is <code>True</code> after stripping it from whitespaces, then it is different from an empty string, thus you add it to your list.</p>
<pre class=... | python|regex|string|split | 1 |
3,251 | 72,575,581 | How to get a text from html using Selenium WebDriver with python-Using CSS selector | <p>Anyone know how to get the text from the below html code. Just I need '383' as a text by using CSS selector from the below html.</p>
<pre><code><td align="right" style="background-color: rgb(147, 191, 179); color: rgb(255, 255, 255);" xpath="1">383&nbsp;&nbsp;</td>
<... | <p>First start the webdriver</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
your_chromedriver_path = '...'
driver = webdriver.Chrome(service=Service(your_chromedriver_path))
</code></pre>
<p>then load the webpage</p>
<pre>... | python|html|css|selenium|selenium-webdriver | 0 |
3,252 | 72,661,685 | How to parse Python files to see if they are compatible with Python 3.7 | <p>I am currently deploying some code on a fleet of raspberry pi systems. The systems all have python 3.7.x installed but one of my team's custom libraries has some python 3.8 features (a few walrus operators, etc). I need to modify my library to remove all of the 3.8 features so that the code runs on these machines. I... | <p>Run a static analysis tool, like <code>pylint</code> or <code>mypy</code>, and make sure that it's running on the appropriate version of Python. One of the first things these tools do is parse the code using the Python parser, and they'll report any SyntaxErrors they find.</p> | python|python-3.x | 3 |
3,253 | 16,504,911 | Resize Image before Upload to Google App engine | <p>I would like to be able resize an image blob before I save it to a database with google app engine </p>
<pre><code>from google.appengine.api import images
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext import db
class ImageModel(db.Mo... | <p>now blobstore support write file directly
<a href="https://developers.google.com/appengine/docs/python/blobstore/overview#Writing_Files_to_the_Blobstore" rel="nofollow">https://developers.google.com/appengine/docs/python/blobstore/overview#Writing_Files_to_the_Blobstore</a></p>
<p>so you can have something like thi... | python|image|google-app-engine|blob | 2 |
3,254 | 16,353,131 | Byte Code File for Python | <p>I am unable to see Compiled Python File (Byte Code) on my hard drive.
I can only see script file with py extension but no Compiled file with pyc extension</p>
<p>I have Windows 7 OS installed.</p> | <p>Only imported modules get a byte-code cache, a <code>.pyc</code> file. For the main script file, the one you run first, <em>no</em> byte cache file is created.</p>
<p>Bytecode cache files are only created if Python has write access to the file system.</p>
<p>For Python 3.2 newer, these bytecode files have been mov... | python|bytecode | 5 |
3,255 | 16,135,692 | Two 'for' loops at once in python | <p>Say I'm iterating through a list in python:</p>
<pre><code>lines = [1, 2, 3, 4]
linecount = len(lines)
#I want to be able to do this:
for i, j in range(linecount - 1, -1, -1), range(linecount, -1, -1):
print i, j
"""
This would print out
3 4
2 3
1 2
0 1
0 0
"""
</code></pre>
<p>How could I go about doing th... | <pre><code>for i, j in zip(range(linecount - 1, -1, -1), range(linecount, -1, -1)):
print i, j
</code></pre> | python|list | 5 |
3,256 | 31,879,423 | wxpython ProgressDialog segmentation fault (lin, not win) | <p>Up until recently, a code I have been working on and running in both Windows (8) and Linux (XUbuntu 14.04) environments started to give segmentation faults upon creating a wx ProgressDialog, but only on the latter platform. This minimal code sample illustrates the problem:</p>
<pre><code>#!/usr/bin/python
import w... | <p>The call to Pulse() does seem to cause it to break on my system as well. I am using wxPython 2.8.12.1 with Python 2.7 on Xubuntu 14.04. If I swap out <code>Pulse</code> for <code>Update</code>, it works fine:</p>
<pre><code>import wx
import time
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__i... | python|linux|windows|wxpython | 1 |
3,257 | 38,649,575 | acess class attribute in another file | <p>I'm new to python.</p>
<p>I have a question about accessing attribute in class</p>
<p>t1.py</p>
<pre><code>#!/usr/bin/python
import t2
class A:
flag = False
if __name__ == "__main__":
t2.f()
print(A.flag)
</code></pre>
<p>t2.py</p>
<pre><code>#!/usr/bin/python
import t1
def f():
... | <p>When you do</p>
<pre><code>./t1.py
</code></pre>
<p>you're executing the <code>t1.py</code> file, but it's not executed as the <code>t1</code> module. It's considered to be the <code>__main__</code> module. (This is what that <code>if __name__ == '__main__'</code> line checks for.) That means that when this line:<... | python | 2 |
3,258 | 38,594,047 | Error running tests with Conda and Tox | <p>I am having trouble running tests with Tox while having virtual environments created with Conda. The steps to reproduce the error are below.</p>
<p>Download the repository (it is small) and <code>cd</code> to it:</p>
<pre><code>git clone https://github.com/opensistemas-hub/osbrain.git
cd osbrain
</code></pre>
<p>... | <p>I managed to work around this by <a href="https://github.com/conda-forge/staged-recipes/issues/1139" rel="nofollow noreferrer">installing virtualenv</a> through conda:</p>
<p><code>conda install virtualenv
</code></p>
<p>It's not recommended to use virtualenv yourself (stick with conda environments). However, when... | python|conda|tox | 3 |
3,259 | 40,705,237 | django.db.migrations.exceptions.CircularDependencyError | <p>I have a problem with Django migrations on empty DB. When I want to migrate I have a circular dependency error. Circular dependency error between two apps that related by foreign keys</p>
<p>/firstapp/models.py </p>
<pre><code>class Person(models.Model):
...
class Doctor(Person):
hospital = models.Forei... | <p>Temporarily comment out foreign keys to break the circular dependency. It looks like you could do this by commenting out <code>Hospital.doctor</code>. Remove the existing migrations and run <code>makemigrations</code> to recreate them.</p>
<p>Finally, uncomment the foreign keys, and run <code>makemigrations</code> ... | python|django|django-migrations|django-database | 22 |
3,260 | 51,821,711 | Stacking different types of arrays in numpy | <p>I'm having difficulties in stacking different "types" of numpy arrays. </p>
<p>array_1 is <code>array([(3,111),(3,222)])</code></p>
<p>array_2 is <code>array([(4,111),(4,222)])</code></p>
<p>array_3 is <code>array([[5,111],[5,222]])</code></p>
<p>(notice the change in brackets in array_3). </p>
<p>I can easily ... | <p>convert every array to numpy array and then use np.hstack</p>
<pre><code>array_1 = np.array([(3,111),(3,222)])
array_2 = np.array([(4,111),(4,222)])
array_3 = np.array([[5,111],[5,222]])
np.hstack((array_1,array_2,array_3))
</code></pre>
<p>I got the following output</p>
<blockquote>
<p>array([[ 3, 111, 4... | python|numpy | 0 |
3,261 | 68,389,375 | Python ord() equivalent in NumPy | <p>In Python, to get the ASCII value of a character we can do:</p>
<pre><code>>>> x = ord('k')
>>> x
107
</code></pre>
<p>What is the equivalent Python "ord" method in NumPy? I see some solutions say to do hacks like list comprehension before passing it NumPy. However, I want a NumPy method ... | <p><a href="https://numpy.org/doc/stable/reference/generated/numpy.ndarray.view.html" rel="nofollow noreferrer">numpy.ndarray.view</a> returns a view of the same array with another (equally sized) datatype, and should due to not copying anything pretty much be instantaneous.</p>
<pre><code>>>> x = np.array(['g... | numpy | 4 |
3,262 | 32,522,198 | Python - Trying to use a list value in an IF statment | <p>I need to ask a user to input a question that will be compared to a list. The matched word will be displayed and then linked to an option menu. I have added the code below. I have managed to get the the program to search the input and return the word in the find list if a match appears. However I can not figure out ... | <p>If what you are trying to achieve is given the user input, whether any of the words in the user given by the user is also present in <code>find</code> list. Then you should just check whether the result list is empty or not. If the <code>result</code> list is empty, that means that none of the words in <code>find</... | python|string|list | 2 |
3,263 | 54,723,581 | Python: Removing all words that start with a Capital Letter and does not arise after punctuation | <p>I want to use regex to remove all words from a text that start with a capital Letter and satisfies these two conditions:</p>
<p>1) They are followed by only lower case letters or " 's" (possessive) or punctuation (.,?!). </p>
<p>2) They do not come after ".", "!" and "?"</p>
<p>I tried </p>
<pre><code>import re
... | <p>To remove <em>whole words</em>, you want to use <code>\b</code> boundary anchors, so that you don't match a partial word. To remove words that are preceded by punctuation, you can use a negative lookbehind, <em>provided</em> that there is always a fixed amount of whitespace between the punctuation and the first lett... | regex|python-3.x | 2 |
3,264 | 28,386,367 | Parse Apache log with Python 2.7 | <p>I'm trying to read a log file from a github url, add some geographic info using the IP as a lookup key, and then write some log info and the geographic info to a file. I've got the reading from and writing to file from the log, but I'm not sure what lib to use for looking up coordinates and such from an IP address, ... | <ol>
<li>The <a href="https://docs.python.org/3.4/library/re.html" rel="nofollow noreferrer">re module</a> isn't deprecated, and is part of the standard library. <strong>Edit:</strong> <a href="https://docs.python.org/2.7/library/re.html" rel="nofollow noreferrer">here's the link</a> for the 2.7 module</li>
<li>Your <c... | python|python-2.7|parsing|logging | 1 |
3,265 | 43,985,866 | Boto error in Scrapy: "The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256." | <p>I'm trying to crawl the following spider:</p>
<pre><code>import scrapy
from tutorial.items import QuoteItem
class QuotesSpider(scrapy.Spider):
name = "quotes"
custom_settings = {
'FEED_URI': 's3://apkmirror/quotes.json',
'AWS_ACCESS_KEY_ID': 'foo',
... | <blockquote>
<p>One solution involves changing the host argument in boto's connect_to_region.</p>
</blockquote>
<p>Storage backend for exporting to S3 is handled by <a href="https://github.com/scrapy/scrapy/blob/master/scrapy/extensions/feedexport.py#L94" rel="nofollow noreferrer">scrapy.extensions.feedexport.S3Feed... | python|amazon-s3|scrapy|boto | 2 |
3,266 | 44,217,492 | Python - language-check 1.0 | <p>Can anyone please let me know why my code is not providing the correct output.</p>
<p>My code:</p>
<pre><code>import language_check
tool = language_check.LanguageTool('en-US')
text='this are bad'
matches = tool.check(text)
t=len(matches)
for i in range(0,t):
print(matches[i].ruleId,matches[i].replacements)
new=l... | <p>Could you be using an old version of LanguageTool? I have installed language_check with Python 3.6.1 just to test your code and it gave me the output "these are bad".</p>
<p>Edit: Precisely, that's what I get on output with exact same code:</p>
<pre><code>THIS_NNS ['these']
these are bad
</code></pre> | python | 0 |
3,267 | 32,830,092 | protocol buffer different languages | <p>I'm trying to read a protocol buffer file in Python that was written with Java and I am having issues as i get this error when calling ParseFromString().</p>
<pre>
File "build/bdist.linux-x86_64/egg/google/protobuf/message.py", line 182, in ParseFromString
File "build/bdist.linux-x86_64/egg/google/protobuf/inte... | <p>What is written in the link you post is true, you have to make some sort of delimiter to know where messages start and end. It is also up to you to handle this before pushing the data to the decoder.</p> | python|protocol-buffers | 0 |
3,268 | 14,033,637 | Python - Different ways of printing? | <p>I've installed PyDev into Eclipse, and when I do the print method in a .py file as <code>print "Hello World"</code> it didn't work. But then I did <code>print ("Hello World")</code> and it worked. I looked on the internet and everything says to do it without parentheses, but it doesn't work, and gives the error:</p>... | <p>You appear to be using Python 3.</p>
<p>In Python 2 <code>print</code> was a keyword and the parentheses were not required.</p>
<p>In Python 3 <code>print</code> was changed to be a function. When calling a function the parentheses are required. </p>
<p><strong>Related</strong></p>
<ul>
<li><a href="http://docs.... | python|python-3.x | 10 |
3,269 | 34,489,948 | Delete all .py files which dont have a corresponding .pyc file | <p>We want to ship a smaller chunk of python distribution to the customer.
So, the idea here is to use the existing python distribution in our application and to do all possible tests. This will make sure that the <strong>.pyc</strong> files are created only for those <strong>.py</strong> files which are being used by ... | <p>Python script that should do the job, but I'd be curious to know if Python will still work after running it.</p>
<pre><code>import os
pyc_files = []
py_files = []
for root, dirnames, filenames in os.walk('.'):
for filename in filenames:
if filename.endswith('.pyc'):
pyc_files.append(os.pat... | python | 2 |
3,270 | 34,595,440 | Python module Installing | <p>I wrote this command to install NLTK python module :</p>
<pre><code>sudo pip install -U nltk
</code></pre>
<p>The first time it seemed to work well but when I wanted to test it, it didn't. So I re-wrote the command and then I got</p>
<pre><code>The directory '/Users/apple/Library/Caches/pip/http' or its parent di... | <p>You'll want to create a <code>virtualenv</code> to install Python packages. This prevents the need to install them globally on the machine (and generally makes installing modules less painful). We'll also include <code>virtualenvwrapper</code> to make things easier.</p>
<p>The steps are to install <code>virtualenv<... | python|import|module|pip|sudo | 0 |
3,271 | 34,422,367 | Python 2: adding integers in a FOR loop | <p>I am working on lab in class and came across this problem:</p>
<p><strong>Write a program using a for statement as a counting loop that adds up integers that the user enters. First the program asks how many numbers will be added up. Then the program prompts the user for each number. Finally it prints the sum.</stro... | <p>I think this is what you're asking: </p>
<p>Write, using a for loop, a program that will ask the user how many numbers they want to add up. Then it will ask them this amount of times for a number which will be added to a total. This will then be printed.</p>
<p>If this is the case, then I believe you just need to ... | python | 1 |
3,272 | 12,117,310 | calling third party c functions from python | <p>I have a requirement of calling third party c functions from inside python.
To do this I created a c api which has all the python specific c code ( using METH_VARARGS) to call the third party functions. I linked this code liba.so with the 3 party library libb.so
In my python file , I'm doing:</p>
<pre><code>import ... | <p>You have to include <code>liba.so</code> in your PATH, otherwise Python won't know where to look for it.</p>
<p>Try the following code, it'll load the library if it can find it from PATH, otherwise it'll try loading it from the directory of the load script</p>
<pre><code>from ctypes import *
from ctypes.util impor... | python|python-c-api|python-c-extension | 2 |
3,273 | 23,442,696 | What does next mean here? Python Instagram API | <p>I'm trying to use the Python Instagram API and came across a sample code on its github documentation that I don't understand.</p>
<p>In the fifth line, why do we put next? What is next doing?<br>
Why aren't we allowed to simply write recent_media = api.user_recent_media(user_ir)?</p>
<pre><code>from instagram.clie... | <p>The second parameter is for pagination. The API call gives you the first "page" of results, and if you want more results you need to get subsequent "pages". </p>
<p>If you want to retrieve as many images as possible, and end up with the list of media objects in <code>recent_media</code>, you can do something like:<... | python|instagram | 10 |
3,274 | 23,405,675 | Why does this pattern not match? | <p>Using this pattern:</p>
<p><code>(?<=\(\\\\).*(?=\))</code> </p>
<p>and this subject string: <code>'(\\Drafts) "/" "&g0l6P3ux-"'</code> </p>
<p>I was expecting to match <code>Drafts</code></p>
<p>However, it is not working. Can someone explain why?</p>
<p>I am using re module in Python,the following is w... | <p><code>match.groups()</code> is empty because your pattern does not define any capturing groups. <code>match.group(0)</code> is the complete match, while <code>match.group(1)</code> would be the first capturing group if there was one.</p>
<p>To improve readability you should express regex patterns as raw strings. Yo... | python|regex | 0 |
3,275 | 7,703,430 | pygtk custom widgets displaying in separate window | <p>I'm having trouble with custom widgets showing up in a separate window. Separate window not in the sense of all widgets being in a window, but they all come up separately with their own window decorations. I'm not sure where the problem would be, but I guessed it might be in one of the following, maybe to do with ho... | <p>Instead of calling <code>do_realize</code> in <code>__init__</code>, I should be calling <code>queue_draw</code>. I got help on the pygtk irc.</p> | python|gtk|widget|pygtk|pycairo | 1 |
3,276 | 960,963 | Trie (Prefix Tree) in Python | <p>I don't know if this is the place to ask about algorithms. But let's see if I get any answers ... :)</p>
<p>If anything is unclear I'm very happy to clarify things.</p>
<p>I just implemented a <a href="http://en.wikipedia.org/wiki/Trie" rel="noreferrer">Trie</a> in python. However, one bit seemed to be more compli... | <p>At a glance, it sounds like you've implemented a <a href="http://portal.acm.org/citation.cfm?id=321481" rel="noreferrer">Patricia Trie</a>. This approach also is called path compression in some of the literature. There should be copies of that paper that aren't behind the ACM paywall, which will include an insertion... | python|algorithm|trie | 19 |
3,277 | 11,568,291 | Benefit of using threads/Threading module python 2.7 | <p>1) I have read that if I import the threading module in python, CPU bound loads won't see much benefit from using this library because the GIL forces threads to run 1 at a time even if I run code on a multi-core machine. If this is the case what sort of code would benefit from using Python's threading library?</p>
... | <p>Even with the GIL, threading in Python is useful because input/output operations don't block the program. You can perform operations while waiting for the completion of a disk operation or while waiting for a network event.</p>
<p>Threads also play a role in GUI applications, where a program can stay responsive to ... | python | 2 |
3,278 | 33,655,214 | PyQt: QListView drag and drop reordering signal issue | <p>I'm having a bit of trouble implementing drag and drop reordering using a QListView and QStandardItemModel. Using the itemChanged signal for processing checked items is fine however when the items are reordered using drag and drop there seems to be a temporary item created when the signal is triggered. There are 5 i... | <p>Update, I found a workaround on this and it involves using a singleshot timer. After dropping an item in the list, the timer fires the slot and it finds 5 items in the new order instead of 6.</p>
<pre><code>import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
if __name__ == '__main__':
app = QAppli... | python|pyqt|pyqt4 | 2 |
3,279 | 33,798,251 | Access ansible playbook results after run of playbook | <p>I am running an ansible script using <code>ansible-pull</code> on a remote machine(client side) which I can't see . </p>
<p>I want to make sure that : </p>
<ul>
<li>ansible playbook are executed successfully then should send summary </li>
<li>ansible playbook if not executed successfully should send summary of w... | <p>AFAIK there is no variable where you could just get this data from.</p>
<p>But this screams for a <a href="https://docs.ansible.com/ansible/latest/dev_guide/developing_plugins.html#callback-plugins" rel="nofollow noreferrer">callback plugin</a>. Have a look at the plugin <a href="https://github.com/ansible/ansible/... | python|automation|ansible | 7 |
3,280 | 33,556,786 | Python: Accessing list as it is comprehended | <p>Is there a way to access the list as it is comprehended? In particular I'd like to iterate once again over elements already added.</p>
<p>for example, im looking for something like this:</p>
<pre><code>[x for x in range(foo) if x not in self]
</code></pre>
<p>or</p>
<pre><code>[x for x in range(foo) if any(y for... | <p>In short: No. You cannot do this. Python's list comprehensions (and related constructs like generator expressions) are not as powerful as Haskell's lazy lists (which could do what you want). The syntax is similar, but Python is not pure a functional language with lazy, recursive evaluation as a syntax feature; its i... | python|python-3.x|list-comprehension | 5 |
3,281 | 33,928,283 | List index out of range in loop with condition | <pre><code>n = input("How many average temperatures do you want to put in?" + "\n").strip()
temperatures = []
differences = []
diff = 0
print('')
if int(n) > 0 :
for x in range (int(n)):
temp = input("Input a average temperature: " + "\n").strip()
temperatures.append(int(temp))
for y in ran... | <p>Here's the problem:</p>
<pre><code>diff = temperatures[y+1] - temperatures[y]
</code></pre>
<p>When <code>y</code> reaches the last valid index in <code>temperatures</code>, the expression <code>y+1</code> will result in an index outside of the list, causing the error. Define the loop like this instead:</p>
<pre>... | python|list|loops|python-3.x | 1 |
3,282 | 33,774,406 | Python - Checking concordance between two huge text files | <p>So, this one has been giving me a hard time!<br>
I am working with <em>HUGE</em> text files, and by huge I mean 100Gb+. Specifically, they are in the <a href="https://en.wikipedia.org/wiki/FASTQ_format" rel="nofollow">fastq format</a>. This format is used for DNA sequencing data, and consists of records of four line... | <p>Sampling is one approach, but you're relying on luck. Also, Python is the wrong tool for this job. You can do things differently and calculate an exact answer in a still reasonably efficient way, using standard Unix command-line tools:</p>
<ol>
<li>Linearize your FASTQ records: replace the newlines in the first thr... | python|python-2.7|parsing|bigdata|fastq | 3 |
3,283 | 46,647,044 | How to set loss weight in chainer? | <p>First of all I narrate you about my question and situation.
I want to do multi-label classification in chainer and my class imbalance problem is very serious.</p>
<p>In this cases I must slice the vector inorder to calculate loss function, For example, In multi-label classification, ground truth label vector most e... | <p>If you work on multi-label classification, how about using <code>softmax_crossentropy</code> loss?</p>
<p>softmax_crossentropy can take into account the class imbalance by specifying the <code>class_weight</code> attribute.
<a href="https://github.com/chainer/chainer/blob/v3.0.0rc1/chainer/functions/loss/softmax_cr... | python|chainer | 0 |
3,284 | 30,267,199 | Downloading Image Data URIs from Webpages via BeautifulSoup | <p>I need to retrieve an image from a website using Python. However, the image is not in the form of a linked file, but as a GIF Data URI. How do I download this and store it in a .gif file? </p> | <p>This should get you going in the correct direction.</p>
<p>First, I'll assume you have retrieved the image uri data and it is saved in a python variable called img_data:</p>
<pre><code># Example
img_data = 'data:image/jpeg;base64,/9j/4A...<lots of data>...k='
</code></pre>
<p>Now you'll need to decode the p... | python|python-2.7|beautifulsoup | 8 |
3,285 | 61,502,603 | Import Tensorflow without NVIDIA GPU (ImportError: Could not find 'nvcuda.dll') | <p>I have installed the <code>tensorflow</code> package using Anaconda Navigator. When I try to run <code>import tensorflow</code> in a jupyter notebook I get the following error:</p>
<pre><code> OSError Traceback (most recent call last)
D:\ProgrammFiles\Anaconda\lib\site-packages\t... | <p>As discussed in the comments, the problem was only in your installation. Using anaconda-navigator isn't the best way to install <code>tensorflow</code>. My assumption is either <code>tensorflow-base</code> or <code>tensorflow-estimate</code> has a GPU dependency which is the reason why it kept showing the posted err... | python|tensorflow|anaconda | 1 |
3,286 | 43,460,309 | ffmpeg python subprocess error only on ubuntu | <p>Im working on an application that is splitting videos from youtube into images. I work on a macbook pro for development, but our app servers run on an ubuntu 12.04 server. The current code on our servers running right now is the following</p>
<pre><code>ffmpeg -i {video_file} -vf fps={fps}
</code></pre>
<p>which w... | <p>The problem is the range notation <code>{0..3}</code>, which works in bash but not in other shells. While the normal login shell on my Ubuntu system is bash, <code>subprocess.Popen()</code> with <code>shell=True</code> calls <code>/bin/sh</code>, which in my case is not bash but dash, which does not support brace ex... | python|ubuntu|ffmpeg | 0 |
3,287 | 48,706,277 | How can i properly change the keys name in my dict? | <p>trying to change my dictionary keys name using this code :</p>
<pre><code>for key in my_dict_other:
new_key = key + '/' + str(my_dict[key])
# new_key = key + '/' + str(my_dict[key][0][0]) + '-' + str(my_dict[key][0][1])
my_dict_other[new_key] = my_dict_other.pop(key)
</code></pre>
<p>however one of the... | <p>This might work:</p>
<pre><code>import re
key = "9-9/[['2550', '1651']]/[]"
newkey = re.sub("[\[\]']", "", key.replace("/[]", ""))
# '9-9/2550, 1651'
</code></pre> | python|regex|python-3.x|dictionary | 0 |
3,288 | 4,696,642 | How do we handle Python xmlrpclib Connection Refused? | <p>I don't know what the heck I'm doing wrong here, I wrote have an RPC client trying to connect to a non-existent server, and I'm trying to handle the exception that is thrown, but no matter what I try I can't figure out how I'm supposed to handle this:</p>
<pre><code>def _get_rpc():
try:
a = ServerProxy(... | <p>_get_rpc returns a reference to unconnected ServerProxy's supervisor method. The exception isn't happening in the call to _get_rpc where you handle it; it's happening when you try to evaluate this supervisor method (in "if not rpc"). Try from the interactive prompt:</p>
<pre><code>Python 2.6.5 (r265:79063, Apr 16 2... | python|exception-handling|xml-rpc|xmlrpclib | 4 |
3,289 | 48,307,797 | Importing a txt to MySQL with different date format | <p>What I want to do is transfer the "12/26/17 14:30" in txt to "2017-12-26 14:30:00 " in MySQL </p>
<p>I've already tried this <a href="https://stackoverflow.com/questions/8163079/importing-a-csv-to-mysql-with-different-date-format">Importing a CSV to MySQL with different date format0</a></p>
<p>So my code looks li... | <p><code>STR_TO_DATE(@time,'%y-%m-%d %H:%i:%S');</code> is returning null as it's not matching the string input pattern.</p>
<p>Try something like this instead: <code>STR_TO_DATE('12/26/17 14:30','%m/%d/%y %k:%i');</code> </p>
<p>After extracting in DATE, convert it to your desired Date format.</p>
<p>To do in singl... | python|mysql|stock-data | 0 |
3,290 | 51,314,217 | How to Validate a MD5 Hash Being Posted From a Python Script in Laravel | <p>Ok , so I have a python script that will register a new user in Laravel if the provided login fails. In the python script I am passing the following:</p>
<pre><code>import hashlib
import strftime
hashedMessage = hashlib.md5()
hashedMessage.update("Password"+strftime("%m/%d/%Y-%H:%M"))
</code></pre>
<p>This will ... | <p>For md5 you can do something as simple as:</p>
<pre><code>if (request()->input('hashed_message') === md5('Password+' . now()->format('m/d/Y-H:m'))) {
// match
}
</code></pre>
<p>This will fail, however, if the request is sent at the minute boundary - i.e. sent at 3:01:59 but received at 3:02:00.</p> | php|python|laravel|md5|php-carbon | 0 |
3,291 | 51,449,851 | XML to XML in Python | <p>The xml file contains many datas including some invoices. I would like to extract only the invoices from the xml file and create a new xml file that only contains the invoices.</p>
<p>I wrote a code that extract the invoices but when it comes to create a new xml file (with invoices) it only contains one invoice. Ho... | <p>If you want a well-formatted XML you will need a root element in your document, then you can add all your elements to the root and save to your file.</p>
<pre><code>root = ET.Element('root')
root.extend(doc.findall('bizonylat'))
ET.ElementTree(root).write('out.xml', 'utf8')
</code></pre> | python|xml | 1 |
3,292 | 73,650,996 | Add an element to a list base on the value of the list (python) | <p>So I have a list of x elements as such:</p>
<pre><code>list = ['0001', '0002', '0003', '0004', '0005', '0006', '0007', '0008', '0009']
</code></pre>
<p>If a element is removed (ex: '0004'):</p>
<pre><code>['0001', '0002', '0003', '0005', '0006', '0007', '0008', '0009']
</code></pre>
<p>How can I add an element base ... | <p>You can just create a zero padded value adding 1 to to the numeric value at last using <a href="https://docs.python.org/3/library/stdtypes.html#str.zfill" rel="nofollow noreferrer"><code>str.zfill</code></a>, then append to the list:</p>
<pre class="lang-py prettyprint-override"><code>lst = ['0001', '0002', '0003', ... | python|list|append|element | 2 |
3,293 | 17,375,248 | Python 3: List inside dictionary, list index out of range | <p>I have created a dictionary where the entries are lists like this:</p>
<pre><code>new_dict
{0: ['p1', 'R', 'p2', 'S'], 1: ['p3', 'R', 'p4', 'P'], 2: ['p5', 'R', 'p6', 'S'], 3: ['p7', 'R', 'p8', 'R'], 4: ['p9', 'P', 'p10', 'S'], 5: ['p11', 'R', 'p12', 'S'], 6: ['p13', 'S', 'p14', 'S']}
</code></pre>
<p>From her... | <p>Notice that in the first interation of your nested loop, we see the following values that are both in Moves:</p>
<pre><code>>>>new_dict[0][1], new_dict[0][3]
('R', 'S')
</code></pre>
<p>However, on your second iteration in the nested loop, you are trying to evaluate terms that are not included in the dic... | python|list|dictionary|indexing | 1 |
3,294 | 17,159,246 | finding the missing value for ValueError: need more than X values to unpack | <p>I have a function call that looks like this:</p>
<p><code>a,b,c,x,y,z = generatevalues(q)</code></p>
<p>Its in a try block to catch the error but I also need to find out which value is missing. I can't clear the variables beforehand either. I'd also rather not merge the 6 variables inside the function into a list ... | <pre><code>values = tuple(generatevalues(q))
try:
a, b, c, x, y, z = values
except ValueError as e:
print(len(values)) # for example
print(values)
</code></pre>
<p>To <em>debug</em> this function - it's a good time to learn about the <a href="http://docs.python.org/2/library/pdb.html" rel="nofollow">debugg... | python|error-handling|variable-assignment|iterable-unpacking | 3 |
3,295 | 64,437,198 | Does retrbinary() and storbinary() in ftplib raise exception if transfer not successful? | <p>Do the <code>retrbinary()</code> and <code>storbinary()</code> functions in <code>ftplib</code> raise exceptions if transfer not successful (or do I need to explicitly check for this)?</p>
<p>Eg. I currently have code that does...</p>
<pre class="lang-py prettyprint-override"><code>ftp = ftplib.FTP(<all the conne... | <p>Yes, they will throw an exception, if they get an error response from the server or if the connection is lost unexpectedly.</p>
<p><em>Though note that with FTP protocol, in some cases, it's not always possible to tell that the transfer has failed.</em></p> | python|ftplib | 1 |
3,296 | 64,177,183 | Randomly distribute people into groups based on condition | <p>I have a list of people with their departments. I'm trying to distribute them into groups of equal size with the condition that they are not with people from their own departments where possible. I've got a list of 417 people with 19 departments and trying to put them in groups of 10.</p>
<p>Here is an example to il... | <p>Since you already have them sorted by department, with numeric "names", the solution is short.</p>
<pre><code>df.groupby(int("Name")%10)
</code></pre>
<p>If my pre-conditions are wrong, then sort your DF by department, and then distribute by <code>row</code> instead of the numeric name.</p> | python|vba|grouping | 0 |
3,297 | 55,907,892 | Matplotlib: Secondary axis with values mapped from primary axis | <p>I have a graph showing x4 vs y:
<img src="https://i.stack.imgur.com/uhy14.png" alt="graph"> </p>
<p>y is the log of some other variable, say q (i.e. y = log(q) )
the value of q is what the layperson will understand when reading this graph.</p>
<p>I want to set up a secondary axis on the right side of the graph, wh... | <p>You can use a twin axis. The idea is following:</p>
<ul>
<li>Create a twin axis and plot the same data on both the axis. This will make sure that the tick positions are axis limits are same on both y-axis.</li>
<li>Get the tick labels which are strings, convert them to integers and take their exponent using <code>n... | python|python-3.x|pandas|matplotlib | 2 |
3,298 | 73,364,166 | How do I make it print the dice of a certain number in a list? | <p>How do I make my code print out the dice image according to the random dice it rolled? This is the code that I have so far whhich roll the dice according to what the user input and the value will be stored in the result list. how can i print the dice image according to the list? Any guidance or help will be apprecia... | <p>I highly encourage you to do (or perhaps continue) a beginners course of python. That being said:</p>
<pre class="lang-py prettyprint-override"><code>for n in result:
for line in die_art[n]:
print(line)
print("\n")
</code></pre> | python | 1 |
3,299 | 73,187,872 | Splitting Dataset over Multiple GPUs | <p>I'm training a large network that inputs and outputs 512x512 images. At the moment, I have 2 Tesla A100 GPUs with 40 GB of memory each, and a dataset comprising 10,000 input and outputs pairs. This adds up to roughly 38 GB of training data, which leads me to run out of memory when sending this data to the "cuda... | <p>Here is my solution. Open to others, especially more memory-efficient options!</p>
<pre><code>to_t = lambda array: torch.tensor(array, device=device)
class CustomDataset(Dataset):
def __init__(self, image, label):
self.image = image
self.label = label
def __len__(self):
return len(self.label)
def __ge... | deep-learning|pytorch | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.