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 |
|---|---|---|---|---|---|---|---|---|---|
stopping condition on gradient value tensorflow | 38,099,074 | <p>I would like to implement a stopping condition based on the value of the gradient of the loss function w.r.t. the weights.
For example, let's say I have something like this:</p>
<pre><code>optimizer = tf.train.AdamOptimizer()
grads_and_vars = optimizer.compute_gradients(a_loss_function)
train_op = optimizer.apply_g... | 1 | 2016-06-29T12:07:59Z | 38,107,270 | <p>Your line <code>output = sess.run([input], feed_dict=some_dict)</code> makes think that you have a little misunderstanding of the <code>sess.run</code> command. What you call <code>[input]</code> is supposed to be a list of tensors that are to be fetched by the <code>sess.run</code> command. Hence, it is an output r... | 1 | 2016-06-29T18:17:34Z | [
"python",
"machine-learning",
"neural-network",
"tensorflow"
] |
Can't find a button 'ctl00' with selenium | 38,099,082 | <p>From this page:</p>
<pre><code>https://permits.losgatosca.gov/CitizenAccess/default.aspx
</code></pre>
<p>I'm trying to push the <strong>'Search Permits'</strong> button under Building Permits.</p>
<p>This is its xpath:</p>
<pre><code>//*[@id="ctl00_PlaceHolderMain_TabDataList_TabsDataList_ctl01_LinksDataList_ct... | 1 | 2016-06-29T12:08:34Z | 38,099,705 | <p>There is a frame with id <code>ACAFrame</code>, you need to switch that frame first as below :-</p>
<pre><code>driver_1.switch_to_frame("ACAFrame")
NEXT_BUTTON_XPATH = '//*[@id="ctl00_PlaceHolderMain_TabDataList_TabsDataList_ctl01_LinksDataList_ctl00_LinkItemUrl"]/span'
button = driver_1.find_element_by_xpath(NEXT_... | 1 | 2016-06-29T12:34:31Z | [
"python",
"selenium"
] |
Python Django - print within a loop, inside view function | 38,099,162 | <p>I'm trying to find a way to print within a loop, inside a view function.</p>
<p>I want to do something like this: </p>
<pre><code>def some_page(request):
for i in range(1, 5):
print("<span>current index: %s</span>") % (i)
</code></pre>
<p>But I need to use HttpResponse, (or render, but fro... | -2 | 2016-06-29T12:11:52Z | 38,099,248 | <p>You can do this:</p>
<pre><code>def some_page(request):
s = ""
for i in range(1, 5):
s = s + "<span>current index: %s</span>" % i
return HttpResponse(s)
</code></pre>
| 1 | 2016-06-29T12:15:29Z | [
"python",
"django"
] |
authenticate function in django using hashed password not the raw one | 38,099,303 | <p>I am working on openedx(which runs on django) and the user will be redirected here from other site and i'm being given the hashed password from there.
Authenticate(username,password) excepts raw password like "dragon" not the hashed one,</p>
<p>So I need to use the authenticate() with the hashed password so that I ... | 1 | 2016-06-29T12:18:11Z | 38,100,197 | <p>You can <a href="https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#writing-an-authentication-backend" rel="nofollow">create a custom authentication backend for django</a> and override its <code>authenticate</code> and <code>get_user</code> method to authenticate using hashed password and username.</p>
... | 1 | 2016-06-29T12:53:47Z | [
"python",
"django",
"authentication",
"hash",
"openedx"
] |
authenticate function in django using hashed password not the raw one | 38,099,303 | <p>I am working on openedx(which runs on django) and the user will be redirected here from other site and i'm being given the hashed password from there.
Authenticate(username,password) excepts raw password like "dragon" not the hashed one,</p>
<p>So I need to use the authenticate() with the hashed password so that I ... | 1 | 2016-06-29T12:18:11Z | 38,100,443 | <p>Open edX uses the <code>ratelimitbackend.backends.RateLimitModelBackend</code> for authentication, as we can see in the <a href="https://github.com/edx/edx-platform/blob/master/lms/envs/common.py#L532" rel="nofollow">settings</a>. This backend requires the un-hashed password for authentication.</p>
<p>If you wish t... | 0 | 2016-06-29T13:04:26Z | [
"python",
"django",
"authentication",
"hash",
"openedx"
] |
Combine words into lines | 38,099,429 | <p>I have text file and need to filter lines that have more than 6 words.
I create the RDD: </p>
<pre><code>my_data = sc.textFile("lines.txt")
</code></pre>
<p>Then i split each line in words:</p>
<pre><code>line_words = my_data.map(lambda x: x.split(' '))
</code></pre>
<p>And apply filter and save results to a fil... | 1 | 2016-06-29T12:22:55Z | 38,099,544 | <p>You can use the <em>string</em>.join(<em>array</em>) function to convert elements of an array to a string , where <em>string</em> is the delimiter:</p>
<pre><code>line = [u'its', u'fun', u'to', u'have', u'fun', u'but', u'you', u'have', u'to', u'know', u'how']
sentence = " ".join(line)
</code></pre>
<p>Is this what... | 1 | 2016-06-29T12:28:10Z | [
"python",
"apache-spark",
"pyspark"
] |
Combine words into lines | 38,099,429 | <p>I have text file and need to filter lines that have more than 6 words.
I create the RDD: </p>
<pre><code>my_data = sc.textFile("lines.txt")
</code></pre>
<p>Then i split each line in words:</p>
<pre><code>line_words = my_data.map(lambda x: x.split(' '))
</code></pre>
<p>And apply filter and save results to a fil... | 1 | 2016-06-29T12:22:55Z | 38,099,609 | <p>Couldn't you save yourself some processing by skipping the split altogether? You are only counting the number of words for the filter (e.g. the number of spaces in the line). </p>
<p>Alternatively, you can do the split and > 6 filter in the same filter step. Since you are not utilizing the individual words, there i... | 1 | 2016-06-29T12:30:47Z | [
"python",
"apache-spark",
"pyspark"
] |
Click on second button (identical buttons) Selenium python | 38,099,438 | <p>I have 2 buttons with the same value and class, they are identical.</p>
<pre><code><input class="button" value="Ir" type="submit">
</code></pre>
<p>I want to click the second one, that it is in <code><div class="smallfont"></code></p>
<p>How can i do that with python Selenium? Thanks ;D</p>
<p><a hre... | 2 | 2016-06-29T12:23:19Z | 38,099,649 | <p>Here is the example from the documentation:</p>
<pre><code><html>
<body>
<form id="loginForm">
<input name="username" type="text" />
<input name="password" type="password" />
<input name="continue" type="submit" value="Login" />
<input name="continue" type="butt... | 2 | 2016-06-29T12:32:20Z | [
"python",
"selenium",
"button"
] |
Click on second button (identical buttons) Selenium python | 38,099,438 | <p>I have 2 buttons with the same value and class, they are identical.</p>
<pre><code><input class="button" value="Ir" type="submit">
</code></pre>
<p>I want to click the second one, that it is in <code><div class="smallfont"></code></p>
<p>How can i do that with python Selenium? Thanks ;D</p>
<p><a hre... | 2 | 2016-06-29T12:23:19Z | 38,099,958 | <p>Try to resolve in below way.</p>
<pre><code>String cssSelectorOfSameElements="input[type='submit'][id='button']";
List<WebElement>a=driver.findElements(By.cssSelector(cssSelectorOfSameElements);
a.get(0).click();
a.get(1).click();
a.get(2).click();
</code></pre>
<p>Now depends on your req... | -1 | 2016-06-29T12:44:44Z | [
"python",
"selenium",
"button"
] |
Click on second button (identical buttons) Selenium python | 38,099,438 | <p>I have 2 buttons with the same value and class, they are identical.</p>
<pre><code><input class="button" value="Ir" type="submit">
</code></pre>
<p>I want to click the second one, that it is in <code><div class="smallfont"></code></p>
<p>How can i do that with python Selenium? Thanks ;D</p>
<p><a hre... | 2 | 2016-06-29T12:23:19Z | 38,100,356 | <p>If I am correct that there is only one submit button in the div of class "smallfont" (the duplicate button is in a different div that does not have that class), then you can simply use a path similar to:</p>
<pre><code>//div[@class='smallfont']/input
</code></pre>
| 1 | 2016-06-29T13:00:15Z | [
"python",
"selenium",
"button"
] |
Click on second button (identical buttons) Selenium python | 38,099,438 | <p>I have 2 buttons with the same value and class, they are identical.</p>
<pre><code><input class="button" value="Ir" type="submit">
</code></pre>
<p>I want to click the second one, that it is in <code><div class="smallfont"></code></p>
<p>How can i do that with python Selenium? Thanks ;D</p>
<p><a hre... | 2 | 2016-06-29T12:23:19Z | 38,100,419 | <p>You can grab references to both elements and just click the second one.</p>
<pre><code>buttons = driver.find_elements_by_css_selector("input.button");
buttons[2].click()
</code></pre>
| 2 | 2016-06-29T13:03:20Z | [
"python",
"selenium",
"button"
] |
Making lists from pandas.dataframe.iloc slice doesn't work while pandas.dataframe.values slice work | 38,099,481 | <p>I want to agregate columns from a dataframe into a new columns</p>
<p>So I used:</p>
<pre><code>newdataframe["agregate1"]=list(df.iloc[:,0:4])
</code></pre>
<p>but it doesn't work.
It returns an ["intensity_x"] list (with x as column index), these strings being the names of my dataframe columns.</p>
<p>While</p>... | 1 | 2016-06-29T12:25:28Z | 38,099,530 | <p>If use:</p>
<pre><code>df1 = df.iloc[:,0:4]
</code></pre>
<p>output is <code>DataFrame</code>.</p>
<p>If:</p>
<pre><code>df2 = df.iloc[0,0:4]
</code></pre>
<p>Output is <code>Series</code> - first <code>row</code> in <code>df</code> and columns <code>1:4</code>.</p>
<p>Sample:</p>
<pre><code>df = pd.DataFrame... | 1 | 2016-06-29T12:27:44Z | [
"python",
"pandas",
"slice"
] |
fixing mac preinstalled python | 38,099,764 | <p>Recently I try to install some package or update the pip, similar error message pops out. </p>
<pre><code>Exception:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip/basecommand.py", line 211, in main
status = self.run(options, args)
... | 1 | 2016-06-29T12:36:30Z | 38,120,897 | <p>The problem was solved simply by running </p>
<pre><code>sudo pip install --upgrade pip
</code></pre>
| 0 | 2016-06-30T10:47:46Z | [
"python",
"osx"
] |
Beautifulsoup can't find text | 38,099,931 | <p>I'm trying to write a scraper in python using urllib and beautiful soup. I have a csv of URLs for news stories, and for ~80% of the pages the scraper works, but when there is a picture at the top of the story the script no longer pulls the time or the body text. I am mostly confused because soup.find and soup.find_a... | 0 | 2016-06-29T12:43:24Z | 38,102,077 | <p>The issue is that there is no <code>class="article"</code> on the website with the picture in it and same with the <code>"class":"time"</code>. Consequently, it seems that you'll have to detect whether there's a picture on the website or not and then if there is a picture, search for the date and text as follows:</p... | 0 | 2016-06-29T14:06:11Z | [
"python",
"python-3.x",
"beautifulsoup",
"urllib"
] |
What to use: threading or multiprocessing or rq or gevents for a database related use case | 38,099,994 | <p>I want to run concurrent processes for this flow: </p>
<p><code>table A</code> has rows and each row has : <code>source</code> and <code>destination</code> connections with <code>start-time</code> and <code>time-interval</code> for querying the <code>source</code> to insert into <code>destination</code>. Now, the <... | 0 | 2016-06-29T12:46:07Z | 38,122,716 | <p>Usually Multi-Thread is faster but it can give problems when you have shared objects/variables. Multiprocess avoid this case with an appropriated synchronization, with semaphores for example.</p>
| 0 | 2016-06-30T12:10:21Z | [
"python",
"multithreading",
"python-2.7",
"python-3.x",
"multiprocessing"
] |
Datetime differences on python | 38,100,107 | <p>I have DateTime, from string I convert them on IS0 format example. <code>ISODate("2016-06-24T09:07:31.097Z")</code> </p>
<p>I want to find the differences between them using python, so I did this:</p>
<pre><code>string_older = "2016-05-18T20:53:43.776456"
string_young = "2016-05-16T20:53:43.776456"
datetime_older... | 0 | 2016-06-29T12:50:12Z | 38,100,248 | <p>Subtracting both <code>datetime</code>s gives you a <a href="https://docs.python.org/2/library/datetime.html#timedelta-objects" rel="nofollow"><code>timedelta</code></a>. To get the difference expressed in seconds, call its <a href="https://docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds" re... | 3 | 2016-06-29T12:56:00Z | [
"python",
"date",
"datetime"
] |
Datetime differences on python | 38,100,107 | <p>I have DateTime, from string I convert them on IS0 format example. <code>ISODate("2016-06-24T09:07:31.097Z")</code> </p>
<p>I want to find the differences between them using python, so I did this:</p>
<pre><code>string_older = "2016-05-18T20:53:43.776456"
string_young = "2016-05-16T20:53:43.776456"
datetime_older... | 0 | 2016-06-29T12:50:12Z | 38,100,449 | <p>I think you need this; there is no need to use time.mktime() as you already have datetimes.</p>
<pre><code>import time, datetime
string_older = "2016-05-18T20:53:43.776456"
string_young = "2016-05-16T20:53:43.776456"
datetime_older = datetime.datetime.strptime(string_older, "%Y-%m- %dT%H:%M:%S.%f")
datetime_young... | 0 | 2016-06-29T13:04:38Z | [
"python",
"date",
"datetime"
] |
Can conversion from a pandas DataFrame to a raw numpy array improve ML performance? | 38,100,153 | <p><strike>A pandas <code>DataFrame</code> has the limitation of fixed integer datatypes (<code>int64</code>). NumPy arrays don't have this limitation; we can use <code>np.int8</code>, for example (we also have different float sizes available).</strike> (Limitation no longer exists.)</p>
<p><strong>Will scikit-learn p... | 3 | 2016-06-29T12:52:03Z | 38,101,366 | <p>The documentation for RandomForestRegressor states that the input samples will be converted to <code>dtype=np.float32</code> internally.</p>
<hr>
<p><em>Below is the original answer, which addresses the issue of using custom <code>numpy</code> types in Pandas (the struck-through part of the question)</em></p>
<p>... | 2 | 2016-06-29T13:40:31Z | [
"python",
"performance",
"numpy",
"pandas",
"scikit-learn"
] |
how to make a null query selecting all the items | 38,100,191 | <p>I really like the <code>query</code> method. What is the <code>null</code> query that select all the items? I have tried <code>df.query("True")</code>, but it doesn't work.</p>
<p>The only thing I have found to work is <code>df.query("index == 0 | index != 0")</code>.</p>
<p>Why "True" is not working, it is a pred... | 0 | 2016-06-29T12:53:34Z | 38,100,612 | <p>For me works:</p>
<pre><code>df.query("index")
</code></pre>
<p>Sample:</p>
<pre><code>df = pd.DataFrame({'A':[1,2,3],
'B':[4,5,6]},
index=[-1,4,5])
print (df)
A B
-1 1 4
4 2 5
5 3 6
a = df.query("index")
print (a)
A B
-1 1 4
4 2 5
5 3 6
</code></p... | 1 | 2016-06-29T13:10:35Z | [
"python",
"pandas",
"indexing",
"dataframe"
] |
Generate data label with barcode(html or jpg or pdf) and print it (now barcode does not generate) | 38,100,239 | <p>Trying to solve a problem linked to bar-codes in html. What i need to do is to create a template of label with bar-code in it and send to printer. I choosed to use html language to create that template with input data. I could get that html and it looks like this in picture.
<a href="http://i.stack.imgur.com/QEUCA.... | 0 | 2016-06-29T12:55:22Z | 38,286,464 | <p>Check out <a href="https://github.com/libretees/itemize" rel="nofollow">this project</a>, which uses <code>jinja2</code>, <code>z3c.rml</code>, and <code>reportlab</code> to generate PDFs with barcodes on them. All of these libraries can accomplish what you're trying to do, and you can send labels to the printer wit... | 0 | 2016-07-09T21:20:41Z | [
"python",
"html",
"pdf",
"printing"
] |
Generate data label with barcode(html or jpg or pdf) and print it (now barcode does not generate) | 38,100,239 | <p>Trying to solve a problem linked to bar-codes in html. What i need to do is to create a template of label with bar-code in it and send to printer. I choosed to use html language to create that template with input data. I could get that html and it looks like this in picture.
<a href="http://i.stack.imgur.com/QEUCA.... | 0 | 2016-06-29T12:55:22Z | 38,507,014 | <p>ReportLab is very good in this case. I am not sure where I found out this code. But it really helped me.</p>
<pre><code>from reportlab.graphics.barcode import code39, code128, code93
from reportlab.graphics.barcode import eanbc, qr, usps
from reportlab.graphics.shapes import Drawing
from reportlab.lib.pagesizes imp... | 0 | 2016-07-21T14:29:51Z | [
"python",
"html",
"pdf",
"printing"
] |
Some emojis (e.g. â) have two unicode, u'\u2601' and u'\u2601\ufe0f'. What does u'\ufe0f' mean? Is it the same if I delete it? | 38,100,329 | <p>I'm writing a python program to judge emoji with a collected emoji unicode set. During the test, I found that one emoji,take <code>â</code> as an example, has two unicode, <code>u'\u2601'</code> and <code>u'\u2601\ufe0f'</code>, what does <code>\ufe0f</code> mean? Is it the same if I delete it? </p>
| 8 | 2016-06-29T12:59:26Z | 38,100,803 | <p>In Unicode the value <code>U+FE0F</code> is called a <a href="https://en.wikipedia.org/wiki/Variation_Selectors_(Unicode_block)" rel="nofollow">variation selector</a>. The variation selector in the case of emoji is to tell the system rendering the character how it should treat the value. That is, whether it should b... | 2 | 2016-06-29T13:19:09Z | [
"python",
"emoji",
"python-unicode"
] |
Some emojis (e.g. â) have two unicode, u'\u2601' and u'\u2601\ufe0f'. What does u'\ufe0f' mean? Is it the same if I delete it? | 38,100,329 | <p>I'm writing a python program to judge emoji with a collected emoji unicode set. During the test, I found that one emoji,take <code>â</code> as an example, has two unicode, <code>u'\u2601'</code> and <code>u'\u2601\ufe0f'</code>, what does <code>\ufe0f</code> mean? Is it the same if I delete it? </p>
| 8 | 2016-06-29T12:59:26Z | 38,100,927 | <p>That's the <a href="https://en.m.wikipedia.org/wiki/Variant_form_(Unicode)">Variant Form</a>, which provides more information for those displays, that are capable of displaying with colour and other things.</p>
<p><img src="https://mobiforge.com/files/emoji-unicode-tables.png" alt=""></p>
<p><a href="http://unicod... | 6 | 2016-06-29T13:24:12Z | [
"python",
"emoji",
"python-unicode"
] |
Python open FTP url and write to file | 38,100,380 | <p>How can I open and FTP url and download it into a file. What I'm trying looks something like this:</p>
<pre><code>from contextlib import closing
from urllib.request import urlopen
url = 'ftp://whatever.com/file.txt'
target_path = 'file.txt'
with closing(urlopen(url)) as source:
with open(target_path, 'wb') as... | 1 | 2016-06-29T13:01:38Z | 38,112,420 | <p>The <code>write</code> requires object with buffer interface in particular <code>bytes</code>, but the <code>source</code> is actually <code>BufferedReader</code> (or <code>HTTPResonse</code> if http). To get bytes you need to call <a href="https://docs.python.org/3/library/io.html#io.BufferedReader.read" rel="nofol... | 0 | 2016-06-30T01:10:54Z | [
"python",
"python-3.x",
"ftp"
] |
Separating 3-d array into 2-d arrays along the respective columns | 38,100,402 | <pre><code>temp1 = tempObj[0][0]
temp2 = tempObj[0][1]
if len(tempObj) > 1:
for i in range(1, len(tempObj)):
temp1 = np.vstack((temp1, tempObj[i][0]))
temp2 = np.vstack((temp2, tempObj[i][1]))
</code></pre>
<p>The code is in Python. In the above code, I am trying to separate the numpy 3-d array (tempObj... | 0 | 2016-06-29T13:02:40Z | 38,130,994 | <p>use <code>tempObj[:, 0, :]</code> and <code>tempObj[:, 1, :]</code>. here is an example:</p>
<pre><code>import numpy as np
tempObj = np.array([
[
[1,5], [2,7], [3,8], [4,4],
[6, 5], [4, 7], [13, 8], [9, 4]
],
[
[21,25], [22,72], [32,82], [34,43],
[64, 54], [44, 74], [144... | 0 | 2016-06-30T18:44:30Z | [
"python",
"arrays",
"numpy",
"matrix"
] |
django __init__.py file not executing pygame code | 38,100,425 | <p>I'm currently developing a website using django that stores the IP address of people who access the site in a database. The idea is, that every week at midnight the website completes a traceroute on every item in the database and then maps the geographical location of each hop to the destination onto a map using pyg... | -1 | 2016-06-29T13:03:44Z | 38,117,821 | <p>Code at a module top level (whether it's a package's <code>__init__.py</code> or just any regular module) is only executed once per process on the first import of this module. Since Django is served using long-running processes, this code will only get executed when a new process is started.</p>
<p>The simplest sol... | 0 | 2016-06-30T08:31:40Z | [
"python"
] |
Re-write write-protected file | 38,100,441 | <p>Every 4 hours files are updated with new information if needed - i.e. if any new information has been processed for that particular file (files correspond to people).</p>
<p>I'm running this command to convert my .stp files (those being updated every 4 hours) to .xml files.</p>
<pre><code>rule convert_waveform_stp... | 0 | 2016-06-29T13:04:21Z | 38,100,672 | <p>take a look at the os standard library package:</p>
<p><a href="https://docs.python.org/3.5/library/os.html?highlight=chmod#os.chmod" rel="nofollow">https://docs.python.org/3.5/library/os.html?highlight=chmod#os.chmod</a> </p>
<p>It allows for chmod with the following caveat:</p>
<blockquote>
<p>Although Windo... | 1 | 2016-06-29T13:12:38Z | [
"python",
"linux",
"bash",
"snakemake"
] |
Alternate apporach for using a flag in python | 38,100,468 | <p>What is the best/alternate pythonic way for the code below,</p>
<pre><code> li=["Header",1,2,3,4,5]
l=0
for i in li:
if l == 0:
.....
l += 1
else:
....
</code></pre>
| 0 | 2016-06-29T13:05:39Z | 38,100,543 | <p>You can replace:</p>
<pre><code> l=0
for i in li:
if l ==0:
frobnosticate(i)
l+= 1
else:
twiddle(i)
</code></pre>
<p>With:</p>
<pre><code>#do something with header outside the loop
frobnosticate(li[0])
#loop over everything but the first element
for i in li[1:]:
twiddle(i)
</code... | 3 | 2016-06-29T13:08:31Z | [
"python"
] |
Alternate apporach for using a flag in python | 38,100,468 | <p>What is the best/alternate pythonic way for the code below,</p>
<pre><code> li=["Header",1,2,3,4,5]
l=0
for i in li:
if l == 0:
.....
l += 1
else:
....
</code></pre>
| 0 | 2016-06-29T13:05:39Z | 38,100,553 | <pre><code>li=["Header",1,2,3,4,5]
do_stuff(li[0]) # first ....
for i in li[1:]:
normal_stuff(i) # second ...
</code></pre>
<p>This will deal with header first and then iterate through rest of list.</p>
| 2 | 2016-06-29T13:08:50Z | [
"python"
] |
Alternate apporach for using a flag in python | 38,100,468 | <p>What is the best/alternate pythonic way for the code below,</p>
<pre><code> li=["Header",1,2,3,4,5]
l=0
for i in li:
if l == 0:
.....
l += 1
else:
....
</code></pre>
| 0 | 2016-06-29T13:05:39Z | 38,101,003 | <p>Accessing such pattern of elements using slicing is good enough. However, if data type in your list is not fixed/known, you may also use dictionary to redirect element to specified function:</p>
<pre><code>def access_string_element(string):
....
def access_integer_element(integer):
....
access_table = dict... | 0 | 2016-06-29T13:26:38Z | [
"python"
] |
Django - model and serializer class, the best way to do | 38,100,539 | <p>firstly let me explain the situation. I have a model that basically have a title and a TextField that will save a json: </p>
<pre><code>class Content(UUIDObject):
title = models.CharField(_(u"Title"), max_length=300)
custom_fields_json = models.TextField(_(u"Settings"))
</code></pre>
<p>To create this json... | 0 | 2016-06-29T13:08:18Z | 38,101,046 | <p>Use the ModelSerializer:</p>
<pre><code>class ConfigSerializer(serializers.ModelSerializer):
class Meta:
model = Content
fields = ('title', 'custom_fields_json')
</code></pre>
<p>The serializer can give you a dict. Also read about ModelViewSets in django rest framework, they can significally mi... | 0 | 2016-06-29T13:28:28Z | [
"python",
"django",
"serialization"
] |
NameError: name 'num1 is not defined | 38,100,541 | <pre><code>line 24, in <module>
if not num1.isdigit():
NameError: name 'num1' is not defined
>>>
</code></pre>
<p>that's the error that's being displayed, and I believe this is the section causing it(ofc I had to put parentheses <3):</p>
<pre><code>def main1(self):
num1 = input("Enter a num... | -1 | 2016-06-29T13:08:21Z | 38,100,648 | <p>Your conditionals are not indented properly. They aren't inside the function definitions, so they will execute right away, before <code>num1 = ...</code> ever gets a chance to run.</p>
<p>Try:</p>
<pre><code>def main1(self):
num1 = input("Enter a number: ")
if not num1.isdigit():
print("Please ent... | 1 | 2016-06-29T13:11:41Z | [
"python",
"python-3.x"
] |
NameError: name 'num1 is not defined | 38,100,541 | <pre><code>line 24, in <module>
if not num1.isdigit():
NameError: name 'num1' is not defined
>>>
</code></pre>
<p>that's the error that's being displayed, and I believe this is the section causing it(ofc I had to put parentheses <3):</p>
<pre><code>def main1(self):
num1 = input("Enter a num... | -1 | 2016-06-29T13:08:21Z | 38,100,654 | <p>Your num1 has scope local to the function, so if you want to use it you have to indent properly:</p>
<pre><code>def main1(self):
num1 = input("Enter a number: ")
if not num1.isdigit():
print("Please enter a valid number")
main1()
</code></pre>
<p>Or declare it outside the function</p>
| 1 | 2016-06-29T13:11:59Z | [
"python",
"python-3.x"
] |
TensorFlow (Mac OS X) installation: URLError | 38,100,681 | <p><strong>OS X version:</strong> 10.11.5 (El Capitan)</p>
<p><strong>TensorFlow version:</strong> 9.0</p>
<p>After installing pip, I proceeded to install TensorFlow following the instructions under "Pip installation" from <a href="https://www.tensorflow.org/versions/r0.8/get_started/os_setup.html#pip-installation" r... | 1 | 2016-06-29T13:13:02Z | 38,155,674 | <p>I found this <a href="http://stackoverflow.com/questions/34513784/urlopen-error-errno-1-ssl-c510-error14077417ssl">post</a> from Stackoverflow. The accepted answer suggested the cause of "urlopen error" may be the older version of python. After updating python from 2.7.5 to 2.7.12, the problem is solved.</p>
| 0 | 2016-07-02T01:33:01Z | [
"python",
"osx",
"tensorflow"
] |
python shutil.copyfile: retrieve an overwritten copy | 38,100,729 | <p>I have accidentally overwritten my file using shutil.copyfile; is there any way to retrieve a previous copy? (I did not use anything like git/time machine/etc.)
thanks!</p>
| 0 | 2016-06-29T13:15:24Z | 38,100,870 | <p>shutil.copyfile requires a source and a destination file. According to the standard library documentation, </p>
<p><a href="https://docs.python.org/3.5/library/shutil.html" rel="nofollow">https://docs.python.org/3.5/library/shutil.html</a></p>
<blockquote>
<p>If src and dst specify the same file, SameFileError ... | 0 | 2016-06-29T13:21:51Z | [
"python",
"shutil"
] |
python shutil.copyfile: retrieve an overwritten copy | 38,100,729 | <p>I have accidentally overwritten my file using shutil.copyfile; is there any way to retrieve a previous copy? (I did not use anything like git/time machine/etc.)
thanks!</p>
| 0 | 2016-06-29T13:15:24Z | 38,100,982 | <p>As the <a href="https://docs.python.org/2/library/shutil.html#shutil.copyfile" rel="nofollow">docs</a>:</p>
<blockquote>
<p>shutil.copyfile(src, dst) </p>
<p>Copy the contents (no metadata) of the file
named src to a file named dst. dst must be the complete target file
name; look at shutil.copy() for a c... | 0 | 2016-06-29T13:26:06Z | [
"python",
"shutil"
] |
Job status in Airflow | 38,100,914 | <p>I have created a DAG with 3 tasks. One of the task failed so in airflow UI the job is shown as failed. But when I do a backfill of the previous tasks. They now succedd but the status of the JOB still remains unchanged it still shows failed even though the individual tasks have succeeded. Am I missing out something?<... | 0 | 2016-06-29T13:23:35Z | 38,912,582 | <p><code>backfill</code> in airflow doesn't work similarly to the scheduler runs. The <code>backfill</code> command doesn't create dag runs but simply queues the tasks of the dag. The scheduler however creates dag runs in the db and uses them to schedule tasks. Therefore, when the <code>backfill</code> is done, no actu... | 0 | 2016-08-12T07:44:24Z | [
"python",
"airflow"
] |
How do I stop the threads once I found my target? | 38,100,921 | <p>So I wrote a python that will find what the pin the users inputs, everything works fine except one thing, and that's that the script won't exist once the pin is found. Is there a why I can kill all of the other threads once I found the pin?</p>
<pre><code>#!/usr/bin/env python
#
#
#
from threading import Thread
fr... | 1 | 2016-06-29T13:23:52Z | 38,101,277 | <p>You can't simply terminate them. However you can ask to stop. Please see example:</p>
<pre><code>from threading import Thread
from random import randint
from time import sleep
from sys import exit
from os import system
system('clear');sleep(0.7)
Pin = int(raw_input('Enter a pin: '))
terminateAll = false
def Up... | 1 | 2016-06-29T13:37:17Z | [
"python",
"multithreading",
"python-2.7",
"python-3.x"
] |
How do I stop the threads once I found my target? | 38,100,921 | <p>So I wrote a python that will find what the pin the users inputs, everything works fine except one thing, and that's that the script won't exist once the pin is found. Is there a why I can kill all of the other threads once I found the pin?</p>
<pre><code>#!/usr/bin/env python
#
#
#
from threading import Thread
fr... | 1 | 2016-06-29T13:23:52Z | 38,101,942 | <p>All you need to do is make the thread objects <a href="http://stackoverflow.com/questions/190010/daemon-threads-explanation">daemons</a> by setting their <a href="https://docs.python.org/2/library/threading.html#threading.Thread.daemon" rel="nofollow"><code>daemon</code></a> to attribute to <code>True</code> <em>bef... | 0 | 2016-06-29T14:01:32Z | [
"python",
"multithreading",
"python-2.7",
"python-3.x"
] |
Replace cells in row if condition met | 38,100,998 | <p>Is there a way to for Less, Middle Greater columns. If it is greater than 0 to replace the ROW with 1. So the top row would become?</p>
<pre><code> Conc Less Middle Greater
Date
2005-03-02 00:00 10.3 0.000000 1 1
</code></pre>
<p... | 1 | 2016-06-29T13:26:22Z | 38,101,128 | <p>You can use <code>loc</code> with boolean condition:</p>
<pre><code>In [250]:
df.loc[df['Less'] > 0, 'Less'] = 1
df
Out[250]:
Conc Less Middle Greater
Date
2005-03-02 00:00:00 10.3 0.0 0.083333 0.916667
2005-03-02 01:00:00 14.1 0.... | 1 | 2016-06-29T13:31:11Z | [
"python",
"pandas",
"dataframe"
] |
Replace cells in row if condition met | 38,100,998 | <p>Is there a way to for Less, Middle Greater columns. If it is greater than 0 to replace the ROW with 1. So the top row would become?</p>
<pre><code> Conc Less Middle Greater
Date
2005-03-02 00:00 10.3 0.000000 1 1
</code></pre>
<p... | 1 | 2016-06-29T13:26:22Z | 38,104,999 | <p>To do them all at once:</p>
<pre><code>columns = ['Less', 'Middle', 'Greater']
df[columns] = np.where(df[columns] >0, 1 ,0)
</code></pre>
<p>Or to do it individually (Note double brackets for selecting columns):</p>
<pre><code>df[['Less']] = np.where(df[['Less']] >0, 1 ,0)
df[['Middle']] = np.where(df[['Mid... | 0 | 2016-06-29T16:12:50Z | [
"python",
"pandas",
"dataframe"
] |
Changing multiple column names but not all of them - Panda Python | 38,101,009 | <p>I would like to know if there is a function to change specific column names but without selecting a specific name or without changing all of them. </p>
<p>I have the code: </p>
<pre><code>df=df.rename(columns = {'nameofacolumn':'newname'})
</code></pre>
<p>But with it i have to manually change each one of them wr... | 1 | 2016-06-29T13:26:49Z | 38,101,084 | <p>You can use a <code>dict</code> comprehension and pass this to <code>rename</code>:</p>
<pre><code>In [246]:
df = pd.DataFrame(columns=list('abc'))
new_cols=['d','e']
df.rename(columns=dict(zip(df.columns[1:], new_cols)),inplace=True)
df
Out[246]:
Empty DataFrame
Columns: [a, d, e]
Index: []
</code></pre>
<p>It a... | 1 | 2016-06-29T13:29:55Z | [
"python",
"pandas",
"dataframe"
] |
Changing multiple column names but not all of them - Panda Python | 38,101,009 | <p>I would like to know if there is a function to change specific column names but without selecting a specific name or without changing all of them. </p>
<p>I have the code: </p>
<pre><code>df=df.rename(columns = {'nameofacolumn':'newname'})
</code></pre>
<p>But with it i have to manually change each one of them wr... | 1 | 2016-06-29T13:26:49Z | 38,101,272 | <p>You should be able to reference the columns by index using ..df.columns[index]</p>
<pre><code>>> temp = pd.DataFrame(np.random.randn(10, 5),columns=['a', 'b', 'c', 'd', 'e'])
>> print(temp.columns[0])
a
>> print(temp.columns[1])
b
</code></pre>
<p>So to change the value of specific column... | 0 | 2016-06-29T13:37:10Z | [
"python",
"pandas",
"dataframe"
] |
Changing multiple column names but not all of them - Panda Python | 38,101,009 | <p>I would like to know if there is a function to change specific column names but without selecting a specific name or without changing all of them. </p>
<p>I have the code: </p>
<pre><code>df=df.rename(columns = {'nameofacolumn':'newname'})
</code></pre>
<p>But with it i have to manually change each one of them wr... | 1 | 2016-06-29T13:26:49Z | 38,102,366 | <p>say you have a dictionary of the new column names and the name of the column they should replace:</p>
<pre><code>df.rename(columns={'old_col':'new_col', 'old_col_2':'new_col_2'}, inplace=True)
</code></pre>
<p>But, if you don't have that, and you only have the indices, you can do this:</p>
<pre><code>column_indic... | 1 | 2016-06-29T14:17:49Z | [
"python",
"pandas",
"dataframe"
] |
How to write output to pandas | 38,101,103 | <p>So the output of a short little iteration of an xml file I did looks like this: </p>
<pre><code>{'LegalNm': 'LAUNCH ANGELS MANAGEMENT COMPANY, LLC', 'SECRgnCD': 'BRO', 'SECNb': '802-79280', 'FirmCrdNb': '170562', 'BusNm': 'LAUNCH ANGELS'}
{'LegalNm': 'JACOBSEN CAPITAL MANAGEMENT, LLC', 'SECRgnCD': 'DRO', 'SECNb'... | 0 | 2016-06-29T13:30:27Z | 38,101,394 | <p>You can create a data frame out of the dictionary and then concatenate them:</p>
<pre><code>import pandas as pd
adf = pd.DataFrame(a, index = [0])
bdf = pd.DataFrame(b, index = [1])
pd.concat([adf, bdf], axis = 0)
# BusNm FirmCrdNb LegalNm SECNb SECRgnCD
# 0 LAUNCH ANGELS 170562 LAUNCH ANGELS MANAGEMENT COM... | 1 | 2016-06-29T13:41:23Z | [
"python",
"xml",
"python-3.x",
"pandas"
] |
pexpect sometimes hit, sometimes fails and exit on timeout | 38,101,246 | <p>I'm writing a small automation program to connect through ssh to a remote server, activate a PERL script and interact with the script (that generate menus for the user to choose from).
I have a user predefined list of responses, and I've gone through the PERL script and jotted down the menus prompts in order to use ... | 0 | 2016-06-29T13:35:59Z | 38,121,305 | <p>the problem was <code>child.sendline('\n')</code>, the program expected and enter key pressed, but going through the logs closely i saw that in the automation log, i got two newlines, while in the normal output, i had one newline.</p>
<p>it fucked up with the rest of the flow after that and that's why i got weird n... | 1 | 2016-06-30T11:05:02Z | [
"python",
"python-2.7",
"pexpect"
] |
Reading .fods file throwing NotImplementedError | 38,101,259 | <p>I want to open, read and modify a <code>.fods</code> file using <code>pyexcel_ods</code>:</p>
<pre><code>from pyexcel_ods import get_data
codebook_fods = get_data("myfile.fods")
</code></pre>
<p>But I'm getting just a <code>NotImplementedError</code> here.</p>
<p>Is there a way to do this in Python? </p>
| 0 | 2016-06-29T13:36:30Z | 38,101,438 | <p>There is no documentation regarding this package saying it support the <code>.fods</code> file extention. It is probably, as the error means, not implemented yet.</p>
<p>You can read more about it <a href="http://pythonhosted.org/pyexcel-ods/" rel="nofollow">here</a>.</p>
<p>As of what I know, there is no python i... | 0 | 2016-06-29T13:43:03Z | [
"python",
"pyexcel"
] |
Python Dict to numpy multidimensional array | 38,101,292 | <p>I have a python dictionary with keys <code>(0,1,2....n)</code> with each key holding the location co-ordinates in a tuple such as</p>
<pre><code>{0:(x1,y1), 1:(x2,y2), 2:(x3,y3), ....., n-1:(xn,yn)}
</code></pre>
<p>I want to create a multidimensional array like</p>
<pre><code>coordinates= np.array([
[x1, ... | 0 | 2016-06-29T13:37:51Z | 38,101,341 | <p>If you're using python 3.x you should cast explicitly to <code>list</code> as the <code>values()</code> method of <code>dict</code> will return a <code>dict_values</code> object. </p>
<p>You should do:</p>
<pre><code>array = numpy.array(list(vehPositions.values()))
</code></pre>
<p>To create your list of lists f... | 3 | 2016-06-29T13:39:31Z | [
"python",
"arrays",
"numpy",
"multidimensional-array"
] |
Python package for dynamic Monte Carlo / Gillespie algorithm | 38,101,374 | <p>I am working on a model describing a protein. Molecule may be found in few states, transitions from one state to another are described by matrix containing transition rates. Model can be resolved as set of ordinary differential equations giving nice numeric results (starting from adjacency matrix -> transition rate ... | -1 | 2016-06-29T13:40:49Z | 38,101,481 | <p>You could just try using the <code>random</code> module and perform the Monte Carlo simulation yourself, using a random float for the values in your initial adjacency matrix. Just be sure to randomly select a number within the accepted range of what your matrix can take. </p>
<p>To iterate over the simulation, use ... | 0 | 2016-06-29T13:44:42Z | [
"python",
"statistics",
"bioinformatics",
"modeling",
"montecarlo"
] |
Python package for dynamic Monte Carlo / Gillespie algorithm | 38,101,374 | <p>I am working on a model describing a protein. Molecule may be found in few states, transitions from one state to another are described by matrix containing transition rates. Model can be resolved as set of ordinary differential equations giving nice numeric results (starting from adjacency matrix -> transition rate ... | -1 | 2016-06-29T13:40:49Z | 38,101,600 | <p>Beside working with the <code>random</code> module as proposed by @PeterWang and create the matrices yourself, alternatively you can use the <code>numpy</code> module, which also provides random sampling. This way you can create random numbers in any matrix dimensions you prefer. Especially regarding your further ta... | 0 | 2016-06-29T13:49:23Z | [
"python",
"statistics",
"bioinformatics",
"modeling",
"montecarlo"
] |
Yampy import error: no module named 'authenticator' | 38,101,382 | <p><strong>TL;DR</strong>: Yampy uses relative imports... is there some setting I can change that would make it work as-is (without having to refactor every <code>import</code> in the project)?</p>
<hr>
<p>Windows 7, Python 3.4.3, PyCharm 2016.1.4, Yampy 1.0</p>
<p>Should be fairly simple question -- hoping someone ... | 1 | 2016-06-29T13:41:12Z | 38,106,077 | <p>Should have checked GitHub first: there is an <a href="https://github.com/yammer/yam-python/issues/22?_pjax=%23js-repo-pjax-container" rel="nofollow">open issue</a> about this that has been open since Feb 2015. Apparently the project is in Python 2. Going to try forking and updating to Python 3..</p>
<hr>
<p><stro... | 0 | 2016-06-29T17:09:39Z | [
"python",
"pip",
"python-3.4",
"python-import",
"yammer"
] |
Python creating matrix using if condition on indices : incorrect result | 38,101,404 | <p>I have the following code where I have been trying to create a tridiagonal matrix <code>x</code> using <code>if</code>-conditions. </p>
<pre><code>#!/usr/bin/env python
# import useful modules
import numpy as np
N=5
x=np.identity(N)
#x=np.zeros((N,N))
print x
# Construct NxN matrix
for i in range(N):
for ... | 0 | 2016-06-29T13:41:47Z | 38,101,510 | <p><code>elif j-1==1:</code> should be <code>elif j-i==1:</code>.</p>
<p>And no, lists/arrays etc. are always indexed from <code>0</code>.</p>
| 1 | 2016-06-29T13:45:32Z | [
"python",
"arrays",
"matrix"
] |
Python creating matrix using if condition on indices : incorrect result | 38,101,404 | <p>I have the following code where I have been trying to create a tridiagonal matrix <code>x</code> using <code>if</code>-conditions. </p>
<pre><code>#!/usr/bin/env python
# import useful modules
import numpy as np
N=5
x=np.identity(N)
#x=np.zeros((N,N))
print x
# Construct NxN matrix
for i in range(N):
for ... | 0 | 2016-06-29T13:41:47Z | 38,103,828 | <p>As for the bonus question, <strong>the first element of a sequence in Python has always the index 0</strong>. However, if for some particular reason (for example to prevent off-by-one errors) you wish to count the elements of a sequence from a value other than 0, you could use the built-in function <a href="https://... | 1 | 2016-06-29T15:21:34Z | [
"python",
"arrays",
"matrix"
] |
Vectorization: Not a valid collection | 38,101,460 | <p>I wanna vectorize a txt file containing my training corpus for the OneClassSVM classifier. For that I'm using CountVectorizer from the scikit-learn library.
Here's below my code: </p>
<pre><code>def file_to_corpse(file_name, stop_words):
array_file = []
with open(file_name) as fd:
corp = fd.readlin... | 1 | 2016-06-29T13:44:03Z | 38,102,681 | <p>If you look at the source, you can find it <a href="https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/validation.py" rel="nofollow">here</a> for instance, you can find that it checks for this condition to be true (x being your array)</p>
<pre><code>if len(x.shape) == 0:
</code></pre>
<p>if so,... | 0 | 2016-06-29T14:31:38Z | [
"python",
"python-2.7",
"machine-learning",
"scikit-learn",
"vectorization"
] |
What is the current value of a Python itertools counter | 38,101,507 | <p>The <code>itertools.count</code> counter in Python (2.7.9) is very handy for thread-safe counting. How can I get the current value of the counter though?</p>
<p>The counter increments and returns the last value every time you call <code>next()</code>:</p>
<pre><code>import itertools
x = itertools.count()
print x.n... | 0 | 2016-06-29T13:45:25Z | 38,101,806 | <p>According to the <a href="https://docs.python.org/2.7/library/itertools.html#itertools.count" rel="nofollow">documentation</a> there is no way to access the current value of the function. <code>itertools.count()</code> is a <em>generator</em> method from the <code>itertools</code> module. As such, it is common pract... | 1 | 2016-06-29T13:56:52Z | [
"python",
"itertools"
] |
What is the current value of a Python itertools counter | 38,101,507 | <p>The <code>itertools.count</code> counter in Python (2.7.9) is very handy for thread-safe counting. How can I get the current value of the counter though?</p>
<p>The counter increments and returns the last value every time you call <code>next()</code>:</p>
<pre><code>import itertools
x = itertools.count()
print x.n... | 0 | 2016-06-29T13:45:25Z | 38,101,887 | <p><a href="https://docs.python.org/2.7/library/itertools.html#itertools.count" rel="nofollow">It</a> is a generator, it wouldn't be easy to do what you want.</p>
<p>If you want to use it's value in several places, I'd recommend getting a value via <code>.next()</code> and storing it in a variable. If you are concerne... | 0 | 2016-06-29T13:59:36Z | [
"python",
"itertools"
] |
What is the current value of a Python itertools counter | 38,101,507 | <p>The <code>itertools.count</code> counter in Python (2.7.9) is very handy for thread-safe counting. How can I get the current value of the counter though?</p>
<p>The counter increments and returns the last value every time you call <code>next()</code>:</p>
<pre><code>import itertools
x = itertools.count()
print x.n... | 0 | 2016-06-29T13:45:25Z | 38,102,157 | <p>Use the source, Luke!</p>
<p>According to <a href="http://svn.python.org/view/python/tags/r271/Modules/itertoolsmodule.c?view=markup" rel="nofollow">module implementation</a>, it's not possible.</p>
<pre><code>typedef struct {
PyObject_HEAD
Py_ssize_t cnt;
PyObject *long_cnt;
PyObject *long_step;
}... | 2 | 2016-06-29T14:08:48Z | [
"python",
"itertools"
] |
Pyspark BinaryClassficationMetrics areaUnderROC | 38,101,540 | <p>--Edit on 29Jun 2016
Hi,
Following is the error log for the command:</p>
<pre><code>metrics = BinaryClassificationMetrics(labelsAndPreds)
# Area under ROC curve
#print("Area under ROC = %s" % metrics.areaUnderROC)
metrics.areaUnderROC
</code></pre>
<h2>Error Log:</h2>
<pre><code>Py4JJavaError ... | 0 | 2016-06-29T13:47:16Z | 38,115,632 | <p>I have found the error in my code. Both label and prediction in labelsAndPreds should be <em>float</em> for the code to work. In my earlier code, the predictions were not float and that was the reason for the error.</p>
<p>Thanks</p>
| 0 | 2016-06-30T06:39:18Z | [
"python",
"apache-spark",
"pyspark",
"apache-spark-mllib"
] |
Initialization of Xgboost DMatrix reduce features number | 38,101,603 | <p>I am trying to understand following case:</p>
<ol>
<li><p>when I create new <code>xgbost</code> DMatrix </p>
<p><code>xgX = xgb.DMatrix(X, label=Y, missing=np.nan)</code></p></li>
<li><p>based on input data <strong>X</strong> with 64 features
<a href="http://i.stack.imgur.com/JWjms.png" rel="nofollow"><img src="h... | 1 | 2016-06-29T13:49:30Z | 38,193,957 | <p>Take a look at
<a href="https://github.com/dmlc/xgboost/issues/1223" rel="nofollow">xgboost issue #1223</a></p>
<p>There, khotilov makes the comment:</p>
<blockquote>
<p>The problem with CSR is that when you have completely sparse columns at the end, you cannot figure out that they exist by just looking at CSR's... | 1 | 2016-07-05T01:18:37Z | [
"python",
"python-2.7",
"pandas",
"machine-learning",
"xgboost"
] |
maximum recursion deep exceeded when calling for an object attribute | 38,101,631 | <p>I am pretty new to python and I have decided to create a module to manage my monthly budget as a learning occasion.
The basic object in the module would be Debit, defined as</p>
<pre><code>class Debit(object):
currency = "SEK"
def __init__(self,date,tag,ammount):
self.date = date
self.tag ... | 3 | 2016-06-29T13:50:42Z | 38,102,105 | <p>Every object has a namespace (actually a <code>dict</code>) that keeps its members - regardless whether those are attribute, functions/methods or other things.</p>
<p>In your case, you are trying to use the name <code>date</code> both for the <em>method</em> and the <em>primitive</em>. This causes a collision, so e... | 3 | 2016-06-29T14:06:56Z | [
"python"
] |
Find first occurrence of non-integer in a specific column of a dataframe | 38,101,658 | <p>I have a dataframe with a bunch of integers in a column; at some point in the column, a string or letter will appear. I need to find this string or letter or non integer, then remove all data that comes after it.</p>
<p>How would I go about this?</p>
| 3 | 2016-06-29T13:51:38Z | 38,102,573 | <p>That should do the trick:</p>
<pre><code>In [20]: df = pd.DataFrame({'x': [1, 2, 'a', 1, 2]})
In [21]: df
Out[21]:
x
0 1
1 2
2 a
3 1
4 2
In [22]: df.loc[(~df.x.apply(np.isreal)).cumsum() == 0, :]
Out[22]:
x
0 1
1 2
</code></pre>
| 4 | 2016-06-29T14:26:47Z | [
"python",
"string",
"pandas",
"find"
] |
Find first occurrence of non-integer in a specific column of a dataframe | 38,101,658 | <p>I have a dataframe with a bunch of integers in a column; at some point in the column, a string or letter will appear. I need to find this string or letter or non integer, then remove all data that comes after it.</p>
<p>How would I go about this?</p>
| 3 | 2016-06-29T13:51:38Z | 38,102,661 | <p>Try this:</p>
<pre><code>df = pd.DataFrame({'x': [1, 2, 'a', 1, 2]})
df.iloc[:(df.x.apply(type) == str).idxmax()]
x
0 1
1 2
</code></pre>
<p><a href="http://i.stack.imgur.com/OhRzX.png" rel="nofollow"><img src="http://i.stack.imgur.com/OhRzX.png" alt="enter image description here"></a></p>
| 2 | 2016-06-29T14:30:45Z | [
"python",
"string",
"pandas",
"find"
] |
Pandas: reorganizing a dataframe | 38,101,702 | <p>I have this dataframe with four columns:</p>
<pre><code>df = pd.DataFrame({'name': {1:'Aaron', 2:'Bobby', 3:'Carl'},
'job': {1:'mechanic', 2:'carpenter', 3:'plumber'},
'experience': {1:12, 2:23, 3:14},
'type': {1:'owner',2:'contractor',3:'assistant'}},
co... | 2 | 2016-06-29T13:53:06Z | 38,101,843 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.swaplevel.html" rel="nofollow"><code>MultiIndex.swaplevel</code></a>:</p>
<pre><code>df.columns = df.columns.swaplevel(0,1)
print (df)
job carpenter mechanic plumber carpenter mechanic plumber
experience ... | 4 | 2016-06-29T13:57:50Z | [
"python",
"pandas",
"dataframe"
] |
Pandas: reorganizing a dataframe | 38,101,702 | <p>I have this dataframe with four columns:</p>
<pre><code>df = pd.DataFrame({'name': {1:'Aaron', 2:'Bobby', 3:'Carl'},
'job': {1:'mechanic', 2:'carpenter', 3:'plumber'},
'experience': {1:12, 2:23, 3:14},
'type': {1:'owner',2:'contractor',3:'assistant'}},
co... | 2 | 2016-06-29T13:53:06Z | 38,103,149 | <p>Update: I solved by splitting the dataframe into two separate tables, one for <code>experience</code> and one for <code>type</code>. I then merged the two, used the swaplevel command to put the <code>job</code> column header at the top, and ordered the columns using <code>sort_index(axis=1)</code>. </p>
| -1 | 2016-06-29T14:52:42Z | [
"python",
"pandas",
"dataframe"
] |
how to count items/boolean after if-statements (python) | 38,101,704 | <p>I have a csv where I need to count the total number for each category: </p>
<pre><code>New_Cell[2] Category I need to count
1 [A01]
1 [A01]
0 [A01]
1 ... | 0 | 2016-06-29T13:53:07Z | 38,101,789 | <p>Initialize <code>counts</code> before the loop begins, increment it when your condition succeeds, and only print it after the loop ends.</p>
<pre><code>counts = 0
for line in reader:
cells = line
new_cell = cells[0], cells[6], cells[7], cells[8], cells[9], cells[10] # name, # of participation, primary occup... | 1 | 2016-06-29T13:56:18Z | [
"python",
"python-2.7"
] |
how to count items/boolean after if-statements (python) | 38,101,704 | <p>I have a csv where I need to count the total number for each category: </p>
<pre><code>New_Cell[2] Category I need to count
1 [A01]
1 [A01]
0 [A01]
1 ... | 0 | 2016-06-29T13:53:07Z | 38,102,915 | <p>To add on to Kevin's answer, you can also use a dictionary to increment the counts for multiple categories. </p>
<pre><code>categories = {}
counts = 0
for line in reader:
cells = line
new_cell = cells[0], cells[6], cells[7], cells[8], cells[9], cells[10]
if int(new_cell[1]):
primary = new_cell[... | 0 | 2016-06-29T14:42:14Z | [
"python",
"python-2.7"
] |
Pandas dataframe.to_csv file rows out of alignment with each other | 38,101,915 | <p>I want to write my DataFrame to a CSV file. The result is shown below. The rows are out of alignment with each other. Do you have any suggestion to solve this problem?</p>
<p>Code : </p>
<pre><code>dataframe.to_csv(data,sep="",index=False,header=False,encoding='ascii',
float_format='%10.4f',quoti... | 2 | 2016-06-29T14:00:28Z | 38,102,463 | <p>Use delimiter tab:</p>
<pre><code>dataframe.to_csv(data,sep="\t",index=False,header=False,encoding='ascii',
float_format='%10.4f',quoting=csv.QUOTE_NONE, escapechar=" ", mode='a+')
</code></pre>
| 0 | 2016-06-29T14:22:27Z | [
"python",
"csv",
"pandas",
"dataframe",
"alignment"
] |
Pandas dataframe.to_csv file rows out of alignment with each other | 38,101,915 | <p>I want to write my DataFrame to a CSV file. The result is shown below. The rows are out of alignment with each other. Do you have any suggestion to solve this problem?</p>
<p>Code : </p>
<pre><code>dataframe.to_csv(data,sep="",index=False,header=False,encoding='ascii',
float_format='%10.4f',quoti... | 2 | 2016-06-29T14:00:28Z | 38,102,483 | <p>csv files aren't supposed to be vertically aligned in that fashion. They are supposed to have values separated by commas. You seem to want nicely formatted ascii.</p>
<pre><code>print dataframe.__repr__()
C1 c2 c3 c2.1
0 1 1.111 1.111 1.111
1 2 23.261 1.111 1.111
2 3 138... | 2 | 2016-06-29T14:23:29Z | [
"python",
"csv",
"pandas",
"dataframe",
"alignment"
] |
Translating a perl code, utilising the DBI module, to python with MySQLdb | 38,102,029 | <p>I have little python experience, and I have zero perl knowledge, but I need to translate a perl code that connects to a MySQL server into python.</p>
<p>In the perl subroutine, after the standard connectivity actions, the code that appears is:</p>
<pre><code>my @tmp = @{$dbh->selectall_arrayref( $sql )};
my @t... | 0 | 2016-06-29T14:04:48Z | 38,102,678 | <p>You should be able to run the code to discover equivalency, but yes those two things are equivalent.</p>
<p>The thing that causes the syntax to be odd in the perl example is that perl had a very strict separation of scalars, arrays, and hashes in its early days and arrays and hashes could only have scalars as their... | 0 | 2016-06-29T14:31:16Z | [
"python",
"mysql",
"perl"
] |
Many to many Field - Accessing attributes | 38,102,031 | <p>I have these two models related by a ManyToManyField:</p>
<pre><code>class Bar(models.Model):
name = models.CharField(max_length=25, blank=False)
class Foo(models.Model):
bar = models.ManyToManyField(Bar, blank=True, related_name='bb')
def __unicode__(self):
return '%s' % self.bar.name
</code... | 1 | 2016-06-29T14:04:53Z | 38,102,557 | <p>Short answer : you can't.</p>
<p>Long answer : your question "How can I access to the name of bar in Foo" implies a given <code>Foo</code> instance always have one <em>and only one</em> related <code>Bar</code> (not zero, not two, not forty-two, just exactly one), but you're using a <code>ManyToManyField</code> whi... | 1 | 2016-06-29T14:26:01Z | [
"python",
"django",
"django-models"
] |
Python 2.7 cannot import name HTTPChannelHixie76Aware | 38,102,037 | <p>I installed Python 2.7 on a new Windows PC. I'm trying to execute a Python script but I receive this error</p>
<pre><code>from autobahn.twisted.resource import WebSocketResource, \
ImportError: cannot import name HTTPChannelHixie76Aware
</code></pre>
<p>I've already installed all required libraries, including auto... | -2 | 2016-06-29T14:05:01Z | 38,114,118 | <p>Try using <code>from autobahn.twisted.resource import *</code></p>
| 0 | 2016-06-30T04:42:28Z | [
"python",
"python-2.7",
"autobahn"
] |
Django: Properly Setting Cookies For Login | 38,102,074 | <p>I am new to Django's sessions, and i tried to make a login cookie for my website. User's on my website register via social website ( steam in this case ), For that i have different functions: <code>Index</code> view, Login, <code>LoginProcess</code>.</p>
<h1>Information:</h1>
<p><code>Index</code> view is a homepa... | 0 | 2016-06-29T14:06:07Z | 38,103,584 | <p>Maybe I am still reading it wrong, but it is impossible to set the value on a request's cookie.</p>
<pre><code>'WSGIRequest' object has no attribute 'set_cookie'
</code></pre>
<p>but if I assume you meant <code>response.set_cookie(key='logged', value=True)</code> (note <code>response</code>), then this works for m... | 1 | 2016-06-29T15:10:46Z | [
"python",
"django",
"session",
"cookies"
] |
OAuthException: Failed to generate request token with Salesforce | 38,102,078 | <p>I'm facing an issue I can't seems to fix, despite having tried everything I could.</p>
<p>I'm using Flask + Flask_oauthlib to connect to SalesForce. Here's my code :</p>
<pre><code>from flask import Flask, url_for
from flask_oauthlib.client import OAuth
app = Flask(__name__)
oauth = OAuth(app)
salesforce = oaut... | 0 | 2016-06-29T14:06:11Z | 38,103,544 | <p>Ok I've found the solution, it's really vicious !</p>
<pre><code>salesforce = oauth.remote_app('salesforce',
consumer_key='my_consumer_key',
consumer_secret='my_consumer_secret',
access_token_url='https://login.salesforce.com/services/oauth2/token',
authorize_url='https://login.salesforce.com/servic... | 0 | 2016-06-29T15:09:04Z | [
"python",
"oauth",
"salesforce"
] |
Openshift [Errno 13] Permission denied | 38,102,086 | <p>I met an exact same problem with what this link says:<a href="http://stackoverflow.com/questions/25473492/pip-install-failed-in-openshift-the-error-info-is-permission-denied">pip install Failed in OpenShift, the error info is Permission Denied</a>. I encountered the error while I was deploying <code>django-oscar</co... | 1 | 2016-06-29T14:06:28Z | 38,102,718 | <p>sudo is used to execute commands with the root status. You can simply write your command with sudo before like <code>sudo ls</code>.</p>
<p>For your problem I think that pip haven't the execute permission to .cache (if you have the execute permission for a file, then, you can execute this one and, for a directory, ... | 1 | 2016-06-29T14:33:11Z | [
"python",
"linux",
"django",
"pip",
"openshift"
] |
Openshift [Errno 13] Permission denied | 38,102,086 | <p>I met an exact same problem with what this link says:<a href="http://stackoverflow.com/questions/25473492/pip-install-failed-in-openshift-the-error-info-is-permission-denied">pip install Failed in OpenShift, the error info is Permission Denied</a>. I encountered the error while I was deploying <code>django-oscar</co... | 1 | 2016-06-29T14:06:28Z | 38,104,434 | <p>Don't use <code>sudo</code> if you're using <code>pip</code> from within a virtual environment (which you are, judging by the code you've posted) as this will install the package gloabally and <strong>not</strong> in the virtual environment.</p>
<p>Instead, you can use <code>pip</code> with the <code>--user</code> ... | 2 | 2016-06-29T15:47:08Z | [
"python",
"linux",
"django",
"pip",
"openshift"
] |
Openshift [Errno 13] Permission denied | 38,102,086 | <p>I met an exact same problem with what this link says:<a href="http://stackoverflow.com/questions/25473492/pip-install-failed-in-openshift-the-error-info-is-permission-denied">pip install Failed in OpenShift, the error info is Permission Denied</a>. I encountered the error while I was deploying <code>django-oscar</co... | 1 | 2016-06-29T14:06:28Z | 38,631,925 | <p>Try <code>pip install django-oscar --no-cache-dir</code></p>
| 0 | 2016-07-28T09:11:29Z | [
"python",
"linux",
"django",
"pip",
"openshift"
] |
How to load tsv data and split below sample dataset into three columns? | 38,102,104 | <p>Example Dataset:</p>
<pre><code>120GB Hard Disk Drive with 3 Years Warranty for Lenovo Essential B570 Laptop Notebook HDD Computer - Certified 3 Years Warranty from Seifelden 3950 8
"TOSHIBA SATELLITE L305-S5919 LAPTOP LCD SCREEN 15.4"" WXGA CCFL SINGLE SUBSTITUTE REPLACEMENT LCD SCREEN ONLY. NOT A LAPTOP" 35... | 0 | 2016-06-29T14:06:53Z | 38,102,951 | <p>If you don't mind using a library, <a href="http://pandas.pydata.org/pandas-docs/" rel="nofollow">pandas</a> can read csvs and tsvs. You'd want</p>
<pre><code>import pandas
df = pandas.read_csv('<your file>', sep='\t', names=['Product_id', 'order_id', 'item_id'])
</code></pre>
<p>If you want to use vanilla p... | 1 | 2016-06-29T14:43:45Z | [
"python",
"split",
"whitespace",
"multiple-columns"
] |
How to load tsv data and split below sample dataset into three columns? | 38,102,104 | <p>Example Dataset:</p>
<pre><code>120GB Hard Disk Drive with 3 Years Warranty for Lenovo Essential B570 Laptop Notebook HDD Computer - Certified 3 Years Warranty from Seifelden 3950 8
"TOSHIBA SATELLITE L305-S5919 LAPTOP LCD SCREEN 15.4"" WXGA CCFL SINGLE SUBSTITUTE REPLACEMENT LCD SCREEN ONLY. NOT A LAPTOP" 35... | 0 | 2016-06-29T14:06:53Z | 38,103,041 | <p>You could use the <a href="https://docs.python.org/2/library/csv.html#module-csv" rel="nofollow"><code>csv</code></a> module to read the file:</p>
<pre><code>import csv
from pprint import pprint
columns = 'Product_id order_id item_8'.split()
with open('data.tsv', 'rb') as tsv_file:
for row in csv.DictReader(t... | 1 | 2016-06-29T14:47:35Z | [
"python",
"split",
"whitespace",
"multiple-columns"
] |
Semantic equivalent of async for | 38,102,194 | <p>From the docs relative to <code>async for</code> syntax in Python 3.5, I gathered that it was introduced to iterate over an awaitable iterator.</p>
<p>There is something I don't get in the semantic equivalent that follow the description though:</p>
<pre><code>iter = (ITER)
iter = type(iter).__aiter__(iter)
running... | 5 | 2016-06-29T14:10:07Z | 38,102,547 | <p>Magic methods in python, e.g. <code>__add__</code>, are <em>always</em> <a href="https://docs.python.org/3.4/reference/datamodel.html?highlight=data%20model#special-method-lookup" rel="nofollow">looked up on the class</a>. For example, <code>len(foo)</code> will actually <strike>call</strike> resolve to <code>type(f... | 3 | 2016-06-29T14:25:44Z | [
"python",
"python-asyncio"
] |
Turn off logging in schedule library | 38,102,291 | <p><strong>Objective:</strong> prevent <code>schedule</code> from logging every time it runs.</p>
<p><strong>Background:</strong></p>
<p>I am using the <code>logging</code> and <code>schedule</code> libraries in a python project. </p>
<p>My log file contains information about the physical state of a instrument run b... | 6 | 2016-06-29T14:14:19Z | 38,102,389 | <p>The <code>schedule</code> module is <a href="https://github.com/dbader/schedule/blob/master/schedule/__init__.py#L42" rel="nofollow">exclusively using the logger called <code>schedule</code></a>. You can use the <code>logging</code> library to <a href="https://docs.python.org/2.7/library/logging.html#logging.Logger.... | 5 | 2016-06-29T14:18:32Z | [
"python",
"python-2.7",
"logging",
"scheduler"
] |
Why PyPi doesn't show download stats anymore? | 38,102,317 | <p>It was so handy to get an idea if the package is popular or not (even if its popularity is the reason of some "import" case in another popular package). But now I don't see this info for some reason.</p>
<p>An example: <a href="https://pypi.python.org/pypi/blist" rel="nofollow">https://pypi.python.org/pypi/blist</a... | 3 | 2016-06-29T14:15:16Z | 38,102,521 | <p>As can be seen in <a href="https://mail.python.org/pipermail/distutils-sig/2013-May/020855.html">this mail.python.org article</a>, download stats were removed because they weren't updating and would be too difficult to fix.</p>
<p>Donald Stufft, the author of the article, listed these reasons:</p>
<blockquote>
<... | 7 | 2016-06-29T14:24:42Z | [
"python",
"pypi"
] |
save data from a command to a csv file in python | 38,102,450 | <p>I want to save the result of a command in a csv file.
I have this code for the moment :</p>
<pre><code>import sys
import os
import time
import datetime
import subprocess
import csv
with open("compteur_data.csv","a") as csvfile:
date = datetime.datetime.today()
wtr=csv.writer(csvfile)
... | 1 | 2016-06-29T14:14:50Z | 38,102,660 | <p>Add a call to flush the buffered contents to the file. This is achieved by using the call: csvfile.flush()</p>
<pre><code>with open("compteur_data.csv","a") as csvfile:
date = datetime.datetime.today()
wtr=csv.writer(csvfile)
wtr.writerow(['Date/Heure','DATA']) #pillar title
while True:
ts =... | 2 | 2016-06-29T14:30:40Z | [
"python",
"file"
] |
How to stop a thread that is waiting for Client to .connect() | 38,102,504 | <p>Basically I have this problem:<br>
I use <strong><code>ZMQ</code></strong> to use a <strong><code>PUB/SUB</code></strong> formal pattern to publish some pieces of data to other programs. First class, i.e. a Server waits for a client to <code>.connect()</code> and when the client connects, Server sends the data to th... | 1 | 2016-06-29T14:24:08Z | 38,102,662 | <p>The best way to stop your thread is to send a shutdown message, create a shutdown property initialized with a boolean false value, then set it as a condition to run your server (in while loop set while !shutdown) then once your server receives a shutdown request from the client you will modify the value of the shutd... | 0 | 2016-06-29T14:30:47Z | [
"python",
"thread-safety",
"zeromq",
"pyzmq",
"xbmc"
] |
How to stop a thread that is waiting for Client to .connect() | 38,102,504 | <p>Basically I have this problem:<br>
I use <strong><code>ZMQ</code></strong> to use a <strong><code>PUB/SUB</code></strong> formal pattern to publish some pieces of data to other programs. First class, i.e. a Server waits for a client to <code>.connect()</code> and when the client connects, Server sends the data to th... | 1 | 2016-06-29T14:24:08Z | 38,110,633 | <blockquote>
<p><code>ZeroMQ</code> is a very powerfull set of tools for smart distributed applications with messaging + signalling features ready to be "just used" <sub> ( if one knows how - anyway, <a href="http://stackoverflow.com/questions/25729055/understanding-advanced-zeromq-socket-types/25742744#25742744"><st... | 0 | 2016-06-29T21:49:56Z | [
"python",
"thread-safety",
"zeromq",
"pyzmq",
"xbmc"
] |
Numpy and diff() | 38,102,566 | <p>I'm trying to create a diff of my sorted numpy array such that if I record the value of the first row, and the diffs, i can recreate the original table but store less data.</p>
<p>So here's an example of the table:</p>
<pre><code>my_array = numpy.array([(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), ... | 3 | 2016-06-29T14:26:32Z | 38,102,777 | <p>The problem is that you have a structured array instead of a regular 2-dimensional array, so <code>numpy</code> does not know how to subtract one tuple from another.</p>
<p>Convert your structured array to a regular array (<a href="http://stackoverflow.com/questions/5957380/convert-structured-array-to-regular-numpy... | 3 | 2016-06-29T14:35:43Z | [
"python",
"numpy"
] |
Numpy and diff() | 38,102,566 | <p>I'm trying to create a diff of my sorted numpy array such that if I record the value of the first row, and the diffs, i can recreate the original table but store less data.</p>
<p>So here's an example of the table:</p>
<pre><code>my_array = numpy.array([(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), ... | 3 | 2016-06-29T14:26:32Z | 38,104,550 | <p>Thanks to Alberto and Andras, here is what i needed to do:</p>
<p>Change my array from:</p>
<pre><code>my_array = numpy.zeros(6,'uint8,uint8,uint8,uint8,uint8,uint8,uint8,uint8,uint8,uint8,uint8,uint8,uint8,uint8')
</code></pre>
<p>To:</p>
<pre><code>my_array = numpy.zeros((6,14),'uint8')
</code></pre>
<p>I hav... | 0 | 2016-06-29T15:52:43Z | [
"python",
"numpy"
] |
Using python to run Latex compiler, why does it hang if there are errors in the latex? | 38,102,703 | <p>I have a python script that takes the (latex source) content of a google doc and creates a pdf. </p>
<p>This is the function I use for the pdf: </p>
<pre><code># -*- coding: utf-8 -*-
#!/usr/bin/python
"""One of the main activiating files of IMPS - this downloads all the files in a directory, creates the input.t... | 0 | 2016-06-29T14:32:27Z | 38,103,680 | <p>I think what you are missing is that you need to also need to setup a pipe for <code>STDERR</code>. This will let you see the error messages from <code>pdflatex</code>. You could also try explicitly setting the buffer size to zero when calling <code>Popen</code>.</p>
<pre><code>self.child = subprocess.Popen(comman... | 0 | 2016-06-29T15:14:55Z | [
"python",
"latex"
] |
Using python to run Latex compiler, why does it hang if there are errors in the latex? | 38,102,703 | <p>I have a python script that takes the (latex source) content of a google doc and creates a pdf. </p>
<p>This is the function I use for the pdf: </p>
<pre><code># -*- coding: utf-8 -*-
#!/usr/bin/python
"""One of the main activiating files of IMPS - this downloads all the files in a directory, creates the input.t... | 0 | 2016-06-29T14:32:27Z | 38,103,864 | <p>When it encounters errors, <code>pdflatex</code> asks the user about how to proceed, so your script "hangs" because it is expecting input. Use <code>pdflatex -interaction=nonstopmode -halt-on-error</code>. See <a href="http://tex.stackexchange.com/questions/25267/what-reasons-if-any-are-there-for-compiling-in-intera... | 0 | 2016-06-29T15:22:52Z | [
"python",
"latex"
] |
Training tensorflow RNN with large datasets | 38,102,710 | <p>I'm training an RNN in tensorflow. The function used is "rnn" from <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/rnn.py" rel="nofollow">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/rnn.py</a>. </p>
<pre><code>outputs, states = rnn.rnn(cell, inputs,... | 1 | 2016-06-29T14:32:42Z | 38,105,636 | <p>The standard practice here is to break your data up into chunks and work on it a chunk at a time. For example, if you are working with text, you might break your data up into sentences, and pass mini-batches of 10s-100s of sentences to the training process one at a time.</p>
<p>For an example of how to do this, tak... | 2 | 2016-06-29T16:46:56Z | [
"python",
"tensorflow",
"deep-learning",
"recurrent-neural-network"
] |
Convert an Array of ints to Date-Objects | 38,102,712 | <p>I have an array of ints that I would like to convert to date-type objects:</p>
<pre><code>[[19480916 19480901 19480917 19480901 19480901 19481019]
[19480917 19480916 19481019 19480922 19480922 19490902]
[19481004 19480917 19481021 19480924 19481004 19501124]]
</code></pre>
<p>I have the following code that is su... | 3 | 2016-06-29T14:32:45Z | 38,102,779 | <p>Use <code>str()</code> to convert each of the numbers to string and <a href="https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime" rel="nofollow"><code>strptime()</code></a> to load a string into a <code>datetime</code> object:</p>
<pre><code>from datetime import datetime
l = [
[19480916,... | 4 | 2016-06-29T14:35:46Z | [
"python",
"arrays"
] |
Convert an Array of ints to Date-Objects | 38,102,712 | <p>I have an array of ints that I would like to convert to date-type objects:</p>
<pre><code>[[19480916 19480901 19480917 19480901 19480901 19481019]
[19480917 19480916 19481019 19480922 19480922 19490902]
[19481004 19480917 19481021 19480924 19481004 19501124]]
</code></pre>
<p>I have the following code that is su... | 3 | 2016-06-29T14:32:45Z | 38,102,873 | <p>The reason it's not working is because first of all you are trying to pass a slice of the list as parameters to <code>datetime()</code></p>
<p>In your for loop, <code>for s in myArray</code>, each iteration of <code>s</code> looked something like this: <code>[19480916, 19480901, 19480917, 19480901, 19480901, 194810... | 2 | 2016-06-29T14:40:22Z | [
"python",
"arrays"
] |
How to include formatted text in XPath? | 38,102,878 | <p>I am working on a project for my IT job that requires me to write a scraper using Scrapy/XPath to get a fairly simple set of data from a fairly simple HTML page. I've gotten everything to work the way I want it to, with the exception of some italic text (the website being scraped is for a language education program ... | 2 | 2016-06-29T14:40:34Z | 38,102,945 | <p>With <code>text()</code> called on an element you <em>only get the top-level text nodes</em> while you want to go down to every child element as well, use <code>.//text()</code>:</p>
<pre><code>rawTitles = response.xpath('//h2[@class="video"]//text()').extract()
</code></pre>
<p>You can then join the items of a <c... | 1 | 2016-06-29T14:43:27Z | [
"python",
"xpath",
"scrapy"
] |
How to include formatted text in XPath? | 38,102,878 | <p>I am working on a project for my IT job that requires me to write a scraper using Scrapy/XPath to get a fairly simple set of data from a fairly simple HTML page. I've gotten everything to work the way I want it to, with the exception of some italic text (the website being scraped is for a language education program ... | 2 | 2016-06-29T14:40:34Z | 38,103,813 | <p>Let's look at different extraction patterns in scrapy shell, building a selector from your sample HTML:</p>
<pre><code>>>> import scrapy
>>> t = '''<td width="25%" valign="top" align="center">
... <h2 class="video"><img src="content/pl_makingfood_mjadrah.jpg" alt="Thumbnail imag... | 1 | 2016-06-29T15:21:03Z | [
"python",
"xpath",
"scrapy"
] |
Fix up shapely polygon object when discontinuous after map projection | 38,102,927 | <p>This demo program (intended to be run in an IPython notebook; you need <code>matplotlib</code>, <code>mpl_toolkits.basemap</code>, <code>pyproj</code>, and <code>shapely</code>) is supposed to plot increasingly large circles on the surface of the Earth. It works correctly as long as the circle does not cross over o... | 1 | 2016-06-29T14:42:27Z | 38,707,971 | <p>Manually fixing up the projected polygon turns out not to be <em>that</em> bad.
There are two steps: first, find all segments of the polygon that cross the <a href="https://en.wikipedia.org/wiki/Coordinate_singularity" rel="nofollow">coordinate singularity</a> at longitude ±180, and replace them with excursions to ... | 1 | 2016-08-01T20:56:25Z | [
"python",
"maps",
"geospatial",
"shapely"
] |
How to use Rules in Scrapy for following some links? | 38,103,139 | <p>I want to scrape a website by <strong>Python Scrapy</strong> and follow all the links who contain "catalogue"</p>
<p>I think that the smart way is using the Scrapy Rules, i try this but it doesn't follow the links</p>
<pre><code>class Houra(CrawlSpider):
reload(sys)
pageNumber = 0
name = 'houra'
al... | 1 | 2016-06-29T14:52:16Z | 38,103,215 | <p><code>restrict_xpaths</code> defines a region or regions where to look for the links. But you need to use <code>allow</code> instead which would check the link <code>href</code> values:</p>
<pre><code>Rule(LinkExtractor(allow=r'catalogue/'), callback='parse_page', follow=True)
</code></pre>
| 2 | 2016-06-29T14:55:13Z | [
"python",
"scrapy",
"web-crawler",
"scrapy-spider"
] |
How to change size of turtle? | 38,103,158 | <p>I am trying to double the size of the turtle in the window every time I press <code>x</code> on my keyboard. I tried using <code>.turtlesize(2,2,2)</code>, but that's not right. I need to double every time the key is pressed so if the turtle size is <code>(1,1,1)</code>, it will become <code>(2,2,2)</code> then <cod... | 0 | 2016-06-29T14:52:54Z | 38,105,479 | <p>Change this line:</p>
<pre><code>tess.turtlesize(increase)
</code></pre>
<p>to instead be:</p>
<pre><code>tess.turtlesize(*increase)
</code></pre>
<p><code>turtlesize()</code> wants three separate values but you were passing one tuple of three values so we need to spread that tuple across the argument list.</p>
| 0 | 2016-06-29T16:38:09Z | [
"python",
"turtle-graphics"
] |
Python - Easily importing csv arrays from multiple column sets | 38,103,162 | <p>I'm trying to import this data set via csv.</p>
<pre><code>import numpy as np
import csv
Snap1 = []
Snap2 = []
with open('BrownM.csv', 'r') as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
Snap1.append(row[0])
Snap2.append(row[1])
Snap1 = np.array(Snap1)
</code></pre>
<p>T... | 0 | 2016-06-29T14:53:11Z | 38,103,651 | <p>You could try using the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html" rel="nofollow"><code>genfromtxt</code></a> function from <code>numpy</code>. By giving the delimiter as <code>,</code> it loads a csv file into a 2D array that you can slice into columns.</p>
<p>Like this:</p... | 2 | 2016-06-29T15:13:39Z | [
"python",
"csv",
"numpy"
] |
Use separate interface file with PyQt | 38,103,264 | <p>I have an interface file generated from QtDesigner that I want to keep the same in case of changes.</p>
<p>Have a main file called <code>application.py</code> handle all the functions, and one file strictly for interface stuff.</p>
<p>I am using <strong>PyQt5</strong>.</p>
<p>I have not been able to find any tuto... | 0 | 2016-06-29T14:57:34Z | 38,105,580 | <p>This would be the way to connect the signal</p>
<pre><code>ui.quitButton.clicked.connect(QtCore.QCoreApplication.instance().quit)
</code></pre>
<p>That being said, you probably don't want to do this. You should probably connect to the <code>.close</code> method of the window. When the window closes, by default, ... | 2 | 2016-06-29T16:44:25Z | [
"python",
"python-3.x",
"user-interface",
"pyqt"
] |
Use separate interface file with PyQt | 38,103,264 | <p>I have an interface file generated from QtDesigner that I want to keep the same in case of changes.</p>
<p>Have a main file called <code>application.py</code> handle all the functions, and one file strictly for interface stuff.</p>
<p>I am using <strong>PyQt5</strong>.</p>
<p>I have not been able to find any tuto... | 0 | 2016-06-29T14:57:34Z | 38,114,503 | <pre><code>from YatsiInterface import Ui_YatsiWindow
from PyQt5 import QtCore, QtGui
class my_application(QtGui.QWidget, Ui_YatsiWindow):
def __init__(self):
super(my_application, self).__init__()
self.setupUi(self)
self.quitButton.clicked.connect(self.my_mythod)
def my_method(self):
... | 1 | 2016-06-30T05:18:34Z | [
"python",
"python-3.x",
"user-interface",
"pyqt"
] |
Command line user interface instead of web-based interface for django? | 38,103,425 | <p>I have built a web platform with Django. Users with Staff status can log into Django-admin through their web browsers and add, remove or alter different objects, upload files, etc.</p>
<p>Now I want to build a command line tool to enable users to do these tasks via command line. The users need to authenticate in co... | -1 | 2016-06-29T15:04:16Z | 38,104,164 | <p>This looks like a '2-component' thing. </p>
<h3>API</h3>
<p>You will have to expose the desired functionality via an (RESTful) API.<br>
Two common and very good libraries are <a href="http://tastypieapi.org/" rel="nofollow">tastypie</a> and <a href="http://www.django-rest-framework.org/" rel="nofollow">Django REST... | 0 | 2016-06-29T15:35:44Z | [
"python",
"django",
"web-services",
"rest"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.