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 |
|---|---|---|---|---|---|---|---|---|---|
Timed method in Python | 39,272,925 | <p>How do I have a part of python script(only a method, the whole script runs in 24/7) run everyday at a set-time, exactly at every 20th minutes? Like 12:20, 12:40, 13:00 in every hour.</p>
<p>I can not use cron, I tried periodic execution but that is not as accurate as I would... It depends from the script starting t... | 2 | 2016-09-01T13:30:24Z | 39,273,687 | <p>Module <a href="https://github.com/dbader/schedule" rel="nofollow">schedule</a> may be useful for this. See answer to
<a href="http://stackoverflow.com/questions/373335/how-do-i-get-a-cron-like-scheduler-in-python">How do I get a Cron like scheduler in Python?</a> for details.</p>
| 0 | 2016-09-01T14:04:35Z | [
"python"
] |
Python regex similar expressions | 39,272,951 | <p>I have a file with two different types of data I'd like to parse with a regex; however, the data is similar enough that I can't find the correct way to distinguish it.</p>
<p>Some lines in my file are of form:</p>
<pre><code>AED=FRI
AFN=FRI:SAT
AMD=SUN:SAT
</code></pre>
<p>Other lines are of form</p>
<pre><code>... | 1 | 2016-09-01T13:31:31Z | 39,273,094 | <pre><code>r'\S*\d$'
</code></pre>
<p>Will match all non-whitespace characters that end in a digit</p>
<p>Will match <code>AED=20180823</code></p>
<pre><code>r'\S*[a-zA-Z]$'
</code></pre>
<p>Matches all non-whitespace characters that end in a letter.</p>
<p>will match <code>AED=AED=FRI</code>
<code>AFN=FRI:SAT</c... | 2 | 2016-09-01T13:38:11Z | [
"python",
"regex"
] |
Python regex similar expressions | 39,272,951 | <p>I have a file with two different types of data I'd like to parse with a regex; however, the data is similar enough that I can't find the correct way to distinguish it.</p>
<p>Some lines in my file are of form:</p>
<pre><code>AED=FRI
AFN=FRI:SAT
AMD=SUN:SAT
</code></pre>
<p>Other lines are of form</p>
<pre><code>... | 1 | 2016-09-01T13:31:31Z | 39,273,201 | <p>The following is a solution in Python :)</p>
<pre><code>import re
p = re.compile(r'\b([A-Z]{3})=((\d)+|([A-Z])+)')
str_test_01 = "AMD=SUN:SAT"
m = p.search(str_test_01)
print (m.group(1))
print (m.group(2))
str_test_02 = "AMD=20150921"
m = p.search(str_test_02)
print (m.group(1))
print (m.group(2))
"""
<Out... | 2 | 2016-09-01T13:42:55Z | [
"python",
"regex"
] |
Python regex similar expressions | 39,272,951 | <p>I have a file with two different types of data I'd like to parse with a regex; however, the data is similar enough that I can't find the correct way to distinguish it.</p>
<p>Some lines in my file are of form:</p>
<pre><code>AED=FRI
AFN=FRI:SAT
AMD=SUN:SAT
</code></pre>
<p>Other lines are of form</p>
<pre><code>... | 1 | 2016-09-01T13:31:31Z | 39,273,302 | <p>Use pipes to express alternatives in regex. Pattern '[A-Z]{3}:[A-Z]{3}|[A-Z]{3}' will match both ABC and ABC:ABC. Then use parenthesis to group results:</p>
<pre><code>import re
match = re.match(r'([A-Z]{3}:[A-Z]{3})|([A-Z]{3})', 'ABC:ABC')
assert match.groups() == ('ABC:ABC', None)
match = re.match(r'([A-Z]{3}:[... | 2 | 2016-09-01T13:47:55Z | [
"python",
"regex"
] |
Suggestions to handle multiple python pandas scripts | 39,273,012 | <p>I currently have several python pandas scripts that I keep separate because of 1) readability, and 2) sometimes I am interested in the output of these partial individual scripts. </p>
<p>However, generally, the CSV file output of one of these scripts is the CSV input of the next and in each I have to re-read dateti... | 0 | 2016-09-01T13:34:03Z | 39,273,086 | <p>Instead of writing a CSV output which you have to re-parse, you can write and read the <code>pandas.DataFrame</code> in efficient binary format with the methods <code>pandas.DataFrame.to_pickle()</code> and <code>pandas.read_pickle()</code>, respectively.</p>
| 1 | 2016-09-01T13:37:56Z | [
"python",
"pandas"
] |
Suggestions to handle multiple python pandas scripts | 39,273,012 | <p>I currently have several python pandas scripts that I keep separate because of 1) readability, and 2) sometimes I am interested in the output of these partial individual scripts. </p>
<p>However, generally, the CSV file output of one of these scripts is the CSV input of the next and in each I have to re-read dateti... | 0 | 2016-09-01T13:34:03Z | 39,273,803 | <p>If I understand your question well, using modules would be the best approach to me.</p>
<p>You can keep your scripts separated and import them as modules when needed in a dependent script. For example:</p>
<p>Script 1:</p>
<pre><code>import pandas
def create_pandas_dataframe():
# Creating a dataframe ...
... | 1 | 2016-09-01T14:09:17Z | [
"python",
"pandas"
] |
reduceByKey in spark for adding tuples | 39,273,023 | <p>Consider an Rdd with below dataset
where 10000241 is the key and remaining are values</p>
<pre><code> ('10000241',([0,0,1],[None,None,'RX']))
('10000241',([0,2,0],[None,'RX','RX']))
('10000241',([3,0,0],['RX',None,None]))
pv1 = rdd.reduceBykey(lambda x,y :(
addtup(x[0],y[0]),
... | 0 | 2016-09-01T13:34:38Z | 39,273,351 | <p>If I understood you correctly, you want to summarize numbers in the first tuple and to use logic or in the second?</p>
<p>I think you should rewrite your function as following:</p>
<pre><code>def addtup(t1,t2):
left = list(map(lambda x: sum(x), zip(t1[0], t2[0])))
right = list(map(lambda x: x[0] or x[1], zip(t... | 0 | 2016-09-01T13:50:18Z | [
"python",
"apache-spark",
"pyspark",
"apache-spark-sql"
] |
Python - Scrapy data lists | 39,273,143 | <p>I have the following piece of code in my scraper:</p>
<pre><code>import scrapy
import os
import re
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
class MySpider(CrawlSpider):
handle_httpstatus_list = [301,302,404,200,500]
name = 'rust'
allowed_domains = ['e... | 0 | 2016-09-01T13:40:09Z | 39,274,047 | <p>You probably run your scrapy spider from command line.</p>
<p>In that case I would suggest you to debug your spider using pycharm ide.</p>
<p>Just add this code inside <code>yourproject</code> directory and name it something like <code>main.py</code></p>
<pre><code># -*- coding: utf-8 -*-
import logging
from sc... | 0 | 2016-09-01T14:19:12Z | [
"python",
"scrapy"
] |
Python - Scrapy data lists | 39,273,143 | <p>I have the following piece of code in my scraper:</p>
<pre><code>import scrapy
import os
import re
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
class MySpider(CrawlSpider):
handle_httpstatus_list = [301,302,404,200,500]
name = 'rust'
allowed_domains = ['e... | 0 | 2016-09-01T13:40:09Z | 39,300,555 | <p>Maybe it would be easier to grab all the <code>a</code> elements without trying to match their attributes, something like:</p>
<pre><code>for a in response.css('a'):
if a.xpath('@href').extract_first() == 'http://some/link/':
target = a.xpath('@target').extract_first()
rel = a.xpath('@rel').extr... | 1 | 2016-09-02T20:52:42Z | [
"python",
"scrapy"
] |
Flatten pandas pivot table | 39,273,441 | <p>This is a follow up of my <a href="http://stackoverflow.com/questions/39229005/pivot-table-no-numeric-types-to-aggregate/39229396#39229396">question</a>. Rather than a pivot table, is it possible to flatten table to look like the following:</p>
<pre><code>data = {'year': ['2016', '2016', '2015', '2014', '2013'],
... | 2 | 2016-09-01T13:54:05Z | 39,273,531 | <p>Try this:</p>
<pre><code>df.columns = df.columns.get_level_values(0)
</code></pre>
<p>followed by: </p>
<pre><code>df.columns = [' '.join(col).strip() for col in df.columns.values]
</code></pre>
<p>This should flatten your multi-index </p>
| 2 | 2016-09-01T13:58:30Z | [
"python",
"pandas"
] |
Flatten pandas pivot table | 39,273,441 | <p>This is a follow up of my <a href="http://stackoverflow.com/questions/39229005/pivot-table-no-numeric-types-to-aggregate/39229396#39229396">question</a>. Rather than a pivot table, is it possible to flatten table to look like the following:</p>
<pre><code>data = {'year': ['2016', '2016', '2015', '2014', '2013'],
... | 2 | 2016-09-01T13:54:05Z | 39,273,677 | <p>see <a href="http://stackoverflow.com/q/37087020/2336654">collapse a pandas MultiIndex</a></p>
<h3>Solution</h3>
<pre><code>df.columns = df.columns.to_series().str.join('_')
</code></pre>
| 4 | 2016-09-01T14:04:05Z | [
"python",
"pandas"
] |
How to size my imshow? | 39,274,002 | <p>I generated a 2d intensity matrix with the following code:</p>
<pre><code>H, x_e, y_e = np.histogram2d(test_y, test_x, bins=(y_e, x_e))
</code></pre>
<p>The values of x_e and y_e are:</p>
<pre><code>x_e
array([ 0.05 , 0.0530303 , 0.05606061, 0.05909091, 0.06212121,
0.06515152, 0.06818182, 0.071... | 3 | 2016-09-01T14:17:00Z | 39,275,939 | <p>You can set the aspect ratio of the <a href="http://matplotlib.org/api/axes_api.html" rel="nofollow">axes</a> <a href="http://matplotlib.org/examples/pylab_examples/equal_aspect_ratio.html" rel="nofollow">directly</a>. This is independent of the figure size. Here's an example:</p>
<pre><code>import numpy as np
from... | 3 | 2016-09-01T15:48:45Z | [
"python",
"matplotlib"
] |
Need explanation on recursive and generator example | 39,274,019 | <p>I have this recursive function which is used to generate all possible up and lower cases to any string value you pass it to it.</p>
<p>Here is the code sample and the output:</p>
<pre><code>def test (name):
if not name:
yield ""
else:
first=name[:1]
for sub in test(name[1:]):
... | -1 | 2016-09-01T14:17:43Z | 39,278,343 | <p>Where are you stuck in producing your own trace? You've shown that you know how to use <strong>print</strong> statements. I assume that you also know how to search other examples of recursion traces; StackOverflow has many.</p>
<p>To get you started, here's your code with a couple more <strong>print</strong> stat... | 0 | 2016-09-01T18:14:24Z | [
"python",
"python-3.x",
"recursion",
"generator",
"yield"
] |
Need explanation on recursive and generator example | 39,274,019 | <p>I have this recursive function which is used to generate all possible up and lower cases to any string value you pass it to it.</p>
<p>Here is the code sample and the output:</p>
<pre><code>def test (name):
if not name:
yield ""
else:
first=name[:1]
for sub in test(name[1:]):
... | -1 | 2016-09-01T14:17:43Z | 39,295,524 | <p>thanks ....
yesterday i just took a paper ,a pen and i trace this function from stack view and i understand it ... </p>
<p>it's recursive so the function will call itself from the second letter to the end of whole string each time till the the function "test" called with "" value ... </p>
<p>then i have to apply... | 0 | 2016-09-02T15:03:39Z | [
"python",
"python-3.x",
"recursion",
"generator",
"yield"
] |
python code for string re-arrangement | 39,274,110 | <p>Can anyone help me with python code which transforms the word/string as follows Move all consonants before the vowels - The consonants and vowels should be in the reverse order of the original. - If two equal letters come next to each other in the result (case insensitive duplicates), drop the second letter in ... | -3 | 2016-09-01T14:21:40Z | 39,274,252 | <p>Should work, more or less what you had concept wise, with worse far worse string concatenation. </p>
<pre><code>def isvowel(ch):
if ch in ["A", "E", "I", "O", "U", 'a','e','i','o','u']:
return True
else:
return False
vowels = []
consonants = []
for letter in word:
if isvowel(l... | 0 | 2016-09-01T14:26:59Z | [
"python"
] |
Why does round raise on ndigits=None for integers but not for floats? | 39,274,173 | <p>Why does <code>round()</code> behave different for int and float when <code>ndigits</code> is explicitly set to <code>None</code>?</p>
<p>Console test in Python 3.5.1:</p>
<pre><code>>>> round(1, None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneTyp... | 4 | 2016-09-01T14:23:53Z | 39,275,546 | <p>From the source code for <code>float_round</code> in <code>floatobjects.c</code> in <code>3.5</code>:</p>
<pre><code>float_round(PyObject *v, PyObject *args)
...
if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
return NULL;
...
if (o_ndigits == NULL || o_ndigits == Py_None) {
/* s... | 2 | 2016-09-01T15:27:09Z | [
"python",
"rounding",
"python-3.5"
] |
python: how to return 2 columns/index in a list | 39,274,228 | <p>I have a list that I generated using a for loop. it returns:</p>
<pre><code>home1-0002_UUID 3457077784 2132011944 1307504896 62%
home1-0003_UUID 3457077784 2088064860 1351451980 61%
home1-0001_UUID 3457077784 2092270236 1347246604 61%
</code></pre>
<p>How can I return only the third and fifth col... | -1 | 2016-09-01T14:25:49Z | 39,275,408 | <p>As far as I cannot post a comment I will do my best to give you a solution to the question.</p>
<pre><code>def empty_string_filter(value):
return value != ''
def h1ost():
p1 = subprocess.Popen("/opt/lustre-gem_s/default/bin/lfs df /lustre/home1 | sort -r -nk5",stdout=subprocess.PIPE, shell=True)
use = ... | 1 | 2016-09-01T15:20:11Z | [
"python"
] |
tkinter canvas scrolling but scrollbar not adjusting to show canvas size | 39,274,249 | <p>i am trying to place a frame within a canvas with a scroll bar, the canvas scrolls but the scrollbar does not adjust to show the position </p>
<pre><code>from tkinter import *
from tkinter import ttk
parent=Tk()
studentFrame=ttk.Frame(parent)
studentFrame.pack()
#settup the canvas
canvas=Canvas(studentFrame,width=... | 0 | 2016-09-01T14:26:55Z | 39,276,831 | <p>You are setting the scroll region to be -15 pixels tall (you are setting the bottom-right of the scrollable area to be above the top of the scrollable area) </p>
| 0 | 2016-09-01T16:43:16Z | [
"python",
"tkinter"
] |
tkinter canvas scrolling but scrollbar not adjusting to show canvas size | 39,274,249 | <p>i am trying to place a frame within a canvas with a scroll bar, the canvas scrolls but the scrollbar does not adjust to show the position </p>
<pre><code>from tkinter import *
from tkinter import ttk
parent=Tk()
studentFrame=ttk.Frame(parent)
studentFrame.pack()
#settup the canvas
canvas=Canvas(studentFrame,width=... | 0 | 2016-09-01T14:26:55Z | 39,297,569 | <p>Finally got it to work i used
list.update_idletasks()
Before setting the scroll region</p>
| 0 | 2016-09-02T17:06:59Z | [
"python",
"tkinter"
] |
python3 get parameter from command terminal and print input out | 39,274,302 | <pre><code>lines = []
for line in fileinput.input():
lines.append(line)
print(line, end='')
</code></pre>
<p><a href="http://i.stack.imgur.com/3FyUr.png" rel="nofollow"><img src="http://i.stack.imgur.com/3FyUr.png" alt="enter image description here"></a></p>
<p>My question, how can I get 2 into the program an... | 1 | 2016-09-01T14:29:11Z | 39,274,678 | <p>The content of the <code>input.txt</code> file can be accesed using the <code>sys.stdin</code> file handle from inside python.
The arguments must be accesed using the <code>sys.argv</code> array.</p>
<p>Here is a sample script.</p>
<pre><code>#!/usr/bin/python
import sys
arg=sys.argv[1] #take first argument
lines=... | 0 | 2016-09-01T14:47:00Z | [
"python",
"linux",
"unix",
"input"
] |
python3 get parameter from command terminal and print input out | 39,274,302 | <pre><code>lines = []
for line in fileinput.input():
lines.append(line)
print(line, end='')
</code></pre>
<p><a href="http://i.stack.imgur.com/3FyUr.png" rel="nofollow"><img src="http://i.stack.imgur.com/3FyUr.png" alt="enter image description here"></a></p>
<p>My question, how can I get 2 into the program an... | 1 | 2016-09-01T14:29:11Z | 39,274,906 | <p>@Eugene already pointed out, in your command:</p>
<pre><code>./whale.py '2' < input.txt
</code></pre>
<blockquote>
<p><code>input.txt</code> is redirected to the standard input stream. <code>2</code> is going
into argv.</p>
</blockquote>
<p>The error you got was probably because somehow your script thought... | 0 | 2016-09-01T14:57:14Z | [
"python",
"linux",
"unix",
"input"
] |
Queue- Multi Threading Python | 39,274,368 | <p>I have a bunch of code and I am attaching a piece here. Basically I have a thread - which is targeted on a function - that has a while loop as following :</p>
<pre><code>while not stop_event.wait(1): # Continuous Reading Function
#print "hello2"
#print ("working on %s" % arg)
data1 = Read(soa1, bytes1,... | 0 | 2016-09-01T14:32:10Z | 39,420,966 | <p>The following approach reads and processes data from the queue continuously, which allows you to see and respond to data changes as they happen:</p>
<pre><code>while True:
self.data = queue_read.get()
self.update_GUI()
</code></pre>
<p><code>queue_read.get()</code> blocks if <code>queue_read</code> is emp... | 0 | 2016-09-09T23:23:14Z | [
"python",
"multithreading",
"variables",
"queue",
"pyserial"
] |
Python / Pygame FULLSCREEN Tag Creates A Game Screen That Is To Large For The Screen | 39,274,460 | <p><strong>UPDATED ISSUE</strong></p>
<p>I have discovered the issue appears to be with the fact that I am using the FULLSCREEN tag to create the window. I added a rectangle to be drawn in the top left of the scree (0, 0), but when I run the program, It is mostly off the screen. Then, when I Alt-Tab away and back, the... | 1 | 2016-09-01T14:37:00Z | 39,298,107 | <p>Alright, I discovered a solution from <a href="http://gamedev.stackexchange.com/questions/105750/pygame-fullsreen-display-issue">gamedev.stackexchange</a></p>
<p>And I will re-hash it here. The issue was that Using the fullscreen tag was making a screen larger than my computer screen. The following code solves this... | 0 | 2016-09-02T17:45:01Z | [
"python",
"pygame"
] |
How to insert IDs into Nodes when converting .csv to XML? | 39,274,698 | <p>Hello I'm new to Python,</p>
<p>and I would like to convert a <code>.csv</code>file to <code>XML</code>. The desired output should look like, where I would like to have each individual ID within a Node: <code><employee id="5"></code> and the variables corresponding to each individual beneath each other rather... | 2 | 2016-09-01T14:48:04Z | 39,275,116 | <p>You need to specify the delimiter of the csv file when creating the csv reader object (default is ',').</p>
<pre><code>csvData = csv.reader(open(csvFile), delimiter=' ')
</code></pre>
<p>If this is not given, then the entries of tags are not in the format you want.</p>
<hr>
<p>The else section in your for loop i... | 3 | 2016-09-01T15:06:48Z | [
"python"
] |
How to insert IDs into Nodes when converting .csv to XML? | 39,274,698 | <p>Hello I'm new to Python,</p>
<p>and I would like to convert a <code>.csv</code>file to <code>XML</code>. The desired output should look like, where I would like to have each individual ID within a Node: <code><employee id="5"></code> and the variables corresponding to each individual beneath each other rather... | 2 | 2016-09-01T14:48:04Z | 39,275,406 | <p>Using an XML parser will be far easier. Here is your example using the <a href="https://docs.python.org/3.5/library/xml.etree.elementtree.html#building-xml-documents" rel="nofollow">xml.etree.ElementTree</a> module. I assumed that you converted the dataframe to csv with <code>df.to_csv('df.csv')</code></p>
<pre><co... | 2 | 2016-09-01T15:20:02Z | [
"python"
] |
Using path extension \\?\ for windows 7 with python script | 39,274,722 | <p>I'm using the tool <a href="https://github.com/NavicoOS/ac2git" rel="nofollow">ac2git</a> to convert my Accurev depot to git repository. I'm facing a problem when the os.walk() function in the python file runs. Since my project has a pretty complicated build path I have nested files that have path length exceeding t... | 1 | 2016-09-01T14:49:12Z | 39,294,824 | <p>So after much ado, I made changes in the python code, </p>
<p>Apparently this information is very important " <em>File I/O functions in the Windows API convert "/" to "\" as part of converting the name to an NT-style name, except when using the "\?\" prefix as detailed in the following sections.</em>"</p>
<p>So I ... | 2 | 2016-09-02T14:28:32Z | [
"python",
"git",
"windows-7-x64",
"accurev"
] |
Add function name to decorator output | 39,274,743 | <p>I have a python code snippet that allows me to time function as a decorator. I would like to add function name to the output. and time in milli-seconds </p>
<pre><code>def func_timer(func):
def f(*args, **kwargs):
start = time.time()
results = func(*args, **kwargs)
print "Elapsed: %.6f... | 0 | 2016-09-01T14:50:14Z | 39,274,780 | <p>Function objects have a <code>__name__</code> attribute, you can use that. Simply multiply the time by 1000 if you want milliseconds:</p>
<pre><code>print "%s Elapsed: %.6fms" % (func.__name__, (time.time() - start) * 1000)
</code></pre>
| 4 | 2016-09-01T14:52:04Z | [
"python",
"function",
"decorator",
"python-decorators"
] |
How to make python config file, in which relative paths are defined, but when scripts in other directories import config, paths are correct? | 39,274,748 | <p>I have the following directory structure for a program I'm writing in python: </p>
<pre><code>\code\
main.py
config.py
\module_folder1\
script1.1.py
\data\
data_file1
data_file2
</code></pre>
<p>My <code>config.py</code> is a set of global variables that are set by the user, or general... | 0 | 2016-09-01T14:50:37Z | 39,274,866 | <ol>
<li>You know the correct relative path to the file from the directory where <code>config.py</code> is located</li>
<li>You know the correct relative path to the directory where <code>config.py</code> is located (in your case, <code>..</code>)</li>
</ol>
<p>Both of this things are system-independent and do not cha... | 1 | 2016-09-01T14:55:36Z | [
"python",
"module",
"relative-path"
] |
How to make python config file, in which relative paths are defined, but when scripts in other directories import config, paths are correct? | 39,274,748 | <p>I have the following directory structure for a program I'm writing in python: </p>
<pre><code>\code\
main.py
config.py
\module_folder1\
script1.1.py
\data\
data_file1
data_file2
</code></pre>
<p>My <code>config.py</code> is a set of global variables that are set by the user, or general... | 0 | 2016-09-01T14:50:37Z | 39,276,433 | <p>(Not sure who posted this as a comment, then deleted it, but it seems to work so I'm posting as an answer.) The trick is to use <code>os.path.dirname(__file__)</code> in the config file, which gives the directory of the config file (<code>/code/</code>) regardless of where the script that imports config is. </p>
<p... | 0 | 2016-09-01T16:17:54Z | [
"python",
"module",
"relative-path"
] |
Talking SMBus between RaspberryPi and ATMEGA 324PA - AVR not clock stretching | 39,274,784 | <p>I'm trying to get an ATMEGA 324PA to run as an SMBus slave.</p>
<p>I'm using the following code on the Pi:</p>
<pre><code>import smbus as smbus
i2c = smbus.SMBus(1)
i2c_addr = 0x30
result = i2c.read_block_data( i2c_addr, reg )
</code></pre>
<p>On the AVR, I'm using:</p>
<pre><code>#include <avr/io.h>
#incl... | 0 | 2016-09-01T14:52:12Z | 39,289,339 | <p>I tried using SMBus from a Beaglebone instead (replacing the Raspberry Pi).</p>
<p>This worked perfectly, after I added some 10K pull-up resistors to the i2c bus. (The Raspberry Pi has internal pull-ups on the i2c pins.)</p>
| 0 | 2016-09-02T09:44:40Z | [
"python",
"raspberry-pi",
"avr",
"i2c",
"smbus"
] |
Talking SMBus between RaspberryPi and ATMEGA 324PA - AVR not clock stretching | 39,274,784 | <p>I'm trying to get an ATMEGA 324PA to run as an SMBus slave.</p>
<p>I'm using the following code on the Pi:</p>
<pre><code>import smbus as smbus
i2c = smbus.SMBus(1)
i2c_addr = 0x30
result = i2c.read_block_data( i2c_addr, reg )
</code></pre>
<p>On the AVR, I'm using:</p>
<pre><code>#include <avr/io.h>
#incl... | 0 | 2016-09-01T14:52:12Z | 39,292,289 | <p>The issue you linked is the problem -- i2c clock stretching is simply broken on the Raspberry Pi. More info: <a href="http://www.advamation.com/knowhow/raspberrypi/rpi-i2c-bug.html" rel="nofollow">http://www.advamation.com/knowhow/raspberrypi/rpi-i2c-bug.html</a></p>
<p>If a sensor has alternative output such as UA... | 1 | 2016-09-02T12:19:40Z | [
"python",
"raspberry-pi",
"avr",
"i2c",
"smbus"
] |
Print in single line in python using map() function | 39,274,814 | <p>I want to read an integer, and without using any string methods, I want to print something like this using the <code>map()</code> function: </p>
<pre><code>123..N
</code></pre>
<p>For Example: </p>
<pre><code>N:5
output:12345
</code></pre>
<p>And not:</p>
<pre><code>1
2
3
4
5
</code></pre>
<p... | -1 | 2016-09-01T14:53:20Z | 39,355,297 | <p>you can try this on python 2:</p>
<p>from <strong>future</strong> import print_function</p>
<p>map(lambda y:print (y,end=""),[x for x in range(1,int(input())+1)])</p>
| -1 | 2016-09-06T18:10:12Z | [
"python",
"python-2.7",
"python-3.x"
] |
Beautiful Soup Conditional Query | 39,274,823 | <p>I am new to Beautiful Soup.
I need to get data from HTML file.</p>
<pre><code><div class="ques_ans_block">
<div class="question">
<p>is this correct ?</p>
<div>
<p class="answer"></p>
<div class="moreinfo" style="display: block;">
<p cl... | -1 | 2016-09-01T14:53:39Z | 39,285,630 | <p>This will give output as json containing Question, answer and FaqID.</p>
<pre><code>import bs4
import json
import codecs
arrayList = []
bsp = bs4.BeautifulSoup(open('input.html'))
ques_ans_block = bsp.find_all("div", {"class": "ques_ans_block"})
s = ""
count = 1
for i in ques_ans_block:
data = {}
q = i.sele... | 0 | 2016-09-02T06:27:53Z | [
"python",
"python-2.7",
"beautifulsoup"
] |
find and replace using multiple criteria pandas python | 39,274,824 | <p>I have the following dataframe (df):</p>
<pre><code>loc pop_1 source_1 pop_2 source_2
a 99 group_a 77 group_b
b 93 group_a 90 group_b
c 58 group_a 59 group_b
d 47 group_a 62 group_b
</code></pre>
<p>I create an additional column 'upper_limit':</p>
<pre><code>df['upper_limit'] = df[['pop_1',... | 2 | 2016-09-01T14:53:41Z | 39,275,044 | <blockquote>
<p>I now want to add another column that looks at the values in 'upper_limit', compares them to pop_1 and pop_2 and then selects the text from source_1 or source_2 when they match.</p>
</blockquote>
<p>You can do it much more simply using <a href="http://docs.scipy.org/doc/numpy/reference/generated/nump... | 1 | 2016-09-01T15:03:44Z | [
"python",
"pandas"
] |
PuLP: Using only one item per group | 39,274,840 | <p>I have a Pandas dataframe that has following values:</p>
<pre><code> Name Age City Points
1 John 24 CHI 35
2 Mary 18 NY 25
.
.
80 Steve 30 CHI 32
</code></pre>
<p>I'm trying to form a 5 person group that maximizes the sum of points. I'd like to have two constra... | 1 | 2016-09-01T14:54:13Z | 39,275,189 | <p>You can do something like this:</p>
<pre><code>for city in df['City'].unique():
sub_idx = df[df['City']==city].index
mod += pulp.lpSum([x[idx] for idx in sub_idx]) <= 1
</code></pre>
<p>For each city in the DataFrame, this sum is over a subset of DataFrame (indexed by sub_idx) and this sum should be sma... | 1 | 2016-09-01T15:09:46Z | [
"python",
"pandas",
"constraints",
"solver",
"pulp"
] |
How to test RPC of SOAP web services? | 39,274,850 | <p>I am currently learning building a SOAP web services with django and spyne. I have successfully tested my model using unit test. However, when I tried to test all those @rpc functions, I have no luck there at all.</p>
<p>What I have tried in testing those @rpc functions:
1. Get dummy data in model database
2. Start... | 0 | 2016-09-01T14:54:31Z | 39,275,854 | <p>I believe if you are using a service inside a test, that test should not be a <strong>unit</strong> test.</p>
<p>you might want to consider use <strong>factory_boy</strong> or <strong>mock</strong>, both of them are python modules to mock or fake a object, for instance, to fake a object to give a response to your r... | 0 | 2016-09-01T15:43:38Z | [
"python",
"django",
"testing",
"rpc",
"spyne"
] |
How to test RPC of SOAP web services? | 39,274,850 | <p>I am currently learning building a SOAP web services with django and spyne. I have successfully tested my model using unit test. However, when I tried to test all those @rpc functions, I have no luck there at all.</p>
<p>What I have tried in testing those @rpc functions:
1. Get dummy data in model database
2. Start... | 0 | 2016-09-01T14:54:31Z | 39,287,322 | <p>See <a href="http://stackoverflow.com/questions/19383937/testing-spyne-application">Testing Spyne application</a> </p>
<p>Ignore the remaining, it's the trivial answer guard.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim a... | 0 | 2016-09-02T08:05:15Z | [
"python",
"django",
"testing",
"rpc",
"spyne"
] |
How to find consecutive/successive objects in a list of objects | 39,274,953 | <p>I have a list of object that have attributes serial number (SN) and datetime along with others. From how the list is generated, the objects should be in chronological order.
Cronologically, objects can have the following SN:</p>
<p>1,1,1,1,1,2,2,2,3,3,3,3,3,3,2,2,1,2,2,2,2,3,3,1,1,1,3,...</p>
<p>How can I retrive ... | -1 | 2016-09-01T14:59:37Z | 39,275,667 | <p>If I understand your question correctly, maybe you are looking for something like this?</p>
<pre><code>def consecutive(nums, sn):
count = {nums[0]: [[0]]}
for idx, num in enumerate(nums[1:]):
if num == nums[idx]:
try:
count[num][-1][1] = idx + 1
except IndexEr... | 0 | 2016-09-01T15:33:41Z | [
"python"
] |
Get output of pv using python | 39,274,976 | <p>Is there a way to use the program pv from within python so as to get the progress of an operation?</p>
<p>So far I have the following:</p>
<pre><code> p0 = sp.Popen(["pv", "-f", args.filepath],
bufsize=0,
stdout=sp.PIPE,
stderr=sp.PIPE)
p1 = sp.Popen(["a... | 2 | 2016-09-01T15:00:23Z | 39,275,519 | <p>Try something like this.</p>
<pre><code>p = subprocess.Popen(command, stdout=subprocess.PIPE)
for line in iter(p.stdout.readline, ''):
print("line", line)
</code></pre>
| 0 | 2016-09-01T15:25:42Z | [
"python",
"subprocess"
] |
Get output of pv using python | 39,274,976 | <p>Is there a way to use the program pv from within python so as to get the progress of an operation?</p>
<p>So far I have the following:</p>
<pre><code> p0 = sp.Popen(["pv", "-f", args.filepath],
bufsize=0,
stdout=sp.PIPE,
stderr=sp.PIPE)
p1 = sp.Popen(["a... | 2 | 2016-09-01T15:00:23Z | 39,287,568 | <p>try reading from p0.stderr</p>
<p>pv leaves stdout untouched, it writes only to stderr</p>
| 0 | 2016-09-02T08:18:45Z | [
"python",
"subprocess"
] |
Get output of pv using python | 39,274,976 | <p>Is there a way to use the program pv from within python so as to get the progress of an operation?</p>
<p>So far I have the following:</p>
<pre><code> p0 = sp.Popen(["pv", "-f", args.filepath],
bufsize=0,
stdout=sp.PIPE,
stderr=sp.PIPE)
p1 = sp.Popen(["a... | 2 | 2016-09-01T15:00:23Z | 39,292,586 | <p>It turns out <code>pv</code> outputs each line with a carriage return at end (<code>\r</code>). To be able to continuously read from the output, <code>Popen</code> needs to be initialized with <code>universal_lines=True</code>, like this:</p>
<pre><code> p0 = sp.Popen(['pv', '-f', args.filepath],
... | 0 | 2016-09-02T12:34:38Z | [
"python",
"subprocess"
] |
Why, using pyHook, the timestamp (event.Time) of the events is wrong? | 39,274,982 | <p>This is the code that I used to debug the events:</p>
<pre><code>print("Real timestamp:", int(time()))
print("Event Timestamp:", event.Time)
print("Event Time:", strftime("%H:%M:%S %z", localtime(event.Time)))
</code></pre>
<p>And this is the output I got:</p>
<pre><code>Real timestamp: 1472741855
Event Timestamp... | 0 | 2016-09-01T15:00:37Z | 40,049,296 | <p>The time returned is not the actual Timestamp</p>
<p>The time returned comes straight from the "time" member of the Win32 EVENTMSG struct, which is in units of "milliseconds since last boot". </p>
<p>Shameless plugin from <a href="https://mail.python.org/pipermail/python-win32/2007-September/006309.html" rel="nofo... | 1 | 2016-10-14T17:55:03Z | [
"python",
"timestamp",
"pyhook"
] |
Reference part of list item in loop | 39,274,988 | <p>I am trying to turn a txt file into a new txt file with specific formatting so i can put it straight onto a website.</p>
<p>I have created a list called stats of the items to go under the Statistics heading but am now trying to write the loop to tell it to format the text in a specific way and I'm getting invalid s... | 1 | 2016-09-01T15:00:54Z | 39,275,068 | <p>Try to use the + operator when concatenating strings: <code>'<h5><a href=/"' + i.split("\t")[4] + '" target=...'</code></p>
| 0 | 2016-09-01T15:04:35Z | [
"python"
] |
Parse files in AWS S3 with boto3 | 39,275,043 | <p>I am attempting to read files from my S3 bucket, and parse them with a regex pattern. However, I have not been able to figure out to read the files line by line. Is there a way to do this or a different way I need to be approaching this for parsing?</p>
<pre><code>pattern = '^(19|20)\d\d[-.](0[1-9]|1[012])[-.](0[... | 2 | 2016-09-01T15:03:44Z | 39,285,136 | <p>Text file with below content I have used in below solution:</p>
<pre><code>I love AWS.
I love boto3.
I love boto2.
</code></pre>
<p>I think the problem is with line :</p>
<pre><code>for line in body:
</code></pre>
<p>It iterates character by character instead of line by line.</p>
<pre><code>C:\Users\Administrat... | 1 | 2016-09-02T05:49:53Z | [
"python",
"amazon-s3",
"boto3"
] |
NameError while converting tar.gz to zip | 39,275,086 | <p>I got the following code from my question on how to convert the tar.gz file to zip file. </p>
<pre><code>import tarfile, zipfile
tarf = tarfile.open(name='sample.tar.gz', mode='r|gz' )
zipf = zipfile.ZipFile.open( name='myzip.zip', mode='a', compress_type=ZIP_DEFLATED )
for m in tarf.getmembers():
f = tarf.extr... | -1 | 2016-09-01T15:05:10Z | 39,275,142 | <p><code>ZIP_DEFLATED</code> is a name <a href="https://docs.python.org/2/library/zipfile.html#zipfile.ZIP_DEFLATED" rel="nofollow">defined by the <code>zipfile</code> module</a>; reference it from there:</p>
<pre><code>zipf = zipfile.ZipFile(
'myzip.zip', mode='a',
compression=zipfile.ZIP_DEFLATED)
</code></p... | 1 | 2016-09-01T15:07:34Z | [
"python",
"zip",
"tar",
"zipfile",
"tarfile"
] |
How to calculate each string length that belongs to a list of strings by python? | 39,275,108 | <p>Suppose I have a file with <code>n</code> DNA sequences, each one in a line. I need to turn them into a list and then calculate each sequence's length and then total length of all of them together. I am not sure how to do that before they are into a list. </p>
<pre><code># open file and writing each sequences' leng... | 1 | 2016-09-01T15:06:23Z | 39,275,220 | <p>Just a couple of remarks. Use <code>with</code> to handle files so you don't have to worry about closing them after you are done reading\writing, flushing, etc. Also, since you are looping through the file once, why not create the list too? You don't need to go through it again.</p>
<pre><code># open file and writi... | 0 | 2016-09-01T15:11:02Z | [
"python",
"string",
"list",
"python-3.x",
"math"
] |
How to calculate each string length that belongs to a list of strings by python? | 39,275,108 | <p>Suppose I have a file with <code>n</code> DNA sequences, each one in a line. I need to turn them into a list and then calculate each sequence's length and then total length of all of them together. I am not sure how to do that before they are into a list. </p>
<pre><code># open file and writing each sequences' leng... | 1 | 2016-09-01T15:06:23Z | 39,275,248 | <p>Look into the <a href="https://docs.python.org/3/library/statistics.html" rel="nofollow"><code>statistics</code></a> module.
You'll find all kinds of measures of averages and spreads.</p>
<p>You'll get the length of any sequence using <code>len</code>.</p>
<p>In your case, you'll want to map the sequences to their... | 1 | 2016-09-01T15:12:38Z | [
"python",
"string",
"list",
"python-3.x",
"math"
] |
How to calculate each string length that belongs to a list of strings by python? | 39,275,108 | <p>Suppose I have a file with <code>n</code> DNA sequences, each one in a line. I need to turn them into a list and then calculate each sequence's length and then total length of all of them together. I am not sure how to do that before they are into a list. </p>
<pre><code># open file and writing each sequences' leng... | 1 | 2016-09-01T15:06:23Z | 39,275,317 | <p>Try this to output the individual length and calculate the total length:</p>
<pre><code> lines = [line.strip() for line in open('seq.txt')]
total = 0
for line in lines:
print 'this is the length of the given sequence: {}'.format(len(line))
total += len(line)
print 'this is the total len... | 2 | 2016-09-01T15:16:04Z | [
"python",
"string",
"list",
"python-3.x",
"math"
] |
How to calculate each string length that belongs to a list of strings by python? | 39,275,108 | <p>Suppose I have a file with <code>n</code> DNA sequences, each one in a line. I need to turn them into a list and then calculate each sequence's length and then total length of all of them together. I am not sure how to do that before they are into a list. </p>
<pre><code># open file and writing each sequences' leng... | 1 | 2016-09-01T15:06:23Z | 39,275,380 | <p>You have already seen how to get the list of sequences and a list of the lengths using append.</p>
<pre><code> lines = [line.strip() for line in open('seq.txt')]
total = 0
sizes = []
for line in lines:
mysize = len(line)
total += mysize
sizes.append(mysize)
</code></pre>
<p>Note... | 0 | 2016-09-01T15:18:53Z | [
"python",
"string",
"list",
"python-3.x",
"math"
] |
How to calculate each string length that belongs to a list of strings by python? | 39,275,108 | <p>Suppose I have a file with <code>n</code> DNA sequences, each one in a line. I need to turn them into a list and then calculate each sequence's length and then total length of all of them together. I am not sure how to do that before they are into a list. </p>
<pre><code># open file and writing each sequences' leng... | 1 | 2016-09-01T15:06:23Z | 39,275,472 | <p>The map and reduce functions can be useful to work on collections.</p>
<pre><code>import operator
f= open('seq.txt' , 'r')
for line in f:
line= line.strip()
print (line)
print ('this is the length of the given sequence', len(line))
# turning into a list:
lines = [line.strip() for line in open('seq.txt')]
pr... | 1 | 2016-09-01T15:23:44Z | [
"python",
"string",
"list",
"python-3.x",
"math"
] |
How to calculate each string length that belongs to a list of strings by python? | 39,275,108 | <p>Suppose I have a file with <code>n</code> DNA sequences, each one in a line. I need to turn them into a list and then calculate each sequence's length and then total length of all of them together. I am not sure how to do that before they are into a list. </p>
<pre><code># open file and writing each sequences' leng... | 1 | 2016-09-01T15:06:23Z | 39,275,492 | <p>This will do what you require. To do additional calculations you may want to save your results from the text file into a list or set so you won't need to read from a file again.</p>
<pre><code>total_length = 0 # Create a variable that will save our total length of lines read
with open('filename.txt', 'r') as f:
... | 0 | 2016-09-01T15:24:36Z | [
"python",
"string",
"list",
"python-3.x",
"math"
] |
Sort by certain order (Situation: pandas DataFrame Groupby) | 39,275,294 | <p>I want to change the day of order presented by below code.<br>
What I want is a result with the order (Mon, Tue, Wed, Thu, Fri, Sat, Sun) <br> - should I say, sort by key in certain predefined order?</p>
<hr>
<p>Here is my code which needs some tweak:</p>
<pre><code>f8 = df_toy_indoor2.groupby(['device_id', 'day'... | 4 | 2016-09-01T15:14:26Z | 39,275,559 | <p>Probably not the best way, but as far as I know you cannot pass a function/mapping to <code>sort_values</code>. As a workaround, I generally use <code>assign</code> to add a new column and sort by that column. In your example, that also requires resetting the index first (and setting it back).</p>
<pre><code>days =... | 1 | 2016-09-01T15:27:45Z | [
"python",
"sorting",
"pandas"
] |
Sort by certain order (Situation: pandas DataFrame Groupby) | 39,275,294 | <p>I want to change the day of order presented by below code.<br>
What I want is a result with the order (Mon, Tue, Wed, Thu, Fri, Sat, Sun) <br> - should I say, sort by key in certain predefined order?</p>
<hr>
<p>Here is my code which needs some tweak:</p>
<pre><code>f8 = df_toy_indoor2.groupby(['device_id', 'day'... | 4 | 2016-09-01T15:14:26Z | 39,275,671 | <p>If you sort the dataframe prior to the <code>groupby</code>, pandas will maintain the order of your sort. First thing you'll have to do is come up with a good way to sort the days of the week. One way of doing that is to assign an int representing the day of the week to each row, then sort on that column. For exampl... | 1 | 2016-09-01T15:33:57Z | [
"python",
"sorting",
"pandas"
] |
Sort by certain order (Situation: pandas DataFrame Groupby) | 39,275,294 | <p>I want to change the day of order presented by below code.<br>
What I want is a result with the order (Mon, Tue, Wed, Thu, Fri, Sat, Sun) <br> - should I say, sort by key in certain predefined order?</p>
<hr>
<p>Here is my code which needs some tweak:</p>
<pre><code>f8 = df_toy_indoor2.groupby(['device_id', 'day'... | 4 | 2016-09-01T15:14:26Z | 39,275,799 | <p>Took me some time, but I found the solution. <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.reindex.html#pandas.Series.reindex" rel="nofollow">reindex</a> does what you want. See my code example:</p>
<pre><code>a = [1, 2] * 2 + [2, 1] * 3 + [1, 2]
b = ['Mon', 'Wed', 'Thu', 'Fri'] * 3
c... | 8 | 2016-09-01T15:40:33Z | [
"python",
"sorting",
"pandas"
] |
Sort by certain order (Situation: pandas DataFrame Groupby) | 39,275,294 | <p>I want to change the day of order presented by below code.<br>
What I want is a result with the order (Mon, Tue, Wed, Thu, Fri, Sat, Sun) <br> - should I say, sort by key in certain predefined order?</p>
<hr>
<p>Here is my code which needs some tweak:</p>
<pre><code>f8 = df_toy_indoor2.groupby(['device_id', 'day'... | 4 | 2016-09-01T15:14:26Z | 39,276,164 | <p>Set the <code>'day'</code> column as <a href="http://pandas.pydata.org/pandas-docs/stable/categorical.html" rel="nofollow">categorical</a> dtype, just make sure when you set the category your list of days is sorted as you'd like it to be. Performing the <code>groupby</code> will then automatically sort it for you, ... | 2 | 2016-09-01T16:01:07Z | [
"python",
"sorting",
"pandas"
] |
Converting integer tuple to float | 39,275,304 | <p>I have a tuple of integers. In reality, this is no tuple at all but a decimal number that all languages except English represent as <em>1,2</em> while English uses <em>1.2</em>. This "tuple" is read from a file and added into an array along with a series of integers, so the data type is automatically assigned by Pyt... | -2 | 2016-09-01T15:15:02Z | 39,275,354 | <p>You mean like</p>
<pre><code>print "%s.%s"%whatever[7]
</code></pre>
<p>And if you want to convert it to float</p>
<pre><code>float("%s.%s"%whatever[7])
</code></pre>
| 1 | 2016-09-01T15:17:35Z | [
"python",
"python-3.x",
"data-type-conversion"
] |
Converting integer tuple to float | 39,275,304 | <p>I have a tuple of integers. In reality, this is no tuple at all but a decimal number that all languages except English represent as <em>1,2</em> while English uses <em>1.2</em>. This "tuple" is read from a file and added into an array along with a series of integers, so the data type is automatically assigned by Pyt... | -2 | 2016-09-01T15:15:02Z | 39,275,402 | <p>You can convert your tuple to a float by first creating the string representation <code>'1.2'</code> and then feeding that to <code>float</code>.</p>
<p>To do that you could use <code>map</code> to cast <code>int</code>s to <code>str</code>s, join them on <code>'.'</code> and feed that to <code>float()</code>.</p>
... | 1 | 2016-09-01T15:19:56Z | [
"python",
"python-3.x",
"data-type-conversion"
] |
Converting integer tuple to float | 39,275,304 | <p>I have a tuple of integers. In reality, this is no tuple at all but a decimal number that all languages except English represent as <em>1,2</em> while English uses <em>1.2</em>. This "tuple" is read from a file and added into an array along with a series of integers, so the data type is automatically assigned by Pyt... | -2 | 2016-09-01T15:15:02Z | 39,275,493 | <p>How about this?</p>
<pre><code>>>> whatever = 1,2
>>> float('.'.join(str(num) for num in whatever))
1.2
</code></pre>
<p>Like Jim's answer, it creates a <code>str</code> representation of <code>'1.2'</code> but instead of using map, it creates a generator object (basically what's behind list comp... | -1 | 2016-09-01T15:24:40Z | [
"python",
"python-3.x",
"data-type-conversion"
] |
Converting integer tuple to float | 39,275,304 | <p>I have a tuple of integers. In reality, this is no tuple at all but a decimal number that all languages except English represent as <em>1,2</em> while English uses <em>1.2</em>. This "tuple" is read from a file and added into an array along with a series of integers, so the data type is automatically assigned by Pyt... | -2 | 2016-09-01T15:15:02Z | 39,275,687 | <p>The below format will work with your given example.</p>
<pre><code>whatever[7] = 1, 2
new_num = float("{}.{}".format(whatever[7][0], whatever[7][1]))
</code></pre>
| 0 | 2016-09-01T15:34:51Z | [
"python",
"python-3.x",
"data-type-conversion"
] |
How to modify Django form before save? | 39,275,350 | <p>In my project each user can have multiple enemies, like this:</p>
<p><strong>models</strong></p>
<pre><code>class EnemyModel(models.Model):
name = models.CharField(max_length=128)
weapon = models.CharField(max_length=128)
related_user = models.ForeignKey(UserProfile)
class UserProfile(models.Model):
u... | 0 | 2016-09-01T15:17:28Z | 39,275,387 | <p>Use <code>form.instance</code>:</p>
<pre><code>def add_enemy(request):
args={}
if request.method == "POST":
form = AddEnemyForm(request.POST)
# form.instance is the instance to be saved
form.instance.related_user = request.user.userprofile
if form.is_valid():
form... | 1 | 2016-09-01T15:19:04Z | [
"python",
"django"
] |
django cannot fix integrity error | 39,275,366 | <p>I've decided to drop a row from a field from a database i'm setting up in django. I've deleted it in models/form and completely re-ran the database (makemigrations, migrate). However, no matter what I do i keep getting an integrity error (NOT NULL constraint failed: index_user.email). I'm not sure why i'm getting th... | 1 | 2016-09-01T15:18:07Z | 39,275,694 | <p>If you are using Mysql as your database backend, then when you delete any field in the django model, even you run makemigrate and migrate, Mysql will still <strong>NOT</strong> actually delete that field or column inside the database.</p>
<p>Therefore the column <strong>index_user.email</strong>, you think have del... | 0 | 2016-09-01T15:35:15Z | [
"python",
"django",
null,
"integrity"
] |
django cannot fix integrity error | 39,275,366 | <p>I've decided to drop a row from a field from a database i'm setting up in django. I've deleted it in models/form and completely re-ran the database (makemigrations, migrate). However, no matter what I do i keep getting an integrity error (NOT NULL constraint failed: index_user.email). I'm not sure why i'm getting th... | 1 | 2016-09-01T15:18:07Z | 39,276,396 | <p>you can run a fake migrations. It will let you by pass the error for now. Also try to delete your migrations first, if that does not work see if the below works. </p>
<p>python manage.py makemigrations
python manage.py migrate --fake</p>
| 0 | 2016-09-01T16:15:05Z | [
"python",
"django",
null,
"integrity"
] |
Regular expression to find text in specific section | 39,275,503 | <p>I have a regular expression problem. My data is as follows:</p>
<pre><code>[Section 1]
title = RegEx
name = Joe
color = blue
[Section 2]
height = 101
name = Gray
</code></pre>
<p>My question is can I write a regular expression to capture the 'name' key only from [Section 1]? Essentially, capture a... | -2 | 2016-09-01T15:24:56Z | 39,275,879 | <p>Using ConfigParser is pretty simple, but you need to change your data format to be like:</p>
<p>config_file.cfg</p>
<pre><code>[Section 1]
title: RegEx
name: Joe
color: blue
[Section 2]
height: 101
name: Gray
</code></pre>
<p>test_config.py</p>
<pre><code>import ConfigParser
def get_config(section, prop_file_pa... | 0 | 2016-09-01T15:44:57Z | [
"python",
"regex"
] |
Regular expression to find text in specific section | 39,275,503 | <p>I have a regular expression problem. My data is as follows:</p>
<pre><code>[Section 1]
title = RegEx
name = Joe
color = blue
[Section 2]
height = 101
name = Gray
</code></pre>
<p>My question is can I write a regular expression to capture the 'name' key only from [Section 1]? Essentially, capture a... | -2 | 2016-09-01T15:24:56Z | 39,276,158 | <p>While I wouldn't do this with regular expressions, since you asked:</p>
<pre><code>\[Section 1\][^[]*name\s*=\s*(.*)
</code></pre>
<p>The <code>[^[]</code> bit prevents the regular expression from being too greedy and matching a "name" outside of the specified section (assuming no other fields/lines within a secti... | 0 | 2016-09-01T16:00:49Z | [
"python",
"regex"
] |
Regular expression to find text in specific section | 39,275,503 | <p>I have a regular expression problem. My data is as follows:</p>
<pre><code>[Section 1]
title = RegEx
name = Joe
color = blue
[Section 2]
height = 101
name = Gray
</code></pre>
<p>My question is can I write a regular expression to capture the 'name' key only from [Section 1]? Essentially, capture a... | -2 | 2016-09-01T15:24:56Z | 39,279,468 | <p>Just for reference, you could use the newer <code>regex</code> module and named capture groups:</p>
<pre><code>import regex as re
rx = re.compile("""
(?(DEFINE)
(?<section>^\[Section\ \d+\])
)
(?&section)
(?:(?!(?&section))[\s\S])*
... | 0 | 2016-09-01T19:27:52Z | [
"python",
"regex"
] |
Select row from a DataFrame based on the type of the object(i.e. str) | 39,275,533 | <p>So there's a DataFrame say:</p>
<pre><code>>>> df = pd.DataFrame({
... 'A':[1,2,'Three',4],
... 'B':[1,'Two',3,4]})
>>> df
A B
0 1 1
1 2 Two
2 Three 3
3 4 4
</code></pre>
<p>I want to select the rows whose datatype of particular ... | 3 | 2016-09-01T15:26:20Z | 39,275,726 | <p>You can do something <em>similar</em> to what you're asking with</p>
<pre><code>In [14]: df[pd.to_numeric(df.A, errors='coerce').isnull()]
Out[14]:
A B
2 Three 3
</code></pre>
<p>Why only similar? Because Pandas stores things in homogeneous columns (all entries in a column are of the same type). Even th... | 2 | 2016-09-01T15:36:46Z | [
"python",
"pandas"
] |
Select row from a DataFrame based on the type of the object(i.e. str) | 39,275,533 | <p>So there's a DataFrame say:</p>
<pre><code>>>> df = pd.DataFrame({
... 'A':[1,2,'Three',4],
... 'B':[1,'Two',3,4]})
>>> df
A B
0 1 1
1 2 Two
2 Three 3
3 4 4
</code></pre>
<p>I want to select the rows whose datatype of particular ... | 3 | 2016-09-01T15:26:20Z | 39,277,211 | <p>This works:</p>
<pre><code>df[df['A'].apply(lambda x: type(x)==str)]
</code></pre>
| 2 | 2016-09-01T17:03:33Z | [
"python",
"pandas"
] |
Tokenizing a corpus composed of articles into sentences Python | 39,275,547 | <p>I will like to analyze my first deep learning model using Python and in order to do so I have to first split my corpus (8807 articles) into sentences. My corpus is built as follows:</p>
<pre><code>## Libraries to download
from nltk.tokenize import RegexpTokenizer
from nltk.corpus import stopwords
from nltk.stem.por... | 2 | 2016-09-01T15:27:12Z | 39,277,615 | <p>So, Gensim's <code>Word2Vec</code> requires this format for its training input: <code>sentences = [['first', 'sentence'], ['second', 'sentence']]</code>.</p>
<p>I assume your documents contain more than one sentence. You should first split by sentences, you can do that with <a href="http://www.nltk.org/api/nltk.tok... | 1 | 2016-09-01T17:29:38Z | [
"python",
"deep-learning",
"gensim",
"word2vec"
] |
Regrid numpy array based on cell area | 39,275,552 | <pre><code>import numpy as np
from skimage.measure import block_reduce
arr = np.random.random((6, 6))
area_cell = np.random.random((6, 6))
block_reduce(arr, block_size=(2, 2), func=np.ma.mean)
</code></pre>
<p>I would like to regrid a numpy array <code>arr</code> from 6 x 6 size to 3 x 3. Using the skimage function ... | 3 | 2016-09-01T15:27:22Z | 39,284,287 | <p>It seems you are still reducing by blocks, but after scaling <code>arr</code> with <code>area_cell</code>. So, you just need to perform element-wise multiplication between these two arrays and use the same <code>block_reduce</code> code on that product array, like so -</p>
<pre><code>block_reduce(arr*area_cell, blo... | 2 | 2016-09-02T04:25:03Z | [
"python",
"numpy",
"skimage"
] |
TensorFlow: How to write multistep decay | 39,275,641 | <p>There is multistep decay in Caffe. It is calculated as <code>base_lr * gamma ^ (floor(step))</code> where <code>step</code> is incremented after each of your decay steps. For example with <code>[100, 200]</code> decay steps and <code>global step=101</code> I want get <code>base_lr * gamma ^ 1</code>, for <code>globa... | 0 | 2016-09-01T15:31:40Z | 39,278,807 | <p>Use <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/train.html#exponential_decay" rel="nofollow"><code>tf.train.exponential_decay()</code></a>, it's exactly what you're looking for. The decayed learning rate is computed as follows:</p>
<pre><code>decayed_learning_rate = learning_rate *
... | 0 | 2016-09-01T18:46:23Z | [
"python",
"tensorflow"
] |
Python Tools for Visual Studio and Unit Tests (PTVS) | 39,275,712 | <p>Hopefully someone can give me a hand/few pointers.</p>
<p>So I am currently working on some python scripts and wanted to get some tests written.</p>
<p>My environment is as follows:
MS Visual Studio Community 2015, v.14 Update 3
PTVS v.2.2.4 (2.2.40623.00-14.0)
Python 3.5 64-bit Environment</p>
<p>I have some dem... | 0 | 2016-09-01T15:36:08Z | 39,348,631 | <p>Ok, so it seems that PTVS does not fully work with VS2015 Community Edition.</p>
<p>You can run your scripts etc, but it does not integrate with the test explorer properly.</p>
<p>You will need to download VS2013 CE, and PTVS 2.2.2. Then you can run the test explorer and click run all, which will find all your tes... | 0 | 2016-09-06T12:04:13Z | [
"python",
"python-3.x",
"visual-studio-2015",
"ptvs"
] |
Check if object attribute name appears in a string python | 39,275,713 | <p>I want to:</p>
<ul>
<li>check whether a string contains an object property</li>
<li>if it does then access the attribute</li>
</ul>
<p>So for an object of class </p>
<pre><code>class Person(object):
name = ""
age = 0
major = ""
def __init__(self, name="", surname="", father="", age =0):
s... | 1 | 2016-09-01T15:36:17Z | 39,275,857 | <p>You are looking for the function <code>hasattr()</code> and <code>getattr()</code>.</p>
<p>To check whether the attribute exists:</p>
<pre><code>hasattr(Person(), 'string')
</code></pre>
<p>And to call the attribute:</p>
<pre><code>getattr(Person(), 'string')
</code></pre>
| 3 | 2016-09-01T15:43:50Z | [
"python",
"string",
"python-2.7",
"class",
"object"
] |
Check if object attribute name appears in a string python | 39,275,713 | <p>I want to:</p>
<ul>
<li>check whether a string contains an object property</li>
<li>if it does then access the attribute</li>
</ul>
<p>So for an object of class </p>
<pre><code>class Person(object):
name = ""
age = 0
major = ""
def __init__(self, name="", surname="", father="", age =0):
s... | 1 | 2016-09-01T15:36:17Z | 39,276,801 | <p>As others have noted, <a href="https://docs.python.org/3/library/functions.html#getattr" rel="nofollow"><code>getattr</code></a> is generally useful.</p>
<p><a href="https://docs.python.org/3/library/functions.html#hasattr" rel="nofollow"><code>hasattr</code></a> is of lesser utility; internally, it's basically a <... | 1 | 2016-09-01T16:41:23Z | [
"python",
"string",
"python-2.7",
"class",
"object"
] |
TypeError: in method 'new_Dialog', expected argument 1 of type 'wxWindow *' | 39,275,718 | <p>I am trying to build a file browser that uses SSH to browse files in a remote location. My GUI code keeps throwing one error or another at me so I can't even test the SSH portion (not included in below code). My current error seems to be a problem with either my class constructor or the way I call it [SSHFileDialog]... | 0 | 2016-09-01T15:36:25Z | 39,275,778 | <p>you are likely working off an old tutorial</p>
<pre><code>wx.Dialog.__init__(self,*args,**kwargs) #here you need self, as this does not pass self implicitly
</code></pre>
<p>whereas </p>
<pre><code>super(MyDialogClass,self).__init__(*args,**kwargs) # here self is passed implicitly (eg you do not pass self as the ... | 1 | 2016-09-01T15:39:41Z | [
"python",
"user-interface",
"inheritance",
"wxpython"
] |
TypeError: in method 'new_Dialog', expected argument 1 of type 'wxWindow *' | 39,275,718 | <p>I am trying to build a file browser that uses SSH to browse files in a remote location. My GUI code keeps throwing one error or another at me so I can't even test the SSH portion (not included in below code). My current error seems to be a problem with either my class constructor or the way I call it [SSHFileDialog]... | 0 | 2016-09-01T15:36:25Z | 39,277,564 | <p>You are passing an extra <code>self</code> to <code>wx.Dialog.__init__</code>. The call to <code>super</code> is essentially creating the bound method for you so you don't need to pass <code>self</code> again.</p>
<pre><code>super(SSHFileDialog, self).__init__(parent, -1, style = wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_... | 0 | 2016-09-01T17:26:31Z | [
"python",
"user-interface",
"inheritance",
"wxpython"
] |
Python Check for decimals | 39,275,730 | <p>i'm making a program which divides a lot of numbers and I want to check if the number gets decimals or not. I also want it to print those decimals. Example:</p>
<pre><code>foo = 7/3
if foo has a 3 in the decimals: (Just an example of what I want to do there)
print("It works!)
elif foo has no decimals: (another ... | 1 | 2016-09-01T15:36:50Z | 39,275,765 | <p>Based on the wording of your question I am assuming that you are looking to see if a certain number comes after the decimal point? If that is the case...</p>
<p>What you can do is split foo using <code>.</code> as the delimiter and check to see if the number, in this case you're looking for 3, is in portion after t... | 0 | 2016-09-01T15:39:15Z | [
"python"
] |
Python Check for decimals | 39,275,730 | <p>i'm making a program which divides a lot of numbers and I want to check if the number gets decimals or not. I also want it to print those decimals. Example:</p>
<pre><code>foo = 7/3
if foo has a 3 in the decimals: (Just an example of what I want to do there)
print("It works!)
elif foo has no decimals: (another ... | 1 | 2016-09-01T15:36:50Z | 39,275,808 | <p>If you just want to test whether a division has decimals, just check the modulo:</p>
<pre><code>foo = a % b
if foo != 0:
# Then foo contains decimals
pass
if foo == 0:
# Then foo does NOT contain decimals
pass
</code></pre>
<p>However (since your question is a bit unclear) if you want to split the... | 2 | 2016-09-01T15:41:02Z | [
"python"
] |
Python Check for decimals | 39,275,730 | <p>i'm making a program which divides a lot of numbers and I want to check if the number gets decimals or not. I also want it to print those decimals. Example:</p>
<pre><code>foo = 7/3
if foo has a 3 in the decimals: (Just an example of what I want to do there)
print("It works!)
elif foo has no decimals: (another ... | 1 | 2016-09-01T15:36:50Z | 39,275,846 | <p>your question is slightly unclear. However this bit of code might get you in the right direction. Just call <code>Decimal_Checker</code> and input the numbers you want.</p>
<pre><code>def Decimal_Checker(x,y):
if x %y != 0:
print("it has decimals")
else:
print("it does not have decimals")
D... | 0 | 2016-09-01T15:42:32Z | [
"python"
] |
Change components properties in large scale | 39,275,731 | <p>I have a reasonable amount of components attached to a window. I want to change some properties of these components when a button is pressed.
But do this in one component at a time is a boring job and will involve many lines of code.
It is possible to make a component to listen the other component signal to perform ... | 0 | 2016-09-01T15:36:50Z | 39,286,333 | <p>This may not be the answer you wanted but...</p>
<p>You are probably optimizing in the wrong place. The window in your example takes about 6 lines of very straight-forward code to 'reset'. This is insignificant compared to the benefits of the solution:</p>
<ul>
<li>the code is very easy to understand later on</li>... | 0 | 2016-09-02T07:10:41Z | [
"python",
"gtk",
"gtk3"
] |
QTreeView checkbox has empty focus | 39,275,876 | <p>Why does my QTreeView, using PySide, have this little small empty boxed area that the user can click and get a dotted focus box around? How can I remove it? I only want a simple checkbox in the first column.</p>
<p><a href="http://i.stack.imgur.com/6nsWd.png" rel="nofollow"><img src="http://i.stack.imgur.com/6nsWd.... | 1 | 2016-09-01T15:44:49Z | 39,278,382 | <p>The first column shows a focus-rectangle because you set its text to an empty string. So if you don't want that to happen, don't set any text all.</p>
<p>Alternatively, you could make the view show a focus-rectangle for the whole row, rather than separately for each column:</p>
<pre><code> self.uiItems.setAllCo... | 1 | 2016-09-01T18:16:55Z | [
"python",
"checkbox",
"pyside",
"qtreeview"
] |
Setting label_suffix for a Django model formset | 39,275,925 | <p>I have a Product model that I use to create ProductFormSet. How do I specify the label_suffix to be something other than the default colon? I want it to be blank. Solutions I've seen only seem to apply when initiating a form - <a href="http://stackoverflow.com/questions/23973954/adding-a-label-suffix-to-modelform">h... | 2 | 2016-09-01T15:47:38Z | 39,276,286 | <p>In Django 1.9+, you can use the <a href="https://docs.djangoproject.com/en/1.10/topics/forms/formsets/#passing-custom-parameters-to-formset-forms" rel="nofollow"><code>form_kwargs</code></a> option.</p>
<pre><code>ProductFormSet = modelformset_factory(Product, exclude=('abc',))
products = Product.objects.order_... | 1 | 2016-09-01T16:08:28Z | [
"python",
"django"
] |
Python detect linux shutdown and run a command before shutting down | 39,275,948 | <p>Is it possible to detect and interrupt linux (Ubuntu 16.04) shutdown signal (e.g. power button clicked or runs out of battery). I have a python application that is always recording a video and I want to detect such signal so I close the recording properly before OS shutdown.</p>
| 2 | 2016-09-01T15:49:07Z | 39,275,997 | <p>When linux is shut down, all processes receive <code>SIGTERM</code> and if they won't terminate after some timeout they are killed with <code>SIGKILL</code>. You can implement a signal handler to properly shutdown your application using the <a href="https://docs.python.org/2.7/library/signal.html" rel="nofollow"><c... | 1 | 2016-09-01T15:51:59Z | [
"python",
"linux",
"python-2.7",
"ubuntu"
] |
Python detect linux shutdown and run a command before shutting down | 39,275,948 | <p>Is it possible to detect and interrupt linux (Ubuntu 16.04) shutdown signal (e.g. power button clicked or runs out of battery). I have a python application that is always recording a video and I want to detect such signal so I close the recording properly before OS shutdown.</p>
| 2 | 2016-09-01T15:49:07Z | 39,276,283 | <p>Look into <a href="http://askubuntu.com/questions/1175/execute-script-before-shutting-down">this</a>
Basically, put a script in /etc/rc0.d/ with the right name and execute a call to you python script. </p>
| 0 | 2016-09-01T16:08:09Z | [
"python",
"linux",
"python-2.7",
"ubuntu"
] |
Accessing the most recent line in a continuously updating file using python | 39,276,062 | <p>I am reading data from a file 'aisha.txt'. The data is read line by line and the file is continuously updating and now I want to access the most recent line or end of file. How can I do that?</p>
<p>The code used for writing to the file is: </p>
<pre><code>import time
a= open('c:/test/aisha.txt','w')
while(1):
... | 0 | 2016-09-01T15:55:33Z | 39,276,656 | <p>To read the last line in a file, it is easiest if you know the maximum length of any line in the file. Then you can seek back that number of characters from the end of the file and read forward. The last line you read before end of file is the one you want.</p>
<pre><code>import os
MAXLEN = 132
file = open('te... | 0 | 2016-09-01T16:32:31Z | [
"python",
"file"
] |
Creating an MD5 Hash of A ZipFile | 39,276,248 | <p>I want to create an MD5 hash of a <code>ZipFile</code>, not of one of the files inside it. However, <code>ZipFile</code> objects aren't easily convertible to streams.</p>
<pre><code>from hashlib import md5
from zipfile import ZipFile
zipped = ZipFile(r'/Foo/Bar/Filename.zip')
hasher = md5()
hasher.update(zipped)
... | 0 | 2016-09-01T16:05:48Z | 39,276,476 | <p>This function should return the MD5 hash of any file, provided it's path (requires <code>pycrypto</code> module):</p>
<pre><code>from Crypto.Hash import MD5
def get_MD5(file_path):
chunk_size = 8192
h = MD5.new()
with open(file_path, 'rb') as f:
while True:
chunk = f.read(chunk_... | 3 | 2016-09-01T16:20:52Z | [
"python"
] |
Creating an MD5 Hash of A ZipFile | 39,276,248 | <p>I want to create an MD5 hash of a <code>ZipFile</code>, not of one of the files inside it. However, <code>ZipFile</code> objects aren't easily convertible to streams.</p>
<pre><code>from hashlib import md5
from zipfile import ZipFile
zipped = ZipFile(r'/Foo/Bar/Filename.zip')
hasher = md5()
hasher.update(zipped)
... | 0 | 2016-09-01T16:05:48Z | 39,276,477 | <p>Just open the ZipFile as a regular file. Following code works on my machine.</p>
<pre><code>from hashlib import md5
m = md5()
with open("/Foo/Bar/Filename.zip", "rb") as f:
data = f.read() #read file in chunk and call update on each chunk if file is large.
m.update(data)
print m.hexdigest()
</code></pre... | 3 | 2016-09-01T16:21:01Z | [
"python"
] |
merge two dataframe columns into 1 in pandas | 39,276,249 | <p>I have 2 columns in my data frame and I need to merge it into 1 single column</p>
<pre><code>Index A Index B
0 A 0 NAN
1 NAN 1 D
2 B 2 NAN
3 NAN 3 E
4 C 4 NAN
</code></pre>
<p>there will al... | 3 | 2016-09-01T16:05:50Z | 39,276,308 | <p><strong><em>Option 1</em></strong></p>
<pre><code>df.stack().dropna().reset_index(drop=True)
0 A
1 D
2 B
3 E
4 C
dtype: object
</code></pre>
<p><strong><em>Option 2</em></strong>
If Missing values are always alternating</p>
<pre><code>df.A.combine_first(df.B)
Index
0 A
1 D
2 B
3 E
4 ... | 4 | 2016-09-01T16:09:26Z | [
"python",
"pandas"
] |
apply 1-to-group tranformations in pandas - python | 39,276,293 | <p>I have a dataframe like the following</p>
<pre><code>import pandas as pd
df = pd.DataFrame({"id": ["a", "b", "c", "d"], "v": [1,2,3,4], "type": ["X", "Y", "Y", "Y"]}).set_index("id")
print(df)
</code></pre>
<p>which yields:</p>
<pre><code> type v
id
a X 1
b Y 2
c Y 3
d Y 4
</code><... | 2 | 2016-09-01T16:08:41Z | 39,276,392 | <p>Transform will actually get you what you want (if I understand correctly):</p>
<pre><code>df['v'] = df['v'] - df.groupby('type')['v'].transform('mean')
</code></pre>
<p>Transform calculates the applied function by group, but broadcasts the result on the original index.</p>
<hr>
<p><strong>Edit</strong>: timing c... | 4 | 2016-09-01T16:14:51Z | [
"python",
"function",
"pandas",
"grouping"
] |
apply 1-to-group tranformations in pandas - python | 39,276,293 | <p>I have a dataframe like the following</p>
<pre><code>import pandas as pd
df = pd.DataFrame({"id": ["a", "b", "c", "d"], "v": [1,2,3,4], "type": ["X", "Y", "Y", "Y"]}).set_index("id")
print(df)
</code></pre>
<p>which yields:</p>
<pre><code> type v
id
a X 1
b Y 2
c Y 3
d Y 4
</code><... | 2 | 2016-09-01T16:08:41Z | 39,278,439 | <p>IIUC try this:</p>
<pre><code> df ['v'] = df.groupby("type")['v'].apply(lambda x: x-x.mean())
df
type v
id
a X 0.0
b Y -1.0
c Y 0.0
d Y 1.0
â
</code></pre>
| 1 | 2016-09-01T18:21:16Z | [
"python",
"function",
"pandas",
"grouping"
] |
Unable to use filter on an iterable RDD in pyspark | 39,276,344 | <p>I'm trying to apply a function that filters out certain values in a dataset based on ranges of data in another dataset. I've performed a few groupBys and joins, so the format of the parameter I'm passing into the function has two Iterables, and goes as follows:</p>
<pre><code>g1 = g0.map(lambda x: timefilter(x[0]))... | 0 | 2016-09-01T16:11:59Z | 39,278,814 | <p>Turns out that filtering on an iterable RDD isn't possible, so I just used the python in-built filter function. Something along the lines of the following: <code>filter(lambda x: x[1] in oneList, twoList)</code>.</p>
| 0 | 2016-09-01T18:46:40Z | [
"python",
"list",
"filter",
"pyspark",
"iterable"
] |
How get specific element from a div with same id and class in Python | 39,276,346 | <p>I want to print "United state" and California in separated lines like</p>
<pre><code>Country is : United State
State is : California
</code></pre>
<p>The problem is each list item has the same class and id so when I loop through the list items it gives United States and California together.</p>
<p>I hope you guys... | 0 | 2016-09-01T16:12:08Z | 39,276,398 | <p>You have the relevant parts of <code>onclick</code> attribute defining what breadcrumb is country and which is state. I would use a partial match via <code>*=</code> <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors" rel="nofollow">CSS selector</a> to implement that:</p>
<pre><code># -*-... | 1 | 2016-09-01T16:15:19Z | [
"python",
"html5",
"python-3.x",
"beautifulsoup"
] |
Iteratively count elements in list and store count in dictionary | 39,276,375 | <p>I have a piece of code that loops through a set of nodes and counts the path length connecting the given node to each other node in my network. For each node my code returns me a list, <code>b</code> containing integer values giving me the path length for every possible connection. I want to count the number of occu... | 2 | 2016-09-01T16:14:09Z | 39,276,738 | <p>The check that element exists in <code>dict</code> is not really necessary. You can just use <code>collections.defaultdict</code>. Its initialization accepts callable object (like function) that will be called if you want to access (or assign something to) element that does not exist to generate the value (i.e. func... | 1 | 2016-09-01T16:37:40Z | [
"python",
"performance",
"list",
"dictionary",
"graph-tool"
] |
Iteratively count elements in list and store count in dictionary | 39,276,375 | <p>I have a piece of code that loops through a set of nodes and counts the path length connecting the given node to each other node in my network. For each node my code returns me a list, <code>b</code> containing integer values giving me the path length for every possible connection. I want to count the number of occu... | 2 | 2016-09-01T16:14:09Z | 39,276,773 | <p>Since <code>gt.shortest_distance</code> returns an <code>ndarray</code>, <code>numpy</code> math is fastest:</p>
<pre><code>max_dist = len(vertices) - 1
hist_length = max_dist + 2
no_path_dist = max_dist + 1
hist = np.zeros(hist_length)
for ver in vertices:
dist = gt.shortest_distance(g, source=g.vertex(ver))
... | 1 | 2016-09-01T16:39:52Z | [
"python",
"performance",
"list",
"dictionary",
"graph-tool"
] |
Iteratively count elements in list and store count in dictionary | 39,276,375 | <p>I have a piece of code that loops through a set of nodes and counts the path length connecting the given node to each other node in my network. For each node my code returns me a list, <code>b</code> containing integer values giving me the path length for every possible connection. I want to count the number of occu... | 2 | 2016-09-01T16:14:09Z | 39,282,221 | <p>I think you can bypass this code entirely. Your question is tagged with <a href="/questions/tagged/graph-tool" class="post-tag" title="show questions tagged 'graph-tool'" rel="tag">graph-tool</a>. Take a look at this section of their documentation: <a href="https://graph-tool.skewed.de/static/doc/stats.html?... | 0 | 2016-09-01T23:20:22Z | [
"python",
"performance",
"list",
"dictionary",
"graph-tool"
] |
Iteratively count elements in list and store count in dictionary | 39,276,375 | <p>I have a piece of code that loops through a set of nodes and counts the path length connecting the given node to each other node in my network. For each node my code returns me a list, <code>b</code> containing integer values giving me the path length for every possible connection. I want to count the number of occu... | 2 | 2016-09-01T16:14:09Z | 39,292,803 | <p>There is a utility in the <code>collections</code> module called <code>Counter</code>. This is even cleaner than using a <code>defaultdict(int)</code></p>
<pre><code>from collections import Counter
hist = Counter()
for ver in vertices:
dist = gt.shortest_distance(g, source=g.vertex(ver))
a = dist.a
#Del... | 1 | 2016-09-02T12:46:58Z | [
"python",
"performance",
"list",
"dictionary",
"graph-tool"
] |
How to create a csv file of data created in python | 39,276,423 | <p>I am new to programming. I was wondering if anyone can help me create a csv file for the data that I created in python.
My data looks like this</p>
<pre><code>import numpy as np
print np.__version__
a = 0.75 + (1.25 - 0.75)*np.random.sample(10000)
print a
b = 8 + (12 - 8)*np.random.sample(10000)
print b
c = -12 ... | 2 | 2016-09-01T16:17:31Z | 39,276,585 | <pre><code>with open("file.csv",'w') as f:
f.write('a,b,c,x0\n')
--forloop where you generate a,b,c,x0:
f.write(','.join(map(str,[a,b,c,x0])) + '\n')
</code></pre>
| 2 | 2016-09-01T16:28:04Z | [
"python",
"python-2.7",
"python-3.x",
"csv",
"export-to-csv"
] |
How to create a csv file of data created in python | 39,276,423 | <p>I am new to programming. I was wondering if anyone can help me create a csv file for the data that I created in python.
My data looks like this</p>
<pre><code>import numpy as np
print np.__version__
a = 0.75 + (1.25 - 0.75)*np.random.sample(10000)
print a
b = 8 + (12 - 8)*np.random.sample(10000)
print b
c = -12 ... | 2 | 2016-09-01T16:17:31Z | 39,278,929 | <p>There are four range of values you need to iterate over. Every iteration should correspond to each new line written.</p>
<p>Try this:</p>
<pre><code>import numpy as np
print np.__version__
import csv
a_range = 0.75 + (1.25 - 0.75)*np.random.sample(10000)
b_range = 8 + (12 - 8)*np.random.sample(10000)
c_range = -... | 1 | 2016-09-01T18:54:08Z | [
"python",
"python-2.7",
"python-3.x",
"csv",
"export-to-csv"
] |
Read a column then write in another column from a CSV file with Python | 39,276,431 | <p>I have a CSV file which contains 10 lines and 5 column.</p>
<p>For each lines, excepted first line,
I need to read column 2 and to recognize the beginning or the end of the cell.
Depending on what the script reads on each column 2, it writes a letter in colomn 6 from the same line.</p>
<p>Thank a lot in advance i... | -1 | 2016-09-01T16:17:49Z | 39,277,149 | <p>If that is your actual code, you do not have the variable "rows" available at the current scope. You have 'line'. Perhaps you mean something to the effect of </p>
<pre><code>for row in reader
</code></pre>
<p>?? The documentation I'm reading says that a line is a row, there should be columns in your line/row.</p>
| 1 | 2016-09-01T17:00:24Z | [
"python",
"csv",
"pandas",
"data-science"
] |
Transform dictionary object | 39,276,493 | <p>This dict structure :</p>
<pre class="lang-py prettyprint-override"><code>data = {
'a': { 'category': ['c', 'd'] },
'b': { 'category': ['c', 'd'] }
}
</code></pre>
<p>should become this dict structure:</p>
<pre class="lang-py prettyprint-override"><code>data = {
'c' : ['a', 'b'],
'd' : ['a', 'b']
... | 4 | 2016-09-01T16:22:03Z | 39,276,521 | <p>You can solve it with a <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict(list)</code></a>, iterating over the categories and appending keys:</p>
<pre><code>>>> from collections import defaultdict
>>>
>>> d = defaultdict(... | 4 | 2016-09-01T16:24:03Z | [
"python",
"python-3.x",
"dictionary"
] |
Transform dictionary object | 39,276,493 | <p>This dict structure :</p>
<pre class="lang-py prettyprint-override"><code>data = {
'a': { 'category': ['c', 'd'] },
'b': { 'category': ['c', 'd'] }
}
</code></pre>
<p>should become this dict structure:</p>
<pre class="lang-py prettyprint-override"><code>data = {
'c' : ['a', 'b'],
'd' : ['a', 'b']
... | 4 | 2016-09-01T16:22:03Z | 39,276,624 | <pre><code>if 'category' in value:
</code></pre>
<p>This line makes sure that the key <code>category</code> is in the dictionary, before using it. Then you get the value from the dictionary corresponding to <code>category</code> and iterate it. You can simplify this with <code>dict.get</code> method, which would retur... | 2 | 2016-09-01T16:30:38Z | [
"python",
"python-3.x",
"dictionary"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.