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 |
|---|---|---|---|---|---|---|---|---|---|
How to use groupby agg and rename functions for all columns | 38,382,327 | <h3>Question</h3>
<p><strong><em>How do I get the following result without having to assign a function dictionary for every column?</em></strong></p>
<pre><code>df.groupby(level=0).agg({'one': {'SUM': 'sum', 'HowMany': 'count'},
'two': {'SUM': 'sum', 'HowMany': 'count'}})
</code></pre>
<p><a... | 3 | 2016-07-14T19:06:34Z | 38,382,848 | <p>This is an ugly answer:</p>
<pre><code>gb = df.stack(0).groupby(level=[0, -1])
df1 = gb.agg({'SUM': 'sum', 'HowMany': 'count'})
df1.unstack().swaplevel(0, 1, 1).sort_index(1, 0)
</code></pre>
<p><a href="http://i.stack.imgur.com/CKIyQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/CKIyQ.png" alt="enter ima... | 2 | 2016-07-14T19:37:28Z | [
"python",
"pandas",
"group-by"
] |
Numpy recarray indexing by column truncates floats | 38,382,497 | <p>In a simple recarray in python, the output value is getting truncated when indexed by column name:</p>
<pre><code>import numpy #1.10.0
arr = numpy.zeros(1, dtype=[('a', np.float)])
arr[0]['a'] = 0.1234567891234
print arr
print arr['a']
[(0.1234567891234,)]
[ 0.12345679]
</code></pre>
<p>Why does this happen? Can ... | 0 | 2016-07-14T19:17:28Z | 38,383,353 | <p>The print precision for a numeric array is 8 digits:</p>
<pre><code>In [250]: np.get_printoptions()
Out[250]:
{'edgeitems': 3,
'formatter': None,
'infstr': 'inf',
'linewidth': 75,
'nanstr': 'nan',
'precision': 8,
'suppress': False,
'threshold': 1000}
</code></pre>
<p>But it doesn't use that value when disp... | 1 | 2016-07-14T20:05:44Z | [
"python",
"numpy"
] |
Numpy recarray indexing by column truncates floats | 38,382,497 | <p>In a simple recarray in python, the output value is getting truncated when indexed by column name:</p>
<pre><code>import numpy #1.10.0
arr = numpy.zeros(1, dtype=[('a', np.float)])
arr[0]['a'] = 0.1234567891234
print arr
print arr['a']
[(0.1234567891234,)]
[ 0.12345679]
</code></pre>
<p>Why does this happen? Can ... | 0 | 2016-07-14T19:17:28Z | 38,417,071 | <p>As others have mentioned, this is a question of printing precision. You can set a different value like this, using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.set_printoptions.html" rel="nofollow"><code>set_printoptions</code></a>:</p>
<pre><code>import numpy
numpy.set_printoptions(precision=... | 0 | 2016-07-17T01:17:16Z | [
"python",
"numpy"
] |
Sending JSON data to client django | 38,382,514 | <p>I am creating mobile applications for my django web applicaiton. I have it set up like so</p>
<p><strong>models.py</strong></p>
<pre><code> class Comment(models.Model):
CommentDescription = models.CharField(max_length=120)
Owner = models.ForeignKey(User,null=True)
PostToCommentOn = models.Foreign... | 1 | 2016-07-14T19:18:29Z | 38,382,686 | <p>Take a look over <a href="https://docs.djangoproject.com/es/1.9/ref/request-response/#jsonresponse-objects" rel="nofollow">JsonResponse</a>:</p>
<pre><code>>>> from django.http import JsonResponse
>>> response = JsonResponse({'foo': 'bar'})
>>> response.content
b'{"foo": "bar"}'
</code></... | 2 | 2016-07-14T19:28:53Z | [
"python",
"json",
"django",
"swift"
] |
Recursively checking for balanced string in Python | 38,382,519 | <p>I've been stuck on this for quite a while, I can't come up with recursive cases, in particular I don't understand how to split a list to check if its balanced.
If someone could help me I would really appreciate it.</p>
<pre><code>def balanced_str(s):
"""
Return whether string s is balanced or not. A balance... | 1 | 2016-07-14T19:18:41Z | 38,382,643 | <p>A simple, iterative approach could be to create a tiny lexer. It will increase a counter <code>o</code> when an opening parentheses <code>(</code> appears, and decreases the counter if a closing parentheses <code>)</code> appears. If meanwhile searching the string the counter <code>o</code> gets negative, or by the ... | 1 | 2016-07-14T19:26:31Z | [
"python",
"recursion"
] |
Recursively checking for balanced string in Python | 38,382,519 | <p>I've been stuck on this for quite a while, I can't come up with recursive cases, in particular I don't understand how to split a list to check if its balanced.
If someone could help me I would really appreciate it.</p>
<pre><code>def balanced_str(s):
"""
Return whether string s is balanced or not. A balance... | 1 | 2016-07-14T19:18:41Z | 38,382,712 | <p>For a recursive approach, you can create a small helper function that takes more parameters (ie. the number of parens we've seen so far). Below this approach, you can see how you can do it <em>without</em> a helper function through the use of <code>global</code></p>
<pre><code>def balanced_str(s):
"""
Retur... | 2 | 2016-07-14T19:30:49Z | [
"python",
"recursion"
] |
Recursively checking for balanced string in Python | 38,382,519 | <p>I've been stuck on this for quite a while, I can't come up with recursive cases, in particular I don't understand how to split a list to check if its balanced.
If someone could help me I would really appreciate it.</p>
<pre><code>def balanced_str(s):
"""
Return whether string s is balanced or not. A balance... | 1 | 2016-07-14T19:18:41Z | 38,383,574 | <p>Here's my candidate solution:</p>
<pre><code>def balanced(iterable, semaphore=0):
if semaphore < 0 or len(iterable) == 0:
return semaphore == 0
first, *rest = iterable
return balanced(rest, semaphore + { "(": 1, ")": -1 }.get(first, 0))
</code></pre>
<p>I've renamed <code>balanced_str()</... | 0 | 2016-07-14T20:19:36Z | [
"python",
"recursion"
] |
How can I do this python list comprehension in NumPy? | 38,382,601 | <p>Let's say I have an array of values, <code>r</code>, which range anywhere from <code>0</code> to <code>1</code>. I want to remove all values that are some threshold value away from the median. Let's assume here that that threshold value is <code>0.5</code>, and <code>len(r) = 3000</code>. Then to mask out all values... | 3 | 2016-07-14T19:23:49Z | 38,382,890 | <p>You can use numpy conditional selections to create new array, without those values.</p>
<pre><code>start = time.time()
m = np.median(r)
maxr,minr = m-0.5, m+0.5
filtered_array = r[ (r < minr) | (r > maxr) ]
end = time.time()
print('Took %.4f seconds'%(end-start))
</code></pre>
<p><code>filtered_array</code> ... | 3 | 2016-07-14T19:39:44Z | [
"python",
"arrays",
"numpy",
"masking",
"bitmask"
] |
How can I do this python list comprehension in NumPy? | 38,382,601 | <p>Let's say I have an array of values, <code>r</code>, which range anywhere from <code>0</code> to <code>1</code>. I want to remove all values that are some threshold value away from the median. Let's assume here that that threshold value is <code>0.5</code>, and <code>len(r) = 3000</code>. Then to mask out all values... | 3 | 2016-07-14T19:23:49Z | 38,383,036 | <p>One liner...</p>
<pre><code>new_mask = abs(np.median(r) - r) > 0.5
</code></pre>
| 3 | 2016-07-14T19:48:11Z | [
"python",
"arrays",
"numpy",
"masking",
"bitmask"
] |
Dealing with excel files in Python | 38,382,632 | <p>I have a folder with .xlsx files in and I need sum every three files together and output the result into a new .xlsx file using Python. There are over one hundred files. What is the most efficient way to do this? </p>
| 1 | 2016-07-14T19:25:51Z | 38,383,757 | <p>You can use <a href="https://pypi.python.org/pypi/xlrd" rel="nofollow">xlrd</a> in order to read the data and <a href="https://pypi.python.org/pypi/XlsxWriter" rel="nofollow">xlsxwriter</a> in order to create a new excel file.</p>
<p>If you write some python code of what you have already tried and doesn't work we m... | 1 | 2016-07-14T20:31:32Z | [
"python",
"excel",
"dataframe"
] |
NÃM matrix multiplication for python | 38,382,653 | <p>i am actually writing a code to actually perform matrix multiplication on a nÃm matrix
the closest that i got is the following </p>
<pre><code>X = [[15,2,9],
[1 ,3,4],
[7 ,2,9]]
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
for i in range(len(... | 1 | 2016-07-14T19:26:56Z | 38,382,879 | <p>Your question seems to be unclear, although I'm pretty sure there are duplicates.</p>
<p>If your question was to perform multiplication of two dimensional array, here is how to create n x m or m x n matrix:</p>
<pre><code>n = int(input())
m = int(input())
matrix = [[0 for i in range(m) for j in range(n)]
</code><... | 0 | 2016-07-14T19:39:06Z | [
"python",
"matrix"
] |
NÃM matrix multiplication for python | 38,382,653 | <p>i am actually writing a code to actually perform matrix multiplication on a nÃm matrix
the closest that i got is the following </p>
<pre><code>X = [[15,2,9],
[1 ,3,4],
[7 ,2,9]]
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
for i in range(len(... | 1 | 2016-07-14T19:26:56Z | 38,383,548 | <p>Hello guys thank you for your help i was actually able to solve my problem, and i am posting my solution for everyone to benefit from it, Since the code is fully ready for anyone to use it you can see lots of printing happening but that is just to illustrate everything </p>
<p>Thank you again </p>
<pre><code>print... | 0 | 2016-07-14T20:18:24Z | [
"python",
"matrix"
] |
NÃM matrix multiplication for python | 38,382,653 | <p>i am actually writing a code to actually perform matrix multiplication on a nÃm matrix
the closest that i got is the following </p>
<pre><code>X = [[15,2,9],
[1 ,3,4],
[7 ,2,9]]
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
for i in range(len(... | 1 | 2016-07-14T19:26:56Z | 38,383,874 | <p>You should find this useful: </p>
<p><a href="https://repl.it/CcJA" rel="nofollow"><strong>Run it online in REPL</strong></a> or... <a href="http://ideone.com/mRWCDt" rel="nofollow"><strong>Run it online in Ideone</strong></a></p>
<pre class="lang-python prettyprint-override"><code>x,y = input("Enter the dimension... | 0 | 2016-07-14T20:39:06Z | [
"python",
"matrix"
] |
How can I parse the emotes out of a Twitch IRC response into an list of dictionaries? | 38,382,703 | <p>I would like to parse an IRC message from Twitch to a list of dictionaries, accounting for emotes.</p>
<p>Here is a sample of what I can get from Twitch:</p>
<pre><code>"Testing. :) Confirmed!"
{"emotes": [(1, (9, 10))]}
</code></pre>
<p>It describes that there is the emote with ID 1 from characters 9 to 10 (wit... | 1 | 2016-07-14T19:30:22Z | 38,625,349 | <p>I have found a solution which, although quite ugly, works.</p>
<pre><code>import re
packet_expression = re.compile(r'(@.+)? :([a-zA-Z0-9][\w]{2,23})!\2@\2.tmi.twitch.tv PRIVMSG #([a-zA-Z0-9][\w]{2,23}) :(.+)')
def parse_twitch(packet):
match = re.match(packet_expression, packet)
items = match.group(1)[1... | 0 | 2016-07-28T00:37:08Z | [
"python",
"python-3.x",
"parsing",
"python-3.5",
"twitch"
] |
How can I parse the emotes out of a Twitch IRC response into an list of dictionaries? | 38,382,703 | <p>I would like to parse an IRC message from Twitch to a list of dictionaries, accounting for emotes.</p>
<p>Here is a sample of what I can get from Twitch:</p>
<pre><code>"Testing. :) Confirmed!"
{"emotes": [(1, (9, 10))]}
</code></pre>
<p>It describes that there is the emote with ID 1 from characters 9 to 10 (wit... | 1 | 2016-07-14T19:30:22Z | 38,625,611 | <p>I'm not sure if your incoming message looks like this:</p>
<pre><code>message = '''\
"Testing. :) Confirmed!"
{"emotes": [(1, (9, 10))]}'''
</code></pre>
<p>Or</p>
<pre><code>text = "Testing. :) Confirmed!"
meta = '{"emotes": [(1, (9, 10))]}'
</code></pre>
<p>I'm going to assume it's the latter, because it's ea... | 2 | 2016-07-28T01:14:24Z | [
"python",
"python-3.x",
"parsing",
"python-3.5",
"twitch"
] |
Run script from within pyspark shell | 38,382,737 | <p>I can run my python+pyspark script from the unix command line by typing</p>
<pre><code>pyspark script.py
</code></pre>
<p>But how do I run script.py from within the pyspark shell? This seems like an elementary question but I can't find the answer anywhere. I tried </p>
<pre><code>execfile('script.py')
</code></pr... | 1 | 2016-07-14T19:32:11Z | 39,125,094 | <p>Could the error come from <code>script.py</code> trying to create a new SparkContext variable?</p>
<p>When you launch the pyspark interactive client it usually says :
<code>SparkContext available as sc, HiveContext available as sqlContext.</code></p>
<p>If your script file contains <code>sc = SparkContext()</code>... | 0 | 2016-08-24T13:46:04Z | [
"python",
"pyspark"
] |
Jinja conditional clause dependent on data type | 38,382,765 | <p>I'm using SaltStack to manage BIND9 zone files. Previously I have used pillar data like this:</p>
<pre><code>zones:
example.com:
a:
www1: 1.2.3.4
www2: 1.2.3.5
</code></pre>
<p>along with a jinja templated file (indented just for readability) like this:</p>
<pre><code>{% if info.a is defined %}
... | 1 | 2016-07-14T19:33:46Z | 38,384,039 | <p>If the value can only be a string or a list, you can just check that this is not a string with <a href="http://jinja.pocoo.org/docs/dev/templates/#list-of-builtin-tests" rel="nofollow">builtin test</a></p>
<pre><code>{% if defn is not string %}
{% for ip in defn %}
{{ host }} IN A {{ ip }}
{% endfor... | 2 | 2016-07-14T20:52:13Z | [
"python",
"jinja2",
"salt-stack"
] |
How do I quickly create a numpy or pandas 2D array with both axis in a range and the values a product? | 38,382,824 | <p>The title is more complicated than I was expecting, but I am basically looking for a quick way to make a multiplication table that starts at abitraty integers for both X and Y axises.</p>
<p>My output would be similar to this for X being a range of <code>(5, 12, 1)</code> and Y being a range of <code>(20, 25, 1)</c... | 3 | 2016-07-14T19:36:34Z | 38,382,935 | <p><a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html"><code>NumPy broadcasting</code></a> for pandas!</p>
<pre><code>row = np.arange(20,25)
col = np.arange(5,12)
df = pd.DataFrame(row[:,None]*col,index=row,columns=col)
</code></pre>
<p>Sample run -</p>
<pre><code>In [224]: row = np.arange(20,25)... | 6 | 2016-07-14T19:42:02Z | [
"python",
"numpy",
"pandas"
] |
How to plot data being read at 12KHz in pyqtgraph on raspberry pi? | 38,382,867 | <p>My python script runs on a raspberry pi and reads voltage data at 12000 samples per second in chunks of 1200 samples from a LabJack U3. These data are stored in a list, and a time list with values corresponding to each voltage point is created artificially by referring to the voltage data read rate.
What is the best... | 0 | 2016-07-14T19:38:34Z | 38,409,230 | <p>If, as you say, you don't need to plot the full 12000 samples, you can down sample them. The <a href="http://www.pyqtgraph.org/documentation/graphicsItems/plotitem.html#pyqtgraph.PlotItem.setDownsampling" rel="nofollow">PlotItem.setDownSampling</a> method does exactly that. Or you can do it yourself with Numpy.</p>
... | 0 | 2016-07-16T08:16:12Z | [
"python",
"plot",
"pyqtgraph"
] |
Find and update row in Pandas DataFrame with non-unique index | 38,382,872 | <p>I have a pandas DataFrame with a non-unique index, and I need to update one of the rows. I am able to update the row if I can index it numerically, as below:</p>
<pre><code>array = np.random.randint(1, 10, (3, 3))
df = pd.DataFrame(array, index=['one', 'one', 'two'], columns=['col1', 'col2', 'col3'])
# df looks l... | 3 | 2016-07-14T19:38:45Z | 38,383,024 | <p>You can access it with <code>df.iloc[(df.index == 'one').argmax()]</code>.</p>
<p>So your assignment would look like:</p>
<pre><code>df.iloc[(df.index == 'one').argmax()] = new_data
</code></pre>
| 2 | 2016-07-14T19:47:24Z | [
"python",
"pandas"
] |
change ip address from the available addresses of the network in python | 38,383,003 | <p>Actually Iam trying to extract data from a site.But it ends with </p>
<blockquote>
<p>Maximum tries exceeded Error</p>
</blockquote>
<p>I have tried sleep() method also but didnt work.so how to find all the available addresses for my machine.</p>
<p>I found this example in <a href="https://docs.python.org/3.4/h... | 0 | 2016-07-14T19:46:09Z | 38,383,134 | <p>If it says <strong>Maximum tries exceeded</strong>, then the system is doing one of two things:</p>
<ol>
<li><p>It's using your session information to track how many times you've tried - in this case, you can just start a new <code>requests.session()</code> to fix this</p></li>
<li><p>It's using your external IP ad... | 1 | 2016-07-14T19:52:47Z | [
"python",
"python-3.x",
"ip",
"python-requests"
] |
Pandas pd.isnull() function | 38,383,037 | <p>I need to replace not null values in my dataframe with 1 and null values with 0.</p>
<p>Here is my dataframe:</p>
<pre><code>my_list= [['a','b','c'],['test1','test2',None],[None,'101','000']]
mydf= pd.DataFrame(my_list,columns=['col1','col2','col3'])
mydf
col1 col2 col3
0 a b c
1 test1 t... | 1 | 2016-07-14T19:48:11Z | 38,383,090 | <p>Just do:</p>
<pre><code>mydf = mydf.notnull() * 1
mydf
</code></pre>
<p><a href="http://i.stack.imgur.com/V5mwU.png" rel="nofollow"><img src="http://i.stack.imgur.com/V5mwU.png" alt="enter image description here"></a></p>
<p><strong>For completeness</strong></p>
<pre><code>mydf.isnull() * 1
</code></pre>
<p><a ... | 2 | 2016-07-14T19:50:33Z | [
"python",
"pandas"
] |
Pandas pd.isnull() function | 38,383,037 | <p>I need to replace not null values in my dataframe with 1 and null values with 0.</p>
<p>Here is my dataframe:</p>
<pre><code>my_list= [['a','b','c'],['test1','test2',None],[None,'101','000']]
mydf= pd.DataFrame(my_list,columns=['col1','col2','col3'])
mydf
col1 col2 col3
0 a b c
1 test1 t... | 1 | 2016-07-14T19:48:11Z | 38,383,282 | <p>This is the expected behavior for <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.where.html" rel="nofollow"><code>where</code></a>. According to the docs, <code>where</code> keeps values that are <code>True</code> and replaces values that are <code>False</code>, and <code>pd.isnull</... | 2 | 2016-07-14T20:01:05Z | [
"python",
"pandas"
] |
Updating a pandas DataFrame row with a dictionary | 38,383,127 | <p>I've found a behavior in pandas DataFrames that I don't understand.</p>
<pre><code>df = pd.DataFrame(np.random.randint(1, 10, (3, 3)), index=['one', 'one', 'two'], columns=['col1', 'col2', 'col3'])
new_data = pd.Series({'col1': 'new', 'col2': 'new', 'col3': 'new'})
df.iloc[0] = new_data
# resulting df looks like:
... | 2 | 2016-07-14T19:52:30Z | 38,383,334 | <p>It's the difference between how a dictionary iterates and how a pandas series is treated.</p>
<p>A pandas series matches it's index to columns when being assigned to a row and matches to index if being assigned to a column. After that, it assigns the value that corresponds to that matched index or column.</p>
<p>... | 2 | 2016-07-14T20:04:41Z | [
"python",
"pandas"
] |
function and method and str or return issue | 38,383,176 | <p>so i have a program that takes a description, password,and key. but when i put the password and key into the encrypt method i get errors when i try to get a return due to it being a function, so how do i get around this?</p>
<pre><code>def encrypt(plaintext, key):
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLM... | -1 | 2016-07-14T19:55:29Z | 38,383,256 | <p>You're mishandling function usage:</p>
<pre><code>encrypt(entry2, entry3)
entry2 = encrypt
</code></pre>
<p>In the first line, you call the <code>encrypt</code> function on <code>entry2</code> and <code>entry3</code> and it returns the result, which is then immediately thrown away because you haven't assigned it t... | 1 | 2016-07-14T19:59:46Z | [
"python",
"python-2.7",
"python-3.x",
"encryption"
] |
Python: How to get some images from a video in Python3? | 38,383,182 | <p>How can I extract frames from a video file using Python3?</p>
<p>For example, I want to get 16 picture from a video and combine them into a 4x4 grid.</p>
<p>I don't want 16 separate images at the end, I want one image containing 16 frames from the video.</p>
<p>----Edit----</p>
<pre><code>import av
container = ... | -1 | 2016-07-14T19:55:44Z | 38,383,459 | <p>Use PyMedia or PyAV to access image data and PIL or Pillow to manipulate it in desired form(s).</p>
<p>These libraries have plenty of examples, so with basic knowledge about the video muxing/demuxing and picture editing you should be able to do it pretty quickly. It's not so complicated as it would seem at first.</... | -1 | 2016-07-14T20:11:38Z | [
"python",
"python-3.x",
"video"
] |
Python: How to get some images from a video in Python3? | 38,383,182 | <p>How can I extract frames from a video file using Python3?</p>
<p>For example, I want to get 16 picture from a video and combine them into a 4x4 grid.</p>
<p>I don't want 16 separate images at the end, I want one image containing 16 frames from the video.</p>
<p>----Edit----</p>
<pre><code>import av
container = ... | -1 | 2016-07-14T19:55:44Z | 38,383,729 | <p>You can do that with OpenCV3, the Python wrapper and Numpy.
First you need to do is capture the frames then save them separately and finally paste them all in a bigger matrix.</p>
<pre><code>import numpy as np
import cv2
cap = cv2.VideoCapture(video_source)
# capture the 4 frames
_, frame1 = cap.read()
_, frame2 ... | 0 | 2016-07-14T20:29:33Z | [
"python",
"python-3.x",
"video"
] |
Need regex to take only the first two sentences even if other instances occur | 38,383,208 | <p>I need help with a regex that finds the first two words at the start then takes only the first two sentences after, despite how many instances occur in the text.</p>
<pre><code>text = "The Smithsonian museum is home to a variety of different art displays. According various reports art appreciation is on the rise. ... | 0 | 2016-07-14T19:56:51Z | 38,383,659 | <p>Try this:</p>
<blockquote>
<p><code>^(The Smithsonian|The Metropolitan).+?(?>\.).+?(?>\.)</code></p>
</blockquote>
| 0 | 2016-07-14T20:24:59Z | [
"python",
"regex",
"python-2.7",
"regex-lookarounds"
] |
Need regex to take only the first two sentences even if other instances occur | 38,383,208 | <p>I need help with a regex that finds the first two words at the start then takes only the first two sentences after, despite how many instances occur in the text.</p>
<pre><code>text = "The Smithsonian museum is home to a variety of different art displays. According various reports art appreciation is on the rise. ... | 0 | 2016-07-14T19:56:51Z | 38,383,752 | <p>I'm not python dev, but the problem seems that you are using <code>findall</code>, so as far as I know you can use <code>finditer</code> (and search the first iteration) or <code>search</code> to find just once match object.</p>
<p>However, if you want to use <code>findall</code>, then you can add the <code>^</code... | 0 | 2016-07-14T20:31:19Z | [
"python",
"regex",
"python-2.7",
"regex-lookarounds"
] |
Need regex to take only the first two sentences even if other instances occur | 38,383,208 | <p>I need help with a regex that finds the first two words at the start then takes only the first two sentences after, despite how many instances occur in the text.</p>
<pre><code>text = "The Smithsonian museum is home to a variety of different art displays. According various reports art appreciation is on the rise. ... | 0 | 2016-07-14T19:56:51Z | 38,383,879 | <p>With this <code>regex</code>, you don't have to hard code any beginning phrase for the sentences. It will match <strong>exactly 2</strong> occurrences of a sentence followed by the spaces before the next sentence.</p>
<pre><code>^((?:\w+(?:\s|\.))+\s+){2}
</code></pre>
<p>Here is the testing link for it: <a href="... | 0 | 2016-07-14T20:39:28Z | [
"python",
"regex",
"python-2.7",
"regex-lookarounds"
] |
Need regex to take only the first two sentences even if other instances occur | 38,383,208 | <p>I need help with a regex that finds the first two words at the start then takes only the first two sentences after, despite how many instances occur in the text.</p>
<pre><code>text = "The Smithsonian museum is home to a variety of different art displays. According various reports art appreciation is on the rise. ... | 0 | 2016-07-14T19:56:51Z | 38,390,700 | <p>If you want to exclude "The Smithsonian" etc. from the result, use <code>(?:)</code> in the second group:</p>
<pre><code>((?:The Smithsonian|The Metropolitan)[^\.]*\.[^\.]*\.)
</code></pre>
<p>Now your group 0 should only return the sentences.</p>
<pre><code>>>> x = "The Smithsonian museum is home to a v... | 0 | 2016-07-15T07:51:00Z | [
"python",
"regex",
"python-2.7",
"regex-lookarounds"
] |
How does pandas rolling_mean() work? | 38,383,222 | <p>I need to use a moving average to smooth my data, so I have written a function using convolution. But the results are a left shift compared to my raw data. So I have used the built-in <code>rolling_mean()</code> from pandas and it works just fine. The problem is I don't want to use pandas and I'm trying to rewrite t... | 0 | 2016-07-14T19:57:33Z | 38,384,505 | <p>There isn't one correct way to smooth data, and even if you're using the mean there's still a lot of variation. Shifting is a very common result from simple rolling means though.</p>
<p>The bit of code you posted from <code>pandas.rolling_mean</code> doesn't show the operation; you can see where it specifies, for ... | 1 | 2016-07-14T21:23:46Z | [
"python",
"pandas",
"moving-average"
] |
python using smaller 2D array to map with another bigger array | 38,383,269 | <p>I have a smaller array as:</p>
<pre><code>A = np.array([2013, 2014, 2015])
Aval = np.array([14, 10, 35])
</code></pre>
<p>I have another array:</p>
<pre><code>A2 = np.array([2013, 2014, 2015, 2013, 2014, 2015, 2013, 2013, 2013])
</code></pre>
<p>I want to create A2val such that:</p>
<pre><code>Arval = np.array(... | 1 | 2016-07-14T20:00:21Z | 38,383,298 | <p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html" rel="nofollow"><code>np.searchsorted</code></a> to create the mapping indices and then index into <code>Aval</code> for selecting elements off it, like so -</p>
<pre><code>Aval[np.searchsorted(A,A2)]
</code></pre>
<p>... | 2 | 2016-07-14T20:02:20Z | [
"python",
"numpy"
] |
How to pass multiple parameters to python function | 38,383,300 | <p>I have a numpy array with 300 entries. Within each entry is another numpy array [2048 x 2048].</p>
<p>Each entry is a "tiff" entry (in matrix form) which corresponds to the pixel position in a detector. Now, what I want to do is centralize this so that I have an [2048 x 2048] array with each entry having 300 entrie... | 1 | 2016-07-14T20:02:31Z | 38,383,636 | <p>In numpy we often add dimmensions to an array instead of using nested arrays (which is the norm with lists for examples). Once you have all your data in a single array, it's easy to operate on it. In your case it looks like you're looking to transpose the array. An example:</p>
<pre><code>import numpy as np
example... | 2 | 2016-07-14T20:23:57Z | [
"python",
"arrays",
"numpy"
] |
How to pass multiple parameters to python function | 38,383,300 | <p>I have a numpy array with 300 entries. Within each entry is another numpy array [2048 x 2048].</p>
<p>Each entry is a "tiff" entry (in matrix form) which corresponds to the pixel position in a detector. Now, what I want to do is centralize this so that I have an [2048 x 2048] array with each entry having 300 entrie... | 1 | 2016-07-14T20:02:31Z | 38,383,750 | <p>you can use this way</p>
<pre><code>result = map(lambda x: zip(*x) ,zip(*Tiffs))
</code></pre>
<p>and here is full example</p>
<pre><code>list1 = [[1,2,3,4],[1,2,3,4],[1,2,3,4]]
list2 = [[5,6,7,8],[5,6,7,8],[5,6,7,8]]
listoflists = [list1,list2]
result = map(lambda x: zip(*x) ,zip(*listoflists))
print result
... | 0 | 2016-07-14T20:31:15Z | [
"python",
"arrays",
"numpy"
] |
How to pass multiple parameters to python function | 38,383,300 | <p>I have a numpy array with 300 entries. Within each entry is another numpy array [2048 x 2048].</p>
<p>Each entry is a "tiff" entry (in matrix form) which corresponds to the pixel position in a detector. Now, what I want to do is centralize this so that I have an [2048 x 2048] array with each entry having 300 entrie... | 1 | 2016-07-14T20:02:31Z | 38,385,408 | <p>Would you describe this as an array of 3 items, where each is a 2x4 array?</p>
<pre><code>In [300]: Tiffs=np.arange(24).reshape(3,2,4)
In [301]: Tiffs
Out[301]:
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7]],
[[ 8, 9, 10, 11],
[12, 13, 14, 15]],
[[16, 17, 18, 19],
[20, 21, 22... | 0 | 2016-07-14T22:47:09Z | [
"python",
"arrays",
"numpy"
] |
Successful connection to MS SQL DB on Azure using pymssql, INSERT statement executing with no error message but 0 rows inserted | 38,383,457 | <p>I'm using pymssql to connect to a MS SQL DB on Azure and insert records from a CSV file. I've verified that the connection is successful, and that the list used for the executemany parameter contains all of the data in the correct format and with the correct number of values. However, when I run the script 0 rows ... | 2 | 2016-07-14T20:11:27Z | 38,386,246 | <p>Using the float placeholder (%f) was in fact the issue. Only %s and %d are supported, but are purely placeholders and do not have any impact on formatting the way that they typically do in python, so really only %s is needed. The working code is as follows:</p>
<pre><code>cursor.executemany("INSERT INTO myTable V... | 2 | 2016-07-15T00:41:38Z | [
"python",
"sql-server",
"python-2.7",
"sql-azure",
"pymssql"
] |
numpy meshgrid filter out points | 38,383,477 | <p>I have a meshgrid in numpy. I make some calculations on the points. I want to filter out points that could not be calcutaled for some reason ( division by zero).</p>
<pre><code>from numpy import arange, array
Xout = arange(-400, 400, 20)
Yout = arange(0, 400, 20)
Zout = arange(0, 400, 20)
Xout_3d, Yout_3d, Zout_3d ... | 2 | 2016-07-14T20:12:57Z | 38,383,973 | <p>To perform <code>z / ( y - x )</code> using those <code>3D</code> mesh arrays, you can create a mask of the valid ones. Now, the valid ones would be the ones where any pair of combinations between <code>y</code> and <code>x</code> aren't identical. So, this mask would be of shape <code>(M,N)</code>, where <code>M</c... | 1 | 2016-07-14T20:46:44Z | [
"python",
"numpy"
] |
Specifying a strftime format to speed up pandas' to_datetime() method | 38,383,672 | <p>Consider the following code:</p>
<pre><code>import pandas as pd
some_time='01/01/2011 12:02:41 AM'
print(pd.to_datetime(some_time))
print(pd.to_datetime(some_time, format='%m/%d/%Y %I:%M:%S %r'))
</code></pre>
<p>The first <code>to_datetime()</code> conversion works and prints the output</p>
<pre><code>2011-01-01... | 0 | 2016-07-14T20:25:42Z | 38,383,755 | <p>I think you just need <code>%p</code> instead of <code>%r</code>. The difference is <code>%r</code> expects punctuation (A.M. or P.M.), whereas <code>%p</code> does not (AM or PM).</p>
<p>Your code does not produce any errors when I make the change:</p>
<pre><code>pd.to_datetime(some_time, format='%m/%d/%Y %I:%M:%... | 2 | 2016-07-14T20:31:27Z | [
"python",
"pandas",
"strftime"
] |
Specifying a strftime format to speed up pandas' to_datetime() method | 38,383,672 | <p>Consider the following code:</p>
<pre><code>import pandas as pd
some_time='01/01/2011 12:02:41 AM'
print(pd.to_datetime(some_time))
print(pd.to_datetime(some_time, format='%m/%d/%Y %I:%M:%S %r'))
</code></pre>
<p>The first <code>to_datetime()</code> conversion works and prints the output</p>
<pre><code>2011-01-01... | 0 | 2016-07-14T20:25:42Z | 38,383,812 | <p>The correct answer was given by <a href="http://stackoverflow.com/users/3339965/root">root</a> in a comment. For the sake of completeness, the <code>%r</code> needs to be replaced by a <code>%p</code>:</p>
<pre><code>some_time='01/01/2011 12:02:41 AM'
print(pd.to_datetime(some_time))
print(pd.to_datetime(some_time,... | 0 | 2016-07-14T20:34:41Z | [
"python",
"pandas",
"strftime"
] |
python handling DictReader missing keys | 38,383,680 | <p>This script is working fine, until I hit a cell that is empty:</p>
<pre><code>import csv,time,string,os,requests
dw = "\\\\network\\folder\\btc.csv"
inv_fields = ["id", "rsl", "number", "GP%"]
with open(dw) as infile, open("c:\\upload\\log.csv", "wb") as outfile:
r = csv.DictReader(infile)
w = csv.DictWri... | 1 | 2016-07-14T20:26:05Z | 38,383,762 | <p>You can check if key <code>'GP%'</code> is the in the <code>row</code> dictionary before attempting to update its value. If it isn't you could assign a default value so the entry related to that <code>id</code> is blank in the output file:</p>
<pre><code>for i, row in enumerate(r, start=1):
row['id'] = i
if... | 1 | 2016-07-14T20:31:45Z | [
"python",
"csv"
] |
python handling DictReader missing keys | 38,383,680 | <p>This script is working fine, until I hit a cell that is empty:</p>
<pre><code>import csv,time,string,os,requests
dw = "\\\\network\\folder\\btc.csv"
inv_fields = ["id", "rsl", "number", "GP%"]
with open(dw) as infile, open("c:\\upload\\log.csv", "wb") as outfile:
r = csv.DictReader(infile)
w = csv.DictWri... | 1 | 2016-07-14T20:26:05Z | 38,383,774 | <p>you can use <code>"GP%" in row</code> to check whether <code>GP%</code> exist in row or not.</p>
<p>Alternatively, you can catch the exception:</p>
<pre><code>try:
row['GP%'] = row['GP%'].replace("%","")
except KeyError as ke:
print "Error:{0}, row info:{1}".format(ke, row)
</code></pre>
| 1 | 2016-07-14T20:32:22Z | [
"python",
"csv"
] |
Not able to extract complete city list | 38,383,699 | <p>I am using the following code to extract the list of cities mentioned on this page, but it gives me just the first 23 cities.
Can't figure out where I am going wrong!</p>
<pre><code>import requests,bs4
res=requests.get('http://www.citymayors.com/statistics/largest-cities-population-125.html')
text=bs4.BeautifulSoup... | 0 | 2016-07-14T20:27:40Z | 38,384,073 | <p><em>lxml</em> works fine for me, I get 124 cities using your own code so it has nothing to do with the parser, you are either using an old version of <em>bs4</em> or it is an encoding issue, you should call <em>.content</em> and let requests handle the encoding, you are also missing a city using your logic, to get... | 0 | 2016-07-14T20:54:26Z | [
"python",
"beautifulsoup"
] |
Tkinter: update TopLevel window when closing another TopLevel window above first? (Reference?) | 38,383,715 | <p>I'm a python beginner making a program that is supposed to save and present reservations for a campingsite (just for fun...). I've structured it in an OOP-way meaning that I define a class for each seperate window. What I need to do is to update a TopLevel window (SubWindow2) presenting database entries, when anothe... | 1 | 2016-07-14T20:28:53Z | 38,384,634 | <p>I should preface this by claiming that I am also a novice, and I would greatly appreciate the advice of others in order not to spread misinformation.</p>
<p>From what I can see, you have some misunderstandings with how inheritance vs. encapsulation works in Python. Firstly, within a Tkinter application, there shoul... | 0 | 2016-07-14T21:34:37Z | [
"python",
"python-2.7",
"tkinter"
] |
SQLAlchemy dynamic query using object attribute | 38,383,725 | <p>I'm looking to query an object's attribute dynamically. I will not know which attribute, or column in this case, that I'll be using at the time of execution.</p>
<pre><code>class Product(Base):
__tablename__ = 'products'
sku = Column(String, primary_key=True)
list_price = Column(String)
status = Co... | 0 | 2016-07-14T20:29:20Z | 38,385,037 | <p>To dynamically access attributes, you should use the <a href="https://docs.python.org/3/library/functions.html#getattr" rel="nofollow"><code>getattr</code></a> builtin.</p>
<pre><code>new_price = getattr(product, price_list.db_col_name)
</code></pre>
<p>If the instance is stale, you should use <a href="http://docs... | 1 | 2016-07-14T22:10:09Z | [
"python",
"sqlalchemy"
] |
Django passing multiple models to a template | 38,383,836 | <p>I'm developing Django app for first time. How can I pass multiple models to a template</p>
<p>views.py</p>
<pre><code>from django.views.generic import ListView, DetailView
from django.utils import timezone
from LastAlly.models import Article, Episode
class IndexView(ListView):
queryset = Article.objects.all(... | 0 | 2016-07-14T20:36:19Z | 38,383,995 | <p>You can edit the view's methods, in this case you can edit the <a href="https://docs.djangoproject.com/es/1.9/ref/class-based-views/mixins-simple/#django.views.generic.base.ContextMixin.get_context_data" rel="nofollow"><code>.get_context_data()</code></a> method:</p>
<pre><code>class IndexView(ListView):
querys... | 0 | 2016-07-14T20:48:46Z | [
"python",
"django",
"templates",
"model"
] |
drop column based on a string condition | 38,383,886 | <p>How can I delete a dataframe column based on a certain string in its name?</p>
<p>Example:</p>
<pre><code> house1 house2 chair1 chair2
index
1 foo lee sam han
2 fowler smith had sid
3 cle meg mag mog
</code></pre>
<p>I wa... | 5 | 2016-07-14T20:40:05Z | 38,383,919 | <pre><code>df.drop([col for col in df.columns if 'chair' in col],axis=1,inplace=True)
</code></pre>
| 5 | 2016-07-14T20:42:51Z | [
"python",
"string",
"pandas",
"dataframe"
] |
drop column based on a string condition | 38,383,886 | <p>How can I delete a dataframe column based on a certain string in its name?</p>
<p>Example:</p>
<pre><code> house1 house2 chair1 chair2
index
1 foo lee sam han
2 fowler smith had sid
3 cle meg mag mog
</code></pre>
<p>I wa... | 5 | 2016-07-14T20:40:05Z | 38,383,920 | <p>This should do it:</p>
<pre><code>df.drop(df.columns[df.columns.str.match(r'chair')], axis=1)
</code></pre>
<p><a href="http://i.stack.imgur.com/8US6d.png" rel="nofollow"><img src="http://i.stack.imgur.com/8US6d.png" alt="enter image description here"></a></p>
<hr>
<h3>Timing</h3>
<p><strong>MaxU method 2</stro... | 4 | 2016-07-14T20:42:53Z | [
"python",
"string",
"pandas",
"dataframe"
] |
drop column based on a string condition | 38,383,886 | <p>How can I delete a dataframe column based on a certain string in its name?</p>
<p>Example:</p>
<pre><code> house1 house2 chair1 chair2
index
1 foo lee sam han
2 fowler smith had sid
3 cle meg mag mog
</code></pre>
<p>I wa... | 5 | 2016-07-14T20:40:05Z | 38,383,971 | <p><strong>UPDATE2:</strong></p>
<pre><code>In [315]: df
Out[315]:
3M110% 3M80% 6M90% 6M95% 1N90% 2M110% 3M95%
1 foo lee sam han aaa aaa fff
2 fowler smith had sid aaa aaa fff
3 cle meg mag mog aaa aaa fff
In [316]: df.ix[:, ~df.columns.str.contains('90|110')]
Out[... | 5 | 2016-07-14T20:46:30Z | [
"python",
"string",
"pandas",
"dataframe"
] |
drop column based on a string condition | 38,383,886 | <p>How can I delete a dataframe column based on a certain string in its name?</p>
<p>Example:</p>
<pre><code> house1 house2 chair1 chair2
index
1 foo lee sam han
2 fowler smith had sid
3 cle meg mag mog
</code></pre>
<p>I wa... | 5 | 2016-07-14T20:40:05Z | 38,384,055 | <p>One more alternative:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'house1':['foo','fowler','cle'],
'house2':['lee','smith','meg'],
'chair1':['sam','had','mag'],
'chair2':['han','sid','mog']})
mask = ['chair' not in x for x in df]
df = df[df.colum... | 3 | 2016-07-14T20:53:07Z | [
"python",
"string",
"pandas",
"dataframe"
] |
Can I execute a remote python script from Mathematica? | 38,383,909 | <p>Mathematica newbie here. I'm looking to execute a remote python script from Mathematica. Is this possible? I've tried using "Run" but I get numerical outputs that don't make sense (like 65280 for the input Run[ssh IP "local path"]. Is this syntax right or is that my issue?</p>
| 1 | 2016-07-14T20:42:12Z | 38,398,677 | <pre><code>Run["ssh IP \"local path\""]
</code></pre>
<p>or, for example</p>
<pre><code>Run["ssh IP \"C:\\temp directory\\local\""]
</code></pre>
| 0 | 2016-07-15T14:29:08Z | [
"python",
"wolfram-mathematica",
"remote-server"
] |
python multiprocessing.pool.map, passing arguments to spawned processes | 38,383,981 | <pre><code>def content_generator(applications, dict):
for app in applications:
yield(app, dict[app])
with open('abc.pickle', 'r') as f:
very_large_dict = pickle.load(f)
all_applications = set(very_large_dict.keys())
pool = multiprocessing.Pool()
for result in pool.imap_unordered(func_process_applicati... | 3 | 2016-07-14T20:47:15Z | 38,384,516 | <p>The comments are becoming impossible to follow, so I'm pasting in my important comment here:</p>
<p>On a Linux-y system, new processes are created by <code>fork()</code>, so get a copy of the entire parent-process address space at the time they're created. It's "copy on write", so is more of a "virtual" copy than a... | 1 | 2016-07-14T21:24:41Z | [
"python",
"multiprocessing",
"python-multiprocessing"
] |
Creating a 'histogram' from a occurrence list | 38,384,053 | <p>Python noob here in need of some help.</p>
<p>I have a set of data that is in the format <code>[['item', count], ........]</code> and a need to create a histogram of sort that prints an asterisk for every ten occurrences counted. </p>
<p>Example:</p>
<pre><code>list=[['a', 22], ['b', 11], ['c', 45]]
</code></pre>... | -2 | 2016-07-14T20:53:05Z | 38,384,114 | <pre><code>data = [['a', 22], ['b', 11], ['c', 45]]
for item in data:
print(item[0] + ': ' + ('*' * (item[1] // 10)))
</code></pre>
<p>You can print a string multiple times with the <code>*</code> operator. So <code>'*' * 5</code> produces <code>*****</code>. I would use a dictionary instead of a list though:</p>
... | 0 | 2016-07-14T20:58:30Z | [
"python",
"histogram"
] |
Is there a better way to write the len of string to var while compairing to string lengths in python3 | 38,384,137 | <p>I am trying to get my head around single line evaluations and this is what I came up with. I am sure there is a better more pythonic what to write this line.</p>
<pre><code>s1 = 'abcdef'
s2 = 'abcdefghi'
ln = len(s1) if len(s2) > len(s1) else len(s2)
print(ln) # prints 6
</code></pre>
<p>edit: updated code
T... | 0 | 2016-07-14T20:59:28Z | 38,384,216 | <p>Just store the results of <code>len</code> in variables:</p>
<pre><code>s1 = 'abcdef'
s2 = 'abcdefghi'
l1 = len(s1)
l2 = len(s2)
ln = l1 if l2 > l1 else l2
</code></pre>
<p>If you need to do this for more strings, you can use <code>min</code>. Doing this for just 2 strings is overkill though, and I don't recom... | 0 | 2016-07-14T21:03:56Z | [
"python",
"string"
] |
Selenium Web-driver automation not working properly | 38,384,138 | <p>So I found this script online, which is meant to brute-force web-forms online etc. using Selenium, and I thought it would be a good idea to take it, modify it a bit and experiment with it. This time, I tried creating a bot that:</p>
<ol>
<li>Signs up to Twitter</li>
<li>Goes to twitter.com</li>
<li>Posts something.... | 0 | 2016-07-14T20:59:32Z | 38,479,481 | <p>See the link below. That could be the problem.</p>
<p><a href="https://github.com/SeleniumHQ/selenium/issues/2257" rel="nofollow">https://github.com/SeleniumHQ/selenium/issues/2257</a></p>
| 0 | 2016-07-20T11:03:15Z | [
"python",
"selenium"
] |
Pandas, DataFrame: Spiting one column into multiple columns | 38,384,145 | <p>I have the following data frame. I am wondering whether it is possible to break the "data" column into multiple columns, please see below:</p>
<pre>
ID Date data
6 21/05/2016 A: 7, B: 8, C: 5, D: 5, A: 8
6 21/01/2014 B: 5, C: 5, D: 7
6 02/04/2013 A: 4, D:7
7 05/06/2014 C: 25
... | 2 | 2016-07-14T20:59:41Z | 38,384,172 | <pre><code>df = pd.DataFrame([
[6, "a: 1, b: 2"],
[6, "a: 1, b: 2"],
[6, "a: 1, b: 2"],
[6, "a: 1, b: 2"],
], columns=['ID', 'dictionary'])
def str2dict(s):
split = s.strip().split(',')
d = {}
for pair in split:
k, v = [_.strip() for _ in pair.split(':')]
... | 2 | 2016-07-14T21:01:09Z | [
"python",
"pandas"
] |
Pandas, DataFrame: Spiting one column into multiple columns | 38,384,145 | <p>I have the following data frame. I am wondering whether it is possible to break the "data" column into multiple columns, please see below:</p>
<pre>
ID Date data
6 21/05/2016 A: 7, B: 8, C: 5, D: 5, A: 8
6 21/01/2014 B: 5, C: 5, D: 7
6 02/04/2013 A: 4, D:7
7 05/06/2014 C: 25
... | 2 | 2016-07-14T20:59:41Z | 38,384,553 | <p>Here is a function that can convert the string to a dictionary and aggregate values based on the key; After the conversion it will be easy to get the results with the <code>pd.Series</code> method:</p>
<pre><code>def str_to_dict(str1):
import re
from collections import defaultdict
d = defaultdict(int)
... | 3 | 2016-07-14T21:28:07Z | [
"python",
"pandas"
] |
Why some python build in functions only have pass? | 38,384,206 | <p>I wanted to see how a <code>math.py</code> function was implemented, but when I opened the file I found that all the functions are empty and there is a simple <code>pass</code>. For example :</p>
<pre><code>def ceil(x): # real signature unknown; restored from __doc__
"""
ceil(x)
Return the ceiling of x... | 5 | 2016-07-14T21:03:08Z | 38,384,411 | <p>PyCharm is lying to you. The source code you're looking at is a fake that PyCharm has created. PyCharm knows what functions should be there, and it can guess at their signatures using the function docstrings, but it has no idea what the function bodies should look like.</p>
<p>If you want to see the real source cod... | 4 | 2016-07-14T21:16:11Z | [
"python",
"standard-library",
"c-standard-library"
] |
How do I subset this hacked together pandas dataframe? | 38,384,222 | <p>How do I subset rows 11 - 13?</p>
<p>I have a pandas dataframe with some hacked together data and I'm having the hardest time subsetting rows 11, 12, and 13. Essentially, I want to separate rows that start with "<strong>dunntest</strong>" and have <strong>TRUE</strong> in column 5 then put them into a new dataframe... | 1 | 2016-07-14T21:04:21Z | 38,384,272 | <p>You can try <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p>
<pre><code>print (df[(df["Group"] == "dunntest") & (df["CL3"] == 'TRUE' )])
Group CL CL1 CL2 CL3
11 dunntest none CL - CL3... | 4 | 2016-07-14T21:07:08Z | [
"python",
"pandas",
"dataframe"
] |
How do I subset this hacked together pandas dataframe? | 38,384,222 | <p>How do I subset rows 11 - 13?</p>
<p>I have a pandas dataframe with some hacked together data and I'm having the hardest time subsetting rows 11, 12, and 13. Essentially, I want to separate rows that start with "<strong>dunntest</strong>" and have <strong>TRUE</strong> in column 5 then put them into a new dataframe... | 1 | 2016-07-14T21:04:21Z | 38,385,696 | <p>The straight forward approach will be:</p>
<pre><code>df = df[(df["Group"] == "dunntest") & (df.iloc[4] == 'TRUE' )]
</code></pre>
| 0 | 2016-07-14T23:21:03Z | [
"python",
"pandas",
"dataframe"
] |
unpack return function arguments with *args | 38,384,293 | <p>Looking for some guidance on how I can properly unpack return arguments in other functions using *args? This is the code;</p>
<pre><code> #!/usr/bin/python
def func1():
test1 = 'hello'
test2 = 'hey'
return test1, test2
def func2(*args):
print args[0]
print args[1]
func2(func1)
</code></pr... | 1 | 2016-07-14T21:08:27Z | 38,384,334 | <p>func2 takes multiple arguments and you specified only one in your code<br>
You can easily see if by printing all the <code>args</code>. You can also see, that it fails to print <code>args[1]</code> not <code>args[0]</code>, because you have passed one argument to that function.</p>
| -1 | 2016-07-14T21:11:17Z | [
"python",
"function",
"args"
] |
unpack return function arguments with *args | 38,384,293 | <p>Looking for some guidance on how I can properly unpack return arguments in other functions using *args? This is the code;</p>
<pre><code> #!/usr/bin/python
def func1():
test1 = 'hello'
test2 = 'hey'
return test1, test2
def func2(*args):
print args[0]
print args[1]
func2(func1)
</code></pr... | 1 | 2016-07-14T21:08:27Z | 38,384,337 | <p>You didn't call <code>func</code>, so your <code>func2</code> is actually getting a single argument, which is a function object. Change your code to: <code>func2(*func1())</code></p>
<pre><code># While you're at it, also unpack the results so hello and hey are interpreted as 2 separate string arguments, and not a s... | 3 | 2016-07-14T21:11:29Z | [
"python",
"function",
"args"
] |
How to split dense Vector into columns - using pyspark | 38,384,347 | <p><strong>Context:</strong> I have a dataframe with 2 columns: word and vector. Where the column type of "vector" is VectorUDT.</p>
<p>An Example:</p>
<pre><code>word | vector
assert | [435,323,324,212...]
</code></pre>
<p>And I want to get this:</p>
<pre><code>word | v1 | v2 | v3 | v4 | v5 | v6 ......
... | 4 | 2016-07-14T21:12:03Z | 38,385,033 | <p>One possible approach is to convert to and from RDD:</p>
<pre><code>from pyspark.mllib.linalg import Vectors
df = sc.parallelize([
("assert", Vectors.dense([1, 2, 3]))
]).toDF(["word", "vector"])
def extract(row):
return (row.word, ) + tuple(float(x) for x in row.vector.values)
df.rdd.map(extract).toDF([... | 1 | 2016-07-14T22:09:23Z | [
"python",
"vector",
"apache-spark",
"pyspark",
"spark-dataframe"
] |
How to use locks without causing deadlock in concurrent.futures.ThreadPoolExecutor? | 38,384,359 | <p>I'm processing Jira changelog history data, and due to the large amount of data, and the fact that most of the processing time is I/O based, I figured that an asynchronous approach might work well. </p>
<p>I have a list of all <code>issue_id</code>'s, which I'm feeding into a function that makes a request through ... | 1 | 2016-07-14T21:12:48Z | 39,439,157 | <p>You need to store the result of <code>exec</code> into a list, conventionally named <code>futs</code>, and then loop through that list calling <code>result()</code> to get their result, handling any errors that might have happened.</p>
<p>(I'd also chance <code>exec</code> to <code>executor</code> as that's more co... | 0 | 2016-09-11T18:10:48Z | [
"python",
"multithreading",
"concurrent.futures"
] |
How to properly join a process when KeyboardInterrupt received? | 38,384,373 | <p>I have a server which I want to run in a separate process and handle <code>KeyBoardInterrupt</code> exception for stopping it:</p>
<pre><code>import multiprocessing as mp
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
def server_spawner():
server = HTTPServer(('', 12345), BaseHTTPRequestHandler)
... | 2 | 2016-07-14T21:13:42Z | 38,416,141 | <p>From <a href="http://jessenoller.com/blog/2009/01/08/multiprocessingpool-and-keyboardinterrupt" rel="nofollow">Jesse Noller</a>'s blog.</p>
<pre><code>import multiprocessing as mp
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
def server_spawner():
server = HTTPServer(('', 12345), BaseHTTPReques... | 0 | 2016-07-16T22:14:19Z | [
"python",
"multiprocessing"
] |
Why can't Flask can't see my environment variables from Apache (mod_wsgi)? | 38,384,454 | <p>I want to pass in environment variables through Apache + mod_wsgi to tell my app whether it's running in a development or production environment. (This needs to happen when the app is launched, before any requests have come in.) For example:</p>
<pre><code><VirtualHost *:80>
...
SetEnv ENVTYPE produ... | 0 | 2016-07-14T21:19:24Z | 38,386,242 | <p>I solved problem #1 thanks to <a href="http://ericplumb.com/blog/passing-apache-environment-variables-to-django-via-mod_wsgi.html" rel="nofollow">this tip</a></p>
<blockquote>
<p>Note that the Flask app is imported inside the def application block â if you import it outside of this block, you won't be able to u... | 0 | 2016-07-15T00:41:13Z | [
"python",
"apache",
"flask",
"environment-variables",
"mod-wsgi"
] |
TensorFlow - nn.max_pooling increases memory usage enormously | 38,384,531 | <p>I try to create a simple convolution neural network in TensorFlow. Everything seems fine when I run my code below. I run it in Spyder IDE and monitor memory usage - it grows to 64-65% on my laptop and not goes any further.</p>
<pre><code>batch_size = 16
patch_size = 5
depth = 16
num_hidden = 64
graph = tf.Graph()
... | 0 | 2016-07-14T21:26:14Z | 38,385,434 | <p>Assume you are using one 3x3 filter on single channel 6x6 input.</p>
<p>When you are doing strided convolution of strides 2 you produce a result that is 3x3.</p>
<blockquote>
<p>So effectively you use input 36 units + filter 9 units + output 9 units of memory.</p>
</blockquote>
<p>Now when you are trying to app... | 1 | 2016-07-14T22:49:49Z | [
"python",
"memory",
"machine-learning",
"tensorflow",
"deep-learning"
] |
Use Python to run a .exe file in Windows Command Prompt | 38,384,543 | <p>I am trying to integrate an existing program into a developing Python 2.7 script. Currently the program can be successfully run by typing the following in the command prompt:</p>
<pre><code> `C:\wisdem\plugins\JacketSE\src\jacketse\SubDyn\bin\SubDyn_Win32.exe C:\wisdem\plugins\JacketSE\src\jacketse\SubDyn\CertT... | 0 | 2016-07-14T21:26:55Z | 38,384,622 | <pre><code>import os
print os.popen(r'''echo "hello"''').read()
</code></pre>
<p>I would suggest putting the full command within the triple quotes, and attempting. This will execute the command, and then print the output.</p>
<p>Using a String literal with prefix <code>r</code> should help with any weird escape chara... | 0 | 2016-07-14T21:33:21Z | [
"python",
"windows",
"python-2.7",
"command-prompt",
"openmdao"
] |
Spark Documentation : simple example to add list elements | 38,384,546 | <p>I'm learning Spark and came across <a href="http://spark.apache.org/docs/latest/programming-guide.html#parallelized-collections" rel="nofollow">this</a> section of the documentation dealing with parallelized collections. I replicate the following in python from the documentation to perform a Reduce step:</p>
<pre>... | 0 | 2016-07-14T21:27:22Z | 38,385,249 | <p>This is purely a question on how <a href="https://docs.python.org/2/library/functions.html#reduce" rel="nofollow"><code>reduce</code></a> works.</p>
<p>The left argument of the lambda function (<code>a</code> in this case) represents the aggregated values of applying the lambda function <code>a + b</code>. The val... | 1 | 2016-07-14T22:30:45Z | [
"python",
"apache-spark",
"lambda",
"mapreduce"
] |
Trace the id's that constructed a zip | 38,384,617 | <p>Once a zip element has been constructed, say for example from two lists, </p>
<pre><code>z = zip(l1, l2)
</code></pre>
<p>Is there a method to get from <code>z</code> the id's of the constructing <code>l1</code> and <code>l2</code> lists, or is <code>z</code> completely ignorant of its origin?</p>
<p>I did not fi... | 1 | 2016-07-14T21:32:44Z | 38,384,929 | <p><code>zip</code> does not provide the functionality that you seek. </p>
<p>You could instead create a <em>wrapper class</em> that provides this functionality:</p>
<pre><code>class Zip:
def __init__(self, func=zip):
self.ids = None
self.func = func
def __call__(self, *args):
self.i... | 0 | 2016-07-14T21:59:14Z | [
"python",
"python-3.x"
] |
Trace the id's that constructed a zip | 38,384,617 | <p>Once a zip element has been constructed, say for example from two lists, </p>
<pre><code>z = zip(l1, l2)
</code></pre>
<p>Is there a method to get from <code>z</code> the id's of the constructing <code>l1</code> and <code>l2</code> lists, or is <code>z</code> completely ignorant of its origin?</p>
<p>I did not fi... | 1 | 2016-07-14T21:32:44Z | 38,385,073 | <p>It's theoretically possible in limited cases. You might want to do something like this in interactive mode or a <code>pdb</code> debugging session if it's the only way to get at an object you forgot to keep a reference to, but it's not something you should ever use in a program.</p>
<p>Let's take a look at what ref... | 3 | 2016-07-14T22:13:56Z | [
"python",
"python-3.x"
] |
python setup.py build ignoring some files | 38,384,677 | <p>I have the following structure for my Python package:</p>
<pre><code>$ tree -d | grep -v "__pycache__"
.
âââ src
â  âââ poliastro
â  â  âââ iod
â  â  âââ tests
â  â  âââ twobody
â  â  âââ tests
âââ setup.py
âââ MANIFEST... | 5 | 2016-07-14T21:37:59Z | 38,394,715 | <p>Try putting <code>__init__.py</code> files inside the included folders specified in <code>MANIFEST.in</code>.</p>
| 0 | 2016-07-15T11:12:30Z | [
"python",
"setuptools",
"packaging"
] |
python setup.py build ignoring some files | 38,384,677 | <p>I have the following structure for my Python package:</p>
<pre><code>$ tree -d | grep -v "__pycache__"
.
âââ src
â  âââ poliastro
â  â  âââ iod
â  â  âââ tests
â  â  âââ twobody
â  â  âââ tests
âââ setup.py
âââ MANIFEST... | 5 | 2016-07-14T21:37:59Z | 39,189,413 | <p>Your <code>setup()</code> is missing <code>include_package_data=True</code>. See this PR I have made <a href="https://github.com/poliastro/poliastro/pull/139" rel="nofollow">https://github.com/poliastro/poliastro/pull/139</a></p>
<p>Discussion: Without this, non-python package files (such as the test py files you l... | 2 | 2016-08-28T08:36:10Z | [
"python",
"setuptools",
"packaging"
] |
Pillow installed, but attributes not present | 38,384,700 | <p>So I have installed pillow using the installer "Pillow-3.3.0.win32-py2.7.exe", but for some reason after I import it none of it's attributes are available. If I run the following code</p>
<pre><code>import PIL
print(dir(PIL))
</code></pre>
<p>it will return</p>
<pre><code>['PILLOW_VERSION', 'VERSION', '__builtins... | 0 | 2016-07-14T21:40:02Z | 38,384,833 | <p>The answer is <a href="http://stackoverflow.com/questions/11911480/python-pil-has-no-attribute-image">here</a>, </p>
<blockquote>
<p>PIL's <strong>init</strong>.py is just an empty stub as is common. It won't
magically import anything by itself.</p>
<p>When you do from PIL import Image it looks in the PIL ... | 1 | 2016-07-14T21:50:27Z | [
"python",
"pillow"
] |
Pillow installed, but attributes not present | 38,384,700 | <p>So I have installed pillow using the installer "Pillow-3.3.0.win32-py2.7.exe", but for some reason after I import it none of it's attributes are available. If I run the following code</p>
<pre><code>import PIL
print(dir(PIL))
</code></pre>
<p>it will return</p>
<pre><code>['PILLOW_VERSION', 'VERSION', '__builtins... | 0 | 2016-07-14T21:40:02Z | 38,384,850 | <p>Pillow doesn't support <code>import PIL</code>. Use <code>from PIL import Image</code>.</p>
| 1 | 2016-07-14T21:51:38Z | [
"python",
"pillow"
] |
Python -- turning string inputs into a function | 38,384,702 | <p>I am wanting to ask the user for a formula then execute that formula inside a function. This is what I have so far. I have seen how to evaluate a string such as "2**4" to give 16 but I want to be able to input 5*x, so formula is "y=5*x" and let func(4) return 20.</p>
<pre><code>formula = raw_input("y= ")
formula = ... | -2 | 2016-07-14T21:40:08Z | 38,384,966 | <p>You're pretty close with <code>eval</code> (assuming you don't care about malicious input):</p>
<pre><code>def f(x):
formula = raw_input("y=")
return eval('%s' % formula)
print f(3)
</code></pre>
<p>Running that and entering <code>2*x</code> into the input box results in <code>6</code></p>
| 0 | 2016-07-14T22:02:14Z | [
"python",
"string",
"function"
] |
Function patch not being picked up by imported module | 38,384,709 | <p>I feel like this should be an easy mock, but I have not gotten it to work yet. </p>
<p>I am working off of the following directory structure:</p>
<pre><code>module
âââ utilities.py
âââ order.py
âââ test
â âââ test_order.py
</code></pre>
<p>The relevant code is as follows:</p>
<h1>-- u... | 0 | 2016-07-14T21:41:02Z | 38,397,716 | <p>It does not look like creating the patch outside of the class was getting picked up. It started working when I pulled the patch in as a decorator for the specific test.</p>
<pre><code>class TestOrder(unittest.TestCase):
@patch('utilities.order.get_file_path')
def test_load_order_by_number(self, file_mock):... | 0 | 2016-07-15T13:46:30Z | [
"python",
"unit-testing",
"python-3.x",
"mocking"
] |
Python gives syntax error but there is no mistake? | 38,384,778 | <p>Can someone say why python doesn't allow this?</p>
<pre><code># -*- coding: utf-8 -*
import win32api,win32con,os,time,sys
x_pad =464
y_pad =235
def tik():
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
time.sleep(.1)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
print "Click.".deco... | -1 | 2016-07-14T21:47:00Z | 38,384,808 | <p>You sure there's no syntax error?</p>
<pre><code>win32api.SetCursorPos((x_pad + cord[0], y_pad + cord[1])
12 2 1???
</code></pre>
<p>The line that a syntax error is reported on is not necessary where the syntax error is. It's merely the first place where an earl... | 2 | 2016-07-14T21:47:58Z | [
"python",
"syntax",
"syntax-error",
"user-defined-functions"
] |
Python gives syntax error but there is no mistake? | 38,384,778 | <p>Can someone say why python doesn't allow this?</p>
<pre><code># -*- coding: utf-8 -*
import win32api,win32con,os,time,sys
x_pad =464
y_pad =235
def tik():
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
time.sleep(.1)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
print "Click.".deco... | -1 | 2016-07-14T21:47:00Z | 38,384,818 | <p>Look at the code immediately above the reported error:</p>
<pre><code>def mousePos(cord):
win32api.SetCursorPos((x_pad + cord[0], y_pad + cord[1])
</code></pre>
<p>You're missing a closing parentheses.</p>
| 2 | 2016-07-14T21:49:08Z | [
"python",
"syntax",
"syntax-error",
"user-defined-functions"
] |
Reading an excel data set saved as CSV file in pandas | 38,384,953 | <p>There is a very similar question to the one I am about to ask posted here: </p>
<p><a href="http://stackoverflow.com/questions/17063458/reading-an-excel-file-in-python-using-pandas">Reading an Excel file in python using pandas</a></p>
<p>Except when I attempt to use the solutions posted here I am countered with</p... | 0 | 2016-07-14T22:01:13Z | 38,385,308 | <p>Your error message means exactly what it says: <code>AttributeError: 'DataFrame' object has no attribute 'read'</code></p>
<p>When you use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow">pandas.read_csv</a> you're actually reading the <code>csv</code> file into a... | 0 | 2016-07-14T22:36:16Z | [
"python",
"excel",
"csv",
"pandas"
] |
Practice Makes Perfect median | 38,385,017 | <p>Hey :) I'm newbie to python and I'm wondering how to delete square brackets from my return output. I get an error Oops, try again. median([1]) returned <strong>[1]</strong> instead of 1. How to delete these square brackets? Is the rest of code OK or does it need changes?
This is my code:</p>
<pre><code>def median(L... | 1 | 2016-07-14T22:08:12Z | 38,385,043 | <p>Delete this line:</p>
<pre><code>return newlist
</code></pre>
<p>That's returning a copy of the list and then not executing the rest of your function.</p>
<p><strong>EDIT</strong></p>
<p>A big issue with your current code is that you're choosing the wrong indices when the array is an even length. (For a length-4... | 0 | 2016-07-14T22:10:30Z | [
"python",
"python-2.7"
] |
iPython debugger not providing any insight | 38,385,020 | <p>Let's say I have the following function:</p>
<pre><code>def simple_func():
a = 4
b = 5
c = a * b
print c
</code></pre>
<p>Here's what I get when I run <code>%debug simple_func()</code>:</p>
<pre><code>NOTE: Enter 'c' at the ipdb> prompt to continue execution.
None
> <string>(1)<mod... | 0 | 2016-07-14T22:08:31Z | 38,387,072 | <p>It doesn't look like <code>debug</code> works with a function that's simply defined in the <code>ipython</code> session. It needs to be imported from a file (that is, the <code>--breakpoint</code> parameter takes a file name and line).</p>
<p>If I create a file <code>test.py</code></p>
<pre><code>In [9]: cat test... | 2 | 2016-07-15T02:40:24Z | [
"python",
"debugging",
"ipython",
"pdb",
"ipdb"
] |
smtpauthenticationerror 534 django python registration | 38,385,026 | <p>I know that this question was asked a lot o times, but I have a little different situation. I am deploying my django app with implemented django-registration-redux on heroku. The registration works fine on local machine, but it gives smtpauthenticationerror 534 on heroku. </p>
<p>I ALLOWED less secure apps on my go... | 0 | 2016-07-14T22:08:50Z | 38,385,755 | <p>It seems like google banned the usage of it's accounts for automatic email-sending. The best choice in this case is just to use another service or create an email service <a href="https://docs.djangoproject.com/en/1.9/topics/email/" rel="nofollow">by yourself</a></p>
| 0 | 2016-07-14T23:28:39Z | [
"python",
"django",
"email",
"heroku",
"django-registration"
] |
Cron not working on Amazon Elastic Beanstalk with Python and PostgreSQL | 38,385,031 | <p>I have built a simple Django app and successfully deployed it to Beanstalk. The app uses a PostgreSQL backend on an RDS instance. From a browser, I can successfully access the admin and create and delete models inside of it. However, I'm also trying to run a cron that updates the database. I installed the cron on th... | 0 | 2016-07-14T22:09:13Z | 38,385,211 | <p>This is the way you run a python script.</p>
<p>It is a question on cron.
First is add a SHEBANG line on top of your python script.</p>
<pre><code>#!/usr/bin/env python3
</code></pre>
<p>Make your script executable with <code>chmod +x</code></p>
<p>And do a crontab -e and add <code>0 0 */2 * * /path/to/your/pyth... | 0 | 2016-07-14T22:26:31Z | [
"python",
"django",
"postgresql",
"amazon-web-services",
"beanstalk"
] |
Cron not working on Amazon Elastic Beanstalk with Python and PostgreSQL | 38,385,031 | <p>I have built a simple Django app and successfully deployed it to Beanstalk. The app uses a PostgreSQL backend on an RDS instance. From a browser, I can successfully access the admin and create and delete models inside of it. However, I'm also trying to run a cron that updates the database. I installed the cron on th... | 0 | 2016-07-14T22:09:13Z | 38,385,430 | <p>I'm dumb. I forgot to actually set the environment variables in the AWS console. What can I say, it has been a long day.</p>
| 0 | 2016-07-14T22:49:19Z | [
"python",
"django",
"postgresql",
"amazon-web-services",
"beanstalk"
] |
Get stream URL in Kodi | 38,385,034 | <p>I'm trying to figure out how to get the playing item URL (live TV).
I tried overriding Player but couldn't get the play method to be called and looked at jsonRPC calls, but couldn't find anything resembling what I want.
Is there a way to do it?</p>
<p>On another issue, I want to use ffmpeg and I noticed that Kodi a... | 0 | 2016-07-14T22:09:27Z | 38,436,735 | <p>You can try <code>Player.Filename</code> infolabel like this:</p>
<pre><code>filename = xbmc.getInfoLabel('Player.Filename')
</code></pre>
<p>Or you can use <code>Player.GetItem</code> JSON-RPC method.</p>
<p><strong>UPD</strong>: This is a snippet from one of my addons:</p>
<pre><code>def get_now_played():
"""
... | 0 | 2016-07-18T12:28:41Z | [
"python",
"live-streaming",
"kodi"
] |
how to convert repr into encoded string | 38,385,089 | <p>I have this <code>str</code> (coming from a file I can't fix):</p>
<pre><code>In [131]: s
Out[131]: '\\xce\\xb8Oph'
</code></pre>
<p>This is close to the repr of a string encoded in utf8:</p>
<pre><code>In [132]: repr('θOph'.encode('utf8'))
Out[132]: "b'\\xce\\xb8Oph'"
</code></pre>
<p>I need the original encod... | 2 | 2016-07-14T22:15:44Z | 38,385,618 | <p>Unfortunately, this is really problematic. It's \ killing you softly here.</p>
<p>I can only think of:</p>
<pre><code>s = '\\xce\\xb8Oph\\r\\nMore test\\t\\xc5\\xa1'
n = ""
x = 0
while x!=len(s):
if s[x]=="\\":
sx = s[x+1:x+4]
marker = sx[0:1]
if marker=="x": n += chr(int(sx[1:], 16))... | 2 | 2016-07-14T23:11:42Z | [
"python",
"python-3.x"
] |
how to convert repr into encoded string | 38,385,089 | <p>I have this <code>str</code> (coming from a file I can't fix):</p>
<pre><code>In [131]: s
Out[131]: '\\xce\\xb8Oph'
</code></pre>
<p>This is close to the repr of a string encoded in utf8:</p>
<pre><code>In [132]: repr('θOph'.encode('utf8'))
Out[132]: "b'\\xce\\xb8Oph'"
</code></pre>
<p>I need the original encod... | 2 | 2016-07-14T22:15:44Z | 38,401,636 | <p>Your solution is OK, the only thing is that <code>eval</code> is dangerous when used in arbitrary inputs. Instead, use <code>ast.literal_eval</code>, it is safe:</p>
<pre><code>>>> s = '\\xce\\xb8Oph'
>>> from ast import literal_eval
>>> literal_eval("b'{}'".format(s)).decode('utf8')
'\u0... | 3 | 2016-07-15T17:05:58Z | [
"python",
"python-3.x"
] |
how to convert repr into encoded string | 38,385,089 | <p>I have this <code>str</code> (coming from a file I can't fix):</p>
<pre><code>In [131]: s
Out[131]: '\\xce\\xb8Oph'
</code></pre>
<p>This is close to the repr of a string encoded in utf8:</p>
<pre><code>In [132]: repr('θOph'.encode('utf8'))
Out[132]: "b'\\xce\\xb8Oph'"
</code></pre>
<p>I need the original encod... | 2 | 2016-07-14T22:15:44Z | 38,402,041 | <p>Just open your file with <code>unicode_escape</code> encoding, like:</p>
<pre><code>with open('name', encoding="unicode_escape") as f:
pass # your code here
</code></pre>
<h2>Original answer:</h2>
<pre><code>>>> '\\xce\\xb8Oph'.encode('utf-8').decode('unicode_escape')
'øOph'
</code></pre>
<p>You ... | 3 | 2016-07-15T17:30:38Z | [
"python",
"python-3.x"
] |
how to convert repr into encoded string | 38,385,089 | <p>I have this <code>str</code> (coming from a file I can't fix):</p>
<pre><code>In [131]: s
Out[131]: '\\xce\\xb8Oph'
</code></pre>
<p>This is close to the repr of a string encoded in utf8:</p>
<pre><code>In [132]: repr('θOph'.encode('utf8'))
Out[132]: "b'\\xce\\xb8Oph'"
</code></pre>
<p>I need the original encod... | 2 | 2016-07-14T22:15:44Z | 38,439,425 | <p>To make a <em>teeny</em> improvement on GingerPlusPlus's answer:</p>
<pre><code>import tempfile
with tempfile.TemporaryFile(mode='rb+') as f:
f.write(r'\xce\xb8Oph'.encode())
f.flush() ... | 0 | 2016-07-18T14:34:44Z | [
"python",
"python-3.x"
] |
Adding simple error bars to Seaborn factorplot | 38,385,099 | <p>I have a <code>factorplot</code> that I have generated from a summary table, rather than raw data:</p>
<p><img src="http://dsh.re/db165" alt=""></p>
<p>Using the following code:</p>
<pre><code>sns.factorplot(col="followup", y="probability", hue="next intervention", x="age",
data=table_flat[table_f... | 0 | 2016-07-14T22:16:20Z | 38,406,233 | <p>You can pass <code>plt.errorbar</code> to <code>FacetGrid.map</code> but it requires a small wrapper function to reformat the arguments properly (and explicitly passing the category order):</p>
<pre><code>import numpy as np
from scipy import stats
import seaborn as sns
import matplotlib.pyplot as plt
# Reformat th... | 0 | 2016-07-15T23:22:40Z | [
"python",
"plot",
"seaborn"
] |
Django authorization when calling other view | 38,385,156 | <p>I have a django system for building formsheets on refrigeration systems.</p>
<p>I have a model called System.</p>
<p>I have plenty of models which represent a form paper and many have :</p>
<ol>
<li>a Foreign key to System called anlage</li>
<li>a Method called get_pdf_url which returns an url to the pdf generato... | 0 | 2016-07-14T22:21:13Z | 38,445,710 | <p>Like I said in the comments, you are making an external call to your own website, you should call the pdf view directly pass along the request object to retain the session as below, but it seems it bit difficult to modify the request object to construct your different PDFs</p>
<pre><code>def pdf_view(request):
.... | 0 | 2016-07-18T20:45:45Z | [
"python",
"django",
"session",
"url",
"request"
] |
Django authorization when calling other view | 38,385,156 | <p>I have a django system for building formsheets on refrigeration systems.</p>
<p>I have a model called System.</p>
<p>I have plenty of models which represent a form paper and many have :</p>
<ol>
<li>a Foreign key to System called anlage</li>
<li>a Method called get_pdf_url which returns an url to the pdf generato... | 0 | 2016-07-14T22:21:13Z | 38,469,905 | <p>Use the session from the connected client and a simple javascript function to collect the files.</p>
<p>In the template of the django view I create a script that collects all pdf files from the page and builds a zip file from it.</p>
<pre><code><input id="zipme" type="button" value="Create Zip File (takes some ... | 0 | 2016-07-19T23:03:47Z | [
"python",
"django",
"session",
"url",
"request"
] |
Muti-table inheritance and reverse relation django | 38,385,159 | <p>I've been reading and practicing django 1.9 documentation about multi-table inheritance and reverse relation, this is my code:</p>
<pre><code>@python_2_unicode_compatible
class Place(models.Model):
name=models.CharField('Restaurant Name',max_length=50,db_column='name of restaurant')
address=models.CharField... | 1 | 2016-07-14T22:21:40Z | 38,387,749 | <p>After i try and modify my code finally i can make the Consumer Objects, this is the code that i have been modified (i add an id attribute in Place class since error happends in Autofield class ini <code>__init__.py</code> line 976)</p>
<pre><code>@python_2_unicode_compatible
class Place(models.Model):
name=mode... | 1 | 2016-07-15T04:12:26Z | [
"python",
"django",
"django-models",
"django-inheritance"
] |
calculating slope for a series trendline in Pandas | 38,385,162 | <p>Is there an idiomatic way of getting the slope for linear trend line fitting values in a <code>DataFrame</code> column? The data is indexed with <code>DateTime</code> index.</p>
| 1 | 2016-07-14T22:21:45Z | 38,385,293 | <p>This should do it:</p>
<pre><code>import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.rand(100, 5), pd.date_range('2012-01-01', periods=100))
def trend(df):
df = df.copy().sort_index()
dates = df.index.to_julian_date().values[:, None]
x = np.concatenate([np.ones_like(dates), dates], axi... | 1 | 2016-07-14T22:34:46Z | [
"python",
"numpy",
"pandas"
] |
Python Facebook Ads API call not going through | 38,385,187 | <p>I am trying to extract data from ads I am running from my facebook page into a csv and push it into a sql db.I am new to web development, and I am unsure whether I have to make a separate fb app and use the ads sdk in order to do this, or if i can just write a script,or if I am going in the right direction at all. T... | 1 | 2016-07-14T22:24:21Z | 38,389,787 | <pre><code>#!/usr/bin/env/python
import urllib2
import json
from facebookads.adobjects.campaign import Campaign
from facebookads.adobjects.adsinsights import AdsInsights
from facebookads.adobjects.adreportrun import AdReportRun
from facebookads.api import FacebookAdsApi
from facebookads import objects
import time
# i... | 1 | 2016-07-15T07:01:57Z | [
"python",
"facebook",
"facebook-graph-api",
"facebook-marketing-api"
] |
Error installing python packages that require .so files after upgrading to macports python 3.5 | 38,385,191 | <p>I've seen similar questions, but none that have given answers to my problem. I recently upgraded to python v3.5 using Macports on Mac OS X. Installing python packages works fine if there is a valid Macport:</p>
<pre><code>sudo port install py35-numpy
</code></pre>
<p>However, if I try to install python packages th... | 1 | 2016-07-14T22:24:48Z | 38,386,621 | <p>Are you sure <code>pip3</code> belongs to a version of <code>pip</code> installed by MacPorts, preferably <code>pip-3.5</code>? My guess is that you are using a <code>pip</code> from a different Python installation, which will therefore link C extensions to the wrong Python library, and force installation into the p... | 2 | 2016-07-15T01:36:08Z | [
"python",
"osx",
"macports",
"python-3.5"
] |
Grouping similar URLs / Finding Common URL patterns (Python) | 38,385,251 | <p>I have around 100k URLs each of which have been marked as positive or negative. I want to see what type of URLs corresponds to positive? (similarly for negative)</p>
<p>I started by grouping sub-domains and identified the most common positive and negative sub-domains. </p>
<p>Now, for sub-domains that have an equa... | 1 | 2016-07-14T22:30:56Z | 38,407,777 | <p><strong>Solved this</strong>: Ended up taking cue from <code>finding largest common substring</code> problem. </p>
<p>The solution includes building a parse tree from each character of the url. Each node in the tree stores positive, negative, total counts. Finally, the tree is pruned to return most common patterns.... | 0 | 2016-07-16T04:38:52Z | [
"python",
"parsing",
"url"
] |
Find if a specific string exists after a specific string on the following line | 38,385,274 | <p>I'm creating a script in which i'm looking for a specific string in a file, then print the next 5 following lines, However, the initial string could be found in other areas of the file and are unnecessary, So i'm trying to add an additional check to see if <strong>the next line</strong> contains a specific string th... | 0 | 2016-07-14T22:33:00Z | 38,385,344 | <p>First attempt:</p>
<pre><code>from itertools import islice
first_string = 'Description = "'
second_string = 'ErrorCode'
with open('test.txt') as f:
for line in f:
if first_string in line:
next_line = next(f)
if second_string in next_line:
print(next_line + ''.jo... | 0 | 2016-07-14T22:40:03Z | [
"python",
"linux"
] |
Pyflakes reports an invalid syntax error in a print command | 38,385,288 | <p>Pyflakes reports an invalid syntax error in a print (to file) command in a class method. Here is the code:</p>
<pre><code>class Controller():
def __init__(self):
self.base_url = ''
self.permissions = None
self.url = ''
self.description = ''
self.requests = ''
sel... | 0 | 2016-07-14T22:34:33Z | 38,385,362 | <p>remove that back slash here and you are fine:</p>
<pre><code>'}', \
file=self.json_file
</code></pre>
| 0 | 2016-07-14T22:41:35Z | [
"python",
"pyflakes"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.