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
Python during runtime does not consider a number entered as a int or float
39,497,067
<p>I am a beginner and it might feel like a silly question. </p> <p>I am trying to create a simple program,a temperature converter from Celsius to F*.</p> <p>Which takes:</p> <ol> <li>'quit' for stopping program</li> <li>int values for providing the correct result</li> </ol> <p>Problem: any text value entered by user is handled through try expect error and a while loop which ask them to enter the int value again, but the second time user enters a correct value (which is int) the system considers it as a string and the loop is never ending.</p> <p>Here is my program:</p> <pre><code># Program to convert Celsius to Fahrenheit import time while True: userinput= input(" 1 Enter the temperature in celsius: " "Enter Quit if you want to close the converter") if userinput.lower()=='quit': print('Closing the application. Thanks for using the converter') break try: userinput= float(userinput) except ValueError: print('You cannot enter text, please use numbers') while userinput.lower()!='quit': if type(userinput)!=str: userinput = float(userinput) print(type(userinput)) break else: while type(userinput)==str: userinput = (input(" 2. Oops Enter the temperature in celsius: " "Enter Quit if you want to close the converter")) print(type(userinput)) ## my problem is here even if enter a integer 2 as userinput. i am getting the type userinput as str. Can someone help me type(userinput) userinput=float(userinput) f=userinput*9.0/5+32 print('Your input was:',userinput,'\n'*2,'The corresponding Fareinheit is',f,'\n'*3, '---'*25) </code></pre>
0
2016-09-14T18:15:09Z
39,497,230
<p>You are using three nested while loops here for no obvious resons. When the user enters a wrong value, he gets transferred to the next while loop which never ends. This is a quick and dirty solution.</p> <pre><code># Program to convert Celsius to Fahrenheit import time while True: userinput= input(" 1 Enter the temperature in celsius: " "Enter Quit if you want to close the converter") try: userinput= float(userinput) type(userinput) userinput=float(userinput) f=userinput*9.0/5+32 print('Your input was:',userinput,'\n'*2,'The corresponding Fareinheit is',f,'\n'*3, '---'*25) except ValueError: print('You cannot enter text, please use numbers') if userinput.lower()=='quit': print('Closing the application. Thanks for using the converter') break </code></pre>
0
2016-09-14T18:25:44Z
[ "python", "input" ]
Python during runtime does not consider a number entered as a int or float
39,497,067
<p>I am a beginner and it might feel like a silly question. </p> <p>I am trying to create a simple program,a temperature converter from Celsius to F*.</p> <p>Which takes:</p> <ol> <li>'quit' for stopping program</li> <li>int values for providing the correct result</li> </ol> <p>Problem: any text value entered by user is handled through try expect error and a while loop which ask them to enter the int value again, but the second time user enters a correct value (which is int) the system considers it as a string and the loop is never ending.</p> <p>Here is my program:</p> <pre><code># Program to convert Celsius to Fahrenheit import time while True: userinput= input(" 1 Enter the temperature in celsius: " "Enter Quit if you want to close the converter") if userinput.lower()=='quit': print('Closing the application. Thanks for using the converter') break try: userinput= float(userinput) except ValueError: print('You cannot enter text, please use numbers') while userinput.lower()!='quit': if type(userinput)!=str: userinput = float(userinput) print(type(userinput)) break else: while type(userinput)==str: userinput = (input(" 2. Oops Enter the temperature in celsius: " "Enter Quit if you want to close the converter")) print(type(userinput)) ## my problem is here even if enter a integer 2 as userinput. i am getting the type userinput as str. Can someone help me type(userinput) userinput=float(userinput) f=userinput*9.0/5+32 print('Your input was:',userinput,'\n'*2,'The corresponding Fareinheit is',f,'\n'*3, '---'*25) </code></pre>
0
2016-09-14T18:15:09Z
39,497,248
<p>the problem is here:</p> <pre><code>if type(userinput)!=str: </code></pre> <p>since input returns a string, userinput is always a string: Thus, the above snippet is always false. you should try parsing it as a float like in <a href="http://stackoverflow.com/a/736050/5036612">this answer</a></p>
0
2016-09-14T18:26:38Z
[ "python", "input" ]
Python during runtime does not consider a number entered as a int or float
39,497,067
<p>I am a beginner and it might feel like a silly question. </p> <p>I am trying to create a simple program,a temperature converter from Celsius to F*.</p> <p>Which takes:</p> <ol> <li>'quit' for stopping program</li> <li>int values for providing the correct result</li> </ol> <p>Problem: any text value entered by user is handled through try expect error and a while loop which ask them to enter the int value again, but the second time user enters a correct value (which is int) the system considers it as a string and the loop is never ending.</p> <p>Here is my program:</p> <pre><code># Program to convert Celsius to Fahrenheit import time while True: userinput= input(" 1 Enter the temperature in celsius: " "Enter Quit if you want to close the converter") if userinput.lower()=='quit': print('Closing the application. Thanks for using the converter') break try: userinput= float(userinput) except ValueError: print('You cannot enter text, please use numbers') while userinput.lower()!='quit': if type(userinput)!=str: userinput = float(userinput) print(type(userinput)) break else: while type(userinput)==str: userinput = (input(" 2. Oops Enter the temperature in celsius: " "Enter Quit if you want to close the converter")) print(type(userinput)) ## my problem is here even if enter a integer 2 as userinput. i am getting the type userinput as str. Can someone help me type(userinput) userinput=float(userinput) f=userinput*9.0/5+32 print('Your input was:',userinput,'\n'*2,'The corresponding Fareinheit is',f,'\n'*3, '---'*25) </code></pre>
0
2016-09-14T18:15:09Z
39,497,259
<p>Code after <strong><em>print('You cannot enter text, please use numbers')</em></strong> is not required. Due this code, it is stucked in infinite loop once you enter wrong input</p> <p>Since input is asked in while loop, user input will be asked though the wrong input is given.</p> <p><strong>Code (<em>Check comments</em>):</strong></p> <pre><code>while True: #Get input userinput= input(" 1 Enter the temperature in celsius: " " Enter Quit if you want to close the converter") #Check user wants to quit if userinput.lower()=='quit': print('Closing the application. Thanks for using the converter') break try: #Check type of userinput print "Type is =",type(userinput) #Check user input is number userinput= float(userinput) f=userinput*9.0/5+32 print('Your input was:',userinput,'\n'*2,'The corresponding Fareinheit is',f,'\n'*3, '---'*25) except ValueError: #If user input is not number, then print error message. #After this, again user input will be asked due to while loop. print('You cannot enter text, please use numbers') </code></pre> <p><strong>Output:</strong></p> <pre><code> C:\Users\dinesh_pundkar\Desktop&gt;python c.py 1 Enter the temperature in celsius: Enter Quit if you want to close the conve rter"57" Type is = &lt;type 'str'&gt; ('Your input was:', 57.0, '\n\n', 'The corresponding Fareinheit is', 134.6, '\n\ n\n', '------------------------------------------------------------------------- --') 1 Enter the temperature in celsius: Enter Quit if you want to close the conve rter"asd" Type is = &lt;type 'str'&gt; You cannot enter text, please use numbers 1 Enter the temperature in celsius: Enter Quit if you want to close the conve rter"34" Type is = &lt;type 'str'&gt; ('Your input was:', 34.0, '\n\n', 'The corresponding Fareinheit is', 93.2, '\n\n \n', '-------------------------------------------------------------------------- -') 1 Enter the temperature in celsius: Enter Quit if you want to close the conve rter"quit" Closing the application. Thanks for using the converter C:\Users\dinesh_pundkar\Desktop&gt; </code></pre> <p><em>Also, if you are using Python 2, then use raw_input instead of input. For Python 3 input works.</em></p>
1
2016-09-14T18:27:09Z
[ "python", "input" ]
Python during runtime does not consider a number entered as a int or float
39,497,067
<p>I am a beginner and it might feel like a silly question. </p> <p>I am trying to create a simple program,a temperature converter from Celsius to F*.</p> <p>Which takes:</p> <ol> <li>'quit' for stopping program</li> <li>int values for providing the correct result</li> </ol> <p>Problem: any text value entered by user is handled through try expect error and a while loop which ask them to enter the int value again, but the second time user enters a correct value (which is int) the system considers it as a string and the loop is never ending.</p> <p>Here is my program:</p> <pre><code># Program to convert Celsius to Fahrenheit import time while True: userinput= input(" 1 Enter the temperature in celsius: " "Enter Quit if you want to close the converter") if userinput.lower()=='quit': print('Closing the application. Thanks for using the converter') break try: userinput= float(userinput) except ValueError: print('You cannot enter text, please use numbers') while userinput.lower()!='quit': if type(userinput)!=str: userinput = float(userinput) print(type(userinput)) break else: while type(userinput)==str: userinput = (input(" 2. Oops Enter the temperature in celsius: " "Enter Quit if you want to close the converter")) print(type(userinput)) ## my problem is here even if enter a integer 2 as userinput. i am getting the type userinput as str. Can someone help me type(userinput) userinput=float(userinput) f=userinput*9.0/5+32 print('Your input was:',userinput,'\n'*2,'The corresponding Fareinheit is',f,'\n'*3, '---'*25) </code></pre>
0
2016-09-14T18:15:09Z
39,497,298
<p>In the 1 input, you cast it, in the second one, you never cast.</p> <p>I also noticed, you never actually implemented the "quit" functionality for that loop. This should make your code a bit easier to read.</p> <pre><code>def checkToClose(value): if (value.lower() == 'quit') quit() while True: userinput= input(" 1 Enter the temperature in celsius: " "Enter Quit if you want to close the converter") checkToClose(userinput) try: userinput= float(userinput) catch: continue f = userinput * 9.0 / 5 + 32 print('Your input was:',userinput,'\n'*2,'The corresponding Fareinheit is',f,'\n'*3, '---'*25) </code></pre>
0
2016-09-14T18:29:12Z
[ "python", "input" ]
how to get partial text from a long tag using BeautifulSoup
39,497,104
<p>I have been studying a shopping website, and I want to extract the brandname and the product name from its html code like the following:</p> <p><code>&lt;h1 class="product-name elim-suites"&gt;Chantecaille&lt;span itemprop="name" &gt;Limited Edition Protect the Lion Eye Palette&lt;/span&gt;&lt;/h1&gt;</code></p> <p>I tried: <code>results = soup.findAll("h1", {"class" : "product-name elim-suites"})[0].text</code></p> <p>and got: <code>u'ChantecailleLimited Edition Protect the Lion Eye Palette'</code></p> <p>As you can see, Chantecaille is the brandname, the rest is the product name, but they are now sticked to each other, any suggestion? Thank you!</p>
0
2016-09-14T18:18:21Z
39,497,758
<p>You can use <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#next-sibling-and-previous-sibling" rel="nofollow"><code>previous_sibling</code></a>, which gets the previous node that has the same parent (same level in the parse tree).</p> <p>Also, instead of <code>findAll</code>, when you are searching for a single element, use <code>find</code>.</p> <pre><code>item_span = soup.find("h1", {"class" : "product-name elim-suites"}).find("span") product_name = item_span.previous_sibling brand_name = item_span.text print product_name print brand_name </code></pre> <p>Output:</p> <pre><code>Chantecaille Limited Edition Protect the Lion Eye Palette </code></pre>
0
2016-09-14T18:58:16Z
[ "python", "parsing", "beautifulsoup" ]
how to get partial text from a long tag using BeautifulSoup
39,497,104
<p>I have been studying a shopping website, and I want to extract the brandname and the product name from its html code like the following:</p> <p><code>&lt;h1 class="product-name elim-suites"&gt;Chantecaille&lt;span itemprop="name" &gt;Limited Edition Protect the Lion Eye Palette&lt;/span&gt;&lt;/h1&gt;</code></p> <p>I tried: <code>results = soup.findAll("h1", {"class" : "product-name elim-suites"})[0].text</code></p> <p>and got: <code>u'ChantecailleLimited Edition Protect the Lion Eye Palette'</code></p> <p>As you can see, Chantecaille is the brandname, the rest is the product name, but they are now sticked to each other, any suggestion? Thank you!</p>
0
2016-09-14T18:18:21Z
39,498,119
<p>You could use <em>get_text</em> and pass a character to separate the text or pull the text using <code>. h1.find(text=True, recursive=False)</code> on the <code>h1</code> and pull the text from the <em>span</em> directly:</p> <pre><code>In [1]: h ="""&lt;h1 class="product-name elim-suites"&gt;Chantecaille&lt;span itemprop="name" &gt;Limited Edition Protect the Lion Eye Palette ...: &lt;/span&gt;&lt;/h1&gt;""" In [2]: from bs4 import BeautifulSoup In [3]: soup = BeautifulSoup(h, "html.parser") In [4]: h1 = soup.select_one("h1.product-name.elim-suites") In [5]: print(h1.get_text("\n")) Chantecaille Limited Edition Protect the Lion Eye Palette In [6]: prod, desc = h1.find(text=True, recursive=False), h1.span.text In [7]: print(prod, desc) (u'Chantecaille', u'Limited Edition Protect the Lion Eye Palette\n') </code></pre> <p>Or if text could appear after the <em>span</em> also use <em>find_all</em>:</p> <pre><code>In [8]: h ="""&lt;h1 class="product-name elim-suites"&gt;Chantecaille &lt;span itemprop="name" &gt;Limited Edition Protect the Lion Eye Palette&lt;/span&gt;other text&lt;/h1&gt;""" In [9]: from bs4 import BeautifulSoup In [10]: soup = BeautifulSoup(h, "html.parser") In [11]: h1 = soup.select_one("h1.product-name.elim-suites") In [12]: print(h1.get_text("\n")) Chantecaille Limited Edition Protect the Lion Eye Palette other text In [13]: prod, desc = " ".join(h1.find_all(text=True, recursive=False)), h1.span.text In [14]: In [14]: print(prod, desc) (u'Chantecaille other text', u'Limited Edition Protect the Lion Eye Palette') </code></pre>
0
2016-09-14T19:21:53Z
[ "python", "parsing", "beautifulsoup" ]
Get md5 from Owncloud with Webdav
39,497,139
<p>I'm using Webdav to synchronize files into my Owncloud. All working very fine. </p> <p>But I need get MD5 from files in my result list. And i'm not having success in do this, and I not found nothing on owncloud's documentation. There are a way to receive the md5 file that's stored on owncloud?</p> <p>I imagine it is some setting in ownCloud, or the header of the request should be made. But really I did not find anything on how to achieve this.</p>
0
2016-09-14T18:20:33Z
39,749,299
<p>This is a method to get the hash. (I'm not sure this is the most correct way).</p> <pre><code>\OC\Files\Filesystem::hash('md5',$path_to_file); </code></pre> <p>(ex. 8aed7f13a298b27cd2f9dba91eb0698a)</p>
1
2016-09-28T13:41:50Z
[ "python", "webdav", "owncloud" ]
remove the default select in ForeignKey Field of django admin
39,497,185
<p>There are 150k entries in User model. When i am using it in django-admin without the raw_id_fields it is causing problem while loading all the entries as a select menu of foreign key. is there alternate way so that it could be loaded easily or could become searchable?</p> <p>I have these models as of defined above and there is a User model which is used as ForeignKey in ProfileRecommendation models. The database entry for user model consist of around 150k entries. I don't want default select option for these foreign fields. Instead if can filter them out and load only few entries of the user table. How I can make them searchable like autocomplete suggestion?</p> <p>admin.py</p> <pre><code>class ProfileRecommendationAdmin(admin.ModelAdmin): list_display = ('user', 'recommended_by', 'recommended_text') raw_id_fields = ("user", 'recommended_by') search_fields = ['user__username', 'recommended_by__username',] admin.site.register(ProfileRecommendation, ProfileRecommendationAdmin) </code></pre> <p>models.py</p> <pre><code>class ProfileRecommendation(models.Model): user = models.ForeignKey(User, related_name='recommendations') recommended_by = models.ForeignKey(User, related_name='recommended') recommended_on = models.DateTimeField(auto_now_add=True, null=True) recommended_text = models.TextField(default='') </code></pre>
0
2016-09-14T18:23:05Z
39,522,788
<p>you can use method formfield_for_foreignkey</p> <p>something like this:</p> <pre><code>class ProfileRecommendationAdmin(admin.ModelAdmin): def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "user": kwargs["queryset"] = User.objects.filter(is_superuser=True) return super(ProfileRecommendationAdmin,self).formfield_for_foreignkey(db_field, request, **kwargs) </code></pre> <p>or other way is to override the form for that modeladmin class</p> <pre><code>from django import forms from django.contrib import admin from myapp.models import Person class PersonForm(forms.ModelForm): class Meta: model = Person exclude = ['name'] class PersonAdmin(admin.ModelAdmin): exclude = ['age'] form = PersonForm </code></pre> <p>you can change the widget and use something like the selectize with autocomplete and ajax.</p>
1
2016-09-16T02:03:06Z
[ "python", "django", "django-forms", "django-admin" ]
How to split an SSH address + path?
39,497,199
<p>A Python 3 function receives an SSH address like <code>user@132.243.32.14:/random/file/path</code>. I want to access this file with the <code>paramiko</code> lib, which needs the username, IP address, and file path separately.</p> <p>How can I split this address into these 3 parts, knowing that the input will sometimes omit the username ?</p>
1
2016-09-14T18:23:55Z
39,500,132
<h1>use</h1> <p>not set(p).isdisjoint(set("0123456789$,")) where p is the SSH.</p>
-2
2016-09-14T21:46:51Z
[ "python", "python-3.x", "parsing", "ssh", "ip-address" ]
How to split an SSH address + path?
39,497,199
<p>A Python 3 function receives an SSH address like <code>user@132.243.32.14:/random/file/path</code>. I want to access this file with the <code>paramiko</code> lib, which needs the username, IP address, and file path separately.</p> <p>How can I split this address into these 3 parts, knowing that the input will sometimes omit the username ?</p>
1
2016-09-14T18:23:55Z
39,504,811
<p><code>str.partition</code> and <code>rpartition</code> will do what you want:</p> <pre><code>def ssh_splitter(ssh_connect_string): user_host, _, path = ssh_connect_string.partition(':') user, _, host = user_host.rpartition('@') return user, host, path print(ssh_splitter('user@132.243.32.14:/random/file/path')) print(ssh_splitter('132.243.32.14:/random/file/path')) </code></pre> <p>gives:</p> <pre><code>('user', '132.243.32.14', '/random/file/path') ('', '132.243.32.14', '/random/file/path') </code></pre>
2
2016-09-15T06:58:37Z
[ "python", "python-3.x", "parsing", "ssh", "ip-address" ]
Django migrations - change model from Int to CharField and pre-populate from choice option
39,497,266
<p>In a model, I have an <code>IntegerField</code> that is mapped to a <code>CHOICES</code> tuple. The requirements for that field have changed to the point that updating the options in that tuple will require too frequent maintenance, so I've decided to alter it to a <code>CharField</code></p> <p>Is there a way I can do this inside the migrations, or would it be better to create a new column, update with the appropriate value and delete old column?</p>
1
2016-09-14T18:27:34Z
39,497,453
<p>You've changed your Schema so you'll definitely need a Schema migration and Django will do that for you, with the <code>makemigrations</code> command.</p> <p>But since you're also changing the type of a column, in which is filled with integers and now should be cast to characters, Django won't do that automatically for you and you need to write <a href="https://docs.djangoproject.com/en/1.10/topics/migrations/#data-migrations" rel="nofollow">Data migrations</a>.</p> <p>In my experience, it's better to generate multiple migrations; one that creates a new CharField and then write to this new column via RunPython. Then, run a second migration that removes the original IntegerField and renames the new CharField column as your original column. (I guess it's what you yourself suggested)</p>
1
2016-09-14T18:38:27Z
[ "python", "django", "django-migrations" ]
Django migrations - change model from Int to CharField and pre-populate from choice option
39,497,266
<p>In a model, I have an <code>IntegerField</code> that is mapped to a <code>CHOICES</code> tuple. The requirements for that field have changed to the point that updating the options in that tuple will require too frequent maintenance, so I've decided to alter it to a <code>CharField</code></p> <p>Is there a way I can do this inside the migrations, or would it be better to create a new column, update with the appropriate value and delete old column?</p>
1
2016-09-14T18:27:34Z
39,500,672
<p>To make it more clear, you need 3 migrations.</p> <ol> <li>for Schema migration - adding a new field.</li> <li>for Data migration - You can use the link below which is perfect example for data migration.</li> <li>for Schema migration - deleting the old field.</li> </ol> <p>Here is the example I've followed before doing my first data migrations.</p> <p><a href="https://realpython.com/blog/python/data-migrations/" rel="nofollow">Data Migration Example</a></p>
0
2016-09-14T22:36:06Z
[ "python", "django", "django-migrations" ]
Python- can't connect to my IP
39,497,282
<p>I started learning about computer networks and I tried using sockets in Python. With a little help from a youtube video, I made a very simple Chatting program between a Server and a Client. When I tried to connect the client with 'localhost', it worked just the way I wanted. But when I tried using the IP address (that I found on findmyip.org, for example lets say 12.123.12.123), It just didn't show any sign of a connection. The Server is:</p> <pre><code>import socket import sys def socket_create(): try: global host global port global s host = '' port = 9998 s = socket.socket() except socket.error as msg: print "socket creation error bluhbluh" print "socket created" def socket_bind(): try: global host global port global s print "Binding socket to port" s.bind((host,port)) s.listen(5) except socket.error as msk: print "socket binding error" socket_bind() def socket_accept(): conn,address = s.accept() print "connection has been established" print address[0] send_msg(conn) conn.close() def send_msg(conn): while 1: mess=raw_input() if mess == "quit": conn.send(mess) conn.close() s.close() sys.exit() if len(mess)&gt;0: conn.send(mess) resp=conn.recv(1024) print resp def main(): socket_create() socket_bind() socket_accept() main() </code></pre> <p>The Client is:</p> <pre><code>import socket import os import sys s = socket.socket() host = '12.123.12.123' #replace with 'localhost' for a working version! :D port = 9998 s.connect((host,port)) while 1: data = s.recv(1024) print data if data=="quit": s.close() else: mess=raw_input() s.send(mess) </code></pre> <p>I Had this problem before, and from what I can remember, I didn't manage to fix it then aswell.. I tried port forwarding (at least I THINK I did it right) I hope you could help me Thank you in advance :)</p>
0
2016-09-14T18:28:35Z
39,497,515
<p>You issue is likely related to the network. The IP you posted is what is called a routable IP, the IP exposed to the internet. It normally gets assigned to the WAN side of your ISP provided modem or a router. Machines like your PC will normally live on the LAN side of the network device and will likely be assigned a non-routable IP, these cannot be seen from the internet.</p> <p>When you go to a site that shows your IP it is showing your routable IP, not the one the network device assigned to your machine. To see that address you can type 'ipconfig' in a command window on Windows or 'ifconfig' in a terminal shell on linux and mac. You should see in that output a list of one or more interfaces which contain IP addresses. One will likely have the address of 127.0.0.1 which is equal to localhost and is known as your loopback address. You may see another one starting with 10. or 192. . That address is likely the one assigned to you by the network device. You can try that address and see if your program works.</p>
0
2016-09-14T18:42:16Z
[ "python", "sockets", "networking", "ip" ]
Python - Function Calls involving Object Inheritance
39,497,300
<p>Suppose I have a parent class <code>foo</code> and an inheriting class <code>bar</code> defined as such:</p> <pre><code>class foo(object): def __init__(self, args): for key in args.keys(): setattr(self, key, args[key]) self.subinit() def subunit(self): pass ... </code></pre> <hr> <pre><code>import math class bar(foo): def __init__(self, arg1, arg2, ...): args = locals() del args['self'] super(foo, self).__init__(args) def subunit(self): super(foo, self).subinit() self.arg1 = math.radians(self.arg1) self.arg2 = math.radians(self.arg2) ... ... </code></pre> <p>I have <code>bar</code> overriding the function <code>subinit</code> as it was defined by the parent class <code>foo</code>. However, since I am executing the line <code>self.subinit()</code> from inside the superclass constructor. I'm concerned that the <code>subinit</code> definition for <code>foo</code> will be used instead of the overridden <code>subinit</code> for <code>bar</code>. So my question, then, is this: What is the scope of execution here? If I call <code>subinit</code> from the superclass constructor, will it work in the scope of the totality of the instance and call <code>bar.subinit()</code> or will it work in the scope of the function and call <code>foo.subinit()</code></p>
0
2016-09-14T18:29:17Z
39,497,641
<p>To answer my own question, I ran a test after adjusting the example a little:</p> <pre><code>class foo(object): def __init__(self, args): for key in args.keys(): setattr(self, key, args[key]) self.subinit() def subinit(self): pass </code></pre> <hr> <pre><code>class bar(foo): def __init__(self, arg1, arg2, arg3): args = locals() del args['self'] super(self.__class__, self).__init__(args) def subinit(self): print self.arg1, self.arg2, self.arg3 </code></pre> <p>The scope appears to be in the totality of the object, not just within the superclass. Therefore, <code>bar.subinit()</code> is getting called. Good to know.</p>
0
2016-09-14T18:51:12Z
[ "python", "class", "inheritance", "scope", "initialization" ]
How to loop through a list of dictionary, and print out every key and value pair in Ansible
39,497,351
<p>I have an list of dictionary in Ansible config</p> <pre><code>myList - name: Bob age: 25 - name: Alice age: 18 address: USA </code></pre> <p>I write code as</p> <pre><code>- name: loop through debug: msg ="{{item.key}}:{{item.value}}" with_items: "{{ myList }}" </code></pre> <p>I want to print out like</p> <pre><code>msg: "name:Bob age:25 name:Alice age:18 address:USA" </code></pre> <p>How can I loop through this dictionary and get key and value pairs? Because it don't know what is the key. If I change as {{ item.name }}, ansible will work, but I also want to know key</p>
2
2016-09-14T18:32:42Z
39,497,784
<p>Here is your text: myList - name: Bob age: 25 - name: Alice age: 18 address: USA</p> <p>Here is the Answer:</p> <blockquote> <blockquote> <blockquote> <p>text='''myList - name: Bob age: 25 - name: Alice age: 18 address: USA'''</p> </blockquote> </blockquote> </blockquote> <pre><code>&gt;&gt;&gt; final_text='' </code></pre> <blockquote> <blockquote> <blockquote> <p>for line in text.split('\n'): line1=line.replace(' ','').replace('-','') if 'myList' not in line1: final_text+=line1+' '</p> <p>final_text 'name:Bob age:25 name:Alice age:18 address:USA '</p> </blockquote> </blockquote> </blockquote>
0
2016-09-14T18:59:44Z
[ "python", "ansible" ]
How to loop through a list of dictionary, and print out every key and value pair in Ansible
39,497,351
<p>I have an list of dictionary in Ansible config</p> <pre><code>myList - name: Bob age: 25 - name: Alice age: 18 address: USA </code></pre> <p>I write code as</p> <pre><code>- name: loop through debug: msg ="{{item.key}}:{{item.value}}" with_items: "{{ myList }}" </code></pre> <p>I want to print out like</p> <pre><code>msg: "name:Bob age:25 name:Alice age:18 address:USA" </code></pre> <p>How can I loop through this dictionary and get key and value pairs? Because it don't know what is the key. If I change as {{ item.name }}, ansible will work, but I also want to know key</p>
2
2016-09-14T18:32:42Z
39,498,994
<pre><code>class Person(object): def __init__(self, name, age, address): self.name = name self.age = age self.address = address def __str__(self): # String Representation of your Data. return "name:%s age:%d address:%s" % (self.name, self.age, self.address) </code></pre> <p>then you can have a list of objects you created. I am using some sample data here to create a list of dicts.</p> <pre><code>dict={"name":"Hello World", "age":23, "address":"Test address"} myList = [dict,dict,dict] objList = [] for row in myList: objList.append(str(Person(**row))) result = ' '.join(objList) print(result) </code></pre> <p>It ends out printing: <strong>name:Hello World age:23 address:Test address name:Hello World age:23 address:Test address name:Hello World age:23 address:Test address</strong></p> <p>I was going to do REPR but that is used a bit more differently, and i thought this might be better suited for your needs.</p> <p>If you want to keep it really simple you can do this:</p> <pre><code>dict={"name":"Hello World", "age":23, "address":"Test address"} myList = [dict,dict,dict] objList = [] for row in myList; tmp = [] for k in row: tmp.append("%s:%s" % (k, row[k])) objList.append(" ".join(tmp)) print(" ".join(objList)) </code></pre>
0
2016-09-14T20:19:52Z
[ "python", "ansible" ]
How to loop through a list of dictionary, and print out every key and value pair in Ansible
39,497,351
<p>I have an list of dictionary in Ansible config</p> <pre><code>myList - name: Bob age: 25 - name: Alice age: 18 address: USA </code></pre> <p>I write code as</p> <pre><code>- name: loop through debug: msg ="{{item.key}}:{{item.value}}" with_items: "{{ myList }}" </code></pre> <p>I want to print out like</p> <pre><code>msg: "name:Bob age:25 name:Alice age:18 address:USA" </code></pre> <p>How can I loop through this dictionary and get key and value pairs? Because it don't know what is the key. If I change as {{ item.name }}, ansible will work, but I also want to know key</p>
2
2016-09-14T18:32:42Z
39,500,368
<p>If you want to loop through the list and parse every item separately:</p> <pre><code>- debug: msg="{{ item | dictsort | map('join',':') | join(' ') }}" with_items: "{{ myList }}" </code></pre> <p>Will print:</p> <pre><code>"msg": "age:25 name:Bob" "msg": "address:USA age:18 name:Alice" </code></pre> <p>If you want to join everything into one line, use:</p> <pre><code>- debug: msg="{{ myList | map('dictsort') | sum(start=[]) | map('join',':') | join(' ') }}" </code></pre> <p>This will give:</p> <pre><code>"msg": "age:25 name:Bob address:USA age:18 name:Alice" </code></pre> <p>Keep in mind that dicts are not sorted in Python, so you generally can't expect your items to be in the same order as in yaml-file. In my example, they are sorted by key name after dictsort filter.</p>
3
2016-09-14T22:06:00Z
[ "python", "ansible" ]
How to loop through a list of dictionary, and print out every key and value pair in Ansible
39,497,351
<p>I have an list of dictionary in Ansible config</p> <pre><code>myList - name: Bob age: 25 - name: Alice age: 18 address: USA </code></pre> <p>I write code as</p> <pre><code>- name: loop through debug: msg ="{{item.key}}:{{item.value}}" with_items: "{{ myList }}" </code></pre> <p>I want to print out like</p> <pre><code>msg: "name:Bob age:25 name:Alice age:18 address:USA" </code></pre> <p>How can I loop through this dictionary and get key and value pairs? Because it don't know what is the key. If I change as {{ item.name }}, ansible will work, but I also want to know key</p>
2
2016-09-14T18:32:42Z
39,500,408
<p>You can use a Jinja2 template:</p> <pre><code>vars: myList: - name: Bob age: 25 - name: Alice age: 18 address: USA tasks: - debug: msg="{% for item in myList %}{% if not loop.first %} {% endif %}{% for key, value in item.items() %}{% if not loop.first %} {% endif %}{{ key }}:{{ value}}{% endfor %}{% endfor %}"; </code></pre> <p>Will get you:</p> <blockquote> <p>"msg": "\"age:25 name:Bob age:18 name:Alice address:USA\";"</p> </blockquote> <p>The only problem that remains is the order of elements. I'm not sure what you can do except for naming them <code>1name</code>, <code>2age</code>, <code>3address</code> and sort them alphabetically in the <code>for</code>.</p>
0
2016-09-14T22:09:31Z
[ "python", "ansible" ]
Not all the links are triggering AJAX call, only the first one does in Python Flask Application
39,497,363
<p>I have strange issue with the AJAX that I have implemented for the 'like' and 'unlike' buttons in the python flask application. Below is the code for the .html and .js files.</p> <p>.html</p> <pre><code>{% for article in articles %} {% if article._id in likes %} &lt;button data-toggle="tooltip" title="Unlike" id="unlike-button" value="{{article._id}}"&gt;&lt;span id="user-like-recommend" class="glyphicon glyphicon-heart" aria-hidden="true"&gt;&lt;/span&gt;&lt;/button&gt; {% else %} &lt;button data-toggle="tooltip" title="Like" id="like-button" value="{{article._id}}"&gt;&lt;span id="user-like-recommend" class="glyphicon glyphicon-heart-empty" aria-hidden="true"&gt;&lt;/span&gt;&lt;/button&gt; {% endif %} {% endfor %} </code></pre> <p>.js</p> <pre><code>document.getElementById("like-button").addEventListener("click", function(e) { e.preventDefault(); var article = $('#like-button').val(); var data = {"article": article}; console.log(data); if(data){ $.ajax({ type: 'POST', contentType: 'application/json', url: '/article_liked', dataType : 'json', data : JSON.stringify(data), success: function (response) { success("Article was successfully liked."); } </code></pre> <p>So, only the first active article can have an AJAX call.</p>
0
2016-09-14T18:33:20Z
39,648,574
<p>Well, there are more than one html elements with the same id, so all events will fire only for first of them. </p> <p>Just use classes in html: </p> <pre><code>{% for article in articles %} {% if article._id in likes %} &lt;button class="unlike-button" ...&gt;&lt;/button&gt; {% else %} &lt;button class="like-button" ...&gt;&lt;/button&gt; {% endif %} {% endfor %} </code></pre> <p>And use jquery selector in your JavaScript:</p> <pre><code>$('.like-button').on('click', function(){ var data = { "article": $(this).val()}; ... your ajax code } </code></pre>
1
2016-09-22T20:44:41Z
[ "javascript", "jquery", "python", "ajax" ]
python regex matching between multiple lines and every other match
39,497,375
<p>So I've been playing around with this for a few days and here is what I am looking for and the regex I have now. I have a file in this format (there are some other fields but I have omitted those:</p> <p>I just want to match the bold text </p> <pre><code>ADDR 1 - XXXXXX ADDR 1 - **XXXXXX** ADDR 2 - XXXXXX ADDR 2 - XXXXXX ADDR 1 - XXXXXX ADDR 1 - **XXXXXX** ADDR 2 - XXXXXX ADDR 2 - XXXXXX </code></pre> <p>The regex I have written only matches the first ADDR 1 - XXXXX, but I need to match all instances of the bolded XXXXX.</p> <pre><code>re.findall(r'ADDR 1- .*? ADDR 1-(.*?)(?=ADDR 2-)', lines, re.DOTALL) </code></pre> <p>Any suggestions? I feel like I might be missing something simple, but not sure.</p>
2
2016-09-14T18:33:48Z
39,497,633
<p><strong>Code:</strong></p> <pre><code>import re str= """ ADDR 1 - XXXXXX ADDR 1 - ABCDEF ADDR 2 - XXXXXX ADDR 2 - XXXXXX ADDR 1 - XXXXXX ADDR 1 - UVWXYZ ADDR 2 - XXXXXX ADDR 2 - XXXXXX """ m = re.findall(r".*ADDR\s+1\s+-\s+(.*)",str) print m </code></pre> <p><strong>Output:</strong></p> <pre><code>C:\Users\dinesh_pundkar\Desktop&gt;python c.py ['ABCDEF', 'UVWXYZ'] C:\Users\dinesh_pundkar\Desktop&gt; </code></pre> <p><strong>How it works:</strong></p> <pre><code>.*ADDR\s+1\s+-\s+(.*) </code></pre> <p><img src="https://www.debuggex.com/i/90HlB1jEj2mJ_4V_.png" alt="Regular expression visualization"></p> <p><a href="https://www.debuggex.com/r/90HlB1jEj2mJ_4V_" rel="nofollow">Debuggex Demo</a></p> <p>Lets take a line - <strong>ADDR 1 - XXXXXX ADDR 1 - ABCDEF</strong></p> <ul> <li><code>.*ADDR</code> will match <em>ADDR 1 - XXXXXX ADDR</em>. Since <code>.*</code> match anything and by nature regex are greedy, so to stop I have add <code>ADDR</code> after <code>.*</code></li> <li><code>\s+1\s+-\s+(.*)</code> will match rest <em>1 - ABCDEF</em>. <code>\s+1\s+-\s+</code> is required since we need to match <em>ADDR 1</em> and not <em>ADDR 2</em>. <code>(.*)</code> will match <em>ABCDEF</em> and store it.</li> </ul>
3
2016-09-14T18:50:37Z
[ "python", "regex" ]
python regex matching between multiple lines and every other match
39,497,375
<p>So I've been playing around with this for a few days and here is what I am looking for and the regex I have now. I have a file in this format (there are some other fields but I have omitted those:</p> <p>I just want to match the bold text </p> <pre><code>ADDR 1 - XXXXXX ADDR 1 - **XXXXXX** ADDR 2 - XXXXXX ADDR 2 - XXXXXX ADDR 1 - XXXXXX ADDR 1 - **XXXXXX** ADDR 2 - XXXXXX ADDR 2 - XXXXXX </code></pre> <p>The regex I have written only matches the first ADDR 1 - XXXXX, but I need to match all instances of the bolded XXXXX.</p> <pre><code>re.findall(r'ADDR 1- .*? ADDR 1-(.*?)(?=ADDR 2-)', lines, re.DOTALL) </code></pre> <p>Any suggestions? I feel like I might be missing something simple, but not sure.</p>
2
2016-09-14T18:33:48Z
39,499,216
<p>If wanting to capture every other instance of something then splitting or slicing the string is going to be <strong>much faster</strong> than using regex — the following demonstrates a very <em>basic</em> example:</p> <p><strong><em>split()</em></strong> method:</p> <pre><code>&gt;&gt;&gt; [i.split('ADDR 1 - ')[-1] for i in s.split('\n')[::2]] &gt;&gt;&gt; ['AXXXXZ', 'AXXXXY'] &gt;&gt;&gt; ''' 18.3057999611 seconds - 10000000 iterations ''' </code></pre> <p><strong><em>findall()</em></strong> method:</p> <pre><code>&gt;&gt;&gt; re.findall(".*ADDR\s+1\s+-\s+(.*)", s) &gt;&gt;&gt; ['AXXXXZ', 'AXXXXY'] &gt;&gt;&gt; ''' 77.5003650188 seconds - 10000000 iterations ''' </code></pre> <p>In situations where you know regex isn't absolutely necessary consider using an alternative. Also the regex shown in the accepted answer could be optimized to cut the time nearly in half (eg. <code>re.findall("ADDR 1 .+ - (.+)", s</code>) - <code>37.0185003658 seconds - 10000000 iterations</code>.</p>
1
2016-09-14T20:33:58Z
[ "python", "regex" ]
ImageDraw.draw.line() : SystemError: new style getargs format but argument is not a tuple
39,497,458
<p>I saw multiple questions on this but was not able to find answer to my problem. Basically I just want to draw a line on an image taking the co-ordinates from a external file in python. And here goes my code :</p> <pre><code>import Image, ImageDraw import sys import csv im = Image.open("screen.png") draw = ImageDraw.Draw(im) with open("outputfile.txt") as file: reader = csv.reader(file, delimiter=' ') for row in reader: if row[0] == 'H': print "Horizontal line" endx = row[2] endy = int(row[3])+int(row[1]) elif row[0] == 'V': print "Vertical line" endx = row[2]+row[1] endy = row[3] x = row[2] y = row[3] draw.line((x,y, endx,endy), fill = 1) im.show() </code></pre> <p>Everything works except the line :</p> <pre><code>draw.line((x,y, endx,endy), fill = 1) </code></pre> <p>where i see the following error :</p> <pre><code>File "dummy_test.py", line 21, in &lt;module&gt; draw.line((x,y, endx,endy), fill = 1) File "/Library/Python/2.7/site-packages/PIL-1.1.7-py2.7-macosx-10.10- intel.egg/ImageDraw.py", line 200, in line self.draw.draw_lines(xy, ink, width) SystemError: new style getargs format but argument is not a tuple </code></pre> <p>If i hard-code the values, I see no problems. Issue happens only on the above case. Can anyone point out the problem?</p>
0
2016-09-14T18:38:37Z
39,497,707
<p>Looks like just few <code>int(...)</code> were missing?</p> <pre><code>--- a.py.ORIG 2016-09-14 20:54:47.442291244 +0200 +++ a.py 2016-09-14 20:53:34.990627259 +0200 @@ -1,4 +1,4 @@ -import Image, ImageDraw +from PIL import Image, ImageDraw import sys import csv im = Image.open("screen.png") @@ -8,13 +8,13 @@ for row in reader: if row[0] == 'H': print "Horizontal line" - endx = row[2] + endx = int(row[2]) endy = int(row[3])+int(row[1]) elif row[0] == 'V': print "Vertical line" - endx = row[2]+row[1] - endy = row[3] - x = row[2] - y = row[3] + endx = int(row[2])+int(row[1]) + endy = int(row[3]) + x = int(row[2]) + y = int(row[3]) draw.line((x,y, endx,endy), fill = 1) im.show() </code></pre>
0
2016-09-14T18:55:17Z
[ "python" ]
Get Subset of MultiIndex Pandas DataFrame with Single Index Boolean Indexer
39,497,487
<p>If I have this dataframe</p> <pre><code>import pandas as pd tuples_index = [(1,1990), (2,1999), (2,2002), (3,1992), (3,1994), (3,1996)] index = pd.MultiIndex.from_tuples(tuples_index, names=['id', 'FirstYear']) df = pd.DataFrame([2007, 2006, 2006, 2000, 2000, 2000], index=index, columns=['LastYear'] ) df Out[2]: LastYear id FirstYear 1 1990 2007 2 1999 2006 2002 2006 3 1992 2000 1994 2000 1996 2000 </code></pre> <p>And i'd like to get a subset of the dataframe where the groups based on id are longer than one, I could do this, but its slow:</p> <pre><code>%timeit df.groupby(level=0).filter(lambda x: len(x) &gt; 1) 1000 loops, best of 3: 1.36 ms per loop </code></pre> <p>My df has tens of millions of rows and a huge number of groups as well (most groups are of len 1) so the time adds up. I can get a boolean indexer much more quickly this way:</p> <pre><code>%timeit df.groupby(level=0).size() &gt; 1 1000 loops, best of 3: 364 µs per loop </code></pre> <p>But the boolean indexer only has the id as its index:</p> <pre><code>id 1 False 2 True 3 True </code></pre> <p>I guess maybe I gave more context than necessary, but how can I use a boolean indexer with a single index to get a subset from a dataframe with a MultiIndex? Desired output would be:</p> <pre><code> LastYear id FirstYear 2 1999 2006 2002 2006 3 1992 2000 1994 2000 1996 2000 </code></pre>
3
2016-09-14T18:40:27Z
39,497,629
<p>Use <code>groupby</code> and <code>transform</code> to build a mask</p> <pre><code>df[df.groupby(level=0).transform(np.size).gt(1).values] </code></pre> <p><a href="http://i.stack.imgur.com/Zmwup.png" rel="nofollow"><img src="http://i.stack.imgur.com/Zmwup.png" alt="enter image description here"></a></p>
1
2016-09-14T18:50:05Z
[ "python", "pandas" ]
Angle between two vectors 3D? python
39,497,496
<p>I am new in python. I have two vectors in 3d space, and I want to know the angle between two</p> <p>I tried:</p> <pre><code>vec1=[x1,y1,z1] vec2=[x2,y2,z2] angle=np.arccos(np.dot(vec1,vec2)/(np.linalg.norm(vec1)*np.linalg.norm(vec2))) </code></pre> <p>but when change the order, vec2,vec1 obtain the same angle and no higher. I want to give me a greater angle when the order of the vectors changes.</p>
1
2016-09-14T18:41:15Z
39,497,577
<p>The dot product is commutative, so you'll have to use a different metric. It doesn't care about the order.</p>
0
2016-09-14T18:46:49Z
[ "python", "python-2.7", "numpy", "computational-geometry" ]
Angle between two vectors 3D? python
39,497,496
<p>I am new in python. I have two vectors in 3d space, and I want to know the angle between two</p> <p>I tried:</p> <pre><code>vec1=[x1,y1,z1] vec2=[x2,y2,z2] angle=np.arccos(np.dot(vec1,vec2)/(np.linalg.norm(vec1)*np.linalg.norm(vec2))) </code></pre> <p>but when change the order, vec2,vec1 obtain the same angle and no higher. I want to give me a greater angle when the order of the vectors changes.</p>
1
2016-09-14T18:41:15Z
39,497,695
<p>Since the dot product is <a href="https://en.wikipedia.org/wiki/Dot_product#Properties" rel="nofollow">commutative</a>, simply reversing the order you put the variables into the function will not work. </p> <p>If your objective is to find the obtuse(larger) angle rather than the acute(smaller) one, subtract the value returned by your function from 360 degrees. Since you seem to have a criteria for when you want to switch the variables around, you should use that same criteria to determine when to subtract your found value from 360. This will give you the value you are looking for in these cases. </p>
0
2016-09-14T18:54:39Z
[ "python", "python-2.7", "numpy", "computational-geometry" ]
Angle between two vectors 3D? python
39,497,496
<p>I am new in python. I have two vectors in 3d space, and I want to know the angle between two</p> <p>I tried:</p> <pre><code>vec1=[x1,y1,z1] vec2=[x2,y2,z2] angle=np.arccos(np.dot(vec1,vec2)/(np.linalg.norm(vec1)*np.linalg.norm(vec2))) </code></pre> <p>but when change the order, vec2,vec1 obtain the same angle and no higher. I want to give me a greater angle when the order of the vectors changes.</p>
1
2016-09-14T18:41:15Z
39,528,809
<p>What you are asking is impossible as the plane that contains the angle can be oriented two ways and nothing in the input data gives a clue about it.</p> <p>All you can do is to compute the smallest angle between the vectors (or its complement to 360°), and swapping the vectors can't have an effect.</p> <p>The dot product isn't guilty here, this is a geometric dead-end.</p>
1
2016-09-16T10:06:00Z
[ "python", "python-2.7", "numpy", "computational-geometry" ]
Angle between two vectors 3D? python
39,497,496
<p>I am new in python. I have two vectors in 3d space, and I want to know the angle between two</p> <p>I tried:</p> <pre><code>vec1=[x1,y1,z1] vec2=[x2,y2,z2] angle=np.arccos(np.dot(vec1,vec2)/(np.linalg.norm(vec1)*np.linalg.norm(vec2))) </code></pre> <p>but when change the order, vec2,vec1 obtain the same angle and no higher. I want to give me a greater angle when the order of the vectors changes.</p>
1
2016-09-14T18:41:15Z
39,533,085
<p>Use a function to help you choose which angle do you want. In the beggining of your code, write:</p> <pre><code>def angle(v1, v2, acute): # v1 is your firsr vector # v2 is your second vector angle = np.arccos(np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))) if (acute == True): return angle else: return 2 * np.pi - angle </code></pre> <p>Then, when you want to calculate an angle (in radians) in your program just write</p> <pre><code>angle(vec1, vec2, 'True') </code></pre> <p>for acute angles, and</p> <pre><code>angle(vec2, vec1, 'False') </code></pre> <p>for obtuse angles.</p> <p>For example:</p> <pre><code>vec1 = [1, -1, 0] vec2 = [1, 1, 0] #I am explicitly converting from radian to degree print(180* angle(vec1, vec2, True)/np.pi) #90 degrees print(180* angle(vec2, vec1, False)/np.pi) #270 degrees </code></pre>
0
2016-09-16T13:46:40Z
[ "python", "python-2.7", "numpy", "computational-geometry" ]
is python dict.items() threadsafe?
39,497,583
<p>Python raises an exception if a dictionary changes its size during iteration using <code>iteritems()</code>.</p> <p>I am hit by this problem since my program is <em>multithreaded</em> and there are cases that I need to iterate over the <code>dict</code> while another thread is adding keys into the <code>dict</code>.</p> <p>Fortunately, I don't need the iteration to be very precise on every element in the <code>dict</code>. Therefore I am thinking to use <code>items()</code> instead of <code>iteritems()</code> to do the iteration. I think <code>items()</code> makes a static snapshot of the <code>dict</code> and I would work around the problem. </p> <p>My question is: does <code>items()</code> raises an exception if the <code>dict</code> size is changing at the same time with <code>items()</code> execution?</p> <p>thanks</p>
0
2016-09-14T18:47:24Z
39,505,359
<p>As the excellent comments noted:</p> <ol> <li><p>This is not thread safe.</p></li> <li><p>You should really use a lock when doing such things.</p></li> </ol> <p>It is possible to see this in <a href="https://svn.python.org/projects/python/trunk/Objects/dictobject.c" rel="nofollow">the CPython source code, <code>dictobject.c</code></a>:</p> <p>If you look at the function</p> <pre><code>static PyObject * dict_items(register PyDictObject *mp) </code></pre> <p>which is used for <code>items</code>, you can see that (after some clever pre-allocation for the results), it basically iterates over the array <code>mp-&gt;ma_table</code> (using a mask to see where there are entries).</p> <p>Now if you look at the function</p> <pre><code>static int dictresize(PyDictObject *mp, Py_ssize_t minused) </code></pre> <p>which is used when the table needs to be resized, then you can see that <code>ma_table</code>'s elements can be moved into a completely different buffer, and then it can be freed using <a href="https://docs.python.org/3.1/c-api/memory.html#PyMem_Free" rel="nofollow"><code>PYMem_Free</code></a>.</p> <p>So, you have a very real risk of accessing garbage memory, if things are done concurrently without synchronization.</p>
0
2016-09-15T07:31:19Z
[ "python", "multithreading", "dictionary" ]
can I have a global variable in python without declaring it as global?
39,497,628
<p>I want some sort of a global state that maintains the current number, as well as a function to generate the next number.</p> <p>I can write a generator to give me the next number. </p> <pre><code> def gen(self, n): yield n yield n + 1 </code></pre> <p>but what is a clean way to maintain its state? I do not want to simply have a global variable. Is there a better way to do this? or is that my only option?</p> <p>I tried to make a class like this:</p> <pre><code>class Count: """ Represents the counter which generates variables """ def __init__(self, curr=0): """ :param curr: the current integer """ self.curr = curr def gen(self): """ A generator for the next number :return: generator """ self.curr += 1 yield self.curr yield self.curr + 1 </code></pre> <p>but this will not work, because every time I create Count(), it will reset my counter which I don't want. </p>
0
2016-09-14T18:50:04Z
39,497,973
<p>If my understanding is correct, to eliminate the <code>global</code> counter you could create a closure for you variable and return a function that increments it. </p> <p>The original function <code>counter</code> is called only once, consecutive calls simply increment the counter:</p> <pre><code>def count(n): c = n def incr(): nonlocal c c += 1 print(c) return c return incr </code></pre> <p><code>count</code> is initialized with some state <code>n</code> and <code>incr</code> references that state in consecutive calls:</p> <pre><code>&gt;&gt;&gt; f = count(2) &gt;&gt;&gt; f() 3 &gt;&gt;&gt; f() 4 &gt;&gt;&gt; f() 5 </code></pre>
0
2016-09-14T19:11:12Z
[ "python", "python-3.x", "generator", "counter" ]
can I have a global variable in python without declaring it as global?
39,497,628
<p>I want some sort of a global state that maintains the current number, as well as a function to generate the next number.</p> <p>I can write a generator to give me the next number. </p> <pre><code> def gen(self, n): yield n yield n + 1 </code></pre> <p>but what is a clean way to maintain its state? I do not want to simply have a global variable. Is there a better way to do this? or is that my only option?</p> <p>I tried to make a class like this:</p> <pre><code>class Count: """ Represents the counter which generates variables """ def __init__(self, curr=0): """ :param curr: the current integer """ self.curr = curr def gen(self): """ A generator for the next number :return: generator """ self.curr += 1 yield self.curr yield self.curr + 1 </code></pre> <p>but this will not work, because every time I create Count(), it will reset my counter which I don't want. </p>
0
2016-09-14T18:50:04Z
39,498,290
<p>Or you can use the next(generator) function.</p> <pre><code>def num_gen(): n=1 while n: yield n n += 1 </code></pre> <p>Then</p> <pre><code>&gt;&gt;my_gen = num_gen() &gt;&gt;next(my_gen) 1 &gt;&gt;next(my_gen) 2 </code></pre> <p>And so forth. Whenever a generator yields a value, the state of the generator is stored so that it can resume execution later.</p>
0
2016-09-14T19:32:34Z
[ "python", "python-3.x", "generator", "counter" ]
can I have a global variable in python without declaring it as global?
39,497,628
<p>I want some sort of a global state that maintains the current number, as well as a function to generate the next number.</p> <p>I can write a generator to give me the next number. </p> <pre><code> def gen(self, n): yield n yield n + 1 </code></pre> <p>but what is a clean way to maintain its state? I do not want to simply have a global variable. Is there a better way to do this? or is that my only option?</p> <p>I tried to make a class like this:</p> <pre><code>class Count: """ Represents the counter which generates variables """ def __init__(self, curr=0): """ :param curr: the current integer """ self.curr = curr def gen(self): """ A generator for the next number :return: generator """ self.curr += 1 yield self.curr yield self.curr + 1 </code></pre> <p>but this will not work, because every time I create Count(), it will reset my counter which I don't want. </p>
0
2016-09-14T18:50:04Z
39,498,527
<p>If you want to maintain state across multiple instances of <code>Count</code>, then use a variable in the class scope, and reference it with the <code>Count.</code> prefix, like this:</p> <pre><code>class Count: curr = 0 def __init__(self, startWith = None): if startWith is not None: Count.curr = startWith - 1 def gen(self): while True: Count.curr += 1 yield Count.curr </code></pre> <p>Note that if you want to maintain state, the constructor should allow for the possibility to <em>not</em> reset the counter, but leave it untouched.</p> <p>As a side note, you might be interested in letting the generator generate a never ending series as shown above.</p> <p>Here is how you could use the above class:</p> <pre><code># Get generator that starts with 2 gen = Count(2).gen(); print (next(gen)); # -&gt; 2 print (next(gen)); # -&gt; 3 print (next(gen)); # -&gt; 4 # Get a generator that continues ... gen2 = Count().gen(); print (next(gen2)); # -&gt; 5 # We can still use the previous generator also: print (next(gen)); # -&gt; 6 # Start with 0: gen3 = Count(0).gen(); print (next(gen3)); # -&gt; 0 # Other generators follow suit: print (next(gen)); # -&gt; 1 print (next(gen2)); # -&gt; 2 </code></pre>
0
2016-09-14T19:47:39Z
[ "python", "python-3.x", "generator", "counter" ]
How to close the chrome window that is opened by applying the code webbrowser.open?
39,497,632
<p>I imported webbrowser in the very beginning of this file. The whole code was like this in the below.</p> <pre><code>import time import webbrowser break_times = 3 break_count = 0 print ("Program started at: " + time.ctime()) while break_count &lt; break_times : time.sleep(5) webbrowser.open("https://www.youtube.com/watch?v=m69d-KNi2Q0") break_count = break_count + 1 </code></pre> <p>But I am stuck here. The code opens my chrome browser but I couldn't close it using code. Any suggestion would be helpful.</p> <p>Thank you.</p>
1
2016-09-14T18:50:36Z
39,497,985
<p>Try using <code>selenium</code>.</p> <pre><code>import time from selenium import webdriver break_times = 3 break_count = 0 browser = webdriver.Firefox() print("Program started at: " + time.ctime()) while break_count &lt; break_times: time.sleep(5) browser.get("https://www.youtube.com/watch?v=m69d-KNi2Q0") break_count = break_count + 1 browser.close() </code></pre>
0
2016-09-14T19:12:01Z
[ "python", "import" ]
How to call class methods from different instantiations in parallel in Python 2.7?
39,497,652
<p>I have a class which contains functions that perform calculations. If I have several instances of these objects, how do I make the calculations to go in parallel?</p> <pre><code>class SomeClass: def __init__(self, arg): .... def compute(self): .... </code></pre> <p>And then in a different script:</p> <pre><code>from multiprocessing import Pool from wherever import SomeClass g1 = SomeClass(arg1) g2 = SomeClass(arg2) pool = Pool(processes = 2) </code></pre> <p>How do I make one of the workers do g1.compute() and the other g2.compute()?</p>
1
2016-09-14T18:51:38Z
39,498,744
<p>On python2.7 you'll have to define a worker function that calls the compute method on the given argument, then you can use it with <code>pool.map()</code>:</p> <pre><code>def call_compute(o): return o.compute() ... result = pool.map(call_compute, [g1, g2]) </code></pre> <p>On python3 (tested on 3.5) it's possible to use <code>pool.map(SomeClass.comute, [g1, g2])</code> instead because pickling instance methods is supported there.</p>
0
2016-09-14T20:01:45Z
[ "python", "python-2.7", "multiprocessing", "python-multiprocessing" ]
Multiple Inheritance With Same Method Names but Different Arguments Creates TypeError
39,497,656
<p>I have a four distinct classes. There is a main base/parent class, two main classes that inherit from this parent class, and another class that inherits from both of these main classes. If I have a method with the same name but a different number of arguments as a parent class, I get a TypeError.</p> <pre><code># Example class Parent(object): def check(self, arg): tmp = { 'one': False, 'two': False } try: if 'one' in arg: tmp['one'] = True if 'two' in arg: tmp['two'] = True except TypeError: pass return tmp class Child(Parent): def check(self, arg): return Parent.check(self, arg)['one'] def method(self, arg): if self.check(arg): print 'One!' class ChildTwo(Parent): def check(self, arg): return Parent.check(self, arg)['two'] def method(self, arg): if self.check(arg): print 'Two!' class ChildThree(Child, ChildTwo): def check(self, arg, arg2): print arg2 return Child.check(self, arg) def method(self, arg): if self.check(arg, 'test'): print 'One!' ChildTwo.method(self, arg) test = ChildThree() test = test.method('one and two') </code></pre> <blockquote> <p>runfile('untitled6.py', wdir='./Documents')<br> test<br> One!<br> Traceback (most recent call last):<br> File "&lt; stdin >", line 1, in &lt; module ><br> File "C:\Users\py\AppData\Local\Continuum\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 714, in runfile<br> execfile(filename, namespace)<br> File "C:\Users\py\AppData\Local\Continuum\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 74, in execfile<br> exec(compile(scripttext, filename, 'exec'), glob, loc)<br> File "untitled6.py", line 49, in <br> test = test.method('one and two')<br> File "untitled6.py", line 46, in method<br> ChildTwo.method(self, arg)<br> File "untitled6.py", line 34, in method<br> if self.check(arg): </p> <p>TypeError: check() takes exactly 3 arguments (2 given)</p> </blockquote> <p>However, when I remove the second argument from the 'check' method in 'ChildThree', it seems to work fine:</p> <pre><code>class ChildThree(Child, ChildTwo): def check(self, arg): return Child.check(self, arg) def method(self, arg): if self.check(arg): print 'One!' ChildTwo.method(self, arg) </code></pre> <blockquote> <p>runfile('untitled6.py', wdir='./Documents')<br> One!<br> Two!</p> </blockquote> <p>I am fairly new to classes/inheritance, so I am not sure why an extra argument causes a TypeError even though it calls the parent class method with a single argument.</p>
1
2016-09-14T18:51:50Z
39,497,749
<p>Consider this line:</p> <pre><code>ChildTwo.method(self, arg) </code></pre> <p>You passed in <code>self</code> explicitly. <code>self</code> here is a reference to a <code>ChildThree</code> instance. Later, in the body of <code>ChildTwo.method</code>:</p> <pre><code>if self.check(arg): </code></pre> <p>It's the same <code>self</code> we're talking about here; <code>self</code> is still a reference on your <code>ChildThree</code> instance.</p> <p>It looks like you expected <code>self</code> to do something magical, but it doesn't - it's just a plain old name. For it to refer to a <code>ChildTwo</code> instance it would have had to be called like a bound method. Compare and contrast:</p> <ul> <li><code>my_child_two.method(arg)</code> &lt;-- "self" gets passed implicitly by descriptor protocol </li> <li><code>ChildTwo.method(self, arg)</code> &lt;-- "self" is just whatever it is </li> </ul>
1
2016-09-14T18:57:44Z
[ "python", "class", "inheritance", "typeerror" ]
Multiple Inheritance With Same Method Names but Different Arguments Creates TypeError
39,497,656
<p>I have a four distinct classes. There is a main base/parent class, two main classes that inherit from this parent class, and another class that inherits from both of these main classes. If I have a method with the same name but a different number of arguments as a parent class, I get a TypeError.</p> <pre><code># Example class Parent(object): def check(self, arg): tmp = { 'one': False, 'two': False } try: if 'one' in arg: tmp['one'] = True if 'two' in arg: tmp['two'] = True except TypeError: pass return tmp class Child(Parent): def check(self, arg): return Parent.check(self, arg)['one'] def method(self, arg): if self.check(arg): print 'One!' class ChildTwo(Parent): def check(self, arg): return Parent.check(self, arg)['two'] def method(self, arg): if self.check(arg): print 'Two!' class ChildThree(Child, ChildTwo): def check(self, arg, arg2): print arg2 return Child.check(self, arg) def method(self, arg): if self.check(arg, 'test'): print 'One!' ChildTwo.method(self, arg) test = ChildThree() test = test.method('one and two') </code></pre> <blockquote> <p>runfile('untitled6.py', wdir='./Documents')<br> test<br> One!<br> Traceback (most recent call last):<br> File "&lt; stdin >", line 1, in &lt; module ><br> File "C:\Users\py\AppData\Local\Continuum\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 714, in runfile<br> execfile(filename, namespace)<br> File "C:\Users\py\AppData\Local\Continuum\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 74, in execfile<br> exec(compile(scripttext, filename, 'exec'), glob, loc)<br> File "untitled6.py", line 49, in <br> test = test.method('one and two')<br> File "untitled6.py", line 46, in method<br> ChildTwo.method(self, arg)<br> File "untitled6.py", line 34, in method<br> if self.check(arg): </p> <p>TypeError: check() takes exactly 3 arguments (2 given)</p> </blockquote> <p>However, when I remove the second argument from the 'check' method in 'ChildThree', it seems to work fine:</p> <pre><code>class ChildThree(Child, ChildTwo): def check(self, arg): return Child.check(self, arg) def method(self, arg): if self.check(arg): print 'One!' ChildTwo.method(self, arg) </code></pre> <blockquote> <p>runfile('untitled6.py', wdir='./Documents')<br> One!<br> Two!</p> </blockquote> <p>I am fairly new to classes/inheritance, so I am not sure why an extra argument causes a TypeError even though it calls the parent class method with a single argument.</p>
1
2016-09-14T18:51:50Z
39,498,049
<p>This type of inheritance is called <a href="https://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem" rel="nofollow">"The Diamond Problem"</a>. It is a topic for itself, so I'll explain on a simpler case:</p> <pre><code>class C1(object): def check(self, arg): return 1 def method(self, arg): return self.check(arg) class C2(C1): def check(self, arg1, arg2): # this overrides C1.check! return x + C1.check(self, arg1) c2 = C2() c2.method(55) # fails </code></pre> <p><code>C2.check</code> overrides <code>C1.check</code> on all C2 instances. Therefore, when <code>self.check(arg)</code> is called from <code>method</code>, it calls <code>C2.check</code> for instances of C2. That will fail because <code>C2.check</code> takes two arguments.</p> <p>How to resolve that? When overriding methods, do not change their signature (number and type of received arguments and type of return value), or you'll get in trouble.</p> <p><em>[more advanced]</em> You could have more freedom with functions which take <a href="https://docs.python.org/2/faq/programming.html#how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another" rel="nofollow"><code>*args</code> and <code>**kwargs</code></a>.</p> <hr> <p>Besides that, I see that <code>ChildThree.check</code> calls <code>Child.check</code> which calls <code>Parent.check</code>, but noone calls <code>ChildTwo.check</code>. That cannot be right. You should either call the method on all base classes (and risk calling the Parent implementation twice, which may even be right here), or use <a href="https://docs.python.org/2/library/functions.html#super" rel="nofollow"><code>super()</code></a>.</p>
1
2016-09-14T19:16:25Z
[ "python", "class", "inheritance", "typeerror" ]
Python file path based on dates
39,497,717
<p>Creating a script that will automatically process the file path for that day, perform some actions, and then save to the same directory. </p> <p>Folder structure is based on Date:</p> <p><code>maindir</code> -> <code>year</code> -> <code>month</code> -> files for that month.</p> <p>So far, my approach would be:</p> <pre><code>year = time.strftime("%Y") month = time.strftime("%B") dir = parse('C:\maindir' + '\' + str(year) + '\' + str(month)) os.chdir(dir) </code></pre> <p>However, I would like to reuse this with <code>os.makedirs</code> later so that the folder structure will be automatically generated as I go.</p> <p>Or would it be better to make a method which parses the dir path so that I can call that as in:</p> <pre><code>if not os.path.exists(method): try: os.makedirs(os.path.dirname(method)) </code></pre> <p><strong>Update:</strong></p> <p>Happened to find this discussion which helped a lot - <a href="http://stackoverflow.com/questions/17429044/constructing-absolute-path-with-os-join">constructing absolute path with os.join()</a></p> <pre><code>netdrive="\\network.com\mainfolder$" year = time.strftime("%Y") month = time.strftime("%B") path=path.abspath(path.join(os.sep,netdrive,year,month)) if not os.path.exists(path): os.makedirs(path) os.chdir(path) </code></pre> <p>So, I have made some progress with this - however, now I'm having the issue of recognizing the net drive as currently this uses the <code>C:/</code> default as part of the <code>path.abspath</code>. How can I override that to a new root drive independent of what the drive is mapped to? <code>D:/</code> for one user, <code>E:/</code> for second - etc.</p>
0
2016-09-14T18:55:51Z
39,499,003
<p>Since the path contains only Year and Month, the directory would remain same for 30 consecutive days on average.</p> <p>Hence it would be better to check if the directory already exists, before creating it.</p> <pre><code>if not os.path.exists(directory): os.makedirs(directory) </code></pre>
1
2016-09-14T20:20:32Z
[ "python", "windows" ]
Understanding index out of range Python
39,497,726
<p>Hello thanks in advance.</p> <p>i can get my code to work but i need help understanding what the problem is.</p> <p>i am doing a test questions on codingbat and came across this one.</p> <p>Return the number of times that the string "code" appears anywhere in the given string, accept any letter for the 'd', so "cope" and "cooe" count.</p> <blockquote> <p>count_code('aaacodebbb') → 1 count_code('codexxcode') → 2 count_code('cozexxcope') → 2</p> </blockquote> <p>now after a few tries i got my code to work </p> <blockquote> <pre><code>def count_code(str): count =0 for i in range(len(str)): if str[i:i+2] == 'co' and str[i+3:i+4]=='e': count += 1 return count print(count_code('codecodecode')) </code></pre> </blockquote> <p>^ I understand this (and I could have done regular expressions but i can not import) </p> <p>But my first attempt was this:</p> <blockquote> <pre><code>def count_code(str): count =0 for i in range(len(str)): if str[i:i+2] == 'co' and str[i+3]=='e': count += 1 return count print(count_code('codecodecode')) </code></pre> </blockquote> <p>the browser (the browser saves, compiles, and runs) gave me an index out of range error and after testing i understand why. when i = 9 ... i +9 = 12 which is longer than the string so out of range i get it. But i ran the 2nd code in Aptana and it worked fine so is the second bad code or not? </p> <p>but the code that works containing str[i+3:i+4] == 'e' does not go out of range and i do not understand why. when i reaches counter 9 then it would be str[12:13] which is longer than the string. </p> <p>thanks for the help still learning basics and want to make sure i have a good foundation.</p>
-1
2016-09-14T18:56:11Z
39,497,946
<p>This is just a feature of slicing strings in Python. Notice that</p> <pre><code>stringvar = 'aaacodebbb' stringvar[10000:10001] </code></pre> <p>returns an empty string value and no error.</p> <p>However, </p> <pre><code>stringvar[10000] </code></pre> <p><em>will</em> return an error.</p> <p>As explained in the answer of <a href="http://stackoverflow.com/a/509295/6815126">this question</a>:</p> <blockquote> <p>Python is kind to the programmer if there are fewer items than you ask for. For example, if you ask for a[:-2] and a only contains one element, you get an empty list instead of an error. Sometimes you would prefer the error, so you have to be aware that this may happen.</p> </blockquote> <p>In the examples you've given, having python <em>not</em> return an "index out of range" error is ideal.</p>
0
2016-09-14T19:09:47Z
[ "python" ]
Understanding index out of range Python
39,497,726
<p>Hello thanks in advance.</p> <p>i can get my code to work but i need help understanding what the problem is.</p> <p>i am doing a test questions on codingbat and came across this one.</p> <p>Return the number of times that the string "code" appears anywhere in the given string, accept any letter for the 'd', so "cope" and "cooe" count.</p> <blockquote> <p>count_code('aaacodebbb') → 1 count_code('codexxcode') → 2 count_code('cozexxcope') → 2</p> </blockquote> <p>now after a few tries i got my code to work </p> <blockquote> <pre><code>def count_code(str): count =0 for i in range(len(str)): if str[i:i+2] == 'co' and str[i+3:i+4]=='e': count += 1 return count print(count_code('codecodecode')) </code></pre> </blockquote> <p>^ I understand this (and I could have done regular expressions but i can not import) </p> <p>But my first attempt was this:</p> <blockquote> <pre><code>def count_code(str): count =0 for i in range(len(str)): if str[i:i+2] == 'co' and str[i+3]=='e': count += 1 return count print(count_code('codecodecode')) </code></pre> </blockquote> <p>the browser (the browser saves, compiles, and runs) gave me an index out of range error and after testing i understand why. when i = 9 ... i +9 = 12 which is longer than the string so out of range i get it. But i ran the 2nd code in Aptana and it worked fine so is the second bad code or not? </p> <p>but the code that works containing str[i+3:i+4] == 'e' does not go out of range and i do not understand why. when i reaches counter 9 then it would be str[12:13] which is longer than the string. </p> <p>thanks for the help still learning basics and want to make sure i have a good foundation.</p>
-1
2016-09-14T18:56:11Z
39,497,960
<p>When you say <code>mystring[x:y]</code>, that is called <em>slicing</em>, which has built-in bounds checking.</p> <p>But a plain list index such as <code>mystring[99]</code> does not have built-in bounds checking, so you get an <code>IndexError</code>.</p>
0
2016-09-14T19:10:33Z
[ "python" ]
Unsupported operand type for - list and list
39,497,815
<p>I am using an older version of python which doesnt have support to subtract dict's.</p> <pre><code>d1={'ab': ['3'], 'hij': ['1200']} d2={'ab': ['1'], 'hij': ['600']} </code></pre> <p>Basically my code looks like this:</p> <pre><code> for key in d1.keys(): if key in d2: d3[key]=d1[key]-d2[key] </code></pre> <p>output should be like</p> <pre><code>d2={'ab': ['2'], 'hij': ['600']} </code></pre> <p>It returns unsupported operand type for - : list and list. Any ideas on how to get around this</p>
-3
2016-09-14T19:01:32Z
39,497,942
<p>Try the following:</p> <pre><code>d1={'ab': ['3'], 'hij': ['1200']} d2={'ab': ['1'], 'hij': ['600']} d3={} for key in d1.keys(): if key in d2: d3[key] = [str(int(d1[key][i]) - int(d2[key][i])) for i in xrange(len(d1[key]))] print d3 </code></pre>
0
2016-09-14T19:09:30Z
[ "python", "python-2.7" ]
Unsupported operand type for - list and list
39,497,815
<p>I am using an older version of python which doesnt have support to subtract dict's.</p> <pre><code>d1={'ab': ['3'], 'hij': ['1200']} d2={'ab': ['1'], 'hij': ['600']} </code></pre> <p>Basically my code looks like this:</p> <pre><code> for key in d1.keys(): if key in d2: d3[key]=d1[key]-d2[key] </code></pre> <p>output should be like</p> <pre><code>d2={'ab': ['2'], 'hij': ['600']} </code></pre> <p>It returns unsupported operand type for - : list and list. Any ideas on how to get around this</p>
-3
2016-09-14T19:01:32Z
39,497,957
<p>Get the first values from the list and cast them to <code>int</code>s.</p> <pre><code>d1 = {'ab': ['3'], 'hij': ['1200']} d2 = {'ab': ['1'], 'hij': ['600']} d3 = {} for key in d1.keys(): if key in d2: d3[key] = int(d1[key][0]) - int(d2[key][0]) print d3 </code></pre> <p>Output:</p> <pre><code>{'hij': 600, 'ab': 2} </code></pre> <hr> <p>To support floats, you need to cast to <code>float</code>. If you want to have 4 digits of precision, then you can use the <a href="https://docs.python.org/2/library/functions.html#round" rel="nofollow"><code>round</code></a> function.</p> <pre><code>d1 = {'ab': ['3.2462353'], 'hij': ['1200.223353']} d2 = {'ab': ['1.346733'], 'hij': ['600.252341']} d3 = {} for key in d1.keys(): if key in d2: num1 = float(d1[key][0]) d3[key] = round(float(d1[key][0]) - float(d2[key][0]), 4) print d3 </code></pre> <p>Output:</p> <pre><code>{'hij': 599.971, 'ab': 1.8995} </code></pre>
0
2016-09-14T19:10:27Z
[ "python", "python-2.7" ]
Unsupported operand type for - list and list
39,497,815
<p>I am using an older version of python which doesnt have support to subtract dict's.</p> <pre><code>d1={'ab': ['3'], 'hij': ['1200']} d2={'ab': ['1'], 'hij': ['600']} </code></pre> <p>Basically my code looks like this:</p> <pre><code> for key in d1.keys(): if key in d2: d3[key]=d1[key]-d2[key] </code></pre> <p>output should be like</p> <pre><code>d2={'ab': ['2'], 'hij': ['600']} </code></pre> <p>It returns unsupported operand type for - : list and list. Any ideas on how to get around this</p>
-3
2016-09-14T19:01:32Z
39,498,077
<p>You can't subtract lists like so. </p> <p>You could instead use a <em>dictionary comprehensio</em>n and then <code>zip</code> the lists so you can then subtract their content:</p> <pre><code>d1={'ab': ['3'], 'hij': ['1200']} d2={'ab': ['1'], 'hij': ['600']} d3 = {k: ['{}'.format(int(i) - int(j)) for i, j in zip(d1[k], d2[k])] for k in d1} print(d3) # {'hij': ['600'], 'ab': ['2']} </code></pre> <p>Notice the items where casted to <code>int</code> and then back to string using string formatting. Might be better if your data was actually stored as integers in the first place.</p>
0
2016-09-14T19:18:23Z
[ "python", "python-2.7" ]
Unsupported operand type for - list and list
39,497,815
<p>I am using an older version of python which doesnt have support to subtract dict's.</p> <pre><code>d1={'ab': ['3'], 'hij': ['1200']} d2={'ab': ['1'], 'hij': ['600']} </code></pre> <p>Basically my code looks like this:</p> <pre><code> for key in d1.keys(): if key in d2: d3[key]=d1[key]-d2[key] </code></pre> <p>output should be like</p> <pre><code>d2={'ab': ['2'], 'hij': ['600']} </code></pre> <p>It returns unsupported operand type for - : list and list. Any ideas on how to get around this</p>
-3
2016-09-14T19:01:32Z
39,498,357
<p>Have you tried looking at d1[key] and d2[key] to get an idea of what the error is about ? Well if not you should have, that's the first step of debugging code: looking where it failed and what was involved in the failure.</p> <p>So the explaination of your problem is the following d1['ab'] is not a number, it is a list , that list is <code>['3']</code> to be more precise. So writing <code>d1['ab'] - d2['ab']</code> translates to <code>['3'] - ['1']</code> and that would be equivalent to doing <code>list() - list()</code> and as the error states there is no way to substract two list, the operation is simply not defined. So what you want is to take what is <strong>inside</strong> the list and not the list itself but be carefull inside those lists you only have <strong>strings</strong> not actual numbers so you have to convert the string to a number and only then you will be able to do the expected substaction.</p> <p>But all that is fairly tedious and I assume the mistake is that you didn't totaly undersand the syntax of dictionnaries when you wrote the code. You don't have to put the numbers as strings and inside a list to put them in the dict, you could directly put the number as is : <code>d1={'ab': 3, 'hij': 1200}</code> is perfectly valid python code. Then when you call <code>d1['ab']</code> you directly get the number you expect.</p>
0
2016-09-14T19:36:24Z
[ "python", "python-2.7" ]
Python running setup.py through cmd doesn't work?
39,497,856
<p>So I'm trying to install via cmd using a setup.py file.. <a href="http://i.stack.imgur.com/OrvUA.png" rel="nofollow"><img src="http://i.stack.imgur.com/OrvUA.png" alt=""></a></p> <p>However, when I try to install it through CMD, this happens: <a href="http://i.stack.imgur.com/90xNn.png" rel="nofollow"><img src="http://i.stack.imgur.com/90xNn.png" alt="enter image description here"></a></p>
-2
2016-09-14T19:03:51Z
39,497,900
<p>The first way you were trying to install it is correct <code>python setup.py install</code>, however you need Python 2.x for this installer to work. You are in a Python 3.2 environment and it appears that this module has not been updated to work with Python3 at this time.</p> <p><a href="http://ocemp.sourceforge.net/manual/installation.html" rel="nofollow">http://ocemp.sourceforge.net/manual/installation.html</a></p> <p>The <code>print bdist.bdist_base, self.install_dir</code> statement is Python 2.x syntax. If it were compatible with Python3, it would be <code>print(bdist.bdist_base, self.install_dir)</code></p> <p><strong>----------</strong></p> <p>If you require development in both Python3 and Python2, I highly recommend installing Anaconda</p> <p><a href="https://www.continuum.io/downloads" rel="nofollow">https://www.continuum.io/downloads</a></p> <p>You can set up multiple environments with whatever versions of Python that you want. Then you can activate each one as necessary.</p> <p><a href="http://conda.pydata.org/docs/py2or3.html" rel="nofollow">http://conda.pydata.org/docs/py2or3.html</a></p>
1
2016-09-14T19:06:28Z
[ "python" ]
Write a series of SQL queries to single csv in python
39,497,887
<p>Basically I want to create a single csv file from several SQL queries. What I have so far:</p> <pre><code>import pyodbc import csv import itertools conn = pyodbc.connect("user") cur = conn.cursor() sql_queries = ['query_1', 'query_2', 'query_3'] columns = [] rows = [] for query in sql_queries: cur.execute(query) columns.append([i[0] for i in cur.description]) rows.append(cur.fetchall()) flat_columns = list(itertools.chain.from_iterable(columns)) fp = open('temp_file.csv', 'w') my_file = csv.writer(fp) my_file.writerow(flat_columns) for row in rows: my_file.writerows(row) fp.close() </code></pre> <p>The flat_columns correctly prints all the column headers of the various queries at the top, but then the rows print sequentially (i.e., not under the correct header, except for the first query). Is there a way to get them to line up horizontally under the appropriate header? The queries produce differing numbers of rows and columns. </p> <p><strong>EDIT</strong> For example, let's say query1 produces 2 columns (headers1-2) and query2 and query3 each produce 1 column (header3 and header4 respectively), where query1 yields results of form 'xx', query2 'yy' and query3 'zz'. This is what I'm currently getting:</p> <pre><code>header1 header2 header3 header4 xx xx xx xx xx xx yy yy zz </code></pre> <p>And this is what I want:</p> <pre><code>header1 header2 header3 header4 xx xx yy zz xx xx yy xx xx </code></pre>
0
2016-09-14T19:05:45Z
39,500,021
<p>This answer is assuming that the variable <code>rows</code> contains a list of list of tuples like this <code>[[('xx', 'xx'), ('xx', 'xx'), ('xx', 'xx')], [('yy',), ('yy',)], [('zz',)]]</code> and that you're working with Python2</p> <pre><code>from itertools import izip_longest rows = [[('xx', 'xx'), ('xx', 'xx'), ('xx', 'xx')], [('yy',), ('yy',)], [('zz',)]] final_rows = map(lambda x: reduce(lambda y,z: y+z,x),list(izip_longest(*rows, fillvalue=(None,)))) with open('temp_file.csv', 'w') as outfile: writer = csv.writer(outfile, delimiter = "\t") writer.writerow(flat_columns) writer.writerows(final_rows) </code></pre> <p>Output:</p> <pre><code>header1 header2 header3 header4 xx xx yy zz xx xx yy xx xx </code></pre> <p>Note: If you wish to use Python3, you may want to wrap the output of the <code>map</code> function around <code>list()</code>, and also <code>import zip_longest</code> instead of <code>izip_longest</code>.</p> <p>I hope this helps.</p>
0
2016-09-14T21:37:56Z
[ "python", "sql", "csv" ]
Xlsx Writer getting corrupted with Strings
39,497,898
<p>I am currently exporting a dataframe to an excel spreadsheet, but my one of my columns which has long strings with varying lengths cause the file to get corrupted. </p> <pre><code>with pd.ExcelWriter('thing.xlsx'.format(path), engine='xlsxwriter',options={'strings_to_urls': False}) as writer: </code></pre> <p>Here I make put it into excel</p> <pre><code>df.to_excel(writer, 'long_text', index=False) </code></pre> <p><strong>Edit</strong> </p> <p>When I remove that column from the dataframe it ceases to corrupt, but I want to keep the column. When I limit the characters to 37 characters it also ceases to be corrupted. Which suggests that there is a character that is having trouble being encoded.</p> <p>Any ideas as to how to handle this? </p>
1
2016-09-14T19:06:23Z
39,536,829
<p>as @jmcnamara remarked my issue was that one of my strings was not encoded in UTF-8, but after encoding all the strings the excel file ceased to be corrupted</p>
1
2016-09-16T17:10:36Z
[ "python", "pandas", "dataframe", "xlsxwriter" ]
Find how many words start with certain letter in a list
39,497,934
<p>I am trying to output the total of how many words start with a letter <code>'a'</code> in a list from a separate text file. I'm looking for an output such as this. </p> <pre><code>35 words start with a letter 'a'. </code></pre> <p>However, i'm outputting all the words that start with an <code>'a'</code> instead of the total with my current code. Should I be using something other than a for loop? </p> <p>So far, this is what I have attempted:</p> <pre><code>wordsFile = open("words.txt", 'r') words = wordsFile.read() wordsFile.close() wordList = words.split() print("Words:",len(wordList)) # prints number of words in the file. a_words = 0 for a_words in wordList: if a_words[0]=='a': print(a_words, "start with the letter 'a'.") </code></pre> <p>The output I'm getting thus far:</p> <pre><code>Words: 334 abate start with the letter 'a'. aberrant start with the letter 'a'. abeyance start with the letter 'a'. </code></pre> <p>and so on. </p>
0
2016-09-14T19:09:10Z
39,498,053
<p>You could replace this with a <code>sum</code> call in which you feed <code>1</code> for every word in <code>wordList</code> that starts with <code>a</code>:</p> <pre><code>print(sum(1 for w in wordList if w.startswith('a')), 'start with the letter "a"') </code></pre> <p>This can be further trimmed down if you use the boolean values returned by <code>startswith</code> instead, since <code>True</code> is treated as <code>1</code> in these contexts the effect is the same:</p> <pre><code>print(sum(w.startswith('a') for w in a), 'start with the letter "a"') </code></pre> <p>With your current approach, you're not summing anything, you're simply printing any word that matches. In addition, you're re-naming <code>a_word</code> from an <code>int</code> to the contents of the list as you iterate through it.</p> <p>Also, instead of using <code>a_word[0]</code> to check for the first character, you could use <code>startswith(character)</code> which has the same effect and is a bit more readable.</p>
3
2016-09-14T19:16:46Z
[ "python", "list", "python-3.x" ]
Find how many words start with certain letter in a list
39,497,934
<p>I am trying to output the total of how many words start with a letter <code>'a'</code> in a list from a separate text file. I'm looking for an output such as this. </p> <pre><code>35 words start with a letter 'a'. </code></pre> <p>However, i'm outputting all the words that start with an <code>'a'</code> instead of the total with my current code. Should I be using something other than a for loop? </p> <p>So far, this is what I have attempted:</p> <pre><code>wordsFile = open("words.txt", 'r') words = wordsFile.read() wordsFile.close() wordList = words.split() print("Words:",len(wordList)) # prints number of words in the file. a_words = 0 for a_words in wordList: if a_words[0]=='a': print(a_words, "start with the letter 'a'.") </code></pre> <p>The output I'm getting thus far:</p> <pre><code>Words: 334 abate start with the letter 'a'. aberrant start with the letter 'a'. abeyance start with the letter 'a'. </code></pre> <p>and so on. </p>
0
2016-09-14T19:09:10Z
39,498,130
<p>You are using the <code>a_words</code> as the value of the word in each iteration and missing a counter. If we change the for loop to have <code>words</code> as the value and reserved <code>a_words</code> for the counter, we can increment the counter each time the criteria is passed. You could change <code>a_words</code> to <code>wordCount</code> or something generic to make it more portable and friendly for other letters.</p> <pre><code>a_words = 0 for words in wordList: if words[0]=='a': a_words += 1 print(a_words, "start with the letter 'a'.") </code></pre>
2
2016-09-14T19:22:34Z
[ "python", "list", "python-3.x" ]
Find how many words start with certain letter in a list
39,497,934
<p>I am trying to output the total of how many words start with a letter <code>'a'</code> in a list from a separate text file. I'm looking for an output such as this. </p> <pre><code>35 words start with a letter 'a'. </code></pre> <p>However, i'm outputting all the words that start with an <code>'a'</code> instead of the total with my current code. Should I be using something other than a for loop? </p> <p>So far, this is what I have attempted:</p> <pre><code>wordsFile = open("words.txt", 'r') words = wordsFile.read() wordsFile.close() wordList = words.split() print("Words:",len(wordList)) # prints number of words in the file. a_words = 0 for a_words in wordList: if a_words[0]=='a': print(a_words, "start with the letter 'a'.") </code></pre> <p>The output I'm getting thus far:</p> <pre><code>Words: 334 abate start with the letter 'a'. aberrant start with the letter 'a'. abeyance start with the letter 'a'. </code></pre> <p>and so on. </p>
0
2016-09-14T19:09:10Z
39,498,319
<p><code>sum(generator)</code> is a way to go, but for completeness sake, you may want to do it with list comprehension (maybe if it's slightly more readable or you want to do something with words starting with <em>a</em> etc.).</p> <pre><code>words_starting_with_a = [word for word in word_list if word.startswith('a')] </code></pre> <p>After that you may use <code>len</code> built-in to retrieve length of your new list.</p> <pre><code>print(len(words_starting_with_a), "words start with a letter 'a'") </code></pre>
1
2016-09-14T19:34:21Z
[ "python", "list", "python-3.x" ]
Find how many words start with certain letter in a list
39,497,934
<p>I am trying to output the total of how many words start with a letter <code>'a'</code> in a list from a separate text file. I'm looking for an output such as this. </p> <pre><code>35 words start with a letter 'a'. </code></pre> <p>However, i'm outputting all the words that start with an <code>'a'</code> instead of the total with my current code. Should I be using something other than a for loop? </p> <p>So far, this is what I have attempted:</p> <pre><code>wordsFile = open("words.txt", 'r') words = wordsFile.read() wordsFile.close() wordList = words.split() print("Words:",len(wordList)) # prints number of words in the file. a_words = 0 for a_words in wordList: if a_words[0]=='a': print(a_words, "start with the letter 'a'.") </code></pre> <p>The output I'm getting thus far:</p> <pre><code>Words: 334 abate start with the letter 'a'. aberrant start with the letter 'a'. abeyance start with the letter 'a'. </code></pre> <p>and so on. </p>
0
2016-09-14T19:09:10Z
39,498,404
<p>Simple alternative solution using <code>re.findall</code> function(without splitting text and <code>for</code> loop):</p> <pre><code>import re ... words = wordsFile.read() ... total = len(re.findall(r'\ba\w+?\b', words)) print('Total number of words that start with a letter "a" : ', total) </code></pre>
0
2016-09-14T19:39:31Z
[ "python", "list", "python-3.x" ]
Where's the logic that returns an instance of a subclass of OSError exception class?
39,498,031
<p>I've been hunting for something that could be relatively stupid to some people, but to me very interesting! :-)</p> <p>Input and output errors have been merged with <code>OSError</code> in Python 3.3, so there's a change in the exception class hierarchy. One interesting feature about the builtin class <code>OSError</code> is that, it returns a subclass of it when passed <code>errno</code> and <code>strerror</code></p> <pre><code>&gt;&gt;&gt; OSError(2, os.strerror(2)) FileNotFoundError(2, 'No such file or directory') &gt;&gt;&gt; OSError(2, os.strerror(2)).errno 2 &gt;&gt;&gt; OSError(2, os.strerror(2)).strerror 'No such file or directory' </code></pre> <p>As you can see passing <code>errno</code> and <code>strerror</code> to the constructor of <code>OSError</code> returns <code>FileNotFoundError</code> instance which is a subclass of <code>OSError</code>.</p> <p><em>Python Doc:</em> </p> <blockquote> <p>The constructor often actually returns a subclass of OSError, as described in OS <a href="https://docs.python.org/3/library/exceptions.html#os-exceptions" rel="nofollow">exceptions</a> below. The particular subclass depends on the final errno value. <strong>This behaviour only occurs when constructing OSError directly or via an alias, and is not inherited when subclassing.</strong></p> </blockquote> <p>I wanted to code a subclass that would behave in this way. It's mostly curiosity and not real world code. I'm also trying to know, where's the logic that creates the subclass object, is it coded in <code>__new__</code> for example? If <code>__new__</code> contains the logic for creating the instances of the subclasses, then inheriting from <code>OSError</code> would typically return this behavior, unless if there's some sort of type checking in <code>__new__</code>:</p> <pre><code>&gt;&gt;&gt; class A(OSError): pass &gt;&gt;&gt; A(2, os.strerror(2)) A(2, 'No such file or directory') </code></pre> <p>There must be type checking then: </p> <pre><code># If passed OSError, returns subclass instance &gt;&gt;&gt; A.__new__(OSError, 2, os.strerror(2)) FileNotFoundError(2, 'No such file or directory') # Not OSError? Return instance of A &gt;&gt;&gt; A.__new__(A, 2, os.strerror(2) A(2, 'No such file or directory') </code></pre> <p>I've been digging through C code to find out where's this code is placed exactly and since I'm not an expert in C, I suspect this is really the logic and (I'm quite skeptical about that to be frank): </p> <p><a href="https://hg.python.org/cpython/file/5ae8756a1ae0/Objects/exceptions.c" rel="nofollow">exceptions.c</a></p> <pre><code>if (myerrno &amp;&amp; PyLong_Check(myerrno) &amp;&amp; errnomap &amp;&amp; (PyObject *) type == PyExc_OSError) { PyObject *newtype; newtype = PyDict_GetItem(errnomap, myerrno); if (newtype) { assert(PyType_Check(newtype)); type = (PyTypeObject *) newtype; } else if (PyErr_Occurred()) goto error; } } </code></pre> <p>Now I'm wondering about the possibility of expanding <code>errnomap</code> from Python itself without playing with C code, so that <code>OSErro</code> can make instances of user-defined classes, if you ask me why would you do that? I would say, just for fun. </p>
7
2016-09-14T19:14:54Z
39,498,441
<p>You can't change the behavior of <code>OSError</code> from Python because it's not implemented in Python.</p> <p>For classes implemented in Python, you can write <code>__new__</code> so it only returns a subclass if it's being called on the base class. Then the behavior won't be inherited.</p> <pre><code>class MyClass(object): def __new__(cls, sub=0, _subtypes={}): if cls is MyClass: if sub not in _subtypes: _subtypes[sub] = type("MyClass(%s)" % sub, (MyClass,), {}) return _subtypes[sub](sub) return object.__new__(cls, sub) def __init__(self, sub): assert type(self).__name__ == "MyClass(%s)" % sub class SubClass(MyClass): def __init__(self, sub=None): assert type(self).__name__ == "SubClass" print(MyClass(1)) # &lt;__main__.MyClass(1) object at 0x01EB1EB0&gt; print(SubClass()) # &lt;__main__.SubClass object at 0x01EB1CD0&gt; </code></pre>
0
2016-09-14T19:41:22Z
[ "python" ]
Where's the logic that returns an instance of a subclass of OSError exception class?
39,498,031
<p>I've been hunting for something that could be relatively stupid to some people, but to me very interesting! :-)</p> <p>Input and output errors have been merged with <code>OSError</code> in Python 3.3, so there's a change in the exception class hierarchy. One interesting feature about the builtin class <code>OSError</code> is that, it returns a subclass of it when passed <code>errno</code> and <code>strerror</code></p> <pre><code>&gt;&gt;&gt; OSError(2, os.strerror(2)) FileNotFoundError(2, 'No such file or directory') &gt;&gt;&gt; OSError(2, os.strerror(2)).errno 2 &gt;&gt;&gt; OSError(2, os.strerror(2)).strerror 'No such file or directory' </code></pre> <p>As you can see passing <code>errno</code> and <code>strerror</code> to the constructor of <code>OSError</code> returns <code>FileNotFoundError</code> instance which is a subclass of <code>OSError</code>.</p> <p><em>Python Doc:</em> </p> <blockquote> <p>The constructor often actually returns a subclass of OSError, as described in OS <a href="https://docs.python.org/3/library/exceptions.html#os-exceptions" rel="nofollow">exceptions</a> below. The particular subclass depends on the final errno value. <strong>This behaviour only occurs when constructing OSError directly or via an alias, and is not inherited when subclassing.</strong></p> </blockquote> <p>I wanted to code a subclass that would behave in this way. It's mostly curiosity and not real world code. I'm also trying to know, where's the logic that creates the subclass object, is it coded in <code>__new__</code> for example? If <code>__new__</code> contains the logic for creating the instances of the subclasses, then inheriting from <code>OSError</code> would typically return this behavior, unless if there's some sort of type checking in <code>__new__</code>:</p> <pre><code>&gt;&gt;&gt; class A(OSError): pass &gt;&gt;&gt; A(2, os.strerror(2)) A(2, 'No such file or directory') </code></pre> <p>There must be type checking then: </p> <pre><code># If passed OSError, returns subclass instance &gt;&gt;&gt; A.__new__(OSError, 2, os.strerror(2)) FileNotFoundError(2, 'No such file or directory') # Not OSError? Return instance of A &gt;&gt;&gt; A.__new__(A, 2, os.strerror(2) A(2, 'No such file or directory') </code></pre> <p>I've been digging through C code to find out where's this code is placed exactly and since I'm not an expert in C, I suspect this is really the logic and (I'm quite skeptical about that to be frank): </p> <p><a href="https://hg.python.org/cpython/file/5ae8756a1ae0/Objects/exceptions.c" rel="nofollow">exceptions.c</a></p> <pre><code>if (myerrno &amp;&amp; PyLong_Check(myerrno) &amp;&amp; errnomap &amp;&amp; (PyObject *) type == PyExc_OSError) { PyObject *newtype; newtype = PyDict_GetItem(errnomap, myerrno); if (newtype) { assert(PyType_Check(newtype)); type = (PyTypeObject *) newtype; } else if (PyErr_Occurred()) goto error; } } </code></pre> <p>Now I'm wondering about the possibility of expanding <code>errnomap</code> from Python itself without playing with C code, so that <code>OSErro</code> can make instances of user-defined classes, if you ask me why would you do that? I would say, just for fun. </p>
7
2016-09-14T19:14:54Z
39,500,064
<p>You're correct that <code>errnomap</code> is the variable that holds the mapping from errno values to <code>OSError</code> subclasses, but unfortunately it's not exported outside the <code>exceptions.c</code> source file, so there's no portable way to modify it.</p> <hr> <p>It <em>is</em> possible to access it using <strong>highly</strong> non-portable hacks, and I present one possible method for doing so (using a debugger) below purely in a spirit of fun. This should work on any x86-64 Linux system.</p> <pre><code>&gt;&gt;&gt; import os, sys &gt;&gt;&gt; os.system("""gdb -p %d \ -ex 'b PyDict_GetItem if (PyLong_AsLongLong($rsi) == -1 ? \ (PyErr_Clear(), 0) : PyLong_AsLongLong($rsi)) == 0xbaadf00d' \ -ex c \ -ex 'call PySys_SetObject("errnomap", $rdi)' --batch &gt;/dev/null 2&gt;&amp;1 &amp;""" % os.getpid()) 0 &gt;&gt;&gt; OSError(0xbaadf00d, '') OSError(3131961357, '') &gt;&gt;&gt; sys.errnomap {32: &lt;class 'BrokenPipeError'&gt;, 1: &lt;class 'PermissionError'&gt; [...]} &gt;&gt;&gt; class ImATeapotError(OSError): pass &gt;&gt;&gt; sys.errnomap[99] = ImATeapotError &gt;&gt;&gt; OSError(99, "I'm a teapot") ImATeapotError(99, "I'm a teapot") </code></pre> <p>Quick explanation of how this works:</p> <p><code>gdb -p %d [...] --batch &gt;/dev/null 2&gt;&amp;1 &amp;</code></p> <p>Attach a debugger to the current Python process (<code>os.getpid()</code>), in unattended mode (<code>--batch</code>), discarding output (<code>&gt;/dev/null 2&gt;&amp;1</code>) and in the background (<code>&amp;</code>), allowing Python to continue running.</p> <p><code>b PyDict_GetItem if (PyLong_AsLongLong($rsi) == -1 ? (PyErr_Clear(), 0) : PyLong_AsLongLong($rsi)) == 0xbaadf00d</code></p> <p>When the Python program <a href="https://docs.python.org/3/c-api/dict.html#c.PyDict_GetItem">accesses <em>any</em> dictionary</a>, break if the key <a href="https://docs.python.org/3/c-api/long.html#c.PyLong_AsLongLong">is an <code>int</code></a> with a magic value (used as <code>OSError(0xbaadf00d, '')</code> later); if it isn't an int, we've just raised <code>TypeError</code>, so <a href="https://docs.python.org/3/c-api/exceptions.html#c.PyErr_Clear">suppress it</a>.</p> <p><code>call PySys_SetObject("errnomap", $rdi)</code></p> <p>When this happens, we know the dictionary being looked up in is the <code>errnomap</code>; <a href="https://docs.python.org/3/c-api/sys.html#system-functions">store it as an attribute on the <code>sys</code> module</a>.</p>
5
2016-09-14T21:42:12Z
[ "python" ]
Simple python telnet client/server example doesn't work
39,498,117
<p>I'm trying to create mockup telnet server (for some functional testing of existing code). Right now I only modified server welcome message and I was trying to read this message using client code, but it read method fails on timeout with no additional info. But with pudb debugger enabled it works most of the time...</p> <p>I'm using virtualenv, with pudb and telnetsrv installed using pip. Python 2.7.12, ubuntu 16.04.</p> <p>Server code:</p> <pre><code>import SocketServer from telnetsrv.threaded import TelnetHandler class MyHandler(TelnetHandler): WELCOME = "HI from custom server" class TelnetServer(SocketServer.TCPServer): allow_reuse_address = True server = TelnetServer(("0.0.0.0", 8023), MyHandler) server.serve_forever() </code></pre> <p>Client code:</p> <pre><code>import telnetlib HOST = '127.0.0.1' PORT = 8023 # from pudb import set_trace; set_trace() tn = telnetlib.Telnet(HOST, PORT) data = tn.read_until("custom server", timeout=1) print "Data: " + data tn.close() </code></pre> <p>Client output:</p> <pre><code>$ python client.py Data: </code></pre> <p>Client output with pudb enabled (with step-by-step execution)</p> <pre><code>$ python client.py Data: HI from custom server </code></pre> <p>Of course when I execute shell telnet command, it all works fine:</p> <pre><code>$ telnet 127.0.0.1 8023 Trying 127.0.0.1... Connected to 127.0.0.1. Escape character is '^]'. HI from custom server Telnet Server&gt; </code></pre> <p>I'd really appreciate any hints on how to debug this problem. Thanks!</p>
0
2016-09-14T19:21:52Z
40,003,240
<p>Be sure there is actually connecting going on. To do that put edit your code to add <strong>tn.set_debuglevel(100)</strong> into your script to look like this:</p> <pre><code>import telnetlib HOST = '127.0.0.1' PORT = 8023 # from pudb import set_trace; set_trace() tn = telnetlib.Telnet(HOST, PORT) tn.set_debuglevel(100) data = tn.read_until("custom server", timeout=1) print "Data: " + data tn.close() </code></pre> <p>This will ensure all the data is printed out so you can see what's going on.</p> <p>My theory is, that you're not connecting, or that your data isn't actually outputting "custom server" and therefor it won't catch it, or your timeout is too low.</p>
0
2016-10-12T16:04:23Z
[ "python", "telnetlib" ]
How do I use a while loop to add a variable every time it loops?
39,498,152
<p>I'm writing a program that tells the user to input the amount of rooms that a property has, and then a while loop finds out the width and length of each room. I feel like I need the while loop to create two extra variables to store the width and length every time it iterates, however I can not figure out how. here is my code so far:</p> <pre><code>roomCount = 1 print("Please answer the questions to find the floor size.") rooms = int(input("How many rooms has the property got?:\n")) while roomcount &gt;= rooms: print("For room", roomcount,", what is the length?:\n") </code></pre> <p>Its not much, but I have been searching the internet and haven't found out how.</p> <p>What I would like the program to do is to ask the user how many rooms the property has and then for each room it should ask for the width and length of the room. The program then should display the total area of the floor space in a user friendly format</p> <p>updated code:</p> <pre><code>currentRoomNumber = 0 currentRoomNumber2 = 0 floorspace = 0 whileLoop = 0 print("Please answer the questions to find the floor size.") numberOfRooms = int(input("How many rooms has the property got?: ")) roomWidths= list() roomLengths = list() while currentRoomNumber &lt; numberOfRooms: roomWidths.append(int(input("For room " + str(currentRoomNumber + 1) + ", what is the width?: "))) roomLengths.append(int(input("For room " + str(currentRoomNumber + 1) + ", what is the length?: "))) currentRoomNumber += 1 while whileLoop &lt; numberOfRooms: floorspace += (roomLengths[(currentRoomNumer2)] * roomWidths[(currentRoomNumber2)]) currentRoomNumber2 += 1 whileLoop += 1 print(floorspace) </code></pre> <p>However, after inputting the values of the room dimensions, it gives me a traceback error on line 15 and says <code>currentRoomNumber2</code> is not defined. Where have I gone wrong?</p>
0
2016-09-14T19:24:04Z
39,498,363
<p>Thinking you want the length and breadth to be saved by the room number, I would do something like this:</p> <pre><code>rooms = {} print("Please answer the questions to find the floor size.") rooms = int(input("How many rooms has the property got?:\n")) for room_num in range(1, rooms+1): length = int(input("What is the lenth of room number {}: ".format(room_num))) width = int(input("What is the lwidth of room number {}: ".format(room_num))) rooms[room_num] = {'length': length, 'width': width} </code></pre> <p>Then to get the length of room 1, just look it up: <code>rooms[1]['length']</code>, width: <code>rooms[1]['width']</code> ,etc. etc.</p>
0
2016-09-14T19:37:00Z
[ "python", "variables", "while-loop" ]
How do I use a while loop to add a variable every time it loops?
39,498,152
<p>I'm writing a program that tells the user to input the amount of rooms that a property has, and then a while loop finds out the width and length of each room. I feel like I need the while loop to create two extra variables to store the width and length every time it iterates, however I can not figure out how. here is my code so far:</p> <pre><code>roomCount = 1 print("Please answer the questions to find the floor size.") rooms = int(input("How many rooms has the property got?:\n")) while roomcount &gt;= rooms: print("For room", roomcount,", what is the length?:\n") </code></pre> <p>Its not much, but I have been searching the internet and haven't found out how.</p> <p>What I would like the program to do is to ask the user how many rooms the property has and then for each room it should ask for the width and length of the room. The program then should display the total area of the floor space in a user friendly format</p> <p>updated code:</p> <pre><code>currentRoomNumber = 0 currentRoomNumber2 = 0 floorspace = 0 whileLoop = 0 print("Please answer the questions to find the floor size.") numberOfRooms = int(input("How many rooms has the property got?: ")) roomWidths= list() roomLengths = list() while currentRoomNumber &lt; numberOfRooms: roomWidths.append(int(input("For room " + str(currentRoomNumber + 1) + ", what is the width?: "))) roomLengths.append(int(input("For room " + str(currentRoomNumber + 1) + ", what is the length?: "))) currentRoomNumber += 1 while whileLoop &lt; numberOfRooms: floorspace += (roomLengths[(currentRoomNumer2)] * roomWidths[(currentRoomNumber2)]) currentRoomNumber2 += 1 whileLoop += 1 print(floorspace) </code></pre> <p>However, after inputting the values of the room dimensions, it gives me a traceback error on line 15 and says <code>currentRoomNumber2</code> is not defined. Where have I gone wrong?</p>
0
2016-09-14T19:24:04Z
39,498,447
<p>I'd recommend going for a <code>Room</code> class. Then you can define an <code>area</code> method on it. </p> <pre><code>class Room(): def __init__(self, w, l): self.width = w self.length = l def area(self): return self.width * self.length </code></pre> <p>Then, for your input, store those into a list. Use a for-loop instead. No need for a while-loop. </p> <pre><code>print("Please answer the questions to find the floor size.") roomCount = int(input("How many rooms does the property have?\n")) rooms = [] for roomNum in range(roomCount): l = float(input("For room {} what is the length?\n".format(roomNum + 1))) w = float(input("For room {} what is the width?\n".format(roomNum + 1))) rooms.append(Room(w, l)) </code></pre> <p>When you are done with that, you just loop over the objects and add up the areas. </p> <pre><code>size = sum(r.area() for r in rooms) print(size) </code></pre>
0
2016-09-14T19:41:49Z
[ "python", "variables", "while-loop" ]
How do I use a while loop to add a variable every time it loops?
39,498,152
<p>I'm writing a program that tells the user to input the amount of rooms that a property has, and then a while loop finds out the width and length of each room. I feel like I need the while loop to create two extra variables to store the width and length every time it iterates, however I can not figure out how. here is my code so far:</p> <pre><code>roomCount = 1 print("Please answer the questions to find the floor size.") rooms = int(input("How many rooms has the property got?:\n")) while roomcount &gt;= rooms: print("For room", roomcount,", what is the length?:\n") </code></pre> <p>Its not much, but I have been searching the internet and haven't found out how.</p> <p>What I would like the program to do is to ask the user how many rooms the property has and then for each room it should ask for the width and length of the room. The program then should display the total area of the floor space in a user friendly format</p> <p>updated code:</p> <pre><code>currentRoomNumber = 0 currentRoomNumber2 = 0 floorspace = 0 whileLoop = 0 print("Please answer the questions to find the floor size.") numberOfRooms = int(input("How many rooms has the property got?: ")) roomWidths= list() roomLengths = list() while currentRoomNumber &lt; numberOfRooms: roomWidths.append(int(input("For room " + str(currentRoomNumber + 1) + ", what is the width?: "))) roomLengths.append(int(input("For room " + str(currentRoomNumber + 1) + ", what is the length?: "))) currentRoomNumber += 1 while whileLoop &lt; numberOfRooms: floorspace += (roomLengths[(currentRoomNumer2)] * roomWidths[(currentRoomNumber2)]) currentRoomNumber2 += 1 whileLoop += 1 print(floorspace) </code></pre> <p>However, after inputting the values of the room dimensions, it gives me a traceback error on line 15 and says <code>currentRoomNumber2</code> is not defined. Where have I gone wrong?</p>
0
2016-09-14T19:24:04Z
39,498,590
<p>I'd do it this way.</p> <pre><code>rooms_total = int(input('How many rooms?')) rooms_info = list() for i in range(rooms_total): length = int(input('Length for room #{}?'.format(i))) width = int(input('Width for room #{}?'.format(i))) rooms_info.append({'length': length, 'width': width}) space = sum([x['length'] * x['width'] for x in rooms_info]) print(space) </code></pre> <p>Class feels like an overkill (unless you specifically want to practice classes), and dictionary doesn't feel like a proper outer data structure here.</p> <p>It's just my humble opinion, but you need to read more about loops and basic data structures in Python.</p>
0
2016-09-14T19:51:22Z
[ "python", "variables", "while-loop" ]
How do I use a while loop to add a variable every time it loops?
39,498,152
<p>I'm writing a program that tells the user to input the amount of rooms that a property has, and then a while loop finds out the width and length of each room. I feel like I need the while loop to create two extra variables to store the width and length every time it iterates, however I can not figure out how. here is my code so far:</p> <pre><code>roomCount = 1 print("Please answer the questions to find the floor size.") rooms = int(input("How many rooms has the property got?:\n")) while roomcount &gt;= rooms: print("For room", roomcount,", what is the length?:\n") </code></pre> <p>Its not much, but I have been searching the internet and haven't found out how.</p> <p>What I would like the program to do is to ask the user how many rooms the property has and then for each room it should ask for the width and length of the room. The program then should display the total area of the floor space in a user friendly format</p> <p>updated code:</p> <pre><code>currentRoomNumber = 0 currentRoomNumber2 = 0 floorspace = 0 whileLoop = 0 print("Please answer the questions to find the floor size.") numberOfRooms = int(input("How many rooms has the property got?: ")) roomWidths= list() roomLengths = list() while currentRoomNumber &lt; numberOfRooms: roomWidths.append(int(input("For room " + str(currentRoomNumber + 1) + ", what is the width?: "))) roomLengths.append(int(input("For room " + str(currentRoomNumber + 1) + ", what is the length?: "))) currentRoomNumber += 1 while whileLoop &lt; numberOfRooms: floorspace += (roomLengths[(currentRoomNumer2)] * roomWidths[(currentRoomNumber2)]) currentRoomNumber2 += 1 whileLoop += 1 print(floorspace) </code></pre> <p>However, after inputting the values of the room dimensions, it gives me a traceback error on line 15 and says <code>currentRoomNumber2</code> is not defined. Where have I gone wrong?</p>
0
2016-09-14T19:24:04Z
39,498,592
<p>From your question it seems like this is what you want:</p> <pre><code> print("Please answer the questions to find the floor size.") numberOfRooms = int(input("How many rooms has the property got?: ")) currentRoomNumber = 0 roomLengths = list() while currentRoomNumber &lt; numberOfRooms: roomLengths.append(int(input("For room " + str(currentRoomNumber + 1) + ", what is the length?: "))) currentRoomNumber += 1 print roomLengths </code></pre> <p>This puts each room's length into a list (keep in mind room "1" according to the user is room "0" to you).</p> <p>When you run this, it looks like this (I put the length of each room as whatever the room number was):</p> <pre><code> Please answer the questions to find the floor size. How many rooms has the property got?: 5 For room 1, what is the length?: 1 For room 2, what is the length?: 2 For room 3, what is the length?: 3 For room 4, what is the length?: 4 For room 5, what is the length?: 5 [1, 2, 3, 4, 5] </code></pre> <p>To access the lengths of each room, like I said before, make sure you reference room "1" (length 1) as room "0", meaning you will reference it as:</p> <pre><code> print roomLengths[0] </code></pre> <p>This may be simple, but I wanted to make it clear to you since you were asking how to "create variables", really what you want is a list since you don't know how many "variables" you will want to create; so this list can have however many room lengths you need.</p> <p>To add the width in there, you would just add another list and input like so:</p> <pre><code> print("Please answer the questions to find the floor size.") numberOfRooms = int(input("How many rooms has the property got?: ")) currentRoomNumber = 0 roomWidths= list() roomLengths = list() while currentRoomNumber &lt; numberOfRooms: roomWidths.append(int(input("For room " + str(currentRoomNumber + 1) + ", what is the width?: "))) roomLengths.append(int(input("For room " + str(currentRoomNumber + 1) + ", what is the length?: "))) currentRoomNumber += 1 print "Room widths:" print roomWidths print "Room lengths:" print roomLengths </code></pre> <p>The output/running of the script would then be something like this:</p> <pre><code> Please answer the questions to find the floor size. How many rooms has the property got?: 3 For room 1, what is the width?: 1 For room 1, what is the length?: 2 For room 2, what is the width?: 3 For room 2, what is the length?: 4 For room 3, what is the width?: 5 For room 3, what is the length?: 6 Room widths: [1, 3, 5] Room lengths: [2, 4, 6] </code></pre>
1
2016-09-14T19:51:26Z
[ "python", "variables", "while-loop" ]
Python 2.7.9 Getting error:TypeError: argument must be 9-item sequence, not datetime.datetime
39,498,169
<p>This is occurring on the following code line:</p> <p><code>epoch_time = int(time.mktime(time.strptime( time.strftime( "%Y-%m-%d %H:%M:%S", status.sensorBGLTimestamp ), '%Y-%m-%d %H:%M:%S').timetuple()) - time.timezone )</code></p> <p>Anyone able to help with why?</p>
0
2016-09-14T19:25:12Z
39,498,265
<p>If you are trying to simply get the epoch time, you should use</p> <pre><code>import calendar import time calendar.timegm(time.gmtime()) </code></pre> <p><strong>Returns:</strong> <code>1473881423</code></p>
0
2016-09-14T19:31:12Z
[ "python", "datetime", "time" ]
Append to each dictionary within a list
39,498,211
<p>I have a list of dictionary objects:</p> <pre><code>[{u'ID': 46757, u'currentenddate': u'09/30/2016', u'name': u'Project A', u'projstartdate': u'05/01/2016'}, {u'ID': 46625, u'currentenddate': u'07/15/2016', u'name': u'Project B', u'projstartdate': u'05/02/2016'}, {u'ID': 47100, u'currentenddate': u'08/02/2016', u'name': u'Project C', u'projstartdate': u'06/01/2016'}] </code></pre> <p>and I would like to append to ALL dictionary items a new field <code>client_id</code>, resulting in:</p> <pre><code>[{u'ID': 46757, u'currentenddate': u'09/30/2016', u'name': u'Project A', u'projstartdate': u'05/01/2016'}, u'client_id': u'12398'}, {u'ID': 46625, u'currentenddate': u'07/15/2016', u'name': u'Project B', u'projstartdate': u'05/02/2016'}, u'client_id': u'12398'}, {u'ID': 47100, u'currentenddate': u'08/02/2016', u'name': u'Project C', u'projstartdate': u'06/01/2016'} u'client_id': u'12398'}] </code></pre> <p><code>client_id</code> will remain the same for all dictionary items. I know I can achieve the outcome using a <code>for</code> loop coupled with <code>dict['client_id'] = id</code> but the code is no longer vectorized. Is there a pythonic way to append to each dict item within the list?</p> <hr> <p><strong>UPDATE:</strong></p> <p>Thanks for the lively conversation about list comprehensions versus <code>for</code> loops. I'll test both methods and use the faster of the two for my situation. Also, going forward, I'll explicitly define what I mean by 'vectorized' and 'pythonic' in my questions, so we're all on the same page (thanks, @Adam Smith).</p>
2
2016-09-14T19:27:33Z
39,498,414
<p>Something like this could do the trick.</p> <pre><code>result = [dict(data, client_id='') for data in list_of_dicts] </code></pre>
1
2016-09-14T19:40:05Z
[ "python", "list", "dictionary" ]
Append to each dictionary within a list
39,498,211
<p>I have a list of dictionary objects:</p> <pre><code>[{u'ID': 46757, u'currentenddate': u'09/30/2016', u'name': u'Project A', u'projstartdate': u'05/01/2016'}, {u'ID': 46625, u'currentenddate': u'07/15/2016', u'name': u'Project B', u'projstartdate': u'05/02/2016'}, {u'ID': 47100, u'currentenddate': u'08/02/2016', u'name': u'Project C', u'projstartdate': u'06/01/2016'}] </code></pre> <p>and I would like to append to ALL dictionary items a new field <code>client_id</code>, resulting in:</p> <pre><code>[{u'ID': 46757, u'currentenddate': u'09/30/2016', u'name': u'Project A', u'projstartdate': u'05/01/2016'}, u'client_id': u'12398'}, {u'ID': 46625, u'currentenddate': u'07/15/2016', u'name': u'Project B', u'projstartdate': u'05/02/2016'}, u'client_id': u'12398'}, {u'ID': 47100, u'currentenddate': u'08/02/2016', u'name': u'Project C', u'projstartdate': u'06/01/2016'} u'client_id': u'12398'}] </code></pre> <p><code>client_id</code> will remain the same for all dictionary items. I know I can achieve the outcome using a <code>for</code> loop coupled with <code>dict['client_id'] = id</code> but the code is no longer vectorized. Is there a pythonic way to append to each dict item within the list?</p> <hr> <p><strong>UPDATE:</strong></p> <p>Thanks for the lively conversation about list comprehensions versus <code>for</code> loops. I'll test both methods and use the faster of the two for my situation. Also, going forward, I'll explicitly define what I mean by 'vectorized' and 'pythonic' in my questions, so we're all on the same page (thanks, @Adam Smith).</p>
2
2016-09-14T19:27:33Z
39,498,476
<p>A <strong>Python 3.5</strong> solution showcasing the new dict <em>unpacking</em>. </p> <pre><code>[{**dict_element, **{u'client_id':u'12398'}} for dict_element in your_list] </code></pre> <p>Check <a href="https://www.python.org/dev/peps/pep-0448/" rel="nofollow">this</a>.</p> <p><strong>Demo</strong></p> <pre><code>&gt;&gt;&gt; your_list = [{u'ID': 46757, ... u'currentenddate': u'09/30/2016', ... u'name': u'Project A', ... u'projstartdate': u'05/01/2016'}, ... {u'ID': 46625, ... u'currentenddate': u'07/15/2016', ... u'name': u'Project B', ... u'projstartdate': u'05/02/2016'}, ... {u'ID': 47100, ... u'currentenddate': u'08/02/2016', ... u'name': u'Project C', ... u'projstartdate': u'06/01/2016'}] &gt;&gt;&gt; &gt;&gt;&gt; from pprint import pprint &gt;&gt;&gt; pprint([{**dict_element, **{u'client_id':u'12398'}} for dict_element in your_list]) [{'ID': 46757, 'client_id': '12398', 'currentenddate': '09/30/2016', 'name': 'Project A', 'projstartdate': '05/01/2016'}, {'ID': 46625, 'client_id': '12398', 'currentenddate': '07/15/2016', 'name': 'Project B', 'projstartdate': '05/02/2016'}, {'ID': 47100, 'client_id': '12398', 'currentenddate': '08/02/2016', 'name': 'Project C', 'projstartdate': '06/01/2016'}] </code></pre>
-1
2016-09-14T19:44:12Z
[ "python", "list", "dictionary" ]
I don't understand this python build synax "python3 setup.py build"
39,498,250
<p>Can someone please explain this build syntax here?</p> <pre><code>python3 setup.py build sudo python3 setup.py install </code></pre> <p>Source: <a href="http://askubuntu.com/a/406410/327339">http://askubuntu.com/a/406410/327339</a></p> <p>I just used the instructions at the source above to install pygame in python 3.x, and it worked great, but I don't understand the syntax of the commands, and I don't know where to find documentation on it. </p> <p><code>python3 file.py</code> calls a given module (<code>file.py</code> in this case, or <code>setup.py</code> above), but what about the word <em>after</em> that, ie: "build" in the command above? Is that a built-in Python command, is that a folder where outputs from setup.py are going, or what is it? </p> <p>Same with the "install" command. Can you please explain that syntax and help me find any relevant documentation? I tried searching around for a while, ex "python3 build", "python 3 module install", "python 3 module build," etc, but can't seem to find anything very informative on the matter.</p> <p>Also, what exactly are the build and install commands doing?</p> <p>Note: here is the contents of the "pygame" folder where I am running these commands.</p> <p><a href="http://i.stack.imgur.com/E4T3E.png" rel="nofollow"><img src="http://i.stack.imgur.com/E4T3E.png" alt="enter image description here"></a></p>
1
2016-09-14T19:30:29Z
39,498,563
<p>From my use of Python in the terminal, this command tells Python 'python3', so whatever version of Python 3.x your system is running, 'setup.py' is the Python script you're running and 'build' and 'install' are part of the distutils module to make it easier to install modules.</p>
0
2016-09-14T19:49:47Z
[ "python", "python-3.x", "build", "install" ]
Ιnitialising dictionary like class
39,498,302
<pre><code>class fileInfo(dict): def __init__(self, name, typ, size = 1): self = {} self["name"] = name self["type"] = typ self["size"] = size def __getitem__(self, key): if key == "name": return dict.__getitem__(self, "name")+ "." + dict.__getitem__(self, "type") return dict.__getitem__(self, key) </code></pre> <p>I have created this class, but I have problems with the <strong>init</strong> function. When I try to initialize an object of this class, the <strong>init</strong> function returns me an empty dictionary.</p> <p>What am I not understanding as far as the initialization function is concerned?</p>
2
2016-09-14T19:33:15Z
39,498,333
<p>This line doesn't do what you think it does:</p> <pre><code> self = {} </code></pre> <p>That line creates a new object of type <code>dict</code>, and binds the local name <code>self</code> to it. This is wholly unrelated to the previous value of <code>self</code>, which is lost. And, since <code>self</code> is a local variable, the object created by this line will be marked for deletion when <code>__init__()</code> returns.</p> <p>Try this instead:</p> <pre><code>super(fileInfo, self).__init__() </code></pre> <p>This neither creates nor destroys any objects, but modifies the object referred to by <code>self</code>.</p> <p>Reference:</p> <ul> <li><a href="http://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods">Understanding Python super() with __init__() methods</a></li> <li><a href="https://docs.python.org/2/reference/datamodel.html" rel="nofollow">https://docs.python.org/2/reference/datamodel.html</a></li> </ul>
2
2016-09-14T19:35:18Z
[ "python", "dictionary", "initialization" ]
Ιnitialising dictionary like class
39,498,302
<pre><code>class fileInfo(dict): def __init__(self, name, typ, size = 1): self = {} self["name"] = name self["type"] = typ self["size"] = size def __getitem__(self, key): if key == "name": return dict.__getitem__(self, "name")+ "." + dict.__getitem__(self, "type") return dict.__getitem__(self, key) </code></pre> <p>I have created this class, but I have problems with the <strong>init</strong> function. When I try to initialize an object of this class, the <strong>init</strong> function returns me an empty dictionary.</p> <p>What am I not understanding as far as the initialization function is concerned?</p>
2
2016-09-14T19:33:15Z
39,498,430
<p>The <code>__init__</code> method of any class is called once you create an instance of the class. You can't call it manually to instantiate the class, but use the class name.</p> <p>Also, you are not really initializing a class that inherits it's methods and properties from <code>dict</code>. You need to use <a href="https://docs.python.org/2/library/functions.html#super" rel="nofollow"><code>super</code></a> for that. Also, this is a case where calling <code>__init__</code> makes actual sense.</p> <pre><code>class fileInfo(dict): def __init__(self, name, typ, size = 1): super(fileInfo, self).__init__() self["name"] = name self["type"] = typ self["size"] = size def __getitem__(self, key): if key == "name": return dict.__getitem__(self, "name")+ "." + dict.__getitem__(self, "type") return dict.__getitem__(self, key) file_info = fileInfo("file-name", "txt", 100) print file_info["name"] </code></pre> <p>Output:</p> <pre><code>file-name.txt </code></pre>
0
2016-09-14T19:40:56Z
[ "python", "dictionary", "initialization" ]
How to use pymongo command updateUser
39,498,500
<p>How do i use pymongo command updateUser ?</p> <p>I've tried the following commands but with no success:</p> <pre><code>db.command({'updateUser': 'my_user','update':{'$set':{"pwd":"my_pwd"}}}) </code></pre> <p>And </p> <pre><code>db.command('updateUser', {"updateUser":"my_user","pwd":"my_pwd"}) </code></pre> <p>Returns</p> <pre><code>pymongo.errors.OperationFailure: Must specify at least one field to update in updateUser </code></pre> <p>Thanks.</p>
1
2016-09-14T19:45:35Z
39,503,243
<p>The python code is executing the MongoDB command "updateUser" on the database side. The command being executed in your code doesn't match the syntax shown in the <a href="https://docs.mongodb.com/manual/reference/command/updateUser/" rel="nofollow">updateUser documentation</a>.</p> <p>Try the following: </p> <pre><code>db.command( { updateUser: "&lt;username&gt;", pwd: "&lt;cleartext new password&gt;", roles: [ // specify any roles assigned to this user. ] }) </code></pre> <p>The command will completely replace the database user, so any and all role or permission information will need to be specified in the update command.</p>
0
2016-09-15T04:40:57Z
[ "python", "linux", "mongodb", "pymongo-3.x" ]
How can I create a new file containing a list with a single line of code?
39,498,525
<p>I know this is probably very easy to do, but I am very new to coding. I can accomplish this in more than one line, but for my assignment it needs to be done in one line.</p> <p>This is what I have, which raises an error that I don't understand.</p> <pre><code>trees = open('trees.txt', 'w').write["Tree1", "Tree2", "Tree3"] </code></pre> <blockquote> <p>TypeError: 'builtin_function_or_method' object is not subscriptable</p> </blockquote> <p>I imagine that my problem is that I can't just tack on the "write" command where/how I did, but I am lost on how to do this correctly. Thanks in advance for any help or hints!</p>
1
2016-09-14T19:47:31Z
39,498,613
<p>Just apply <code>write</code> on the file handle. To get proper text and not python list representation, you have to join the list into multiline text (if it's what you want!).</p> <p>Your fixed code (not the best there is, though):</p> <pre><code>open('trees.txt', 'w').write("\n".join(["Tree1", "Tree2", "Tree3"])) </code></pre> <p>BTW: I removed the assignment of <code>trees = open(...</code> since you get the return of the <code>write</code> operation which is <code>None</code></p> <p>note: this is a oneliner but not the proper way to go. Better use <code>with open</code></p> <pre><code>with open('trees.txt', 'w') as f: f.write("\n".join(["Tree1", "Tree2", "Tree3"])) </code></pre> <p>that way you are sure that the file is closed properly when going out of scope</p>
2
2016-09-14T19:53:03Z
[ "python", "list" ]
PyCharm Error Loading Package List
39,498,602
<p>I just downloaded PyCharm the other day and wanted to download a few packages. I'm using Windows 10 with PyCharm 2016.2.2 and python 3.5.2. When I go to the available packages screen it continually states:</p> <blockquote> <p>Error loading package list:pypi.python.org</p> </blockquote> <p>I was just trying to download BeautifulSoup and I'm clearly missing something. Any help would be wonderful.</p>
1
2016-09-14T19:52:28Z
39,498,957
<p>This was an issue this past summer: <a href="https://intellij-support.jetbrains.com/hc/en-us/community/posts/207207469-PyCharm-interpreter-can-t-find-new-packages" rel="nofollow">https://intellij-support.jetbrains.com/hc/en-us/community/posts/207207469-PyCharm-interpreter-can-t-find-new-packages</a></p> <p>Have you tried pulling from <a href="http://pypi.python.org/simple/" rel="nofollow">http://pypi.python.org/simple/</a> ?</p>
0
2016-09-14T20:17:40Z
[ "python", "pycharm", "pypi" ]
PyCharm Error Loading Package List
39,498,602
<p>I just downloaded PyCharm the other day and wanted to download a few packages. I'm using Windows 10 with PyCharm 2016.2.2 and python 3.5.2. When I go to the available packages screen it continually states:</p> <blockquote> <p>Error loading package list:pypi.python.org</p> </blockquote> <p>I was just trying to download BeautifulSoup and I'm clearly missing something. Any help would be wonderful.</p>
1
2016-09-14T19:52:28Z
39,499,006
<p>You should update to PyCharm 2016.2.3</p> <p><code>Help -&gt; Check for Updates...</code></p>
0
2016-09-14T20:20:50Z
[ "python", "pycharm", "pypi" ]
Drop null rows with dtype object from a DataFrame with Pandas
39,498,689
<p>I have a DataFrame that looks like this:</p> <pre><code>Oper ST result T2 9:24:09 NaN T3 9:25:10 Fail T4 9:25:36 Pass T5 9:25:36 NaN </code></pre> <p>I want to drop the NaN rows from the 'result' column. All columns are dtype object:</p> <pre><code>df.dtypes Oper object ST object result object </code></pre> <p>If I print the values and dytpes to a list they appear in this format:</p> <pre><code>rlist = df['result'].tolist() for r in rlist: print(r,type(r)) -&gt; nan &lt;class 'float'&gt; </code></pre> <p>I tried these things unsuccessfully:</p> <p>dropna:</p> <pre><code>df.dropna(subset=['result']) </code></pre> <p>filtering:</p> <pre><code>df = df[df['result'] != 'nan'] </code></pre> <p>I also tried to find a way to convert the object to a string and then filter but could not find a way to do that either. </p>
2
2016-09-14T19:57:56Z
39,498,743
<p><code>dropna</code> does not work in-place: you have to assign the result to the dataframe itself or it will be lost:</p> <pre><code> df = df.dropna(subset=['result']) </code></pre>
2
2016-09-14T20:01:38Z
[ "python", "pandas" ]
Passing arguments to Python from Shell Script
39,498,702
<p>I wrote a small shell script that looks like:</p> <pre><code>cd models/syntaxnet var1=$(jq --raw-output '.["avl_text"]' | syntaxnet/demo.sh) echo $var1 python /home/sree/python_code1.py $var1 </code></pre> <p>My <code>python_code1.py</code> looks like:</p> <p>import sys</p> <pre><code>data = sys.argv[1] print "In python code" print data print type(data) </code></pre> <p>Now, the output of echo $var1 in my shell script is exactly what I wanted to see:</p> <p><code>1 Check _ VERB VB _ 0 ROOT _ _ 2 out _ PRT RP _ 1 prt _ _ 3 this _ DET DT _ 4 det _ _ 4 video _ NOUN NN _ 1 dobj _ _ 5 about _ ADP IN _ 4 prep _ _ 6 Northwest _ NOUN NNP _ 7 nn _ _ 7 Arkansas _ NOUN NNP _ 5 pobj _ _ 8 - _ . , _ 7 punct _ _ 9 https _ X ADD _ 7 appos _ _</code></p> <p>But the output of <code>print data</code> in the python code is jus <code>1</code>. i.e. the first letter of the argument.</p> <p>Why is this happening? I want to pass the entire string to the python code.</p>
1
2016-09-14T19:58:40Z
39,498,877
<p>If there is space in between argument and argument is not in quotes, then python consider as two different arguments.</p> <p>That's why the output of print data in the python code is just 1.</p> <p>Check the below output.</p> <pre><code>[root@dsp-centos ~]# python dsp.py Dinesh Pundkar In python code Dinesh [root@dsp-centos ~]# python dsp.py "Dinesh Pundkar" In python code Dinesh Pundkar [root@dsp-centos ~]# </code></pre> <p><strong><em>So, in your shell script, put $var1 in quotes.</em></strong></p> <p><strong>Content of shell script(<em>a.sh</em>):</strong></p> <pre><code>var1="Dinesh Pundkar" python dsp.py "$var1" </code></pre> <p><strong>Content of python code(<em>dsp.py</em>)</strong>:</p> <pre><code>import sys data = sys.argv[1] print "In python code" print data </code></pre> <p><strong>Output:</strong></p> <pre><code>[root@dsp-centos ~]# sh a.sh In python code Dinesh Pundkar </code></pre>
1
2016-09-14T20:10:48Z
[ "python", "shell", "arguments" ]
Passing arguments to Python from Shell Script
39,498,702
<p>I wrote a small shell script that looks like:</p> <pre><code>cd models/syntaxnet var1=$(jq --raw-output '.["avl_text"]' | syntaxnet/demo.sh) echo $var1 python /home/sree/python_code1.py $var1 </code></pre> <p>My <code>python_code1.py</code> looks like:</p> <p>import sys</p> <pre><code>data = sys.argv[1] print "In python code" print data print type(data) </code></pre> <p>Now, the output of echo $var1 in my shell script is exactly what I wanted to see:</p> <p><code>1 Check _ VERB VB _ 0 ROOT _ _ 2 out _ PRT RP _ 1 prt _ _ 3 this _ DET DT _ 4 det _ _ 4 video _ NOUN NN _ 1 dobj _ _ 5 about _ ADP IN _ 4 prep _ _ 6 Northwest _ NOUN NNP _ 7 nn _ _ 7 Arkansas _ NOUN NNP _ 5 pobj _ _ 8 - _ . , _ 7 punct _ _ 9 https _ X ADD _ 7 appos _ _</code></p> <p>But the output of <code>print data</code> in the python code is jus <code>1</code>. i.e. the first letter of the argument.</p> <p>Why is this happening? I want to pass the entire string to the python code.</p>
1
2016-09-14T19:58:40Z
39,498,894
<p>Use Join and list slicing</p> <pre><code>import sys data = ' '.join(sys.argv[1:]) print "In python code" print data print type(data) </code></pre>
1
2016-09-14T20:12:57Z
[ "python", "shell", "arguments" ]
Compute the running max for a dataframe in pandas
39,498,729
<p>Given:</p> <pre class="lang-py prettyprint-override"><code>d = { 'High': [954, 953, 952, 955, 956, 952, 951, 950, ] } df = pandas.DataFrame(d) </code></pre> <p>I want to add another column which is the max at each index from the beginning. For example the desired column would be:</p> <pre class="lang-py prettyprint-override"><code>'Max': [954, 954, 954, 955, 956, 956, 956, 956] </code></pre> <p>I tried with a pandas rolling function but the window cannot be dynamic it seems</p>
3
2016-09-14T20:01:06Z
39,498,794
<p>Use <code>cummax</code></p> <pre><code>df.High.cummax() 0 954 1 954 2 954 3 955 4 956 5 956 6 956 7 956 Name: High, dtype: int64 </code></pre> <hr> <pre><code>df['Max'] = df.High.cummax() df </code></pre> <p><a href="http://i.stack.imgur.com/IfnS4.png" rel="nofollow"><img src="http://i.stack.imgur.com/IfnS4.png" alt="enter image description here"></a></p>
4
2016-09-14T20:04:42Z
[ "python", "pandas" ]
Computed static property in python
39,498,891
<p>Is it possible to have a static property on a class that would be computed as a one off. The idea would be to be able to do it like so:</p> <pre><code>class Foo: static_prop = Foo.one_off_static_method() @staticmethod def one_off_static_method(): return 'bar' </code></pre> <p>I thought of using <code>__new__</code> as well.</p> <pre><code>Class Foo: def __new__(cls): cls.static_prop = ... do everything here </code></pre> <p>Not sure the implications of that though.</p>
3
2016-09-14T20:12:23Z
39,498,950
<p>Until the class is actually created, <code>one_off_static_method</code> is just a regular function. It needs to be defined before you attempt to call it, since you want to call it while the <code>class</code> statement is being executed. Once you are done with it, you can simply delete it.</p> <pre><code>class Foo: def _one_off_static_method(): return 'bar' static_prop = _one_off_static_method() del _one_off_static_method </code></pre>
1
2016-09-14T20:16:57Z
[ "python", "static-methods" ]
Computed static property in python
39,498,891
<p>Is it possible to have a static property on a class that would be computed as a one off. The idea would be to be able to do it like so:</p> <pre><code>class Foo: static_prop = Foo.one_off_static_method() @staticmethod def one_off_static_method(): return 'bar' </code></pre> <p>I thought of using <code>__new__</code> as well.</p> <pre><code>Class Foo: def __new__(cls): cls.static_prop = ... do everything here </code></pre> <p>Not sure the implications of that though.</p>
3
2016-09-14T20:12:23Z
39,499,163
<p>If you want it computed at class definition time, see <a href="http://stackoverflow.com/a/39498950/674039">chepner's answer</a> - although I would recommend just to use a module level function instead.</p> <p>If you want it lazily evaluated, then you might be interested in a <a href="https://pypi.python.org/pypi/cached-property/" rel="nofollow"><code>cached_property</code></a>. </p> <pre><code>&gt;&gt;&gt; from random import random &gt;&gt;&gt; from cached_property import cached_property &gt;&gt;&gt; class Foo(object): ... @cached_property ... def one_off_thing(self): ... print('computing...') ... return random() ... &gt;&gt;&gt; foo = Foo() &gt;&gt;&gt; foo.one_off_thing computing... 0.5804382038855782 &gt;&gt;&gt; foo.one_off_thing 0.5804382038855782 </code></pre> <p><em>Note:</em> it seems every man and his dog has an implementation of memo decorators in Python, this is one of many. If you're on Python 3, consider <a href="https://docs.python.org/3/library/functools.html#functools.lru_cache" rel="nofollow">functools.lru_cache</a> because it's in the core libraries. </p>
2
2016-09-14T20:30:42Z
[ "python", "static-methods" ]
Computed static property in python
39,498,891
<p>Is it possible to have a static property on a class that would be computed as a one off. The idea would be to be able to do it like so:</p> <pre><code>class Foo: static_prop = Foo.one_off_static_method() @staticmethod def one_off_static_method(): return 'bar' </code></pre> <p>I thought of using <code>__new__</code> as well.</p> <pre><code>Class Foo: def __new__(cls): cls.static_prop = ... do everything here </code></pre> <p>Not sure the implications of that though.</p>
3
2016-09-14T20:12:23Z
39,499,304
<p>Here you go, I made a small descriptor for you :-)</p> <p>Upon accessing the attribute, it will be computed and cached.</p> <pre><code>class CachedStaticProperty: """Works like @property and @staticmethod combined""" def __init__(self, func): self.func = func def __get__(self, inst, owner): result = self.func() setattr(owner, self.func.__name__, result) return result </code></pre> <p>The way it works is rather simple:</p> <ol> <li>Upon using the decorator syntax, I save the function internally.</li> <li>Upon access, I call the function and set the value as the class value with the same name as the original function.</li> </ol> <p>That's all there is to it. Simple and efficient.</p>
0
2016-09-14T20:39:32Z
[ "python", "static-methods" ]
Unable to subset Pandas dataframe
39,498,923
<p>I have the following data in a data frame named <code>in_file</code>:</p> <pre><code>Client Value_01 Value_02 Date ABC 100 500 2016-09-01T ABC 14 90 2016-09-02T DEF 95 1000 2016-09-01T DEF 200 600 2016-09-02T GHI 75 19 2016-09-01T GHI 300 700 2016-09-02T JKL 50 02 2016-09-01T JKL 400 800 2016-09-02T </code></pre> <p>I subset the data frame with the following (which we'll call 'subset 1'):</p> <pre><code>df_01 = in_file.loc[(in_file.Date == '2016-09-01T') &amp; (in_file.Client &lt;&gt; 'ABC') &amp; (in_file.Client &lt;&gt; 'DEF')].sort_values('Value_01', ascending=False) </code></pre> <p>and I get back:</p> <pre><code>Client Value_01 Value_02 Date GHI 75 19 2016-09-01T JKL 50 02 2016-09-01T </code></pre> <p>Then, I attempt to subset the data frame with the following (which we'll call 'subset 2'):</p> <pre><code>df_02 = in_file.loc[(in_file.Date == '2016-09-01T') &amp; (in_file.Client == 'ABC') &amp; (in_file.Client == 'DEF')].sort_values('Value_01', ascending=False) </code></pre> <p>With 'subset 2', I get back an <strong>empty data frame</strong>. But, I was expecting to see the following:</p> <pre><code>Client Value_01 Value_02 Date ABC 100 500 2016-09-01T DEF 95 1000 2016-09-01T </code></pre> <p>Does anyone know why the 'subset 2' code is not returning the data frame that I expect?</p> <p>Thanks in advance.</p>
2
2016-09-14T20:15:26Z
39,499,047
<p>including <code>isin()</code>:</p> <pre><code>In [28]: in_file.loc[(in_file.Date == '2016-09-01T') &amp; in_file.Client.isin(['ABC', 'DEF'])].sort_values('Value_01', ascending=False) Out[28]: Client Value_01 Value_02 Date 0 ABC 100 500 2016-09-01T 2 DEF 95 1000 2016-09-01T </code></pre> <p>excluding:</p> <pre><code>In [29]: in_file.loc[(in_file.Date == '2016-09-01T') &amp; (~in_file.Client.isin(['ABC', 'DEF']))].sort_values('Value_01', ascending=False) Out[29]: Client Value_01 Value_02 Date 4 GHI 75 19 2016-09-01T 6 JKL 50 2 2016-09-01T </code></pre> <p>Or bit slower, but much nicer <code>query()</code> method:</p> <pre><code>In [30]: in_file.query("Date == '2016-09-01T' and Client in ['ABC', 'DEF']") Out[30]: Client Value_01 Value_02 Date 0 ABC 100 500 2016-09-01T 2 DEF 95 1000 2016-09-01T In [31]: in_file.query("Date == '2016-09-01T' and Client not in ['ABC', 'DEF']") Out[31]: Client Value_01 Value_02 Date 4 GHI 75 19 2016-09-01T 6 JKL 50 2 2016-09-01T </code></pre>
2
2016-09-14T20:22:52Z
[ "python", "pandas", "subset" ]
Unable to subset Pandas dataframe
39,498,923
<p>I have the following data in a data frame named <code>in_file</code>:</p> <pre><code>Client Value_01 Value_02 Date ABC 100 500 2016-09-01T ABC 14 90 2016-09-02T DEF 95 1000 2016-09-01T DEF 200 600 2016-09-02T GHI 75 19 2016-09-01T GHI 300 700 2016-09-02T JKL 50 02 2016-09-01T JKL 400 800 2016-09-02T </code></pre> <p>I subset the data frame with the following (which we'll call 'subset 1'):</p> <pre><code>df_01 = in_file.loc[(in_file.Date == '2016-09-01T') &amp; (in_file.Client &lt;&gt; 'ABC') &amp; (in_file.Client &lt;&gt; 'DEF')].sort_values('Value_01', ascending=False) </code></pre> <p>and I get back:</p> <pre><code>Client Value_01 Value_02 Date GHI 75 19 2016-09-01T JKL 50 02 2016-09-01T </code></pre> <p>Then, I attempt to subset the data frame with the following (which we'll call 'subset 2'):</p> <pre><code>df_02 = in_file.loc[(in_file.Date == '2016-09-01T') &amp; (in_file.Client == 'ABC') &amp; (in_file.Client == 'DEF')].sort_values('Value_01', ascending=False) </code></pre> <p>With 'subset 2', I get back an <strong>empty data frame</strong>. But, I was expecting to see the following:</p> <pre><code>Client Value_01 Value_02 Date ABC 100 500 2016-09-01T DEF 95 1000 2016-09-01T </code></pre> <p>Does anyone know why the 'subset 2' code is not returning the data frame that I expect?</p> <p>Thanks in advance.</p>
2
2016-09-14T20:15:26Z
39,499,119
<p>You have two conflicting conditions for your second subset dataframe</p> <p><code>(in_file.Client == 'ABC')</code> &amp; <code>(in_file.Client == 'DEF')</code></p> <p>Can never both be true at the same time. </p> <p>What you seem to be looking for is 'or' logic not '&amp;' logic. So </p> <p><code>df_02 = in_file.loc[(in_file.Date == '2016-09-02T') or (in_file.Client == 'ABC') or (in_file.Client == 'DEF')].sort_values('Value_01', ascending=False)</code></p> <p>will give you</p> <pre><code>ABC 100 500 2016-09-01T ABC 14 90 2016-09-02T DEF 95 1000 2016-09-01T DEF 200 600 2016-09-02T GHI 300 700 2016-09-02T JKL 400 800 2016-09-02T </code></pre>
0
2016-09-14T20:27:41Z
[ "python", "pandas", "subset" ]
Unable to subset Pandas dataframe
39,498,923
<p>I have the following data in a data frame named <code>in_file</code>:</p> <pre><code>Client Value_01 Value_02 Date ABC 100 500 2016-09-01T ABC 14 90 2016-09-02T DEF 95 1000 2016-09-01T DEF 200 600 2016-09-02T GHI 75 19 2016-09-01T GHI 300 700 2016-09-02T JKL 50 02 2016-09-01T JKL 400 800 2016-09-02T </code></pre> <p>I subset the data frame with the following (which we'll call 'subset 1'):</p> <pre><code>df_01 = in_file.loc[(in_file.Date == '2016-09-01T') &amp; (in_file.Client &lt;&gt; 'ABC') &amp; (in_file.Client &lt;&gt; 'DEF')].sort_values('Value_01', ascending=False) </code></pre> <p>and I get back:</p> <pre><code>Client Value_01 Value_02 Date GHI 75 19 2016-09-01T JKL 50 02 2016-09-01T </code></pre> <p>Then, I attempt to subset the data frame with the following (which we'll call 'subset 2'):</p> <pre><code>df_02 = in_file.loc[(in_file.Date == '2016-09-01T') &amp; (in_file.Client == 'ABC') &amp; (in_file.Client == 'DEF')].sort_values('Value_01', ascending=False) </code></pre> <p>With 'subset 2', I get back an <strong>empty data frame</strong>. But, I was expecting to see the following:</p> <pre><code>Client Value_01 Value_02 Date ABC 100 500 2016-09-01T DEF 95 1000 2016-09-01T </code></pre> <p>Does anyone know why the 'subset 2' code is not returning the data frame that I expect?</p> <p>Thanks in advance.</p>
2
2016-09-14T20:15:26Z
39,499,133
<p><strong><em>Caveat</em></strong> This is not the best solution!!!<br> I only want to point out what you were doing wrong.<br> @MaxU has the best answer</p> <p>define <code>cond2</code></p> <pre><code>cond2 = (in_file.Date == '2016-09-01T') &amp; \ (in_file.Client == 'ABC') &amp; \ (in_file.Client == 'DEF') </code></pre> <p>This will always be <code>False</code> as <code>in_file.Client</code> can never be both <code>'ABC'</code> and <code>'DEF'</code>. You must use 'or' <code>|</code></p> <p>Instead</p> <pre><code>cond2 = (in_file.Date == '2016-09-01T') &amp; \ ((in_file.Client == 'ABC') | (in_file.Client == 'DEF')) </code></pre> <p>Then</p> <pre><code>df_02 = in_file.loc[cond2].sort_values('Value_01', ascending=False) df_02 </code></pre> <p><a href="http://i.stack.imgur.com/czQvv.png" rel="nofollow"><img src="http://i.stack.imgur.com/czQvv.png" alt="enter image description here"></a></p> <hr> <h1>But Don't Choose This Answer</h1> <p>It is not as good as using <code>isin</code></p>
0
2016-09-14T20:28:45Z
[ "python", "pandas", "subset" ]
Join all PostgreSQL tables and make a Python dictionary
39,498,948
<p>I need to join <strong>all</strong> PostgreSQL tables and convert them in a Python dictionary. There are 72 tables in the database. The total number of columns is greater than <strong>1600</strong>. </p> <p>I wrote a simple Python script that joins several tables but fails to join all of them due to <a href="https://gist.github.com/SergeyBondarenko/a753689a86b9af209e6dd6ef2c2f7eef" rel="nofollow">the memory error</a>. All memory is occupied during the script execution. And I run the script on a new virtual server with <strong>128GB</strong> RAM and 8 CPU. It fails during the lambda function execution. </p> <p>How could the following code be improved to execute <strong>all</strong> tables join?</p> <pre><code>from sqlalchemy import create_engine import pandas as pd auth = 'user:pass' engine = create_engine('postgresql://' + auth + '@host.com:5432/db') sql_tables = ['table0', 'table1', 'table3', ..., 'table72'] df_arr = [] [df_arr.append(pd.read_sql_query('select * from "' + table + '"', con=engine)) for table in sql_tables] df_join = reduce(lambda left, right: pd.merge(left, right, how='outer', on=['USER_ID']), df_arr) raw_dict = pd.DataFrame.to_dict(df_join.where((pd.notnull(df_join)), 'no_data')) print(df_join) print(raw_dict) print(len(df_arr)) </code></pre> <p>Is it ok to use <a href="http://pandas.pydata.org/pandas-docs/stable/" rel="nofollow">Pandas</a> for my purpose? Are there better solutions?</p> <p>The ultimate goal is to <a href="https://www.elastic.co/guide/en/elasticsearch/guide/current/denormalization.html" rel="nofollow">denormalize</a> DB data to be able to index it into <a href="https://www.elastic.co" rel="nofollow">Elasticsearch</a> as documents, one document per user.</p>
5
2016-09-14T20:16:56Z
39,499,237
<p>I'm not certain this will help, but you can try <code>pd.concat</code></p> <pre><code>raw_dict = pd.concat([d.set_index('USER_ID') for d in df_arr], axis=1) </code></pre> <p>Or, to get a bit more disctinction</p> <pre><code>raw_dict = pd.concat([d.set_index('USER_ID') for d in df_arr], axis=1, keys=sql_tables) </code></pre> <hr> <p>If this isn't helpful, let me know and I'll delete it.</p>
0
2016-09-14T20:35:05Z
[ "python", "database", "postgresql", "pandas", "elasticsearch" ]
Join all PostgreSQL tables and make a Python dictionary
39,498,948
<p>I need to join <strong>all</strong> PostgreSQL tables and convert them in a Python dictionary. There are 72 tables in the database. The total number of columns is greater than <strong>1600</strong>. </p> <p>I wrote a simple Python script that joins several tables but fails to join all of them due to <a href="https://gist.github.com/SergeyBondarenko/a753689a86b9af209e6dd6ef2c2f7eef" rel="nofollow">the memory error</a>. All memory is occupied during the script execution. And I run the script on a new virtual server with <strong>128GB</strong> RAM and 8 CPU. It fails during the lambda function execution. </p> <p>How could the following code be improved to execute <strong>all</strong> tables join?</p> <pre><code>from sqlalchemy import create_engine import pandas as pd auth = 'user:pass' engine = create_engine('postgresql://' + auth + '@host.com:5432/db') sql_tables = ['table0', 'table1', 'table3', ..., 'table72'] df_arr = [] [df_arr.append(pd.read_sql_query('select * from "' + table + '"', con=engine)) for table in sql_tables] df_join = reduce(lambda left, right: pd.merge(left, right, how='outer', on=['USER_ID']), df_arr) raw_dict = pd.DataFrame.to_dict(df_join.where((pd.notnull(df_join)), 'no_data')) print(df_join) print(raw_dict) print(len(df_arr)) </code></pre> <p>Is it ok to use <a href="http://pandas.pydata.org/pandas-docs/stable/" rel="nofollow">Pandas</a> for my purpose? Are there better solutions?</p> <p>The ultimate goal is to <a href="https://www.elastic.co/guide/en/elasticsearch/guide/current/denormalization.html" rel="nofollow">denormalize</a> DB data to be able to index it into <a href="https://www.elastic.co" rel="nofollow">Elasticsearch</a> as documents, one document per user.</p>
5
2016-09-14T20:16:56Z
39,499,314
<p>Why don't you create a postgres function instead of script?</p> <p>Here are some advises that could help you to avoid the memory error:</p> <ul> <li>You can use <strong>WITH</strong> clause which makes better use of your memory.</li> <li>You can create some physical tables for storing the information of different groups of tables of your database. These physical tables will avoid to use a great amount of memory. After that, all you have to do is joining only those physical tables. You can create a function for it.</li> <li>You can create a Data Warehouse by denormalizing the tables you need. </li> <li>Last but not least: Make sure you are using <strong>Indexes</strong> appropriately.</li> </ul>
1
2016-09-14T20:40:07Z
[ "python", "database", "postgresql", "pandas", "elasticsearch" ]
Date and Time Python (Stuck)
39,499,079
<p>I am Python beginner. I have a question about Date and time code:</p> <pre><code>import datetime date = datetime.date.today() print(date.strftime('date is %d%b,%Y')) </code></pre> <p>Now I want to print the date of my own choice. How can I do it? </p> <p>For example, if today's date is (15 sep 2016) and I want to print (23 oct 1998), what should I do in order to make it work?</p>
1
2016-09-14T20:24:51Z
39,499,117
<p>You may do it like so:</p> <pre><code>&gt;&gt;&gt; from datetime import date &gt;&gt;&gt; date(year=1998, month=10, day=23) datetime.date(1998, 10, 23) &gt;&gt;&gt; _.strftime('date is %d %b,%Y') 'date is 23 Oct,1998' </code></pre> <p>As per <a href="https://docs.python.org/3/library/datetime.html#datetime.date" rel="nofollow"><code>datetime.date()</code></a> documentation, <code>date()</code> accepts a year, month and a day.</p>
1
2016-09-14T20:27:39Z
[ "python" ]
Date and Time Python (Stuck)
39,499,079
<p>I am Python beginner. I have a question about Date and time code:</p> <pre><code>import datetime date = datetime.date.today() print(date.strftime('date is %d%b,%Y')) </code></pre> <p>Now I want to print the date of my own choice. How can I do it? </p> <p>For example, if today's date is (15 sep 2016) and I want to print (23 oct 1998), what should I do in order to make it work?</p>
1
2016-09-14T20:24:51Z
39,499,156
<p>You can initialize date using datetime constructor.</p> <pre><code>&gt;&gt;&gt;import datetime &gt;&gt;&gt;d = datetime.datetime(1998,10,23) &gt;&gt;&gt;print(d.strftime('date is %d %b,%Y')) </code></pre>
0
2016-09-14T20:30:27Z
[ "python" ]
Date and Time Python (Stuck)
39,499,079
<p>I am Python beginner. I have a question about Date and time code:</p> <pre><code>import datetime date = datetime.date.today() print(date.strftime('date is %d%b,%Y')) </code></pre> <p>Now I want to print the date of my own choice. How can I do it? </p> <p>For example, if today's date is (15 sep 2016) and I want to print (23 oct 1998), what should I do in order to make it work?</p>
1
2016-09-14T20:24:51Z
39,499,203
<p>If you needed to take a string value as input you can use</p> <pre><code>from dateutil import parser datestring = "23 Oct 1998" customDate = parser.parse(datestring) print(customDate.strftime('date is %d%b,%y')) </code></pre>
0
2016-09-14T20:33:10Z
[ "python" ]
plotly - changing the line styles
39,499,173
<p>I am trying to plot multiple yet related things on a plotly graph. </p> <p>I want to differentiate and relate the lines at the same time. To make myself more clearer, I am plotting ROC characteristics of the classifiers that I trained. I want a particular classifier of the same color but different line styles for the method of training.</p> <p>I currently use this to fulfill my requirement: <a href="http://i.stack.imgur.com/yqGq9.png" rel="nofollow"><img src="http://i.stack.imgur.com/yqGq9.png" alt="enter image description here"></a></p> <p>Here is the code for the same,</p> <pre><code> data = [ go.Scatter( mode='lines+markers', x=df_LogisticRegression['FPR'], # assign x as the dataframe column 'x' y=df_LogisticRegression['TPR'], name = "Logistic Regression all attributes", marker=dict( color="blue", symbol='square' ), ), # and so on for all other algos go.Scatter( mode='lines+markers', x=df_LogisticRegression_nonSP['FPR'], # assign x as the dataframe column 'x' y=df_LogisticRegression_nonSP['TPR'], name = "Logistic Regression non-sparse attributes", marker=dict( color="blue", symbol='square-open' ), ), # and so on for all other algos ] layout = go.Layout( title='ROC Curve', yaxis=dict(title='True Positive Rates(TPR)'), xaxis=dict(title='False Positive Rates(FPR)') ) fig = go.Figure(data=data,layout=layout) iplot(fig) </code></pre> <p>For instance, I am looking to have the color of logistic regression as blue, but the one with "all attributes should be a solid line and the one with "non-sparse attributes" should be broken lines.</p> <p>I tried to look up and read up the documentation for plotly but could not find anything help.</p>
0
2016-09-14T20:31:34Z
39,499,306
<p>It is because the plotly, plots the data based on the mode which you ask it to do. If you say <code>mode=markers</code> it is going to plot just the markers. If you say <code>mode=lines</code> it is going the join all the points in the data and plot it as lines.</p> <p>Please see this page <a href="https://plot.ly/python/line-and-scatter/#line-and-scatter-plots" rel="nofollow">https://plot.ly/python/line-and-scatter/#line-and-scatter-plots</a> for more examples of lines that can be plotted using plotly. </p>
0
2016-09-14T20:39:32Z
[ "python", "plot", "plotly", "roc" ]
numpy.genfromtxt- ValueError- Line # (got n columns instead of m)
39,499,231
<p>So, I've been writing up code to read in a dataset from a file and separate it out for analysis. </p> <p>The data in question is read from a .dat file, and looks like this:</p> <pre><code>14 HO2 O3 OH O2 O2 15 HO2 HO2 H2O2 O2 16 H2O2 OH HO2 H2O 17 O O O2 18 O O2 O3 19 O O3 O2 O2 </code></pre> <p>The code I've written looks like this:</p> <pre><code>edge_data=np.genfromtxt('Early_earth_reaction.dat', dtype = str, missing_values=True, filling_values=bool) </code></pre> <p>The plan was that I'd then run the values from the dataset and build a paired list from them.</p> <pre><code>edge_list=[] for i in range(360): edge_list.append((edge_data[i,0],edge_data[i,2])) edge_list.append((edge_data[i,1],edge_data[i,2])) print edge_data[i,0] if edge_data[i,3] != None: edge_list.append((edge_data[i,0],edge_data[i,3])) edge_list.append((edge_data[i,1],edge_data[i,3])) if edge_data[i,4]!= None: edge_list.append((edge_data[i,0],edge_data[i,4])) edge_list.append((edge_data[i,1,edge_data[i,4])) </code></pre> <p>However, upon running it, I get the error message </p> <pre><code>File "read_early_earth.py", line 52, in main edge_data=np.genfromtxt('Early_earth_reaction.dat', dtype = str, usecols=(1,2,3,4,5), missing_values=True, filling_values=bool) File "/usr/lib/python2.7/dist-packages/numpy/lib/npyio.py", line 1667, in genfromtxt raise ValueError(errmsg) ValueError: Some errors were detected ! Line #6 (got 4 columns instead of 5) Line #14 (got 6 columns instead of 5) Line #17 (got 4 columns instead of 5) </code></pre> <p>And so on and so forth. As far as I can tell, this is happening because there are rows where not all the columns have values in them, which apparently throws numpy for a loop. </p> <p>Is there a work-around for this in numpy? Alternatively, is there another way to accomplish this task? I know, worse comes to worse, I can torture some regular expressions into doing the job, but I'd prefer a method that's a bit more efficient if at all possible.</p> <p>Thanks!</p>
3
2016-09-14T20:34:50Z
39,500,178
<p>Looks like you've already read <code>genfromtxt</code> about missing values. Does it say anything about the use of delimiters?</p> <p>I think it can handle missing values with lines like</p> <pre><code>'one, 1, 234.4, , ,' 'two, 3, , 4, 5' </code></pre> <p>but when the delimiter is the default 'white-space' it can't. One of the first steps after reading a line is</p> <pre><code> strings = line.split(delimiter) </code></pre> <p>And objects if <code>len(strings)</code> doesn't match with the initial target. Apparently it does not try to guess that you want to pad the line with <code>n-len(strings)</code> missing values.</p> <p>Options that come to mind:</p> <ul> <li><p>try Pandas; it may make more effort to guess your intentions</p></li> <li><p>write your own reader. Pandas is compiled; <code>genfromtxt</code> is plain numpy Python. It reads the file line by line, splits and converts fields, and appends the list to a master list. It converts that list of lists into array at the end. Your own reader should be just as efficient.</p></li> <li><p>preprocess your file to add the missing values or change the delimiter. <code>genfromtxt</code> accepts anything that feeds it lines. So it works with a list of strings, a file reader that yields modified lines, etc. This may be simplest.</p> <p>def foo(astr): strs=astr.split() if len(strs)&lt;6: strs.extend([b' ']*(6-len(strs))) return b','.join(strs)</p></li> </ul> <p>Simulating with a list of strings (in Py3):</p> <pre><code>In [139]: txt=b"""14 HO2 O3 OH O2 O2 ...: 15 HO2 HO2 H2O2 O2 ...: 16 H2O2 OH HO2 H2O ...: 17 O O O2 ...: 18 O O2 O3 ...: 19 O O3 O2 O2""".splitlines() In [140]: [foo(l) for l in txt] Out[140]: [b'14,HO2,O3,OH,O2,O2', b'15,HO2,HO2,H2O2,O2, ', b'16,H2O2,OH,HO2,H2O, ', b'17,O,O,O2, , ', b'18,O,O2,O3, , ', b'19,O,O3,O2,O2, '] In [141]: np.genfromtxt([foo(l) for l in txt], dtype=None, delimiter=',') Out[141]: array([(14, b'HO2', b'O3', b'OH', b'O2', b'O2'), (15, b'HO2', b'HO2', b'H2O2', b'O2', b''), (16, b'H2O2', b'OH', b'HO2', b'H2O', b''), (17, b'O', b'O', b'O2', b' ', b''), (18, b'O', b'O2', b'O3', b' ', b''), (19, b'O', b'O3', b'O2', b'O2', b'')], dtype=[('f0', '&lt;i4'), ('f1', 'S4'), ('f2', 'S3'), ('f3', 'S4'), ('f4', 'S3'), ('f5', 'S2')]) </code></pre>
2
2016-09-14T21:49:48Z
[ "python", "numpy", "genfromtxt" ]
numpy.genfromtxt- ValueError- Line # (got n columns instead of m)
39,499,231
<p>So, I've been writing up code to read in a dataset from a file and separate it out for analysis. </p> <p>The data in question is read from a .dat file, and looks like this:</p> <pre><code>14 HO2 O3 OH O2 O2 15 HO2 HO2 H2O2 O2 16 H2O2 OH HO2 H2O 17 O O O2 18 O O2 O3 19 O O3 O2 O2 </code></pre> <p>The code I've written looks like this:</p> <pre><code>edge_data=np.genfromtxt('Early_earth_reaction.dat', dtype = str, missing_values=True, filling_values=bool) </code></pre> <p>The plan was that I'd then run the values from the dataset and build a paired list from them.</p> <pre><code>edge_list=[] for i in range(360): edge_list.append((edge_data[i,0],edge_data[i,2])) edge_list.append((edge_data[i,1],edge_data[i,2])) print edge_data[i,0] if edge_data[i,3] != None: edge_list.append((edge_data[i,0],edge_data[i,3])) edge_list.append((edge_data[i,1],edge_data[i,3])) if edge_data[i,4]!= None: edge_list.append((edge_data[i,0],edge_data[i,4])) edge_list.append((edge_data[i,1,edge_data[i,4])) </code></pre> <p>However, upon running it, I get the error message </p> <pre><code>File "read_early_earth.py", line 52, in main edge_data=np.genfromtxt('Early_earth_reaction.dat', dtype = str, usecols=(1,2,3,4,5), missing_values=True, filling_values=bool) File "/usr/lib/python2.7/dist-packages/numpy/lib/npyio.py", line 1667, in genfromtxt raise ValueError(errmsg) ValueError: Some errors were detected ! Line #6 (got 4 columns instead of 5) Line #14 (got 6 columns instead of 5) Line #17 (got 4 columns instead of 5) </code></pre> <p>And so on and so forth. As far as I can tell, this is happening because there are rows where not all the columns have values in them, which apparently throws numpy for a loop. </p> <p>Is there a work-around for this in numpy? Alternatively, is there another way to accomplish this task? I know, worse comes to worse, I can torture some regular expressions into doing the job, but I'd prefer a method that's a bit more efficient if at all possible.</p> <p>Thanks!</p>
3
2016-09-14T20:34:50Z
39,502,405
<p>It looks like your data is nicely aligned in fields of exactly 10 characters. If that is always the case, you can tell <code>genfromtxt</code> the field widths to use by specifying the sequence of field widths in the <code>delimiter</code> argument.</p> <p>Here's an example.</p> <p>First, your data file:</p> <pre><code>In [20]: !cat reaction.dat 14 HO2 O3 OH O2 O2 15 HO2 HO2 H2O2 O2 16 H2O2 OH HO2 H2O 17 O O O2 18 O O2 O3 19 O O3 O2 O2 </code></pre> <p>For convenience, I'll define the number of fields and the field width here. (In general, it is not necessary that all the fields have the same width.)</p> <pre><code>In [21]: numfields = 6 In [22]: fieldwidth = 10 </code></pre> <p>Tell <code>genfromtxt</code> that the data is in fixed width columns by passing in the argument <code>delimiter=(10, 10, 10, 10, 10, 10)</code>:</p> <pre><code>In [23]: data = genfromtxt('reaction.dat', dtype='S%d' % fieldwidth, delimiter=(fieldwidth,)*numfields) </code></pre> <p>Here's the result. Note that "missing" fields are empty strings. Also note that non-empty fields include the white space, and the last non-empty field in each row includes the newline character:</p> <pre><code>In [24]: data Out[24]: array([[b'14 ', b'HO2 ', b'O3 ', b'OH ', b'O2 ', b'O2\n'], [b'15 ', b'HO2 ', b'HO2 ', b'H2O2 ', b'O2\n', b''], [b'16 ', b'H2O2 ', b'OH ', b'HO2 ', b'H2O\n', b''], [b'17 ', b'O ', b'O ', b'O2\n', b'', b''], [b'18 ', b'O ', b'O2 ', b'O3\n', b'', b''], [b'19 ', b'O ', b'O3 ', b'O2 ', b'O2\n', b'']], dtype='|S10') In [25]: data[1] Out[25]: array([b'15 ', b'HO2 ', b'HO2 ', b'H2O2 ', b'O2\n', b''], dtype='|S10') </code></pre> <p>We could clean up the strings in a second step, or we can have <code>genfromtxt</code> do it by providing a converter for each field that simply strips the white space from the field:</p> <pre><code>In [26]: data = genfromtxt('reaction.dat', dtype='S%d' % fieldwidth, delimiter=(fieldwidth,)*numfields, converters={k: lambda s: s. ...: strip() for k in range(numfields)}) In [27]: data Out[27]: array([[b'14', b'HO2', b'O3', b'OH', b'O2', b'O2'], [b'15', b'HO2', b'HO2', b'H2O2', b'O2', b''], [b'16', b'H2O2', b'OH', b'HO2', b'H2O', b''], [b'17', b'O', b'O', b'O2', b'', b''], [b'18', b'O', b'O2', b'O3', b'', b''], [b'19', b'O', b'O3', b'O2', b'O2', b'']], dtype='|S10') In [28]: data[:,0] Out[28]: array([b'14', b'15', b'16', b'17', b'18', b'19'], dtype='|S10') In [29]: data[:,5] Out[29]: array([b'O2', b'', b'', b'', b'', b''], dtype='|S10') </code></pre>
0
2016-09-15T02:45:33Z
[ "python", "numpy", "genfromtxt" ]
Write to a file with sudo privileges in Python
39,499,233
<p>The following code throws an error if it's run by a non-root user for a file owned by root, even when the non-root user has sudo privileges:</p> <pre><code>try: f = open(filename, "w+") except IOError: sys.stderr.write('Error: Failed to open file %s' % (filename)) f.write(response + "\n" + new_line) f.close() </code></pre> <p>Is there a way to run <code>open(filename, "w+")</code> with sudo privileges, or an alternative function that does this?</p>
5
2016-09-14T20:34:54Z
39,499,327
<p>Your script is limited to the permissions it is run with as you cannot change users without already having root privileges.</p> <p>As Rob said, the only way to do this without changing your file permissions is to run with <code>sudo</code>.</p> <pre><code>sudo python ./your_file.py </code></pre>
0
2016-09-14T20:41:07Z
[ "python", "file-writing", "ioerror" ]
Write to a file with sudo privileges in Python
39,499,233
<p>The following code throws an error if it's run by a non-root user for a file owned by root, even when the non-root user has sudo privileges:</p> <pre><code>try: f = open(filename, "w+") except IOError: sys.stderr.write('Error: Failed to open file %s' % (filename)) f.write(response + "\n" + new_line) f.close() </code></pre> <p>Is there a way to run <code>open(filename, "w+")</code> with sudo privileges, or an alternative function that does this?</p>
5
2016-09-14T20:34:54Z
39,499,692
<p>You have a few options:</p> <ul> <li>Run your script as root or with sudo</li> <li>Set the setuid bit and have root own the script (although on many systems this won't work with scripts, and then the script will be callable by anyone)</li> <li>Detect that you're not running as root (<code>os.geteuid() != 0</code>), then call yourself with <code>sudo</code> infront (which will ask the user to enter their password) and exit:</li> </ul> <p>‌</p> <pre><code>import os import sys import subprocess if os.geteuid() == 0: print("We're root!") else: print("We're not root.") subprocess.call(['sudo', 'python3', *sys.argv]) </code></pre> <p>Calling it looks like this:</p> <pre><code>$ python3 be_root.py We're not root. Password: We're root! </code></pre>
1
2016-09-14T21:10:53Z
[ "python", "file-writing", "ioerror" ]
Write to a file with sudo privileges in Python
39,499,233
<p>The following code throws an error if it's run by a non-root user for a file owned by root, even when the non-root user has sudo privileges:</p> <pre><code>try: f = open(filename, "w+") except IOError: sys.stderr.write('Error: Failed to open file %s' % (filename)) f.write(response + "\n" + new_line) f.close() </code></pre> <p>Is there a way to run <code>open(filename, "w+")</code> with sudo privileges, or an alternative function that does this?</p>
5
2016-09-14T20:34:54Z
39,499,718
<p>Having possibility to using <code>sudo</code> don't give you any privileges if you don't actually use it. So as other guys suggested you probably should just start your program with use of <code>sudo</code>. But if you don't like this idea (I don't see any reason for that) you can do other trick.</p> <p>Your script can check if is run with root privileges or if it work only with user privileges. Than script can actually run itself with higher privileges. Here you have an example (please note that storing password in source code isn't a good idea). </p> <pre><code>import os.path import subprocess password_for_sudo = 'pass' def started_as_root(): if subprocess.check_output('whoami').strip() == 'root': return True return False def runing_with_root_privileges(): print 'I have the power!' def main(): if started_as_root(): print 'OK, I have root privileges. Calling the function...' runing_with_root_privileges() else: print "I'm just a user. Need to start new process with root privileges..." current_script = os.path.realpath(__file__) os.system('echo %s|sudo -S python %s' % (password_for_sudo, current_script)) if __name__ == '__main__': main() </code></pre> <p>Output:</p> <pre><code>$ python test.py I'm just a user. Need to start new process with root privileges... OK, I have root privileges. Calling the function... I have the power! $ sudo python test.py OK, I have root privileges. Calling the function... I have the power! </code></pre>
0
2016-09-14T21:12:43Z
[ "python", "file-writing", "ioerror" ]
what is the wrong with my Dividing Sequences code
39,499,275
<p>I am trying to code this problem: </p> <blockquote> <p>This problem is about sequences of positive integers a1,a2,...,aN. A subsequence of a sequence is anything obtained by dropping some of the elements. For example, 3,7,11,3 is a subsequence of 6,3,11,5,7,4,3,11,5,3 , but 3,3,7 is not a subsequence of 6,3,11,5,7,4,3,11,5,3 .</p> <p>Given a sequence of integers your aim is to find the length of the longest fully dividing subsequence of this sequence.</p> <p>A fully dividing sequence is a sequence a1,a2,...,aN where ai divides aj whenever i &lt; j. For example, 3, 15, 60, 720 is a fully dividing sequence.</p> </blockquote> <p>My code is:</p> <pre><code>n=input() ar=[] temp=0 for i in range (0,n): temp=input() ar.append(temp) def best(i): if i==0: return (1) else: ans =1 for j in range (0,i): if (ar[j]%ar[i]==0): ans=max(ans,(best(j)+1)) return (ans) an=[] for i in range (0,n): temp=best(i) an.append(temp) print max(an) </code></pre> <p>the input was </p> <pre><code>9 2 3 7 8 14 39 145 76 320 </code></pre> <p>and I should get 3 (because of 2, 8, 320) as output but I am getting 1</p>
0
2016-09-14T20:37:37Z
39,499,582
<p>As <code>j &lt; i</code>, you need to check whether <code>a[j]</code> is a divider of <code>a[i]</code>, not vice versa. So this means you need to put this condition (and <em>only</em> this one, not combined with the inverse):</p> <pre><code> if (ar[i]%ar[j]==0): </code></pre> <p>With this change the output for the given sample data is 3.</p> <p>The confusion comes from the definition, in which <code>i &lt; j</code>, while in your code <code>j &lt; i</code>.</p>
3
2016-09-14T21:01:14Z
[ "python", "algorithm" ]
what is the wrong with my Dividing Sequences code
39,499,275
<p>I am trying to code this problem: </p> <blockquote> <p>This problem is about sequences of positive integers a1,a2,...,aN. A subsequence of a sequence is anything obtained by dropping some of the elements. For example, 3,7,11,3 is a subsequence of 6,3,11,5,7,4,3,11,5,3 , but 3,3,7 is not a subsequence of 6,3,11,5,7,4,3,11,5,3 .</p> <p>Given a sequence of integers your aim is to find the length of the longest fully dividing subsequence of this sequence.</p> <p>A fully dividing sequence is a sequence a1,a2,...,aN where ai divides aj whenever i &lt; j. For example, 3, 15, 60, 720 is a fully dividing sequence.</p> </blockquote> <p>My code is:</p> <pre><code>n=input() ar=[] temp=0 for i in range (0,n): temp=input() ar.append(temp) def best(i): if i==0: return (1) else: ans =1 for j in range (0,i): if (ar[j]%ar[i]==0): ans=max(ans,(best(j)+1)) return (ans) an=[] for i in range (0,n): temp=best(i) an.append(temp) print max(an) </code></pre> <p>the input was </p> <pre><code>9 2 3 7 8 14 39 145 76 320 </code></pre> <p>and I should get 3 (because of 2, 8, 320) as output but I am getting 1</p>
0
2016-09-14T20:37:37Z
39,500,806
<p>For the graph theory solution I alluded to in a comment:</p> <pre><code>class Node(object): def __init__(self, x): self.x = x self.children = [] def add_child(self, child_x): # Not actually used here, but a useful alternate constructor! new = self.__class__(child_x) self.children.append(new) return new def how_deep(self): """Does a DFS to return how deep the deepest branch goes.""" maxdepth = 1 for child in self.children: maxdepth = max(maxdepth, child.how_deep()+1) return maxdepth nums = [9, 2, 3, 7, 8, 14, 39, 145, 76, 320] nodes = [Node(num) for num in nums] for i,node in enumerate(nodes): for other in nodes[i:]: if other.x % node.x == 0: node.children.append(other) # graph built, rooted at nodes[0] result = max([n.how_deep() for n in nodes]) </code></pre>
0
2016-09-14T22:50:33Z
[ "python", "algorithm" ]
what is the wrong with my Dividing Sequences code
39,499,275
<p>I am trying to code this problem: </p> <blockquote> <p>This problem is about sequences of positive integers a1,a2,...,aN. A subsequence of a sequence is anything obtained by dropping some of the elements. For example, 3,7,11,3 is a subsequence of 6,3,11,5,7,4,3,11,5,3 , but 3,3,7 is not a subsequence of 6,3,11,5,7,4,3,11,5,3 .</p> <p>Given a sequence of integers your aim is to find the length of the longest fully dividing subsequence of this sequence.</p> <p>A fully dividing sequence is a sequence a1,a2,...,aN where ai divides aj whenever i &lt; j. For example, 3, 15, 60, 720 is a fully dividing sequence.</p> </blockquote> <p>My code is:</p> <pre><code>n=input() ar=[] temp=0 for i in range (0,n): temp=input() ar.append(temp) def best(i): if i==0: return (1) else: ans =1 for j in range (0,i): if (ar[j]%ar[i]==0): ans=max(ans,(best(j)+1)) return (ans) an=[] for i in range (0,n): temp=best(i) an.append(temp) print max(an) </code></pre> <p>the input was </p> <pre><code>9 2 3 7 8 14 39 145 76 320 </code></pre> <p>and I should get 3 (because of 2, 8, 320) as output but I am getting 1</p>
0
2016-09-14T20:37:37Z
39,532,670
<p>This solves your problem without using any recursion :) </p> <pre><code>n = int(input()) ar = [] bestvals = [] best_stored = [] for x in range(n): ar.append(int(input())) best_stored.append(0) best_stored[0] = 1 for i in range(n): maxval = 1 for j in range(i): if ar[i] % ar[j] == 0: maxval = max(maxval,(best_stored[j])+1) best_stored[i] = maxval print(max(best_stored)) </code></pre>
0
2016-09-16T13:26:02Z
[ "python", "algorithm" ]
Is it good to change the Python antigravity library
39,499,348
<p>I came across Python's antigravity library recently and got information about it from <a href="http://python-history.blogspot.com/2010/06/import-antigravity.html" rel="nofollow">this</a> post. I then tried <code>import antigravity</code> in the interpreter: it opened the URL of the xkcd comic as expected but did not display the image of the comic in that page.</p> <p>I then found that the comic did not show up because the URL in the antigravity library was a HTTP one and when I tried to load the page after changing the URL from <a href="http://xkcd.com/353/" rel="nofollow">http://xkcd.com/353/</a> to <a href="https://xkcd.com/353/" rel="nofollow">https://xkcd.com/353/</a> the image showed up.</p> <p>This made me think if this could be corrected. Is it good to report this as an issue in the Python code (or) change the following line in the antigravity library :</p> <pre><code>webbrowser.open("http://xkcd.com/353/") </code></pre> <p>to</p> <pre><code>webbrowser.open("https://xkcd.com/353/") </code></pre> <p>and submit as to their Issue tracker.</p> <p>What would be the consequences of the above change? Would it cause any backward compatibility issue?</p> <h2>Edit</h2> <p>Just for the Note. This problem has been fixed after filing an issue in the Python Bug Tracker. You may find the issue using <a href="https://bugs.python.org/issue28181" rel="nofollow">this link.</a></p>
0
2016-09-14T20:42:31Z
39,499,535
<p>Report it to the Python issue tracker. Its purpose is to get questions like "will there be problems with backward compatibility" into the view of the people best capable of making that determination. Even if they reject the change, the issue will be documented, in case a later review reverses that decision.</p>
3
2016-09-14T20:57:46Z
[ "python" ]
How to connect a QPushButton to a function
39,499,349
<p>I want to create a simple program with a PyQt GUI. For this I used Qt Designer, and I made a window with a push-button named <code>OpenImage</code>. Moreover, I have a file named <em>rony.py</em> that has a function <code>show</code>. So I want that when the user clicks the button, the image will appear.</p> <p>This is my code:</p> <pre><code>from PyQt4 import QtCore, QtGui import rony try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(800, 600) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.horizontalLayout = QtGui.QHBoxLayout(self.centralwidget) self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) self.OpenImage = QtGui.QPushButton(self.centralwidget) self.OpenImage.setObjectName(_fromUtf8("OpenImage")) self.horizontalLayout.addWidget(self.OpenImage) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21)) self.menubar.setObjectName(_fromUtf8("menubar")) MainWindow.setMenuBar(self.menubar) self.statusbar = QtGui.QStatusBar(MainWindow) self.statusbar.setObjectName(_fromUtf8("statusbar")) MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None)) self.OpenImage.setText(_translate("MainWindow", "PushButton", None)) OpenImage.connect(show()) # Why this line don't work if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) MainWindow = QtGui.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) </code></pre> <p>rony.py</p> <pre><code>from PIL import Image img = Image.open("pipe.png") def show(): img.show() </code></pre>
0
2016-09-14T20:42:42Z
39,499,989
<p>You have to reference the name of your script when calling a function from it. It works as a library:</p> <pre><code>OpenImage.connect(rony.show()) </code></pre>
0
2016-09-14T21:35:41Z
[ "python", "pyqt", "signals-slots", "qpushbutton" ]
PyCharm import MySQL
39,499,387
<p>I am trying </p> <pre><code>import MySQLdb as mdb </code></pre> <p>on PyCharm and get the error:</p> <pre><code>ImportError: No module named MySQLdb </code></pre> <p>From the PyCharm-preference, cannot find MySQLdb to import. pymysql was successfully installed on PyCharm though. Suggestions ? Thank you very much. </p> <p><a href="http://i.stack.imgur.com/ACWaY.png" rel="nofollow"><img src="http://i.stack.imgur.com/ACWaY.png" alt="enter image description here"></a> <a href="http://i.stack.imgur.com/VOLu4.png" rel="nofollow"><img src="http://i.stack.imgur.com/VOLu4.png" alt="enter image description here"></a></p>
0
2016-09-14T20:46:15Z
39,499,681
<p>You can use <code>pymysql</code> installing through PyCharm instead of MySQLdb. It's a drop-in replacement for it.</p> <p><strong>Documentation:</strong> <a href="https://github.com/PyMySQL/PyMySQL" rel="nofollow">https://github.com/PyMySQL/PyMySQL</a></p>
2
2016-09-14T21:09:40Z
[ "python", "mysql", "python-2.7", "pycharm", "mysql-python" ]
How can I find dict keys for matching values in two dicts?
39,499,409
<p>I have two dictionaries mapping IDs to values. For simplicity, lets say those are the dictionaries:</p> <pre><code>d_source = {'a': 1, 'b': 2, 'c': 3, '3': 3} d_target = {'A': 1, 'B': 2, 'C': 3, '1': 1} </code></pre> <p>As named, the dictionaries are not symmetrical. I would like to get a dictionary of <em>keys</em> from dictionaries <code>d_source</code> and <code>d_target</code> whose values match. The resulting dictionary would have <code>d_source</code> keys as its own keys, and <code>d_target</code> keys as that keys value (in either a <code>list</code>, <code>tuple</code> or <code>set</code> format).</p> <p>This would be The expected returned value for the above example should be the following list:</p> <pre><code>{'a': ('1', 'A'), 'b': ('B',), 'c': ('C',), '3': ('C',)} </code></pre> <p>There are two somewhat <a href="http://stackoverflow.com/questions/21631951/find-matching-key-value-pairs-of-two-dictionaries">similar</a> <a href="http://stackoverflow.com/questions/11615041/how-to-find-match-items-from-two-lists">questions</a>, but those solutions can't be easily applied to my question.</p> <p>Some characteristics of the data:</p> <ol> <li>Source would usually be smaller than target. Having roughly few thousand sources (tops) and a magnitude more targets.</li> <li>Duplicates in the same dict (both <code>d_source</code> and <code>d_target</code>) are not too likely on values.</li> <li>matches are expected to be found for (a rough estimate) not more than 50% than <code>d_source</code> items.</li> <li>All keys are integers.</li> </ol> <p>What is the best (performance wise) solution to this problem? Modeling data into other datatypes for improved performance is totally ok, even when using third party libraries (i'm thinking <a href="http://www.numpy.org/" rel="nofollow">numpy</a>)</p>
1
2016-09-14T20:47:55Z
39,499,478
<pre><code>from collections import defaultdict from pprint import pprint d_source = {'a': 1, 'b': 2, 'c': 3, '3': 3} d_target = {'A': 1, 'B': 2, 'C': 3, '1': 1} d_result = defaultdict(list) {d_result[a].append(b) for a in d_source for b in d_target if d_source[a] == d_target[b]} pprint(d_result) </code></pre> <p><strong>Output:</strong></p> <pre><code>{'3': ['C'], 'a': ['A', '1'], 'b': ['B'], 'c': ['C']} </code></pre> <hr> <p><em>Timing results:</em> </p> <pre><code>from collections import defaultdict from copy import deepcopy from random import randint from timeit import timeit def Craig_match(source, target): result = defaultdict(list) {result[a].append(b) for a in source for b in target if source[a] == target[b]} return result def Bharel_match(source_dict, *rest): flipped_rest = defaultdict(list) for d in rest: while d: k, v = d.popitem() flipped_rest[v].append(k) return {k: tuple(flipped_rest.get(v, ())) for k, v in source_dict.items()} def modified_Bharel_match(source_dict, *rest): """Optimized for ~50% source match due to if statement addition. Also uses less memory. """ unique_values = set(source_dict.values()) flipped_rest = defaultdict(list) for d in rest: while d: k, v = d.popitem() if v in unique_values: flipped_rest[v].append(k) return {k: tuple(flipped_rest.get(v, ())) for k, v in source_dict.items()} # generate source, target such that: # a) ~10% duplicate values in source and target # b) 2000 unique source keys, 20000 unique target keys # c) a little less than 50% matches source value to target value # d) numeric keys and values source = {} for k in range(2000): source[k] = randint(0, 1800) target = {} for k in range(20000): if k &lt; 1000: target[k] = randint(0, 2000) else: target[k] = randint(2000, 19000) best_time = {} approaches = ('Craig', 'Bharel', 'modified_Bharel') for a in approaches: best_time[a] = None for _ in range(3): for approach in approaches: test_source = deepcopy(source) test_target = deepcopy(target) statement = 'd=' + approach + '_match(test_source,test_target)' setup = 'from __main__ import test_source, test_target, ' + approach + '_match' t = timeit(stmt=statement, setup=setup, number=1) if not best_time[approach] or (t &lt; best_time[approach]): best_time[approach] = t for approach in approaches: print(approach, ':', '%0.5f' % best_time[approach]) </code></pre> <p><strong>Output:</strong></p> <pre><code>Craig : 7.29259 Bharel : 0.01587 modified_Bharel : 0.00682 </code></pre>
1
2016-09-14T20:53:19Z
[ "python", "dictionary", "optimization" ]
How can I find dict keys for matching values in two dicts?
39,499,409
<p>I have two dictionaries mapping IDs to values. For simplicity, lets say those are the dictionaries:</p> <pre><code>d_source = {'a': 1, 'b': 2, 'c': 3, '3': 3} d_target = {'A': 1, 'B': 2, 'C': 3, '1': 1} </code></pre> <p>As named, the dictionaries are not symmetrical. I would like to get a dictionary of <em>keys</em> from dictionaries <code>d_source</code> and <code>d_target</code> whose values match. The resulting dictionary would have <code>d_source</code> keys as its own keys, and <code>d_target</code> keys as that keys value (in either a <code>list</code>, <code>tuple</code> or <code>set</code> format).</p> <p>This would be The expected returned value for the above example should be the following list:</p> <pre><code>{'a': ('1', 'A'), 'b': ('B',), 'c': ('C',), '3': ('C',)} </code></pre> <p>There are two somewhat <a href="http://stackoverflow.com/questions/21631951/find-matching-key-value-pairs-of-two-dictionaries">similar</a> <a href="http://stackoverflow.com/questions/11615041/how-to-find-match-items-from-two-lists">questions</a>, but those solutions can't be easily applied to my question.</p> <p>Some characteristics of the data:</p> <ol> <li>Source would usually be smaller than target. Having roughly few thousand sources (tops) and a magnitude more targets.</li> <li>Duplicates in the same dict (both <code>d_source</code> and <code>d_target</code>) are not too likely on values.</li> <li>matches are expected to be found for (a rough estimate) not more than 50% than <code>d_source</code> items.</li> <li>All keys are integers.</li> </ol> <p>What is the best (performance wise) solution to this problem? Modeling data into other datatypes for improved performance is totally ok, even when using third party libraries (i'm thinking <a href="http://www.numpy.org/" rel="nofollow">numpy</a>)</p>
1
2016-09-14T20:47:55Z
39,499,490
<p>It is up to you to determine the <em>best</em> solution. Here is <em>a</em> solution:</p> <pre><code>def dicts_to_tuples(*dicts): result = {} for d in dicts: for k,v in d.items(): result.setdefault(v, []).append(k) return [tuple(v) for v in result.values() if len(v) &gt; 1] d1 = {'a': 1, 'b': 2, 'c':3} d2 = {'A': 1, 'B': 2} print dicts_to_tuples(d1, d2) </code></pre>
0
2016-09-14T20:54:09Z
[ "python", "dictionary", "optimization" ]
How can I find dict keys for matching values in two dicts?
39,499,409
<p>I have two dictionaries mapping IDs to values. For simplicity, lets say those are the dictionaries:</p> <pre><code>d_source = {'a': 1, 'b': 2, 'c': 3, '3': 3} d_target = {'A': 1, 'B': 2, 'C': 3, '1': 1} </code></pre> <p>As named, the dictionaries are not symmetrical. I would like to get a dictionary of <em>keys</em> from dictionaries <code>d_source</code> and <code>d_target</code> whose values match. The resulting dictionary would have <code>d_source</code> keys as its own keys, and <code>d_target</code> keys as that keys value (in either a <code>list</code>, <code>tuple</code> or <code>set</code> format).</p> <p>This would be The expected returned value for the above example should be the following list:</p> <pre><code>{'a': ('1', 'A'), 'b': ('B',), 'c': ('C',), '3': ('C',)} </code></pre> <p>There are two somewhat <a href="http://stackoverflow.com/questions/21631951/find-matching-key-value-pairs-of-two-dictionaries">similar</a> <a href="http://stackoverflow.com/questions/11615041/how-to-find-match-items-from-two-lists">questions</a>, but those solutions can't be easily applied to my question.</p> <p>Some characteristics of the data:</p> <ol> <li>Source would usually be smaller than target. Having roughly few thousand sources (tops) and a magnitude more targets.</li> <li>Duplicates in the same dict (both <code>d_source</code> and <code>d_target</code>) are not too likely on values.</li> <li>matches are expected to be found for (a rough estimate) not more than 50% than <code>d_source</code> items.</li> <li>All keys are integers.</li> </ol> <p>What is the best (performance wise) solution to this problem? Modeling data into other datatypes for improved performance is totally ok, even when using third party libraries (i'm thinking <a href="http://www.numpy.org/" rel="nofollow">numpy</a>)</p>
1
2016-09-14T20:47:55Z
39,499,499
<p>Here is another solution. There are a lot of ways to do this</p> <pre><code>for key1 in d1: for key2 in d2: if d1[key1] == d2[key2]: stuff </code></pre> <p>Note that you can use any name for key1 and key2.</p>
1
2016-09-14T20:55:02Z
[ "python", "dictionary", "optimization" ]
How can I find dict keys for matching values in two dicts?
39,499,409
<p>I have two dictionaries mapping IDs to values. For simplicity, lets say those are the dictionaries:</p> <pre><code>d_source = {'a': 1, 'b': 2, 'c': 3, '3': 3} d_target = {'A': 1, 'B': 2, 'C': 3, '1': 1} </code></pre> <p>As named, the dictionaries are not symmetrical. I would like to get a dictionary of <em>keys</em> from dictionaries <code>d_source</code> and <code>d_target</code> whose values match. The resulting dictionary would have <code>d_source</code> keys as its own keys, and <code>d_target</code> keys as that keys value (in either a <code>list</code>, <code>tuple</code> or <code>set</code> format).</p> <p>This would be The expected returned value for the above example should be the following list:</p> <pre><code>{'a': ('1', 'A'), 'b': ('B',), 'c': ('C',), '3': ('C',)} </code></pre> <p>There are two somewhat <a href="http://stackoverflow.com/questions/21631951/find-matching-key-value-pairs-of-two-dictionaries">similar</a> <a href="http://stackoverflow.com/questions/11615041/how-to-find-match-items-from-two-lists">questions</a>, but those solutions can't be easily applied to my question.</p> <p>Some characteristics of the data:</p> <ol> <li>Source would usually be smaller than target. Having roughly few thousand sources (tops) and a magnitude more targets.</li> <li>Duplicates in the same dict (both <code>d_source</code> and <code>d_target</code>) are not too likely on values.</li> <li>matches are expected to be found for (a rough estimate) not more than 50% than <code>d_source</code> items.</li> <li>All keys are integers.</li> </ol> <p>What is the best (performance wise) solution to this problem? Modeling data into other datatypes for improved performance is totally ok, even when using third party libraries (i'm thinking <a href="http://www.numpy.org/" rel="nofollow">numpy</a>)</p>
1
2016-09-14T20:47:55Z
39,499,834
<p>All answers have <code>O(n^2)</code> efficiency which isn't very good so I thought of answering myself.</p> <p>I use <code>2(source_len) + 2(dict_count)(dict_len)</code> memory and I have <code>O(2n)</code> efficiency which is the best you can get here I believe.</p> <p>Here you go:</p> <pre><code>from collections import defaultdict d_source = {'a': 1, 'b': 2, 'c': 3, '3': 3} d_target = {'A': 1, 'B': 2, 'C': 3, '1': 1} def merge_dicts(source_dict, *rest): flipped_rest = defaultdict(list) for d in rest: while d: k, v = d.popitem() flipped_rest[v].append(k) return {k: tuple(flipped_rest.get(v, ())) for k, v in source_dict.items()} new_dict = merge_dicts(d_source, d_target) </code></pre> <p>By the way, I'm using a tuple in order not to link the resulting lists together.</p> <hr> <p>As you've added specifications for the data, here's a closer matching solution:</p> <pre><code>d_source = {'a': 1, 'b': 2, 'c': 3, '3': 3} d_target = {'A': 1, 'B': 2, 'C': 3, '1': 1} def second_merge_dicts(source_dict, *rest): """Optimized for ~50% source match due to if statement addition. Also uses less memory. """ unique_values = set(source_dict.values()) flipped_rest = defaultdict(list) for d in rest: while d: k, v = d.popitem() if v in unique_values: flipped_rest[v].append(k) return {k: tuple(flipped_rest.get(v, ())) for k, v in source_dict.items()} new_dict = second_merge_dicts(d_source, d_target) </code></pre>
2
2016-09-14T21:22:34Z
[ "python", "dictionary", "optimization" ]
How can I find dict keys for matching values in two dicts?
39,499,409
<p>I have two dictionaries mapping IDs to values. For simplicity, lets say those are the dictionaries:</p> <pre><code>d_source = {'a': 1, 'b': 2, 'c': 3, '3': 3} d_target = {'A': 1, 'B': 2, 'C': 3, '1': 1} </code></pre> <p>As named, the dictionaries are not symmetrical. I would like to get a dictionary of <em>keys</em> from dictionaries <code>d_source</code> and <code>d_target</code> whose values match. The resulting dictionary would have <code>d_source</code> keys as its own keys, and <code>d_target</code> keys as that keys value (in either a <code>list</code>, <code>tuple</code> or <code>set</code> format).</p> <p>This would be The expected returned value for the above example should be the following list:</p> <pre><code>{'a': ('1', 'A'), 'b': ('B',), 'c': ('C',), '3': ('C',)} </code></pre> <p>There are two somewhat <a href="http://stackoverflow.com/questions/21631951/find-matching-key-value-pairs-of-two-dictionaries">similar</a> <a href="http://stackoverflow.com/questions/11615041/how-to-find-match-items-from-two-lists">questions</a>, but those solutions can't be easily applied to my question.</p> <p>Some characteristics of the data:</p> <ol> <li>Source would usually be smaller than target. Having roughly few thousand sources (tops) and a magnitude more targets.</li> <li>Duplicates in the same dict (both <code>d_source</code> and <code>d_target</code>) are not too likely on values.</li> <li>matches are expected to be found for (a rough estimate) not more than 50% than <code>d_source</code> items.</li> <li>All keys are integers.</li> </ol> <p>What is the best (performance wise) solution to this problem? Modeling data into other datatypes for improved performance is totally ok, even when using third party libraries (i'm thinking <a href="http://www.numpy.org/" rel="nofollow">numpy</a>)</p>
1
2016-09-14T20:47:55Z
39,500,376
<p>This maybe "cheating" in some regards, although if you are looking for the matching values of the keys regardless of the case sensitivity then you might be able to do:</p> <pre><code>import sets aa = {'a': 1, 'b': 2, 'c':3} bb = {'A': 1, 'B': 2, 'd': 3} bbl = {k.lower():v for k,v in bb.items()} result = {k:k.upper() for k,v in aa.iteritems() &amp; bbl.viewitems()} print( result ) </code></pre> <p><strong>Output:</strong></p> <pre><code>{'a': 'A', 'b': 'B'} </code></pre> <p>The <code>bbl</code> declaration changes the <code>bb</code> keys into lowercase (it could be either <code>aa</code>, or <code>bb</code>). </p> <p><sub>* I only tested this on my phone, so just throwing this idea out there I suppose... Also, you've changed your question radically since I began composing my answer, so you get what you get.</sub> </p>
1
2016-09-14T22:06:31Z
[ "python", "dictionary", "optimization" ]
Package only binary compiled .so files of a python library compiled with Cython
39,499,453
<p>I have a package named <code>mypack</code> which inside has a module <code>mymod.py</code>, and the <code>__init__.py</code>. For some reason that is not in debate, I need to package this module compiled (nor .py or .pyc files are allowed). That is, the <code>__init__.py</code> is the only source file allowed in the distributed compressed file.</p> <p>The folder structure is:</p> <pre><code>. │ ├── mypack │ ├── __init__.py │ └── mymod.py ├── setup.py </code></pre> <p>I find that Cython is able to do this, by converting each .py file in a .so library that can be directly imported with python. </p> <p>The question is: how the <code>setup.py</code> file must be in order to allow an easy packaging and installation?</p> <p>The target system has a virtualenv where the package must be installed with whatever method that allows easy install and uninstall (easy_install, pip, etc are all welcome). </p> <p>I tried all that was at my reach. I read <code>setuptools</code> and <code>distutils</code> documentation, all stackoverflow related questions, and tried with all kind of commands (sdist, bdist, bdist_egg, etc), with lots of combinations of setup.cfg and MANIFEST.in file entries.</p> <p>The closest I got was with the below setup file, that would subclass the bdist_egg command in order to remove also .pyc files, but that is breaking the installation.</p> <p>A solution that installs "manually" the files in the venv is also good, provided that all ancillary files that are included in a proper installation are covered (I need to run <code>pip freeze</code> in the venv and see <code>mymod==0.0.1</code>).</p> <p>Run it with:</p> <pre><code>python setup.py bdist_egg --exclude-source-files </code></pre> <p>and (try to) install it with </p> <pre><code>easy_install mymod-0.0.1-py2.7-linux-x86_64.egg </code></pre> <p>As you may notice, the target is linux 64 bits with python 2.7.</p> <pre><code>from Cython.Distutils import build_ext from setuptools import setup, find_packages from setuptools.extension import Extension from setuptools.command import bdist_egg from setuptools.command.bdist_egg import walk_egg, log import os class my_bdist_egg(bdist_egg.bdist_egg): def zap_pyfiles(self): log.info("Removing .py files from temporary directory") for base, dirs, files in walk_egg(self.bdist_dir): for name in files: if not name.endswith('__init__.py'): if name.endswith('.py') or name.endswith('.pyc'): # original 'if' only has name.endswith('.py') path = os.path.join(base, name) log.info("Deleting %s",path) os.unlink(path) ext_modules=[ Extension("mypack.mymod", ["mypack/mymod.py"]), ] setup( name = 'mypack', cmdclass = {'build_ext': build_ext, 'bdist_egg': my_bdist_egg }, ext_modules = ext_modules, version='0.0.1', description='This is mypack compiled lib', author='Myself', packages=['mypack'], ) </code></pre>
2
2016-09-14T20:51:12Z
39,640,762
<p>This was exactly the sort of problem <a href="http://lucumr.pocoo.org/2014/1/27/python-on-wheels/" rel="nofollow"><strong>the Python wheels format</strong></a> – <a href="https://www.python.org/dev/peps/pep-0427/" rel="nofollow">described in PEP 427</a> – was developed to address.</p> <p>Wheels are a replacement for Python eggs (which were/are problematic for a bunch of reasons) – <a href="https://packaging.python.org/installing/" rel="nofollow">they are supported by <code>pip</code></a>, can contain architecture-specific private binaries (here is <a href="https://github.com/lepture/python-wheels/blob/master/.travis.yml" rel="nofollow">one example of such an arrangement</a>) and are accepted generally by the Python communities who have stakes in these kind of things.</p> <p>Here is one <code>setup.py</code> snippet from the <a href="http://lucumr.pocoo.org/2014/1/27/python-on-wheels/" rel="nofollow">aforelinked</a> <em>Python on Wheels</em> article, showing how one sets up a binary distribution:</p> <pre><code>import os from setuptools import setup from setuptools.dist import Distribution class BinaryDistribution(Distribution): def is_pure(self): return False setup( ..., include_package_data=True, distclass=BinaryDistribution, ) </code></pre> <p>… in leu of the older (but probably somehow still canonically supported) <code>setuptools</code> classes you are using. It’s very straightforward to make Wheels for your distribution purposes, as outlined – as I recall from experience, either the <code>wheel</code> modules’ build process is somewhat cognizant of <code>virtualenv</code>, or it’s very easy to use one within the other.</p> <p>In any case, trading in the <code>setuptools</code> egg-based APIs for wheel-based tooling should save you some serious pain, I should think.</p>
1
2016-09-22T13:41:44Z
[ "python", "cython", "setuptools", "distutils", "setup.py" ]
Tkinter Threading causing UI freeze
39,499,468
<p>I've searched this site (and others) up and down but I can't seem to find the right solution.</p> <p>I have a client program that connects to a server and automatically sends a message every few seconds, as well as on user command. I'm using multiple threads for this. Enter Tkinter: Once I hit the 'Connect' button, my UI freezes, either until the connection attempt times out or until the end of time, should the client connect to the server.</p> <p>I've tried calling the thread from the button's command parameter, from inside the main loop, and outside the main loop. I've tried putting the main loop in a thread and then creating a new thread for the connection from there. Nothing seems to be working...the UI continues to hang.</p> <pre><code>class EventSim(Frame): def __init__(self, parent): self.queue = Queue Frame.__init__(self, parent) self.parent = parent def initUI(self,IP_Address,Port_Number,Events_Directory): #... self.Con_Button = Button(frame7,text='Connect', command = lambda: self.connect(IP_Text.get(),Port_Text.get(),)) def connect(self,IP,Port): ConnectionThread = Thread(eventsim.con_thread(IP,Port)) ConnectionThread.start() def main(): root = Tk() root.geometry("300x310+750+300") Sim = EventSim(root) eventsim.readconfig() Sim.initUI(eventsim.ipa,eventsim.portnum,eventsim.event_dir) root.mainloop() </code></pre>
0
2016-09-14T20:52:20Z
39,501,945
<p>You pass the result of <code>eventsim.con_thread(IP,Port)</code> to <code>Thread(...)</code> function, so it will wait until the execution of <code>eventsim.con_thread(...)</code> completes. Try changing:</p> <pre><code>def connect(self, IP, Port): ConnectionThread = Thread(eventsim.con_thread(IP,Port)) ConnectionThread.start() </code></pre> <p>to:</p> <pre><code>def connect(self, IP, Port): ConnectionThread = Thread(target=lambda ip=IP, port=Port: eventsim.con_thread(ip,port)) ConnectionThread.start() </code></pre>
1
2016-09-15T01:32:01Z
[ "python", "multithreading", "tkinter" ]