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 |
|---|---|---|---|---|---|---|---|---|---|
SyntaxError on setup.py | 38,018,959 | <p>I am new to python and I am trying to make an exe file, using py2exe, from a python code I made. I made the following setup.py file following a tutorial on how to use py2exe:</p>
<pre><code>from distutils.core import setup
from glob import glob
import py2exe
setup(console=['App.py'])
data_files = [("msvcr90.dll",... | 0 | 2016-06-24T17:22:44Z | 38,018,998 | <blockquote>
<p>I have read several other posts on this error basically saying that I should <strong>have the "etc" before "data_files"</strong>. However when I do this, I get a name error <code>undefined name sys</code></p>
</blockquote>
<p>That IS the solution to this problem, though you will then encounter the sa... | 2 | 2016-06-24T17:25:52Z | [
"python",
"py2exe"
] |
Does pd.Period max out at microsecond period? | 38,018,975 | <p>I was trying to see just how detailed I can make a <code>pd.Period</code> and here's what I got:</p>
<pre><code>pd.Period('2016-01-01 10:10:10.123456789')
</code></pre>
<p>which produces:</p>
<pre><code>Period('2016-01-01 10:10:10.123456', 'U')
</code></pre>
<p>Is that really the max? I didn't see this addressed... | 2 | 2016-06-24T17:24:02Z | 38,019,092 | <p>There's nanosecond, which is finer than microsecond (U):</p>
<pre><code>In [11]: pd.Period("2016-01-01", "n")
Out[11]: Period('2016-01-01 00:00:00.000000000', 'N')
In [12]: pd.Period("2016-01-01", "u")
Out[12]: Period('2016-01-01 00:00:00.000000', 'U')
</code></pre>
<p>The possible frequencies are in the <a href=... | 0 | 2016-06-24T17:32:00Z | [
"python",
"pandas"
] |
A function to create interaction variables: what is wrong with the code? | 38,019,029 | <p>Iâve written a function below that takes, as arguments, a dataframe (<code>df</code>) and two of its column names (<code>var1</code>, <code>var2</code>). Then it creates interaction variables for the two variables and adds those columns to the original dataframe. The code works when I hard code it, but when I tr... | 1 | 2016-06-24T17:27:57Z | 38,019,145 | <p>You need to check scoping on your variables. Within the create_interactions function, you never change dataframe directly. First, you copy the dataframe in:</p>
<pre><code>variables = df[[var1,var2]]
</code></pre>
<p>then you assign the dataframe variable in:</p>
<pre><code> df = pd.concat([df, pd.Series(variabl... | 1 | 2016-06-24T17:35:53Z | [
"python",
"function",
"pandas"
] |
A function to create interaction variables: what is wrong with the code? | 38,019,029 | <p>Iâve written a function below that takes, as arguments, a dataframe (<code>df</code>) and two of its column names (<code>var1</code>, <code>var2</code>). Then it creates interaction variables for the two variables and adds those columns to the original dataframe. The code works when I hard code it, but when I tr... | 1 | 2016-06-24T17:27:57Z | 38,019,160 | <p>Your problem is in this line:</p>
<pre><code>df = pd.concat([df, pd.Series(variables[col1] * variables[col2], name=name)], axis=1)
</code></pre>
<p>you are creating a new dataframe and assigning it to the variable <code>df</code>. <code>df</code> is no longer pointing to the <code>df</code> that was passed. What... | 2 | 2016-06-24T17:36:33Z | [
"python",
"function",
"pandas"
] |
A function to create interaction variables: what is wrong with the code? | 38,019,029 | <p>Iâve written a function below that takes, as arguments, a dataframe (<code>df</code>) and two of its column names (<code>var1</code>, <code>var2</code>). Then it creates interaction variables for the two variables and adds those columns to the original dataframe. The code works when I hard code it, but when I tr... | 1 | 2016-06-24T17:27:57Z | 38,019,171 | <p>Doing <code>df = ...</code> doesn't modify the original df. It just makes a new local variable with your new df.</p>
<p>You could return <code>df</code> from your function, and then use it like <code>df = create_interactions(df, 'var1', 'var2')</code>.</p>
<p>But if you do want your function to modify the origina... | 1 | 2016-06-24T17:37:01Z | [
"python",
"function",
"pandas"
] |
How to find the nth prime number faster? | 38,019,091 | <p>I just started to learn how to program and I was trying to make a program to find the nth prime number. And I did it. But it takes a very long time for large number. Is there a way to make it faster? Here's the code I used(it's really basic):</p>
<pre><code>def prime_finder(nth1):
s = 1
n = 0
while n < ... | 0 | 2016-06-24T17:31:59Z | 38,019,191 | <p>This is less about Python and more about <a href="https://en.wikipedia.org/wiki/Algorithm">algorithms</a>. Try looking at <a href="https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes">the Sieve of Eratosthenes</a>, for example. There is pseudo-code there that should get you started. Also, you can just google for ... | 5 | 2016-06-24T17:38:21Z | [
"python"
] |
How to find the nth prime number faster? | 38,019,091 | <p>I just started to learn how to program and I was trying to make a program to find the nth prime number. And I did it. But it takes a very long time for large number. Is there a way to make it faster? Here's the code I used(it's really basic):</p>
<pre><code>def prime_finder(nth1):
s = 1
n = 0
while n < ... | 0 | 2016-06-24T17:31:59Z | 38,019,374 | <p>You could speed it up by instead of iterating
<code>range(2,s)</code> to find a factor, try
<code>range(2,int(math.sqrt(s)))</code>
If a number doesn't divide anything less than its square root, it must be prime. </p>
<p>Remember to
<code>import math</code></p>
<p>as well.</p>
| 0 | 2016-06-24T17:51:23Z | [
"python"
] |
How can I determine the largest integer value in a string? | 38,019,107 | <p>Here is what I have:</p>
<pre><code>largest_int=None
def largest_digit(string_one):
for ch in string_one:
if not string_one.isdigit():
largest_int=None
elif ch in string_one.isdigit():
largest_int=ch>ch
print (largest_int)
largest_digit('Hello 1 2 3 5 4')... | -3 | 2016-06-24T17:32:49Z | 38,019,163 | <p>If you create a generator that yields only the digits in the string, you will be able to use <code>max</code>.</p>
<pre><code>def largest_digit(string_one):
return max(int(ch) for ch in string_one.split() if ch.isdigit())
</code></pre>
| 2 | 2016-06-24T17:36:36Z | [
"python",
"python-3.x"
] |
How can I determine the largest integer value in a string? | 38,019,107 | <p>Here is what I have:</p>
<pre><code>largest_int=None
def largest_digit(string_one):
for ch in string_one:
if not string_one.isdigit():
largest_int=None
elif ch in string_one.isdigit():
largest_int=ch>ch
print (largest_int)
largest_digit('Hello 1 2 3 5 4')... | -3 | 2016-06-24T17:32:49Z | 38,019,204 | <pre><code>def get_largest_digit(string_one):
digits_only = [x for x in string_one if x in [str(y) for y in range(0, 10)]]
return max(digits_only)
print(get_largest_digit('Hello 1 2 3 5 4'))
</code></pre>
| -3 | 2016-06-24T17:39:32Z | [
"python",
"python-3.x"
] |
How can I determine the largest integer value in a string? | 38,019,107 | <p>Here is what I have:</p>
<pre><code>largest_int=None
def largest_digit(string_one):
for ch in string_one:
if not string_one.isdigit():
largest_int=None
elif ch in string_one.isdigit():
largest_int=ch>ch
print (largest_int)
largest_digit('Hello 1 2 3 5 4')... | -3 | 2016-06-24T17:32:49Z | 38,019,228 | <pre><code>def largest_digit(string_one):
tmp=[]
for e in string_one.split():
try:
tmp.append( int(e) )
except:
pass
print( max( tmp ) )
largest_digit('Hello 1 2 3 5 4')
</code></pre>
| -1 | 2016-06-24T17:41:00Z | [
"python",
"python-3.x"
] |
How can I determine the largest integer value in a string? | 38,019,107 | <p>Here is what I have:</p>
<pre><code>largest_int=None
def largest_digit(string_one):
for ch in string_one:
if not string_one.isdigit():
largest_int=None
elif ch in string_one.isdigit():
largest_int=ch>ch
print (largest_int)
largest_digit('Hello 1 2 3 5 4')... | -3 | 2016-06-24T17:32:49Z | 38,019,626 | <p>You can use 'filter' combined with a lambda expression. I don't know if it's the better solution, but I will put here to show another way to solve the problem.</p>
<pre><code>def largest_digit(string_one):
return max(filter(lambda x: int(x) if x.isdigit() else 0, string_one.split()))
</code></pre>
| 0 | 2016-06-24T18:08:14Z | [
"python",
"python-3.x"
] |
Where is the location of the template files of pinax-stripe package? | 38,019,165 | <p>I have installed the following package in my django application:</p>
<p>Pinax Stripe : <a href="https://github.com/pinax/pinax-stripe" rel="nofollow">https://github.com/pinax/pinax-stripe</a></p>
<p>In my application, I can see the page for 'add subscription' after I add this application to my settings.py file. I ... | 0 | 2016-06-24T17:36:48Z | 38,021,293 | <p>I found what appears to be the correct template files on <a href="https://github.com/pinax/pinax-theme-bootstrap/tree/master/pinax_theme_bootstrap/templates/pinax/stripe" rel="nofollow">Github</a>. The easiest way to setup the template would just to be to install the entire package. </p>
<p>First, install pinax-the... | 0 | 2016-06-24T20:05:01Z | [
"python",
"django",
"pinax"
] |
Why -l and -r don't have spaces in them? | 38,019,168 | <p>Why -l and -r don't have spaces in them when we run <code>pip install -rrequirements</code>?</p>
<p>I was wondering why we don't run <code>pip install -r requirements</code>? (with a space). This allows us to use tab and is more clear.</p>
| -2 | 2016-06-24T17:36:55Z | 38,019,210 | <p>You are free to use as many spaces there as you wish.</p>
<p>Its customary for single letter switches to be usable with and without these spaces in Unix programs.</p>
<p>The longer named version, normally coming with <code>--</code> instead of the <code>-</code>, usually have the space mandatory.</p>
| 2 | 2016-06-24T17:40:04Z | [
"python",
"pip"
] |
Python Gui button command executing without button push. Only passing function and have tried Lambda | 38,019,185 | <p>The command for my button on my secondary window is executing as soon as the primary window is opened. I have seen other related answers and am only passing the function object. I have also tried Lambda even though I'm not passing any arguments. New to GUIs. Appreciate the help. Code below:</p>
<pre><code>import tk... | 0 | 2016-06-24T17:37:40Z | 38,020,437 | <p>Turns out I had an execution statement at the bottom of the file I was importing that was used for debugging that module. It was executing right away. I only found it thanks to those who said it worked fine without the import statement. </p>
| 0 | 2016-06-24T19:04:35Z | [
"python",
"tkinter"
] |
Visual Basic type IDE with GUI form editor | 38,019,266 | <p>I'm new to Python and Pygame, and would like to start building apps with GUI forms, controls, and dropdown menus.</p>
<p>I come from Visual Basic, where you can just go in the IDE and click "new form",
and voila, you have your form on the screen that you can just drag & drop controls onto, and double-click on ... | -1 | 2016-06-24T17:43:14Z | 38,027,766 | <p>With a bit of researches, I found <a href="http://page.sourceforge.net/" rel="nofollow">this</a>, however I'll recommend you to learn creating these GUIs by hand.</p>
<p>It can of course be a harsh job, but if you run into any kind of problem, you'll exactly know where to search, where it would fail, and more impor... | 0 | 2016-06-25T11:03:08Z | [
"python",
"visual-studio",
"python-3.x",
"user-interface",
"ide"
] |
Import data from excel spreadsheet to django model | 38,019,267 | <p>I'm building a website that'll have a django backend. I want to be able to serve the medical billing data from a database that django will have access to. However, all of the data we receive is in excel spreadsheets. So I've been looking for a way to get the data from a spreadsheet, and then import it into a django ... | -1 | 2016-06-24T17:43:17Z | 38,021,137 | <p>Use <a href="http://www.python-excel.org/" rel="nofollow">http://www.python-excel.org/</a> and consider this process:</p>
<ol>
<li>Make a view where user can upload the xls file.</li>
<li>Open the file with xlrd. <code>xlrd.open_workbook(filename)</code></li>
<li>Extract, create dict to map the data you want to syn... | 0 | 2016-06-24T19:53:24Z | [
"python",
"django",
"database",
"excel",
"model"
] |
Import data from excel spreadsheet to django model | 38,019,267 | <p>I'm building a website that'll have a django backend. I want to be able to serve the medical billing data from a database that django will have access to. However, all of the data we receive is in excel spreadsheets. So I've been looking for a way to get the data from a spreadsheet, and then import it into a django ... | -1 | 2016-06-24T17:43:17Z | 38,021,142 | <p>Excel spreadsheets are saved as .csv files, and there are plenty of examples and explanations on how to work with them, such as <a href="http://mitchfournier.com/2011/10/11/how-to-import-a-csv-or-tsv-file-into-a-django-model/" rel="nofollow">here</a> and <a href="http://stackoverflow.com/questions/2459979/how-to-imp... | 0 | 2016-06-24T19:53:57Z | [
"python",
"django",
"database",
"excel",
"model"
] |
ODOO8: Untaxed and total amount in order lines not calculating | 38,019,268 | <p>I add multiple PRODUCTS in the order lines of the REPAIR-ORDER, the price of each product shows up - but the untaxed sub total and total display (0) instead of the total of all products.</p>
<p><a href="http://i.stack.imgur.com/GJiOp.png" rel="nofollow"><img src="http://i.stack.imgur.com/GJiOp.png" alt="TOTAL AMOUN... | 0 | 2016-06-24T17:43:19Z | 38,052,353 | <p>I found that without the code below (this code causes MRP_REPAIR to add order lines both to the REPAIR ORDER and SALES ORDER), adding a product with a price doesnt get calculated in total field, and shows zero (0)</p>
<pre><code> elif this.repair_sale_order_line_id:
sale_obj = self.pool.get('sal... | 0 | 2016-06-27T11:05:43Z | [
"python",
"openerp",
"odoo-8"
] |
with pd.read_ How to use parse_dates and then set the index to the result of parsing the dates? | 38,019,274 | <p>Is it possible in a one line call to read this file:</p>
<pre><code>http://www.cpc.ncep.noaa.gov/products/precip/CWlink/daily_ao_index/monthly.ao.index.b50.current.ascii
</code></pre>
<p>which has data like this:</p>
<pre><code> 1950 1 -0.60310E-01
1950 2 0.62681E+00
1950 3 -0.81275E-02
1950 4 ... | 1 | 2016-06-24T17:43:54Z | 38,019,398 | <p>You can add parameter <code>index_col = 0</code>:</p>
<pre><code>df = pd.read_fwf('http://www.cpc.ncep.noaa.gov/products/precip/CWlink/daily_ao_index/monthly.ao.index.b50.current.ascii',
parse_dates = [[0, 1]],
infer_datetime_format = True,
header = None,
... | 1 | 2016-06-24T17:53:02Z | [
"python",
"parsing",
"datetime",
"pandas",
"dataframe"
] |
AVS V2 Establishing HTTP2 Connection | 38,019,382 | <p>I'm trying to create an HTTP/2 connection using Python, Requests, and the Hyper HTTP20Adapter (for HTTP/2 support) to AVS (Version 20160207 of the API). I asked a similar question <a href="http://stackoverflow.com/questions/37952758/establishing-http2-connection-with-avs-python-requests-library">here</a>, and determ... | 1 | 2016-06-24T17:51:57Z | 38,642,837 | <p>1) sorry, I don't know - I had problems using the adapter - my requests were not terminating, so I switched to using the asyncio protocol-based flow shown in the <a href="http://python-hyper.org/projects/h2/en/stable/asyncio-example.html" rel="nofollow">hyper server example</a> (it's not too bad to convert that to a... | 0 | 2016-07-28T17:16:06Z | [
"python",
"python-requests",
"http2",
"alexa-voice-service"
] |
pandas dataframe convert columns as rows | 38,019,397 | <p>I am looking for a way to convert my dataframe columns as rows. Following is my example dataframe:</p>
<pre><code>mylist= [['xx'], [None, 'yy'], ['xx', None], ['xx',None],['xx','yy']]
pd.DataFrame(mylist,index=['A','B','C','D','E'],columns=['Col1','Col2'])
</code></pre>
<p>Input DataFrame:</p>
<pre><code>-------... | 1 | 2016-06-24T17:52:58Z | 38,019,545 | <pre><code>df = pd.DataFrame(mylist,index=['A','B','C','D','E'],columns=['Col1','Col2'])
# rotate df
stacked_df = pd.DataFrame(df.stack().reset_index())
# name columns
stacked_df.columns = ['Ind','Columns','Values']
# reorder columns
reordered_df = pd.DataFrame(stacked_df,columns=['Ind','Values','Columns'])
</code></pr... | 2 | 2016-06-24T18:03:33Z | [
"python",
"pandas"
] |
pandas dataframe convert columns as rows | 38,019,397 | <p>I am looking for a way to convert my dataframe columns as rows. Following is my example dataframe:</p>
<pre><code>mylist= [['xx'], [None, 'yy'], ['xx', None], ['xx',None],['xx','yy']]
pd.DataFrame(mylist,index=['A','B','C','D','E'],columns=['Col1','Col2'])
</code></pre>
<p>Input DataFrame:</p>
<pre><code>-------... | 1 | 2016-06-24T17:52:58Z | 38,019,670 | <p>Another option is to use <code>melt</code>:</p>
<pre><code>longDf = pd.melt(df.reset_index(), id_vars=['index'], var_name=['Columns'])
longDf[pd.notnull(longDf.value)]
index Columns value
0 A Col1 xx
2 C Col1 xx
3 D Col1 xx
4 E Col1 xx
6 B Col2 yy
9 E Col2 yy
</code></pr... | 3 | 2016-06-24T18:11:01Z | [
"python",
"pandas"
] |
pandas dataframe convert columns as rows | 38,019,397 | <p>I am looking for a way to convert my dataframe columns as rows. Following is my example dataframe:</p>
<pre><code>mylist= [['xx'], [None, 'yy'], ['xx', None], ['xx',None],['xx','yy']]
pd.DataFrame(mylist,index=['A','B','C','D','E'],columns=['Col1','Col2'])
</code></pre>
<p>Input DataFrame:</p>
<pre><code>-------... | 1 | 2016-06-24T17:52:58Z | 38,019,755 | <p>In the case of two values, it appears that you only want the first (e.g. the last row of your example).</p>
<p>You can use <code>loc</code> to first set the second value to None in the case both columns have values.</p>
<pre><code>df.loc[(df.Col1.notnull()) & (df.Col2.notnull()), 'Col2'] = None
</code></pre>
... | 1 | 2016-06-24T18:16:35Z | [
"python",
"pandas"
] |
pyspark: remove rows that have duplicated values for a given field | 38,019,399 | <p>I have the following data frame:</p>
<pre><code>field_A | field_B | field_C | field_D
cat | 12 | black | 11
dog | 128 | white | 19
dog | 35 | yellow | 20
dog | 21 | brown | 4
bird | 10 | blue | 7
cow | 99 | brown | 34
</code></pre>
<hr>
<p>Is it po... | -1 | 2016-06-24T17:53:04Z | 38,019,700 | <p>Create data</p>
<pre><code>rdd = sc.parallelize([(0,1), (0,10), (0,20), (1,2), (2,1), (3,5), (3,18), (4,15), (5,18)])
t = sqlContext.createDataFrame(rdd, ["id", "score"])
t.collect()
</code></pre>
<blockquote>
<p>[Row(id=0, score=1),
Row(id=0, score=10),
Row(id=0, score=20),
Row(id=1, score=2),
Row(i... | 2 | 2016-06-24T18:13:02Z | [
"python",
"apache-spark",
"pyspark",
"spark-dataframe"
] |
Raspberry Pi Python Press button and run some code | 38,019,426 | <p>I'm a total noob with Raspberry Pi and Python, and I'm trying to make a simple traffic light simulator with 5 LEDs and a button. Here's my code:</p>
<p>while True:</p>
<pre><code>inputValue = GPIO.input(17)
if (inputValue == False): #if the button was pushed
print("Button press ")
else: #if it wasn't pressed
... | 1 | 2016-06-24T17:55:09Z | 40,019,899 | <p>First of all you seem to have inverted <code>HIGH</code> and <code>LOW</code>. </p>
<p>You need a service/background script to listen to the input port and put the state in a file for example. If installed, Node-RED can monitor GPIO ports so you won't need to program a service.</p>
<p><a href="https://www.cl.cam.a... | 0 | 2016-10-13T11:37:04Z | [
"python",
"raspberry-pi3"
] |
Selective vertical whitespace in matplotlib legend | 38,019,467 | <p>I'm trying to create some extra vertical whitespace in a legend produced using <code>matplotlib.pyplot</code>. However, want this extra whitespace to only be between two entries in the legend, while the remaining entries are left untouched. I have a MWE and the image it produces, edited to show where I want the ex... | 2 | 2016-06-24T17:58:15Z | 38,019,554 | <p>You probably have to use a Proxy Artist for this. Here is an example:</p>
<pre><code>a, = plt.plot([0,1],[.2,.2],label = "A")
b, = plt.plot([0,1],[.4,.4],label = "B")
c, = plt.plot([0,1],[.6,.6],label = "C")
d, = plt.plot([0,1],[.8,.8],label = "D")
plt.legend([a,b,c,matplotlib.lines.Line2D([],[],linestyle=''),d],[... | 2 | 2016-06-24T18:04:14Z | [
"python",
"matplotlib",
"legend"
] |
Python anywhere modules not accessible outside main directory | 38,019,470 | <p>In my attempts to create a web app with python anywhere I have discovered that my preferred module web.py is not preinstalled like other modules such as flask. Upon looking through some forums I came to the understanding that installation would occur in the following fashion in the hash console:</p>
<pre><code>pip ... | 0 | 2016-06-24T17:58:36Z | 38,086,091 | <p>I apologize for my stupidity... It turns out that pythonanywhere defaults to python 3.x and seeing as web.py is a 2.x module, it was unsuccessful. I can only hope that perhaps this post will help some equally unassuming individual such as myself in the future.</p>
| 1 | 2016-06-28T20:51:35Z | [
"python",
"pip",
"pythonanywhere"
] |
Python recursive tree or fowards? Fix and simplify code | 38,019,582 | <p>I originally was using recursion to minimax my tree from the leaves where only I have scores evaluated, but because I needed to know the depth to know whether to min or max, I switched to starting at <code>depth=0</code>. However, errors since sometimes <code>currentRoot.ia = None</code> since no score has been calc... | 0 | 2016-06-24T18:05:42Z | 38,023,552 | <p>I'm thinking this might solve my error, but I don't feel it is elegant. I recurse until I found a value so ia is not None, and I go deeper until I find I am at a leaf where the tree has not been evaluated further.</p>
<pre><code>def minimax(currentRoot, depth):
notAtLeaf = True
if currentRoot.ia is None:
... | 0 | 2016-06-24T23:41:49Z | [
"python",
"recursion",
"tree",
"minimax"
] |
Get the torrent download directory from a torrent file using python-libtorrent | 38,019,615 | <p>I need the default directory a torrent file will create when it is started using any torrent manager - as a string. I'm not a programmer, but with other help I was able to obtain the contents (files) of the torrent as strings:</p>
<pre><code>info = libtorrent.torrent_info(torrent_file)
for f in info.files():
... | 0 | 2016-06-24T18:07:33Z | 38,024,250 | <p>One thing to keep in mind is that there are two <em>kinds</em> of torrent files. Single-file torrents and multi-file torrents. The typical filename structure of the two kinds are:</p>
<p>single-file torrents: <em>save-path</em>/<em>torrent-name</em></p>
<p>multi-file torrents: <em>save-path</em>/<em>torrent-name</... | 1 | 2016-06-25T01:57:14Z | [
"python",
"libtorrent",
"torrent"
] |
Print specific value index from key in dictionary | 38,019,716 | <p>I have a dictionary that has many values per key.
How do I print a specific value from that key?</p>
<p>for example, my key is "CHMI" but it has 14 values associated with it. How do I print only <code>CHMI: 48680</code> value?</p>
<pre><code>CHMI: ['CHMI', '16', '16.09', '15.92', '16.01', '0.02', '0.13', '48680',... | -1 | 2016-06-24T18:14:17Z | 38,019,774 | <p>Although I don't understand why you would want to do it (if you already know what value you want, why not use it directly?), it can be done with the <code>index</code> method of lists, which returns the index of the provided value in the list</p>
<pre><code>d = {'CHMI': ['CHMI', '16', '16.09', '15.92', '16.01', '0.... | 0 | 2016-06-24T18:18:04Z | [
"python",
"dictionary"
] |
Print specific value index from key in dictionary | 38,019,716 | <p>I have a dictionary that has many values per key.
How do I print a specific value from that key?</p>
<p>for example, my key is "CHMI" but it has 14 values associated with it. How do I print only <code>CHMI: 48680</code> value?</p>
<pre><code>CHMI: ['CHMI', '16', '16.09', '15.92', '16.01', '0.02', '0.13', '48680',... | -1 | 2016-06-24T18:14:17Z | 38,019,829 | <p>You have a dictionary with a key:value pair where the value is a list.</p>
<p>To reference values within this list, you do your normal dictionary reference, ie </p>
<pre><code> dict['chmi']
</code></pre>
<p>But you need to add a way to manipulate your list. You can use any of the list methods, or just use a list... | 1 | 2016-06-24T18:21:41Z | [
"python",
"dictionary"
] |
Print specific value index from key in dictionary | 38,019,716 | <p>I have a dictionary that has many values per key.
How do I print a specific value from that key?</p>
<p>for example, my key is "CHMI" but it has 14 values associated with it. How do I print only <code>CHMI: 48680</code> value?</p>
<pre><code>CHMI: ['CHMI', '16', '16.09', '15.92', '16.01', '0.02', '0.13', '48680',... | -1 | 2016-06-24T18:14:17Z | 38,019,839 | <p>Do you want the 8th element of the list, or an element with a specific value? If you already know the value - then you can print it without looking it up in the list so I assume you want to just retrieve one of the elements:</p>
<pre><code>print(my_dict['CHMI'][7])
</code></pre>
<p>This is equivalent to:</p>
<pre... | 0 | 2016-06-24T18:22:27Z | [
"python",
"dictionary"
] |
Adding new django rest framework app to settings | 38,019,729 | <p>I'm going through this tutorial: <a href="http://www.django-rest-framework.org/tutorial/1-serialization/" rel="nofollow">http://www.django-rest-framework.org/tutorial/1-serialization/</a> and there's one thing I don't understand a bit. They are doing <code>python manage.py startapp snippets</code> and adding <code>'... | 1 | 2016-06-24T18:15:14Z | 38,020,129 | <p>If you are using below djagno1.9 just add <code>snippets</code>. In older django versions <code>startapp</code> management command will not create apps.py. you have to create new apps.py.</p>
<p>For > Django 1.9
<a href="https://docs.djangoproject.com/en/dev/releases/1.9/#management-commands" rel="nofollow">apps.py... | 1 | 2016-06-24T18:43:10Z | [
"python",
"django",
"django-rest-framework"
] |
Faster Lemmatization techniques in Python | 38,019,823 | <p>I am trying to find out a faster way to lemmatize words in a list (named <i> <strong>text</strong></i>) using the NLTK Word Net Lemmatizer. Apparently this is the most time consuming step in my whole program(used cProfiler to find the same). </p>
<p>Following is the piece of code that I am trying to optimize for sp... | 1 | 2016-06-24T18:21:14Z | 38,020,540 | <p>If you have a few cores to spare, try using the <code>multiprocessing</code> library:</p>
<pre><code>from nltk import WordNetLemmatizer
from multiprocessing import Pool
def lemmed(text, cores=6): # tweak cores as needed
with Pool(processes=cores) as pool:
wnl = WordNetLemmatizer()
result = pool... | 1 | 2016-06-24T19:11:05Z | [
"python",
"performance",
"python-3.x",
"nltk",
"lemmatization"
] |
Python: many-to-many comparison to find required set of data | 38,019,830 | <p>This is my first question so please forgive any mistakes.</p>
<p>I have a large file(csv) with several(~10000000+) lines of information like the following example:</p>
<pre><code>date;box_id;box_length;box_width;box_height;weight;type
--snip--
1999-01-01 00:00:20;nx1124;10;4;5.5;2.1;oversea
1999-01-01 00:00:20;np1... | 2 | 2016-06-24T18:21:43Z | 38,021,439 | <p>Taking the first timestamp as start of a one hour window (instead of clock hour bins always staring at hour:00:00) I think a quite feasible implementation for data amounts as small as a few ten million lines of data might be (expect time ordered entriesin file):</p>
<pre><code>#! /usr/bin/env python
from __future__... | 1 | 2016-06-24T20:16:35Z | [
"python",
"algorithm",
"bigdata"
] |
Python: Writing to csv-file | 38,019,888 | <p>I am trying to read a csv-style file and create another one.
Here is the (simplified) code.</p>
<pre><code>import os
import csv
import sys
fn = 'C:\mydird\Temp\xyz'
ext = '.txt'
infn = fn+ext
outfn = fn+'o'+ext
infile = open(infn, newline='')
outfile = open(outfn, 'w', newline='')
try:
reader = csv.reader(i... | 1 | 2016-06-24T18:26:13Z | 38,019,929 | <p>Your code doesn't define a writer.</p>
<p>Add <code>writer = csv.writer(outfile)</code> and then close the outfile and it should work. Using the <code>with</code> idiom makes the code cleaner.</p>
<pre><code>import csv
fn = 'C:\mydird\Temp\xyz'
ext = '.txt'
infn = fn+ext
outfn = fn+'o'+ext
with open(infn) as rf... | 4 | 2016-06-24T18:29:26Z | [
"python",
"csv"
] |
Pandas time series documentation example not working | 38,019,960 | <p>I'm trying to make this example from the <code>pandas</code> docs work:</p>
<pre><code>In [28]: df = pd.DataFrame({'year': [2015, 2016],
....: 'month': [2, 3],
....: 'day': [4, 5],
....: 'hour': [2, 3]})
....:
In [29]: pd.to_datetime(df)
Out[29]... | 1 | 2016-06-24T18:32:18Z | 38,020,079 | <p>The behavior of <code>to_datetime</code> you are testing is <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#whatsnew-0181-enhancements-assembling" rel="nofollow">new in v0.18.1</a>. My guess is you are using an older version.</p>
| 2 | 2016-06-24T18:39:42Z | [
"python",
"pandas"
] |
Pandas time series documentation example not working | 38,019,960 | <p>I'm trying to make this example from the <code>pandas</code> docs work:</p>
<pre><code>In [28]: df = pd.DataFrame({'year': [2015, 2016],
....: 'month': [2, 3],
....: 'day': [4, 5],
....: 'hour': [2, 3]})
....:
In [29]: pd.to_datetime(df)
Out[29]... | 1 | 2016-06-24T18:32:18Z | 38,020,100 | <pre><code>import sys
import pandas as pd
print sys.version
print pd.__version__
2.7.11 |Anaconda custom (x86_64)| (default, Dec 6 2015, 18:57:58)
[GCC 4.2.1 (Apple Inc. build 5577)]
0.18.1
</code></pre>
<p>The following worked for me.</p>
<pre><code>df = pd.DataFrame({'year': [2015, 2016],
'mo... | 1 | 2016-06-24T18:40:46Z | [
"python",
"pandas"
] |
How to finds if two entities are in the same group in a dataframe? | 38,019,976 | <p>I have a dataframe as follwos:</p>
<pre><code> City Name
0 Seattle Alice
1 Seattle Bob
2 Portland Mallory
3 Portland Bob
</code></pre>
<p>Given two names I want to find whether they are in the same or not.
What is an efficient way to do this?
I was thinking about group by "City... | 0 | 2016-06-24T18:33:05Z | 38,020,222 | <p>You could use:</p>
<pre><code>names = ['Alice', 'Bob']
df[df.Name.isin(names)].groupby('City').Name.nunique() > 1
</code></pre>
<p>yields</p>
<pre><code>City
Portland False
Seattle True
Name: Name, dtype: bool
</code></pre>
<p>Enclose with <code>(..).any()</code> to get a summary <code>True</code> / <... | 1 | 2016-06-24T18:48:51Z | [
"python",
"pandas"
] |
How to finds if two entities are in the same group in a dataframe? | 38,019,976 | <p>I have a dataframe as follwos:</p>
<pre><code> City Name
0 Seattle Alice
1 Seattle Bob
2 Portland Mallory
3 Portland Bob
</code></pre>
<p>Given two names I want to find whether they are in the same or not.
What is an efficient way to do this?
I was thinking about group by "City... | 0 | 2016-06-24T18:33:05Z | 38,020,243 | <p>Try this:</p>
<pre><code>def bothInCity(df, n1, n2):
s = {n1, n2}
c = df.groupby('City').Name.apply(set)
chk = lambda x: s.issubset(x)
return c.loc[c.apply(chk)]
</code></pre>
<p>Then use it like:</p>
<pre><code>bothInCity(df, 'Bob', 'Alice')
City
Seattle {Bob, Alice}
Name: Name, dtype: object... | 1 | 2016-06-24T18:50:08Z | [
"python",
"pandas"
] |
How to finds if two entities are in the same group in a dataframe? | 38,019,976 | <p>I have a dataframe as follwos:</p>
<pre><code> City Name
0 Seattle Alice
1 Seattle Bob
2 Portland Mallory
3 Portland Bob
</code></pre>
<p>Given two names I want to find whether they are in the same or not.
What is an efficient way to do this?
I was thinking about group by "City... | 0 | 2016-06-24T18:33:05Z | 38,020,296 | <p>A possible way to use <code>groupby</code>:</p>
<pre><code>x = "Mallory"
y = "Alice"
any(any(names[1].str.contains(x)) and any(names[1].str.contains(y)) for names in df.groupby('City').Name)
# False
</code></pre>
| 1 | 2016-06-24T18:53:47Z | [
"python",
"pandas"
] |
PyQt5 app exits on error where PyQt4 app would not | 38,020,020 | <p>I have been developing a scientific application using PyQt4 for a couple of weeks, and decided to switch over to PyQt5. Aside from a few things to iron out one thing is puzzling me, and I'm not sure if its intended behavior or not.</p>
<p>When Using PyQt4:
if I had a python error (AttributeError, FileNotFoundError ... | 1 | 2016-06-24T18:35:20Z | 38,020,962 | <p>The old behavior can be forced by calling this code, which I found after more searching. <s>I'm not sure I understand why this is bad behavior that needed to be deprecated, but this does work.</s></p>
<p>I submit that this should not be the default behavior, and that properly catching exceptions is the correct way... | 2 | 2016-06-24T19:40:07Z | [
"python",
"qt",
"pyqt",
"pyqt4",
"pyqt5"
] |
make QTableView column read-only using Python | 38,020,127 | <p>I have searched the archives and I found the following code:</p>
<pre><code>class ManifestModel: public QSqlTableModel
{
public:
ManifestModel(QObject * parent = 0, QSqlDatabase db = QSqlDatabase() ):
QSqlTableModel(parent, db)
{ }
~ManifestModel() { }
Qt::ItemFlags flags ( const QModelInde... | 0 | 2016-06-24T18:43:05Z | 38,020,981 | <p>This should work but I didn't test it:</p>
<pre><code>from PyQt4.QtCore import Qt
from PyQt4.QtSql import QSqlTableModel, QSqlDatabase
class ManifestModel(QSqlTableModel):
def __init__(self, parent=None, db=QSqlDatabase()):
super(ManifestModel, self).__init__(parent, db)
def flags(self, index):
... | 1 | 2016-06-24T19:42:17Z | [
"python",
"pyqt",
"qtableview"
] |
make QTableView column read-only using Python | 38,020,127 | <p>I have searched the archives and I found the following code:</p>
<pre><code>class ManifestModel: public QSqlTableModel
{
public:
ManifestModel(QObject * parent = 0, QSqlDatabase db = QSqlDatabase() ):
QSqlTableModel(parent, db)
{ }
~ManifestModel() { }
Qt::ItemFlags flags ( const QModelInde... | 0 | 2016-06-24T18:43:05Z | 38,150,268 | <p>This is what works in PyQt5:</p>
<p>class ManifestModel(QtSql.QSqlTableModel):</p>
<pre><code>def __init__(self, parent=None, db=QtSql.QSqlDatabase()):
super(ManifestModel, self).__init__(parent, db)
def flags(self, index):
if (index.column() == 4):
return QtCore.Qt.ItemIsEnabled
elif (index.c... | 0 | 2016-07-01T16:37:35Z | [
"python",
"pyqt",
"qtableview"
] |
How to use categorial properties of Vertices and Edges to draw colors in graph-tool? | 38,020,354 | <p>I have a graph_tool.Graph generated as follows:</p>
<pre><code>import random
import graph_tool.all as gt
G = gt.Graph()
# Add a categorical property
cprop = G.new_vertex_property('string')
G.vertex_properties['type'] = cprop
# Add some verticies with alternating properties
for idx in range(10):
v = G.add... | 2 | 2016-06-24T18:58:05Z | 38,183,925 | <p>Maybe I didn't really understand what you were trying to do. If you'd like to set RGB values to color your edges for example, you can do;</p>
<pre><code>#Add a property map
edge_color = G.new_edge_property('vector<double>')
G.edge_properties['edge_color']=edge_color
#Color your edges
for e in G.edges():
... | 0 | 2016-07-04T11:44:05Z | [
"python",
"graph",
"graph-tool"
] |
Convert column of timestamp with a different UTC base to current UTC using Python | 38,020,396 | <p>I have a dataframe with timestamps that are number of seconds since Jan 1,2010 midnight UTC time zone. I need to convert them to the present UTC time. I am able to do that for a given row using timedelta but not able to implement that for the entire timestamp column.</p>
<pre><code> # The base of my timestamp is... | 3 | 2016-06-24T19:01:04Z | 38,020,420 | <p>try this:</p>
<pre><code>dif = (datetime.datetime(2010,1,1) - datetime.datetime(1970,1,1)).total_seconds()
sec_shift = 4*60*60
pd.to_datetime(df.timestamp + diff + sec_shift, unit='s')
</code></pre>
<p>demo:</p>
<pre><code>In [29]: pd.to_datetime(df.timestamp + dif + sec_shift, unit='s')
Out[29]:
0 2016-05-25 1... | 4 | 2016-06-24T19:03:18Z | [
"python",
"pandas",
"dataframe"
] |
Convert column of timestamp with a different UTC base to current UTC using Python | 38,020,396 | <p>I have a dataframe with timestamps that are number of seconds since Jan 1,2010 midnight UTC time zone. I need to convert them to the present UTC time. I am able to do that for a given row using timedelta but not able to implement that for the entire timestamp column.</p>
<pre><code> # The base of my timestamp is... | 3 | 2016-06-24T19:01:04Z | 38,020,582 | <p>You can add a Series of Timedeltas to a Timestamp:</p>
<pre><code>df['date'] = pd.Timestamp('2010-1-1')+pd.to_timedelta(df['timestamp'], unit='s')
</code></pre>
<hr>
<p>For example,</p>
<pre><code>import pandas as pd
df = pd.DataFrame({"timestamp":[201852000,201852060,201852120,201852180,201852240],
... | 4 | 2016-06-24T19:14:05Z | [
"python",
"pandas",
"dataframe"
] |
Convert column of timestamp with a different UTC base to current UTC using Python | 38,020,396 | <p>I have a dataframe with timestamps that are number of seconds since Jan 1,2010 midnight UTC time zone. I need to convert them to the present UTC time. I am able to do that for a given row using timedelta but not able to implement that for the entire timestamp column.</p>
<pre><code> # The base of my timestamp is... | 3 | 2016-06-24T19:01:04Z | 38,020,610 | <pre><code>df = pd.DataFrame(range(201851000, 201852000, 100), columns=['seconds'])
df['timedelta'] = df.seconds.apply(lambda x: pd.Timedelta(seconds=x))
df['UpdatedTimestamp'] = df.timedelta + pd.Timestamp('2010-01-01')
df
</code></pre>
<p><a href="http://i.stack.imgur.com/nZLzo.png" rel="nofollow"><img src="http://... | 3 | 2016-06-24T19:16:22Z | [
"python",
"pandas",
"dataframe"
] |
Convert column of timestamp with a different UTC base to current UTC using Python | 38,020,396 | <p>I have a dataframe with timestamps that are number of seconds since Jan 1,2010 midnight UTC time zone. I need to convert them to the present UTC time. I am able to do that for a given row using timedelta but not able to implement that for the entire timestamp column.</p>
<pre><code> # The base of my timestamp is... | 3 | 2016-06-24T19:01:04Z | 38,020,616 | <p>I came up with this solution that works, but if there is a better solution please update. It would be great to find better ways of doing this. </p>
<pre><code> # Calculating the seconds between 1/1/1970 - 1/1/2010
# Adding that to the timestamp column to get the seconds from 1/1/1970
seconds_from_2010= ... | 4 | 2016-06-24T19:16:40Z | [
"python",
"pandas",
"dataframe"
] |
How to make bullet hit target and display either target was hit or missed? | 38,020,415 | <p>So for this project, I have to make a bullet hit a target.
The bullet is shot using degrees to hit the target.
I made the bullet be able to shoot as well as a target being randomly created.
However, everytime I shoot the bullet, it simply just asks to enter another degree
to shoot a bullet. I am ... | 1 | 2016-06-24T19:02:49Z | 38,023,666 | <p>The code keeps asking for a new <code>degrees</code> because it always thinks you miss the target. I have no idea how your current calculation of whether you hit or not is supposed to work, so I don't really know how to fix it directly. But I've come up with two new ways to make the thing function as intended.</p>
... | 0 | 2016-06-25T00:02:25Z | [
"python"
] |
TypeError converting Pandas dataframe to Spark dataframe | 38,020,429 | <p>I have a Pandas dataframe called <code>pdf</code> that is simply four columns of float64s. Here are the first five lines:</p>
<pre><code>pdf[:5]
x1 x2 x3 y
0 9.082060 12.837502 6.484107 10.985202
1 9.715981 14.870818 8.026042 12.815644
2 11.303901 21.286343 7.787188 15.... | 2 | 2016-06-24T19:03:47Z | 38,254,401 | <p>I've successfully reproduced this, and it seems to just be closing the ipython notebook and reopening it. When I spin up a new cluster with nothing but Python 2.7, pip and numpy installed (default in the bootstrap) and install Pandas 0.18.1 using pip.main(), then try to convert it to a Spark dataframe using createDa... | 0 | 2016-07-07T20:08:54Z | [
"python",
"pandas",
"pyspark"
] |
Adding multiple netcdf variables using nco tools | 38,020,436 | <p>Is there a nco operator to create a new variable by adding multiple variables in a single netcdf file? I know you can use ncdiff to subtract, is there anything equaivalent operator for adding?</p>
| 1 | 2016-06-24T19:04:28Z | 38,020,966 | <p>Yes, <a href="http://nco.sourceforge.net/nco.html#ncbo-netCDF-Binary-Operator" rel="nofollow">NCO's ncbo</a> function has subtraction, addition, multiplication, and division capabilities. For adding in specific, you can alternatively call <code>ncadd</code>. From the docs:</p>
<pre><code>Definition: file_3 = file... | 2 | 2016-06-24T19:40:35Z | [
"python",
"netcdf",
"nco"
] |
where does initialization code go for large flask applications | 38,020,477 | <p>I am building a flask application to control GPIO on my raspberry pi. I am using the <a href="http://flask.pocoo.org/docs/0.11/patterns/packages/" rel="nofollow">larger application Flask structure</a> because even though my app isn't huge I very much enjoy having everything in separate files. </p>
<p>One thing I am... | 1 | 2016-06-24T19:06:40Z | 38,023,934 | <p>If you look on github, you can see the convention is usually to do something like put main.py, or app.py to build app, then in another file such as run.py, uwsgi.py, server.py where app is imported in and ran. </p>
| 0 | 2016-06-25T00:50:23Z | [
"python",
"flask"
] |
All possible team rosters algorithm? Similar to knapsack maybe? | 38,020,513 | <p>I have been working on a hobby project for a while that involves finding all possible team rosters given the constraints of a salary cap and player positions while trying to N <code>teams</code> with the maximum projection. This is specifically for fantasy football, but the problem can be more generalized to a maxim... | 2 | 2016-06-24T19:08:37Z | 38,020,721 | <p>This looks like a <a href="https://en.wikipedia.org/wiki/Mathematical_optimization" rel="nofollow">mathematical optimization</a> or <a href="https://en.wikipedia.org/wiki/Constraint_programming" rel="nofollow">constraint programming</a> problem. There are many libraries available to help you solve these types of pr... | 1 | 2016-06-24T19:23:58Z | [
"python",
"algorithm",
"search"
] |
All possible team rosters algorithm? Similar to knapsack maybe? | 38,020,513 | <p>I have been working on a hobby project for a while that involves finding all possible team rosters given the constraints of a salary cap and player positions while trying to N <code>teams</code> with the maximum projection. This is specifically for fantasy football, but the problem can be more generalized to a maxim... | 2 | 2016-06-24T19:08:37Z | 38,039,680 | <p>OK, as requested, here is my MIP model to find the best team. </p>
<p><a href="http://i.stack.imgur.com/faT2o.gif" rel="nofollow"><img src="http://i.stack.imgur.com/faT2o.gif" alt="enter image description here"></a></p>
<p>Note that <code>minpos</code> and <code>maxpos</code> states how many players we want for ea... | 2 | 2016-06-26T14:48:47Z | [
"python",
"algorithm",
"search"
] |
Jupyter: Write a custom magic that modifies the contents of the cell it's in | 38,020,679 | <p>In a Jupyter notebook there are some built-in magics that change the contents of a notebook cell. For example, the <code>%load</code> magic replaces the contents of the current cell with the contents of a file on the file system.</p>
<p>How can I write a custom magic command that does something similar?</p>
<p>Wha... | 8 | 2016-06-24T19:21:00Z | 38,103,336 | <p><strong><em>EDIT</strong>: After a little further digging, I found that the current build of notebook cannot do both.</em></p>
<p>Well, this is a little tricky... Looking at the IPython code, it looks like you need to use <code>set_next_input</code> if you want to replace the cell, and <code>run_cell</code> if you... | 4 | 2016-06-29T15:00:32Z | [
"python",
"ipython-notebook",
"jupyter",
"jupyter-notebook"
] |
SQLAlchemy column with enum using PEP 435 compliant enum produces table creation error | 38,020,681 | <p>I have an enum... defined very similarly to <a href="http://docs.sqlalchemy.org/en/latest/core/type_basics.html#sqlalchemy.types.Enum" rel="nofollow">here</a>.</p>
<p>When I try to create a table using the enum, as in the example, I get an error during table creation. It is a very vague error. Here is code that rep... | 2 | 2016-06-24T19:21:07Z | 38,022,183 | <p><a href="http://docs.sqlalchemy.org/en/latest/changelog/changelog_11.html#change-9d6d98d7acabc8564b8eebb11c28a624" rel="nofollow">PEP-435 enum support</a> is being added in 1.1.</p>
<p>1.1.0b1 was recently released. You can upgrade to 1.1.0b1 but be wary of bugs. Based on release history I would say the stable vers... | 4 | 2016-06-24T21:11:41Z | [
"python",
"orm",
"enums",
"sqlalchemy"
] |
Extract json objects within a list using a list comprehesion | 38,020,723 | <p>I am trying to save specific items from one list in an other list using list comprehesion.</p>
<p>I downloaded several tweets and I saved them in a text file.</p>
<p>I called txt files and saved all items in a list.</p>
<p>This is my code so far:</p>
<pre><code>import json, random
allTweets = []
i = range(1,50)
... | 0 | 2016-06-24T19:24:14Z | 38,021,231 | <p>This works for me (manually made JSON string from your json object):</p>
<pre><code>import json, random
j = """
{
"id": 746029083335680003,
"created_at": "Thu Jun 23 17:16:08 +0000 2016",
"text": "The text",
"user": {
"screen_name": "usr123",
"description": "description",
"s... | 1 | 2016-06-24T20:00:35Z | [
"python",
"json",
"python-3.x",
"twitter",
"list-comprehension"
] |
MultiValueDictKeyError in Django Login and Registration project | 38,020,886 | <p>I'm working on a Login and Registration page, but keep hitting this error:</p>
<pre><code>MultiValueDictKeyError at /pokesregister/
"'name'"
</code></pre>
<p>Below is my views.py code (along with lines commented out form various things I've tried based on google searching):</p>
<pre><code> from django.shortcut... | 0 | 2016-06-24T19:35:26Z | 38,021,126 | <p>You are getting the error because the key you are trying to fetch ('name') is not there. If there is a situation where the user requests the register view without having the 'name' key, then it will throw an error.</p>
<p>Instead of:</p>
<pre><code>request.POST['name']
</code></pre>
<p>Do:</p>
<pre><code>request... | 0 | 2016-06-24T19:52:40Z | [
"python",
"django"
] |
How to install Openface in windows python | 38,020,889 | <p>I am a newbie to Openface. Due to some reasons I want to install Openface in windows with python. It would be great if anyone could guide me through that. I have searched online, but not a single article talks about windows python installation. May be I am asking a very simple question but please help me through thi... | 0 | 2016-06-24T19:35:47Z | 38,162,847 | <p>I'm not aware of OpenFace being used on Windows directly, but please contribute any changes necessary to the repository if you start working on this. I expect there to be a few compatibility issues with Linux-only features.</p>
<p>A workaround solution is to the prebuilt OpenFace Docker container on Windows with a ... | 0 | 2016-07-02T17:38:28Z | [
"python",
"windows",
"installation",
"deep-learning",
"face-recognition"
] |
Scrapy/Python - How deal with missing data? | 38,020,997 | <p>I am writing a scrapy program that captures social network profile URLs from pages (eg facebook, twitter etc).</p>
<p>Some of the pages that I scrape dont have those links on them so the program needs to be able to deal with that.</p>
<p>I have this line of code that finds a Twitter profile link when the link is o... | 0 | 2016-06-24T19:43:09Z | 38,021,213 | <p>Use the <a href="http://doc.scrapy.org/en/latest/topics/selectors.html#id1" rel="nofollow"><code>.extract_first()</code></a> method instead of <code>.extract()[0]</code>. It returns <code>None</code> when there's nothing to extract.</p>
<p>So, instead of:</p>
<pre><code>item['twitterprofileurl'] = startupdetails.x... | 2 | 2016-06-24T19:59:49Z | [
"python",
"scrapy"
] |
The value of None | 38,021,003 | <p>I am learning here... </p>
<p>I'm perplexed by the value of "None". In the following snippet, I'm trying to find all the views where the view parameter called "View Owner" is either None, or != None. </p>
<p>The bellow snippet tells me I have a Views list length of 3548 items and the number of items that != None ... | 0 | 2016-06-24T19:43:39Z | 38,021,019 | <p>Use:</p>
<pre><code>is None
</code></pre>
<p>And</p>
<pre><code>is not None
</code></pre>
<p>instead <code>==</code> and <code>!=</code></p>
| 2 | 2016-06-24T19:45:17Z | [
"python",
"revitpythonshell"
] |
The value of None | 38,021,003 | <p>I am learning here... </p>
<p>I'm perplexed by the value of "None". In the following snippet, I'm trying to find all the views where the view parameter called "View Owner" is either None, or != None. </p>
<p>The bellow snippet tells me I have a Views list length of 3548 items and the number of items that != None ... | 0 | 2016-06-24T19:43:39Z | 38,030,281 | <p>There are a couple of things that should be avoided in the sample code snippet, IMHO:</p>
<ul>
<li><p>Comparing by name should always be avoided, if possible. It is language dependent and less efficient than comparing numbers. In this case, it is probably possible to replace the string comparisons by element id one... | 0 | 2016-06-25T15:58:23Z | [
"python",
"revitpythonshell"
] |
Check if the Cells of a Column Begin With a Specific String [Pandas] | 38,021,060 | <p>First of all, thanks for taking the time of reading this.</p>
<p>I have imported the data from a csv into a table in Pandas.
What I want to do is to create a new column and fill it with different numbers that will depend on the string inside of another column.</p>
<p>So if the first column is something like:</p>
... | 2 | 2016-06-24T19:48:05Z | 38,021,171 | <p>try this:</p>
<pre><code>In [34]: mapping = {
....: 'Horse': 1,
....: 'Chicken': 2,
....: 'Cow': 3,
....: 'Dog': 4,
....: }
In [40]: df['Column2'] = df.Column1.str.replace(r'\d+', '').map(mapping)
In [41]: df
Out[41]:
Column1 Column2
0 Horse1 1
1 Horse2 1
2 Chicken... | 1 | 2016-06-24T19:56:11Z | [
"python",
"pandas"
] |
How come "median" is 2x faster than "mean" using statistics package? | 38,021,111 | <p>This surprises me... To illustrate I've used this small code to calculate mean and median of 1M random numbers:</p>
<pre><code>import numpy as np
import statistics as st
import time
listofrandnum = np.random.rand(1000000,)
t = time.time()
print('mean is:', st.mean(listofrandnum))
print('time to calc mean:', time... | 2 | 2016-06-24T19:51:38Z | 38,021,197 | <p><code>statistics</code> isn't part of NumPy. It's a Python standard library module with a rather different design philosophy; it goes for accuracy at all costs, even for unusual input datatypes and extremely poorly-conditioned input. Performing a sum the way the <code>statistics</code> module does it is <em>really</... | 6 | 2016-06-24T19:58:48Z | [
"python",
"python-3.x",
"numpy",
"statistics"
] |
Mining 7 days worth of Tweets from Twitter API with a certain hashtag using Python Tweepy | 38,021,138 | <p>I am mining 7 days worth of Tweets from the Twitter API using Python, Tweepy, Django, Celery, Django REST framework.</p>
<p>I am sending a request every minute using a celery beat and storing the collected data to a Postgresql database using the Django ORM.</p>
<p>To ensure that the api doesn't keep sending the sa... | 0 | 2016-06-24T19:53:25Z | 38,021,453 | <p>Try this:</p>
<pre><code># Check for the minimum tweet_id and set it as max_id.
# This ensures the API call doesn't keep getting the same tweets.
date_partition = get_seven_day_partition
## Since you're cutting off every seven days, you should know how
## to separate your weeks into seven day sections
max_id = mi... | 0 | 2016-06-24T20:17:24Z | [
"python",
"django",
"orm",
"celery",
"tweepy"
] |
Python Algorithm: search in a list which difference is equal to k | 38,021,217 | <pre><code>number = [5,1,5,3,4]
k = 2
</code></pre>
<p>return the count which the difference is equal to k</p>
<pre><code>cnt = 0
for i in nums:
for j in nums:
if i != j:
if i-j == k:
cnt += 1
return cnt
</code></pre>
<p>You can solve by O(N^2)<br>
Can it be done in a faster way... | 1 | 2016-06-24T19:59:54Z | 38,021,305 | <p>This uses a generator. It is still O(N^2), but should be twice as fast because you only check one side of the pair. For example, if the the numbers are [3, 1, 4], you only check (3-1), (3-4) and (1-4) instead of (3-1), (3-4), (1-3), (1-4), (4-3), (4-1).</p>
<pre><code>>>> sum(1 if abs(x - y) == k else 0 ... | 1 | 2016-06-24T20:06:06Z | [
"python",
"algorithm"
] |
Python Algorithm: search in a list which difference is equal to k | 38,021,217 | <pre><code>number = [5,1,5,3,4]
k = 2
</code></pre>
<p>return the count which the difference is equal to k</p>
<pre><code>cnt = 0
for i in nums:
for j in nums:
if i != j:
if i-j == k:
cnt += 1
return cnt
</code></pre>
<p>You can solve by O(N^2)<br>
Can it be done in a faster way... | 1 | 2016-06-24T19:59:54Z | 38,021,311 | <p>The simple O(n) solution is to create an index using hashtable (<code>set</code> in python work perfectly) and look for a pair for each element in the list.</p>
<p>But since we care for the number of identical items, we should use <code>dict</code> or <code>Counter</code> to track the number of them.</p>
<pre><cod... | 3 | 2016-06-24T20:06:47Z | [
"python",
"algorithm"
] |
Python Algorithm: search in a list which difference is equal to k | 38,021,217 | <pre><code>number = [5,1,5,3,4]
k = 2
</code></pre>
<p>return the count which the difference is equal to k</p>
<pre><code>cnt = 0
for i in nums:
for j in nums:
if i != j:
if i-j == k:
cnt += 1
return cnt
</code></pre>
<p>You can solve by O(N^2)<br>
Can it be done in a faster way... | 1 | 2016-06-24T19:59:54Z | 38,021,531 | <p>There is a simple <code>O(n * log(n))</code> solution with constant memory usage:</p>
<ol>
<li>Sort the list : <code>O(n * log(n))</code></li>
<li>For each element <code>k</code> in the sorted list, search for <code>k + 2</code> in the list using <em>binary search</em>: <code><count of elements which is n> * ... | 1 | 2016-06-24T20:23:02Z | [
"python",
"algorithm"
] |
Python Algorithm: search in a list which difference is equal to k | 38,021,217 | <pre><code>number = [5,1,5,3,4]
k = 2
</code></pre>
<p>return the count which the difference is equal to k</p>
<pre><code>cnt = 0
for i in nums:
for j in nums:
if i != j:
if i-j == k:
cnt += 1
return cnt
</code></pre>
<p>You can solve by O(N^2)<br>
Can it be done in a faster way... | 1 | 2016-06-24T19:59:54Z | 38,030,789 | <p>You could use itertools. Also you could use generator which is more efficient.</p>
<pre><code>import itertools
number = [5,1,5,3,4]
k = 2
for item in itertools.combinations(number,2):
if abs(item[0] - item[1]) == k :
print item
</code></pre>
<p>(Or) </p>
<p>the same code in one line(below):</p>
<pre><c... | 1 | 2016-06-25T16:56:21Z | [
"python",
"algorithm"
] |
python xml.etree - remove node but keep children (assign children to grandparents) | 38,021,298 | <p>In Python, how do I remove a node but keep its children using <code>xml.etree</code> API?</p>
<p>Yes I know there's an <a href="http://stackoverflow.com/questions/15168259/python-xml-remove-some-elements-and-their-children-but-keep-specific-elements-an">answer using lxml</a> but since <code>xml.etree</code> is part... | 1 | 2016-06-24T20:05:40Z | 38,021,894 | <p>Remove this line from your program:</p>
<pre><code> country.remove(country_child)
</code></pre>
<p>The iteration of an <code>xml.etree.ElementTree.Element</code> is essentially passed through to the <code>list</code> of sub-elements. Modifying that list during iteration will yield odd results.</p>
| 1 | 2016-06-24T20:48:15Z | [
"python",
"xml",
"xml-parsing"
] |
AppEngine Python NDB Type Error on .order() | 38,021,393 | <pre><code>@property
def returns_an_int(self):
some_var = do_something_that_returns_int()
if some_var:
return int(some_var)
else:
return 0
</code></pre>
<p>I have a property using the code above, which is supposed to (and does) return an int. (I put the int casting on it to double check) Ho... | 0 | 2016-06-24T20:13:30Z | 38,021,495 | <p>When you query the datastore, you need to query on one of the various <a href="https://cloud.google.com/appengine/docs/python/ndb/entity-property-reference#types" rel="nofollow"><code>ndb.Property</code> types</a>. You are querying on a vanilla python property. This doesn't work because the python property data ne... | 3 | 2016-06-24T20:20:21Z | [
"python",
"google-app-engine",
"models",
"app-engine-ndb"
] |
Python requests login with redirection | 38,021,429 | <p>Here is a site <a href="http://pro.wialon.com/" rel="nofollow">http://pro.wialon.com/</a> where I want to login with python requests module. Login and pass are demo. </p>
<pre><code>import requests
with requests.Session()as c:
url = 'http://pro.wialon.com/'
payload = dict(user='demo',
... | 1 | 2016-06-24T20:16:12Z | 38,021,735 | <p>The post url is incorrect and you are missing form data, you need to also do an initial request, post to the correct url and then get <code>http://pro.wialon.com/service.html</code>:</p>
<pre><code>data = {"user": "demo",
"passw": "demo",
"submit": "Enter",
"lang": "en",
"action": "login"}
head =... | 0 | 2016-06-24T20:36:56Z | [
"python",
"login",
"python-requests"
] |
pyspark: distinctCount - AnalysisException: u"cannot resolve 'x' given input columns: | 38,021,432 | <p>I have the following data frame:</p>
<pre><code>Id | field_A | field_B | field_C | field_D
1 | cat | 12 | black | 11
1 | dog | 128 | white | 19
2 | dog | 35 | yellow | 20
2 | dog | 21 | brown | 4
3 | bird | 10 | blue | 7
4 | cow | 99 | brown | ... | -1 | 2016-06-24T20:16:25Z | 38,022,594 | <p>I got it to work by <strong>withColumnRenamed</strong> instead of <strong>alias</strong></p>
<pre><code>myDF.groupBy(['Id']).agg(countDistinct('field_A')).withColumnRenamed('count(field_A)','distinct_A_count').filter('distinct_A_count = 1').show(20,False)
</code></pre>
| 0 | 2016-06-24T21:51:07Z | [
"python",
"apache-spark",
"pyspark",
"spark-dataframe"
] |
Need help understanding some code (Beginner) | 38,021,505 | <p>I am trying to learn about while and for loops. This function prints out the highest number in a list. But, I'm not entirely sure how it works. Can anyone break down how it works for me. Maybe step by step and/or with a flowchart. I'm struggling and want to learn.</p>
<pre><code>def highest_number(list_tested)... | -5 | 2016-06-24T20:20:54Z | 38,021,571 | <p>One of the most helpful things for understanding new code is going through it step by step:</p>
<p><a href="http://www.pythontutor.com/visualize.html#mode=edit" rel="nofollow">PythonTutor</a> has a visualizer: Paste in your code and hit visualize execution.</p>
<p>What this is going form the first to the last numb... | 4 | 2016-06-24T20:26:09Z | [
"python",
"python-3.x"
] |
Need help understanding some code (Beginner) | 38,021,505 | <p>I am trying to learn about while and for loops. This function prints out the highest number in a list. But, I'm not entirely sure how it works. Can anyone break down how it works for me. Maybe step by step and/or with a flowchart. I'm struggling and want to learn.</p>
<pre><code>def highest_number(list_tested)... | -5 | 2016-06-24T20:20:54Z | 38,021,578 | <p>See my comments for step by step explanation of each line</p>
<pre><code>def highest_number(list_tested): # function defined to take a list
x=list_tested[0] # x is assigned the value of first element of list
for number in list_tested: # iterate over all the elements of input list
if x<number: # i... | 1 | 2016-06-24T20:26:34Z | [
"python",
"python-3.x"
] |
Need help understanding some code (Beginner) | 38,021,505 | <p>I am trying to learn about while and for loops. This function prints out the highest number in a list. But, I'm not entirely sure how it works. Can anyone break down how it works for me. Maybe step by step and/or with a flowchart. I'm struggling and want to learn.</p>
<pre><code>def highest_number(list_tested)... | -5 | 2016-06-24T20:20:54Z | 38,021,688 | <p>Looks like you are new to the programming world. Maybe you should start with some basic concepts, for/while loops are some among which, that would be helpful for you before jumping into something like this.</p>
<p>Here is one of the explanations you may easily find on the Internet <a href="http://www.teamten.com/la... | 0 | 2016-06-24T20:34:21Z | [
"python",
"python-3.x"
] |
How can I parse pexpect in real time? | 38,021,554 | <p>I'm considering <code>pexpect</code> (totally open to alternatives, if there are better ones I'm not aware of) in one of our deploy script wrappers -- but I need a way to read the output in real-time, not only once we've hit the <code>EOF</code>. Since this is a deployment package, used for all environments, we need... | 0 | 2016-06-24T20:24:49Z | 39,287,193 | <p><code>EOF</code> is hit when the child process terminates. To get real time output of the commands being sent and replies received, you can log the output to stdout or a file.</p>
<p>Spawn class of Pexpect has a logfile_read attribute which writes the output of child process to the file specified.
Modifying the cod... | 0 | 2016-09-02T07:57:05Z | [
"python",
"python-2.7",
"pexpect"
] |
javascript to python array translation | 38,021,583 | <p>We are working on a project where we are translating javaScript code into python. Everything is going pretty smoothly, except for this one line of code that has given us errors on multiple translations:</p>
<blockquote>
<p>"primes" is an empty array BTW.</p>
</blockquote>
<p>JavaScript:</p>
<pre><code> var prim... | -1 | 2016-06-24T20:26:46Z | 38,022,000 | <p>Python hasn't a safe get so you should change your code this way:</p>
<pre><code>primes = []
if primes and primes[len(primes) - 1] > 3:
...
</code></pre>
<p>Even better, to get the last of the list you can use <code>primes[-1]</code></p>
<pre><code>primes = []
if primes and primes[-1] > 3:
...
</c... | 4 | 2016-06-24T20:55:27Z | [
"javascript",
"python",
"arrays"
] |
what exactly is .bash_profile.pysave? | 38,021,598 | <p>I just noticed that I have a .bash_profile and a .bash_profile.pysave and I was wondering what the .pysave was, if I can delete it and how/why it came into existence.</p>
| 1 | 2016-06-24T20:27:56Z | 38,021,808 | <p>When python is installed, some installers will modify your <code>.bash_profile</code>. They save your previous version in <code>.bash_profile.pysave</code>.</p>
| 1 | 2016-06-24T20:42:51Z | [
"python",
"bash"
] |
Best non-regex way to remove all characters after and including the first non-digit in Python | 38,021,643 | <p>Assume a string of 5 chars. The title, I think, is clear, but here are some examples:</p>
<pre><code>'716-0' --> '716'
'77820' --> '77820'
</code></pre>
<p>Regex works fine</p>
<pre><code>import re
re.findall(r'\d+', '716-0')[0]
</code></pre>
<p>but how about a good non-regex way?</p>
| 0 | 2016-06-24T20:30:50Z | 38,021,722 | <p>Regex is probably the best way to do it, but if for whatever reason you want to avoid it, you can make use of <a href="https://docs.python.org/3/library/stdtypes.html#str.isdigit" rel="nofollow"><code>str.isdigit()</code></a> and <a href="https://docs.python.org/3/library/itertools.html#itertools.takewhile" rel="nof... | 1 | 2016-06-24T20:36:08Z | [
"python"
] |
Best non-regex way to remove all characters after and including the first non-digit in Python | 38,021,643 | <p>Assume a string of 5 chars. The title, I think, is clear, but here are some examples:</p>
<pre><code>'716-0' --> '716'
'77820' --> '77820'
</code></pre>
<p>Regex works fine</p>
<pre><code>import re
re.findall(r'\d+', '716-0')[0]
</code></pre>
<p>but how about a good non-regex way?</p>
| 0 | 2016-06-24T20:30:50Z | 38,021,781 | <pre><code>def trim(x):
output=[]
for digit in x:
if digit in [str(x) for x in range(10)]:
output.append(digit)
else:
break
return ''.join(output)
</code></pre>
| 0 | 2016-06-24T20:40:44Z | [
"python"
] |
Select date and year only SQLite | 38,021,649 | <p>I have an SQLite database structured like so:</p>
<pre><code>ID Date Time Cost
"1" "2016-05-14" "17:39:35.925973" "1.98"
"2" "2016-05-14" "17:39:54.181083" "2.84"
"3" "2016-05-14" "17:40:26.408492" "2.99"
"4" "2016-05-14" "17:41:28.197353" "3.39"
"25" "2016-05-19" ... | 2 | 2016-06-24T20:31:40Z | 38,022,149 | <p>SQLite doesn't have a format specifier for a 2-digit year. Reference: <a href="https://www.sqlite.org/lang_datefunc.html" rel="nofollow">https://www.sqlite.org/lang_datefunc.html</a></p>
<p>And, as @DanielRoseman mentions: </p>
<ol>
<li>you are mixing up your years and months, and </li>
<li>you're unnecessarily c... | 1 | 2016-06-24T21:08:01Z | [
"python",
"sqlite",
"datetime",
"sum"
] |
How to get a dictionary with keys equal to group members in dataframe and the values to the group ids? | 38,021,656 | <p>I have a dataframe as follwos:</p>
<pre><code> City Name
0 Seattle Alice
1 Seattle Bob
2 Portland Mallory
3 Portland Bob
</code></pre>
<p>I have used df.groupby('City') and for the above example we would have 2 groups, i.e., 1)Seattle 2)Portland. Now I want to get a dictionary ... | -4 | 2016-06-24T20:32:05Z | 38,023,122 | <p>This code will get you a list as the entry in the dictionary for each name:</p>
<pre><code> array = df.data
names = array[:,2] # slice out the names
places = array[:,1] #slice out the places
places = [list(set(places)).index(place) for place in places] #convert the places to ints
pairs = zip(name... | 0 | 2016-06-24T22:47:21Z | [
"python",
"pandas"
] |
Get Certain Tags Within Parent Tag Using Beautifulsoup4 | 38,021,706 | <p>I am using beautifulsoup4 with Python to scrape content from the web, with which I am attempting to extract content from specific html tags, while ignoring others.</p>
<p>I have the following html:</p>
<pre><code><div class="the-one-i-want">
<p>
"random text content here and about"
<... | 1 | 2016-06-24T20:35:08Z | 38,021,917 | <pre><code>h = """<div class="the-one-i-want">
<p>
"random text content here and about"
</p>
<p>
"random text content here and about"
</p>
<p>
"random text content here and about"
</p>
<div class="random-inserted-element-i-... | 2 | 2016-06-24T20:49:34Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
Pandas dataframe to dictionary with value as a list | 38,021,728 | <p>We have the following dataframe df,</p>
<pre><code> 0 1 2 3
0 'a' 'b' 1 2
1 'a' 'c' 2 4
</code></pre>
<p>I want output as</p>
<pre><code>{('a', 'b'): [1, 2], ('a', 'c'): [2, 4]}
</code></pre>
<p>How to use .to_dict() to generate the output?</p>
<p>I tried</p>
<pre><code>df.set_index([0,1])[[2,3]].to_di... | 1 | 2016-06-24T20:36:28Z | 38,021,881 | <p>Try:</p>
<pre><code>{k: v.tolist() for k, v in df.set_index([0, 1]).iterrows()}
{('a', 'b'): [1, 2], ('a', 'c'): [2, 4]}
</code></pre>
| 2 | 2016-06-24T20:47:34Z | [
"python",
"pandas"
] |
Pandas dataframe to dictionary with value as a list | 38,021,728 | <p>We have the following dataframe df,</p>
<pre><code> 0 1 2 3
0 'a' 'b' 1 2
1 'a' 'c' 2 4
</code></pre>
<p>I want output as</p>
<pre><code>{('a', 'b'): [1, 2], ('a', 'c'): [2, 4]}
</code></pre>
<p>How to use .to_dict() to generate the output?</p>
<p>I tried</p>
<pre><code>df.set_index([0,1])[[2,3]].to_di... | 1 | 2016-06-24T20:36:28Z | 38,021,895 | <p>After setting the index, take the transpose and then use <code>to_dict</code> with <code>orient='list'</code>:</p>
<pre><code>df.set_index([0,1]).T.to_dict(orient='list')
</code></pre>
<p>The resulting output:</p>
<pre><code>{('a', 'b'): [1, 2], ('a', 'c'): [2, 4]}
</code></pre>
| 3 | 2016-06-24T20:48:16Z | [
"python",
"pandas"
] |
How do you specify the assumptions/types on the elements of a Function or IndexedBase? | 38,021,866 | <p>If I have a simple variable, I can specify the assumptions or type as follows:</p>
<pre><code>import sympy as sy
k = sy.Symbol('k', integer=True)
assert k.is_integer
assert k.is_real
</code></pre>
<p>What if I want to do the the same for an <a href="http://docs.sympy.org/dev/modules/tensor/indexed.html#sympy.ten... | 1 | 2016-06-24T20:46:33Z | 38,022,009 | <p>The old-style assumptions are implemented in the class constructor of the SymPy object through various mechanisms. This should be implemented for every SymPy class separately. Some classes simply do not have this implementation available and you can't use it.</p>
<p>I suggest to use the new-style assumptions, where... | 1 | 2016-06-24T20:56:14Z | [
"python",
"sympy"
] |
How do you specify the assumptions/types on the elements of a Function or IndexedBase? | 38,021,866 | <p>If I have a simple variable, I can specify the assumptions or type as follows:</p>
<pre><code>import sympy as sy
k = sy.Symbol('k', integer=True)
assert k.is_integer
assert k.is_real
</code></pre>
<p>What if I want to do the the same for an <a href="http://docs.sympy.org/dev/modules/tensor/indexed.html#sympy.ten... | 1 | 2016-06-24T20:46:33Z | 38,025,028 | <p>There's no syntactic sugar for <code>Function</code> or <code>Indexed</code>, but you can still add assumptions by subclassing them. <code>Function('f')</code> creates a subclass of <code>Function</code> called <code>f</code>. You can use</p>
<pre><code>class f(Function):
is_integer = True
</code></pre>
<p>to ... | 0 | 2016-06-25T04:41:47Z | [
"python",
"sympy"
] |
Getting imageitem values from pyqtgraph | 38,021,869 | <p>I am working on my first PyQt program and feel like I am missing something obvious about ImageItems or GraphicsScenes. I have a 2d ImageItem displayed with PyQtGraph using ImageView. My data is a numpy array. When the mouse is hovered over a spot on the image, I am able to get x and y position values, but would a... | 0 | 2016-06-24T20:46:44Z | 38,026,588 | <p>Looking at the <a href="https://github.com/pyqtgraph/pyqtgraph/blob/pyqtgraph-0.9.10/pyqtgraph/imageview/ImageView.py" rel="nofollow">source code</a> of <code>ImageView.setData</code>, it seems that the <code>image</code> member is used to store the data.</p>
<p>Even though it's a public member, it is not a nice ge... | 0 | 2016-06-25T08:36:16Z | [
"python",
"pyqt",
"pyqtgraph"
] |
Accessing item in tuple nested in dictionary python | 38,021,882 | <p>So I'm a little confused about the dictionary this <a href="http://api.rethinkrobotics.com/baxter_interface/html/index.html" rel="nofollow">function</a> returns. (The endpoint_pose function)</p>
<p>It seems to be a dictionary, with nested dictionary or tuple I am not sure. What the function returns is this </p>
<p... | 0 | 2016-06-24T20:47:36Z | 38,022,008 | <p>Assuming that <code>Point</code> is a class (or <code>namedtuple</code> or whatever) with a <code>z</code> attribute (the <code>repr</code> can be deceiving, but usually not like this), you can look up by key, then access attributes normally:</p>
<pre><code>mydict['position'].z
</code></pre>
| 0 | 2016-06-24T20:56:08Z | [
"python",
"dictionary",
"indexing",
"nested",
"tuples"
] |
Accessing item in tuple nested in dictionary python | 38,021,882 | <p>So I'm a little confused about the dictionary this <a href="http://api.rethinkrobotics.com/baxter_interface/html/index.html" rel="nofollow">function</a> returns. (The endpoint_pose function)</p>
<p>It seems to be a dictionary, with nested dictionary or tuple I am not sure. What the function returns is this </p>
<p... | 0 | 2016-06-24T20:47:36Z | 38,022,013 | <p>Your link doesn't actually go to any function (due to the frames), but I'm guessing it's this one you're speaking of:</p>
<p><a href="http://api.rethinkrobotics.com/baxter_interface/html/baxter_interface.limb.Limb-class.html#endpoint_pose" rel="nofollow">http://api.rethinkrobotics.com/baxter_interface/html/baxter_i... | 0 | 2016-06-24T20:56:44Z | [
"python",
"dictionary",
"indexing",
"nested",
"tuples"
] |
Accessing item in tuple nested in dictionary python | 38,021,882 | <p>So I'm a little confused about the dictionary this <a href="http://api.rethinkrobotics.com/baxter_interface/html/index.html" rel="nofollow">function</a> returns. (The endpoint_pose function)</p>
<p>It seems to be a dictionary, with nested dictionary or tuple I am not sure. What the function returns is this </p>
<p... | 0 | 2016-06-24T20:47:36Z | 38,022,021 | <p>What you get as a return is a dictionary of <a href="https://docs.python.org/3.4/library/collections.html#collections.namedtuple" rel="nofollow">namedtuple</a>, so to access the z-element, simply:</p>
<pre><code>>>> from collections import namedtuple
>>>
>>> Point = namedtuple('Point', ['... | 1 | 2016-06-24T20:57:41Z | [
"python",
"dictionary",
"indexing",
"nested",
"tuples"
] |
Accessing item in tuple nested in dictionary python | 38,021,882 | <p>So I'm a little confused about the dictionary this <a href="http://api.rethinkrobotics.com/baxter_interface/html/index.html" rel="nofollow">function</a> returns. (The endpoint_pose function)</p>
<p>It seems to be a dictionary, with nested dictionary or tuple I am not sure. What the function returns is this </p>
<p... | 0 | 2016-06-24T20:47:36Z | 38,022,155 | <p>The result looks like a dictionary with objects. Look at how datetime looks:</p>
<pre><code>>>> import datetime
>>> datetime.date.today()
datetime.date(2016, 6, 24)
</code></pre>
<p>To access variable <strong>z</strong> in the object is a simple dictionary lookup and accessing the attribute:</p>... | 0 | 2016-06-24T21:08:45Z | [
"python",
"dictionary",
"indexing",
"nested",
"tuples"
] |
Export machine learning model | 38,021,937 | <p>I am creating a machine learning algorithm and want to export it.
Suppose i am using scikit learn library and Random Forest algorithm. </p>
<pre><code> modelC=RandomForestClassifier(n_estimators=30)
m=modelC.fit(trainvec,yvec)
</code></pre>
<blockquote>
<p>modelC.model</p>
</blockquote>
<p>How can i export it... | -1 | 2016-06-24T20:51:18Z | 38,021,990 | <p>If you follow the scikit <a href="http://scikit-learn.org/stable/modules/model_persistence.html" rel="nofollow">documentation</a> on model persistence </p>
<pre><code>In [1]: from sklearn.ensemble import RandomForestClassifier
In [2]: from sklearn import datasets
In [3]: from sklearn.externals import joblib
In [4]:... | 2 | 2016-06-24T20:54:55Z | [
"python",
"python-2.7",
"machine-learning",
"scikit-learn"
] |
Open links from txt file in python | 38,022,010 | <p>I would like to ask for help with a rss program. What I'm doing is collecting sites which are containing relevant information for my project and than check if they have rss feeds.
The links are stored in a txt file(one link on each line).
So I have a txt file with full of base urls what are needed to be checked f... | 1 | 2016-06-24T20:56:34Z | 38,022,056 | <p>i guess you can make it by using urllib</p>
<pre><code> import urllib
f = open('test.txt','r')
#considering each url in a new line...
while True:
URL = f.readline()
if not URL:
break
mycontent=urllib.urlopen(URL).read()
</code></pre>
| 0 | 2016-06-24T21:00:33Z | [
"python",
"beautifulsoup",
"urllib2",
"urllib"
] |
Open links from txt file in python | 38,022,010 | <p>I would like to ask for help with a rss program. What I'm doing is collecting sites which are containing relevant information for my project and than check if they have rss feeds.
The links are stored in a txt file(one link on each line).
So I have a txt file with full of base urls what are needed to be checked f... | 1 | 2016-06-24T20:56:34Z | 38,022,063 | <p>Typically you'd do something like this:</p>
<pre><code>with open('links.txt', 'r') as f:
for line in f:
get_rss_feed(line)
</code></pre>
<p>Also, it's a bad idea to define a function with the name <code>open</code> unless you intend to replace the builtin function <code>open</code>.</p>
| 1 | 2016-06-24T21:00:57Z | [
"python",
"beautifulsoup",
"urllib2",
"urllib"
] |
Django Subquery with Scalar Value | 38,022,035 | <p>Is it possible to compare subqueries results with scalar values using Django ORM? I'm having a hard time to convert this:</p>
<pre><code>SELECT payment_subscription.*
FROM payment_subscription payment_subscription
JOIN payment_recurrent payment_recurrent ON payment_subscription.id = payment_recurrent.subscription... | 0 | 2016-06-24T20:58:46Z | 38,022,894 | <pre><code>Subscription.objects.annotate(
max_expiraton_date=Max('transaction__expiration_date')
).filter(
status=1,
recurrent__isnull=False, # [inner] join with recurrent
transaction__status__in=['OK', 'Complete'],
max_expiraton_date=date_value
)
</code></pre>
<p>This produces other SQL query, bu... | 0 | 2016-06-24T22:20:28Z | [
"python",
"mysql",
"django",
"database"
] |
Convert string of list to list | 38,022,075 | <p>I have the list of strings: </p>
<pre><code>['[12 9 15]','[98 12 18]','[56 45 45]']
</code></pre>
<p>and I want to convert it to </p>
<pre><code>[[12,9,15],[98,12,18],[56,45,45]]
</code></pre>
| 3 | 2016-06-24T21:01:46Z | 38,022,159 | <p>You can use <a href="https://docs.python.org/3/library/stdtypes.html#str.split" rel="nofollow"><code>split</code></a> inside a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a> to do this. </p>
<p>As <code>[1 2 3]</code> is not the proper repr... | 6 | 2016-06-24T21:09:24Z | [
"python",
"string",
"list",
"python-2.7"
] |
Convert string of list to list | 38,022,075 | <p>I have the list of strings: </p>
<pre><code>['[12 9 15]','[98 12 18]','[56 45 45]']
</code></pre>
<p>and I want to convert it to </p>
<pre><code>[[12,9,15],[98,12,18],[56,45,45]]
</code></pre>
| 3 | 2016-06-24T21:01:46Z | 38,022,164 | <p>Your strings <code>[12 9 15]</code> aren't formatted like python lists (commas are missing). You've got a couple options depending on how robust your parser needs to be:</p>
<pre><code>import ast
out_list = []
for string_list in list_of_strings:
list_repr = ','.join(string_list.split())
out_list.append(ast... | 2 | 2016-06-24T21:10:06Z | [
"python",
"string",
"list",
"python-2.7"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.