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 |
|---|---|---|---|---|---|---|
300 | 11,590,173 | Scrapy SgmlLinkExtractor and span attribute | <p>I need to match attribute against some strings.
I tried to add the span attribute to sgmllinkextractor but it seems to ignore it since it has no link in it.</p>
<p>is there an option to use a callback function that will be called when no link could be extract via linkExtractor?</p>
<p>I want to match the page aga... | <p>Try subclassing <a href="http://doc.scrapy.org/en/latest/topics/spiders.html#basespider" rel="nofollow">BaseSpider</a> instead of using CrawlSpider.</p> | python|scrapy | 0 |
301 | 11,577,681 | A Simple View to Display/Render a Static image in Django | <p>I am trying to find the most efficient way of displaying an image using django's template context loader. I have a static dir within my app which contains the image 'victoryDance.gif' and an empty static root dir at the project level (with <code>settings.py</code>). assuming the paths within my <code>urls.py</code> ... | <p>If you need to render an image read a bit here <a href="http://www.djangobook.com/en/1.0/chapter11/" rel="noreferrer">http://www.djangobook.com/en/1.0/chapter11/</a> and use your version of the following code:</p>
<p>For django version <= 1.5:</p>
<pre><code>from django.http import HttpResponse
def my_image(re... | python|django|django-staticfiles|django-1.4 | 29 |
302 | 58,402,973 | How to create train, test and validation splits in tensorflow 2.0 | <p>I am new to tensorflow, and I have started to use tensorflow 2.0</p>
<p>I have built a tensorflow dataset for a multi-class classification problem. Let's call this <code>labeled_ds</code>. I have prepared this dataset by loading all the image files from their respective class wise directories. I have followed along... | <p>Please refer below code to create train, test and validation splits using tensorflow dataset "oxford_flowers102" </p>
<pre><code>!pip install tensorflow==2.0.0
import tensorflow as tf
print(tf.__version__)
import tensorflow_datasets as tfds
labeled_ds, summary = tfds.load('oxford_flowers102', split='train+test+va... | python|tensorflow|tensorflow-datasets|tensorflow2.0 | 2 |
303 | 33,720,522 | Python: convention name for a test | <p>Is there a convention for naming tests in Python when using the <code>unittest</code> module. I know that each method inside a class which inherits from <code>unittest.TestCase</code> should start with test, but I wonder what is much better:</p>
<p><strong>1. A short descriptive name without docstring</strong></p>
... | <pre><code>Generally it is preferable to increase readability by :
- choosing an adequate name
- describing how it works
</code></pre>
<p>Choose your name such that it will be short and descriptive. For readability, use snake_case. For example : test_week_date.</p>
<p>Always include a docstring in your f... | python|python-unittest | 1 |
304 | 33,819,825 | Memory error while generating the openstreet map tiles from generate_tiles.py | <p>I am facing weired behavioue of python. when i set the small value of the bound i am able to generate the tiles for small portion .but when i am setting bound value to large number like 60232323.73 i am getting memory error in Generate_tile.py.</p>
<p>Please help on this</p> | <p><code>6191256.42, 842455.88, 11502754.24, 4218918.81</code> is not a valid <a href="https://wiki.openstreetmap.org/wiki/Bounding_Box" rel="nofollow">bounding box</a>. The latitude (2nd and 4th parameter) must be between <code>-90.0</code> and <code>90.0</code> and the longitude (1st and 3rd parameter) must be betwee... | python-2.7|openstreetmap | 0 |
305 | 47,030,450 | Merge two data-sets in Python Pandas | <p>I have two datasets in the below format & want to merge them into a single dataset based on City+Age+Gender. Thanks in advance</p>
<p>Dataset1:</p>
<pre><code> City Age Gender Source Count
0 California 15-24 Female Amazon Prime Video 14629
1 California 15-24 Female ... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer"><code>pandas.concat</code></a> with <code>rename</code> columns for align columns - need same columns in <code>both DataFrames</code>:</p>
<pre><code>df = pd.concat([df1, df2.rename(columns={'Feeds':'Cou... | python|pandas|merge | 2 |
306 | 37,662,464 | python 2.7 wand: UnicodeDecodeError: (Error in get_font_metrics) | <p>I am getting this error "UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 17: ordinal not in range(128)" when I try to merge this image "La Pocatière.png".</p>
<pre><code> Python 2.7.11
bg_img = Image(filename='C:/Pocatière.png')
bg_img.resize(1200,628)
bg_img.composite('C:/test.p... | <p>Is this python v2 or v3? </p>
<p>In case this is Python version 2 (which I think it is), then you might be better of with calling </p>
<pre><code>Image(filename=u'C:/Pocatière.png')
</code></pre>
<p>you can also notice this in the working sample where it states </p>
<pre><code>u'La Pocati\xe8re.png'
</code></pr... | python|imagemagick|python-unicode|wand | 2 |
307 | 38,034,585 | Retaining longest consecutive occurrence that does not equal a specific value | <p>I have a df like so:</p>
<pre><code>Value
0
1
3
-999
4
5
6
2
7
8
9
-999
3
2
-999
1
</code></pre>
<p>and I want to retain the most consecutive values in the dataframe that are NOT <code>-999</code></p>
<p>which for this example would give me this:</p>
<pre><code>Value
4
5
6
2
7
8
9
</code></pre>
<p>I have multip... | <p>You can do a <code>cumsum()</code> on the condition series which gives a unique groupId for each consecutive sequence from one <code>-999</code> to another. Then find the maximum length of the groupId and filter on that should give the desired output:</p>
<pre><code>df['groupId'] = (df['Value'] == -999).cumsum()
df... | python|pandas | 1 |
308 | 37,793,011 | Add a value if this value doesn't exist in dictionary | <p>I have a default dictionary. I loop through many strings and add them to the directory under the key as a number but only if there is no that value already in dictionary. So my code looks like this:</p>
<pre><code>from collections import defaultdict
strings = ["val1", "val2", "val2", "val3"]
my_dict = defaultdict(l... | <p>Notice that <code>my_dict.itervalues()</code> returns a list of lists in your case. So <code>string not in lists</code> always returns <code>True</code>, as you can see from the following code,</p>
<pre><code>>>> "val2" not in [["val1"], ["val2"]]
True
</code></pre>
<p>To get the desired result, flat a li... | python|python-2.7 | 2 |
309 | 48,565,253 | serving media files with dj-static in heroku | <p>I'm trying to serve media files that are registered in django-admin.</p>
<p>When accessing an image by api error 404 Not found.</p>
<p>I made a configuration as the recommended <a href="https://github.com/kennethreitz/dj-static" rel="nofollow noreferrer">documentation</a>, but in heroku does not work.</p>
<p>sett... | <p>I had the same issue and fixed it by changing my path on models.py to a different one... It was configured to access it through <strong>media/images/img.jpg</strong>, but the page using dj-static was requesting it from the same folder structure as static files, which should be located at <strong>myapp/media/images/i... | python|django|heroku | 0 |
310 | 4,497,038 | Algorithm to sum/stack values from a time series graph where data points don't match on time | <p>I have a graphing/analysis problem i can't quite get my head around. I can do a brute force, but its too slow, maybe someone has a better idea, or knows or a speedy library for python?</p>
<p>I have 2+ time series data sets (x,y) that i want to aggregate (and subsequently plot). The issue is that the x values acros... | <p>Something like this:</p>
<pre><code>def join_series(s1, s2):
S1 = iter(s1)
S2 = iter(s2)
value1 = 0
value2 = 0
time1, next1 = next(S1)
time2, next2 = next(S2)
end1 = False
end2 = False
while True:
time = min(time1, time2)
if time == time1:
value1 ... | python|graph|aggregate-functions|analysis|data-analysis | 1 |
311 | 48,252,914 | How can I modify and remove special characters in keys of Python2 dictionary | <p>I am trying to get rid of special characters in Python dictionary keys and add the <code>year</code> of the key to its corresponding <code>value</code> if the year exist:</p>
<pre><code>{'New Year Day 2019\\xa0': 'Tuesday, January 1', 'Good Friday': 'Friday, March 30', 'New Year Day 2018\\xa0': 'Monday, January 1'}... | <p>If it's the special character "\xa0" you are trying to remove from the keys, try this:</p>
<pre><code>data = {'New Year Day 2019\\xa0': 'Tuesday, January 1', 'Good Friday': 'Friday, March 30', 'New Year Day 2018\\xa0': 'Monday, January 1'}
for i in data:
if "\\xa0" in i:
data[i.replace("\\xa0", "")] = d... | python|json|dictionary|unicode|key | 0 |
312 | 48,359,744 | Original files are automatically deleted by the process while compiling code | <p>I have written a code in python to convert dicom (.dcm) data into a csv file. However, if I run the code for more than once on my database directory, the data is automatically getting lost/deleted. I tried searching in 'recycle bin' but could not find the deleted data. I am not aware of the process of what went wron... | <p>You have something like the following scenario:</p>
<p>After 1st iteration, you end with the files: <code>MR0001.dcm</code>, <code>MR0002.dcm</code>, <code>MR0003.dcm</code>... In 2nd iteration, there are the following changes:</p>
<pre><code>os.rename('some_file', 'MR0001.dcm')
os.rename('MR0001.dcm', 'MR0002.dc... | python|python-3.x|csv|export-to-excel|dicom | 1 |
313 | 51,287,196 | Saving every rows of pandas dataframe to txt file | <p>So, I open a dataset from a HDF5 file like below:</p>
<pre><code>import pandas as pd
import numpy as np
data1 = pd.read_hdf('sport.hdf5', usecols=['category','title','images','link','date','desc'])
</code></pre>
<p>It will give me output like below:</p>
<pre><code>category ... | <p>After hours of working, here's the idea to solve the problem:</p>
<p>First, make iteration of rows for Data1 dataframe. Don't forget to add attribute iterrows that will return row selection. And don't forget to define index and rows.</p>
<p>To make file for every row, define the directory followed by (row[title]) ... | python|pandas|numpy|hdf5 | 0 |
314 | 17,445,969 | What does the second argument of the read command mean? | <p>I have this Python code:</p>
<pre><code>for name, age in read(file, ('name','age')):
</code></pre>
<p>Could anybody please explain what it means?</p> | <p><code>('name','age')</code> is a tuple, an <a href="http://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange" rel="noreferrer">immutable sequence type</a>, similar to a list.</p>
<p>If you're asking what it means in regards to the <code>read()</code> function, I'm... | python|syntax|io | 7 |
315 | 64,491,470 | Split list into lists containing only 1s | <p>I have this list in python:</p>
<pre><code>[100, 96, 1, 1, 1, 2, 4, 1, 1, 1, 1, 55, 1]
</code></pre>
<p>How could I split the given list (and other lists containing 1s) so that I get sub-lists containing only neighbouring 1s - so the result would be:</p>
<pre><code> [ [1, 1, 1], [1, 1, 1, 1], [1] ]
</code></pre>
<... | <p>I guess there could be an approach using maybe <code>itertools</code>' <code>takewhile</code>/<code>dropwhile</code> or something, but this simple for loop does it:</p>
<pre><code>l = [100, 96, 1, 1, 1, 2, 4, 1, 1, 1, 1, 55, 1]
res = []
tmp = []
for i in l:
if i == 1:
tmp.append(i)
elif tmp:
res.append... | python|python-3.x|list|grouping | 3 |
316 | 55,641,125 | Minimum required hardware component to install tensorflow-gpu in python | <p>I'm tried many PC with different hardware capability to install tensorflow on gpu, they are either un-compatible or compatible but stuck in some point. I would like to know the minimum hardware required to install tensorflow-gpu. And also I would like to ask about some hardware, Is they are allowed or not:
Can I use... | <p>TensorFlow (TF) GPU 1.6 and above requires cuda compute capability (ccc) of 3.5 or higher and requires AVX instruction support.<br>
<a href="https://www.tensorflow.org/install/gpu#hardware_requirements" rel="nofollow noreferrer">https://www.tensorflow.org/install/gpu#hardware_requirements</a>.
<a href="https://www.t... | python|tensorflow|gpu|cpu | 3 |
317 | 73,179,713 | How to compare two dates that are datetime64[ns] and choose the newest | <p>I have a dataset and I want to compare to dates, both are datetime64[ns] if one is the newest I need to choose the other.</p>
<p>Here is my code:</p>
<pre><code>df_analisis_invertido['Fecha de la primera conversion']=df_analisis_invertido.apply(lambda x: x['Fecha de creacion'] if df_analisis_invertido['Fecha de la ... | <p>The approach you chose is almost fine, except the comparison of the series objects. If you replace them with x instead of the df_analisis_invertido, it should work.</p>
<p>Here an example:</p>
<pre><code>import pandas as pd
data = {'t_first_conv': [5, 21, 233],
't_creation': [3, 23, 234],
}
df = pd.DataFr... | python|pandas|datetime | 1 |
318 | 49,889,448 | Transform a python nested list into an HTML table | <p>I want to transform a list of rows in Python into an HTML table to ultimately send in an email body. Let's say my list of rows is stored as the variable <code>req_list</code> (representing the import data from a .csv file, for example) looks like:</p>
<pre><code>> [['Email', 'Name', 'Name ID', 'Policy ID',
> ... | <p>You can use Pandas for that, only two lines of code:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(req_list[1:], columns=req_list[0])
df.to_html()
'<table border="1" class="dataframe">\n <thead>\n <tr style="text-align: right;">\n <th></th>\n <th>Email</... | python|html|python-3.x|nested-lists | 3 |
319 | 49,799,798 | Can not import opencv in python3 in Raspberry Pi3? | <p>Any solution for this error ?, need help :(</p>
<p>I import cv2 in python3:</p>
<pre><code>import cv2
</code></pre>
<p>and it results like this:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/dist-packages/cv2/__init__.py", line 4,... | <p>Use this:</p>
<pre><code>sudo apt install libqt4-test
</code></pre>
<p>Reference: </p>
<ul>
<li><a href="https://raspberrypi.stackexchange.com/questions/83648/how-can-i-use-opencv-with-python-3-on-a-raspberry-pi">RPi-Stackexchange</a></li>
</ul> | python-3.x | 12 |
320 | 62,777,867 | python vaex groupby with custom function | <p>Is there a way to apply a custom function to a group using the groupby function of a vaex DataFrameArray?</p>
<p>I can do: <br />
<code>df_vaex.groupby(['col_x1','col_x2','col_x3','col_x4'], agg=vaex.agg.mean(df_vaex['col_y']))</code></p>
<p>But is there a way to do pandas: <br />
<code>df.groupby(['col_x1','col_x2'... | <p>Unfortunately, not. There's an open issue requesting it, and the Vaex team is thinking about/working on a solution.</p>
<p><a href="https://github.com/vaexio/vaex/issues/763" rel="nofollow noreferrer">https://github.com/vaexio/vaex/issues/763</a></p> | python|vaex | 0 |
321 | 62,661,353 | How to combine multiple different numpy arrays along a single common dimension, while setting unique variables as separate dimensions | <p>I have multiple different <code>numpy</code> arrays, all with different shapes and containing different information. But all contain a <code>'timestamp'</code> axis.</p>
<p>For example, I have 2 arrays, a, b as follows:</p>
<ul>
<li><code>a = np.array([[1,[1,2,3,4,5,6,7,8,9,10]],[2,[11,12,13,14,15,16,17,18,19,20]],[... | <p>Maybe the previous answer using a zip solved it for you but it works only if the 2 lists have the "index element" in the same order. In case they are not (or if there are few indexes missing), the zip will not work properly.</p>
<p>Try this.</p>
<pre><code>import itertools
[[i[0][0],[i[0][1],i[1][1]]] for... | arrays|numpy | 0 |
322 | 61,619,101 | How to create a column that has the same value per group in Python Pandas? | <p>I currently have a Pandas Dataframe with lots of stock tickers in my first column. They are time series so each Tickers appears more than once. In my second column I have a CUSIP code, but this code only appears in the row where the ticker appears first, all the next rows do not contain this CUSIP code. I would like... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.ffill.html#pandas-dataframe-ffill" rel="nofollow noreferrer"><code>ffill</code></a> - To fill NA/NaN values using the specified forward method.</p>
<pre><code>>>> df.ffill()
0 1 2 ... | python|pandas|pandas-groupby | 0 |
323 | 61,740,656 | Is there a way to change windows folder thumbnails with Python? | <p>I have hundreds of folders of images on my HDD, and with very few exceptions they each have a cover image that I want to use as their respective folder thumbnails, or at least a memorable first image. Unfortunately, Windows 10 defaults to using two random images in the folder as the thumbnail, and I have to manually... | <p>I don't have reputation to comment, so I pile up my answer here. I feel you are better of using folder <em>icons</em> for this purpose, since nowhere on the Internet could I find a way to programmatically set folder <em>pictures</em>, but I'm sure its some registry trickery.</p>
<pre><code>import os
from PIL import ... | python|windows|file-properties | 1 |
324 | 67,361,773 | Is it possible to use SQLite on a VPS for a Discord bot? | <p>Is it possible to use SQLite on a VPS as a database? I've been making a Discord bot and I used SQLite for leveling, warns and changing prefix etc.</p>
<p>I don't really want to use JSON as a database since I'll be making this bot a public bot for everyone's usage, and JSON seems to slow down when the file gets chunk... | <p>The sqlite3 module is part of the standard Python library, so any standard Ubuntu installation or any VPS with Python installed will not require further installation.</p>
<p>If you need to manually install it use:</p>
<pre><code>sudo apt-get update
sudo apt-get install sqlite3 libsqlite3-dev
</code></pre>
<p>Keep in... | python|sqlite|discord.py | 1 |
325 | 60,463,401 | Python variables format changes inside an IF while the first condition is ok | <p>I am doing a very simple aplication of calculating a cost, and I want to have a Radiobutton where I can choose the currency.</p>
<p>I am wondering what is the problem here, because whith the first condition(Run in EUR), everything goes well, but if there is the second condition, I got the problem: </p>
<pre><code>... | <p>You are missing parenthesis:</p>
<pre><code>Beneficio_Bruto_EUR = Label(root, width=20, borderwidth=5,
text="%.2f€" % (Beneficio_Bruto/d))
</code></pre>
<p>String formatting is always applied before operations:</p>
<pre><code>>>> '%d' % (4 * 2)
'8'
>>> '%d' % 4 * 2
'4... | python | 0 |
326 | 60,590,442 | Abstract dataclass without abstract methods in Python: prohibit instantiation | <p>Even if a class is inherited from <code>ABC</code>, it can still be instantiated unless it contains abstract methods.</p>
<p>Having the code below, what is the best way to prevent an <code>Identifier</code> object from being created: <code>Identifier(['get', 'Name'])</code>?</p>
<pre><code>from abc import ABC
from t... | <p>You can create a <code>AbstractDataclass</code> class which guarantees this behaviour, and you can use this every time you have a situation like the one you described.</p>
<pre><code>@dataclass
class AbstractDataclass(ABC):
def __new__(cls, *args, **kwargs):
if cls == AbstractDataclass or cls.__bases... | python|python-3.x|oop|abc|python-dataclasses | 14 |
327 | 71,258,084 | only convert to date cells with data | <p>I have a data frame with dates and missing dates:</p>
<pre><code>date
2022-02-02
2022-02-03
-
-
</code></pre>
<p>I need to convert to date only the ones different from '-', I'm using .loc for this but is not working:</p>
<pre><code>df.loc[oppty['date'] != '-', 'date'] = pd.to_datetime(df['date'])
</code></pre>
<bloc... | <p>Will this work?</p>
<pre><code>df1 = pd.DataFrame({'date':['2022-02-02', '2022-02-03', '-','-']})
df1
pd.to_datetime(df1['date'], errors='coerce')
</code></pre>
<p><a href="https://i.stack.imgur.com/wZ5mU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wZ5mU.png" alt="enter image description here"... | python|datetime|pandas-loc | 1 |
328 | 11,006,829 | Sum possibilities, one loop | <p>Earlier I had a lot of wonderful programmers help me get a function done. however the instructor wanted it in a single loop and all the working solutions used multiple loops.</p>
<p>I wrote an another program that almost solves the problem. Instead of using a loop to compare all the values, you have to use the func... | <p>You can use <a href="http://docs.python.org/library/collections.html?highlight=counter#collections.Counter" rel="nofollow">collections.Counter</a> function instead of the <code>level5.charCount</code></p>
<p>And I don't know why you need to check <code>if level5.charCount(theList).get(a):</code>. I think it is no n... | python | 4 |
329 | 63,569,356 | Django 2.2 with 2 domains | <p>I have a Django web app and 2 domains. I want to use these domains for the different Django apps.</p>
<p>For example:</p>
<ul>
<li>firstdomain.com -> stuff app</li>
<li>seconddomain.com -> customer app</li>
</ul>
<p>Is it possible? How should urls.py looks like?</p> | <blockquote>
<p>Django comes with an optional “sites” framework. It’s a hook for associating objects and functionality to particular websites, and it’s a holding place for the domain names and “verbose” names of your Django-powered sites.
<strong>Use it if your single Django installation powers more than one site and y... | python|django | 3 |
330 | 63,554,707 | Django can't call custom django commands extwith call_command | <p>This is probably a really basic question but I can't find the answer anywhere for some reason. I created a custom command which I can call from the command line with <code>python manage.py custom_command</code>. I want to run it from elsewhere but don't know how to do so. I have added pages to my INSTALLED_APPS in s... | <p>Not sure if this will help anyone, but it turns out I was doing this the wrong way. Generally, I don't think my method above will work because you have to call a django command from outside the django project basically which means the settings will not be configured. My use case was running a django command in the b... | python|python-3.x|django | 1 |
331 | 63,614,888 | i = self.pos[0] is saying TypeError: 'int' object is not subscriptable, line 18 and 19 of my code | <p>I'm trying to build a snake game with pygame by following a video posted by Tech with Tim I'm at part 3 of the video and I don't know my i saying it's not subscriptable when it didn't for him.</p>
<pre><code>class cube(object):
rows = 20
w = 500
def __init__(self, start, dirnx=1, dirny=0, color=(255, 0,... | <p>You create the <code>snake</code> object as</p>
<pre><code>snake((0, 170, 0), 10)
</code></pre>
<p>Inside the <code>snake.__init__</code> function you create a <code>cube</code> object as</p>
<pre><code>cube(pos)
</code></pre>
<p>Where <code>pos</code> is the value <code>10</code> you passed to the <code>snake.__ini... | python|typeerror | 2 |
332 | 62,466,383 | Django: How to compare two querysets and get the difference without including the PK | <p>I don't think the word <code>difference</code> is correct because you might think <code>difference()</code> but it makes sense to me what I am trying to achieve. I do apologize if this is a common problem that's already been solved but I can't find a solution or dumbed down understanding of it.</p>
<p>I have two qu... | <pre><code>qs1 = ErrorLog.objects.filter(report=original_report) # 272 rows
qs2 = ErrorLog.objects.filter(report=new_report) # 266 rows
diff_qs = qs1.difference(qs2) # 6 rows
</code></pre> | python-3.x|django|django-models|django-queryset|set-difference | 0 |
333 | 62,341,893 | how to read csv rows and compare it with a my list | <p>Suppose, we have a list of <code>listdata = [23, 511, 62]</code> and we want to check whether this list exist in a <code>csv</code> file and find out the name of the person who matches it</p>
<h3>for e.g. csv file:</h3>
<blockquote>
<pre><code>name,age,height,weight
bob,24,6,82
ash,23,511,62
mary,22,62,55
</code></p... | <pre><code>import csv
listdata = [23, 511, 62]
with open('file.csv', newline='') as csvfile:
reader = list(csv.reader(csvfile, delimiter=',', quotechar='|'))
# we remove the first row because it contains headers
for row in reader[1:]:
row = list(row)
if listdata == row[1:]:
pr... | python | 1 |
334 | 58,870,276 | In python using iloc how would you retrive the last 12 values of a specific column in a data frame? | <p>So the problem I seem to have is that I want to acces the data in a dataframe but only the last twelve numbers in every column so I have a data frame:</p>
<pre><code>index A B C
20 1 2 3
21 2 5 6
22 7 8 9
23 10 1 2
24 3 1 2
25 4 9 0
26 10 11 12
2... | <p>You can get the last n rows of a DataFrame by:</p>
<pre><code>df.tail(n)
</code></pre>
<p>or</p>
<pre><code>df.iloc[-n-1:-1]
</code></pre> | python|pandas|dataframe | 1 |
335 | 49,036,748 | Python 3.6 SSL - Uses TLSv1.0 instead of TLSv1.2 cipher - (2 way auth and self-signed cert) | <p>I'm using the ssl library with python 3.6. I'm using self-signed ECDSA certificate that I generated with openssl. </p>
<p><strong>Server/client code:</strong></p>
<pre><code># Create a context in TLSv1.2, requiring a certificate (2-way auth)
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
context.options |= ssl.OP_... | <p>This cipher is compatible with TLS 1.2, it's an ordinary cipher defined in <a href="https://www.rfc-editor.org/rfc/rfc5289" rel="nofollow noreferrer">RFC 5289</a>.</p>
<p>I think we need to interpret somewhat Python's doc to know what get_ciphers() is returning exactly as it's not explained. But cipher() gives us th... | python|python-3.x|ssl|openssl|tls1.2 | 1 |
336 | 60,240,602 | Conversion between Cartesian vs. Polar Coordinates. Hoping the result is positive | <p>I have several points that I need to covert them from Cartesian to Polar Coordinates. But for some points, the results I got were negative values.</p>
<p>For example, the origin or the center of the system is (50,50), and the point I want to covert is (10, 43). The angle I got from my code is -170.07375449, but I w... | <p>If you need to convert [-180; 180] angle to [0; 360] you can use this code:</p>
<pre><code>def convert_angle(angle):
return (angle + 360) % 360
</code></pre> | python|numpy | 1 |
337 | 65,485,736 | Generate all permutations of n entries in a w x h matrix | <p>I'd like to generate all the permutations of n entries in a w x h matrix:
example with a 2x2 matrix and n = 1:</p>
<pre><code>| 1 0 |
| 0 0 |
| 0 1 |
| 0 0 |
| 0 0 |
| 1 0 |
| 0 0 |
| 0 1 |
</code></pre>
<p>example with a 3x3 matrix and n = 2 (partial):</p>
<pre><code>| 0 0 1|
| 0 0 1|
| 0 0 0|
| 1 0 0|
| 0 0 1|... | <p>There are <code>w * h</code> available positions in which you want to place <code>n</code> 1's and fill the rest with 0's.</p>
<p>You can create all possible combinations of positions for the <code>n</code> 1's by using <code>itertools.combinations</code>:</p>
<pre class="lang-none prettyprint-override"><code>>&g... | python-3.x|multidimensional-array|combinations|itertools | 1 |
338 | 50,483,279 | Make a 2D histogram with HEALPix pixellization using healpy | <p>The data are coordinates of objects in the sky, for example as follows:</p>
<pre><code>import pylab as plt
import numpy as np
l = np.random.uniform(-180, 180, 2000)
b = np.random.uniform(-90, 90, 2000)
</code></pre>
<p>I want to do a 2D histogram in order to plot a map of the density of some point with <code>(l, b... | <p>Great question! I've written a short function to convert a catalogue into a HEALPix map of number counts:</p>
<pre><code>from astropy.coordinates import SkyCoord
import healpy as hp
import numpy as np
def cat2hpx(lon, lat, nside, radec=True):
"""
Convert a catalogue to a HEALPix map of number counts per re... | python|plot|astronomy|healpy|histogram2d | 7 |
339 | 61,583,566 | Pipe unbuffered stdout from subprocess to websocket | <p>How would you pipe the stdout from subprocess to the websocket without needing to wait for a newline character?
Currently, the code below only sends the stdout on a newline.</p>
<p>Code attached for the script being run by the subprocess. Is the output not being flushed properly from there?</p>
<p>send_data.py:</p... | <p>If you write</p>
<pre><code> for line in p.stdout:
</code></pre>
<p>then you (kind of) implicitly say, that you want to wait for a complete line</p>
<p>you had to use <code>read(num_bytes)</code> and not <code>readline()</code></p>
<p>Below one example to illustrate:</p>
<p><strong>sub.py</strong>: (exampl... | python|websocket|subprocess|stdout | 1 |
340 | 57,966,313 | Passing a list to a method inside a class from another class in order to modify said list and pass back to the original class in Python | <p>I am writing a novel <strong>Blackjack</strong> program for my online portfolio that creates cards from random. </p>
<p>In order to not create duplicate cards in one round I have created a list that stores the cards that have already been created. The new random card is then checked against the cards contained insi... | <p>Figured out what was wrong with the method. "self" does not need to be placed in the method definition. For some reason placing self in the method call didn't pass the list dealed_cards correctly. Also, dealed_cards can just be passed as dealed_cards, not dealed_cards = [].
So the new correct method definition is <... | python-3.x|algorithm|oop|methods | 0 |
341 | 42,320,151 | Print unknown number of lists as columns | <p>I am using <strong>Python 3.5.2</strong>, and I want to create an user-friendly program that outputs a range of numbers in some columns. </p>
<pre><code>#User input
start = 0
until = 50
number_of_columns = 4
#Programmer
#create list of numbers
list_of_stuff = [str(x) for x in range(start,until)]
print("-Created "+... | <p>Use:</p>
<pre><code>for t in zip(generated_lists[0],generated_lists[1],generated_lists[2]):
print(' '.join(str(x) for x in t))
</code></pre>
<p>or more succinctly:</p>
<pre><code>for t in zip(*generated_lists[:3]):
print(' '.join(map(str, t)))
</code></pre>
<p>So what you need to change is 3 to whatever ... | python|list | 2 |
342 | 53,959,442 | Lookup values in cells based on values in another column | <p>I have a pandas dataframe that looks like:</p>
<pre><code> Best_val A B C Value(1 - Best_Val)
A 0.1 0.29 0.3 0.9
B 0.33 0.21 0.45 0.79
A 0.16 0.71 0.56 0.84
C 0.51 0.26 0.85 0.15
</code></pre>
<p>I want to fe... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.lookup.html" rel="nofollow noreferrer"><code>DataFrame.lookup</code></a> for performance.</p>
<pre><code>df['Value'] = 1 - df.lookup(df.index, df.BestVal)
df
BestVal A B C Value
0 A 0.10 0.29 0.30 0.90
1 ... | python|pandas|dataframe | 1 |
343 | 58,416,423 | Filter points between polygons | <p>I have polygon like this:</p>
<pre><code>MULTIPOLYGON(((3.6531688909 22.2345676543....)))
MULTIPOLYGON(((3.7531688909 22.6543234523....)))
…
</code></pre>
<p><a href="https://i.stack.imgur.com/RvOeO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RvOeO.png" alt="enter image description here"></a... | <p>What does your polygon data look like? Do you have geometry fields? If so, you could use <a href="http://geopandas.org/reference.html#geopandas.GeoSeries.contains" rel="nofollow noreferrer">geopandas <code>contains</code></a> to check if your blue polygons contain your points.</p> | python|pandas|geolocation|filtering | 1 |
344 | 57,120,555 | decode TFRecord fail. Expected image (JPEG, PNG, or GIF), got unknown format starting with '\257\ | <p>I encoded some images to TFRecords as an example and then try to decode them. However, there is a bug during the decode process and I really cannot fix it.</p>
<p>InvalidArgumentError: Expected image (JPEG, PNG, or GIF), got unknown format starting with '\257\222\244\257\222\244\260\223\245\260\223\245\262\225\247\... | <p>I can use tf.io.decode_raw() to decode the TFRecords and then use tf.reshape() to get the original image. While still don't know when to use tf.io.decode_raw() and when to use tf.io.decode_jpeg().</p> | image|tensorflow|deep-learning|computer-vision|tfrecord | 0 |
345 | 44,565,861 | scrollToTop not working correctly in ScrollPanel with RadioBox | <p>I'm having a problem with a <code>wxPython</code> scrolled panel which contains a radiobox. The scroll bar jumps to the top when trying to select an item from the radiobox when changing focus from another panel. You then need to scroll and click again. A minimal example which reproduces the problem:</p>
<pre><code>... | <p>OnChildFocus(self, evt)<br>
If the child window that gets the focus is not fully visible, this handler will try to scroll enough to see it.</p>
<p>Parameters: evt – a ChildFocusEvent event to be processed.</p>
<p>and apparently it works in this case, at least on Linux</p>
<pre><code>#!/bin/env python
import wx
im... | wxpython | 1 |
346 | 20,977,909 | Sending data through broken pipe | <p>When I connect a socket to a server socket, and the server socket at a given time shuts down, I get a <code>BrokenPipeError</code> on the client side. But not the next time I try to send something, but the time after that.</p>
<p>Here a SSCCE:</p>
<p>Server:</p>
<pre><code>#! /usr/bin/python3
import socket
s = ... | <p>The send function only ensures that the data has been transferred to the socket buffer. When the server closes it sends a FIN,ACK packet to which the client replies only ACK. The socket from client side will not be closed until the client calls the close method itself too. The connection is then "Half-Open".</p>
<p... | python|sockets | 1 |
347 | 53,630,915 | How to extract time from datetime module and increment it | <p>I am trying to increment time. For that I stripped time from datetime and tried to add that. But it throws an exception. What is wrong here?</p>
<pre><code>st_time = datetime.datetime.strptime(st_time, '%H:%M:%S').time()
en_time = datetime.datetime.strptime(en_time, '%H:%M:%S').time()
while st_time < en_time:
... | <p>You need full datetime objects. Not just time. This is a design constraint to forbid wrapping around of time, guaranteeing that </p>
<pre><code>b = a + delta
a == b - delta
</code></pre>
<p>which would be violated if delta became bigger than 24h. </p> | python|file|datetime|counter | 1 |
348 | 53,498,097 | Sampling points from multiple Gaussians | <p>If I have one Gaussian with center=[x, y] and std=z I can sample one point using:</p>
<pre><code>np.random.normal(loc=[x, y], scale=std)
</code></pre>
<p>But if I'm given two Gaussians with centers=[[x1, y1], [x2, y2]] and stds=[z1, z2] how can I sample points from these Gaussians together (or for n Gaussians)</p> | <p>You could just loop,</p>
<pre><code>import numpy as np
x1 = 0.; y1=0.; z1 = 1.
x2 = 1.; y2=0.; z2 = 1.
centers=[[x1, y1], [x2, y2]]
stds=[z1, z2]
np.random.seed(1)
smpl = []
for c, std in zip(centers, stds):
smpl.append(np.random.normal(loc=c, scale=std))
print(smpl)
</code></pre>
<p>but passing as lists al... | python|numpy | 0 |
349 | 54,954,191 | How to import the numpy module on AWS lambda? | <p>I am new beginner for AWS system, I am doing my python project, want to use AWS lambda function to run my serverless python program, I have all my resource on AWS S3 bucket, I would like to simply take one of my images from S3 bucket (let's say source-bucket), turn it to grey color and save it back to the other S3 b... | <p><strong>Method 1</strong></p>
<p>Run this command in your project root directory</p>
<pre><code>pip install --target="." package_name
</code></pre>
<p>Zip your project folder and upload it on AWS</p>
<p><strong>Method 2</strong></p>
<p><a href="https://gist.github.com/joseph-zhong/372a47bb618111dcd2c81008d00357... | python|numpy|aws-lambda|serverless | 0 |
350 | 33,135,942 | Cannot get the js file under the static folder in Flask | <p>It all works in my local server, but when others try to deploy what I have done to the server, it fails.</p>
<p>the file system is the server something like:</p>
<pre><code>SERVER_FOLDER
--homepage
----static
----templates
------404.html
----app.py
----config.py
</code></pre>
<p>for example: The ser... | <p>Build toward your solution:</p>
<ol>
<li><p>Get flask serving image files from static</p>
<p>Put an image in the static directory and call it from your browser: <a href="http://yoursite/static/some_image_there.jpg" rel="nofollow">http://yoursite/static/some_image_there.jpg</a></p>
<p>Plug away until that works.<... | javascript|python|flask|static | 0 |
351 | 73,711,678 | Python - Pivot Table : Count the Occurrence of Value based on the Last Index | <p>could you help me how I can count the occurence of the last index in pivot table?</p>
<p>Raw data
<a href="https://i.stack.imgur.com/7LPjS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7LPjS.png" alt="enter image description here" /></a></p>
<pre><code>Here is my code -- but the last column is r... | <p>To get the expected count for column 'G', I included columns 'A'-'D' as indices and count of 'G' as follows:</p>
<pre><code>pd.pivot_table(df, index=['A','B','C','D'],values='G',aggfunc={'G': ['count']})
</code></pre>
<p>Here is the resulting pivot table, where the expected count is shown:</p>
<p><a href="https://i.... | python|indexing|count|pivot|pivot-table | 0 |
352 | 52,775,450 | Converting Values of series with dictionary values to DataFrame. Not the Series itself | <p>I have series which looks like this:</p>
<pre><code>d1 = {'Class': 'A', 'age':35, 'Name': 'Manoj'}
d2 = {'Class': 'B', 'age':15, 'Name': 'Mot'}
d3 = {'Class': 'B', 'age':25, 'Name': 'Vittoo'}
ser = [d1, d2, d3]
dummy = pd.Series(ser)
dummy
0 {'Class': 'A', 'age': 35, 'Name': 'Manoj'}
1 {'Class': 'B', 'ag... | <p>Use <code>DataFrame</code> constructor instead <code>Series</code> constructor:</p>
<pre><code>d1 = {'Class': 'A', 'age':35, 'Name': 'Manoj'}
d2 = {'Class': 'B', 'age':15, 'Name': 'Mot'}
d3 = {'Class': 'B', 'age':25, 'Name': 'Vittoo'}
ser = [d1, d2, d3]
df = pd.DataFrame(ser)
print (df)
Class Name age
0 ... | python|python-3.x|pandas | 2 |
353 | 40,749,442 | Add matrices with different labels and different dimensions | <p>I have two large square matrices ( in two CSV files). The two matrices may have a few different labels and different dimensions.
I want to add these two matrices and retain all labels. How do I do this in python?</p>
<p>Example:</p>
<p>{a, b, c ... e} are labels. </p>
<pre><code> a b c d ... | <p>use the <code>add</code> method with the parameter <code>fill_value=0</code></p>
<pre><code>X.add(Y, fill_value=0).fillna(0)
</code></pre>
<p><a href="https://i.stack.imgur.com/9o7gS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9o7gS.png" alt="enter image description here"></a></p> | python|pandas|matrix | 1 |
354 | 25,961,545 | Iterate over columns of a NumPy array and elements of another one? | <p>I am trying to replicate the behaviour of <code>zip(a, b)</code> in order to be able to loop simultaneously along two <code>NumPy</code> arrays. In particular, I have two arrays <code>a</code> and <code>b</code>:</p>
<pre><code>a.shape=(n,m)
b.shape=(m,)
</code></pre>
<p>I would like to get for every loop a colum... | <p>You can still use <code>zip</code> on numpy arrays, because they are iterables.</p>
<p>In your case, you'd need to transpose <code>a</code> first, to make it an array of shape <code>(m,n)</code>, i.e. an iterable of length <code>m</code>:</p>
<pre><code>for a_column, b_element in zip(a.T, b):
...
</code></pre> | python|arrays|numpy | 1 |
355 | 34,844,423 | Index lookup for calculation | <p>This is a follow-up of the following question: <a href="https://stackoverflow.com/questions/34735915/pandas-dataframe-window-function">Pandas DataFrame Window Function</a></p>
<pre><code> analysis first_pass fruit order second_pass test units highest \
0 full 12.1 apple 2 20.1 ... | <p>You could use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.sign.html" rel="nofollow"><code>np.sign()</code></a>:</p>
<pre><code>second_pass = df.groupby(['test', 'analysis']).apply(lambda x: {fruit: int(np.sign(x.loc[x.fruit==fruit, 'second_pass'].iloc[0] - x.loc[x.fruit==fruit, 'first_... | python|numpy|pandas | 0 |
356 | 51,162,409 | append many string in list seperated by split() | <p>If I write this code:</p>
<pre><code>b=list()
b.append(input())
print(b)
</code></pre>
<p>Simply the output will be:</p>
<pre><code>["My text"]
</code></pre>
<p>But i want output like that:</p>
<pre><code>["My","text"]
</code></pre>
<p>so I wrote this code:</p>
<pre><code>b=list()
b.append(input("Enter your t... | <p>You can simply write</p>
<pre><code>b = input("Enter your text: ").split()
</code></pre> | python-3.x | 3 |
357 | 55,859,199 | GDAL installation error "error: command 'x86_64-linux-gnu-gcc' failed with exit status 1" | <p>I'm trying to install GDAL with python.But it failed with error.</p>
<p>The command I use is <code>pip install GDAL</code>. </p>
<pre><code> x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-securit... | <p>Here is the answer I found that worked:</p>
<p>"you might have to change the gdal version to the version installed on your host. So I had to do this since I have gdal==1.11.2 on my host:"</p>
<pre><code>pip install gdal==1.11.2 --global-option=build_ext --global-option="-I/usr/include/gdal/"
</co... | python|gdal | 2 |
358 | 55,782,147 | How can i send data to a database from a view in Django? | <p>I created a form in my Django project, i would now like to have this form interact with a database. </p>
<p>Basically, when the user inputs some data, it must be sent to a database. Note: i already have a database in my django project, i defined it on my <strong>settings.py</strong>, but i must not send the data to... | <p>You need to define the second database in settings, see:
<a href="https://docs.djangoproject.com/fr/2.2/topics/db/multi-db/" rel="nofollow noreferrer">https://docs.djangoproject.com/fr/2.2/topics/db/multi-db/</a></p>
<p>Then you will just save the form in a particular database like this:
<code>form.save(using='data... | python|django|database | 1 |
359 | 50,138,795 | Split Multiple Values into New Rows | <p>I have a dataframe where a few columns may have multiple values in a single observation. Each observation in these rows has a "/" at the end of the observation, regardless of whether or not there are multiple. This means that some of the values look like this: 'OneThing/' while others like this: 'OneThing/AnotherThi... | <p>Your method would work (I think) if you use <code>df['column_of_interest'] = df['column_of_interest'].str.rstrip('/')</code>, as it would get rid of that annoying <code>/</code> at the end of your observations. However, the loop is inneficient, and the way you have it, requires that you know how many observations yo... | python|python-3.x|pandas|split|append | 1 |
360 | 66,351,420 | Python condition to append json items | <p>I have no experience with python, just started looking into this week:</p>
<pre><code>messages = []
msg_list = ticket.message
for message in msg_list:
for item in msg_list:
item_json = json.loads(message.body)
tmp_item.date = item_json['date']
tmp_item.time = item_json['time']
tmp_item.author = ite... | <p>What you refer to as json data (after parsing) is actually a dict in python.
To check whether a key exists in a dictionary the most common way is to use <code>in</code> operator</p>
<pre class="lang-py prettyprint-override"><code>if 'key' in dictionary:
print(dictionary['key']) # if key exists
else:
print(&q... | python|json | 1 |
361 | 66,647,787 | AttributeError: can't set attribute when connecting to sqlite database with flask-sqlalchemy | <p>I've been learning the flask web application framework and feel quite comfortable with it. I've previously built a simple to do app that worked perfectly. I was working on the same project, but trying to implement it using TDD. I've encountered an error with the database that I've never seen before and don't know ho... | <h2>Edit</h2>
<p>If you're experiencing this, upgrading Flask-SQLAlchemy to >= 2.5 should resolve the issue per <a href="https://github.com/pallets/flask-sqlalchemy/issues/910#issuecomment-802098285" rel="noreferrer">https://github.com/pallets/flask-sqlalchemy/issues/910#issuecomment-802098285</a>.</p>
<p>Pinning SQ... | python|sqlalchemy|flask-sqlalchemy | 44 |
362 | 64,090,531 | Pick a Random Images and Do PIL for Watermark | <p>I've error when i pick a random image in a folder and i want to edit with PIL.</p>
<p>My code is</p>
<pre><code>import os
import random
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
def watermark_text(input_image_path,
output_image_path,
text, pos):
... | <p>i was careless about this, I should have written like this</p>
<pre><code>import os
import random
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
def watermark_text(input_image_path,
output_image_path,
text, pos):
photo = Image.open(input_image_pat... | python|python-imaging-library | 0 |
363 | 53,085,769 | Deploying static files for a Wagtail application on Divio | <p>I'm struggling to understand how I can implement my static files live. This is my first project I'm trying to deploy so it's possible I've missed something, and I'm finding it hard to understand which documentation is best to follow here - Wagtail, Divio or Django?</p>
<p>I can view my website with the localhost fi... | <p>In a Divio Cloud project, the settings for things like static files handling and <code>DEBUG</code> are managed automatically according to the server environment (Live, Test or Local). </p>
<p>See the table in <a href="http://docs.divio.com/en/latest/how-to/local-in-live-mode.html" rel="nofollow noreferrer">How to ... | python|django|wagtail|divio | 0 |
364 | 53,154,023 | How to acess matrix's elements and pass matrix as function argument? | <p>My program is supposed to simulate a Bingo game. It receives as input a 5X5 matrix (the Bingo card), the number of elements(which are integers) it should verify whether they are on the card and the series of elements, one by one. The goal is to verify whether or not each element is in the matrix: if affirmative, the... | <p>My take on it, I use atom text editor for my python programming so I don't have <code>input()</code> functions so I had to randomize my bingo array</p>
<pre><code>import random
import numpy as np
m=5 #lines
n=5 #columns/rows
mat=[]
bingo_numbers = np.linspace(1,n*m,n*m,dtype=int)
remaining_... | python|matrix|multidimensional-array|nested-lists | 0 |
365 | 65,215,182 | Scrape table from email and write to CSV (Removing \r\n) - Python | <p>I'm trying to scrape the table from an email and remove any special characters (\r\n etc) before writing to a csv file.</p>
<p>I've managed to scrape the data however <strong>the columns are wrapped in '\r\n' which I cannot remove</strong> (I'm new to this)</p>
<p>Table attempting to scrape:</p>
<p><a href="https://... | <p>to remove those, you'd want to use <code>.strip()</code> on those strings. So try:</p>
<pre><code>tab_data = [[item.text.strip() for item in row_data.select("td")]
for row_data in table_tag.select("tr")]
</code></pre>
<p>But could I suggest, just let pandas parse the table from the ht... | python|beautifulsoup | 1 |
366 | 65,433,625 | What does a , operator do when used in the right hand side of a conditional? | <pre><code>a = 10
b = 20
c = 30
if(a > b,c):
print('In if')
else:
print('In else')
</code></pre>
<p>Someone posted the above piece of code, and asked why the above always results in 'In if', being printed regardless of the values of b and c.</p>
<p>Although this seems like poor programming style, I am curiou... | <p><code>a > b, c</code> is the tuple <code>((a > b), c)</code>.</p>
<p>So if <code>a=10, b=20, c=30</code>, then we're asking if the tuple <code>(False, 30)</code> is <a href="https://stackoverflow.com/questions/39983695/what-is-truthy-and-falsy-how-is-it-different-from-true-and-false">truish</a>. All non-empty ... | python|python-3.x | 5 |
367 | 65,174,223 | Python: understanding lambda operations in a function | <p>Suppose I have a function designed to find the largest <code>Y</code> value in a list of dictionaries.</p>
<pre><code>s1 = [
{'x':10, 'y':8.04},
{'x':8, 'y':6.95},
{'x':13, 'y':7.58},
{'x':9, 'y':8.81},
{'x':11, 'y':8.33},
{'x':14, 'y':9.96},
{'x':6, 'y':7.24},
{'x':4, 'y':4.26},
... | <p><code>y</code> is a function, where the function is defined by the <code>lambda</code> statement. The function accepts a dictionary as an argument, and returns the value at key <code>'y'</code> in the dictionary.</p>
<p><code>min(list_of_dicts, key=y)</code> returns the dictionary from the list with the smallest val... | python|function|lambda | 1 |
368 | 71,798,291 | ElasticSearch ImportError: cannot import name 'Mapping' from 'elasticsearch.compat' | <p>I get this import error when trying to run</p>
<pre><code>from elasticsearch_dsl import Search, A
</code></pre>
<p>Full traceback</p>
<pre><code>ImportError: cannot import name 'Mapping' from 'elasticsearch.compat' (C:\Users\SANA\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\loc... | <p>You must have installed elasticsearch_dsl. Install elasticsearch-dsl.</p>
<p>Try doing :</p>
<pre><code>pip uninstall elasticsearch_dsl
pip install elasticsearch-dsl
</code></pre>
<p>this should work.</p> | python|elasticsearch | 2 |
369 | 10,260,994 | psycopg2 out of shared memory and hints of increase max_pred_locks_per_transaction | <p>While inserting a lot of data into postgresql 9.1. using a Python script, we are getting the following error on this query:</p>
<pre>
X: psycopg2.ProgrammingError in /home/hosting/apps/X
X_psycopg.py:162 in : Execute 'execute' (
SELECT * FROM xml_fifo.fifo
WHERE type_... | <p>PostgreSQL added new functionality to <code>SERIALIZABLE</code> transactions in version 9.1, to avoid some serialization anomalies which were previously possible at that isolation level. The error you are seeing is only possible when using these new serializable transactions. Some workloads have run into the issue... | python|postgresql|isolation-level|postgresql-9.1 | 8 |
370 | 10,309,794 | How to host Django1.3.1 in Apache2.2? | <p>I am Using python 2.7.2,Django 1.3.1, Apache 2.2.22 on WindowsXP(win32). By the documentation i found <a href="http://pradyumnajoshi.wordpress.com/2009/06/09/setting-up-mod_wsgi-for-apache-and-django-on-windows/" rel="nofollow">here</a> i did the step by step, but when the directory section is given</p>
<pre><code>... | <p>I got it solved, it was the version problem, as i worked with Apache 2.2.21 instead of Apache 2.2.22, its working. i followed the step in this <a href="http://sdtidbits.blogspot.in/2009/10/deploying-django-application-on-apache.html" rel="nofollow">link</a>. </p>
<p>Install Python 2.7.2, Django 1.3.1 and Apache2... | python|windows|django|apache2|django-wsgi | 3 |
371 | 5,229,783 | Where to Put Python Utils Folder? | <p>I've a whole bunch of scripts organized like this:</p>
<pre><code>root
group1
script1.py
script2.py
group2
script1.py
script2.py
group3
script1.py
script2.py
utils
utils1.py
utils2.py
</code></pre>
<p>All the scripts*.py use functions inside the utils folder. At the moment, ... | <p>Make all your directories importable first i.e. use <code>__init__.py</code>.
Then have a top level script that accepts arguments and invokes scripts based on that.</p>
<p>For long term what Keith has mentioned about distutils holds true. Otherwise here is a simpler (sure not the best) solution. </p>
<p><strong>O... | python|code-organization | 5 |
372 | 62,894,103 | python file operation slowing down on massive text files | <p>This python code is slowing down the longer it runs.</p>
<p>Can anyone please tell me why?</p>
<p>I hope it is not reindexing for every line I query and counting from start again, I thought it would be some kind of file-stream ?!</p>
<p>From 10k to 20k it takes 2 sec. from 300k to 310k it takes like 5 min. and getti... | <p>actually <em>in</em> operation for list is not the same every time in fact it is O(n) so it gets slower and slower as you add</p>
<p>you want to use set
See here <a href="https://wiki.python.org/moin/TimeComplexity" rel="nofollow noreferrer">https://wiki.python.org/moin/TimeComplexity</a></p>
<p>You didn't ask for t... | python|list|text-processing | 1 |
373 | 61,691,079 | Request form flask is empty in GET request | <p>I'm trying to make a search form to get some data from my Api but the request form always return empty. I've read the other post with a similar problem but I didn't find the answer.</p>
<p>I just want to make an search from the main page and display de second page if the button of the form was pressed with some con... | <p>I assume that you want the data from the form. As you are using a GET request, in flask you should acces them by this code</p>
<pre><code>request.args['key']
</code></pre>
<p>You can use <code>reequest.form[]</code> when you are handling a POST request</p> | python|python-3.x|flask|request|frontend | 1 |
374 | 61,820,909 | Dataframe Boxplot in Python displays incorrect whiskers | <p>In this simple example it gives wrong min and max whis.</p>
<pre><code>df = pd.DataFrame(np.array([1,2,3, 4, 5]),
columns=['a'])
df.boxplot()
</code></pre>
<p>Outcome:</p>
<p><a href="https://i.stack.imgur.com/JcCxc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JcCxc.png" a... | <p><a href="https://en.wikipedia.org/wiki/Box_plot#Example_without_outliers" rel="nofollow noreferrer">Source</a></p>
<blockquote>
<p>From above the upper quartile, a distance of 1.5 times the IQR is measured out and a whisker is drawn up to the largest observed point from the dataset that falls within this distance... | python|pandas|plot|boxplot | 1 |
375 | 60,670,566 | Scipy curve_fit confusion using bounds and initial parameters on simple data | <p>while I've gotten great fits for other datasets, for some reason the following code is not working for a relatively simple set of points. I've tried both a decaying exponential and power, along with initial parameters and bounds. I believe this is exposing my deeper misunderstanding; I appreciate any advice.</p>
<p... | <p>This worked for me. There were a couple issues. Including my comment. There is also a 'divide by zero' error in your xlist, so I avoided that by adding 0.01 to <code>xlist</code>, and increasing the density of points so the curve is rounded.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from sci... | python|scipy|curve-fitting | 2 |
376 | 60,523,176 | pandas cumsum replace the result calculated by cumsum with the content at the specified position | <p>data</p>
<pre><code>data = [
{"content": "1", "title": "app sotre", "info": "", "time": 1578877014},
{"content": "2", "title": "app", "info": "", "time": 1579877014},
{"content": "3", "title": "pandas", "info": "", "time": 1582877014},
{"content": "12", "title": "a", "info": "", "time": 1582876014},... | <p>I suggest loop by zipped original list <code>data</code> with <code>Series</code> <code>cdata</code> and then set new values:</p>
<pre><code>cdata = pd.to_numeric(s.str.get('content'), errors='coerce').cumsum()
print (cdata)
0 1.0
1 3.0
2 6.0
3 18.0
4 51.0
5 67.0
6 NaN
dtype: float64
for o... | python|pandas | 0 |
377 | 64,319,469 | Creating a new DataFrame out of 2 existing Dataframes with Values coming from Dataframe 1? | <p>I have 2 DataFrames.</p>
<p>DF1:</p>
<pre><code>movieId title genres
0 1 Toy Story (1995) Adventure|Animation|Children|Comedy|Fantasy
1 2 Jumanji (1995) Adventure|Children|Fantasy
2 3 Grumpier Old Men (1995) Comedy|Romance
3 4 Waiting to Exhale (1995) Comedy|Drama|Romance
4 5 Father of t... | <p>The problem consists of essentially 2 parts:</p>
<ol>
<li>How to transpose <code>df2</code>, the sole table where user ratings comes from, to the desired format. <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot_table.html" rel="nofollow noreferrer">pd.DataFrame.pivot_table</... | pandas|dataframe|concatenation | 1 |
378 | 64,529,641 | how restarting game on pygame works | <p>how can I restart the game with user input? i searched all over the place and i wasnt able to discover how i can restart my game, i just want to press <strong>ESC</strong> and my game restart, after knowing how to do that i will implement a button, but how can I restart my game? this is my main loop:</p>
<pre class=... | <p>I think it should be something like this</p>
<pre><code># imports
restart = False
while running:
if restart:
# create instance of all objects used
# score = 0
# Default values should be initialised
# Keyboard events go here
# code for restarting
if event.key == pygame.K_ESCAPE... | python|python-3.x|loops|while-loop|pygame | 4 |
379 | 64,195,565 | Python does deepcopy of an object duplicate its static variables? | <p>I'm used to code in C and Java and I just got into Python.</p>
<p>I have a Class Obj that has 2 static class variables <code>a</code> and <code>b</code> and has 2 instance variables <code>x</code> and <code>y</code>. I have an instance of Obj <code>obj</code>. During the program I need to make copies of <code>obj</c... | <p>Python has a specific way of working with static fields of classes. If you change the static field of class accessing through an object you will change the value only for this object.</p>
<pre><code>obj.a = foo # changes the field a only for obj
</code></pre>
<p>But if you change field accessing through the class it... | python|static|static-variables | 1 |
380 | 70,284,076 | Is `asyncio.open_connection(host, port)` blocking? | <p>I am new to asyncio library and am struggling with the behavior of asyncio.open_connection. I have created a task and has <code>await asyncio.open_connection(host, port)</code>within it. I want the call to <code>open_connection</code> blocking, that is, don't yield to the event loop until the connection is establish... | <ol>
<li>Yes, it yields to event loop.</li>
</ol>
<p>In asyncio's source code:</p>
<pre class="lang-py prettyprint-override"><code>async def open_connection(host=None, port=None, *,
limit=_DEFAULT_LIMIT, **kwds):
"""A wrapper for create_connection() returning a (reader, writ... | python-3.x|async-await|python-asyncio | 0 |
381 | 70,575,042 | Show django-debug-toolbar to specific users | <p>I have seen <a href="https://stackoverflow.com/questions/6548947/how-can-django-debug-toolbar-be-set-to-work-for-just-some-users/6549317#6549317">this question</a> over the issue of DjDT. However when I implement it gives an error.</p>
<pre><code>'WSGIRequest' object has no attribute 'user'
</code></pre>
<p>This is ... | <p>I got this working by putting the <code>debugtoolbarMiddleware</code> after the <code>AuthenticationMiddleware</code>
Thank you @Flimm for taking me towards that direction.</p> | python|django|debugging | 0 |
382 | 63,536,827 | Transform a HTML in CSV Using Python and Javascript | <p>I have a doubt, I'm Working in a program that need do take data from website, but that site doesn't have any API.</p>
<p>So I'm thinking to combine JavaScript and Python.</p>
<p>I'm using JavaScript to transform HTML in this data:</p>
<pre><code><html xmlns="http://www.w3.org/1999/xhtml"><head>... | <pre><code>const str = `<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>BLUE - Amil Ltda14/07/2020;;102636;Name censured;213113;10101039;1;Única;20/09/2020;102636;HCRIANÇASJ;83,00; <br>BLUE18 - Amil Ltda21/07/2020;;102636;Name Censured Again;213029;10101039;1;Única;... | javascript|python|html|selenium|csv | 0 |
383 | 66,218,471 | Can Plotly timeline be used / reproduced in Jupyter Notebook Widget? | <p>The plotly plotly.express.timeline is marvelous, but creates it's own figure. It seems like I need to embed this visual in a FigureWidget to get it to play nice with the layout in a Jupyter Notebook. So I am trying to re-create the plot using the plotly.graph_objects.Bar() that px.timeline() is built upon.</p>
<p>... | <p>I can't answer how to embed the timeline in a <code>FigureWidget</code>, but I think I have the answer to your original problem of getting the timeline to play nicely with the jupyter notebook layout. I'm guessing you want to be able to update the timeline interactively?</p>
<p>I have gotten around this problem by e... | python|pandas|jupyter-notebook|plotly|plotly-express | 0 |
384 | 69,242,407 | Cannot convert int string into chr string | <p>I am very new to Python coding and am currently taking courses on Grok Learning.
There is a specific question I am stuck on, I have tried everything I can think of. It is probably obvious as hell but I am completely braindead with this one. Here is my code and error message:</p>
<pre><code>values = int(input("C... | <p>You are converting the inputted <code>str</code> into an <code>int</code>. You need to keep it as a <code>str</code> in order to split it, so remove the "<code>int(...)</code>" from line 1. You need to convert each individual value into an <code>int</code> in the <code>for</code> loop instead. So:</p>
<pre... | python | 1 |
385 | 72,624,965 | How do I get "@app.before_request" to run only once? | <p>I have a flask web app and I wanted a function to be called every time the page loads. I got it to work using "@app.before_request", my only problem is, I have 4 requests that are being made on every page load.</p>
<p>Here's my logs in my console</p>
<pre><code>127.0.0.1 - - [14/Jun/2022 17:54:47] "GE... | <p>@app.before_first_request is what solved it!</p> | python|flask | 0 |
386 | 68,216,397 | Converting dataframe to list of tuples changes datetime.datetime to int | <p>I have some code I wrote using Pandas which does the exact processing I want, but unfortunately is slow. In an effort to speed up processing times, I have gone down the path of converting the dataframe to a list of tuples, where each tuple is a row in the dataframe.</p>
<p>I have found that the datetime.datetime ob... | <p>Change the dtype of your column <code>start_time</code> to convert <code>Timestamp</code> to an integer (nanoseconds):</p>
<pre><code>df = pd.DataFrame({'start_time': ['2021-06-02 08:16:33']}) \
.astype({'start_time': 'datetime64'})
>>> df
start_time
0 2021-06-02 08:16:33
>>> df... | python|pandas|datetime | 0 |
387 | 72,952,555 | Python : making instances of a class with required parameters dynamically | <p>I have seen other links similar to my problem but is have another problem.
In a part of my code in a function I need to pass the class and in that function I want to make instances of that class dynamically.</p>
<p>For example here is the class and calling the function:</p>
<pre><code>class obj:
def __init__(sel... | <p>Sounds like you want something like this:</p>
<pre><code>def convert_data(obj_cls, raw_data, column_names, column_types):
"""
Parse raw_data (an iterable of comma-separated strings) into obj_cls objects.
:param raw_data: Raw data of strings.
:param column_names: Column names (obj_cls a... | python | 1 |
388 | 62,176,929 | Initialize Vaex Dataframe Column to a value | <p>I want to initialize a column of my vaex dataframe to the int value 0</p>
<p>I have the following:</p>
<pre><code>right_csv = "animal_data.csv"
vaex_df = vaex.open(right_csv,dtype='object',convert=True)
vaex_df["initial_color"] = 0
</code></pre>
<p>But this will throw an error for line 3 complaining about how v... | <p>Good question, the most memory efficient way now (vaex-core v2.0.2, vaex v3) is:</p>
<pre><code>df['test'] = vaex.vrange(0, len(df)) # add a 'virtual range' column, which takes no memory
df['test'] = df['test']* 0 + 111 # multiply by zero, and add the initial value
</code></pre>
<p>We should probably have a more... | python|vaex | 2 |
389 | 62,052,289 | Gcc error, No such file or directory "Python.h" -- installing pyAudio on centOS7 | <p>I have python 3.6.8 installed on CentOS7 and I'm trying to install pyaudio with </p>
<blockquote>
<p>sudo python3.6 -m pip install pyaudio</p>
</blockquote>
<p>This format worked to install a number of other things right beforehand, but if I try to use it here i get the following error</p>
<pre><code>src/_porta... | <blockquote>
<p>fatal error: Python.h: No such file or directory</p>
</blockquote>
<p>It looks like <code>pyaudio</code> is compiling some C code who require <code>Python.h</code>, to fix your issue check this answer <a href="https://stackoverflow.com/a/21530768/9799292">https://stackoverflow.com/a/21530768/9799292<... | python-3.x|centos7|pyaudio|portaudio | 0 |
390 | 73,280,534 | Python - Delete a file with a certain character in it | <p>I have a lot of duplicate files in a folder and I would like to delete the duplicate. As of now i have <code>FileA.jpg</code> and <code>FileA(1).jpg</code>. I would like to make a short script that open a directory and finds any file name that has a <code>(</code> and then delete it.</p>
<p>How would I do this?</p> | <p>You can use <code>OS</code> package.</p>
<pre><code>import os
for filePath in os.listdir("/path/to/dir"):
if "(" in filePath:
os.remove(filePath)
</code></pre> | python | 1 |
391 | 59,581,746 | Why does VS-Code Autopep8 format 2 white lines? | <pre><code>print("Hello")
def world():
print("Hello")
world()
</code></pre>
<p>Gets corrected to:</p>
<pre><code>print("Hello")
def world():
print("Hello")
world()
</code></pre>
<p>I have tried to:</p>
<ul>
<li>Reinstall Virtual Studio Code</li>
<li>Reinstall Python 3.8</li>
<li>Computer Reboot</li>
<... | <p>Because auto<strong>pep8</strong> follows <a href="https://www.python.org/dev/peps/pep-0008/#blank-lines" rel="nofollow noreferrer"><strong>PEP8</strong></a> which suggests 2 blank lines around top-level functions.</p>
<blockquote>
<p>Surround top-level function and class definitions with two blank lines.</p>
</b... | python|format|autopep8 | 2 |
392 | 59,880,311 | Debugging Python: Why don't my variables update? | <p>I'm using PyCharm 2019.2 Professional, Win 10 x64, Python 3.7, and IPython 7.11.1.</p>
<p>When running a script in debug mode and hitting a breakpoint, I can execute statements in the IPython prompt. However, I (sometimes?) cannot change the variables values.</p>
<p>For example, I have a dataframe and check on som... | <p>I have encountered this bug as well. I have always assumed it is a PyCharm bug not Python. Might be worth raising a bug with JetBrains, think you can do that here:</p>
<p><a href="https://youtrack.jetbrains.com/issues/PY" rel="nofollow noreferrer">https://youtrack.jetbrains.com/issues/PY</a></p> | python|pandas | 0 |
393 | 25,036,498 | Is it possible to limit Flask POST data size on a per-route basis? | <p>I am aware it is possible to <a href="http://flask.pocoo.org/docs/patterns/fileuploads/">set an overall limit on request size</a> in Flask with:</p>
<pre><code>app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
</code></pre>
<p>BUT I want to ensure that one specific route will not accept POST data over a certain ... | <p>You'll need to check this for the specific route itself; you can always test the content length; <a href="http://werkzeug.pocoo.org/docs/wrappers/#werkzeug.wrappers.CommonRequestDescriptorsMixin.content_length"><code>request.content_length</code></a> is either <code>None</code> or an integer value:</p>
<pre><code>c... | python|python-3.x|flask | 40 |
394 | 25,336,314 | Win7 query hardware keyboard Caps Lock current state | <p>I'm writing a Tkinter application with Python 2.7 on OS windows7.<br>
I want to query the current state of the hardware keyboard Caps Lock without capturing keyboard events, sending them anywhere, or toggling it. </p>
<p>Does the OS keyboard interrupt handler take on a modal state when the user physically?</p>
<p>... | <p><code>GetKeyState</code> is the Windows API that you would use to find out the current state of the capslock key in C/C++, so using ctypes you could do something like this:</p>
<pre><code>import ctypes
VK_CAPITAL = 0x14
if ctypes.windll.user32.GetKeyState(VK_CAPITAL) & 1:
print "Caps Lock On"
else:
pr... | python|tkinter | 3 |
395 | 25,278,383 | How do I get values from a dictionary run them through an equation and return the key with the greatest value | <p>So my assignment has been easy up to this point. Useing Python 3</p>
<p>GetSale - Finds the maximum expected value of selling a stock. The expected sale value of a stock is the current profit minus the future value of the stock:
Expected Sale value = ( ( Current Price - Buy Price ) - Risk * CurrentPrice ) * Shares
... | <blockquote>
<p>How do I get values from a dictionary</p>
</blockquote>
<pre><code>d.values()
</code></pre>
<blockquote>
<p>run them through an equation</p>
</blockquote>
<pre><code>(equation(value) for value in d.values())
</code></pre>
<blockquote>
<p>and return the key with the greatest value</p>
</blockqu... | python|python-3.x|dictionary | 2 |
396 | 70,816,583 | Can't load audio on pygame - Pygame error when loading audio: Failed loading libvorbisfile-3.dll: The specified module could not be found | <p>I've been using <code>pygame 2.0.1</code> consistently for months. Today, after I upgraded to the latest version (2.1.2), I started getting this error when trying to load an audio file:</p>
<pre><code>'pygame.error: Failed loading libvorbisfile-3.dll: The specified module could not be found'.
</code></pre>
<p>Things... | <p>I solved the issue by uninstalling Python, installing the latest version (3.10.2), creating a new virtual environment, upgrading <code>pip</code> to the latest version (21.2.4) and then installing <code>pygame</code> via <code>pip</code>.</p> | python|dll|pygame | 0 |
397 | 71,070,860 | PyQt5.uic.exceptions.NoSuchWidgetError: Unknown Qt widget: KPIM.AddresseeLineEdit | <h1>Problem</h1>
<p>I am importing a .ui from pyqt5 inside a python3 file. In other projects my code worked fine but now I am receiving <code>PyQt5.uic.exceptions.NoSuchWidgetError: Unknown Qt widget: KPIM.AddresseeLineEdit</code></p>
<p>My code:</p>
<pre class="lang-py prettyprint-override"><code>import sqlite3
from P... | <p>It seems I was using <strong>not supported</strong> widgets by pyqt5. To solve it I just need to <code>replace</code> <code>KPIM::AddresseeLineEdit</code> by <code>QTextEdit</code> in the <code>.ui</code> file solves the problem</p> | python|python-3.x|qt|pyqt|pyqt5 | 0 |
398 | 60,205,551 | add count column in time series plot | <p>I want to plot the mean based on month and years. </p>
<p>My data have two columns (count, mean) and the date as index.</p>
<p>As shown here is a plot similar to my plot where x is years and y is mean </p>
<p><a href="https://i.stack.imgur.com/jns7z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.c... | <pre><code>idx = pd.date_range(start='1901-01-01', end='1903-12-31', freq='1M')
df = pd.DataFrame({"mean": np.random.random(size=(idx.size,)), "count": np.random.randint(0,10, size=(idx.size,))}, index=idx)
plt.figure()
ax = df['mean'].plot(figsize=(8,4))
for d,row in df.iterrows():
ax.annotate('{:.0f}'.format(row... | python|matplotlib | 1 |
399 | 2,980,196 | Change|Assign parent for the Model instance on Google App Engine Datastore | <p>Is it possible to change or assign new parent to the Model instance that already in datastore? For example I need something like this</p>
<pre><code>task = db.get(db.Key(task_key))
project = db.get(db.Key(project_key))
task.parent = project
task.put()
</code></pre>
<p>but it doesn't works this way because <code>ta... | <p>According to <a href="http://code.google.com/appengine/docs/python/datastore/keysandentitygroups.html#Entity_Groups_Ancestors_and_Paths" rel="noreferrer">the docs</a>, no:</p>
<blockquote>
<p>The parent of an entity is defined
when the entity is created, and cannot
be changed later.</p>
<p>...</p>
<... | python|google-app-engine|transactions|google-cloud-datastore | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.