title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Replace Values in Dictionary | 39,602,476 | <p>I am trying to replace the <code>values</code> in the <code>lines dictionary</code> by the <code>values of the corresponding key</code> in the <code>points dictionary</code></p>
<pre><code>lines = {'24': ('2', '10'), '25': ('17', '18')} #k,v => Line ID(Points)
points = {'10': ('2.416067758476', '2.075872272548'... | 2 | 2016-09-20T19:37:41Z | 39,602,647 | <p>Just use a dictionary comprehension:</p>
<pre><code>>>> {k:points[v[0]]+points[v[1]] for k,v in lines.items()}
{'24': ('3.541310767185', '2.774647545044', '2.416067758476', '2.075872272548'), '25': ('2.454725131264', '5.000000000000', '1.828299357105', '5.000000000000')}
</code></pre>
| 3 | 2016-09-20T19:49:03Z | [
"python",
"python-2.7",
"dictionary"
] |
How to append lists of list into one list | 39,602,512 | <p>Mylists = [['A B','A B C','A B C D'],['C','D E F','A B']]</p>
<p>How can I get a list like: myli = [['A','B','A','B','C','A','B','C','D'],['C','D','E','F','A','B']]</p>
<p>Here is my code:</p>
<pre><code>x = []
myli = []
for item in Mylists:
for i in range(len(item)):
x.extend(item[i].split())
my... | 1 | 2016-09-20T19:40:35Z | 39,602,606 | <p>You need to initialize x inside the outer forloop.</p>
<p>Your code</p>
<pre><code>Mylists = [['A B','A B C','A B C D'],['C','D E F','A B']]
x = []
myli = []
for item in Mylists:
for i in range(len(item)):
# BUG: since x is not reinitialized, it contains the same old
# memory address that was ... | 2 | 2016-09-20T19:46:26Z | [
"python",
"list"
] |
How to append lists of list into one list | 39,602,512 | <p>Mylists = [['A B','A B C','A B C D'],['C','D E F','A B']]</p>
<p>How can I get a list like: myli = [['A','B','A','B','C','A','B','C','D'],['C','D','E','F','A','B']]</p>
<p>Here is my code:</p>
<pre><code>x = []
myli = []
for item in Mylists:
for i in range(len(item)):
x.extend(item[i].split())
my... | 1 | 2016-09-20T19:40:35Z | 39,602,642 | <p>Assuming that <code>mylist</code> is a list of lists of strings where words are separated by spaces:</p>
<pre><code>ml = [['A B','A B C','A B C D'],['C','D E F','A B']]
l = []
for inner in ml:
newinner = []
for innerstr in inner:
for word in innerstr.split(' ')
newinner.append(word)
... | 0 | 2016-09-20T19:48:47Z | [
"python",
"list"
] |
Select reverse Foreign Key in ModelChoicefield | 39,602,579 | <p>I have an order form where the user can choose one item and select a quantity. The price depends on how much is ordered. For example, each item is $10 if you order <100, but $7 if you order 100-200.</p>
<p>In the template, I want to display the pricing information underneath the form for each choice.</p>
<p>The... | 0 | 2016-09-20T19:45:01Z | 39,604,904 | <p>For (non)perfectionists with deadlines, this code works, albeit inefficiently.</p>
<pre><code>{% for choice in form.product %}
{% for price_candidate in form.mailer.field.queryset %}
{% if price_candidate.id == choice.choice_value|add:0 %}
<h1>{{ choice.tag }} {{ choice.choice_label }}... | 0 | 2016-09-20T22:49:33Z | [
"python",
"django",
"django-templates"
] |
Is there a way to share a link with only a spefic mail recipient? | 39,602,586 | <p>Not sure if this question should come to SO, but here it goes.</p>
<p>I have the following scenario:</p>
<p>A Flask app with typical users that can login using username / password. Users can share some resources among them, but now we want to let them share those with anyone, not users of the app basically.</p>
<... | 0 | 2016-09-20T19:45:31Z | 39,603,344 | <p>The first time someone accesses the URL, you could send them a random cookie, and save that cookie with the document. On future accesses, check if the cookie matches the saved cookie. If they share the URL with someone, that person won't have the cookie.</p>
<p>Caveats:</p>
<ol>
<li><p>If they share the URL with s... | 2 | 2016-09-20T20:39:38Z | [
"javascript",
"python",
"email",
"security"
] |
Python, Pandas - Issue applying function to a column in a dataframe to replace only certain items | 39,602,588 | <p>I have a dictionary of abbreviations of some city names that our system (for some reason) applies to data (i.e. 'Kansas City' is abbreviated 'Kansas CY', and Oklahoma City is spelled correctly).</p>
<p>I am having an issue getting my function to apply to the column of the dataframe but it works when I pass in strin... | 1 | 2016-09-20T19:45:32Z | 39,602,922 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow"><code>map</code></a> and pass a dict to replace exact matches against the dict keys with the dict values, as you may have case-sensitive matches I'd <a href="http://pandas.pydata.org/pandas-docs/stable/g... | 2 | 2016-09-20T20:07:37Z | [
"python",
"pandas",
"data-munging"
] |
Custom Actions triggered by Parsed values in Python | 39,602,760 | <p>I am looking to build or more preferably use a framework to implement custom Assertions in python. I am listing below potential input that will be parsed to trigger the various assertions on retrieved data </p>
<pre><code>assertValue : [ SOME STRING A ]
or
assertValue : [ SOME STRING B ]
or
assertValue : [ ... | 1 | 2016-09-20T19:56:37Z | 39,603,335 | <p>Maybe you're looking for something along the lines of one of <a href="https://github.com/cucumber/cucumber/wiki/Python" rel="nofollow">Cucumber's Python ports? </a></p>
| 0 | 2016-09-20T20:39:00Z | [
"python",
"event-triggers"
] |
Complex time operations in Pandas | 39,602,785 | <p>Below is a small sample of my very large dataframe:</p>
<pre><code>In [38]: df
Out[38]:
Send_Customer Pay_Customer Send_Time
0 1000000000284044644 1000000000251680999 2016-08-01 09:55:48
1 2000000000223021617 1000000000190078650 2016-08-01 02:44:23
2 20000000002893... | 4 | 2016-09-20T19:58:04Z | 39,612,548 | <p>If I understand correctly: after a <code>diff</code> the first row is <code>NaT</code>. In order to preserve the first row you could replace <code>NaT</code> values with something that would not be filtered out by your condition, for instance <code>0</code>.</p>
<p>Here I simply add <code>.fillna(0)</code> at the e... | 0 | 2016-09-21T09:26:03Z | [
"python",
"pandas"
] |
Python Break Inside Function | 39,602,810 | <p>I am using Python 3.5, and I would like to use the <code>break</code> command inside a function, but I do not know how.
I would like to use something like this:</p>
<pre><code>def stopIfZero(a):
if int(a) == 0:
break
else:
print('Continue')
while True:
stopIfZero(input('Number: '))
</co... | 2 | 2016-09-20T19:59:25Z | 39,602,851 | <p>Usually, this is done by returning some value that lets you decide whether or not you want to stop the while loop (i.e. whether some condition is true or false):</p>
<pre><code>def stopIfZero(a):
if int(a) == 0:
return True
else:
print('Continue')
return False
while True:
if sto... | 5 | 2016-09-20T20:02:18Z | [
"python",
"function",
"python-3.x",
"break"
] |
Python Break Inside Function | 39,602,810 | <p>I am using Python 3.5, and I would like to use the <code>break</code> command inside a function, but I do not know how.
I would like to use something like this:</p>
<pre><code>def stopIfZero(a):
if int(a) == 0:
break
else:
print('Continue')
while True:
stopIfZero(input('Number: '))
</co... | 2 | 2016-09-20T19:59:25Z | 39,602,853 | <p>A function can't <code>break</code> on behalf of its caller. The <code>break</code> has to be syntactically inside the loop.</p>
| 3 | 2016-09-20T20:02:24Z | [
"python",
"function",
"python-3.x",
"break"
] |
Python Break Inside Function | 39,602,810 | <p>I am using Python 3.5, and I would like to use the <code>break</code> command inside a function, but I do not know how.
I would like to use something like this:</p>
<pre><code>def stopIfZero(a):
if int(a) == 0:
break
else:
print('Continue')
while True:
stopIfZero(input('Number: '))
</co... | 2 | 2016-09-20T19:59:25Z | 39,602,864 | <p>You want to use <code>return</code>, not <code>break</code>. </p>
<p><a href="https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops" rel="nofollow"><code>break</code></a> is used to stop a loop. </p>
<blockquote>
<p>The break statement, like in C, breaks out ... | 0 | 2016-09-20T20:03:08Z | [
"python",
"function",
"python-3.x",
"break"
] |
Python Break Inside Function | 39,602,810 | <p>I am using Python 3.5, and I would like to use the <code>break</code> command inside a function, but I do not know how.
I would like to use something like this:</p>
<pre><code>def stopIfZero(a):
if int(a) == 0:
break
else:
print('Continue')
while True:
stopIfZero(input('Number: '))
</co... | 2 | 2016-09-20T19:59:25Z | 39,602,910 | <p>The <code>break</code> keyword is meant to be used as in your loop example only and must be inside the loop's scope.</p>
<p>Update your function to return <code>True</code> or <code>False</code> only instead:</p>
<pre><code>def is_zero(value):
if value == 0:
return True
return False
</code></pre>
... | 0 | 2016-09-20T20:06:46Z | [
"python",
"function",
"python-3.x",
"break"
] |
pandas: replace string with another string | 39,602,824 | <p>I have the following data frame</p>
<pre><code> prod_type
0 responsive
1 responsive
2 respon
3 r
4 respon
5 r
6 responsive
</code></pre>
<p>I would like to replace <code>respon</code> and <code>r</code> with <code>responsive</code>, so the final data frame is</p>
<pre><code> prod_type
0 resp... | 4 | 2016-09-20T20:00:39Z | 39,602,862 | <p>You don't need to pass <code>regex=True</code> here, as this will look for partial matches, as you''re after exact matches just pass the params as separate args:</p>
<pre><code>In [7]:
df['prod_type'] = df['prod_type'].replace('respon' ,'responsvie')
df['prod_type'] = df['prod_type'].replace('r', 'responsive')
df
... | 2 | 2016-09-20T20:03:06Z | [
"python",
"string",
"python-2.7",
"pandas",
"replace"
] |
pandas: replace string with another string | 39,602,824 | <p>I have the following data frame</p>
<pre><code> prod_type
0 responsive
1 responsive
2 respon
3 r
4 respon
5 r
6 responsive
</code></pre>
<p>I would like to replace <code>respon</code> and <code>r</code> with <code>responsive</code>, so the final data frame is</p>
<pre><code> prod_type
0 resp... | 4 | 2016-09-20T20:00:39Z | 39,602,902 | <p>Solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.replace.html" rel="nofollow"><code>replace</code></a> by <code>dictionary</code>:</p>
<pre><code>df['prod_type'] = df['prod_type'].replace({'respon':'responsive', 'r':'responsive'})
print (df)
prod_type
0 responsive
1 r... | 3 | 2016-09-20T20:06:18Z | [
"python",
"string",
"python-2.7",
"pandas",
"replace"
] |
pandas: replace string with another string | 39,602,824 | <p>I have the following data frame</p>
<pre><code> prod_type
0 responsive
1 responsive
2 respon
3 r
4 respon
5 r
6 responsive
</code></pre>
<p>I would like to replace <code>respon</code> and <code>r</code> with <code>responsive</code>, so the final data frame is</p>
<pre><code> prod_type
0 resp... | 4 | 2016-09-20T20:00:39Z | 39,603,224 | <p>Other solution in case all items from <code>df['prod_type']</code> will be the same:</p>
<pre><code>df['prod_type'] = ['responsive' for item in df['prod_type']]
In[0]: df
Out[0]:
prod_type
0 responsive
1 responsive
2 responsive
3 responsive
4 responsive
5 responsive
6 responsive
</code></pre>
| 1 | 2016-09-20T20:30:55Z | [
"python",
"string",
"python-2.7",
"pandas",
"replace"
] |
comparing object with repr() is throwing NameError | 39,602,833 | <p>So I'm trying to compare a Deck object with the evaluated representation of a Deck object and getting</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/Philipp/PycharmProjects/fnaround/src.py", line 3, in <module>
print(Deck() == eval(repr(Deck())))
File "<string>", line 1, in <... | -1 | 2016-09-20T20:01:08Z | 39,603,269 | <p>Your Deck class takes no arguments, but your representation passes a list of cards as argument. You can change your <code>Deck.__init__</code> to something like this:</p>
<pre><code>def __init__(self, deck=None):
if deck:
self.deck = deck
else:
self.deck = [Card(r, s) for r in self.ranks for... | 0 | 2016-09-20T20:34:16Z | [
"python",
"class",
"eval",
"repr"
] |
comparing object with repr() is throwing NameError | 39,602,833 | <p>So I'm trying to compare a Deck object with the evaluated representation of a Deck object and getting</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/Philipp/PycharmProjects/fnaround/src.py", line 3, in <module>
print(Deck() == eval(repr(Deck())))
File "<string>", line 1, in <... | -1 | 2016-09-20T20:01:08Z | 39,603,296 | <p>I get this output;</p>
<pre><code>deck.py", line 32, in <module>
print(Deck() == eval(repr(Deck())))
File "<string>", line 1, in <module>
TypeError: __init__() takes 1 positional argument but 2 were given
<<< Process finished. (Exit code 1)
</code></pre>
<p>Your repr is trying to pass ... | 0 | 2016-09-20T20:36:01Z | [
"python",
"class",
"eval",
"repr"
] |
comparing object with repr() is throwing NameError | 39,602,833 | <p>So I'm trying to compare a Deck object with the evaluated representation of a Deck object and getting</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/Philipp/PycharmProjects/fnaround/src.py", line 3, in <module>
print(Deck() == eval(repr(Deck())))
File "<string>", line 1, in <... | -1 | 2016-09-20T20:01:08Z | 39,603,520 | <p>The current issue (causing the <code>NameError</code>) is that when you're running the <code>eval</code> on a <code>Deck</code> instance's <code>repr</code>, you don't have the name <code>Card</code> in the local namespace. This means that When <code>eval</code> tries to interpret the string that <code>repr(Deck())<... | 0 | 2016-09-20T20:51:59Z | [
"python",
"class",
"eval",
"repr"
] |
how to find that file is image or document or ... without extension and content type? | 39,602,869 | <h1>File Manager</h1>
<p>I want uploading any file and i have a file manager service that get the file and saving without extension and files name are UUID and return file information.</p>
<p>my file manager handler :</p>
<pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
from pyramid_storage.exceptio... | 2 | 2016-09-20T20:03:42Z | 39,602,941 | <p>There's a UNIX utility called <code>file</code> that uses "magic" to recognize known file types. <code>file</code> uses a library called <code>libmagic</code> for this purpose.</p>
<p>The python interface to <code>libmagic</code> is called <code>filemagic</code> and you can get it <a href="https://pypi.python.org/... | 1 | 2016-09-20T20:08:41Z | [
"python",
"file-upload"
] |
Django form. How hidden colon from initial_text? | 39,602,903 | <p>I'm try do this:</p>
<pre>
class NoClearableFileInput(ClearableFileInput):
initial_text = ''
input_text = ''
class ImageUploadForm(forms.ModelForm):
title = forms.CharField(label="TITLE", required=False,widget=forms.TextInput(attrs={'placeholder': 'name'}), label_suffix="")
image = forms.ImageFi... | 0 | 2016-09-20T20:06:26Z | 39,604,248 | <p>You have to override the <code>label_suffix</code> on initialization. Try making the following changes:</p>
<pre><code>class ImageUploadForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
kwargs.setdefault('label_suffix', '')
super(ImageUploadForm, self).__init__(*args, **kwargs)
# ... | 0 | 2016-09-20T21:49:02Z | [
"python",
"django",
"forms"
] |
Unable to load pickle file | 39,602,907 | <p>I was previously able to load a pickle file. I saved a new file under a different name. I am unable to load either the old or the new file. Which is a bummer as it contains data which I have worked hard to scrub.</p>
<p>Here is the code that I use to save:</p>
<pre><code>def pickleStore():
pickle.dump(store, o... | 1 | 2016-09-20T20:06:39Z | 39,602,992 | <p>As a general and more versatile approach I would suggest something like this:</p>
<pre><code>def load(file_name):
with open(simulation, 'rb') as pickle_file:
return pickle.load(pickle_file)
def save(file_name, data):
with open(file_name, 'wb') as f:
pickle.dump(data, f)
</code></pre>
<p>I ... | 1 | 2016-09-20T20:12:18Z | [
"python",
"pickle"
] |
Unable to load pickle file | 39,602,907 | <p>I was previously able to load a pickle file. I saved a new file under a different name. I am unable to load either the old or the new file. Which is a bummer as it contains data which I have worked hard to scrub.</p>
<p>Here is the code that I use to save:</p>
<pre><code>def pickleStore():
pickle.dump(store, o... | 1 | 2016-09-20T20:06:39Z | 39,603,293 | <p>If you want to write to a module-level variable from a function, you need to use the <code>global</code> keyword:</p>
<pre><code>store = None
def pickleLoad():
global store
store = pickle.load(open(".../shelf3.p","rb" ) )
</code></pre>
<p>...or return the value and perform the assignment from module-level... | 2 | 2016-09-20T20:35:49Z | [
"python",
"pickle"
] |
How to display specific parts of json? | 39,602,939 | <p>Can someone help me with this python api calling program? </p>
<pre><code>import json
from pprint import pprint
import requests
weather = requests.get('http://api.openweathermap.org/data/2.5/weather?
q=London&APPID=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
pprint(weather.json())
wjson = weather.read()
wjdata = js... | 1 | 2016-09-20T20:08:38Z | 39,602,964 | <p><a href="http://docs.python-requests.org/en/master/user/quickstart/#json-response-content"><code>.json()</code></a> is a built into <code>requests</code> JSON decoder, no need to parse JSON separately:</p>
<pre><code>import requests
weather = requests.get('http://api.openweathermap.org/data/2.5/weather?q=London&am... | 5 | 2016-09-20T20:10:13Z | [
"python",
"json",
"api"
] |
How to display specific parts of json? | 39,602,939 | <p>Can someone help me with this python api calling program? </p>
<pre><code>import json
from pprint import pprint
import requests
weather = requests.get('http://api.openweathermap.org/data/2.5/weather?
q=London&APPID=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
pprint(weather.json())
wjson = weather.read()
wjdata = js... | 1 | 2016-09-20T20:08:38Z | 39,604,118 | <p>alecxe is correct with using the json library, if you want to know more about referencing specific values in a json object, look into pythons Dictionary data types. That is what json essentially converts them into.</p>
<p><a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries" rel="nofollow">h... | 0 | 2016-09-20T21:36:14Z | [
"python",
"json",
"api"
] |
Using more memory than available | 39,602,962 | <p>I have written a program that expands a database of prime numbers. This program is written in python and runs on windows 10 (x64) with 8GB RAM.</p>
<p>The program stores all primes it has found in a <code>list</code> of <code>integers</code> for further calculations and uses approximately <code>6-7GB</code> of RAM ... | 2 | 2016-09-20T20:09:55Z | 39,603,005 | <p>1, 2, and 3 are incorrect theories.</p>
<p>4 is correct. Windows (not Python) is moving some of your process memory to swap space. This is almost totally transparent to your application - you don't need to do anything special to respond to or handle this situation. The only thing you will notice is your application... | 3 | 2016-09-20T20:12:59Z | [
"python",
"windows",
"memory",
"memory-management"
] |
Using more memory than available | 39,602,962 | <p>I have written a program that expands a database of prime numbers. This program is written in python and runs on windows 10 (x64) with 8GB RAM.</p>
<p>The program stores all primes it has found in a <code>list</code> of <code>integers</code> for further calculations and uses approximately <code>6-7GB</code> of RAM ... | 2 | 2016-09-20T20:09:55Z | 39,603,049 | <p>Have you heard of paging? Windows dumps some ram (that hasn't been used in a while) to your hard drive to keep your computer from running out or ram and ultimately crashing.</p>
<p>Only Windows deals with memory management. Although, if you use Windows 10, it will also compress your memory, somewhat like a zip file... | 0 | 2016-09-20T20:16:18Z | [
"python",
"windows",
"memory",
"memory-management"
] |
Pyjnius, Facebook/Google SDK for Sign in Button with Kivy | 39,603,112 | <p>So I have been wondering. Can this be implemented with kivy?</p>
<p>I have seen read <a href="https://kivy.org/planet/2013/08/using-facebook-sdk-with-python-for-android-kivy/" rel="nofollow">this post in kivy planet</a> about it, but noticed that the login button was a problem.
The article is from 2013, so I would ... | 0 | 2016-09-20T20:21:09Z | 39,603,276 | <p>A Facebook/Google sign in can be implemented with Kivy. You do not necessarily have to use the Google or Facebook SDK, there are other auth libraries available in Python.</p>
<p>If you are to use the Facebook/Google SDKs, it is still possible as you can execute any Java code with Pyjnius. Per your question about in... | 0 | 2016-09-20T20:34:36Z | [
"android",
"python",
"facebook",
"kivy",
"pyjnius"
] |
Having issues with optimizing query on foreign key | 39,603,206 | <p>I have tried different ways of querying my data, but still results in a large amount of pings to the DB. </p>
<p>I have tried using <code>select_related</code>.</p>
<p>Here are my models:</p>
<pre><code>class Order(models.Model):
num = models.CharField(max_length=50, unique=True)
class OrderInfo(models.Model... | 0 | 2016-09-20T20:29:58Z | 39,604,088 | <p>Based on <a href="http://stackoverflow.com/a/14293530/4978266">this stack overflow answer to a similar question</a>, I think you'd just need to split this up into two queries to hopefully reduce how much you have to peg the database.</p>
<p>Since you're using SQLite, you do not have access to <code>DISTINCT ON</cod... | 0 | 2016-09-20T21:33:21Z | [
"python",
"django",
"sqlite3"
] |
Having issues with optimizing query on foreign key | 39,603,206 | <p>I have tried different ways of querying my data, but still results in a large amount of pings to the DB. </p>
<p>I have tried using <code>select_related</code>.</p>
<p>Here are my models:</p>
<pre><code>class Order(models.Model):
num = models.CharField(max_length=50, unique=True)
class OrderInfo(models.Model... | 0 | 2016-09-20T20:29:58Z | 39,608,023 | <p>How many <code>OrderInfo</code> objects are there per order? If it's small, it is probably easiest to use <code>prefetch_related</code> and just do the filtering in python:</p>
<pre><code>class Order(models.Model):
num = models.CharField(max_length=50, unique=True)
@property
def latest_order_info(self):... | 0 | 2016-09-21T05:12:38Z | [
"python",
"django",
"sqlite3"
] |
Numpy create index/slicing programmatically from array | 39,603,246 | <p>I can use <code>numpy.mgrid</code> as follows:</p>
<pre><code>a = numpy.mgrid[x0:x1, y0:y1] # 2 dimensional
b = numpy.mgrid[x0:x1, y0:y1, z0:z1] # 3 dimensional
</code></pre>
<p>Now, I'd like to create the expression in brackets programmatically, because I do not know whether I have 1, 2, 3 or more dimensions. I'm... | 2 | 2016-09-20T20:32:49Z | 39,603,562 | <p>Use the <a href="https://docs.python.org/2/library/functions.html#slice" rel="nofollow"><code>slice</code> object</a>. For example:</p>
<pre><code>shape = np.array([[0, 10], [0, 10]])
idx = tuple(slice(s[0],s[1], 1) for s in shape)
#yields the following
#(slice(0, 10, 1), slice(0, 10, 1))
np.mgrid[idx]
</code></pr... | 4 | 2016-09-20T20:55:38Z | [
"python",
"numpy"
] |
Sending And Receiving Bytes through a Socket, Depending On Your Internet Speed | 39,603,248 | <p>I made a quick program that sends a file using sockets in python.</p>
<p>Server:</p>
<pre><code>import socket, threading
#Create a socket object.
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Bind the socket.
sock.bind( ("", 5050) )
#Start listening.
sock.listen()
#Accept client.
client, addr = soc... | 1 | 2016-09-20T20:32:53Z | 39,603,386 | <p>Just send those bytes in a loop until all were sent, here's an <a href="https://docs.python.org/2/howto/sockets.html#using-a-socket" rel="nofollow">example from the docs</a></p>
<pre><code>def mysend(self, msg):
totalsent = 0
while totalsent < MSGLEN:
sent = self.sock.send(msg[totalsent:])
... | 1 | 2016-09-20T20:42:19Z | [
"python",
"sockets"
] |
Sending And Receiving Bytes through a Socket, Depending On Your Internet Speed | 39,603,248 | <p>I made a quick program that sends a file using sockets in python.</p>
<p>Server:</p>
<pre><code>import socket, threading
#Create a socket object.
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Bind the socket.
sock.bind( ("", 5050) )
#Start listening.
sock.listen()
#Accept client.
client, addr = soc... | 1 | 2016-09-20T20:32:53Z | 39,606,825 | <p>There are input/output buffers at all steps along the way between your source and destination. Once a buffer fills, nothing else will be accepted on to it until space has been made available.</p>
<p>As your application attempts to send data, it will fill up a buffer in the operating system that is cleared as the ... | 1 | 2016-09-21T02:59:33Z | [
"python",
"sockets"
] |
Sending And Receiving Bytes through a Socket, Depending On Your Internet Speed | 39,603,248 | <p>I made a quick program that sends a file using sockets in python.</p>
<p>Server:</p>
<pre><code>import socket, threading
#Create a socket object.
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Bind the socket.
sock.bind( ("", 5050) )
#Start listening.
sock.listen()
#Accept client.
client, addr = soc... | 1 | 2016-09-20T20:32:53Z | 39,606,911 | <p><code>send</code> makes no guarantees that all the data is sent (it not directly tied to network speed; there are multiple reasons it could send less than requested), just that it lets you know how much was sent. You could explicitly write loops to <code>send</code> until it's all really sent, per <a href="http://st... | 1 | 2016-09-21T03:10:17Z | [
"python",
"sockets"
] |
Sending And Receiving Bytes through a Socket, Depending On Your Internet Speed | 39,603,248 | <p>I made a quick program that sends a file using sockets in python.</p>
<p>Server:</p>
<pre><code>import socket, threading
#Create a socket object.
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Bind the socket.
sock.bind( ("", 5050) )
#Start listening.
sock.listen()
#Accept client.
client, addr = soc... | 1 | 2016-09-20T20:32:53Z | 39,607,144 | <blockquote>
<p>From experience a learn that send can send an amount of bytes that
your network speed is capble of sending them.</p>
</blockquote>
<p>Since you are using a TCP Socket (i.e. SOCK_STREAM), speed-of-transmission issues are handled for you automatically. That is, once some bytes have been copied from ... | 1 | 2016-09-21T03:39:39Z | [
"python",
"sockets"
] |
Sending And Receiving Bytes through a Socket, Depending On Your Internet Speed | 39,603,248 | <p>I made a quick program that sends a file using sockets in python.</p>
<p>Server:</p>
<pre><code>import socket, threading
#Create a socket object.
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Bind the socket.
sock.bind( ("", 5050) )
#Start listening.
sock.listen()
#Accept client.
client, addr = soc... | 1 | 2016-09-20T20:32:53Z | 39,611,867 | <p>@Jeremy Friesner</p>
<p>So I can do something like that:</p>
<pre><code>file = open(filename, "rb")
read = file.read(1024**3) #Read 1 gb.
totalsend = 0
#Send Loop
while totalsend < filesize:
#Try to send all the bytes.
send = sock.send(read)
totalsend += send
#If failed, then seek into the ... | 0 | 2016-09-21T08:56:33Z | [
"python",
"sockets"
] |
How to delete unpopulated placeholder items using python-pptx | 39,603,318 | <p>This is very simple, but I cannot find the actual method anywhere in the documentation or otherwise. </p>
<p>I am using the python-pptx module and all I need to do is delete a single placeholder item, an empty text box, on some slides (without having to create a completely new layout just for these slides) - the cl... | 0 | 2016-09-20T20:37:50Z | 39,608,066 | <p>There is no API support for this, but if you delete the text box shape element, that should do the trick. It would be something like this:</p>
<pre><code>textbox = shapes[textbox_idx]
sp = textbox.element
sp.getparent().remove(sp)
</code></pre>
<p>Using the <code>textbox</code> variable/reference after this operat... | 0 | 2016-09-21T05:16:06Z | [
"python",
"python-pptx"
] |
Most efficient way to store list of integers | 39,603,364 | <p>I have recently been doing a project in which one of the aims is to use as little memory as possible to store a series of files using Python 3. Almost all of the files take up very little space, apart from one list of integers that is roughly <code>333,000</code> integers long and has integers up to about <code>8000... | 0 | 2016-09-20T20:41:15Z | 39,603,768 | <p>One <code>stdlib</code> solution you could use is arrays from <a href="https://docs.python.org/3/library/array.html" rel="nofollow"><code>array</code></a>, from the docs:</p>
<blockquote>
<p>This module defines an object type which can compactly represent an array of basic values: characters, integers, floating p... | 2 | 2016-09-20T21:10:15Z | [
"python",
"list",
"python-3.x",
"memory",
"integer"
] |
Most efficient way to store list of integers | 39,603,364 | <p>I have recently been doing a project in which one of the aims is to use as little memory as possible to store a series of files using Python 3. Almost all of the files take up very little space, apart from one list of integers that is roughly <code>333,000</code> integers long and has integers up to about <code>8000... | 0 | 2016-09-20T20:41:15Z | 39,603,864 | <p>Here is a small demo, which uses Pandas module:</p>
<pre><code>import numpy as np
import pandas as pd
import feather
# let's generate an array of 1M int64 elements...
df = pd.DataFrame({'num_col':np.random.randint(0, 10**9, 10**6)}, dtype=np.int64)
df.info()
%timeit -n 1 -r 1 df.to_pickle('d:/temp/a.pickle')
%ti... | 1 | 2016-09-20T21:17:54Z | [
"python",
"list",
"python-3.x",
"memory",
"integer"
] |
Most efficient way to store list of integers | 39,603,364 | <p>I have recently been doing a project in which one of the aims is to use as little memory as possible to store a series of files using Python 3. Almost all of the files take up very little space, apart from one list of integers that is roughly <code>333,000</code> integers long and has integers up to about <code>8000... | 0 | 2016-09-20T20:41:15Z | 39,604,308 | <p>I like <a href="http://stackoverflow.com/a/39603768/1392132">Jim's suggestion</a> of using the <a href="https://docs.python.org/3/library/array.html" rel="nofollow"><code>array</code></a> module. If your numeric values are small enough to fit into the machine's native <code>int</code> type, then this is a fine solut... | 0 | 2016-09-20T21:53:50Z | [
"python",
"list",
"python-3.x",
"memory",
"integer"
] |
using more than one highlight color in pygments | 39,603,381 | <p>I'm using pygments to highlight lines from a file, but I want to highlight different lines with different colors.</p>
<p><strong>note</strong> While I was writing this question I tried different things until I found what looks like a decent solution that solves my problem. I'll post it in the answers.</p>
<p>My fi... | 0 | 2016-09-20T20:42:10Z | 39,603,382 | <p>My solution subclassed the <code>HtmlFormatter</code> class as suggested by the documentation like this:</p>
<pre class="lang-py prettyprint-override"><code>class MyFormatter(HtmlFormatter):
"""Overriding formatter to highlight more than one kind of lines"""
def __init__(self, **kwargs):
super(MyFor... | 0 | 2016-09-20T20:42:10Z | [
"python",
"css",
"pygments"
] |
Short-circuit evaluation like Python's "and" while storing results of checks | 39,603,391 | <p>I have multiple expensive functions that return results. I want to return a tuple of the results of all the checks if all the checks succeed. However, if one check fails I don't want to call the later checks, like the short-circuiting behavior of <code>and</code>. I could nest <code>if</code> statements, but that... | 26 | 2016-09-20T20:42:29Z | 39,603,504 | <p>Just use a plain old for loop:</p>
<pre><code>results = {}
for function in [check_a, check_b, ...]:
results[function.__name__] = result = function()
if not result:
break
</code></pre>
<p>The results will be a mapping of the function name to their return values, and you can do what you want with the... | 27 | 2016-09-20T20:51:07Z | [
"python",
"short-circuiting"
] |
Short-circuit evaluation like Python's "and" while storing results of checks | 39,603,391 | <p>I have multiple expensive functions that return results. I want to return a tuple of the results of all the checks if all the checks succeed. However, if one check fails I don't want to call the later checks, like the short-circuiting behavior of <code>and</code>. I could nest <code>if</code> statements, but that... | 26 | 2016-09-20T20:42:29Z | 39,603,506 | <p>Write a function that takes an iterable of functions to run. Call each one and append the result to a list, or return <code>None</code> if the result is <code>False</code>. Either the function will stop calling further checks after one fails, or it will return the results of all the checks.</p>
<pre><code>def all... | 9 | 2016-09-20T20:51:16Z | [
"python",
"short-circuiting"
] |
Short-circuit evaluation like Python's "and" while storing results of checks | 39,603,391 | <p>I have multiple expensive functions that return results. I want to return a tuple of the results of all the checks if all the checks succeed. However, if one check fails I don't want to call the later checks, like the short-circuiting behavior of <code>and</code>. I could nest <code>if</code> statements, but that... | 26 | 2016-09-20T20:42:29Z | 39,603,512 | <p>Try this:</p>
<pre><code>mapping = {'a': assign_a(), 'b': assign_b()}
if None not in mapping.values():
return mapping
</code></pre>
<p>Where <code>assign_a</code> and <code>assign_b</code> are of the form:</p>
<pre><code>def assign_<variable>():
if condition:
return value
else:
r... | -2 | 2016-09-20T20:51:32Z | [
"python",
"short-circuiting"
] |
Short-circuit evaluation like Python's "and" while storing results of checks | 39,603,391 | <p>I have multiple expensive functions that return results. I want to return a tuple of the results of all the checks if all the checks succeed. However, if one check fails I don't want to call the later checks, like the short-circuiting behavior of <code>and</code>. I could nest <code>if</code> statements, but that... | 26 | 2016-09-20T20:42:29Z | 39,603,516 | <p>You could use either a list or an OrderedDict, using a for loop would serve the purpose of emulating short circuiting.</p>
<pre><code>from collections import OrderedDict
def check_a():
return "A"
def check_b():
return "B"
def check_c():
return "C"
def check_d():
return False
def method1(*a... | 3 | 2016-09-20T20:51:46Z | [
"python",
"short-circuiting"
] |
Short-circuit evaluation like Python's "and" while storing results of checks | 39,603,391 | <p>I have multiple expensive functions that return results. I want to return a tuple of the results of all the checks if all the checks succeed. However, if one check fails I don't want to call the later checks, like the short-circuiting behavior of <code>and</code>. I could nest <code>if</code> statements, but that... | 26 | 2016-09-20T20:42:29Z | 39,603,737 | <p>If i understand correctly you don't need skip the last functions because if the the first condition fails, the others will not be evaluated. </p>
<p>For me your code:</p>
<pre><code>a = check_a()
b = check_b()
c = check_c()
....
if a and b and c and ...
return (a, b, c, ...)
</code></pre>
<p>is right. If a fa... | -3 | 2016-09-20T21:07:49Z | [
"python",
"short-circuiting"
] |
Short-circuit evaluation like Python's "and" while storing results of checks | 39,603,391 | <p>I have multiple expensive functions that return results. I want to return a tuple of the results of all the checks if all the checks succeed. However, if one check fails I don't want to call the later checks, like the short-circuiting behavior of <code>and</code>. I could nest <code>if</code> statements, but that... | 26 | 2016-09-20T20:42:29Z | 39,605,495 | <p>In other languages that did have <a href="http://stackoverflow.com/q/4869770/1048572">assignments as expressions</a> you would be able to use</p>
<pre><code>if (a = check_a()) and (b = check_b()) and (c = check_c()):
</code></pre>
<p>but Python is no such language. Still, we can circumvent the restriction and emul... | 6 | 2016-09-20T23:57:59Z | [
"python",
"short-circuiting"
] |
Short-circuit evaluation like Python's "and" while storing results of checks | 39,603,391 | <p>I have multiple expensive functions that return results. I want to return a tuple of the results of all the checks if all the checks succeed. However, if one check fails I don't want to call the later checks, like the short-circuiting behavior of <code>and</code>. I could nest <code>if</code> statements, but that... | 26 | 2016-09-20T20:42:29Z | 39,609,961 | <p>main logic:</p>
<pre><code>results = list(takewhile(lambda x: x, map(lambda x: x(), function_list)))
if len(results) == len(function_list):
return results
</code></pre>
<p>you can learn a lot about collection transformations if you look at all methods of an api like <a href="http://www.scala-lang.org/api/2.11.7/... | 1 | 2016-09-21T07:23:25Z | [
"python",
"short-circuiting"
] |
Short-circuit evaluation like Python's "and" while storing results of checks | 39,603,391 | <p>I have multiple expensive functions that return results. I want to return a tuple of the results of all the checks if all the checks succeed. However, if one check fails I don't want to call the later checks, like the short-circuiting behavior of <code>and</code>. I could nest <code>if</code> statements, but that... | 26 | 2016-09-20T20:42:29Z | 39,610,678 | <p>Since I can not comment "wim":s answer as guest, I'll just add an extra answer.
Since you want a tuple, you should collect the results in a list and then cast to tuple.</p>
<pre><code>def short_eval(*checks):
result = []
for check in checks:
checked = check()
if not checked:
brea... | 0 | 2016-09-21T07:58:42Z | [
"python",
"short-circuiting"
] |
Short-circuit evaluation like Python's "and" while storing results of checks | 39,603,391 | <p>I have multiple expensive functions that return results. I want to return a tuple of the results of all the checks if all the checks succeed. However, if one check fails I don't want to call the later checks, like the short-circuiting behavior of <code>and</code>. I could nest <code>if</code> statements, but that... | 26 | 2016-09-20T20:42:29Z | 39,611,845 | <p>There are lots of ways to do this! Here's another.</p>
<p>You can use a generator expression to defer the execution of the functions. Then you can use <code>itertools.takewhile</code> to implement the short-circuiting logic by consuming items from the generator until one of them is false.</p>
<pre><code>from ite... | 2 | 2016-09-21T08:55:32Z | [
"python",
"short-circuiting"
] |
Short-circuit evaluation like Python's "and" while storing results of checks | 39,603,391 | <p>I have multiple expensive functions that return results. I want to return a tuple of the results of all the checks if all the checks succeed. However, if one check fails I don't want to call the later checks, like the short-circuiting behavior of <code>and</code>. I could nest <code>if</code> statements, but that... | 26 | 2016-09-20T20:42:29Z | 39,612,853 | <p>You can try use <code>@lazy_function</code> decorator from <code>lazy_python</code>
<a href="https://pypi.python.org/pypi/lazy_python/0.2.1" rel="nofollow">package</a>. Example of usage:</p>
<pre><code>from lazy import lazy_function, strict
@lazy_function
def check(a, b):
strict(print('Call: {} {}'.format(a, ... | 0 | 2016-09-21T09:39:03Z | [
"python",
"short-circuiting"
] |
Short-circuit evaluation like Python's "and" while storing results of checks | 39,603,391 | <p>I have multiple expensive functions that return results. I want to return a tuple of the results of all the checks if all the checks succeed. However, if one check fails I don't want to call the later checks, like the short-circuiting behavior of <code>and</code>. I could nest <code>if</code> statements, but that... | 26 | 2016-09-20T20:42:29Z | 39,613,007 | <p>Flexible short circuiting is really best done with Exceptions. For a very simple prototype you could even just assert each check result:</p>
<pre><code>try:
a = check_a()
assert a
b = check_b()
assert b
c = check_c()
assert c
return a, b, c
except AssertionException as e:
return Non... | 1 | 2016-09-21T09:46:09Z | [
"python",
"short-circuiting"
] |
Short-circuit evaluation like Python's "and" while storing results of checks | 39,603,391 | <p>I have multiple expensive functions that return results. I want to return a tuple of the results of all the checks if all the checks succeed. However, if one check fails I don't want to call the later checks, like the short-circuiting behavior of <code>and</code>. I could nest <code>if</code> statements, but that... | 26 | 2016-09-20T20:42:29Z | 39,615,548 | <p>If you don't need to take an arbitrary number of expressions at runtime (possibly wrapped in lambdas), you can expand your code directly into this pattern:</p>
<pre><code>def f ():
try:
return (<a> or jump(),
<b> or jump(),
<c> or jump())
except NonL... | 1 | 2016-09-21T11:38:48Z | [
"python",
"short-circuiting"
] |
Short-circuit evaluation like Python's "and" while storing results of checks | 39,603,391 | <p>I have multiple expensive functions that return results. I want to return a tuple of the results of all the checks if all the checks succeed. However, if one check fails I don't want to call the later checks, like the short-circuiting behavior of <code>and</code>. I could nest <code>if</code> statements, but that... | 26 | 2016-09-20T20:42:29Z | 39,619,506 | <p>This is similar to Bergi's answer but I think that answer misses the point of wanting separate functions (check_a, check_b, check_c):</p>
<pre><code>list1 = []
def check_a():
condition = True
a = 1
if (condition):
list1.append(a)
print ("checking a")
return True
else:
... | 0 | 2016-09-21T14:32:14Z | [
"python",
"short-circuiting"
] |
Short-circuit evaluation like Python's "and" while storing results of checks | 39,603,391 | <p>I have multiple expensive functions that return results. I want to return a tuple of the results of all the checks if all the checks succeed. However, if one check fails I don't want to call the later checks, like the short-circuiting behavior of <code>and</code>. I could nest <code>if</code> statements, but that... | 26 | 2016-09-20T20:42:29Z | 39,642,669 | <p>Another way to tackle this is using a generator, since generators use lazy evaluation. First put all checks into a generator:</p>
<pre><code>def checks():
yield check_a()
yield check_b()
yield check_c()
</code></pre>
<p>Now you could force evaluation of everything by converting it to a list:</p>
<pre>... | 2 | 2016-09-22T15:06:54Z | [
"python",
"short-circuiting"
] |
Short-circuit evaluation like Python's "and" while storing results of checks | 39,603,391 | <p>I have multiple expensive functions that return results. I want to return a tuple of the results of all the checks if all the checks succeed. However, if one check fails I don't want to call the later checks, like the short-circuiting behavior of <code>and</code>. I could nest <code>if</code> statements, but that... | 26 | 2016-09-20T20:42:29Z | 39,675,635 | <p>If the main objection is</p>
<blockquote>
<p>This is messy if there are many checks:</p>
</blockquote>
<pre><code>if a:
b = check_b()
if b:
c = check_c()
if c:
return a, b, c
</code></pre>
<p>A fairly nice pattern is to reverse the condition and return early</p>
<pre><code>if not ... | 0 | 2016-09-24T11:06:15Z | [
"python",
"short-circuiting"
] |
pandas daily average, pandas.resample | 39,603,399 | <p>I have a csv file similar to this</p>
<pre><code>Date,Temp1,Temp2
23-Oct-09 01:00:00,21.1,22.3
23-Oct-09 04:00:00,22.3,23.8
23-Oct-09 07:00:00,21.4,21.3
23-Oct-09 10:00:00,21.5,21.6
23-Oct-09 13:00:00,22.3,23.8
23-Oct-09 16:00:00,21.4,21.3
23-Oct-09 19:00:00,21.1,22.3
23-Oct-09 22:00:00,21.4,21.3
24-Oct-09... | 3 | 2016-09-20T20:43:13Z | 39,603,437 | <p>You need convert <code>string</code> columns to <code>float</code> first:</p>
<pre><code>#add parameter parse_dates for convert to datetime first column
df=pd.read_csv('data.csv', index_col=0, parse_dates=[0])
df['Temp1'] = df.Temp1.astype(float)
df['Temp2'] = df.Temp2.astype(float)
df_avg = df.resample('D', how ... | 2 | 2016-09-20T20:46:07Z | [
"python",
"pandas",
"mean",
"numeric",
"resampling"
] |
Determining Increasing or Decreasing Values based on Sequential Rows Per Key | 39,603,514 | <p>I have a dataset of 90,000 records. These 90,000 records belong to about 3,000 unique Keys. For each Key, the values are ordered starting with an ItemNumber of 1 and going up to 'n'. </p>
<p>For each Key 1 to n, I want to compare the 2nd row to the first row, the 3rd row to the 2nd row and so on. A sample of my tab... | 0 | 2016-09-20T20:51:42Z | 39,603,694 | <p>Once you have transferred the data to text, you could use a set of lists and a for loop to parse through and compare:</p>
<pre><code>keylistA = [0.2, 1.7, 2.5, 5, 9, 12]
listAdirection = ['(start)']
for i in range(0, len(keylistA)):
if keylistA[i] > keylistA[i+1]:
listAdirection.append('DESC')
e... | 0 | 2016-09-20T21:04:47Z | [
"python",
"list",
"direction"
] |
Python authentication for ServiceNow JSON Web Service | 39,603,523 | <p>I'm working on a reporting tool in Python which would fetch data from JSON Web Service of ServiceNow. Our ServiceNow instance uses normal user id / pw authentication plus SHA-1 certification. My problem is that I'm not able to access the JSON Web Service result page (<a href="https://servicenowserver.com/table.do?JS... | 0 | 2016-09-20T20:52:08Z | 39,663,432 | <p>I could manage to figure out the solution, so I'm publishing it here. What I'm going to publish here is not the exact solution for my problem rather a general approach to understand and check how authentication can be tracked. I used this technique to trace the login process in my case.</p>
<p>In my case ServiceNow... | 1 | 2016-09-23T14:35:41Z | [
"python",
"authentication",
"servicenow"
] |
How to Combine CSV Files with Pandas (And Add Identifying Column) | 39,603,567 | <p>How do I add multiple CSV files together and an extra column to indicate where each file came from?</p>
<p>So far I have:</p>
<pre><code>import os
import pandas as pd
import glob
os.chdir('C:\...') # path to folder where all CSVs are stored
for f, i in zip(glob.glob('*.csv'), short_list):
df = pd.read_csv(f, ... | 1 | 2016-09-20T20:56:00Z | 39,604,159 | <p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html" rel="nofollow">.assign(id=i)</a> method, which will add <code>id</code> column to each parsed CSV and will populate it with the <code>i</code> value:</p>
<pre><code>df = pd.concat([pd.read_csv(f, header = None).... | 3 | 2016-09-20T21:40:03Z | [
"python",
"csv",
"pandas"
] |
Key error in data-frame handling | 39,603,571 | <p>I have a dataframe <code>stockData</code>. A part example looks like:</p>
<pre><code>Name: BBG.XCSE.CARLB.S_LAST_ADJ BBG.XCSE.CARLB.S_FX .....
date
2015-09-11 0.1340 490.763
2015-09-14 0.1340 484.263
2015-09-15 0.1340 484.75... | 3 | 2016-09-20T20:56:15Z | 39,603,747 | <p>In your <code>for</code> loop, try adding something akin to</p>
<pre><code>for uid, row in staticData.iterrows():
if uid not in stockData.columns:
stockData[uid + "_FX"] = np.nan
stockData[uid + "_LAST_ADJ"] = np.nan
# continue with what you have:
# no longer needed
#stockData[uid+"... | 1 | 2016-09-20T21:08:32Z | [
"python",
"pandas"
] |
Key error in data-frame handling | 39,603,571 | <p>I have a dataframe <code>stockData</code>. A part example looks like:</p>
<pre><code>Name: BBG.XCSE.CARLB.S_LAST_ADJ BBG.XCSE.CARLB.S_FX .....
date
2015-09-11 0.1340 490.763
2015-09-14 0.1340 484.263
2015-09-15 0.1340 484.75... | 3 | 2016-09-20T20:56:15Z | 39,603,963 | <p>I'd start by parsing your columns into a multiindex</p>
<pre><code>tups = df.columns.to_series() \
.str.extract(r'(.*)_(LAST_ADJ|FX)', expand=False) \
.apply(tuple, 1).tolist()
df.columns = pd.MultiIndex.from_tuples(tups).swaplevel(0, 1)
df
</code></pre>
<p><a href="http://i.stack.imgur.com/1dS... | 2 | 2016-09-20T21:25:04Z | [
"python",
"pandas"
] |
tastypie: sequence item 0: expected string, function found | 39,603,617 | <pre><code>class ActionResource(ModelResource):
#place = fields.ManyToManyField('restaurant.resource.PlaceResource', 'place', full=True, null=True)
place = fields.ManyToManyField(PlaceResource,
attribute=lambda bundle: PlaceInfo.objects.filter(action=bundle.obj))
class Meta:... | 0 | 2016-09-20T20:59:59Z | 39,622,751 | <p>Try setting <code>ActionResource.place.attribute</code> equal to the name (or reverse name, depending on your models) of the relation.</p>
<pre><code>class ActionResource(ModelResource):
place = fields.ToOneField(PlaceResource, 'reverse_name_here')
</code></pre>
| 0 | 2016-09-21T17:16:08Z | [
"python",
"django",
"tastypie"
] |
nltk semantic word substitution | 39,603,633 | <p>I'm trying to find different ways of writing "events in [city]" which are semantically similar. I am trying to do this by finding words that are semantically similar to "events" so I can substitute them in. </p>
<p>To find these words I'm using nltk's wordnet corpus, but I'm getting some pretty strange results. For... | 0 | 2016-09-20T21:00:46Z | 39,605,656 | <p>The <em>hyponyms</em> of "event" are types of "event". One of them is "miracle", some others are:</p>
<pre><code>>>> [s for w in synset.hyponyms() for s in w.lemma_names][:7] # is 7 enough? :)
['zap', 'act', 'deed', 'human_action', 'human_activity', 'happening', 'occurrence']
</code></pre>
<p>"Event's" <... | 1 | 2016-09-21T00:22:10Z | [
"python",
"nlp",
"nltk"
] |
nltk semantic word substitution | 39,603,633 | <p>I'm trying to find different ways of writing "events in [city]" which are semantically similar. I am trying to do this by finding words that are semantically similar to "events" so I can substitute them in. </p>
<p>To find these words I'm using nltk's wordnet corpus, but I'm getting some pretty strange results. For... | 0 | 2016-09-20T21:00:46Z | 39,623,043 | <p>You can take a deep learning approach. Train a word2vec model and get the most similar vectors to the "event" vector.</p>
<p>You can test a model here <a href="http://turbomaze.github.io/word2vecjson/" rel="nofollow" title="Word2Vec">Word2Vec Demo</a></p>
| 1 | 2016-09-21T17:33:29Z | [
"python",
"nlp",
"nltk"
] |
Clustering dense data points horizontally | 39,603,813 | <p>I have a set of about 34,000 data labels with their respective features (state probabilities) in a 2D numpy array that, visualised as a scatter plot, looks <img src="http://i.stack.imgur.com/UlYJG.png" alt="like this">.</p>
<p>It's easy to see that the majority of b data points is at the bottom and quite dense. I w... | 0 | 2016-09-20T21:13:30Z | 39,608,788 | <ol>
<li><p>Never include ID attributes. Your "node index" supposedly should not be used for similarity computations, should it?</p></li>
<li><p>When your <strong>attributes have different units and scale</strong> you need to be very careful. A popular heuristic is <code>StandardScaler</code>, i.e. normalize each attri... | 0 | 2016-09-21T06:17:23Z | [
"python",
"scipy",
"scikit-learn",
"cluster-analysis",
"dbscan"
] |
Python: How to activate an event by keypress with pyautogui? | 39,603,897 | <p>I've installed the pyautogui package to use the .hotkey() function to trigger an event. For example: If you press the key combination "Ctrl + c" the console shall display the message "Hello world".</p>
<p>I tried something like this:</p>
<pre><code>while True:
if pyautogui.hotkey("ctrl", "c"):
print("Hell... | 0 | 2016-09-20T21:20:01Z | 39,608,720 | <p>I solved the problem myself. It seems to be you don't need the pyautogui modul at all and you only have to implement tkinter bindings like this:</p>
<pre><code>import tkinter from *
root = TK()
def keyevent(event):
if event.keycode == 67: #Check if pressed key has code 67 (character 'c')
prin... | 0 | 2016-09-21T06:13:09Z | [
"python",
"events",
"key",
"key-events",
"pyautogui"
] |
Reading a tarfile into BytesIO | 39,603,978 | <p>I'm using <a href="https://docker-py.readthedocs.io/en/latest/api/#put_archive" rel="nofollow">Docker-py</a> API to handle and manipulate <code>Docker</code> containers. In the <code>API</code>, the <code>put_archive</code> function expects the <code>data</code> field to be in bytes.
So, using the <code>tarfile</cod... | 1 | 2016-09-20T21:25:59Z | 39,605,507 | <p>You could do this way (untested because I don't have<code>Docker-py</code> installed):</p>
<pre><code>with open('keys.tar', 'rb') as fin:
data = io.BytesIO(fin.read())
</code></pre>
| 1 | 2016-09-20T23:59:44Z | [
"python",
"byte",
"tar"
] |
Python Code not Working in Certain Versions | 39,604,004 | <p>So for my school, I have to make this script that calculates the tip and tax of a meal. I'm ahead of everyone in my class, so no others have had this issue. </p>
<p>The code works fine in the Python3 IDLE on my PC, it also works fine at <a href="https://repl.it/languages/python3" rel="nofollow">repl.it</a>. Oddly e... | 1 | 2016-09-20T21:28:07Z | 39,604,295 | <p>I agree with edwinksl comment, check which version of python is on your schools computer. You can right click your python file and click edit with idle, the version should be in the top right coner of the page (next to the file path).</p>
<p>I have one other note however. Your teacher could have otherwise specified... | 0 | 2016-09-20T21:52:54Z | [
"python",
"python-2.7",
"python-3.x",
"calculator"
] |
Python Code not Working in Certain Versions | 39,604,004 | <p>So for my school, I have to make this script that calculates the tip and tax of a meal. I'm ahead of everyone in my class, so no others have had this issue. </p>
<p>The code works fine in the Python3 IDLE on my PC, it also works fine at <a href="https://repl.it/languages/python3" rel="nofollow">repl.it</a>. Oddly e... | 1 | 2016-09-20T21:28:07Z | 39,604,418 | <p>The fact that you get $0 as answer may show that python (2, likely) still represents numbers as integers. Try explicitly casting to floats.
Such as:</p>
<pre><code>tip1 = tp/100.0 # instead of 100
</code></pre>
<p>or</p>
<pre><code>tx = float(input("What is the tax %? "))
</code></pre>
<p>Also the clipping for ... | 1 | 2016-09-20T22:02:37Z | [
"python",
"python-2.7",
"python-3.x",
"calculator"
] |
Path for Windows10 Python 2.7 USB COM6 | 39,604,083 | <p>I am trying to access my USB COM6 port on my windows10 using python2.7</p>
<p>The original code was for Linux was: </p>
<pre><code>board = MultiWii("/dev/ttyUSB0")
</code></pre>
<p>My modified code for Windows is:</p>
<pre><code>board = MultiWii("/COM6")
</code></pre>
<p>Is the correct code?</p>
| 0 | 2016-09-20T21:33:05Z | 39,604,704 | <p>No, <code>/COM6</code> is not correct in Windows. Try <code>COM6</code> and <code>\\.\COM6</code>. To write the latter one inside a string literal in Python, you probably have to escape the back slashes, so you would write <code>"\\\\.\\COM6"</code>.</p>
| 0 | 2016-09-20T22:29:27Z | [
"python",
"python-2.7",
"usb",
"hardware"
] |
Pandas delete all rows that are not a 'datetime' type | 39,604,094 | <p>I've got a large file with login information for a list of users. The problem is that the file includes other information in the <code>Date</code> column. I would like to remove all rows that are not of type <code>datetime</code> in the <code>Date</code> column. My data resembles</p>
<pre><code>df=
Name Date
n... | 2 | 2016-09-20T21:33:50Z | 39,604,232 | <p>Use <code>pd.to_datetime</code> with parameter <code>errors='coerce'</code> to make non-dates into <code>NaT</code> null values. Then you can drop those rows</p>
<pre><code>df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
df = df.dropna(subset=['Date'])
df
</code></pre>
<p><a href="http://i.stack.imgur.c... | 6 | 2016-09-20T21:47:09Z | [
"python",
"pandas"
] |
(python and jes) How to find the position of a character in a string if 2 characters are the same? | 39,604,193 | <pre><code>def sumNumbers1(num1,num2):
sum= str(num1+num2)
print "Sum is " + sum
for char in sum:
digit = sum.find(char)+1
print "Digit " + str(digit) + " is " + char
</code></pre>
<p>I'm trying to get a function that prints the sum of two numbers, then the first digit of the sum and what t... | 0 | 2016-09-20T21:42:35Z | 39,604,221 | <p>You likely want to use <code>enumerate</code>. <code>sum</code> is a string, enumerate will let you iterate over the characters in that string while also returning the index of each character. Python indexing is 0-based, so if you want the <em>digit</em> index to start at 1, you need to add 1 to <code>i</code></p>... | 1 | 2016-09-20T21:45:55Z | [
"python",
"jes"
] |
(python and jes) How to find the position of a character in a string if 2 characters are the same? | 39,604,193 | <pre><code>def sumNumbers1(num1,num2):
sum= str(num1+num2)
print "Sum is " + sum
for char in sum:
digit = sum.find(char)+1
print "Digit " + str(digit) + " is " + char
</code></pre>
<p>I'm trying to get a function that prints the sum of two numbers, then the first digit of the sum and what t... | 0 | 2016-09-20T21:42:35Z | 39,604,696 | <pre><code>def sumNumbers1(num1,num2):
sum = num1 + num2
print ("the sum is" , sum)
s = str(sum)
for digit,i in enumerate(s,start =1):
print("digit ", digit, "is", i)
sumNumbers1(2230,20)
def sumNumbers1(num1,num2):
sum = num1 + num2
pos = 1
print ("the sum is" , sum)
for e i... | 0 | 2016-09-20T22:28:46Z | [
"python",
"jes"
] |
subprocess Popen: signal not propagating | 39,604,228 | <p>execute_sleep.py</p>
<pre><code>import os
import time
import subprocess
sleep_script = 'sleep_forever.py'
child = subprocess.Popen(sleep_script,
shell=True,
close_fds=True,
stdout=subprocess.PIPE,
stderr=subprocess.... | 1 | 2016-09-20T21:47:04Z | 39,604,645 | <p>You need to handle the signal, otherwise you are creating orphans (sleep_script processes). So that when the signal to terminate the father process is caught it propagates to child processes before.</p>
<pre><code>def handler(signum, frame):
functionToKillSleeper(pidtokill)
signal.signal(signal.SIGTERM, handl... | 1 | 2016-09-20T22:23:51Z | [
"python",
"subprocess",
"signals"
] |
Django 1.8 calls to database in html code | 39,604,282 | <p>long-time lurker for this website, but I finally decided to join the community.</p>
<p>I have a quick question on some of my code. I took a job this year for my university developing a website for the journalist department. The website was being built the previous year by another student using Django 1.8, python 2,... | 0 | 2016-09-20T21:51:50Z | 39,604,365 | <p>As I understand, you just need to add if statement:</p>
<pre><code>{% for article, section in featured_articles %}
{% if section.name == 'look' %}
<div class="media panel panel-default">
<div class="panel-body">
<div class="media-left">
<a href="articles/{{ article.url }... | 0 | 2016-09-20T21:58:09Z | [
"python",
"html",
"django"
] |
Django 1.8 calls to database in html code | 39,604,282 | <p>long-time lurker for this website, but I finally decided to join the community.</p>
<p>I have a quick question on some of my code. I took a job this year for my university developing a website for the journalist department. The website was being built the previous year by another student using Django 1.8, python 2,... | 0 | 2016-09-20T21:51:50Z | 39,608,619 | <p>Overall, it is a not such a good idea. You are sending all data to the template engine and doing the filtering there?</p>
<p>Why not filter it in the view function / view class and then return that data inside a template variable and then render in the front end?</p>
<pre><code>def detail(request, poll_id): ... | 1 | 2016-09-21T06:03:46Z | [
"python",
"html",
"django"
] |
How to catch an index error | 39,604,377 | <p>Given <code>mylist = [0, 1]</code></p>
<pre><code>def catch_index_error(value):
try:
return value
except IndexError:
return None
catch_index_error(mylist[5])
</code></pre>
<p>returns an <code>IndexError</code></p>
<p>The argument is evaluated prior to the function being executed and there... | 1 | 2016-09-20T21:58:53Z | 39,604,416 | <pre><code>try:
catch_index_error(mylist[5])
except IndexError:
do something
</code></pre>
<p>The error occurs in the call</p>
| 1 | 2016-09-20T22:02:18Z | [
"python"
] |
How to catch an index error | 39,604,377 | <p>Given <code>mylist = [0, 1]</code></p>
<pre><code>def catch_index_error(value):
try:
return value
except IndexError:
return None
catch_index_error(mylist[5])
</code></pre>
<p>returns an <code>IndexError</code></p>
<p>The argument is evaluated prior to the function being executed and there... | 1 | 2016-09-20T21:58:53Z | 39,604,430 | <p>Use this:</p>
<pre><code>try:
mylist[5]
except IndexError:
#your code
</code></pre>
| 1 | 2016-09-20T22:03:29Z | [
"python"
] |
How to catch an index error | 39,604,377 | <p>Given <code>mylist = [0, 1]</code></p>
<pre><code>def catch_index_error(value):
try:
return value
except IndexError:
return None
catch_index_error(mylist[5])
</code></pre>
<p>returns an <code>IndexError</code></p>
<p>The argument is evaluated prior to the function being executed and there... | 1 | 2016-09-20T21:58:53Z | 39,604,436 | <p>The expression <code>mylist[5]</code> causes the <code>IndexError</code>, because it is evaluated <em>before</em> the function is called.</p>
<p>The only way to fix this is by letting the function return the correct value <em>from <code>mylist</code></em>:</p>
<pre><code>mylist = [0,1]
def catch_index_error(index)... | 2 | 2016-09-20T22:04:08Z | [
"python"
] |
How to catch an index error | 39,604,377 | <p>Given <code>mylist = [0, 1]</code></p>
<pre><code>def catch_index_error(value):
try:
return value
except IndexError:
return None
catch_index_error(mylist[5])
</code></pre>
<p>returns an <code>IndexError</code></p>
<p>The argument is evaluated prior to the function being executed and there... | 1 | 2016-09-20T21:58:53Z | 39,604,882 | <p>All the answers mentioned here will suffice your requirement. But I believe the ideal way to achieve this is via using <code>decorator</code>. In fact they exist in python for such kind of scenarios. For example, create a decorator as:</p>
<pre><code>def wrap_index_error(func):
def wrapped_func(*args, **kwargs)... | 0 | 2016-09-20T22:46:55Z | [
"python"
] |
Counting paths in a recursive call | 39,604,394 | <p>The problem I'm working on is this, from Cracking the Coding Interview:</p>
<p>"A child is running up a staircase with n steps, and can hop either 1 step, 2 steps,
or 3 steps at a time. Implement a method to count how many possible ways the
child can run up the stairs."</p>
<p>Coming from C++ I know that a counter... | 1 | 2016-09-20T22:00:24Z | 39,604,622 | <p>In your function __calculatePaths, you have to set paths = 0, before the for loop. Otherwise it is add the values to the global instance of paths and that's why you are getting wrong answer.</p>
<pre><code>def __calculatePaths(currPathLength, paths, currSeries):
if currPathLength == 0:
print "successful serie... | 0 | 2016-09-20T22:21:15Z | [
"python",
"recursion",
"counter"
] |
Counting paths in a recursive call | 39,604,394 | <p>The problem I'm working on is this, from Cracking the Coding Interview:</p>
<p>"A child is running up a staircase with n steps, and can hop either 1 step, 2 steps,
or 3 steps at a time. Implement a method to count how many possible ways the
child can run up the stairs."</p>
<p>Coming from C++ I know that a counter... | 1 | 2016-09-20T22:00:24Z | 39,604,777 | <p>Most important, realize that you don't have to determine those sequences: you need only to count them. For instance, there's only one way to finish from step N-1: hop 1 step. From N-2, there are two ways: hop both steps at once, or hop 1 step and finish from there. Our "ways to finish" list now looks like this, w... | 1 | 2016-09-20T22:35:34Z | [
"python",
"recursion",
"counter"
] |
Counting paths in a recursive call | 39,604,394 | <p>The problem I'm working on is this, from Cracking the Coding Interview:</p>
<p>"A child is running up a staircase with n steps, and can hop either 1 step, 2 steps,
or 3 steps at a time. Implement a method to count how many possible ways the
child can run up the stairs."</p>
<p>Coming from C++ I know that a counter... | 1 | 2016-09-20T22:00:24Z | 39,604,838 | <p>This should be the most efficient way to do it computing-wise using your solution:</p>
<pre><code>from collections import deque
def calculate_paths(length):
count = 0 # Global count
def calcuate(remaining_length):
# 0 means success
# 1 means only 1 option is available (hop 1)
if ... | 0 | 2016-09-20T22:42:53Z | [
"python",
"recursion",
"counter"
] |
Adaline Learning Algorithm | 39,604,428 | <p>I can not seem to debug the following implementation of an Adaline neuron... I'm hoping someone can spot what I cannot. I think the problem lies in the last few lines of my train method?</p>
<pre><code>from numpy import random, array, dot
import numpy as np
import matplotlib.pyplot as plt
from random import choice
... | 0 | 2016-09-20T22:03:12Z | 39,624,302 | <p>There is nothing really wrong, but:</p>
<ol>
<li><p>You are using "i" for iterator in <strong>both</strong> loops, in this code it does not matter since you do not really use it in the outer loop, but it could lead to very nasty bugs in general.</p></li>
<li><p>Your gamma is too high, change it to 0.01 </p></li>
<l... | 0 | 2016-09-21T18:46:06Z | [
"python",
"machine-learning",
"neural-network"
] |
API Call - Multi dimensional nested dictionary to pandas data frame | 39,604,461 | <p>I need your help with converting a multidimensional dict to a pandas data frame. I get the dict from a JSON file which I retrieve from a API call (Shopify). </p>
<pre><code>response = requests.get("URL", auth=("ID","KEY"))
data = json.loads(response.text)
</code></pre>
<p>The "data" dictionary looks as follows:</... | 2 | 2016-09-20T22:05:58Z | 39,604,682 | <p>There are a number of ways to do this. This is just a way I decided to do it. You need to explore how you want to see this represented, then figure out how to get there.</p>
<pre><code>df = pd.DataFrame(data['orders'])
df1 = df.line_items.str[0].apply(pd.Series)
df2 = df1.destination_location.apply(pd.Series)
... | 1 | 2016-09-20T22:27:17Z | [
"python",
"json",
"pandas",
"dictionary",
"dataframe"
] |
break out of list comprehension? | 39,604,476 | <p>I am taking in an integer value, finding the factorial of that value and trying to count the number of trailing zeros if any are present. For example:</p>
<pre><code>def zeros(n):
import math
factorial = str(math.factorial(n))
zeros_lst = [number if number == "0" (else) for number in factorial[::-1]]
... | 0 | 2016-09-20T22:07:14Z | 39,604,572 | <p>There is no "breaking" in list comprehensions, but there are other tricks, e.g. <code>itertools.takewhile</code> which iterates an iterable while a condition is satisfied:</p>
<pre><code>>>> from itertools import takewhile
>>>
>>> values = [7, 9, 11, 4, 2, 78, 9]
>>> list(takewh... | 0 | 2016-09-20T22:15:15Z | [
"python",
"list-comprehension",
"break"
] |
break out of list comprehension? | 39,604,476 | <p>I am taking in an integer value, finding the factorial of that value and trying to count the number of trailing zeros if any are present. For example:</p>
<pre><code>def zeros(n):
import math
factorial = str(math.factorial(n))
zeros_lst = [number if number == "0" (else) for number in factorial[::-1]]
... | 0 | 2016-09-20T22:07:14Z | 39,604,607 | <blockquote>
<p>If someone knows how to break from a list comprehension </p>
</blockquote>
<p>You can not break a list compression. </p>
<p>But you can modify your list comprehension with the <code>if</code> condition in <code>for</code> loop. With if, you can decide what values are needed to be the part of the lis... | 0 | 2016-09-20T22:19:34Z | [
"python",
"list-comprehension",
"break"
] |
break out of list comprehension? | 39,604,476 | <p>I am taking in an integer value, finding the factorial of that value and trying to count the number of trailing zeros if any are present. For example:</p>
<pre><code>def zeros(n):
import math
factorial = str(math.factorial(n))
zeros_lst = [number if number == "0" (else) for number in factorial[::-1]]
... | 0 | 2016-09-20T22:07:14Z | 39,604,895 | <p>There is a more mathematical approach to this problem that is very simple and easy to implement. We only need to count how many factors of ten there are in factorial(n). We have an excess of factors of 2, so we choose to count factors of 5. It doesn't look as clean, but it avoids the computation of a factorial. The ... | 0 | 2016-09-20T22:48:35Z | [
"python",
"list-comprehension",
"break"
] |
break out of list comprehension? | 39,604,476 | <p>I am taking in an integer value, finding the factorial of that value and trying to count the number of trailing zeros if any are present. For example:</p>
<pre><code>def zeros(n):
import math
factorial = str(math.factorial(n))
zeros_lst = [number if number == "0" (else) for number in factorial[::-1]]
... | 0 | 2016-09-20T22:07:14Z | 39,605,022 | <p>Here is a function that will count the zeros, you just need to pass it your number. This saves the string operations you had before. It will terminate once there are no more trailing zeros.</p>
<pre><code>def count_zeros(n):
n_zeros = 0;
while True:
if n%10 == 0:
n = n/10
n_z... | 0 | 2016-09-20T23:02:58Z | [
"python",
"list-comprehension",
"break"
] |
Problems Using the Berkeley DB Transactional Processing | 39,604,509 | <p>I'm writing a set of programs that have to operate on a common database, possibly concurrently. For the sake of simplicity (for the user), I didn't want to require the setup of a database server. Therefore I setteled on Berkeley DB, where one can just fire up a program and let it create the DB if it doesn't exist.</... | 0 | 2016-09-20T22:10:14Z | 39,919,736 | <p>RPM (see <a href="http://rpm5.org" rel="nofollow">http://rpm5.org</a>) uses Berkeley DB in transactional mode. There's a fair number of gotchas, depending on what you are attempting.</p>
<p>You have already found DB_CONFIG: you MUST configure the sizes for mutexes and locks, the defaults are invariably too small.</... | 0 | 2016-10-07T14:30:42Z | [
"python",
"python-3.x",
"berkeley-db"
] |
Pandas apply with list output gives ValueError once df contains timeseries | 39,604,586 | <p>I'm trying to implement an apply function that returns two values because the calculations are similar and pretty time consuming, so I don't want to do apply twice.
The below is an MWE that is pretty stupid and I know there are easier ways to achieve what this MWE does. My actual function is more complicated, but I ... | 3 | 2016-09-20T22:16:47Z | 39,604,756 | <p>have <code>function</code> return a <code>pd.Series</code> instead. Returning a list is making apply try to fit the list into the existing row. Returning a <code>pd.Series</code> convinces pandas of something different.</p>
<pre><code>def function(row):
return pd.Series([row.A, row.A/2])
df2 = pd.DataFrame(... | 2 | 2016-09-20T22:33:56Z | [
"python",
"pandas",
"time-series"
] |
Can you construct csrf from request object - csrf constructor exception? | 39,604,591 | <p>I am following an example of user registration and my code looks like this</p>
<pre><code>from django.views.decorators import csrf
def register_user(request):
args={}
args.update(csrf(request)) #---->Crashes here
args["form"] = UserCreationForm()
return render_to_response("register.html",args)
<... | 0 | 2016-09-20T22:17:26Z | 39,604,627 | <p>A quick google shows that the correct import for the csrf decorator is</p>
<pre><code>from django.views.decorators.csrf import csrf_protect
</code></pre>
<p>My guess (I don't have django available to test) is that you're importing something else, although it's probably a non callable module :)</p>
| 1 | 2016-09-20T22:21:53Z | [
"python",
"django"
] |
Can you construct csrf from request object - csrf constructor exception? | 39,604,591 | <p>I am following an example of user registration and my code looks like this</p>
<pre><code>from django.views.decorators import csrf
def register_user(request):
args={}
args.update(csrf(request)) #---->Crashes here
args["form"] = UserCreationForm()
return render_to_response("register.html",args)
<... | 0 | 2016-09-20T22:17:26Z | 39,604,691 | <p>There are two way to CSRF protect your django websites :</p>
<h1>1 - Using the middleware, the simplest way :</h1>
<p>The <code>django.middleware.csrf.CsrfViewMiddleware</code> automatically adds a CSRF token to the context.</p>
<p>This middleware is enabled by default in your <code>settings.py</code> file and yo... | 2 | 2016-09-20T22:28:04Z | [
"python",
"django"
] |
Can you construct csrf from request object - csrf constructor exception? | 39,604,591 | <p>I am following an example of user registration and my code looks like this</p>
<pre><code>from django.views.decorators import csrf
def register_user(request):
args={}
args.update(csrf(request)) #---->Crashes here
args["form"] = UserCreationForm()
return render_to_response("register.html",args)
<... | 0 | 2016-09-20T22:17:26Z | 39,605,030 | <p>Judging from your code, you need <code>django.template.context_processors.csrf()</code>, not <code>django.views.decorators.csrf</code>. This puts the csrf token in the template context.</p>
<p>The recommended way is to use <code>render</code> instead of <code>render_to_response</code>. This will run all configured ... | 1 | 2016-09-20T23:03:35Z | [
"python",
"django"
] |
Sorting 2D array by Mathematical Equation | 39,604,638 | <p>I have a 2D array list that contains (x,y), however I want to sort this list by the Equation of Minimum value of (square root of (x^2 + y^2)).</p>
<p>For example I have these four 2D lists:</p>
<pre><code>(20,10)
(3,4)
(5,6)
(1.2,7)
</code></pre>
<p>If I take the square root of each 2D array in this list and retu... | 0 | 2016-09-20T22:23:00Z | 39,605,073 | <p>the code below will solve what you request, uncomment the print statements if you wish to see how the ordering works!!</p>
<pre><code>import math
array = [(20,10), (3,4), (5,6), (1.2,7)]
sortList = []
count = 0
tempList = []
placeholder = []
#Compute the Equation of Minimum Value
for x,y in array:
tempList.appe... | 0 | 2016-09-20T23:07:44Z | [
"python",
"arrays",
"sorting"
] |
Sorting 2D array by Mathematical Equation | 39,604,638 | <p>I have a 2D array list that contains (x,y), however I want to sort this list by the Equation of Minimum value of (square root of (x^2 + y^2)).</p>
<p>For example I have these four 2D lists:</p>
<pre><code>(20,10)
(3,4)
(5,6)
(1.2,7)
</code></pre>
<p>If I take the square root of each 2D array in this list and retu... | 0 | 2016-09-20T22:23:00Z | 39,605,122 | <p>Switch your data structure to a list of tuples and then sort using minimal value as the key function (with memoization for efficiency):</p>
<pre><code>M = [(20, 10), (3, 4), (5,6), (1.2, 7), (6.5, 4)]
def minimum_value(coordinate, dictionary={}): # intentional dangerous default value
if coordinate not in dict... | 0 | 2016-09-20T23:12:57Z | [
"python",
"arrays",
"sorting"
] |
Sorting 2D array by Mathematical Equation | 39,604,638 | <p>I have a 2D array list that contains (x,y), however I want to sort this list by the Equation of Minimum value of (square root of (x^2 + y^2)).</p>
<p>For example I have these four 2D lists:</p>
<pre><code>(20,10)
(3,4)
(5,6)
(1.2,7)
</code></pre>
<p>If I take the square root of each 2D array in this list and retu... | 0 | 2016-09-20T22:23:00Z | 39,605,145 | <p>Use the built in sort method of a list:</p>
<pre><code>from math import sqrt
def dist(elem):
return sqrt(pow(elem[0], 2) + pow(elem[1], 2))
def sorting_func(first, second):
if dist(first) < dist(second):
return 1
elif dist(second) < dist(first):
return -1
else:
retur... | 1 | 2016-09-20T23:14:32Z | [
"python",
"arrays",
"sorting"
] |
Can SlidingWindows have half second periods in python apache beam? | 39,604,646 | <p>SlidingWindows seems to be rounding my periods. If I set the period to 1.5 and size to 3.5 seconds, it will create 3.5 windows every 1.0 second. It expected to have 3.5 second windows every 1.5 seconds. </p>
<p>Is it possible to have a period that is a fraction of a second?</p>
| 1 | 2016-09-20T22:24:14Z | 39,624,079 | <p>It should be possible; I've filed <a href="https://issues.apache.org/jira/browse/BEAM-662" rel="nofollow">https://issues.apache.org/jira/browse/BEAM-662</a> to address this</p>
| 1 | 2016-09-21T18:32:55Z | [
"python",
"google-cloud-dataflow",
"dataflow",
"apache-beam"
] |
Java byte array to Ruby | 39,604,672 | <p>I have a Desktop application using java swing frames. I have to rewrite the application to either Ruby or python. However I understand java to certain extent - I need help rewriting certain piece of the code in java.</p>
<p>1.</p>
<pre><code>byte[] ModuleGuid = new byte[]{
(byte)0xe1, (byte)0x9a, (byte)0x6... | -2 | 2016-09-20T22:26:14Z | 39,604,992 | <ol>
<li><p>There's no such thing as <code>byte</code> in Ruby. When you want to store a sequence of bytes, you store it in a string:</p>
<pre><code>module_guid = "\xE1\x9A\x69\x01...".force_encoding('ASCII-8BIT')
</code></pre>
<p>If you want to copy and paste from Java code, then use:</p>
<pre><code>module_guid = [... | 2 | 2016-09-20T22:59:00Z | [
"java",
"python",
"ruby"
] |
Running PySpark using Cronjob (crontab) | 39,604,706 | <p>First, I assume that we have <code>SPARK_HOME</code> set up, in my case it's at <code>~/Desktop/spark-2.0.0</code>. Basically, I want to run my PySpark script using Cronjob (e.g. <code>crontab -e</code>). My question is how to add environment path to make Spark script works with Cronjob. Here is my sample script, <c... | 0 | 2016-09-20T22:29:30Z | 39,605,198 | <p>What you can do is , add following line in your .bashrc file in home location.</p>
<pre><code>export PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$HOME/anaconda/bin
</code></pre>
<p>then you can have following entry in crontab</p>
<pre><code>* * * * * source ~/.bashrc;sh run_example.sh
</code></pre>
<p>This... | 2 | 2016-09-20T23:21:58Z | [
"python",
"cron",
"pyspark",
"crontab"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.