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
A python regex that matches the regional indicator character class
39,108,298
<p>Flags in emoji are indicated by a pair of <a href="https://en.wikipedia.org/wiki/Regional_Indicator_Symbol" rel="nofollow">Regional Indicator Symbols</a>. I would like to write a python regex to insert spaces between a string of emoji flags. </p> <p>For example, this string is two Brazilian flags:</p> <pre><code>u"\U0001F1E7\U0001F1F7\U0001F1E7\U0001F1F7" </code></pre> <p>Which will render like this: 🇧🇷🇧🇷</p> <p>I'd like to insert spaces between any pair of regional indicator symbols. Something like this:</p> <pre><code>re.sub(re.compile(u"([\U0001F1E6-\U0001F1FF][\U0001F1E6-\U0001F1FF])"), r"\1 ", u"\U0001F1E7\U0001F1F7\U0001F1E7\U0001F1F7") </code></pre> <p>Which would result in:</p> <pre><code>u"\U0001F1E7\U0001F1F7 \U0001F1E7\U0001F1F7 " </code></pre> <p>But that code gives me an error:</p> <pre><code>sre_constants.error: bad character range </code></pre> <p>A hint (I think) at what's going wrong is the following, which shows that \U0001F1E7 is turning into two "characters" in the regex:</p> <pre><code>re.search(re.compile(u"([\U0001F1E7])"), u"\U0001F1E7\U0001F1F7\U0001F1E7\U0001F1F7").group(0) </code></pre> <p>This results in:</p> <pre><code>u'\ud83c' </code></pre> <p>Sadly my understanding of unicode is too weak for me to make further progress.</p> <p>EDIT: I am using python 2.7.10 on a Mac.</p>
4
2016-08-23T18:26:36Z
39,108,371
<p>I believe you're using Python 2.7 in Windows or Mac, which has the narrow 16-bit Unicode build - Linux/Glibc usually have 32-bit full unicode, also Python 3.5 has wide Unicode on all platforms. </p> <p>What you see is the one code being split into a surrogate pair. Unfortunately it also means that you cannot use a single character class easily for this task. However it is still possible. The UTF-16 representation of <a href="http://www.fileformat.info/info/unicode/char/1f1e6/index.htm" rel="nofollow">U+1F1E6 (🇦)</a> is <code>\uD83C\uDDE6</code>, and that of <a href="http://www.fileformat.info/info/unicode/char/1f1ff/index.htm" rel="nofollow">U+1F1FF (🇿)</a> is <code>\uD83C\uDDFF</code>.</p> <p>I do not even have an access to such Python build at all, but you could try</p> <pre><code>\uD83C[\uDDE6-\uDDFF] </code></pre> <p>as a replacement for single <code>[\U0001F1E6-\U0001F1FF]</code>, thus your whole regex would be</p> <pre><code>(\uD83C[\uDDE6-\uDDFF]\uD83C[\uDDE6-\uDDFF]) </code></pre> <p>The reason why the character class doesn't work is that it tries to make a range from the second half of the first surrogate pair to the first half of the second surrogate pair - this fails, because the start of the range is lexicographically greater than the end.</p> <p>However, this regular expression still wouldn't work on Linux, you need to use the original there. Or upgrade to Python 3.5.</p>
7
2016-08-23T18:32:00Z
[ "python", "regex", "unicode" ]
Numpy unicode to int
39,108,376
<p>Using python 2.7 through Pycharm</p> <p>I have a python code - which is very simple. </p> <pre><code>a = [2, 3, 4, 5] b = [30,32,33,34] c = ['test1', 'test2', 'test3', 'test4'] a = np.asarray(a) # -- Similarly for b and c </code></pre> <p>I converted these lists to numpy array.</p> <p>Then I did the following</p> <pre><code>d = np.transpose(np.vstack((a,b,c))) </code></pre> <p>Through which I got a 3D numpy array. </p> <p>when I print d I see a <code>u"</code> before each element, Which probably indicating unicode data type. </p> <p>Now how can I access the columns of a,b and do some arithmetic operations on those values. Whenever I am trying to access a value and convert them to int -- it is saying <code>invalid literal for int() with base 10</code>.</p> <p>All I need is read the first or second column -- do some arithmetic operations. First and second column values will be of <code>a</code> and <code>b</code></p>
0
2016-08-23T18:32:12Z
39,108,513
<pre><code>a = np.array(a) b = np.array(b) </code></pre> <blockquote> <p>Now how can I access the columns of a,b and do some arithmetic operations on those values.</p> </blockquote> <pre><code>a + b </code></pre>
0
2016-08-23T18:40:36Z
[ "python", "python-2.7", "numpy", "unicode" ]
Numpy unicode to int
39,108,376
<p>Using python 2.7 through Pycharm</p> <p>I have a python code - which is very simple. </p> <pre><code>a = [2, 3, 4, 5] b = [30,32,33,34] c = ['test1', 'test2', 'test3', 'test4'] a = np.asarray(a) # -- Similarly for b and c </code></pre> <p>I converted these lists to numpy array.</p> <p>Then I did the following</p> <pre><code>d = np.transpose(np.vstack((a,b,c))) </code></pre> <p>Through which I got a 3D numpy array. </p> <p>when I print d I see a <code>u"</code> before each element, Which probably indicating unicode data type. </p> <p>Now how can I access the columns of a,b and do some arithmetic operations on those values. Whenever I am trying to access a value and convert them to int -- it is saying <code>invalid literal for int() with base 10</code>.</p> <p>All I need is read the first or second column -- do some arithmetic operations. First and second column values will be of <code>a</code> and <code>b</code></p>
0
2016-08-23T18:32:12Z
39,108,526
<p>Because the last column is text, the other two columns are converted to text also. You can have only one type for one matrix. The solution would be a structured array:</p> <pre><code>a = [2, 3, 4, 5] b = [30,32,33,34] c = ['test1', 'test2', 'test3', 'test4'] matrix = np.array(zip(a,b,c), dtype=[('a',int),('b',int),('c','S5')]) </code></pre> <p>To access the values, you have to use the column name:</p> <pre><code>matrix['a'][2:4] </code></pre> <p>or</p> <pre><code>matrix[5]['b'] </code></pre>
1
2016-08-23T18:41:17Z
[ "python", "python-2.7", "numpy", "unicode" ]
Surviving icinga2 restart in a python requests stream
39,108,449
<p>I have been working on a chatbot interface to icinga2, and have not found a persistent way to survive the restart/reload of the icinga2 server. After a week of moving try/except blocks, using requests sessions, et al, it's time to reach out to the community.</p> <p>Here is the current iteration of the request function:</p> <pre><code> def i2api_request(url, headers={}, data={}, stream=False, *, auth=api_auth, ca=api_ca): ''' Do not call this function directly; it's a helper for the i2* command functions ''' # Adapted from http://docs.icinga.org/icinga2/latest/doc/module/icinga2/chapter/icinga2-api # Section 11.10.3.1 try: r = requests.post(url, headers=headers, auth=auth, data=json.dumps(data), verify=ca, stream=stream ) except (requests.exceptions.ChunkedEncodingError,requests.packages.urllib3.exceptions.ProtocolError, http.client.IncompleteRead,ValueError) as drop: return("No connection to Icinga API") if r.status_code == 200: for line in r.iter_lines(): try: if stream == True: yield(json.loads(line.decode('utf-8'))) else: return(json.loads(line.decode('utf-8'))) except: debug("Could not produce JSON from "+line) continue else: #r.raise_for_status() debug('Received a bad response from Icinga API: '+str(r.status_code)) print('Icinga2 API connection lost.') </code></pre> <p>(The debug function just flags and prints the indicated error to the console.)</p> <p>This code works fine handling events from the API and sending them to the chatbot, but if the icinga server is reloaded, as would be needed after adding a new server definition in /etc/icinga2..., the listener crashes.</p> <p>Here is the error response I get when the server is restarted:</p> <pre><code> Exception in thread Thread-11: Traceback (most recent call last): File "/home/errbot/err3/lib/python3.4/site-packages/requests/packages/urllib3/response.py", line 447, in _update_chunk_length self.chunk_left = int(line, 16) ValueError: invalid literal for int() with base 16: b'' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/errbot/err3/lib/python3.4/site-packages/requests/packages/urllib3/response.py", line 228, in _error_catcher yield File "/home/errbot/err3/lib/python3.4/site-packages/requests/packages/urllib3/response.py", line 498, in read_chunked self._update_chunk_length() File "/home/errbot/err3/lib/python3.4/site-packages/requests/packages/urllib3/response.py", line 451, in _update_chunk_length raise httplib.IncompleteRead(line) http.client.IncompleteRead: IncompleteRead(0 bytes read) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/errbot/err3/lib/python3.4/site-packages/requests/models.py", line 664, in generate for chunk in self.raw.stream(chunk_size, decode_content=True): File "/home/errbot/err3/lib/python3.4/site-packages/requests/packages/urllib3/response.py", line 349, in stream for line in self.read_chunked(amt, decode_content=decode_content): File "/home/errbot/err3/lib/python3.4/site-packages/requests/packages/urllib3/response.py", line 526, in read_chunked self._original_response.close() File "/usr/lib64/python3.4/contextlib.py", line 77, in __exit__ self.gen.throw(type, value, traceback) File "/home/errbot/err3/lib/python3.4/site-packages/requests/packages/urllib3/response.py", line 246, in _error_catcher raise ProtocolError('Connection broken: %r' % e, e) requests.packages.urllib3.exceptions.ProtocolError: ('Connection broken: IncompleteRead(0 bytes read)', IncompleteRead(0 bytes read)) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib64/python3.4/threading.py", line 920, in _bootstrap_inner self.run() File "/usr/lib64/python3.4/threading.py", line 868, in run self._target(*self._args, **self._kwargs) File "/home/errbot/plugins/icinga2bot.py", line 186, in report_events for line in queue: File "/home/errbot/plugins/icinga2bot.py", line 158, in i2events for line in queue: File "/home/errbot/plugins/icinga2bot.py", line 98, in i2api_request for line in r.iter_lines(): File "/home/errbot/err3/lib/python3.4/site-packages/requests/models.py", line 706, in iter_lines for chunk in self.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode): File "/home/errbot/err3/lib/python3.4/site-packages/requests/models.py", line 667, in generate raise ChunkedEncodingError(e) requests.exceptions.ChunkedEncodingError: ('Connection broken: IncompleteRead(0 bytes read)', IncompleteRead(0 bytes read)) </code></pre> <p>With Icinga2.4, this crash happened every time the server was restarted. I thought the problem had gone away after we upgraded to 2.5, but it now appears to have turned into a heisenbug. </p>
1
2016-08-23T18:36:33Z
39,171,305
<p>I wound up getting advice on IRC to reorder the try/except blocks and make sure they were in the right places. Here's the working result.</p> <pre><code>def i2api_request(url, headers={}, data={}, stream=False, *, auth=api_auth, ca=api_ca): ''' Do not call this function directly; it's a helper for the i2* command functions ''' # Adapted from http://docs.icinga.org/icinga2/latest/doc/module/icinga2/chapter/icinga2-api # Section 11.10.3.1 debug(url) debug(headers) debug(data) try: r = requests.post(url, headers=headers, auth=auth, data=json.dumps(data), verify=ca, stream=stream ) debug("Connecting to Icinga server") debug(r) if r.status_code == 200: try: for line in r.iter_lines(): debug('in i2api_request: '+str(line)) try: if stream == True: yield(json.loads(line.decode('utf-8'))) else: return(json.loads(line.decode('utf-8'))) except: debug("Could not produce JSON from "+line) return("Could not produce JSON from "+line) except (requests.exceptions.ChunkedEncodingError,ConnectionRefusedError): return("Connection to Icinga lost.") else: debug('Received a bad response from Icinga API: '+str(r.status_code)) print('Icinga2 API connection lost.') except (requests.exceptions.ConnectionError, requests.packages.urllib3.exceptions.NewConnectionError) as drop: debug("No connection to Icinga API. Error received: "+str(drop)) sleep(5) return("No connection to Icinga API.") </code></pre>
0
2016-08-26T16:59:26Z
[ "python", "python-requests", "icinga" ]
Find and select a required word from a sentence?
39,108,452
<p>I am trying to get <code>raw_input</code> from user and then find a required word from that input. If the required word is there, then a function runs. So I tried <code>.split</code> to split the input but how do I find if the required word is in the list.</p>
2
2016-08-23T18:36:36Z
39,108,469
<p>It's really simple to get this done. Python has an <code>in</code> operator that does exactly what you need. You can see if a word is present in a string and then do whatever else you'd like to do.</p> <pre><code>sentence = 'hello world' required_word = 'hello' if required_word in sentence: # do whatever you'd like </code></pre> <p>You can see some basic examples of the <code>in</code> operator in action <a href="http://www.tutorialspoint.com/python/membership_operators_example.htm" rel="nofollow">here</a>.</p> <p>Depending on the complexity of your input or lack of complexity of your required word, you may run into some problems. To deal with that you may want to be a little more specific with your required word.</p> <p>Let's take this for example:</p> <pre><code>sentence = 'i am harrison' required_word = 'is' </code></pre> <p>This example will evaluate to <code>True</code> if you were to do<code>if required_word in sentence:</code> because technically the letters <code>is</code> are a substring of the word "harrison".</p> <p>To fix that you would just simply do this:</p> <pre><code>sentence = 'i am harrison' required_word = ' is ' </code></pre> <p>By putting the empty space before and after the word it will specifically look for occurrences of the required word as a separate word, and not as a part of a word.</p> <p><strong>HOWEVER,</strong> if you are okay with matching substrings as well as word occurrences then you can ignore what I previously explained.</p> <blockquote> <p>If there's a group of words and if any of them is the required one, then what should I do? Like, the required word is either "yes" or "yeah". And the input by user contains "yes" or "yeah".</p> </blockquote> <p>As per this question, an implementation would look like this:</p> <pre><code>sentence = 'yes i like to code in python' required_words = ['yes', 'yeah'] ^ ^ ^ ^ # add spaces before and after each word if you don't # want to accidentally run into a chance where either word # is a substring of one of the words in sentence if any(word in sentence for word in required_words): # do whatever you'd like </code></pre> <p>This makes use of the <code>any</code> operator. The if statement will evaluate to true as long as at least one of the words in <code>required_words</code> is found in <code>sentence</code>.</p>
6
2016-08-23T18:37:56Z
[ "python", "python-2.7" ]
Find and select a required word from a sentence?
39,108,452
<p>I am trying to get <code>raw_input</code> from user and then find a required word from that input. If the required word is there, then a function runs. So I tried <code>.split</code> to split the input but how do I find if the required word is in the list.</p>
2
2016-08-23T18:36:36Z
39,109,444
<p>Harrison's way is one way. Here are other ways:</p> <p>Way 1:</p> <pre><code>sentence = raw_input("enter input:") words = sentence.split(' ') desired_word = 'test' if desired_word in words: # do required operations </code></pre> <p>Way 2:</p> <pre><code>import re sentence = raw_input("enter input:") desired_word = 'test' if re.search('\s' + desired_word + '\s', sentence.strip()): # do required operations </code></pre> <p>Way 3 (especially if there are punctuations at the end of the word):</p> <pre><code>import re sentence = raw_input("enter input:") desired_word = 'test' if re.search('\s' + desired_word + '[\s,:;]', sentence.strip()): # do required operations </code></pre>
1
2016-08-23T19:41:38Z
[ "python", "python-2.7" ]
Running two separate (non-nested) for loops within one CSV file
39,108,464
<p>I am currently trying to create a config template using CSV rows and columns as variable output into a text file for one of my network configurations. Here is the code:</p> <pre><code>import sys import os import csv with open('VRRP Mapping.csv', 'rb') as f: reader = csv.reader(f) myfile = open('VRRP fix.txt', 'w') next(reader, None) myfile.write('*' * 50 + '\n' + 'VLAN interfaces for Core A\n' + '*' * 50 + '\n\n') for row in reader: #First, for the A side myfile.write('interface vlan ' + str(row[0]) + '\n') myfile.write('no ip vrrp ' + str(row[7]) + '\n') myfile.write('ip vrrp ' + str(row[8]) + ' ' + row[9] + '\n') myfile.write('ip vrrp ' + str(row[8]) + ' adver-int 10\n') myfile.write('ip vrrp ' + str(row[8]) + ' backup-master enable\n') myfile.write('ip vrrp ' + str(row[8]) + ' holddown-timer 60\n') myfile.write('ip vrrp ' + str(row[8]) + ' priority ' + str(row[3]) + '\n') myfile.write('ip vrrp ' + str(row[8]) + ' enable\n') myfile.write('exit\n\n') myfile.write('*' * 50 + '\n' + 'VLAN interfaces for Core B\n' + '*' * 50 + '\n\n') for row in reader: #And then the B side myfile.write('interface vlan ' + str(row[0]) + '\n') myfile.write('no ip vrrp ' + str(row[7]) + '\n') myfile.write('ip vrrp ' + str(row[8]) + ' ' + row[9] + '\n') myfile.write('ip vrrp ' + str(row[8]) + ' adver-int 10\n') myfile.write('ip vrrp ' + str(row[8]) + ' backup-master enable\n') myfile.write('ip vrrp ' + str(row[8]) + ' holddown-timer 60\n') myfile.write('ip vrrp ' + str(row[8]) + ' priority ' + str(row[5]) + '\n') myfile.write('ip vrrp ' + str(row[8]) + ' enable\n') myfile.write('exit\n\n') myfile.close() </code></pre> <p>The problem I am having is after the first for loop. The 'VLAN interfaces for core b' shows up, but everything in the second for loop does not output to the text file at all.</p> <p>Suggestions?</p>
0
2016-08-23T18:37:32Z
39,108,579
<p>You have consumed all lines in your reader object and need to start from the beginning again. Before the second for loop add:</p> <pre><code>f.seek(0) </code></pre> <p>This will bring the pointer back to the beginning of the file so you can loop over it again. <a href="http://www.tutorialspoint.com/python/file_seek.htm" rel="nofollow">http://www.tutorialspoint.com/python/file_seek.htm</a></p>
2
2016-08-23T18:45:28Z
[ "python", "networking", "network-programming" ]
Running two separate (non-nested) for loops within one CSV file
39,108,464
<p>I am currently trying to create a config template using CSV rows and columns as variable output into a text file for one of my network configurations. Here is the code:</p> <pre><code>import sys import os import csv with open('VRRP Mapping.csv', 'rb') as f: reader = csv.reader(f) myfile = open('VRRP fix.txt', 'w') next(reader, None) myfile.write('*' * 50 + '\n' + 'VLAN interfaces for Core A\n' + '*' * 50 + '\n\n') for row in reader: #First, for the A side myfile.write('interface vlan ' + str(row[0]) + '\n') myfile.write('no ip vrrp ' + str(row[7]) + '\n') myfile.write('ip vrrp ' + str(row[8]) + ' ' + row[9] + '\n') myfile.write('ip vrrp ' + str(row[8]) + ' adver-int 10\n') myfile.write('ip vrrp ' + str(row[8]) + ' backup-master enable\n') myfile.write('ip vrrp ' + str(row[8]) + ' holddown-timer 60\n') myfile.write('ip vrrp ' + str(row[8]) + ' priority ' + str(row[3]) + '\n') myfile.write('ip vrrp ' + str(row[8]) + ' enable\n') myfile.write('exit\n\n') myfile.write('*' * 50 + '\n' + 'VLAN interfaces for Core B\n' + '*' * 50 + '\n\n') for row in reader: #And then the B side myfile.write('interface vlan ' + str(row[0]) + '\n') myfile.write('no ip vrrp ' + str(row[7]) + '\n') myfile.write('ip vrrp ' + str(row[8]) + ' ' + row[9] + '\n') myfile.write('ip vrrp ' + str(row[8]) + ' adver-int 10\n') myfile.write('ip vrrp ' + str(row[8]) + ' backup-master enable\n') myfile.write('ip vrrp ' + str(row[8]) + ' holddown-timer 60\n') myfile.write('ip vrrp ' + str(row[8]) + ' priority ' + str(row[5]) + '\n') myfile.write('ip vrrp ' + str(row[8]) + ' enable\n') myfile.write('exit\n\n') myfile.close() </code></pre> <p>The problem I am having is after the first for loop. The 'VLAN interfaces for core b' shows up, but everything in the second for loop does not output to the text file at all.</p> <p>Suggestions?</p>
0
2016-08-23T18:37:32Z
39,108,587
<p>If you need to read the reader twice, you need to read the file twice. Once you finish a book, you don't just keep reading and expect to find anything else. You need to go back to the beginning. To do that, use</p> <pre><code>f.seek(0) next(reader, None) </code></pre> <p>between the <code>for</code> loops. Note that <code>f</code> is a terrible name for a file object, as also is <code>myfile</code>. They are not at all descriptive of what file it is or what the file is for.</p>
2
2016-08-23T18:45:57Z
[ "python", "networking", "network-programming" ]
How to pass commands to gcc through cx_Freeze
39,108,524
<p>How to pass commands to gcc through cx_Freeze 'disutils.core.setup()' arguments?</p> <p>Specifically, i want my <code>.exe</code> file to use relative paths in traceback messages, rather than the path where i build <code>.exe</code> file</p> <p>Here is my setup.py file:</p> <pre><code>setup( name="test", packages=['test'], package_data={'': ['*.py', '*.txt', '*.sample', '*.mo', 'README.rst']}, options={"build_exe": { "icon": r"test\resources\test.ico", "compressed": True, "create_shared_zip": True, "copy_dependent_files": True, "include_files": [ ('test/i18n/', 'i18n/'), ('test/resources/', 'resources/'), ('test/client.conf.sample', 'client.conf.sample'), ], "excludes": [ 'urllib.sys', 'urllib._sre', 'urllib.array', 'urllib._locale', 'urllib.datetime', 'urllib._functools', ] } }, executables=Executable(script=script),) </code></pre>
0
2016-08-23T18:41:10Z
39,148,794
<p>You need to add one additional option to the ones you already have:</p> <pre><code>replace_paths = [("*", "")] </code></pre> <p>That will replace all paths with relative paths. You can also do more interesting things like:</p> <pre><code>replace_paths = [ ("/path/to/python/lib", "&lt;Python&gt;"), ("/path/to/my/script", "&lt;Script&gt;") ] </code></pre> <p>In essence, the first element of the tuple is the part of the path which is to be replaced with the value in the second element of the tuple. A value of * in the search value results in all paths being replaced with the replacement value.</p>
1
2016-08-25T15:06:49Z
[ "python", "gcc", "freeze", "cx-freeze" ]
How can I enable the users delete and edit post they create in Django?
39,108,550
<p>I am trying to have users delete and edit post they create. I was told "Post.user needs to be an object instance what you wrote is incorrect." but I am still newer to django and would like to know the steps to do this as I created this project with some help. </p> <p>here is my models </p> <pre><code> from django.db import models from django.db.models import Count, QuerySet, F from django.utils import timezone from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from django.db.models.signals import pre_save from django.utils.text import slugify from markdown_deux import markdown from django.utils.safestring import mark_safe from taggit.managers import TaggableManager from comments.models import Comment def upload_location(instance, filename): return "%s/%s" %(instance.slug, filename) class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1 ) title = models.CharField(max_length=75) slug = models.SlugField(unique=True) image = models.ImageField( upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="height_field") height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) description = models.TextField() tags = TaggableManager() public = models.BooleanField(default=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) created = models.DateTimeField(auto_now_add=True, auto_now=False) def __str__(self): return self.title def get_absolute_url(self): return reverse("posts:detail", kwargs={"slug": self.slug}) class Meta: ordering = ["-created", "-updated" ] def get_markdown(self): description = self.description markdown_text = markdown(description) return mark_safe(markdown_text) @property def comments(self): instance = self qs = Comment.objects.filter_by_instance(instance) return qs @property def get_content_type(self): instance = self content_type = ContentType.objects.get_for_model(instance.__class__) return content_type def create_slug(instance, new_slug=None): slug = slugify(instance.title) if new_slug is not None: slug = new_slug qs = Post.objects.filter(slug=slug).order_by("-id") exists = qs.exists() if exists: new_slug = "%s-%s" %(slug, qs.first().id) return create_slug(instance, new_slug=new_slug) return slug def pre_save_post_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = create_slug(instance) pre_save.connect(pre_save_post_receiver, sender=Post) </code></pre> <p>Here is my views </p> <pre><code> from django.contrib import messages from django.contrib.contenttypes.models import ContentType from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.db.models import Q from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.shortcuts import render, get_object_or_404, redirect from django.core.exceptions import PermissionDenied from comments.forms import CommentForm from comments.models import Comment from .forms import PostForm from .models import Post def post_main(request): return render(request, "base2.html") @login_required def post_create(request): form = PostForm(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() # message success messages.success(request, "Successfully Created") return HttpResponseRedirect(instance.get_absolute_url()) context = { "form": form, } return render(request, "post_form.html", context) @login_required def post_update(request, slug=None): instance = get_object_or_404(Post, slug=slug) form = PostForm(request.POST or None, request.FILES or None, instance=instance) if form.is_valid(): instance = form.save(commit=False) instance.save() messages.success(request, "Post Saved") return HttpResponseRedirect(instance.get_absolute_url()) context = { "title": instance.title, "instance": instance, "form":form } return render(request, "post_form.html", context) def post_user(request): return HttpResponse("&lt;h1&gt;Users Post&lt;/h1&gt;") @login_required def post_detail(request, slug=None): instance = get_object_or_404(Post, slug=slug) initial_data = { "content_type": instance.get_content_type, "object_id": instance.id } form = CommentForm(request.POST or None, initial=initial_data) if form.is_valid() and request.user.is_authenticated(): c_type = form.cleaned_data.get("content_type") content_type = ContentType.objects.get(model=c_type) obj_id = form.cleaned_data.get('object_id') content_data = form.cleaned_data.get("content") parent_obj = None try: parent_id = int(request.POST.get("parent_id")) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists() and parent_qs.count() == 1: parent_obj = parent_qs.first() new_comment, created = Comment.objects.get_or_create( user = request.user, content_type= content_type, object_id = obj_id, content = content_data, parent = parent_obj, ) return HttpResponseRedirect(new_comment.content_object.get_absolute_url()) comments = instance.comments context = { "title": instance.title, "instance": instance, "comments": comments, "comment_form":form, } return render(request, "post_detail.html", context) @login_required def post_feed(request): queryset_list = Post.objects.all() query = request.GET.get("q") if query: queryset_list = queryset_list.filter( Q(title__icontains=query)| Q(tags__icontains=query)| Q(content__icontains=query)| Q(user__first_name__icontains=query) | Q(user__last_name__icontains=query) ).distinct() paginator = Paginator(queryset_list, 8) # Show 25 contacts per page page_request_var = "page" page = request.GET.get(page_request_var) try: queryset = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. queryset = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. queryset = paginator.page(paginator.num_pages) context = { "object_list": queryset, "title": "List", "page_request_var": page_request_var, } return render(request, "post_feed.html", context) @login_required def post_delete(request, slug=None): instance = get_object_or_404(Post, slug=slug) if request.user == Post.user: instance.delete() # or save edits messages.success(request, "Successfully Deleted") return redirect("posts:feed") else: raise PermissionDenied # import it from django.core.exceptions return redirect("posts:feed") def privacy(request): return render(request, "privacy.html") def post_about(request): return HttpResponse("&lt;h1&gt;About Page&lt;/h1&gt;") def home(request): return render(request, "base2.html") </code></pre> <p>Let me know if any other information is needed.</p>
1
2016-08-23T18:42:38Z
39,108,644
<p>You are almost there.</p> <p>in <code>delete</code>, your check should be:</p> <pre><code>request.user == instance.user </code></pre> <p>instead of </p> <pre><code>request.user == Post.user </code></pre> <p>Similarly in <code>post_update</code>, you could do:</p> <pre><code>if instance.user == request.user: #Now, allow update </code></pre> <p>Also, it might be a good idea to check for the request type. Example:</p> <pre><code>if request.method == "POST": </code></pre> <p>This way, this check would only happen if it is a POST type</p>
2
2016-08-23T18:48:55Z
[ "python", "django", "python-3.x", "edit", "delete-file" ]
updating existing custom field in JIRA with python
39,108,621
<p>Im trying to update an existing custom field within python so that I can automatically add several "values" that can be used in a dropdown box. The below line targets the custom field I want </p> <pre><code>for a in jira.fields(): if a['name'] == "block": #print a.update(fields={'customfield_12100': {'value': "testingtest"}}) print a </code></pre> <p>I know this because it returns the correct fields:</p> <pre><code>{u'name': u'block', u'searchable': True, u'navigable': True, u'custom': True, u'clauseNames': [u'cf[12100]', u'Lease Block'], u'orderable': True, u'id': u'customfield_12100', u'schema': {u'customId': 12100, u'type': u'option', u'custom': u'com.atlassian.jira.plugin.system.customfieldtypes:select'}} </code></pre> <p>But The new value is not added to my list of custom field options. How do you go about adding the value?</p> <p>Jira Version 7.1.7</p>
0
2016-08-23T18:47:35Z
39,154,220
<p>It can not be done with the OOB Jira install. A third party plugin must be installed <a href="https://marketplace.atlassian.com/plugins/jiracustomfieldeditorplugin/server/overview" rel="nofollow">https://marketplace.atlassian.com/plugins/jiracustomfieldeditorplugin/server/overview</a>. </p>
0
2016-08-25T20:27:46Z
[ "python", "jira" ]
Form Data not refreshing with newest entries
39,108,641
<p>When I add a new customer in customer table and access AddOrderForm form, I don't get the new customer in the choices.But on server restart I am able to get the new customer in the choices list.Any reason ?</p> <p>Customer Table </p> <pre><code>class Customer(db.Model): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(120), unique=True) mobile_num = db.Column(db.String(13), unique=True) name = db.Column(db.String(120)) marketing_source = db.Column(db.String(120)) date_of_birth = db.Column(db.DateTime) gender = db.Column(db.String(13)) store_id = db.Column(db.Integer, db.ForeignKey('store.id')) def __init__(self,email,mobile_num,name,marketing_source,date_of_birth, gender,store_id): self.email = email self.mobile_num = mobile_num self.name = name self.marketing_source = marketing_source self.date_of_birth = date_of_birth self.gender = gender self.store_id = store_id def __repr__(self): return '%r, %s ' % (self.name.encode('utf-8'), self.mobile_num) </code></pre> <p>AddOrderForm</p> <pre><code>class AddOrderForm(Form): order_id = TextField('Website Order Id', [validators.length(min=4, max=120)]) item_name = TextField('Item Name', [validators.length(min=4, max=120)]) item_cost = DecimalField('Item Cost' , [validators.Required()]) custmer_id = SelectField('Customer',coerce=int,choices= convert_list_wtforms_choices(Customer.query.all())) order_category = SelectField('Order Category',coerce=int,choices=[(1,'Mobiles'), (2,'Clothing')]) linq_shipping_cost = DecimalField('Linq Shipping Cost' , [validators.Required()]) website_shipping_cost = DecimalField('Website Shipping Cost' , [validators.Required()]) advance_amount = DecimalField('Advance Amount' , [validators.Required()]) website = SelectField('Website', coerce=int,choices=[(1,'Amazon'), (2,'Flipkart')] ) other = TextField('Any Other Information') </code></pre> <p>While accessing the form from a view I don't get the latest added customer in the custmer_id choices. Any idea to fix this?</p>
-1
2016-08-23T18:48:52Z
39,108,873
<p>You're only setting the choices once, when you define the form. Instead, re-select them every time you instantiate the form.</p> <p>class AddOrderForm(Form): customer_id = SelectField('Customer', coerce=int)</p> <pre><code>def __init__(self, *args, **kwargs): super(AddOrderForm, self).__init__(*args, **kwargs) self.customer_id.choices = convert_list_wtforms_choices(Customer.query.all()) </code></pre>
1
2016-08-23T19:04:36Z
[ "python", "flask", "flask-sqlalchemy", "flask-wtforms" ]
How to 'and' data without ignoring digits?
39,108,704
<p>Say I have a number, <code>18573628</code>, where each digit represents some kind of flag, and I want to check if the value of the fourth flag is set to <code>7</code> or not (which it is). </p> <p>I do not want to use indexing. I want to in some way <code>and</code> with a flag mask, such as this:</p> <p><code>00070000</code></p> <p>I would normally use <code>np.logical_and()</code> or something like that, but that will consider <em>any</em> positive value to be <code>True</code>. How can I <code>and</code> while considering the value of a digit? For example, preforming the operation with </p> <p><code>flags = 18573628</code></p> <p>and </p> <p><code>mask = 00070000</code></p> <p>would yield <code>00010000</code></p> <p>though trying a different mask, such as </p> <p><code>mask = 00040000</code></p> <p>would yield <code>00000000</code></p>
0
2016-08-23T18:53:30Z
39,108,779
<p>What you can do is</p> <pre><code>if (x // 10**n % 10) == y: ... </code></pre> <p>to check if the <code>n</code>-th digit of <code>x</code> (counting from <strong>right</strong>) is equal to <code>y</code></p>
4
2016-08-23T18:58:00Z
[ "python", "numpy" ]
How to 'and' data without ignoring digits?
39,108,704
<p>Say I have a number, <code>18573628</code>, where each digit represents some kind of flag, and I want to check if the value of the fourth flag is set to <code>7</code> or not (which it is). </p> <p>I do not want to use indexing. I want to in some way <code>and</code> with a flag mask, such as this:</p> <p><code>00070000</code></p> <p>I would normally use <code>np.logical_and()</code> or something like that, but that will consider <em>any</em> positive value to be <code>True</code>. How can I <code>and</code> while considering the value of a digit? For example, preforming the operation with </p> <p><code>flags = 18573628</code></p> <p>and </p> <p><code>mask = 00070000</code></p> <p>would yield <code>00010000</code></p> <p>though trying a different mask, such as </p> <p><code>mask = 00040000</code></p> <p>would yield <code>00000000</code></p>
0
2016-08-23T18:53:30Z
39,108,800
<p>You have to use divide and modulo for a decimal mask:</p> <pre><code>flags = 18573628 mask = 10000 if (flags / mask) % 10 == 7: do_something </code></pre>
1
2016-08-23T18:58:45Z
[ "python", "numpy" ]
How to 'and' data without ignoring digits?
39,108,704
<p>Say I have a number, <code>18573628</code>, where each digit represents some kind of flag, and I want to check if the value of the fourth flag is set to <code>7</code> or not (which it is). </p> <p>I do not want to use indexing. I want to in some way <code>and</code> with a flag mask, such as this:</p> <p><code>00070000</code></p> <p>I would normally use <code>np.logical_and()</code> or something like that, but that will consider <em>any</em> positive value to be <code>True</code>. How can I <code>and</code> while considering the value of a digit? For example, preforming the operation with </p> <p><code>flags = 18573628</code></p> <p>and </p> <p><code>mask = 00070000</code></p> <p>would yield <code>00010000</code></p> <p>though trying a different mask, such as </p> <p><code>mask = 00040000</code></p> <p>would yield <code>00000000</code></p>
0
2016-08-23T18:53:30Z
39,108,848
<p>if <code>flags</code> and <code>mask</code> are hexadecimal values, you can do:</p> <pre><code>flags = int("18573628", 16) mask = int("00070000", 16) result = flags &amp; mask print(hex(result)) =&gt; '0x70000' </code></pre>
0
2016-08-23T19:02:29Z
[ "python", "numpy" ]
How to 'and' data without ignoring digits?
39,108,704
<p>Say I have a number, <code>18573628</code>, where each digit represents some kind of flag, and I want to check if the value of the fourth flag is set to <code>7</code> or not (which it is). </p> <p>I do not want to use indexing. I want to in some way <code>and</code> with a flag mask, such as this:</p> <p><code>00070000</code></p> <p>I would normally use <code>np.logical_and()</code> or something like that, but that will consider <em>any</em> positive value to be <code>True</code>. How can I <code>and</code> while considering the value of a digit? For example, preforming the operation with </p> <p><code>flags = 18573628</code></p> <p>and </p> <p><code>mask = 00070000</code></p> <p>would yield <code>00010000</code></p> <p>though trying a different mask, such as </p> <p><code>mask = 00040000</code></p> <p>would yield <code>00000000</code></p>
0
2016-08-23T18:53:30Z
39,108,851
<p>You can convert the input number into an array of digit numbers and then simply indexing into that array with that specific index or indices would give us those digit(s). For doing that conversion, we can use <code>np.fromstring</code>, like so -</p> <pre><code>In [87]: nums = np.fromstring(str(18573628),dtype=np.uint8)-48 In [88]: nums Out[88]: array([1, 8, 5, 7, 3, 6, 2, 8], dtype=uint8) In [89]: nums[3] == 7 Out[89]: True </code></pre>
1
2016-08-23T19:02:37Z
[ "python", "numpy" ]
How to 'and' data without ignoring digits?
39,108,704
<p>Say I have a number, <code>18573628</code>, where each digit represents some kind of flag, and I want to check if the value of the fourth flag is set to <code>7</code> or not (which it is). </p> <p>I do not want to use indexing. I want to in some way <code>and</code> with a flag mask, such as this:</p> <p><code>00070000</code></p> <p>I would normally use <code>np.logical_and()</code> or something like that, but that will consider <em>any</em> positive value to be <code>True</code>. How can I <code>and</code> while considering the value of a digit? For example, preforming the operation with </p> <p><code>flags = 18573628</code></p> <p>and </p> <p><code>mask = 00070000</code></p> <p>would yield <code>00010000</code></p> <p>though trying a different mask, such as </p> <p><code>mask = 00040000</code></p> <p>would yield <code>00000000</code></p>
0
2016-08-23T18:53:30Z
39,108,960
<blockquote> <p>Say I have a number, <code>18573628</code>, where each digit represents some kind of flag, and I want to check if the value of the fourth flag is set to <code>7</code></p> </blockquote> <p>Firstly, bitwise operations like <code>&amp;</code> are <em>bit</em>-wise, which is to say they operate on base-2 digits. They don't operate naturally on digits of any other base, although bases which are themselves powers of 2 work out ok.</p> <h2>To stick with bit-wise operations</h2> <p>You need to know how many values each flag can take, to figure out how many bits each flag needs to encode.</p> <p>If you want to allow each flag the values zero to nine, you need four bits. However, in this scheme, your number won't behave like a normal integer (storing a base-10 digit in each 4-bit group is called <em>Binary Coded Decimal</em>).</p> <p>The reason it won't behave like a normal integer is that flag values <code>1,2,3</code> will be stored as <code>1 * 16**2 + 2*16 + 3</code> instead of the <code>1 * 10**2 + 2*10 + 3</code> you'd normally expect. So you'd need to write some code to support this use. However, extracting flag <em>n</em> (counting from zero at the right) just becomes</p> <pre><code>def bcdFlagValue(bcd, flagnum): if flagnum == 0: return bcd &amp; 0x0F; return 0x0F &amp; (bcd &gt;&gt; ((flagnum-1) * 4)) </code></pre> <p>If you actually need a different range of values for each flag, you need to choose the correct number of bits, and adjust the shift and mask values appropriately.</p> <p>In either case, you'll need a helper function if you want to print your flags as the base-10 number you showed.</p> <hr> <h2>To use normal base 10 numbers</h2> <p>You need to use division and modulo (as 6502 showed), because base-10 numbers don't fit evenly into base-2 bits, so simple bit operations don't work</p> <hr> <h2>Note</h2> <p>The BCD approach saves space at the cost of complexity, effort and some speed - from subsequent comments, it's probably simpler to just use the string of digit characters directly unless you really need to save 4 bits per digit.</p>
1
2016-08-23T19:09:55Z
[ "python", "numpy" ]
How to 'and' data without ignoring digits?
39,108,704
<p>Say I have a number, <code>18573628</code>, where each digit represents some kind of flag, and I want to check if the value of the fourth flag is set to <code>7</code> or not (which it is). </p> <p>I do not want to use indexing. I want to in some way <code>and</code> with a flag mask, such as this:</p> <p><code>00070000</code></p> <p>I would normally use <code>np.logical_and()</code> or something like that, but that will consider <em>any</em> positive value to be <code>True</code>. How can I <code>and</code> while considering the value of a digit? For example, preforming the operation with </p> <p><code>flags = 18573628</code></p> <p>and </p> <p><code>mask = 00070000</code></p> <p>would yield <code>00010000</code></p> <p>though trying a different mask, such as </p> <p><code>mask = 00040000</code></p> <p>would yield <code>00000000</code></p>
0
2016-08-23T18:53:30Z
39,112,336
<p>Without dealing with the particulars of your case (the SDSS data, which should be documented in the product specification), let's look at some options.</p> <p>First, you need to to know if it is to be read in big-endian or little-endian order (is the first bit to the right or to the left). Then you need to know the size of each flag. For a series of yes-no parameters, it could simply be 1 bit (0 or 1). For up to four options, it could be two bits (00, 01, 10, 11), etc. It is also possible that some combinations are reserved for future expansion, don't currently have meaning, and should not be expected to occur in the data. I've also seen instances where the flag size varies, so first n bits mean refer to parameter x, next n bits refer to parameter y, etc.</p> <p>There is a good explanation of the concept as part of Landsat-8 satellite imagery: <a href="http://landsat.usgs.gov/qualityband.php" rel="nofollow">http://landsat.usgs.gov/qualityband.php</a></p> <p>To read the values, you convert the base 10 integer to binary, and traverse it in the specified chunks, converting back to int to obtain the parameter values according to your product specification.</p>
0
2016-08-23T23:45:32Z
[ "python", "numpy" ]
appending values to Python dictionary
39,108,729
<p>I have a script that reads a CSV file <a href="http://i.stack.imgur.com/CrflA.png" rel="nofollow">csv file</a></p> <pre><code>Asset IP Address,Vulnerability Title 50.103.128.11,Partition Mounting Weakness 10.103.128.11,UDP IP ID Zero 10.103.128.11,Root's umask value is unsafe 0.103.128.11,Root's umask value is unsafe 20.103.128.11,Root's umask value is unsafe 10.103.128.11,ICMP timestamp response 22.103.128.11,ICMP timestamp response 10.103.128.11,UDP IP ID Zero 10.103.129.11,Partition Mounting Weakness </code></pre> <p>and after running my script</p> <pre><code>import csv from pprint import pprint #with open('test.csv', 'rb') as f: # reader = csv.DictReader(f, delimiter=',') # for row in reader: # print row #dict = {a:[], b:[]} dict = {} with open('test.csv', 'rb') as f: reader = csv.DictReader(f, delimiter=',') for row in reader: a = row["Vulnerability Title"] b = [row["Asset IP Address"]] #b = row(["Asset IP Address"]) #dict = {a:[], b:[]} if a in dict: #print row["Vulnerability Title"] #if row["Vulnerability Title"] in dict: dict[a].append(b) else: dict[a] = b pprint(dict) </code></pre> <p>reads the vulnerability lists and create a dictionary with ips that have that vulnerability.how ever my results are a list that has one extra bracket. wanted to reach out and see anyone has better ideas or can help me out. <a href="http://i.stack.imgur.com/j2M1G.png" rel="nofollow">results</a></p> <pre><code>{'ICMP timestamp response': ['10.103.128.11', ['22.103.128.11']], 'Partition Mounting Weakness': ['50.103.128.11', ['10.103.129.11']], "Root's umask value is unsafe": ['10.103.128.11', ['0.103.128.11'], ['20.103.128.11']], 'UDP IP ID Zero': ['10.103.128.11', ['10.103.128.11']]} </code></pre>
1
2016-08-23T18:54:38Z
39,108,763
<p>You are trying to reinvent the <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a>:</p> <pre><code>from collections import defaultdict d = defaultdict(list) with open('test.csv', 'rb') as f: reader = csv.DictReader(f, delimiter=',') for row in reader: d[row["Vulnerability Title"]].append(row["Asset IP Address"]) pprint(d) </code></pre> <p>As a side note, <code>dict</code> is not the best choice for a variable name - you are <em>shadowing</em> the <a href="https://docs.python.org/2/library/functions.html#func-dict" rel="nofollow">built-in <code>dict()</code></a>, choose a different variable name.</p>
2
2016-08-23T18:57:11Z
[ "python", "list", "csv", "dictionary", "append" ]
appending values to Python dictionary
39,108,729
<p>I have a script that reads a CSV file <a href="http://i.stack.imgur.com/CrflA.png" rel="nofollow">csv file</a></p> <pre><code>Asset IP Address,Vulnerability Title 50.103.128.11,Partition Mounting Weakness 10.103.128.11,UDP IP ID Zero 10.103.128.11,Root's umask value is unsafe 0.103.128.11,Root's umask value is unsafe 20.103.128.11,Root's umask value is unsafe 10.103.128.11,ICMP timestamp response 22.103.128.11,ICMP timestamp response 10.103.128.11,UDP IP ID Zero 10.103.129.11,Partition Mounting Weakness </code></pre> <p>and after running my script</p> <pre><code>import csv from pprint import pprint #with open('test.csv', 'rb') as f: # reader = csv.DictReader(f, delimiter=',') # for row in reader: # print row #dict = {a:[], b:[]} dict = {} with open('test.csv', 'rb') as f: reader = csv.DictReader(f, delimiter=',') for row in reader: a = row["Vulnerability Title"] b = [row["Asset IP Address"]] #b = row(["Asset IP Address"]) #dict = {a:[], b:[]} if a in dict: #print row["Vulnerability Title"] #if row["Vulnerability Title"] in dict: dict[a].append(b) else: dict[a] = b pprint(dict) </code></pre> <p>reads the vulnerability lists and create a dictionary with ips that have that vulnerability.how ever my results are a list that has one extra bracket. wanted to reach out and see anyone has better ideas or can help me out. <a href="http://i.stack.imgur.com/j2M1G.png" rel="nofollow">results</a></p> <pre><code>{'ICMP timestamp response': ['10.103.128.11', ['22.103.128.11']], 'Partition Mounting Weakness': ['50.103.128.11', ['10.103.129.11']], "Root's umask value is unsafe": ['10.103.128.11', ['0.103.128.11'], ['20.103.128.11']], 'UDP IP ID Zero': ['10.103.128.11', ['10.103.128.11']]} </code></pre>
1
2016-08-23T18:54:38Z
39,108,788
<p>Use <code>setdefault()</code>, don't make <code>b</code> a list, and don't use builtins as variable names:</p> <pre><code>d = {} with open('test.csv', 'rb') as f: reader = csv.DictReader(f, delimiter=',') for row in reader: a = row["Vulnerability Title"] b = row["Asset IP Address"] d.setdefault(a, []).append(b) </code></pre>
2
2016-08-23T18:58:28Z
[ "python", "list", "csv", "dictionary", "append" ]
dataframe merge with missing data
39,108,845
<p>I have 2 dataframes:</p> <pre><code>df.head() Out[2]: Unnamed: 0 Symbol Date Close 0 4061 A 2016-01-13 36.515889 1 4062 A 2016-01-14 36.351784 2 4063 A 2016-01-15 36.351784 3 4064 A 2016-01-19 36.590483 4 4065 A 2016-01-20 35.934062 </code></pre> <p>and</p> <pre><code>dfw.head() Out[3]: Symbol Weight 0 A (0.000002) 1 AA 0.000112 2 AAC (0.000004) 3 AAL 0.000006 4 AAMC 0.000002 </code></pre> <p>ISSUE: Not every symbol if df will have a weight in dfw. If it does not I want to drop it from my new dataframe (all dates of it). If the symbol is in dfw I want to merge the weight in with df so that each row has symbol, date, close and weight. I have tried the following but get NaN values. I also am not sure how to remove all symbols with no weights even if I was successful.</p> <pre><code>dfall = df.merge(dfw, on='Symbol', how='left') dfall.head() Out[14]: Unnamed: 0 Symbol Date Close Weight 0 4061 A 2016-01-13 36.515889 NaN 1 4062 A 2016-01-14 36.351784 NaN 2 4063 A 2016-01-15 36.351784 NaN 3 4064 A 2016-01-19 36.590483 NaN 4 4065 A 2016-01-20 35.934062 NaN </code></pre>
1
2016-08-23T19:02:14Z
39,108,951
<pre><code>df_all = df[df.Symbol.isin(dfw.Symbol.unique())].merge(dfw, how='left', on='Symbol') </code></pre> <p>I am not sure why you are getting NaN values. Perhaps you have spaces in you your symbols? You can clean them via: <code>dfw['Symbol'] = dfw.Symbol.str.strip()</code> You would need to do the same for <code>df</code>.</p> <pre><code>&gt;&gt;&gt; df_all Unnamed: 0 Symbol Date Close Weight 0 4061 A 2016-01-13 36.515889 (0.000002) 1 4062 A 2016-01-14 36.351784 (0.000002) 2 4063 A 2016-01-15 36.351784 (0.000002) 3 4064 A 2016-01-19 36.590483 (0.000002) 4 4065 A 2016-01-20 35.934062 (0.000002) </code></pre>
3
2016-08-23T19:09:24Z
[ "python", "pandas", "dataframe", "merge" ]
OSError: The CUDA lib64 path could not be located in /usr/lib64
39,108,859
<p>How can I fix this? </p> <pre><code>(cv) jalal@klein:~/computer_vision/py-faster-rcnn/lib$ make python setup.py build_ext --inplace Traceback (most recent call last): File "setup.py", line 58, in &lt;module&gt; CUDA = locate_cuda() File "setup.py", line 55, in locate_cuda raise EnvironmentError('The CUDA %s path could not be located in %s' % (k, v)) OSError: The CUDA lib64 path could not be located in /usr/lib64 Makefile:2: recipe for target 'all' failed make: *** [all] Error 1 </code></pre> <p>I am using this: <a href="https://github.com/rbgirshick/py-faster-rcnn" rel="nofollow">https://github.com/rbgirshick/py-faster-rcnn</a></p>
1
2016-08-23T19:03:33Z
39,109,011
<p>Solved this problem using the following change for those who might end of using this popular software (for Cuda ~5):</p> <pre><code>jalal@klein:~/computer_vision/py-faster-rcnn/lib$ vi setup.py change: cudaconfig = {'home':home, 'nvcc':nvcc, 'include': pjoin(home, 'include'), 'lib64': pjoin(home, 'lib64')} </code></pre> <p>to:</p> <pre><code>cudaconfig = {'home':home, 'nvcc':nvcc, 'include': pjoin(home, 'include'), 'lib64': pjoin(home, 'lib')} </code></pre> <p>If you are using Cuda7.5 you might need to leave it as lib64 or you might get an error.</p>
1
2016-08-23T19:12:18Z
[ "python", "ubuntu", "path", "gpu" ]
Join two columns in a Dataframe that has been pivoted
39,108,935
<p>I have two columns I am trying to join (Year and Quarter). I have pulled the data from sql and pivoted it as seen below:</p> <pre><code>df3 = pd.pivot_table(df, index=["Year", "Q"], columns='Area', values="Lows", aggfunc=np.sum, fill_value=0) </code></pre> <p>I would now like to join the columns <code>Year</code> and <code>Q</code> together for charting purposes but my indexes seem to be messed up. Below is how the dataframe is displayed. </p> <pre><code>Before: Year Q 2003 1 2 3 4 2004 1 2 Desired output: Period 2003 1 2003 2 2003 3 2003 4 </code></pre>
3
2016-08-23T19:08:43Z
39,109,134
<p>This should work:</p> <pre><code>df3.index = df3.index.to_series().apply(lambda x: ' '.join([str(y) for y in x])) </code></pre> <p><strong><em>more generalized</em></strong></p> <pre><code>join = lambda x, delim=' ': delim.join([str(y) for y in x]) df3.index = df3.index.to_series().apply(join, delim=' ') </code></pre>
2
2016-08-23T19:19:35Z
[ "python", "pandas", "join", "dataframe", "pivot" ]
Join two columns in a Dataframe that has been pivoted
39,108,935
<p>I have two columns I am trying to join (Year and Quarter). I have pulled the data from sql and pivoted it as seen below:</p> <pre><code>df3 = pd.pivot_table(df, index=["Year", "Q"], columns='Area', values="Lows", aggfunc=np.sum, fill_value=0) </code></pre> <p>I would now like to join the columns <code>Year</code> and <code>Q</code> together for charting purposes but my indexes seem to be messed up. Below is how the dataframe is displayed. </p> <pre><code>Before: Year Q 2003 1 2 3 4 2004 1 2 Desired output: Period 2003 1 2003 2 2003 3 2003 4 </code></pre>
3
2016-08-23T19:08:43Z
39,120,371
<p>Another faster solutions:</p> <pre><code>df.index = ['{} {}'.format(idx[1], idx[0]) for idx in df.index] </code></pre> <p>and</p> <pre><code>df.index = [' '.join((str(idx[0]), str(idx[1]))) for idx in df.index] </code></pre> <p><strong>Timings</strong>:</p> <pre><code>In [190]: %timeit df.index.to_series().apply(lambda x: ' '.join([str(y) for y in x])) 10 loops, best of 3: 44.5 ms per loop In [191]: %timeit [' '.join((str(idx[0]), str(idx[1]))) for idx in df.index] 10 loops, best of 3: 26.6 ms per loop In [192]: %timeit ['{} {}'.format(idx[1], idx[0]) for idx in df.index] 100 loops, best of 3: 19.2 ms per loop </code></pre> <p><strong>Code for timings</strong>:</p> <pre><code>df = pd.DataFrame({'A':[2,2,2,1,7,2], 'B':[5,5,5,4,7,4], 'C':[7,8,9,4,8,1]}) df = df.groupby(['A','B']).sum() df = pd.concat([df]*10000) print (df) </code></pre>
0
2016-08-24T10:10:11Z
[ "python", "pandas", "join", "dataframe", "pivot" ]
How to extract the first numbers in a string - Python
39,108,980
<p>How do I remove all the numbers before the first letter in a string? For example,</p> <pre><code>myString = "32cl2" </code></pre> <p>I want it to become:</p> <pre><code>"cl2" </code></pre> <p>I need it to work for any length of number, so 2h2 should become h2, 4563nh3 becomes nh3 etc. <strong>EDIT:</strong> This has numbers without spaces between so it is not the same as the other question and it is specifically the first numbers, not all of the numbers.</p>
1
2016-08-23T19:10:50Z
39,109,017
<p>If you were to solve it without regular expressions, you could have used <a href="https://docs.python.org/2/library/itertools.html#itertools.dropwhile"><code>itertools.dropwhile()</code></a>:</p> <pre><code>&gt;&gt;&gt; from itertools import dropwhile &gt;&gt;&gt; &gt;&gt;&gt; ''.join(dropwhile(str.isdigit, "32cl2")) 'cl2' &gt;&gt;&gt; ''.join(dropwhile(str.isdigit, "4563nh3")) 'nh3' </code></pre> <hr> <p>Or, using <a href="https://docs.python.org/2/library/re.html#re.sub"><code>re.sub()</code></a>, replacing one or more digits at the beginning of a string:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; re.sub(r"^\d+", "", "32cl2") 'cl2' &gt;&gt;&gt; re.sub(r"^\d+", "", "4563nh3") 'nh3' </code></pre>
5
2016-08-23T19:12:47Z
[ "python", "string", "numbers", "truncate" ]
How to extract the first numbers in a string - Python
39,108,980
<p>How do I remove all the numbers before the first letter in a string? For example,</p> <pre><code>myString = "32cl2" </code></pre> <p>I want it to become:</p> <pre><code>"cl2" </code></pre> <p>I need it to work for any length of number, so 2h2 should become h2, 4563nh3 becomes nh3 etc. <strong>EDIT:</strong> This has numbers without spaces between so it is not the same as the other question and it is specifically the first numbers, not all of the numbers.</p>
1
2016-08-23T19:10:50Z
39,109,021
<p>Use <code>lstrip</code>:</p> <pre><code>myString.lstrip('0123456789') </code></pre> <p>or</p> <pre><code>import string myString.lstrip(string.digits) </code></pre>
2
2016-08-23T19:13:00Z
[ "python", "string", "numbers", "truncate" ]
How to specify a variable as a member variables of a class or of an instance of the class?
39,108,996
<p>in latest Python 2.7.x:</p> <ol> <li><p>Given any member variable inside the definition of a class, is the member variable always at the class level in the sense that it is a single variable shared by all the instances of the class?</p></li> <li><p>In the definition of a class, how can I specify </p> <ul> <li>which member variables in the definition of a class belong to the class and thus shared by all the instances of the class, and </li> <li>which belong to a particular instance of the class and not to another instance of the class?</li> </ul></li> <li><p>How can I refer to a member variable of a class?</p> <p>How can I refer to a member variable of an instance of a class?</p></li> <li><p>Do the answers to the above questions appear somewhere in the official python language reference <a href="https://docs.python.org/2/reference/" rel="nofollow">https://docs.python.org/2/reference/</a>? I can't find them there.</p></li> </ol> <p>Thanks.</p>
1
2016-08-23T19:11:33Z
39,109,336
<p>You might want to use the <a href="https://docs.python.org/2/tutorial/classes.html#class-and-instance-variables" rel="nofollow">terminology</a> "class variable" and "instance variable" here, as that's the usual language in python. </p> <pre><code>class Foo(object): var1 = "I'm a class variable" def __init__(self, var2): self.var2 = var2 # var2 is an instance variable </code></pre> <p>The only scoping rule you really need to know in python is the lookup order for names - "LEGB", for Local, Enclosing, Global and Builtin. </p> <p>The class scoped variable <code>var1</code> still has to be looked up by "get attribute", you can only access that by <code>Foo.var1</code> or <code>self.var1</code>. Of course, you can also access it elsewhere inside the class definition block, but that is just an example usage from the "Local" scope. </p> <p>When you see <code>self.var1</code>, you can't immediately know whether it is an instance or a class variable (nor, in fact, if the name is bound to an object at all!). You only know that get attribute is tried on the object itself before it's tried on the class. </p> <p>Indeed, an instance variable can shadow a class variable of the same name: </p> <pre><code>&gt;&gt;&gt; f1 = Foo(var2='f1_2') &gt;&gt;&gt; f2 = Foo(var2='f2_2') &gt;&gt;&gt; f2.var1 "I'm a class variable" &gt;&gt;&gt; f2.var1 = "Boom!" # this shadows the class variable &gt;&gt;&gt; f1.var1, Foo.var1, f2.var1 # but: the class variable still exists ("I'm a class variable", "I'm a class variable", 'Boom!') &gt;&gt;&gt; del f2.var1 # restores the name resolution on the Foo object &gt;&gt;&gt; f2.var1 "I'm a class variable" </code></pre> <p>To complicate matters, we can write fancy code which makes class variables behave more like instance variables; a notable example are "fields" of an <a href="https://en.wikipedia.org/wiki/Object-relational_mapping" rel="nofollow">ORM</a>. For example in <a href="https://www.djangoproject.com/" rel="nofollow">Django</a>, you may define an integer field on the <a href="https://docs.djangoproject.com/en/1.10/topics/db/models/" rel="nofollow">model</a> class - however when you lookup that name on an instance of the model, you get an actual integer returned (not an <code>IntegerField</code> object). </p> <p>If you're interested in this advanced usage of attribute access, read up on the <a href="https://docs.python.org/3/howto/descriptor.html" rel="nofollow">descriptor protocol</a>. For mundane classes you can safely ignore those details, but it's worth knowing that the usual resolution of instance variables and then class variables has <em>lower precedence</em> than any descriptors that may have been defined on the class. </p>
1
2016-08-23T19:33:50Z
[ "python", "python-2.7" ]
django: RecursionError when initialize a object
39,109,000
<p>SO I am trying to build a simple shopping cart feature for my app, that simply add, remove a piece of equipment, and display a list of current cart. Here are my codes for this cart: (codes largely adopted from <a href="https://github.com/bmentges/django-cart" rel="nofollow">https://github.com/bmentges/django-cart</a>)</p> <p>cart.py:</p> <pre><code>import datetime from .models import Cart, Item, ItemManager CART_ID = 'CART-ID' class ItemAlreadyExists(Exception): pass class ItemDoesNotExist(Exception): pass class Cart: def __init__(self, request, *args, **kwargs): super(Cart, self).__init__() cart_id = request.session.get(CART_ID) if cart_id: try: cart = models.Cart.objects.get(id=cart_id, checked_out=False) except models.Cart.DoesNotExist: cart = self.new(request) else: cart = self.new(request) self.cart = cart def __iter__(self): for item in self.cart.item_set.all(): yield item def new(self, request): cart = Cart(request, creation_date=datetime.datetime.now()) cart.save() request.session[CART_ID] = cart.id return cart def add(self, equipment): try: item = models.Item.objects.get( cart=self.cart, equipment=equipment, ) except models.Item.DoesNotExist: item = models.Item() item.cart = self.cart item.equipment = equipment item.save() else: #ItemAlreadyExists item.save() def remove(self, equipment): try: item = models.Item.objects.get( cart=self.cart, equipment=equipment, ) except models.Item.DoesNotExist: raise ItemDoesNotExist else: item.delete() def count(self): result = 0 for item in self.cart.item_set.all(): result += 1 * item.quantity return result def clear(self): for item in self.cart.item_set.all(): item.delete() </code></pre> <p>and models.py:</p> <pre><code>class Cart(models.Model): creation_date = models.DateTimeField(verbose_name=_('creation date')) checked_out = models.BooleanField(default=False, verbose_name=_('checked out')) class Meta: verbose_name = _('cart') verbose_name_plural = _('carts') ordering = ('-creation_date',) def __unicode__(self): return unicode(self.creation_date) class ItemManager(models.Manager): def get(self, *args, **kwargs): if 'equipment' in kwargs: kwargs['content_type'] = ContentType.objects.get_for_model(type(kwargs['equipment'])) kwargs['object_id'] = kwargs['equipment'].pk del(kwargs['equipment']) return super(ItemManager, self).get(*args, **kwargs) class Item(models.Model): cart = models.ForeignKey(Cart, verbose_name=_('cart')) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() objects = ItemManager() class Meta: verbose_name = _('item') verbose_name_plural = _('items') ordering = ('cart',) def __unicode__(self): return u'%d units of %s' % (self.quantity, self.equipment.__class__.__name__) # product def get_product(self): return self.content_type.get_object_for_this_type(pk=self.object_id) def set_product(self, equipment): self.content_type = ContentType.objects.get_for_model(type(equipment)) self.object_id = equipment.pk </code></pre> <p>When trying to go the view displaying current cart, I got this problem:</p> <blockquote> <p>RecursionError at /calbase/cart/ maximum recursion depth exceeded in comparison</p> </blockquote> <p>and basically it repeats calling the following :</p> <pre><code>cart = Cart(request, creation_date=datetime.datetime.now()) cart = self.new(request) cart = Cart(request, creation_date=datetime.datetime.now()) cart = self.new(request) </code></pre> <p>.....</p> <p>I am aware that this is because I am calling <em>init</em> when doing cart = Cart(...) and this again go back to cart = self.new(request) and tried several ways to fix this, in vain. Could somebody help me?</p> <p>Environment:</p> <pre><code>Request Method: GET Request URL: http://127.0.0.1:8000/calbase/cart/ Django Version: 1.10 Python Version: 3.5.2 Installed Applications: ['calbase.apps.CalbaseConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'haystack', 'whoosh'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] </code></pre> <p>Traceback:</p> <pre><code>File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request) File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\hansong.li\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\hansong.li\Documents\GitHub\equipCal\calbase\views.py" in get_cart 72. return render_to_response('cart.html', dict(cart=Cart(request))) File "C:\Users\hansong.li\Documents\GitHub\equipCal\calbase\cart.py" in __init__ 22. cart = self.new(request) File "C:\Users\hansong.li\Documents\GitHub\equipCal\calbase\cart.py" in __init__ 22. cart = self.new(request) File "C:\Users\hansong.li\Documents\GitHub\equipCal\calbase\cart.py" in new 30. cart = Cart(request, creation_date=datetime.datetime.now()) Exception Type: RecursionError at /calbase/cart/ Exception Value: maximum recursion depth exceeded in comparison </code></pre>
1
2016-08-23T19:11:41Z
39,109,394
<p>You have two separate classes called Cart. Rename one of ,them.</p>
2
2016-08-23T19:37:45Z
[ "python", "django", "oop" ]
Numpy "where" with multiple conditions
39,109,045
<p>I try to add a new column "energy_class" to a dataframe "df_energy" which it contains the string "high" if the "consumption_energy" value > 400, "medium" if the "consumption_energy" value is between 200 and 400, and "low" if the "consumption_energy" value is under 200. I try to use np.where from numpy, but I see that <code>numpy.where(condition[, x, y])</code> treat only two condition not 3 like in my case.</p> <p>Any idea to help me please?</p> <p>Thank you in advance</p>
4
2016-08-23T19:14:07Z
39,109,099
<p>You can use a <a href="http://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator">ternary</a>:</p> <pre><code>np.where(consumption_energy &gt; 400, 'high', (np.where(consumption_energy &lt; 200, 'low', 'medium))) </code></pre>
4
2016-08-23T19:17:48Z
[ "python", "pandas", "numpy", "dataframe" ]
Numpy "where" with multiple conditions
39,109,045
<p>I try to add a new column "energy_class" to a dataframe "df_energy" which it contains the string "high" if the "consumption_energy" value > 400, "medium" if the "consumption_energy" value is between 200 and 400, and "low" if the "consumption_energy" value is under 200. I try to use np.where from numpy, but I see that <code>numpy.where(condition[, x, y])</code> treat only two condition not 3 like in my case.</p> <p>Any idea to help me please?</p> <p>Thank you in advance</p>
4
2016-08-23T19:14:07Z
39,109,969
<p>I would use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow">cut()</a> method here, which will generate very efficient and memory-saving <code>category</code> dtype:</p> <pre><code>In [124]: df Out[124]: consumption_energy 0 459 1 416 2 186 3 250 4 411 5 210 6 343 7 328 8 208 9 223 In [125]: pd.cut(df.consumption_energy, [0, 200, 400, np.inf], labels=['low','medium','high']) Out[125]: 0 high 1 high 2 low 3 medium 4 high 5 medium 6 medium 7 medium 8 medium 9 medium Name: consumption_energy, dtype: category Categories (3, object): [low &lt; medium &lt; high] </code></pre>
4
2016-08-23T20:16:18Z
[ "python", "pandas", "numpy", "dataframe" ]
Numpy "where" with multiple conditions
39,109,045
<p>I try to add a new column "energy_class" to a dataframe "df_energy" which it contains the string "high" if the "consumption_energy" value > 400, "medium" if the "consumption_energy" value is between 200 and 400, and "low" if the "consumption_energy" value is under 200. I try to use np.where from numpy, but I see that <code>numpy.where(condition[, x, y])</code> treat only two condition not 3 like in my case.</p> <p>Any idea to help me please?</p> <p>Thank you in advance</p>
4
2016-08-23T19:14:07Z
39,111,919
<p>Try this: Using the setup from @Maxu</p> <pre><code>conditions = [ df2['consumption_energy'] &gt;= 400, (df2['consumption_energy'] &lt; 400) &amp; (df2['consumption_energy']&gt; 200), df2['consumption_energy'] &lt;= 200 ] choices = [ "high", 'medium', 'low' ] df2["energy_class"] = np.select(conditions, choices, default=np.nan) consumption_energy energy_class 0 459 high 1 416 high 2 186 low 3 250 medium 4 411 high 5 210 medium 6 343 medium 7 328 medium 8 208 medium 9 223 medium </code></pre>
1
2016-08-23T22:53:29Z
[ "python", "pandas", "numpy", "dataframe" ]
Why does truncating a BytesIO mess it up?
39,109,068
<p>Running this on Python 3.5.1 on OSX:</p> <pre><code>import io b = io.BytesIO() b.write(b'222') print(b.getvalue()) b.truncate(0) b.write(b'222') print(b.getvalue()) </code></pre> <p>Produces:</p> <pre><code>b'222' b'\x00\x00\x00222' </code></pre> <p>So truncating the <code>BytesIO</code> somehow causes it to start inserting extra zero bytes in the beginning? Why?</p>
0
2016-08-23T19:15:21Z
39,109,137
<p><code>truncate</code> does not move the file pointer. So the next byte is written to the next position. You have also to seek to the beginning:</p> <pre><code>b.seek(0) b.truncate() </code></pre>
3
2016-08-23T19:19:47Z
[ "python", "python-3.x", "bytesio" ]
Checking if epic issue exists and if not, make a new epic issue
39,109,140
<p>So the problem is an IndexError, which makes sense considering there isn't supposed to be any results for that jql query.</p> <pre><code>epic_search = 'project = "EXM" and type = Epic and summary ~ "summaryx" ' esearch = jira.search_issues(epic_search) if esearch[0].key == None: epic_dict = { 'project': {'key': 'EXM'}, 'customfield_12345': 'summaryx', 'summary': 'summaryx', 'issuetype': {'name': 'Epic'}, } new_epic = jira.create_issue(fields=epic_dict) print (new_epic.key) </code></pre> <p>Is there a way I can check the jql results and if empty, create an epic?</p>
1
2016-08-23T19:19:58Z
39,111,416
<p>Probably something like </p> <p>if (count(esearch) > 0):</p> <p>I assume this is python. I don't do python but there must be something like a count() or maybe esearch.length to tell you how many items are in there.</p>
2
2016-08-23T22:06:22Z
[ "python", "python-3.x", "jira", "jql", "python-jira" ]
Dumping JSON directly into a tarfile
39,109,180
<p>I have a large list of dict objects. I would like to store this list in a tar file to exchange remotely. I have done that successfully by writing a json.dumps() string to a tarfile object opened in 'w:gz' mode. </p> <p>I am trying for a piped implementation, opening the tarfile object in 'w|gz' mode. Here is my code so far:</p> <pre><code>from json import dump from io import StringIO import tarfile with StringIO() as out_stream, tarfile.open(filename, 'w|gz', out_stream) as tar_file: for packet in json_io_format(data): dump(packet, out_stream) </code></pre> <p>This code is in a function 'write_data'. 'json_io_format' is a generator that returns one dict object at a time from the dataset (so packet is a dict).</p> <p>Here is my error:</p> <pre><code>Traceback (most recent call last): File "pdml_parser.py", line 35, in write_data dump(packet, out_stream) File "/.../anaconda3/lib/python3.5/tarfile.py", line 2397, in __exit__ self.close() File "/.../anaconda3/lib/python3.5/tarfile.py", line 1733, in close self.fileobj.close() File "/.../anaconda3/lib/python3.5/tarfile.py", line 459, in close self.fileobj.write(self.buf) TypeError: string argument expected, got 'bytes' </code></pre> <p>After some troubleshooting with help from the comments, the error is caused when the 'with' statement exits, and tries to call the context manager __exit__. I <em>BELIEVE</em> that this in turn calls TarFile.close(). If I remove the tarfile.open() call from the 'with' statement, and purposefully leave out the TarFile.close(), I get this code:</p> <pre><code>with StringIO() as out_stream: tarfile.open(filename, 'w|gz', out_stream) as tar_file: for packet in json_io_format(data): dump(packet, out_stream) </code></pre> <p>This version of the program completes, but does not produce the output file 'filname' and yields this error:</p> <pre><code>Exception ignored in: &lt;bound method _Stream.__del__ of &lt;targile._Stream object at 0x7fca7a352b00&gt;&gt; Traceback (most recent call last): File "/.../anaconda3/lib/python3.5/tarfile.py", line 411, in __del__ self.close() File "/.../anaconda3/lib/python3.5/tarfile.py", line 459, in close self.fileobj.write(self.buf) TypeError: string argument expected, got 'bytes' </code></pre> <p>I believe that is caused by the garbage collector. Something is preventing the TarFile object from closing.</p> <p>Can anyone help me figure out what is going on here?</p>
0
2016-08-23T19:22:37Z
39,110,105
<p>Why do you think you can write a tarfile to a StringIO? That doesn't work like you think it does.</p> <p>This approach doesn't error, but it's not actually how you create a tarfile in memory from in-memory objects.</p> <pre><code>from json import dumps from io import BytesIO import tarfile data = [{'foo': 'bar'}, {'cheese': None}, ] filename = 'fnord' with BytesIO() as out_stream, tarfile.open(filename, 'w|gz', out_stream) as tar_file: for packet in data: out_stream.write(dumps(packet).encode()) </code></pre>
0
2016-08-23T20:26:33Z
[ "python", "json", "python-3.x", "tarfile" ]
Python LDAP: LDAPObject.search_s() works, but LDAPObject.search() doesn't
39,109,248
<p>I am trying to implement a basic LDAP authentication script in Python, and I am trying to just perform a simple LDAP search and see if it works. I believe I have correctly created and set up my LDAP object and connection.</p> <p>After binding, I try to perform a search. Using the LDAPObject.search_s() method successfully returns a list of strings with user information. When I use the LDAPObject.search() method, though, the method returns result code 2, which is a protocol error. The reason I want to use the search() method is because it returns an int and not a list. From what I understand according to <a href="https://www.python-ldap.org/doc/html/ldap.html#ldap.LDAPObject.search" rel="nofollow">the Python LDAP documentation</a>, the two methods can take in the same arguments, so I don't understand why one method is returning an error and not the other.</p> <p>Here is my code:</p> <pre><code>import ldap import getpass # get login info username = raw_input("Enter your username: ") password = getpass.getpass("Enter your password: ") ldap_server = "LDAP://ipaddress:port" base_dn = "OU=Domain Users,DC=dummyname,DC=com" user_dn = username + "@dummyname.com" search_filter = "(&amp;(objectClass=user)(sAMAccountName=" + username + "))" ld = ldap.initialize(ldap_server); ld = ldap.open(ldap_server) ld.protocol_version = 3 ld.set_option(ldap.OPT_REFERRALS, 0) # bind user information to ldap connection try: print ld.simple_bind_s(user_dn, password) results = ld.search(base_dn, ldap.SCOPE_SUBTREE, search_filter) print results ld.unbind_s() except ldap.INVALID_CREDENTIALS: print "Your username or password is invalid." except Exception as e: print("Connection unsuccessful: " + str(e.message)) ld.unbind_s() </code></pre> <p>Full output of this code is:</p> <pre><code>Enter your username: myusername Enter your password: (97, [], 1, []) 2 </code></pre> <p>Any help would be greatly appreciated. Thanks.</p>
0
2016-08-23T19:27:43Z
39,309,051
<p>The following command is using an async search which does not block to wait for a return value. The int it returns is actually the MSGID of the LDAPObject which you need to get the return value when it is returned. </p> <pre><code>msgid = ld.search(base_dn, ldap.SCOPE_SUBTREE, search_filter) # Returns int of msgid without blocking </code></pre> <p>To get the actual results you need to call</p> <pre><code>actual_results = ld.result(msgid) # Blocks until search is done and returns [(dn,attrs)] </code></pre> <p>Using the following commands causes the LDAPObject to search in "sequential order" thus blocking the program.</p> <pre><code>results = ld.search_s(base_dn, ldap.SCOPE_SUBTREE, search_filter) # blocks until all results are received [(dn,attrs)] </code></pre>
0
2016-09-03T16:30:02Z
[ "python", "active-directory", "ldap", "ldap-query" ]
C++11 equivalent to Python's all() function
39,109,324
<p>Is there an equivalent function to Python's <a href="https://docs.python.org/3/library/functions.html#all" rel="nofollow"><code>all()</code></a> built-in function?</p> <p>In other words: Does a C++11 function exist that returns <code>true</code> when all of the elements of an iterable meet a certain condition and <code>false</code> otherwise?</p>
-2
2016-08-23T19:33:07Z
39,109,362
<p>Check out <code>std::all_of</code> in the <code>&lt;algorithm&gt;</code> header. You can pass a custom predicate that evaluates to true or false on each element.</p>
2
2016-08-23T19:35:16Z
[ "python", "c++11", "iterable", "built-in" ]
C++11 equivalent to Python's all() function
39,109,324
<p>Is there an equivalent function to Python's <a href="https://docs.python.org/3/library/functions.html#all" rel="nofollow"><code>all()</code></a> built-in function?</p> <p>In other words: Does a C++11 function exist that returns <code>true</code> when all of the elements of an iterable meet a certain condition and <code>false</code> otherwise?</p>
-2
2016-08-23T19:33:07Z
39,109,741
<p>Also, for doing the same thing with template parameter pack (like <code>template &lt;bool... values&gt;</code>) you can use fold expression: <code>(values &amp;&amp; ...)</code>, but only since C++17. Documentation of this feature is here:</p> <p><a href="http://en.cppreference.com/w/cpp/language/fold" rel="nofollow">http://en.cppreference.com/w/cpp/language/fold</a></p>
0
2016-08-23T20:00:34Z
[ "python", "c++11", "iterable", "built-in" ]
"list indices must be integers, not list" with enumerate
39,109,342
<p>I have this code</p> <pre><code>cNames = data["channelnames"] goodChannels = [i for i,x in enumerate(cNames) if x!='Skipped'] data["channelnames"]=cNames[goodChannels] </code></pre> <p>I need the channel numbers later, but the cNames[goodChannels] throws the error "list indices must be integers, not list"</p> <p>the list is made of integers. Is there a way to make this work correctly?</p> <p>cNames[np.array(goodChannels)] does not work with the same error, so I am assuming that there is something else going on here.</p>
-2
2016-08-23T19:34:07Z
39,109,409
<p>You need another list comprehension:</p> <pre><code>data["channelnames"] = [cNames[i] for i in goodChannels] </code></pre>
1
2016-08-23T19:38:47Z
[ "python" ]
Making the name of shape node to be the same as the parent
39,109,369
<p>How can I make the name of the shape node to have similar name as its parent node? (Assuming there is only 1 shape node per geometry/object)</p> <p>For eg. parent_geo is called <code>test_geo1</code>, however its shape node is <code>testing_geo2Shape</code> instead of <code>test_geo1Shape</code></p> <p>I tried doing the following:</p> <pre><code>all = cmds.ls(sl=True, dag=True, shapes=True) for shape in all: prt = cmds.listRelatives(shape, parent=True) for i in prt: child = cmds.listRelatives(i, c = True) for c in child: cmds.rename(c, str(prt) + "Shape") </code></pre> <p>and I get some funky names such as <code>u_test_geo1__Shape</code> etc</p>
0
2016-08-23T19:35:44Z
39,118,600
<pre><code>all = cmds.ls(sl=True, dag=True, shapes=True) for shape in all: ''' shape contain the dag path exm.: grp_a grp_aShape grp_b grp_bShape print cmds.ls('grp_a', dag=1, shapes=1) &gt;&gt;('grp_a|grp_aShape', 'grp_b|grp_bShape') now rename the object, we have already the dag path so the input of the rename command is unique, you can also split the dag path by '|'[0] as parent ''' cmds.rename(shape, "{0}Shape".format(cmds.listRelatives(shape, parent=True)[0])) </code></pre> <p>tested hierarchy was like:</p> <pre><code>grp_a shape grp_a grp_b same name like shape grp_c grp_c shape grp_c grp_d same name like shape grp_c grp_e same name like shape grp_c </code></pre> <p>select only the top grp</p>
1
2016-08-24T08:49:34Z
[ "python", "maya" ]
NotImplementedError: 'pop' not supported on frozendict
39,109,393
<p>I'm adapting a module for Odoo v9 community</p> <p>It uses frozendict, but everytime I try to use a feature, it throws:</p> <pre><code>NotImplementedError: 'pop' not supported on frozendict </code></pre> <p>The code is as follows:</p> <pre><code>def fields_view_get(self, cr, uid, view_id=None, view_type=False, context=None, toolbar=False, submenu=False): if context is None: context = {} journal_obj = self.pool.get('account.journal') user_obj = self.pool.get('res.users') # remove the entry with key 'form_view_ref', otherwise fields_view_get # crashes #context=dict(context) context.pop('form_view_ref', None) res = super(AccountInvoiceRefund, self).\ fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu) type = context.get('type', 'out_invoice') company_id = user_obj.browse( cr, uid, uid, context=context).company_id.id journal_type = (type == 'out_invoice') and 'sale_refund' or \ (type == 'out_refund') and 'sale' or \ (type == 'in_invoice') and 'purchase_refund' or \ (type == 'in_refund') and 'purchase' for field in res['fields']: if field == 'journal_id': journal_select = journal_obj._name_search(cr, uid, '', [('type', '=', journal_type), ('company_id', 'child_of', [company_id])], context=context) res['fields'][field]['selection'] = journal_select return res </code></pre> <p>Following <a href="http://poncesoft.blogspot.com/2015/03/solucion-error-notimplementederror.html" rel="nofollow">this</a> I've added this code to the line:</p> <pre><code>if context is None: context = {} journal_obj = self.pool.get('account.journal') user_obj = self.pool.get('res.users') context=dict(context) context.pop('form_view_ref', None) res = super(AccountInvoiceRefund, self).\ </code></pre> <p>Instead of:</p> <pre><code>if context is None: context = {} journal_obj = self.pool.get('account.journal') user_obj = self.pool.get('res.users') context.pop('form_view_ref', None) res = super(AccountInvoiceRefund, self).\ </code></pre> <p>As You can see I've added <code>context=dict(context)</code>, but still get the same error.</p> <p>Any ideas about this?</p> <p>Thanks in advance!</p>
0
2016-08-23T19:37:42Z
39,109,844
<p>Contexts are <a href="https://pypi.python.org/pypi/frozendict" rel="nofollow">frozendict</a> objects that you cannot directly modify. This has been implemented on version 9 from what I am aware, </p> <p>If you want to modify the context in your code you have to use methods provided by Odoo's API, take a look at the definition of the method named <code>with_context</code> on <code>openerp/models.py</code> around line 5460. It is sufficiently documented and you can find many examples on the source files as to how it is used.</p>
2
2016-08-23T20:07:31Z
[ "python", "openerp", "odoo-9" ]
NotImplementedError: 'pop' not supported on frozendict
39,109,393
<p>I'm adapting a module for Odoo v9 community</p> <p>It uses frozendict, but everytime I try to use a feature, it throws:</p> <pre><code>NotImplementedError: 'pop' not supported on frozendict </code></pre> <p>The code is as follows:</p> <pre><code>def fields_view_get(self, cr, uid, view_id=None, view_type=False, context=None, toolbar=False, submenu=False): if context is None: context = {} journal_obj = self.pool.get('account.journal') user_obj = self.pool.get('res.users') # remove the entry with key 'form_view_ref', otherwise fields_view_get # crashes #context=dict(context) context.pop('form_view_ref', None) res = super(AccountInvoiceRefund, self).\ fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu) type = context.get('type', 'out_invoice') company_id = user_obj.browse( cr, uid, uid, context=context).company_id.id journal_type = (type == 'out_invoice') and 'sale_refund' or \ (type == 'out_refund') and 'sale' or \ (type == 'in_invoice') and 'purchase_refund' or \ (type == 'in_refund') and 'purchase' for field in res['fields']: if field == 'journal_id': journal_select = journal_obj._name_search(cr, uid, '', [('type', '=', journal_type), ('company_id', 'child_of', [company_id])], context=context) res['fields'][field]['selection'] = journal_select return res </code></pre> <p>Following <a href="http://poncesoft.blogspot.com/2015/03/solucion-error-notimplementederror.html" rel="nofollow">this</a> I've added this code to the line:</p> <pre><code>if context is None: context = {} journal_obj = self.pool.get('account.journal') user_obj = self.pool.get('res.users') context=dict(context) context.pop('form_view_ref', None) res = super(AccountInvoiceRefund, self).\ </code></pre> <p>Instead of:</p> <pre><code>if context is None: context = {} journal_obj = self.pool.get('account.journal') user_obj = self.pool.get('res.users') context.pop('form_view_ref', None) res = super(AccountInvoiceRefund, self).\ </code></pre> <p>As You can see I've added <code>context=dict(context)</code>, but still get the same error.</p> <p>Any ideas about this?</p> <p>Thanks in advance!</p>
0
2016-08-23T19:37:42Z
39,113,481
<p>A quick way to get over this would be to copy the frozen dictionary to another dictionary and then pass that dictionary to the method either as an argument or if you are using the new api, use the 'with_context' method.</p> <p>Here is an example:</p> <pre><code>ctx = dict(self._context) self.with_context(ctx).write({'invoice_line': []}) </code></pre> <p>As you can see in the above example the _context is copied to ctx and then with_context is used to pass the new modified context.</p>
1
2016-08-24T02:27:44Z
[ "python", "openerp", "odoo-9" ]
Underscore after a variable name in python
39,109,398
<p>I am deciphering someone else's code and I see the following:</p> <pre><code>def get_set_string(set_): if PY3: return str(set_) else: return str(set_) </code></pre> <p>Does the underscore AFTER the variable mean anything or is this just a part of the variable's name and means nothing?</p>
0
2016-08-23T19:37:53Z
39,109,438
<p>It means nothing. I believe the one who wrote this wanted a variable name designating a set, but <code>set</code> is a type in Python (which creates a set), so he added the underscore.</p>
1
2016-08-23T19:41:03Z
[ "python", "python-3.x" ]
Underscore after a variable name in python
39,109,398
<p>I am deciphering someone else's code and I see the following:</p> <pre><code>def get_set_string(set_): if PY3: return str(set_) else: return str(set_) </code></pre> <p>Does the underscore AFTER the variable mean anything or is this just a part of the variable's name and means nothing?</p>
0
2016-08-23T19:37:53Z
39,109,501
<p>No semantics are associated with a trailing underscore. According to <a href="https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles" rel="nofollow"><code>PEP 8</code></a>, the style guide for Python, users are urged to use trailing underscores in order to not conflict with Python keywords and/or Python built-ins:</p> <blockquote> <p><code>single_trailing_underscore_</code> : used by convention to avoid conflicts with Python keyword, e.g.</p> <p><code>Tkinter.Toplevel(master, class_='ClassName')</code></p> </blockquote> <p>Using <code>set_</code> means that the built-in <code>set</code> won't get shadowed and lose its meaning during the function call. </p>
2
2016-08-23T19:45:18Z
[ "python", "python-3.x" ]
Using itertools for arbitrary number of nested loops of different ranges with dependencies?
39,109,537
<p>Given a list of upperbounds: B1, B2, .. BN;<br> Dependency Functions: f1, ..., fN-1, </p> <p>I'm wondering if there's a recipe using itertools or other classes in python for:</p> <pre><code>for i1 in range(0, B1): for i2 in range(f1(i1), B2): ... for iN in range(fN-1(iN-1), BN) dostuff(i1, i2, ... iN) </code></pre> <p>Where there are N levels of nesting?<br> I want to use this helper function like this:<br> <strong>dependentProducts(Bs, fs, dostuff)</strong>,<br> which returns a list or iterable </p> <p>Ideally, the implementation would be iterative instead of recursive.</p>
4
2016-08-23T19:48:17Z
39,110,133
<p>Here is an example of what you want:</p> <pre><code>B = [10, 15, 20, 5] F = [lambda x: x, lambda x: x * x, lambda x: x * 2 - 5] def dostuff(i0, i1, i2, i3): print((i0, i1, i2, i3)) expected = [] for i0 in range(0, B[0]): for i1 in range(F[0](i0), B[1]): for i2 in range(F[1](i1), B[2]): for i3 in range(F[2](i2), B[3]): expected.append([i0, i1, i2, i3]) </code></pre> <p>I found a recursive solution like this:</p> <pre><code>def iter_rec(found, fL, bL): if fL and bL: ik = found[-1] if found else 0 fk = fL[0] bk = bL[0] for i in range(fk(ik), bk): for item in iter_rec(found + [i], fL[1:], bL[1:]): yield item else: yield found # prepend the null function to ensure F and B have the same size F = [lambda x: 0] + F current = [item for item in iter_rec([], F, B)] </code></pre> <p>We have the same result.</p> <pre><code>assert expected == current </code></pre>
2
2016-08-23T20:28:39Z
[ "python", "python-3.x", "itertools", "functools" ]
Using itertools for arbitrary number of nested loops of different ranges with dependencies?
39,109,537
<p>Given a list of upperbounds: B1, B2, .. BN;<br> Dependency Functions: f1, ..., fN-1, </p> <p>I'm wondering if there's a recipe using itertools or other classes in python for:</p> <pre><code>for i1 in range(0, B1): for i2 in range(f1(i1), B2): ... for iN in range(fN-1(iN-1), BN) dostuff(i1, i2, ... iN) </code></pre> <p>Where there are N levels of nesting?<br> I want to use this helper function like this:<br> <strong>dependentProducts(Bs, fs, dostuff)</strong>,<br> which returns a list or iterable </p> <p>Ideally, the implementation would be iterative instead of recursive.</p>
4
2016-08-23T19:48:17Z
39,111,298
<p>An iterative solution using @LaurentLAPORTE's setup. Put this code right under his and it should work. My <code>args</code> is a stack of the arguments fed into <code>dostuff</code> whenever it's full. The actual solution is the middle part, top and bottom parts are just testing.</p> <pre><code>stefan = [] def dostuff(*args): stefan.append(list(args)) args = [-1] while args: n = len(args) args[-1] += 1 if args[-1] &gt;= B[n-1]: args.pop() elif n == len(B): dostuff(*args) else: args.append(F[n](args[-1]) - 1) assert expected == stefan </code></pre>
3
2016-08-23T21:56:34Z
[ "python", "python-3.x", "itertools", "functools" ]
__str__() doesn't work after importing class
39,109,677
<p>I encountered a problem while importing a class: the <strong>str</strong>() doesn't work after importing the class </p> <pre><code>class unit: value = None node = None def __init__(self,value,node): self.value = value self.node = node def __str__(self): if self.node == None: return str(self.value) + " -&gt; " + "Null" else: return str(self.value) + " -&gt; " + str(self.node.value) </code></pre> <p>within the class file, the <strong>str</strong>() works as expected:</p> <pre><code>print unit(5,None) 5 -&gt; Null </code></pre> <p>but when I import the class and test on the print function, it returns the object address instead of text pre-specified:</p> <pre><code>from unit import unit new = unit(5,None) print new &lt;unit.unit instance at 0x000000000A8420C8&gt; </code></pre> <p>Can you help me understanding what's going wrong?</p>
0
2016-08-23T19:56:44Z
39,115,939
<p>Assuming you put both <code>.py</code> files in the same directory, your <code>Python 2.7</code> code runs fine with a standard <code>CPython</code> interpreter such as <code>Canopy</code>. <code>Python 3.5</code> interpreters such as Anaconda will complain about the <code>print</code> not being used as a function and will thus not execute. </p> <p>Since your <code>print</code> behaves as the default <code>print</code> implementation for objects, you need to recompile (<code>.pyc</code> files) the involved <code>.py</code> files. This can easily be done by restarting your kernel in some IDE.</p> <p>Canopy IDE allows you to run a <code>.py</code> file again while the Python interpreter is still active. However, all objects created before this re-run stay the same and do not magically obtain your overridden <code>__str__</code> member method.</p>
0
2016-08-24T06:30:17Z
[ "python", "string", "oop", "import" ]
check if pair of values is in pair of columns in pandas
39,109,688
<p>Basically, I have latitude and longitude (on a grid) in two different columns. I am getting fed two-element lists (could be numpy arrays) of a new coordinate set and I want to check if it is a duplicate before I add it.</p> <p>For example, my data:</p> <pre><code>df = pd.DataFrame([[4,8, 'wolf', 'Predator', 10], [5,6,'cow', 'Prey', 10], [8, 2, 'rabbit', 'Prey', 10], [5, 3, 'rabbit', 'Prey', 10], [3, 2, 'cow', 'Prey', 10], [7, 5, 'rabbit', 'Prey', 10]], columns = ['lat', 'long', 'name', 'kingdom', 'energy']) newcoords1 = [4,4] newcoords2 = [7,5] </code></pre> <p>Is it possible to write one <code>if</code> statement to tell me whether there is already a row with that latitude and longitude. In pseudo code: </p> <pre><code>if newcoords1 in df['lat', 'long']: print('yes! ' + str(newcoords1)) </code></pre> <p>(In the example, <code>newcoords1</code> should be <code>false</code> and <code>newcoords2</code> should be <code>true</code>.</p> <p>Sidenote: <code>(newcoords1[0] in df['lat']) &amp; (newcoords1[1] in df['long'])</code> doesn't work because that checks them independently, but I need to know if that combination appears in a single row.</p> <p>Thank you in advance!</p>
3
2016-08-23T19:57:19Z
39,109,736
<p>you can do it this way:</p> <pre><code>In [140]: df.query('@newcoords2[0] == lat and @newcoords2[1] == long') Out[140]: lat long name kingdom energy 5 7 5 rabbit Prey 10 In [146]: df.query('@newcoords2[0] == lat and @newcoords2[1] == long').empty Out[146]: False </code></pre> <p>the following line will return a number of found rows:</p> <pre><code>In [147]: df.query('@newcoords2[0] == lat and @newcoords2[1] == long').shape[0] Out[147]: 1 </code></pre> <p>or using NumPy approach:</p> <pre><code>In [103]: df[(df[['lat','long']].values == newcoords2).all(axis=1)] Out[103]: lat long name kingdom energy 5 7 5 rabbit Prey 10 </code></pre> <p>this will show whether at least one row has been found:</p> <pre><code>In [113]: (df[['lat','long']].values == newcoords2).all(axis=1).any() Out[113]: True In [114]: (df[['lat','long']].values == newcoords1).all(axis=1).any() Out[114]: False </code></pre> <p>Explanation:</p> <pre><code>In [104]: df[['lat','long']].values == newcoords2 Out[104]: array([[False, False], [False, False], [False, False], [False, False], [False, False], [ True, True]], dtype=bool) In [105]: (df[['lat','long']].values == newcoords2).all(axis=1) Out[105]: array([False, False, False, False, False, True], dtype=bool) </code></pre>
2
2016-08-23T20:00:26Z
[ "python", "pandas", "dataframe" ]
check if pair of values is in pair of columns in pandas
39,109,688
<p>Basically, I have latitude and longitude (on a grid) in two different columns. I am getting fed two-element lists (could be numpy arrays) of a new coordinate set and I want to check if it is a duplicate before I add it.</p> <p>For example, my data:</p> <pre><code>df = pd.DataFrame([[4,8, 'wolf', 'Predator', 10], [5,6,'cow', 'Prey', 10], [8, 2, 'rabbit', 'Prey', 10], [5, 3, 'rabbit', 'Prey', 10], [3, 2, 'cow', 'Prey', 10], [7, 5, 'rabbit', 'Prey', 10]], columns = ['lat', 'long', 'name', 'kingdom', 'energy']) newcoords1 = [4,4] newcoords2 = [7,5] </code></pre> <p>Is it possible to write one <code>if</code> statement to tell me whether there is already a row with that latitude and longitude. In pseudo code: </p> <pre><code>if newcoords1 in df['lat', 'long']: print('yes! ' + str(newcoords1)) </code></pre> <p>(In the example, <code>newcoords1</code> should be <code>false</code> and <code>newcoords2</code> should be <code>true</code>.</p> <p>Sidenote: <code>(newcoords1[0] in df['lat']) &amp; (newcoords1[1] in df['long'])</code> doesn't work because that checks them independently, but I need to know if that combination appears in a single row.</p> <p>Thank you in advance!</p>
3
2016-08-23T19:57:19Z
39,109,824
<pre><code>x, y = newcoords1 &gt;&gt;&gt; df[(df.lat == x) &amp; (df.long == y)].empty True # Coordinates are not in the dataframe, so you can add it. x, y = newcoords2 &gt;&gt;&gt; df[(df.lat == x) &amp; (df.long == y)].empty False # Coordinates already exist. </code></pre>
2
2016-08-23T20:06:01Z
[ "python", "pandas", "dataframe" ]
Form input-box not displaying
39,109,694
<p>I'm trying to display a simple form input-text box with Django. I'm am deploying on Amazon AWS. The site works fine on a different server (pythonanywhere) but there is a major problem on AWS. Specifically, the input box is not being displayed. I'm using templates as follows:</p> <p><strong>home.html</strong></p> <pre><code>{% extends 'lists/base.html' %} {% block header_text %}Start a new To-Do list {% endblock %} {% block form_action %}{% url 'new_list' %}{% endblock %} </code></pre> <p><strong>base.html</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta http-equiv="X UA-Compatible" content="IE-edge"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;title&gt;To-Do lists&lt;/title&gt; &lt;link href="/static/bootstrap/css/bootstrap.min.css" rel="stylesheet"&gt; &lt;link href="/static/base.css" rel="stylesheet"&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-md-6 col-md-offset-3 jumbotron"&gt; &lt;div class="text-center"&gt; &lt;h1&gt;{% block header_text %}{% endblock %}&lt;/h1&gt; &lt;form method="POST" action="{% block form_action %}{% endblock %}"&gt; {{ form.text }} {% csrf_token %} {% if form.errors %} &lt;div class = "form-group has-error"&gt; &lt;span class = "help-block"&gt;{{ form.text.errors }}&lt;/span&gt; &lt;/div&gt; {% endif %} &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-md-6 col-md-offset-3"&gt; {% block table %} {% endblock %} &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>models.py</strong></p> <pre><code>from django.db import models from django .core.urlresolvers import reverse class List(models.Model): def get_absolute_url(self): return reverse('view_list', args=[self.id]) # Create your models here. class Item(models.Model): text = models.TextField(default = '') list = models.ForeignKey(List, default = None) #list = models.ForeignKey(List , default=None) </code></pre> <p><strong>forms.py</strong></p> <pre><code>from django import forms from lists.models import Item EMPTY_ITEM_ERROR = "You can't have an empty list item" class ItemForm(forms.models.ModelForm): class Meta: model = Item fields = ('text',) widgets ={ 'text' : forms.fields.TextInput(attrs={ 'placeholder': 'Enter a to-do item', 'class': 'form-control input-lg', }), } error_messages = { 'text' : { 'required': EMPTY_ITEM_ERROR } } </code></pre> <p><strong>views.py</strong> </p> <pre><code>from django.shortcuts import redirect, render from lists.models import Item, List from django.core.exceptions import ValidationError from lists.forms import ItemForm from lists.models import Item, List # Create your views here. def home_page(request): return render(request, 'lists/home.html', {'form': ItemForm()}) </code></pre> <p><strong>urls.py</strong></p> <pre><code>from django.conf.urls import url from lists import views urlpatterns = [ url(r'^new$', views.new_list, name='new_list'), url(r'^(\d+)/$', views.view_list, name='view_list'), ] </code></pre> <p>Currently the site displays the following:</p> <p><a href="http://i.stack.imgur.com/nLkIw.png" rel="nofollow"><img src="http://i.stack.imgur.com/nLkIw.png" alt="enter image description here"></a></p> <p>However it should (and does on a different website) display this: <a href="http://i.stack.imgur.com/j61nl.png" rel="nofollow"><img src="http://i.stack.imgur.com/j61nl.png" alt="enter image description here"></a></p> <p>I've pushed/pulled the entire project to github and the code between each site is identical, yet I'm not seeing why the text input isn't displayed, unless the form needs to be initialized in Django somehow or a quirk to AWS?</p> <p>When comparing the two sites, the one without the text-box does not generate the following:</p> <pre><code>&lt;input class="form-control input-lg" id="id_text" name="text" placeholder="Enter a to-do item" type="text" /&gt; </code></pre> <p>Even though it should, per the <strong>base.html</strong> syntax. </p> <p><em>Updated</em></p> <p>The full <strong>views.py</strong> (per suggested comment) is: </p> <pre><code>from django.shortcuts import redirect, render from lists.models import Item, List from django.core.exceptions import ValidationError from lists.forms import ItemForm from lists.models import Item, List # Create your views here. def home_page(request): return render(request, 'lists/home.html', {'form': ItemForm()}) def new_list(request): form = ItemForm(data=request.POST) if form.is_valid(): list_ = List.objects.create() Item.objects.create(text=request.POST['text'], list=list_) return redirect(list_) else: return render(request, 'lists/home.html', {"form": form}) def view_list(request, list_id): list_ = List.objects.get(id=list_id) form = ItemForm() if request.method == 'POST': form = ItemForm(data=request.POST) if form.is_valid(): Item.objects.create(text=request.POST['text'], list=list_) return redirect(list_) return render(request, 'lists/list.html', {'list': list_, "form": form}) </code></pre>
3
2016-08-23T19:57:41Z
39,126,082
<p>In my experience with Django, there are 2 things you often (always?) need to do to get static files to "refresh" after pushing them to a remote server:</p> <ol> <li>Run <code>./manage.py collectstatic</code> to make sure all your static files are in the right place.</li> <li>While <code>ssh</code>ed into your server run the command <code>sudo reboot now</code> to restart your server (note that this will kick you out of your ssh session, and your server will be unreachable for a moment - usually just a few seconds in my case).</li> </ol> <p>As for step <strong>2</strong> there might be a better way to do this, but in my experience, when I update static files the updated version is not served until I do this, and restarting <code>nginx</code> or the like is not sufficient for the changes to take effect. Note that this will mean that your site, if live, will not be reachable for a few seconds while the server is restarting (which is what makes me think there might be a better way to do it) but for me and my small user base this is not a big issue.</p> <p>From reading some other posts about static files not updating, it seems like it could also be the case that your browser is caching the static files, and that restarting your browser/clearing the cache might do the trick as well, but I have not had a chance to try this yet. </p>
3
2016-08-24T14:27:42Z
[ "python", "django", "forms", "amazon-web-services", "input" ]
python POST with file - convert from RAW data
39,109,698
<p>I have been trying to get this thing to work for days, with no luck. I have worked through the majority of my issues, but I am now at a new error and I don't know why. </p> <p>I have read multiple posts, and even asked a few questions along the way, but now I am completely stumped and it seems that nothing that I search for helps. </p> <p><strong>Here is the scenario:</strong></p> <ul> <li>I need to log into a website (let's call it site_A) and pull a report</li> <li>Next, I need to log into a separate website (site_B) so I can upload that report </li> <li>With site_B, I am required to log in, get a session ID, then use that session ID to upload my file</li> </ul> <p>This all done with API https POST calls... (yes, the API requires POST for everything).</p> <p>site_A works perfectly - I log in and pull the data, which gives me an XML file. This file is then converted into a CSV file, due to site_B only accepting .csv.</p> <p>site_B however, is giving me errors. </p> <p>Using BURP, I am able to intercept the raw data of a test API published by the company. This raw data looks something like this (some data removed):</p> <pre><code>POST /api/import HTTP/1.1 Host: hostURL Accept: application/json, text/javascript, */*; q=0.01 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate, br X-Requested-With: XMLHttpRequest Content-Type: multipart/form-data; boundary=---------------------------28791504620783 Cookie: asc_session_id=sessionToken; SkipBrowserCheck=True; JSESSIONID=sessionStuff; ASP.NET_SessionId=ASPSession Connection: close -----------------------------28791504620783 Content-Disposition: form-data; name="token" sessionToken -----------------------------28791504620783 Content-Disposition: form-data; name="Name" WH -----------------------------28791504620783 Content-Disposition: form-data; name="uploadedfile"; filename="data.csv" Content-Type: application/vnd.ms-excel data,data,data,data data,data,data,data -----------------------------28791504620783-- </code></pre> <p>I have converted this into the following python program:</p> <pre><code># Login - get session token app = requests.Session() loginResponse = app.post(loginURL, headers=headers, data=json.dumps(post_body), verify=False) if loginResponse.status_code != 200: print ('Login attempt failed. Please try again later.') else: userData = json.loads(loginResponse.text) sessionToken = userData["sessionId"] print ('Login successful! Attempting to upload file...') # Now try to upload file uploadURL = 'uploadURL/' headers = { 'token': sessionToken, 'Name': 'WH', 'POST': '/api/import/285/2 HTTP/1.1', 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate, br', 'Connection': 'close' } files = {'data.csv': open('data.csv', newline='')} uploadResponse = app.post(uploadURL, headers=headers, files=files, verify=False) if uploadResponse.status_code != 200: print ('Status report: %i' % uploadResponse.status_code) else: print ('Upload Complete') </code></pre> <p>I have tried to move things around a bit, and place somethings in the body rather than the header. But this also gives me errors either with logging in, or incorrect file type. I have established that I NEED to use the token and the Name in the header. I am not sure if I have to use the "files" variable in python requests (files='whatever')</p> <p>But from this point, I get a 500 error. </p> <p>Can someone please point me in the right direction?</p> <p>I have read the following posts, and while they have helped a little, they aren't helping here: <a href="http://stackoverflow.com/questions/12385179/how-to-send-a-multipart-form-data-with-requests-in-python">Post 1</a>, <a href="http://stackoverflow.com/questions/3508338/what-is-the-boundary-in-multipart-form-data">Post 2</a>, <a href="http://stackoverflow.com/questions/10768522/python-send-post-with-header">Post 3</a></p> <p><strong>NOTE:</strong> I have NOT confirmed that the problem isn't on the server. It may not be with my code at all. But it seems that since the API test code on the website works, it should work in python as well. </p>
0
2016-08-23T19:57:54Z
39,126,162
<p>I am not sure if it's the API, or if I was messing something up, but in this case I had to create a body that looked similar to the RAW data. I was under the impression that "files=" would do this for me, but apparently it did not. </p> <p>I defined a boundary in the multipart/form and then used that to add my sections.</p> <p>The end result looked something like:</p> <pre><code>headers = { 'Content-Type': 'multipart/form-data; boundary=159753', 'asc_xsrf_token': sessionToken, } with open('data.csv', newline='') as csvFile: post_body = ( "\n--159753\n" "Content-Disposition: form-data; name=\"asc_xsrf_token\"\n\n" + sessionToken + "\n--159753\n" "Content-Disposition: form-data; name=\"Name\"\n\n" "WH\n" "--159753\n" "Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"data.csv\"\n" "Content-Type: application/vnd.ms-excel\n\n" + csvFile.read() + "\n--159753--" ) csvFile.close() </code></pre>
0
2016-08-24T14:31:00Z
[ "python", "python-3.x", "csv", "post", "python-requests" ]
Adding New Text to Sklearn TFIDIF Vectorizer (Python)
39,109,743
<p>Is there a function to add to the existing corpus? I've already generated my matrix, I'm looking to periodically add to the table without re-crunching the whole sha-bang</p> <p>e.g;</p> <pre><code>articleList = ['here is some text blah blah','another text object', 'more foo for your bar right now'] tfidf_vectorizer = TfidfVectorizer( max_df=.8, max_features=2000, min_df=.05, preprocessor=prep_text, use_idf=True, tokenizer=tokenize_text ) tfidf_matrix = tfidf_vectorizer.fit_transform(articleList) #### ADDING A NEW ARTICLE TO EXISTING SET? bigger_tfidf_matrix = tfidf_vectorizer.fit_transform(['the last article I wanted to add']) </code></pre>
4
2016-08-23T20:00:40Z
39,114,555
<p>You can access the <code>vocabulary_</code> attribute of your vectoriser directly, and you can access the <code>idf_</code> vector via <code>_tfidf._idf_diag</code>, so it would be possible to monkey-patch something like this:</p> <pre><code>import re from scipy.sparse.dia import dia_matrix def partial_fit(self, X): max_idx = max(self.vocabulary_.values()) for a in X: #update vocabulary_ if self.lowercase: a = a.lower() tokens = re.findall(self.token_pattern, a) for w in tokens: if w not in self.vocabulary_: max_idx += 1 self.vocabulary_[w] = max_idx #update idf_ df = (self.n_docs + self.smooth_idf)/np.exp(self.idf_ - 1) - self.smooth_idf self.n_docs += 1 df.resize(len(self.vocabulary_)) for w in tokens: df[self.vocabulary_[w]] += 1 idf = np.log((self.n_docs + self.smooth_idf)/(df + self.smooth_idf)) + 1 self._tfidf._idf_diag = dia_matrix((idf, 0), shape=(len(idf), len(idf))) self._tfidf._idf_diag print((len(idf), len(idf))) print(vec._tfidf._idf_diag.shape) TfidfVectorizer.partial_fit = partial_fit vec = TfidfVectorizer() vec.fit(articleList) vec.n_docs = len(articleList) vec.partial_fit(['the last text I wanted to add']) vec.transform(['the last text I wanted to add']).toarray() # array([[ 0. , 0. , 0. , 0. , 0. , # 0. , 0. , 0. , 0. , 0. , # 0. , 0. , 0.27448674, 0. , 0.43003652, # 0.43003652, 0.43003652, 0.43003652, 0.43003652]]) </code></pre>
3
2016-08-24T04:41:50Z
[ "python", "scikit-learn", "tf-idf" ]
Which recursive approach is a better design?
39,109,765
<p>Suppose I have a multi-line string which may contain lines consisting of a single file name. I want to print each line in the string, unless the line is a file name (defined here as ending in '.txt'), in which case I want to print each line in that file, unless the line in that file is a file name etc.</p> <p>My initial approach is to use a helper function as follows:</p> <pre><code>def deep_print_helper(file_path, line_sep): with open(file_path) as f: text = f.read() return deep_print(text, line_sep) def deep_print(s, line_sep): lines = s.split(line_sep) for l in lines: if l.endswith('.txt'): deep_print_helper(l, line_sep) else: print(l) </code></pre> <p>But having to pass <code>line_sep</code> to the helper function only to pass it back again seems inelegant. </p> <p>So I tried an approach that uses only one function:</p> <pre><code>def deep_print(line_sep, s='', file_path=''): if file_path: with open(file_path) as f: s = f.read() lines = s.split(line_sep) for l in lines: if l.endswith('.txt'): deep_print(line_sep, file_path=l) else: print(l) </code></pre> <p>This has an implicit required argument (either <code>s</code> or <code>file_path</code> but not both), but since the user of the function will only use one form (<code>s=</code>) it may not be too kludgey. It also seems a little odd from a user's perspective that <code>line_sep</code> is the first argument.</p> <p>Which approach is a better design? Is there another approach I should consider?</p>
0
2016-08-23T20:01:55Z
39,109,840
<p>To avoid passing the <code>line_sep</code> parameter, you can define the helper function inside the recursive function:</p> <pre><code>def deep_print(s, line_sep): def deep_print_helper(file_path): with open(file_path) as f: text = f.read() return deep_print(text, line_sep) lines = s.split(line_sep) for l in lines: if l.endswith('.txt'): deep_print_helper(l) else: print(l) </code></pre>
0
2016-08-23T20:07:14Z
[ "python", "recursion", "design", "arguments", "parameter-passing" ]
Which recursive approach is a better design?
39,109,765
<p>Suppose I have a multi-line string which may contain lines consisting of a single file name. I want to print each line in the string, unless the line is a file name (defined here as ending in '.txt'), in which case I want to print each line in that file, unless the line in that file is a file name etc.</p> <p>My initial approach is to use a helper function as follows:</p> <pre><code>def deep_print_helper(file_path, line_sep): with open(file_path) as f: text = f.read() return deep_print(text, line_sep) def deep_print(s, line_sep): lines = s.split(line_sep) for l in lines: if l.endswith('.txt'): deep_print_helper(l, line_sep) else: print(l) </code></pre> <p>But having to pass <code>line_sep</code> to the helper function only to pass it back again seems inelegant. </p> <p>So I tried an approach that uses only one function:</p> <pre><code>def deep_print(line_sep, s='', file_path=''): if file_path: with open(file_path) as f: s = f.read() lines = s.split(line_sep) for l in lines: if l.endswith('.txt'): deep_print(line_sep, file_path=l) else: print(l) </code></pre> <p>This has an implicit required argument (either <code>s</code> or <code>file_path</code> but not both), but since the user of the function will only use one form (<code>s=</code>) it may not be too kludgey. It also seems a little odd from a user's perspective that <code>line_sep</code> is the first argument.</p> <p>Which approach is a better design? Is there another approach I should consider?</p>
0
2016-08-23T20:01:55Z
39,110,361
<p>Your question should not be related to Pythonic way to achieve this. It is related to the design, independent of language. If you ask me among the two approaches, I'll go with <code>1</code>. But the better way to achieve is via class having your functions within it. In Python you may do it like:</p> <pre><code>class DeepPrint(object): def __init__(self, file_path): DeepPrint._deep_print_helper(file_path) @staticmethod def _deep_print_helper(file_path): with open(file_path) as f: return DeepPrint._deep_print(f) @staticmethod def _deep_print(f): for l in f.readlines(): if l.endswith('.txt'): DeepPrint._deep_print_helper(l) else: print(l) </code></pre>
2
2016-08-23T20:45:53Z
[ "python", "recursion", "design", "arguments", "parameter-passing" ]
Which recursive approach is a better design?
39,109,765
<p>Suppose I have a multi-line string which may contain lines consisting of a single file name. I want to print each line in the string, unless the line is a file name (defined here as ending in '.txt'), in which case I want to print each line in that file, unless the line in that file is a file name etc.</p> <p>My initial approach is to use a helper function as follows:</p> <pre><code>def deep_print_helper(file_path, line_sep): with open(file_path) as f: text = f.read() return deep_print(text, line_sep) def deep_print(s, line_sep): lines = s.split(line_sep) for l in lines: if l.endswith('.txt'): deep_print_helper(l, line_sep) else: print(l) </code></pre> <p>But having to pass <code>line_sep</code> to the helper function only to pass it back again seems inelegant. </p> <p>So I tried an approach that uses only one function:</p> <pre><code>def deep_print(line_sep, s='', file_path=''): if file_path: with open(file_path) as f: s = f.read() lines = s.split(line_sep) for l in lines: if l.endswith('.txt'): deep_print(line_sep, file_path=l) else: print(l) </code></pre> <p>This has an implicit required argument (either <code>s</code> or <code>file_path</code> but not both), but since the user of the function will only use one form (<code>s=</code>) it may not be too kludgey. It also seems a little odd from a user's perspective that <code>line_sep</code> is the first argument.</p> <p>Which approach is a better design? Is there another approach I should consider?</p>
0
2016-08-23T20:01:55Z
39,110,873
<p>Your requirements may not allow for this, but using <a href="https://docs.python.org/3/library/stdtypes.html#str.splitlines" rel="nofollow">str.splitlines</a> would make things a little less complicated. In the same vain, is there a reason why the original file is not opened as part of the recursion (i.e., rather than passing a string into <code>deep_print</code>, you could pass in a file_path)? If those two constraints can be lifted, you could do something like the following:</p> <pre><code>def deep_print(file_path): with open(file_path) as f: s = f.read() for line in [l.strip() for l in s.splitlines()]: if line.endswith('.txt'): deep_print(line) else: print(line) </code></pre>
0
2016-08-23T21:20:53Z
[ "python", "recursion", "design", "arguments", "parameter-passing" ]
Count how often a specific string occurs in a list
39,109,780
<p>I want to pairwise compare several lists in a kind of "bag of words" approach. I have only strings in my lists.<br> Unfortunatelly, I have a bug in my script that I cannot fix.<br> The code works if there are numbers in the lists but as soon as I have strings in the lists it doesn't run anymore. I appreciate your help.</p> <p>I receive following error message:</p> <pre><code>Traceback (most recent call last): File "test.py", line 21, in &lt;module&gt; bow_matrix[0, p] = list_words_ab[p] ValueError: could not convert string to float: 'd' </code></pre> <p>My code:</p> <pre><code>a = ["a", "b", "c", "d"] b = ["b", "c", "d", "e"] p = 0 if len(a) &gt; len(b): max_words = len(a) else: max_words = len(b) list_words_ab = list(set(a) | set(b)) len_bow_matrix = len(list_words_ab) bow_matrix = numpy.zeros(shape = (3, len_bow_matrix)) while p &lt; len_bow_matrix: bow_matrix[0, p] = list_words_ab[p] p = p+1 p = 0 while p &lt; len_bow_matrix: bow_matrix[1, p] = a.count(bow_matrix[0, p]) bow_matrix[2, p] = b.count(bow_matrix[0, p]) p = p+1 </code></pre>
1
2016-08-23T20:03:17Z
39,109,907
<p>By default <code>numpy.zeros</code> makes an empty array of floats, to use strings you need to specify <code>dtype=str</code>:</p> <pre><code>bow_matrix = numpy.zeros(shape = (3, len_bow_matrix),dtype=str) </code></pre>
3
2016-08-23T20:12:01Z
[ "python", "string", "list", "numpy" ]
attribute call speed VS method call Python
39,109,799
<p>Hi I have a simple question but I wasn't able to find the direct comparison I was looking for.</p> <p>My question is:</p> <p>Does calling attribute tend to be faster than calling a method in Python.</p> <p>I have a game and I want to check whether or not a player has discovered a planet. I can either do a call to:</p> <pre><code>def check_exploration(self, planet): return True if self.name in planet.explored_by else False </code></pre> <p>or check the attribute:</p> <pre><code>self.game.player.logbook[planet.name].is_discovered == True </code></pre> <p>The reason I'm asking is because I want to remove one of the two ways of doing it but I'm not sure which way to go.</p> <p>As you might have notice I have a lot of calls when using the attribute, this is because of my game design. Every object links back to my game object. So I can access each object by going to the game object and "back down" into the location of the target object. It is tedious but I found that it is much less messy than jumping around between modules which causes endless circular references.</p> <p>thank you for your advice.</p>
0
2016-08-23T20:04:45Z
39,110,377
<p>I've maked some script that generate 'planetsCount' of planets in galaxy, and checks 'testsCount' times. (code at end of message) Some results:</p> <pre><code>Preparing was done in 0.0 seconds, planetsCount is 10, testsCount is 1000000 First test time is 2.50099992752 sec Second test time is 2.5 sec Preparing was done in 0.0160000324249 seconds, planetsCount is 1000, testsCount is 1000000 First test time is 6.97200012207 sec Second test time is 2.54799985886 sec Preparing was done in 0.406000137329 seconds, planetsCount is 100000, testsCount is 10000 First test time is 6.09399986267 sec Second test time is 0.0310001373291 sec </code></pre> <p>Checking via attribute have stable time. Checking via "item in list" faster on small lists, but very slow on big lists. Code was below </p> <pre><code>import random import base64 import time class Planet(object): def __init__(self, state, name): self.is_discovered = state self.name = base64.b64encode(name) class Galaxy(object): planets = {} explored = [] def __init__(self, planetCount): for planetIndex in xrange(planetCount): planetName = base64.b64encode(str(planetIndex)) is_discovered = random.choice([True, False]) planet = Planet(is_discovered, planetName) self.planets.update({planetName: planet}) if is_discovered: self.explored.append(planetName) startTime = time.time() planetsCount = 10 testsCount = 1000000 galaxy = Galaxy(planetsCount) print "Preparing was done in {} seconds, planetsCount is {}, testsCount is {}".format(time.time() - startTime, planetsCount, testsCount) startTime = time.time() for x in xrange(testsCount): planetName = base64.b64encode(str(random.randint(0, planetsCount - 1))) planetName in galaxy.explored print "First test time is {} sec".format(time.time() - startTime) startTime = time.time() for x in xrange(testsCount): planetName = base64.b64encode(str(random.randint(0, planetsCount - 1))) galaxy.planets[planetName].is_discovered print "Second test time is {} sec".format(time.time() - startTime) </code></pre>
1
2016-08-23T20:46:48Z
[ "python", "class", "optimization", "methods", "attributes" ]
Resolving 2 Python version in Mac OSX
39,109,843
<p>I am running <strong>Mac OS X 10.11.5</strong>. I have two Python versions on my machine:</p> <ol> <li><p><strong>Python 2.7</strong> (Inbuilt python in OSX) and </p></li> <li><p><strong>Python 3.5</strong> (Anaconda version- 4.1.1)</p></li> </ol> <p>The path is set up as shown:</p> <blockquote> <p>$PATH</p> <p>-bash: /Users/userNMS/anaconda/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin: No such file or directory</p> </blockquote> <p>The problem is when I am trying to install few packages like pandas, Theano etc., using anaconda. I get <strong>ERROR: Failure: ImportError</strong> (No Module found)</p> <p>By default the Python Path points to this one i.e (Python version- 2.7)</p> <p><code>&gt; whereis python</code></p> <pre><code>/usr/bin/python </code></pre> <p>But my actual Path which I want to work is Python 3.5 (Anaconda version):</p> <pre><code>&gt; which python /Users/userNMS/anaconda/bin/python </code></pre> <p>The Python site packages path is as follows:</p> <pre><code>/Users/userNMS/anaconda/lib/python3.5/site-packages </code></pre> <p>The packages from site-packages ( say pandas, Theano etc., ) is not getting retrieved from the above path, giving away <strong>Import Error</strong></p> <p>Please help me on this !! Thanks in Advance :)</p>
-1
2016-08-23T20:07:25Z
39,110,921
<p>My approach would be to create a new conda enviornment and install your packages there. This will help you avoid any issues if you still want to use 2.7. Example would be: </p> <p><code>conda create --name foo python=3 pandas Theano</code></p>
0
2016-08-23T21:24:21Z
[ "python", "osx", "python-3.x", "path", "anaconda" ]
Ply example calculator multiple expressions
39,109,851
<p>I've been trying out the Ply <a href="https://github.com/dabeaz/ply/blob/master/example/calc/calc.py" rel="nofollow">example calculator from Github</a>.</p> <p>When I run the calculator, it runs inside of a REPL. How would I use Ply to enable multiple expressions to be evaluated, one after the other.</p> <p>For example, if I enter <code>3+4</code> the REPL does this:</p> <pre><code>calc &gt; 3+4 7 calc &gt; </code></pre> <p>If I enter <code>4+3 6+2</code> the REPL does this:</p> <pre><code>calc &gt; 4+3 6+2 Syntax error at '6' 2 calc &gt; </code></pre> <p>How would I modify the example calculator to enable the REPL to do this:</p> <pre><code>calc &gt; 4+3 6+2 7 8 calc &gt; </code></pre> <p>Do I need to modify the grammar, the parser or both? I've tried modifying the grammar to make it left recursive but it doesn't seem to work.</p>
-1
2016-08-23T20:08:14Z
39,110,837
<p>The sample calculator's grammar allows expressions like <code>- 42</code> (or <code>-(4*8)+7</code>). If such an expression were the second expression on a line, it would create an ambiguity. Is:</p> <pre><code>calc &gt; 4 * 3 -(4*8)+7 </code></pre> <p>one expression or two?</p> <p>One way to make the grammar unambiguous would be to allow multiple expressions on a line separated with a comma. You could do that by just adding <code>'.'</code> to the list of literal tokens, and placing the function</p> <pre><code>def p_line(p): '''line : statement | line ',' statement''' pass </code></pre> <p>as the <em>first</em> parser function (i.e., just before <code>p_statement_assign</code>.</p> <p>With that change:</p> <pre><code>$ python calc.py Generating LALR tables calc &gt; 2+3 5 calc &gt; 2+3,4+6 5 10 calc &gt; 2,3 2 3 calc &gt; a=2,a+7 9 </code></pre>
1
2016-08-23T21:18:18Z
[ "python", "parsing", "lexer", "ply" ]
How do I assign series or sequences to dask dataframe column?
39,109,855
<p>My <strong>dask dataframe</strong> is the follwing:</p> <pre><code>In [65]: df.head() Out[65]: id_orig id_cliente id_cartao inicio_processo fim_processo score \ 0 1.0 1.0 1.0 1.0 1.0 1.0 1 1.0 1.0 1.0 1.0 1.0 1.0 2 1.0 1.0 1.0 1.0 1.0 1.0 3 1.0 1.0 1.0 1.0 1.0 1.0 4 1.0 1.0 1.0 1.0 1.0 1.0 automatico canal aceito motivo_recusa variante 0 1.0 1.0 1.0 1.0 1.0 1 1.0 1.0 1.0 1.0 1.0 2 1.0 1.0 1.0 1.0 1.0 3 1.0 1.0 1.0 1.0 1.0 4 1.0 1.0 1.0 1.0 1.0 </code></pre> <p>Assigning an integer works:</p> <pre><code>In [92]: df = df.assign(id_cliente=999) In [93]: df.head() Out[93]: id_orig id_cliente id_cartao inicio_processo fim_processo score \ 0 1.0 999 1.0 1.0 1.0 1.0 1 1.0 999 1.0 1.0 1.0 1.0 2 1.0 999 1.0 1.0 1.0 1.0 3 1.0 999 1.0 1.0 1.0 1.0 4 1.0 999 1.0 1.0 1.0 1.0 automatico canal aceito motivo_recusa variante 0 1.0 1.0 1.0 1.0 1.0 1 1.0 1.0 1.0 1.0 1.0 2 1.0 1.0 1.0 1.0 1.0 3 1.0 1.0 1.0 1.0 1.0 4 1.0 1.0 1.0 1.0 1.0 </code></pre> <p>However no other method for assigning Series or any other iterable in existing columns works.</p> <p>How can I achieve that?</p>
1
2016-08-23T20:08:32Z
39,109,961
<p>DataFrame.assign accepts any scalar or any <code>dd.Series</code></p> <pre><code>df = df.assign(a=1) # accepts scalars df = df.assign(z=df.x + df.y) # accepts dd.Series objects </code></pre> <p>If you are trying to assign a NumPy array or Python list then it might be your data is small enough to fit in RAM, and so Pandas might be a better fit than Dask.dataframe.</p>
1
2016-08-23T20:15:34Z
[ "python", "dataframe", "dask" ]
How can I make this code quicker?
39,109,877
<p>I have a lot of 750x750 images. I want to take the geometric mean of non-overlapping 5x5 patches from each image, and then for each image, average those geometric means to create one feature per image. I wrote the code below, and it seems to work just fine. But, I know it's not very efficient. Running it on 300 or so images takes around 60 seconds. I have about 3000 images. So, while it works for my purpose, it's not efficient. How can I improve this code?</p> <pre><code>#each sublist of gmeans will contain a list of 22500 geometric means #corresponding to the non-overlapping 5x5 patches for a given image. gmeans = [[],[],[],[],[],[],[],[],[],[],[],[]] #the loop here populates gmeans. for folder in range(len(subfolders)): just_thefilename, colorsourceimages, graycroppedfiles = get_all_images(folder) for items in graycroppedfiles: myarray = misc.imread(items) area_of_big_matrix=750*750 area_of_small_matrix= 5*5 how_many = area_of_big_matrix / area_of_small_matrix n = 0 p = 0 mylist=[] while len(mylist) &lt; how_many: mylist.append(gmean(myarray[n:n+5,p:p+5],None)) n=n+5 if n == 750: p = p+5 n = 0 gmeans[folder].append(my list) #each sublist of mean_of_gmeans will contain just one feature per image, the mean of the geometric means of the 5x5 patches. mean_of_gmeans = [[],[],[],[],[],[],[],[],[],[],[],[]] for folder in range(len(subfolders)): for items in range(len(gmeans[0])): mean_of_gmeans[folder].append((np.mean(gmeans[folder][items],dtype=np.float64))) </code></pre>
-1
2016-08-23T20:09:54Z
39,111,456
<p>I can understand the suggestion to move this to the code review site, but this problem provides a nice example of the power of using vectorized numpy and scipy functions, so I'll give an answer.</p> <p>The function below, cleverly called <code>func</code>, computes the desired value. The key is to reshape the image into a four-dimensional array. Then it can be interpreted as a two-dimensional array of two-dimensional arrays, where the inner arrays are the 5x5 blocks. </p> <p><a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gmean.html" rel="nofollow"><code>scipy.stats.gmean</code></a> can compute the geometric mean over more than one dimension, so that is used to reduce the four-dimensional array to the desired two-dimensional array of geometric means. The return value is the (arithmetic) mean of those geometric means.</p> <pre><code>import numpy as np from scipy.stats import gmean def func(img, blocksize=5): # img must be a 2-d array whose dimensions are divisible by blocksize. if (img.shape[0] % blocksize) != 0 or (img.shape[1] % blocksize) != 0: raise ValueError("blocksize does not divide the shape of img.") # Reshape 'img' into a 4-d array 'blocks', so blocks[i, :, j, :] is # the subarray with shape (blocksize, blocksize). blocks_nrows = img.shape[0] // blocksize blocks_ncols = img.shape[1] // blocksize blocks = img.reshape(blocks_nrows, blocksize, blocks_ncols, blocksize) # Compute the geometric mean over axes 1 and 3 of 'blocks'. This results # in the array of geometric means with size (blocks_nrows, blocks_ncols). gmeans = gmean(blocks, axis=(1, 3), dtype=np.float64) # The return value is the average of 'gmeans'. avg = gmeans.mean() return avg </code></pre> <p>For example, here the function is applied to an array with shape (750, 750).</p> <pre><code>In [358]: np.random.seed(123) In [359]: img = np.random.randint(1, 256, size=(750, 750)).astype(np.uint8) In [360]: func(img) Out[360]: 97.035648309350179 </code></pre> <p>It isn't easy to verify that that is the correct result, so here is a much smaller example:</p> <pre><code>In [365]: np.random.seed(123) In [366]: img = np.random.randint(1, 4, size=(3, 6)) In [367]: img Out[367]: array([[3, 2, 3, 3, 1, 3], [3, 2, 3, 2, 3, 2], [1, 2, 3, 2, 1, 3]]) In [368]: func(img, blocksize=3) Out[368]: 2.1863131342986666 </code></pre> <p>Here is the direct calculation:</p> <pre><code>In [369]: 0.5*(gmean(img[:,:3], axis=None) + gmean(img[:, 3:], axis=None)) Out[369]: 2.1863131342986666 </code></pre>
2
2016-08-23T22:09:38Z
[ "python", "scipy" ]
Run scripts in php
39,109,891
<p>I am running a python script through my php. It works fine on console but returns null when I run it on browser.I even tried writing output to a file, but it doesn't return anything. The php code is:</p> <pre><code>&lt;?php $y = "python Code.py"; $output = shell_exec($y); if($output!=null){ echo $output; } else { echo "No output"; } $myfile = fopen("test.txt", "w") or die("Unable to open file!"); fwrite($myfile, $output); fclose($myfile); ?&gt; </code></pre>
-2
2016-08-23T20:10:48Z
39,109,946
<pre><code>$command = escapeshellcmd('/usr/custom/test.py'); $output = shell_exec($command); echo $output; #!/usr/bin/env python **is this in the first line of you python script?** chmod +x /usr/custom/test.py </code></pre>
0
2016-08-23T20:14:31Z
[ "php", "python", "web" ]
global variable not working python
39,109,901
<p>Hello there developers,</p> <p>i am writing code that takes the user input and initializes a class depending on the input like in the example code below:</p> <pre><code>class X: def __init__(self): return def run(self): print("i am X") def func1(cls): exec("global " + cls.lower()) exec(cls.lower() + " = " + cls + "()") def func2(mode_to_set): exec(mode_to_set.lower() + ".run()") </code></pre> <p>but as I run the code like this:</p> <pre><code>func1('X') func2('X') </code></pre> <p>i keep getting this error:</p> <pre><code>Traceback (most recent call last): File "/Users/noahchalifour/Desktop/test.py", line 16, in &lt;module&gt; func2('X') File "/Users/noahchalifour/Desktop/test.py", line 13, in func2 exec(mode_to_set.lower() + ".run()") File "&lt;string&gt;", line 1, in &lt;module&gt; NameError: name 'x' is not defined </code></pre> <p>Can anyone help me?</p>
-5
2016-08-23T20:11:29Z
39,109,940
<p>It seems like you'd be better off having <code>func2</code> instantiate <em>and</em> run the method:</p> <pre><code>def func2(mode_to_set): globals()[mode_to_set]().run() </code></pre> <p>In this way, you don't have a whole bunch of undesireable cruft floating about in your global namespace and you don't end up doing an untrusted <code>exec</code>. Also, <code>exec</code>ing a <code>global</code> statement inside a function doesn't work (as you've seen)... <code>exec</code> is a way to execute a string as if it were code. It <em>isn't</em> a way to drop dynamically created statements into the current function.</p>
0
2016-08-23T20:13:47Z
[ "python", "class", "python-3.x", "input", "global-variables" ]
global variable not working python
39,109,901
<p>Hello there developers,</p> <p>i am writing code that takes the user input and initializes a class depending on the input like in the example code below:</p> <pre><code>class X: def __init__(self): return def run(self): print("i am X") def func1(cls): exec("global " + cls.lower()) exec(cls.lower() + " = " + cls + "()") def func2(mode_to_set): exec(mode_to_set.lower() + ".run()") </code></pre> <p>but as I run the code like this:</p> <pre><code>func1('X') func2('X') </code></pre> <p>i keep getting this error:</p> <pre><code>Traceback (most recent call last): File "/Users/noahchalifour/Desktop/test.py", line 16, in &lt;module&gt; func2('X') File "/Users/noahchalifour/Desktop/test.py", line 13, in func2 exec(mode_to_set.lower() + ".run()") File "&lt;string&gt;", line 1, in &lt;module&gt; NameError: name 'x' is not defined </code></pre> <p>Can anyone help me?</p>
-5
2016-08-23T20:11:29Z
39,110,057
<p>A much better way to instantiate a class based on user input would be to use a "factory pattern":</p> <p><a href="http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Factory.html" rel="nofollow">http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Factory.html</a></p> <p>Basically you create a class whose whole purpose is to create other classes based on a value. Some people might find that overkill, so you could also use a function that creates classes based on input.</p> <p>Whatever you do though, the way you have it now, running raw, user-input strings using exec, is a bad idea. The best case scenario is that it introduces new bugs that are near-impossible to trace since they aren't actually recorded anywhere. Worst case scenario, a user somehow finds a way to send a string to the function, you've pretty much destroyed whatever security you've hoped for.</p> <p>Basically "exec" should generally be a last resort. There are usually more elegant and secure ways to solve the problem.</p>
1
2016-08-23T20:22:19Z
[ "python", "class", "python-3.x", "input", "global-variables" ]
global variable not working python
39,109,901
<p>Hello there developers,</p> <p>i am writing code that takes the user input and initializes a class depending on the input like in the example code below:</p> <pre><code>class X: def __init__(self): return def run(self): print("i am X") def func1(cls): exec("global " + cls.lower()) exec(cls.lower() + " = " + cls + "()") def func2(mode_to_set): exec(mode_to_set.lower() + ".run()") </code></pre> <p>but as I run the code like this:</p> <pre><code>func1('X') func2('X') </code></pre> <p>i keep getting this error:</p> <pre><code>Traceback (most recent call last): File "/Users/noahchalifour/Desktop/test.py", line 16, in &lt;module&gt; func2('X') File "/Users/noahchalifour/Desktop/test.py", line 13, in func2 exec(mode_to_set.lower() + ".run()") File "&lt;string&gt;", line 1, in &lt;module&gt; NameError: name 'x' is not defined </code></pre> <p>Can anyone help me?</p>
-5
2016-08-23T20:11:29Z
39,110,126
<p>Dictionaries, dictionaries, dictionaries. Your program should maintain control over what code gets executed, rather than letting the user construct new code dynamically.</p> <pre><code>classes = {'X': X} instances = {} def func1(cls): var = cls.lower() instances[var] = classes[cls]() def func2(mode_to_set): instances[mode_to_set.lower()].run() func1('X') func2('X') </code></pre> <p>The only difference is that you don't have a global variable named <code>x</code>; you have a global dictionary with a key <code>x</code> that refers to your instance.</p>
0
2016-08-23T20:28:06Z
[ "python", "class", "python-3.x", "input", "global-variables" ]
Validate WTForm before submitting
39,109,933
<p>Is it possible to validate a WTForm field after leaving the field but before submit? For example, after entering a username, that field is validated to see if its available and shows a checkmark, before the user clicks submit.</p>
0
2016-08-23T20:13:28Z
39,110,440
<p>When the field is changed, perform a check and change the text in an adjacent node. Some things can be validated directly in the browser. To validate against data on the server, send a request with JavaScript to a view that checks the data and returns a JSON response.</p> <pre><code>@app.route('/username-exists', methods=['POST']) def username_exists(): username = request.form['username'] exists = check_if_user_exists(username) return jsonify(exists=exists) </code></pre> <pre class="lang-html prettyprint-override"><code>&lt;input id='username' name='username'&gt; &lt;p id='username-status'&gt;&lt;/p&gt; </code></pre> <pre class="lang-javascript prettyprint-override"><code>var username_input = $('#username'); var username_status = $('#username-status'); $('#username').on('focusout', function () { $.post( "{{ url_for('username_exists') }}", { username: username_input.val() }, function (data) { username_status.text(data.exists ? '✔️' : '🙅'); } ); }); </code></pre> <p>This example uses jQuery, but the concept is not specific to any library.</p> <p>Alternatively, post the entire form to a separate view that only validates the fields, then <code>return jsonify(form.errors)</code> and do something with them in the browser. The code would be essentially the same as above, with some extra logic to put the error messages next to the correct fields.</p> <p>Remember to still validate the data when the form is submitted, as requests can be made outside the browser with other</p>
0
2016-08-23T20:50:15Z
[ "python", "flask", "jinja2", "flask-wtforms" ]
Convert '%m/%d/%Y' string index into pandas datetime index
39,109,971
<p>MY index is datetime string with format <code>'%m/%d/%Y' ('09/26/2007')</code> </p> <p>When I try to convert the index into datetime index using <code>pd.to_datetime</code> function <code>pd.to_datetime(df.index)</code>, I got error message <code>OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 1-01-01 00:00:00</code></p> <p>It looks like pandas can't detect the right string format, how I can convert the index into datetime index?</p> <p>Thanks</p>
3
2016-08-23T20:16:23Z
39,110,086
<p>The the look of the error message, it appears you may have the string <code>'1/1/0001'</code> in your index. For example,</p> <pre><code>df = pd.DataFrame([1,2], index=['09/26/2007', '1/1/0001']) pd.to_datetime(df.index) </code></pre> <p>raises </p> <pre><code>OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 1-01-01 00:00:00 </code></pre> <p>This error arises because the DatetimeIndex uses an array of NumPy <code>datetime64[ns]</code>s which can not represent the date 0001-01-01. The <code>datetime64[ns]</code> dtype can only represent <a href="http://docs.scipy.org/doc/numpy/reference/arrays.datetime.html#datetime-units" rel="nofollow">dates in the range <code>[1678 AD, 2262 AD]</code></a>.</p> <p>There is a <a href="https://github.com/pydata/pandas/issues/7307" rel="nofollow">pandas github issue</a> discussing this limitation. </p> <p>For now, the recommended solution is to use a PeriodIndex instead of a DatetimeIndex:</p> <pre><code>df = pd.DataFrame([1,2], index=['09/26/2007', '1/1/0001']) df.index = pd.PeriodIndex(df.index, freq='D') </code></pre> <p>yields</p> <pre><code> 0 2007-09-26 1 1-01-01 2 </code></pre>
3
2016-08-23T20:25:18Z
[ "python", "pandas" ]
Finding random pairs in a large directory
39,110,012
<p>I have ~5M csv files stored in ~100.000 folders. Each folder contains roughly the same number of files and there's always an even number of files in a folder. I need to find the paths to all these files and load them into a list in a somewhat strange order for a statistical modeling project.</p> <p>In particular, I need the following to be upheld:</p> <ul> <li>Uniqueness: Each file must only be in the list once</li> <li>Pairs: Each file must be next to another file from the same folder (it can be next to two if due to randomness)</li> <li>Randomness: The probability of any two files that are not "paired" being next to each other should be the same (i.e. it wouldn't work just to iterative over all files)</li> </ul> <p>I've created an example below.</p> <p><strong>Files</strong></p> <pre><code>Folder_1 - File_A - File_B - File_C - File_D Folder_2 - File_E - File_F - File_G - File_H </code></pre> <p><strong>Good Result (randomized, but upholds the rule of pairs)</strong></p> <pre><code>paths = ['Folder_1/File_A', 'Folder_1/File_D', 'Folder_2/File_G', 'Folder_2/File_F', 'Folder_2/File_E', 'Folder_2/File_H', 'Folder_1/File_C', 'Folder_1/File_B'] </code></pre> <p>A simple approach might be something like "Pick a random folder, pick a random file in that folder and a random pair in the folder. Save these picks in a list to avoid getting picked again. Repeat.". However, that would take far too long. Can you recommend a good strategy for creating this list? The randomness requirement can be relaxed a bit if needed.</p>
3
2016-08-23T20:19:08Z
39,110,408
<p>One way to ensure that everything's random is to use <code>random.shuffle</code>, which shuffles a list inplace. That way you can simply pair each item with its neighbor, safe in the knowledge that the pairing is random. To achieve a result like your example you can then shuffle and flatten the resulting list of pairs. Here's an example:</p> <pre><code>from random import shuffle # generate some sample directory names ls = [[]] * 5 i = 0 while i &lt; len(ls): ls[i] = [str(i) + chr(j) for j in range(97,101)] i += 1 # shuffle files within each directory pairs = [] for l in ls: shuffle(l) pairs += list(zip(l[1::2], l[::2])) # shuffle and flatten the list of pairs shuffle(pairs) flat = [item for sublist in pairs for item in sublist] print(flat) </code></pre>
1
2016-08-23T20:48:10Z
[ "python", "performance", "design", "io" ]
Finding random pairs in a large directory
39,110,012
<p>I have ~5M csv files stored in ~100.000 folders. Each folder contains roughly the same number of files and there's always an even number of files in a folder. I need to find the paths to all these files and load them into a list in a somewhat strange order for a statistical modeling project.</p> <p>In particular, I need the following to be upheld:</p> <ul> <li>Uniqueness: Each file must only be in the list once</li> <li>Pairs: Each file must be next to another file from the same folder (it can be next to two if due to randomness)</li> <li>Randomness: The probability of any two files that are not "paired" being next to each other should be the same (i.e. it wouldn't work just to iterative over all files)</li> </ul> <p>I've created an example below.</p> <p><strong>Files</strong></p> <pre><code>Folder_1 - File_A - File_B - File_C - File_D Folder_2 - File_E - File_F - File_G - File_H </code></pre> <p><strong>Good Result (randomized, but upholds the rule of pairs)</strong></p> <pre><code>paths = ['Folder_1/File_A', 'Folder_1/File_D', 'Folder_2/File_G', 'Folder_2/File_F', 'Folder_2/File_E', 'Folder_2/File_H', 'Folder_1/File_C', 'Folder_1/File_B'] </code></pre> <p>A simple approach might be something like "Pick a random folder, pick a random file in that folder and a random pair in the folder. Save these picks in a list to avoid getting picked again. Repeat.". However, that would take far too long. Can you recommend a good strategy for creating this list? The randomness requirement can be relaxed a bit if needed.</p>
3
2016-08-23T20:19:08Z
39,111,100
<p>The best strategy would be to divide and conquer with some help from threading. You want to get the file names loaded into memory as quick as possible for fastest completion.</p> <p>First step would be to create a queue for the folder names and another for the list of the files in each folder. Something like:</p> <pre><code>folders = queue.Queue() files = queue.Queue() </code></pre> <p>A Queue is a lot like a list, only it can be shared safely between different threads. Using threads to tackle multiple folders at once will speed up processing time.</p> <p>Create a function that will get the paths to each folders, then store each path "folders" queue.</p> <pre><code>folderPaths = getFolderPaths() for path in folderPaths: folders.put(path) </code></pre> <p>Eventually you will end up with a queue with all the folder paths in it (e.g. ["Folder A", "Folder B", ...])</p> <p>Make a worker function for the threads that will go through all the files in a folder and store the names of each in a list. The general idea is:</p> <pre><code>def threadJob(): while True: folderPath = folders.get() if folderPath is None: break fileNames = getFilesInFolder(folderPath) files.put(fileNames) </code></pre> <p>Here "getFilesInFolder()" is a function that takes in a path argument and returns a list of all the files in that folder.</p> <p>By the time all the threads are finished, "files" should be full of lists of files for each folder. Now you need to empty the queue into a regular list.</p> <pre><code>fileList = [] file = files.get() while file not None: fileList.append(file) file = files.get() </code></pre> <p>Now you have a list of lists. Shuffle each of the lists to randomize the file order:</p> <pre><code>for files in fileList: random.shuffle(files) </code></pre> <p>Now you can create the final list (statList) and pop off pairs of files from randomly chosen sub-lists until all the files have been appended:</p> <pre><code>statList = [] while len(finalFileList &gt; 0): index = random.randrange(len(fileList)) if len(fileList[index]) == 0: fileList.pop(index) else: statList.append(fileList.pop()) statList.append(fileList.pop()) </code></pre> <p>No guarantees that this will be speedy, but it's the fastest method I can think of. </p> <p>More information about queues and threading if interested:</p> <p><a href="https://docs.python.org/3/library/queue.html" rel="nofollow">https://docs.python.org/3/library/queue.html</a></p> <p><a href="http://www.tutorialspoint.com/python3/python_multithreading.htm" rel="nofollow">http://www.tutorialspoint.com/python3/python_multithreading.htm</a></p>
1
2016-08-23T21:39:30Z
[ "python", "performance", "design", "io" ]
ImportError: No module named tflearn
39,110,075
<p>Above Error comes only when i am trying to run the script : <code>"rgarg:pytutorial raghav$ python tflearn11.py"</code></p> <p>It working fine in Rodeo IDE, also if I put <code>"import tflearn "</code> in command line python interpreter it works fine (even I typed full script in command line , it worked fine w/o import issue) .</p> <p>My packages are in same location as i have given in my bash (Mac OS El Captain)</p> <pre><code>export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python2.7/site-packages </code></pre> <p>A similar problem i found <a href="http://stackoverflow.com/a/38810996/5947775">Link</a> but not getting how can i remove path(0) when running from python interpreter.</p> <p>Thanks </p>
0
2016-08-23T20:23:48Z
39,129,241
<p>As @Two-Bit mentioned i used virtualenvs <a href="http://docs.python-guide.org/en/latest/dev/virtualenvs/" rel="nofollow">Link</a>.</p> <p>But please make sure use below for installation of virtualenvs</p> <p><em>$ sudo easy_install virtualenvs</em></p> <p>instead of pip install virtualenvs.</p>
1
2016-08-24T17:06:59Z
[ "python", "bash", "python-import" ]
CSS Selector not parsing anything in Python Webscrape
39,110,188
<p>I am trying to webscrape this website: <a href="http://canoeracing.org.uk/marathon/results/burton2016.htm" rel="nofollow">http://canoeracing.org.uk/marathon/results/burton2016.htm</a> using Python and CSS selectors, but my CSS selectors which I'm using aren't finding anything to parse in the DOM tree. I've managed to scrape it using the webscraping tool Kimono, which uses CSS selectors too, so I know they're correct. Code is below and the CSS selector I'm using is for the second column in each of the tables in the website - <code>body &gt; table &gt; tbody &gt; tr &gt; td:nth-child(2)</code>. I've taken the CSS scraping code from <a href="http://www.ilab.rutgers.edu/~vverna/scrape-the-web-using-css-selectors-in-python.html" rel="nofollow">http://www.ilab.rutgers.edu/~vverna/scrape-the-web-using-css-selectors-in-python.html</a>.</p> <pre><code>import lxml.html from lxml.cssselect import CSSSelector # get some html import requests r = requests.get('http://canoeracing.org.uk/marathon/results/burton2016.htm') # build the DOM Tree tree = lxml.html.fromstring(r.text) # construct a CSS Selector sel = CSSSelector('body &gt; table &gt; tbody &gt; tr &gt; td:nth-child(2)') # Apply the selector to the DOM tree. results = sel(tree) print results # print the HTML for the first result. match = results[0] print lxml.html.tostring(match) # get the href attribute of the first result print match.get('href') # print the text of the first result. print match.text # get the text out of all the results data = [result.text for result in results] </code></pre>
3
2016-08-23T20:33:00Z
39,110,390
<p>There is no tbody, that is added by the browser, you want <em><code>body &gt; table &gt; tr &gt; td:nth-child(2)</code></em>:</p> <p>With that change:</p> <pre><code>In [1]: import lxml.html In [2]: import requests In [3]: r = requests.get('http://canoeracing.org.uk/marathon/results/burton2016.htm') In [4]: tree = lxml.html.fromstring(r.text) In [5]: results = tree.cssselect('body &gt; table &gt; tr &gt; td:nth-child(2)') In [6]: print results [&lt;Element td at 0x7f1cb1334100&gt;, &lt;Element td at 0x7f1cb1334260&gt;, &lt;Element td at 0x7f1cb13342b8&gt;, &lt;Element td at 0x7f1cb1334470&gt;, &lt;Element td at 0x7f1cb1334368&gt;, &lt;Element td at 0x7f1cb13344c8&gt;, &lt;Element td at 0x7f1cb1334578&gt;, &lt;Element td at 0x7f1cb1334628&gt;, &lt;Element td at 0x7f1cb1334aa0&gt;, &lt;Element td at 0x7f1cb1334788&gt;, &lt;Element td at 0x7f1cb13347e0&gt;, &lt;Element td at 0x7f1cb1334940&gt;, &lt;Element td at 0x7f1cb1334a48&gt;, &lt;Element td at 0x7f1cb1334af8&gt;, &lt;Element td at 0x7f1cb1328310&gt;, &lt;Element td at 0x7f1cb1328788&gt;, &lt;Element td at 0x7f1cb1328158&gt;, &lt;Element td at 0x7f1cb1328260&gt;, &lt;Element td at 0x7f1cb1328470&gt;, &lt;Element td at 0x7f1cb1328578&gt;, &lt;Element td at 0x7f1cb1328628&gt;, &lt;Element td at 0x7f1cb1328aa0&gt;, &lt;Element td at 0x7f1cb13288e8&gt;, &lt;Element td at 0x7f1cb1328940&gt;, &lt;Element td at 0x7f1cb1328a48&gt;, &lt;Element td at 0x7f1cb1328e10&gt;, &lt;Element td at 0x7f1cb1328c58&gt;, &lt;Element td at 0x7f1cb1328c00&gt;, &lt;Element td at 0x7f1cb1328db8&gt;, &lt;Element td at 0x7f1cb1328ec0&gt;, &lt;Element td at 0x7f1cb1328f70&gt;, &lt;Element td at 0x7f1cb1328af8&gt;, &lt;Element td at 0x7f1cb13282b8&gt;, &lt;Element td at 0x7f1cb1328cb0&gt;, &lt;Element td at 0x7f1cb132e100&gt;, &lt;Element td at 0x7f1cb132e0a8&gt;, &lt;Element td at 0x7f1cb132e368&gt;, &lt;Element td at 0x7f1cb132e680&gt;, &lt;Element td at 0x7f1cb1343730&gt;, &lt;Element td at 0x7f1cb1343680&gt;, &lt;Element td at 0x7f1cb1343628&gt;, &lt;Element td at 0x7f1cb13435d0&gt;, &lt;Element td at 0x7f1cb1343578&gt;, &lt;Element td at 0x7f1cb13434c8&gt;, &lt;Element td at 0x7f1cb1343470&gt;, &lt;Element td at 0x7f1cb13436d8&gt;, &lt;Element td at 0x7f1cb1343368&gt;, &lt;Element td at 0x7f1cb13432b8&gt;, &lt;Element td at 0x7f1cb1343158&gt;, &lt;Element td at 0x7f1cb13430a8&gt;, &lt;Element td at 0x7f1cb13433c0&gt;, &lt;Element td at 0x7f1cb1343788&gt;, &lt;Element td at 0x7f1cb13437e0&gt;, &lt;Element td at 0x7f1cb1343838&gt;, &lt;Element td at 0x7f1cb1343890&gt;, &lt;Element td at 0x7f1cb13438e8&gt;, &lt;Element td at 0x7f1cb1343940&gt;, &lt;Element td at 0x7f1cb1343998&gt;, &lt;Element td at 0x7f1cb13439f0&gt;, &lt;Element td at 0x7f1cb1343a48&gt;, &lt;Element td at 0x7f1cb1343aa0&gt;, &lt;Element td at 0x7f1cb1343af8&gt;, &lt;Element td at 0x7f1cb1343b50&gt;, &lt;Element td at 0x7f1cb1343ba8&gt;, &lt;Element td at 0x7f1cb1343c00&gt;, &lt;Element td at 0x7f1cb1343c58&gt;, &lt;Element td at 0x7f1cb1343cb0&gt;, &lt;Element td at 0x7f1cb1343d08&gt;, &lt;Element td at 0x7f1cb1343d60&gt;, &lt;Element td at 0x7f1cb1343db8&gt;, &lt;Element td at 0x7f1cb1343e10&gt;, &lt;Element td at 0x7f1cb1343e68&gt;, &lt;Element td at 0x7f1cb1343ec0&gt;, &lt;Element td at 0x7f1cb1343f18&gt;, &lt;Element td at 0x7f1cb1343f70&gt;, &lt;Element td at 0x7f1cb1343fc8&gt;, &lt;Element td at 0x7f1cb134b050&gt;, &lt;Element td at 0x7f1cb134b0a8&gt;, &lt;Element td at 0x7f1cb134b100&gt;, &lt;Element td at 0x7f1cb134b158&gt;, &lt;Element td at 0x7f1cb134b1b0&gt;, &lt;Element td at 0x7f1cb134b208&gt;, &lt;Element td at 0x7f1cb134b260&gt;, &lt;Element td at 0x7f1cb134b2b8&gt;, &lt;Element td at 0x7f1cb134b310&gt;, &lt;Element td at 0x7f1cb134b368&gt;, &lt;Element td at 0x7f1cb134b3c0&gt;, &lt;Element td at 0x7f1cb134b418&gt;, &lt;Element td at 0x7f1cb134b470&gt;, &lt;Element td at 0x7f1cb134b4c8&gt;, &lt;Element td at 0x7f1cb134b520&gt;, &lt;Element td at 0x7f1cb134b578&gt;, &lt;Element td at 0x7f1cb134b5d0&gt;, &lt;Element td at 0x7f1cb134b628&gt;, &lt;Element td at 0x7f1cb134b680&gt;, &lt;Element td at 0x7f1cb134b6d8&gt;, &lt;Element td at 0x7f1cb134b730&gt;, &lt;Element td at 0x7f1cb134b788&gt;, &lt;Element td at 0x7f1cb134b7e0&gt;, &lt;Element td at 0x7f1cb134b838&gt;, &lt;Element td at 0x7f1cb134b890&gt;, &lt;Element td at 0x7f1cb134b8e8&gt;, &lt;Element td at 0x7f1cb134b940&gt;, &lt;Element td at 0x7f1cb134b998&gt;, &lt;Element td at 0x7f1cb134b9f0&gt;, &lt;Element td at 0x7f1cb134ba48&gt;, &lt;Element td at 0x7f1cb134baa0&gt;, &lt;Element td at 0x7f1cb134baf8&gt;, &lt;Element td at 0x7f1cb134bb50&gt;, &lt;Element td at 0x7f1cb134bba8&gt;, &lt;Element td at 0x7f1cb134bc00&gt;, &lt;Element td at 0x7f1cb134bc58&gt;, &lt;Element td at 0x7f1cb134bcb0&gt;, &lt;Element td at 0x7f1cb134bd08&gt;, &lt;Element td at 0x7f1cb134bd60&gt;, &lt;Element td at 0x7f1cb134bdb8&gt;, &lt;Element td at 0x7f1cb134be10&gt;, &lt;Element td at 0x7f1cb134be68&gt;, &lt;Element td at 0x7f1cb134bec0&gt;, &lt;Element td at 0x7f1cb134bf18&gt;, &lt;Element td at 0x7f1cb134bf70&gt;, &lt;Element td at 0x7f1cb134bfc8&gt;, &lt;Element td at 0x7f1cb134c050&gt;, &lt;Element td at 0x7f1cb134c0a8&gt;, &lt;Element td at 0x7f1cb134c100&gt;, &lt;Element td at 0x7f1cb134c158&gt;, &lt;Element td at 0x7f1cb134c1b0&gt;, &lt;Element td at 0x7f1cb134c208&gt;, &lt;Element td at 0x7f1cb134c260&gt;, &lt;Element td at 0x7f1cb134c2b8&gt;, &lt;Element td at 0x7f1cb134c310&gt;, &lt;Element td at 0x7f1cb134c368&gt;, &lt;Element td at 0x7f1cb134c3c0&gt;, &lt;Element td at 0x7f1cb134c418&gt;, &lt;Element td at 0x7f1cb134c470&gt;, &lt;Element td at 0x7f1cb134c4c8&gt;, &lt;Element td at 0x7f1cb134c520&gt;, &lt;Element td at 0x7f1cb134c578&gt;, &lt;Element td at 0x7f1cb134c5d0&gt;, &lt;Element td at 0x7f1cb134c628&gt;, &lt;Element td at 0x7f1cb134c680&gt;, &lt;Element td at 0x7f1cb134c6d8&gt;, &lt;Element td at 0x7f1cb134c730&gt;, &lt;Element td at 0x7f1cb134c788&gt;, &lt;Element td at 0x7f1cb134c7e0&gt;, &lt;Element td at 0x7f1cb134c838&gt;, &lt;Element td at 0x7f1cb134c890&gt;, &lt;Element td at 0x7f1cb134c8e8&gt;, &lt;Element td at 0x7f1cb134c940&gt;, &lt;Element td at 0x7f1cb134c998&gt;, &lt;Element td at 0x7f1cb134c9f0&gt;, &lt;Element td at 0x7f1cb134ca48&gt;, &lt;Element td at 0x7f1cb134caa0&gt;, &lt;Element td at 0x7f1cb134caf8&gt;, &lt;Element td at 0x7f1cb134cb50&gt;, &lt;Element td at 0x7f1cb134cba8&gt;, &lt;Element td at 0x7f1cb134cc00&gt;, &lt;Element td at 0x7f1cb134cc58&gt;, &lt;Element td at 0x7f1cb134ccb0&gt;, &lt;Element td at 0x7f1cb134cd08&gt;, &lt;Element td at 0x7f1cb134cd60&gt;, &lt;Element td at 0x7f1cb134cdb8&gt;, &lt;Element td at 0x7f1cb134ce10&gt;, &lt;Element td at 0x7f1cb134ce68&gt;, &lt;Element td at 0x7f1cb134cec0&gt;, &lt;Element td at 0x7f1cb134cf18&gt;, &lt;Element td at 0x7f1cb134cf70&gt;, &lt;Element td at 0x7f1cb134cfc8&gt;, &lt;Element td at 0x7f1cb134d050&gt;, &lt;Element td at 0x7f1cb134d0a8&gt;, &lt;Element td at 0x7f1cb134d100&gt;] In [7]: match = results[0] In [8]: print lxml.html.tostring(match) &lt;td&gt;CONNOR PETERS&lt;/td&gt; In [9]: print match.get('href') None In [10]: print match.text CONNOR PETERS In [11]: data = [result.text for result in results] In [12]: print(data) ['CONNOR PETERS', 'NICKY CRESSER', 'MARK WILKES', 'MATT PARKES', 'ALEX ABRAHAM', 'JOE FITZPATRICK', 'RICHARD ROGERS', 'DANNY BEAZLEY', 'JAMES SMYTHE', 'JAMIE CHRISTIE', 'JAMES HINVES', 'DAVID BELBIN', 'TOM DIAPER', 'PETER DEBOER', 'MARTIN RINVOLUCRI', 'LEE HOWSON', 'DAMON GRIMSEY', 'MATTHEW OLIVER', 'JOSHUA BEST', 'CHRIS CARTER', 'DUNCAN OUGHTON', 'HOWARD BLACKMAN', 'PATRICK MONGAN', 'JAMES DORAN', 'MICHAEL FITZSIMONS', 'SHUNA NEAVE', 'GUY PETERS', 'WILLIAM DOUGHTY', 'MICK NADAL', 'BILL LAWRENSON', 'MARK WEVILL', 'JOHN ASTBURY', 'JACOB HUBNER', 'SEB SHAW', 'TONY BATES', 'PETER MIETUS', 'CHRISTOPHER SKELLERN', 'GEORGE RANDALL', 'NEVILLE COLLEY', 'COLIN CHUDLEY', 'DAVE RICKETTS', 'LEWIS SMITH', 'ALASKA SIMPSON', 'DAVID CUDDINGTON', 'BEN BEDDARD', 'DAVID GLOVER', 'DEBORAH QUITTENTON', 'NEIL ORME', 'KASIA CHMIEL', 'RICHARD HUMPHREYS', 'MARCIN KRUCZYNSKI', 'IMRE KUCSKA', 'JOSHUA SMITH', 'DAVE HADLEY', 'LAURENCE FOWKES', 'AMELIA DINGLEY', 'MICHELLE BUTLER', 'LYNDA OUGHTON', 'LUCY GUEST', 'GARETH FERGUSSON', 'TOMASZ CHLIPALA', 'TONY SPENCER', 'KATIE BROOKES', 'HAYDYN COOKE-BAYLEY', 'DAVID WALTERS', 'STEPHEN KITSON', 'BEN ASTON', "ANGUS O'CONNOR", 'KEVIN LACK', 'MOLLY LEVER', 'MAX BEDDARD', 'CALLUM ADAIR', 'EMMA WILKINSON', 'DAVE CIANCHI', 'STEPHEN HALL', 'NAT KEMP', 'ANDREW LEGGATT', 'JACK ROUNSLEY', 'KATE MCMANUS', 'RICHARD MONGAN', 'LYNETTE SHAHMORADIAN', 'ALAN WILLIAMS', 'SIMON LEWIS', 'OLIVER 1 COOK', 'SARAH MILLEST', 'ALEXANDRA FARMER', 'RAY SIMMONS', 'CATHERINE CATON', 'KARL ZAREMBA', 'PHIL ROBERTS', 'CLAIRE COOPER', 'EMMA SMITHSON', 'HELEN RANDALL', 'SAM MARSH', 'LIAM NELSON', 'KATH NADAL', 'ADAM PRICE', 'AMANDA MYLETT', 'SAM DARLING', 'JULIA MIETUS', 'LINDSEY LACK', 'STEVE SAUNDERS', 'PHILL BURGESS', 'PENNY GLOVER', 'PETER KILLEY', 'EDWARD SHAW', 'JESS PROCTOR', 'JULIANNE WALTERS', 'JESSICA STEWART', 'KERRY CHRISTIE', 'ANDY COOK', 'LIAM HALL', 'KEITH NEWBOLD', 'JANET HICKMAN', 'ELLIOT COOPS', 'TEIFION ROGERS', 'JUSTIN ROE', 'ABBIE FISHER', 'EMMA CHRISTIE', 'ZARA MONTGOMERY', 'TESNI MILES', 'LEWIS ANDREWS', 'CONOR SIMMONS', 'IGGY ROGERS', 'MATTHEW COOK', 'ARCHIE LEVER', 'CHARLIE MAYNE', 'MCKENZIE MILES', 'LIBBY MAYNE', 'ROSS ORME', 'BRUCE BLACKMAN', 'STEPHEN BALL', 'SIMON RICKETTS', 'ALISON CHMIEL', 'PATRICK ALLINSON', 'PASCAL BAUER', 'MICHEAL WALTERS', 'JONATHAN CAVE', 'ANDREW NEVITT', 'MICK MORAN', 'STANI CHMIEL', 'MICHAEL FUDGER', 'LEE CHAMP', 'ROB KIRBY', 'KAY SPENCER', 'JANE MILLAR', 'THOMAS GILL', 'LOUISE CLIVE', 'BECKY FARMER', 'DAVID TARBUCK', 'OSCAR HUISSOON', 'ELLIE LAWLEY', 'ALLISON MILES', 'NICOLA RUDGE', 'EMMA CHRISTIE', 'LEWIS ANDREWS', '01:27:25.46', '01:34:13.50', '01:07:30.70', '01:12:06.66', '01:16:39.34', '00:33:38.65', '00:35:38.33', '00:37:39.45', '00:39:39.12', '01:02:58.03', '01:07:30.70', '01:12:06.66', '00:32:38.65', '00:35:38.33', '00:37:39.45'] </code></pre> <p>There is also no <em>href</em> attribute inside the first or i think any td so not sure what that is supposed to get.</p>
1
2016-08-23T20:47:26Z
[ "python", "css", "web-scraping" ]
What Happens when a Generator Runs out of Values to Yield?
39,110,210
<p>To illustrate the question, suppose we have this simple generator:</p> <pre><code>def firstn(n): num = 0 while num &lt; n: yield num num += 1 for i in firstn(10): print i </code></pre> <p>This will print the digits 0 through 9. But what if we have:</p> <pre><code>def firstn(n): num = 0 while num &lt; 5 &lt; n: yield num num += 1 for i in firstn(10): print i </code></pre> <p>(The change is in the <code>while</code> statement.) Then it prints only digits 0 through 4. Once <code>num &gt;= 5</code>, then the generator no longer yields values.</p> <p>What I'm curious about is what goes on under the hood: I used <a href="http://www.pythontutor.com/visualize.html#mode=display" rel="nofollow">PythonTutor</a> to step through the code, and the impression I'm under is that once the <code>while</code> statement is no longer <code>True</code>, the function implicitly returns <code>None</code>, which the <code>for</code> loop somehow detects, and then also breaks. I used the <code>next</code> built-in to inspect this more closely:</p> <pre><code>&gt;&gt;&gt; def firstn(n): ... num = 0 ... while num &lt; 5 &lt; n: ... yield num ... num += 1 ... &gt;&gt;&gt; &gt;&gt;&gt; mygen = firstn(100) &gt;&gt;&gt; next(mygen) 0 &gt;&gt;&gt; next(mygen) 1 &gt;&gt;&gt; next(mygen) 2 &gt;&gt;&gt; next(mygen) 3 &gt;&gt;&gt; next(mygen) 4 &gt;&gt;&gt; next(mygen) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; StopIteration </code></pre> <p>Which supports my theory. My big question: how does <code>StopIteration</code> work, and does this mean that calling a generator with a large value can be equivalent to calling it with its smallest terminating value? In our example, <code>for i in firstn(5)</code> and <code>for i in firstn(9999999999999)</code> should be equivalent, right?</p>
0
2016-08-23T20:34:35Z
39,110,344
<p>This isn't very mysterious. When a generator runs out of values to yield, it raises a <code>StopIteration</code> exception. You just need to understand how a for-loop works in Python. Essentially, it is equivalent to the following code:</p> <pre><code>iterator = iter(collection) while True: try: x = next(iterator) # do something except StopIteration as e: break </code></pre> <p>The above is equivalent to:</p> <pre><code>for x in collection: # do something </code></pre>
1
2016-08-23T20:44:36Z
[ "python", "generator", "yield-keyword" ]
Storing a score in Python
39,110,212
<p>So far I have made a short game in which you have to guess the area of the shape in question. Only the triangle works so far and the correct answer is B for testing.</p> <p>I am trying to store the user's progress by putting it into a text file, but when I call a function to update the score, it overwrites the file so the score is removed! How can I get around this, and if I can't is there another way of doing this, because I want the user to be able to go from level to level?</p> <p>My code:</p> <pre><code>User_Points = '0' def LoginScreen(): print("Welcome to Area Trainer") print("Please enter the username for your account") global user_name user_name = str(input()) save = open(user_name + '.txt', 'w') save.write(str(User_Points)) PasswordCheck= True while PasswordCheck: user_password = input("Type in your password: ") if len(user_password) &lt; 8: print("Your password must be 8 characters long") elif not any(i.isdigit() for i in user_password): print("You need a number in your password") elif not any(i.isupper() for i in user_password): print("You need a capital letter in your password") elif not any(i.islower() for i in user_password): print("You need a lowercase letter in your password") else: PasswordCheck = False def MenuTriangle(): global User_Points User_Points = '' print('''Here is a triangle with a height of 12 cm and a width of 29 cm /\ | *Not to scale. / \ | / \ | 12 cm / \ | &lt;-------&gt; 29 cm You must find out the area and select the correct answer from these options''') print('''A) 175 B) 174 C) 2000 D) 199 ''') user_input = input().upper() if user_input == "A": print("I'm sorry this is incorrect, but you still have a chance to get 1 point!") MenuTriangle2() elif user_input == "C": print("I'm sorry this is incorrect, but you still have a chance to get 1 point!") MenuTriangle2() elif user_input == "D": print("I'm sorry this is incorrect, but you still have a chance to get 1 point!") MenuTriangle2() elif user_input == "B": print("Congratulations! You got it right; someone's a smart cookie. Here have two points!") reading = open(user_name + '.txt') score = reading.read() score = score + '2' print("Your score is", score) save = open(user_name + '.txt', 'a') save.write(str(score)) MenuStart() def MenuStart(): print("Welcome to the mathematical area game!") print("In this game you will be required to calculate the area of multiple shapes.") print("To do this you must know how to calculate the area of different shapes with increasing difficulty.") print('''Please select a shape you want to play, A) Triangle B) Square C) Circle''') user_input = input().upper() if user_input == "A": print("You have chosen to calculate the area of a triangle!") MenuTriangle() elif user_input == "B": print("You have chosen to calculate the area of a square!") MenuSquare() elif user_input == "C": print("You have chosen the calculate the area of a circle!") MenuCircle() else: print("Oops! I didn't understand that &gt;:") MenuStart() LoginScreen() MenuStart() </code></pre>
-1
2016-08-23T20:34:38Z
39,110,738
<p>It's not saving because you never close the file. This is why most people agree <code>with open(filename, 'w+')</code> is best practice.</p> <p>Try using the below format for <code>LoginScreen()</code></p> <pre><code>def LoginScreen(): print("Welcome to Area Trainer") print("Please enter the username for your account") global user_name user_name = str(input()) with open(user_name + '.txt', 'w') as f: f.write(str(User_Points)) # Remaining code below here... </code></pre> <p>I also noticed at the end of <code>MenuTriangle()</code> you try to add strings together rather than adding integers. You'll want to convert the string you read from file to an integer before increasing the score. You also don't provide which mode of opening the file you need. It does default to <code>'r'</code> but it's better to be explicit.</p> <pre><code>def MenuTriangle(): # if: ... # elif: ... # elif: ... elif user_input == "B": print("Congratulations! You got it right, someone's a smart cookie. Here have two points!") with open(user_name + '.txt', 'r') as f: score = f.read() new_score = int(score) + 2 print("Your score is {}".format(new_score)) with open(user_name + '.txt', 'w+') as w: # Wouldn't you want to overwrite this rather than continue appending numbers? w.write(str(new_score)) MenuStart() # Call this outside of your with statements so that the file closes </code></pre>
1
2016-08-23T21:12:14Z
[ "python", "python-3.x" ]
Storing a score in Python
39,110,212
<p>So far I have made a short game in which you have to guess the area of the shape in question. Only the triangle works so far and the correct answer is B for testing.</p> <p>I am trying to store the user's progress by putting it into a text file, but when I call a function to update the score, it overwrites the file so the score is removed! How can I get around this, and if I can't is there another way of doing this, because I want the user to be able to go from level to level?</p> <p>My code:</p> <pre><code>User_Points = '0' def LoginScreen(): print("Welcome to Area Trainer") print("Please enter the username for your account") global user_name user_name = str(input()) save = open(user_name + '.txt', 'w') save.write(str(User_Points)) PasswordCheck= True while PasswordCheck: user_password = input("Type in your password: ") if len(user_password) &lt; 8: print("Your password must be 8 characters long") elif not any(i.isdigit() for i in user_password): print("You need a number in your password") elif not any(i.isupper() for i in user_password): print("You need a capital letter in your password") elif not any(i.islower() for i in user_password): print("You need a lowercase letter in your password") else: PasswordCheck = False def MenuTriangle(): global User_Points User_Points = '' print('''Here is a triangle with a height of 12 cm and a width of 29 cm /\ | *Not to scale. / \ | / \ | 12 cm / \ | &lt;-------&gt; 29 cm You must find out the area and select the correct answer from these options''') print('''A) 175 B) 174 C) 2000 D) 199 ''') user_input = input().upper() if user_input == "A": print("I'm sorry this is incorrect, but you still have a chance to get 1 point!") MenuTriangle2() elif user_input == "C": print("I'm sorry this is incorrect, but you still have a chance to get 1 point!") MenuTriangle2() elif user_input == "D": print("I'm sorry this is incorrect, but you still have a chance to get 1 point!") MenuTriangle2() elif user_input == "B": print("Congratulations! You got it right; someone's a smart cookie. Here have two points!") reading = open(user_name + '.txt') score = reading.read() score = score + '2' print("Your score is", score) save = open(user_name + '.txt', 'a') save.write(str(score)) MenuStart() def MenuStart(): print("Welcome to the mathematical area game!") print("In this game you will be required to calculate the area of multiple shapes.") print("To do this you must know how to calculate the area of different shapes with increasing difficulty.") print('''Please select a shape you want to play, A) Triangle B) Square C) Circle''') user_input = input().upper() if user_input == "A": print("You have chosen to calculate the area of a triangle!") MenuTriangle() elif user_input == "B": print("You have chosen to calculate the area of a square!") MenuSquare() elif user_input == "C": print("You have chosen the calculate the area of a circle!") MenuCircle() else: print("Oops! I didn't understand that &gt;:") MenuStart() LoginScreen() MenuStart() </code></pre>
-1
2016-08-23T20:34:38Z
39,110,758
<p>The addition that you are doing here</p> <pre><code>score = reading.read() score = score + '2' </code></pre> <p>is of <code>type str</code> so you keep getting values like <code>024</code>, change the value in the file to <code>int</code> first.</p> <pre><code> score = int(score) + '2' </code></pre> <p>Also open the file in <code>w+</code> mode</p> <pre><code>save = open(user_name + '.txt', 'w+') </code></pre> <p>or use <code>with</code> as it's been recommended by others.</p>
2
2016-08-23T21:13:40Z
[ "python", "python-3.x" ]
python Combining items in a list of lists based on contents
39,110,235
<p>I have a list of lists which will have a different amount of lists each time depending on other conditions. Each of the list contains 4 items. I want to say if elements 1,2,3 of two of the inner lists are the same, add element 0 and delete the duplicates. The list looks something like this:</p> <pre><code> [ [4, 'blue', 'round', None], [6, 'blue', 'round', None], [8, 'red', 'round', None], [10, 'red', 'round', None], [8, 'red', 'square', None], ] </code></pre> <p>I think making a new list might help but am not sure. I need the end product to be:</p> <pre><code>[ [10, 'blue', 'round', None], [18, 'red', 'round', None], [8, 'red', 'square', None], ] </code></pre> <p>The amount of different lists inside the list will always be different. Any help with this would be greatly appreciated.</p>
0
2016-08-23T20:36:42Z
39,110,354
<p>You may try the <code>groupby</code> from itertools with the original list sorted by the last three elements of the sublist:</p> <pre><code>lst=[[4,"blue","round","none"], [6,"blue","round","none"], [8,"red","round","none"], [10,"red","round","none"], [8,"red","square","none"]] from itertools import groupby [[sum(v[0] for v in g)] + k for k, g in groupby(sorted(lst, key = lambda x: x[1:4]), key = lambda x: x[1:4])] # [[10, 'blue', 'round', 'none'], # [18, 'red', 'round', 'none'], # [8, 'red', 'square', 'none']] </code></pre>
2
2016-08-23T20:45:17Z
[ "python", "list" ]
python Combining items in a list of lists based on contents
39,110,235
<p>I have a list of lists which will have a different amount of lists each time depending on other conditions. Each of the list contains 4 items. I want to say if elements 1,2,3 of two of the inner lists are the same, add element 0 and delete the duplicates. The list looks something like this:</p> <pre><code> [ [4, 'blue', 'round', None], [6, 'blue', 'round', None], [8, 'red', 'round', None], [10, 'red', 'round', None], [8, 'red', 'square', None], ] </code></pre> <p>I think making a new list might help but am not sure. I need the end product to be:</p> <pre><code>[ [10, 'blue', 'round', None], [18, 'red', 'round', None], [8, 'red', 'square', None], ] </code></pre> <p>The amount of different lists inside the list will always be different. Any help with this would be greatly appreciated.</p>
0
2016-08-23T20:36:42Z
39,110,435
<p>You can use a counter to accumulate the results:</p> <pre><code>&gt;&gt;&gt; in_data = [[4,'blue','round',None], [6,'blue','round',None], [8,'red','round',None], [10,'red','round',None], [8,'red','square',None]] &gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; counter = Counter() &gt;&gt;&gt; for count, *keys in in_data: ... counter[tuple(keys)] += count ... &gt;&gt;&gt; counter Counter({('blue', 'round', None): 10, ('red', 'round', None): 18, ('red', 'square', None): 8}) </code></pre> <p>It's easy to transform back into the output format you asked for:</p> <pre><code>&gt;&gt;&gt; [[count, *keys] for keys, count in counter.items()] [[8, 'red', 'square', None], [18, 'red', 'round', None], [10, 'blue', 'round', None]] </code></pre> <p>I agree with the commentators that you could use a better data structure than a list here. </p> <p>My example uses <a class='doc-link' href="http://stackoverflow.com/documentation/python/809/compatibility-between-python-3-and-python-2/4554/extended-list-set-and-dictionary-unpacking#t=201608232242301225754">some python3.5 specific syntax</a>, if you're on an older version you should prefer the answer from <a href="http://stackoverflow.com/a/39110438/674039">2ps</a> which implements the same idea. </p>
2
2016-08-23T20:49:53Z
[ "python", "list" ]
python Combining items in a list of lists based on contents
39,110,235
<p>I have a list of lists which will have a different amount of lists each time depending on other conditions. Each of the list contains 4 items. I want to say if elements 1,2,3 of two of the inner lists are the same, add element 0 and delete the duplicates. The list looks something like this:</p> <pre><code> [ [4, 'blue', 'round', None], [6, 'blue', 'round', None], [8, 'red', 'round', None], [10, 'red', 'round', None], [8, 'red', 'square', None], ] </code></pre> <p>I think making a new list might help but am not sure. I need the end product to be:</p> <pre><code>[ [10, 'blue', 'round', None], [18, 'red', 'round', None], [8, 'red', 'square', None], ] </code></pre> <p>The amount of different lists inside the list will always be different. Any help with this would be greatly appreciated.</p>
0
2016-08-23T20:36:42Z
39,110,438
<p>Roughly speaking, all you are doing is associating element 0 with a tuple defined as the last three elements of any given list. Luckily, it's perfectly okay for a tuple to be a key of a dictionary!</p> <pre><code>from collections import OrderedDict color_data = [[4,'blue','round','none'], [6,'blue','round','none'], [8,'red','round','none'], [10,'red','round','none'], [8,'red','square','none']] data = OrderedDict() for x in color_data: key = tuple(x[1:]) value = data.setdefault(key, 0) + x[0] data[key] = value color_data = [ [ value] + list(key) for key, value in data.items() ] </code></pre>
1
2016-08-23T20:50:06Z
[ "python", "list" ]
python Combining items in a list of lists based on contents
39,110,235
<p>I have a list of lists which will have a different amount of lists each time depending on other conditions. Each of the list contains 4 items. I want to say if elements 1,2,3 of two of the inner lists are the same, add element 0 and delete the duplicates. The list looks something like this:</p> <pre><code> [ [4, 'blue', 'round', None], [6, 'blue', 'round', None], [8, 'red', 'round', None], [10, 'red', 'round', None], [8, 'red', 'square', None], ] </code></pre> <p>I think making a new list might help but am not sure. I need the end product to be:</p> <pre><code>[ [10, 'blue', 'round', None], [18, 'red', 'round', None], [8, 'red', 'square', None], ] </code></pre> <p>The amount of different lists inside the list will always be different. Any help with this would be greatly appreciated.</p>
0
2016-08-23T20:36:42Z
39,110,457
<p>if you feel like use pandas, you could do:</p> <pre><code>import pandas data = [ [4,"blue","round","none"], [6,"blue","round","none"], [8,"red","round","none"], [10,"red","round","none"], [8,"red","square","none"] ] summary = ( pandas.DataFrame(data, columns=['q', 'color', 'shape', 'other']) .groupby(by=['color', 'shape'], as_index=False) .agg({'q': 'sum', 'other': 'first'}) .reset_index(drop=True) ) print(summary) color shape q other 0 blue round 10 none 1 red round 18 none 2 red square 8 none </code></pre>
0
2016-08-23T20:51:28Z
[ "python", "list" ]
python Combining items in a list of lists based on contents
39,110,235
<p>I have a list of lists which will have a different amount of lists each time depending on other conditions. Each of the list contains 4 items. I want to say if elements 1,2,3 of two of the inner lists are the same, add element 0 and delete the duplicates. The list looks something like this:</p> <pre><code> [ [4, 'blue', 'round', None], [6, 'blue', 'round', None], [8, 'red', 'round', None], [10, 'red', 'round', None], [8, 'red', 'square', None], ] </code></pre> <p>I think making a new list might help but am not sure. I need the end product to be:</p> <pre><code>[ [10, 'blue', 'round', None], [18, 'red', 'round', None], [8, 'red', 'square', None], ] </code></pre> <p>The amount of different lists inside the list will always be different. Any help with this would be greatly appreciated.</p>
0
2016-08-23T20:36:42Z
39,110,580
<p>So there's a <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow">collections.Counter</a> class that makes incrementing over a list of keys very convenient.</p> <pre><code>import collections list_ = [ [4, 'blue', 'round', None], [6, 'blue', 'round', None], [8, 'red', 'round', None], [10, 'red', 'round', None], [8, 'red', 'square', None], ] counts = collections.Counter() for i in list_: count = i[0] key = tuple(i[1:4]) # ex. ('blue', 'round', None) --&gt; 6 counts[key] += count for i in counts.items(): print(i) </code></pre> <p>Output:</p> <pre><code>(('blue', 'round', None), 10) (('red', 'round', None), 18) (('red', 'square', None), 8) </code></pre> <p>You can easily tweak this formatting to be exactly what you want.</p> <p>Notes</p> <ul> <li>The use of <code>+=</code> without initializing the key first is not a typo. Because a <code>Counter</code> instance returns a value of 0 for undefined keys automatically.</li> <li>I used <code>list_</code> over the variable name <code>list</code> in the original problem, because naming it that masks <a href="https://docs.python.org/2/library/functions.html#list" rel="nofollow">the list(...) built-in</a>.</li> <li>The insertion uses a tuple because it's <a href="https://docs.python.org/2/glossary.html#term-hashable" rel="nofollow">hashable</a> to be a dictionary key, while a list is not since the list is mutable.</li> <li>Works in Python 2 / 3.</li> </ul>
0
2016-08-23T20:59:14Z
[ "python", "list" ]
python Combining items in a list of lists based on contents
39,110,235
<p>I have a list of lists which will have a different amount of lists each time depending on other conditions. Each of the list contains 4 items. I want to say if elements 1,2,3 of two of the inner lists are the same, add element 0 and delete the duplicates. The list looks something like this:</p> <pre><code> [ [4, 'blue', 'round', None], [6, 'blue', 'round', None], [8, 'red', 'round', None], [10, 'red', 'round', None], [8, 'red', 'square', None], ] </code></pre> <p>I think making a new list might help but am not sure. I need the end product to be:</p> <pre><code>[ [10, 'blue', 'round', None], [18, 'red', 'round', None], [8, 'red', 'square', None], ] </code></pre> <p>The amount of different lists inside the list will always be different. Any help with this would be greatly appreciated.</p>
0
2016-08-23T20:36:42Z
39,110,602
<p>If <code>a</code> is your list of lists, then:</p> <pre><code>import collections d = collections.defaultdict(int) for row in a: key = tuple(row[1:]) d[key] += row[0] e = [list((val,) + key) for key, val in d.items()] </code></pre> <p>Output:</p> <pre><code>In [14]: e Out[14]: [[18, 'red', 'round', None], [8, 'red', 'square', None], [10, 'blue', 'round', None]] </code></pre>
0
2016-08-23T21:00:56Z
[ "python", "list" ]
3d scatter plot with color in matplotlib
39,110,336
<p>I am using scatter 3d plot in matplotlib in python for plotting following data,</p> <pre><code> x y z b2 3.28912855713 4.64604863545 3.95526335139 1.0 3.31252670518 4.65385917898 3.96834118896 1.0 </code></pre> <p>When the plot is 2d,</p> <pre><code>fig = plt.figure() ax = fig.add_subplot(111) line =ax.scatter(x,y,c=b2,s=500,marker='*',edgecolors='none') cb = plt.colorbar(line) </code></pre> <p>It generates following image, which is perfectly right. <a href="http://i.stack.imgur.com/atfUK.png" rel="nofollow"><img src="http://i.stack.imgur.com/atfUK.png" alt="enter image description here"></a></p> <p>Now, I want to plot 3d points, for which the code is:</p> <pre><code>fig = plt.figure() ax = fig.add_subplot(111,projection='3d') line = ax.scatter(x,y,z,c=b2,s=1500,marker='*',edgecolors='none',depthshade=0) cb = plt.colorbar(line) </code></pre> <p>And I get following plot, which is not right since the color should be green like previous case (b2 doesn't change). <a href="http://i.stack.imgur.com/f9NiY.png" rel="nofollow"><img src="http://i.stack.imgur.com/f9NiY.png" alt="enter image description here"></a></p> <p>Am I missing something ?</p>
0
2016-08-23T20:43:58Z
39,122,150
<p>Probably not. I don't know what version of Matplotlib you are using but at some point a bug existed with this issue that apparently still has repercussions for the version I'm using today, i.e. 1.5.1 (check <a href="http://stackoverflow.com/questions/8971309/matplotlib-3d-scatter-color-lost-after-redraw">this question</a> for more on this).</p> <p>Adapting @Yann solution to your problem should resolve that issue. I tested it in my computer and the result is the following:</p> <pre><code>import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D x = [3.28912855713, 3.31252670518] y = [4.64604863545, 4.65385917898] z = [3.95526335139, 3.96834118896] b2 = [1, 1] fig = plt.figure() ax = fig.add_subplot(111,projection='3d') line = ax.scatter(x, y ,z , c=b2, s=1500, marker='*', edgecolors='none', depthshade=0) cb = plt.colorbar(line) def forceUpdate(event): global line line.changed() fig.canvas.mpl_connect('draw_event', forceUpdate) plt.show() </code></pre> <p>Images of the plot at entry and after a rotation are:</p> <p><a href="http://i.stack.imgur.com/kaXsE.png" rel="nofollow"><img src="http://i.stack.imgur.com/kaXsE.png" alt="3D matplotlib scatterplot with color"></a></p> <p><a href="http://i.stack.imgur.com/CbLY0.png" rel="nofollow"><img src="http://i.stack.imgur.com/CbLY0.png" alt="3D matplotlib scatterplot with color after rotation"></a></p>
1
2016-08-24T11:30:55Z
[ "python", "matplotlib", "plot", "colors", "3d" ]
Object permissions with read only access for anonymous users in Django Rest Framework
39,110,380
<p><strong>The problem</strong></p> <p>I am using Django REST Framework - and so far I have been using the <code>DjangoObjectPermissions</code> permissions class. I use <code>django-rules</code> to determine which users have permissions for objects.</p> <p>However, this permissions class seems to deny read access to anonymous users.</p> <p>I need to find the best way to allow read-only access to all users (authenticated or not). For additions, modifications and deletions - the object permissions should be applied as normal.</p> <p>What is the best approach to solving this problem? Django does not seem to provide a <code>can_view</code> permission by default.</p> <p>Perhaps this will involve manually adding a <code>can_view</code> permission for each model. Or maybe it's better to somehow implement a <code>DjangoObjectPermissionsOrAnonReadOnly</code> permissions class?</p>
0
2016-08-23T20:46:58Z
39,113,738
<pre><code>from rest_framework import permissions </code></pre> <p>and Just give </p> <pre><code> permission_classes = [permissions.IsAuthenticatedOrReadOnly, YourPermissionshere, ] </code></pre> <p>in your viewset. That will do the job. if not authenticated, Anonymous users will be getting a read-only permission </p> <p>you can control when the permissions are checked and not checked by handling the function</p> <pre><code>self.check_object_permissions(self.request, obj) </code></pre>
0
2016-08-24T03:02:35Z
[ "python", "django", "permissions", "django-rest-framework", "anonymous-users" ]
Object permissions with read only access for anonymous users in Django Rest Framework
39,110,380
<p><strong>The problem</strong></p> <p>I am using Django REST Framework - and so far I have been using the <code>DjangoObjectPermissions</code> permissions class. I use <code>django-rules</code> to determine which users have permissions for objects.</p> <p>However, this permissions class seems to deny read access to anonymous users.</p> <p>I need to find the best way to allow read-only access to all users (authenticated or not). For additions, modifications and deletions - the object permissions should be applied as normal.</p> <p>What is the best approach to solving this problem? Django does not seem to provide a <code>can_view</code> permission by default.</p> <p>Perhaps this will involve manually adding a <code>can_view</code> permission for each model. Or maybe it's better to somehow implement a <code>DjangoObjectPermissionsOrAnonReadOnly</code> permissions class?</p>
0
2016-08-23T20:46:58Z
39,319,138
<p>The fix was actually really simple. It's possible to create a custom permissions class extending <code>DjangoObjectPermissions</code>, and to override the <code>authenticated_users_only</code> variable.</p> <pre><code>class DjangoObjectPermissionsOrAnonReadOnly(DjangoObjectPermissions): authenticated_users_only = False </code></pre>
0
2016-09-04T16:34:29Z
[ "python", "django", "permissions", "django-rest-framework", "anonymous-users" ]
NameError: global name 'workflow' is not defined - Odoo v9
39,110,424
<p>I have this code:</p> <pre><code>def compute_refund(self, cr, uid, ids, mode='refund', context=None): """@param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param ids: the account invoice refund’s ID or list of IDs """ inv_obj = self.pool.get('account.invoice') reconcile_obj = self.pool.get('account.move.reconcile') account_m_line_obj = self.pool.get('account.move.line') mod_obj = self.pool.get('ir.model.data') act_obj = self.pool.get('ir.actions.act_window') wf_service = workflow inv_tax_obj = self.pool.get('account.invoice.tax') inv_line_obj = self.pool.get('account.invoice.line') res_users_obj = self.pool.get('res.users') if context is None: context = {} </code></pre> <p>Every time I try to execute this it throws <code>NameError: global name 'workflow' is not defined</code></p> <p>This is the complete traceback:</p> <pre><code>Traceback (most recent call last): File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/http.py", line 646, in _handle_exception return super(JsonRequest, self)._handle_exception(exception) File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/http.py", line 683, in dispatch result = self._call_function(**self.params) File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/http.py", line 319, in _call_function return checked_call(self.db, *args, **kwargs) File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/service/model.py", line 118, in wrapper return f(dbname, *args, **kwargs) File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/http.py", line 312, in checked_call result = self.endpoint(*a, **kw) File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/http.py", line 962, in __call__ return self.method(*args, **kw) File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/http.py", line 512, in response_wrap response = f(*args, **kw) File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/addons/web/controllers/main.py", line 901, in call_button action = self._call_kw(model, method, args, {}) File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/addons/web/controllers/main.py", line 889, in _call_kw return getattr(request.registry.get(model), method)(request.cr, request.uid, *args, **kwargs) File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/api.py", line 250, in wrapper return old_api(self, *args, **kwargs) File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/addons/debit_credit_note/wizard/account_invoice_refund.py", line 279, in invoice_refund return self.compute_refund(cr, uid, ids, data_refund, context=context) File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/api.py", line 250, in wrapper return old_api(self, *args, **kwargs) File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/addons/debit_credit_note/wizard/account_invoice_refund.py", line 116, in compute_refund wf_service = workflow NameError: global name 'workflow' is not defined </code></pre> <p>I've found that the function should have <code>self</code> as parameter, but it does have it, I'm quite puzzled at this, I don't know if this is about the way I'm calling <code>workflow</code></p> <p>Any ideas?</p> <p>Thanks in advance!</p> <p><strong>EDIT</strong></p> <p>This is all the function:</p> <pre><code>def compute_refund(self, cr, uid, ids, mode='refund', context=None): """@param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param ids: the account invoice refund’s ID or list of IDs """ inv_obj = self.pool.get('account.invoice') reconcile_obj = self.pool.get('account.move.reconcile') account_m_line_obj = self.pool.get('account.move.line') mod_obj = self.pool.get('ir.model.data') act_obj = self.pool.get('ir.actions.act_window') wf_service = workflow inv_tax_obj = self.pool.get('account.invoice.tax') inv_line_obj = self.pool.get('account.invoice.line') res_users_obj = self.pool.get('res.users') if context is None: context = {} for form in self.browse(cr, uid, ids, context=context): created_inv = [] date = False period = False description = False company = res_users_obj.browse( cr, uid, uid, context=context).company_id journal_id = form.journal_id.id for inv in inv_obj.browse(cr, uid, context.get('active_ids'), context=context): if inv.state in ['draft', 'proforma2', 'cancel']: raise osv.except_osv(_('Error!'), _( 'Cannot %s draft/proforma/cancel invoice.') % (mode)) if inv.reconciled and mode in ('cancel', 'modify'): raise osv.except_osv(_('Error!'), _( 'Cannot %s invoice which is already reconciled, ' 'invoice should be unreconciled first. You can only ' 'refund this invoice.') % (mode)) if form.period.id: period = form.period.id else: period = inv.period_id and inv.period_id.id or False if not journal_id: journal_id = inv.journal_id.id if form.date: date = form.date if not form.period.id: cr.execute("select name from ir_model_fields \ where model = 'account.period' \ and name = 'company_id'") result_query = cr.fetchone() if result_query: cr.execute("""select p.id from account_fiscalyear y , account_period p where y.id=p.fiscalyear_id \ and date(%s) between p.date_start AND p.date_stop and y.company_id = %s limit 1""", (date, company.id,)) else: cr.execute("""SELECT id from account_period where date(%s) between date_start AND date_stop \ limit 1 """, (date,)) res = cr.fetchone() if res: period = res[0] else: date = inv.date_invoice if form.description: description = form.description else: description = inv.name if not period: raise osv.except_osv(_('Insufficient Data!'), _('No period found on the invoice.')) refund_id = inv_obj.refund(cr, uid, [ inv.id], date, period, description, journal_id, context=context) refund = inv_obj.browse(cr, uid, refund_id[0], context=context) # Add parent invoice inv_obj.write(cr, uid, [refund.id], {'date_due': date, 'check_total': inv.check_total, 'parent_id': inv.id}) inv_obj.button_compute(cr, uid, refund_id) created_inv.append(refund_id[0]) if mode in ('cancel', 'modify'): movelines = inv.move_id.line_id to_reconcile_ids = {} for line in movelines: if line.account_id.id == inv.account_id.id: to_reconcile_ids[line.account_id.id] = [line.id] if type(line.reconcile_id) != osv.orm.browse_null: reconcile_obj.unlink(cr, uid, line.reconcile_id.id) wf_service.trg_validate(uid, 'account.invoice', refund.id, 'invoice_open', cr) refund = inv_obj.browse( cr, uid, refund_id[0], context=context) for tmpline in refund.move_id.line_id: if tmpline.account_id.id == inv.account_id.id: to_reconcile_ids[ tmpline.account_id.id].append(tmpline.id) for account in to_reconcile_ids: account_m_line_obj.reconcile( cr, uid, to_reconcile_ids[account], writeoff_period_id=period, writeoff_journal_id=inv.journal_id.id, writeoff_acc_id=inv.account_id.id ) if mode == 'modify': invoice = inv_obj.read(cr, uid, [inv.id], ['name', 'type', 'number', 'reference', 'comment', 'date_due', 'partner_id', 'partner_insite', 'partner_contact', 'partner_ref', 'payment_term', 'account_id', 'currency_id', 'invoice_line', 'tax_line', 'journal_id', 'period_id'], context=context) invoice = invoice[0] del invoice['id'] invoice_lines = inv_line_obj.browse( cr, uid, invoice['invoice_line'], context=context) invoice_lines = inv_obj._refund_cleanup_lines( cr, uid, invoice_lines, context=context) tax_lines = inv_tax_obj.browse( cr, uid, invoice['tax_line'], context=context) tax_lines = inv_obj._refund_cleanup_lines( cr, uid, tax_lines, context=context) invoice.update({ 'type': inv.type, 'date_invoice': date, 'state': 'draft', 'number': False, 'invoice_line': invoice_lines, 'tax_line': tax_lines, 'period_id': period, 'name': description, 'origin': self._get_orig(cr, uid, inv, context={}), }) for field in ( 'partner_id', 'account_id', 'currency_id', 'payment_term', 'journal_id'): invoice[field] = invoice[ field] and invoice[field][0] inv_id = inv_obj.create(cr, uid, invoice, {}) if inv.payment_term.id: data = inv_obj.onchange_payment_term_date_invoice( cr, uid, [inv_id], inv.payment_term.id, date) if 'value' in data and data['value']: inv_obj.write(cr, uid, [inv_id], data['value']) created_inv.append(inv_id) xml_id = (inv.type == 'out_refund') and 'action_invoice_tree1' or \ (inv.type == 'in_refund') and 'action_invoice_tree2' or \ (inv.type == 'out_invoice') and 'action_invoice_tree3' or \ (inv.type == 'in_invoice') and 'action_invoice_tree4' result = mod_obj.get_object_reference(cr, uid, 'account', xml_id) id = result and result[1] or False result = act_obj.read(cr, uid, id, context=context) invoice_domain = eval(result['domain']) invoice_domain.append(('id', 'in', created_inv)) result['domain'] = invoice_domain return result </code></pre>
1
2016-08-23T20:49:22Z
39,115,050
<p>You can try with following code.</p> <p>Replace code </p> <pre><code>wf_service.trg_validate(uid, 'account.invoice',refund.id, 'invoice_open', cr) </code></pre> <p>with </p> <pre><code>refund.signal_workflow('invoice_open') </code></pre> <p><strong>EDIT</strong></p> <p>Remove following line</p> <pre><code>wf_service = workflow </code></pre>
1
2016-08-24T05:25:37Z
[ "python", "openerp", "odoo-9" ]
Sphinx: list local sections first, linked pages last in TOC
39,110,429
<p>Let's say I have the following <code>index.rst</code>:</p> <pre><code>Some global topic ===================== .. toctree:: :glob: nested/index Global topic introduction ------------------------ </code></pre> <p>And <code>nested/index.rst</code>:</p> <pre><code>Some sub-topic ============== </code></pre> <p>I want TOC to be like:</p> <ul> <li>Some global topic <ul> <li>Global topic introduction</li> <li>Some sub-topic</li> </ul></li> </ul> <p>Instead, I get the following:</p> <ul> <li>Some global topic <ul> <li>Some sub-topic</li> <li>Global topic introduction</li> </ul></li> </ul> <p>How to make local sections appear first, and linked pages after them?</p>
1
2016-08-23T20:49:28Z
39,118,622
<p>It's not a perfect solution, but how about</p> <pre><code>.. contents:: :local: .. toctree:: :glob: nested/index </code></pre> <p>That will give you: </p> <ul> <li>Some global topic <ul> <li>Global topic introduction</li> </ul></li> <li>Some sub-topic</li> </ul>
0
2016-08-24T08:50:26Z
[ "python", "python-sphinx", "restructuredtext" ]
Pad dates within groups with pandas
39,110,470
<p>I'm trying to pad dates within a group ('type') and backfill the new rows. I've seen examples using reindex, but I'm not sure how to pad these dates while maintaining the groups.</p> <p>in:</p> <pre><code>type date value a 2016-01-01 1 a 2016-01-04 3 b 2016-01-10 4 b 2016-01-13 7 </code></pre> <p>desired out:</p> <pre><code>type date value a 2016-01-01 1 a 2016-01-02 3 a 2016-01-03 3 a 2016-01-04 3 b 2016-01-10 4 b 2016-01-11 7 b 2016-01-12 7 b 2016-01-13 7 </code></pre>
3
2016-08-23T20:52:08Z
39,110,574
<pre><code>df.set_index('date').groupby('type', as_index=False).resample('d').bfill().reset_index().drop('level_0', axis=1) Out: date type value 0 2016-01-01 a 1 1 2016-01-02 a 3 2 2016-01-03 a 3 3 2016-01-04 a 3 4 2016-01-10 b 4 5 2016-01-11 b 7 6 2016-01-12 b 7 7 2016-01-13 b 7 </code></pre>
5
2016-08-23T20:58:50Z
[ "python", "pandas" ]
Python Pandas Groupby Resetting Values Based on Index
39,110,476
<p>So I have a dataframe that contains some wrong information that I want to fix:</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[4]: LastYear id FirstYear 1 1990 2007 2 1999 2006 2002 2006 3 1992 2000 1994 2000 1996 2000 </code></pre> <p>id refers to a business, and this DataFrame is a small example slice of a much larger one that shows how a business moves. Each record is a unique location, and I want to capture the first and last year it was there. The current 'LastYear' is accurate for businesses with only one record, and accurate for the latest record of businesses for more than one record. What the df should look like at the end is this:</p> <pre><code> LastYear id FirstYear 1 1990 2007 2 1999 2002 2002 2006 3 1992 1994 1994 1996 1996 2000 </code></pre> <p>And what I did to get it there was super clunky:</p> <pre><code>multirecord = df.groupby(level=0).filter(lambda x: len(x) &gt; 1) multirecord_grouped = multirecord.groupby(level=0) ls = [] for _, group in multirecord_grouped: levels = group.index.get_level_values(level=1).tolist() + [group['LastYear'].iloc[-1]] ls += levels[1:] multirecord['LastYear'] = pd.Series(ls, index=multirecord.index.copy()) final_joined = pd.concat([df.groupby(level=0).filter(lambda x: len(x) == 1),multirecord]).sort_index() </code></pre> <p>Is there a better way?</p>
5
2016-08-23T20:52:31Z
39,112,266
<pre><code>shift_year = lambda df: df.index.get_level_values('FirstYear').to_series().shift(-1) df.groupby(level=0).apply(shift_year) \ .combine_first(df.LastYear).astype(int) \ .rename('LastYear').to_frame() </code></pre> <p><a href="http://i.stack.imgur.com/Lph1W.png"><img src="http://i.stack.imgur.com/Lph1W.png" alt="enter image description here"></a></p>
6
2016-08-23T23:34:27Z
[ "python", "pandas" ]
Python program terminating unexpectedly
39,110,504
<p>I have a program that scrapes a website and downloads files when it finds it. Often it runs just fine but at other times it flat out terminates the operation of the program before it is finishing searching the sequence. I'm stumped. It never quits while downloading only while searching. I'm currently guessing a socket error problem but like I said above I'm stumped. I've put in httperror checking and nothing gets displayed for an http error code. I'm trying right now to insert socket error checking and it gets even crazier. Prior to adding anything for socket error checking it works fine. Once I add in the socket error checking the program won't even run. It brings up the IDLE display and shows the cursor, like IDLE is ready and waiting for the next command. Otherwise without socket error checking it indicates that the program is running until either the tkinter window shuts down(err program terminates unexpectedly). If the tkinter window shuts downs it doesn't give any error on IDLE.</p> <p>What do I have to do to find out why this program is terminating early at times and be able to trap it out so it won't terminate and just go back and rerun the same web address again. I think I have the rerunning the same web address taken care of but I don't have the socket error handling correct, if it's even socket error trouble. I'm stumped.</p> <pre><code>#!/usr/bin/python3.4 import urllib.request import os from tkinter import * import time import urllib.error import errno root = Tk() root.title("photodownloader") root.geometry("200x200") app = Frame(root) app.grid() os.chdir('/home/someone/somewhere/') Fileupdate = 10000 Filecount = 19999 while Fileupdate &lt;= Filecount: try: root.title(Fileupdate) url = 'http://www.webpage.com/photos/'+str(Fileupdate)+'.jpg' a = urllib.request.urlopen(url) urllib.request.urlretrieve(url, str(Fileupdate)+'.jpg') except urllib.error.HTTPError as err: if err.code == 404: Fileupdate = Fileupdate + 1 root.update_idletasks() continue else: print(err.code) Fileupdate = Fileupdate + 1 root.update_idletasks() continue except socket.error, v: print(Fileupdate, v[0]) continue Fileupdate = Fileupdate+1 root.update_idletasks() </code></pre>
1
2016-08-23T20:54:39Z
39,111,138
<p>I think the problem is caused by tkinter not given the chance to start it's main event loop which is done when you call <code>root.mainloop()</code>, I'd recommend making the code you currently have in a <code>while</code> loop instead to be a function that is periodically called with the <code>root.after()</code> method. I have included a potential change to test if this would fix the issue.</p> <p>Note that the lines:</p> <pre><code> Fileupdate = Fileupdate + 1 root.update_idletasks() continue </code></pre> <p>in some except branches are redundant since that would happen if the code kept going anyway, so part of modifying the code to work in a function was to simply get rid of those parts. Here is the code I'd like you to try running starting from the original <code>while</code> statement:</p> <pre><code>#-while Fileupdate &lt;= Filecount: def UPDATE_SOCKET(): global Fileupdate #allow the global variable to be changed if Fileupdate &lt;= Filecount: #/+ try: root.title(Fileupdate) url = 'http://www.webpage.com/photos/'+str(Fileupdate)+'.jpg' a = urllib.request.urlopen(url) urllib.request.urlretrieve(url, str(Fileupdate)+'.jpg') except urllib.error.HTTPError as err: #&lt;large redundant section removed&gt; print("error code",err.code) except socket.error as v: print("socket error",Fileupdate, v[0]) #- continue root.after(500, UPDATE_SOCKET) return #/+ Fileupdate = Fileupdate+1 #- root.update_idletasks() root.after(100, UPDATE_SOCKET) #after 100 milliseconds call the function again #change 100 to a smaller time to call this more frequently. root.after(0,UPDATE_SOCKET) #when it has a chance, call the update for first time root.mainloop() #enter main event loop #/+ </code></pre> <p>I indicate changed lines with a <code>#-</code> followed by the chunk that replaces it ending with a <code>#/+</code></p>
1
2016-08-23T21:42:14Z
[ "python", "sockets", "python-3.x", "tkinter" ]
Call a C++ function from Python and convert a OpenCV Mat to a Numpy array
39,110,507
<p><strong>Background situation</strong></p> <p>I'm trying to use the OpenCV Stitching module via the Python bindings, but I'm getting an error:</p> <pre><code>import cv2 stitcher = cv2.createStitcher(False) imageL = cv2.imread("imageL.jpg") imageC = cv2.imread("imageC.jpg") imageR = cv2.imread("imageR.jpg") stitcher.stitch((imageL, imageC)) </code></pre> <blockquote> <p>error: /home/user/OpenCV3.1.0/opencv/modules/python/src2/cv2.cpp:163: error: (-215) The data should normally be NULL! in function allocate</p> </blockquote> <p>Similar people suffering this:</p> <ul> <li><a href="http://stackoverflow.com/a/36646256/1253729">http://stackoverflow.com/a/36646256/1253729</a></li> <li><a href="http://stackoverflow.com/q/38914916/1253729">How to stitch images from a UAV using opencv python with Stitcher class</a></li> <li><a href="https://github.com/opencv/opencv/issues/6969" rel="nofollow">https://github.com/opencv/opencv/issues/6969</a></li> </ul> <p><strong>The problem at hand</strong> </p> <p>So I decided to use a official C++ OpenCV stitching example and use Python to call it using Boost.Python. However, I'm still unable to figure out how to properly use Boost.Python + <a href="https://github.com/spillai/numpy-opencv-converter" rel="nofollow">numpy-opencv-converter</a> to handle the C++ Mat vs Numpy array conversion.</p> <p><strong>¿How do I call the numpy-opencv-converter?</strong> I've only got Boost.Python in place, and when running my python function to call the C++ file I got this (expected) outcome:</p> <pre><code>$ python python_caller.py Traceback (most recent call last): File "python_caller.py", line 10, in &lt;module&gt; visualize(A) Boost.Python.ArgumentError: Python argument types in testing.visualize(numpy.ndarray) did not match C++ signature: visualize(cv::Mat) </code></pre> <p>Thanks.</p> <p>PD: I'm in Ubuntu 14.04, Python 2.7.4 using OpenCV 3.1.0 compiled from sources and inside a virtualenv.</p> <hr> <p>These are the files I'm using.</p> <p><strong>testing.cpp:</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;opencv2/opencv.hpp&gt; #include &lt;boost/python.hpp&gt; using namespace cv; int main(){} Mat visualize(const cv::Mat input_image) { cv::Mat image; image = input_image; namedWindow("Display Image", WINDOW_AUTOSIZE ); imshow("Display Image", image); waitKey(0); return image; } using namespace boost::python; BOOST_PYTHON_MODULE(testing) // file name { def("visualize", visualize); //function name } </code></pre> <p><strong>python_caller.py:</strong></p> <pre><code>import cv2 import numpy as np from testing import visualize A = cv2.imread("imageL.jpg") visualize(A) </code></pre> <p><strong>Makefile:</strong></p> <pre><code>CFLAGS=`pkg-config --cflags opencv` LDFLAGS=`pkg-config --libs opencv` testing.so: testing.o g++ -shared -Wl,--export-dynamic -o testing.so testing.o -L/usr/lib -lboost_python -L/usr/lib/python2.7/config -lpython2.7 -L/usr/lib/x86_64-linux-gnu/ -lopencv_calib3d -lopencv_contrib -lopencv_core -lopencv_features2d -lopencv_flann -lopencv_gpu -lopencv_highgui -lopencv_imgproc -lopencv_legacy -lopencv_ml -lopencv_objdetect -lopencv_ocl -lopencv_photo -lopencv_stitching -lopencv_superres -lopencv_ts -lopencv_video -lopencv_videostab testing.o: testing.cpp g++ -I/usr/include/python2.7 -I/usr/include -fPIC -c testing.cpp </code></pre>
2
2016-08-23T20:55:04Z
39,130,543
<p>You need to convert the Python NDArray &lt;=> C++ cv::Mat. I can recommend this <a href="https://github.com/Algomorph/pyboostcvconverter" rel="nofollow">GitHub Repo</a>. It contains an example that should fit to your needs. I am using the converter on Ubuntu 15.10 with Python 2.7/3.4 and OpenCV 3.1.</p>
1
2016-08-24T18:25:46Z
[ "python", "c++", "opencv", "numpy", "boost" ]
Getting an argument name as a string - Python
39,110,640
<p>I have a function that takes in a variable as an argument. That variable happens to contain a directory, also holding a bunch of txt files.</p> <p>I was wondering if there is a way for that variable to be taken as a string? Not what's inside the variable, just the name of that variable. Thanks a bunch!</p> <pre><code>import glob import pandas as pd variable_1 = glob.glob('dir_pathway/*txt') variable_2 = glob.glob('other_dir_pathway/*txt') def my_function(variable_arg): ## a bunch of code to get certain things from the directory ## variable_3 = pd.DataFrame( ## stuff taken from directory ## ) variable_3.to_csv(variable_arg + "_add_var_to_me.txt") </code></pre>
1
2016-08-23T21:04:14Z
39,110,763
<p>Although that is very weird request, here is how you get the name of argument from inside the function</p> <pre><code>import inspect def f(value): frame = inspect.currentframe() print(inspect.getargvalues(frame)[0][0]) f(10) f("Hello world") f([1, 2, 3]) </code></pre> <p>Prints</p> <pre><code>value value value </code></pre>
2
2016-08-23T21:13:55Z
[ "python", "glob" ]
Python - If WGET access denied then
39,110,724
<p>I am writing a python script that performs an os.system call to wget and attempts to download a file from a set location. At the point of execution it does not know if the server has HTTP-AUTH or not but will attempt a wget of the default page. If not successful it needs to then run some alternative code. I have seen this question in Bash but not in python.</p> <p>if os.system("wget http://{}".format IP)</p> <p>else run other code</p>
0
2016-08-23T21:10:47Z
39,111,746
<p>You can use <code>subprocess.run</code> to execute <code>wget</code> then use the <code>returncode</code> to determine if it was successful. So it might look like this:</p> <pre><code>output = subprocess.run(["wget", "http://..."]) if output.returncode == 0: &lt; wget worked&gt; else: &lt; wget did not work&gt; </code></pre> <p>You will need to look up wget's return codes <a href="https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html" rel="nofollow">here</a></p> <p>For more info on the subprocess look <a href="https://docs.python.org/3/library/subprocess.html" rel="nofollow">here</a></p>
0
2016-08-23T22:37:15Z
[ "python", "wget" ]
POST XML information using Python
39,110,765
<p>I am creating a program in python that posts an XML file to a website's rest API to create a VCS root (this is what the website API documentation suggests). My program creates an XML file, based on user input, posts it (using the requests library), then deletes the file. Is there a way I can post the information contained in the XML file (mostly property values), without creating and deleting this temporary XML file? Can I post the information as a string or something? Examples in python or cURL could help.</p>
0
2016-08-23T21:13:58Z
39,132,533
<p>Use the data-Attribute of <code>requests</code>:</p> <pre><code>from io import BytesIO import xml.etree.ElementTree as et data = et.Element('some-xml') tree = et.ElementTree(data) payload = BytesIO() tree.write(payload) r = requests.post(url, data=payload.getvalue()) </code></pre>
0
2016-08-24T20:30:12Z
[ "python", "xml", "post", "curl" ]
Disable Alt+Tab Combination on Tkinter App
39,110,800
<p>How can i disable Alt+Tab combination, especially tab on my Tkinter App. I disabled Alt and F4 with <em>-</em> return "break" <em>-</em> but i can't disable Tab key with it.</p>
0
2016-08-23T21:16:08Z
39,112,160
<p>Tkinter provides no option for this. Alt-tab is intercepted before tkinter ever sees it. If you want to do this, you'll have to find some platform-specific hooks.</p>
0
2016-08-23T23:21:53Z
[ "python", "python-3.x", "tkinter" ]
Can SQLAlchemy Use MySQL's SSCursor For Only Some Queries?
39,110,864
<p>I have a query that fetches a lot of data from my MySQL db, where loading all of the data into memory isn't an option. Luckily, SQLAlchemy lets me create an engine using MySQL's SSCursor, so the data is streamed and not fully loaded into memory. I can do this like so:</p> <pre><code>create_engine(connect_str, connect_args={'cursorclass': MySQLdb.cursors.SSCursor}) </code></pre> <p>That's great, but I don't want to use SSCursor for all my queries including very small ones. I'd rather only use it where it's really necessary. I thought I'd be able to do this with the <code>stream_results</code> setting like so:</p> <pre><code>conn.execution_options(stream_results=True).execute(MyTable.__table__.select()) </code></pre> <p>Unfortunately, when monitoring memory usage when using that, it seems to use the exact same amount of memory as if I don't do that, whereas using <code>SSCursor</code>, my memory usage goes down to nil as expected. What am I missing? Is there some other way to accomplish this?</p>
1
2016-08-23T21:20:31Z
39,112,538
<p>From the <a href="http://docs.sqlalchemy.org/en/latest/core/connections.html" rel="nofollow">docs</a>:</p> <blockquote> <p>stream_results – Available on: Connection, statement. Indicate to the dialect that results should be “streamed” and not pre-buffered, if possible. This is a limitation of many DBAPIs. <strong>The flag is currently understood only by the psycopg2 dialect.</strong></p> </blockquote> <p>I <em>think</em> you just want to create multiple sessions one for streaming and one for normal queries, like:</p> <pre><code>from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine def create_session(engine): # configure Session class with desired options Session = sessionmaker() # associate it with our custom Session class Session.configure(bind=engine) # work with the session session = Session() return session #streaming stream_engine = create_engine(connect_str, connect_args={'cursorclass': MySQLdb.cursors.SSCursor}) stream_session = create_session(stream_engine) stream_session.execute(MyTable.__table__.select()) #normal normal_engine = create_engine(connect_str) normal_session = create_session(normal_engine) normal_session.execute(MyTable.__table__.select()) </code></pre>
0
2016-08-24T00:12:16Z
[ "python", "mysql", "sqlalchemy" ]
python cant use a function to change the value of a variable
39,110,902
<p>I'm rather new to python and was wondering why the function and therefore the if statement returns "100" instead of "83" in the code below. I'm not sure if I'm missing something obvious but it seems as if it should work.<a href="http://i.stack.imgur.com/KFmsn.png" rel="nofollow">This is the code I'm refering to:</a></p> <pre><code>playerhp = 100 def attack1(x): x = (x - 17) return x while playerhp &gt; 0: enemyattack = input("please type the word 'attack': ") if enemyattack.upper() == "ATTACK": attack1(playerhp) print(playerhp) else: break </code></pre>
-1
2016-08-23T21:23:23Z
39,111,008
<p>You have to assign the return value of <code>attack1</code> to <code>playerhp</code>:</p> <pre><code>def attack1(x): x = (x - 17) return x playerhp = 100 while playerhp &gt; 0: enemyattack = input("please type the word 'attack': ") if enemyattack.upper() == "ATTACK": playerhp = attack1(playerhp) print(playerhp) else: break </code></pre>
2
2016-08-23T21:32:08Z
[ "python", "function" ]
python cant use a function to change the value of a variable
39,110,902
<p>I'm rather new to python and was wondering why the function and therefore the if statement returns "100" instead of "83" in the code below. I'm not sure if I'm missing something obvious but it seems as if it should work.<a href="http://i.stack.imgur.com/KFmsn.png" rel="nofollow">This is the code I'm refering to:</a></p> <pre><code>playerhp = 100 def attack1(x): x = (x - 17) return x while playerhp &gt; 0: enemyattack = input("please type the word 'attack': ") if enemyattack.upper() == "ATTACK": attack1(playerhp) print(playerhp) else: break </code></pre>
-1
2016-08-23T21:23:23Z
39,111,058
<p>Here's a working example of your code:</p> <pre><code>playerhp = 100 def attack1(x): x = (x - 17) return x while playerhp &gt; 0: enemyattack = input("please type the word 'attack': ") if enemyattack.upper() == "ATTACK": playerhp = attack1(playerhp) print(playerhp) else: break </code></pre> <p>But the most important about your question is your really understand how passing arguments works, there are tons of sites explaining that, here's just <a href="http://www.python-course.eu/passing_arguments.php" rel="nofollow">one</a></p>
0
2016-08-23T21:35:14Z
[ "python", "function" ]
python cant use a function to change the value of a variable
39,110,902
<p>I'm rather new to python and was wondering why the function and therefore the if statement returns "100" instead of "83" in the code below. I'm not sure if I'm missing something obvious but it seems as if it should work.<a href="http://i.stack.imgur.com/KFmsn.png" rel="nofollow">This is the code I'm refering to:</a></p> <pre><code>playerhp = 100 def attack1(x): x = (x - 17) return x while playerhp &gt; 0: enemyattack = input("please type the word 'attack': ") if enemyattack.upper() == "ATTACK": attack1(playerhp) print(playerhp) else: break </code></pre>
-1
2016-08-23T21:23:23Z
39,111,086
<p>As mentioned in a comment above, this issue comes down to scoping. Try googling that for more info, but I'll try to give a beginner level explanation here.</p> <p>When you declare a variable, it exists in a specific scope, and can only be accessed by variables in the same or a lower scope. For example,</p> <pre><code>var1 = 5 if var1 &lt; 6: print(var1) var2 = 7 print(var2) #error on this line </code></pre> <p><code>var1</code> exists in the highest scope in this example, so it is accessible to lower ones, so the <code>print(var1)</code> line works fine. However, <code>var2</code> is in a higher scope than the statement attempting to print it, and as such it cannot find the variable. Since Python forces nice formatting, you can think of scope broadly as each level of indentation. If you have to go to a section more indented, it can find it, but if you need to go through a section that is less indented to find it, then you can't.</p> <p>This extends to functions. Your function <code>attack1</code> exists in a different scope than what is inside your while loop, and the variable <code>x</code> only exists within that function. As such, when you modify <code>x</code>, it only modifies it in that scope, not the original. It is beyond the scope of your original question, but look up what <code>passing by value</code> and <code>passing by reference</code> mean, and how they apply to Python. As other answers point out, you can fix this by assigning the <code>return value</code> of x to the original number you are passing in, i.e.</p> <pre><code>playerhp = attack1(playerhp) </code></pre> <p>to take the new number, 17 less than it used to be, and reassign it to the original value, so it assumes this new value instead.</p> <p><strong>Edit with regards to what other answers suggest</strong></p> <p>Some people suggest modifying the global variable directly. (I'm assuming Python 3 here, I don't know which version you're using or if Python 2 is even different), you can do that. Python is a little funny about scoping out of functions, but it is simple to rewrite your attack function like this:</p> <pre><code>def attack1(): global playerhp playerhp -= 17 #shortcut to subtract 17, same as playerhp = playerhp - 17 </code></pre> <p>and you can call it simply with </p> <pre><code>attack1() </code></pre> <p>and it will work the same way. Many programmers would shy away from using global variables if you can avoid it, but that is very subjective and they'll fight all day about that until the end of time. </p>
0
2016-08-23T21:38:04Z
[ "python", "function" ]
python cant use a function to change the value of a variable
39,110,902
<p>I'm rather new to python and was wondering why the function and therefore the if statement returns "100" instead of "83" in the code below. I'm not sure if I'm missing something obvious but it seems as if it should work.<a href="http://i.stack.imgur.com/KFmsn.png" rel="nofollow">This is the code I'm refering to:</a></p> <pre><code>playerhp = 100 def attack1(x): x = (x - 17) return x while playerhp &gt; 0: enemyattack = input("please type the word 'attack': ") if enemyattack.upper() == "ATTACK": attack1(playerhp) print(playerhp) else: break </code></pre>
-1
2016-08-23T21:23:23Z
39,111,090
<p>There are two approaches to achieve it.</p> <p><em>Approach 1</em>: Update <code>playerhp</code>'s value based on value return by <code>attack1()</code>. For example:</p> <pre><code>&gt;&gt;&gt; playerhp = 100 &gt;&gt;&gt; def attack1(x): ... return x -= 17 ... &gt;&gt;&gt; playerhp = attack1(playerhp) &gt;&gt;&gt; playerhp 83 </code></pre> <p><em>Approach 2</em>: Do not pass <code>x</code> as param to <code>attack1()</code>. Instead use <code>global playerhp</code> within function like:</p> <pre><code>&gt;&gt;&gt; playerhp = 100 &gt;&gt;&gt; def attack1(): ... global playerhp ... playerhp -= 17 ... &gt;&gt;&gt; attack1() &gt;&gt;&gt; playerhp 83 </code></pre>
0
2016-08-23T21:38:46Z
[ "python", "function" ]
python cant use a function to change the value of a variable
39,110,902
<p>I'm rather new to python and was wondering why the function and therefore the if statement returns "100" instead of "83" in the code below. I'm not sure if I'm missing something obvious but it seems as if it should work.<a href="http://i.stack.imgur.com/KFmsn.png" rel="nofollow">This is the code I'm refering to:</a></p> <pre><code>playerhp = 100 def attack1(x): x = (x - 17) return x while playerhp &gt; 0: enemyattack = input("please type the word 'attack': ") if enemyattack.upper() == "ATTACK": attack1(playerhp) print(playerhp) else: break </code></pre>
-1
2016-08-23T21:23:23Z
39,112,231
<pre><code>#this works for me. You were not printing the result of the function. def attack1(x): return(x-17) playerhp=100 while playerhp&gt;0: enemyattack= input("Please type the word 'attack':") if enemyattack.upper()=="ATTACK": x=attack1(playerhp) print (x) else: break </code></pre>
0
2016-08-23T23:30:59Z
[ "python", "function" ]
Run pip through jenkins-plugin?
39,110,980
<p>If pip is not installed on the jenkins linux-box, is there any jenkins-plugin that lets me run pip, without installing it at the os-level?</p>
0
2016-08-23T21:29:59Z
39,111,137
<p>Create a <a href="https://docs.python.org/3/library/venv.html" rel="nofollow">virtual environment</a>. It should come with pip, but otherwise install it in the virtualenv.</p>
0
2016-08-23T21:42:06Z
[ "python", "linux", "jenkins", "pip" ]
Run pip through jenkins-plugin?
39,110,980
<p>If pip is not installed on the jenkins linux-box, is there any jenkins-plugin that lets me run pip, without installing it at the os-level?</p>
0
2016-08-23T21:29:59Z
39,174,711
<p>Not a specific plug-in like you might want, but as was said, you can create a virtual environment in one of a few ways to get the functionality you're after.</p> <p>Docker can handle this, you can create a small script to build a docker image that will have access to pip and there are Jenkins plug-ins for docker.</p>
0
2016-08-26T21:14:37Z
[ "python", "linux", "jenkins", "pip" ]