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 against some string if and only if there was no match with linkExtractor.</p> <p>Thanks</p>
<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> and <code>settings.py</code> files are correct. what is the best view?</p> <pre><code>from django.shortcuts import HttpResponse from django.conf import settings from django.template import RequestContext, Template, Context def image1(request): # good because only the required context is rendered html = Template('&lt;img src="{{ STATIC_URL }}victoryDance.gif" alt="Hi!" /&gt;') ctx = { 'STATIC_URL':settings.STATIC_URL} return HttpResponse(html.render(Context(ctx))) def image2(request): # good because you don't have to explicitly define STATIC_URL html = Template('&lt;img src="{{ STATIC_URL }}victoryDance.gif" alt="Hi!" /&gt;') return HttpResponse(html.render(RequestContext(request))) def image3(request): # This allows you to load STATIC_URL selectively from the template end html = Template('{% load static %}&lt;img src="{% static "victoryDance.gif" %}" /&gt;') return HttpResponse(html.render(Context(request))) def image4(request): # same pros as image3 html = Template('{% load static %} &lt;img src="{% get_static_prefix %}victoryDance.gif" %}" /&gt;') return HttpResponse(html.render(Context(request))) def image5(request): html = Template('{% load static %} {% get_static_prefix as STATIC_PREFIX %} &lt;img src="{{ STATIC_PREFIX }}victoryDance.gif" alt="Hi!" /&gt;') return HttpResponse(html.render(Context(request))) </code></pre> <p>thanks for answers These views all work!</p>
<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 &lt;= 1.5:</p> <pre><code>from django.http import HttpResponse def my_image(request): image_data = open("/path/to/my/image.png", "rb").read() return HttpResponse(image_data, mimetype="image/png") </code></pre> <p>For django 1.5+ <code>mimetype</code> was replaced by <code>content_type</code>(so happy I'm not working with django anymore):</p> <pre><code>from django.http import HttpResponse def my_image(request): image_data = open("/path/to/my/image.png", "rb").read() return HttpResponse(image_data, content_type="image/png") </code></pre> <p>Also there's <a href="https://stackoverflow.com/questions/3003146/best-way-to-write-an-image-to-a-django-httpresponse/15832328">a better way</a> of doing things!</p> <p>Else, if you need a efficient template engine use Jinja2</p> <p>Else, if you are using Django's templating system, from my knowledge you don't need to define STATIC_URL as it is served to your templates by the "static" context preprocessor:</p> <pre><code>TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.static', 'django.core.context_processors.media', 'django.core.context_processors.request', 'django.contrib.messages.context_processors.messages', ) </code></pre>
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 the tutorial here : <a href="https://www.tensorflow.org/tutorials/load_data/images" rel="noreferrer">tensorflow guide to load image dataset</a></p> <p>Now, I need to split <code>labeld_ds</code> into three disjoint pieces : train, validation and test. I was going through the tensorflow API, but there was no example which allows to specify the split percentages. I found something in the <a href="https://www.tensorflow.org/datasets/api_docs/python/tfds/load" rel="noreferrer">load method</a>, but I am not sure how to use it. Further, how can I get splits to be stratified ?</p> <pre><code># labeled_ds contains multi class data, which is unbalanced. train_ds, val_ds, test_ds = tf.data.Dataset.tfds.load(labeled_ds, split=["train", "validation", "test"]) </code></pre> <p>I am stuck here, would appreciate any advice on how to progress from here. Thanks in advance.</p>
<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+validation', with_info=True) labeled_all_length = [i for i,_ in enumerate(labeled_ds)][-1] + 1 train_size = int(0.8 * labeled_all_length) val_test_size = int(0.1 * labeled_all_length) df_train = labeled_ds.take(train_size) df_test = labeled_ds.skip(train_size) df_val = df_test.skip(val_test_size) df_test = df_test.take(val_test_size) df_train_length = [i for i,_ in enumerate(df_train)][-1] + 1 df_val_length = [i for i,_ in enumerate(df_val)][-1] + 1 df_test_length = [i for i,_ in enumerate(df_test)][-1] + 1 print('Original: ', labeled_all_length) print('Train: ', df_train_length) print('Validation :', df_val_length) print('Test :', df_test_length) </code></pre>
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>def test_for_a_date_on_a_weekday(self): customer_type = "Regular" dates = ["16Mar2009(mon)"] self.assertEquals(self.hotel_reservation_system.find_cheapest_hotel(customer_type, dates), "Lakewood") </code></pre> <p><strong>2. A number following the word test with a docstring which explains the test.</strong></p> <pre><code>def test_1(self): """Tests the cheapest hotel when the date is on a weekday. """ customer_type = "Regular" dates = ["16Mar2009(mon)"] self.assertEquals(self.hotel_reservation_system.find_cheapest_hotel(customer_type, dates), "Lakewood") </code></pre> <p>Which option is much preferable, and if any of them what should I use?</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 function. This will allow the reader to get all necessary information if the name isn't clear enough OR if he doesn't really understand what the method does / how she does it.</p> <p>Conclusion : short and descriptive (snake_case) name with a docstring.</p>
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 between <code>-180.0</code> and <code>180.0</code>.</p>
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 &amp; 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 Fubo TV 3840 2 California 15-24 Female Hulu 54067 3 California 15-24 Female Netflix 11713 4 California 15-24 Female Sling TV 10642 </code></pre> <p>Dataset2:</p> <pre><code> City Age Gender Source Feeds 0 California 15-24 Female Blogs 150 1 California 15-24 Female Customsite 57 2 California 15-24 Female Discussions 28 3 California 15-24 Female Facebook Comment 555 4 California 15-24 Female Google+ 19 </code></pre> <p>Expected resulting dataset:</p> <pre><code> City Age Gender Source Count California 15-24 Female Amazon Prime Video 14629 California 15-24 Female Fubo TV 3840 California 15-24 Female Hulu 54067 California 15-24 Female Netflix 11713 California 15-24 Female Sling TV 10642 California 15-24 Female Blogs 150 California 15-24 Female Customsite 57 California 15-24 Female Discussions 28 California 15-24 Female Facebook Comment 555 California 15-24 Female Google+ 19 </code></pre> <p>Note : Feeds/Count signify the same meaning. So okay to have either of them as the column name in the merged dataset.</p>
<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':'Count'})], ignore_index=True) print (df) City Age Gender Source Count 0 California 15-24 Female Amazon Prime Video 14629 1 California 15-24 Female Fubo TV 3840 2 California 15-24 Female Hulu 54067 3 California 15-24 Female Netflix 11713 4 California 15-24 Female Sling TV 10642 5 California 15-24 Female Blogs 150 6 California 15-24 Female Customsite 57 7 California 15-24 Female Discussions 28 8 California 15-24 Female Facebook Comment 555 9 California 15-24 Female Google+ 19 </code></pre> <p>Alternative with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.append.html" rel="nofollow noreferrer"><code>DataFrame.append</code></a> - not pure <a href="https://docs.python.org/3.5/tutorial/datastructures.html" rel="nofollow noreferrer"><code>python append</code></a>:</p> <pre><code>df = df1.append(df2.rename(columns={'Feeds':'Count'}), ignore_index=True) print (df) City Age Gender Source Count 0 California 15-24 Female Amazon Prime Video 14629 1 California 15-24 Female Fubo TV 3840 2 California 15-24 Female Hulu 54067 3 California 15-24 Female Netflix 11713 4 California 15-24 Female Sling TV 10642 5 California 15-24 Female Blogs 150 6 California 15-24 Female Customsite 57 7 California 15-24 Female Discussions 28 8 California 15-24 Female Facebook Comment 555 9 California 15-24 Female Google+ 19 </code></pre>
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.png', left=0, top=0) </code></pre> <p>when I do print I can see the right unicode:</p> <pre><code>bg_img u'La Pocati\xe8re.png' &gt;&gt;&gt; print bg_img La Pocatière.png </code></pre> <p>Not sure how I can bypass this issue?</p> <hr> <p>Answer: After doing lots research and in discussion with my colleague we were able to solve this issue by setting : text_encoding = 'utf-8' For some reason wand wasn't able to set it automatically</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></pre>
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 multiple dataframes (originally csv files) that have the <code>-999</code> values in different locations and I would like to apply the same method to all dataframes.</p>
<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.Value[df.groupId == df.groupId.value_counts().idxmax()][1:] # 4 4 # 5 5 # 6 6 # 7 2 # 8 7 # 9 8 # 10 9 # Name: Value, dtype: int64 </code></pre>
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(list) key = 0 for string in strings: if string not in my_dict.itervalues(): my_dict[key].append(string) key += 1 print my_dict </code></pre> <p>but it seems not to work because all of strings are added to the dictionary, like this:</p> <p><code>defaultdict(&lt;type 'list'&gt;, {0: ['val1'], 1: ['val2'], 2: ['val2'], 3: ['val3']})</code></p> <p>'val2' shouldn't be added and it should looks like this:</p> <p><code>defaultdict(&lt;type 'list'&gt;, {0: ['val1'], 1: ['val2'], 2: ['val3']})</code></p> <p>What am I doing wrong?</p>
<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>&gt;&gt;&gt; "val2" not in [["val1"], ["val2"]] True </code></pre> <p>To get the desired result, flat a list of lists into a list using <a href="https://docs.python.org/2/library/itertools.html#itertools.chain.from_iterable" rel="nofollow"><code>itertools.chain.from_iterable</code></a>,</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; "val2" not in itertools.chain.from_iterable([["val1"], ["val2"]]) False </code></pre> <hr> <p>The full source code for your case,</p> <pre><code>from collections import defaultdict import itertools strings = ["val1", "val2", "val2", "val3"] my_dict = defaultdict(list) key = 0 for string in strings: if string not in itertools.chain.from_iterable(my_dict.values()): # flat a list of lists into a list my_dict[key].append(string) key += 1 print(my_dict) # Output defaultdict(&lt;type 'list'&gt;, {0: ['val1'], 1: ['val2'], 2: ['val3']}) </code></pre>
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>settings.py</p> <pre><code>import os from decouple import config, Csv from dj_database_url import parse as dburl BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', default=False, cast=bool) ALLOWED_HOSTS = config('ALLOWED_HOSTS', default=[], cast=Csv()) default_dburl = 'sqlite:///' + os.path.join(BASE_DIR, 'db.sqlite3') DATABASES = { 'default': config('DATABASE_URL', default=default_dburl, cast=dburl), } </code></pre> <p>(...)</p> <pre><code>STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') </code></pre> <p>wsgi.py</p> <pre><code>import os from dj_static import Cling, MediaCling from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "integrafundaj.settings") application = Cling(MediaCling(get_wsgi_application())) </code></pre> <p>requirements.txt</p> <pre><code>dj-database-url==0.4.2 dj-static==0.0.6 Django==1.11.3 djangorestframework==3.7.7 easy-thumbnails==2.4.2 olefile==0.44 Pillow==4.3.0 python-decouple==3.1 pytz==2017.3 static3==0.7.0 Unidecode==0.4.21 gunicorn==19.4.1 psycopg2==2.7.1 </code></pre>
<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/img.jpg</strong> (static files were the same thing but with <em>static</em> instead of <em>media</em>).</p> <p>After this change, and after re-uploading the images to the new folder, everything worked fine! (remember to change myapp to the your app's name).</p>
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 across the series don't match up, and i really don't want to resort to duplicating values into time bins.</p> <p>So, given these 2 series:</p> <pre><code>S1: (1;100) (5;100) (10;100) S2: (4;150) (5;100) (18;150) </code></pre> <p>When added together, should result in:</p> <pre><code>ST: (1;100) (4;250) (5;200) (10;200) (18;250) </code></pre> <p>Logic:</p> <pre><code>x=1 s1=100, s2=None, sum=100 x=4 s1=100, s2=150, sum=250 (note s1 value from previous value) x=5 s1=100, s2=100, sum=200 x=10 s1=100, s2=100, sum=200 x=18 s1=100, s2=150, sum=250 </code></pre> <p>My current thinking is to iterate a sorted list of keys(x), keep the previous value for each series, and query each set if it has a new y for the x.</p> <p>Any ideas would be appreciated!</p>
<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 = next1 try: time1, next1 = next(S1) except StopIteration: end1 = True time1 = time2 if time == time2: value2 = next2 try: time2, next2 = next(S2) except StopIteration: end2 = True time2 = time1 yield time, value1 + value2 if end1 and end2: raise StopIteration S1 = ((1, 100), (5, 100), (10, 100)) S2 = ((4, 150), (5, 100), (18, 150)) for result in join_series(S1, S2): print(result) </code></pre> <p>It basically keeps the current value of S1 and S2, together with the next of S1 and S2, and steps through them based on which has the lowest "upcoming time". Should handle lists of different lengths to, and uses iterators all the way so it should be able to handle massive dataseries, etc, etc.</p>
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'} </code></pre> <p>The key and values are all string. I want this to look like the following:</p> <pre><code>{'New Year Day': 'Tuesday, January 1, 2019', 'Good Friday': 'Friday, March 30', 'New Year Day': 'Monday, January 1, 2018'} </code></pre> <p>I have tried to remove <code>\xa0</code> but was unsuccessful:</p> <pre><code> for key in data: key.replace('\xa0', '') print key </code></pre> <p>I think I will need to use the <code>(re.search(r'[12]\d{3}', key)).group[0]</code> regex for getting the year. But how will I remove it from the keys?</p>
<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", "")] = data.pop(i) print data </code></pre> <p>Hope this helped.</p>
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 wrong with the data. </p> <p>Is there anything wrong with my code? Any suggestions are highly appreciated.</p> <p>here is my code:</p> <pre><code>import xlsxwriter import os.path import sys import dicom import xlrd import csv root = input("Enter Directory Name: ") #path = os.path.join(root, "targetdirectory") i=1 for path, subdirs, files in os.walk(root): for name in files: os.rename(os.path.join(path, name), os.path.join(path,'MR000'+ str(i)+'.dcm')) i=i+1 dcm_files = [] for path, dirs, files in os.walk(root): for names in files: if names.endswith(".dcm"): dcm_files.append(os.path.join(path, names)) print (dcm_files) with open('junk/test_0.csv', 'w', newline='') as csvfile: spamwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) spamwriter.writerow(["Folder Name","File Name", "PatientName", "PatientID", "PatientBirthDate","SliceThickness","Rows"]) for dcm_file in dcm_files: ds = dicom.read_file(dcm_file) fileName = dcm_file.split("/") spamwriter.writerow([fileName[1],fileName[2], ds.get("PatientName", "None"), ds.get("PatientID", "None"), ds.get("PatientBirthDate", "None"), ds.get("SliceThickness", "None"), ds.get("Rows", "None")]) </code></pre>
<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.dcm') os.rename('MR0002.dcm', 'MR0003.dcm') os.rename('MR0003.dcm', 'MR0004.dcm') ... </code></pre> <p>So at the end there is only a file 'MR0004.dcm'. </p> <p>Add the following line just below renaming:</p> <pre><code>print( os.path.join(path, name), '--&gt;', os.path.join(path,'MR000'+ str(i)+'.dcm')) </code></pre> <p>Then you will see, what exactly files are renamed.</p>
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 title images \ 0 raket Kevin/Marcus Langsung Fokus ke Kejuaraan Dunia... NaN 1 f1 Vettel Menangi GP Inggris yang Penuh Drama NaN 2 others Semangat 'Semakin di Depan' Warnai Kejuaraan M... NaN 5 sepakbola Roberto Martinez Mengejar Status Elite NaN 6 sepakbola Nyaris Separuh Gol Piala Dunia 2018 Lahir dari... NaN link \ 0 https://sport.detik.com/raket/d-4104834/kevinm... 1 https://sport.detik.com/f1/d-4104788/vettel-me... 2 https://sport.detik.com/sport-lain/d-4105193/s... 5 https://sport.detik.com/sepakbola/berita/d-410... 6 https://sport.detik.com/sepakbola/berita/d-410... date \ 0 Senin 09 Juli 2018, 00:31 WIB 1 Minggu 08 Juli 2018, 22:35 WIB 2 Senin 09 Juli 2018, 11:15 WIB 5 Senin 09 Juli 2018, 12:35 WIB 6 Senin 09 Juli 2018, 12:51 WIB desc 0 - Setelah , Kevin Sanjaya/Marcus Gideon suda... 1 - Driver Ferrari keluar sebagai pemenang Gr... 2 - Kejuaraan Dunia Motocross Grand Prix (MXGP)... 5 - bisa jadi mulai kerap diperbinc... 6 - Berakhirnya perempatfinal Piala D... </code></pre> <hr> <p>Now, I need to save every single row that contain <strong>desc</strong> with the title of <strong>title</strong>, I'm using the code belom:</p> <pre><code>np.savetxt(data1['title']+'.txt', data1['desc'], fmt='%s') </code></pre> <p>but, it come out with the result like this:</p> <pre><code>Traceback (most recent call last): File "index.py", line 23, in &lt;module&gt; np.savetxt(data1['title']+'.txt', data1['desc'], fmt='%s') File "/home/adminsvr/tf-py3/lib/python3.5/site-packages/numpy/lib/npyio.py", line 1187, in savetxt if fname.endswith('.gz'): File "/home/adminsvr/tf-py3/lib/python3.5/site-packages/pandas/core/generic.py", line 3614, in __getattr__ return object.__getattribute__(self, name) AttributeError: 'Series' object has no attribute 'endswith' </code></pre> <p>Any solution or ideas?</p>
<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]) to make it dynamic.</p> <p>However, the directory <em>result/</em> is not exist yet. User makedirs to make it.</p> <p>And finally, write (row[desc]) inside the txt file.</p> <p>Here we go:</p> <pre><code>import os for idx,row in data1.iterrows(): filename = "result/"+str(row['title'])+".txt" os.makedirs(os.path.dirname(filename), exist_ok=True) with open(filename, "w+") as f: f.write(row['desc']) f.close() print (idx) </code></pre>
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 sure that can be found at the specific module's documentation, because <code>read</code> is not a built-in function <a href="http://docs.python.org/2/library/functions.html" rel="noreferrer">last I heard</a> :p.</p>
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 I am looking to build a function that would somehow detect the &quot;outer&quot; 1s as the points of list separation:</p> <p><a href="https://i.stack.imgur.com/CvtCv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CvtCv.png" alt="enter image description here" /></a></p>
<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(tmp) tmp = [] if tmp: res.append(tmp) print(res) </code></pre> <p>Output:</p> <pre><code>[[1, 1, 1], [1, 1, 1, 1], [1]] </code></pre>
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 core i5 instead of core i7 ?? Is 4 GB gpu enough for training the dataset?? Is 8 GB ram enough for training and evaluating the dataset ?? with most thanks.</p>
<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.tensorflow.org/install/pip#hardware-requirements" rel="nofollow noreferrer">https://www.tensorflow.org/install/pip#hardware-requirements</a>.</p> <p>Therefore you would want to buy a graphics card that has ccc above 3.5. Here's a link that shows ccc for various nvidia graphic cards <a href="https://developer.nvidia.com/cuda-gpus" rel="nofollow noreferrer">https://developer.nvidia.com/cuda-gpus</a>.</p> <p>However if your cuda compute capability is below 3.5 you have to compile TF from sources yourself. This procedure may or may not work depending on the build flags you choose while compiling and is not straightforward. In my humble opinion, The simplest way is to use TF-GPU pre-built binaries to install TF GPU.</p> <p>To answer your questions. Yes you can use TF comfortably on i5 with 4gb of graphics card and 8gb ram. The training time may take longer though, depending on task at hand.</p> <p>In summary, the main hardware requirement to install TF GPU is getting a Nvidia graphics card with cuda compute capability more than 3.5, more the merrier. Note that TF officially supports only NVIDIA graphics card.</p>
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 primera conversion'] &lt; df_analisis_invertido['Fecha de creacion'] else x['Fecha de la primera conversion'], axis=1) </code></pre> <p>this is the error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().</p>
<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.DataFrame(data) df['t_first_conv'] = pd.to_datetime(df['t_first_conv']) df['t_creation'] = pd.to_datetime(df['t_creation']) print(df) # Change entry of first conversion column in case it is older/smaller than creation value (timestamps) # Expected: # 0: 5 3 # 1: 23 23 # 2: 234 234 df['t_first_conv']=df.apply(lambda x: x['t_creation'] if x['t_first_conv'] &lt; x['t_creation'] else x['t_first_conv'], axis=1) print(df) </code></pre>
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>&gt; [['Email', 'Name', 'Name ID', 'Policy ID', &gt; 'Policy Number', 'Policy Effective Date'], &gt; ['[email protected]','My Name', '5700023153486', '57000255465455','C4545647216', '1/1/2017']] </code></pre> <p>Please ignore the above <code>&gt;</code> formatting that appears incorrect.</p> <p>You can probably guess that the first row in the list contains column headers. I want to generate an HTML table out of this list. Assume for this example that there could be <strong>any number of additional rows to add to the table</strong>, but no need to teach me about looping to handle this or error handling if there are 0.</p> <p>How can I change this into an HTML table formatted relatively well? (e.g. black and white, with gridlines perhaps). I do not know HTML very well and have tried the following:</p> <pre><code>for thing in req_list: for cell in thing: req_tbl = req_tbl + "&lt;tr&gt;&lt;td&gt;" + str(cell) </code></pre> <p>Which yields basically each "cell" in the list printed one after another on a single line, when read in my email inbox (the code sends this <code>req_table</code> variable to myself in an email)</p> <pre><code>Email Name Name ID Policy ID </code></pre> <p>and so on. </p> <p>How can I get this formatted into a proper HTML table? Furthermore, is there a way I can read the "html" text contained in <code>req_table</code> within python so I can check my work? I have used urllib to open pages/files but can't seem to pass it a variable.</p>
<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() '&lt;table border="1" class="dataframe"&gt;\n &lt;thead&gt;\n &lt;tr style="text-align: right;"&gt;\n &lt;th&gt;&lt;/th&gt;\n &lt;th&gt;Email&lt;/th&gt;\n &lt;th&gt;Name&lt;/th&gt;\n &lt;th&gt;Name ID&lt;/th&gt;\n &lt;th&gt;Policy ID&lt;/th&gt;\n &lt;th&gt;Policy Number&lt;/th&gt;\n &lt;th&gt;Policy Effective Date&lt;/th&gt;\n &lt;/tr&gt;\n &lt;/thead&gt;\n &lt;tbody&gt;\n &lt;tr&gt;\n &lt;th&gt;0&lt;/th&gt;\n &lt;td&gt;[email protected]&lt;/td&gt;\n &lt;td&gt;My Name&lt;/td&gt;\n &lt;td&gt;5700023153486&lt;/td&gt;\n &lt;td&gt;57000255465455&lt;/td&gt;\n &lt;td&gt;C4545647216&lt;/td&gt;\n &lt;td&gt;1/1/2017&lt;/td&gt;\n &lt;/tr&gt;\n &lt;/tbody&gt;\n&lt;/table&gt;' </code></pre> <p>You can also read a html table into a DataFrame using:</p> <pre><code>df = pd.read_html(req_table) </code></pre>
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 "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.5/dist-packages/cv2/__init__.py", line 4, in &lt;module&gt; from .cv2 import * ImportError: libQtTest.so.4: cannot open shared object file: No such file or directory </code></pre>
<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','col_x3','col_x4']).apply(lambda x: my_own_function(x['col_y']))</code></p>
<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]],[3,[1,2,3,4,5,6,7,8,9,10]],[4,[11,12,13,14,15,16,17,18,19,20]]])</code></li> <li><code>b = np.array([[1,0],[2,1],[3,1],[4,0]])</code></li> </ul> <p>I want to combine them to create the following</p> <pre><code>([ [1, [[1,2,3,4,5,6,7,8,9,10], 0]], [2, [[11,12,13,14,15,16,17,18,19,20], 1]], [3, [[1,2,3,4,5,6,7,8,9,10], 1]], [4, [[11,12,13,14,15,16,17,18,19,20], 0]] ]) </code></pre> <p>I have been going in circles and have tried using different techniques like <code>vstack</code>, <code>concatenation</code>, as well as a bunch of others, but have not been successful.</p> <p>Any guidance would be gratefully appreciated!</p>
<p>Maybe the previous answer using a zip solved it for you but it works only if the 2 lists have the &quot;index element&quot; 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 i in itertools.product(a,b) if i[1][0]==i[0][0]] </code></pre> <p>This is basically the same as taking a join on the index element.</p> <pre><code>[[1, [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 0]], [2, [[11, 12, 13, 14, 15, 16, 17, 18, 19, 20], 1]], [3, [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 1]], [4, [[11, 12, 13, 14, 15, 16, 17, 18, 19, 20], 0]]] </code></pre>
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 to have this same CUSIP code in all the columns that match the same ticker. This is what my dataframe looks like, I want all the NaN to fill with the correct CUSIP so that you get the dataframe below</p> <pre><code>MSFT.OQ 594918104 FY2019 55252000000 United States USA 1 MSFT.OQ NaN FY2018 44501000000 United States USA 1 MSFT.OQ NaN FY2017 42730000000 United States USA 1 MSFT.OQ NaN FY2016 25145000000 United States USA 1 EFT_pa^E08 449515402 FY2001 6642000 United States USA 1 EFT_pa^E08 NaN FY2000 12161000 United States USA 1 EFT_pa^E08 NaN FY1999 MSFT.OQ 594918104 FY2019 55252000000 United States USA 1 MSFT.OQ 594918104 FY2018 44501000000 United States USA 1 MSFT.OQ 594918104 FY2017 42730000000 United States USA 1 MSFT.OQ 594918104 FY2016 25145000000 United States USA 1 EFT_pa^E08 449515402 FY2001 6642000 United States USA 1 EFT_pa^E08 449515402 FY2000 12161000 United States USA 1 EFT_pa^E08 449515402 FY1999 </code></pre>
<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>&gt;&gt;&gt; df.ffill() 0 1 2 3 4 5 6 7 0 MSFT.OQ 594918104.0 FY2019 5.525200e+10 United States USA 1.0 1 MSFT.OQ 594918104.0 FY2018 4.450100e+10 United States USA 1.0 2 MSFT.OQ 594918104.0 FY2017 4.273000e+10 United States USA 1.0 3 MSFT.OQ 594918104.0 FY2016 2.514500e+10 United States USA 1.0 4 EFT_pa^E08 449515402.0 FY2001 6.642000e+06 United States USA 1.0 5 EFT_pa^E08 449515402.0 FY2000 1.216100e+07 United States USA 1.0 6 EFT_pa^E08 449515402.0 FY1999 1.216100e+07 United States USA 1.0 </code></pre>
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 select the first image as the thumbnail in the folder properties every singe time. Recently Windows automatically wiped the thumbnail cache, and I really don't want to manually reset the thumbnails on these folders.</p> <p>Is there a way to automate going into a folder's properties, the customize tab, folder pictures, and selecting the first item in the folder every time? Or would I need a hypothetical "Folder.properties.setFolderPicture()" that Windows doesn't have for security reasons? Python is the only language I have any experience with, but if I need another language to do this I'm willing to try it.</p>
<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 Image from configparser import ConfigParser MAX_SIZE = 256, 256 image = Image.open(name_dot_format) image.thumbnail(MAX_SIZE) image.save(name_dot_ico) ini = ConfigParser() ini['.ShellClassInfo'] = {'IconResource': f'{name_dot_ico},0'} try: with open('desktop.ini', 'w') as desktop_ini: ini.write(desktop_ini) os.system(&quot;attrib +s +h desktop.ini&quot;) os.system(&quot;attrib +r .&quot;) except PermissionError: # Don't mess up the already existing desktop.ini os.system(&quot;attrib -r .&quot;) os.system(&quot;attrib -s -h desktop.ini&quot;) with open('desktop.ini', 'a') as desktop_ini: ini.write(desktop_ini) os.system(&quot;attrib +s +h desktop.ini&quot;) os.system(&quot;attrib +r .&quot;) </code></pre>
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 chunky enough. Also using SQLite seemed easier for me rather than using JSON.</p> <p>If SQLite doesn't work on a VPS, is there an alternative way of making a database for leveling or other type of stuff that requires a database?</p>
<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 mind that Sqlite can only support one writer at a time. The official documentation talks about the pros and cons of SQLite (<a href="https://www.sqlite.org/whentouse.html" rel="nofollow noreferrer">https://www.sqlite.org/whentouse.html</a>)</p>
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> File "C:\Users\Iker\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1883, in __call__ return self.func(*args) File "C:\Users\Iker\eclipse-workspace\Prueba2\Prueba2.py", line 128, in &lt;lambda&gt; Button_1 = Button(root, text="Calcular", padx=20, pady=10, command=lambda:calcular(Moneda.get())) File "C:\Users\Iker\eclipse-workspace\Prueba2\Prueba2.py", line 71, in calcular Beneficio_Bruto_EUR = Label(root, width=20, borderwidth=5, text="%.2f€"%Beneficio_Bruto/d) TypeError: unsupported operand type(s) for /: 'str' and 'float' </code></pre> <p>I really don't get it, because if there a problem defining the variables, shouldn't be in the <code>if</code> and <code>else</code> the same?</p> <pre><code>def calcular(Moneda): a=float(Precio_de_venta.get()) b=float(Portes.get()) c=float(Precio_de_compra.get()) d=float(1.04) #Beneficio Bruto Beneficio_Bruto=a-c-b-(a*0.1)-((a*0.029)+0.35) Beneficio_Brutolbl=Label(root, text="Beneficio Bruto") Beneficio_Brutolbl.grid(row=3, column=0) if Moneda == 0: Beneficio_Bruto_EUR = Label(root, width=20, borderwidth=5, text="%.2f€"%Beneficio_Bruto) Beneficio_Bruto_EUR.grid(row=3, column=1) Beneficio_Bruto_USD = Label(root, width=10, borderwidth=5, text="%.2f USD"%(Beneficio_Bruto*d)) Beneficio_Bruto_USD.grid(row=3, column=2) elif Moneda == 1: Beneficio_Bruto_EUR = Label(root, width=20, borderwidth=5, text="%.2f€"%Beneficio_Bruto/d) Beneficio_Bruto_EUR.grid(row=3, column=2) Beneficio_Bruto_USD = Label(root, width=10, borderwidth=5, text="%.2f USD"%(Beneficio_Bruto)) Beneficio_Bruto_USD.grid(row=3, column=1) </code></pre>
<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>&gt;&gt;&gt; '%d' % (4 * 2) '8' &gt;&gt;&gt; '%d' % 4 * 2 '44' &gt;&gt;&gt; '%d' % (4 / 2) '2' &gt;&gt;&gt; '%d' % 4 / 2 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for /: 'str' and 'int' </code></pre>
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 typing import List from dataclasses import dataclass @dataclass class Identifier(ABC): sub_tokens: List[str] @staticmethod def from_sub_tokens(sub_tokens): return SimpleIdentifier(sub_tokens) if len(sub_tokens) == 1 else CompoundIdentifier(sub_tokens) @dataclass class SimpleIdentifier(Identifier): pass @dataclass class CompoundIdentifier(Identifier): pass </code></pre>
<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__[0] == AbstractDataclass: raise TypeError("Cannot instantiate abstract class.") return super().__new__(cls) </code></pre> <p>So, if <code>Identifier</code> inherits from <code>AbstractDataclass</code> instead of from <code>ABC</code> directly, modifying the <code>__post_init__</code> will not be needed.</p> <pre><code>@dataclass class Identifier(AbstractDataclass): sub_tokens: List[str] @staticmethod def from_sub_tokens(sub_tokens): return SimpleIdentifier(sub_tokens) if len(sub_tokens) == 1 else CompoundIdentifier(sub_tokens) @dataclass class SimpleIdentifier(Identifier): pass @dataclass class CompoundIdentifier(Identifier): pass </code></pre> <p>Instantiating <code>Identifier</code> will raise <code>TypeError</code> but not instantiating <code>SimpleIdentifier</code> or <code>CompountIdentifier</code>. And the <code>AbstractDataclass</code> can be re-used in other parts of the code. </p>
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> <blockquote> <p>in parse raise ParserError(&quot;String does not contain a date: %s&quot;, timestr) dateutil.parser._parser.ParserError: String does not contain a date: -</p> </blockquote>
<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" /></a></p> <p>if you want to keep <code>'-'</code> change <code>'coerce'</code> to <code>'ignore'</code></p> <p><a href="https://i.stack.imgur.com/qEyHo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qEyHo.png" alt="enter image description here" /></a></p>
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 function has_key to see if that specific key exists. Answer of that will rid you of the need to iter through the dictionary to find matching values because u can just know if they are matching or not. again, charCount is just a function that enters the constants of itself into a dictionary and returns the dictionary.</p> <pre><code>def sumPair(theList, n): for a, b in level5.charCount(theList).iteritems(): x = n - a if level5.charCount(theList).get(a): if a == x: if b &gt; 1: #this checks that the frequency of the number is greater then one so the program wouldn't try to multiply a single possibility by itself and use it (example is 6+6=12. there could be a single 6 but it will return 6+6 return a, x else: if level5.charCount(theList).get(a) != x: return a, x print sumPair([6,3,8,3,2,8,3,2], 9) </code></pre> <p>I need to just make this code find the sum without iteration by seeing if the current element exists in the list of elements.</p>
<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 need. <code>a</code> is the key you get from the <code>level5.charCount(theList)</code></p> <p>So I simplify you code:</p> <pre><code>form collections import Counter def sumPair(the_list, n): for a, b in Counter(the_list).iteritems(): x = n - a if a == x and b &gt;1: return a, x if a != x and b != x: return a, x print sumPair([6, 3, 8, 3, 2, 8, 3, 2], 9) #output&gt;&gt;&gt; (8, 1) </code></pre> <p>The also can use <a href="http://www.python.org/dev/peps/pep-0202/" rel="nofollow">List Comprehension</a> like this:</p> <pre><code>&gt;&gt;&gt;result = [(a, n-a) for a, b in Counter(the_list).iteritems() if a==n-a and b&gt;1 or (a != n-a and b != n-a)] &gt;&gt;&gt;print result [(8, 1), (2, 7), (3, 6), (6, 3)] &gt;&gt;&gt;print result[0] #this is the result you want (8, 1) </code></pre>
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 -&gt; stuff app</li> <li>seconddomain.com -&gt; 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 you need to differentiate between those sites in some way.</strong></p> </blockquote> <p><a href="https://docs.djangoproject.com/en/dev/ref/contrib/sites/" rel="nofollow noreferrer">The &quot;sites&quot; framework</a></p>
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 settings.py. This question: <a href="https://stackoverflow.com/questions/27196845/django-custom-command-works-on-command-line-but-not-call-command">Django custom command works on command line, but not call_command</a> is very similar but I'm not sure what the answer means and I think it's unrelated. My file structure is :</p> <pre><code>├── custom_script │ ├── script.py │ ├── __init__.py ├── project │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── pages │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── __init__.py │ ├── management │ │ ├── commands │ │ │ ├── __init__.py │ │ │ └── custom_command.py │ │ ├── __init__.py │ ├── migrations │ │ ├── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py </code></pre> <p>content of script.py</p> <pre><code>from django.core.management import call_command call_command('custom_command', 'hi') </code></pre> <p>content of custom_command.py</p> <pre><code>from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('message', type=str) def handle(self, *args, **options): print('it works') </code></pre> <p>I want to run <code>python custom_script/script.py</code> which will call the <code>custom_command</code> but keep getting: django.core.management.base.CommandError: Unknown command: 'custom_command'. I have isolated the problem to the fact that django can't see my command as when I run <code>print(management.get_commands())</code> my custom command is not listed. Additionally, after looking through the django python code for management for a while I noticed this <code>settings.configured</code> variable which upon checking is False which means it only passes in the default commands when <code>management.get_commands</code> is run. How can I get this to become True? Technically, I could use a subprocess if I really wanted to but since there is already a call_command feature I figured I'd try and use it.</p>
<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 background on a webserver using script.py as the file to run the command. If your use case is similar you should instead call the custom command directly from the command line with python manage.py custom_command, this worked for me at least.</p>
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, 0)): self.pos = start self.dirnx = 1 self.dirny = 0 self.color = color def move(self, dirnx, dirny): self.dirnx = dirnx self.dirny = dirny self.pos(self.pos[0] + self.dirnx, self.pos[1] + self.dirny) def draw(self, surface, eyes=False): dis = self.w // self.rows i = self.pos[0] j = self.pos pygame.draw.rect(surface, self.color, (self.pos[0]*dis+1, self.pos[0]*dis+1, dis -2, dis -2) ) if eyes: centre = dis // 2 radius = 3 circleMiddle = (i*dis+centre-radius, j*dis+8) circleMiddle2 = (i*dis+dis - radius*2, j*dis+8) pygame.draw.rect(surface, (0, 0, 0), circleMiddle) pygame.draw.rect(surface, (0, 0, 0,), circleMiddle2) </code></pre> <p>This is the class where I'm experiencing the problem and if this information isn't enough here's the full code I've finished up till now I sincerely hope someone can help me.</p> <pre><code> import math import random import pygame import tkinter as tk from tkinter import messagebox class cube(object): rows = 20 w = 500 def __init__(self, start, dirnx=1, dirny=0, color=(255, 0, 0)): self.pos = start self.dirnx = 1 self.dirny = 0 self.color = color def move(self, dirnx, dirny): self.dirnx = dirnx self.dirny = dirny self.pos(self.pos[0] + self.dirnx, self.pos[1] + self.dirny) def draw(self, surface, eyes=False): dis = self.w // self.rows i = self.pos[0] j = self.pos pygame.draw.rect(surface, self.color, (self.pos[0]*dis+1, self.pos[0]*dis+1, dis -2, dis -2) ) if eyes: centre = dis // 2 radius = 3 circleMiddle = (i*dis+centre-radius, j*dis+8) circleMiddle2 = (i*dis+dis - radius*2, j*dis+8) pygame.draw.rect(surface, (0, 0, 0), circleMiddle) pygame.draw.rect(surface, (0, 0, 0,), circleMiddle2) class snake(object): body = [] turns = {} def __init__(self, color, pos): self.color = color self.head = cube(pos) self.body.append(self.head) self.dirnx = 0 self.dirny = 1 def move(self): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() keys = pygame.key.get_pressed() for key in keys: if keys[pygame.K_LEFT]: self.dirnx == -1 self.dirny = 0 self.turns[self.head.pos[:]] == [self.dirnx, self.dirny] elif keys[pygame.K_RIGHT]: self.dirnx == 1 self.dirny = 0 self.turns[self.head.pos[:]] == [self.dirnx, self.dirny] elif keys[pygame.K_UP]: self.dirnx == 0 self.dirny = -1 self.turns[self.head.pos[:]] == [self.dirnx, self.dirny] elif keys[pygame.K_DOWN]: self.dirnx == 0 self.dirny = 1 self.turns[self.head.pos[:]] == [self.dirnx, self.dirny] for i, c in enumerate: p = c.pos[:] if p in self.turns: turn = self.turns[p] c.move[turn[1], turn[0]] if i == len(self.body) - 1: self.turns.pop(p) else: if c.dirnx == -1 and c.pos[0] &lt;= 0: c.pos == (c.rows -1,c.pos[1]) elif c.dirnx == 1 and c.pos[0] &gt;= c.rows[-1]: c.pos == (0, c.pos[1]) elif c.dirny == 1 and c.pos[1] &gt;= c.rows[-1]: c.pos == (c.rows[0],c.pos[0]) elif c.dirny == -1 and c.pos[1] &lt;= 0: c.pos == (c.pos[0], c.rows -1) else: c.move(c.dirnx, c.dirny) def reset(self, pos): pass def addCube(self): pass def draw(self, surface): for i, c in enumerate(self.body): if i == 0: c.draw(surface,True) else: c.draw(surface) def drawGrid(w, rows, surface): sizeBtwn = w // rows x = 0 y = 0 for l in range(rows): x = x + sizeBtwn y = y + sizeBtwn pygame.draw.line(surface, (255, 255, 255), (x, 0), (x, w)) pygame.draw.line(surface, (255, 255, 255), (0, y), (w, y)) def redrawWindow(surface): global rows, width, s surface.fill((0, 0, 0)) s.draw(surface) drawGrid(width, rows, surface) pygame.display.update() def randomSnack(rows, item): pass def message_box(subject, content): pass def main(): global width, rows, s width = 500 rows = 20 win = pygame.display.set_mode((width, width)) s = snake((0, 170, 0), 10) clock = pygame.time.Clock() flag = True while flag: pygame.event.get() pygame.time.delay(50) # lower this is the faster clock.tick(10) # lower this is the slower redrawWindow(win) main() ``` </code></pre>
<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.__init__</code> function. <code>10</code> is indeed an <code>int</code> object, and you can't use it as a list, tuple or dictionary (it's not <em>subscriptable</em>).</p>
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 querysets of the same model as follows:</p> <pre><code>qs1 = ErrorLog.objects.get(report=original_report).defer('report') # 272 rows returned qs2 = ErrorLog.objects.get(report=new_report).defer('report') # 266 rows returned </code></pre> <p>I want to compare the first one to the second one and find the <code>6</code> rows that don't match in the first <code>qs1</code></p> <p>I tried <code>difference()</code> and <code>intersection()</code> but I keep ending up with the same <code>272</code> rows or <code>0</code> rows. I have a feeling that it sees <code>pk</code> as a unique value so it never finds matching rows. I tried the following:</p> <pre><code># Get the 4 fields I want to compare and exclude field_1 = [error.field_1 for error in qs2] field_2 = [error.field_2 for error in qs2] field_3 = [error.field_3 for error in qs2] field_4 = [error.field_4 for error in qs2] # Assuming this would work qs3 = qs1.exclude(field_1__in=field_1, field_2__in=field_2, field_3__in=field_3, field_4__in=field_4) # But ended up with 10 rows in qs3 since it doesn't loop thru the fields it just excludes it if found, which isn't ideal since some rows might be duplicate in qs1 so. </code></pre> <p>I then thought maybe <code>union()</code> would combine the two and exclude any duplicates between the two then I could just use an <code>exclude(pk__in=qs3_union)</code>. But I realized that's not how <code>union()</code> works.</p>
<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></pre> </blockquote> <p>How can we do so by reading it into memory using <code>csv.DictReader</code> and checking the information if it matches print out it's name</p> <p>I don't know how can I compare the whole <code>listdata</code> variable with the values in dictionary (<code>csv.DictReader</code>) as only way I know how to use dictionaries is by accessing them with key and key here is pretty limited as it can't take the whole list and compare with other keys in a same line/row.</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:]: print(row[0]) break </code></pre>
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 27 1 2 3 28 2 1 5 29 6 7 8 30 8 4 5 31 1 3 4 32 1 2 3 33 5 6 7 34 1 3 4 </code></pre> <p>The values inside A,B,C are not important they are just to show an example currently I am using </p> <pre><code> df1=df2.iloc[23:35] </code></pre> <p>perhaps there is an easier way to do this because I have to do this for around 20 different dataframes of different sizes I know that if I use </p> <pre><code>df1=df2.iloc[-1] </code></pre> <p>it will return the last number but I dont know how to incorporate it for the last twelve numbers. any help would be appreciated.</p>
<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_NO_TLSv1 context.options |= ssl.OP_NO_TLSv1_1 context.verify_mode = ssl.CERT_REQUIRED context.check_hostname = True # This line ommited in server code # Set the list of allowed ciphers to those with key length of at least 128 # TODO Figure out why this isn't working context.set_ciphers('TLSv1.2+HIGH+SHA256+ECDSA') # Print some info about the connection for cipher in context.get_ciphers(): print(cipher) </code></pre> <p>Output: </p> <pre><code>{'id': 50380835, 'name': 'ECDHE-ECDSA-AES128-SHA256', 'protocol': 'TLSv1/SSLv3', 'description': 'ECDHE-ECDSA-AES128-SHA256 TLSv1.2 Kx=ECDH Au=ECDSA Enc=AES(128) Mac=SHA256', 'strength_bits': 128, 'alg_bits': 128} </code></pre> <p>The current cipher:</p> <pre><code> connection.cipher() </code></pre> <p>('ECDHE-ECDSA-AES128-SHA256', 'TLSv1/SSLv3', 128)</p> <p>My question: why is the selected cipher not TLSv1.2?</p> <p><strong>Edit: Requested screenshots</strong></p> <p><a href="https://i.stack.imgur.com/YZRKF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YZRKF.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/PdJwR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PdJwR.png" alt="enter image description here"></a></p> <p>Based on another thread, I tried changing my code to the following, without any success.</p> <pre><code> # Create a context in TLSv1.2, requiring a certificate (2-way auth) self.context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) self.context.options |= ssl.OP_NO_SSLv2 self.context.options |= ssl.OP_NO_SSLv3 self.context.options |= ssl.OP_NO_TLSv1 self.context.options |= ssl.OP_NO_TLSv1_1 self.context.verify_mode = ssl.CERT_REQUIRED # self.context.check_hostname = True # Set the list of allowed ciphers to those with high key length # I went with SHA384 because it seemed to have more security self.context.set_ciphers('TLSv1.2+ECDSA+HIGH') </code></pre>
<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 the answer maybe :</p> <blockquote> <p>SSLSocket.cipher()</p> <p>Returns a three-value tuple containing the name of the cipher being used, <strong>the version of the SSL protocol that defines its use</strong>, and the number of secret bits being used. If no connection has been established, returns None.</p> </blockquote> <p>A network capture would confirm the TLS protocol version.</p>
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 wish the angle is 189.92624551. (I hope all of the angles after conversion are between 0~360 degree)</p> <p>How I fix this?</p> <p>Thanks!!!</p> <pre><code>import numpy as np points = np.array([(10, 43), (10, 44), (10, 45), (10, 46), (10, 47)]) #Set the center (origin) at (50, 50). Not (0, 0) def cart_to_pol(coords, center = [50,50], deg = True): complex_format = np.array(coords, dtype = float).view(dtype = np.complex) -\ np.array(center, dtype = float).view(dtype = np.complex) # return np.abs(complex_format).squeeze(), np.angle(complex_format, deg = deg).squeeze() return np.angle(complex_format, deg=deg).squeeze() print(cart_to_pol(points)) </code></pre>
<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| | 0 0 0| </code></pre> <p>...</p> <p>I would like to avoid the usage of numpy, so I think itertool is the way to go. I am looking at one dimensional solutions but all I got is something slightly different , like itertools.product that iterates with a fixed number of values, e.g.</p> <pre><code>itertools.product([0,'n'],repeat=6) [(0, 0, 0, 0, 0, 0),....('n', 'n', 'n', 'n', 'n', 'n')] </code></pre> <p>any hint would be gladly appreciated</p>
<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>&gt;&gt;&gt; w = 2 &gt;&gt;&gt; h = 2 &gt;&gt;&gt; n = 2 &gt;&gt;&gt; list(itertools.combinations(range(w * h), n)) [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] </code></pre> <p>To create the actual matrix (as a list of 1's and 0's) from one of the positions tuples you can for example use a list comprehension:</p> <pre class="lang-none prettyprint-override"><code>&gt;&gt;&gt; positions = (1, 3) &gt;&gt;&gt; [1 if i in positions else 0 for i in range(w * h)] [0, 1, 0, 1] </code></pre> <p>For very large <code>n</code> the lookup <code>i in positions</code> becomes inefficient and it would be better to change this to a function like:</p> <pre><code>def create_matrix(positions): matrix = [0] * w * h for i in positions: matrix[i] = 1 return matrix </code></pre> <p>Now you can put everything together:</p> <pre class="lang-none prettyprint-override"><code>&gt;&gt;&gt; [[1 if i in p else 0 for i in range(w * h)] ... for p in itertools.permutations(range(w * h), n)] [[1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1], [1, 1, 0, 0], [0, 1, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 1, 0], [0, 0, 1, 1], [1, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1]] </code></pre> <p>Or, if you use the <code>create_matrix</code> function:</p> <pre class="lang-none prettyprint-override"><code>&gt;&gt;&gt; [create_matrix(p) for p in itertools.permutations(range(w * h), n)] </code></pre>
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)</code> coordinates in the sky, using HEALPix pixellization on Mollweide projection. How can I do this using healpy ?</p> <p>The tutorial:</p> <blockquote> <p><a href="http://healpy.readthedocs.io/en/v1.9.0/tutorial.html" rel="noreferrer">http://healpy.readthedocs.io/en/v1.9.0/tutorial.html</a></p> </blockquote> <p>says how to plot a 1D array, or a fits file, but I don't find how to do a 2d histogram using this pixellization.</p> <p>I also found this function, but it is not working , so I am stuck.</p> <pre><code>hp.projaxes.MollweideAxes.hist2d(l, b, bins=10) </code></pre> <p>I can do a plot of these points in Mollweide projection this way :</p> <pre><code>l_axis_name ='Latitude l (deg)' b_axis_name = 'Longitude b (deg)' fig = plt.figure(figsize=(12,9)) ax = fig.add_subplot(111, projection="mollweide") ax.grid(True) ax.scatter(np.array(l)*np.pi/180., np.array(b)*np.pi/180.) plt.show() </code></pre> <p>Thank you very much in advance for your help.</p>
<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 resolution element. Parameters ---------- lon, lat : (ndarray, ndarray) Coordinates of the sources in degree. If radec=True, assume input is in the icrs coordinate system. Otherwise assume input is glon, glat nside : int HEALPix nside of the target map radec : bool Switch between R.A./Dec and glon/glat as input coordinate system. Return ------ hpx_map : ndarray HEALPix map of the catalogue number counts in Galactic coordinates """ npix = hp.nside2npix(nside) if radec: eq = SkyCoord(lon, lat, 'icrs', unit='deg') l, b = eq.galactic.l.value, eq.galactic.b.value else: l, b = lon, lat # conver to theta, phi theta = np.radians(90. - b) phi = np.radians(l) # convert to HEALPix indices indices = hp.ang2pix(nside, theta, phi) idx, counts = np.unique(indices, return_counts=True) # fill the fullsky map hpx_map = np.zeros(npix, dtype=int) hpx_map[idx] = counts return hpx_map </code></pre> <p>You can then use that to populate the HEALPix map:</p> <pre><code>l = np.random.uniform(-180, 180, 20000) b = np.random.uniform(-90, 90, 20000) hpx_map = hpx.cat2hpx(l, b, nside=32, radec=False) </code></pre> <p>Here, the <code>nside</code> determines how fine or coarse your pixel grid is.</p> <pre><code>hp.mollview(np.log10(hpx_map+1)) </code></pre> <p><a href="https://i.stack.imgur.com/Ezbil.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Ezbil.png" alt="enter image description here"></a></p> <p>Also note that by sampling uniformly in Galactic latitude, you'll prefer data points at the Galactic poles. If you want to avoid that, you can scale that down with a cosine.</p> <pre><code>hp.orthview(np.log10(hpx_map+1), rot=[0, 90]) hp.graticule(color='white') </code></pre> <p><a href="https://i.stack.imgur.com/KFLmq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/KFLmq.png" alt="enter image description here"></a></p>
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> <pre><code>import asyncio import websockets import subprocess import sys import os async def foo(websocket, path): print ("socket open") await websocket.send("successfully connected") with subprocess.Popen(['sudo','python3', '-u','inline_print.py'],stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0, universal_newlines=True) as p: for line in p.stdout: line = str(line.rstrip()) await websocket.send(line) p.stdout.flush() for line in p.stderr: line = str(line.rstrip()) await websocket.send(line) p.stdout.flush() start_server = websockets.serve(foo, "localhost", 8765) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever() </code></pre> <p>inline_print.py:</p> <pre><code>from time import sleep import sys loading = 'LOADING...LOADING...LOADING...LOADING...LOADING...' for i in range(50): print(loading[i], sep='', end=' ', flush=True) sleep(0.1) </code></pre> <p>if <code>end=' '</code> is changed to <code>end='\n'</code> then the stdout from <code>send_data.py</code> occurs in realtime.</p> <p>js client:</p> <pre><code>var ws = new WebSocket('ws://localhost:8765/'); ws.onmessage = function(event) { console.log(event.data); }; </code></pre> <p>I acknowledge this question is similar to these:</p> <p><a href="https://stackoverflow.com/questions/1606795/catching-stdout-in-realtime-from-subprocess">catching-stdout-in-realtime-from-subprocess</a></p> <p><a href="https://stackoverflow.com/questions/874815/how-do-i-get-real-time-information-back-from-a-subprocess-popen-in-python-2-5">how-do-i-get-real-time-information-back-from-a-subprocess-popen-in-python-2-5</a></p> <p><a href="https://stackoverflow.com/questions/527197/intercepting-stdout-of-a-subprocess-while-it-is-running">intercepting-stdout-of-a-subprocess-while-it-is-running</a></p> <p>yet none of the solutions work without a newline character from the subprocess.</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>: (example subprocess)</p> <pre><code>import sys, time for v in range(20): print(".", end="") sys.stdout.flush() if v % 4 == 0: print() if v % 3 != 0: time.sleep(0.5) </code></pre> <p><strong>rdunbuf.py</strong>: (example reading stddout unbuffered)</p> <pre><code>contextlib, time, subprocess def unbuffered(proc, stream='stdout'): stream = getattr(proc, stream) with contextlib.closing(stream): while True: last = stream.read(80) # read up to 80 chars # stop when end of stream reached if not last: if proc.poll() is not None: break else: yield last # open subprocess without buffering and without universal_newlines=True proc = subprocess.Popen(["./sub.py"], stdout=subprocess.PIPE, bufsize=0) for l in unbuffered(proc): print(l) print("end") </code></pre> <p>Please note as well, that your code might block if it produces a lot of error messages before producing normal output, as you try first to read all normal output and only then data from stderr.</p> <p>You should read whataver data your subprocess produces as before any pipeline buffers are blocking independently whether this is stdout or stderr. You can use <code>select.select()</code> ( <a href="https://docs.python.org/3.8/library/select.html#select.select" rel="nofollow noreferrer">https://docs.python.org/3.8/library/select.html#select.select</a> ) in order to decide whether you had to read from stdout, or stderr</p>
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 inside the dealed_cards list, if it is duplicate the method is called again and a new card assigned. </p> <p>My dealed_cards list is initiated inside a class that creates the round and then is passed from class to class as a list that can re-initialized at the beginning of a new round of game play. However the list is not passing correctly into the method within the class that assigns new card values. </p> <p>Some ways that I have tried to pass the list in are: (self, dealed_cards), with this I get error </p> <pre><code>TypeError deal_card_out() missing 1 required positional argument: 'dealed_cards' With (self, dealed_cards = [], *args) </code></pre> <p>which at least works but doesn't necessarily pass the list correctly, when I try to print the dealed_cards list out from within the method before modifying it I get an empty list.</p> <p>with <strong>(self, *dealed_cards)</strong> this returns the list as a tuple and doesn't pass it correct. and finally with <strong>(self, dealed_cards = [])</strong> result: still not passing in the list dealed_cards from inside the function</p> <p>Here is a test block of code I broke off from the main program in order to test this method.</p> <pre class="lang-py prettyprint-override"><code>class deal_card(object): def __init__(self): pass def deal_card_out(self, dealed_cards = []): print("This is a test print statement at the beginning of this method to test that dealed_cards was passed in correctly.") print(dealed_cards) card_one_face_value = 'Seven' card_one_suit_value = 'Clubs' for _ in dealed_cards: if card_one_face_value == [_[0]]: print(f"This is a test print statement inside the for loop within deal_card out, it willl print out [_[0]] inside this for loop: {[_[0]]}") if card_one_suit_value == [_[1]]: print("test loop successful") else: print(f"This is a test print statement inside the for loop within deal_card out, it willl print out [_[0]] inside this for loop: {[_[0]]}") pass else: print(f"this is a test print statement inside the for loop within deal_card out it will print out dealed_cards[_[1]] to show what is happening inside this loop: {[_[1]]}") pass dealed_cards.append([card_one_face_value,card_one_suit_value]) print("This is a test print inside of deal_card_out, it prints list dealed_cards after method modifies the list") print(dealed_cards) return [dealed_cards,card_one_face_value,card_one_suit_value] dealed_cards = [['Place','Holder'],['Seven','Clubs']] print("this is a test print statement outside of the method to test that dealed_cards is being passed in correctly") print(dealed_cards) test_run = deal_card.deal_card_out(dealed_cards) </code></pre>
<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 <code>def deal_card_out(dealed_cards):</code> The for loop was also misbehaving, the test statement <code>if card_one_face_value == [_[0]]:</code> needed to be changed to <code>if card_one_face_value == _[0]:</code> otherwise you are testing with brackets around seven, the string inside that nested list.</p>
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 "+str(len(list_of_stuff))+" numbers.") #calculate the number of numbers per column stuff_per_column = int(len(list_of_stuff) / number_of_columns) print("-I must add "+str(stuff_per_column)+" numbers on each column.") #generate different lists with their numbers generated_lists = list(zip(*[iter(list_of_stuff)]*stuff_per_column)) print("-Columns are now filled with their numbers.") </code></pre> <p>Until that everything is fine, but <strong>here I'm stuck:</strong> </p> <pre><code>#print lists together as columns for x,y,z in zip(generated_lists[0],generated_lists[1],generated_lists[2]): print(x,y,z) print("-Done!") </code></pre> <p>I tried to use that code and it does what I want except because it involves to have hardcoded the number of columns. x,y,z for example would be for 3 columns, but I want to set the number of columns at the User input and remove the need to hardcode it everytime.</p> <p>What am I missing? How can I make the print understand how many lists do I have?</p> <p><strong>Desired output:</strong> If user sets number of columns on 4, for example, the output would be:</p> <pre><code>1 6 11 16 2 7 12 17 3 8 13 18 4 9 14 19 5 10 15 20 Etc... </code></pre>
<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 number you want</p>
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 fetch the column value from Best_val for that row an use it as column name to subtract t from 1 to be stored in Value</p>
<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 B 0.33 0.21 0.45 0.79 2 A 0.16 0.71 0.56 0.84 3 C 0.51 0.26 0.85 0.15 </code></pre>
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> <p>And I have data like this (small part):</p> <pre><code>df = id_easy latitude longitude e705ac2 22.0171 3.6687 e705ac2 22.0238 3.6709 e705ac2 22.0299 3.6733 e705ac2 22.0319 3.6725 7eb84c8 22.0567 3.6821 3264cc7 22.0754 3.7277 3264cc7 22.0766 3.7208 3264cc7 22.0754 3.7163 3264cc7 22.0753 3.7102 </code></pre> <p>Is it possible to check points started in one blue zone and ended in other blue zone?</p> <p>For example, I need to check: if locations of value <code>e705ac2</code> starting in left zone and ending in right zone</p>
<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\263' [[{{node DecodeJpeg}}]] [Op:IteratorGetNextSync]</p> <p>encode: def _bytes_feature(value): """Returns a bytes_list from a string / byte.""" return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))</p> <pre><code>def _float_feature(value): """Returns a float_list from a float / double.""" return tf.train.Feature(float_list=tf.train.FloatList(value=[value])) def _int64_feature(value): """Returns an int64_list from a bool / enum / int / uint.""" return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) src_path = r"E:\data\example" record_path = r"E:\data\data" sum_per_file = 4 num = 0 key = 3 for img_name in os.listdir(src_path): recordFileName = "trainPrecipitate.tfrecords" writer = tf.io.TFRecordWriter(record_path + recordFileName) img_path = os.path.join(src_path, img_name) img = Image.open(img_path, "r") height = np.array(img).shape[0] width = np.array(img).shape[1] img_raw = img.tobytes() example = tf.train.Example(features = tf.train.Features(feature={ 'image/encoded': _bytes_feature(img_raw), 'image/class/label': _int64_feature(key), 'image/height': _int64_feature(height), 'image/width': _int64_feature(width) })) writer.write(example.SerializeToString()) writer.close() </code></pre> <p>decode: import IPython.display as display</p> <pre><code>train_files = tf.data.Dataset.list_files(r"E:\data\datatrainPrecipitate.tfrecords") train_files = train_files.interleave(tf.data.TFRecordDataset) def decode_example(example_proto): image_feature_description = { 'image/height': tf.io.FixedLenFeature([], tf.int64), 'image/width': tf.io.FixedLenFeature([], tf.int64), 'image/class/label': tf.io.FixedLenFeature([], tf.int64, default_value=3), 'image/encoded': tf.io.FixedLenFeature([], tf.string) } parsed_features = tf.io.parse_single_example(example_proto, image_feature_description) height = tf.cast(parsed_features['image/height'], tf.int32) width = tf.cast(parsed_features['image/width'], tf.int32) label = tf.cast(parsed_features['image/class/label'], tf.int32) image_buffer = parsed_features['image/encoded'] image = tf.io.decode_jpeg(image_buffer, channels=3) image = tf.cast(image, tf.float32) return image, label def processed_dataset(dataset): dataset = dataset.repeat() dataset = dataset.batch(1) dataset = dataset.prefetch(buffer_size=tf.data.experimental.AUTOTUNE) # print(dataset) return dataset train_dataset = train_files.map(decode_example) # train_dataset = processed_dataset(train_dataset) print(train_dataset) for (image, label) in train_dataset: print(repr(image)) </code></pre> <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\263' [[{{node DecodeJpeg}}]] [Op:IteratorGetNextSync]</p>
<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>#!/bin/env python import wx import wx.lib.scrolledpanel as SP class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, - 1, "Frame", size=(300, 300)) self.scrolledPanel = ScrollPanel(self, size=(-1, 200)) self.panel = PlotTypePanel(self) hbox = wx.BoxSizer(wx.VERTICAL) hbox.Add(self.scrolledPanel, 0, wx.EXPAND | wx.ALL, 0) hbox.Add(self.panel, 1, wx.EXPAND | wx.ALL, 0) self.SetSizer(hbox) class PlotTypePanel(wx.Panel): def __init__(self, parent, **kwargs): wx.Panel.__init__(self, parent,**kwargs) self.anotherradiobox = wx.RadioBox(self,label='other', style=wx.RA_SPECIFY_COLS, choices=["some", "other", "box"]) class ScrollPanel(SP.ScrolledPanel): def __init__(self, parent, **kwargs): SP.ScrolledPanel.__init__(self, parent, -1, **kwargs) self.parent = parent self.SetupScrolling(scroll_x=False, scroll_y=True, scrollToTop=False) choices = [l for l in "abcdefghijklmnopqrstuv"] self.fieldradiobox = wx.RadioBox(self,label='letters', style=wx.RA_SPECIFY_ROWS, choices=choices) vbox = wx.BoxSizer(wx.VERTICAL) vbox.Add(self.fieldradiobox, 0, wx.EXPAND|wx.ALL, 10) self.SetSizer(vbox) self.SetupScrolling(scroll_x=False, scrollToTop=False) if __name__ == '__main__': app = wx.App() frame = MyFrame() frame.Show(True) app.MainLoop() </code></pre> <p>When I click on the other radio panel and back to the scrolled panel, as here,</p> <p><a href="https://i.stack.imgur.com/S72pj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/S72pj.png" alt="enter image description here"></a></p> <p>it jumps to the top and doesn't select the radio button. I've checked and it seems the <code>EVT_COMBOBOX</code> is not triggered by this first click. I've also tried adding <code>scrollToTop=False</code> which didn't help. I'm using Python 2.7.3 with wxPython version 3.0.2.0.</p>
<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 import wx.lib.scrolledpanel as SP class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, - 1, "Frame", size=(300, 300)) self.scrolledPanel = ScrollPanel(self, size=(-1, 200)) self.panel = PlotTypePanel(self) hbox = wx.BoxSizer(wx.VERTICAL) hbox.Add(self.scrolledPanel, 0, wx.EXPAND | wx.ALL, 0) hbox.Add(self.panel, 1, wx.EXPAND | wx.ALL, 0) self.SetSizer(hbox) class PlotTypePanel(wx.Panel): def __init__(self, parent, **kwargs): wx.Panel.__init__(self, parent,**kwargs) self.anotherradiobox = wx.RadioBox(self,label='other', style=wx.RA_SPECIFY_COLS, choices=["some", "other", "box"]) class ScrollPanel(SP.ScrolledPanel): def __init__(self, parent, **kwargs): SP.ScrolledPanel.__init__(self, parent, -1, **kwargs) self.parent = parent self.SetupScrolling(scroll_x=False, scroll_y=True, scrollToTop=False) choices = [l for l in "abcdefghijklmnopqrstuv"] self.fieldradiobox = wx.RadioBox(self,label='letters', style=wx.RA_SPECIFY_ROWS, choices=choices) vbox = wx.BoxSizer(wx.VERTICAL) vbox.Add(self.fieldradiobox, 0, wx.EXPAND|wx.ALL, 10) self.SetSizer(vbox) self.Bind(wx.EVT_CHILD_FOCUS, self.on_focus) self.SetupScrolling(scroll_x=False, scrollToTop=False) def on_focus(self,event): pass if __name__ == '__main__': app = wx.App() frame = MyFrame() frame.Show(True) app.MainLoop() </code></pre> <p>Note: It's not an issue but you have <code>self.SetupScrolling</code> declared twice.</p>
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 = socket.socket (socket.AF_INET, socket.SOCK_STREAM) s.setsockopt (socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind ( ('', 10100) ) s.listen (1) print ('Waiting on client') client, _ = s.accept () print ('Accepted') data = b'' done = False while not done: data += client.recv (4096) msgs = data.split (b'\r') for msg in msgs [:-1]: print ('received {}'.format (msg) ) done = msg == b'exit' data = msgs [-1] s.close () print ('Server down') </code></pre> <p>Client: </p> <pre><code>#! /usr/bin/python3 import socket s = socket.socket (socket.AF_INET, socket.SOCK_STREAM) print ('Connecting') s.connect ( ('localhost', 10100) ) print ('Connected') for msg in [b'ping', b'pang', b'exit', b'ping', b'pang']: print ('Sending {}'.format (msg) ) sent = s.send (msg + b'\r') print ('Sent {}. {} bytes transmitted'.format (msg, sent) ) input ('&gt;&gt; ') </code></pre> <p>I start up the server, then the client and hit enter to step through the messages.</p> <p>The server output is:</p> <pre><code>Waiting on client Accepted received b'ping' received b'pang' received b'exit' Server down </code></pre> <p>The client output is:</p> <pre><code>Connecting Connected Sending b'ping' Sent b'ping'. 5 bytes transmitted &gt;&gt; Sending b'pang' Sent b'pang'. 5 bytes transmitted &gt;&gt; Sending b'exit' Sent b'exit'. 5 bytes transmitted &gt;&gt; Sending b'ping' Sent b'ping'. 5 bytes transmitted &gt;&gt; Sending b'pang' Traceback (most recent call last): File "./client.py", line 10, in &lt;module&gt; sent = s.send (msg + b'\r') BrokenPipeError: [Errno 32] Broken pipe </code></pre> <p>Why do I get the <code>BrokenPipeError</code> after the last <code>pang</code> and not after the <code>ping</code>?</p> <p>Why does <code>send</code> return 5 when sending the <code>ping</code> after the <code>exit</code>?</p> <p>Why is the pipe not broken immediately after the server is down?</p> <hr> <p>EDIT: After having sent <code>exit</code>, I don't hit enter on the client console unless the server console has already printed <code>Server down</code>.</p>
<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>When the client sends again data to the closed server socket, the server replies with RST to which the client is expected to abort the connection. See <a href="http://tools.ietf.org/search/rfc793#page-33" rel="nofollow">http://tools.ietf.org/search/rfc793#page-33</a> on Half-Open Connections and Other Anomalies. However, the socket is closed after the send method has returned. That's why only the next send will crash on BrokenPipe, as the connection is now closed from the client side too.</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 &lt; en_time: if str(st_time) in line: between = True break st_time = st_time + datetime.timedelta(seconds=1) </code></pre> <p>Exception: <code>TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'</code></p> <p>What is wrong here?</p>
<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 also seems to work and would probably be more efficient,</p> <pre><code>np.random.seed(1) smpl = np.random.normal(loc=centers, scale=std) print(smpl) </code></pre>
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 bucket (result-bucket). My question is how to I import the numpy and the cv2 module on AWS lambda, I followed guide from <a href="https://serverless.com/blog/serverless-python-packaging/" rel="nofollow noreferrer">https://serverless.com/blog/serverless-python-packaging/</a> however, it return me an error message:</p> <pre class="lang-none prettyprint-override"><code>An error occurred: NumpyLambdaFunction - Function not found: arn:aws:lambda:us-east-1:......:function:numpy-test-dev-numpy (Service: AWSLambdaInternal; Status Code: 404; Error code: ResourceNotFoundException; Request ID: ....). </code></pre> <p>What can I do to fix this error? or is there another better method for doing so? (P.S. I am using the window computer) Thank you very much!</p>
<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/372a47bb618111dcd2c81008d00357b2" rel="nofollow noreferrer">Check out this readme</a></p>
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 server is: <code>MY_SERVER</code></p> <p>and then in my <code>app.py</code>, I use </p> <pre><code>@app.route('/homepage/') @app.route('/homepage/index') def index(): # TODO </code></pre> <p>to define the homepage, and <code>@app.errorhandler(404)</code> to redirect all the not found page to <code>404.html</code></p> <p>So I can get access to my homepage with <code>http://MY_SERVER/homepage/</code>, a little different than my local server. That's one thing that I am confused. </p> <p>What I think is that the <code>app.py</code> runs under the <code>MY_SERVER</code> rather than <code>MY_SERVER/homepage</code> right?</p> <p>But, in this way, when I run a template in my template file, and the <code>html</code> template file will use the <code>js</code> file under the <code>static</code> folder. the response always shows the <code>js</code> file is not found.</p> <ol> <li>when I use <code>&lt;script src="{{ url_for('static', filename='file.js') }}"&gt;&lt;/script&gt;</code>, it shows not found in <code>MY_SERVER/static</code> and return to 404</li> <li>when I try <code>&lt;script src="../homepage/static/file.js"&gt;&lt;/script&gt;</code>, same result.</li> </ol> <p>How to handle this?</p>
<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.</p></li> <li><p>Get flask serving the js file directly to your browser</p> <p>Now put your js file into static and do as you did for the image. Plug away until you can call it from the browser: <a href="http://yoursite/static/yourfile.js" rel="nofollow">http://yoursite/static/yourfile.js</a></p></li> <li><p>get your html to call the js file from static</p> <p>Now you know that there is no problem actually serving the file, and you know the exact url to it. So it's not a big step to getting the HTML to reference it and your browser to load it.</p></li> </ol>
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 returning me the Grand Total - based on the 1st index (A) df.pivot_table(index=['A','B','C','D,'E','F','G'] , aggfunc={'G' : ['count',len]}) </code></pre> <p>This should be the result (last column) once pivoted <a href="https://i.stack.imgur.com/jm4uD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jm4uD.png" alt="enter image description here" /></a></p>
<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.stack.imgur.com/8KEZF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8KEZF.png" alt="pivot table" /></a></p> <p>If however we include all columns as indices, the count of 'G' stays at 1.</p> <p>Creating a similar pivot table with all columns in Excel shows an identical behaviour with only count of 1's:</p> <p><a href="https://i.stack.imgur.com/9l5LT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9l5LT.png" alt="pivot table in Excel" /></a></p>
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', 'age': 15, 'Name': 'Mot'} 2 {'Class': 'B', 'age': 25, 'Name': 'Vittoo'} </code></pre> <p>When I use the to_frame function, it does this:</p> <pre><code>dummy.to_frame() 0 0 {'Class': 'A', 'age': 35, 'Name': 'Manoj'} 1 {'Class': 'B', 'age': 15, 'Name': 'Mot'} 2 {'Class': 'B', 'age': 25, 'Name': 'Vittoo'} </code></pre> <p>But what I intent to get is this:</p> <pre><code>Class Name age 0 A Manoj 35 1 B Mot 15 2 B Vittoo 25 </code></pre> <p>I have tried this which works fine:</p> <pre><code>df = pd.DataFrame(dummy) df = df[0].apply(pd.Series) df </code></pre> <p>But it feels very inefficient because I need to convert the Series to a dataframe and again apply the Series function to the complete dataframe. As I'm working with millions of rows, I'd like to know if there is a more efficient solution.</p>
<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 A Manoj 35 1 B Mot 15 2 B Vittoo 25 </code></pre> <hr> <p>If input data is <code>Series</code> fiiled by dictionaries convert it to lists before <code>DataFrame</code> constructor, <code>to_frame</code> is not necessary:</p> <pre><code>dummy = pd.Series(ser) df = pd.DataFrame(dummy.values.tolist()) print (df) Class Name age 0 A Manoj 35 1 B Mot 15 2 B Vittoo 25 </code></pre>
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 a e a 1.2 1.3 1.4 1.5 a 9.1 9.2 X= b 2.1 2.2 2.3 2.4 Y= e 8.1 8.2 c 3.3 3.4 3.5 3.6 d 4.2 4.3 4.4 4.5 a b c d e a 1.2+9.1 1.3 1.4 1.5 9.2 X+Y= b 2.1 2.2 2.3 2.4 0 c 3.3 3.4 3.5 3.6 0 d 4.2 4.3 4.4 4.5 0 e 8.1 0 0 0 8.2 </code></pre> <p>If someone wants to see the files (matrices), they are <a href="https://drive.google.com/drive/folders/0B0byAC8kZZPhTExOUFZqQkQ1VTQ?usp=sharing" rel="nofollow noreferrer">here</a>. </p> <p>** Trying the method suggested by @piRSquared</p> <pre><code>import pandas as pd X= pd.read_csv('30203_Transpose.csv') Y= pd.read_csv('62599_1999psCSV.csv') Z= X.add(Y, fill_value=0).fillna(0) print Z </code></pre> <p>Z -> 467 rows x 661 columns</p> <p>The resulting matrix should be square too. This approach also causes the row headers to be lost ( now become 1,2,3 .. , They should be 10010, 10071, 10107, 1013 ..)</p> <pre><code> 10010 10071 10107 1013 .... 0 0 0 0.01705 0.0439666659 1 0 0 0 0 2 0 0 0 0.0382000022 3 0.0663666651 0 0 0.0491333343 4 0 0 0 0 5 0.0208000001 0 0 0.1275333315 . . </code></pre> <p>What should I be doing? </p>
<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 column of <code>a</code> and an element of <code>b</code>. </p> <p>So far, I have tried the following:</p> <pre><code>for a_column, b_element in np.nditer([a, b]): print(a_column) </code></pre> <p>However, I get printed the element <code>a[0,0]</code> rather than the column <code>a[0,:]</code>, which I want. </p> <p>How can I solve this?</p>
<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 1 g True 1 full 7.1 apple 1 12.0 2 g False 2 partial 14.3 apple 3 13.1 1 g False 3 full 20.1 orange 2 20.1 1 g True 4 full 17.1 orange 1 18.5 2 g True 5 partial 23.4 orange 3 22.7 1 g True 6 full 23.1 grape 3 14.1 1 g False 7 full 17.2 grape 2 17.1 2 g False 8 partial 19.1 grape 1 19.4 1 g False highest_fruit 0 [apple, orange] 1 [orange] 2 [orange] 3 [apple, orange] 4 [orange] 5 [orange] 6 [apple, orange] 7 [orange] 8 [orange] </code></pre> <p>In the original question, I was guided to the above table in which the highest fruit(s) for a given analysis and test combination was indicated by doing a transformation on the table (e.g. a <strong>full analysis</strong> on <strong>test 1</strong> resulted in apple and orange fruits having the highest second pass numbers). </p> <p>I'm now trying to use this information to calculate those fruit(s) relative performance to their first pass. For example, now that I know <strong>apple and orange</strong> are the highest fruits for a <strong>full analysis, test 1</strong>, I'd like to know if they improved over their first passes. (apple improved with a score of 20.1 on the second pass compared to 12.1 on their first_pass; likewise orange improved to 20.1 after scoring 19.1 on it's first pass). </p> <p>I'd like a tables similar to the one below (1 = improved, 0 = no change, -1 worse):</p> <pre><code> analysis first_pass fruit order second_pass test units highest \ 0 full 12.1 apple 2 20.1 1 g True 1 full 7.1 apple 1 12.0 2 g False 2 partial 14.3 apple 3 13.1 1 g False 3 full 20.1 orange 2 20.1 1 g True 4 full 17.1 orange 1 18.5 2 g True 5 partial 23.4 orange 3 22.7 1 g True 6 full 23.1 grape 3 14.1 1 g False 7 full 17.2 grape 2 17.1 2 g False 8 partial 19.1 grape 1 19.4 1 g False highest_fruit score_change_between_passes 0 [apple, orange] {"apple" : 1, "orange" : 0} 1 [orange] {"orange" : 1} 2 [orange] {"orange" : -1} 3 [apple, orange] {"apple" : 1, "orange" : 0} 4 [orange] {"orange" " 1} 5 [orange] {"orange" : -1} 6 [apple, orange] {"apple" : 1, "orange" : 0} 7 [orange] {"orange" : 1} 8 [orange] {"orange" : -1} </code></pre>
<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_pass'].iloc[0])) for fruit in x.highest_fruit.iloc[0]}).reset_index() df = df.merge(second_pass, on=['test', 'analysis'], how='left').rename(columns={0: 'second_pass_comp'}) analysis first_pass fruit order second_pass test units highest \ 0 full 12.1 apple 2 20.1 1 g True 1 full 7.1 apple 1 12.0 2 g False 2 partial 14.3 apple 3 13.1 1 g False 3 full 19.1 orange 2 20.1 1 g True 4 full 17.1 orange 1 18.5 2 g True 5 partial 23.4 orange 3 22.7 1 g True 6 full 23.1 grape 3 14.1 1 g False 7 full 17.2 grape 2 17.1 2 g False 8 partial 19.1 grape 1 19.4 1 g False highest_fruit first_pass_highest_fruit second_pass_comp 0 [apple, orange] {'orange': 19.1, 'apple': 12.1} {'orange': 1, 'apple': 1} 1 [orange] {'orange': 17.1} {'orange': 1} 2 [orange] {'orange': 23.4} {'orange': -1} 3 [apple, orange] {'orange': 19.1, 'apple': 12.1} {'orange': 1, 'apple': 1} 4 [orange] {'orange': 17.1} {'orange': 1} 5 [orange] {'orange': 23.4} {'orange': -1} 6 [apple, orange] {'orange': 19.1, 'apple': 12.1} {'orange': 1, 'apple': 1} 7 [orange] {'orange': 17.1} {'orange': 1} 8 [orange] {'orange': 23.4} {'orange': -1} </code></pre>
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 text: ").split()) print(b) </code></pre> <p>but in there the output is:</p> <pre><code>[['My', 'text']] </code></pre> <p>If I use split(),I am observing there are creating list including list.Why this...?? And how can I solve this problem..??</p>
<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-security -fPIC -I../../port -I../../gcore -I../../alg -I../../ogr/ -I../../ogr/ogrsf_frmts -I../../gnm -I../../apps -I/usr/include/python2.7 -I/usr/local/lib/python2.7/dist-packages/numpy/core/include -I/usr/include -c extensions/gdal_wrap.cpp -o build/temp.linux-x86_64-2.7/extensions/gdal_wrap.o -std=c++11 -I/usr/include/gdal extensions/gdal_wrap.cpp:3177:27: fatal error: cpl_vsi_error.h: No such file or directory compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 </code></pre> <p>and </p> <pre><code> ---------------------------------------- Failed building wheel for GDAL Running setup.py clean for GDAL Failed to build GDAL Installing collected packages: GDAL Running setup.py install for GDAL ... error Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-_spRXy/GDAL/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-NxpUaO-record/install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build/lib.linux-x86_64-2.7 copying gdal.py -&gt; build/lib.linux-x86_64-2.7 ... creating build/temp.linux-x86_64-2.7/extensions 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-security -fPIC -I../../port -I../../gcore -I../../alg -I../../ogr/ -I../../ogr/ogrsf_frmts -I../../gnm -I../../apps -I/usr/include/python2.7 -I/usr/local/lib/python2.7/dist-packages/numpy/core/include -I/usr/include -c extensions/gdal_wrap.cpp -o build/temp.linux-x86_64-2.7/extensions/gdal_wrap.o -std=c++11 -I/usr/include/gdal extensions/gdal_wrap.cpp:3177:27: fatal error: cpl_vsi_error.h: No such file or directory compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-_spRXy/GDAL/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-NxpUaO-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-_spRXy/GDAL/ </code></pre> <p>I've already tried <code>sudo apt-get install build-essential</code>, but stil the same error occurs.</p>
<p>Here is the answer I found that worked:</p> <p>&quot;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:&quot;</p> <pre><code>pip install gdal==1.11.2 --global-option=build_ext --global-option=&quot;-I/usr/include/gdal/&quot; </code></pre> <p>Where the 1.11.2 should be updated to your gdal_version, which can be found in the line <code># define GDAL_RELEASE_NAME</code> of the <code>/usr/include/gdal/gdal_version.h</code> file (at least on my system running Kubuntu).</p> <p>Link to original <a href="https://gist.github.com/cspanring/5680334" rel="nofollow noreferrer">github page</a> with this answer from Basaks, mentioned in the comment above by Craicerjack.</p>
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 that DB, but to a <em>different</em> database, since that db will interact with another Python script.</p> <p>Now, what i don't know, is how can i use another database in Django? Where should i define the whole second database configuration? </p> <p>This is what my basic view looks like at the moment:</p> <pre><code>def input(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = InputForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: messages.success(request, f"Success") # if a GET (or any other method) we'll create a blank form else: form = InputForm() return render(request, "main/data.html", context={"form":form}) </code></pre>
<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='database_name')</code></p> <p>Or if you're using it for a particular model in your project you can overload save method of this model to be stored in another DB:</p> <pre><code>class SomeModel(models.Model): foo = models.CharField(max_length=100) def save(self, ...): # ALL the signature super(SomeModel, self).save(using='database_name') </code></pre>
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/AnotherThing/'</p> <p>I need to take the values where there is more than one value in an observation and split them into individual rows. </p> <p>This is a general example of what the dataframe looks like before:</p> <pre><code>ID Date Name ColA ColB Col_of_Int ColC ColD 1 09/12 Ann String String OneThing/ String String 2 09/13 Pete String String OneThing/AnotherThing String String 3 09/13 Ann String String OneThing/AnotherThing/ThirdThing/ String String 4 09/12 Pete String String OneThing/ String String </code></pre> <p>What I want the output to be:</p> <pre><code>ID Date Name ColA ColB Col_of_Int ColC ColD 1 09/12 Ann String String OneThing String String 2 09/13 Pete String String OneThing String String 2 09/13 Pete String String Another Thing String String 3 09/13 Ann String String OneThing String String 3 09/13 Ann String String AnotherThing String String 3 09/13 Ann String String ThirdThing String String 4 09/12 Pete String String OneThing/ String String </code></pre> <p>I've tried the following: </p> <pre><code>df = df[df['Column1'].str.contains('/')] df_split = df[df['Column1'].str.contains('/')] df1 = df_split.copy() df2 = df_split.copy() split_cols = ['Column1'] for c in split_cols: df1[c] = df1[c].apply(lambda x: x.split('/')[0]) df2[c] = df2[c].apply(lambda x: x.split('/')[1]) new_rows = df1.append(df2) df.drop(df_split.index, inplace=True) df = df.append(new_rows, ignore_index=True) </code></pre> <p>This works, but I think it is creating new rows after every '/', which means that <strong><em>one</em></strong> new row is being created for every observation with only one value (where I want zero new rows), and two new rows are being created for every observation with two values (only need one), etc. </p> <p>This is particularly frustrating where there are three or more values in an observation because I am getting several unnecessary rows. </p> <p>Is there any way to fix this so that only observations with more than one get added to new rows? </p>
<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 you maximally have in your column. Here is another way, which I think achieves what you need:</p> <p>Take this example <code>df</code>:</p> <pre><code>df = pd.DataFrame({'column_of_interest':['onething/', 'onething/twothings/', 'onething/twothings/threethings/'], 'values1': [1,2,3], 'values2': [5,6,7]}) &gt;&gt;&gt; df column_of_interest values1 values2 0 onething/ 1 5 1 onething/twothings/ 2 6 2 onething/twothings/threethings/ 3 7 </code></pre> <p>This gets a bit messy because your want to presumably keep the data that is in the columns outside <code>column_of_interest</code>. So, you can temporarily find those and cast those aside, using:</p> <pre><code>value_columns = [i for i in df.columns if i != 'column_of_interest'] </code></pre> <p>And put them in the index for the following manipulation (which restores them at the end):</p> <pre><code>new_df = (df.set_index(value_columns) .column_of_interest.str.rstrip('/') .str.split('/') .apply(pd.Series) .stack() .rename('new_column_of_interest') .reset_index(value_columns)) </code></pre> <p>And your <code>new_df</code> then looks like:</p> <pre><code>&gt;&gt;&gt; new_df values1 values2 new_column_of_interest 0 1 5 onething 0 2 6 onething 1 2 6 twothings 0 3 7 onething 1 3 7 twothings 2 3 7 threethings </code></pre> <p>Or alternatively, using <code>merge</code>:</p> <pre><code>new_df = (df[value_columns].merge(df.column_of_interest .str.rstrip('/') .str.split('/') .apply(pd.Series) .stack() .reset_index(1, drop=True) .to_frame('new_column_of_interest'), left_index=True, right_index=True)) </code></pre> <p><strong>EDIT:</strong> On the dataframe you posted, this results in:</p> <pre><code> ID Date Name ColA ColB ColC ColD new_column_of_interest 0 1 09/12 Ann String String String String OneThing 0 2 09/13 Pete String String String String OneThing 1 2 09/13 Pete String String String String AnotherThing 0 3 09/13 Ann String String String String OneThing 1 3 09/13 Ann String String String String AnotherThing 2 3 09/13 Ann String String String String ThirdThing 0 4 09/12 Pete String String String String OneThing </code></pre>
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 = item_json['author'] tmp_item.location = item_json['location'] tmp_item.message = item_json['message'] msg_list.append(tmp_item) return {&quot;payload&quot;: msg_list} </code></pre> <p>Is there a way I can check if the item_json(message.body) does not have the following props, &quot;date&quot;, &quot;time&quot;, &quot;author&quot;, &quot;location&quot; and &quot;message&quot; to simply avoid it,and do not append to msg_list??</p> <p>So basically I just want to append if it meets that criteria, example would be</p> <pre><code>if item_json['date'] and item_json['time'] and item_json['author'].... : </code></pre>
<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(&quot;Key doesn't exist&quot;) </code></pre> <p>See <a href="https://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary">Check if a given key already exists in a dictionary</a></p>
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 how to fix.</p> <p>When I examine my code, I cant see any issue. It also looks identical to the code of the working project, so I really don't know what I am doing wrong.</p> <p>Here is the errors:</p> <pre><code>(env) PS C:\coding-projects\task-master-tdd&gt; flask shell Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32 App: project [development] Instance: C:\coding-projects\task-master-tdd\instance &gt;&gt;&gt; from project import db &gt;&gt;&gt; db Traceback (most recent call last): File &quot;&lt;console&gt;&quot;, line 1, in &lt;module&gt; File &quot;c:\coding-projects\task-master-tdd\env\lib\site-packages\flask_sqlalchemy\__init__.py&quot;, line 1060, in __repr__ self.engine.url if self.app or current_app else None File &quot;c:\coding-projects\task-master-tdd\env\lib\site-packages\flask_sqlalchemy\__init__.py&quot;, line 943, in engine return self.get_engine() File &quot;c:\coding-projects\task-master-tdd\env\lib\site-packages\flask_sqlalchemy\__init__.py&quot;, line 962, in get_engine return connector.get_engine() File &quot;c:\coding-projects\task-master-tdd\env\lib\site-packages\flask_sqlalchemy\__init__.py&quot;, line 555, in get_engine options = self.get_options(sa_url, echo) File &quot;c:\coding-projects\task-master-tdd\env\lib\site-packages\flask_sqlalchemy\__init__.py&quot;, line 570, in get_options self._sa.apply_driver_hacks(self._app, sa_url, options) File &quot;c:\coding-projects\task-master-tdd\env\lib\site-packages\flask_sqlalchemy\__init__.py&quot;, line 914, in apply_driver_hacks sa_url.database = os.path.join(app.root_path, sa_url.database) AttributeError: can't set attribute &gt;&gt;&gt; </code></pre> <p>my config.py file:</p> <pre><code>import os # load the environment variables from the .env file from dotenv import load_dotenv load_dotenv() # Determine the folder of the top-level directory of this project BASEDIR = os.path.abspath(os.path.dirname(__file__)) class Config: FLASK_ENV = 'development' TESTING = False DEBUG = False SECRET_KEY = os.getenv('SECRET_KEY', default='A very terrible secret key.') SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL', default=f&quot;sqlite:///{os.path.join(BASEDIR, 'instance', 'app.db')}&quot;) SQLALCHEMY_TRACK_MODIFICATIONS = False class DevelopmentConfig(Config): DEBUG = True class TestingConfig(Config): TESTING = True SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL', default=f&quot;sqlite:///{os.path.join(BASEDIR, 'instance', 'test.db')}&quot;) class ProductionConfig(Config): FLASK_ENV = 'production' </code></pre> <p>my user model:</p> <pre><code>from project import db, login_manager from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash class User(db.Model, UserMixin): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String, unique=True) hashed_password = db.Column(db.String) def __init__(self, username, password): self.username = username self.hashed_password = generate_password_hash(password) def is_password_valid(self, password): return check_password_hash(self.hashed_password, password) def __repr__(self): return '&lt;User {}&gt;'.format(self.id) @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) </code></pre>
<h2>Edit</h2> <p>If you're experiencing this, upgrading Flask-SQLAlchemy to &gt;= 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 SQLAlchemy to ~1.3 should no longer be necessary.</p> <hr /> <p>I ran into this issue a little earlier, but think I've figured out what's going on.</p> <p>SQLAlchemy is automatically installed as a dependency for Flask-SQLAlchemy and its latest release (1.4.0) introduces the following breaking change:</p> <blockquote> <p>The URL object is now an immutable named tuple. To modify a URL object, use the URL.set() method to produce a new URL object.</p> </blockquote> <p>I was able to fix this issue by simply installing the previous version of SQL Alchemy (1.3.23).</p>
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): photo = Image.open(input_image_path) # make the image editable drawing = ImageDraw.Draw(photo) black = (255, 255, 255) font = ImageFont.truetype(&quot;font.ttf&quot;, 40) drawing.text(pos, text, fill=black, font=font) photo.show() photo.save(output_image_path) if __name__ == '__main__': path=&quot;./bg&quot; files=os.listdir(path) d=random.choice(files) img = d watermark_text(img, '1.jpg', text='Risna Fadillah', pos=(0, 0)) </code></pre> <p>and error showing like this</p> <blockquote> <p>Traceback (most recent call last): File &quot;quotes.py&quot;, line 26, in watermark_text(img, '1.jpg', File &quot;quotes.py&quot;, line 10, in watermark_text photo = Image.open(input_image_path) File &quot;/data/data/com.termux/files/usr/lib/python3.8/site-packages/PIL/Image.py&quot;, line 2878, in open fp = builtins.open(filename, &quot;rb&quot;) FileNotFoundError: [Errno 2] No such file or directory: '1qqq.jpg'</p> </blockquote> <p>How to fix it?</p>
<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_path) # make the image editable drawing = ImageDraw.Draw(photo) black = (255, 255, 255) font = ImageFont.truetype(&quot;font.ttf&quot;, 40) drawing.text(pos, text, fill=black, font=font) photo.show() photo.save(output_image_path) if __name__ == '__main__': path=&quot;./bg/&quot; files=os.listdir(path) d=random.choice(files) img = path + d watermark_text(img, '1.jpg', text='Risna Fadillah', pos=(0, 0)) </code></pre> <p>sorry.</p>
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 fine, the static files are read. But when deploying to Divio’s test servers, no longer, just Bootstrap stylings. Am i meant to set debug to False somewhere, and if so where do I set it so? </p> <p>The dockerfile in the Divio project contains this command, which I sense is related to deploying live:</p> <pre><code># &lt;STATIC&gt; RUN DJANGO_MODE=build python manage.py collectstatic --noinput # &lt;/STATIC&gt; </code></pre> <p>What are the steps needed to transition from operating on the localhost and viewing my static correctly, to having it display in test/live deployments? I thought I could link them with the settings.py file but when I try to do this I experience a problem related to the following step:</p> <pre><code>Step 7/7 : RUN DJANGO MODE=build python manage.py collectstatic —noinput </code></pre> <p>It seems to hang almost indefinitely, failing after a long time - the following are the last few lines of my logs.</p> <pre><code>Copying '/virtualenv/lib/python3.5/site-packages/wagtail/admin/static/wagtailadmin/fonts/opensans-regular.woff' Copying '/virtualenv/lib/python3.5/site-packages/wagtail/admin/static/wagtailadmin/fonts/wagtail.svg' Copying '/virtualenv/lib/python3.5/site-packages/wagtail/admin/static/wagtailadmin/fonts/robotoslab-regular.woff' Copying '/virtualenv/lib/python3.5/site-packages/wagtail/admin/static/wagtailadmin/fonts/opensans-semibold.woff' </code></pre> <p>Thanks all in advance for your time and help!</p>
<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 run a local project in live configuration</a>. You can override these manually if you need to, but there is no need whatsoever in normal use.</p> <p>If you have added settings related to static file handling to your <code>settings.py</code>, try commenting them out - almost certainly, it will just work.</p>
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 program should replace the corresponding element by "XX". The program should continuously proceed in the forementioned fashion until all elements are verified. If all the elements of any row, column or either diagonals are replaced by "XX", the program is to print the final scenario (the final stage of the matrix), with the correct elements replaced by "XX" and the word BINGO!, and just the final scenario otherwise. The first line of the matrix contains the letters B I N G O, thus identifying each matrix's column by its corresponding label letter, "B" for the first, "I" for the second, and so on, in a way that the input should be on the form: label_letter-XY, where X and Y represent the numerals. I've already managed to correctly print the Bingo card, but I'm still not able to iterate over the matrix's lines and columns, verify whether of not the candidate numbers are in</p> <h2>those columns, and replace them by "XX". I'm not actually sure what my program is actually doing, since it's only printing the original bingo card, which makes me conclude that the I'm not correctly accessing the matrix. If anyone could give me some insight on what I'm doing wrong, I'll be extremely grateful!</h2> <pre><code>m=5 #lines n=5 #columns/rows mat=[] data=[] for i in range(m): col=input().split() mat.append(col) num=int(input()) blank='' def printbingocard(mat): print("+", end=blank) print((16)*"-" + "+") print("| ", end=blank) print("B ", end=blank) print("I ", end=blank) print("N ", end=blank) print("G ", end=blank) print("O ", end=blank) print("|") print("+" + (16)*"=" + "+") for i in range(m): print("| ", end=blank) for j in range(n): print(mat[i][j] + " ", end='') print("|") print("+" + (16)*"-" + "+") printbingocard(mat) for i in range(num): input=str(input()).split("-") input_data.append(input) for j in range(n): if input_data[i][0]=="B": if mat[0][j]==input_data[i][1]: mat[0][j]="XX" printbingocard(mat) if input_data[i][0]=="I": if mat[1][j]==input_data[i][1]: mat[1][j]="XX" printbingocard(mat) if input_data[i][0]=="N": if mat[2][j]==input_data[i][1]: mat[2][j]="XX" printbingocard(mat) if input_data[i][0]=="G": if mat[3][j]==input_data[i][1]: mat[3][j]="XX" printbingocard(mat) if input_data[i][0]=="O": if mat[4][j]==input_data[i][1]: mat[4][j]="XX" printbingocard(mat) for i in range(m): for j in range(n): if mat[i][j]== "XX": bol=True else: bol=False break for j in range(n): for i in range(m): if mat[i][j]== "XX": bol=True else: bol=False break printbingocard(mat) if bol==True: print("BINGO!") for j in range(n): for i in range(m): if mat[j][j]=="XX" or mat[i][i]=="XX": bol=True else: bol=False break printbingocard(mat) if bol==True: print("BINGO!") for j in range(4,n,-1): for i in range(1,m,1): if mat[i][j]=="XX": bol=True else: bol=False break printbingocard(mat) if bol==True: print("BINGO!") </code></pre>
<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_numbers = bingo_numbers # I need this later on to know what numbers are left random.shuffle(bingo_numbers) print(bingo_numbers) completed_lines = 0 for i in range(m): col=bingo_numbers[i*5:(i+1)*5] mat.append(list(col)) def imprimecartela(mat, completed_lines): # Function to print the bingo card print("+", end=branco) print((16)*"-" + "+") print("| ", end=branco) if (completed_lines == 0): print(5*"_ ", end=branco) elif(completed_lines == 1): print("B ", end=branco) print(4*"_ ", end=branco) elif(completed_lines == 2): print("B ", end=branco) print("I ", end=branco) print(3*"_ ", end=branco) elif(completed_lines == 3): print("B ", end=branco) print("I ", end=branco) print("N ", end=branco) print(2*"_ ", end=branco) elif(completed_lines == 4): print("B ", end=branco) print("I ", end=branco) print("N ", end=branco) print("G ", end=branco) print("_ ", end=branco) else: print("B ", end=branco) print("I ", end=branco) print("N ", end=branco) print("G ", end=branco) print("O ", end=branco) print("|") print("+" + (16)*"=" + "+") for i in range(m): print("| ", end=branco) for j in range(n): if mat[i][j] != 0: # Check values of &lt;mat&gt;: if non zero print number with 2 digits, if zero print 'XX' print(str(mat[i][j]).zfill(2) + " ", end='') else: print("XX" + " ", end='') print("|") print("+" + (16)*"-" + "+") def check_completed_lines(mat): completed_lines = 0 for i in range(m): temp = [x[i] for x in mat] if (temp == [0,0,0,0,0]): completed_lines += 1 for x in mat: if x==[0,0,0,0,0]: completed_lines += 1 if (mat[0][0] == 0 and mat[1][1] == 0 and mat[2][2] == 0 and mat[3][3] == 0 and mat[4][4] == 0): completed_lines += 1 if (mat[0][4] == 0 and mat[1][3] == 0 and mat[2][2] == 0 and mat[3][1] == 0 and mat[4][0] == 0): completed_lines += 1 return completed_lines imprimecartela(mat,completed_lines) while (len(remaining_numbers) != 0): # Looping through turns call_number = random.choice(remaining_numbers) # &lt;-- Next number print("next number is : ", call_number) remaining_numbers = np.delete(remaining_numbers, np.where(remaining_numbers==call_number)) # Remove the number so it doesn't occur again for i in mat: if call_number in i: i[i.index(call_number)] = 0 # Change the value current round number to 0 in &lt;mat&gt; completed_lines = check_completed_lines(mat) # This function checks rows and columns and diagonals for completeness, every completed line will add a letter to "BINGO" on the card imprimecartela(mat, completed_lines) if completed_lines == 5: break # When 5 lines are completed, you win, break </code></pre> <p>I added comments inside the code to explain the process, but basically you don't need to change the matrix to include <code>'XX'</code> just change the value to <code>0</code> since zero is already not a bingo number and use your print function to print <code>'XX'</code> if the value is <code>0</code>. Cheers.</p>
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://i.stack.imgur.com/T9HDX.png" rel="nofollow noreferrer">Table - Image</a></p> <p><strong>Python Code:</strong></p> <pre><code>for emailid in items: # getting the mail content resp, data = m.fetch(emailid, '(UID BODY[TEXT])') text = str(data[0][1]) tree = BeautifulSoup(text, &quot;lxml&quot;) table_tag = tree.select(&quot;table&quot;)[0] tab_data = [[item.text for item in row_data.select(&quot;td&quot;)] for row_data in table_tag.select(&quot;tr&quot;)] print(table_tag) for data in tab_data: writer.writerow(data) print(' '.join(data)) </code></pre> <p><strong>Results:</strong></p> <p><em>\r\nQuick No.\r\n \r\nOrder No=\r\n\r\n \r\nPart Number\r\n \r\nDescription\r\n \r\nUOM=\r\n\r\n \r\nOrder Qty\r\n \r\nQty Received\r\n \r\nReceived Date\r\n(dd/mm/yyyy)\r\n \r\nAdditional Information\r\n \r\nE03B1A\r\n \r\nE0015130\r\n \r\nYK71114105=\r\np&gt;\r\n \r\nCOLOUR TOP ASSY (R)=\r\n\r\n \r\nPIECE\r\n \r\n1\r\n \r\n1\r\n \r\n06/10/2020=\r\np&gt;\r\n \r\n \r\nE03B1E\r\n \r\nE0015134\r\n \r\nYK78804497=\r\np&gt;\r\n \r\nDIE BUTTON=\r\np&gt;\r\n \r\nPIECE\r\n \r\n4\r\n \r\n4\r\n \r\n06/10/2020=\r\np&gt;\r\n \r\n</em></p> <p><strong>Expected Result</strong></p> <ul> <li>Quick No. Order No Part Number</li> <li>nE03B1A nE0015130 nYK71114105</li> <li>nE03B1E nE0015134 nYK78804497</li> </ul> <p>Thanks in advance (This is my first post so please be gentle)</p>
<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(&quot;td&quot;)] for row_data in table_tag.select(&quot;tr&quot;)] </code></pre> <p>But could I suggest, just let pandas parse the table from the html:</p> <pre><code>import pandas as pd for emailid in items: # getting the mail content resp, data = m.fetch(emailid, '(UID BODY[TEXT])') text = str(data[0][1]) table = pd.read_html(text)[0] df_obj = table.select_dtypes(['object']) table[df_obj.columns] = df_obj.apply(lambda x: x.str.strip()) print(table) table.to_csv('file.csv', index=False) </code></pre>
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 &gt; 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 curious what the <code>,</code> operator is doing.</p> <p>I have not been able to find an answer in the documentation so far. Can anyone provide an explanation ?</p>
<p><code>a &gt; b, c</code> is the tuple <code>((a &gt; 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 tuples are truish, so this would always trigger the same path through the conditional.</p>
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}, {'x':12, 'y':10.84}, {'x':7, 'y':4.82}, {'x':5, 'y':5.68}, ] def range_y(list_of_dicts): y = lambda dict: dict['y'] return y(min(list_of_dicts, key=y)), y(max(list_of_dicts, key=y)) range_y(s1) </code></pre> <p>This works and gives the intended result.</p> <p>What I don't understand is the <code>y</code> before the <code>(min(list_of_dicts, key=y)</code>. I know I can find the <code>min</code> and <code>max</code> with <code>min(list_of_dicts, key=lambda d: d['y'])['y']</code> where the <code>y</code> parameter goes at the end (obviously swapping <code>min</code> for <code>max</code>).</p> <p>Can someone explain to me what is happening in <code>y(min(list_of_dicts, key=y))</code> with the <code>y</code> and the parenthetical?</p>
<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 value under key <code>'y'</code></p> <p>so putting it together, you get the value at key <code>'y'</code> in the dictionary from the list with the smallest value under key <code>'y'</code> of all dictionaries in the list</p>
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\local-packages\Python37\site-packages\elasticsearch\compat.py) </code></pre> <p>elasticsearch version: 7.13.3 elasticsearch-dsl version: 7.4.0</p> <p>I have tried:</p> <pre><code>from collections.abc import Mapping </code></pre> <p>And can't seem to google my way to an answer</p>
<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_id IN (1,2) ORDER BY type_id, timestamp LIMIT 10 ): out of shared memory HINT: You might need to increase max_pred_locks_per_transaction </pre> <p>We increased this number but still we get a out of shared memory (max_pred_locks_per_transaction = 192). Everytime we start the script again it runs for some time then gives this error message. On Postgres 8.1 we did not have this problem.</p> <p>Here is a piece of the postgresql log file:</p> <pre> 2012-06-28 02:55:43 CEST HINT: Use the escape string syntax for backslashes, e.g., E'\\'. 2012-06-28 02:55:43 CEST WARNING: nonstandard use of \\ in a string literal at character 271 2012-06-28 02:55:43 CEST HINT: Use the escape string syntax for backslashes, e.g., E'\\'. 2012-06-28 02:55:43 CEST WARNING: nonstandard use of \\ in a string literal at character 271 2012-06-28 02:55:43 CEST HINT: Use the escape string syntax for backslashes, e.g., E'\\'. 2012-06-28 02:56:11 CEST WARNING: there is already a transaction in progress 2012-06-28 02:57:01 CEST WARNING: there is already a transaction in progress 2012-06-28 02:57:01 CEST ERROR: out of shared memory 2012-06-28 02:57:01 CEST HINT: You might need to increase max_pred_locks_per_transaction. 2012-06-28 02:57:01 CEST STATEMENT: SELECT * FROM xml_fifo.fifo WHERE type_id IN (1,2) ORDER BY type_id ASC, timestamp LIMIT 10 2012-06-28 02:57:01 CEST ERROR: out of shared memory 2012-06-28 02:57:01 CEST HINT: You might need to increase max_pred_locks_per_transaction. 2012-06-28 02:57:01 CEST STATEMENT: SELECT * FROM xml_fifo.fifo WHERE type_id IN (1,2) ORDER BY type_id ASC, timestamp LIMIT 10 </pre> <p>What would be the problem?</p>
<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 you describe when using serializable transactions in 9.1.</p> <p>One solution would be to use the <code>REPEATABLE READ</code> transaction isolation level instead of SERIALIZABLE. This will give you exactly the same behavior that SERIALIZABLE transactions did in PostgreSQL versions before 9.1. Before deciding to do that, you might want to read up on the differences, so that you know whether it is likely to be worthwhile to instead reconfigure your environment to avoid the issue at the SERIALIZABLE isolation level:</p> <p><a href="http://www.postgresql.org/docs/9.1/interactive/transaction-iso.html">http://www.postgresql.org/docs/9.1/interactive/transaction-iso.html</a></p> <p><a href="http://wiki.postgresql.org/wiki/SSI">http://wiki.postgresql.org/wiki/SSI</a></p> <p>If increasing max_pred_locks_per_transaction doesn't fix it (and you could try going significantly higher without chewing up too much RAM), you could try increasing max_connections (without increasing actual connections used).</p> <p>I worked on the Serializable Snapshot Isolation feature for 9.1, along with Dan R.K. Ports of MIT. The cause of this problem is that the heuristic for combining multiple fine-grained predicate locks into a single coarser-grained lock is really simple in this initial version. I'm sure it can be improved, but any information you could give me on the circumstances under which it is hitting this problem would be valuable in terms of designing a better heuristic. If you could tell me a little bit about the number of CPUs you are using, the number of active database connections, and a bit about the workload where you hit this, I would really appreciate it.</p> <p>Thanks for any info, and my apologies for the problem.</p>
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> `Alias /media/ C:/Programs/TestDjango/mysite/media/ &lt;Directory C:/Programs/TestDjango/mysite/media/&gt; Order deny,allow Allow from all &lt;/Directory&gt; WSGIScriptAlias / C:/Programs/TestDjango/mysite/apache/django.wsgi &lt;Directory C:/Programs/TestDjango/mysite/apache&gt; Order deny,allow Allow from all &lt;/Directory&gt;` </code></pre> <p>and restarted the Apache, On opening localhost/mysite i get a Microsoft Visual C++ Library runtime error, and the Apache error log shows "Caught ImproperlyConfigured while rendering: Error loading pyodbc module: DLL load failed: A dynamic link library (DLL) initialization routine failed."....My Django app run in WAMP but wish to know where did i go wrong using Apache2.2.22 alone. Followed many Django documentation but still the same, Please to help me find where did i go wrong. thanks</p> <p>(identation was fixed by guettli)</p>
<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.2.21 Install the modwsgi module. </p> <p>The module file will be named something like mod_wsgi-win32-ap22py26-2.6.so <a href="http://code.google.com/p/modwsgi/downloads/list/" rel="nofollow">get mod_wsgi</a>.</p> <p>Copy it to the modules directory of the Apache installation. E.g., C:/Program Files/Apache Software Foundation/Apache2.2/modules.</p> <p>Rename it to mod_wsgi.so. Right click--> properties click Unblock and apply</p> <p>Open Apache's http.conf file.</p> <p>Add the line LoadModule wsgi_module modules/mod_wsgi.so before all the other LoadModule entries.</p> <p>Configure Apache for your Django project by adding the following to end of http.conf:</p> <pre><code># Static content Alias /media/ C:/Programs/TestDjango/mysite/media/ &lt;Directory C:/Programs/TestDjango/mysite/media/&gt; Order deny,allow Allow from all &lt;/Directory&gt; # Django dynamic content WSGIScriptAlias / C:/Programs/TestDjango/mysite/apache/django.wsgi &lt;Directory C:/Programs/TestDjango/mysite/apache&gt; Order deny,allow Allow from all &lt;/Directory&gt;` </code></pre> <p>Where icardtest is the Django project root. The paths below icardtest will be specific to your project. This configuration serves all static media via the URL space /media/ and all the rest via WSGI and Django. Create a file django.wsgi and add the following to it:</p> <pre><code> ` import os import sys sys.path.append('C:/Programs/TestDjango') os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler()` </code></pre> <p>Restart Apache.</p>
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, I append the utils path to the scripts in order to import utils. </p> <p>However, this seems to be bad practice (or "not Pythonic"). In addition, the groups in actuality is not as flat as this and there are more util folders than listed above. Hence, the append path solution is getting messier and messier.</p> <p>How can I organize this differently?</p>
<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>Organization</strong> </p> <pre><code>runscript.py group1 __init__.py script1.py utils __init__.py utils1.py </code></pre> <p><strong>Invocation</strong></p> <pre><code>python runscript -g grp1 -s script1 </code></pre> <p><strong>runscript.py</strong></p> <pre><code>import utils def main(): script_to_exec = process_args() import script_to_exec as script # __import__ script.main() main() </code></pre> <p>Maybe your script can have main function which is then invoked by runscript. I suggest that you have a script at the top level which imports the script. </p>
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 getting worse. The code is only running in the ELSE part up to that point and 'listoflines' is constant at that point (850000 lines in list) and of type 'list[ ]' as well as 'offset' is just a constant 'int' at that point.</p> <p>The source file has millions of lines up to over 20 million lines.</p> <p>'dummyline not in listoflines' should take the same time every time.</p> <pre><code>with open(filename, &quot;rt&quot;) as source: for dummyline in source: if (len(dummyline) &gt; 1) and (dummyline not in listoflines): # RUN compute # this part is not reached where I have the problem else: if dummyalreadycheckedcounter % 10000 == 0: print (&quot;%d/%d: %s already checked or not valid &quot; % (dummyalreadycheckedcounter, offset, dummyline) ) dummyalreadycheckedcounter = dummyalreadycheckedcounter +1 </code></pre>
<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 this but I'd suggest turning this into a processing pipe line, so your compute part would not be mixed with the dedup logic</p> <pre><code>def dedupped_stream(filename): seen = set() with open(filename, &quot;rt&quot;) as source: for each_line in source: if len(line)&gt;1 and each_line not in seen: seen.add(each_line) yield each_line </code></pre> <p>then you can do just</p> <pre><code>for line in dedupped_stream(...): ... </code></pre> <p>you would not need to worry about deduplication here at all</p>
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 content.</p> <pre><code>@app.route('/', methods=['GET', 'POST']) def home(): print(request.form) if 'btn_search' in request.form: search = request.args.get('search') print(search) r = requests.get('http://127.0.0.1:8000/estacionesbykm/?ciudad='+search) render_template('estacion_por_ciudad.html', estaciones=json.loads(r.text), ciudad=search) else: r = requests.get('http://127.0.0.1:8000/estaciones/') return render_template('principal.html', estaciones=json.loads(r.text)) </code></pre> <p>And the template of the homepage is also simple:</p> <pre><code> &lt;h2&gt;Search&lt;/h2&gt; &lt;form method="GET"&gt; &lt;input name="search" type="text" placeholder="Search city"&gt; &lt;button name= "btn_search" type="submit"&gt;Search&lt;/button&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>There is an special reason to why the form is returning me empty all the time?</p> <p>Help would be appreciated.</p>
<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" alt="enter image description here"></a></p> <p>Following regular formula (Q3 + 1.5 * IQR) it should be 7 and -1, but as seen on pic it's 5 and 1. Looks like formula uses 0.5 instead of 1.5. How can I change back to standard?</p> <pre><code>Q1 = df['a'].quantile(0.25) Q2 = df['a'].quantile(0.50) Q3 = df['a'].quantile(0.75) print(Q1,Q2, Q3) IQR = Q3 - Q1 MaxO = (Q3 + 1.5 * IQR) MinO = (Q1 - 1.5 * IQR) print("IQR:", IQR, "Max:", MaxO, "Min:" ,MinO) </code></pre> <p>Outcome:</p> <p>2.0 3.0 4.0</p> <p>IQR: 2.0 Max:%: 7.0 Min:% -1.0</p> <p>(Q1, Q2, Q3 nad IQR are correct, but not Min or Max)</p>
<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. Similarly, a distance of 1.5 times the IQR is measured out below the lower quartile and a whisker is drawn up to the lower observed point from the dataset that falls within this distance. All other observed points are plotted as outliers.</p> </blockquote>
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> <pre><code> snr = [1e10, 5, 1, .5, .1, .05] tau = [1, 8, 10, 14, 35, 80] fig1, ax1 = plt.subplots() def fit(x, a, b, c): #c: asymptote #return a * np.exp(b * x) + 1. return np.power(x,a)*b + c xlist = np.arange(0,len(snr),1) p0 = [-1., 1., 1.] params = curve_fit(fit, xlist, tau, p0)#, bounds=([-np.inf, 0., 0.], [0., np.inf, np.inf])) a, b, c = params[0] print(a,b,c) ax1.plot(xlist, fit(xlist, a, b, c), c='b', label='Fit') #ax1.plot(snr, tau, zorder=-1, c='k', alpha=.25) ax1.scatter(snr, tau) ax1.set_xscale('log') #ax1.set_xlim(.02, 15) plt.show() </code></pre> <hr> <p><strong>Update 1:</strong> reference figure, following Eric M's code: <a href="https://i.stack.imgur.com/0Oz8o.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0Oz8o.png" alt="Figure"></a> Will comment in the post below.</p> <hr> <p><strong>Fix for Update 1:</strong> <code>xlist = np.arange(0.01,10000,1)/1000+0.01</code></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 scipy.optimize import curve_fit snr = [1e10, 5, 1, .5, .1, .05] tau = [1, 8, 10, 14, 35, 80] fig1, ax1 = plt.subplots() def fit(x, a, b, c): return np.power(x, a)*b + c xlist = np.arange(0.01,10000,1)/1000+0.01 xlist = np.append(xlist, 1e10) p0 = [-10, 10., 1.] params = curve_fit(fit, snr, tau, p0) print('Fitting parameters: {}'.format(params[0])) ax1.plot(xlist, fit(xlist, *params[0]), c='b', label='Fit') ax1.scatter(snr, tau) ax1.set_xscale('log') plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/2S1dm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2S1dm.png" alt="enter image description here"></a></p>
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}, {"content": "33", "title": "apple", "info": "", "time": 1581877014}, {"content": "16", "title": "banana", "info": "", "time": 1561877014}, {"content": "aa", "title": "banana", "info": "", "time": 1582876014}, ] </code></pre> <p>my code </p> <pre><code>def cumsum(is_test=False): cdata = pd.to_numeric(s.str.get('content'), errors='coerce').cumsum() if is_test: print(list(cdata)) return list(cdata) for i, v in enumerate(s): s.iloc[i]['content'] = str(cdata[i]) return list(s) assert cumsum(is_test=True)==[1.0, 3.0, 6.0, 18.0, 51.0, 67.0, 'nan'] </code></pre> <p>res is not true, how to solve? final how to my code pythonic way? Replace the result calculated by cumsum with the content at the specified position。 i hope data is :</p> <pre><code>[{'content': '1.0', 'title': 'app sotre', 'info': '', 'time': 1578877014}, {'content': '3.0', 'title': 'app', 'info': '', 'time': 1579877014}, {'content': '6.0', 'title': 'pandas', 'info': '', 'time': 1582877014}, {'content': '18.0', 'title': 'a', 'info': '', 'time': 1582876014}, {'content': '51.0', 'title': 'apple', 'info': '', 'time': 1581877014}, {'content': '67.0', 'title': 'banana', 'info': '', 'time': 1561877014}, {'content': 'nan', 'title': 'banana', 'info': '', 'time': 1582876014}] </code></pre>
<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 old, new in zip(data, cdata): old['content'] = str(new) print (data) [{'content': '1.0', 'title': 'app sotre', 'info': '', 'time': 1578877014}, {'content': '3.0', 'title': 'app', 'info': '', 'time': 1579877014}, {'content': '6.0', 'title': 'pandas', 'info': '', 'time': 1582877014}, {'content': '18.0', 'title': 'a', 'info': '', 'time': 1582876014}, {'content': '51.0', 'title': 'apple', 'info': '', 'time': 1581877014}, {'content': '67.0', 'title': 'banana', 'info': '', 'time': 1561877014}, {'content': 'nan', 'title': 'banana', 'info': '', 'time': 1582876014}] </code></pre>
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 the Bride Part II (1995) Comedy </code></pre> <p>DF2:</p> <pre><code>userId movieId rating timestamp 0 1 1 4.0 964982703 1 1 3 4.0 964981247 2 1 6 4.0 964982224 3 1 47 5.0 964983815 4 1 50 5.0 964982931 </code></pre> <p>My new DataFrame should look like this.</p> <p>DF_new:</p> <pre><code>userID Toy Story Jumanji Grumpier Old Men Waiting to Exhale Father of the Pride Part II 1 4.0 2 3 4 </code></pre> <p>The Values will be the ratings of the the indiviudel user to each movie. The movie titles are now the columns. The userId are now the rows.</p> <p>I think it will work over concatinating via the movieid. But im not sure how to do this exactly, so that i still have the movie names attached to the movieid.</p> <p>Anybody has an idea?</p>
<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</a> is the standard way to go.</li> <li>The rest is about mapping the <code>movieID</code>s to their names. This can be easily done by direct substitution on <code>df.columns</code>.</li> </ol> <p>In addition, if movies receiving no ratings were to be listed as well, just insert the missing <code>movieID</code>s directly before name substitution mentioned previously.</p> <h2>Code</h2> <pre><code>import pandas as pd import numpy as np df1 = pd.DataFrame( data={ &quot;movieId&quot;: [1,2,3,4,5], &quot;title&quot;: [&quot;toy story (1995)&quot;, &quot;Jumanji (1995)&quot;, &quot;Grumpier 33 (1995)&quot;, # shortened for printing &quot;Waiting 44 (1995)&quot;, &quot;Father 55 (1995)&quot;], } ) # to better demonstrate the correctness, 2 distinct user ids were used. df2 = pd.DataFrame( data={ &quot;userId&quot;: [1,1,1,2,2], &quot;movieId&quot;: [1,2,2,3,5], &quot;rating&quot;: [4,5,4,5,4] } ) # 1. Produce the main table df_new = df2.pivot_table(index=[&quot;userId&quot;], columns=[&quot;movieId&quot;], values=&quot;rating&quot;) print(df_new) # already pretty close Out[17]: movieId 1 2 3 5 userId 1 4.0 4.5 NaN NaN 2 NaN NaN 5.0 4.0 # 2. map movie ID's to titles # name lookup dataset df_names = df1[[&quot;movieId&quot;, &quot;title&quot;]].set_index(&quot;movieId&quot;) # strip the last 7 characters containing year # (assume consistent formatting in df1) df_names[&quot;title&quot;] = df_names[&quot;title&quot;].apply(lambda s: s[:-7]) # (optional) fill unrated columns and sort for movie_id in df_names.index.values: if movie_id not in df_new.columns.values: df_new[movie_id] = np.nan else: df_new = df_new[df_names.index.values] # replace IDs with titles df_new.columns = df_names.loc[df_new.columns, &quot;title&quot;].values </code></pre> <h2>Result</h2> <pre><code>df_new Out[16]: toy story Jumanji Grumpier 33 Waiting 44 Father 55 userId 1 4.0 4.5 NaN NaN NaN 2 NaN NaN 5.0 NaN 4.0 </code></pre>
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="lang-py prettyprint-override"><code>while True: pygame.time.Clock().tick(fps) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() #input elif event.type == pygame.KEYDOWN: #snake if event.key == ord('w'): change_to = 'UP' if event.key == ord('s'): change_to = 'DOWN' if event.key == ord('a'): change_to = 'LEFT' if event.key == ord('d'): change_to = 'RIGHT' #snake2 if event.key == pygame.K_UP: change2_to = 'UP' if event.key == pygame.K_DOWN: change2_to = 'DOWN' if event.key == pygame.K_LEFT: change2_to = 'LEFT' if event.key == pygame.K_RIGHT: change2_to = 'RIGHT' #quit game if event.key == pygame.K_ESCAPE: #here is where was supposed to restart the game </code></pre> <p>i cut the major part to not be so long but i dont know how to restart my game</p>
<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: restart = True </code></pre>
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</code> (i.e. obj2) so that <code>obj.x</code> and <code>obj2.x</code> are not the same object, but <code>obj.a</code> and <code>obj2.a</code> are the same object (same pointer).</p> <p>If I make something like <code>obj.a = foo</code>, then <code>obj2.a == foo</code> should be true.</p> <p>I'm creating <code>obj2</code> by making <code>obj2 = copy.deepcopy(obj)</code>, but they are not sharing the pointer, it's creating another instance <code>obj2.a</code> and <strong>using more memory then needed</strong>.</p> <p>I need them to work exactly like static variables in Java. How can I do this?</p>
<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 will change values for all instances of this class.</p> <pre><code>Obj.a = foo # changes the field a for all instances </code></pre> <p>Also if you want to compare references you should use <code>is</code> keyword</p> <pre><code>class Dog: type=&quot;Dog&quot; a = Dog() from copy import deepcopy b = deepcopy(a) a.type is b.type &gt;&gt;True a.type == b.type &gt;&gt;True a.type = &quot;Cat&quot; a.type is b.type &gt;&gt;False b.type is Dog.type &gt;&gt;True </code></pre>
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 established. However, my experience is suggesting that it is not blocking and yields to the loop. So here I have two questions</p> <ol> <li>I want to make sure if <code>await asyncio.open_connection</code> really yields to the event loop?</li> <li>And if yes, what is the best way to avoid this?</li> </ol>
<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): &quot;&quot;&quot;A wrapper for create_connection() returning a (reader, writer) pair. The reader returned is a StreamReader instance; the writer is a StreamWriter instance. The arguments are all the usual arguments to create_connection() except protocol_factory; most common are positional host and port, with various optional keyword arguments following. Additional optional keyword arguments are loop (to set the event loop instance to use) and limit (to set the buffer limit passed to the StreamReader). (If you want to customize the StreamReader and/or StreamReaderProtocol classes, just copy the code -- there's really nothing special here except some convenience.) &quot;&quot;&quot; loop = events.get_running_loop() reader = StreamReader(limit=limit, loop=loop) protocol = StreamReaderProtocol(reader, loop=loop) transport, _ = await loop.create_connection( lambda: protocol, host, port, **kwds) writer = StreamWriter(transport, protocol, reader, loop) return reader, writer </code></pre> <p>it calls <code>loop.create_connection</code> which is also <code>await</code> call, and about <code>loop.create_connection</code>:</p> <blockquote> <p>This method will try to establish the connection in the <strong>background</strong>. When successful, it returns a (transport, protocol) pair.</p> </blockquote> <p>Says the Docs. So it is then yielding control to event loop and let other coroutines run, while previous coroutine is waiting in <code>await</code> for connection to be established.</p> <hr /> <ol start="2"> <li>If you absolutely sure you want to block the thread that is running the event loop then you can just use low-level <a href="https://docs.python.org/3/library/socket.html" rel="nofollow noreferrer">socket</a>. Honestly I really am against this idea because there's not many reason to do so.</li> </ol> <hr /> <p>Just a minor addition, I saw you wasn't accepting answers on your previous questions. People write answers spending their own time and effort to help other peoples in help. If answer solved your questions then marking them as answer is a way to thank their efforts! Please refer <a href="https://stackoverflow.com/tour">Stackoverflow tour</a> for more tips!</p>
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 my code</p> <pre><code>def show_toolbar(request): return not request.is_ajax() and request.user and request.user.username == 'ptar' DEBUG_TOOLBAR_CONFIG = {'SHOW_TOOLBAR_CALLBACK': 'libert.settings.show_toolbar',} </code></pre> <p>MIDDLEWARES</p> <pre><code>MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', &quot;debug_toolbar.middleware.DebugToolbarMiddleware&quot;,# 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'session_security.middleware.SessionSecurityMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'online_users.middleware.OnlineNowMiddleware', #'user_visit.middleware.UserVisitMiddleware', #'django_htmx.middleware.HtmxMiddleware', </code></pre> <p>]</p>
<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>&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt;BLUE - Amil Ltda14/07/2020;;102636;Name censured;213113;10101039;1;Única;20/09/2020;102636;HCRIANÇASJ;83,00; &lt;br&gt;BLUE18 - Amil Ltda21/07/2020;;102636;Name Censured Again;213029;10101039;1;Única;20/09/2020;102636;HCRI;83,00; </code></pre> <p>But python interprets like one string and I need to convert in <code>csv</code> or <code>json</code> like format.</p> <p>I'm trying to use <code>.replace (&lt;br&gt;,//n)</code> but it didn't work.</p> <p>Plus, I need to delete the following section:</p> <pre><code>&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt;BLUE - Amil Ltda14/07/2020 </code></pre>
<pre><code>const str = `&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt;BLUE - Amil Ltda14/07/2020;;102636;Name censured;213113;10101039;1;Única;20/09/2020;102636;HCRIANÇASJ;83,00; &lt;br&gt;BLUE18 - Amil Ltda21/07/2020;;102636;Name Censured Again;213029;10101039;1;Única;20/09/2020;102636;HCRI;83,00;`; const lines = str.split(/&lt;br&gt;/gs); for (let i = 0; i &lt; lines.length; i++) { lines[i] = lines[i].replace(/(.*)BLUE\d*\s-\sAmil\sLtda\d+\/\d+\/\d+;;/, ''); } console.log(lines); </code></pre>
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>Unfortunately, I can't figure out how to accomplish this. It appears that the values for the bars are added to the 'base' vector (as a relative value) not used as absolute positions. Plotly does not appear to understand datetime.timedelta() objects. Printing the timeline() figure version shows the values as an array of floating point values which it isn't clear how they are computed. I've tried simply copying them, but this ends up with plotly thinking the x axis isn't a datetime axis.</p> <p>Any clue would be most welcome. Either how to use the Box() to draw the appropriate figure, or how to embed/animate/layout the px.timeline() figure in a notebook.</p> <pre><code>import pandas as pd import plotly.express as px import plotly.graph_objects as go from datetime import datetime # the data: df = pd.DataFrame([ dict(Task=&quot;one&quot;, Start=datetime(2009,1,1), Finish=datetime(2009,4,28)), dict(Task=&quot;two&quot;, Start=datetime(2009,5,5), Finish=datetime(2009,7,15)), dict(Task=&quot;three&quot;, Start=datetime(2009,7,20), Finish=datetime(2009,9,30)) ]) # working plotly express figure: pxfig = px.timeline(df, x_start=&quot;Start&quot;, x_end=&quot;Finish&quot;, y=&quot;Task&quot;) pxfig.show() # looks great # Broken bar figure: plainfig = go.Figure() plainfig.add_bar(base=df['Start'], # x=pxfig.data[0].x, # this breaks the axis as they are not of type datetime. # x=df['Finish']-df['Start'], # this doesn't produce the right plot x=df['Finish'], # these appear to be relative to base, not absolute y=df['Task'], orientation='h') plainfig.show() # looking at the two shows interesting differences in the way the x data is stored print(pxfig) print(plainfig) </code></pre> <p><a href="https://i.stack.imgur.com/XDkln.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XDkln.png" alt="TimelinePlot" /></a> <a href="https://i.stack.imgur.com/jXIc6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jXIc6.png" alt="BoxPlot" /></a></p> <pre><code>Figure({ 'data': [{'alignmentgroup': 'True', 'base': array([datetime.datetime(2009, 1, 1, 0, 0), datetime.datetime(2009, 5, 5, 0, 0), datetime.datetime(2009, 7, 20, 0, 0)], dtype=object), 'x': array([1.01088e+10, 6.13440e+09, 6.22080e+09]), 'xaxis': 'x', 'y': array(['one', 'two', 'three'], dtype=object), 'yaxis': 'y'}], 'layout': {'barmode': 'overlay', 'legend': {'tracegroupgap': 0}, 'margin': {'t': 60}, 'template': '...', 'xaxis': {'anchor': 'y', 'domain': [0.0, 1.0], 'type': 'date'}, 'yaxis': {'anchor': 'x', 'domain': [0.0, 1.0], 'title': {'text': 'Task'}}} }) Figure({ 'data': [{'base': array([datetime.datetime(2009, 1, 1, 0, 0), datetime.datetime(2009, 5, 5, 0, 0), datetime.datetime(2009, 7, 20, 0, 0)], dtype=object), 'orientation': 'h', 'type': 'bar', 'x': array([datetime.datetime(2009, 4, 28, 0, 0), datetime.datetime(2009, 7, 15, 0, 0), datetime.datetime(2009, 9, 30, 0, 0)], dtype=object), 'y': array(['one', 'two', 'three'], dtype=object)}], 'layout': {'template': '...'} }) </code></pre>
<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 embedding the figure produced by <code>px.timeline</code> in an output widget. Then whenever I need the figure to be updated (from a button callback, for example) I just clear the output in the output widget, create a new timeline figure and display that new figure. It's not the most elegant way of doing things but it gets the job done.</p> <pre><code>import ipywidgets as widgets from IPython.display import display, clear_output import pandas as pd import plotly.express as px from datetime import datetime output = widgets.Output() df = pd.DataFrame([ dict(Task=&quot;one&quot;, Start=datetime(2009,1,1), Finish=datetime(2009,4,28)), dict(Task=&quot;two&quot;, Start=datetime(2009,5,5), Finish=datetime(2009,7,15)), dict(Task=&quot;three&quot;, Start=datetime(2009,7,20), Finish=datetime(2009,9,30)) ]) updated_df = pd.DataFrame([ dict(Task=&quot;one&quot;, Start=datetime(2009,1,1), Finish=datetime(2009,4,28)), dict(Task=&quot;two&quot;, Start=datetime(2009,5,5), Finish=datetime(2009,7,15)), dict(Task=&quot;three&quot;, Start=datetime(2009,7,20), Finish=datetime(2009,9,30)), dict(Task=&quot;four&quot;, Start=datetime(2009,10,5), Finish=datetime(2009,10,10)) ]) # display the original timeline figure pxfig = px.timeline(df, x_start=&quot;Start&quot;, x_end=&quot;Finish&quot;, y=&quot;Task&quot;) with output: display(pxfig) # create a button which when pressed will update the timeline figure button = widgets.Button(description='update figure') def on_click(button): with output: clear_output() new_pxfig = px.timeline(updated_df, x_start=&quot;Start&quot;, x_end=&quot;Finish&quot;, y=&quot;Task&quot;) display(new_pxfig) button.on_click(on_click) display(button) </code></pre>
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(&quot;Codes: &quot;)) separated_values = values.split() for value in separated_values: print(chr(value)) </code></pre> <p>error:</p> <pre><code>Traceback (most recent call last): File &quot;program.py&quot;, line 1, in &lt;module&gt; values = int.split(&quot; &quot;) AttributeError: type object 'int' has no attribute 'split' </code></pre> <p><img src="https://i.stack.imgur.com/xFmbE.png" alt="The problem i need to fix" /></p>
<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 &quot;<code>int(...)</code>&quot; 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><code>values = input(&quot;Codes: &quot;) separated_values = values.split() for value in separated_values: print(chr(int(value))) </code></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 &quot;@app.before_request&quot;, 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] &quot;GET / HTTP/1.1&quot; 200 - 127.0.0.1 - - [14/Jun/2022 17:54:48] &quot;GET /static/style.css HTTP/1.1&quot; 304 - 127.0.0.1 - - [14/Jun/2022 17:54:48] &quot;GET /static/profile.jpg HTTP/1.1&quot; 304 - 127.0.0.1 - - [14/Jun/2022 17:54:48] &quot;GET /favicon.ico HTTP/1.1&quot; 404 - </code></pre> <p>Obviously it's running before every single request, including requests just for loading my html and css files. I want to limit it so that it only runs once and not 4 times. I'm having it add +1 to a count on a database and since 4 requests are being run, it's running 4 times and adding 4 every time.</p> <p>Here's my before_request class and function, that I want to somehow limit to running only once (maybe the initial request) and not all 4</p> <pre><code>@app.before_request def before_request(): dbcounter = handler() print(dbcounter) @app.route('/') def home(): count = handler() return render_template(&quot;index.html&quot;) if __name__ == &quot;__main__&quot;: app.run(host='0.0.0.0', port=80) </code></pre>
<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 objects are converted to long ints, 1622623719000000000 for example.</p> <p>I need to calculate the time difference between each row, so my thought was 'ok, I'm not great at python/pandas, but I know I can do <code>datetime.fromtimestamp(1622623719000000000)</code> to get a datetime object back.</p> <p>Unfortunately, <code>datetime.fromtimestamp(1622623719000000000)</code> throws <code>OSError: [Errno 22] Invalid argument</code>.</p> <p>So, off to Google/SO to find a solution. I find <a href="https://stackoverflow.com/questions/9744775/how-to-convert-integer-timestamp-to-python-datetime">this example</a> which shows dividing the long int by <code>1e3</code>. I try that, but still get 'invalid argument.'</p> <p>I play around with the division of the long int, and dividing by <code>1e9</code> gets me the closest to the original datetime.datetime value, but not quite.</p> <p>How do I successfully convert the long int back to the correct datetime value?</p> <p>Code to convert string format to datetime:</p> <pre><code>df.start_time = pd.to_datetime(df.report_date + &quot; &quot; + df.start_time) </code></pre> <p>Info on dataframe:</p> <pre><code>&lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 46 entries, 0 to 45 Data columns (total 19 columns): report_date 46 non-null object ... ... ... start_time 46 non-null datetime64[ns] ... ... ... dtypes: datetime64[ns](1), float64(7), int64(1), object(10) memory usage: 6.9+ KB None </code></pre> <p>My test code:</p> <pre><code>print(&quot;DF start time&quot;, df.start_time[5], &quot;is type&quot;, type(df.start_time[5])) print(&quot;list start time&quot;, tup_list[5][7], &quot;is type&quot;, type(tup_list[5][7]),&quot;\n&quot;) print(&quot;Convert long int in row tuple to datetime&quot;) print(datetime.fromtimestamp(int(1622623719000000000/1e9))) </code></pre> <p>Output:</p> <pre><code>DF start time 2021-06-02 08:16:33 is type &lt;class 'pandas._libs.tslibs.timestamps.Timestamp'&gt; list start time 1622623719000000000 is type &lt;class 'int'&gt; Convert int in row tuple to datetime 2021-06-02 03:48:39 </code></pre>
<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'}) &gt;&gt;&gt; df start_time 0 2021-06-02 08:16:33 &gt;&gt;&gt; df['start_time'].astype(int) 0 1622621793000000000 # NOT 1622623719000000000 Name: start_time, dtype: int64 &gt;&gt;&gt; pd.to_datetime(1622621793000000000) # Right Timestamp('2021-06-02 08:16:33') &gt;&gt;&gt; pd.to_datetime(1622623719000000000) # Wrong Timestamp('2021-06-02 08:48:39') </code></pre>
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__(self, id:int, param1:float, param2:int): self.id = id self.param1 = param1 self.param2 = param2 data = db.get_db('test.txt',obj) </code></pre> <p>and in the function I have class parameter names and types and some data which I want to cast into a list of instances of the above class. and here is some of the code:</p> <pre><code>data = [] for line in raw_data: line_data = line.split(',') for i, c in enumerate(_db_info.column_names): casted_data = _db_info.column_types[c](line_data[i]) setattr(_class, c, casted_data) _instance = copy.deepcopy(_class) data.append(_instance) return data </code></pre> <p>and there is one problem, every time I insert data to <code>_class</code> despite using <code>deepcopy</code> , the <code>_instance</code> stays the same object as the <code>_class</code> and the made list is a list of last object, because last object altered at the end and <code>_class</code> would be the last object at the end.</p> <p>I think it's because the passed object is the class it self and it should be mutable for the deepcopy to change the id and first i made in instance then tried to set parameters but the parameters should be required and I couldn't do that.</p> <p>I think the solution is something that make instance and set parameters of a class dynamically at the same time.</p>
<p>Sounds like you want something like this:</p> <pre><code>def convert_data(obj_cls, raw_data, column_names, column_types): &quot;&quot;&quot; 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 arguments). :param column_types: Column types (used to cast each column). :return: Iterable of obj_cls objects. &quot;&quot;&quot; for line in raw_data: line_data = line.split(&quot;,&quot;) # Split data # Cast and name each column named_data = { name: cast(value) for (name, cast, value) in zip(column_names, column_types, line_data) } yield obj_cls(**named_data) # Create instance using kwargs # --- class MyObject: def __init__(self, id: int, param1: float, param2: int): self.id = id self.param1 = param1 self.param2 = param2 def __repr__(self): return f&quot;&lt;obj id={self.id} param1={self.param1} param2={self.param2}&gt;&quot; raw_data = [ &quot;12,34.5,8&quot;, &quot;13,45.6,9&quot;, &quot;14,56.7,10&quot;, ] converted_data = list( convert_data( MyObject, raw_data, column_names=[&quot;id&quot;, &quot;param1&quot;, &quot;param2&quot;], column_types=[int, float, int], ) ) print(converted_data) </code></pre> <p>The output is</p> <pre><code>[ &lt;obj id=12 param1=34.5 param2=8&gt;, &lt;obj id=13 param1=45.6 param2=9&gt;, &lt;obj id=14 param1=56.7 param2=10&gt; ] </code></pre>
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 vaex was expecting a str Expression and got an integer instead. <br> How do I make a vaex expression set every row of a column to a single value?</p>
<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 convenient way to do this, I opened <a href="https://github.com/vaexio/vaex/issues/802" rel="nofollow noreferrer">https://github.com/vaexio/vaex/issues/802</a> for this.</p>
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/_portaudiomodule.c:28:10: fatal error: Python.h: No such file or directory #include "Python.h" ^~~~~~~~~~ compilation terminated. error: command 'gcc' failed with exit status 1 ---------------------------------------- </code></pre> <p>pip install pyaudio yeilds the same results</p> <p>I have read the question and answer <a href="https://stackoverflow.com/questions/20023131/cannot-install-pyaudio-gcc-error">here</a> but I still cannot figure it out</p> <p>Any advice in installation? Thank you in advance!</p>
<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</a></p> <blockquote> <p>(also, "pip install pyaudio" prints "bash: pip: command not found")</p> </blockquote> <p>To fix this try to install pip by running this command</p> <pre class="lang-sh prettyprint-override"><code>sudo yum install python3-pip </code></pre>
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(&quot;/path/to/dir&quot;): if &quot;(&quot; 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> <li>Using other formatters like Black and yapf but got the same result</li> </ul>
<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> </blockquote>
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 some condition to get a bool-Series, which I then sum up to check the number of thruths in the dataframe, and if there are none, append another dataframe:</p> <p>(note that this is a simplified example, I'm not looking to improve this specific snipped)</p> <pre><code>a_lim = 0.01 my_mask = df_old['A'] &lt; a_lim if sum(my_mask) == 0: df_new = generate_new_df() df_old = df_old.append(df_new, ignore_index=True) \ .sort_values(by=['A'], ascending=True) \ .reset_index(drop=True) pass </code></pre> <p>Lets assume df_new contains one row of data that evaluates as True. If I set a breakpoint the if-statement, <code>sum(my_mask)</code> would be 0. If I set my breakpoint at <code>pass</code>, I can check <code>df_old</code> and see the added rows from df_new. At that point, <code>sum(my_mask)</code> is still 0. That is fine.</p> <p>My Problem:</p> <p>Stopped at <code>pass</code>, I evaluate <code>my_mask = df_old['A'] &lt; a_lim</code>. Then, I check <code>sum(my_mask)</code> and it <em>still returns 0</em>. However, if I evaluate <code>sum(df_old['A'] &lt; a_lim)</code>, I will get 1 (the expected result).</p> <p>What is happening behind the scenes, that Python/IPython seems to selectively update variables, and not others?</p> <p>Thanks!</p>
<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 size.</p> <p>Is this possible?</p>
<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>cl = request.content_length if cl is not None and cl &gt; 3 * 1024 * 1024: abort(413) </code></pre> <p>Do this before accessing form or file data on the request.</p> <p>You can make this into a decorator for your views:</p> <pre><code>from functools import wraps from flask import request, abort def limit_content_length(max_length): def decorator(f): @wraps(f) def wrapper(*args, **kwargs): cl = request.content_length if cl is not None and cl &gt; max_length: abort(413) return f(*args, **kwargs) return wrapper return decorator </code></pre> <p>then use this as:</p> <pre><code>@app.route('/...') @limit_content_length(3 * 1024 * 1024) def your_view(): # ... </code></pre> <p>This is <em>essentially</em> what Flask does; when you try to access request data, the Content-Length header is checked first before attempting to parse the request body. With the decorator or manual check you just made the same test, but a little earlier in the view lifecycle.</p>
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>Presses the hardware keyboard caps lock key?, or is Caps Lock an internal logic state within the keyboard itself? is there a Python means to query the current state of Caps Lock?</p> <p>I've been searching for YEARS, read thousands of posts relating to keyboards, and all I find is keyboard event capturing and toggling.</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) &amp; 1: print "Caps Lock On" else: print "Caps Lock Off" </code></pre> <p>And no, the capslock functionality isn't implemented in the keyboard itself. The keyboard just tells the computer when the Caps Lock key is pressed. Windows then keeps track of capslock state itself. It even has to tell the keyboard when to turn the capslock indicator on or off. The keyboard won't do this on its own.</p>
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 The GetSale function should calculate this value for each stock in the portfolio, and return the stock symbol with the highest expected sale value.</p> <p>We are using 3 separate dictionaries: Names, Prices and Exposure.</p> <p>For the GetSale I know I need to call the Prices and Exposure dictionaries to get the values for the equation; however, I have no idea how to get those values and run them. </p> <p>so far this is the code:</p> <pre><code>Names = {} Prices = {} Exposure = {} def AddName(): name = input('Please enter the company name: ') stock_symbol = input('Please enter the comapny stock symbol: ') Names[name] = stock_symbol def AddPrices(): stock_symbol = input('Please enter the company stock symbol: ') Buy_Price = float(input('Please enter the buy price: ')) Current_Price = float(input('Please enter the current price: ')) Prices[stock_symbol] = 'Buy_Price:', [Buy_Price], 'Current Price', [Current_Price] def AddExposure(): stock_symbol = input('Please enter the company stock symbol: ') Risk = float(input('Please enter the risk of the stock: ')) Shares = float(input('Please enter the shares of the stock: ')) Exposure[stock_symbol] = 'Risk:', [Risk], 'Shares:', [Shares] def AddStock(): AddName() AddPrices() AddExposure() </code></pre> <p>I know that it must somehow be done with a loop since it will have the run the equation over and over to find the greatest Expected Sale Value and then it will return the Stock Symbol of the greatest one.</p> <pre><code>def GetSale(): for stock_symbol, Buy_Price, Current_Price in Prices.items(): </code></pre> <p>P.S. I'm sorry if it isn't very clear and specific I tried to make it to the point so please forgive me its only my second post.</p>
<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> </blockquote> <p>Here's where it gets interesting. You need the keys and values together for that. So let's start over.</p> <blockquote> <p>How do I get keys and values from a dictionary</p> </blockquote> <pre><code>d.items() </code></pre> <blockquote> <p>run the values through an equation</p> </blockquote> <pre><code>((equation(v), k) for k, v in d.items()) </code></pre> <blockquote> <p>and return the key with the greatest value</p> </blockquote> <pre><code>max((equation(v), k) for k, v in d.items()) </code></pre> <blockquote> <p>no, the key, not the value and key</p> </blockquote> <pre><code>max((equation(v), k) for k, v in d.items())[1] </code></pre>
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 I have tried so far:</p> <ul> <li>Downloading the dll and copying it to <code>/site-packages/pygame</code> (it was already there).</li> <li>Downloading the dll and copying to the folder of the script being run</li> <li>Restarting the IDE</li> <li>Restarting Windows</li> <li>Reinstalling pygame</li> <li>Downgrading to pygame 2.0.1</li> </ul> <p>I'm using Windows 10, Python 3.9.10 and running a virtualenv through PyCharm.</p>
<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 PyQt5.uic import * from PyQt5.QtWidgets import * from os import path import sys conn = sqlite3.connect('database.sqlite') cur = conn.cursor() FORM_CLASS,_ = loadUiType(path.join(path.dirname(__file__), &quot;login.ui&quot;)) class Main(QMainWindow, FORM_CLASS): def __init__(self, parent=None): super(Main, self).__init__(parent) self.setupUi(self) def main(): app = QApplication(sys.argv) window = Main() window.show() app.exec_() if __name__ == '__main__': main() </code></pre> <p>Output:</p> <pre class="lang-py prettyprint-override"><code>Traceback (most recent call last): File &quot;/usr/lib/python3.9/idlelib/run.py&quot;, line 559, in runcode exec(code, self.locals) File &quot;/home/lixt/Desktop/Zamaio/ui/remade/register/zamaio.py&quot;, line 8, in &lt;module&gt; FORM_CLASS,_ = loadUiType(path.join(path.dirname(__file__), &quot;login.ui&quot;)) File &quot;/usr/local/lib/python3.9/dist-packages/PyQt5/uic/__init__.py&quot;, line 200, in loadUiType winfo = compiler.UICompiler().compileUi(uifile, code_string, from_imports, File &quot;/usr/local/lib/python3.9/dist-packages/PyQt5/uic/Compiler/compiler.py&quot;, line 111, in compileUi w = self.parse(input_stream, resource_suffix) File &quot;/usr/local/lib/python3.9/dist-packages/PyQt5/uic/uiparser.py&quot;, line 1037, in parse actor(elem) File &quot;/usr/local/lib/python3.9/dist-packages/PyQt5/uic/uiparser.py&quot;, line 828, in createUserInterface self.traverseWidgetTree(elem) File &quot;/usr/local/lib/python3.9/dist-packages/PyQt5/uic/uiparser.py&quot;, line 806, in traverseWidgetTree handler(self, child) File &quot;/usr/local/lib/python3.9/dist-packages/PyQt5/uic/uiparser.py&quot;, line 264, in createWidget self.stack.push(self.setupObject(widget_class, parent, elem)) File &quot;/usr/local/lib/python3.9/dist-packages/PyQt5/uic/uiparser.py&quot;, line 228, in setupObject obj = self.factory.createQObject(clsname, name, args, is_attribute) File &quot;/usr/local/lib/python3.9/dist-packages/PyQt5/uic/objcreator.py&quot;, line 116, in createQObject raise NoSuchWidgetError(classname) PyQt5.uic.exceptions.NoSuchWidgetError: Unknown Qt widget: KPIM.AddresseeLineEdit </code></pre> <p>My ui file</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;ui version=&quot;4.0&quot;&gt; &lt;class&gt;Form&lt;/class&gt; &lt;widget class=&quot;QWidget&quot; name=&quot;Form&quot;&gt; &lt;property name=&quot;geometry&quot;&gt; &lt;rect&gt; &lt;x&gt;0&lt;/x&gt; &lt;y&gt;0&lt;/y&gt; &lt;width&gt;524&lt;/width&gt; &lt;height&gt;555&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name=&quot;windowTitle&quot;&gt; &lt;string&gt;Form&lt;/string&gt; &lt;/property&gt; &lt;property name=&quot;styleSheet&quot;&gt; &lt;string notr=&quot;true&quot;&gt;background-color: rgb(29, 68, 9);&lt;/string&gt; &lt;/property&gt; &lt;widget class=&quot;QLabel&quot; name=&quot;title&quot;&gt; &lt;property name=&quot;geometry&quot;&gt; &lt;rect&gt; &lt;x&gt;0&lt;/x&gt; &lt;y&gt;10&lt;/y&gt; &lt;width&gt;521&lt;/width&gt; &lt;height&gt;41&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name=&quot;statusTip&quot;&gt; &lt;string&gt;Zamaio is a new social platform!&lt;/string&gt; &lt;/property&gt; &lt;property name=&quot;whatsThis&quot;&gt; &lt;string&gt;Zamaio is a new social platform!&lt;/string&gt; &lt;/property&gt; &lt;property name=&quot;styleSheet&quot;&gt; &lt;string notr=&quot;true&quot;&gt;color: rgb(25, 255, 0);&lt;/string&gt; &lt;/property&gt; &lt;property name=&quot;text&quot;&gt; &lt;string&gt;&amp;lt;html&amp;gt;&amp;lt;head/&amp;gt;&amp;lt;body&amp;gt;&amp;lt;p align=&amp;quot;center&amp;quot;&amp;gt;&amp;lt;span style=&amp;quot; font-size:26pt; font-weight:600;&amp;quot;&amp;gt;Zamaio&amp;lt;/span&amp;gt;&amp;lt;/p&amp;gt;&amp;lt;/body&amp;gt;&amp;lt;/html&amp;gt;&lt;/string&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class=&quot;QLabel&quot; name=&quot;username_text&quot;&gt; &lt;property name=&quot;geometry&quot;&gt; &lt;rect&gt; &lt;x&gt;20&lt;/x&gt; &lt;y&gt;120&lt;/y&gt; &lt;width&gt;121&lt;/width&gt; &lt;height&gt;31&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name=&quot;font&quot;&gt; &lt;font&gt; &lt;family&gt;Sans Serif&lt;/family&gt; &lt;weight&gt;50&lt;/weight&gt; &lt;italic&gt;false&lt;/italic&gt; &lt;bold&gt;false&lt;/bold&gt; &lt;/font&gt; &lt;/property&gt; &lt;property name=&quot;statusTip&quot;&gt; &lt;string&gt;Zamaio is a new social platform!&lt;/string&gt; &lt;/property&gt; &lt;property name=&quot;whatsThis&quot;&gt; &lt;string&gt;Zamaio is a new social platform!&lt;/string&gt; &lt;/property&gt; &lt;property name=&quot;styleSheet&quot;&gt; &lt;string notr=&quot;true&quot;&gt;color: rgb(181, 195, 130);&lt;/string&gt; &lt;/property&gt; &lt;property name=&quot;text&quot;&gt; &lt;string&gt;&amp;lt;html&amp;gt;&amp;lt;head/&amp;gt;&amp;lt;body&amp;gt;&amp;lt;p align=&amp;quot;center&amp;quot;&amp;gt;&amp;lt;span style=&amp;quot; font-size:11pt; font-weight:600;&amp;quot;&amp;gt;Username:&amp;lt;/span&amp;gt;&amp;lt;/p&amp;gt;&amp;lt;/body&amp;gt;&amp;lt;/html&amp;gt;&lt;/string&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class=&quot;KPIM::AddresseeLineEdit&quot; name=&quot;username&quot;&gt; &lt;property name=&quot;geometry&quot;&gt; &lt;rect&gt; &lt;x&gt;130&lt;/x&gt; &lt;y&gt;120&lt;/y&gt; &lt;width&gt;221&lt;/width&gt; &lt;height&gt;28&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name=&quot;styleSheet&quot;&gt; &lt;string notr=&quot;true&quot;&gt;background-color: rgb(44, 97, 4); color: rgb(240, 255, 233); border-width: 1px; border-style: solid; border-color: black black black black;&lt;/string&gt; &lt;/property&gt; &lt;property name=&quot;maxLength&quot;&gt; &lt;number&gt;29&lt;/number&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class=&quot;QLabel&quot; name=&quot;password_text&quot;&gt; &lt;property name=&quot;geometry&quot;&gt; &lt;rect&gt; &lt;x&gt;20&lt;/x&gt; &lt;y&gt;170&lt;/y&gt; &lt;width&gt;121&lt;/width&gt; &lt;height&gt;31&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name=&quot;font&quot;&gt; &lt;font&gt; &lt;family&gt;Sans Serif&lt;/family&gt; &lt;weight&gt;50&lt;/weight&gt; &lt;italic&gt;false&lt;/italic&gt; &lt;bold&gt;false&lt;/bold&gt; &lt;/font&gt; &lt;/property&gt; &lt;property name=&quot;statusTip&quot;&gt; &lt;string&gt;Zamaio is a new social platform!&lt;/string&gt; &lt;/property&gt; &lt;property name=&quot;whatsThis&quot;&gt; &lt;string&gt;Zamaio is a new social platform!&lt;/string&gt; &lt;/property&gt; &lt;property name=&quot;styleSheet&quot;&gt; &lt;string notr=&quot;true&quot;&gt;color: rgb(181, 195, 130);&lt;/string&gt; &lt;/property&gt; &lt;property name=&quot;text&quot;&gt; &lt;string&gt;&amp;lt;html&amp;gt;&amp;lt;head/&amp;gt;&amp;lt;body&amp;gt;&amp;lt;p align=&amp;quot;center&amp;quot;&amp;gt;&amp;lt;span style=&amp;quot; font-size:11pt; font-weight:600;&amp;quot;&amp;gt;Password:&amp;lt;/span&amp;gt;&amp;lt;/p&amp;gt;&amp;lt;/body&amp;gt;&amp;lt;/html&amp;gt;&lt;/string&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class=&quot;KPIM::AddresseeLineEdit&quot; name=&quot;password&quot;&gt; &lt;property name=&quot;geometry&quot;&gt; &lt;rect&gt; &lt;x&gt;130&lt;/x&gt; &lt;y&gt;170&lt;/y&gt; &lt;width&gt;221&lt;/width&gt; &lt;height&gt;28&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name=&quot;styleSheet&quot;&gt; &lt;string notr=&quot;true&quot;&gt;background-color: rgb(44, 97, 4); color: rgb(240, 255, 233); border-width: 1px; border-style: solid; border-color: black black black black; password::hover { border-color: black black white white; }&lt;/string&gt; &lt;/property&gt; &lt;property name=&quot;maxLength&quot;&gt; &lt;number&gt;32&lt;/number&gt; &lt;/property&gt; &lt;property name=&quot;readOnly&quot;&gt; &lt;bool&gt;false&lt;/bool&gt; &lt;/property&gt; &lt;property name=&quot;urlDropsEnabled&quot;&gt; &lt;bool&gt;false&lt;/bool&gt; &lt;/property&gt; &lt;property name=&quot;trapEnterKeyEvent&quot; stdset=&quot;0&quot;&gt; &lt;bool&gt;false&lt;/bool&gt; &lt;/property&gt; &lt;property name=&quot;squeezedTextEnabled&quot;&gt; &lt;bool&gt;false&lt;/bool&gt; &lt;/property&gt; &lt;property name=&quot;passwordMode&quot;&gt; &lt;bool&gt;true&lt;/bool&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class=&quot;QLabel&quot; name=&quot;Age_text&quot;&gt; &lt;property name=&quot;geometry&quot;&gt; &lt;rect&gt; &lt;x&gt;20&lt;/x&gt; &lt;y&gt;370&lt;/y&gt; &lt;width&gt;121&lt;/width&gt; &lt;height&gt;41&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name=&quot;font&quot;&gt; &lt;font&gt; &lt;family&gt;Sans Serif&lt;/family&gt; &lt;weight&gt;50&lt;/weight&gt; &lt;italic&gt;false&lt;/italic&gt; &lt;bold&gt;false&lt;/bold&gt; &lt;/font&gt; &lt;/property&gt; &lt;property name=&quot;statusTip&quot;&gt; &lt;string&gt;Zamaio is a new social platform!&lt;/string&gt; &lt;/property&gt; &lt;property name=&quot;whatsThis&quot;&gt; &lt;string&gt;Zamaio is a new social platform!&lt;/string&gt; &lt;/property&gt; &lt;property name=&quot;styleSheet&quot;&gt; &lt;string notr=&quot;true&quot;&gt;color: rgb(181, 195, 130);&lt;/string&gt; &lt;/property&gt; &lt;property name=&quot;text&quot;&gt; &lt;string&gt;&amp;lt;html&amp;gt;&amp;lt;head/&amp;gt;&amp;lt;body&amp;gt;&amp;lt;p align=&amp;quot;center&amp;quot;&amp;gt;&amp;lt;span style=&amp;quot; font-size:11pt; font-weight:600;&amp;quot;&amp;gt;Age:&amp;lt;/span&amp;gt;&amp;lt;/p&amp;gt;&amp;lt;/body&amp;gt;&amp;lt;/html&amp;gt;&lt;/string&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class=&quot;QLabel&quot; name=&quot;confirm_password_texr&quot;&gt; &lt;property name=&quot;geometry&quot;&gt; &lt;rect&gt; &lt;x&gt;10&lt;/x&gt; &lt;y&gt;220&lt;/y&gt; &lt;width&gt;161&lt;/width&gt; &lt;height&gt;31&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name=&quot;font&quot;&gt; &lt;font&gt; &lt;family&gt;Sans Serif&lt;/family&gt; &lt;weight&gt;50&lt;/weight&gt; &lt;italic&gt;false&lt;/italic&gt; &lt;bold&gt;false&lt;/bold&gt; &lt;/font&gt; &lt;/property&gt; &lt;property name=&quot;statusTip&quot;&gt; &lt;string&gt;Zamaio is a new social platform!&lt;/string&gt; &lt;/property&gt; &lt;property name=&quot;whatsThis&quot;&gt; &lt;string&gt;Zamaio is a new social platform!&lt;/string&gt; &lt;/property&gt; &lt;property name=&quot;styleSheet&quot;&gt; &lt;string notr=&quot;true&quot;&gt;color: rgb(181, 195, 130);&lt;/string&gt; &lt;/property&gt; &lt;property name=&quot;text&quot;&gt; &lt;string&gt;&amp;lt;html&amp;gt;&amp;lt;head/&amp;gt;&amp;lt;body&amp;gt;&amp;lt;p align=&amp;quot;center&amp;quot;&amp;gt;&amp;lt;span style=&amp;quot; font-size:11pt; font-weight:600;&amp;quot;&amp;gt;Confirm Password:&amp;lt;/span&amp;gt;&amp;lt;/p&amp;gt;&amp;lt;/body&amp;gt;&amp;lt;/html&amp;gt;&lt;/string&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class=&quot;KPIM::AddresseeLineEdit&quot; name=&quot;confirm_password&quot;&gt; &lt;property name=&quot;geometry&quot;&gt; &lt;rect&gt; &lt;x&gt;180&lt;/x&gt; &lt;y&gt;220&lt;/y&gt; &lt;width&gt;171&lt;/width&gt; &lt;height&gt;28&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name=&quot;styleSheet&quot;&gt; &lt;string notr=&quot;true&quot;&gt;background-color: rgb(44, 97, 4); color: rgb(240, 255, 233); border-width: 1px; border-style: solid; border-color: black black black black; password::hover { border-color: black black white white; }&lt;/string&gt; &lt;/property&gt; &lt;property name=&quot;maxLength&quot;&gt; &lt;number&gt;32&lt;/number&gt; &lt;/property&gt; &lt;property name=&quot;readOnly&quot;&gt; &lt;bool&gt;false&lt;/bool&gt; &lt;/property&gt; &lt;property name=&quot;urlDropsEnabled&quot;&gt; &lt;bool&gt;false&lt;/bool&gt; &lt;/property&gt; &lt;property name=&quot;trapEnterKeyEvent&quot; stdset=&quot;0&quot;&gt; &lt;bool&gt;false&lt;/bool&gt; &lt;/property&gt; &lt;property name=&quot;squeezedTextEnabled&quot;&gt; &lt;bool&gt;false&lt;/bool&gt; &lt;/property&gt; &lt;property name=&quot;passwordMode&quot;&gt; &lt;bool&gt;true&lt;/bool&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class=&quot;QSlider&quot; name=&quot;age_slider&quot;&gt; &lt;property name=&quot;geometry&quot;&gt; &lt;rect&gt; &lt;x&gt;110&lt;/x&gt; &lt;y&gt;380&lt;/y&gt; &lt;width&gt;261&lt;/width&gt; &lt;height&gt;17&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name=&quot;orientation&quot;&gt; &lt;enum&gt;Qt::Horizontal&lt;/enum&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class=&quot;QLabel&quot; name=&quot;Age_counter&quot;&gt; &lt;property name=&quot;geometry&quot;&gt; &lt;rect&gt; &lt;x&gt;370&lt;/x&gt; &lt;y&gt;370&lt;/y&gt; &lt;width&gt;151&lt;/width&gt; &lt;height&gt;41&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name=&quot;font&quot;&gt; &lt;font&gt; &lt;family&gt;Sans Serif&lt;/family&gt; &lt;weight&gt;50&lt;/weight&gt; &lt;italic&gt;false&lt;/italic&gt; &lt;bold&gt;false&lt;/bold&gt; &lt;/font&gt; &lt;/property&gt; &lt;property name=&quot;statusTip&quot;&gt; &lt;string&gt;Zamaio is a new social platform!&lt;/string&gt; &lt;/property&gt; &lt;property name=&quot;whatsThis&quot;&gt; &lt;string&gt;Zamaio is a new social platform!&lt;/string&gt; &lt;/property&gt; &lt;property name=&quot;styleSheet&quot;&gt; &lt;string notr=&quot;true&quot;&gt;color: rgb(181, 195, 130);&lt;/string&gt; &lt;/property&gt; &lt;property name=&quot;text&quot;&gt; &lt;string&gt;&amp;lt;html&amp;gt;&amp;lt;head/&amp;gt;&amp;lt;body&amp;gt;&amp;lt;p align=&amp;quot;center&amp;quot;/&amp;gt;&amp;lt;/body&amp;gt;&amp;lt;/html&amp;gt;&lt;/string&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class=&quot;QPushButton&quot; name=&quot;pushButton&quot;&gt; &lt;property name=&quot;geometry&quot;&gt; &lt;rect&gt; &lt;x&gt;380&lt;/x&gt; &lt;y&gt;470&lt;/y&gt; &lt;width&gt;90&lt;/width&gt; &lt;height&gt;28&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name=&quot;styleSheet&quot;&gt; &lt;string notr=&quot;true&quot;&gt;QPushButton { color: #FFFFFF; background-color: rgb(17, 176, 27); border-style: outset; padding: 2px; font: bold 20px; border-width: 2px; border-radius: 4px; border-color: rgb(19, 197, 0); } QPushButton:hover { background-color: rgb(47, 105, 37); border-color: rgb(33, 163, 30); } QPushButton::clicked { background-color : red; }&lt;/string&gt; &lt;/property&gt; &lt;property name=&quot;text&quot;&gt; &lt;string&gt;Create&lt;/string&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class=&quot;QPushButton&quot; name=&quot;ViewPass1&quot;&gt; &lt;property name=&quot;geometry&quot;&gt; &lt;rect&gt; &lt;x&gt;360&lt;/x&gt; &lt;y&gt;170&lt;/y&gt; &lt;width&gt;31&lt;/width&gt; &lt;height&gt;28&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name=&quot;text&quot;&gt; &lt;string/&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class=&quot;QPushButton&quot; name=&quot;ViewPass1_2&quot;&gt; &lt;property name=&quot;geometry&quot;&gt; &lt;rect&gt; &lt;x&gt;360&lt;/x&gt; &lt;y&gt;220&lt;/y&gt; &lt;width&gt;31&lt;/width&gt; &lt;height&gt;28&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name=&quot;text&quot;&gt; &lt;string/&gt; &lt;/property&gt; &lt;/widget&gt; &lt;/widget&gt; &lt;customwidgets&gt; &lt;customwidget&gt; &lt;class&gt;KPIM::AddresseeLineEdit&lt;/class&gt; &lt;extends&gt;QLineEdit&lt;/extends&gt; &lt;header&gt;LibkdepimAkonadi/AddresseeLineEdit&lt;/header&gt; &lt;/customwidget&gt; &lt;/customwidgets&gt; &lt;resources/&gt; &lt;connections/&gt; &lt;/ui&gt; </code></pre> <p>Is there any kind of bug?</p> <h1>Solution</h1> <p>By replace KPIM::AddresseeLineEdit by QTextEdit in the .ui file solves the problem</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.com/jns7z.png" alt="enter image description here"></a></p> <p>Here is my code</p> <pre><code> import matplotlib.pyplot as plt diet = df[['mean']] diet.plot(figsize=(20,10), linewidth=5, fontsize=20 ,marker='&lt;') plt.xlabel('Year', fontsize=20); plt.xlabel('Month/Year') plt.ylabel('mean') </code></pre> <p>Is there any way to add the count column on the all point line like this to know the count number in each month. <a href="https://i.stack.imgur.com/Brs7W.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Brs7W.png" alt="enter image description here"></a></p>
<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['count']), xy=(d,row['mean']), ha='center') </code></pre> <p><a href="https://i.stack.imgur.com/ZxnEd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZxnEd.png" alt="enter image description here"></a></p>
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>task.parent</code> is built-in method. I was thinking about creating a new Key instance for the task but there is no way to change key as well.</p> <p>Any thoughts?</p>
<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> <p>The complete key of an entity, including the path, the kind and the name or numeric ID, is unique and specific to that entity. The complete key is assigned when the entity is created in the datastore, and none of its parts can change.</p> </blockquote> <p>Setting a parent entity is useful when you need to manipulate the parent and child in the same transaction. Otherwise, you're just limiting performance by forcing them both to be in the same entity group, and restricting your ability to update the relationship after the entity has been created.</p> <p>Use a ReferenceProperty instead.</p>
python|google-app-engine|transactions|google-cloud-datastore
9