title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Matlab diff(F,var,n) vs Python numpy diff(a, n=1, axis=-1)
39,410,096
<p>I am trying to calculate matlab function in python.</p> <pre><code>y = diff(x,1,2) </code></pre> <p>x is and grayscale image </p> <p>i tried numpy diff function but i get different answer</p> <p>please help</p>
-1
2016-09-09T11:01:55Z
39,411,638
<p>in the comment to your question, it appears you swapped the arguments to the <code>diff</code> functions. However, the documentation states that both in matlab and in numpy, the order of the arguments is:</p> <ul> <li><p>array</p></li> <li><p>n</p></li> <li><p>dimension</p></li> </ul>
0
2016-09-09T12:28:56Z
[ "python", "matlab", "numpy", "scipy" ]
Matlab diff(F,var,n) vs Python numpy diff(a, n=1, axis=-1)
39,410,096
<p>I am trying to calculate matlab function in python.</p> <pre><code>y = diff(x,1,2) </code></pre> <p>x is and grayscale image </p> <p>i tried numpy diff function but i get different answer</p> <p>please help</p>
-1
2016-09-09T11:01:55Z
39,418,024
<p>There are two problems here. </p> <p>First, you swapped the order of arguments in <code>np.diff</code>. MATLAB and Python use the same argument order. Python supports named arguments, so it is often better to use the argument name to avoid this sort of problem.</p> <p>Second, python indexing starts with 0, while MATLAB indexing starts with <code>1</code>. This applies to axes as well, so MATLAB's axis <code>2</code> is Python's axis <code>1</code>.</p> <p>So the correct function call in Python is <code>np.diff(fimg, 1, 1)</code>, but <code>np.diff(fimg, axis=1)</code> is better IMO.</p> <p>MATLAB:</p> <pre><code>&gt;&gt; a = reshape(1:100, 10, [])' a = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 &gt;&gt; diff(a,1, 2) ans = 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 </code></pre> <p>Python:</p> <pre><code>&gt;&gt;&gt; a = np.arange(100).reshape(10, -1) &gt;&gt;&gt; print(a) [[ 0 1 2 3 4 5 6 7 8 9] [10 11 12 13 14 15 16 17 18 19] [20 21 22 23 24 25 26 27 28 29] [30 31 32 33 34 35 36 37 38 39] [40 41 42 43 44 45 46 47 48 49] [50 51 52 53 54 55 56 57 58 59] [60 61 62 63 64 65 66 67 68 69] [70 71 72 73 74 75 76 77 78 79] [80 81 82 83 84 85 86 87 88 89] [90 91 92 93 94 95 96 97 98 99]] &gt;&gt;&gt; print(np.diff(a, axis=1)) [[1 1 1 1 1 1 1 1 1] [1 1 1 1 1 1 1 1 1] [1 1 1 1 1 1 1 1 1] [1 1 1 1 1 1 1 1 1] [1 1 1 1 1 1 1 1 1] [1 1 1 1 1 1 1 1 1] [1 1 1 1 1 1 1 1 1] [1 1 1 1 1 1 1 1 1] [1 1 1 1 1 1 1 1 1] [1 1 1 1 1 1 1 1 1]] </code></pre>
1
2016-09-09T18:50:28Z
[ "python", "matlab", "numpy", "scipy" ]
JSON parsing encoding causes a unicode encode error
39,410,173
<p>I need to parse some simple JOSN in bash which contains non-ascii characters without external dependencies, so I used a python solution <a href="http://stackoverflow.com/a/1955555/296446">from this answer</a></p> <pre><code>cat $JSON_FILE | python -c "import sys, json; print json.load(sys.stdin)['$KEY']" </code></pre> <p>This works for ascii values but other values throws this error:</p> <blockquote> <p>'ascii' codec can't encode character u'\u2019' in position 1212: ordinal not in range(128)</p> </blockquote> <p>Looking at <a href="http://stackoverflow.com/a/8591554/296446">this answer</a> I think I need to cast to the <code>unicode</code> type, but I don't know how.</p>
1
2016-09-09T11:06:57Z
39,410,214
<p>You already have <code>unicode</code>, but <strong>encoding</strong> when printing fails.</p> <p>That's either because you don't have a locale set, have your locale set to ASCII, or you are piping the Python result to something else (but did not include that in your question). In the latter case Python refuses to guess what codec to use when connected to a pipe (it can use your terminal locale otherwise).</p> <p>Set the <a href="https://docs.python.org/2/using/cmdline.html#envvar-PYTHONIOENCODING" rel="nofollow"><code>PYTHONIOENCODING</code> environment variable</a> to a suitable codec; if your terminal uses UTF-8 for example:</p> <pre><code>cat $JSON_FILE | PYTHONIOENCODING=UTF-8 python -c "import sys, json; print json.load(sys.stdin)['$KEY']" </code></pre>
3
2016-09-09T11:09:43Z
[ "python", "json", "bash", "python-2.x" ]
readonly_fields returns empty value in django inlined models
39,410,176
<p>i am new in django framework, in my current try, i have two models (Client and Facture). Facture is displayed as a TabularInline in client change view.</p> <p>i want display a link for each inlined facture object to download the file. so i added a custom view that download the facture file, but dont know how to link to it</p> <pre><code>class Client(models.Model): ... class Facture(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) numero = models.IntegerField(unique=True, default=rand_code) ... </code></pre> <p>and in the admin.py:</p> <pre><code>class FactureInline(admin.TabularInline): model = Facture extra = 0 readonly_fields = ('numero', 'dl_link') def DLFacture(self, request, obj): ... response.write(pdf) return response def get_urls(self): urls = super(FactureAdmin, self).get_urls() from django.conf.urls import url download_url = [ url(r'^(?P&lt;pk&gt;\d+)/download/$', self.admin_site.admin_view(self.DLFacture), name="download"), ] return download_url + urls def dl_link(self, obj): from django.core.urlresolvers import reverse return reverse("admin:clients_facture_download", args=[obj.pk]) admin.site.register(Facture, FactureAdmin) class ClientAdmin(admin.ModelAdmin): inlines = [ FactureInline, ] admin.site.register(Client, ClientAdmin) </code></pre> <p>i get the following error:</p> <pre><code>Reverse for 'clients_facture_download' with arguments '(1,)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] </code></pre> <p>all works fine when i change the reverse url to</p> <pre><code>reverse("admin:clients_facture_change", args=[obj.pk]) </code></pre> <p>so any one could help me know how to reverse the download view and if i am doing thinks right ?</p> <p>thanks for any help</p>
0
2016-09-09T11:06:59Z
39,411,018
<p>I would think you need to reverse the order in the url:</p> <pre><code>url(r'^download/(?P&lt;pk&gt;\d+)$', self.admin_site.admin_view(self.DLFacture), name="download"), ] </code></pre>
0
2016-09-09T11:54:48Z
[ "python", "django", "django-admin", "django-views", "django-urls" ]
readonly_fields returns empty value in django inlined models
39,410,176
<p>i am new in django framework, in my current try, i have two models (Client and Facture). Facture is displayed as a TabularInline in client change view.</p> <p>i want display a link for each inlined facture object to download the file. so i added a custom view that download the facture file, but dont know how to link to it</p> <pre><code>class Client(models.Model): ... class Facture(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) numero = models.IntegerField(unique=True, default=rand_code) ... </code></pre> <p>and in the admin.py:</p> <pre><code>class FactureInline(admin.TabularInline): model = Facture extra = 0 readonly_fields = ('numero', 'dl_link') def DLFacture(self, request, obj): ... response.write(pdf) return response def get_urls(self): urls = super(FactureAdmin, self).get_urls() from django.conf.urls import url download_url = [ url(r'^(?P&lt;pk&gt;\d+)/download/$', self.admin_site.admin_view(self.DLFacture), name="download"), ] return download_url + urls def dl_link(self, obj): from django.core.urlresolvers import reverse return reverse("admin:clients_facture_download", args=[obj.pk]) admin.site.register(Facture, FactureAdmin) class ClientAdmin(admin.ModelAdmin): inlines = [ FactureInline, ] admin.site.register(Client, ClientAdmin) </code></pre> <p>i get the following error:</p> <pre><code>Reverse for 'clients_facture_download' with arguments '(1,)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] </code></pre> <p>all works fine when i change the reverse url to</p> <pre><code>reverse("admin:clients_facture_change", args=[obj.pk]) </code></pre> <p>so any one could help me know how to reverse the download view and if i am doing thinks right ?</p> <p>thanks for any help</p>
0
2016-09-09T11:06:59Z
39,411,381
<p>Firstly, you are using <code>name='download'</code>, but trying to reverse <code>clients_facture_download</code>.</p> <p>I would try changing the url from</p> <pre><code>url(r'^(?P&lt;pk&gt;\d+)/download/$', self.admin_site.admin_view(self.DLFacture), name="download"), </code></pre> <p>to</p> <pre><code>url(r'^(?P&lt;pk&gt;\d+)/download/$', self.admin_site.admin_view(self.DLFacture), name="clients_fracture_download"), </code></pre> <p>Secondly, InlineModelAdmin <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#inlinemodeladmin-options" rel="nofollow">does not have</a> a <code>get_urls</code> method. You should move it to your <code>ClientAdmin</code> class.</p>
0
2016-09-09T12:15:28Z
[ "python", "django", "django-admin", "django-views", "django-urls" ]
How can l convert tuple to integer to do some calculations?
39,410,205
<p>l have 41 years dataset including 10 columns and l m trying to plot these data with Matplotlib and l m able to plot columns without error. However , l would like to produce different kind of graphes like yearly average pcp ,monthly average pcp and yearly sum of pcp etc. l got data from columns and l have problem with transforming these data as integer to do some calculations.</p> <p>here is example dataset from Csv file:</p> <pre><code>date day month year pcp1 pcp2 pcp3 pcp4 pcp5 pcp6 1.01.1979 1 1 1979 0.431 2.167 9.375 0.431 2.167 9.375 2.01.1979 2 1 1979 1.216 2.583 9.162 1.216 2.583 9.162 3.01.1979 3 1 1979 4.041 9.373 23.169 4.041 9.373 23.169 4.01.1979 4 1 1979 1.799 3.866 8.286 1.799 3.866 8.286 5.01.1979 5 1 1979 0.003 0.051 0.342 0.003 0.051 0.342 6.01.1979 6 1 1979 2.345 3.777 7.483 2.345 3.777 7.483 7.01.1979 7 1 1979 0.017 0.031 0.173 0.017 0.031 0.173 8.01.1979 8 1 1979 5.061 5.189 43.313 5.061 5.189 43.313 </code></pre> <p>here is my code:</p> <pre><code>import csv import numpy as np import matplotlib.pyplot as plt with open('output813b.csv', 'r') as csvfile: # get number of columns for line in csvfile.readlines(): array = line.split() first_item = array[0] num_columns = len(array) csvfile.seek(0) reader = csv.reader(csvfile, delimiter=',') next(reader) included_col1 = [1] included_col6=[4] x=[] y=[] for row in reader: content = list(row[i] for i in included_col1) content2= list(row[i] for i in included_col6) x.append(content) y.append(content2) klm=tuple(x[i] for i in range(1,1000) if x[i]==["1979"]) s=0 for i in range(1,len(klm)): s+=y[i] #### error (for +=: 'int' and 'list') print (tuple(y[5])) ###example output ('2.345',) print (int(y [5][0])) #### error invalid literal for int() with base 10: '2.345' </code></pre> <p>tuple in tuple ,l use <code>int(y[5][0])</code> to covert tuple to int but l got an error. l put error messages in my code. how can l fix this problem and l do some calculations. Thanks in advance</p>
1
2016-09-09T11:09:09Z
39,410,303
<p>The simplest thing would be:</p> <pre><code>int(float(y[5][0])) </code></pre> <p>Instead. Since your string value has a decimal in it, you will not be able to convert directly to <code>int</code> without converting to <code>float</code> first. Keep in mind, you will lose some precision though:</p> <pre><code>&gt;&gt;&gt; int(float('2.345')) 2 </code></pre> <p>So if you want to use these values in calculations, you may just want to convert your tuple values to floats instead:</p> <pre><code>float(y[5][0]) </code></pre>
1
2016-09-09T11:14:03Z
[ "python", "csv", "numpy", "matplotlib" ]
How can l convert tuple to integer to do some calculations?
39,410,205
<p>l have 41 years dataset including 10 columns and l m trying to plot these data with Matplotlib and l m able to plot columns without error. However , l would like to produce different kind of graphes like yearly average pcp ,monthly average pcp and yearly sum of pcp etc. l got data from columns and l have problem with transforming these data as integer to do some calculations.</p> <p>here is example dataset from Csv file:</p> <pre><code>date day month year pcp1 pcp2 pcp3 pcp4 pcp5 pcp6 1.01.1979 1 1 1979 0.431 2.167 9.375 0.431 2.167 9.375 2.01.1979 2 1 1979 1.216 2.583 9.162 1.216 2.583 9.162 3.01.1979 3 1 1979 4.041 9.373 23.169 4.041 9.373 23.169 4.01.1979 4 1 1979 1.799 3.866 8.286 1.799 3.866 8.286 5.01.1979 5 1 1979 0.003 0.051 0.342 0.003 0.051 0.342 6.01.1979 6 1 1979 2.345 3.777 7.483 2.345 3.777 7.483 7.01.1979 7 1 1979 0.017 0.031 0.173 0.017 0.031 0.173 8.01.1979 8 1 1979 5.061 5.189 43.313 5.061 5.189 43.313 </code></pre> <p>here is my code:</p> <pre><code>import csv import numpy as np import matplotlib.pyplot as plt with open('output813b.csv', 'r') as csvfile: # get number of columns for line in csvfile.readlines(): array = line.split() first_item = array[0] num_columns = len(array) csvfile.seek(0) reader = csv.reader(csvfile, delimiter=',') next(reader) included_col1 = [1] included_col6=[4] x=[] y=[] for row in reader: content = list(row[i] for i in included_col1) content2= list(row[i] for i in included_col6) x.append(content) y.append(content2) klm=tuple(x[i] for i in range(1,1000) if x[i]==["1979"]) s=0 for i in range(1,len(klm)): s+=y[i] #### error (for +=: 'int' and 'list') print (tuple(y[5])) ###example output ('2.345',) print (int(y [5][0])) #### error invalid literal for int() with base 10: '2.345' </code></pre> <p>tuple in tuple ,l use <code>int(y[5][0])</code> to covert tuple to int but l got an error. l put error messages in my code. how can l fix this problem and l do some calculations. Thanks in advance</p>
1
2016-09-09T11:09:09Z
39,410,312
<p>Thats because you are trying to convert a decimal number into an int</p> <p>If you want to use the exact value you can use <code>float(tuple(y[5][0]))</code> Or else if you want to truncate the value you can use <code>int(float(tuple(y[5][0])))</code></p>
1
2016-09-09T11:14:34Z
[ "python", "csv", "numpy", "matplotlib" ]
How can l convert tuple to integer to do some calculations?
39,410,205
<p>l have 41 years dataset including 10 columns and l m trying to plot these data with Matplotlib and l m able to plot columns without error. However , l would like to produce different kind of graphes like yearly average pcp ,monthly average pcp and yearly sum of pcp etc. l got data from columns and l have problem with transforming these data as integer to do some calculations.</p> <p>here is example dataset from Csv file:</p> <pre><code>date day month year pcp1 pcp2 pcp3 pcp4 pcp5 pcp6 1.01.1979 1 1 1979 0.431 2.167 9.375 0.431 2.167 9.375 2.01.1979 2 1 1979 1.216 2.583 9.162 1.216 2.583 9.162 3.01.1979 3 1 1979 4.041 9.373 23.169 4.041 9.373 23.169 4.01.1979 4 1 1979 1.799 3.866 8.286 1.799 3.866 8.286 5.01.1979 5 1 1979 0.003 0.051 0.342 0.003 0.051 0.342 6.01.1979 6 1 1979 2.345 3.777 7.483 2.345 3.777 7.483 7.01.1979 7 1 1979 0.017 0.031 0.173 0.017 0.031 0.173 8.01.1979 8 1 1979 5.061 5.189 43.313 5.061 5.189 43.313 </code></pre> <p>here is my code:</p> <pre><code>import csv import numpy as np import matplotlib.pyplot as plt with open('output813b.csv', 'r') as csvfile: # get number of columns for line in csvfile.readlines(): array = line.split() first_item = array[0] num_columns = len(array) csvfile.seek(0) reader = csv.reader(csvfile, delimiter=',') next(reader) included_col1 = [1] included_col6=[4] x=[] y=[] for row in reader: content = list(row[i] for i in included_col1) content2= list(row[i] for i in included_col6) x.append(content) y.append(content2) klm=tuple(x[i] for i in range(1,1000) if x[i]==["1979"]) s=0 for i in range(1,len(klm)): s+=y[i] #### error (for +=: 'int' and 'list') print (tuple(y[5])) ###example output ('2.345',) print (int(y [5][0])) #### error invalid literal for int() with base 10: '2.345' </code></pre> <p>tuple in tuple ,l use <code>int(y[5][0])</code> to covert tuple to int but l got an error. l put error messages in my code. how can l fix this problem and l do some calculations. Thanks in advance</p>
1
2016-09-09T11:09:09Z
39,410,381
<p>You have got 2 different problems:</p> <p><strong>1. s+=y[i] #### error (for +=: 'int' and 'list')</strong></p> <p>Here are the relevant part of the code:</p> <pre><code>y=[] for row in reader: content2= list(row[i] for i in included_col6) y.append(content2) s=0 for i in range(1,len(klm)): s+=y[i] #### error (for +=: 'int' and 'list') </code></pre> <p>Then:</p> <ol> <li><code>s</code> is an <code>int</code></li> <li><code>y</code> is a list of <code>content2</code></li> <li><code>content2</code> is a <code>list</code></li> </ol> <p>Then you add to an <code>int</code> <code>s</code> a <code>list</code> <code>y[i]</code>. That is impossible. What do you really want?</p> <p><strong>2. #### error invalid literal for int() with base 10: '2.345'</strong></p> <p>You are trying to convert a decimal number into an int.</p> <p>You should either keep the float number with <code>float(tuple(y[5][0]))</code> or convert it to an int with <code>int(float(tuple(y[5][0])))</code></p>
1
2016-09-09T11:18:24Z
[ "python", "csv", "numpy", "matplotlib" ]
How can l convert tuple to integer to do some calculations?
39,410,205
<p>l have 41 years dataset including 10 columns and l m trying to plot these data with Matplotlib and l m able to plot columns without error. However , l would like to produce different kind of graphes like yearly average pcp ,monthly average pcp and yearly sum of pcp etc. l got data from columns and l have problem with transforming these data as integer to do some calculations.</p> <p>here is example dataset from Csv file:</p> <pre><code>date day month year pcp1 pcp2 pcp3 pcp4 pcp5 pcp6 1.01.1979 1 1 1979 0.431 2.167 9.375 0.431 2.167 9.375 2.01.1979 2 1 1979 1.216 2.583 9.162 1.216 2.583 9.162 3.01.1979 3 1 1979 4.041 9.373 23.169 4.041 9.373 23.169 4.01.1979 4 1 1979 1.799 3.866 8.286 1.799 3.866 8.286 5.01.1979 5 1 1979 0.003 0.051 0.342 0.003 0.051 0.342 6.01.1979 6 1 1979 2.345 3.777 7.483 2.345 3.777 7.483 7.01.1979 7 1 1979 0.017 0.031 0.173 0.017 0.031 0.173 8.01.1979 8 1 1979 5.061 5.189 43.313 5.061 5.189 43.313 </code></pre> <p>here is my code:</p> <pre><code>import csv import numpy as np import matplotlib.pyplot as plt with open('output813b.csv', 'r') as csvfile: # get number of columns for line in csvfile.readlines(): array = line.split() first_item = array[0] num_columns = len(array) csvfile.seek(0) reader = csv.reader(csvfile, delimiter=',') next(reader) included_col1 = [1] included_col6=[4] x=[] y=[] for row in reader: content = list(row[i] for i in included_col1) content2= list(row[i] for i in included_col6) x.append(content) y.append(content2) klm=tuple(x[i] for i in range(1,1000) if x[i]==["1979"]) s=0 for i in range(1,len(klm)): s+=y[i] #### error (for +=: 'int' and 'list') print (tuple(y[5])) ###example output ('2.345',) print (int(y [5][0])) #### error invalid literal for int() with base 10: '2.345' </code></pre> <p>tuple in tuple ,l use <code>int(y[5][0])</code> to covert tuple to int but l got an error. l put error messages in my code. how can l fix this problem and l do some calculations. Thanks in advance</p>
1
2016-09-09T11:09:09Z
39,410,388
<p>Since 2.345 is not an integer, you need to determine what to do with the floating part. Do you want to ceil or floor it or round it?</p> <ul> <li><p><code>int(round(float("2.345")))</code> gives 2</p></li> <li><p><code>int(math.ceil(float("2.345")))</code> gives 3</p></li> <li><p><code>int(math.floor(float("2.345")))</code> gives 2</p></li> </ul>
1
2016-09-09T11:18:40Z
[ "python", "csv", "numpy", "matplotlib" ]
ValueError: invalid literal for int() with base 10: 'abc'
39,410,215
<p><strong>models.py</strong></p> <pre><code>class answers(models.Model): username = models.ForeignKey(settings.AUTH_USER_MODEL) title = models.ForeignKey(Task) answer = models.URLField() ANSWER_CHOICES = ( ('F', 'Declined'), ('T', 'Accepted'), ) accept_answer = models.CharField(max_length=1, choices=ANSWER_CHOICES, default='f') def __str__(self): return self.answer def __unicode__(self): return self.answer </code></pre> <p><strong>views.py</strong></p> <pre><code>def full_task(request, id): task = Task.objects.get(id = id) instance = get_object_or_404(answers, title=task.title) form = AnswerForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.save() context = { 'form':form, 'task': task, } **forms.py** from django import forms from .models import answers class AnswerForm(forms.ModelForm): answer = forms.URLField() class Meta: model = answers fields = [ "answer" ] </code></pre> <p><strong>TRACEBACK</strong></p> <pre><code>Traceback: File "C:\Users\rohit\Desktop\asad\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request) File "C:\Users\rohit\Desktop\asad\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\rohit\Desktop\asad\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\rohit\Desktop\asad\website\user_profile\views.py" in full_task 75. instance = get_object_or_404(answers, title=task.title) File "C:\Users\rohit\Desktop\asad\lib\site-packages\django\shortcuts.py" in get_object_or_404 85. return queryset.get(*args, **kwargs) File "C:\Users\rohit\Desktop\asad\lib\site-packages\django\db\models\query.py" in get 376. clone = self.filter(*args, **kwargs) File "C:\Users\rohit\Desktop\asad\lib\site-packages\django\db\models\query.py" in filter 796. return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\rohit\Desktop\asad\lib\site-packages\django\db\models\query.py" in _filter_or_exclude 814. clone.query.add_q(Q(*args, **kwargs)) File "C:\Users\rohit\Desktop\asad\lib\site-packages\django\db\models\sql\query.py" in add_q 1227. clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\rohit\Desktop\asad\lib\site-packages\django\db\models\sql\query.py" in _add_q 1253. allow_joins=allow_joins, split_subq=split_subq, File "C:\Users\rohit\Desktop\asad\lib\site-packages\django\db\models\sql\query.py" in build_filter 1183. condition = lookup_class(lhs, value) File "C:\Users\rohit\Desktop\asad\lib\site-packages\django\db\models\lookups.py" in __init__ 19. self.rhs = self.get_prep_lookup() File "C:\Users\rohit\Desktop\asad\lib\site-packages\django\db\models\fields\related_lookups.py" in get_prep_lookup 100. self.rhs = target_field.get_prep_value(self.rhs) File "C:\Users\rohit\Desktop\asad\lib\site-packages\django\db\models\fields\__init__.py" in get_prep_value 946. return int(value) Exception Type: ValueError at /tasks/1/ Exception Value: invalid literal for int() with base 10: 'abc' </code></pre> <p>i have used title as foreign key of Task model. and when i am using query like <code>get_object_or_404(answers, title=task.title)</code> and <code>Task.objects.get(title=task.title)</code> it is giving me this traceback. well i don't know how to remove this error . and one thing i cant understand that the title is a foreign field then how can i get data from diffrent using this foreign key? </p>
0
2016-09-09T11:09:43Z
39,410,283
<p>You need to pass in the <code>task</code> instance, not <code>task.title</code>:</p> <pre><code>instance = get_object_or_404(answers, title=task) </code></pre> <p><code>task.title</code> is a Unicode string, but the <code>answers.title</code> field is a foreign key. You could also pass in the <code>Task.id</code> field (assuming that that is the primary key field for that type).</p>
2
2016-09-09T11:12:50Z
[ "python", "django", "django-models", "django-views" ]
Horizontal layout of patches in legend (matplotlib)
39,410,223
<p>I create legend in my chart this way:</p> <pre><code>legend_handles.append(matplotlib.patches.Patch(color=color1, label='group1')) legend_handles.append(matplotlib.patches.Patch(color=color2, label='group2')) ax.legend(loc='upper center', handles=legend_handles, fontsize='small') </code></pre> <p>This results in the legend items stacked vertically (top-bottom), while I would like to put them horizontally left to right.</p> <p>How can I do that?</p> <p>(<code>matplotlib</code> v1.4.3)</p>
0
2016-09-09T11:10:25Z
39,410,716
<p>There is an argument determining the number of columns <code>ncol=</code>.</p> <pre><code>ax.legend(loc='upper center', handles=legend_handles, fontsize='small', ncol=2) </code></pre> <p>This should do the trick. Got it from <a href="http://stackoverflow.com/questions/14737681/fill-the-right-column-of-a-matplotlib-legend-first?rq=1">this</a> thread.</p>
1
2016-09-09T11:37:08Z
[ "python", "matplotlib" ]
QtQuickControls 2.0 with PyQt5
39,410,243
<p>I setup a virtualenv and installed pyqt5 (PyQt5-5.7-cp35-cp35m-manylinux1_x86_64.whl):</p> <pre><code>virtualenv -p /usr/bin/python3.5 . source bin/activate pip install pyqt5 </code></pre> <p>I created a basic.qml file:</p> <pre><code>import QtQuick 2.7 import QtQuick.Controls 2.0 Rectangle { width: 300 height: 100 color: "red" } </code></pre> <p>and tried to load it in my python code with:</p> <pre><code>import sys from PyQt5.QtCore import QUrl from PyQt5.QtWidgets import QApplication from PyQt5.QtQuick import QQuickView if __name__ == '__main__': myApp = QApplication(sys.argv) view = QQuickView() view.setSource(QUrl('basic.qml')) view.show() sys.exit(myApp.exec_()) </code></pre> <p>It fails with</p> <pre><code>file:///[...]/main.qml:2:1: plugin cannot be loaded for module "QtQuick.Controls": Cannot load library /[virtualenv]/lib/python3.5/site-packages/PyQt5/Qt/qml/QtQuick/Controls.2/libqtquickcontrols2plugin.so: (libQt5QuickTemplates2.so.5: Can't open shared object file: File or directory not found) import QtQuick.Controls 2.0 ^ Process finished with exit code 0 </code></pre> <p>I checked. This file it complains about actually doesn't exist. But how can I install it? Does PyQt5 support QtQuickControls2 at all?</p> <p>If I switch the import in basic.qml from <code>import QtQuick.Controls 2.0</code> to <code>import QtQuick.Controls 1.2</code>, it works. But I want to use the new controls.</p>
0
2016-09-09T11:11:14Z
39,420,154
<p>This looks like a bug in PyQt5. The package is missing both <code>libQt5QuickTemplates2.so</code> and <code>libQt5QuickControls2.so</code>.</p> <p>Hoping that the Qt 5.7 build contained by the PyQt 5.7 package and the official Qt 5.7 build available at qt.io are built in a fully binary compatible way, one possibility could be to download and install Qt 5.7 from qt.io, and copy the missing libraries into your virtualenv. For example:</p> <pre><code>$ cp ~/Qt/5.7/gcc_64/lib/libQt5QuickTemplates2.* path/to/lib/python3.5/site-packages/PyQt5/Qt/lib $ cp ~/Qt/5.7/gcc_64/lib/libQt5QuickControls2.* path/to/lib/python3.5/site-packages/PyQt5/Qt/lib </code></pre>
1
2016-09-09T21:46:13Z
[ "python", "pyqt", "pyqt5", "qtquickcontrols", "qtquickcontrols2" ]
Coreference resolution in python nltk using Stanford coreNLP
39,410,282
<p>Stanford CoreNLP provides coreference resolution <a href="http://nlp.stanford.edu/software/dcoref.shtml" rel="nofollow">as mentioned here</a>, also <a href="http://stackoverflow.com/questions/30954649/coreference-resolution-using-stanford-corenlp">this thread</a>, <a href="http://stackoverflow.com/questions/30362691/stanford-corenlp-wrong-coreference-resolution">this</a>, provides some insights about its implementation in Java.</p> <p>However, I am using python and NLTK and I am not sure how can I use Coreference resolution functionality of CoreNLP in my python code. I have been able to set up StanfordParser in NLTK, this is my code so far.</p> <pre><code>from nltk.parse.stanford import StanfordDependencyParser stanford_parser_dir = 'stanford-parser/' eng_model_path = stanford_parser_dir + "stanford-parser-models/edu/stanford/nlp/models/lexparser/englishRNN.ser.gz" my_path_to_models_jar = stanford_parser_dir + "stanford-parser-3.5.2-models.jar" my_path_to_jar = stanford_parser_dir + "stanford-parser.jar" </code></pre> <p>How can I use coreference resolution of CoreNLP in python?</p>
1
2016-09-09T11:12:47Z
39,514,695
<p>Maybe this works for you? <a href="https://github.com/dasmith/stanford-corenlp-python" rel="nofollow">https://github.com/dasmith/stanford-corenlp-python</a> If not, you can try to combine the two yourself using <a href="http://www.jython.org/" rel="nofollow">http://www.jython.org/</a></p>
0
2016-09-15T15:16:07Z
[ "python", "nlp", "nltk", "stanford-nlp" ]
Match URLs by file path and GET parameters (but not their values)
39,410,308
<p>How can I check if any of my list of URLs match the given <code>url</code>? I need URLs to match only if all GET parameter names (not their values) and the path are the same. For example, I have this list:</p> <pre><code>links = [ "http://example.com/page.php?param1=111&amp;param2=222", "http://example.com/page2.php?param1=111&amp;param2=222", "http://example.com/page2.php?param1=111&amp;param2=222&amp;someParameterN=NumberN" ] url = "http://example.com/page2.php?param1=NOT111&amp;param2=NOT222" </code></pre> <p>This example is <code>True</code> because <code>url</code> matches <code>links[1]</code>. But how to match it in the most efficient way? I don't know what <code>url</code> will looks like.</p>
1
2016-09-09T11:14:25Z
39,410,546
<p>I think <a href="http://www.tutorialspoint.com/python/string_split.htm" rel="nofollow">split</a> is your friend )</p> <p>First compare <code>links[i].split('?')[0]</code> with <code>url.split('?')[0]</code></p> <p>Then if true - split your vars with <code>'&amp;'</code>. </p> <p>I think there exists more optimal way, i'm only a newbee, but this way will works.</p>
1
2016-09-09T11:27:28Z
[ "python", "regex", "list", "url", "match" ]
Match URLs by file path and GET parameters (but not their values)
39,410,308
<p>How can I check if any of my list of URLs match the given <code>url</code>? I need URLs to match only if all GET parameter names (not their values) and the path are the same. For example, I have this list:</p> <pre><code>links = [ "http://example.com/page.php?param1=111&amp;param2=222", "http://example.com/page2.php?param1=111&amp;param2=222", "http://example.com/page2.php?param1=111&amp;param2=222&amp;someParameterN=NumberN" ] url = "http://example.com/page2.php?param1=NOT111&amp;param2=NOT222" </code></pre> <p>This example is <code>True</code> because <code>url</code> matches <code>links[1]</code>. But how to match it in the most efficient way? I don't know what <code>url</code> will looks like.</p>
1
2016-09-09T11:14:25Z
39,410,728
<p>You ideally want to use python's urlparse library. Parse your url like so:</p> <pre><code>import urlparse url = "http://example.com/page2.php?param1=NOT111&amp;param2=NOT222" parsed_url = urlparse.urlparse(url) urlparse.parse_qs(parsed_url.query).keys() </code></pre> <p>Then you create a datastructure which looks something like this:</p> <pre><code>seen_pages = set() # Stores all pages you've already seen. </code></pre> <p>And then all your pages to it like so:</p> <pre><code>for page in list_of_pages: parsed_url = urlparse.urlparse(page) current_page = (parsed_url.path, frozenset(urlparse.parse_qs(parsed_url.query).keys()) seen_pages.add(current_page) </code></pre> <p>This stores all your pages in the form: <code>tuple(link, set(param1,param2))</code> in a set.</p> <p>To look up if you've already visited the page, with those exact parameters, simply create the <code>current_page</code> structure again and look it up in the set. Look up and addition to a set is an <code>O(1)</code> operation, that is, it is as fast as you can get.</p>
3
2016-09-09T11:37:54Z
[ "python", "regex", "list", "url", "match" ]
Match URLs by file path and GET parameters (but not their values)
39,410,308
<p>How can I check if any of my list of URLs match the given <code>url</code>? I need URLs to match only if all GET parameter names (not their values) and the path are the same. For example, I have this list:</p> <pre><code>links = [ "http://example.com/page.php?param1=111&amp;param2=222", "http://example.com/page2.php?param1=111&amp;param2=222", "http://example.com/page2.php?param1=111&amp;param2=222&amp;someParameterN=NumberN" ] url = "http://example.com/page2.php?param1=NOT111&amp;param2=NOT222" </code></pre> <p>This example is <code>True</code> because <code>url</code> matches <code>links[1]</code>. But how to match it in the most efficient way? I don't know what <code>url</code> will looks like.</p>
1
2016-09-09T11:14:25Z
39,410,780
<p>I think that <a href="https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlparse" rel="nofollow"><code>urllib.parse.urlparse()</code></a> (if you are using Python 3) will help you, or <code>urlparse.urlparse()</code> for Python 2.</p> <p>This function will break the URL up into its various components. Then you can compare all components, or a subset of them as you require. Example (Python 3)</p> <pre><code>&gt;&gt;&gt; from urllib.parse import urlparse &gt;&gt;&gt; urlparse('http://example.com/page.php?param1=111&amp;param2=222') ParseResult(scheme='http', netloc='example.com', path='/page.php', params='', query='param1=111&amp;param2=222', fragment='') &gt;&gt;&gt; url1 = urlparse('http://example.com/page.php?param1=111&amp;param2=222') &gt;&gt;&gt; url2 = urlparse('http://example.com/page.php?param1=111&amp;param2=222') &gt;&gt;&gt; url1 == url2 True &gt;&gt;&gt; url3 = urlparse('http://example.com/page2.php?param2=222&amp;param1=111') &gt;&gt;&gt; url1 == url3 False &gt;&gt;&gt; url1.query == url3.query # same GET params but in different order False </code></pre> <p>The last example shows that the order of parameters in the query string affects the comparison. You can account for that by using <code>urllib.parse.parse_qs()</code>:</p> <pre><code>&gt;&gt;&gt; from urllib.parse import parse_qs &gt;&gt;&gt; parse_qs(url1.query) {'param2': ['222'], 'param1': ['111']} &gt;&gt;&gt; parse_qs(url1.query) == parse_qs(url3.query) True </code></pre> <p>You can use the <code>.path</code> attribute of the <code>ParseResult</code> to compare "pages".</p> <p>As I said, I think that will help you, however, I don't fully understand exactly what you are trying to do.</p>
1
2016-09-09T11:40:46Z
[ "python", "regex", "list", "url", "match" ]
Match URLs by file path and GET parameters (but not their values)
39,410,308
<p>How can I check if any of my list of URLs match the given <code>url</code>? I need URLs to match only if all GET parameter names (not their values) and the path are the same. For example, I have this list:</p> <pre><code>links = [ "http://example.com/page.php?param1=111&amp;param2=222", "http://example.com/page2.php?param1=111&amp;param2=222", "http://example.com/page2.php?param1=111&amp;param2=222&amp;someParameterN=NumberN" ] url = "http://example.com/page2.php?param1=NOT111&amp;param2=NOT222" </code></pre> <p>This example is <code>True</code> because <code>url</code> matches <code>links[1]</code>. But how to match it in the most efficient way? I don't know what <code>url</code> will looks like.</p>
1
2016-09-09T11:14:25Z
39,411,107
<p>Python's standard library comes with a package for parsing urls: <a href="https://docs.python.org/3/library/urllib.parse.html" rel="nofollow"><code>urllib.parse</code></a>. Don't try to write your own regexes for this... <em>especially</em> if you haven't considered all the weird things that are legal parts of a URL.</p> <p>I suggest something like below. <code>is_url_in_list</code> is the question you want answered. It calls <code>url_file_and_params</code> to break the URl into the file path and a set of query parameters. <code>url_file_and_params</code> calls <code>url_params_from_quoted_query</code> to build the set of parameter names.</p> <pre class="lang-python3 prettyprint-override"><code>#!/usr/bin/env python3 from urllib.parse import parse_qs from urllib.parse import urlsplit def url_params_from_quoted_query(query_string): # An empty query string would make parse_qs raise a ValueError. if '' == query_string: return set() params_and_values = parse_qs( query_string, keep_blank_values=True, strict_parsing=True, ) params = set(params_and_values) return params def url_file_and_params(url): parts = urlsplit(url) url_file = parts[2] quoted_query = parts[3] url_params = url_params_from_quoted_query(quoted_query) return url_file, url_params def is_url_in_list(url_target, url_list): target_file, target_params = url_file_and_params(url_target) for url in url_list: url_file, url_params = url_file_and_params(url) if url_file == target_file and url_params == target_params: return True return False def main(): links = [ "http://example.com/page.php?param1=111&amp;param2=222", "http://example.com/page2.php?param1=111&amp;param2=222", "http://example.com/page2.php?param1=&amp;param2=222", "http://example.com/page2.php", "http://example.com/page2.php?param1=111&amp;param2=222&amp;someParameterN=NumberN" ] url = "http://example.com/page2.php?param1=NOT111&amp;param2=NOT222" print(is_url_in_list(url, links)) return if "__main__" == __name__: main() </code></pre> <p>One assumption this code makes is that your URLs are already UTF-8 strings with correctly percent-encoded query strings. If not, you might need to use <a href="https://docs.python.org/3/library/urllib.parse.html#urllib.parse.quote" rel="nofollow"><code>quote</code></a> or <a href="https://docs.python.org/3/library/urllib.parse.html#urllib.parse.quote_from_bytes" rel="nofollow"><code>quote_from_bytes</code></a> before feeding them to <code>is_url_in_list</code>.</p>
2
2016-09-09T11:59:33Z
[ "python", "regex", "list", "url", "match" ]
Max of pandas dataframe columns multiplied together
39,410,335
<p>Given this data:</p> <pre><code>data = {'C1_IND' : [1,1,0,0,1], 'C1_PRICE' : [55,84,0,0,103], 'P1_IND' : [1,0,0,1,1], 'P1_PRICE' : [72,0,0,33,95]} df = pd.DataFrame(data) </code></pre> <p>How can I create a variable in the same dataframe that is:</p> <pre><code>max(C1_IND*C1_PRICE,P1_IND*P1_PRICE) </code></pre> <p>Also, would there be any issues if there are nulls in that data? </p>
2
2016-09-09T11:16:03Z
39,410,487
<p>I think you can select columns by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html" rel="nofollow"><code>filter</code></a>, then multiple by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.prod.html" rel="nofollow"><code>prod</code></a>. Last apply <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.max.html" rel="nofollow"><code>max</code></a>:</p> <pre><code>a = df.filter(like='C1').prod(1) b = df.filter(like='P1').prod(1) df['max'] = pd.DataFrame({'a':a,'b':b}).max(1) print (df) C1_IND C1_PRICE P1_IND P1_PRICE max 0 1 55 1 72 72 1 1 84 0 0 84 2 0 0 0 0 0 3 0 0 1 33 33 4 1 103 1 95 103 </code></pre> <p>Or:</p> <pre><code>df['a'] = df.filter(like='C1').prod(1) df['b'] = df.filter(like='P1').prod(1) df['max'] = df[['a','b']].max(1) df = df.drop(['a','b'], axis=1) print (df) C1_IND C1_PRICE P1_IND P1_PRICE max 0 1 55 1 72 72 1 1 84 0 0 84 2 0 0 0 0 0 3 0 0 1 33 33 4 1 103 1 95 103 </code></pre> <p>It works with <code>NaN</code> also, but add parameter <code>skipna=False</code> to <code>prod</code>:</p> <pre><code>data = {'C1_IND' : [1,1,0,0,1], 'C1_PRICE' : [55,84,0,0,8], 'P1_IND' : [1,0,0,1,10], 'P1_PRICE' : [72,0,0,33,np.nan]} df = pd.DataFrame(data) print (df) C1_IND C1_PRICE P1_IND P1_PRICE 0 1 55 1 72.0 1 1 84 0 0.0 2 0 0 0 0.0 3 0 0 1 33.0 4 1 8 10 NaN a = df.filter(like='C1').prod(1, skipna=False) b = df.filter(like='P1').prod(1, skipna=False) print (pd.DataFrame({'a':a,'b':b})) a b 0 55 72.0 1 84 0.0 2 0 0.0 3 0 33.0 4 8 NaN df['max'] = pd.DataFrame({'a':a,'b':b}).max(1) print (df) C1_IND C1_PRICE P1_IND P1_PRICE max 0 1 55 1 72.0 72.0 1 1 84 0 0.0 84.0 2 0 0 0 0.0 0.0 3 0 0 1 33.0 33.0 4 1 8 10 NaN 8.0 </code></pre>
3
2016-09-09T11:24:13Z
[ "python", "pandas", "dataframe", "max", "multiple-columns" ]
How to create a loop that checks if "Remove" exists for multiple "Remove" [Helium] [Selenium] [Python]
39,410,446
<p>How to loop the below logic inside a script, till all are deleted then continue to the next text. </p> <pre><code>if Text("Remove").exists(): click("Remove") </code></pre> <p>Explaination:</p> <p>==============</p> <p>WEBPAGE 1 CONTENTS:</p> <p>— A (REMOVE) — B (REMOVE) — C (REMOVE)</p> <p>[ “Remove” is a clickable link that removes A, B ,C]</p> <p>==============</p> <p>Part of my script now:</p> <p>if Text(“Remove”).exists(): click(“Remove”) click(“OK”)</p> <p>===============</p> <p>Result:</p> <p>WEBPAGE 1 CONTENTS:</p> <p>—</p> <p>— B (REMOVE) — C (REMOVE)</p> <p>================</p> <p>Above A is removed by the script. My question is how can i loop that, so the result is:</p> <p>===============</p> <p>Result:</p> <p>WEBPAGE 1 CONTENTS:</p> <p>—</p> <p>—</p> <p>—</p> <p>================</p> <p>So for every text on the webpage that containts “Remove” It executes the script untill there is no “Remove” anymore.</p>
-6
2016-09-09T11:22:01Z
39,411,034
<p>String have a replace method which you can directly use to replace the word with <code>''</code></p> <pre><code>page = 'Lorem remove ipsum elit remove id justo eu, finibus remove' page2 = 'Class aptent taciti sociosqu ad litora remove remove remove' pageList = [page, page2] for page in pageList: while 'remove' in page: page = page.replace('remove', '') print page #Out: Lorem ipsum elit id justo eu, finibus #Out: Class aptent taciti sociosqu ad litora </code></pre> <p>If it is specific HTML content replace that. </p> <pre><code>page.replace('&lt;a id="Remove"&gt;Remove&lt;/a&gt;', '') </code></pre> <p>Let me know if that helps. </p>
0
2016-09-09T11:55:40Z
[ "python", "selenium", "helium" ]
How to create a loop that checks if "Remove" exists for multiple "Remove" [Helium] [Selenium] [Python]
39,410,446
<p>How to loop the below logic inside a script, till all are deleted then continue to the next text. </p> <pre><code>if Text("Remove").exists(): click("Remove") </code></pre> <p>Explaination:</p> <p>==============</p> <p>WEBPAGE 1 CONTENTS:</p> <p>— A (REMOVE) — B (REMOVE) — C (REMOVE)</p> <p>[ “Remove” is a clickable link that removes A, B ,C]</p> <p>==============</p> <p>Part of my script now:</p> <p>if Text(“Remove”).exists(): click(“Remove”) click(“OK”)</p> <p>===============</p> <p>Result:</p> <p>WEBPAGE 1 CONTENTS:</p> <p>—</p> <p>— B (REMOVE) — C (REMOVE)</p> <p>================</p> <p>Above A is removed by the script. My question is how can i loop that, so the result is:</p> <p>===============</p> <p>Result:</p> <p>WEBPAGE 1 CONTENTS:</p> <p>—</p> <p>—</p> <p>—</p> <p>================</p> <p>So for every text on the webpage that containts “Remove” It executes the script untill there is no “Remove” anymore.</p>
-6
2016-09-09T11:22:01Z
39,411,666
<p>Since Your mind is orbiting around .remove() :</p> <pre><code>a = 'This is just a Test' a_list = [] for i in range(0, len(a) - 1): a_list.append(a[i]) while 't' in a_list: a_list.remove('t') # This Removes all lower case "t"s in a_list a = '' # Then you can change it into a string again : for n in range(0, len(a_list) - 1): a += a_list[n] print(a) # This is the original 'a' only without lower case "t"s </code></pre> <p>But this is <strong>NOT</strong> a good way to do (it's kinda ridicules) i recommend :</p> <p>.replace(,) </p> <p>which is already explained</p>
0
2016-09-09T12:30:43Z
[ "python", "selenium", "helium" ]
How do you define the real/imaginary parts of long symbolic expression without evaluation?
39,410,579
<p>I'm new to python and am having trouble with sympy. I define complex equations which are functions of the parameters a, b and use hold=true to save computation time. For example I have defined g in terms of other quantities A,B,C,D,E,F, as,</p> <pre><code>In [92]: g=sympy.MatAdd(sympy.MatMul(A, B), \ ...: sympy.MatMul(C, D, hold=sympy.true), \ ...: sympy.MatMul(E, F, hold=sympy.true), hold=sympy.true) </code></pre> <p>I want to define new quantities which are the ratio of the imaginary and real parts. For instance, alpha=Im(g)/Re(g). I have tried this by doing the following,</p> <pre><code>In [93]: alpha=sympy.im(g)/sympy.re(g) </code></pre> <p>,but I get the error,</p> <pre><code>In [94]: alpha=sympy.im(g)/sympy.re(g) Traceback (most recent call last): File "&lt;ipython-input-94-e3054aea27cc&gt;", line 1, in &lt;module&gt; alpha=sympy.im(g)/sympy.re(g) File "C:\Anaconda3\lib\site-packages\sympy\core\function.py", line 385, in __new__ result = super(Function, cls).__new__(cls, *args, **options) File "C:\Anaconda3\lib\site-packages\sympy\core\function.py", line 209, in __new__ evaluated = cls.eval(*args) File "C:\Anaconda3\lib\site-packages\sympy\functions\elementary\complexes.py", line 158, in eval coeff = term.as_coefficient(S.ImaginaryUnit) AttributeError: 'MatAdd' object has no attribute 'as_coefficient' </code></pre> <p>Even if this was successful though, I doubt I'd want to wait around for it to finish. My first question is - how can one fix the definition on line 93, while suppressing the evaluation?</p> <p>Providing this can somehow be done, I want to define f(alpha(a,b), beta(a,b)), where beta is defined similarly to alpha. I want to then plot a and b such that f=0. I was thinking something like this would work,</p> <pre><code>p1=sympy.plot_implicit(f(alpha(a,b),beta(a,b)),(a,0,2.5),(b,0,4)) </code></pre> <p>Is this the most efficient way or would a different approach be better?</p> <p>I was thinking of using lambdify to define g_num,</p> <pre><code>g_num=sympy.lambdify((a,b), g, 'numpy') </code></pre> <p>After that define a lambda function</p> <pre><code>lambda a,b,delta : f(alpha(a,b), beta(a,b)) </code></pre> <p>but then I don't know how to obtain the implicit plot f(a,b)=0 with this method.</p>
2
2016-09-09T11:29:22Z
39,459,583
<p><code>hold=True</code> isn't a real SymPy option. You want <code>evaluate=False</code>. Note that <code>MatMul</code> already doesn't evaluate by default. </p> <p><code>re</code> and <code>im</code> are <a href="https://github.com/sympy/sympy/issues/11600" rel="nofollow">presently</a> only defined to operate on scalars, not matrices. That's why you are getting the error you are getting. Using <code>re(g, evaluate=False)</code> should work, since the lambdified <code>re</code> from NumPy will just broadcast over the array. </p>
1
2016-09-12T22:15:06Z
[ "python", "numpy", "math", "plot", "sympy" ]
Providing 'default' User when not logged in instead of AnonymousUser
39,410,656
<p><strong>Is there a way to globally provide a custom instance of <code>User</code> class instead of <code>AnonymousUser</code>?</strong></p> <p>It is not possible to assign <code>AnonymousUser</code> instances when <code>User</code> is expected (for example in forms, there is need to check for authentication and so on), and therefore having an ordinary <code>User</code> class with name 'anonymous' (so that we could search for it in the DB) would be globally returned when a non-authenticated user visits the page. Somehow implementing a custom authentication mechanism would do the trick? And I also want to ask if such an idea is a standard approach before diving into this.</p>
1
2016-09-09T11:34:02Z
39,411,527
<p>You could create a custom middleware (called after AuthenticationMiddleware), that checks if the user if logged in or not, and if not, replaces the current user object attached to request, with the the user of your choice.</p>
1
2016-09-09T12:23:24Z
[ "python", "django" ]
Different guiding_lines_colos for different leaf nodes in ETE3 using TreeStyle class or anything else
39,410,916
<p>How how can I add different colors for guiding line (connecting leaf node with the text using <a href="http://etetoolkit.org/docs/latest/reference/reference_treeview.html" rel="nofollow">guiding_lines_color in TreeStyle class</a>) in ETE3 python module.</p> <p>Thanks</p>
1
2016-09-09T11:48:46Z
39,414,447
<p>Use TreeStyle.guiding_lines_color </p> <p><a href="http://etetoolkit.org/docs/latest/reference/reference_treeview.html#ete3.TreeStyle" rel="nofollow">http://etetoolkit.org/docs/latest/reference/reference_treeview.html#ete3.TreeStyle</a></p>
1
2016-09-09T14:55:39Z
[ "python", "etetoolkit", "ete3" ]
Render Counter Collections Sort Order
39,410,954
<p>I can't figure out how to display a collections.Counter in the right order in Django: When i use Counter().most_common(5) it should give me the 5 most common keys in order. But it does not.</p> <p>I've got this:</p> <pre><code>users_cities = dict(Counter(User.objects.all().values_list('city', flat=True)).most_common(5)) return render(request,'admin/stats/stats.html', { 'users_cities': users_cities, } </code></pre> <p>But when i loop through them in the template, they arent sorted:</p> <pre><code>{% for label , counter in users_cities.items %} {% if label %} &lt;tr&gt; &lt;th&gt;{{ label }}&lt;/th&gt;&lt;td&gt; {{ counter }}&lt;/td&gt; &lt;/tr&gt; {% endif %} {% endfor %} </code></pre> <p>So where is my mistake?</p>
1
2016-09-09T11:50:53Z
39,411,117
<p>You extracted the most common, but then put them back into a new dict. Dicts are unordered.</p> <p>Skip the <code>dict</code> call and just iterate through the result you get from <code>most_common</code>.</p>
2
2016-09-09T12:00:20Z
[ "python", "django", "collections" ]
Render Counter Collections Sort Order
39,410,954
<p>I can't figure out how to display a collections.Counter in the right order in Django: When i use Counter().most_common(5) it should give me the 5 most common keys in order. But it does not.</p> <p>I've got this:</p> <pre><code>users_cities = dict(Counter(User.objects.all().values_list('city', flat=True)).most_common(5)) return render(request,'admin/stats/stats.html', { 'users_cities': users_cities, } </code></pre> <p>But when i loop through them in the template, they arent sorted:</p> <pre><code>{% for label , counter in users_cities.items %} {% if label %} &lt;tr&gt; &lt;th&gt;{{ label }}&lt;/th&gt;&lt;td&gt; {{ counter }}&lt;/td&gt; &lt;/tr&gt; {% endif %} {% endfor %} </code></pre> <p>So where is my mistake?</p>
1
2016-09-09T11:50:53Z
39,411,920
<p>It is nice that you got the answer. But I wont prefer to go for Counter as we have annotate in Django.</p> <p>When you use Counter the code will be</p> <pre><code>users_cities = Counter(User.objects.all().values_list('city', flat=True)).most_common(5) </code></pre> <p>which results in an SQL query of </p> <pre><code>SELECT city FROM user </code></pre> <p>You can use annotate instead.</p> <pre><code>users_cities = User.objects.all().values('city').annotate(count = Count('city')).order_by('-count')[:5] </code></pre> <p>This results in a query of </p> <pre><code>SELECT city, COUNT(user.city) AS count FROM user GROUP BY user.city </code></pre> <p>ORDER BY count DESC LIMIT 5</p> <p>And the query time will also be less.</p> <p>I hope that this helps. :)</p>
1
2016-09-09T12:44:50Z
[ "python", "django", "collections" ]
AttributeError: 'module' object has no attribute 'graphviz_layout' with networkx 1.11
39,411,102
<p>I'm trying to draw some DAGs using networkx 1.11 but I'm facing some errors, here's the test:</p> <pre><code>import networkx as nx print nx.__version__ G = nx.DiGraph() G.add_node(1,level=1) G.add_node(2,level=2) G.add_node(3,level=2) G.add_node(4,level=3) G.add_edge(1,2) G.add_edge(1,3) G.add_edge(2,4) import pylab as plt nx.draw_graphviz(G, node_size=1600, cmap=plt.cm.Blues, node_color=range(len(G)), prog='dot') plt.show() </code></pre> <p>And here's the traceback:</p> <pre><code>Traceback (most recent call last): File "D:\sources\personal\python\framework\stackoverflow\test_dfs.py", line 69, in &lt;module&gt; prog='dot') File "d:\virtual_envs\py2711\lib\site-packages\networkx\drawing\nx_pylab.py", line 984, in draw_graphviz pos = nx.drawing.graphviz_layout(G, prog) AttributeError: 'module' object has no attribute 'graphviz_layout' </code></pre> <p>I'm using python 2.7.11 x64, networkx 1.11 and I've installed <a href="http://www.graphviz.org/Download_windows.php" rel="nofollow">graphviz-2.38</a> having <code>dot</code> available in PATH. What am I missing?</p> <p>Once it works, how could i draw the graph with nodes which:</p> <ul> <li>Use white background color </li> <li>Have labels inside</li> <li>Have directed arrows</li> <li>Are arranged nicely either automatically or manually</li> </ul> <p>Something similar to the below image</p> <p><a href="http://i.stack.imgur.com/Vhuai.png" rel="nofollow"><img src="http://i.stack.imgur.com/Vhuai.png" alt="enter image description here"></a></p> <p>As you can see in that image, nodes are aligned really nicely</p>
4
2016-09-09T11:59:23Z
39,603,436
<p>The package layout has changed in later versions of networkx. You can import the graphivz_layout function explicitly.</p> <pre><code>import networkx as nx import pylab as plt from networkx.drawing.nx_agraph import graphviz_layout G = nx.DiGraph() G.add_node(1,level=1) G.add_node(2,level=2) G.add_node(3,level=2) G.add_node(4,level=3) G.add_edge(1,2) G.add_edge(1,3) G.add_edge(2,4) nx.draw(G, pos=graphviz_layout(G), node_size=1600, cmap=plt.cm.Blues, node_color=range(len(G)), prog='dot') plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/D0XDx.png" rel="nofollow"><img src="http://i.stack.imgur.com/D0XDx.png" alt="enter image description here"></a></p>
2
2016-09-20T20:46:04Z
[ "python", "python-2.7", "networkx" ]
Make a label / annotation appear, when hovering over an area (rectangle)
39,411,116
<p>As you can see the question above, I was wondering, if it is possible to popup a label, when I hover on a rectangle-area. </p> <p>I found this <a href="http://stackoverflow.com/questions/11537374/matplotlib-basemap-popup-box/11556140#11556140">solution</a> which helped me for popping up a label over a <strong>point</strong>. </p> <p>But is it possible to popup a label, when the user hovers somewhere over an area?</p> <p>On my plot, I'm using this code example for adding rectangles:</p> <p><a href="http://matthiaseisen.com/pp/patterns/p0203/" rel="nofollow">http://matthiaseisen.com/pp/patterns/p0203/</a></p> <p>Let's use this as example:</p> <p><img src="http://matthiaseisen.com/pp/static/p0203_1.png" alt="Hover square"></p> <p>When the user hovers (everywhere) over the blue area, a popup "You are hovering over the blue area" should appear.</p> <p>Is this even possible in matplotlib? I can't find any solution for this problem.</p>
1
2016-09-09T12:00:19Z
39,412,339
<p>Matplotlib by itself isn't going to give you this functionality. Bokeh <a href="http://bokeh.pydata.org/en/latest/docs/user_guide/quickstart.html" rel="nofollow">(link)</a>, another python library, is what you want. <a href="http://bokeh.pydata.org/en/latest/docs/gallery/texas.html" rel="nofollow">Here is an example</a> with the hovertool feature, which is what you're looking for. You can even export the image as html so you can put it on a website or blog. </p>
1
2016-09-09T13:08:34Z
[ "python", "python-2.7", "matplotlib" ]
identify a set containing correct values in dictionary of sets
39,411,357
<p>I have a dictionary of sets, and two values to test. I need to identify the set containing both values (there's only one correct set) and return the key of that set. I thought I could get away with a one-liner like that below, but no success this far. </p> <pre><code>d = {"set1": {"A", "B", "C"}, "set2": {"D", "E", "F"}, "set3":{"A", "D", "C"}} value1 = "A" value2 = "B" def do_values_belong_in_same_set(value1, value2): if all(x in v for k, v in d.items() for x in [value1, value2]) is True: return True, k else: return False </code></pre> <p>The desired output here would be: True, "set1"</p> <p>The "v for k, v in d.items()" part doesn't do the trick. Nor does simpler "x in d.values()" What would work? Or will I just need to construct a proper for-loop for this? Thanks for your help!</p>
1
2016-09-09T12:13:57Z
39,411,404
<pre><code>&gt;&gt;&gt; value1 = "A" &gt;&gt;&gt; value2 = "B" &gt;&gt;&gt; d = {"set1": {"A", "B", "C"}, "set2": {"D", "E", "F"}, "set3":{"A", "D", "C"}} &gt;&gt;&gt; [k for k, v in d.items() if value1 in v and value2 in v] ['set1'] </code></pre>
5
2016-09-09T12:16:47Z
[ "python", "python-3.x" ]
identify a set containing correct values in dictionary of sets
39,411,357
<p>I have a dictionary of sets, and two values to test. I need to identify the set containing both values (there's only one correct set) and return the key of that set. I thought I could get away with a one-liner like that below, but no success this far. </p> <pre><code>d = {"set1": {"A", "B", "C"}, "set2": {"D", "E", "F"}, "set3":{"A", "D", "C"}} value1 = "A" value2 = "B" def do_values_belong_in_same_set(value1, value2): if all(x in v for k, v in d.items() for x in [value1, value2]) is True: return True, k else: return False </code></pre> <p>The desired output here would be: True, "set1"</p> <p>The "v for k, v in d.items()" part doesn't do the trick. Nor does simpler "x in d.values()" What would work? Or will I just need to construct a proper for-loop for this? Thanks for your help!</p>
1
2016-09-09T12:13:57Z
39,411,470
<p>You can use <a href="https://docs.python.org/3/library/stdtypes.html#set.issubset" rel="nofollow"><code>set.issubset</code></a> (which uses the <code>&lt;=</code> operator) by combining your needle characters into a set.</p> <pre><code>d = {"set1": {"A", "B", "C"}, "set2": {"D", "E", "F"}, "set3":{"A", "D", "C"}} value1 = "A" value2 = "B" needle_set = set([value1, value2]) result = next(k for k,v in d.items() if needle_set.issubset(v)) # or needle_set &lt;= v, or v &gt;= needle_set, or # v.issuperset(needle_set), all are the same condition </code></pre> <p>You could roll it into a function with your requested output like:</p> <pre><code>def do_values_belong_in_same_set(source_d, *values): # I use the variadic argument `value` here so you can check any number of values # and include the source dict by name as best practice needle_set = set(values) result = next(k for k,v in source_d.items() if needle_set &lt;= v) if result: return True, result else: return False </code></pre>
3
2016-09-09T12:20:39Z
[ "python", "python-3.x" ]
identify a set containing correct values in dictionary of sets
39,411,357
<p>I have a dictionary of sets, and two values to test. I need to identify the set containing both values (there's only one correct set) and return the key of that set. I thought I could get away with a one-liner like that below, but no success this far. </p> <pre><code>d = {"set1": {"A", "B", "C"}, "set2": {"D", "E", "F"}, "set3":{"A", "D", "C"}} value1 = "A" value2 = "B" def do_values_belong_in_same_set(value1, value2): if all(x in v for k, v in d.items() for x in [value1, value2]) is True: return True, k else: return False </code></pre> <p>The desired output here would be: True, "set1"</p> <p>The "v for k, v in d.items()" part doesn't do the trick. Nor does simpler "x in d.values()" What would work? Or will I just need to construct a proper for-loop for this? Thanks for your help!</p>
1
2016-09-09T12:13:57Z
39,411,501
<p>You can filter the sets for which the set composed of value1 and value2 is a subset:</p> <pre><code>def do_values_belong_in_same_set(value1, value2): sets = [key for key, s in d.items() if {value1, value2} &lt;= s] if sets: return True, sets[0] else: return False </code></pre>
0
2016-09-09T12:22:23Z
[ "python", "python-3.x" ]
identify a set containing correct values in dictionary of sets
39,411,357
<p>I have a dictionary of sets, and two values to test. I need to identify the set containing both values (there's only one correct set) and return the key of that set. I thought I could get away with a one-liner like that below, but no success this far. </p> <pre><code>d = {"set1": {"A", "B", "C"}, "set2": {"D", "E", "F"}, "set3":{"A", "D", "C"}} value1 = "A" value2 = "B" def do_values_belong_in_same_set(value1, value2): if all(x in v for k, v in d.items() for x in [value1, value2]) is True: return True, k else: return False </code></pre> <p>The desired output here would be: True, "set1"</p> <p>The "v for k, v in d.items()" part doesn't do the trick. Nor does simpler "x in d.values()" What would work? Or will I just need to construct a proper for-loop for this? Thanks for your help!</p>
1
2016-09-09T12:13:57Z
39,411,600
<p>You could slightly change the logic in your function to achieve this:</p> <pre><code>def do_values_belong_in_same_set(value1, value2): r = next((k for k, v in d.items() if all(i in v for i in {value1, value2})), False) if r: return True, r else: return r </code></pre> <p>Calling <code>next</code> on the generator will return the first <code>k</code> (set name) if one exists and a default value of <code>False</code> is assigned if the value is not present. Then you return accordingly. </p> <p>This yields the following results for different runs:</p> <pre><code>do_values_belong_in_same_set(value1, value2) (True, 'set1') do_values_belong_in_same_set(value1, 'F') False do_values_belong_in_same_set(value1, 'E') False do_values_belong_in_same_set('F', 'E') (True, 'set2') </code></pre>
0
2016-09-09T12:27:03Z
[ "python", "python-3.x" ]
How do i get my support vector regression to work to plot my polynomial graph
39,411,384
<p>I have compiled my code for a polynomial graph, but it is not plotting. I am using SVR(support vector regression) from scikit learn and my code is below. It is not showing any error message, and it is just showing my data. I don't know what is going on. Does anyone? It is not even showing anything on the variable console describing my data.</p> <pre><code>import pandas as pd import numpy as np from sklearn.svm import SVR from sklearn import cross_validation from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt df = pd.read_csv('coffee.csv') print(df) df = df[['Date','Amount_prod','Beverage_index']] x = np.array(df.Amount_prod) y = np.array(df.Beverage_index) x_train, x_test, y_train, y_test = cross_validation.train_test_split( x, y, test_size=0.2) x_train = np.pad(x, [(0,0)], mode='constant') x_train.reshape((26,1)) y_train = np.pad(y, [(0,0)], mode='constant') y_train.reshape((26,1)) x_train = np.arange(26).reshape((26, 1)) x_train = x.reshape((26, 1)) c = x.T np.all(x_train == c) x_test = np.arange(6).reshape((-1,1)) x_test = x.reshape((-1,1)) c2 = x.T np.all(x_test == c2) y_test = np.arange(6).reshape((-1,1)) y_test = y.reshape((-1,1)) c2 = y.T np.all(y_test ==c2) svr_poly = SVR(kernel='poly', C=1e3, degree=2) y_poly = svr_poly.fit(x_train,y_train).predict(x_train) plt.scatter(x_train, y_train, color='black') plt.plot(x_train, y_poly) plt.show() </code></pre> <p>Data sample:</p> <pre><code> Date Amount_prod Beverage_index 1990 83000 78 1991 102000 78 1992 94567 86 1993 101340 88 1994 96909 123 1995 92987 101 1996 103489 99 1997 99650 109 1998 107849 110 1999 123467 90 2000 112586 67 2001 113485 67 2002 108765 90 </code></pre>
1
2016-09-09T12:15:33Z
39,419,386
<p>Try the code below. Support Vector Machines expect their input to have zero mean and unit variance. It's not the plot, that's blocking. It's the call to <code>fit</code>.</p> <pre><code>from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler svr_poly = make_pipeline(StandardScaler(), SVR(kernel='poly', C=1e3, degree=2)) y_poly = svr_poly.fit(x_train,y_train).predict(x_train) </code></pre>
2
2016-09-09T20:39:32Z
[ "python", "machine-learning", "scikit-learn", "svm" ]
How do i get my support vector regression to work to plot my polynomial graph
39,411,384
<p>I have compiled my code for a polynomial graph, but it is not plotting. I am using SVR(support vector regression) from scikit learn and my code is below. It is not showing any error message, and it is just showing my data. I don't know what is going on. Does anyone? It is not even showing anything on the variable console describing my data.</p> <pre><code>import pandas as pd import numpy as np from sklearn.svm import SVR from sklearn import cross_validation from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt df = pd.read_csv('coffee.csv') print(df) df = df[['Date','Amount_prod','Beverage_index']] x = np.array(df.Amount_prod) y = np.array(df.Beverage_index) x_train, x_test, y_train, y_test = cross_validation.train_test_split( x, y, test_size=0.2) x_train = np.pad(x, [(0,0)], mode='constant') x_train.reshape((26,1)) y_train = np.pad(y, [(0,0)], mode='constant') y_train.reshape((26,1)) x_train = np.arange(26).reshape((26, 1)) x_train = x.reshape((26, 1)) c = x.T np.all(x_train == c) x_test = np.arange(6).reshape((-1,1)) x_test = x.reshape((-1,1)) c2 = x.T np.all(x_test == c2) y_test = np.arange(6).reshape((-1,1)) y_test = y.reshape((-1,1)) c2 = y.T np.all(y_test ==c2) svr_poly = SVR(kernel='poly', C=1e3, degree=2) y_poly = svr_poly.fit(x_train,y_train).predict(x_train) plt.scatter(x_train, y_train, color='black') plt.plot(x_train, y_poly) plt.show() </code></pre> <p>Data sample:</p> <pre><code> Date Amount_prod Beverage_index 1990 83000 78 1991 102000 78 1992 94567 86 1993 101340 88 1994 96909 123 1995 92987 101 1996 103489 99 1997 99650 109 1998 107849 110 1999 123467 90 2000 112586 67 2001 113485 67 2002 108765 90 </code></pre>
1
2016-09-09T12:15:33Z
39,419,716
<p>Just to build on Matt's answer a little. Nothing about your plotting is in error. When you call to svr_poly.fit with 'unreasonably' large numbers no error is thrown (but I still had to kill my kernel). By tinkering the exponent value in this code I reckoned that you could get up to 1e5 before it breaks, but not more. Hence your problem. As Matt says, applying the StandardScaler will solve your problems.</p> <pre><code>import pandas as pd import numpy as np from sklearn.svm import SVR import matplotlib.pyplot as plt x_train = np.random.rand(10,1) # between 0 and 1 y_train = np.random.rand(10,) # between 0 and 1 x_train = np.multiply(x_train,1e5) #scaling up to 1e5 svr_poly = SVR(kernel='poly', C=1e3, degree=1) svr_poly.fit(x_train,y_train)#.predict(x_train) y_poly = svr_poly.predict(x_train) plt.scatter(x_train, y_train, color='black') plt.plot(x_train, y_poly) plt.show() </code></pre>
0
2016-09-09T21:08:37Z
[ "python", "machine-learning", "scikit-learn", "svm" ]
Re-using intermediate results in Dask (mixing delayed and dask.dataframe)
39,411,407
<p>Based on the answer I had received on <a href="http://stackoverflow.com/questions/39328398/locking-in-dask-multiprocessing-get-and-adding-metadata-to-hdf">an earlier question</a>, I have written an ETL procedure that looks as follows: </p> <pre><code>import pandas as pd from dask import delayed from dask import dataframe as dd def preprocess_files(filename): """Reads file, collects metadata and identifies lines not containing data. """ ... return filename, metadata, skiprows def load_file(filename, skiprows): """Loads the file into a pandas dataframe, skipping lines not containing data.""" return df def process_errors(filename, skiplines): """Calculates error metrics based on the information collected in the pre-processing step """ ... def process_metadata(filename, metadata): """Analyses metadata collected in the pre-processing step.""" ... values = [delayed(preprocess_files)(fn) for fn in file_names] filenames = [value[0] for value in values] metadata = [value[1] for value in values] skiprows = [value[2] for value in values] error_results = [delayed(process_errors)(arg[0], arg[1]) for arg in zip(filenames, skiprows)] meta_results = [delayed(process_metadata)(arg[0], arg[1]) for arg in zip(filenames, metadata)] dfs = [delayed(load_file)(arg[0], arg[1]) for arg in zip(filenames, skiprows)] ... # several delayed transformations defined on individual dataframes # finally: categorize several dataframe columns and write them to HDF5 dfs = dd.from_delayed(dfs, meta=metaframe) dfs.categorize(columns=[...]) # I would like to delay this dfs.to_hdf(hdf_file_name, '/data',...) # I would also like to delay this all_operations = error_results + meta_results # + delayed operations on dask dataframe # trigger all computation at once, # allow re-using of data collected in the pre-processing step. dask.compute(*all_operations) </code></pre> <p>The ETL-process goes through several steps:</p> <ol> <li>Pre-process the files, identify lines which do not include any relevant data and parse metadata</li> <li>Using information gathered, process error information, metadata and load data-lines into pandas dataframes in parallel (re-using the results from the pre-processing step). The operations (<code>process_metadata</code>, <code>process_errors</code>, <code>load_file</code>) have a shared data dependency in that they all use information gathered in the pre-processing step. Ideally, the pre-processing step would only be run once and the results shared across processes. </li> <li>eventually, collect the pandas dataframes into a dask dataframe, categorize them and write them to hdf.</li> </ol> <p>The problem I am having with this is, that <code>categorize</code> and <code>to_hdf</code> trigger computation immediately, discarding metadata and error-data which otherwise would be further processed by <code>process_errors</code> and <code>process_metadata</code>. </p> <p>I have been told that delaying operations on <code>dask.dataframes</code> can cause problems, which is why I would be very interested to know whether it is possible to trigger the entire computation (processing metadata, processing errors, loading dataframes, transforming dataframes and storing them in HDF format) at once, allowing the different processes to share the data collected in the pre-processing phase.</p>
2
2016-09-09T12:17:19Z
39,412,000
<p>There are two ways to approach your problem:</p> <ol> <li>Delay everything</li> <li>Compute in stages</li> </ol> <h3>Delay Everything</h3> <p>The to_hdf call accepts a <code>compute=</code> keyword argument that you can set to False. If False it will hand you back a <code>dask.delayed</code> value that you can compute whenever you feel like it.</p> <p>The categorize call however does need to be computed immediately if you want to keep using dask.dataframe. We're unable to create a consistent dask.dataframe without going through the data more-or-less immediately. Recent improvements in Pandas around unioning categoricals will let us change this in the future, but for now you're stuck. If this is a blocker for you then you'll have to switch down to <code>dask.delayed</code> and handle things manually for a bit with <code>df.to_delayed()</code></p> <h3>Compute in Stages</h3> <p>If you use the <a href="http://distributed.readthedocs.io/en/latest/" rel="nofollow">distributed scheduler</a> you can stage your computation by using the <a href="http://distributed.readthedocs.io/en/stable/api.html#distributed.executor.Executor.persist" rel="nofollow"><code>.persist</code> method</a>. </p> <pre><code>from dask.distributed import Executor e = Executor() # make a local "cluster" on your laptop delayed_values = e.persist(*delayed_values) ... define further computations on delayed values ... results = dask.compute(results) # compute as normal </code></pre> <p>This will let you trigger some computations and still let you proceed onwards defining your computation. The values that you persist will stay in memory. </p>
2
2016-09-09T12:48:56Z
[ "python", "dask" ]
flask file upload not working
39,411,417
<p>I have problem with file upload. I getting no errors but i can't to find file. I was looking for solution but without success. Can anyone help to me? My code:</p> <pre><code>UPLOAD_FOLDER = '/upload/' ALLOWED_EXTENSIONS = set(['.xlsx', '.xls']) app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename): print(filename) return '.' in filename and \ filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS @app.route('/file_upload', methods=['GET', 'POST']) def file(): if request.method == 'POST': print(os.getcwd()) if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] # if user does not select file, browser also # submit a empty part without filename if file.filename == '': flash('No selected file') return redirect(request.url) if file and allowed_file(file.filename): print(filename) filename = secure_filename(file.filename) print(filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return redirect(url_for('uploaded_file', filename=filename)) return render_template("/file_upload.html", role="ok") </code></pre> <p>this is example form <a href="http://flask.pocoo.org/docs/0.11/patterns/fileuploads/" rel="nofollow">Flask Doc</a></p>
0
2016-09-09T12:17:54Z
39,411,537
<p>Your <code>allowed_extensions</code> function is splitting on <code>"."</code>, i.e. returning sub-strings split by <code>"."</code>, but then <code>ALLOWED_EXTENSIONS</code> still contains <code>"."</code>s.</p> <p>Replace your <code>ALLOWED_EXTENSIONS</code> with </p> <pre><code>ALLOWED_EXTENSIONS = set(['xlsx', 'xls']) </code></pre>
0
2016-09-09T12:23:52Z
[ "python", "flask" ]
Django - Follow a backward ForeignKey and then a ForeignKey (query)
39,411,477
<p>I use Django 1.9 and Python 2.7.</p> <p>My app has four models. Each "trip" is made of several "steps" chosen by the visitor, which relate to "places", which may have several related "Picture".</p> <pre><code>class Trip(models.Model): title = models.CharField(max_length=140, blank=True) class Step(models.Model): theplace = models.ForeignKey(ThePlace) trip = models.ForeignKey(Trip) class ThePlace(models.Model): name = models.CharField(max_length=200) class Picture(models.Model): file = models.ImageField(upload_to="pictures") slug = models.SlugField(max_length=100, blank=True) theplace = models.ForeignKey(ThePlace, null=True, blank=True) </code></pre> <p>I would like to retrieve all "Picture" objects which are related to a specific Trip, using an existing "selectedtrip" queryset:</p> <pre><code>selectedtrip = Trip.objects.filter(author=request.user)[0] pictures = selectedtrip.step_set.all().theplace.picture_set.all() </code></pre> <p>Django displays the following error: "AttributeError: 'QuerySet' object has no attribute 'theplace'" Any idea why ?</p>
0
2016-09-09T12:20:58Z
39,411,536
<p>Because <code>all()</code> returns a queryset, which is a collection of items; <code>theplace</code> is an attribute on an individual Step, not on the collection.</p> <p>The way to do this type of query is to start from the class you want to retrieve, and follow the relationships within the query using the double-underscore syntax. So:</p> <pre><code>Picture.objects.filter(theplace__step__trip=selectedtrip) </code></pre>
0
2016-09-09T12:23:51Z
[ "python", "django", "django-models", "foreign-keys", "django-queryset" ]
Django - Follow a backward ForeignKey and then a ForeignKey (query)
39,411,477
<p>I use Django 1.9 and Python 2.7.</p> <p>My app has four models. Each "trip" is made of several "steps" chosen by the visitor, which relate to "places", which may have several related "Picture".</p> <pre><code>class Trip(models.Model): title = models.CharField(max_length=140, blank=True) class Step(models.Model): theplace = models.ForeignKey(ThePlace) trip = models.ForeignKey(Trip) class ThePlace(models.Model): name = models.CharField(max_length=200) class Picture(models.Model): file = models.ImageField(upload_to="pictures") slug = models.SlugField(max_length=100, blank=True) theplace = models.ForeignKey(ThePlace, null=True, blank=True) </code></pre> <p>I would like to retrieve all "Picture" objects which are related to a specific Trip, using an existing "selectedtrip" queryset:</p> <pre><code>selectedtrip = Trip.objects.filter(author=request.user)[0] pictures = selectedtrip.step_set.all().theplace.picture_set.all() </code></pre> <p>Django displays the following error: "AttributeError: 'QuerySet' object has no attribute 'theplace'" Any idea why ?</p>
0
2016-09-09T12:20:58Z
39,411,579
<p>Note that your model does not have an author field.</p> <pre><code>class Trip(models.Model): title = models.CharField(max_length=140, blank=True) </code></pre> <p>Assuming that it did, you can try something like this</p> <pre><code>Picture.objects.filter(theplace__step__trip__author=request.user) </code></pre> <p>This achieves the same thing with just one query.</p>
0
2016-09-09T12:25:53Z
[ "python", "django", "django-models", "foreign-keys", "django-queryset" ]
Why kafka-python fails to connect to Bluemix message hub service?
39,411,756
<p>I'm trying to connect to a Bluemix Message Hub instance on <a href="http://bluemix.net" rel="nofollow">http://bluemix.net</a>. This simple script</p> <pre><code>#!/usr/bin/env python from kafka import KafkaProducer from kafka.errors import KafkaError kafka_brokers_sasl = [ "kafka01-prod01.messagehub.services.us-south.bluemix.net:9093", "kafka02-prod01.messagehub.services.us-south.bluemix.net:9093", "kafka03-prod01.messagehub.services.us-south.bluemix.net:9093", "kafka04-prod01.messagehub.services.us-south.bluemix.net:9093", "kafka05-prod01.messagehub.services.us-south.bluemix.net:9093" ] sasl_plain_username = "xxxxxxxxxxxxxxx" sasl_plain_password = "xxxxxxxxxxxxxxxxxxxxxxxxx" sasl_mechanism = 'SASL_PLAINTEXT' producer = KafkaProducer(bootstrap_servers = kafka_brokers_sasl, sasl_plain_username = sasl_plain_username, sasl_plain_password = sasl_plain_password, sasl_mechanism = sasl_mechanism ) </code></pre> <p>ends with the exception below:</p> <pre><code>Traceback (most recent call last): File "./test-mh.py", line 12, in &lt;module&gt; producer = KafkaProducer(bootstrap_servers = kafka_brokers_sasl, sasl_plain_username = sasl_plain_username, sasl_plain_password = sasl_plain_password, sasl_mechanism = sasl_mechanism ) File "/usr/local/lib/python2.7/dist-packages/kafka/producer/kafka.py", line 328, in __init__ **self.config) File "/usr/local/lib/python2.7/dist-packages/kafka/client_async.py", line 202, in __init__ self.config['api_version'] = self.check_version(timeout=check_timeout) File "/usr/local/lib/python2.7/dist-packages/kafka/client_async.py", line 791, in check_version raise Errors.NoBrokersAvailable() kafka.errors.NoBrokersAvailable: NoBrokersAvailable </code></pre> <p>I've got kafka_brokers_sasl, sasl_plain_username, and sasl_plain_password from messagehub service credentials object. I'm using kafka-python 1.3.1, which seems supporting SASL authentication mechanism. Any idea of what am I doing wrong? Thanks.</p>
1
2016-09-09T12:35:23Z
39,415,438
<p>Message Hub requires that clients connect using a TLS 1.2 connection. This means specifying a <code>security_protocol</code> parameter to <code>KafkaProducer</code> and also a <code>ssl.SSLContext</code> via the <code>ssl_context</code> parameter - as it appears that the Python Kafka client creates a <code>SSLv23</code> context by default.</p> <p>Here are the changes required to connect:</p> <pre><code>import ssl from kafka import KafkaProducer from kafka.errors import KafkaError kafka_brokers_sasl = [ "kafka01-prod01.messagehub.services.us-south.bluemix.net:9093", "kafka02-prod01.messagehub.services.us-south.bluemix.net:9093", "kafka03-prod01.messagehub.services.us-south.bluemix.net:9093", "kafka04-prod01.messagehub.services.us-south.bluemix.net:9093", "kafka05-prod01.messagehub.services.us-south.bluemix.net:9093" ] sasl_plain_username = "xxxxxxxxxxxxxxx" sasl_plain_password = "xxxxxxxxxxxxxxxxxxxxxxxxx" sasl_mechanism = 'PLAIN' # &lt;-- changed from 'SASL_PLAINTEXT' security_protocol = 'SASL_SSL' # Create a new context using system defaults, disable all but TLS1.2 context = ssl.create_default_context() context.options &amp;= ssl.OP_NO_TLSv1 context.options &amp;= ssl.OP_NO_TLSv1_1 producer = KafkaProducer(bootstrap_servers = kafka_brokers_sasl, sasl_plain_username = sasl_plain_username, sasl_plain_password = sasl_plain_password, security_protocol = security_protocol, ssl_context = context, sasl_mechanism = sasl_mechanism) </code></pre>
2
2016-09-09T15:54:12Z
[ "python", "apache-kafka", "ibm-bluemix", "message-hub" ]
i want to scrape data using python script
39,411,790
<p>I have written python script to scrape data from <a href="http://www.cricbuzz.com/cricket-stats/icc-rankings/batsmen-rankings" rel="nofollow">http://www.cricbuzz.com/cricket-stats/icc-rankings/batsmen-rankings</a> It is a list of 100 players and I successfully scraped this data. The problem is, when i run script instead of scraping data just one time it scraped the same data 3 times.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="cb-col cb-col-100 cb-font-14 cb-lst-itm text-center"&gt; &lt;div class="cb-col cb-col-16 cb-rank-tbl cb-font-16"&gt;1&lt;/div&gt; &lt;div class="cb-col cb-col-50 cb-lst-itm-sm text-left"&gt; &lt;div class="cb-col cb-col-33"&gt; &lt;div class="cb-col cb-col-50"&gt; &lt;span class=" cb-ico" style="position:absolute;"&gt;&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;– &lt;/div&gt; &lt;div class="cb-col cb-col-50"&gt; &lt;img src="http://i.cricketcb.com/i/stats/fw/50x50/img/faceImages/2250.jpg" class="img-responsive cb-rank-plyr-img"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="cb-col cb-col-67 cb-rank-plyr"&gt; &lt;a class="text-hvr-underline text-bold cb-font-16" href="/profiles/2250/steven-smith" title="Steven Smith's Profile"&gt;Steven Smith&lt;/a&gt; &lt;div class="cb-font-12 text-gray"&gt;AUSTRALIA&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="cb-col cb-col-17 cb-rank-tbl"&gt;906&lt;/div&gt; &lt;div class="cb-col cb-col-17 cb-rank-tbl"&gt;1&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>And here is python script which i write scrap each player data.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>import sys,requests,csv,io from bs4 import BeautifulSoup from urllib.parse import urljoin url = "http://www.cricbuzz.com/cricket-stats/icc-rankings/batsmen-rankings" r = requests.get(url) r.content soup = BeautifulSoup(r.content, "html.parser") maindiv = soup.find_all("div", {"class": "text-center"}) for div in maindiv: print(div.text)</code></pre> </div> </div> </p> <p>but instead of scraping the data once, it scrapes the same data 3 times.</p> <p>Where can I make changes to get data just one time?</p>
1
2016-09-09T12:37:49Z
39,412,107
<p>Select the table and look for the divs in that:</p> <pre><code>maindiv = soup.select("#batsmen-tests div.text-center") for div in maindiv: print(div.text) </code></pre> <p>Your original output and that above gets all the text from the divs as one line which is not really useful, if you just want the player names:</p> <pre><code>anchors = soup.select("#batsmen-tests div.cb-rank-plyr a") for a in anchors: print(a.text) </code></pre> <p>A quick and easy way to get the data in a nice csv format is to just get text from each child:</p> <pre><code>maindiv = soup.select("#batsmen-tests div.text-center") for d in maindiv[1:]: row_data = u",".join(s.strip() for s in filter(None, (t.find(text=True, recursive=False) for t in d.find_all()))) if row_data: print(row_data) </code></pre> <p>Now you get output like:</p> <pre><code># rank, up/down, name, country, rating, best rank 1,–,Steven Smith,AUSTRALIA,906,1 2,–,Joe Root,ENGLAND,878,1 3,–,Kane Williamson,NEW ZEALAND,876,1 4,–,Hashim Amla,SOUTH AFRICA,847,1 5,–,Younis Khan,PAKISTAN,845,1 6,–,Adam Voges,AUSTRALIA,802,5 7,–,AB de Villiers,SOUTH AFRICA,802,1 8,–,Ajinkya Rahane,INDIA,785,8 9,2,David Warner,AUSTRALIA,772,3 10,–,Alastair Cook,ENGLAND,770,2 11,1,Misbah-ul-Haq,PAKISTAN,764,6 </code></pre> <p>As opposed to:</p> <pre><code>PositionPlayerRatingBest Rank Player 1    –Steven SmithAUSTRALIA9061 2    –Joe RootENGLAND8781 3    –Kane WilliamsonNEW ZEALAND8761 4    –Hashim AmlaSOUTH AFRICA8471 5    –Younis KhanPAKISTAN8451 6    –Adam VogesAUSTRALIA8025 </code></pre>
1
2016-09-09T12:54:56Z
[ "python", "html5", "python-3.x", "beautifulsoup", "python-3.4" ]
i want to scrape data using python script
39,411,790
<p>I have written python script to scrape data from <a href="http://www.cricbuzz.com/cricket-stats/icc-rankings/batsmen-rankings" rel="nofollow">http://www.cricbuzz.com/cricket-stats/icc-rankings/batsmen-rankings</a> It is a list of 100 players and I successfully scraped this data. The problem is, when i run script instead of scraping data just one time it scraped the same data 3 times.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="cb-col cb-col-100 cb-font-14 cb-lst-itm text-center"&gt; &lt;div class="cb-col cb-col-16 cb-rank-tbl cb-font-16"&gt;1&lt;/div&gt; &lt;div class="cb-col cb-col-50 cb-lst-itm-sm text-left"&gt; &lt;div class="cb-col cb-col-33"&gt; &lt;div class="cb-col cb-col-50"&gt; &lt;span class=" cb-ico" style="position:absolute;"&gt;&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;– &lt;/div&gt; &lt;div class="cb-col cb-col-50"&gt; &lt;img src="http://i.cricketcb.com/i/stats/fw/50x50/img/faceImages/2250.jpg" class="img-responsive cb-rank-plyr-img"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="cb-col cb-col-67 cb-rank-plyr"&gt; &lt;a class="text-hvr-underline text-bold cb-font-16" href="/profiles/2250/steven-smith" title="Steven Smith's Profile"&gt;Steven Smith&lt;/a&gt; &lt;div class="cb-font-12 text-gray"&gt;AUSTRALIA&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="cb-col cb-col-17 cb-rank-tbl"&gt;906&lt;/div&gt; &lt;div class="cb-col cb-col-17 cb-rank-tbl"&gt;1&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>And here is python script which i write scrap each player data.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>import sys,requests,csv,io from bs4 import BeautifulSoup from urllib.parse import urljoin url = "http://www.cricbuzz.com/cricket-stats/icc-rankings/batsmen-rankings" r = requests.get(url) r.content soup = BeautifulSoup(r.content, "html.parser") maindiv = soup.find_all("div", {"class": "text-center"}) for div in maindiv: print(div.text)</code></pre> </div> </div> </p> <p>but instead of scraping the data once, it scrapes the same data 3 times.</p> <p>Where can I make changes to get data just one time?</p>
1
2016-09-09T12:37:49Z
39,412,444
<p>The reason you get output three times is because the website has three categories you have to select it and then accordingly you can use it.</p> <p>Simplest way of doing it with your code would be to add just one line</p> <pre><code>import sys,requests,csv,io from bs4 import BeautifulSoup url = "http://www.cricbuzz.com/cricket-stats/icc-rankings/batsmen- rankings" r = requests.get(url) r.content soup = BeautifulSoup(r.content, "html.parser") specific_div = soup.find_all("div", {"id": "batsmen-tests"}) maindiv = specific_div[0].find_all("div", {"class": "text-center"}) for div in maindiv: print(div.text) </code></pre> <p>This will give similar reuslts with just test batsmen, for other output just change the "id" in specific_div line.</p>
-1
2016-09-09T13:15:04Z
[ "python", "html5", "python-3.x", "beautifulsoup", "python-3.4" ]
I am not able to run jupyter notebook after installation in ubuntu
39,411,899
<p>I installed jupyter on my ubuntu system via the following command :</p> <pre><code>sudo pip install jupyter </code></pre> <p>After executing it I could run <code>jupyter notebook</code> successfully. But unfortunately while trying to upgrade it for python3, I accidentally deleted all <code>jupyter</code> links from my <code>/usr/local/bin</code>. Now <code>jupyter notebook</code> is not running. I have tried un-installing and re-installing also. I have no clue about what should I do now.</p>
1
2016-09-09T12:43:29Z
39,411,979
<p>Don't install python packages with sudo unless you really know what you're doing.</p> <p>Try this instead:</p> <pre><code>$ virtualenv myvenv $ cd myvenv $ source bin/activate $ pip install jupyter $ jupyter notebook </code></pre> <p>To run it the next time (in a new shell session i.e), simply do:</p> <pre><code>$ cd myvenv $ source bin/activate $ jupyter notebook </code></pre>
1
2016-09-09T12:47:50Z
[ "python", "ubuntu", "jupyter" ]
How to implement Weighted Binary CrossEntropy on theano?
39,412,051
<p><strong>How to implement Weighted Binary CrossEntropy on theano?</strong></p> <p>My Convolutional neural network only predict 0 ~~ 1 (sigmoid).</p> <p><strong>I want to penalize my predictions in this way :</strong></p> <p><a href="http://i.stack.imgur.com/m3rAL.png"><img src="http://i.stack.imgur.com/m3rAL.png" alt="Cost-Table"></a></p> <p>Basically, i want to penalize MORE when the model predicts 0 but the truth was 1.</p> <p><strong>Question :</strong> How can I create this <em>Weighted Binary CrossEntropy</em> function using theano and lasagne ?</p> <p><strong>I tried this below</strong> </p> <pre><code>prediction = lasagne.layers.get_output(model) import theano.tensor as T def weighted_crossentropy(predictions, targets): # Copy the tensor tgt = targets.copy("tgt") # Make it a vector # tgt = tgt.flatten() # tgt = tgt.reshape(3000) # tgt = tgt.dimshuffle(1,0) newshape = (T.shape(tgt)[0]) tgt = T.reshape(tgt, newshape) #Process it so [index] &lt; 0.5 = 0 , and [index] &gt;= 0.5 = 1 # Make it an integer. tgt = T.cast(tgt, 'int32') weights_per_label = theano.shared(lasagne.utils.floatX([0.2, 0.4])) weights = weights_per_label[tgt] # returns a targets-shaped weight matrix loss = lasagne.objectives.aggregate(T.nnet.binary_crossentropy(predictions, tgt), weights=weights) return loss loss_or_grads = weighted_crossentropy(prediction, self.target_var) </code></pre> <p><strong>But I get this error below :</strong></p> <p><strong>TypeError: New shape in reshape must be a vector or a list/tuple of scalar. Got Subtensor{int64}.0 after conversion to a vector.</strong></p> <hr> <p>Reference : <a href="https://github.com/fchollet/keras/issues/2115">https://github.com/fchollet/keras/issues/2115</a></p> <p>Reference : <a href="https://groups.google.com/forum/#!topic/theano-users/R_Q4uG9BXp8">https://groups.google.com/forum/#!topic/theano-users/R_Q4uG9BXp8</a></p>
6
2016-09-09T12:51:50Z
39,536,684
<p>To address your syntax error:</p> <p>Change</p> <pre><code>newshape = (T.shape(tgt)[0]) tgt = T.reshape(tgt, newshape) </code></pre> <p>to</p> <pre><code>newshape = (T.shape(tgt)[0],) tgt = T.reshape(tgt, newshape) </code></pre> <p><code>T.reshape</code> expects a tuple of axes, you didn't provide this, hence the error.</p> <p>Before penalizing false-negatives (prediction 0, truth 1) make sure that this prediction error is not based on the statistics of your training data, as <a href="http://stackoverflow.com/questions/39412051/how-to-implement-weighted-binary-crossentropy-on-theano#comment66149857_39412051">@uyaseen suggested</a>.</p>
0
2016-09-16T17:00:15Z
[ "python", "theano", "keras", "lasagne", "cross-entropy" ]
Create Datetime from year and month hidden in multi-index
39,412,123
<p>I have a dataframe where year and month are hidden in the <code>multi-index</code>. I want to create a datetime index as additional column (or separate series with same index).</p> <pre><code> price mean mom_2 foo bar year month 997182819645 11 2010 1 1.1900 3.000000 2 2.2625 4.001769 </code></pre> <p>I thought of adding the two levels of indices together as strings, and then read in that sequence into <code>pd.to_datetime()</code>. However, adding the two indices, I faced problems. I can add them up as integers just fine, but if I want to add them up as strings, I face some error:</p> <pre><code>In[193]: df.index.get_level_values('year').values.astype(str) Out[193]: array(['2010', '2010', '2010', ..., '2014', '2014', '2014'], dtype='&lt;U21') In[194]: df.index.get_level_values('month').values.astype(str) Out[194]: array(['1', '2', '3', ..., '10', '11', '12'], dtype='&lt;U21') In[195]: df.index.get_level_values('month').values.astype(str) + df.index.get_level_values('year').values.astype(str) TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('&lt;U21') dtype('&lt;U21') dtype('&lt;U21') </code></pre> <p>How can I add create the datetime index here?</p>
2
2016-09-09T12:55:46Z
39,412,380
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a>, but first need multiple <code>year</code> and <code>month</code> values:</p> <pre><code>y = df.index.get_level_values('year') m = df.index.get_level_values('month') df['Date'] = pd.to_datetime(y * 10000 + m * 100 + 1, format="%Y%m%d") print (df) price Date foo bar foo bar year month 997182819645 11 2010 1 1.1900 3.000000 2010-01-01 2 2.2625 4.001769 2010-02-01 </code></pre> <p>If need then append column to <code>index</code>:</p> <pre><code>df['Date'] = pd.to_datetime(y * 10000 + m * 100 + 1, format="%Y%m%d") df.set_index('Date', append=True, inplace=True) print (df) price foo bar foo bar year month Date 997182819645 11 2010 1 2010-01-01 1.1900 3.000000 2 2010-02-01 2.2625 4.001769 </code></pre> <hr> <p>Another solution with creating new <code>DataFrame</code>, but need last <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#whatsnew-0181-enhancements-assembling" rel="nofollow">0.18.1 version</a>:</p> <pre><code>y = df.index.get_level_values('year') m = df.index.get_level_values('month') d = pd.Index(len(df.index) * [1], name='day') df1 = pd.DataFrame({'year':y, 'month':m, 'day':d}, index=df.index) df['Date'] = pd.to_datetime(df1) print (df) price Date foo bar foo bar year month 997182819645 11 2010 1 1.1900 3.000000 2010-01-01 2 2.2625 4.001769 2010-02-01 </code></pre>
2
2016-09-09T13:10:52Z
[ "python", "datetime", "pandas", "multi-index", "datetimeindex" ]
Is There A Built-in Way to Filter with Given Function in Django?
39,412,135
<p>I especially wonder if I can use map, filter and reduce functions with Django model instances. If I cannot, is there a built-in way to pass a function to filter querying in Django?</p> <p>Let me demonstrate my real problem for better understanding. I use PostgreSQL to use ArrayField and I have similiar model as below:</p> <pre><code>class Route(models.Model): stops_forwards = ArrayField( ArrayField( models.PositiveIntegerField(), size=2 ), default=[], verbose_name="Stops Forwards (Ordered)" ) stops_backwards = ArrayField( ArrayField( models.PositiveIntegerField(), size=2 ), default=[], verbose_name="Stops Backwards (Ordered)" ) </code></pre> <p>As you can see above, I have embedded ArrayFields inside <code>stops_forwards</code> and <code>stops_backwards</code>. I use embedded ones so as to keep it in order. An example data is shown as below:</p> <pre><code>[ [1, 35], [2, 40], [3, 180], [4, 285] # ... and it goes ] </code></pre> <p>What I want to do is to check if a particular stop id (like <code>285</code>) is in embedded ArrayField. Assuming that I have a function called <code>has_route_stop</code> that I do not know how it works but I call it as below:</p> <pre><code>filter(lambda: has_route_stop(285), instances) </code></pre> <p>Or, is there a built-in way in Django API to do this?</p> <hr> <h1>Environment</h1> <ul> <li>Python 3.5.1</li> <li>Django 1.9.9</li> <li>PostgreSQL 9.5.4</li> <li>psycopg2 2.6.2</li> </ul>
3
2016-09-09T12:56:08Z
39,412,401
<p>Django's Postgres integration allows you to query in embedded arrays using the <code>__contains</code> operator. So you can do:</p> <pre><code>Route.objects.filter(stops_forwards__contains=[285]) </code></pre> <p>See <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/postgres/fields/#querying-arrayfield" rel="nofollow">the ArrayField documentation</a>.</p>
3
2016-09-09T13:12:14Z
[ "python", "django", "postgresql", "filter" ]
Filter Using Checkboxes w. Jquery
39,412,344
<p>I am trying to create checkbox filters that show or hide boxes on my pagebased on their id. I'm very new to jquery, but have been playing around with this for a while and cannot seem to get the boxes to hide / show. Please see my code below. Thanks!</p> <p>Sport model</p> <pre><code>class Sport(models.Model): name = models.CharField(max_length=128) </code></pre> <p>Snippet of HTML to filter</p> <pre><code>{% for game in game_list %} {% if game.sport = sport %} &lt;div class="col-xs-12 col-sm-12 col-lg-12"&gt; &lt;section id="{{ sport.name }}" class="box pick-game"&gt; &lt;div class="box box-content"&gt; &lt;div class="game-bet-header"&gt; &lt;div class="row"&gt; &lt;div class="col-md-3"&gt; &lt;h4 class="game-date"&gt; {{ game.time|time }} - {{ game.time|date:"M-d" }}&lt;/h4&gt; &lt;/div&gt; &lt;div class="col-md-6"&gt; &lt;h4 class="game-title"&gt;{{ game.team1 }} vs {{ game.team2 }} &lt;/h4&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>HTML Checkboxes to Use as Filters</p> <pre><code>&lt;div class="sport-sidebar"&gt; &lt;section class="sports-box"&gt; {% for sport in sports %} &lt;div id="sport-filter" class="sport-name"&gt; &lt;label for="filter-{{ sport.name }}"&gt;&lt;input type="checkbox" class="sport" value="{{ sport.name }}" id="filter-{{ sport.name }}"&gt;{{ sport.name }}&lt;/label&gt; &lt;/div&gt; {% endfor %} &lt;/section&gt; &lt;/div&gt; </code></pre> <p>Jquery</p> <pre><code>$('#sport-filter input:checkbox').click(function() { $('#sport-filter input:checkbox:checked').each(function() { $("#" +$(this).val()).show() }); }); </code></pre> <p>Please help provide suggestions to solve this problem! Thanks so much </p> <p><strong>Updated Javascript on 9/20, but still not working</strong></p> <p>Please see below for updated javascript. Initializing with .hide() is not working, but if I manually set the id of each sport to display: none in the CSS it does hide. This is leading me to believe that either .show and .hide are not working, or they are not correctly capturing my class. I also added a class to my checkbox in the javascript to distinguish it from the others.</p> <pre><code>$("#mlb-pick").hide(); $("#nfl-pick").hide(); $(".sport-sidebar input[type=checkbox]").on('click', function() { var thisval = $(this).val(); if ($(this).prop('checked')){ $('#' + thisval+"-pick").show(); } else{ $('#' + thisval).hide(); } }); </code></pre>
0
2016-09-09T13:09:03Z
39,412,506
<p>Here's an example of how .each works in jquery</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function toggleChks() { $("input[type=checkbox]").each(function(index, item) { console.log(index, item); if ($(item).prop('checked')) $(item).prop('checked', false); else $(item).prop('checked', true); }) }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;button onclick="toggleChks()"&gt;toggle&lt;/button&gt; &lt;input type="checkbox" checked value="1"&gt; &lt;input type="checkbox" checked value="2"&gt; &lt;input type="checkbox" checked value="3"&gt; &lt;input type="checkbox" value="4"&gt; &lt;input type="checkbox" value="5"&gt; &lt;input type="checkbox" value="6"&gt;</code></pre> </div> </div> </p>
0
2016-09-09T13:18:35Z
[ "javascript", "jquery", "python", "django", "filter" ]
Filter Using Checkboxes w. Jquery
39,412,344
<p>I am trying to create checkbox filters that show or hide boxes on my pagebased on their id. I'm very new to jquery, but have been playing around with this for a while and cannot seem to get the boxes to hide / show. Please see my code below. Thanks!</p> <p>Sport model</p> <pre><code>class Sport(models.Model): name = models.CharField(max_length=128) </code></pre> <p>Snippet of HTML to filter</p> <pre><code>{% for game in game_list %} {% if game.sport = sport %} &lt;div class="col-xs-12 col-sm-12 col-lg-12"&gt; &lt;section id="{{ sport.name }}" class="box pick-game"&gt; &lt;div class="box box-content"&gt; &lt;div class="game-bet-header"&gt; &lt;div class="row"&gt; &lt;div class="col-md-3"&gt; &lt;h4 class="game-date"&gt; {{ game.time|time }} - {{ game.time|date:"M-d" }}&lt;/h4&gt; &lt;/div&gt; &lt;div class="col-md-6"&gt; &lt;h4 class="game-title"&gt;{{ game.team1 }} vs {{ game.team2 }} &lt;/h4&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>HTML Checkboxes to Use as Filters</p> <pre><code>&lt;div class="sport-sidebar"&gt; &lt;section class="sports-box"&gt; {% for sport in sports %} &lt;div id="sport-filter" class="sport-name"&gt; &lt;label for="filter-{{ sport.name }}"&gt;&lt;input type="checkbox" class="sport" value="{{ sport.name }}" id="filter-{{ sport.name }}"&gt;{{ sport.name }}&lt;/label&gt; &lt;/div&gt; {% endfor %} &lt;/section&gt; &lt;/div&gt; </code></pre> <p>Jquery</p> <pre><code>$('#sport-filter input:checkbox').click(function() { $('#sport-filter input:checkbox:checked').each(function() { $("#" +$(this).val()).show() }); }); </code></pre> <p>Please help provide suggestions to solve this problem! Thanks so much </p> <p><strong>Updated Javascript on 9/20, but still not working</strong></p> <p>Please see below for updated javascript. Initializing with .hide() is not working, but if I manually set the id of each sport to display: none in the CSS it does hide. This is leading me to believe that either .show and .hide are not working, or they are not correctly capturing my class. I also added a class to my checkbox in the javascript to distinguish it from the others.</p> <pre><code>$("#mlb-pick").hide(); $("#nfl-pick").hide(); $(".sport-sidebar input[type=checkbox]").on('click', function() { var thisval = $(this).val(); if ($(this).prop('checked')){ $('#' + thisval+"-pick").show(); } else{ $('#' + thisval).hide(); } }); </code></pre>
0
2016-09-09T13:09:03Z
39,566,965
<p>Here's a working one with your example, you've had to put the "id" for the sections, or in other case, change the jquery selector for it's class.</p> <p>Also you have to set the click action for the input checkbox elements.</p> <p>Hope this helps.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>//initialize state $("#mlb").hide(); $("#nfl").hide(); $("input[type=checkbox]").on('click', function() { var thisval = $(this).val(); if ($(this).prop('checked')){ $('#' + thisval).show(); } else{ $('#' + thisval).hide(); } });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div id="sport-filter" class="mlb"&gt; &lt;label for="mlb-filter"&gt;&lt;input type="checkbox" value="mlb" id="mlb-filter"&gt;mlb&lt;/label&gt; &lt;/div&gt; &lt;div id="sport-filter" class="nfl"&gt; &lt;label for="nfl-filter"&gt;&lt;input type="checkbox" value="nfl" id="nfl-filter"&gt;nfl&lt;/label&gt; &lt;/div&gt; &lt;section class=mlb id="mlb"&gt; &lt;p&gt; Hey &lt;/p&gt; &lt;/section&gt; &lt;section class=nfl id="nfl"&gt; &lt;p&gt; Hey 2 &lt;/p&gt; &lt;/section&gt;</code></pre> </div> </div> </p>
0
2016-09-19T06:50:04Z
[ "javascript", "jquery", "python", "django", "filter" ]
Why am I receiving an error when trying to compare two lists?
39,412,387
<p>I am trying to compare two lists on line <code>#12</code> and return matches found. </p> <p>The lists contain one user selected number (<code>un</code>) and one of which have been randomly generated (<code>rn</code>).</p> <p>For example, <code>[['1', '5', '3', '7']]</code> and <code>[['9', '6', '3', '2']]</code> would return <code>[3]</code>.</p> <p>I am fairly new to python and was using the solution found <a href="http://stackoverflow.com/questions/1388818/how-can-i-compare-two-lists-in-python-and-return-matches">HERE</a>, but am yet to have success with my code.</p> <pre><code>import random import re rn = [] un = [] Numbers = range(1000,9999) RandomNumber = random.choice(Numbers) RandomNumber = str(RandomNumber) def check(): x = set(rn) &amp; set(un) #12 print (x) def numsys(): b = list(RandomNumber) rn.append(b) print(rn) print(un) check() def numval(): while True: UserNum = (input("Please enter a 4 digit number: ")) if re.match("^[0-9]{4,4}$", UserNum): a = list(UserNum) un.append(a) numsys() break numval() </code></pre>
1
2016-09-09T13:11:29Z
39,412,511
<p>When you cast a list to a string back and forth, the result wouldn't be the original string. It would be a list containing the characters of the representation of the original string. </p> <pre><code>&gt;&gt;&gt; a = [1, 2, 3] &gt;&gt;&gt; b = str(a) &gt;&gt;&gt; c = list(b) &gt;&gt;&gt; c ['[', '1', ',', ' ', '2', ',', ' ', '3', ']'] </code></pre> <p>Don't do such castings, and if you have to, use <code>','.join(map(str, a))</code> to cast to string, and <code>list(map(int, b.split(',')))</code> to cast to list back.</p>
1
2016-09-09T13:18:54Z
[ "python", "list", "python-3.x", "string-comparison", "list-comparison" ]
Why am I receiving an error when trying to compare two lists?
39,412,387
<p>I am trying to compare two lists on line <code>#12</code> and return matches found. </p> <p>The lists contain one user selected number (<code>un</code>) and one of which have been randomly generated (<code>rn</code>).</p> <p>For example, <code>[['1', '5', '3', '7']]</code> and <code>[['9', '6', '3', '2']]</code> would return <code>[3]</code>.</p> <p>I am fairly new to python and was using the solution found <a href="http://stackoverflow.com/questions/1388818/how-can-i-compare-two-lists-in-python-and-return-matches">HERE</a>, but am yet to have success with my code.</p> <pre><code>import random import re rn = [] un = [] Numbers = range(1000,9999) RandomNumber = random.choice(Numbers) RandomNumber = str(RandomNumber) def check(): x = set(rn) &amp; set(un) #12 print (x) def numsys(): b = list(RandomNumber) rn.append(b) print(rn) print(un) check() def numval(): while True: UserNum = (input("Please enter a 4 digit number: ")) if re.match("^[0-9]{4,4}$", UserNum): a = list(UserNum) un.append(a) numsys() break numval() </code></pre>
1
2016-09-09T13:11:29Z
39,412,932
<p>Rather than using lists to pass the data around, use function parameters.</p> <pre><code>import random import re def check(random_number, user_number): print('random_number {}, user_number {}'.format(random_number, user_number)) x = set(random_number).intersection(user_number) print(x) def numval(): random_num = str(random.choice(range(1000, 9999))) while True: user_num = (input("Please enter a 4 digit number: ")) if re.match("^[0-9]{4,4}$", user_num): check(random_num, user_num) break numval() </code></pre> <p>This avoids accessing global variables within the functions and is generally more readable. Doing this I was able to remove function <code>numsys()</code> because all it was doing was to unnecessarily fiddle with the global variables in order to make their values accessible in function <code>check()</code>.</p> <p>One simplification was to keep the random and user numbers as strings. <code>set()</code> can be called on a string without requiring that it be first converted to a list. And only one of the strings needs to be explicitly converted to a set if you use <code>set.intersection()</code> instead of the <code>&amp;</code> operator.</p> <p>I also took the liberty of renaming the variables to conform with the <a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP8 style guide</a>.</p>
1
2016-09-09T13:40:44Z
[ "python", "list", "python-3.x", "string-comparison", "list-comparison" ]
ImportError: No module named views
39,412,445
<p>Im writing a web app in flask that displays bus stops pulled from an api. </p> <p>i have a form on index.html where a user can input a stop number, that number gets picked up in views.py where the function also runs a task through celery to fetch the api data:</p> <pre><code>from flask import render_template, request from app import app @app.route('/') def index(): return render_template('index.html') @app.route('/stopno', methods=['POST']) def stopno(): stopid = request.form['input'] from app.tasks import apidata apidata.delay() return render_template('action.html') </code></pre> <p>here is my tasks.py:</p> <pre><code>from celery import Celery import json import requests import time ac = Celery('tasks', broker='amqp://localhost') @ac.task(name='tasks.apidata') def apidata(): from views import stopno api = '*apiurl*:' + str(stopid) saveinfo = 'static/stop' + str(stopid)+ '.json' r = requests.get(api) jsondata = json.loads(r.text) with open(saveinfo, 'w') as f: json.dump(jsondata, f) </code></pre> <p>I am importing stopno from views into tasks so i can search the api for the specified stop, currently when a user inputs a stop number the action.html loads fine and displays the stop number the user inputs but no new file or data is created for the stop number and celery throws an error saying</p> <pre><code>ImportError: No module named views </code></pre> <p>structure of my project is</p> <pre><code>|____run.py |____app | |______init__.py | |____views.py | |____tasks.py | |____static | | |____json | |____templates | | |____action.html | | |____index.html </code></pre>
0
2016-09-09T13:15:04Z
39,412,612
<pre><code>from app.views import stopno </code></pre> <p>??</p>
0
2016-09-09T13:24:04Z
[ "python", "module", "celery", "python-import", "celery-task" ]
ImportError: No module named views
39,412,445
<p>Im writing a web app in flask that displays bus stops pulled from an api. </p> <p>i have a form on index.html where a user can input a stop number, that number gets picked up in views.py where the function also runs a task through celery to fetch the api data:</p> <pre><code>from flask import render_template, request from app import app @app.route('/') def index(): return render_template('index.html') @app.route('/stopno', methods=['POST']) def stopno(): stopid = request.form['input'] from app.tasks import apidata apidata.delay() return render_template('action.html') </code></pre> <p>here is my tasks.py:</p> <pre><code>from celery import Celery import json import requests import time ac = Celery('tasks', broker='amqp://localhost') @ac.task(name='tasks.apidata') def apidata(): from views import stopno api = '*apiurl*:' + str(stopid) saveinfo = 'static/stop' + str(stopid)+ '.json' r = requests.get(api) jsondata = json.loads(r.text) with open(saveinfo, 'w') as f: json.dump(jsondata, f) </code></pre> <p>I am importing stopno from views into tasks so i can search the api for the specified stop, currently when a user inputs a stop number the action.html loads fine and displays the stop number the user inputs but no new file or data is created for the stop number and celery throws an error saying</p> <pre><code>ImportError: No module named views </code></pre> <p>structure of my project is</p> <pre><code>|____run.py |____app | |______init__.py | |____views.py | |____tasks.py | |____static | | |____json | |____templates | | |____action.html | | |____index.html </code></pre>
0
2016-09-09T13:15:04Z
39,415,793
<p>You are trying to do a relative import but you are not making it <em>explicitly</em> relative, which may or may not work, and which can cause unexpected errors. You should make your import explicitly relative with:</p> <pre><code>from .views import stopno </code></pre> <p>This way you don't have to worry about reproducing the entire path to the module.</p>
1
2016-09-09T16:17:09Z
[ "python", "module", "celery", "python-import", "celery-task" ]
python create html table from dict
39,412,679
<p>I´m just starting learning python and therefore like to create a html table based on filenames. Imaging following files</p> <pre><code>apple.good.2.svg apple.good.1.svg banana.1.ugly.svg banana.bad.2.svg kiwi.good.svg </code></pre> <p>The kind of object is always the first part (before the first dot) the quality property is somewhere in the name.</p> <p>My resulting table should look like this:</p> <pre><code>Object Name | good | bad | ugly ------------------------------------------------------------------------- apple | apple.good.1.svg | | apple.good.2.svg | ------------------------------------------------------------------------- banana | | banana.bad.2.svg | banana.1.ugly.svg ------------------------------------------------------------------------- kiwi | kiwi.good.svg ------------------------------------------------------------------------- </code></pre> <p>This is what I did so far</p> <pre><code>#!/usr/bin/python import glob from collections import defaultdict fileNames = defaultdict(list) # fill sorted list of tables based on svg filenames svgFiles = sorted(glob.glob('*.svg')) for s in svgFiles: fileNames[s.split('.', 1)[0]].append(s) # write to html html = '&lt;html&gt;&lt;table border="1"&gt;&lt;tr&gt;&lt;th&gt;A&lt;/th&gt;&lt;th&gt;' + '&lt;/th&gt;&lt;th&gt;'.join(dict(fileNames).keys()) + '&lt;/th&gt;&lt;/tr&gt;' for row in zip(*dict(fileNames).values()): html += '&lt;tr&gt;&lt;td&gt;Object Name&lt;/td&gt;&lt;td&gt;' + '&lt;/td&gt;&lt;td&gt;'.join(row) + '&lt;/td&gt;&lt;/tr&gt;' html += '&lt;/table&gt;&lt;/html&gt;' file_ = open('result.html', 'w') file_.write(html) file_.close() </code></pre> <p>I managed to read the files sorted in a dict:</p> <pre><code>{'kiwi': ['kiwi.good.svg'], 'apple': ['apple.good.2.svg', 'apple.good.1.svg'], 'banana': ['banana.1.ugly.svg', 'banana.bad.2.svg']} </code></pre> <p>But fail by generating the html table. </p> <p><a href="http://i.stack.imgur.com/E79th.png" rel="nofollow"><img src="http://i.stack.imgur.com/E79th.png" alt="enter image description here"></a></p> <p>How can I build the html table as shown above? Where Objects are written to the first first column of a row and the filename in columns depending on their quality property?</p>
2
2016-09-09T13:27:34Z
39,412,965
<p>You have to iterate all combinations of fruits from your dictionaries and states, and then create one line (instead of one column) for each fruit. Then just iterate all the files matching that fruit and filter those that contain the current state and join those in one cell.</p> <pre><code>d = {'kiwi': ['kiwi.good.svg'], 'apple': ['apple.good.2.svg', 'apple.good.1.svg'], 'banana': ['banana.1.ugly.svg', 'banana.bad.2.svg']} html = """&lt;html&gt;&lt;table border="1"&gt; &lt;tr&gt;&lt;th&gt;Object&lt;/th&gt;&lt;th&gt;Good&lt;/th&gt;&lt;th&gt;Bad&lt;/th&gt;&lt;th&gt;Ugly&lt;/th&gt;&lt;/tr&gt;""" for fruit in d: html += "&lt;tr&gt;&lt;td&gt;{}&lt;/td&gt;".format(fruit) for state in "good", "bad", "ugly": html += "&lt;td&gt;{}&lt;/td&gt;".format('&lt;br&gt;'.join(f for f in d[fruit] if ".{}.".format(state) in f)) html += "&lt;/tr&gt;" html += "&lt;/table&gt;&lt;/html&gt;" </code></pre> <p>Result:</p> <p><a href="http://i.stack.imgur.com/cLxq9.png" rel="nofollow"><img src="http://i.stack.imgur.com/cLxq9.png" alt="enter image description here"></a></p> <hr> <p>Update: If you have state expressions that are part of other states, like <code>bad</code> and <code>medium_bad</code>, then just using <code>in</code> won't work. Instead, you can use a <a href="https://docs.python.org/3/library/re.html#re.search" rel="nofollow">regular expression</a> to get the best match. </p> <pre><code>&gt;&gt;&gt; fruit = "banana_bad.svg", "banana_medium_bad.svg" &gt;&gt;&gt; [re.search(r"[._](good|bad|medium_bad|ugly)[._]", f).group(1) for f in fruit] ['bad', 'medium_bad'] </code></pre> <p>You could use this code then:</p> <pre><code>d = {'kiwi': ['kiwi.good.svg', 'kiwi_medium_bad.svg'], 'apple': ['apple.good.2.svg', 'apple.good.1.svg'], 'banana': ['banana.1.ugly.svg', 'banana.bad.2.svg']} states = ['good', 'bad', 'medium_bad', 'ugly'] html = """&lt;html&gt;&lt;table border="1"&gt; &lt;tr&gt;&lt;th&gt;Object&lt;/th&gt;&lt;th&gt;{}&lt;/th&gt;&lt;/tr&gt;""".format("&lt;/th&gt;&lt;th&gt;".join(states)) for fruit in d: html += "&lt;tr&gt;&lt;td&gt;{}&lt;/td&gt;".format(fruit) by_state = {f: re.search(r"[._]({})[._]".format('|'.join(states)), f).group(1) for f in d[fruit]} for state in states: html += "&lt;td&gt;{}&lt;/td&gt;".format('&lt;br&gt;'.join(f for f in d[fruit] if by_state[f] == state)) html += "&lt;/tr&gt;" html += "&lt;/table&gt;&lt;/html&gt;" </code></pre> <p>Alternatively, you could also restructure your dictionary to have another "layer" of states, i.e. <code>{"kiwi": {"good": ["kiwi.goog.svg"]}, ...}</code></p> <hr> <p>If you want to wrap the filenames within image tags, you can put another <code>format</code> within the <code>join</code>:</p> <pre><code>html += "&lt;td&gt;{}&lt;/td&gt;".format('&lt;br&gt;'.join('&lt;img src="{}"&gt;'.format(f) for f in d[fruit] if by_state[f] == state)) </code></pre>
2
2016-09-09T13:42:34Z
[ "python" ]
How to pass a bytestring to PyGreSQL?
39,412,754
<p>I've got a PostgreSQL table with a column of type <code>bytea</code>. Porting that table from SQLite, I ran into an issue - I couldn't figure out how to pass raw binary data to an SQL query. The framework I use is PyGreSQL. I want to stick to the DB-API 2.0 interface to avoid a lot of conversion.<br> That interface, unlike the classic one (dollar-sign parameters) and SQLite (question-mark parameters), requires to specify the type (%-formatting like the old Python's).<br> The data I want to pass is a PNG file, binary-read using the <code>'rb'</code> flag in the <code>open()</code> method.<br> The query code looks like this:</p> <pre><code>db = pgdb.connect(args) c = db.cursor() c.execute('INSERT INTO tbl VALUES (%b)', (b'test_bytes',)) </code></pre> <p>This gives an error <code>unsupported format character 'b' (0x62) at index 54</code> and doesn't allow the formatting to happen. What could be done to solve this issue?</p>
0
2016-09-09T13:31:32Z
39,555,893
<p>Not really a solution, but a good-enough workaround. I decided to use <code>psycopg2</code> instead of <code>PyGreSQL</code> as it is more supported and common, so it's easier to find info about any common problems.<br> There, the solution would be to use <code>%s</code> for every type, which I find much more Pythonic (no need to think about types in a dynamically-typed language)</p> <p>So, my query would look like this:</p> <pre><code>c.execute('INSERT INTO tbl VALUES (%s)', (b'test_bytes',)) </code></pre>
0
2016-09-18T09:04:24Z
[ "python", "postgresql", "sqlite", "formatting" ]
passing file path to youtube-dl in python
39,412,810
<p>Im using python <code>subprocess.call()</code> to call <code>[youtube-dl.exe][1]</code> and passing parameters like so</p> <pre><code>downloadLocation = "-o " + "C:/Users/username/Documents/Youtube/%(title)s.%(ext)s" subprocess.call(["youtube-dl", "-f" "bestvideo[ext=mp4, height=1080]+bestaudio[ext=m4a]/best[ext=mp4, height=1080]/best", downloadLocation, url]) </code></pre> <p>But the result is(on python console): <code>[download] Destination: C#\Users\username\Documents\Youtube\myVideoFile.mp4</code></p> <p>And the files are getting downloaded in the current directory from where the python call is made.</p> <p>Example: <code>"C:\Users\username\PycharmProjects\pytest\ C#\Users\username\Documents\Youtube"</code></p> <p>It looks like to me it's unable to escape the ":" character in the file path.</p> <p>Please help </p>
1
2016-09-09T13:34:05Z
39,418,146
<p><strong>Update:</strong> Here's how i got it to work</p> <pre><code>subprocess.call(["youtube-dl", "-f" "bestvideo[ext=mp4, height=1080]+bestaudio[ext=m4a]/best[ext=mp4, height=1080]/best", "-o" "%s" %downloadLocation, "--ignore-errors", url]) </code></pre>
0
2016-09-09T18:59:17Z
[ "python", "python-3.x", "github", "subprocess", "youtube-dl" ]
pandas.read_html not support decimal comma
39,412,829
<p>I was reading an xlm file using <code>pandas.read_html</code> and works <strong>almost perfect</strong>, the problem is that the file has commas as decimal separators instead of dots (the default in <code>read_html</code>). </p> <p>I could easily replace the commas by dots in one file, but i have almost 200 files with that configuration. with <code>pandas.read_csv</code> you can define the decimal separator, but i don't know why in <code>pandas.read_html</code> you can only define the thousand separator. </p> <p>any guidance in this matter?, there is another way to automate the comma/dot replacement before it is open by pandas? thanks in advance! </p>
5
2016-09-09T13:35:16Z
39,413,150
<p>Looking at the source code of <a href="https://github.com/pydata/pandas/blob/master/pandas/io/html.py" rel="nofollow">read_html</a> </p> <pre><code>def read_html(io, match='.+', flavor=None, header=None, index_col=None, skiprows=None, attrs=None, parse_dates=False, tupleize_cols=False, thousands=',', encoding=None, decimal='.', converters=None, na_values=None, keep_default_na=True): </code></pre> <p>The function header implies that there is a decimal separator available in the function call. </p> <p>Further down in the documentation this looks like it was added in version 0.19 (so a bit further down the experimental branch). Can you upgrade your pandas? </p> <blockquote> <p>decimal : str, default '.' Character to recognize as decimal point (e.g. use ',' for European data). .. versionadded:: 0.19.0</p> </blockquote>
3
2016-09-09T13:51:26Z
[ "python", "pandas", "decimal", "xlm" ]
pandas.read_html not support decimal comma
39,412,829
<p>I was reading an xlm file using <code>pandas.read_html</code> and works <strong>almost perfect</strong>, the problem is that the file has commas as decimal separators instead of dots (the default in <code>read_html</code>). </p> <p>I could easily replace the commas by dots in one file, but i have almost 200 files with that configuration. with <code>pandas.read_csv</code> you can define the decimal separator, but i don't know why in <code>pandas.read_html</code> you can only define the thousand separator. </p> <p>any guidance in this matter?, there is another way to automate the comma/dot replacement before it is open by pandas? thanks in advance! </p>
5
2016-09-09T13:35:16Z
39,414,644
<p>Thanks @zhqiat. I think upgrading <code>pandas</code> to version <code>0.19</code> will solve the problem. unfortunately I couldn't found an easy way to accomplish that. I found a tutorial to upgrade Pandas but for <a href="http://askubuntu.com/questions/70883/how-do-i-install-python-pandas/70885">ubuntu</a> (winXP user).</p> <p>I finally chose the workaround, using the method posted <a href="http://stackoverflow.com/a/17550789/5318634">here</a>, basically converting all columns, one by one, to a numeric type of <code>pandas.Series</code></p> <pre><code>result[col] = result[col].apply(lambda x: x.str.replace(".","").str.replace(",",".")) </code></pre> <p>I know that this solution ain't the best, but works. Thanks</p>
2
2016-09-09T15:07:25Z
[ "python", "pandas", "decimal", "xlm" ]
Can I get the total count of a post likes, shares and comments using facebook sdk in Python?
39,412,861
<p>I want to get the total number of counts of a facebook post in python. The code below is giving a json object of some persons who likes the post. But not all. I need total counts. Is it possible?</p> <pre><code>import requests import facebook token='' graph = facebook.GraphAPI(token) lik = graph.get_connections(id='10153608167431961', connection_name='likes') print(lik) </code></pre> <p>Result is :</p> <blockquote> <p>{'data': [{'id': '1583767538554134', 'name': 'Øp Pö'}, {'id': '120568968399628', 'name': 'William Anthony Christo'}, {'id': '699615593474341', 'name': 'Anum Rabani'}, {'id': '290360191169562', 'name': 'রফিকুল ইসলাম তৌফিক'}, {'id': '119195851825867', 'name': 'Anant Gharte'}, {'id': '1584033738513309', 'name': 'Miguel Gates'}, {'id': '170725429957788', 'name': 'Rahmatullah Kazimi'}, {'id': '165244040549022', 'name': 'Jose Marques'}, {'id': '553277864818751', 'name': 'Shubham Kumar'}, {'id': '177910112626556', 'name': 'Rajesh Singh'}, {'id': '10206027408500948', 'name': 'Cüneyt Ekin'}, {'id': '134409193615843', 'name': 'Moazzem Hossain'}, {'id': '1452911201684073', 'name': 'Sohail Noori'}, {'id': '706685776074740', 'name': 'Man Muet'}, {'id': '1655289584790642', 'name': 'Emeghara Lucky Kelechi'}, {'id': '10205877189481867', 'name': 'Danielle Oliver Solomon'}, {'id': '511315079054021', 'name': 'Ajay Kumar'}, {'id': '659773750764822', 'name': 'Tiago Balloni'}, {'id': '385284718315460', 'name': 'Ivica Herman'}, {'id': '394871897335035', 'name': 'Zubayer Hassan'}, {'id': '532960883548514', 'name': 'Mohan Rathod'}, {'id': '373452456160618', 'name': 'Jeevajohthy Pramulu Naidu'}, {'id': '803092719700936', 'name': 'Patricia Ann Harris'}, {'id': '960692997327631', 'name': 'Osama Ozy'}, {'id': '739963022766566', 'name': 'Abdalrhman Selim'}], 'paging': {'next': '<a href="https://graph.facebook.com/v2.1/10153608167431961/likes?access_token=EAACEdEose0cBAJZC5cI5OJZC6l6XZATLGsBjutHdQyvqEs4yQk7HejvKNAHqLwdNgANtMdvnGAekUo7Mx10u8K2MydmOCNNzEDmPAL3kTQITKTYIwwD1ZCNTjpLtSnZATTiW0xWrnaFbjJomXKQUnkMpF3ZCBqh6WYMixkh5tuhQZDZD&amp;limit=25&amp;after=NzM5OTYzMDIyNzY2NTY2" rel="nofollow">https://graph.facebook.com/v2.1/10153608167431961/likes?access_token=EAACEdEose0cBAJZC5cI5OJZC6l6XZATLGsBjutHdQyvqEs4yQk7HejvKNAHqLwdNgANtMdvnGAekUo7Mx10u8K2MydmOCNNzEDmPAL3kTQITKTYIwwD1ZCNTjpLtSnZATTiW0xWrnaFbjJomXKQUnkMpF3ZCBqh6WYMixkh5tuhQZDZD&amp;limit=25&amp;after=NzM5OTYzMDIyNzY2NTY2</a>', 'cursors': {'before': 'MTU4Mzc2NzUzODU1NDEzNAZDZD', 'after': 'NzM5OTYzMDIyNzY2NTY2'}}}</p> </blockquote>
-1
2016-09-09T13:36:55Z
39,413,730
<p>Use this API call:</p> <pre><code>/10153608167431961?fields=likes.limit(0).summary(true) </code></pre> <p>Result:</p> <pre><code>{ "likes": { "data": [ ], "summary": { "total_count": 13260, "can_like": true, "has_liked": false } }, "id": "10153608167431961" } </code></pre> <p>Alternative:</p> <pre><code>/10153608167431961/likes?summary=true&amp;limit=0 </code></pre> <p>Result:</p> <pre><code>{ "data": [ ], "summary": { "total_count": 13260, "can_like": true, "has_liked": false } } </code></pre> <p>The same for comments:</p> <pre><code>/10153608167431961/comments?summary=true&amp;limit=0 </code></pre> <p>I am not sure why it does not work with <code>/sharedposts</code>, it may be a bug, it may be intentional for some reason.</p>
0
2016-09-09T14:18:26Z
[ "python", "facebook", "facebook-graph-api" ]
Can I get the total count of a post likes, shares and comments using facebook sdk in Python?
39,412,861
<p>I want to get the total number of counts of a facebook post in python. The code below is giving a json object of some persons who likes the post. But not all. I need total counts. Is it possible?</p> <pre><code>import requests import facebook token='' graph = facebook.GraphAPI(token) lik = graph.get_connections(id='10153608167431961', connection_name='likes') print(lik) </code></pre> <p>Result is :</p> <blockquote> <p>{'data': [{'id': '1583767538554134', 'name': 'Øp Pö'}, {'id': '120568968399628', 'name': 'William Anthony Christo'}, {'id': '699615593474341', 'name': 'Anum Rabani'}, {'id': '290360191169562', 'name': 'রফিকুল ইসলাম তৌফিক'}, {'id': '119195851825867', 'name': 'Anant Gharte'}, {'id': '1584033738513309', 'name': 'Miguel Gates'}, {'id': '170725429957788', 'name': 'Rahmatullah Kazimi'}, {'id': '165244040549022', 'name': 'Jose Marques'}, {'id': '553277864818751', 'name': 'Shubham Kumar'}, {'id': '177910112626556', 'name': 'Rajesh Singh'}, {'id': '10206027408500948', 'name': 'Cüneyt Ekin'}, {'id': '134409193615843', 'name': 'Moazzem Hossain'}, {'id': '1452911201684073', 'name': 'Sohail Noori'}, {'id': '706685776074740', 'name': 'Man Muet'}, {'id': '1655289584790642', 'name': 'Emeghara Lucky Kelechi'}, {'id': '10205877189481867', 'name': 'Danielle Oliver Solomon'}, {'id': '511315079054021', 'name': 'Ajay Kumar'}, {'id': '659773750764822', 'name': 'Tiago Balloni'}, {'id': '385284718315460', 'name': 'Ivica Herman'}, {'id': '394871897335035', 'name': 'Zubayer Hassan'}, {'id': '532960883548514', 'name': 'Mohan Rathod'}, {'id': '373452456160618', 'name': 'Jeevajohthy Pramulu Naidu'}, {'id': '803092719700936', 'name': 'Patricia Ann Harris'}, {'id': '960692997327631', 'name': 'Osama Ozy'}, {'id': '739963022766566', 'name': 'Abdalrhman Selim'}], 'paging': {'next': '<a href="https://graph.facebook.com/v2.1/10153608167431961/likes?access_token=EAACEdEose0cBAJZC5cI5OJZC6l6XZATLGsBjutHdQyvqEs4yQk7HejvKNAHqLwdNgANtMdvnGAekUo7Mx10u8K2MydmOCNNzEDmPAL3kTQITKTYIwwD1ZCNTjpLtSnZATTiW0xWrnaFbjJomXKQUnkMpF3ZCBqh6WYMixkh5tuhQZDZD&amp;limit=25&amp;after=NzM5OTYzMDIyNzY2NTY2" rel="nofollow">https://graph.facebook.com/v2.1/10153608167431961/likes?access_token=EAACEdEose0cBAJZC5cI5OJZC6l6XZATLGsBjutHdQyvqEs4yQk7HejvKNAHqLwdNgANtMdvnGAekUo7Mx10u8K2MydmOCNNzEDmPAL3kTQITKTYIwwD1ZCNTjpLtSnZATTiW0xWrnaFbjJomXKQUnkMpF3ZCBqh6WYMixkh5tuhQZDZD&amp;limit=25&amp;after=NzM5OTYzMDIyNzY2NTY2</a>', 'cursors': {'before': 'MTU4Mzc2NzUzODU1NDEzNAZDZD', 'after': 'NzM5OTYzMDIyNzY2NTY2'}}}</p> </blockquote>
-1
2016-09-09T13:36:55Z
39,977,752
<p>graph.get_connections(id='10153608167431961', connection_name='likes', summary='true')</p> <p>This should give the total likes for the given post/feed.</p>
0
2016-10-11T12:55:16Z
[ "python", "facebook", "facebook-graph-api" ]
Handling big numbers in Python 3 for calculating combinations
39,412,892
<p>So I have a Python 3 script that calculates combinations in the following way</p> <pre><code>def permutate(n, k): if k == 0: return 1 elif n &lt; n - k + 1: return n else: return n * permutate(n - 1, k - 1) def choose(n, k): if k &gt; n / 2: k = n - k return int(permutate(n, k) / permutate(k, k)) </code></pre> <p>So my problem is when handling big numbers,</p> <pre><code>choose(5, 3) </code></pre> <p>yields 10 which is correct.</p> <pre><code>choose(1000, 1) choose(52, 4) choose(1000, 5) choose(1000, 999) </code></pre> <p>These all yield the correct result, however when I try to pass</p> <pre><code>choose(1000, 800) </code></pre> <p>I get the wrong result, the head of part of my resulting integer is correct but when I reach the tail part of the integer it is not correct, which leads me to believe that the problem lies in Python trying to handle the division of the two very large numbers in the choose function.</p> <pre><code>return int(permutate(n, k) / permutate(k, k)) </code></pre> <p>I'm sorry if I broke any rules or if the code formatting is way off, officially my first post :)</p>
3
2016-09-09T13:38:05Z
39,412,931
<p>Problem is: all your divisions use floating point whereas they are clearly targeted as integer.</p> <p>Python 3 acts differently from Python 2.</p> <pre><code>3/2 =&gt; 1.5 3//2 =&gt; 1 </code></pre> <p>Replace <code>/</code> by <code>//</code> (no need to cast in integer like you did)</p> <pre><code>return permutate(n, k) // permutate(k, k) </code></pre> <p>also here (less important)</p> <pre><code>if k &gt; n // 2 </code></pre>
3
2016-09-09T13:40:37Z
[ "python", "python-3.x" ]
Handling big numbers in Python 3 for calculating combinations
39,412,892
<p>So I have a Python 3 script that calculates combinations in the following way</p> <pre><code>def permutate(n, k): if k == 0: return 1 elif n &lt; n - k + 1: return n else: return n * permutate(n - 1, k - 1) def choose(n, k): if k &gt; n / 2: k = n - k return int(permutate(n, k) / permutate(k, k)) </code></pre> <p>So my problem is when handling big numbers,</p> <pre><code>choose(5, 3) </code></pre> <p>yields 10 which is correct.</p> <pre><code>choose(1000, 1) choose(52, 4) choose(1000, 5) choose(1000, 999) </code></pre> <p>These all yield the correct result, however when I try to pass</p> <pre><code>choose(1000, 800) </code></pre> <p>I get the wrong result, the head of part of my resulting integer is correct but when I reach the tail part of the integer it is not correct, which leads me to believe that the problem lies in Python trying to handle the division of the two very large numbers in the choose function.</p> <pre><code>return int(permutate(n, k) / permutate(k, k)) </code></pre> <p>I'm sorry if I broke any rules or if the code formatting is way off, officially my first post :)</p>
3
2016-09-09T13:38:05Z
39,413,332
<p><strong> Edited for correctness/brevity </strong></p> <hr/> <p>I have another approach that would take the load away from division and put it on multiplication. I would suggest taking advantage of the definition of combinations. Since combinations and permutations are counting techniques, losing precision through arithmetic operations is not good craftsmanship.</p> <p>In the combination, you wanna cancel out the common factors in the numerator and the denominator as best as you can so that you can. So I'd say ditch your permutation function altogether, and your combination function would be something like...</p> <pre><code> def permute(n, k): // P(n,k) = n!/(n-k)! mathematically largest_dividable_number = max(k, n-k) output_value = 1 starting_value = n for i in range(1,largest_dividable_number - 1): output_value = output_value * starting_value starting_value = starting_value - 1 return output_value def choose(n, k): p = permute(n,k) return p//math.factorial(k) </code></pre>
0
2016-09-09T13:59:07Z
[ "python", "python-3.x" ]
Handling big numbers in Python 3 for calculating combinations
39,412,892
<p>So I have a Python 3 script that calculates combinations in the following way</p> <pre><code>def permutate(n, k): if k == 0: return 1 elif n &lt; n - k + 1: return n else: return n * permutate(n - 1, k - 1) def choose(n, k): if k &gt; n / 2: k = n - k return int(permutate(n, k) / permutate(k, k)) </code></pre> <p>So my problem is when handling big numbers,</p> <pre><code>choose(5, 3) </code></pre> <p>yields 10 which is correct.</p> <pre><code>choose(1000, 1) choose(52, 4) choose(1000, 5) choose(1000, 999) </code></pre> <p>These all yield the correct result, however when I try to pass</p> <pre><code>choose(1000, 800) </code></pre> <p>I get the wrong result, the head of part of my resulting integer is correct but when I reach the tail part of the integer it is not correct, which leads me to believe that the problem lies in Python trying to handle the division of the two very large numbers in the choose function.</p> <pre><code>return int(permutate(n, k) / permutate(k, k)) </code></pre> <p>I'm sorry if I broke any rules or if the code formatting is way off, officially my first post :)</p>
3
2016-09-09T13:38:05Z
39,413,857
<p>Here is another solution, which uses the <a href="https://docs.python.org/3.5/library/fractions.html" rel="nofollow">fractions</a> module to (by reducing to lowest terms) do the division as it goes along. It also uses the fact that e.g. <code>choose(100,70) = choose(100,30)</code> so as to not do unneeded multiplication:</p> <pre><code>from fractions import Fraction def choose(n,k): if k &gt; n//2: k = n - k p = Fraction(1) for i in range(1,k+1): p *= Fraction(n - i + 1, i) return int(p) </code></pre> <p>for example,</p> <pre><code>&gt;&gt;&gt; choose(10000,100) 65208469245472575695415972927215718683781335425416743372210247172869206520770178988927510291340552990847853030615947098118282371982392705479271195296127415562705948429404753632271959046657595132854990606768967505457396473467998111950929802400 </code></pre> <p>(which can be verified with a computer algebra system).</p> <p>It is reasonably fast, taking about a second to find all 54341 digits of <code>choose(10**9, 10000)</code>.</p>
2
2016-09-09T14:24:41Z
[ "python", "python-3.x" ]
Allow only one instance of a model in Django
39,412,968
<p>I would like to control some configuration settings for my project using a database model. For example:</p> <pre><code>class JuicerBaseSettings(models.Model): max_rpm = model.IntegerField(default=10) min_rpm = model.IntegerField(default=0) </code></pre> <p>There should only be one instance of this model:</p> <pre><code>juicer_base = JuicerBaseSettings() juicer_base.save() </code></pre> <p>Of course, if someone accidentally creates a new instances, it's not the end of the world. I could just do <code>JuicerBaseSettings.objects.all().first()</code>. However, is there a way to lock it down such that it's impossible to create more than 1 instance?</p> <p>I found two related questions on SO. <a href="http://stackoverflow.com/questions/2273258/how-about-having-a-singletonmodel-in-django">This answer</a> suggests using 3rd party apps like <code>django-singletons</code>, which doesn't seem to be actively maintained (last update to the git repo is 5 years ago). <a href="http://stackoverflow.com/questions/4888159/django-models-only-permit-one-entry-in-a-model">Another answer</a> suggests using a combination of either permissions or <code>OneToOneField</code>. Both answers are from 2010-2011.</p> <p>Given that Django has changed a lot since then, are there any standard ways to solve this problem? Or should I just use <code>.first()</code> and accept that there may be duplicates?</p>
2
2016-09-09T13:42:42Z
39,413,083
<p>You can override <code>save</code> method to control number of instances: </p> <pre><code>class JuicerBaseSettings(models.Model): def save(self, *args, **kwargs): if JuicerBaseSettings.objects.exists() and not self.pk: # if you'll not check for self.pk # then error will also raised in update of exists model raise ValidationError('There is can be only one JuicerBaseSettings instance') return super(JuicerBaseSettings, self).save(*args, **kwargs) </code></pre>
2
2016-09-09T13:47:45Z
[ "python", "django" ]
Allow only one instance of a model in Django
39,412,968
<p>I would like to control some configuration settings for my project using a database model. For example:</p> <pre><code>class JuicerBaseSettings(models.Model): max_rpm = model.IntegerField(default=10) min_rpm = model.IntegerField(default=0) </code></pre> <p>There should only be one instance of this model:</p> <pre><code>juicer_base = JuicerBaseSettings() juicer_base.save() </code></pre> <p>Of course, if someone accidentally creates a new instances, it's not the end of the world. I could just do <code>JuicerBaseSettings.objects.all().first()</code>. However, is there a way to lock it down such that it's impossible to create more than 1 instance?</p> <p>I found two related questions on SO. <a href="http://stackoverflow.com/questions/2273258/how-about-having-a-singletonmodel-in-django">This answer</a> suggests using 3rd party apps like <code>django-singletons</code>, which doesn't seem to be actively maintained (last update to the git repo is 5 years ago). <a href="http://stackoverflow.com/questions/4888159/django-models-only-permit-one-entry-in-a-model">Another answer</a> suggests using a combination of either permissions or <code>OneToOneField</code>. Both answers are from 2010-2011.</p> <p>Given that Django has changed a lot since then, are there any standard ways to solve this problem? Or should I just use <code>.first()</code> and accept that there may be duplicates?</p>
2
2016-09-09T13:42:42Z
39,413,104
<p>i am not an expert but i guess you can overwrite the model's save() method so that it will check if there has already been a instance , if so the save() method will just return , otherwise it will call the super().save()</p>
2
2016-09-09T13:49:19Z
[ "python", "django" ]
Allow only one instance of a model in Django
39,412,968
<p>I would like to control some configuration settings for my project using a database model. For example:</p> <pre><code>class JuicerBaseSettings(models.Model): max_rpm = model.IntegerField(default=10) min_rpm = model.IntegerField(default=0) </code></pre> <p>There should only be one instance of this model:</p> <pre><code>juicer_base = JuicerBaseSettings() juicer_base.save() </code></pre> <p>Of course, if someone accidentally creates a new instances, it's not the end of the world. I could just do <code>JuicerBaseSettings.objects.all().first()</code>. However, is there a way to lock it down such that it's impossible to create more than 1 instance?</p> <p>I found two related questions on SO. <a href="http://stackoverflow.com/questions/2273258/how-about-having-a-singletonmodel-in-django">This answer</a> suggests using 3rd party apps like <code>django-singletons</code>, which doesn't seem to be actively maintained (last update to the git repo is 5 years ago). <a href="http://stackoverflow.com/questions/4888159/django-models-only-permit-one-entry-in-a-model">Another answer</a> suggests using a combination of either permissions or <code>OneToOneField</code>. Both answers are from 2010-2011.</p> <p>Given that Django has changed a lot since then, are there any standard ways to solve this problem? Or should I just use <code>.first()</code> and accept that there may be duplicates?</p>
2
2016-09-09T13:42:42Z
39,413,115
<p>You could use a pre_save signal </p> <pre><code>@receiver(pre_save, sender=JuicerBaseSettings) def check_no_conflicting_juicer(sender, instance, *args, **kwargs): # If another JuicerBaseSettings object exists a ValidationError will be raised if JuicerBaseSettings.objects.exclude(pk=instance.pk).exists(): raise ValidationError('A JuiceBaseSettings object already exists') </code></pre>
2
2016-09-09T13:49:54Z
[ "python", "django" ]
find values for which the result of division change in integer in python
39,412,999
<p>This might be a really silly question but I'm a bit stuck. I have three columns with data. Column C is the result of the division of Column A/Column B. The result of this simple operation gives me real numbers running from 0 to 15. I want to compute for which value in column A, the values in column C change in multiple (from 1, to 2, to 3). i.e.</p> <pre><code>A B C=A/B 0.0 894.57 0.0 1.0 894.579620994 0.00111784348372 11.0 894.579622195 0.0122962783044 21.0 894.579625847 0.0234747130309 30.0 894.579632967 0.0335353040629 40.0 894.57964499 0.0447137381496 ... ... ... 881.0 894.579705447 0.984820016188 891.0 894.579703891 0.995998451703 901.0 894.57970588 1.00717688326 911.0 894.579707084 1.01835531567 ... ... ... 1781.0 894.579658537 1.99087916096 1791.0 894.57965582 2.00205760141 1801.0 894.579658252 2.01323603034 </code></pre> <p>What I want in other words is to find the values of A for which the values in C change the integer. In this case it would be the value for which it changes from 0.99 to 1., so it would be: 901; then from 1 to 2 it would be 1791, and so on. Any ideas are welcome. I thought I could find the residuals (%) but I cannot come up of how. </p>
0
2016-09-09T13:44:15Z
39,413,144
<p>Maybe this would help:</p> <pre><code>A = 1 # adapt this to your data B = 894.57 # adapt this to your data lastInt = -1 for i in range(0,1000): C = A / B newInt = int(C) if newInt!=lastInt: print "CHANGE: from {} to {}. A is {}".format(lastInt, newInt, A) lastInt = newInt A += 10 # adapt this to your data </code></pre>
0
2016-09-09T13:51:08Z
[ "python", "bigdata", "division" ]
find values for which the result of division change in integer in python
39,412,999
<p>This might be a really silly question but I'm a bit stuck. I have three columns with data. Column C is the result of the division of Column A/Column B. The result of this simple operation gives me real numbers running from 0 to 15. I want to compute for which value in column A, the values in column C change in multiple (from 1, to 2, to 3). i.e.</p> <pre><code>A B C=A/B 0.0 894.57 0.0 1.0 894.579620994 0.00111784348372 11.0 894.579622195 0.0122962783044 21.0 894.579625847 0.0234747130309 30.0 894.579632967 0.0335353040629 40.0 894.57964499 0.0447137381496 ... ... ... 881.0 894.579705447 0.984820016188 891.0 894.579703891 0.995998451703 901.0 894.57970588 1.00717688326 911.0 894.579707084 1.01835531567 ... ... ... 1781.0 894.579658537 1.99087916096 1791.0 894.57965582 2.00205760141 1801.0 894.579658252 2.01323603034 </code></pre> <p>What I want in other words is to find the values of A for which the values in C change the integer. In this case it would be the value for which it changes from 0.99 to 1., so it would be: 901; then from 1 to 2 it would be 1791, and so on. Any ideas are welcome. I thought I could find the residuals (%) but I cannot come up of how. </p>
0
2016-09-09T13:44:15Z
39,413,146
<p>Assuming you know how to get the data out since you said you tried <code>%</code> and assuming that the data are not strings, wouldn't this work? A simple if statement with a checker that increments? </p> <pre><code>number_to_check = 1 if c &gt;= number_to_check: number_to_check += 1 print(a) </code></pre>
0
2016-09-09T13:51:16Z
[ "python", "bigdata", "division" ]
find values for which the result of division change in integer in python
39,412,999
<p>This might be a really silly question but I'm a bit stuck. I have three columns with data. Column C is the result of the division of Column A/Column B. The result of this simple operation gives me real numbers running from 0 to 15. I want to compute for which value in column A, the values in column C change in multiple (from 1, to 2, to 3). i.e.</p> <pre><code>A B C=A/B 0.0 894.57 0.0 1.0 894.579620994 0.00111784348372 11.0 894.579622195 0.0122962783044 21.0 894.579625847 0.0234747130309 30.0 894.579632967 0.0335353040629 40.0 894.57964499 0.0447137381496 ... ... ... 881.0 894.579705447 0.984820016188 891.0 894.579703891 0.995998451703 901.0 894.57970588 1.00717688326 911.0 894.579707084 1.01835531567 ... ... ... 1781.0 894.579658537 1.99087916096 1791.0 894.57965582 2.00205760141 1801.0 894.579658252 2.01323603034 </code></pre> <p>What I want in other words is to find the values of A for which the values in C change the integer. In this case it would be the value for which it changes from 0.99 to 1., so it would be: 901; then from 1 to 2 it would be 1791, and so on. Any ideas are welcome. I thought I could find the residuals (%) but I cannot come up of how. </p>
0
2016-09-09T13:44:15Z
39,413,378
<p>It's probably not an elegant solution, but couldn't you just compare the numbers at the beginning of each entry (assuming your data is consistent)? This would make things very easy. The example below assumes your data is separated by whitespace (as in your post) and is stored in a file called "data."</p> <hr> <p>Program:</p> <pre><code>data = open("data", "r") last = "0" for element in data: a, b, c = element.split() if c[0] != last: print(a) last = c[0] </code></pre> <hr> <p>Output:</p> <pre><code>901.0 1791.0 </code></pre>
1
2016-09-09T14:01:22Z
[ "python", "bigdata", "division" ]
numpy mask for 2d array with all values in 1d array
39,413,148
<p>I want to convert a 2d matrix of dates to boolean matrix based on dates in a 1d matrix. i.e., </p> <pre><code>[[20030102, 20030102, 20070102], [20040102, 20040102, 20040102]., [20050102, 20050102, 20050102]] </code></pre> <p>should become</p> <pre><code>[[True, True, False], [False, False, False]., [True, True, True]] </code></pre> <p>if I provide a 1d array [20010203, <strong>20030102</strong>, 20030501, <strong>20050102</strong>, 20060101]</p>
2
2016-09-09T13:51:19Z
39,413,415
<pre><code>import numpy as np dateValues = np.array( [[20030102, 20030102, 20030102], [20040102, 20040102, 20040102], [20050102, 20050102, 20050102]]) requestedDates = [20010203, 20030102, 20030501, 20050102, 20060101] ix = np.in1d(dateValues.ravel(), requestedDates).reshape(dateValues.shape) print(ix) </code></pre> <p><strong>Returns:</strong></p> <pre><code>[[ True True True] [False False False] [ True True True]] </code></pre> <p>Refer to <code>numpy.in1d</code> for more information (documentation): <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html</a></p>
4
2016-09-09T14:02:57Z
[ "python", "numpy" ]
numpy mask for 2d array with all values in 1d array
39,413,148
<p>I want to convert a 2d matrix of dates to boolean matrix based on dates in a 1d matrix. i.e., </p> <pre><code>[[20030102, 20030102, 20070102], [20040102, 20040102, 20040102]., [20050102, 20050102, 20050102]] </code></pre> <p>should become</p> <pre><code>[[True, True, False], [False, False, False]., [True, True, True]] </code></pre> <p>if I provide a 1d array [20010203, <strong>20030102</strong>, 20030501, <strong>20050102</strong>, 20060101]</p>
2
2016-09-09T13:51:19Z
39,416,504
<pre><code>a = np.array([[20030102, 20030102, 20070102], [20040102, 20040102, 20040102], [20050102, 20050102, 20050102]]) b = np.array([20010203, 20030102, 20030501, 20050102, 20060101]) &gt;&gt;&gt; a.shape (3, 3) &gt;&gt;&gt; b.shape (5,) &gt;&gt;&gt; </code></pre> <p>For the comparison, you need to <a href="https://docs.scipy.org/doc/numpy-dev/user/basics.broadcasting.html" rel="nofollow">broadcast</a> <code>b</code> onto <code>a</code> by adding an axis to <code>a</code>. - this compares each element of <code>a</code> with each element of <code>b</code></p> <pre><code>&gt;&gt;&gt; mask = a[...,None] == b &gt;&gt;&gt; mask.shape (3, 3, 5) &gt;&gt;&gt; </code></pre> <p>Then use <code>np.any()</code> to see if there are any matches</p> <pre><code>&gt;&gt;&gt; np.any(mask, axis = 2, keepdims = False) array([[ True, True, False], [False, False, False], [ True, True, True]], dtype=bool) </code></pre> <hr> <p>timeit.Timer comparison with <code>in1d</code>:</p> <pre><code>&gt;&gt;&gt; &gt;&gt;&gt; t = Timer("np.any(a[...,None] == b, axis = 2)","from __main__ import np, a, b") &gt;&gt;&gt; t.timeit(10000) 0.13268041338812964 &gt;&gt;&gt; t = Timer("np.in1d(a.ravel(), b).reshape(a.shape)","from __main__ import np, a, b") &gt;&gt;&gt; t.timeit(10000) 0.26060646913566643 &gt;&gt;&gt; </code></pre>
1
2016-09-09T17:03:34Z
[ "python", "numpy" ]
In 'IDA PRO', let 'IDAPython' import default module at startup
39,413,230
<p>We know 'IDAPython' loads several modules by default at startup, such as idaapi, idautils.... I wrote a module to let python print all numbers as hex format in the command window, which I wish can be imported each time when python loads those default modules. how to achieve that?</p>
0
2016-09-09T13:54:29Z
39,688,418
<p>Create a file <code>%APPDATA%\Hex-Rays\IDA Pro\idapythonrc.py</code> with the following content:</p> <pre><code>import idaapi idaapi.require('mymodule') </code></pre> <p>With this file in place, you can even keep <code>mymodule.py</code> in the same directory.</p> <p>P.S. IDA can tell you the path to this directory, too, which could be handy on other OSes or if the relevant company name changes again ;-). Just enter:</p> <pre><code>get_user_idadir() </code></pre> <p>at the prompt.</p>
0
2016-09-25T15:10:43Z
[ "python", "ida" ]
Sending gzip compressed data through TCP socket in Python
39,413,290
<p>I'm creating an HTTP server in Python without any of the HTTP libraries for learning purposes. Right now it can serve static files fine. </p> <p>The way I serve the file is through this piece of code:</p> <pre><code>with open(self.filename, 'rb') as f: src = f.read() socket.sendall(src) </code></pre> <p>However, I want to optimize its performance a bit by sending compressed data instead of uncompressed. I know that my browser (Chrome) accepts compressed data because it tells me in the header </p> <pre><code>Accept-Encoding: gzip, deflate, sdch </code></pre> <p>So, I changed my code to this</p> <pre><code>with open(self.filename, 'rb') as f: src = zlib.compress(f.read()) socket.sendall(src) </code></pre> <p>But this just outputs garbage. What am I doing wrong?</p>
0
2016-09-09T13:57:06Z
39,416,270
<p>The zlib library implements the deflate compression algorithm (RFC 1951). There are two encapsulations for the deflate compression: zlib (RFC 1950) and gzip (RFC 1952). These differ only in the kind of header and trailer they provide around the deflate compressed data.</p> <p><code>zlib.compress</code> only provides the raw deflate data, without any header and trailer. To get these you need to use a compression object. For gzip this looks like this:</p> <pre><code>z = zlib.compressobj(-1,zlib.DEFLATED,31) gzip_compressed_data = z.compress(data) + z.flush() </code></pre> <p>The important part here is the <code>31</code> as the 3rd argument to <code>compressobj</code>. This specifies gzip format which then can be used with <code>Content-Encoding: gzip</code>. </p>
0
2016-09-09T16:46:36Z
[ "python", "sockets", "http", "get", "bzip" ]
Finding indices from list comprehension in Python 3
39,413,359
<p>I want to find the indices of matches in a list using the best Python syntax. Here is what I have:</p> <pre><code>v = ['=', 'c', '=', 'c', 'c', 'c', '=', 'c', 'c', '='] </code></pre> <p>Now, return the list of integers for the condition of:</p> <pre><code>'=' in v is True </code></pre> <p>So far, I have:</p> <pre><code>[v.index(i) for i in v if i=='='] </code></pre> <p>which return:</p> <pre><code>[ 0, 0, 0, 0 ] </code></pre> <p>instead of:</p> <pre><code>[ 0, 2, 6, 9 ] </code></pre> <p>I'm missing the last step and I don't want to put it into a 'for' loop'.</p>
-1
2016-09-09T14:00:24Z
39,413,406
<p>Use <a href="https://docs.python.org/3.5/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a>:</p> <pre><code>[i for i,x in enumerate(v) if x=='='] </code></pre>
0
2016-09-09T14:02:44Z
[ "python", "if-statement", "list-comprehension" ]
Finding indices from list comprehension in Python 3
39,413,359
<p>I want to find the indices of matches in a list using the best Python syntax. Here is what I have:</p> <pre><code>v = ['=', 'c', '=', 'c', 'c', 'c', '=', 'c', 'c', '='] </code></pre> <p>Now, return the list of integers for the condition of:</p> <pre><code>'=' in v is True </code></pre> <p>So far, I have:</p> <pre><code>[v.index(i) for i in v if i=='='] </code></pre> <p>which return:</p> <pre><code>[ 0, 0, 0, 0 ] </code></pre> <p>instead of:</p> <pre><code>[ 0, 2, 6, 9 ] </code></pre> <p>I'm missing the last step and I don't want to put it into a 'for' loop'.</p>
-1
2016-09-09T14:00:24Z
39,413,411
<p>What you need is this:</p> <pre><code>[i for i, entry in enumerate(v) if entry == '='] </code></pre> <p>The difference between this comprehension and yours is that in yours, after finding a match you get it's <code>index</code> which returns the position in the list in which the object is found <strong>for the first time</strong>. That is why you get the 0s.</p>
0
2016-09-09T14:02:51Z
[ "python", "if-statement", "list-comprehension" ]
Python 2.7 Tkinter: loop through labels to display data on new row
39,413,405
<p>I currently trying to create a weather application and I have code that prints out the day, forecast, and maxtemperture for the next 7 days. </p> <pre><code>weather_req_url = "https://api.forecast.io/forecast/%s/%s,%s?units=uk2" % (weather_api_token, lat,lon) r = requests.get(weather_req_url) weather_obj = json.loads(r.text) t = datetime.now() for i, x in enumerate(weather_obj["daily"]["data"][1:8]): print (t+timedelta(days=i+1)).strftime("\t%a"), x['icon'], ("%.0f" % x['temperatureMax']) </code></pre> <p>This codes prints this information in the shell:</p> <pre><code>Sat rain 20 Sun partly-cloudy-day 21 Mon clear-day 26 Tue partly-cloudy-night 29 Wed rain 28 Thu rain 24 Fri rain 23 </code></pre> <p>I currently have a frame and a label for it however I don't want to manually create a label for each row.</p> <pre><code>self.degreeFrm = Frame(self, bg="black") self.degreeFrm.grid(row = 0, column = 0) self.temperatureLbl = Label(self.degreeFrm, font=('Helvetica Neue UltraLight', 80), fg="white", bg="black") self.temperatureLbl.grid(row = 0, column = 0, sticky = E) </code></pre> <p>Is there a way to run the first chunk of code that creates and displays a label with the information from each iteration of the for loop.</p>
0
2016-09-09T14:02:42Z
39,413,905
<p>As in the comment above, something along these lines should do the trick:</p> <pre><code>forecasts = [] for i, x in enumerate(weather_obj["daily"]["data"][1:8]): forecasts.append((t+timedelta(days=i+1)).strftime("\t%a"), x['icon'], ("%.0f" % x['temperatureMax'])) row_num = 0 for forecast in forecasts: l = Label(self.degreeFrm, font=('Helvetica Neue UltraLight', 80), text = forecast) l.grid(row = row_num, column = 0, sticky= E) row_num +=1 </code></pre> <p>Hope this helps.</p>
2
2016-09-09T14:26:50Z
[ "python", "python-2.7", "for-loop", "tkinter" ]
Function giving wrong output in Python
39,413,447
<p>Through this code, i wish to replace all the dots (<code>.</code>) appearing in the string s with the character present at exactly the symmetrically opposite position. For eg: if <code>s=a.bcdcbba</code>, then the <code>.</code> should be replaced by <code>b</code></p> <p><strong>i.e:</strong></p> <p>The element at <code>i</code>th position should be replaced by the element at <code>len(s)-i-1</code>th position. This function gives wrong output for the cases like <code>g....</code> , <code>.g...</code> etc. Any help ?</p> <pre><code>def replacedots(s): for i in range(0,len(s)): if s[i]==".": s=s.replace(s[i],s[len(s)-i-1],1) return s </code></pre>
0
2016-09-09T14:04:28Z
39,413,707
<p>@chepner's way:</p> <pre><code>def replacedots(s): return ''.join(x if x !='.' else y for x, y in zip(s, reversed(s))) </code></pre> <p>an alternative:</p> <pre><code>def replacedots(s): return ''.join(c if c != '.' else s[-i - 1] for i, c in enumerate(s)) </code></pre> <p>When the char at position <code>i</code> and the char at position <code>len(s) - i - 1</code> is a <code>.</code> the dot will remain a dot.</p> <p><strong>Example:</strong></p> <pre><code>s = "foo.bar" </code></pre>
1
2016-09-09T14:17:19Z
[ "python" ]
How to get a complex number as a user input in python?
39,413,518
<p>I'm trying to build a calculator that does basic operations of complex numbers. I'm using code for a calculator I found online and I want to be able to take user input as a complex number. Right now the code uses int(input) to get integers to evaluate, but I want the input to be in the form of a complex number with the format complex(x,y) where the user only needs to input x,y for each complex number. I'm new to python, so explanations are encouraged and if it's something that's just not possible, that'd be great to know. Here's the code as it is now:</p> <pre><code># define functions def add(x, y): """This function adds two numbers""" return x + y def subtract(x, y): """This function subtracts two numbers""" return x - y def multiply(x, y): """This function multiplies two numbers""" return x * y def divide(x, y): """This function divides two numbers""" return x / y # take input from the user print("Select operation.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") choice = input("Enter choice: 1, 2, 3, or 4: ") num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) if choice == '1': print(num1,"+",num2,"=", add(num1,num2)) elif choice == '2': print(num1,"-",num2,"=", subtract(num1,num2)) elif choice == '3': print(num1,"*",num2,"=", multiply(num1,num2)) elif choice == '4': print(num1,"/",num2,"=", divide(num1,num2)) else: print("Invalid input") </code></pre>
1
2016-09-09T14:07:32Z
39,413,632
<p>Pass your input to the <code>complex</code> type function. This constructor can also be called with a string as argument, and it will attempt to parse it using Python's representation of complex numbers.</p> <p>Example</p> <pre><code>my_number = complex(input("Number")) </code></pre> <p>Note that Python uses "j" as a symbol for the imaginary component; you will have to tell your user to input numbers in this format: <code>1+3j</code></p> <p>If you would like your calculator to support a different syntax, you will have to parse the input and feed it to the <code>complex</code> constructor yourself. Regular expressions may be of help.</p>
1
2016-09-09T14:13:24Z
[ "python", "python-2.7", "input", "calculator", "complex-numbers" ]
python sqlite3 save value out of spinbox into database by pushing button
39,413,521
<p>Trying to save a value from a spinbox into my database. This is a part of my code.</p> <pre><code>numericupdownLL = tk.Spinbox(self, from_=0, to=300) numericupdownLL.pack() def saveDate(title): vLL = int(numericupdownLL.get()) ## convert to int because output of spinbox= str and database=int c.execute("UPDATE settings SET ll=? WHERE name=?",(vLL, title)) conn.commit() buttonSave = tk.Button(self, text='save', command=saveData(something) buttonSave.pack() </code></pre> <p>Now I don't get any error, but the code writes always a zero to my db instead of the value of the spinbox.</p> <p>Any idea?</p>
0
2016-09-09T14:07:41Z
39,424,468
<p>I'll correct the typos in the code in order to be consistent in the explanation</p> <pre><code>numericupdownLL = tk.Spinbox(self, from_=0, to=300) numericupdownLL.pack() # Changed saveDate to saveData that it's actually called in the button def saveData(title): # Corrected indentation vLL = int(numericupdownLL.get()) c.execute("UPDATE settings SET ll=? WHERE name=?",(vLL, title)) conn.commit() # Added a missing parentheses buttonSave = tk.Button(self, text='save', command=saveData(something)) buttonSave.pack() </code></pre> <p>Two notes:</p> <ul> <li>I'll be referencing this code instead of yours mainly because the name of the function called in the button and the name of the declared function does not match.</li> <li>As far as I don't know how looks like your I will assume that the rest of the code works.</li> </ul> <p>So let's start:</p> <p>The first thing to note is that you're calling the function only once and not each time the button is clicked. That's because instead of passing the function you're passing a None which is the return of that function call. So to fix that you should remove the parentheses and just pass the function as a callback</p> <pre><code># WARNING! This code does not work! Keep reading! buttonSave = tk.Button(self, text='save', command=saveData) </code></pre> <p><strong>After correcting that each time you click the button an exception will be risen telling you that the function needs 1 argument and 0 is passed</strong>. This exception is because of the <code>title</code> parameter in the <code>saveData</code> function so if you want something to be passed as a parameter you will need to return a callback that uses that parameter inside but that it does not accept any parameter:</p> <pre><code>def get_save_data_fn(title): def saveData(): vLL = int(numericupdownLL.get()) c.execute("UPDATE settings SET ll=? WHERE name=?",(vLL, title)) conn.commit() return saveData # Returns a function with 0 parameters that uses the given title # Now you can retrieve the function that takes no arguments and has 'something' used # in the sql statement buttonSave = tk.Button(self, text='save', command=get_save_data_fn(something)) </code></pre> <p>So the final code should look like:</p> <pre><code>numericupdownLL = tk.Spinbox(self, from_=0, to=300) numericupdownLL.pack() def get_save_data_fn(title): def saveData(): vLL = int(numericupdownLL.get()) c.execute("UPDATE settings SET ll=? WHERE name=?",(vLL, title)) conn.commit() return saveData # Returns a function with 0 parameters that uses the given title # Now you can retrieve the function that takes no arguments and has 'something' used # in the sql statement buttonSave = tk.Button(self, text='save', command=get_save_data_fn(something)) buttonSave.pack() </code></pre> <p>Summarizing:</p> <ul> <li>The reason the function seems not to be called is because it's called only once when creating the button and it's not called anymore as far as you are not passing that function but None to the command argument.</li> <li>In order to use that <code>something</code> in the callback you must retrieve a function without parameters and use that variable as a closure.</li> </ul> <p>If any part of the code doesn't work for you, let me know!</p>
0
2016-09-10T09:06:00Z
[ "python", "sqlite3" ]
Using pymodbus to read registers
39,413,550
<p>I'm trying to read modbus registers from a PLC using pymodbus. I am following the example posted <a href="http://stackoverflow.com/questions/24872269/reading-registers-with-pymodbus">here</a>. When I attempt <code>print.registers</code> I get the following error: <code>object has no attribute 'registers'</code> The example doesn't show the modules being imported but seems to be the accepted answer. I think the error may be that I'm importing the wrong module or that I am missing a module. I am simply trying to read a register. </p> <p>Here is my code:</p> <pre><code>from pymodbus.client.sync import ModbusTcpClient c = ModbusTcpClient(host="192.168.1.20") chk = c.read_holding_registers(257,10, unit = 1) response = c.execute(chk) print response.registers </code></pre>
0
2016-09-09T14:09:17Z
39,414,431
<p>From reading <a href="https://github.com/bashwork/pymodbus/blob/master/pymodbus/register_read_message.py" rel="nofollow" title="pymodbus read_holding_registers request object">the pymodbus code</a>, it appears that the <code>read_holding_registers</code> object's <code>execute</code> method will return <em>either</em> a response object <em>or</em> an <code>ExceptionResponse</code> object that contains an error. I would guess you're receiving the latter. You need to try something like this:</p> <pre><code>from pymodbus.register_read_message import ReadHoldingRegistersResponse #... response = c.execute(chk) if isinstance(response, ReadHoldingRegistersResponse): print response.registers else: pass # handle error condition here </code></pre>
0
2016-09-09T14:54:48Z
[ "python", "modbus-tcp" ]
Can I send richly-formatted Slack messages as a Bot and not as a Webhook?
39,413,582
<p>I started writing a Slack bot in Python and came to a halt when I couldn't find a way to send richly-formatted messages using the either of the two methods:</p> <pre><code>sc.rtm_send_message("channel_name", my_message) sc.api_call("chat.postMessage", channel="channel_name", text=my_message, username="username", icon_url="icon_url") </code></pre> <p>where <code>my_message = json.dumps({'attachments': [{...}]})</code></p> <p>I now know that I can do this using the webhook approach but is it possible with the above method?</p>
0
2016-09-09T14:11:02Z
39,485,828
<p>Both API (method chat.postMessage) and incoming webhook offer the same options for formatting your messages including markup and attachments.</p> <p>Hint: if you want to use markup in your attachments, make sure to add the field "mrkdwn_in" and name the field your want to use it in or it will be ignored by Slack.</p> <p>Example:</p> <pre><code>{ "attachments": [ { "title": "Title", "pretext": "Pretext _supports_ mrkdwn", "text": "Testing *right now!*", "mrkdwn_in": ["text", "pretext"] } ] } </code></pre> <p>See <a href="https://api.slack.com/docs/message-formatting" rel="nofollow">here</a> for full documentation.</p>
2
2016-09-14T08:29:19Z
[ "python", "slack-api", "slack" ]
Can I send richly-formatted Slack messages as a Bot and not as a Webhook?
39,413,582
<p>I started writing a Slack bot in Python and came to a halt when I couldn't find a way to send richly-formatted messages using the either of the two methods:</p> <pre><code>sc.rtm_send_message("channel_name", my_message) sc.api_call("chat.postMessage", channel="channel_name", text=my_message, username="username", icon_url="icon_url") </code></pre> <p>where <code>my_message = json.dumps({'attachments': [{...}]})</code></p> <p>I now know that I can do this using the webhook approach but is it possible with the above method?</p>
0
2016-09-09T14:11:02Z
39,490,291
<p>I found out where I was going wrong.</p> <p>I was passing my message to the wrong argument in the <code>sc.api_call</code> method.</p> <p>I should've been passing it to <code>sc.api_call(</code><strong><code>attachments=</code></strong><code>...)</code> argument, not the <code>text</code> argument.</p>
1
2016-09-14T12:19:04Z
[ "python", "slack-api", "slack" ]
Convert strings of bytes to floats in Python
39,413,600
<p>I'm using Pandas to handle my data. The first step of my script is to convert a column of strings of bytes to a list of floats. My script is working but its taking too long. Any suggestions on how to speed it up??</p> <pre><code>def byte_to_hex(byte_str): array = ["%02X" % ord(chr(x)) for x in byte_str] return array for index, row in enumerate(data[column].values): row_new = [] row = byte_to_hex(row) stop = len(row) for i in range(4, stop, 4): sample = "".join(row[i:i + 4]) row_new.append(struct.unpack('!f', bytes.fromhex(sample))[0]) </code></pre> <p>Example:<br> b'\x00\x00\x00\x1cB\x80\x1f\xfcB\x80\x1f\xfcB\x80w\xc8Bz\xa1\x97B\x80\x1f\xfcB}LZB\x80\x1f\xfcBz\xa1\x97Bz\xcaoB\x803\xf5B}\xc5\x84B\x80w\xc8B}\xed\xdbB\x80\x1f\xfcB}\xc5\x84B}LZB\x80\x1f\xfcB}#\xe9B}\xed\xdbB}\xc5\x84B\x803\xf5B\x80\x1f\xfcB}\xc5\x84B\x803\xf5B\x803\xf5Bx\xef\tB\x81\xc4\xdf\x7f\xff\xff\xff'</p> <pre><code>[64.06246948242188, 64.06246948242188, 64.23394775390625, 62.65780258178711, 64.06246948242188, 63.324562072753906, 64.06246948242188, 62.65780258178711, 62.697689056396484, 64.10147857666016, 63.44288635253906, 64.23394775390625, 63.48228073120117, 64.06246948242188, 63.44288635253906, 63.324562072753906, 64.06246948242188, 63.28506851196289, 63.48228073120117, 63.44288635253906, 64.10147857666016, 64.06246948242188, 63.44288635253906, 64.10147857666016, 64.10147857666016] </code></pre> <p>Very thankful for any help :)</p>
1
2016-09-09T14:12:02Z
39,414,098
<p>I think you are looking for the <a href="https://docs.python.org/3.4/library/struct.html" rel="nofollow">Struct</a> package</p> <pre><code>import struct struct.pack('f', 3.14) OUT: b'\xdb\x0' struct.unpack('f', b'\xdb\x0fI@') OUT: (3.1415927410125732,) struct.pack('4f', 1.0, 2.0, 3.0, 4.0) OUT: '\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@' </code></pre>
2
2016-09-09T14:37:40Z
[ "python", "pandas", "byte" ]
Taking file input in numpy Matrix
39,413,702
<p>I am unable to find a method to take input of a given file in numpy matrix. I have tried the <code>np.loadtxt()</code> but was unable to get the data.</p> <p>My file format is something like this: Number of col = 9 (except the first field all others are in float).</p> <pre><code>M,0.475,0.37,0.125,0.5095,0.2165,0.1125,0.165,9 F,0.55,0.44,0.15,0.8945,0.3145,0.151,0.32,19 </code></pre> <p>I have also tried taking input in a list and then trying to make it numpy matrix but it was also a failure. </p>
0
2016-09-09T14:16:57Z
39,414,299
<p>You might want to consider using <code>pandas</code> instead - it's much better suited to homogeneous data, and its <code>read_csv</code> function will take your data file and convert it immediately to something you can work with.</p> <p>You can give each column a name - if you don't do this, the function will interpret the first data row as column headings.</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; data = pd.read_csv("/tmp/data.txt", names=['sex', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight']) &gt;&gt;&gt; print(data) sex one two three four five six seven eight 0 M 0.475 0.37 0.125 0.5095 0.2165 0.1125 0.165 9 1 F 0.550 0.44 0.150 0.8945 0.3145 0.1510 0.320 19 </code></pre>
1
2016-09-09T14:47:24Z
[ "python", "numpy" ]
Taking file input in numpy Matrix
39,413,702
<p>I am unable to find a method to take input of a given file in numpy matrix. I have tried the <code>np.loadtxt()</code> but was unable to get the data.</p> <p>My file format is something like this: Number of col = 9 (except the first field all others are in float).</p> <pre><code>M,0.475,0.37,0.125,0.5095,0.2165,0.1125,0.165,9 F,0.55,0.44,0.15,0.8945,0.3145,0.151,0.32,19 </code></pre> <p>I have also tried taking input in a list and then trying to make it numpy matrix but it was also a failure. </p>
0
2016-09-09T14:16:57Z
39,416,578
<p>With your sample as a list of lines:</p> <pre><code>In [1]: txt=b""" ...: M,0.475,0.37,0.125,0.5095,0.2165,0.1125,0.165,9 ...: F,0.55,0.44,0.15,0.8945,0.3145,0.151,0.32,19 ...: """ In [2]: txt=txt.splitlines() </code></pre> <p><code>genfromtxt</code> can load it with <code>dtype=None</code>:</p> <pre><code>In [16]: data = np.genfromtxt(txt, delimiter=',', dtype=None) In [17]: data Out[17]: array([(b'M', 0.475, 0.37, 0.125, 0.5095, 0.2165, 0.1125, 0.165, 9), (b'F', 0.55, 0.44, 0.15, 0.8945, 0.3145, 0.151, 0.32, 19)], dtype=[('f0', 'S1'), ('f1', '&lt;f8'), ('f2', '&lt;f8'), ('f3', '&lt;f8'), ('f4', '&lt;f8'), ('f5', '&lt;f8'), ('f6', '&lt;f8'), ('f7', '&lt;f8'), ('f8', '&lt;i4')]) In [18]: data['f0'] Out[18]: array([b'M', b'F'], dtype='|S1') In [19]: data['f3'] Out[19]: array([ 0.125, 0.15 ]) In [20]: </code></pre> <p>The result is a 1d array (here 2 elements), with many fields, which are accessed by name. Here the first is deduced to be a string, the rest float, except the last integer.</p> <p>I could be more specific about the <code>dtype</code>, and define a field with multiple columns</p> <pre><code>In [21]: data=np.genfromtxt(txt,delimiter=',',dtype=['S3','8float']) In [22]: data Out[22]: array([(b'M', [0.475, 0.37, 0.125, 0.5095, 0.2165, 0.1125, 0.165, 9.0]), (b'F', [0.55, 0.44, 0.15, 0.8945, 0.3145, 0.151, 0.32, 19.0])], dtype=[('f0', 'S3'), ('f1', '&lt;f8', (8,))]) In [23]: data['f1'] Out[23]: array([[ 0.475 , 0.37 , 0.125 , 0.5095, 0.2165, 0.1125, 0.165 , 9. ], [ 0.55 , 0.44 , 0.15 , 0.8945, 0.3145, 0.151 , 0.32 , 19. ]]) </code></pre> <p>The <code>f1</code> field is a 2d array of shape (2,8).</p> <p><code>np.loadtxt</code> will also work, but it's <code>dtype</code> interpretation isn't as flexible. Copying the <code>dtype</code> from the <code>genfromtxt</code> example produces the same thing.</p> <pre><code> datal=np.loadtxt(txt,delimiter=',',dtype=data.dtype) </code></pre> <p><code>pandas</code> also has a good csv reader, with more speed and flexibility. It's a good choice if you are already working with pandas.</p>
1
2016-09-09T17:09:34Z
[ "python", "numpy" ]
Iteration through a range of timestamp in Python
39,413,752
<p>I have a dataframe df :</p> <pre><code>TIMESTAMP equipement1 equipement2 2016-05-10 13:20:00 0.000000 0.000000 2016-05-10 14:40:00 0.400000 0.500000 2016-05-10 15:20:00 0.500000 0.500000 </code></pre> <p>Iam trying to iterate through timestamp by step of 5 minutes . I try : <code>pd.date_range(start, end, freq='5 minutes')</code></p> <p>But I get a problem with timestamp format.</p> <blockquote> <p>" ValueError: Could not evaluate 5 minutes"</p> </blockquote> <p>Any idea to help me to resolve this problem?</p> <p>Thank you</p>
1
2016-09-09T14:19:40Z
39,413,981
<p>First, make sure your TIMESTAMP column is a datetime instead of a string (e.g. <code>df['TIMESTAMP'] = pd.to_datetime(df.TIMESTAMP)</code>).</p> <p>Next, use this column as the index of the dataframe. To make this permanent, <code>df.set_index('TIMESTAMP</code>, inplace=True)`.</p> <p>Now you can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow">resample</a> for any given frequency (e.g. <code>30min</code>) and use different methods of aggregation such as <code>sum</code>, <code>mean</code> (the default), a lambda function, etc).</p> <p>Optionally, you can add <code>.fillna(0)</code> to replace the NaNs with zeros.</p> <pre><code>&gt;&gt;&gt; df.set_index('TIMESTAMP').resample('30min', how='sum') equipement1 equipement2 TIMESTAMP 2016-05-10 13:00:00 0.0 0.0 2016-05-10 13:30:00 NaN NaN 2016-05-10 14:00:00 NaN NaN 2016-05-10 14:30:00 0.4 0.5 2016-05-10 15:00:00 0.5 0.5 </code></pre>
3
2016-09-09T14:31:14Z
[ "python", "date", "pandas" ]
Can I make an ipywidget floatslider with a list of values?
39,413,786
<p>I would like to make an ipywidget floatslider, but passing it a list of values, rather than a range and step. Is there a way to do this, or is making a dropdown widget the only option?</p>
0
2016-09-09T14:21:15Z
39,415,297
<p>Woops! You can use SelectionSlider, e.g.:</p> <pre><code>import ipywidgets as widgets def test(val): print(val) widgets.interact(test, val=widgets.SelectionSlider(description='value', options=['1', '50', '300', '7000'])) </code></pre> <p>This widget wasn't available in my ipywidgets 4.0, so I had to upgrade. Also, make sure that afterward you run </p> <pre><code>jupyter nbextension enable --py --sys-prefix widgetsnbextension </code></pre> <p>as described in their installation instructions.</p>
0
2016-09-09T15:44:29Z
[ "python", "jupyter", "ipywidgets" ]
ImportError: No module named dns.message
39,413,802
<p>When I try to run <code>sudo python dns2proxy.py</code> in Ubuntu, I keep getting this error:</p> <pre><code>Traceback (most recent call last): File "dns2proxy.py", line 21, in &lt;module&gt; import dns.message ImportError: No module named dns.message </code></pre> <p>I have the correct repository cloned (<a href="https://github.com/LeonardoNve/dns2proxy.git" rel="nofollow">see here for GitHub link</a>) and I'm in the correct directory. I've tried running it in Kali linux and it works flawlessly. My intention is to do a <code>gnome-terminal -e "sudo python dns2proxy.py"</code> and make the command run in another terminal.</p>
0
2016-09-09T14:22:05Z
39,413,922
<p>Try running the command</p> <pre><code>pip install dnspython </code></pre> <p>or, if you are using your system Python (not recommended)</p> <pre><code>sudo pip install dnspython </code></pre> <p>This will install the <code>dns</code> package that is currently missing. If, as you say, you have cloned the repository and want to use that version (and possible edit it) you may instead use</p> <pre><code>[sudo] pip install -e . </code></pre> <p>from the cloned directory.</p>
1
2016-09-09T14:27:28Z
[ "python", "linux", "dns" ]
How to extract columns from multiple rows in Python using nested loops?
39,413,828
<p>I have a list with 3 sequences</p> <pre><code>seq_list = ['ACGT', 'ATTT', 'ACCC'] </code></pre> <p>I want to extract the columns from the the list and store it in another list using nested loops in python</p> <p>The final output should be </p> <pre><code>seq_list = ['AAA', 'CTC', 'GTC','TTC'] </code></pre> <p>I have written the following code, but it does not yield the desired output.</p> <pre><code>column = [] for i in range(len(seq_list[0])): #Length of the row for j in range(len(seq_list)): #Length of the column column.append(seq_list[j][i]) print column </code></pre>
0
2016-09-09T14:23:16Z
39,413,884
<p>Alternatively, you can <a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow">"zip" the sequence</a> and <a href="https://docs.python.org/2/library/stdtypes.html#str.join" rel="nofollow">join</a>:</p> <pre><code>&gt;&gt;&gt; [''.join(item) for item in zip(*seq_list)] ['AAA', 'CTC', 'GTC', 'TTC'] </code></pre>
2
2016-09-09T14:25:39Z
[ "python", "python-2.7", "for-loop", "extract", "multiple-columns" ]
How to extract columns from multiple rows in Python using nested loops?
39,413,828
<p>I have a list with 3 sequences</p> <pre><code>seq_list = ['ACGT', 'ATTT', 'ACCC'] </code></pre> <p>I want to extract the columns from the the list and store it in another list using nested loops in python</p> <p>The final output should be </p> <pre><code>seq_list = ['AAA', 'CTC', 'GTC','TTC'] </code></pre> <p>I have written the following code, but it does not yield the desired output.</p> <pre><code>column = [] for i in range(len(seq_list[0])): #Length of the row for j in range(len(seq_list)): #Length of the column column.append(seq_list[j][i]) print column </code></pre>
0
2016-09-09T14:23:16Z
39,413,972
<p>By your method I made little modification, for each inner <code>for</code> loop i created a <code>string</code> and then after inner <code>for</code> loop ends i appended it to <code>column</code>:</p> <pre><code>seq_list = ['ACGT', 'ATTT', 'ACCC'] column = [] for i in range(len(seq_list[0])): #Length of the row string = "" for j in range(len(seq_list)): #Length of the column string += seq_list[j][i] column.append(string) print column </code></pre> <p><strong>Output:</strong></p> <pre><code>['AAA', 'CTC', 'GTC', 'TTC'] </code></pre> <p>Although you could use @alecxe code(using <code>zip</code> and <code>join</code>). I think it's cool and more pythonic.</p>
3
2016-09-09T14:30:40Z
[ "python", "python-2.7", "for-loop", "extract", "multiple-columns" ]
How to extract columns from multiple rows in Python using nested loops?
39,413,828
<p>I have a list with 3 sequences</p> <pre><code>seq_list = ['ACGT', 'ATTT', 'ACCC'] </code></pre> <p>I want to extract the columns from the the list and store it in another list using nested loops in python</p> <p>The final output should be </p> <pre><code>seq_list = ['AAA', 'CTC', 'GTC','TTC'] </code></pre> <p>I have written the following code, but it does not yield the desired output.</p> <pre><code>column = [] for i in range(len(seq_list[0])): #Length of the row for j in range(len(seq_list)): #Length of the column column.append(seq_list[j][i]) print column </code></pre>
0
2016-09-09T14:23:16Z
39,413,986
<pre><code>new_seq_list = reduce( lambda new_seq_list,item: new_seq_list + [''.join([item.pop(0) for item in new_seq_list[0]])] , range(max([len(item) for item in seq_list])) , [[list(item) for item in seq_list]] )[1:] </code></pre> <ol> <li>transform the original list into a list of list-of-characters rather than a list of strings</li> <li>reduce that list once for each character in the longest string</li> <li>each reduction, add to the new list a string consisting of the first item removed from each list-of-characters, joined together.</li> <li>at the end, remove the list of now-empty lists from the beginning of the sequence.</li> </ol>
-2
2016-09-09T14:31:37Z
[ "python", "python-2.7", "for-loop", "extract", "multiple-columns" ]
Return results from a loop for varying portfolio weights into a dataframe in Pandas
39,413,872
<p>I am about to create a portfolio of two assets and would like to vary the weights by a loop, with the weights for the first asset from [-0.5, -0.4, ... 0.4, 0.5] I manage to calculate the risk return points for each of the 11 portfolios by a loop. Nevertheless, the loop creates a new dataframe for each risk/return combination, whereas I would like to create one single dataframe containing all the risk/return points. </p> <p>Here's my code: </p> <pre><code>def imply_x (returns, x): y = 1-x returns.columns = ["A","B"] weighted_return = returns.A * x + returns.B * y name = str(round(x,2)) + "a" return pd.DataFrame({name: weighted_return}) def frange (start, stop, step): x = start while x &lt; stop: yield x x += step for x in frange (-0.5,0.6,0.1): mean_ret = np.mean(imply_x(ret,x)) var_ret = np.percentile(imply_x(ret,x),95) tuple_ret = pd.DataFrame({"risk": var_ret, "mean": mean_ret}) print((tuple_ret)) </code></pre> <p>And here's the result</p> <pre><code> mean risk -0.5a 0.000181 0.018354 mean risk -0.4a 0.000166 0.015611 mean risk -0.3a 0.000151 0.012688 mean risk -0.2a 0.000136 0.0099 mean risk -0.1a 0.000121 0.007454 mean risk -0.0a 0.000106 0.005405 mean risk 0.1a 0.000092 0.004576 mean risk 0.2a 0.000077 0.005007 mean risk 0.3a 0.000062 0.006613 mean risk 0.4a 0.000047 0.008738 mean risk 0.5a 0.000032 0.011082 </code></pre> <p>I'd be thankful if anyone helped me on how to paste the results from the loop into one single data frame</p>
0
2016-09-09T14:25:11Z
39,413,979
<p>You can use <code>pd.concat</code> to create a single dataframe out of them.</p> <p><a href="http://pandas.pydata.org/pandas-docs/stable/merging.html#concatenating-objects" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/merging.html#concatenating-objects</a></p>
0
2016-09-09T14:31:04Z
[ "python", "loops", "dataframe", "weight", "portfolio" ]
How to get nicely formatted documentation in python
39,413,937
<p>I'm an R user and I'm just moving to Python for data analysis. </p> <p>What I'm looking for is a way to pull documentation for any python object (classes, modules, functions...) in a nice-looking, HTML-ish formatted way instead of the output I get when typing <code>help(...)</code>, just like what I would obtain in Rstudio. </p> <p>For example, if I type <code>help(matplotlib.pyplot.fill_betweenx)</code> in a <code>jupyter notebook</code> or in an <code>IPython</code> shell, an extract of the output I get is the following: </p> <p><a href="http://i.stack.imgur.com/glejK.png" rel="nofollow"><img src="http://i.stack.imgur.com/glejK.png" alt="enter image description here"></a></p> <p>Instead, it would be great to have an output as the one in the "online version" of the <code>matplotlib</code> documentation (<a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.fill_betweenx" rel="nofollow">link</a>), even if it would mean opening a new tab in the browser (just look at the example plots in the online version of the documentation: it would be of great help to see them instead of just having the <code>Examples</code> string I get when calling <code>help()</code>).</p> <p>I saw that someone suggested using the <code>pydoc</code> module, but it doesn't work on my machine for some reason (Windows 10 with Anaconda)</p>
0
2016-09-09T14:28:14Z
39,414,081
<p>You might want to check out <a href="http://www.stack.nl/~dimitri/doxygen/" rel="nofollow">DoxyGen</a> - It supports automatic documentation generation for Python with outputs in, among other formats, HTML.</p> <p>It doesn't provide quite the interface you're looking for, but may still be useful to you.</p>
0
2016-09-09T14:36:53Z
[ "python", "formatting", "documentation" ]
'EntryPoint' object has no attribute 'resolve' when using Google Compute Engine
39,413,987
<p>I have an issue related to Cryptography package in Python. Can you please help in resolving these, if possible ? (tried a lot, but couldnt figure out the exact solution)</p> <p>The python code which initiates this error: </p> <pre><code>print("Salt: %s" % salt) server_key = pyelliptic.ECC(curve="prime256v1") # -----&gt;&gt; Line2 print("Server_key: %s" % server_key) # -----&gt;&gt; Line3 server_key_id = base64.urlsafe_b64encode(server_key.get_pubkey()[1:]) http_ece.keys[server_key_id] = server_key http_ece.labels[server_key_id] = "P-256" encrypted = http_ece.encrypt(data, salt=salt, keyid=server_key_id, dh=self.receiver_key, authSecret=self.auth_key) # -----&gt;&gt; Line8 </code></pre> <p>Value of "Salt" is getting displayed in 100% of the cases. </p> <p>If <strong>Line3</strong> gets executed successfully, I see the the following EntryPoint Error because of http_ece.encrypt() call (<strong>Line8</strong>):</p> <pre><code>AttributeError("'EntryPoint' object has no attribute 'resolve'",) </code></pre> <p>(Ref. File Link: <a href="https://github.com/martinthomson/encrypted-content-encoding/blob/master/python/http_ece/__init__.py#L128">https://github.com/martinthomson/encrypted-content-encoding/blob/master/python/http_ece/init.py#L128</a> )</p> <p>Requirements.txt(partial):</p> <pre><code>cryptography==1.5 pyelliptic==1.5.7 pyOpenSSL==16.1.0 </code></pre> <p>On Running the command: <code>sudo pip freeze --all |grep setuptools</code>, I get: <code>setuptools==27.1.2</code></p> <p>Please let me know if any more detail is required.</p> <p>This problem seems to be basically due to some Old/Incompatible packages(related to PyElliptic, Cryptography, PyOpenSSL and/or setuptools) installed on the VM. For Reference: <a href="https://github.com/pyca/cryptography/issues/3149">https://github.com/pyca/cryptography/issues/3149</a></p> <p>Can someone please suggest a good solution to resolve this issue completely ?</p> <p>Thanks,</p>
9
2016-09-09T14:31:38Z
39,499,600
<p>The <a href="https://github.com/pyca/cryptography/issues/2838" rel="nofollow">issue</a> referenced in <a href="http://stackoverflow.com/questions/39413987/entrypoint-object-has-no-attribute-resolve-when-using-google-compute-engine?noredirect=1#comment66303382_39413987">c66303382</a> has this traceback (you never gave your traceback so I have to assume yours ends the same way):</p> <pre><code>File "/usr/local/lib/python2.7/dist-packages/cryptography/hazmat/backends/__init__.py", line 35, in default_backend _default_backend = MultiBackend(_available_backends()) File "/usr/local/lib/python2.7/dist-packages/cryptography/hazmat/backends/__init__.py", line 22, in _available_backends "cryptography.backends" </code></pre> <p><a href="https://github.com/pyca/cryptography/blob/1a6628e55126ec1c98c98a46c04f777f77eff934/src/cryptography/hazmat/backends/__init__.py#L19-L24" rel="nofollow">The full line</a> that triggers the error looks like this:</p> <pre><code>_available_backends_list = [ ep.resolve() for ep in pkg_resources.iter_entry_points( "cryptography.backends" ) ] </code></pre> <p>Searching the <a href="https://github.com/pypa/setuptools" rel="nofollow">repository</a> for <code>EntryPoint</code> definition, then <a href="https://github.com/pypa/setuptools/blame/master/pkg_resources/__init__.py#L2260" rel="nofollow">blaming <code>pkg_resources/__init__.py</code></a> where it is reveals that <code>pkg_resources.EntryPoint.resolve()</code> was added in <a href="https://github.com/pypa/setuptools/commit/92a553d3adeb431cdf92b136ac9ccc3f2ef98bf1" rel="nofollow">commit 92a553d3adeb431cdf92b136ac9ccc3f2ef98bf1</a> (2015-01-05) that went into <code>setuptools v11.3</code>.</p> <p>Thus you'll see this error if you use an older version.</p>
3
2016-09-14T21:02:56Z
[ "python", "django", "cryptography", "google-compute-engine" ]
'EntryPoint' object has no attribute 'resolve' when using Google Compute Engine
39,413,987
<p>I have an issue related to Cryptography package in Python. Can you please help in resolving these, if possible ? (tried a lot, but couldnt figure out the exact solution)</p> <p>The python code which initiates this error: </p> <pre><code>print("Salt: %s" % salt) server_key = pyelliptic.ECC(curve="prime256v1") # -----&gt;&gt; Line2 print("Server_key: %s" % server_key) # -----&gt;&gt; Line3 server_key_id = base64.urlsafe_b64encode(server_key.get_pubkey()[1:]) http_ece.keys[server_key_id] = server_key http_ece.labels[server_key_id] = "P-256" encrypted = http_ece.encrypt(data, salt=salt, keyid=server_key_id, dh=self.receiver_key, authSecret=self.auth_key) # -----&gt;&gt; Line8 </code></pre> <p>Value of "Salt" is getting displayed in 100% of the cases. </p> <p>If <strong>Line3</strong> gets executed successfully, I see the the following EntryPoint Error because of http_ece.encrypt() call (<strong>Line8</strong>):</p> <pre><code>AttributeError("'EntryPoint' object has no attribute 'resolve'",) </code></pre> <p>(Ref. File Link: <a href="https://github.com/martinthomson/encrypted-content-encoding/blob/master/python/http_ece/__init__.py#L128">https://github.com/martinthomson/encrypted-content-encoding/blob/master/python/http_ece/init.py#L128</a> )</p> <p>Requirements.txt(partial):</p> <pre><code>cryptography==1.5 pyelliptic==1.5.7 pyOpenSSL==16.1.0 </code></pre> <p>On Running the command: <code>sudo pip freeze --all |grep setuptools</code>, I get: <code>setuptools==27.1.2</code></p> <p>Please let me know if any more detail is required.</p> <p>This problem seems to be basically due to some Old/Incompatible packages(related to PyElliptic, Cryptography, PyOpenSSL and/or setuptools) installed on the VM. For Reference: <a href="https://github.com/pyca/cryptography/issues/3149">https://github.com/pyca/cryptography/issues/3149</a></p> <p>Can someone please suggest a good solution to resolve this issue completely ?</p> <p>Thanks,</p>
9
2016-09-09T14:31:38Z
39,507,792
<p>Ran Following Commands from the project path /opt/projects/myproject-google/myproject and it resolved the Attribute EntryPoint Error Issue:</p> <p>(Assuming project virtual env path as: /opt/projects/myproject-google/venv)</p> <p>Command: (from path: /opt/projects/myproject-google/myproject)</p> <pre><code>export PYTHONPATH= # [Blank] sudo pip install --upgrade virtualenv setuptools sudo rm -rf ../venv sudo virtualenv ../venv source ../venv/bin/activate sudo pip install --upgrade -r requirements.txt deactivate </code></pre> <p>Running the above commands upgraded the virtual environment &amp; the setuptools version inside the virtual Env. located at path: /opt/projects/myproject-google/venv/lib/python2.7/site-packages. To test if setuptools have upgraded successfully, try some of these commands:</p> <ol> <li><strong>Command</strong>: <code>sudo virtualenv --version</code> <strong>Output</strong>: <code>15.0.3</code></li> <li><strong>Command</strong>: <code>echo $PYTHONPATH</code> <strong>Output</strong>: [blank]</li> <li><strong>Command</strong>: <code>python -c 'import pkg_resources; print(pkg_resources.__file__)'</code> <strong>Output</strong>: <code>~/.local/lib/python2.7/site-packages/pkg_resources/__init__.pyc</code></li> <li><strong>Command</strong>: <code>python -c 'import sys; print(sys.path)'</code> <strong>Output</strong>: <code>['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '~/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/dist-packages', '/opt/projects/myproject-google/myproject', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat']</code></li> <li><strong>Command</strong>: <code>ls /opt/projects/myproject-google/venv/lib/python2.7/site-packages</code> <strong>Output</strong>: <code>easy_install.py pip pkg_resources setuptools-27.2.0.dist-info wheel-0.30.0a0.dist-info easy_install.pyc pip-8.1.2.dist-info setuptools wheel</code></li> <li><strong>Command</strong>: <code>python -c 'from cryptography.hazmat.backends import default_backend; print(default_backend())'</code> <strong>Output</strong>: <code>&lt;cryptography.hazmat.backends.multibackend.MultiBackend object at 0x7ff83a838d50&gt;</code></li> <li><strong>Command</strong> <code>/opt/projects/myproject-google/venv/bin/python -c 'from cryptography.hazmat.backends import default_backend; print(default_backend())'</code> <strong>Output</strong> <code> Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; ImportError: No module named cryptography.hazmat.backends </code></li> <li><strong>Command</strong>: <code>/opt/projects/myproject-google/venv/bin/python -c "import pkg_resources; print(pkg_resources.__file__)"</code> <strong>Output</strong>: <code>/opt/projects/myproject-google/venv/local/lib/python2.7/site-packages/pkg_resources/__init__.pyc</code></li> </ol> <p>Ref Link: <a href="https://github.com/pyca/cryptography/issues/3149" rel="nofollow">https://github.com/pyca/cryptography/issues/3149</a></p> <p>These Steps resolved the Attribute EntryPoint Issue completely with an updated version of cryptography package &amp; the setuptools.</p> <p><strong>Update</strong> As on 15 September 2016, The Cryptography Team has again added the workaround for supporting old packages too. (Ref. Link: <a href="https://github.com/pyca/cryptography/issues/3150" rel="nofollow">https://github.com/pyca/cryptography/issues/3150</a> )</p>
1
2016-09-15T09:39:43Z
[ "python", "django", "cryptography", "google-compute-engine" ]
Translating Matlab code to Python
39,413,998
<p>I need to translate chunks of matlab code into Python. My code seems to be 'unreachable' though. Any idea why this is happening? Also: am I doing it right? I'm a real newbie.</p> <p>Matlab code:</p> <pre><code>function Dir = getScriptDir() fullPath = mfilename('fullpath'); [Dir, ~,~] = fileparts(fullPath); end function [list,listSize] = getFileList(Dir) DirResult = dir( Dir ); list = DirResult(~[DirResult.isdir]); % select files listSize = size(list); end </code></pre> <p>My Python code: </p> <pre><code>def Dir = getScriptDir(): return os.path.dirname(os.path.realpath(__file__) def getFileList(Dir): list = os.listdir(Dir) listSize = len(list) getFileList() = [list, listSize] </code></pre>
0
2016-09-09T14:32:19Z
39,414,082
<p>Remember that you need to return variables from a python-function to get their results. </p> <p>More on how to define your own functions in python: <a href="https://docs.python.org/3/tutorial/controlflow.html#defining-functions" rel="nofollow">https://docs.python.org/3/tutorial/controlflow.html#defining-functions</a></p>
0
2016-09-09T14:36:54Z
[ "python", "matlab", "function", "translation" ]
Translating Matlab code to Python
39,413,998
<p>I need to translate chunks of matlab code into Python. My code seems to be 'unreachable' though. Any idea why this is happening? Also: am I doing it right? I'm a real newbie.</p> <p>Matlab code:</p> <pre><code>function Dir = getScriptDir() fullPath = mfilename('fullpath'); [Dir, ~,~] = fileparts(fullPath); end function [list,listSize] = getFileList(Dir) DirResult = dir( Dir ); list = DirResult(~[DirResult.isdir]); % select files listSize = size(list); end </code></pre> <p>My Python code: </p> <pre><code>def Dir = getScriptDir(): return os.path.dirname(os.path.realpath(__file__) def getFileList(Dir): list = os.listdir(Dir) listSize = len(list) getFileList() = [list, listSize] </code></pre>
0
2016-09-09T14:32:19Z
39,414,121
<p>Your function definitions were incorrect. I have modified the code you provided. You can also consolidate the <code>getScriptDir()</code> functionality into the <code>getFileList()</code> function.</p> <pre><code>import os def getFileList(): dir = os.path.dirname(os.path.realpath(__file__)) list = os.listdir(dir) listSize = len(list) fileList = [list, listSize] return fileList print(getFileList()) </code></pre> <p><strong>Returns: (in my environment)</strong></p> <pre><code>[['test.py', 'test.txt', 'test2.py', 'test2.txt', 'test3.py', 'test4.py', 'testlog.txt', '__pycache__'], 8] </code></pre> <p>Your script functions - including getScriptDir(modified):</p> <pre><code>import os def getScriptDir(): return os.path.dirname(os.path.realpath(__file__)) def getFileList(dir): dir = os.path.dirname(os.path.realpath(__file__)) list = os.listdir(dir) listSize = len(list) fileList = [list, listSize] return fileList dir = getScriptDir() print(getFileList(dir)) </code></pre>
0
2016-09-09T14:38:34Z
[ "python", "matlab", "function", "translation" ]
Translating Matlab code to Python
39,413,998
<p>I need to translate chunks of matlab code into Python. My code seems to be 'unreachable' though. Any idea why this is happening? Also: am I doing it right? I'm a real newbie.</p> <p>Matlab code:</p> <pre><code>function Dir = getScriptDir() fullPath = mfilename('fullpath'); [Dir, ~,~] = fileparts(fullPath); end function [list,listSize] = getFileList(Dir) DirResult = dir( Dir ); list = DirResult(~[DirResult.isdir]); % select files listSize = size(list); end </code></pre> <p>My Python code: </p> <pre><code>def Dir = getScriptDir(): return os.path.dirname(os.path.realpath(__file__) def getFileList(Dir): list = os.listdir(Dir) listSize = len(list) getFileList() = [list, listSize] </code></pre>
0
2016-09-09T14:32:19Z
39,414,162
<p>Your syntax is incorrect. If I'm reading this correctly, you're trying to get the names of the files in the same directory as the script and print the number of files in that list.</p> <hr> <p>Here's an example of how you might do this (based on the program you gave):</p> <pre><code>import os def getFileList(directory = os.path.dirname(os.path.realpath(__file__))): list = os.listdir(directory) listSize = len(list) return [list, listSize] print(getFileList()) </code></pre> <hr> <p>Output example:</p> <pre><code>[['program.py', 'data', 'syntax.py'], 3] </code></pre>
2
2016-09-09T14:40:20Z
[ "python", "matlab", "function", "translation" ]
making pySFML work on linux
39,414,057
<p>This might be stupid question, but I am not sure what do to. Basically I have install sfml-dev (2.3.2) and later python-sfml(2.2) and cython(0.23.4) because by my understanding python-sfml is "not a pure python library. Rather, it is a set of extensions that provide a Pythonic API around a C++ library. As such, every PySFML object is really a wrapped C++ object which can be manipulated through Python methods".</p> <p>Now I have wrote a small program (displaying a window) in python, but I get error 'module' object has no attribute 'RenderWindow'.</p> <p>What am I doing wrong?</p>
-2
2016-09-09T14:35:43Z
39,420,813
<p>kk, I managed to fix it. You need to have these two lines at the beginning of the code when </p> <pre><code> import sfml as sf from sfml import sf #your code in python using the SFML library </code></pre>
0
2016-09-09T23:01:19Z
[ "python", "linux", "sfml" ]
Adding an extra hidden layer using Google's TensorFlow
39,414,060
<p>I am trying to create a multi-label classifier using TensorFlow. Though I'm having trouble adding and connecting hidden layers.</p> <p>I was following this tutorial: <a href="http://jrmeyer.github.io/tutorial/2016/02/01/TensorFlow-Tutorial.html" rel="nofollow">http://jrmeyer.github.io/tutorial/2016/02/01/TensorFlow-Tutorial.html</a></p> <p>The data I'm using is UCI's Iris data, encoded to one-hot:</p> <p>Training X [105,4]</p> <pre><code>5,3.2,1.2,0.2 5.5,3.5,1.3,0.2 4.9,3.1,1.5,0.1 4.4,3,1.3,0.2 5.1,3.4,1.5,0.2 . . . </code></pre> <p>Training Y [105,3]</p> <pre><code>0,0,1 0,0,1 0,0,1 0,0,1 0,0,1 0,0,1 . . . </code></pre> <p>I'm also using testing data X and Y which are [45,4] and [45,3] respectively. </p> <p>Here is my python code:</p> <pre><code>import tensorflow as tf import numpy as np import tarfile import os import matplotlib.pyplot as plt import time ## Import data def csv_to_numpy_array(filePath, delimiter): return np.genfromtxt(filePath, delimiter=delimiter, dtype=None) trainX = csv_to_numpy_array("Iris_training_x.csv", delimiter=",").astype(np.float32) trainY = csv_to_numpy_array("Iris_training_y.csv", delimiter=",").astype(np.float32) testX = csv_to_numpy_array("Iris_testing_x.csv", delimiter=",").astype(np.float32) testY = csv_to_numpy_array("Iris_testing_y.csv", delimiter=",").astype(np.float32) # Data Set Paramaters numFeatures = trainX.shape[1] numLabels = trainY.shape[1] # Training Session Parameters numEpochs = 1000 learningRate = tf.train.exponential_decay(learning_rate=0.008, global_step= 1, decay_steps=trainX.shape[0], decay_rate= 0.95, staircase=True) # Placeholders X=tf.placeholder(tf.float32, [None, numFeatures]) y=tf.placeholder(tf.float32, [None, numLabels]) # Initialize our weights and biases Weights = tf.Variable(tf.random_normal([numFeatures, numLabels], mean=0, stddev=(np.sqrt(6 / numFeatures + numLabels + 1)), name="Weights")) bias = tf.Variable(tf.random_normal([1, numLabels], mean=0, stddev=(np.sqrt(6 / numFeatures + numLabels + 1)), name="bias")) # Prediction algorithm (feedforward) apply_weights_OP = tf.matmul(X, Weights, name="apply_weights") add_bias_OP = tf.add(apply_weights_OP, bias, name="add_bias") activation_OP = tf.nn.sigmoid(add_bias_OP, name="activation") numFeatures = activation_OP apply_weights_OP = tf.matmul(X, Weights, name="apply_weights") add_bias_OP = tf.add(apply_weights_OP, bias, name="add_bias") activation_OP = tf.nn.sigmoid(add_bias_OP, name="activation") init_OP = tf.initialize_all_variables() # Cost function (Mean Squeared Error) cost_OP = tf.nn.l2_loss(activation_OP-y, name="squared_error_cost") # Optimization Algorithm (Gradient Descent) training_OP = tf.train.GradientDescentOptimizer(learningRate).minimize(cost_OP) # Visualize epoch_values=[] accuracy_values=[] cost_values=[] # Turn on interactive plotting plt.ion() # Create the main, super plot fig = plt.figure() # Create two subplots on their own axes and give titles ax1 = plt.subplot("211") ax1.set_title("TRAINING ACCURACY", fontsize=18) ax2 = plt.subplot("212") ax2.set_title("TRAINING COST", fontsize=18) plt.tight_layout() # Create a tensorflow session sess = tf.Session() # Initialize all tensorflow variables sess.run(init_OP) ## Ops for vizualization # argmax(activation_OP, 1) gives the label our model thought was most likely # argmax(y, 1) is the correct label correct_predictions_OP = tf.equal(tf.argmax(activation_OP,1),tf.argmax(y,1)) # False is 0 and True is 1, what was our average? accuracy_OP = tf.reduce_mean(tf.cast(correct_predictions_OP, "float")) # Summary op for regression output activation_summary_OP = tf.histogram_summary("output", activation_OP) # Summary op for accuracy accuracy_summary_OP = tf.scalar_summary("accuracy", accuracy_OP) # Summary op for cost cost_summary_OP = tf.scalar_summary("cost", cost_OP) # Summary ops to check how variables (W, b) are updating after each iteration weightSummary = tf.histogram_summary("Weights", Weights.eval(session=sess)) biasSummary = tf.histogram_summary("biases", bias.eval(session=sess)) # Merge all summaries all_summary_OPS = tf.merge_all_summaries() # Summary writer writer = tf.train.SummaryWriter("summary_logs", sess.graph_def) # Initialize reporting variables cost = 0 diff = 1 # Training epochs for i in range(numEpochs): if i &gt; 1 and diff &lt; .0001: print("change in cost %g; convergence."%diff) break else: # Run training step step = sess.run(training_OP, feed_dict={X: trainX, y: trainY}) # Report occasional stats if i % 10 == 0: #Add epoch to epoch_values epoch_values.append(i) #Generate accuracy stats on test data summary_results, train_accuracy, newCost = sess.run( [all_summary_OPS, accuracy_OP, cost_OP], feed_dict={X: trainX, y: trainY} ) # Add accuracy to live graphing variable accuracy_values.append(train_accuracy) # Add cost to live graphing variable cost_values.append(newCost) #Write summary stats to writer #writer.add_summary(summary_results, i) # Re-assign values for variables diff = abs(newCost - cost) cost = newCost #generate print statements print("step %d, training accuracy %g"%(i, train_accuracy)) print("step %d, cost %g"%(i, newCost)) print("step %d, change in cost %g"%(i, diff)) # Plot progress to our two subplots accuracyLine, = ax1.plot(epoch_values, accuracy_values) costLine, = ax2.plot(epoch_values, cost_values) fig.canvas.draw() #time.sleep(1) # How well do we perform on held-out test data? print("final accuracy on test set: %s" %str(sess.run(accuracy_OP, feed_dict={X: testX, y: testY}))) # Create Saver saver = tf.train.Saver() # Save variables to .ckpt file # saver.save(sess, "trained_variables.ckpt") # Close tensorflow session sess.close() </code></pre> <p>The problem is here: </p> <pre><code># Prediction algorithm (feedforward) apply_weights_OP = tf.matmul(X, Weights, name="apply_weights") add_bias_OP = tf.add(apply_weights_OP, bias, name="add_bias") activation_OP = tf.nn.sigmoid(add_bias_OP, name="activation") numFeatures = activation_OP apply_weights_OP = tf.matmul(activation_OP, Weights, name="apply_weights") add_bias_OP = tf.add(apply_weights_OP, bias, name="add_bias") activation_OP = tf.nn.sigmoid(add_bias_OP, name="activation") </code></pre> <p>My understanding is that the output of one layer should connect to the input of the next one. I just don't know how to modify either the output or input of the layers; it keeps giving me this compatibility error:</p> <pre><code>/usr/bin/python3.5 /home/marco/PycharmProjects/NN_Iris/main Traceback (most recent call last): File "/home/marco/PycharmProjects/NN_Iris/main", line 132, in &lt;module&gt; apply_weights_OP = tf.matmul(activation_OP, Weights, name="apply_weights") File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/math_ops.py", line 1346, in matmul name=name) File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/gen_math_ops.py", line 1271, in _mat_mul transpose_b=transpose_b, name=name) File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/op_def_library.py", line 703, in apply_op op_def=op_def) File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/ops.py", line 2312, in create_op set_shapes_for_outputs(ret) File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/ops.py", line 1704, in set_shapes_for_outputs shapes = shape_func(op) File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/common_shapes.py", line 94, in matmul_shape inner_a.assert_is_compatible_with(inner_b) File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/tensor_shape.py", line 108, in assert_is_compatible_with % (self, other)) ValueError: Dimensions 3 and 4 are not compatible Process finished with exit code 1 </code></pre> <p>Any suggestions on how to properly connect the two hidden layers? Thanks.</p>
0
2016-09-09T14:35:54Z
39,414,552
<p>If you want a fully connected network with one hidden layer and an output layer there is how their shapes should look like:</p> <pre><code># hidden layer weights_hidden = tf.Variable(tf.random_normal([numFeatures, num_nodes]) bias_hidden = tf.Variable(tf.random_normal([num_nodes]) preactivations_hidden = tf.add(tf.matmul(X, weights_hidden), bias_hidden) activations_hidden = tf.nn.sigmoid(preactivations_hidden) # output layer weights_output = tf.Variable(tf.random_normal([num_nodes, numLabels]) bias_output = tf.Variable(tf.random_normal([numLabels]) preactivations_output = tf.add(tf.matmul(activations_hidden, weights_output), bias_output) </code></pre> <p>Where <code>num_nodes</code> is number of nodes in the hidden layer that you select yourself. <code>X</code> is a <code>[105, numFeatures]</code> matrix, <code>weights_hidden</code> is <code>[numFeatures, num_nodes]</code> matrix, so output of first hidden layer is <code>[105, num_nodes]</code>. In the same way, <code>[105, num_nodes]</code> multiplied by <code>[num_nodes, numLabels]</code> yields <code>[105, numLabels]</code> output.</p>
1
2016-09-09T15:01:56Z
[ "python", "machine-learning", "neural-network", "tensorflow" ]
How to convert the following string in python?
39,414,085
<p>Input : UserID/ContactNumber </p> <p>Output: user-id/contact-number</p> <p>I have tried the following code:</p> <pre><code>s ="UserID/ContactNumber" list = [x for x in s] for char in list: if char != list[0] and char.isupper(): list[list.index(char)] = '-' + char fin_list=''.join((list)) print(fin_list.lower()) </code></pre> <p>but the output i got is:</p> <pre><code> user-i-d/-contact-number </code></pre>
4
2016-09-09T14:36:55Z
39,414,269
<p>What about something like that:</p> <pre><code>s ="UserID/ContactNumber" so = '' for counter, char in enumerate(s): if counter == 0: so = char elif char.isupper() and not (s[counter - 1].isupper() or s[counter - 1] == "/"): so += '-' + char else: so += char print(so.lower()) </code></pre> <p>What did I change from your snippet?</p> <ul> <li>You were checking if this is the first char and if it is a upper char.</li> <li><p>I have add a check on the previous char, to not consider when the previous is upper (for the D of ID) or when the previous is \ for the C of Contact.</p></li> <li><p>You are also editing the list <code>list</code> while iterating on it's element, that is dangerous.</p></li> <li>I have instead create an output string to store the new values</li> </ul>
2
2016-09-09T14:45:59Z
[ "python", "python-2.7", "python-3.x" ]
How to convert the following string in python?
39,414,085
<p>Input : UserID/ContactNumber </p> <p>Output: user-id/contact-number</p> <p>I have tried the following code:</p> <pre><code>s ="UserID/ContactNumber" list = [x for x in s] for char in list: if char != list[0] and char.isupper(): list[list.index(char)] = '-' + char fin_list=''.join((list)) print(fin_list.lower()) </code></pre> <p>but the output i got is:</p> <pre><code> user-i-d/-contact-number </code></pre>
4
2016-09-09T14:36:55Z
39,414,310
<p>You could use a <a href="https://docs.python.org/3.5/library/re.html">regular expression</a> with a positive lookbehind assertion:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s ="UserID/ContactNumber" &gt;&gt;&gt; re.sub('(?&lt;=[a-z])([A-Z])', r'-\1', s).lower() 'user-id/contact-number' </code></pre>
7
2016-09-09T14:48:18Z
[ "python", "python-2.7", "python-3.x" ]
How to convert the following string in python?
39,414,085
<p>Input : UserID/ContactNumber </p> <p>Output: user-id/contact-number</p> <p>I have tried the following code:</p> <pre><code>s ="UserID/ContactNumber" list = [x for x in s] for char in list: if char != list[0] and char.isupper(): list[list.index(char)] = '-' + char fin_list=''.join((list)) print(fin_list.lower()) </code></pre> <p>but the output i got is:</p> <pre><code> user-i-d/-contact-number </code></pre>
4
2016-09-09T14:36:55Z
39,415,778
<p>I did something like this</p> <pre><code>s ="UserID/ContactNumber" new = [] words = s.split("/") for word in words: new_word = "" prev = None for i in range(0, len(word)): if prev is not None and word[i].isupper() and word[i-1].islower(): new_word = new_word + "-" + word[i] prev = word[i] continue new_word = new_word + word[i] prev = word[i] new.append(new_word.lower()) print "/".join(new) </code></pre> <blockquote> <p>user-id/contact-number</p> </blockquote>
-1
2016-09-09T16:15:59Z
[ "python", "python-2.7", "python-3.x" ]