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...
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 ...
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...
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...
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 comme...
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...
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=...
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> <...
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 ...
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> <...
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 i...
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 ...
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 ...
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) r...
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>[email protected]:/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 somet...
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>[email protected]:/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 somet...
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('[email protected]:/random/file...
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 ca...
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...
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 ca...
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 ...
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 (th...
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...
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> ...
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): ...
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 wa...
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: U...
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 wa...
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...
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 wa...
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 ...
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 wa...
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}}...
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...
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;...
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 AD...
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\d...
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 AD...
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
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...
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 ...
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]: ...
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 a...
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 a...
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 val...
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 a...
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...
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 a...
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 angl...
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>...
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>di...
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 no...
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): ...
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 no...
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 sta...
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 no...
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 = s...
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....
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"...
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:</...
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 possi...
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># E...
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 th...
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># E...
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,...
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:</...
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 "c...
-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 th...
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 "c...
-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]...
-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]...
-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'...
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]...
-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(d...
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]...
-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 ...
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="htt...
-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.ne...
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(que...
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')...
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...
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...
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...
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...
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</...
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...
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')...
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...
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...
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 MyC...
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...
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 usi...
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...<...
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_debugleve...
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 i...
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("...
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 i...
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, st...
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 i...
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...
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 i...
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: ...
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...
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...
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>...
-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 pytho...
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, "t...
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 ...
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, "t...
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 hre...
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>...
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>...
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", ...
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"])...
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 do...
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...
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 do...
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 <...
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 "I...
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...
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 "I...
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...
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.s...
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 usin...
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:...
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 usin...
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/ca...
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 usin...
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): ...
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-...
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-01...
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-...
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...
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-...
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 =...
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:...
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) </...
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:...
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 ...
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...
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" r...
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...
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...
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 t...
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/...
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 ...
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 c...
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 ...
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> <pr...
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() <...
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() <...
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>),...
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() <...
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...
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...
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...
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...
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) ...
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...
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...
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...
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>Thi...
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 muc...
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</e...
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><...
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</e...
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...
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</e...
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</e...
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 collection...
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</e...
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.upp...
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 t...
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 replacemen...
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...
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)) Co...
1
2016-09-15T01:32:01Z
[ "python", "multithreading", "tkinter" ]