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
listlengths
1
5
What is the Python equivalent of close() in Java?
38,745,269
<p>In Java, using the <code>close()</code> method frees resources by removing out of scope objects. I am confused as to what is the Python equivalent for this? </p> <ul> <li>Does Python's garbage collector automatically do this?</li> <li>Is it the <code>del</code> method?</li> <li>Should I use the <code>with</code> statement?</li> </ul> <p>Any help will be appreciated.</p> <p>Edit: My goal is to explicitly remove <strong>class objects</strong> when desired, not file objects.</p>
3
2016-08-03T13:37:09Z
38,745,393
<blockquote> <p>Should I use the with statement?</p> </blockquote> <p>Yes, according to <a href="https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects" rel="nofollow">the documentation</a>:</p> <blockquote> <p>It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks:</p> </blockquote>
0
2016-08-03T13:43:33Z
[ "java", "python", "python-2.7", "python-3.x", "resources" ]
What is the Python equivalent of close() in Java?
38,745,269
<p>In Java, using the <code>close()</code> method frees resources by removing out of scope objects. I am confused as to what is the Python equivalent for this? </p> <ul> <li>Does Python's garbage collector automatically do this?</li> <li>Is it the <code>del</code> method?</li> <li>Should I use the <code>with</code> statement?</li> </ul> <p>Any help will be appreciated.</p> <p>Edit: My goal is to explicitly remove <strong>class objects</strong> when desired, not file objects.</p>
3
2016-08-03T13:37:09Z
38,745,426
<p>You will find your answer <a href="http://stackoverflow.com/questions/1316767/how-can-i-explicitly-free-memory-in-python">here</a>: place gc.collect() before your code.</p>
0
2016-08-03T13:44:43Z
[ "java", "python", "python-2.7", "python-3.x", "resources" ]
What is the Python equivalent of close() in Java?
38,745,269
<p>In Java, using the <code>close()</code> method frees resources by removing out of scope objects. I am confused as to what is the Python equivalent for this? </p> <ul> <li>Does Python's garbage collector automatically do this?</li> <li>Is it the <code>del</code> method?</li> <li>Should I use the <code>with</code> statement?</li> </ul> <p>Any help will be appreciated.</p> <p>Edit: My goal is to explicitly remove <strong>class objects</strong> when desired, not file objects.</p>
3
2016-08-03T13:37:09Z
38,745,600
<p>ICart's comment is spot on for many different situations. However, regarding the creation and disposal of objects in general, I think <a href="http://stackoverflow.com/questions/6315244/how-to-give-object-away-to-python-garbage-collection">this other thread</a> provides a pretty good explanation of how python handles their objects (reference counts), and where garbage collection comes in.</p>
0
2016-08-03T13:52:29Z
[ "java", "python", "python-2.7", "python-3.x", "resources" ]
In DRF(django-rest-framework), null value in column "author_id" violates not-null constraint. What should i do?
38,745,280
<p>I made django project through DRF. <a href="http://i.stack.imgur.com/g2cxY.png" rel="nofollow">enter image description here</a></p> <p>From that window, i clicked post so then it did not worked.</p> <p><strong>traceback</strong></p> <pre><code>#I almost omitted other codes Environment: Request Method: POST Request URL: http://127.0.0.1:8000/comments/ Django Version: 1.9.7 Python Version: 3.5.2 Traceback: Exception Type: IntegrityError at /comments/ Exception Value: null value in column "author_id" violates not-null constraint DETAIL: Failing row contains (2, comment1, 2016-08-03 13:30:59.536186+00, null, null). </code></pre> <p><strong>serializers.py</strong></p> <pre><code>class UserSerializer(serializers.HyperlinkedModelSerializer): posts = serializers.HyperlinkedRelatedField(many=True, view_name='post-detail', read_only=True) comments = serializers.HyperlinkedRelatedField(many=True, view_name='comment-detail', read_only=True) class Meta: model = User fields = ('url','id', 'pk', 'username', 'email', 'comments', 'posts', 'author') class CommentSerializer(serializers.HyperlinkedModelSerializer): author = serializers.ReadOnlyField(source='author.username') post = serializers.ReadOnlyField(source='post.title') highlight = serializers.HyperlinkedIdentityField(view_name='comment-highlight', format='html') class Meta: model = Comment fields = ('url','id', 'pk', 'post', 'author', 'text','highlight') </code></pre> <p><strong>models.py</strong></p> <pre><code>class Comment(models.Model): post = models.ForeignKey('blog.Post', related_name='related_comments') author = models.ForeignKey(User, related_name='related_commentwriter') text = models.TextField(max_length=500) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.text </code></pre> <p>Additionally, i'm using django rest auth.</p> <p>Why this error comes? How to solve this?</p> <p>Thanks for reading.</p>
1
2016-08-03T13:37:52Z
38,745,996
<p>You could not create Comment instance with null in <code>author</code> field. For fix it you can add author when you create new comment </p> <pre><code>class CommentSerializer(serializers.HyperlinkedModelSerializer): ................... def create(self, validated_data): validated_data['author'] = self.context['request'].user return super(CommentSerializer, self).create(validated_data) </code></pre> <p>The same with <code>post</code> field.</p>
0
2016-08-03T14:08:55Z
[ "python", "django", "django-rest-framework" ]
concatenating 2 list in python
38,745,327
<p>this is what I have. I want to concatenate this 2 list together</p> <pre><code>first_name = ['Homer', 'Marge', 'Bart', 'Lisa', 'Maggie', 'Carl', 'Ned', 'Barney', 'Lenny', 'Otto', 'Seymour'] last_name = ['Simpson', 'Simpson', 'Simpson', 'Simpson', 'Simpson', 'Carlson', 'Flanders', 'Gumble', 'Leonard', 'Mann', 'Skinner'] for (i, j) in zip(first_name, last_name): print (first_name[i] + " " + last_name[j]) </code></pre> <p>But there is an error message saying </p> <pre><code>TypeError: list indices must be integers, not str </code></pre> <p>on the line with the "print" statement </p>
-1
2016-08-03T13:39:45Z
38,745,346
<p>your loop actually iterates through the elements, not the indices</p> <pre><code>for (f, l) in zip(first_name, last_name): print (f + " " + l) </code></pre>
6
2016-08-03T13:40:46Z
[ "python", "string", "list" ]
concatenating 2 list in python
38,745,327
<p>this is what I have. I want to concatenate this 2 list together</p> <pre><code>first_name = ['Homer', 'Marge', 'Bart', 'Lisa', 'Maggie', 'Carl', 'Ned', 'Barney', 'Lenny', 'Otto', 'Seymour'] last_name = ['Simpson', 'Simpson', 'Simpson', 'Simpson', 'Simpson', 'Carlson', 'Flanders', 'Gumble', 'Leonard', 'Mann', 'Skinner'] for (i, j) in zip(first_name, last_name): print (first_name[i] + " " + last_name[j]) </code></pre> <p>But there is an error message saying </p> <pre><code>TypeError: list indices must be integers, not str </code></pre> <p>on the line with the "print" statement </p>
-1
2016-08-03T13:39:45Z
38,745,458
<p><strong>EDIT:</strong> in case of using indexes, but iterating through elemenets is better</p> <p>The two lists have same length so:</p> <pre><code>for i in range(len(first_name)): print(first_name[i] + " " + last_name[j]) </code></pre>
0
2016-08-03T13:45:58Z
[ "python", "string", "list" ]
concatenating 2 list in python
38,745,327
<p>this is what I have. I want to concatenate this 2 list together</p> <pre><code>first_name = ['Homer', 'Marge', 'Bart', 'Lisa', 'Maggie', 'Carl', 'Ned', 'Barney', 'Lenny', 'Otto', 'Seymour'] last_name = ['Simpson', 'Simpson', 'Simpson', 'Simpson', 'Simpson', 'Carlson', 'Flanders', 'Gumble', 'Leonard', 'Mann', 'Skinner'] for (i, j) in zip(first_name, last_name): print (first_name[i] + " " + last_name[j]) </code></pre> <p>But there is an error message saying </p> <pre><code>TypeError: list indices must be integers, not str </code></pre> <p>on the line with the "print" statement </p>
-1
2016-08-03T13:39:45Z
38,745,825
<p>You can use Python <a href="https://docs.python.org/2/library/functions.html#map" rel="nofollow">map function</a> in the following way to get the output you want:</p> <pre><code>print(map(lambda f,l: f + " " + l, first_name, last_name)) </code></pre>
0
2016-08-03T14:01:19Z
[ "python", "string", "list" ]
Saving a list of UUID numbers to a .csv file in python
38,745,365
<p>I am trying to create a .csv file of UUID numbers. I see how to make a single UUID number in python but can't get the correct syntax to make 50 numbers and save them to a .csv file. I've googled and found many ways to create .csv files and how to use For loop but none seem to pertain to this particular application. Thank you for any help.</p>
2
2016-08-03T13:41:50Z
38,745,428
<p>Just combine <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">a csv writer</a> with <a href="https://docs.python.org/2/library/uuid.html" rel="nofollow">an uuid generator</a></p> <pre><code>import csv import uuid with open('uuids.csv', 'w') as csvfile: uuidwriter = csv.writer(csvfile) for i in range(50): uuidwriter.writerow([uuid.uuid1()]) </code></pre>
-1
2016-08-03T13:44:47Z
[ "python", "csv", "for-loop", "uuid" ]
Saving a list of UUID numbers to a .csv file in python
38,745,365
<p>I am trying to create a .csv file of UUID numbers. I see how to make a single UUID number in python but can't get the correct syntax to make 50 numbers and save them to a .csv file. I've googled and found many ways to create .csv files and how to use For loop but none seem to pertain to this particular application. Thank you for any help.</p>
2
2016-08-03T13:41:50Z
38,745,728
<p>a csv is basically a text file, and since yours have only one column you won't need separators :</p> <pre><code>import uuid with open('uuids.csv', 'w') as f: f.writelines(str(uuid.uuid1()) + "\n" for i in range(50)) </code></pre>
-1
2016-08-03T13:57:28Z
[ "python", "csv", "for-loop", "uuid" ]
facebook integration error, django-allauth
38,745,579
<p>I want to integrante django allauth to my website, I followed the tutorial but I am facing an error while I use ElasticBeanStalk servers but not on localhost.</p> <pre><code>Reverse for 'facebook_login' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] </code></pre> <p>Here is my <strong>settings</strong> :</p> <pre><code>INSTALLED_APPS = [ ... 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'utilisateur', ] AUTHENTICATION_BACKENDS = ( # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ) SITE_ID = 1 LOGIN_REDIRECT_URL = '/' SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'SCOPE': ['email'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'METHOD': 'oauth2', 'VERIFIED_EMAIL': False, } } </code></pre> <p><strong>urls.py</strong> :</p> <pre><code>url(r'^accounts/', include('allauth.urls')), </code></pre> <p><a href="http://i.stack.imgur.com/UMFT1.png" rel="nofollow"><img src="http://i.stack.imgur.com/UMFT1.png" alt="enter image description here"></a></p> <p>This error only raise on the page : 'MyDomain/accounts/login/' when logged out, also there is no links for 'facebook/login/' as on localhost.</p> <p>I already configured the facebook application, with the ElasticBeanStalk URL.</p> <p>Any help would be appreciated, I am on it for a while now, how can I resolve this problem ?</p>
0
2016-08-03T13:51:12Z
38,751,004
<p>Found the answer on another post : Facebook SDK egg which allauth relies on was missing on the webserver ElasticBeanStalk.</p> <p>You can learn more on this post : <a href="http://stackoverflow.com/questions/11065610/using-django-allauth?rq=1">using django-allauth</a></p>
0
2016-08-03T18:21:50Z
[ "python", "django", "django-allauth" ]
simplest python equivalent to R's grepl
38,745,710
<p>Is there a simple/one-line python equivalent to R's <code>grepl</code> function?</p> <pre><code>strings = c("aString", "yetAnotherString", "evenAnotherOne") grepl(pattern = "String", x = strings) #[1] TRUE TRUE FALSE </code></pre>
4
2016-08-03T13:56:45Z
38,745,802
<p>You can use list comprehension:</p> <pre><code>strings = ["aString", "yetAnotherString", "evenAnotherOne"] ["String" in i for i in strings] #Out[76]: [True, True, False] </code></pre> <p>Or use <code>re</code> module:</p> <pre><code>import re [bool(re.search("String", i)) for i in strings] #Out[77]: [True, True, False] </code></pre> <p>Or with <code>Pandas</code> (R user may be interested in this library, using a dataframe "similar" structure):</p> <pre><code>import pandas as pd pd.Series(strings).str.contains('String').tolist() #Out[78]: [True, True, False] </code></pre>
9
2016-08-03T14:00:27Z
[ "python", "python-2.7" ]
simplest python equivalent to R's grepl
38,745,710
<p>Is there a simple/one-line python equivalent to R's <code>grepl</code> function?</p> <pre><code>strings = c("aString", "yetAnotherString", "evenAnotherOne") grepl(pattern = "String", x = strings) #[1] TRUE TRUE FALSE </code></pre>
4
2016-08-03T13:56:45Z
38,745,835
<p>A one-line equivalent is possible, using <code>re</code>:</p> <pre><code>import re strings = ['aString', 'yetAnotherString', 'evenAnotherOne'] [re.search('String', x) for x in strings] </code></pre> <p>This won’t give you boolean values, but truthy results that are just as good.</p>
2
2016-08-03T14:01:44Z
[ "python", "python-2.7" ]
simplest python equivalent to R's grepl
38,745,710
<p>Is there a simple/one-line python equivalent to R's <code>grepl</code> function?</p> <pre><code>strings = c("aString", "yetAnotherString", "evenAnotherOne") grepl(pattern = "String", x = strings) #[1] TRUE TRUE FALSE </code></pre>
4
2016-08-03T13:56:45Z
38,746,108
<p>If you do not need a regular expression, but are just testing for the existence of a susbtring in a string:</p> <pre><code>["String" in x for x in strings] </code></pre>
1
2016-08-03T14:13:40Z
[ "python", "python-2.7" ]
How to merge/join two resultset/table in django?
38,745,759
<p>I'm trying to display a list of employees that are part of the same company. So for example with the given URL localhost/app/company-slug/ I'd like to show a list of rows where there are the details of all three models:</p> <p>| first_name | last_name | company-slug | employee_status | employee_type |</p> <p>With this models, how I can retrieve this kind of data?</p> <pre><code>class Employee(models.Model): company = models.ForeignKey(Company) class EmployeeProfile(models.Model): employee = models.OneToOneField(Employee) # Base first_name = models.CharField(max_length=31) middle_name = models.CharField(max_length=31, null=True, blank=True) class EmployeeJob(models.Model): employee = models.OneToOneField(Employee) # Employment status employment_status = models.ForeignKey(EmploymentStatus, null=True, blank=True) employment_type = models.ForeignKey(EmploymentType, null=True, blank=True) </code></pre> <h1>Edit 1:</h1> <p>I didn't know was possible join tables within template tags. This is a working solution suggested by @Shang Wang</p> <pre><code>{% for employee in employees %} &lt;tr class="table-row clickable" data-href="{% url 'hrm:detail' company.slug employee.pk %}"&gt; &lt;td&gt;&lt;strong&gt;A&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;{{ employee.employeeprofile.first_name }} {{ employee.employeeprofile.last_name }}&lt;/td&gt; &lt;td&gt;{{ employee.employeejob.employment_status }}&lt;/td&gt; &lt;td&gt;{{ employee.employeejob.employment_type }}&lt;/td&gt; &lt;td&gt;4&lt;/td&gt; &lt;/tr&gt; {% endfor %} </code></pre>
0
2016-08-03T13:59:06Z
38,745,985
<p>do you have a views.py which serves these models? you could easily use the django <a href="https://docs.djangoproject.com/en/1.9/topics/http/shortcuts/#render" rel="nofollow">render</a> function to serve all three of these models to the dom. this is a rather comprehensive, all encompassing process but I'd be more than happy to assist you </p>
1
2016-08-03T14:08:21Z
[ "python", "django", "join", "orm", "merge" ]
How to merge/join two resultset/table in django?
38,745,759
<p>I'm trying to display a list of employees that are part of the same company. So for example with the given URL localhost/app/company-slug/ I'd like to show a list of rows where there are the details of all three models:</p> <p>| first_name | last_name | company-slug | employee_status | employee_type |</p> <p>With this models, how I can retrieve this kind of data?</p> <pre><code>class Employee(models.Model): company = models.ForeignKey(Company) class EmployeeProfile(models.Model): employee = models.OneToOneField(Employee) # Base first_name = models.CharField(max_length=31) middle_name = models.CharField(max_length=31, null=True, blank=True) class EmployeeJob(models.Model): employee = models.OneToOneField(Employee) # Employment status employment_status = models.ForeignKey(EmploymentStatus, null=True, blank=True) employment_type = models.ForeignKey(EmploymentType, null=True, blank=True) </code></pre> <h1>Edit 1:</h1> <p>I didn't know was possible join tables within template tags. This is a working solution suggested by @Shang Wang</p> <pre><code>{% for employee in employees %} &lt;tr class="table-row clickable" data-href="{% url 'hrm:detail' company.slug employee.pk %}"&gt; &lt;td&gt;&lt;strong&gt;A&lt;/strong&gt;&lt;/td&gt; &lt;td&gt;{{ employee.employeeprofile.first_name }} {{ employee.employeeprofile.last_name }}&lt;/td&gt; &lt;td&gt;{{ employee.employeejob.employment_status }}&lt;/td&gt; &lt;td&gt;{{ employee.employeejob.employment_type }}&lt;/td&gt; &lt;td&gt;4&lt;/td&gt; &lt;/tr&gt; {% endfor %} </code></pre>
0
2016-08-03T13:59:06Z
38,746,000
<p>I assume you already had an object for <code>company</code> in current page, getting the employees is really easy:</p> <pre><code>employees = Employee.objects.filter(company=company) for employee in employees: print employee.employeeprofile.first_name print employee.employeeprofile.last_name print employee.employeejob.employment_status print employee.employeejob.employee_type </code></pre> <p>Django doc about <a href="https://docs.djangoproject.com/en/1.9/topics/db/examples/one_to_one/" rel="nofollow">OneToOneField</a>.</p>
1
2016-08-03T14:09:07Z
[ "python", "django", "join", "orm", "merge" ]
Unable to handle "HTTP Badstatus line" exception
38,745,812
<p>I want to handle <code>http.client.BadStatusLine: ''</code> exception. I am on python3. My code is </p> <pre><code>import http.client try: req = urllib.request.Request(url, headers={'User-Agent': 'Chrome/51'}) html = urllib.request.urlopen(req).read() soup = BeautifulSoup(html,"html.parser") return soup except http.client.HTTPException as eror: print("Boom") </code></pre> <p>but <code>httpException</code> is not in python3? <a href="http://i.stack.imgur.com/fFbLd.png" rel="nofollow"><img src="http://i.stack.imgur.com/fFbLd.png" alt="Figure"></a> </p> <p>I read <a href="http://stackoverflow.com/questions/8734617/python-django-badstatusline-error">stackOverFloeQuestion</a> and <a href="http://stackoverflow.com/questions/29981182/python-3-urllib-exception-http-client-badstatusline">this</a> but unable to catch it. Any help?</p>
-1
2016-08-03T14:00:49Z
38,746,006
<p>You need to make up your mind :-). You can either use <code>http.client</code> or <code>urllib.request</code>, but you should not use one and then try to catch errors from the other. If you want to stick with urllib.request, the class to catch is <code>urllib.error.HTTPError</code>.</p> <p>Perhaps it may be more opportune in your case to use <a href="http://docs.python-requests.org/en/master/" rel="nofollow">Requests</a>, which is a higher level http library.</p>
0
2016-08-03T14:09:17Z
[ "python", "python-3.x" ]
Prompting with previous input from sys.stdin
38,745,956
<p>I have a standard server-client TCP setup. The basic idea is a chat system. Looking at only the client's side of the conversation, the client prompts the user for input with:</p> <pre><code>sys.stdout.write('&lt;%s&gt; ' % username) sys.stdout.flush() </code></pre> <p>using the following logic:</p> <pre><code>while True: socket_list = [sys.stdin, s] read_sockets, write_sockets, error_sockets = select.select(socket_list, [], []) for sock in read_sockets: if sock == s: data = sock.recv(4096) if data: output('\a\r%s' % data) #output incoming message sys.stdout.write('&lt;%s&gt; ' % username) #prompt for input sys.stdout.flush() else: raise SystemExit else: msg = getASCII(sys.stdin.readline()) # returns only the ascii if msg: s.send(msg) sys.stdout.write('&lt;%s&gt; ' % username) sys.stdout.flush()) </code></pre> <p>(Note: truncated snippet. <s> Full code can be found <a href="https://github.com/libeclipse/edgychat/blob/master/edgychat.py" rel="nofollow">here</a> </s> Linked code has been updated and so is no longer relevant.)</p> <p>The problem is, when the user is typing and it gets an incoming message from the server, the client outputs the message and prompts for input again. The message that was being typed is still in the stdin buffer but has gone from the screen. If the user presses enter to send the message, the entire message will be sent including what was in the buffer, but on the user's screen, only the second part of the message, the part after the interruption, will be displayed.</p> <p>I have a possible solution, which is that when I prompt for input, I check if there's anything in the buffer and output that along with the prompt, but I have no idea how to implement it. Any help is appreciated.</p>
1
2016-08-03T14:07:19Z
38,891,727
<p>As an alternative to implementing your own editing line input function as discussed in the question's comments, consider this approach: Change the scrolling region to leave out the screen's bottom line (the user input line) and enter the scrolling region only temporarily to output incoming server messages. <a href="http://stackoverflow.com/a/34992925/2413201">That answer</a> contains an example.</p>
0
2016-08-11T08:57:32Z
[ "python", "sockets", "io", "buffer", "stdin" ]
Prompting with previous input from sys.stdin
38,745,956
<p>I have a standard server-client TCP setup. The basic idea is a chat system. Looking at only the client's side of the conversation, the client prompts the user for input with:</p> <pre><code>sys.stdout.write('&lt;%s&gt; ' % username) sys.stdout.flush() </code></pre> <p>using the following logic:</p> <pre><code>while True: socket_list = [sys.stdin, s] read_sockets, write_sockets, error_sockets = select.select(socket_list, [], []) for sock in read_sockets: if sock == s: data = sock.recv(4096) if data: output('\a\r%s' % data) #output incoming message sys.stdout.write('&lt;%s&gt; ' % username) #prompt for input sys.stdout.flush() else: raise SystemExit else: msg = getASCII(sys.stdin.readline()) # returns only the ascii if msg: s.send(msg) sys.stdout.write('&lt;%s&gt; ' % username) sys.stdout.flush()) </code></pre> <p>(Note: truncated snippet. <s> Full code can be found <a href="https://github.com/libeclipse/edgychat/blob/master/edgychat.py" rel="nofollow">here</a> </s> Linked code has been updated and so is no longer relevant.)</p> <p>The problem is, when the user is typing and it gets an incoming message from the server, the client outputs the message and prompts for input again. The message that was being typed is still in the stdin buffer but has gone from the screen. If the user presses enter to send the message, the entire message will be sent including what was in the buffer, but on the user's screen, only the second part of the message, the part after the interruption, will be displayed.</p> <p>I have a possible solution, which is that when I prompt for input, I check if there's anything in the buffer and output that along with the prompt, but I have no idea how to implement it. Any help is appreciated.</p>
1
2016-08-03T14:07:19Z
38,906,306
<p>The problem seems to be that you are letting the messages from the other user interrupt the typing. I recommend you either only listen to one thing at a time (when the user is typing you let him finish and press enter before listening for remote messages) <em>or</em> you listen for the user's input one key at a time and build up your own buffer (see <a href="http://stackoverflow.com/questions/292095/polling-the-keyboard-detect-a-keypress-in-python">Polling the keyboard (detect a keypress) in python</a>). The downside to the later approach is that you need to implement key editing, etc. There may be a library that accomplishes this for you.</p> <p>Note that in most chat programs, the area you type is in a separate window/screen region than where you are seeing the messages. All messages (yours as well as others) show up when complete in this message area. Perhaps you can use just display messages (independent of input) somewhere else on the screen.</p>
0
2016-08-11T21:18:08Z
[ "python", "sockets", "io", "buffer", "stdin" ]
Prompting with previous input from sys.stdin
38,745,956
<p>I have a standard server-client TCP setup. The basic idea is a chat system. Looking at only the client's side of the conversation, the client prompts the user for input with:</p> <pre><code>sys.stdout.write('&lt;%s&gt; ' % username) sys.stdout.flush() </code></pre> <p>using the following logic:</p> <pre><code>while True: socket_list = [sys.stdin, s] read_sockets, write_sockets, error_sockets = select.select(socket_list, [], []) for sock in read_sockets: if sock == s: data = sock.recv(4096) if data: output('\a\r%s' % data) #output incoming message sys.stdout.write('&lt;%s&gt; ' % username) #prompt for input sys.stdout.flush() else: raise SystemExit else: msg = getASCII(sys.stdin.readline()) # returns only the ascii if msg: s.send(msg) sys.stdout.write('&lt;%s&gt; ' % username) sys.stdout.flush()) </code></pre> <p>(Note: truncated snippet. <s> Full code can be found <a href="https://github.com/libeclipse/edgychat/blob/master/edgychat.py" rel="nofollow">here</a> </s> Linked code has been updated and so is no longer relevant.)</p> <p>The problem is, when the user is typing and it gets an incoming message from the server, the client outputs the message and prompts for input again. The message that was being typed is still in the stdin buffer but has gone from the screen. If the user presses enter to send the message, the entire message will be sent including what was in the buffer, but on the user's screen, only the second part of the message, the part after the interruption, will be displayed.</p> <p>I have a possible solution, which is that when I prompt for input, I check if there's anything in the buffer and output that along with the prompt, but I have no idea how to implement it. Any help is appreciated.</p>
1
2016-08-03T14:07:19Z
38,907,018
<p>To implement your solution, you will have to read from stdin in an unbuffered way. readline() and read() block until an EOL or EOF. You need the data from stdin BEFORE the return key is pressed. To achieve that, this might prove helpful: <a href="http://code.activestate.com/recipes/134892-getch-like-unbuffered-character-reading-from-stdin/" rel="nofollow">http://code.activestate.com/recipes/134892-getch-like-unbuffered-character-reading-from-stdin/</a> When you are about to write data, you could then read from stdin, store it somewhere and output it again after outputting the message. As select won't be called for stdin, make a separate read-thread that reads stdin. Use locks for accessing stdin's data so far.</p>
1
2016-08-11T22:22:51Z
[ "python", "sockets", "io", "buffer", "stdin" ]
Embedding python in C++, Segmentation fault
38,745,999
<p>I am trying to embed python script in a c++ application. To try out the integration, I made a pilot code:</p> <pre><code>// c++ code int main(int argc, char *argv[]) { PyObject *pName, *pModule, *pDict, *pFunc, *pValue; if (argc &lt; 3) { printf("Usage: exe_name python_source function_name\n"); return 1; } // Initialize the Python Interpreter Py_Initialize(); // Build the name object pName = PyBytes_FromString(argv[1]); //std::to_string(argv[1]).encode( // Load the module object pModule = PyImport_Import(pName); // pDict is a borrowed reference pDict = PyModule_GetDict(pModule); // pFunc is also a borrowed reference pFunc = PyDict_GetItemString(pDict, argv[2]); if (PyCallable_Check(pFunc)) { PyObject_CallObject(pFunc, NULL); } else { PyErr_Print(); } // Clean up Py_DECREF(pModule); Py_DECREF(pName); // Finish the Python Interpreter Py_Finalize(); return 0; } # Python script def multiply(): c = 12345*6789 print ('The result of 12345 x 6789 :' + str(c)) </code></pre> <p>I came across the posts that suggest to use boost. Is boost simpler than this? Def of simple: less code, straight forward, largely used by community.</p> <p>I am interested in these questions because the real code we are going to integrate is pretty complex (because not following the coding ethics), and it needs to communicate with Python code at many times, hence there is synchronization issue as well.</p>
0
2016-08-03T14:09:02Z
38,791,595
<p>It might be easier to use <code>boost::python</code> or the code generated by cython.</p> <p>The main culprit seems to be the missing </p> <pre><code>PySys_SetArgv(argc, wargs); </code></pre> <p>where <code>wargs</code> contains the arguments as wide character strings. Without it, relative imports do not work.</p> <p>The following code (compiled with gcc, g++ would require some casts in case of <code>malloc()</code>) seems to work.</p> <pre><code>#include &lt;Python.h&gt; #include &lt;string.h&gt; int to_wide_args(wchar_t **argsw[], int argc, char *argv[]) { int i; size_t len; wchar_t *wstr; wchar_t **tmp = NULL; tmp = malloc(sizeof(wchar_t **) * argc); for (i = 0; i &lt; argc; i++) { /* In case of python 3.5, see Py_DecodeLocale */ len = mbstowcs(NULL, argv[i], 0); wstr = malloc(sizeof(wchar_t) * (len + 1)); if (len != mbstowcs(wstr, argv[i], len + 1)) { return -1; } tmp[i] = wstr; } *argsw = tmp; return 0; } int main(int argc, char *argv[]) { PyObject *dict = 0; PyObject *func = 0; PyObject *module = 0; wchar_t **wargs = NULL; int rc = 0; if (argc &lt; 3) { printf("Usage: exe_name python_source function_name\n"); return 1; } if (to_wide_args(&amp;wargs, argc, argv) &lt; 0) goto error; Py_SetProgramName(wargs[0]); Py_Initialize(); PySys_SetArgv(argc, wargs); if (PyErr_Occurred()) goto error; module = PyImport_ImportModule(argv[1]); printf("Module ptr: %p\n", module); if (module == NULL || PyErr_Occurred()) goto error; dict = PyModule_GetDict(module); printf("Module dict ptr: %p\n", dict); if (dict == NULL || PyErr_Occurred()) goto error; func = PyDict_GetItemString(dict, argv[2]); printf("Function ptr: %p\n", func); if (func == NULL || PyErr_Occurred()) goto error; if (PyCallable_Check(func)) { PyObject_CallObject(func, NULL); } else { goto error; } goto ok; error: PyErr_Print(); rc = 1; ok: Py_XDECREF(module); Py_Finalize(); return rc; } </code></pre>
0
2016-08-05T14:23:55Z
[ "python", "c++", "embedding" ]
Strange Python numpy array indexing behaviour
38,746,001
<p>I have the following array</p> <pre><code>[0. 100. 200. 300. 400. -500. -400. -300. -200. -100.] </code></pre> <p>which I'm trying to rearrange to be from smallest to largest.</p> <p>I find the turning point from pos to neg which is stored in j.</p> <p>If I print the following I get </p> <pre><code>&gt;&gt;print(frequencies[4]) 400.0 </code></pre> <p>BUT</p> <pre><code>&gt;&gt;print(frequencies[0:4-1]) [0. 100. 200. 300.] </code></pre> <p>Why doesn't it go all the way up to 400? Seems like an odd choice of syntax convention.</p>
-3
2016-08-03T14:09:09Z
38,746,049
<p>Almost everywhere through Python the behavior is <code>[)</code>, meaning the left (or start) argument is inclusive and the right (or end) argument is exclusive. Be it list slicing, string slicing, the <code>range</code> function, etc.</p> <p>It only makes sense for <code>numpy</code> to follow this convention.</p>
3
2016-08-03T14:11:07Z
[ "python", "arrays", "numpy" ]
PyQt - QFileDialog - directly browse to a folder?
38,746,002
<p>Is there any way to directly browse to a folder using QFileDialog?</p> <p>Meaning, instead of double clicking on each folder while navigating to the destination folder, simply enter the path somewhere or use a hotkey like the one (Shift+Command+G) in Finder on Mac OS X.</p> <p>Thanks!</p> <p><strong>EDIT:</strong> (my code)</p> <pre><code> filter = "Wav File (*.wav)" self._audio_file = QtGui.QFileDialog.getOpenFileName(self, "Audio File", "/myfolder/folder", filter) self._audio_file = str(self._audio_file) </code></pre>
2
2016-08-03T14:09:10Z
38,746,444
<p>Below you'll find a simple test which opens directly the dialog at a certain path, in this case will be the current working directory. If you want to open directly another path you can just use python's directory functions included in os.path module:</p> <pre><code> import sys import os from PyQt4 import QtGui def test(): filename = QtGui.QFileDialog.getOpenFileName( None, 'Test Dialog', os.getcwd(), 'All Files(*.*)') def main(): app = QtGui.QApplication(sys.argv) test() sys.exit(app.exec_()) if __name__ == "__main__": main() </code></pre>
0
2016-08-03T14:27:28Z
[ "python", "qt", "pyqt" ]
PyQt - QFileDialog - directly browse to a folder?
38,746,002
<p>Is there any way to directly browse to a folder using QFileDialog?</p> <p>Meaning, instead of double clicking on each folder while navigating to the destination folder, simply enter the path somewhere or use a hotkey like the one (Shift+Command+G) in Finder on Mac OS X.</p> <p>Thanks!</p> <p><strong>EDIT:</strong> (my code)</p> <pre><code> filter = "Wav File (*.wav)" self._audio_file = QtGui.QFileDialog.getOpenFileName(self, "Audio File", "/myfolder/folder", filter) self._audio_file = str(self._audio_file) </code></pre>
2
2016-08-03T14:09:10Z
38,746,526
<p>In <code>PyQt 4</code>, you're able to just add a <code>QFileDialog</code> to construct a window that has a path textfield embedded inside of the dialog. You can paste your path in here.</p> <pre><code>QtGui.QFileDialog.getOpenFileName(self, 'Select file') # For file. </code></pre> <p>For selecting a directory: </p> <pre><code>QtGui.QFileDialog.getExistingDirectory(self, 'Select directory') </code></pre> <p>Each will feature a <strong>path textfield</strong>:</p> <p><a href="http://i.stack.imgur.com/A4CC6.png" rel="nofollow"><img src="http://i.stack.imgur.com/A4CC6.png" alt="enter image description here"></a></p>
1
2016-08-03T14:31:30Z
[ "python", "qt", "pyqt" ]
PyQt - QFileDialog - directly browse to a folder?
38,746,002
<p>Is there any way to directly browse to a folder using QFileDialog?</p> <p>Meaning, instead of double clicking on each folder while navigating to the destination folder, simply enter the path somewhere or use a hotkey like the one (Shift+Command+G) in Finder on Mac OS X.</p> <p>Thanks!</p> <p><strong>EDIT:</strong> (my code)</p> <pre><code> filter = "Wav File (*.wav)" self._audio_file = QtGui.QFileDialog.getOpenFileName(self, "Audio File", "/myfolder/folder", filter) self._audio_file = str(self._audio_file) </code></pre>
2
2016-08-03T14:09:10Z
38,748,766
<p>If you use the static <code>QFileDialog</code> functions, you'll get a <em>native</em> file-dialog, and so you'll be limited to the functionality provided by the platform. You can consult the documentation for your platform to see if the functionality you want is available.</p> <p>If it's not available, you'll have to settle for Qt's <em>built-in</em> file-dialog, and add your own features. For your specific use-case, this should be easy, because the built-in dialog already seems to have what you want. It has a <a href="http://doc.qt.io/qt-4.8/qfiledialog.html#setSidebarUrls" rel="nofollow">side-bar</a> that shows a list of "Places" that the user can navigate to directly. You can set your own places like this:</p> <pre><code>dialog = QtGui.QFileDialog(self, 'Audio Files', directory, filter) dialog.setFileMode(QtGui.QFileDialog.DirectoryOnly) dialog.setSidebarUrls([QtCore.QUrl.fromLocalFile(place)]) if dialog.exec_() == QtGui.QDialog.Accepted: self._audio_file = dialog.selectedFiles()[0] </code></pre>
1
2016-08-03T16:12:32Z
[ "python", "qt", "pyqt" ]
Error: error during read: Connection reset by peer
38,746,042
<p>I have openocd running and am sending a simple reset command to my board. However I am getting this error:</p> <p><strong>Info : accepting 'telnet' connection from 4444</strong></p> <p><strong>Error: error during read: Connection reset by peer</strong></p> <p><strong>Info : dropped 'telnet' connection</strong></p> <p>Here is the basic script. </p> <pre><code>import socket clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) clientsocket.connect(('localhost', 4444)) clientsocket.send('reset') </code></pre> <p>Using the command line <code>nc localhost 4444 &lt;&lt;EOF reset EOF</code> it works fine. So my openocd connection is working</p>
0
2016-08-03T14:10:48Z
38,890,971
<p>Your try using a here document on the command line works fine because the <code>reset</code> command is followed by a <code>\n</code> character, which the <code>send('reset')</code> lacks. Correct: <code>send('reset\n')</code>.</p>
0
2016-08-11T08:21:35Z
[ "python", "sockets", "telnet", "netcat" ]
openpyxl trendline and R-squared value
38,746,053
<p>I'm trying to add "linear" trend-line to my excel chart and display R-squared value using openpyxl, but i cannot find any example. </p> <p>Below is python code that generates chart shown on image without trend-line and R-squared formula <a href="http://i.stack.imgur.com/8H3MH.jpg" rel="nofollow">chart image</a>.</p> <p>Thanks!</p> <pre><code>from openpyxl import Workbook, load_workbook from openpyxl.chart import ( ScatterChart, Reference, Series, ) from openpyxl.chart.trendline import Trendline wb = load_workbook(r"path to load blank workbook\data.xlsx") ws = wb.active rows = [ ['Size', 'Batch 1'], [3, 40], [4, 50], [2, 40], [5, 30], [6, 25], [7, 20], ] for row in rows: ws.append(row) chart = ScatterChart() chart.title = "Scatter Chart" #chart.style = 13 chart.x_axis.title = 'Size' chart.y_axis.title = 'Percentage' xvalues = Reference(ws, min_col=1, min_row=2, max_row=8) for i in range(2, 4): values = Reference(ws, min_col=i, min_row=2, max_row=8) series = Series(values, xvalues, title_from_data=True) chart.series.append(series) line = chart.series[0] line.graphicalProperties.line.noFill = True line.marker.symbol = "circle" ws.add_chart(chart, "A10") wb.save("path to save workbook\scatter.xlsx") </code></pre>
0
2016-08-03T14:11:22Z
38,750,136
<p>It's basically impossible to document all the possibilities for charts so you will occasionally have to dive into the XML of a relevant chart to find out how it's done. That said, trendlines are pretty easy to do.</p> <pre><code>from openpyxl.chart.trendline import Trendline line.trendline = Trendline() </code></pre>
1
2016-08-03T17:27:49Z
[ "python", "excel", "openpyxl" ]
Vectorizing a Nested Loop
38,746,087
<p>I am looking to vectorize a nested loop, which will work on a list of 300,000 lists, with each of these lists containing 3 values. The nested loop compares the values of each of the lists with the corresponding values in the other lists, and will only append the list indices which have corresponding values having a maximum difference of 0.1 between them. Thus, a list containing [0.234, 0.456, 0.567] and a list containing [0.246, 0.479, 0.580] would fall in this category, since their corresponding values (i.e. 0.234 and 0.246; 0.456 and 0.479; 0.567 and 0.580) have a difference of less than 0.1 between them.</p> <p>I currently use the following nested loop to do this, but it would currently take approximately 58 hours to complete (a total of 90 trillion iterations);</p> <pre><code>import numpy as np variable = np.random.random((300000,3)).tolist() out1=list() out2=list() for i in range(0:300000): for j in range(0:300000): if ((i&lt;j) and ((abs(variable[i][0]-variable[j][0]))&lt;0.1) and ((abs(variable[i][1]-variable[j] [1]))&lt;0.1) and ((abs(variable[i][2]-variable[j][2]))&lt;0.1)): out1.append(i) out2.append(j) </code></pre>
5
2016-08-03T14:12:51Z
38,746,251
<p>Convert to NumPy array to make it easier to use NumPy funcs thereafter. Then, two approaches could be suggested. </p> <p><strong>Approach #1</strong></p> <p>NumPy broadcasting could be used to extend those to 3D arrays and perform the operations in a vectorized manner. Thus, we would have an implementation like so -</p> <pre><code>th = 0.1 # Threshold arr = np.asarray(variable) out1,out2 = np.where(np.triu((np.abs(arr[:,None,:] - arr) &lt; th).all(-1),1)) </code></pre> <p><strong>Approach #2</strong></p> <p>Alternative implementation with focus on memory efficiency that uses selective indices that would be responsible for such iterations -</p> <pre><code>th = 0.1 # Threshold arr = np.asarray(variable) R,C = np.triu_indices(arr.shape[0],1) mask = (np.abs(arr[R] - arr[C])&lt;th).all(-1) out1,out2 = R[mask], C[mask] </code></pre>
3
2016-08-03T14:19:34Z
[ "python", "numpy", "vectorization" ]
Vectorizing a Nested Loop
38,746,087
<p>I am looking to vectorize a nested loop, which will work on a list of 300,000 lists, with each of these lists containing 3 values. The nested loop compares the values of each of the lists with the corresponding values in the other lists, and will only append the list indices which have corresponding values having a maximum difference of 0.1 between them. Thus, a list containing [0.234, 0.456, 0.567] and a list containing [0.246, 0.479, 0.580] would fall in this category, since their corresponding values (i.e. 0.234 and 0.246; 0.456 and 0.479; 0.567 and 0.580) have a difference of less than 0.1 between them.</p> <p>I currently use the following nested loop to do this, but it would currently take approximately 58 hours to complete (a total of 90 trillion iterations);</p> <pre><code>import numpy as np variable = np.random.random((300000,3)).tolist() out1=list() out2=list() for i in range(0:300000): for j in range(0:300000): if ((i&lt;j) and ((abs(variable[i][0]-variable[j][0]))&lt;0.1) and ((abs(variable[i][1]-variable[j] [1]))&lt;0.1) and ((abs(variable[i][2]-variable[j][2]))&lt;0.1)): out1.append(i) out2.append(j) </code></pre>
5
2016-08-03T14:12:51Z
38,746,508
<p>Look into scipy.spatial; it has a lot of functionality for solving such spatial queries efficiently; <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.query_pairs.html#scipy.spatial.cKDTree.query_pairs" rel="nofollow">KDTrees</a> in particular, ie:</p> <pre><code>import scipy.spatial out = scipy.spatial.cKDTree(variable).query_pairs(r=0.1, p=np.infinity) </code></pre>
2
2016-08-03T14:30:44Z
[ "python", "numpy", "vectorization" ]
Get attribute using xpath
38,746,090
<p>Given HTML structure like so:</p> <pre><code>&lt;dd itemprop="actors"&gt; &lt;span itemscope="" itemtype="http://schema.org/Person"&gt; &lt;a itemprop="name"&gt;Yumi Kazama&lt;/a&gt;, &lt;/span&gt; &lt;span itemscope="" itemtype="http://schema.org/Person"&gt; &lt;a itemprop="name"&gt;Yuna Mizumoto&lt;/a&gt;, &lt;/span&gt; &lt;span itemscope="" itemtype="http://schema.org/Person"&gt; &lt;a itemprop="name"&gt;Rei Aoki&lt;/a&gt;, &lt;/span&gt; &lt;/dd&gt; </code></pre> <p>How to get all value of <code>a/text()</code>, for the all <code>itemprop="name"</code> element?</p> <p>url:</p> <pre><code>//*[@itemprop='actors']//*[@itemprop='name']/text() </code></pre> <p>is getting only first <code>a/text</code>.</p>
-1
2016-08-03T14:12:58Z
38,751,978
<p>Assuming your html file is <strong>test.html</strong> the following should work:</p> <pre><code>from lxml import html with open(r'E:/backup/GoogleDrive/py/scrapy/test.html', "r") as f: page = f.read() tree = html.fromstring(page) names = tree.xpath("//a[@itemprop='name']//text()") print names </code></pre>
1
2016-08-03T19:19:10Z
[ "python", "xpath", "scrapy" ]
Django WhiteNoise collectstatic repeatedly post-processes CSS files
38,746,109
<p>I am successfully using WhiteNoise in my Django project.</p> <p>My problem is when running the <code>collectstatic</code> command. WhiteNoise post-processes all my .css files, even when they have not changed. It does not unnecessarily post-process .js or .png files, only .css files.</p> <p>This seems like a bug in WhiteNoise. Has anyone else seen this behaviour?</p> <p><strong>An example:</strong></p> <p>The first time I run <code>collectstatic</code>, all of the files are copied by django and post-processed by WhiteNoise:</p> <pre><code>Copying '&lt;path...&gt;.svg' Copying '&lt;path...&gt;.js' Copying '&lt;path...&gt;.css' Copying '&lt;path...&gt;.txt' ... etc ... Post-processed '&lt;path...&gt;.svg' Post-processed '&lt;path...&gt;.js' Post-processed '&lt;path...&gt;.css' Post-processed '&lt;path...&gt;.txt' ... etc ... 77 static files copied to 'C:\&lt;path...&gt;\staticfiles', 77 post-processed. </code></pre> <p>This is all working correctly.</p> <p>But if I immediately run <code>collectstatic</code> again (without modifying any files), WhiteNoise post-processes the .css files again:</p> <pre><code>Post-processed '&lt;path...&gt;.css' Post-processed '&lt;path...&gt;.css' ... etc ... 0 static files copied to 'C:\&lt;path...&gt;\staticfiles', 77 unmodified, 13 post-processed. </code></pre> <p>This is an issue for me because I am considering using WhiteNoise in development as well as in production, to minimise the differences between my development and production environments. Waiting for WhiteNoise to post-process every .css file in the project (including any libraries) whenever I change any file is clearly too much to ask for a development environment.</p> <p>This feels like a bug in WhiteNoise because it correctly notices that the .js and .svg files have not changed, but not the .css files. Has anyone else seen this behaviour?</p>
0
2016-08-03T14:13:41Z
38,748,935
<p>This is a feature of Django, rather than a bug in WhiteNoise: CSS files can contain references to other static files (usually images) and the cache-busting mechanism causes the names of these image files to change whenever their contents change. So the processed output of the CSS file can change even if the original CSS file hasn't, just because one of the images it refers to has changed its content. This is why Django <a href="https://github.com/django/django/blob/4a696bbe13383b14b2762cc5accd45849e9dcfba/django/contrib/staticfiles/storage.py#L200" rel="nofollow">reprocesses</a> the CSS files every time.</p> <p>You don't need to run <code>collectstatic</code> in development to pick up changes to your files however. WhiteNoise follows the standard Django behaviour of serving your unprocessed files directly when the <code>DEBUG</code> setting is True.</p>
1
2016-08-03T16:21:06Z
[ "python", "django", "static-files" ]
Removing objects that have changed from a Python set
38,746,185
<p>Given this program:</p> <pre><code>class Obj: def __init__(self, a, b): self.a = a self.b = b def __hash__(self): return hash((self.a, self.b)) class Collection: def __init__(self): self.objs = set() def add(self, obj): self.objs.add(obj) def find(self, a, b): objs = [] for obj in self.objs: if obj.b == b and obj.a == a: objs.append(obj) return objs def remove(self, a, b): for obj in self.find(a, b): print('removing', obj) self.objs.remove(obj) o1 = Obj('a1', 'b1') o2 = Obj('a2', 'b2') o3 = Obj('a3', 'b3') o4 = Obj('a4', 'b4') o5 = Obj('a5', 'b5') objs = Collection() for o in (o1, o2, o3, o4, o5): objs.add(o) objs.remove('a1', 'b1') o2.a = 'a1' o2.b = 'b1' objs.remove('a1', 'b1') o3.a = 'a1' o3.b = 'b1' objs.remove('a1', 'b1') o4.a = 'a1' o4.b = 'b1' objs.remove('a1', 'b1') o5.a = 'a1' o5.b = 'b1' </code></pre> <p>If I run this a few times with Python 3.4.2, sometimes it will succeed, other times it throws a KeyError after removing 2 or 3 objects:</p> <pre><code>$ python3 py_set_obj_remove_test.py removing &lt;__main__.Obj object at 0x7f3648035828&gt; removing &lt;__main__.Obj object at 0x7f3648035860&gt; removing &lt;__main__.Obj object at 0x7f3648035898&gt; removing &lt;__main__.Obj object at 0x7f36480358d0&gt; $ python3 py_set_obj_remove_test.py removing &lt;__main__.Obj object at 0x7f156170b828&gt; removing &lt;__main__.Obj object at 0x7f156170b860&gt; Traceback (most recent call last): File "py_set_obj_remove_test.py", line 42, in &lt;module&gt; objs.remove('a1', 'b1') File "py_set_obj_remove_test.py", line 27, in remove self.objs.remove(obj) KeyError: &lt;__main__.Obj object at 0x7f156170b860&gt; </code></pre> <p>Is this a bug in Python? Or something about the implementation of sets I don't know about?</p> <p>Interestingly, it seems to always fail at the second <code>objs.remove()</code> call in Python 2.7.9.</p>
1
2016-08-03T14:17:12Z
38,746,264
<p>You are changing the objects (ie changing the objects' hash) <em>after</em> they were added to the set. </p> <p>When <code>remove</code> is called, it can't find that hash in the set because it was changed after it was calculated (when the objects were originally added to the set). </p>
3
2016-08-03T14:19:54Z
[ "python", "python-3.x" ]
Removing objects that have changed from a Python set
38,746,185
<p>Given this program:</p> <pre><code>class Obj: def __init__(self, a, b): self.a = a self.b = b def __hash__(self): return hash((self.a, self.b)) class Collection: def __init__(self): self.objs = set() def add(self, obj): self.objs.add(obj) def find(self, a, b): objs = [] for obj in self.objs: if obj.b == b and obj.a == a: objs.append(obj) return objs def remove(self, a, b): for obj in self.find(a, b): print('removing', obj) self.objs.remove(obj) o1 = Obj('a1', 'b1') o2 = Obj('a2', 'b2') o3 = Obj('a3', 'b3') o4 = Obj('a4', 'b4') o5 = Obj('a5', 'b5') objs = Collection() for o in (o1, o2, o3, o4, o5): objs.add(o) objs.remove('a1', 'b1') o2.a = 'a1' o2.b = 'b1' objs.remove('a1', 'b1') o3.a = 'a1' o3.b = 'b1' objs.remove('a1', 'b1') o4.a = 'a1' o4.b = 'b1' objs.remove('a1', 'b1') o5.a = 'a1' o5.b = 'b1' </code></pre> <p>If I run this a few times with Python 3.4.2, sometimes it will succeed, other times it throws a KeyError after removing 2 or 3 objects:</p> <pre><code>$ python3 py_set_obj_remove_test.py removing &lt;__main__.Obj object at 0x7f3648035828&gt; removing &lt;__main__.Obj object at 0x7f3648035860&gt; removing &lt;__main__.Obj object at 0x7f3648035898&gt; removing &lt;__main__.Obj object at 0x7f36480358d0&gt; $ python3 py_set_obj_remove_test.py removing &lt;__main__.Obj object at 0x7f156170b828&gt; removing &lt;__main__.Obj object at 0x7f156170b860&gt; Traceback (most recent call last): File "py_set_obj_remove_test.py", line 42, in &lt;module&gt; objs.remove('a1', 'b1') File "py_set_obj_remove_test.py", line 27, in remove self.objs.remove(obj) KeyError: &lt;__main__.Obj object at 0x7f156170b860&gt; </code></pre> <p>Is this a bug in Python? Or something about the implementation of sets I don't know about?</p> <p>Interestingly, it seems to always fail at the second <code>objs.remove()</code> call in Python 2.7.9.</p>
1
2016-08-03T14:17:12Z
38,746,268
<p>This is not a bug in Python, your code is violating a principle of sets: that the <em>hash value must not change</em>. By mutating your object attributes, the hash changes and the set can no longer reliably locate the object in the set.</p> <p>From the <a href="https://docs.python.org/3/reference/datamodel.html#object.__hash__" rel="nofollow"><code>__hash__</code> method documentation</a>:</p> <blockquote> <p>If a class defines mutable objects and implements an <code>__eq__()</code> method, it should not implement <code>__hash__()</code>, since the implementation of hashable collections requires that a key’s hash value is immutable (if the object’s hash value changes, it will be in the wrong hash bucket).</p> </blockquote> <p>Custom Python classes define a default <code>__eq__</code> method that returns True when both operands reference the same object (<code>obj1 is obj2</code> is true).</p> <p>That it <em>sometimes</em> works in Python 3 is a property of <a href="https://docs.python.org/3/using/cmdline.html#cmdoption-R" rel="nofollow">hash randomisation</a> for strings. Because the hash value for a string changes between Python interpreter runs, and because the modulus of a hash against the size of the hash table is used, you <em>can</em> end up with the right hash slot anyway, purely by accident, and then the <code>==</code> equality test will still be true because you didn't implement a custom <code>__eq__</code> method.</p> <p>Python 2 has hash randomisation too but it is disabled by default, but you could make your test 'pass' anyway by carefully picking the 'right' values for the <code>a</code> and <code>b</code> attributes.</p> <p>Instead, you could make your code work by basing your hash on the <code>id()</code> of your instance; that makes the hash value not change and would match the default <code>__eq__</code> implementation:</p> <pre><code>def __hash__(self): return hash(id(self)) </code></pre> <p>You could also just <em>remove</em> your <code>__hash__</code> implementation for the same effect, as the default implementation does basically the above (with the <code>id()</code> value rotated by 4 bits to evade memory alignment patterns). Again, from the <code>__hash__</code> documentation:</p> <blockquote> <p>User-defined classes have <code>__eq__()</code> and <code>__hash__()</code> methods by default; with them, all objects compare unequal (except with themselves) and <code>x.__hash__()</code> returns an appropriate value such that <code>x == y</code> implies both that <code>x is y</code> and <code>hash(x) == hash(y)</code>.</p> </blockquote> <p>Alternatively, implement an <code>__eq__</code> method that bases equality on equality of the attributes of the instance, and <em>don't mutate the attributes</em>.</p>
5
2016-08-03T14:20:03Z
[ "python", "python-3.x" ]
Python: use of same IV for encryption and decryption in AES
38,746,213
<p>I struggle to understand the correct use of an IV (Initialization Vector) when encrypting data in AES.</p> <p>Precisely, I'm not sure where to store my randomly generated IV: in my script, the data will be encrypted, then saved to a file, then the program will terminate. During the next session, the previously saved data must be decrypted. If my understanding of IVs is correct, I have to use the same IV for decryption as for encryption (but another random-IV for every single encryption process). Thus, I have to store the IV somewhere - some people recommend prepending it to the encrypted data, but if I get it right that won't work in my case, because I need the IV <em>in order</em> to be able to decrypt it. </p> <p>Is this correct or did I misunderstand something? I want to avoid saving the encrypted/hashed key and the IV (even if hashed itself) inside some unencrypted plain-text-settings-file or something.</p>
0
2016-08-03T14:18:27Z
38,746,551
<p>The IV itself is not sensitive data; its just used to scramble the state of the first cipher-text block and the scrambling is not recoverable from the IV itself (the key adds in the "secret" factor). </p> <p>For "proper" chaining modes the IV is separate from the cipher text (you need the initial IV for both encryption and decryption) and must be stored separately and passed separately to the crypto library API. After encryption you can store the IV however you like - just don't lose it ;).</p> <p>You can certainly "prepend" / "append" to the cipher text so you only have to store a single blob of data - but you'll just have to split it off prior to decryption as that is what the API will expect.</p> <p>The "unproper" way to do an IV (e.g. if your crypto library API doesn't have native IV support, but does support chaining) is just to prepend a single block of random data to the plaintext before encrypting it. In this case there isn't any IV to store separately - you simply encrypt the entire IV+message binary pair - and then you simply delete the first block of data after decrypting it. The "random data" you prepend has the same constraints as a real IV (don't reuse the same random data with the same key, etc).</p> <p>The two approaches are semantically different at the API level, but the effect on the actual encryption is the same (scamble the first block of real payload unpredictably).</p> <p>In terms of how the IV is used - there are many possible schemes. See the wikipedia article on block chaining here for a convenient picture showing how the IV can be used in various chaining modes when it is really store separately. </p> <p><a href="https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation" rel="nofollow">https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation</a></p>
-2
2016-08-03T14:32:33Z
[ "python", "encryption", "aes", "initialization-vector" ]
Python Celery subtask group not executing
38,746,257
<p>I'm trying to use Celery to handle background tasks. I currently have the following setup:</p> <pre><code>@app.task def test_subtask(id): print('test_st:', id) @app.task def test_maintask(): print('test_maintask') g = group(test_subtask.s(id) for id in range(10)) g.delay() </code></pre> <p><code>test_maintask</code> is scheduled to execute every <em>n</em> seconds, which works (I see the print statement appearing in the command line window where I started the worker). What I'm trying to do is have this scheduled task spawn a series of subtasks, which I've grouped here using <code>group()</code>.</p> <p>It seems, however, like none of the <code>test_subtask</code> tasks are being executed. What am I doing wrong? I don't have any timing/result constraints for these subtasks and just want them to happen some time from now, asynchronously, in no particular order. <em>n</em> seconds later, <code>test_maintask</code> will fire again (and again) but with none of the subtasks executing.</p> <p>I'm using one worker, one beat, and AMQP as a broker (on a separate machine).</p> <p><strong>EDIT</strong>: For what it's worth, the problem seems to be purely because of one task calling another (and not something because of the main task being scheduled). If I call the main task manually:</p> <pre><code>celery_funcs.test_maintask.delay() </code></pre> <p>I see the main task's print statement but -- again -- not the subtasks. Calling a subtask directly does work however:</p> <pre><code>celery_funcs.test_subtask.delay(10) </code></pre>
0
2016-08-03T14:19:42Z
38,752,053
<p>Sigh... just found out the answer, I used the following to configure my Celery app:</p> <pre><code>app = Celery('celery_app', broker='&lt;my_broker_here&gt;') </code></pre> <p>Strangely enough, this is not being picked up in the task itself... that is, </p> <pre><code>print('test_maintask using broker', app.conf.BROKER_URL, current_app.conf.BROKER_URL) </code></pre> <p>Gives back <code>'&lt;my_broker_here&gt;'</code> and <code>None</code> respectively, causing the group to be send of to... some default broker (I guess?).</p> <p>Adding <code>BROKER_URL</code> to <code>app.conf.update</code> does the trick, though I'm still not completely clear on what's going on in Celery's internals here...</p>
0
2016-08-03T19:24:38Z
[ "python", "celery" ]
Why is this xpath expression not working?
38,746,273
<p>Scrapy is a web crawler and I have created a spider. I want the spider to create 2 html files with the body of the 2 links. The html files created are empty.</p> <pre><code> import scrapy from scrapy.selector import Selector from scrapy.http import HtmlResponse class DmozSpider(scrapy.Spider): name = "dmoz" allowed_domains = ["dmoz.org"] start_urls = [ "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/", "http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/" ] def parse(self, response): x=response.xpath("//body/text()").extract() filename = response.url.split("/")[-2] + '.html' with open(filename, 'wb') as f: f.write(x) </code></pre>
-4
2016-08-03T14:20:10Z
38,746,874
<p>Please revisit the <a href="http://doc.scrapy.org/en/1.1/intro/tutorial.html" rel="nofollow">Scrapy tutorial</a> and double-check; your example is basically a verbatim copy of <code>dmoz_spider.py</code>.</p> <p>First of all, note that <code>xpath()</code> returns a selector list. Calling <code>extract()</code> on the selector list gives you a list of unicode strings, which you can't write into a file as is. You need to join the strings and encode the result (e.g. using UTF-8).</p> <pre><code>with open(filename, 'wb') as f: f.write(u"".join(x).encode("UTF-8")) </code></pre> <p>As to why it's not working now: You use an XPath expression to select all text nodes of the body element. As the text nodes only contain whitespace characters, the created files appear to be empty.</p> <p>The result of <code>response.xpath("//body/text()").extract()</code> is <code>[u'\r\n\r\n ', u'\r\n\r\n ', u'\r\n\r\n ', u'\r\n\r\n ', u'\r\n\r\n ', u'\r\n\r\n ', u'\r\n\r\n ', u'\r\n ', u'\r\n ', u'\r\n\r\n ', u'\r\n\r\n ', u'\r\n\r\n ', u'\r\n\r\n ', u'\r\n\r\n ', u'\r\n\r\n ']</code>, so your files should contain some whitespace characters.</p> <p>To select all nodes below the body element, use <code>response.xpath("//body/node())</code>.</p> <p>To e.g. select all <code>div</code> elements having the class <code>hero</code>, use <code>response.xpath("//div[@class = 'hero']")</code>.</p> <p>And perhaps you should first read some basic tutorial on XPath. Learning by doing will not work here, you really need to get the basics straight first.</p>
-1
2016-08-03T14:45:35Z
[ "python", "xpath", "scrapy" ]
Ansible mysql_user with Percona 57 and RHEL7
38,746,361
<p>I am trying to use ansible mysql_user module on RHEL7 with Percona 57 though but it fails on</p> <blockquote> <p>the python mysqldb module is required</p> </blockquote> <p>I have installed full Percona 57 I`ve also tried to install yum install MySQL-python. (1.2.3) but in Python when i try to import MySQLdb i get</p> <blockquote> <p>ImportError: libmysqlclient.so.18: cannot open shared object file: No such file or directory</p> </blockquote> <p>pip install MySQL-python fails on error (1.2.5)</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>unable to execute gcc: No such file or directory error: command 'gcc' failed with exit status 1 ---------------------------------------- Command "/usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-build-_9GWXZ/MySQL-python/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-rmYnmt-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-_9GWXZ/MySQL-python</code></pre> </div> </div> </p> <p>Anybody other had that problem ?</p>
0
2016-08-03T14:24:17Z
38,758,674
<p>so finally i've found out it was SELinux blocking ports >&lt;</p>
0
2016-08-04T04:48:39Z
[ "python", "mysql", "ansible", "percona", "rhel7" ]
Most efficient way to write to file conditionally?
38,746,421
<p>I would like to write a string to a file only if it's not presently in the file.</p> <p>My first thought was to do something like this, however it's not writing anything to the file.</p> <pre><code>with open("FILE PATH", "a+") as database: for lines in database.read(): if 'MY STRING' in lines: continue else: database.write('MY STRING') </code></pre> <p>Firstly, what am I doing wrong here? Secondly, assuming this was functioning properly, would there be a more efficient way to do this? I am assuming there is.</p> <p>Thanks</p>
1
2016-08-03T14:26:44Z
38,746,697
<p>Using <code>database.read()</code> will read your text file and return a single string containing the entire file. Looping over this string will return each character within that string individually, so you won't find <code>'MY STRING'</code> in it. Simply look for <code>'MY STRING'</code> within the file as a whole like so:</p> <pre><code>with open("FILE PATH", "a+") as database: if 'MY STRING' not in database.read(): database.write('MY STRING') </code></pre> <p>You don't need the first <code>if</code> statement seeing as it's only a <code>continue</code>, like this you only have one <code>if</code>, making it a little more efficient.</p>
1
2016-08-03T14:38:19Z
[ "python" ]
How come when I import of two functions from the same module, the import works only for one the two?
38,746,450
<p><strong>Intro</strong><br> I am running a python script on an cluster. I run everything in virtualenv and in the code I am importing two functions from the same module (written in SC_module.py):</p> <p>ex. SC_module.py</p> <pre><code>def funA(): def funB(): </code></pre> <p>In the script script.py I have the following import</p> <pre><code>from SC_module import funA,funB </code></pre> <p>when I run the code on the HPC I get import error funB cannot be found. If I type</p> <pre><code>from SC_module import funA </code></pre> <p>everything works fine. If I run <code>python3</code> from the command line and run </p> <pre><code>from SC_module import funA,funB </code></pre> <p>everything works and fun(B) is imported.</p> <p><strong>Question</strong><br> The only difference between funA() and funB() is that have been coded in two different days.<br> <em>NB</em>: If I add an new function to the module it will not be loaded when starting the process but will be imported if I will use the terminal. Is there something I miss in the loading of the module in the cluster?</p> <p>Thanks</p>
-1
2016-08-03T14:27:53Z
38,747,175
<p>Remove file: <code>SC_module.pyc</code>, and try run it again.</p>
0
2016-08-03T14:59:27Z
[ "python", "virtualenv", "hpc" ]
How come when I import of two functions from the same module, the import works only for one the two?
38,746,450
<p><strong>Intro</strong><br> I am running a python script on an cluster. I run everything in virtualenv and in the code I am importing two functions from the same module (written in SC_module.py):</p> <p>ex. SC_module.py</p> <pre><code>def funA(): def funB(): </code></pre> <p>In the script script.py I have the following import</p> <pre><code>from SC_module import funA,funB </code></pre> <p>when I run the code on the HPC I get import error funB cannot be found. If I type</p> <pre><code>from SC_module import funA </code></pre> <p>everything works fine. If I run <code>python3</code> from the command line and run </p> <pre><code>from SC_module import funA,funB </code></pre> <p>everything works and fun(B) is imported.</p> <p><strong>Question</strong><br> The only difference between funA() and funB() is that have been coded in two different days.<br> <em>NB</em>: If I add an new function to the module it will not be loaded when starting the process but will be imported if I will use the terminal. Is there something I miss in the loading of the module in the cluster?</p> <p>Thanks</p>
-1
2016-08-03T14:27:53Z
38,748,821
<p>I suggest that you print out your import path list and check that they match what you think they are, in both environments:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; for d in sys.path: ... print d </code></pre> <p>Plus: </p> <pre><code>import SC_module print dir(SC_module) </code></pre> <p>to see what functions are in the imported module.<br> There must be a mismatch somewhere!</p>
0
2016-08-03T16:15:03Z
[ "python", "virtualenv", "hpc" ]
Django: 'BaseTable' object does not support indexing
38,746,460
<p>I'm migrating my project to Django 1.8 and I am receiving an error related to 'johnny cache. Specifically in 'johnny/cache.py/'.</p> <p><strong>Error:</strong> lib/python2.7/site-packages/johnny/cache.py", line 87, in get_tables_for_query tables = set([v[0] for v in getattr(query, 'alias_map', {}).values()])</p> <p><strong>TypeError: 'BaseTable' object does not support indexing</strong></p> <p>I have included my code below for the function where the error is originating from. Advice no whether I should use something other than 'johnny -cache' for caching would be helpful and/or info as to what is the meaning of this error and how to fix it. Thank you!</p> <pre><code>def get_tables_for_query(query): """ Takes a Django 'query' object and returns all tables that will be used in that query as a list. Note that where clauses can have their own querysets with their own dependent queries, etc. """ from django.db.models.sql.where import WhereNode, SubqueryConstraint from django.db.models.query import QuerySet tables = set([v[0] for v in getattr(query, 'alias_map', {}).values()]) def get_sub_query_tables(node): query = node.query_object if not hasattr(query, 'field_names'): query = query.values(*node.targets) else: query = query._clone() query = query.query return set([v[0] for v in getattr(query, 'alias_map',{}).values()]) def get_tables(node, tables): if isinstance(node, SubqueryConstraint): return get_sub_query_tables(node) for child in node.children: if isinstance(child, WhereNode): # and child.children: tables = get_tables(child, tables) elif not hasattr(child, '__iter__'): continue else: for item in (c for c in child if isinstance(c, QuerySet)): tables += get_tables_for_query(item.query) return tables if query.where and query.where.children: where_nodes = [c for c in query.where.children if isinstance(c, (WhereNode, SubqueryConstraint))] for node in where_nodes: tables += get_tables(node, tables) return list(set(tables)) </code></pre>
0
2016-08-03T14:28:28Z
38,748,073
<p>Found your problem when I looked a bit further into your library.</p> <p>From the <a href="https://pythonhosted.org/johnny-cache/" rel="nofollow">Johnny Cache documentation</a>:</p> <blockquote> <p>It works with Django 1.1 thru 1.4 and python 2.4 thru 2.7.</p> </blockquote> <p>From your question:</p> <blockquote> <p>I'm migrating my project to Django 1.8.</p> </blockquote> <p>In fact, it looks like the library you're using is woefully out of date and no longer maintained:</p> <blockquote> <p>Latest commit d96ea94 on Nov 10, 2014</p> </blockquote>
1
2016-08-03T15:38:28Z
[ "python", "django", "indexing", "django-1.8", "django-johnny-cache" ]
How to correctly install pyinstaller
38,746,462
<p>I have attempted to install pyinstaller (on Ubuntu 16.0.4) using pip:</p> <pre><code>pip3 install pyinstaller Collecting pyinstaller Using cached PyInstaller-3.2.tar.gz Collecting setuptools (from pyinstaller) Using cached setuptools-25.1.3-py2.py3-none-any.whl Building wheels for collected packages: pyinstaller Running setup.py bdist_wheel for pyinstaller ... done Stored in directory: /home/.../.cache/pip/wheels/fc/b3/10/006225b1c1baa34750a7b587d3598d47d18114c06b696a8e0e Successfully built pyinstaller Installing collected packages: setuptools, pyinstaller Successfully installed pyinstaller setuptools-20.7.0 You are using pip version 8.1.1, however version 8.1.2 is available. You should consider upgrading via the 'pip install --upgrade pip' command. </code></pre> <p>However, if I then try to call <code>pyinstaller</code> I get the error <code>pyinstaller: command not found</code></p> <p>Why am I unable to run pyinstaller when the pip install appears to have been successful.</p>
0
2016-08-03T14:28:29Z
38,747,467
<p>You may check if your PATH contains site-packages directory.</p> <p>In Windows, this is the path.</p> <p><strong>C:\Python27\Lib\site-packages.</strong> </p> <p>You can do the equivalent for ubuntu. Let me know if it works.</p>
-1
2016-08-03T15:12:54Z
[ "python", "pip", "pyinstaller" ]
How to correctly install pyinstaller
38,746,462
<p>I have attempted to install pyinstaller (on Ubuntu 16.0.4) using pip:</p> <pre><code>pip3 install pyinstaller Collecting pyinstaller Using cached PyInstaller-3.2.tar.gz Collecting setuptools (from pyinstaller) Using cached setuptools-25.1.3-py2.py3-none-any.whl Building wheels for collected packages: pyinstaller Running setup.py bdist_wheel for pyinstaller ... done Stored in directory: /home/.../.cache/pip/wheels/fc/b3/10/006225b1c1baa34750a7b587d3598d47d18114c06b696a8e0e Successfully built pyinstaller Installing collected packages: setuptools, pyinstaller Successfully installed pyinstaller setuptools-20.7.0 You are using pip version 8.1.1, however version 8.1.2 is available. You should consider upgrading via the 'pip install --upgrade pip' command. </code></pre> <p>However, if I then try to call <code>pyinstaller</code> I get the error <code>pyinstaller: command not found</code></p> <p>Why am I unable to run pyinstaller when the pip install appears to have been successful.</p>
0
2016-08-03T14:28:29Z
38,748,447
<p><code>pyinstaller</code> appears to have installed correctly, but the command is not available on <code>PATH</code>. You need to locate where the executable was placed. This will depend on your system configuration, if you're using virtualenv, and other system and usage dependent factors.</p> <p>One thing you could try is using <code>find</code> to locate the executable:</p> <pre><code>sudo find / -name pyinstaller </code></pre> <p>This recursively looks for a file named <code>pyinstaller</code>, starting at the root of the file system. If you have some idea where the executable may have been placed, you can narrow the search to that directory.</p> <p>Once you have the absolute path of the executable, you can either call it directly:</p> <pre><code>/my/path/to/pyinstaller </code></pre> <p>Or if you're not using virtualenv or anything, you could modify <code>PATH</code> to include the executable's parent directory:</p> <pre><code>$PATH = $PATH:/my/path/to </code></pre> <p>If you want to make that change permanent, you need to <a href="http://unix.stackexchange.com/q/117467/84908">modify a script somewhere</a>.</p>
0
2016-08-03T15:56:38Z
[ "python", "pip", "pyinstaller" ]
Create variations of a string
38,746,525
<p>I generated random strings of 16-characters each and added them to a list using the following:</p> <pre><code>import random strings = [] for x in range(0, 99): strings.append(''.join(random.choice('0123456789ABCDEF') for i in range(16))) </code></pre> <p>This worked as expected. Now, for each generated string, I want to find all possible combinations such that at least two characters remain same as the original string and the order of characters does not change. For example, if we have CDD733665417E3F1, then I want to generate all CDXXXXXXXXXXXXXX where X could be anything (0-9 or A-F). Similarly XXD7XXXXXXXXXXXX and so on. Previous similar questions hint towards using <code>itertools.product</code> but I am not sure how it can be used to generate permutations and not fixed replacements. Any help will be appreciated. Thank you</p>
0
2016-08-03T14:31:30Z
38,747,794
<p>Create an iterator for the indices of the two characters you want to stay the same using <code>itertools.combinations</code></p> <pre><code>&gt;&gt;&gt; from itertools import combinations &gt;&gt;&gt; s = 'ABC123' &gt;&gt;&gt; for indices in combinations(range(len(s)), 2): ... print ''.join([s[x] if x in indices else 'X' for x in range(len(s))]) ... ABXXXX AXCXXX AXX1XX AXXX2X AXXXX3 XBCXXX XBX1XX XBXX2X XBXXX3 XXC1XX XXCX2X XXCXX3 XXX12X XXX1X3 XXXX23 </code></pre> <p>Creates all the variable strings.</p> <p>You can then do a nested loop to replace the <code>X</code>'s.</p> <p>Then you can use <code>product</code> to get all the letters that you would need to replace the <code>X</code>'s with:</p> <pre><code>&gt;&gt;&gt; for letters in product('ABCDEF0123456789', repeat = 4): ... print letters ... ('A', 'A', 'A', 'A') ('A', 'A', 'A', 'B') ('A', 'A', 'A', 'C') ('A', 'A', 'A', 'D') ('A', 'A', 'A', 'E') ('A', 'A', 'A', 'F') ('A', 'A', 'A', '0') ('A', 'A', 'A', '1') ('A', 'A', 'A', '2') ('A', 'A', 'A', '3') ('A', 'A', 'A', '4') ('A', 'A', 'A', '5') ('A', 'A', 'A', '6') ('A', 'A', 'A', '7') ('A', 'A', 'A', '8') ('A', 'A', 'A', '9') ('A', 'A', 'B', 'A') ('A', 'A', 'B', 'B') ('A', 'A', 'B', 'C') ('A', 'A', 'B', 'D') ('A', 'A', 'B', 'E') ('A', 'A', 'B', 'F') ('A', 'A', 'B', '0') ('A', 'A', 'B', '1') ('A', 'A', 'B', '2') . . . </code></pre> <p>Combine these together and you would get all the combinations of what you want.</p> <p>You can probably do something like:</p> <pre><code>&gt;&gt;&gt; for indices in combinations(range(len(s)), 2): ... for letters in product('ABCDEF0123456789', repeat = 4): ... letter_iter = iter(letters) ... print ''.join([s[x] if x in indices else letter_iter.next() for x in range(len(s))]) </code></pre> <p>NOTE 1: you can change the <code>2</code> in the call of <code>combinations</code> to change the amount of indices you want to stay the same. Likewise, you can change the <code>repeat</code> parameter in the call to product to reflect those changes (<code>repeat = n</code> where <code>n = len(s) - number_in_combinations</code>)</p> <p>NOTE 2: These are stupidly large amounts of values. You know this. Please be careful that you don't destroy your memory. When I did the <code>product</code> call, I added an index counter and broke the loop after the index counter got greater than 20 to avoid hell breaking loose.</p>
1
2016-08-03T15:26:42Z
[ "python", "string", "itertools" ]
Automatic Code Update for Exception Handling in Python
38,746,545
<p>This older syntax was removed in Python 3:</p> <pre><code>try: ... except MyException, exc: # Don't do that! ... </code></pre> <p>New</p> <pre><code>try: ... except MyException as exc: ... </code></pre> <p>I checked how many times the old syntax gets used in the code I work on:</p> <pre><code>find */* -name '*.py'|xargs grep 'except.*,.*:'| wc -l 551 </code></pre> <p>Wow, that's a lot</p> <p>Is there a way to automated this particular Python2 to Python3 update?</p>
0
2016-08-03T14:32:26Z
38,746,546
<p>... answering my own question. I found the <code>futurize</code> from <a href="http://python-future.org/automatic_conversion.html" rel="nofollow">python-future</a>:</p> <pre><code>futurize --write --nobackups --fix lib2to3.fixes.fix_except src/mylib/ </code></pre> <p>It supports a lot of other fixes, but today I want to focus in the exception handling.</p> <p>It works well and saves me a lot of time :-)</p>
1
2016-08-03T14:32:26Z
[ "python", "python-3.x" ]
Reading from a file deletes the last letter of the last string in the document?
38,746,561
<p>I am writing code which take a .txt doc and stores each word on each line of that .txt file in a list of strings. However my code decides it wants to delete the last letter of the last string for some random reason, can anyone tell me why?</p> <p>My code: </p> <pre><code>import sys listofStr = [] print (" ") fname = input("Please enter file name: ") print (" ") try : f = open(fname) myLine = f.readline() tuplist = [] while (len(myLine)&gt;0) : strings = myLine[:-1] listofStr.append(strings) myLine = f.readline() f.close() except IOError as e : print("Problem opening file (Remember the file extension '.txt')") sys.exit() print(listofStr) </code></pre> <p>when ran:</p> <pre><code>Please enter file name: test.txt ['TEST', 'WAS', 'VERY', 'SUCCESSFU'] </code></pre> <p>expected outcome:</p> <pre><code>['TEST','WAS','VERY','SUCCESSFUL'] </code></pre>
1
2016-08-03T14:33:08Z
38,746,592
<p>The last line doesn't have a linebreak in it, so when you do</p> <pre><code> strings = myLine[:-1] </code></pre> <p>you strip off the last char in the line, no matter what it is, and you kill off an actual character.</p>
1
2016-08-03T14:34:26Z
[ "python", "file", "python-3.x" ]
Reading from a file deletes the last letter of the last string in the document?
38,746,561
<p>I am writing code which take a .txt doc and stores each word on each line of that .txt file in a list of strings. However my code decides it wants to delete the last letter of the last string for some random reason, can anyone tell me why?</p> <p>My code: </p> <pre><code>import sys listofStr = [] print (" ") fname = input("Please enter file name: ") print (" ") try : f = open(fname) myLine = f.readline() tuplist = [] while (len(myLine)&gt;0) : strings = myLine[:-1] listofStr.append(strings) myLine = f.readline() f.close() except IOError as e : print("Problem opening file (Remember the file extension '.txt')") sys.exit() print(listofStr) </code></pre> <p>when ran:</p> <pre><code>Please enter file name: test.txt ['TEST', 'WAS', 'VERY', 'SUCCESSFU'] </code></pre> <p>expected outcome:</p> <pre><code>['TEST','WAS','VERY','SUCCESSFUL'] </code></pre>
1
2016-08-03T14:33:08Z
38,746,656
<p>You are missing the final newline on your file, so the <code>strings = myLine[:-1]</code> removes the final character. If you replace this with <code>strings = myLine.rstrip()</code> that will remove any trailing whitespace on the line but won't remove that final character.</p>
1
2016-08-03T14:37:05Z
[ "python", "file", "python-3.x" ]
Reading from a file deletes the last letter of the last string in the document?
38,746,561
<p>I am writing code which take a .txt doc and stores each word on each line of that .txt file in a list of strings. However my code decides it wants to delete the last letter of the last string for some random reason, can anyone tell me why?</p> <p>My code: </p> <pre><code>import sys listofStr = [] print (" ") fname = input("Please enter file name: ") print (" ") try : f = open(fname) myLine = f.readline() tuplist = [] while (len(myLine)&gt;0) : strings = myLine[:-1] listofStr.append(strings) myLine = f.readline() f.close() except IOError as e : print("Problem opening file (Remember the file extension '.txt')") sys.exit() print(listofStr) </code></pre> <p>when ran:</p> <pre><code>Please enter file name: test.txt ['TEST', 'WAS', 'VERY', 'SUCCESSFU'] </code></pre> <p>expected outcome:</p> <pre><code>['TEST','WAS','VERY','SUCCESSFUL'] </code></pre>
1
2016-08-03T14:33:08Z
38,746,677
<p>Change this:</p> <pre><code>while (len(myLine)&gt;0) : strings = myLine[:-1] listofStr.append(strings) myLine = f.readline() </code></pre> <p>to this:</p> <pre><code>while myLine.strip() : strings = myLine.strip() listofStr.append(strings) myLine = f.readline() </code></pre>
1
2016-08-03T14:37:45Z
[ "python", "file", "python-3.x" ]
Reading from a file deletes the last letter of the last string in the document?
38,746,561
<p>I am writing code which take a .txt doc and stores each word on each line of that .txt file in a list of strings. However my code decides it wants to delete the last letter of the last string for some random reason, can anyone tell me why?</p> <p>My code: </p> <pre><code>import sys listofStr = [] print (" ") fname = input("Please enter file name: ") print (" ") try : f = open(fname) myLine = f.readline() tuplist = [] while (len(myLine)&gt;0) : strings = myLine[:-1] listofStr.append(strings) myLine = f.readline() f.close() except IOError as e : print("Problem opening file (Remember the file extension '.txt')") sys.exit() print(listofStr) </code></pre> <p>when ran:</p> <pre><code>Please enter file name: test.txt ['TEST', 'WAS', 'VERY', 'SUCCESSFU'] </code></pre> <p>expected outcome:</p> <pre><code>['TEST','WAS','VERY','SUCCESSFUL'] </code></pre>
1
2016-08-03T14:33:08Z
38,746,689
<p>You're slicing the last line which doesn't have the newline character:</p> <pre><code>strings = myLine[:-1] </code></pre> <p>To fix this you can just manually go to your file and append an extra line. Or change said line to <code>strings = myLine.strip()</code>. There is no need to slice the string manually since <code>strip</code> will handle whitespace and newlines.</p>
2
2016-08-03T14:38:03Z
[ "python", "file", "python-3.x" ]
Using variables from other python files
38,746,578
<p>I'm having some problems with this:</p> <p>I have two files: random and random2</p> <p>random has this:</p> <pre><code> import random2 print(random2.verb_list) print(random2.x) </code></pre> <p>random2 has this:</p> <pre><code> verb_list = ['x', 'y', 'z'] other_list = ['1', '2', '3'] something_else = False def Main(): global x x = 1 print(verb_list) if __name__ == "__main__": Main() </code></pre> <p>It gives me this error when I run random:</p> <pre><code>AttributeError: module 'random2' has no attribute 'x' </code></pre> <p>Is there a way so I can call the variable x in random? I have python3</p>
-1
2016-08-03T14:33:59Z
38,747,012
<p>The variable <code>x</code> is not created until the <code>Main()</code> function is run. Importing a module means that <code>__name__</code> isn't set to <code>__main__</code>, so the function is never executed.</p> <p>You must execute the Main() function. Put <code>random2.Main()</code> in the file <code>random.py</code> after the import line. </p> <p>The name <code>random</code> is a very poor name for a module, since it collides with the standard python <code>random</code> module. It can create unexpected side effects.</p>
1
2016-08-03T14:51:49Z
[ "python" ]
pyplot axes title not showing
38,746,759
<p>I have written this code to check object bounding box but when I give <code>title</code> to the <code>axes</code>, it doesn't show up. (I was going to give the file number as title).</p> <pre><code>#!/home/ckim/anaconda2/bin/python #%pylab import os.path as osp import sys import cv2 import matplotlib import matplotlib.pyplot as plt import matplotlib.patches as patches def add_path(path): if path not in sys.path: sys.path.insert(0, path) def move_figure(f, x, y): backend = matplotlib.get_backend() f.canvas.manager.window.move(x,y) plt.show() # Add lib to PYTHONPATH lib_path = osp.join('/home/ckim/Neuro/py-faster-rcnn/', 'lib') add_path(lib_path) import datasets import datasets.pascal_voc as pv #plt.ion() fig, ax = plt.subplots(figsize=(8,8)) im = cv2.imread(osp.join('/home/ckim/Neuro/py-faster-rcnn/data/VOCdevkit2007/VOC2007/JPEGImages/', '{0:06d}'.format(eval(sys.argv[1])) + '.jpg')) #im = cv2.imread(osp.join('000005.jpg')) im = im[:, :, (2, 1, 0)] ax.imshow(im, aspect='equal') #res = pv._load_pascal_annotation(sys.argv[1]) d = datasets.pascal_voc('trainval', '2007') res = d._load_pascal_annotation('{0:06d}'.format(eval(sys.argv[1]))) # return {'boxes' : boxes, # 'gt_classes': gt_classes, # 'gt_overlaps' : overlaps, # 'flipped' : False} for i in range(len(res['boxes'])): x1 = res['boxes'][i][0] y1 = res['boxes'][i][1] x2 = res['boxes'][i][2] y2 = res['boxes'][i][3] ax.add_patch(patches.Rectangle((x1,y1), x2-x1, y2-y1, fill=False, edgecolor='red', linewidth=1.5)) ax.text(x1, y1 - 5, '{:s}'.format(d._classes[res['gt_classes'][i]]), \ bbox=dict(facecolor='blue', alpha=0.5), fontsize=14, color='white') #thismanager = get_current_fig_manager() #thismanager.window.SetPosition((500, 0)) #thismanager.window.wm_geometry("+500+0") move_figure(fig, 500, 500) #fig.show() #fig.suptitle("Title x") ax.set_title("Title x") plt.pause(0) </code></pre> <p><a href="http://i.stack.imgur.com/CsHDw.png" rel="nofollow"><img src="http://i.stack.imgur.com/CsHDw.png" alt="enter image description here"></a> To test what is the problem, I reduced the code to below, but this abridged version works either for graph plot (case 1) and image display (case 2). I can't find the difference from above code. Could anyone tell me what has gone wrong in above code? (about title now showing)</p> <pre><code>#!/home/ckim/anaconda2/bin/python import cv2 import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(8,8)) # case 1 : plot #ax.plot([1,2,3,4],[1,4,9,16]) # case 2 : image display im = cv2.imread('000005.jpg') im = im[:, :, (2, 1, 0)] ax.imshow(im, aspect='equal') ax.set_title("Title x") plt.pause(0) </code></pre> <p><a href="http://i.stack.imgur.com/wtvvn.png" rel="nofollow"><img src="http://i.stack.imgur.com/wtvvn.png" alt="enter image description here"></a></p>
0
2016-08-03T14:40:55Z
38,748,790
<p>There is a call to <code>plt.show()</code> in <code>move_figure</code> which means the figure is shown. As this is a <a href="http://matplotlib.org/faq/howto_faq.html#use-show" rel="nofollow">blocking command</a>, no further code will be run until you close this figure. As a result, the title is not set until the figure has disappeared. If you swap the last few lines of you first code as follows,</p> <pre><code>ax.set_title("Title x") move_figure(fig, 500, 500) plt.pause(0) </code></pre> <p>the title should appear. Alternatively, I'd suggest removing <code>plt.show</code> from <code>move_figure</code> so you can show when you want or <code>savefig</code> etc later on.</p>
0
2016-08-03T16:13:37Z
[ "python", "matplotlib", "pycaffe" ]
concurrent.futures.ThreadPoolExecutor max_workers can't be 0
38,746,782
<p>If I spin up a <code>ThreadPoolExecutor(max_workers=0)</code> it works with Python3.4 and Python2.7 but raises an error with Python3.5 and Python3.6. I'm trying to create a <code>ThreadPoolExecutor</code> where I want to ensure that no task gets added to the threadpool. Currently, I created a subclass from <code>ThreadPoolExecutor</code> and raised and exception in the overloaded <code>submit</code> method. Is there a better way to do this?</p>
0
2016-08-03T14:41:36Z
39,059,864
<p>Simply put, with Python3.5 and 3.6, the <code>max_workers</code> argument is not allowed to be <code>0</code> for sanity reasons. So my solution was to make a more "mocky" version of the ThreadPoolExecutor that would record the activity of the ThreadPool in case something is added to the queue and then make assertions about that. I'll share the code here in case someone wants to reuse it for their purposes.</p> <pre><code>import threading from concurrent import futures class RecordingThreadPool(futures.Executor): """A thread pool that records if used.""" def __init__(self, max_workers): self._tp_executor = futures.ThreadPoolExecutor(max_workers=max_workers) self._lock = threading.Lock() self._was_used = False def submit(self, fn, *args, **kwargs): with self._lock: self._was_used = True self._tp_executor.submit(fn, *args, **kwargs) def was_used(self): with self._lock: return self._was_used </code></pre>
0
2016-08-21T00:29:51Z
[ "python", "python-3.x", "concurrent.futures" ]
How to parse rss using beautifulsoup?
38,746,838
<p>I have this rss: <a href="http://socialminisite.com/tnuvabot/?cat=190&amp;feed=rss2" rel="nofollow">http://socialminisite.com/tnuvabot/?cat=190&amp;feed=rss2</a> .</p> <p>How can I get this value:</p> <pre><code>&lt;div class="title"&gt;מצרכים:&lt;/div&gt; </code></pre> <p>From this RSS:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;&lt;rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" &gt; &lt;channel&gt; &lt;title&gt;בריא &amp;#8211; Tnuva Bot&lt;/title&gt; &lt;atom:link href="http://socialminisite.com/tnuvabot/?cat=190&amp;#038;feed=rss2" rel="self" type="application/rss+xml" /&gt; &lt;link&gt;http://socialminisite.com/tnuvabot&lt;/link&gt; &lt;description&gt;Just another WordPress site&lt;/description&gt; &lt;lastBuildDate&gt;Wed, 03 Aug 2016 08:56:16 +0000&lt;/lastBuildDate&gt; &lt;language&gt;en-US&lt;/language&gt; &lt;sy:updatePeriod&gt;hourly&lt;/sy:updatePeriod&gt; &lt;sy:updateFrequency&gt;1&lt;/sy:updateFrequency&gt; &lt;generator&gt;https://wordpress.org/?v=4.5.3&lt;/generator&gt; &lt;item&gt; &lt;title&gt;עוגת גבינה דיאטטית&lt;/title&gt; &lt;link&gt;http://socialminisite.com/tnuvabot/?p=1774&lt;/link&gt; &lt;comments&gt;http://socialminisite.com/tnuvabot/?p=1774#respond&lt;/comments&gt; &lt;pubDate&gt;Tue, 26 Jul 2016 10:39:41 +0000&lt;/pubDate&gt; &lt;dc:creator&gt;&lt;![CDATA[Tnuva Bot]]&gt;&lt;/dc:creator&gt; &lt;category&gt;&lt;![CDATA[בריא]]&gt;&lt;/category&gt; &lt;guid isPermaLink="false"&gt;http://socialminisite.com/tnuvabot/?p=1774&lt;/guid&gt; &lt;description&gt;&lt;![CDATA[מספר מנות: תבנית מרובעת בגודל 20X20 ס&amp;#8221;מ &amp;#124; סיווג כשרות: מתכון חלבי &amp;#124; מקור מתכון: מתכון: יעל גרטי; סטיילינג: אינה גוטמן; צילום: גל בן זאב &amp;#124; זמן עבודה: 10 דקות &amp;#124; מיומנות: קל מצרכים: 4 ביצים גדולות 5 כפות (60 גרם) סוכר 500 גרם גבינה לבנה 5% &amp;#8220;תנובה&amp;#8221; 50 גרם (5 כפות) קמח לבן (רגיל) לשידרוג: כפית קליפת לימון מגוררת או כפית תמצית וניל עוגת גבינה דיאטטית &amp;#8211; &amp;#8230; &lt;a href="http://socialminisite.com/tnuvabot/?p=1774" class="more-link"&gt;Continue reading&lt;span class="screen-reader-text"&gt; "עוגת גבינה דיאטטית"&lt;/span&gt;&lt;/a&gt;]]&gt;&lt;/description&gt; &lt;content:encoded&gt;&lt;![CDATA[&lt;p&gt;&lt;span class="prop_title"&gt;מספר מנות: &lt;/span&gt;&lt;span class="prop_text"&gt;תבנית מרובעת בגודל 20X20 ס&amp;#8221;מ&lt;/span&gt;&lt;span class="prop_text1"&gt; | &lt;/span&gt;&lt;span class="prop_title"&gt;סיווג כשרות: &lt;/span&gt;&lt;span class="prop_text"&gt;מתכון חלבי&lt;/span&gt;&lt;span class="prop_text1"&gt; | &lt;/span&gt;&lt;span class="prop_title"&gt;מקור מתכון: &lt;/span&gt;&lt;span class="prop_text"&gt;מתכון: יעל גרטי; סטיילינג: אינה גוטמן; צילום: גל בן זאב&lt;/span&gt;&lt;span class="prop_text1"&gt; | &lt;/span&gt;&lt;span class="prop_title"&gt;זמן עבודה: &lt;/span&gt;&lt;span class="prop_text"&gt;&lt;time datetime="PT10M"&gt;10 דקות&lt;/time&gt;&lt;/span&gt;&lt;span class="prop_text1"&gt; | &lt;/span&gt;&lt;span class="prop_title"&gt;מיומנות: &lt;/span&gt;&lt;span class="prop_text"&gt;קל&lt;/span&gt;&lt;/p&gt; &lt;div class="title"&gt;מצרכים:&lt;/div&gt; &lt;div class="bottom10px right5px;"&gt;4 ביצים גדולות&lt;/p&gt; &lt;div class="sep-ingredients"&gt;&lt;/div&gt; &lt;p&gt;5 כפות (60 גרם) סוכר&lt;/p&gt; &lt;div class="sep-ingredients"&gt;&lt;/div&gt; &lt;p&gt;500 גרם גבינה לבנה 5% &amp;#8220;תנובה&amp;#8221;&lt;/p&gt; &lt;div class="sep-ingredients"&gt;&lt;/div&gt; &lt;p&gt;50 גרם (5 כפות) קמח לבן (רגיל)&lt;/p&gt; &lt;div class="sep-ingredients"&gt;&lt;/div&gt; &lt;p&gt;לשידרוג: כפית קליפת לימון מגוררת או כפית תמצית וניל&lt;/p&gt;&lt;/div&gt; &lt;h3 class="title"&gt;עוגת גבינה דיאטטית &amp;#8211; אופן הכנה:&lt;/h3&gt; &lt;div class="text14 right5px"&gt;1. מחממים תנור ל-160 מעלות (בתוכנית טורבו) ומשמנים תבנית במעט חמאה מומסת או שמן קנולה.&lt;br /&gt; 2. מפרידים ביצים. בקערה קטנה מערבבים גבינה לבנה, חלמונים וקליפת לימון (או תמצית וניל).&lt;br /&gt; 3. שמים חלבונים במיקסר עם וו הקצפה ומקציפים במהירות גבוהה מאוד במשך דקה או עד שמתחיל להווצר קצף לבן. מוסיפים בהדרגה סוכר ומקציפים דקה, עד לקבלת קצף תפוח מאוד.&lt;br /&gt; 4. מוסיפים את תערובת הגבינה הלבנה לקצף החלבונים ומערבלים במהירות איטית עד לאיחוד. עוצרים את פעולת המיקסר, אוספים בעזרת מרית את שניתז לדופנות ומערבלים שוב, לאיחוד – ולא מעבר לכך.&lt;br /&gt; 5. מוסיפים את הקמח ומקציפים באיטיות עד להיטמעות הקמח ולא מעבר לכך. עוצרים את פעולת המיקסר, אוספים בעזרת מרית את שניתז לדופנות ומערבלים שוב, לאיחוד – ולא מעבר לכך. יוצקים את העיסה לתבנית המשומנת ומיישרים בעזרת מרית. כשהתנור חם, מכניסים את התבנית למרכזו ואופים במשך 38-40 דקות או עד להתייצבות והזהבה יפה. מוציאים, מצננים שעה בטמפ&amp;#8217; החדר ועוד 3 שעות במקרר לפני ההגשה. מגישים קר.&lt;/div&gt; ]]&gt;&lt;/content:encoded&gt; &lt;wfw:commentRss&gt;http://socialminisite.com/tnuvabot/?feed=rss2&amp;#038;p=1774&lt;/wfw:commentRss&gt; &lt;slash:comments&gt;0&lt;/slash:comments&gt; &lt;/item&gt; &lt;item&gt; &lt;title&gt;עוגת מעדן יולו שוקולד מריר&lt;/title&gt; &lt;link&gt;http://socialminisite.com/tnuvabot/?p=1770&lt;/link&gt; &lt;comments&gt;http://socialminisite.com/tnuvabot/?p=1770#respond&lt;/comments&gt; &lt;pubDate&gt;Tue, 26 Jul 2016 10:37:44 +0000&lt;/pubDate&gt; &lt;dc:creator&gt;&lt;![CDATA[Tnuva Bot]]&gt;&lt;/dc:creator&gt; &lt;category&gt;&lt;![CDATA[בריא]]&gt;&lt;/category&gt; &lt;guid isPermaLink="false"&gt;http://socialminisite.com/tnuvabot/?p=1770&lt;/guid&gt; &lt;description&gt;&lt;![CDATA[מספר מנות: תבנית אינגליש באורך 30 ס&amp;#8221;מ – לא חד פעמית &amp;#8211; או ל-16-23 מאפינס קטנים-בינוניים &amp;#124; סיווג כשרות: מתכון חלבי &amp;#124; מקור מתכון: מתכון: יעל גרטי; סטיילינג: אינה גוטמן; צילום: גל בן זאב &amp;#124; זמן עבודה: 10 דקות &amp;#124; מיומנות: קל מצרכים: 3 ביצים גדולות 180 גרם (כוס פחות 1-2 כפות) סוכר 3 גביעי &amp;#8220;יולו&amp;#8221; שוקולד מריר (123 גרם כל גביע) של &amp;#8220;תנובה&amp;#8221; 2 כפות שמן &amp;#8230; &lt;a href="http://socialminisite.com/tnuvabot/?p=1770" class="more-link"&gt;Continue reading&lt;span class="screen-reader-text"&gt; "עוגת מעדן יולו שוקולד מריר"&lt;/span&gt;&lt;/a&gt;]]&gt;&lt;/description&gt; &lt;content:encoded&gt;&lt;![CDATA[&lt;p&gt;&lt;span class="prop_title"&gt;מספר מנות: &lt;/span&gt;&lt;span class="prop_text"&gt;תבנית אינגליש באורך 30 ס&amp;#8221;מ – לא חד פעמית &amp;#8211; או ל-16-23 מאפינס קטנים-בינוניים &lt;/span&gt;&lt;span class="prop_text1"&gt; | &lt;/span&gt;&lt;span class="prop_title"&gt;סיווג כשרות: &lt;/span&gt;&lt;span class="prop_text"&gt;מתכון חלבי&lt;/span&gt;&lt;span class="prop_text1"&gt; | &lt;/span&gt;&lt;span class="prop_title"&gt;מקור מתכון: &lt;/span&gt;&lt;span class="prop_text"&gt;מתכון: יעל גרטי; סטיילינג: אינה גוטמן; צילום: גל בן זאב&lt;/span&gt;&lt;span class="prop_text1"&gt; | &lt;/span&gt;&lt;span class="prop_title"&gt;זמן עבודה: &lt;/span&gt;&lt;span class="prop_text"&gt;&lt;time datetime="PT10M"&gt;10 דקות&lt;/time&gt;&lt;/span&gt;&lt;span class="prop_text1"&gt; | &lt;/span&gt;&lt;span class="prop_title"&gt;מיומנות: &lt;/span&gt;&lt;span class="prop_text"&gt;קל&lt;/span&gt;&lt;/p&gt; &lt;div class="title"&gt;מצרכים:&lt;/div&gt; &lt;div class="bottom10px right5px;"&gt; &lt;p&gt;3 ביצים גדולות&lt;/p&gt; &lt;div class="sep-ingredients"&gt;&lt;/div&gt; &lt;p&gt;180 גרם (כוס פחות 1-2 כפות) סוכר&lt;/p&gt; &lt;div class="sep-ingredients"&gt;&lt;/div&gt; &lt;p&gt;3 גביעי &amp;#8220;יולו&amp;#8221; שוקולד מריר (123 גרם כל גביע) של &amp;#8220;תנובה&amp;#8221;&lt;/p&gt; &lt;div class="sep-ingredients"&gt;&lt;/div&gt; &lt;p&gt;2 כפות שמן קנולה (או שמן צמחי נטרלי אחר)&lt;/p&gt; &lt;div class="sep-ingredients"&gt;&lt;/div&gt; &lt;p&gt;220 גרם (כוס וחצי ועוד כף) קמח תופח&lt;/p&gt; &lt;div class="sep-ingredients"&gt;&lt;/div&gt; &lt;/div&gt; &lt;h3 class="title"&gt;עוגת מעדן יולו שוקולד מריר &amp;#8211; אופן הכנה:&lt;/h3&gt; &lt;div class="text14 right5px"&gt;1. מחממים תנור ל-170 מעלות ומשמנים תבנית אינגליש (לא חד-פעמית) באורך 30 ס&amp;#8221;מ (או את השקעים בשתי תבניות מאפינס מסיליקון) במעט שמן קנולה.&lt;br /&gt; 2. בקערה בינונית-גדולה טורפים ביצים וסוכר במטרף ידני עד לאיחוד והשגת מעט נפח.&lt;br /&gt; 3. מוסיפים 3 גביעי &amp;#8220;יולו&amp;#8221; שוקולד מריר ושמן קנולה וטורפים לאיחוד.&lt;br /&gt; 4. מוסיפים קמח תופח וטורפים לאיחוד – ולא מעבר לכך. הימנעו מערבוב יתר. יוצקים לתבנית המשומנת. כשהתנור חם מכניסים למרכז התנור ואופים במשך 45 דקות (לתבנית אינגליש 30 ס&amp;#8221;מ) או 15 דקות (למאפינס בגודל קטן-בינוני). מוציאים, מצננים כשעה ומגישים.&lt;/div&gt; ]]&gt;&lt;/content:encoded&gt; &lt;wfw:commentRss&gt;http://socialminisite.com/tnuvabot/?feed=rss2&amp;#038;p=1770&lt;/wfw:commentRss&gt; &lt;slash:comments&gt;0&lt;/slash:comments&gt; &lt;/item&gt; &lt;item&gt; &lt;title&gt;קעריות שוקולד ממולאות מוס פטל&lt;/title&gt; &lt;link&gt;http://socialminisite.com/tnuvabot/?p=1767&lt;/link&gt; &lt;comments&gt;http://socialminisite.com/tnuvabot/?p=1767#respond&lt;/comments&gt; &lt;pubDate&gt;Tue, 26 Jul 2016 10:35:48 +0000&lt;/pubDate&gt; &lt;dc:creator&gt;&lt;![CDATA[Tnuva Bot]]&gt;&lt;/dc:creator&gt; &lt;category&gt;&lt;![CDATA[בריא]]&gt;&lt;/category&gt; &lt;guid isPermaLink="false"&gt;http://socialminisite.com/tnuvabot/?p=1767&lt;/guid&gt; &lt;description&gt;&lt;![CDATA[מספר מנות: 6 קעריות &amp;#124; סיווג כשרות: מתכון חלבי &amp;#124; מקור מתכון: מתכון: יעל גרטי; סטיילינג: אינה גוטמן; צילום: גל בן זאב &amp;#124; זמן עבודה: 15 דקות &amp;#124; מיומנות: קל מצרכים: אם רוצים מוס ריבת חלב במקום מוס פטל מוסיפים לקצפת 2 כפות גדושות ריבת חלב (50-60 גרם). אם משתמשים בשוקולד 70% מוצקי קקאו, מומלץ להוסיף לו 1-2 כפות אבקת סוכר לפני ההמסה, כדי שהתוצאה לא תהיה מרירה &amp;#8230; &lt;a href="http://socialminisite.com/tnuvabot/?p=1767" class="more-link"&gt;Continue reading&lt;span class="screen-reader-text"&gt; "קעריות שוקולד ממולאות מוס פטל"&lt;/span&gt;&lt;/a&gt;]]&gt;&lt;/description&gt; &lt;content:encoded&gt;&lt;![CDATA[&lt;p&gt;&lt;span class="prop_title"&gt;מספר מנות: &lt;/span&gt;&lt;span class="prop_text"&gt;6 קעריות&lt;/span&gt;&lt;span class="prop_text1"&gt; | &lt;/span&gt;&lt;span class="prop_title"&gt;סיווג כשרות: &lt;/span&gt;&lt;span class="prop_text"&gt;מתכון חלבי&lt;/span&gt;&lt;span class="prop_text1"&gt; | &lt;/span&gt;&lt;span class="prop_title"&gt;מקור מתכון: &lt;/span&gt;&lt;span class="prop_text"&gt;מתכון: יעל גרטי; סטיילינג: אינה גוטמן; צילום: גל בן זאב&lt;/span&gt;&lt;span class="prop_text1"&gt; | &lt;/span&gt;&lt;span class="prop_title"&gt;זמן עבודה: &lt;/span&gt;&lt;span class="prop_text"&gt;&lt;time datetime="PT15M"&gt;15 דקות&lt;/time&gt;&lt;/span&gt;&lt;span class="prop_text1"&gt; | &lt;/span&gt;&lt;span class="prop_title"&gt;מיומנות: &lt;/span&gt;&lt;span class="prop_text"&gt;קל&lt;/span&gt;&lt;/p&gt; &lt;div class="title"&gt;מצרכים:&lt;/div&gt; &lt;div class="bottom10px right5px;"&gt;אם רוצים מוס ריבת חלב במקום מוס פטל מוסיפים לקצפת 2 כפות גדושות ריבת חלב (50-60 גרם). אם משתמשים בשוקולד 70% מוצקי קקאו, מומלץ להוסיף לו 1-2 כפות אבקת סוכר לפני ההמסה, כדי שהתוצאה לא תהיה מרירה מדי&lt;/div&gt; &lt;h3 class="title"&gt;קעריות שוקולד ממולאות מוס פטל &amp;#8211; אופן הכנה:&lt;/h3&gt; &lt;div class="text14 right5px"&gt;1. שמים בקערית חסינת-חום שוקולד מריר. מכניסים למיקרוגל, מפעילים למשך 30 שניות, מוציאים, מערבבים וכך שוב עוד פעמיים-שלוש או עד לקבלת נוזל חלק ואחיד, ללא גושים. מושחים מיד את השקעים בתבנית מאפינס בגודל בינוני מסיליקון, כך שמצפים לגמרי את תוכן השקעים בשוקולד. מוודאים שהשקעים מלאים שוקולד ושלא נותרו חורים. מכניסים למקפיא למשך 10 דקות. כעבור 10 דקות מוציאים את התבנית מהמקפיא, מחלצים את קעריות השוקולד מהתבנית ומעבירים לצלחת הגשה או מגש. מאחסנים במקפיא או במקרר עד להמשך. שימו לב שלא להרבות במגע ידני עם גביעי השוקולד.&lt;br /&gt; 2. מקציפים שמנת מתוקה וכף סוכר במיקסר עם וו הקצפה במהירות הגבוהה ביותר, במשך דקה וחצי עד שתי דקות, עד לקבלת קצפת יפה.&lt;br /&gt; 3. מוסיפים 2 כפות ריבת פטל לקצפת ומערבלים במהירות נמוכה לאיחוד. משחררים מהמיקסר, מערבבים במרית ויוצקים 1-2 כפות מהקצפת הוורודה לכל קערית שוקולד (להגשה יפה מעבירים את הקצפת הוורודה לשק זילוף עם צנתר משונן ומזלפים לגביעי השוקולד). מאחסנים כחצי שעה (עד ארבע שעות) במקרר או 40-50 דקות במקפיא לפני ההגשה.&lt;/div&gt; ]]&gt;&lt;/content:encoded&gt; &lt;wfw:commentRss&gt;http://socialminisite.com/tnuvabot/?feed=rss2&amp;#038;p=1767&lt;/wfw:commentRss&gt; &lt;slash:comments&gt;0&lt;/slash:comments&gt; &lt;/item&gt; &lt;/channel&gt; &lt;/rss&gt; </code></pre>
0
2016-08-03T14:43:45Z
38,754,022
<p>To get what you want, all you need is a simple select using <em>lxml</em> or <em>html5lib</em> as the parser:</p> <pre><code>In [6]: import requests In [7]: from bs4 import BeautifulSoup In [8]: url = "http://socialminisite.com/tnuvabot/?cat=190&amp;feed=rss2" In [9]: soup = BeautifulSoup(requests.get(url).content,"lxml") In [10]: print(soup.select_one("div.title")) &lt;div class="title"&gt;מצרכים:&lt;/div&gt; </code></pre>
0
2016-08-03T21:35:08Z
[ "python", "xml", "beautifulsoup" ]
Why do I keep getting TypeError?
38,746,845
<p>This is the error I am getting, but only when I try to run the code using <code>argparse</code></p> <p>Error:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "portscanner.py", line 63, in &lt;module&gt; Main() File "http://portscanner.py", line 58, in Main AN(args.ip_addr) File "http://portscanner.py", line 34, in AN s = IP(dst=ip_addr)/TCP(sport=80, dport=80, flags="S") # creates packet ("S") TypeError: __init__() got an unexpected keyword argument 'dst' </code></pre> <p>Code:</p> <pre><code>from logging import getLogger, ERROR getLogger("scapy.runtime").setLevel(ERROR) from scapy.all import * import argparse import sys import socket from IPy import IP def create_packet(ip_addr): s = IP(dst=ip_addr)/TCP(sport=80, dport=80, flags="S") # creates packet ("S") print "pass" def Main(): parser = argparse.ArgumentParser(description='Script for port scanning') parser.add_argument("-H", "--host", help="host IP", dest="ip_addr", required=True, default="localhost") parser.add_argument("-s", "--syn", help="conduct a syn flag scan", action="store_true") parser.add_argument("-i", "--icmp", help="conduct a ICMP scan", action="store_true") parser.add_argument("-sp", "--start-port", help="starting/main port (s)", dest="dest_port", type=int, action="store") parser.add_argument("-ep", "--end-port", help="ending port port (s)", dest="eport", type=int, action="store") args = parser.parse_args() if args.syn: IP(args.ip_addr) create_packet(args.ip_addr) else: print 'fail' if __name__ == '__main__': Main() </code></pre> <p>The error happens on like 34 where <code>scapy</code> is crafting the packet. Now when the similar code (craft the packet in a different program) I do not get the "dst" error.</p> <pre><code>def scan(port): s = IP(dst=ip_addr)/TCP(sport=s_port, dport=port, flags="S") # creates packet ("S") snd = sr1(s, timeout=2) # sends packet if str(type(snd)) == "&lt;type 'NoneType'&gt;": pass elif snd.haslayer(TCP): # checks the layer of the response from server if snd.getlayer(TCP).flags == 0x12: r = IP(dst=ip_addr)/TCP(sport=s_port, dport=port, flags="R") rsnd = sr(r, timeout=2) # closes the connection print '[*] Port %d is open' % port elif snd.getlayer(TCP).flags == 0x14: pass # checks for rst packet </code></pre> <p>I searched Google, and I saw a similar error that other had, but I could not see why my code is doing this. Especially when it works in a different program.</p>
-1
2016-08-03T14:44:05Z
38,746,976
<p>You are passing in a <code>dst=</code> keyword argument to the <code>IPy.IP()</code> class:</p> <pre><code>from IPy import IP # ... IP(dst=ip_addr) </code></pre> <p>That class doesn't define such a keyword argument. Looking at the <a href="https://github.com/autocracy/python-ipy/" rel="nofollow">project documentation</a> I see no such keyword defined, there is only a <em>positional</em> <code>data</code> argument <a href="https://github.com/autocracy/python-ipy/blob/master/IPy.py#L139" rel="nofollow">defined in the <code>__init__</code> method</a>:</p> <pre><code>def __init__(self, data, ipversion=0, make_net=0): </code></pre> <p>You could drop the <code>dst=</code> part:</p> <pre><code>IP(ip_addr) </code></pre> <p>But perhaps you got confused with the <code>scapy</code> <code>IP()</code> class instead.</p> <p>I certainly doubt you can mix the <code>IPy.IP()</code> class with the <code>scapy</code> <code>TCP()</code> class like you try to do in your code. Perhaps you want to <em>remove</em> the <code>from IPy import IP</code> line altogether instead.</p>
0
2016-08-03T14:50:18Z
[ "python", "init", "scapy" ]
Plotting of MFCC power spectrogram Python
38,746,889
<p>Can anyone help me plot a <code>mfcc</code> feature as a power spectrogram! I am only able to plot <code>mfcc</code> coefficients which is not represented in time domain. I want to plot <code>mfcc</code> feature in time domain. I also tried applying DCT to convert it into time domain! </p> <pre><code>from python_speech_features import mfcc #from python_speech_features import logfbank `enter code here` import scipy.io.wavfile as wav import pandas as pd import matplotlib.pyplot as plt from python_speech_features import logfbank import scipy.fftpack (rate,sig) = wav.read("Voice0003.wav") mfcc_feat = mfcc(sig,rate) (rate2,sig2) = wav.read("Voice0004.wav") mfcc_feat2 = mfcc(sig2,rate2) yf = scipy.fftpack.fft(sig,rate) #fbank_feat = logfbank(yf) #dct=scipy.fftpack.dct(fbank_feat tried converting into Time Domain didnt help print(len(mfcc_feat)) print(len(mfcc_feat2)) pd.DataFrame(mfcc_feat2).T.plot() plt.show() pd.DataFrame(mfcc_feat).T.plot() plt.show() </code></pre>
0
2016-08-03T14:46:15Z
38,783,427
<p>Pxx, freqs, bins, im = plt.specgram(signal, NFFT=NFFT, Fs=2,noverlap=100, cmap=None) #signal is 1D array of .wav file</p>
0
2016-08-05T07:20:44Z
[ "python", "python-2.7", "matplotlib", "scipy" ]
Should put in requirements.txt dependency targeting packege in pypi or github repo?
38,747,052
<p>Are there any technical indications to prefer referencing a package on PyPI over the original source on GitHub in <code>requirements.txt</code>?</p> <p>Only thing that comes to my mind is that freezing a package on a certain version is very cumbersome with GitHub (<code>package==1.0.0</code> vs <code>git://github.com/{ username }/{ reponame }.git@{ tag name }#egg={ desired egg name }</code>), but I'm not sure if this can cause any problems.</p> <p>Other thing is necessity to install git on target machine. </p> <p>Are there any other indications?</p>
-1
2016-08-03T14:53:49Z
38,748,416
<p>PyPI is the accepted defacto location for distributing <em>released versions</em> of a package, and it could be that not all Python packaging tools support installing from GitHub.</p> <p>And as you already noticed, for <code>pip</code> to support GitHub you must have <code>git</code> installed; this limits portability of your file.</p> <p>Next, not all project maintainers remember to tag releases in GitHub; what is distributed to PyPI may be hard to locate on GitHub. The tag could also be <em>wrong</em>. You could end up installing a subtly different version from PyPI, creating confusion when you run into a support issue.</p> <p>On the other hand, if you must install a non-released development version (say, you need a critical bugfix but no release has been rolled since), then GitHub may be the only place you can get that version.</p> <p>So, in short, you should prefer using PyPI over GitHub, as that ensures that you got an official release, and is more portable. Only use a GitHub URL in <code>requirements.txt</code> if there is no other source for a specific version.</p>
1
2016-08-03T15:55:10Z
[ "python", "github", "pypi" ]
Portable python script: Is it possible to include third party libraries in script?
38,747,073
<p>I have a Python script which uses open source third party libraries for geoprocessing (OGR and Shapely). My plan is to execute this script on a computer without having to install the required libraries.</p> <p>I know that there are tools such as py2exe available for this purpose. However, compiling an executable file is not my first choice as I noticed that such files can get pretty large in size. Besides, I would like to use the code within another script. I would therefore like to create a portable python script which already includes the third party methods needed for executing. </p> <p>Is it possible to include third party methods in a Python script in order to avoid the installation of third party libraries? And if not, what can I do instead, besides compiling an executable file? I work on Windows OS. </p>
0
2016-08-03T14:54:46Z
38,747,314
<p>You can export your libraries using pip and embbed them into your application.</p> <p>pip wheel requires the wheel package to be installed, which provides the "bdist_wheel" setuptools extension that it uses.</p> <p>To build wheels for your requirements and all their dependencies to a local directory:</p> <pre><code>pip install wheel pip freeze &gt; requirements.txt </code></pre> <p>At this point check requirements.txt, clean it up, then you can download wheels in a local folder :</p> <pre><code>pip wheel --wheel-dir=/local/wheels -r requirements.txt </code></pre> <p>And then to install those requirements just using your local directory of wheels (and not from PyPI):</p> <pre><code>pip install --no-index --find-links=/local/wheels -r requirements.txt </code></pre> <p>Then though you'll need pip, though it's shipped with latest versions of python.</p> <p>Check this : <a href="https://pip.readthedocs.io/en/latest/user_guide/#requirements-files" rel="nofollow">https://pip.readthedocs.io/en/latest/user_guide/#requirements-files</a></p>
0
2016-08-03T15:05:49Z
[ "python" ]
Portable python script: Is it possible to include third party libraries in script?
38,747,073
<p>I have a Python script which uses open source third party libraries for geoprocessing (OGR and Shapely). My plan is to execute this script on a computer without having to install the required libraries.</p> <p>I know that there are tools such as py2exe available for this purpose. However, compiling an executable file is not my first choice as I noticed that such files can get pretty large in size. Besides, I would like to use the code within another script. I would therefore like to create a portable python script which already includes the third party methods needed for executing. </p> <p>Is it possible to include third party methods in a Python script in order to avoid the installation of third party libraries? And if not, what can I do instead, besides compiling an executable file? I work on Windows OS. </p>
0
2016-08-03T14:54:46Z
38,747,336
<p>If your third party lib does not have any dependencies you can get the source files (.py) put into your project folder and use it as package by using import, else it has dependencies your project size grow more better create exe for your script. </p>
0
2016-08-03T15:06:49Z
[ "python" ]
how to find if an element from an array is a substring of a string?
38,747,178
<p>Given a string <code>s = "Leonhard Euler"</code>, I need to find if an element in my surname array is a substring of s. For example:</p> <pre><code>s = "Leonhard Euler" surnames = ["Cantor", "Euler", "Fermat", "Gauss", "Newton", "Pascal"] if any(surnames) in s: print("We've got a famous mathematician!") </code></pre>
0
2016-08-03T14:59:38Z
38,747,260
<p>Consider <code>if any(i in surnames for i in s.split()):</code>.</p> <p>This will work for both <code>s = "Leonhard Euler"</code> and <code>s = "Euler Leonhard"</code>.</p>
5
2016-08-03T15:03:10Z
[ "python" ]
how to find if an element from an array is a substring of a string?
38,747,178
<p>Given a string <code>s = "Leonhard Euler"</code>, I need to find if an element in my surname array is a substring of s. For example:</p> <pre><code>s = "Leonhard Euler" surnames = ["Cantor", "Euler", "Fermat", "Gauss", "Newton", "Pascal"] if any(surnames) in s: print("We've got a famous mathematician!") </code></pre>
0
2016-08-03T14:59:38Z
38,747,285
<pre><code>s = "Leonhard Euler" surnames = ["Cantor", "Euler", "Fermat", "Gauss", "Newton", "Pascal"] for surname in surnames: if(surname in s): print("We've got a famous mathematician!") </code></pre> <p>Loops through each string in surnames and checks if its a substring of s</p>
1
2016-08-03T15:04:22Z
[ "python" ]
how to find if an element from an array is a substring of a string?
38,747,178
<p>Given a string <code>s = "Leonhard Euler"</code>, I need to find if an element in my surname array is a substring of s. For example:</p> <pre><code>s = "Leonhard Euler" surnames = ["Cantor", "Euler", "Fermat", "Gauss", "Newton", "Pascal"] if any(surnames) in s: print("We've got a famous mathematician!") </code></pre>
0
2016-08-03T14:59:38Z
38,747,299
<p>Actually I didn't test the the code but should be something like this (if I understood the question):</p> <pre><code>for surname in surnames: if surname in s: print("We've got a famous mathematician!") </code></pre>
0
2016-08-03T15:04:59Z
[ "python" ]
how to find if an element from an array is a substring of a string?
38,747,178
<p>Given a string <code>s = "Leonhard Euler"</code>, I need to find if an element in my surname array is a substring of s. For example:</p> <pre><code>s = "Leonhard Euler" surnames = ["Cantor", "Euler", "Fermat", "Gauss", "Newton", "Pascal"] if any(surnames) in s: print("We've got a famous mathematician!") </code></pre>
0
2016-08-03T14:59:38Z
38,747,342
<p>If you don't need to know which surname is in s you can do that using any and list comprehension:</p> <pre><code>if any(surname in s for surname in surnames): print("We've got a famous mathematician!") </code></pre>
1
2016-08-03T15:07:04Z
[ "python" ]
how to find if an element from an array is a substring of a string?
38,747,178
<p>Given a string <code>s = "Leonhard Euler"</code>, I need to find if an element in my surname array is a substring of s. For example:</p> <pre><code>s = "Leonhard Euler" surnames = ["Cantor", "Euler", "Fermat", "Gauss", "Newton", "Pascal"] if any(surnames) in s: print("We've got a famous mathematician!") </code></pre>
0
2016-08-03T14:59:38Z
38,747,444
<p>You can use isdisjoint attribute of sets after splitting the string to list to check if the two lists casted to sets have any elements in common.</p> <pre><code>s = "Leonhard Euler" surnames = ["Cantor", "Euler", "Fermat", "Gauss", "Newton", "Pascal"] strlist = s.split() if not set(strlist).isdisjoint(surnames): print("We've got a famous mathematician!") </code></pre>
2
2016-08-03T15:11:52Z
[ "python" ]
How to create a symmetric matrix from a numpy 1D array the most efficient way
38,747,311
<p>I have a 1d <code>np.array</code>. Its length may vary according to user input, but it will always stay single-dimesional. Please advise if there is an efficient way to create a symmetric 2d <code>np.array</code> from it? By 'symmetric' I mean that its elements will be according to the rule k[i, j] = k[j, i].</p> <p>I realise it is possible to do with a python <code>for</code> loop and <code>list</code>s, but that is very inefficient.</p> <p>Many thanks in advance!</p> <p><strong>EXAMPLE:</strong> For example, we have <code>x = np.array([1, 2, 3])</code>. The desired result should be </p> <pre><code>M = np.array([[1, 2, 3], [2, 1, 2], [3, 2, 1]) </code></pre>
0
2016-08-03T15:05:36Z
38,747,900
<p><strong>Interpretation #1</strong></p> <p>Seems like you are reusing elements at each row. So, with that sort of idea, an implementation using <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> would be -</p> <pre><code>def symmetricize(arr1D): ID = np.arange(arr1D.size) return arr1D[np.abs(ID - ID[:,None])] </code></pre> <p>Sample run -</p> <pre><code>In [170]: arr1D Out[170]: array([59, 21, 70, 10, 42]) In [171]: symmetricize(arr1D) Out[171]: array([[59, 21, 70, 10, 42], [21, 59, 21, 70, 10], [70, 21, 59, 21, 70], [10, 70, 21, 59, 21], [42, 10, 70, 21, 59]]) </code></pre> <hr> <p><strong>Interpretation #2</strong></p> <p>Another interpretation I had when you would like to assign the elements from the input <code>1D</code> array into a symmetric <code>2D</code> array <strong>without re-use</strong>, such that we would fill in the upper triangular part once and then replicate those on the lower triangular region by keeping symmetry between the row and column indices. As such, it would only work for a specific size of it. So, as a pre-processing step, we need to perform that error-checking. After we are through the error-checking, we will initialize an output array and use row and column indices of a <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.triu.html" rel="nofollow"><code>triangular array</code></a> to assign values once as they are and once with swapped indices to assign values in the other triangular part, thus giving it the symmetry <em>effect</em>.</p> <p>It seemed like <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.spatial.distance.squareform.html" rel="nofollow"><code>Scipy's squareform</code></a> should do be able to do this task, but from the docs, it doesn't look like it supports filling up the diagonal elements with the input array elements. So, let's give our solution a closely-related name.</p> <p>Thus, we would have an implementation like so -</p> <pre><code>def squareform_diagfill(arr1D): n = int(np.sqrt(arr1D.size*2)) if (n*(n+1))//2!=arr1D.size: print "Size of 1D array not suitable for creating a symmetric 2D array!" return None else: R,C = np.triu_indices(n) out = np.zeros((n,n),dtype=arr1D.dtype) out[R,C] = arr1D out[C,R] = arr1D return out </code></pre> <p>Sample run -</p> <pre><code>In [179]: arr1D = np.random.randint(0,9,(12)) In [180]: squareform_diagfill(arr1D) Size of 1D array not suitable for creating a symmetric 2D array! In [181]: arr1D = np.random.randint(0,9,(10)) In [182]: arr1D Out[182]: array([0, 4, 3, 6, 4, 1, 8, 6, 0, 5]) In [183]: squareform_diagfill(arr1D) Out[183]: array([[0, 4, 3, 6], [4, 4, 1, 8], [3, 1, 6, 0], [6, 8, 0, 5]]) </code></pre>
1
2016-08-03T15:31:08Z
[ "python", "arrays", "numpy", "matrix", "linear-algebra" ]
How to create a symmetric matrix from a numpy 1D array the most efficient way
38,747,311
<p>I have a 1d <code>np.array</code>. Its length may vary according to user input, but it will always stay single-dimesional. Please advise if there is an efficient way to create a symmetric 2d <code>np.array</code> from it? By 'symmetric' I mean that its elements will be according to the rule k[i, j] = k[j, i].</p> <p>I realise it is possible to do with a python <code>for</code> loop and <code>list</code>s, but that is very inefficient.</p> <p>Many thanks in advance!</p> <p><strong>EXAMPLE:</strong> For example, we have <code>x = np.array([1, 2, 3])</code>. The desired result should be </p> <pre><code>M = np.array([[1, 2, 3], [2, 1, 2], [3, 2, 1]) </code></pre>
0
2016-08-03T15:05:36Z
38,750,253
<p>What you're looking for is a special Toeplitz matrix and easy to generate with scipy</p> <pre><code>from numpy import concatenate, zeros from scipy.linalg import toeplitz toeplitz([1,2,3]) array([[1, 2, 3], [2, 1, 2], [3, 2, 1]]) </code></pre> <p>another special matrix interpretation can be using Hankel matrix, which will give you minimum dimension square matrix for a given array.</p> <pre><code>from scipy.linalg import hankel a=[1,2,3] t=int(len(a)/2)+1 s=t-2+len(a)%2 hankel(a[:t],a[s:]) array([[1, 2], [2, 3]]) </code></pre>
4
2016-08-03T17:34:19Z
[ "python", "arrays", "numpy", "matrix", "linear-algebra" ]
Return Function description as string?
38,747,526
<p>Is it possible to output the content of a user-defined function as a string (not the enumeration, but just the function call):</p> <p>Function:</p> <pre><code>def sum(x,y): return x+y </code></pre> <p>Function content as a string:</p> <pre><code>"sum(), return x+y" </code></pre> <p>The inspect function might have worked but it seems to be for just python 2.5 and below?</p>
0
2016-08-03T15:15:23Z
38,747,679
<p>The <a href="https://docs.python.org/2/library/inspect.html#retrieving-source-code" rel="nofollow"><code>inspect</code> module</a> works just fine for retrieving source code, this is not limited to older Python versions.</p> <p>Provided the source is available (e.g. the function is not defined in C code or the interactive interpreter, or was imported from a module for which only the <code>.pyc</code> bytecode cache is available), then you can use:</p> <pre><code>import inspect import re import textwrap def function_description(f): # remove the `def` statement. source = inspect.getsource(f).partition(':')[-1] first, _, rest = source.partition('\n') if not first.strip(): # only whitespace left, so not a one-liner source = rest return "{}(), {}".format( f.__name__, textwrap.dedent(source)) </code></pre> <p>Demo:</p> <pre><code>&gt;&gt;&gt; print open('demo.py').read() # show source code def sum(x, y): return x + y def mean(x, y): return sum(x, y) / 2 def factorial(x): product = 1 for i in xrange(1, x + 1): product *= i return product &gt;&gt;&gt; from demo import sum, mean, factorial &gt;&gt;&gt; print function_description(sum) sum(), return x + y &gt;&gt;&gt; print function_description(mean) mean(), return sum(x, y) / 2 &gt;&gt;&gt; print function_description(factorial) factorial(), product = 1 for i in xrange(1, x + 1): product *= i return product </code></pre>
2
2016-08-03T15:21:36Z
[ "python", "python-2.7", "function", "introspection" ]
Is there an analogue of a MATLAB function `mscohere` in Python?
38,747,539
<p>In MATLAB have a function <code>mscohere</code> me it needs to be implemented in Python. The MATLAB code is as follows:</p> <pre><code>[Cxy,~] = mscohere(LS,RS); </code></pre> <p>LS,RS - Arrays type float.</p> <p>Do modules to the calculation of coherence? Or can anyone have expected it in Python?</p> <p><a href="http://www.mathworks.com/help/signal/ref/mscohere.html?requestedDomain=www.mathworks.com" rel="nofollow">Documentation <code>mscohere</code> in MATLAB</a></p>
1
2016-08-03T15:16:01Z
38,747,938
<p>Yes, it has one in the scipy module:</p> <pre><code>scipy.signal.coherence(x, y, fs=1.0, window='hann', nperseg=256, noverlap=None, nfft=None, detrend='constant', axis=-1) </code></pre> <p>Detailed documentation with examples can be found <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.coherence.html" rel="nofollow">here</a></p>
2
2016-08-03T15:32:42Z
[ "python", "matlab" ]
Console tool for python type hint checking
38,747,565
<p>I have a project with type hints (Python 3.5.2). I would like to run the static checker to verify that the constraints specified in the type hints are being respected. What tools are available for this? I have been unable to find a reference in the <a href="https://www.python.org/dev/peps/pep-0484/" rel="nofollow">corresponding PEP</a></p>
0
2016-08-03T15:17:36Z
38,935,096
<p><a href="http://mypy-lang.org/" rel="nofollow">Mypy</a> is probably what you're looking for. It's a console-based tool that can typecheck your Python code using PEP 484 type annotations. The reason why it isn't mentioned in PEP 484 is because there's no inherent reason why mypy would be the only possible typechecker out there -- Pycharm, for example, implements something similar also based on PEP 484 annotations.</p> <p>Mypy is still under active development/beta mode and so you might run into the occasional bugs, but it's relatively stable.</p>
1
2016-08-13T17:06:16Z
[ "python", "type-hinting" ]
Numpy array to csv
38,747,682
<p>I have a np array with 1000 rows, and 4608 columns each rows</p> <p>I try to save a csv file with:</p> <pre><code>myfile = open('dataset.csv', 'wb') wr = csv.writer(myfile,delimiter='\n') wr.writerow(Prueba[0]) </code></pre> <p>But if I open the csv file with LibreOffice this:</p> <pre><code>[153 147 147 ..., 142 147 146] [183 247 147 ..., 126 123 104] ... </code></pre> <p>No apears the 4608 columns!!</p> <p>Some idea?</p> <p>Thank you!</p> <p>Regards, Andres.</p>
0
2016-08-03T15:21:44Z
38,747,765
<p>Try this.</p> <pre><code>numpy.savetxt("FILENAME.csv", a, delimiter=",") </code></pre> <p>Where filename is your filename and a is your array.</p>
3
2016-08-03T15:25:29Z
[ "python", "arrays", "csv", "numpy" ]
Numpy array to csv
38,747,682
<p>I have a np array with 1000 rows, and 4608 columns each rows</p> <p>I try to save a csv file with:</p> <pre><code>myfile = open('dataset.csv', 'wb') wr = csv.writer(myfile,delimiter='\n') wr.writerow(Prueba[0]) </code></pre> <p>But if I open the csv file with LibreOffice this:</p> <pre><code>[153 147 147 ..., 142 147 146] [183 247 147 ..., 126 123 104] ... </code></pre> <p>No apears the 4608 columns!!</p> <p>Some idea?</p> <p>Thank you!</p> <p>Regards, Andres.</p>
0
2016-08-03T15:21:44Z
38,748,140
<p>The type of the <code>array</code> and the <code>fmt</code> option must match. Try:</p> <pre><code>import numpy as np np.savetxt('dataset.csv', array.astype(np.int), fmt='%d', delimiter=',') </code></pre> <p>where <code>array</code> is your numpy array.</p>
0
2016-08-03T15:41:42Z
[ "python", "arrays", "csv", "numpy" ]
Reshape (M, N, 3) numpy array to (M*N, 3)
38,747,683
<p>Suppose I have an RGB (or HSV) image represented by an (M, N, 3) numpy array wherein each dimension (<code>[x, y, 0]</code> or <code>[x, y, 1]</code>) represents a color channel value at a specific pixel. I want to reshape the array to (M*N, 3) where the color channels are combined (<code>[R1, G1, B1], [R2, G2, B2]</code>...) into a flat list (is that the correct terminology in this case?). I understand that one must use the reshape function, but I'm having difficulty understanding <em>how</em> to use the function. Any help is appreciated. </p> <p>EDIT: Here is an example of what I would like to happen. </p> <p>Input: (640 x 640 x 3) array representative of image where <code>[40, 40, 1]</code> would be the G value for a specific pixel. I want to take all 3 color channels and combine them into the following output. </p> <p>Output: <code>([R, G, B], [R, G, B], [R, G, B]...)</code></p>
0
2016-08-03T15:21:46Z
38,748,018
<p>If I understood you correctly, then, I would do something like this:</p> <pre><code>## loading the image... import matplotlib.pyplot as plt import matplotlib.image as mpimg image = mpimg.imread("my_image.jpg") ## extracting R, G, B and flatten them separately and then make ## an array out of them. res = np.transpose(np.array([image[...,0].flatten(), image[...,1].flatten(), image[...,2].flatten()])) </code></pre> <p>This might not be the most elegant way, but it will work. Actually, this do not give <code>(M, 3)</code> but it give <code>(MxN, 3)</code>. This should be actually desired, because with <code>(M, 3)</code> you are loosing some data!</p>
1
2016-08-03T15:36:22Z
[ "python", "arrays", "numpy" ]
Reshape (M, N, 3) numpy array to (M*N, 3)
38,747,683
<p>Suppose I have an RGB (or HSV) image represented by an (M, N, 3) numpy array wherein each dimension (<code>[x, y, 0]</code> or <code>[x, y, 1]</code>) represents a color channel value at a specific pixel. I want to reshape the array to (M*N, 3) where the color channels are combined (<code>[R1, G1, B1], [R2, G2, B2]</code>...) into a flat list (is that the correct terminology in this case?). I understand that one must use the reshape function, but I'm having difficulty understanding <em>how</em> to use the function. Any help is appreciated. </p> <p>EDIT: Here is an example of what I would like to happen. </p> <p>Input: (640 x 640 x 3) array representative of image where <code>[40, 40, 1]</code> would be the G value for a specific pixel. I want to take all 3 color channels and combine them into the following output. </p> <p>Output: <code>([R, G, B], [R, G, B], [R, G, B]...)</code></p>
0
2016-08-03T15:21:46Z
38,748,129
<p>If <code>img</code> is your array, you can use <code>img.reshape(-1, 3)</code>.</p> <p>For example,</p> <pre><code>In [50]: img.shape Out[50]: (5, 2, 3) In [51]: img Out[51]: array([[[2, 0, 4], [1, 4, 3]], [[2, 1, 4], [3, 2, 2]], [[2, 4, 1], [4, 0, 2]], [[1, 4, 2], [3, 2, 2]], [[3, 2, 1], [2, 1, 0]]]) In [53]: x = img.reshape(-1, 3) In [54]: x.shape Out[54]: (10, 3) In [55]: x Out[55]: array([[2, 0, 4], [1, 4, 3], [2, 1, 4], [3, 2, 2], [2, 4, 1], [4, 0, 2], [1, 4, 2], [3, 2, 2], [3, 2, 1], [2, 1, 0]]) </code></pre>
3
2016-08-03T15:41:14Z
[ "python", "arrays", "numpy" ]
Django rest framework filter by datetime field
38,747,697
<p>In <code>django-rest-framework</code> how can I filter a <code>datetimefield</code> using greater than filters.</p> <pre><code>class RestaurantList(generics.ListAPIView): serializer_class = RestaurantSerializer def get_queryset(self): #This returns equals but if I use the &gt; sign it does not work return Restaurant.objects.filter(last_update_time = "2016-08-03") </code></pre>
0
2016-08-03T15:22:28Z
38,752,616
<p>You can use <code>gt</code> statement like this:</p> <pre><code>def get_queryset(self): return Restaurant.objects.filter(last_update_time__gt=datetime(2016, 08, 03) </code></pre> <p>For more information see <a href="https://docs.djangoproject.com/en/1.9/ref/models/querysets/#gt" rel="nofollow">doc</a></p>
1
2016-08-03T20:01:32Z
[ "python", "django-models", "django-views", "django-rest-framework", "django-serializer" ]
Create QIcon from resources.qrc file
38,747,744
<p>I have a <code>resources.qrc</code> file that looks like this:</p> <pre><code>&lt;RCC&gt; &lt;qresource prefix="/plugins/fw_einsatz"&gt; &lt;file&gt;base_aerial.png&lt;/file&gt; &lt;file&gt;base_alkis.png&lt;/file&gt; &lt;file&gt;adr.png&lt;/file&gt; &lt;file&gt;gps_coord.png&lt;/file&gt; &lt;file&gt;road.png&lt;/file&gt; &lt;file&gt;route.png&lt;/file&gt; &lt;file&gt;icon.png&lt;/file&gt; &lt;/qresource&gt; &lt;/RCC&gt; </code></pre> <p>I want to create a QIcon from these resources with</p> <pre><code>icon = QIcon('qrc:///route.png') </code></pre> <p>and then put it on a QPushButton with</p> <pre><code>self.pushButton_toggle_epl_view.setIcon(icon) </code></pre> <p>but no Icon is displayed. What am I missing? Wrong path?</p>
0
2016-08-03T15:24:39Z
38,748,033
<p>Your path is wrong, try this instead :</p> <pre><code>icon = QIcon(":/plugins/fw_einsatz/route.png"); </code></pre>
2
2016-08-03T15:36:52Z
[ "python", "qt", "resources", "pyqt4", "qicon" ]
How to set request args with Flask test_client?
38,747,784
<p>I have to test out a certain view that gets certain information from request.args.</p> <p>I can't mock this since a lot of stuff in the view uses the request object. The only alternative I can think of is to manually set request.args.</p> <p>I can do that with he test_request_context(), e.g:</p> <pre><code>with self.app.test_request_context() as req: req.request.args = {'code': 'mocked access token'} MyView() </code></pre> <p>Now the request inside this view will have the arguments that I've set. However I need to call my view, not just initialize it, so I use this:</p> <pre><code>with self.app.test_client() as c: resp = c.get('/myview') </code></pre> <p>But I don't know how to manipulate the request arguments in this manner.</p> <p>I have tried this:</p> <pre><code>with self.app.test_client() as c: with self.app.test_request_context() as req: req.request.args = {'code': 'mocked access token'} resp = c.get('/myview') </code></pre> <p>but this does not set request.args.</p>
1
2016-08-03T15:26:19Z
38,748,102
<p>Pass the <code>query_string</code> argument to <code>c.get</code>, which can either be a <code>dict</code>, a <code>MultiDict</code>, or an already encoded string.</p> <pre><code>with app.test_client() as c: r = c.get('/', query_string={'name': 'davidism'}) </code></pre> <p>The <a href="http://werkzeug.pocoo.org/docs/0.11/test/#werkzeug.test.Client.open" rel="nofollow">test client request methods</a> pass their arguments to Werkzeug's <a href="http://werkzeug.pocoo.org/docs/0.11/test/#werkzeug.test.EnvironBuilder" rel="nofollow"><code>EnvironBuilder</code></a>, which is where this is documented.</p>
2
2016-08-03T15:40:02Z
[ "python", "unit-testing", "testing", "flask", "flask-testing" ]
Reindexing stacked DataFrame
38,747,804
<p>I would like to stack a dataframe and reindex. </p> <p>Initial dataframe looks like this:</p> <pre><code> 00:00 00:30 01:00 01:30 02:00 02:30 03:00 03:30 04:00 Date 2015-09-30 1.18 1.18 1.21 1.20 1.14 1.22 1.17 1.16 1.18 2015-01-10 1.19 1.22 1.19 1.21 1.15 1.19 1.22 1.18 1.93 2015-02-10 1.19 1.19 1.14 1.16 1.20 1.19 1.13 1.16 1.41 2015-03-10 1.16 1.19 1.16 1.15 1.16 1.16 1.18 1.12 1.16 2015-04-10 1.21 1.22 1.15 1.18 1.21 1.15 1.21 1.17 1.14 2015-05-10 1.18 1.20 1.14 1.19 1.13 1.23 1.18 1.13 1.98 2015-06-10 2.19 1.90 1.25 1.21 1.25 1.22 1.18 1.22 1.26 </code></pre> <p>after <code>stacked = df.stack()</code> I get the following:</p> <pre><code>Date 2015-09-30 00:00 1.18 00:30 1.18 01:00 1.21 01:30 1.20 02:00 1.14 02:30 1.22 03:00 1.17 03:30 1.16 04:00 1.18 04:30 3.21 05:00 13.70 05:30 10.55 06:00 6.77 06:30 4.69 07:00 3.52 07:30 3.04 08:00 5.42 08:30 4.92 09:00 5.31 09:30 5.89 10:00 5.61 10:30 5.48 11:00 4.15 11:30 4.13 12:00 5.40 12:30 6.22 13:00 4.98 13:30 4.12 14:00 4.32 14:30 5.29 2016-01-07 09:00 6.36 09:30 6.74 </code></pre> <p>which is what I would expect but then I want to reindex so index is correct timestamp like <code>YYYY-MM-DD HH:mm:ss</code>. I have tried:</p> <p><code>date_index = pd.date_range(data.index[0], end='2016-01-07 23:30:00', freq='30T' ) stackedreindex(date_index)</code></p> <p>but I'm getting an error</p> <p><code>ValueError: cannot include dtype 'M' in a buffer</code></p> <p>Any ideas? Thanks</p>
0
2016-08-03T15:27:09Z
38,751,540
<p>Let us create a dataframe that looks like what the OP has, </p> <pre><code>import pandas as pd cols = ['00:00', '00:30', '01:00', '01:30', '02:00', '02:30', '03:00', '03:30', '04:00'] df = pd.DataFrame(columns = cols) df.ix['2015-09-30'] = [1.18, 1.18, 1.21, 1.20, 1.14, 1.22, 1.17, 1.16, 1.18] df.ix['2015-01-10'] = [1.18, 1.18, 1.21, 1.20, 1.14, 1.22, 1.17, 1.16, 1.18] df.ix['2015-02-10'] = [1.18, 1.18, 1.21, 1.20, 1.14, 1.22, 1.17, 1.16, 1.18] df.ix['2015-03-10'] = [1.18, 1.18, 1.21, 1.20, 1.14, 1.22, 1.17, 1.16, 1.18] df.ix['2015-04-10'] = [1.18, 1.18, 1.21, 1.20, 1.14, 1.22, 1.17, 1.16, 1.18] df.ix['2015-05-30'] = [1.18, 1.18, 1.21, 1.20, 1.14, 1.22, 1.17, 1.16, 1.18] </code></pre> <p>When we stack this dataframe, we get a multilevel index. This can be converted to a single level index by using 'reset_index'. 'reset_index' gives us access to the levels as columns, like so,</p> <pre><code>stacked = df.stack().reset_index() print (stacked.head()) level_0 level_1 0 0 2015-09-30 00:00 1.18 1 2015-09-30 00:30 1.18 2 2015-09-30 01:00 1.21 3 2015-09-30 01:30 1.20 4 2015-09-30 02:00 1.14 </code></pre> <p>Now, we can merge the level_0 and level_1, convert it to a datetime index, drop the level_0 and level_1 columns to get the desired result, like so,</p> <pre><code>new_index = pd.to_datetime(stacked.level_0.astype('str')+' '+stacked.level_1.astype('str')) stacked.set_index(new_index, inplace = True) stacked.drop(['level_0', 'level_1'], axis =1, inplace = True) print (stacked.head()) 0 2015-09-30 00:00:00 1.18 2015-09-30 00:30:00 1.18 2015-09-30 01:00:00 1.21 2015-09-30 01:30:00 1.20 2015-09-30 02:00:00 1.14 </code></pre>
2
2016-08-03T18:53:13Z
[ "python", "pandas" ]
Django Static Url Error, Not Loading
38,747,850
<p>I'm currently mad at Django (1.9) right now! The saddest thing is 'Static URL' is the one giving me problem. 'Media URL' is working fine, no problem, but the static url is giving a huge headache.</p> <p>in my settings_dev.py</p> <pre><code>import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_PATH = os.path.abspath(os.path.dirname(__file__)) STATIC_ROOT = os.path.join(PROJECT_PATH,'../static/') STATIC_URL = '/static/' </code></pre> <p>when I add the below tag:</p> <pre><code>{% load static from staticfiles %} &lt;script type="text/javascript" src="{% static 'datepicker/js/bootstrap-datepicker.js' %}"&gt;&lt;/script&gt; </code></pre> <p>The js file won't load. when I check my source code, it will display the below link.</p> <pre><code> &lt;script type="text/javascript" src="/static/datepicker/js/bootstrap-datepicker.js"&gt;&lt;/script&gt; </code></pre> <p>And when I click it will redirect me to </p> <pre><code> http://127.0.0.1:8000/static/datepicker/js/bootstrap-datepicker.js </code></pre> <p>And display </p> <pre><code> Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/static/datepicker/js/bootstrap- datepicker.js </code></pre> <p>Now, I adjusted my urls.py to</p> <pre><code>if settings_dev.DEBUG: # static files (images, css, javascript, etc.) urlpatterns += patterns('', (r'^media/(?P&lt;path&gt;.*)$', 'django.views.static.serve', { 'document_root': settings_dev.MEDIA_ROOT, 'show_indexes': True}), (r'^static/(?P&lt;path&gt;.*)$', 'django.views.static.serve', { 'document_root': settings_dev.STATIC_ROOT, 'show_indexes': True}), ) </code></pre> <p>Yet, I'm still getting the same error!! Page not found issues.</p> <p>Project Directory</p> <pre><code>PROJECT NAME: Book/ SUB DIRECTORY: media static Template book bookapp manage.py (this is a file) </code></pre> <p>What am I missing?</p>
0
2016-08-03T15:28:56Z
38,748,202
<pre><code>STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"),] </code></pre> <p>That line is enough for serving your project <code>static</code> folder files... And you have to set this in your urls.py </p> <pre><code>urlpatterns = [ ... ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) </code></pre>
1
2016-08-03T15:45:05Z
[ "python", "django" ]
Django Static Url Error, Not Loading
38,747,850
<p>I'm currently mad at Django (1.9) right now! The saddest thing is 'Static URL' is the one giving me problem. 'Media URL' is working fine, no problem, but the static url is giving a huge headache.</p> <p>in my settings_dev.py</p> <pre><code>import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_PATH = os.path.abspath(os.path.dirname(__file__)) STATIC_ROOT = os.path.join(PROJECT_PATH,'../static/') STATIC_URL = '/static/' </code></pre> <p>when I add the below tag:</p> <pre><code>{% load static from staticfiles %} &lt;script type="text/javascript" src="{% static 'datepicker/js/bootstrap-datepicker.js' %}"&gt;&lt;/script&gt; </code></pre> <p>The js file won't load. when I check my source code, it will display the below link.</p> <pre><code> &lt;script type="text/javascript" src="/static/datepicker/js/bootstrap-datepicker.js"&gt;&lt;/script&gt; </code></pre> <p>And when I click it will redirect me to </p> <pre><code> http://127.0.0.1:8000/static/datepicker/js/bootstrap-datepicker.js </code></pre> <p>And display </p> <pre><code> Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/static/datepicker/js/bootstrap- datepicker.js </code></pre> <p>Now, I adjusted my urls.py to</p> <pre><code>if settings_dev.DEBUG: # static files (images, css, javascript, etc.) urlpatterns += patterns('', (r'^media/(?P&lt;path&gt;.*)$', 'django.views.static.serve', { 'document_root': settings_dev.MEDIA_ROOT, 'show_indexes': True}), (r'^static/(?P&lt;path&gt;.*)$', 'django.views.static.serve', { 'document_root': settings_dev.STATIC_ROOT, 'show_indexes': True}), ) </code></pre> <p>Yet, I'm still getting the same error!! Page not found issues.</p> <p>Project Directory</p> <pre><code>PROJECT NAME: Book/ SUB DIRECTORY: media static Template book bookapp manage.py (this is a file) </code></pre> <p>What am I missing?</p>
0
2016-08-03T15:28:56Z
38,748,791
<p>Okay to make things clear for you.</p> <p>STATIC_ROOT is that directory where all your static data gets collected when you want to serve your files on another server, say <strong>APACHE or NGINX or maybe on Heroku</strong> or so.</p> <p>If don't want just want to run your web-app on your local development server, you don't require <code>python manage.py collectstatic</code> and hence you don't need STATIC_ROOT.</p> <p>All you need is <code>STATIC_URL</code> and in case you have your static files at some other location as well then you also need <code>STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"),]</code>.</p> <p>So you'll be having a folder named `static' at the base directory level where django will look for your static files.</p> <p>If you specify the same folder for <code>STATIC_DIRS</code> and <code>STATIC_ROOT</code> then you'll automatically get an error. Django won't allow you to do that as technically you are trying to give the same directory for two different purposes.</p> <p>See this for a detailed explanation -> <a href="http://stackoverflow.com/questions/24022558/differences-between-staticfiles-dir-static-root-and-media-root">Differences between STATICFILES_DIR, STATIC_ROOT and MEDIA_ROOT</a></p>
1
2016-08-03T16:13:38Z
[ "python", "django" ]
python runtime version statistics
38,747,864
<p>Is there any breakdown of how many devices have python 2.6, 2.7, 3.*?</p> <p>I'm spoiled by OS install statistics, like <a href="https://developer.android.com/about/dashboards/index.html" rel="nofollow">Android's</a>. Of course, the collection methods used there aren't available to Python. For Java, I found <a href="https://plumbr.eu/blog/java/java-version-and-vendor-data-analyzed-2016-edition" rel="nofollow">this</a>, which certainly isn't official, and the methodology leaves a lot to be desired, but that's the kind of thing I'm interested in.</p>
0
2016-08-03T15:29:34Z
38,748,469
<p>There was a survey in 2014 on usage statistics, mostly on 2.x vs 3.x. But not including platforms/devices.</p> <p><a href="http://www.randalolson.com/2015/01/30/python-usage-survey-2014/" rel="nofollow">The python usage survey</a> includes a more thorough breakdown: <a href="http://i.stack.imgur.com/Jqi6q.png" rel="nofollow"><img src="http://i.stack.imgur.com/Jqi6q.png" alt="python usage survey graph"></a></p> <p>The website credited with the underlying data is <a href="http://web.archive.org/web/20150228101023/http://blog.frite-camembert.net:80/python-survey-2014.html" rel="nofollow">here</a>.</p> <p>And there is always google trends, which obviously is not a usage breakdown but rather a more general account of how popular search terms are. It would allow for search terms such as "python android" and "python iOS". See <a href="https://www.google.co.uk/trends/explore?date=today%2012-m&amp;q=python%202,python%203,python%202.7" rel="nofollow">here</a>: <a href="http://i.stack.imgur.com/G0ibP.png" rel="nofollow"><img src="http://i.stack.imgur.com/G0ibP.png" alt="google trends python comparison"></a></p> <p>I think checking distributions such as Anaconda would be a way of approximating python version and OSs. Unfortunately, the Anaconda website does not include a number-of-downloads tracker that is rather common. Another approximation would be the number of commits for Spyder releases on <a href="https://github.com/spyder-ide/spyder/releases" rel="nofollow">GitHub</a>.</p>
1
2016-08-03T15:58:08Z
[ "python" ]
How do I prevent my medians from being rounded?
38,747,952
<p>I have code which calculates the median of z-scores, which range from 0 to 1. Python is rounding all these numbers to 0. How would I make sure these numbers are not rounded?</p> <p>Here's the line of code in which I calculate the medians:</p> <pre><code>gene_medians = GCT_object.data_df.median(axis=1) </code></pre> <pre><code>import matplotlib.pyplot as plt import parse_gctoo def histo_plotter(file, plot_title, ax): # read in file as string GCT_object = parse_gctoo.parse(file) # computing median of rows in data_df gene_medians = GCT_object.data_df.median(axis=1) unrounded_gm = format(gene_medians, ".7f") # making histogram of medians print gene_medians' </code></pre> <p>Outcome of .describe: /Users/eibelman/miniconda2/envs/josh_env/bin/python2.7 /Users/eibelman/Analysis/ComparingMedianGeneExpressionDifCellLines.py cid CXA061_SKL_48H_X1_B29:A03 CXA061_SKL_48H_X1_B29:A04 \ count 978.000000 978.000000<br> mean 0.072729 0.078196<br> std 2.909874 3.086884<br> min -18.698500 -63.467600<br> 25% -0.742375 -0.422625<br> 50% -0.030950 0.205600<br> 75% 0.656550 0.885275<br> max 29.803200 27.347300 </p> <p>cid CXA061_SKL_48H_X1_B29:A05 CXA061_SKL_48H_X1_B29:A06 \ count 978.000000 978.000000<br> mean 0.036843 0.002883<br> std 2.471833 2.576255<br> min -17.170500 -26.433600<br> 25% -0.653925 -0.674250<br> 50% -0.081250 -0.070600<br> 75% 0.548900 0.561250<br> max 31.356600 34.249100 </p> <p>cid CXA061_SKL_48H_X1_B29:A07 CXA061_SKL_48H_X1_B29:A08 \ count 978.000000 978.000000<br> mean 0.017625 0.096359<br> std 2.012941 2.671352<br> min -18.651800 -27.609600<br> 25% -0.711400 -0.730225<br> 50% -0.048900 -0.012100<br> 75% 0.585300 0.670100<br> max 23.690800 27.509200 </p> <p>cid CXA061_SKL_48H_X1_B29:A09 CXA061_SKL_48H_X1_B29:A10 \ count 978.000000 978.000000<br> mean -0.024301 -0.048213<br> std 3.317470 3.431853<br> min -70.184100 -43.255000<br> 25% -0.556725 -0.916150<br> 50% 0.009950 -0.071200<br> 75% 0.629525 0.836525<br> max 32.083000 36.831200 </p> <p>cid CXA061_SKL_48H_X1_B29:A11 CXA061_SKL_48H_X1_B29:A12 \ count 978.000000 978.000000<br> mean 0.040646 -0.013686<br> std 2.568421 3.296173<br> min -17.213400 -42.862500<br> 25% -0.636600 -0.719425<br> 50% -0.032850 -0.033950<br> 75% 0.593925 0.680675<br> max 26.524500 50.334500 </p> <p>cid ... CXA061_SKL_48H_X1_B29:P15 \ count ... 978.000000<br> mean ... -0.006012<br> std ... 2.564106<br> min ... -20.208400<br> 25% ... -0.706475<br> 50% ... -0.136300<br> 75% ... 0.557025<br> max ... 27.509500 </p> <p>cid CXA061_SKL_48H_X1_B29:P16 CXA061_SKL_48H_X1_B29:P17 \ count 978.000000 978.000000<br> mean 0.041587 -0.001685<br> std 1.713974 3.091669<br> min -12.695900 -34.948900<br> 25% -0.569150 -0.642050<br> 50% 0.000000 0.050800<br> 75% 0.637700 0.818025<br> max 22.556600 25.772400 </p> <p>cid CXA061_SKL_48H_X1_B29:P18 CXA061_SKL_48H_X1_B29:P19 \ count 978.000000 978.000000<br> mean -0.019696 0.061637<br> std 2.570132 2.648487<br> min -33.142900 -29.076300<br> 25% -0.798700 -0.632600<br> 50% -0.057600 0.048900<br> 75% 0.588375 0.679500<br> max 30.018900 30.709400 </p> <p>cid CXA061_SKL_48H_X1_B29:P20 CXA061_SKL_48H_X1_B29:P21 \ count 978.000000 978.000000<br> mean 0.026416 -0.004739<br> std 2.616890 2.135260<br> min -31.187200 -15.955000<br> 25% -0.608050 -0.732750<br> 50% 0.008050 -0.116500<br> 75% 0.638025 0.647625<br> max 23.348100 24.229200 </p> <p>cid CXA061_SKL_48H_X1_B29:P22 CXA061_SKL_48H_X1_B29:P23 \ count 978.000000 978.000000<br> mean 0.019632 0.002053<br> std 2.581926 2.356626<br> min -23.168000 -27.271400<br> 25% -0.674500 -0.683150<br> 50% -0.026800 -0.001000<br> 75% 0.711800 0.721400<br> max 38.533300 27.568000 </p> <p>cid CXA061_SKL_48H_X1_B29:P24<br> count 978.000000<br> mean -0.043314<br> std 1.704406<br> min -9.464100<br> 25% -0.780525<br> 50% -0.144250<br> 75% 0.515325<br> max 19.056400 </p> <p>[8 rows x 372 columns]</p> <p>Process finished with exit code 0</p>
0
2016-08-03T15:33:22Z
38,748,349
<p>If you are using pandas data frame (data_df) then you can use median function form numpy package. </p> <pre><code>gene_medians = numpy.median(GCT_object.data_df[[1]]) </code></pre> <p>or </p> <pre><code>gene_medians = GCT_object.data_df[[1]].apply(numpy.median) </code></pre>
0
2016-08-03T15:51:51Z
[ "python", "rounding", "median" ]
Why does this return None?
38,747,994
<p>I'm testing out <a href="https://repl.it/languages/python3" rel="nofollow">repl.it</a> (running Python 3.5.1) and I noticed that after every line of input into the console, the console replies with <code>None</code>. I'm not using any fancy definitions with forgotten return values, this happens even after assignment statements. What is going on here? </p> <p>Example:</p> <pre><code>x,y,z=1,2,3 =&gt; None print(x+y+z) 6 =&gt; None </code></pre>
0
2016-08-03T15:35:05Z
38,748,258
<p>None is the default return value of statements that do not have a return value. Some interpreter shells display it, some don't.</p> <p>It's perfectly normal, don't worry about it.</p>
2
2016-08-03T15:47:57Z
[ "python", "python-3.5" ]
Passing data from a method to a class then returning value in another method
38,748,010
<p>Question how can I pass the value from get_sheet_header class into another method basically I want to the set a HTML response header and my pk then drop it down into another method I use any help would be greatly appreciated and any questions please let me know. </p> <p>Here is what I have so far </p> <p>views.py </p> <pre><code>**#here is where I want to pass the value to my get_sheet_header class** def update_sheet(request, pk=None): obj = get_object_or_404(Sheet, pk=pk) form = SheetUpdateForm(request.POST or None, request.FILES or None, instance=obj) if request.method == 'POST': if form.is_valid(): form.save() return redirect('sheet_update.html') response = render(request, 'app/sheet_update.html', { 'sheet_form': form, 'title':'Update Sheet', }) response['SHEET_ID'] = pk get_sheet_header.sheet_header(get_sheet_header(pk)) return response **#here is my get_sheet_header class** class get_sheet_header(object): def __init__(self, s_id): self.s_id = s_id def sheet_header(self): s = self.s_id return s **#here is where I want to use the value that the above returns ^** def add_dimensions(request, pk): pk = get_sheet_header() #this should be the return value from my get_sheet_header class </code></pre>
-2
2016-08-03T15:35:57Z
38,748,221
<p>Just create direct instance of your class and then call method.</p> <pre><code>tmp_obj = get_sheet_header(obj) pk = tmp_obj.sheet_reader() </code></pre>
0
2016-08-03T15:46:05Z
[ "python", "django", "python-2.7" ]
Passing data from a method to a class then returning value in another method
38,748,010
<p>Question how can I pass the value from get_sheet_header class into another method basically I want to the set a HTML response header and my pk then drop it down into another method I use any help would be greatly appreciated and any questions please let me know. </p> <p>Here is what I have so far </p> <p>views.py </p> <pre><code>**#here is where I want to pass the value to my get_sheet_header class** def update_sheet(request, pk=None): obj = get_object_or_404(Sheet, pk=pk) form = SheetUpdateForm(request.POST or None, request.FILES or None, instance=obj) if request.method == 'POST': if form.is_valid(): form.save() return redirect('sheet_update.html') response = render(request, 'app/sheet_update.html', { 'sheet_form': form, 'title':'Update Sheet', }) response['SHEET_ID'] = pk get_sheet_header.sheet_header(get_sheet_header(pk)) return response **#here is my get_sheet_header class** class get_sheet_header(object): def __init__(self, s_id): self.s_id = s_id def sheet_header(self): s = self.s_id return s **#here is where I want to use the value that the above returns ^** def add_dimensions(request, pk): pk = get_sheet_header() #this should be the return value from my get_sheet_header class </code></pre>
-2
2016-08-03T15:35:57Z
38,749,049
<p>So instead of making this overly complicated like I was doing. I decided to dumb it down and do it this way and it works :).</p> <pre><code>def update_sheet(request, pk=None): blahh blah... global = SHEET_HEADER_ID SHEET_HEADER_ID = pk def add_dimension(request, pk): pk = SHEET_HEADER_ID </code></pre>
-1
2016-08-03T16:27:32Z
[ "python", "django", "python-2.7" ]
change column values (and type) to a pandas Dataframe
38,748,026
<p>I am trying to rename a column in a pandas dataframes, but different dataframes have different types of columns and I need an help. An easy example will clarify you my issue.</p> <pre><code>import pandas as pd dic1 = {'a': [4, 1, 3, 1], 'b': [4, 2, 1, 4], 'c': [5, 7, 9, 1]} dic2 = {1: [4, 1, 3, 1], 2: [4, 2, 1, 4], 3: [5, 7, 9, 1]} df1 = pd.DataFrame(dic1) df2 = pd.DataFrame(dic2) </code></pre> <p>Now if I type</p> <pre><code>df1.columns.values[-1] = 'newName' </code></pre> <p>I can easily change the last column name of the first dataframe, but if I type</p> <pre><code>df2.columns.values[-1] = 'newName' </code></pre> <p>I get a message of error from Python as the columns in the second dataframe are of different type. Is there a way to change the type of those columns and/or make Python understand in some ways that even the last column of df2 has to be named 'newName'?</p>
2
2016-08-03T15:36:40Z
38,748,104
<p>This isn't the normal method to rename a column, you should use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rename.html" rel="nofollow"><code>rename</code></a> to do this:</p> <pre><code>In [95]: df2.rename(columns={df2.columns[-1]:'newName'}, inplace=True) df2 Out[95]: 1 2 newName 0 4 4 5 1 1 2 7 2 3 1 9 3 1 4 1 </code></pre>
3
2016-08-03T15:40:11Z
[ "python", "pandas" ]
Remove or empty all data from a pandas dataframe
38,748,032
<p>I have a dataframe (df) which I would like to recycle. Its full of data and I would like to remove everything from this dataframe. Would df.drop() work?</p> <p>Thanks</p>
1
2016-08-03T15:36:48Z
38,749,922
<p>if you want to free some space</p> <pre><code>import gc del adios_df gc.collect() </code></pre>
1
2016-08-03T17:15:40Z
[ "python", "pandas" ]
How to migrate the local database on heroku with new tables?
38,748,038
<p>I get the error:</p> <pre><code>Exception Value: no such table: hello_surname </code></pre> <p>when i try to show a view that accesses the Surname model</p> <p>in my models.py</p> <pre><code>class Surname(models.Model): created = models.DateTimeField('date created', auto_now_add=True) name = models.CharField(max_length=35) </code></pre> <p>I've tried to run the migrate <code>$ heroku run python manage.py migrate</code></p> <p>ouput:</p> <pre><code>Running python manage.py migrate on ⬢ sleepy-fjord... up, run.7027 Operations to perform: Apply all migrations: sessions, auth, hello, contenttypes, admin Running migrations: No migrations to apply. Your models have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. </code></pre> <p>then i run <code>$ heroku run python manage.py makemigrations</code></p> <p>output: </p> <pre><code>Running python manage.py makemigrations on ⬢ sleepy-fjord... up, run.8567 Migrations for 'hello': 0002_surname.py: - Create model Surname </code></pre> <p>when i run the top migrate again, it just gives the same output as when i ran it the first time. Seems like I am missing a step here, but with the output i can't seem to figure it out by myself. Anyone know any solutions?</p>
1
2016-08-03T15:37:17Z
38,748,138
<p>You <strong>must</strong> run make migrations <em>locally</em>, commit the results, then run migrate on Heroku.</p>
0
2016-08-03T15:41:37Z
[ "python", "django", "heroku" ]
Functions on groups in pandas with range selected by label
38,748,191
<p>Consider the following Multiindex Pandas Seires:</p> <pre><code>import pandas as pd import numpy as np val = np.array([ 0.4, -0.6, 0.6, 0.5, -0.4, 0.2, 0.6, 1.2, -0.4]) inds = [(-1000, 1921.6), (-1000, 1922.3), (-1000, 1923.0), (-500, 1921.6), (-500, 1922.3), (-500, 1923.0), (-400, 1921.6), (-400, 1922.3), (-400, 1923.0)] names = ['pp_delay', 'wavenumber'] example = pd.Series(val) example.index = pd.MultiIndex.from_tuples(inds, names=names) </code></pre> <p><code>example</code> should now look like</p> <pre><code>pp_delay wavenumber -1000 1921.6 0.4 1922.3 -0.6 1923.0 0.6 -500 1921.6 0.5 1922.3 -0.4 1923.0 0.2 -400 1921.6 0.6 1922.3 1.2 1923.0 -0.4 dtype: float64 </code></pre> <p>I want to group example by <code>pp_delay</code> and select a <strong>range within each group</strong> using the <code>wavenumber</code> <strong>index</strong> and perform an operation on that subgroup. To clarify what I mean, I have a few examples.</p> <p>Here is a position based solution.</p> <pre><code>example.groupby(level="pp_delay").nth(list(range(1,3))).groupby(level="pp_delay").sum() </code></pre> <p>this gives</p> <pre><code>pp_delay -1000 0.0 -500 -0.2 -400 0.8 dtype: float64 </code></pre> <p>Now the last to elements of each <code>pp_delay</code> group have been summed.</p> <p>An alternative solution and more straight forward is to loop over the groups:</p> <pre><code>delays = example.index.levels[0] res = np.zeros(delays.shape) roi = slice(1922, 1924) for i in range(3): res[i] = example[delays[i]][roi].sum() res </code></pre> <p>gives</p> <pre><code>array([ 0. , -0.2, 0.8]) </code></pre> <p>Anyhow I don't like it much ether because it doesn't fit well with the usual pandas style.</p> <p>Now what I ideally would want something like:</p> <pre><code>example.groupby(level="pp_delay").loc[1922:1924].sum() </code></pre> <p>or maybe even something like</p> <pre><code>example[:, 1922:1924].sum() </code></pre> <p>But apparently pandas indexing doesn't work that way. Anybody got a better way?</p> <p>Cheers</p>
1
2016-08-03T15:44:25Z
38,748,745
<p>I'd skip the <code>groupby</code></p> <pre><code>example.unstack(0).ix[1922:1924].sum() pp_delay -1000 0.0 -500 -0.2 -400 0.8 dtype: float64 </code></pre>
3
2016-08-03T16:11:22Z
[ "python", "pandas" ]
Checking and accessing array element without error
38,748,252
<p>I have array, which I want to validate, 2nd item of that array. There are 2 ways which comes to my mind</p> <ol> <li><p>Check for <code>array</code> length</p> <pre><code>if len(array) &gt; 1: # Process for array[1] </code></pre></li> <li><p>Catch <code>IndexError</code> and process in <code>else</code> block.</p> <pre><code>try: array[1] except IndexError: pass else: # Process for array[1] </code></pre></li> </ol> <p>Which one is better?</p> <p>If you have any other option, I am ready to learn :)</p>
1
2016-08-03T15:47:43Z
38,748,438
<p>Python encourages <a href="https://docs.python.org/3/glossary.html#term-eafp" rel="nofollow">EAFP coding style</a>:</p> <blockquote> <p><strong>EAFP</strong><br> Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many <a href="https://docs.python.org/3/reference/compound_stmts.html#try" rel="nofollow"><code>try</code></a> and <a href="https://docs.python.org/3/reference/compound_stmts.html#except" rel="nofollow"><code>except</code></a> statements. The technique contrasts with the <a href="https://docs.python.org/3/glossary.html#term-lbyl" rel="nofollow">LBYL</a> style common to many other languages such as C.</p> </blockquote> <p>This means the <code>try</code> / <code>except</code> is perfectly fine, but you do not have to use the <code>else</code> clause, simply do:</p> <pre><code>try: # Process for array[1] except IndexError: pass </code></pre>
4
2016-08-03T15:56:20Z
[ "python", "if-statement", "exception" ]
Checking and accessing array element without error
38,748,252
<p>I have array, which I want to validate, 2nd item of that array. There are 2 ways which comes to my mind</p> <ol> <li><p>Check for <code>array</code> length</p> <pre><code>if len(array) &gt; 1: # Process for array[1] </code></pre></li> <li><p>Catch <code>IndexError</code> and process in <code>else</code> block.</p> <pre><code>try: array[1] except IndexError: pass else: # Process for array[1] </code></pre></li> </ol> <p>Which one is better?</p> <p>If you have any other option, I am ready to learn :)</p>
1
2016-08-03T15:47:43Z
38,748,500
<p>If your array should have at least 2 items, I would do an assert:</p> <pre><code>assert len(array) &gt; 1, "Array should have at least 2 items" </code></pre> <p>If your array could have 2 items I would use the first form:</p> <pre><code>if len(array) &gt; 1: # Process for array[1] </code></pre> <p>For me the try form can be less readable in the long run especially if you need to catch exceptions in the "Process for array[1]" part...</p>
1
2016-08-03T15:59:19Z
[ "python", "if-statement", "exception" ]
Disable autouse fixtures on specific pytest marks
38,748,257
<p>Is it possible to prevent the execution of "function scoped" fixtures with <code>autouse=True</code> on specific marks only?</p> <p>I have the following fixture set to autouse so that all outgoing requests are automatically mocked out:</p> <pre><code>@pytest.fixture(autouse=True) def no_requests(monkeypatch): monkeypatch.setattr("requests.sessions.Session.request", MagicMock()) </code></pre> <p>But I have a mark called <code>endtoend</code> that I use to define a series of tests that are allowed to make external requests for more robust end to end testing. I would like to inject <code>no_requests</code> in all tests (the vast majority), but not in tests like the following:</p> <pre><code>@pytest.mark.endtoend def test_api_returns_ok(): assert make_request().status_code == 200 </code></pre> <p>Is this possible?</p>
0
2016-08-03T15:47:56Z
38,750,332
<p>I wasn't able to find a way to disable fixtures with <code>autouse=True</code>, but I did find a way to revert the changes made in my <code>no_requests</code> fixture. <a href="http://doc.pytest.org/en/latest/monkeypatch.html" rel="nofollow"><code>monkeypatch</code></a> has a method <code>undo</code> that reverts all patches made on the stack, so I was able to call it in my endtoend tests like so:</p> <pre><code>@pytest.mark.endtoend def test_api_returns_ok(monkeypatch): monkeypatch.undo() assert make_request().status_code == 200 </code></pre>
0
2016-08-03T17:39:12Z
[ "python", "py.test", "pytest-django" ]
Disable autouse fixtures on specific pytest marks
38,748,257
<p>Is it possible to prevent the execution of "function scoped" fixtures with <code>autouse=True</code> on specific marks only?</p> <p>I have the following fixture set to autouse so that all outgoing requests are automatically mocked out:</p> <pre><code>@pytest.fixture(autouse=True) def no_requests(monkeypatch): monkeypatch.setattr("requests.sessions.Session.request", MagicMock()) </code></pre> <p>But I have a mark called <code>endtoend</code> that I use to define a series of tests that are allowed to make external requests for more robust end to end testing. I would like to inject <code>no_requests</code> in all tests (the vast majority), but not in tests like the following:</p> <pre><code>@pytest.mark.endtoend def test_api_returns_ok(): assert make_request().status_code == 200 </code></pre> <p>Is this possible?</p>
0
2016-08-03T15:47:56Z
38,754,249
<p><strong>It would be difficult and probably not possible to cancel or change the autouse</strong></p> <p>You can't canel an autouse, being as it's <strong>auto</strong>use. Maybe you could do something to change the autouse fixture based on a mark's condition. But this would be hackish and difficult.</p> <p>possibly with:</p> <pre><code>import pytest from _pytest.mark import MarkInfo </code></pre> <p>I couldn't find a way to do this, but maybe the <code>@pytest.fixture(autouse=True)</code> could get the MarkInfo and if it came back 'endtoend' the fixture wouldn't set the attribute. But you would also have to set a condition in the fixture parameters.</p> <p>i.e.: <code>@pytest.fixture(True=MarkInfo, autouse=True)</code>. Something like that. But I couldn't find a way.</p> <hr> <p><strong>It's recommended that you organize tests to prevent this</strong></p> <p>You could just separate the no_requests from the endtoend tests by either:</p> <ol> <li>limit the scope of your autouse fixture</li> <li>put the no_requests into a class</li> <li>Not make it an auto use, just pass it into the params of each def you need it</li> </ol> <p>Like so: </p> <pre><code>class NoRequests: @pytest.fixture(scope='module', autouse=True) def no_requests(monkeypatch): monkeypatch.setattr("requests.sessions.Session.request", MagicMock()) def test_no_request1(self): # do stuff here # and so on </code></pre> <p>This is good practice. Maybe a different organization could help</p> <hr> <h2>But in your case, it's probably easiest to <code>monkeypatch.undo()</code></h2>
0
2016-08-03T21:52:37Z
[ "python", "py.test", "pytest-django" ]
Disable autouse fixtures on specific pytest marks
38,748,257
<p>Is it possible to prevent the execution of "function scoped" fixtures with <code>autouse=True</code> on specific marks only?</p> <p>I have the following fixture set to autouse so that all outgoing requests are automatically mocked out:</p> <pre><code>@pytest.fixture(autouse=True) def no_requests(monkeypatch): monkeypatch.setattr("requests.sessions.Session.request", MagicMock()) </code></pre> <p>But I have a mark called <code>endtoend</code> that I use to define a series of tests that are allowed to make external requests for more robust end to end testing. I would like to inject <code>no_requests</code> in all tests (the vast majority), but not in tests like the following:</p> <pre><code>@pytest.mark.endtoend def test_api_returns_ok(): assert make_request().status_code == 200 </code></pre> <p>Is this possible?</p>
0
2016-08-03T15:47:56Z
38,763,328
<p>You can also use the <a href="http://docs.pytest.org/en/latest/fixture.html#fixtures-can-introspect-the-requesting-test-context" rel="nofollow"><code>request</code> object</a> in your fixture to check the markers used on the test, and don't do anything if a specific marker is set:</p> <pre><code>import pytest @pytest.fixture(autouse=True) def autofixt(request): if 'noautofixt' in request.keywords: return print("patching stuff") def test1(): pass @pytest.mark.noautofixt def test2(): pass </code></pre> <p>Output with <code>-vs</code>:</p> <pre><code>x.py::test1 patching stuff PASSED x.py::test2 PASSED </code></pre>
2
2016-08-04T09:19:41Z
[ "python", "py.test", "pytest-django" ]
Trying to convert all values in a dictionary to int through dictionary comprehension
38,748,420
<p>I have a dictionary like this:</p> <pre><code>{1: 'rattle', 2: '204', 3: 'three', 4: 404, 5: '104', 6: 'pythonic'} </code></pre> <p>And I want to convert all values to integer, wherever possible, through dictionary comprehension. So I want this:</p> <pre><code>{1: 'rattle', 2: 204, 3: 'three', 4: 404, 5: 104, 6: 'pythonic'} </code></pre> <p>I tried:</p> <pre><code>{i: int(m[i]) for i in m if type(m[i]) == str and m[i].isdigit()} </code></pre> <p>but it includes only those values which are string and can be converted to integer. I have also tried putting the whole thing in a try catch, but it doesn't work</p> <p>I know this can be done through a simple for loop but is there any other way?</p>
0
2016-08-03T15:55:23Z
38,748,461
<p>By adding an <code>if</code> to the end of your loop, you are <em>filtering</em>, limiting your output to key-value pairs where the value is a string and consists of digits.</p> <p>Use a conditional expression in the value expression instead; that way you keep <em>all</em> key-value pairs but only apply <code>int()</code> to values where this matters and include the rest unchanged:</p> <pre><code>{k: int(v) if isinstance(v, str) and v.isdigit() else v for k, v in m.items()} </code></pre> <p>Rather than just iterate over <code>m</code> (and only get the keys), I used <code>dict.items()</code> to get both the key and the corresponding value in one step.</p>
2
2016-08-03T15:57:37Z
[ "python", "dictionary", "dictionary-comprehension" ]
Trying to convert all values in a dictionary to int through dictionary comprehension
38,748,420
<p>I have a dictionary like this:</p> <pre><code>{1: 'rattle', 2: '204', 3: 'three', 4: 404, 5: '104', 6: 'pythonic'} </code></pre> <p>And I want to convert all values to integer, wherever possible, through dictionary comprehension. So I want this:</p> <pre><code>{1: 'rattle', 2: 204, 3: 'three', 4: 404, 5: 104, 6: 'pythonic'} </code></pre> <p>I tried:</p> <pre><code>{i: int(m[i]) for i in m if type(m[i]) == str and m[i].isdigit()} </code></pre> <p>but it includes only those values which are string and can be converted to integer. I have also tried putting the whole thing in a try catch, but it doesn't work</p> <p>I know this can be done through a simple for loop but is there any other way?</p>
0
2016-08-03T15:55:23Z
38,748,518
<pre><code>{k: int(v) if str(v).isdigit() else v for k, v in m.items()} </code></pre>
1
2016-08-03T16:00:23Z
[ "python", "dictionary", "dictionary-comprehension" ]
Can't run script from another script
38,748,435
<p>I'd like to end a process after certain conditions are met within a script. like this:</p> <pre><code>import psutil PROCNAME = "standard.exe" for proc in psutil.process_iter(): if proc.name() == PROCNAME: proc.kill() </code></pre> <p>I can run this standalone script (processkiller.py) in Spyder and it works but I'd would like to run this script from another script, like this:</p> <pre><code>os.system("C:\\Users\\s086372\\Desktop\\results\ProcessKiller.py") </code></pre> <p>This doesn't work, any suggestions? I'm still a beginner who is using simple codes to script engineering simulations.</p> <p>the <code>mdb.jobs.kill(</code>) within abaqus doesn't work, it's bugging, so I have to manually kill the process in some way.</p>
0
2016-08-03T15:56:16Z
38,748,494
<p>Use:</p> <pre><code>os.system("python C:\\Users\\s086372\\Desktop\\results\ProcessKiller.py") </code></pre> <p>You have to pass the .py to the python interpreter.</p>
2
2016-08-03T15:59:08Z
[ "python", "abaqus" ]
Can't run script from another script
38,748,435
<p>I'd like to end a process after certain conditions are met within a script. like this:</p> <pre><code>import psutil PROCNAME = "standard.exe" for proc in psutil.process_iter(): if proc.name() == PROCNAME: proc.kill() </code></pre> <p>I can run this standalone script (processkiller.py) in Spyder and it works but I'd would like to run this script from another script, like this:</p> <pre><code>os.system("C:\\Users\\s086372\\Desktop\\results\ProcessKiller.py") </code></pre> <p>This doesn't work, any suggestions? I'm still a beginner who is using simple codes to script engineering simulations.</p> <p>the <code>mdb.jobs.kill(</code>) within abaqus doesn't work, it's bugging, so I have to manually kill the process in some way.</p>
0
2016-08-03T15:56:16Z
38,754,053
<p>This isn't an answer, but I have to use this since I want to make clear my block of code and I can't in the comments</p> <pre><code>PROCNAME = "standard.exe" for proc in psutil.process_iter(): print ('Entered the for loop') if proc.name() == PROCNAME: print ('Entered the IF statement') proc.terminate() proc.kill() </code></pre> <p>As I have said, I do not enter the IF statement. While this does happen when using the script in spyder. </p>
0
2016-08-03T21:38:01Z
[ "python", "abaqus" ]
How do you concatenate two (or more) dataframes into a panel
38,748,446
<p>I was recently trying to concatenate two dataframes into a panel and I tried to use <code>pd.concat</code> with <code>axis=2</code></p> <p>Consider the dataframes <code>df1</code> and <code>df2</code></p> <pre><code>df1 = pd.DataFrame(np.random.rand(3, 3), list('abc'), list('def')) df2 = pd.DataFrame(np.random.rand(3, 3), list('abc'), list('def')) </code></pre> <p>Then I tried</p> <pre><code>pd.concat([df1, df2], axis=2) </code></pre> <p><a href="http://i.stack.imgur.com/tsMBi.png" rel="nofollow"><img src="http://i.stack.imgur.com/tsMBi.png" alt="enter image description here"></a></p> <p>This looked the same as if I had used <code>axis=1</code>. Maybe pandas is just checking if <code>axis</code> evaluates to <code>True</code>. Let's try</p> <pre><code>pd.concat([df1, df2], axis='This Has To Break...Right?') </code></pre> <p><a href="http://i.stack.imgur.com/tsMBi.png" rel="nofollow"><img src="http://i.stack.imgur.com/tsMBi.png" alt="enter image description here"></a></p> <p>Nope! Did not break. Ok, so how do I concat two dataframes along <code>axis=2</code></p> <p>I could</p> <pre><code>pd.Panel(np.stack([df1, df2])).to_frame() </code></pre> <p><a href="http://i.stack.imgur.com/a3sbN.png" rel="nofollow"><img src="http://i.stack.imgur.com/a3sbN.png" alt="enter image description here"></a></p> <p>But this ignores the indices and will not align them if they were different.</p> <p>I'd want something that looks like</p> <pre><code>panel &lt;class 'pandas.core.panel.Panel'&gt; Dimensions: 2 (items) x 3 (major_axis) x 3 (minor_axis) Items axis: 0 to 1 Major_axis axis: a to c Minor_axis axis: d to f panel.to_frame() </code></pre> <p><a href="http://i.stack.imgur.com/QrFrf.png" rel="nofollow"><img src="http://i.stack.imgur.com/QrFrf.png" alt="enter image description here"></a></p>
1
2016-08-03T15:56:37Z
38,748,564
<p>You can use the <code>pd.Panel</code> constructor and pass a dictionary of dataframes.</p> <pre><code>def concat2(dfs, keys=None): if keys is None: keys = range(len(dfs)) return pd.Panel({k:v for k, v in zip(keys, dfs)}) </code></pre> <p>This feels like what a <code>pd.concat(dfs, axis=1, keys=keys)</code> should do.</p> <hr> <h3>Demonstration</h3> <pre><code>concat2([df1, df2]).to_frame() </code></pre> <p><a href="http://i.stack.imgur.com/YvMWc.png" rel="nofollow"><img src="http://i.stack.imgur.com/YvMWc.png" alt="enter image description here"></a></p> <pre><code>concat2([df1, df2], ['df1', 'df2']).to_frame() </code></pre> <p><a href="http://i.stack.imgur.com/LQe1k.png" rel="nofollow"><img src="http://i.stack.imgur.com/LQe1k.png" alt="enter image description here"></a></p>
1
2016-08-03T16:02:39Z
[ "python", "pandas" ]
How do you concatenate two (or more) dataframes into a panel
38,748,446
<p>I was recently trying to concatenate two dataframes into a panel and I tried to use <code>pd.concat</code> with <code>axis=2</code></p> <p>Consider the dataframes <code>df1</code> and <code>df2</code></p> <pre><code>df1 = pd.DataFrame(np.random.rand(3, 3), list('abc'), list('def')) df2 = pd.DataFrame(np.random.rand(3, 3), list('abc'), list('def')) </code></pre> <p>Then I tried</p> <pre><code>pd.concat([df1, df2], axis=2) </code></pre> <p><a href="http://i.stack.imgur.com/tsMBi.png" rel="nofollow"><img src="http://i.stack.imgur.com/tsMBi.png" alt="enter image description here"></a></p> <p>This looked the same as if I had used <code>axis=1</code>. Maybe pandas is just checking if <code>axis</code> evaluates to <code>True</code>. Let's try</p> <pre><code>pd.concat([df1, df2], axis='This Has To Break...Right?') </code></pre> <p><a href="http://i.stack.imgur.com/tsMBi.png" rel="nofollow"><img src="http://i.stack.imgur.com/tsMBi.png" alt="enter image description here"></a></p> <p>Nope! Did not break. Ok, so how do I concat two dataframes along <code>axis=2</code></p> <p>I could</p> <pre><code>pd.Panel(np.stack([df1, df2])).to_frame() </code></pre> <p><a href="http://i.stack.imgur.com/a3sbN.png" rel="nofollow"><img src="http://i.stack.imgur.com/a3sbN.png" alt="enter image description here"></a></p> <p>But this ignores the indices and will not align them if they were different.</p> <p>I'd want something that looks like</p> <pre><code>panel &lt;class 'pandas.core.panel.Panel'&gt; Dimensions: 2 (items) x 3 (major_axis) x 3 (minor_axis) Items axis: 0 to 1 Major_axis axis: a to c Minor_axis axis: d to f panel.to_frame() </code></pre> <p><a href="http://i.stack.imgur.com/QrFrf.png" rel="nofollow"><img src="http://i.stack.imgur.com/QrFrf.png" alt="enter image description here"></a></p>
1
2016-08-03T15:56:37Z
38,750,028
<p>Not sure what you are looking for, but: </p> <pre><code>pd.Panel(np.stack([df1, df2]), major_axis=df1.index, minor_axis=df2.columns ).to_frame() 0 1 major minor a d 0.630339 0.020119 e 0.736730 0.874750 f 0.530833 0.637081 b d 0.759991 0.499921 e 0.651995 0.310123 f 0.005724 0.759712 c d 0.510702 0.067634 e 0.367993 0.893205 f 0.030383 0.591366 data = {0 : df1, 1 : df2} pd.Panel(data) &lt;class 'pandas.core.panel.Panel'&gt; Dimensions: 2 (items) x 3 (major_axis) x 3 (minor_axis) Items axis: 0 to 1 Major_axis axis: a to c Minor_axis axis: d to f data = {0 : df1, 1 : df2} pd.Panel(data).to_frame() 0 1 major minor a d 0.630339 0.020119 e 0.736730 0.874750 f 0.530833 0.637081 b d 0.759991 0.499921 e 0.651995 0.310123 f 0.005724 0.759712 c d 0.510702 0.067634 e 0.367993 0.893205 f 0.030383 0.591366 </code></pre>
1
2016-08-03T17:21:23Z
[ "python", "pandas" ]
Increment and while loop
38,748,472
<p>Following is the code I'm executing in IDLE for Python 3.5.2 on Windows 10:</p> <pre><code>spam = 0 while spam &lt; 5: print('Hello, world.') spam = spam + 1 </code></pre> <p>I can see Hello World printed 5 times however when entering spam in IDLE, I can see the integer 5. Shouldn't this be logically int 6 since while loop will stop as soon as the spam is incremented by 1 from 5 and spam variable is passed with the incremented int?</p> <p>Thank you!</p>
0
2016-08-03T15:58:14Z
38,748,540
<p>Your while loop is "while spam is <strong>less than</strong> 5", not "while spam is <strong>less than or equal</strong> to 5". The last iteration occurs when spam is 4, and then it gets incremented one last time to 5.</p> <p>If spam equals 5, it is <strong>not</strong> less than 5, so the while loop stops iterating.</p>
2
2016-08-03T16:01:38Z
[ "python", "python-3.x" ]
Increment and while loop
38,748,472
<p>Following is the code I'm executing in IDLE for Python 3.5.2 on Windows 10:</p> <pre><code>spam = 0 while spam &lt; 5: print('Hello, world.') spam = spam + 1 </code></pre> <p>I can see Hello World printed 5 times however when entering spam in IDLE, I can see the integer 5. Shouldn't this be logically int 6 since while loop will stop as soon as the spam is incremented by 1 from 5 and spam variable is passed with the incremented int?</p> <p>Thank you!</p>
0
2016-08-03T15:58:14Z
38,748,549
<p><code>spam &lt; 5</code> can be read as spam is less than 5, so it'll only increment from 0 to 4. In the 4th (last) iteration, <code>spam = 4</code> so it prints 'Hello, world' and then <code>spam + 1 = 5</code>. At that point it will attempt another iteration, but <code>spam &lt; 5</code> is no longer true and therefore will exit the loop.</p> <p>For reference: <code>&lt;</code> means less than, <code>&lt;=</code> means less than or equal to.</p> <p>Any particular reason you think you'd get 6?</p>
3
2016-08-03T16:01:52Z
[ "python", "python-3.x" ]
Increment and while loop
38,748,472
<p>Following is the code I'm executing in IDLE for Python 3.5.2 on Windows 10:</p> <pre><code>spam = 0 while spam &lt; 5: print('Hello, world.') spam = spam + 1 </code></pre> <p>I can see Hello World printed 5 times however when entering spam in IDLE, I can see the integer 5. Shouldn't this be logically int 6 since while loop will stop as soon as the spam is incremented by 1 from 5 and spam variable is passed with the incremented int?</p> <p>Thank you!</p>
0
2016-08-03T15:58:14Z
38,748,829
<p>I added a print statement to illustrate what is happening:</p> <pre><code>spam = 0 while spam &lt; 5: print('Hello, world.') spam = spam + 1 print(spam, 'spam is &lt; 5?', spam &lt; 5, "\n") </code></pre> <p>The output is:</p> <pre><code>Hello, world. 1 spam is &lt; 5? True Hello, world. 2 spam is &lt; 5? True Hello, world. 3 spam is &lt; 5? True Hello, world. 4 spam is &lt; 5? True Hello, world. 5 spam is &lt; 5? False </code></pre>
0
2016-08-03T16:15:28Z
[ "python", "python-3.x" ]