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 |
|---|---|---|---|---|---|---|---|---|---|
Python & Matplotlib: How to plot the range of bootstrap histogram plot? | 38,558,921 | <p>I want to example the variance of a dataset, by bootstrap(resample) the data.</p>
<pre><code>from numpy.random import randn
fig,ax = plt.subplots()
bins = arange(-5,6,0.5)
df = pd.DataFrame(randn(3000))
df.hist(ax=ax, bins=bins, alpha = 0.7, normed=True)
count_collection = []
for i in xrange(1,100):
temp_df ... | 0 | 2016-07-25T02:33:01Z | 38,560,667 | <p>To extract the max and min you may use the following:</p>
<pre><code>count_collection = np.array(count_collection)
mx = np.max(count_collection,0)
mn = np.min(count_collection,0)
</code></pre>
<p>The first line just changes from a list of 1d arrays to 2d array, so max and min can operate.</p>
<p><strong>edit:</st... | 1 | 2016-07-25T06:01:44Z | [
"python",
"numpy",
"matplotlib"
] |
Tensorflow Wide & Deep Example Not Working | 38,558,976 | <p>I am trying to get the <a href="https://www.tensorflow.org/versions/r0.9/tutorials/wide_and_deep/index.html" rel="nofollow">Wide & Deep</a> tutorial working but the following line keeps giving me issues when copying and pasting the code from github and the website. </p>
<pre><code>df_train["income_bracket"].app... | 0 | 2016-07-25T02:43:05Z | 39,359,972 | <p>lambda function is quite useful and simple. It won't create dummy variables.
I've noticed that you import the original data into a CSV file. Try not do that and just use the original downloading data that shown in tutorial code. I have successfully tried in this way.
But I also got the same problem when I change t... | 1 | 2016-09-07T01:24:31Z | [
"python",
"python-2.7",
"tensorflow"
] |
Tensorflow Wide & Deep Example Not Working | 38,558,976 | <p>I am trying to get the <a href="https://www.tensorflow.org/versions/r0.9/tutorials/wide_and_deep/index.html" rel="nofollow">Wide & Deep</a> tutorial working but the following line keeps giving me issues when copying and pasting the code from github and the website. </p>
<pre><code>df_train["income_bracket"].app... | 0 | 2016-07-25T02:43:05Z | 39,405,734 | <p>It's the issue of the data, or the code of TensorFlow. We have submit the issue about that in <a href="https://github.com/tensorflow/tensorflow/issues/4293" rel="nofollow">https://github.com/tensorflow/tensorflow/issues/4293</a></p>
<p>You can download the files manually and remove the broken lines. Then run with t... | 0 | 2016-09-09T07:07:18Z | [
"python",
"python-2.7",
"tensorflow"
] |
Multi-threading vs single thread calculations | 38,559,118 | <pre><code>def dowork():
y = []
z = []
ab = 0
start_time = time.time()
t = threading.current_thread()
for x in range(0,1500):
y.append(random.randint(0,100000))
for x in range(0,1500):
z.append(random.randint(0,1000))
for x in range(0,100):
for k in range(0,len(z)):
ab += y[k] ** z[k]... | 0 | 2016-07-25T03:03:52Z | 38,559,332 | <p>In CPython, threads don't run in parallel because of the Global Intepreter Lock. From the Python wiki (<a href="https://wiki.python.org/moin/GlobalInterpreterLock" rel="nofollow">https://wiki.python.org/moin/GlobalInterpreterLock</a>):</p>
<blockquote>
<p>In CPython, the global interpreter lock, or GIL, is a mute... | 0 | 2016-07-25T03:35:12Z | [
"python",
"multithreading",
"python-3.x"
] |
Multi-threading vs single thread calculations | 38,559,118 | <pre><code>def dowork():
y = []
z = []
ab = 0
start_time = time.time()
t = threading.current_thread()
for x in range(0,1500):
y.append(random.randint(0,100000))
for x in range(0,1500):
z.append(random.randint(0,1000))
for x in range(0,100):
for k in range(0,len(z)):
ab += y[k] ** z[k]... | 0 | 2016-07-25T03:03:52Z | 38,559,358 | <p><a href="http://www.dabeaz.com/GIL/" rel="nofollow">Here is a link to presentations about the GIL</a> <a href="http://www.dabeaz.com/GIL/" rel="nofollow">http://www.dabeaz.com/GIL/</a></p>
<p>The author of these presentations explained GIL in detail with examples. He also has a few videos posted on Youtube</p>
<p>... | 2 | 2016-07-25T03:38:48Z | [
"python",
"multithreading",
"python-3.x"
] |
Multi-threading vs single thread calculations | 38,559,118 | <pre><code>def dowork():
y = []
z = []
ab = 0
start_time = time.time()
t = threading.current_thread()
for x in range(0,1500):
y.append(random.randint(0,100000))
for x in range(0,1500):
z.append(random.randint(0,1000))
for x in range(0,100):
for k in range(0,len(z)):
ab += y[k] ** z[k]... | 0 | 2016-07-25T03:03:52Z | 38,559,374 | <p>Multithreading in Python does not work like other languages, it has something to do with the <a href="https://wiki.python.org/moin/GlobalInterpreterLock" rel="nofollow">global interpreter lock</a> if I recalled correctly. There are a lot of different workarounds though, for example you can use <a href="http://sdiehl... | 2 | 2016-07-25T03:41:50Z | [
"python",
"multithreading",
"python-3.x"
] |
Multi-threading vs single thread calculations | 38,559,118 | <pre><code>def dowork():
y = []
z = []
ab = 0
start_time = time.time()
t = threading.current_thread()
for x in range(0,1500):
y.append(random.randint(0,100000))
for x in range(0,1500):
z.append(random.randint(0,1000))
for x in range(0,100):
for k in range(0,len(z)):
ab += y[k] ** z[k]... | 0 | 2016-07-25T03:03:52Z | 38,596,340 | <p>Here is a complete test and example regarding multithreading and multiprocessing vs single threaded/process.</p>
<p>The computation, you can pick any computation you want.</p>
<pre><code>import time, os, threading, random, multiprocessing
def dowork():
total = 0
start_time = time.time()
t = threading.curr... | 0 | 2016-07-26T17:27:54Z | [
"python",
"multithreading",
"python-3.x"
] |
iterate over only two keys of python dictionary | 38,559,145 | <p>What is the pythonic way to iterate over a dictionary with a setup like this:</p>
<pre><code>dict = {'a': [1, 2, 3], 'b': [3, 4, 5], 'c': 6}
</code></pre>
<p>if I only wanted to iterate a for loop over all the values in <code>a</code> and <code>b</code> and skip <code>c</code>. There's obviously a million ways to... | 0 | 2016-07-25T03:07:37Z | 38,559,202 | <p>You can use <a href="https://docs.python.org/3.5/library/itertools.html#itertools.chain" rel="nofollow"><code>chain</code></a> from the <code>itertools</code> module to do this:</p>
<pre><code>In [29]: from itertools import chain
In [30]: mydict = {'a': [1, 2, 3], 'b': [3, 4, 5], 'c': 6}
In [31]: for item in chai... | 1 | 2016-07-25T03:17:35Z | [
"python",
"dictionary"
] |
iterate over only two keys of python dictionary | 38,559,145 | <p>What is the pythonic way to iterate over a dictionary with a setup like this:</p>
<pre><code>dict = {'a': [1, 2, 3], 'b': [3, 4, 5], 'c': 6}
</code></pre>
<p>if I only wanted to iterate a for loop over all the values in <code>a</code> and <code>b</code> and skip <code>c</code>. There's obviously a million ways to... | 0 | 2016-07-25T03:07:37Z | 38,559,234 | <p>The more generic way is using filter-like approaches by putting an <code>if</code> in the end of a generator expression.</p>
<p>If you want to iterate over every iterable value, filter with <code>hasattr</code>:</p>
<pre><code>for key in (k for k in dict if hasattr(dict[k], '__iter__')):
for item in dict[key]:... | 2 | 2016-07-25T03:22:27Z | [
"python",
"dictionary"
] |
iterate over only two keys of python dictionary | 38,559,145 | <p>What is the pythonic way to iterate over a dictionary with a setup like this:</p>
<pre><code>dict = {'a': [1, 2, 3], 'b': [3, 4, 5], 'c': 6}
</code></pre>
<p>if I only wanted to iterate a for loop over all the values in <code>a</code> and <code>b</code> and skip <code>c</code>. There's obviously a million ways to... | 0 | 2016-07-25T03:07:37Z | 38,559,294 | <p>Similar to SSDMS's solution you can also just do:</p>
<p><code>mydict = {'a': [1, 2, 3], 'b': [3, 4, 5], 'c': 6}
for each in mydict['a']+mydict['b']:
....</code></p>
| 2 | 2016-07-25T03:30:23Z | [
"python",
"dictionary"
] |
How to speed up 4 million set intersections? | 38,559,245 | <p>I'm an inexperienced programmer working through a number of bioinformatics exercises in Python.</p>
<p>One problem area counts elements in the set intersection between name groups, and stores that count in a dictionary. There are two lists of 2000 name groups each; names in the name groups are Latin names of specie... | 4 | 2016-07-25T03:23:36Z | 38,581,603 | <p>Depending on the specifics of your data, an alternative option is, for each possible data item, you record which lists it is contained in.</p>
<p>With such a data structure, for each data item you can quickly determine which pairs of lists contain it, and increment the corresponding entries of <code>overlap</code>.... | 0 | 2016-07-26T05:23:51Z | [
"python",
"set",
"bioinformatics"
] |
How to speed up 4 million set intersections? | 38,559,245 | <p>I'm an inexperienced programmer working through a number of bioinformatics exercises in Python.</p>
<p>One problem area counts elements in the set intersection between name groups, and stores that count in a dictionary. There are two lists of 2000 name groups each; names in the name groups are Latin names of specie... | 4 | 2016-07-25T03:23:36Z | 38,581,702 | <p>In fact you can express each list with one long integer.For example, set with the first element, the second element, but no third element can be expressed as (0 << 3) +ï¼ï¼ï¼ï¼ï¼ï¼ï¼ï¼ï¼ï¼ï¼ï¼ï¼ãï¼ãï¼ï¼</p>
<p>then you can compute set intersection by just compute integer & operation.</... | 0 | 2016-07-26T05:33:15Z | [
"python",
"set",
"bioinformatics"
] |
How to speed up 4 million set intersections? | 38,559,245 | <p>I'm an inexperienced programmer working through a number of bioinformatics exercises in Python.</p>
<p>One problem area counts elements in the set intersection between name groups, and stores that count in a dictionary. There are two lists of 2000 name groups each; names in the name groups are Latin names of specie... | 4 | 2016-07-25T03:23:36Z | 38,582,948 | <p><strong>First,</strong> Python <code>set</code>s are good at finding intersections (they use hashing), but your code constructs the same <code>set</code>s over and over again. E.g. if the two <code>list</code>s contain 2000 elements each [Did you mean the outer or inner <code>list</code>s are that long?], there are ... | 1 | 2016-07-26T06:54:33Z | [
"python",
"set",
"bioinformatics"
] |
How to speed up 4 million set intersections? | 38,559,245 | <p>I'm an inexperienced programmer working through a number of bioinformatics exercises in Python.</p>
<p>One problem area counts elements in the set intersection between name groups, and stores that count in a dictionary. There are two lists of 2000 name groups each; names in the name groups are Latin names of specie... | 4 | 2016-07-25T03:23:36Z | 38,632,673 | <p>This depends on the nature of your data, but may give you a big saving if there are relatively few Latin names common to both super-lists. The method is:</p>
<ol>
<li>Find common names between the lists</li>
<li>compute set intersections only between name groups that contain one of those common names</li>
<li>The r... | 0 | 2016-07-28T09:42:25Z | [
"python",
"set",
"bioinformatics"
] |
change hostname for continuous integration testing | 38,559,252 | <p>I have some functionality that only runs in specific physical locations and it is known by the hostname. This is produced in a cython module that calls socket.gethostname().</p>
<p>Is there anyway to make a test using socket.gethostname() have different data from the host the test is running on?</p>
| 0 | 2016-07-25T03:24:39Z | 38,565,885 | <p>You could use the <a href="https://docs.python.org/dev/library/unittest.mock.html" rel="nofollow"><code>mock</code> module</a>:</p>
<pre><code>import mock
import socket
with mock.patch("socket.gethostname", return_value="completely fake"):
print socket.gethostname()
</code></pre>
<p>Thsi prints <code>complete... | 1 | 2016-07-25T10:55:20Z | [
"python",
"nose"
] |
Matplotlib: scrolling plot | 38,559,270 | <p>I'm new to Python and I want to implement a scrolling plot for a very long time series data. I've found an example from Matplotlib as follows.</p>
<p><a href="http://scipy-cookbook.readthedocs.io/items/Matplotlib_ScrollingPlot.html" rel="nofollow">http://scipy-cookbook.readthedocs.io/items/Matplotlib_ScrollingPlot.... | 1 | 2016-07-25T03:27:06Z | 38,564,453 | <p>Here's an improved version of the example. (Disclaimer: I started digging into it half an hour ago, never before used wx/matplotlib scrollbars so there might be a much better solution.)</p>
<p>The path I took: first I checked the <a href="http://docs.wxwidgets.org/trunk/classwx_scroll_win_event.html" rel="nofollow"... | 2 | 2016-07-25T09:45:23Z | [
"python",
"matplotlib",
"scroll"
] |
Do instance variables in Python have to be initialized in the __init__ method for a Class? | 38,559,314 | <p>Why is it if I don't set <code>self.ser = False</code> first, I cannot pass around the <code>self.ser</code> variable as a handle to write with <code>pyserial</code>?</p>
<pre><code>import serial
import time
class TestClass(object):
def __init__(self, port='/dev/ttyUSB0', baud=9600):
self.baud = baud
... | 1 | 2016-07-25T03:32:41Z | 38,559,408 | <pre><code>def __init__(self, port='/dev/ttyUSB0', baud=9600):
self.baud = baud
self.port = port
self.connect() # it's ok
</code></pre>
| -1 | 2016-07-25T03:46:31Z | [
"python",
"class",
"pyserial"
] |
Too many open files urllib | 38,559,318 | <p>I'm having a problem with processing over 2700 files
This works if I have a little bit of a files like a couple of hundred, and I'm guessing it has to do with windows limiting open files like in linux ulimit can be definied system wide. I'm sure things are not being closed and this is why I am getting this error.</p... | 0 | 2016-07-25T03:33:16Z | 38,560,316 | <p>You can set <code>_setmaxstdio</code> in C to change the number of files which can be opened at a time.</p>
<p>For python you have to use <code>win32file</code> from <code>pywin32</code> as:</p>
<pre><code>import win32file
win32file._setmaxstdio(1024) #set max number of files to 1024
</code></pre>
<p>The default ... | 1 | 2016-07-25T05:30:47Z | [
"python",
"urllib"
] |
grab serial input line and move them to a shell script | 38,559,412 | <p>I tries to grab a uart - line and give this string to a shell script;</p>
<pre><code>#!/usr/bin/env python
import os
import serial
ser = serial.Serial('/dev/ttyAMA0', 4800)
while True :
try:
state=ser.readline()
print(state)
except:
pass
</code></pre>
<p>So, "state" should given to a shell script no... | 0 | 2016-07-25T03:47:08Z | 38,559,526 | <p>There are different ways to combine two strings (namely <code>"./myscript.sh"</code> and <code>ser.readLine()</code>), which will then give you the full command to be run by use of <code>os.system</code>. E.g. strings can be arguments of the <code>string.format</code> method:</p>
<pre><code>os.system('myscript.sh {... | 0 | 2016-07-25T04:03:01Z | [
"python",
"shell",
"variables",
"os.system"
] |
grab serial input line and move them to a shell script | 38,559,412 | <p>I tries to grab a uart - line and give this string to a shell script;</p>
<pre><code>#!/usr/bin/env python
import os
import serial
ser = serial.Serial('/dev/ttyAMA0', 4800)
while True :
try:
state=ser.readline()
print(state)
except:
pass
</code></pre>
<p>So, "state" should given to a shell script no... | 0 | 2016-07-25T03:47:08Z | 38,559,540 | <p>Just simple string concatenation passed to the os.system function.</p>
<pre><code>import os
os.system("myscript.sh " + ser.readline())
</code></pre>
| 0 | 2016-07-25T04:04:27Z | [
"python",
"shell",
"variables",
"os.system"
] |
grab serial input line and move them to a shell script | 38,559,412 | <p>I tries to grab a uart - line and give this string to a shell script;</p>
<pre><code>#!/usr/bin/env python
import os
import serial
ser = serial.Serial('/dev/ttyAMA0', 4800)
while True :
try:
state=ser.readline()
print(state)
except:
pass
</code></pre>
<p>So, "state" should given to a shell script no... | 0 | 2016-07-25T03:47:08Z | 38,559,590 | <p>If <code>myscript</code> can continuously read additional input, you have a much more efficient pipeline.</p>
<pre><code>from subprocess import Popen, PIPE
sink = Popen(['myscript.sh'], stdin=PIPE, stdout=PIPE)
while True:
sink.communicate(ser.readline())
</code></pre>
<p>If you have to start a new <code>myscr... | 0 | 2016-07-25T04:10:58Z | [
"python",
"shell",
"variables",
"os.system"
] |
Why I can't open and read the file on python in powershell? | 38,559,424 | <p><strong>I'm pretty sure I got the ex15_sample.txt in mystuff filefolder!</strong></p>
<p>Here is the error I encounter:
<a href="http://i.stack.imgur.com/d6nkN.png" rel="nofollow"><img src="http://i.stack.imgur.com/d6nkN.png" alt="the powershell"></a></p>
<pre><code>IOError: [Errno 2] No such file or directory: 'e... | 0 | 2016-07-25T03:48:34Z | 38,565,173 | <p>you can use this </p>
<pre><code> import os
__location__ = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
file_name = raw_input("type the file name")
txt = open(os.path.join(__location__, filename))
print txt.read()
</code></pre>
| 0 | 2016-07-25T10:20:42Z | [
"python",
"powershell"
] |
Initialize a Python object from command line input | 38,559,464 | <p>I'm new to Python and am learning input/output. Right now, I'm trying to add attributes to an object from a file that I specify from command line input. </p>
<p>For example, I want to run the following: <code>$ /...filepath.../ python3 myCode.py < 06</code> to pass the contents of file <code>06</code> </p>
<p... | 0 | 2016-07-25T03:52:56Z | 38,559,533 | <p>just because your input stream is not an int, it's a string with space and "\n" delimiter, you have to work on these things first. </p>
<p>The quick and easy way is changing your code to something like this (not tested):</p>
<pre><code>self._num_one = int("".join(sys.stdin.readline().split()))
</code></pre>
| 0 | 2016-07-25T04:03:56Z | [
"python",
"class",
"input",
"command-line"
] |
Initialize a Python object from command line input | 38,559,464 | <p>I'm new to Python and am learning input/output. Right now, I'm trying to add attributes to an object from a file that I specify from command line input. </p>
<p>For example, I want to run the following: <code>$ /...filepath.../ python3 myCode.py < 06</code> to pass the contents of file <code>06</code> </p>
<p... | 0 | 2016-07-25T03:52:56Z | 38,559,587 | <p>There are some problems with your code that stops it from working.</p>
<p>First thing first, you need to remove whitespace before and after if you are reading the input file one line after another. This means a call to the <code>.strip()</code> method after <code>.readline()</code>. You are getting the <code>ValueE... | 0 | 2016-07-25T04:10:34Z | [
"python",
"class",
"input",
"command-line"
] |
Click on link using selenium | 38,559,469 | <p>I am very new to python programming and I need help in clicking a link on tripadvisor website. I need to extract full reviews. Current code take only partial reviews with More link. HTML code for More link is mentioned below. I clicked on Inspect element and copied the HTML code.</p>
<pre><code><span class="taLn... | -2 | 2016-07-25T03:54:32Z | 38,560,092 | <p>There are basically two approach to clicking on the <code>More</code> as below :</p>
<ul>
<li><p>using <code>find_element_by_xpath</code> as below :</p>
<pre><code>driver.find_element_by_xpath("//span[contains(.,'More')]").click()
</code></pre></li>
<li><p>using <code>find_element_by_css_selector</code> as below :... | 0 | 2016-07-25T05:06:19Z | [
"python",
"selenium"
] |
Concatenate a set of column values based on another column in Pandas | 38,559,541 | <p>Given a Pandas dataframe which has a few labeled series in it, say <em>Name</em> and <em>Villain</em>.</p>
<p>Say the dataframe has values such: <br/>
<strong>Name</strong>: {'Batman', 'Batman', 'Spiderman', 'Spiderman', 'Spiderman', 'Spiderman'} <br/>
<strong>Villain</strong>: {'Joker', 'Bane', 'Green Goblin', 'El... | 0 | 2016-07-25T04:04:30Z | 38,559,873 | <p>This is a classic inner-join scenario. In <code>pandas</code>, use the <code>merge</code> module-level function:</p>
<pre><code>In [13]: df1
Out[13]:
Name Villain
0 Batman Joker
1 Batman Bane
2 Spiderman Green Goblin
3 Spiderman Electro
4 Spiderman Venom
5 ... | 1 | 2016-07-25T04:42:55Z | [
"python",
"pandas"
] |
Raising an exception during for loop and continuing at next index in python | 38,559,545 | <p>I've been breaking my head all day, and I cannot seem to solve this. I'm supposed to write an Exception class then raise it during an iteration and continue where I left off.</p>
<pre><code> class OhNoNotTrueException(Exception):
"""Exception raised when False is encountered
Attributes:
message -- ex... | 0 | 2016-07-25T04:04:52Z | 38,559,627 | <p>You should do the loop outside of the try/except block. Then one individual list entry will be checken by the try catch and afterwards the loop will continue with the next one:</p>
<pre><code>for i in am_i_true_or_false:
try:
if i is False:
raise OhNoNotTrueException(i)
else:
... | 1 | 2016-07-25T04:15:36Z | [
"python",
"for-loop",
"exception",
"iteration",
"continue"
] |
Raising an exception during for loop and continuing at next index in python | 38,559,545 | <p>I've been breaking my head all day, and I cannot seem to solve this. I'm supposed to write an Exception class then raise it during an iteration and continue where I left off.</p>
<pre><code> class OhNoNotTrueException(Exception):
"""Exception raised when False is encountered
Attributes:
message -- ex... | 0 | 2016-07-25T04:04:52Z | 38,559,631 | <p>Everything after the exception is raised will never be reached, and you will be taken outside the loop, as if everything in the try-block had never happend. Thus, you need to try/except inside the loop:</p>
<pre><code>In [5]: for i in am_i_true_or_false:
...: try:
...: if i is False:
...: ... | 2 | 2016-07-25T04:15:44Z | [
"python",
"for-loop",
"exception",
"iteration",
"continue"
] |
How to plot coarse-grained average of a set of data points? | 38,559,557 | <p>I have a set of discrete 2-dimensional data points. Each of these points has a measured value associated with it. I would like to get a scatter plot with points colored by their measured values. But the data points are so dense that points with different colors would overlap with each other, that may not be good ... | 0 | 2016-07-25T04:06:55Z | 38,578,500 | <p>I have it done by using <code>sklearn.neighbors.RadiusNeighborsClassifier()</code>, the idea is the take the average of the values of the neighbors within a specific radius. Suppose the coordinates of the data points are in the list <code>temp_coors</code>, the values associated with these points are <code>coloring... | 0 | 2016-07-25T22:43:14Z | [
"python"
] |
Python contextmanager() vs closing(): which is appropriate for a stream object? | 38,559,608 | <p>In <a href="http://stackoverflow.com/a/17603000/760905">another answer here</a> that uses contextlib to define a custom "open" function for use with <code>with</code>, <code>contextmanager</code> from contextlib is used to define a function that handles opening and streaming of data and finally closing of the stream... | 0 | 2016-07-25T04:13:25Z | 38,559,652 | <p>It would be completely inappropriate to stick <code>contextlib.closing</code> around the context manager in that answer, for many reasons:</p>
<ol>
<li>They don't always want to close the file! That context manager is specifically designed to sometimes leave the file open. This is the entire reason that context man... | 1 | 2016-07-25T04:19:29Z | [
"python",
"contextmanager"
] |
regarding setting up ogrid and fillup the corresponding multidimensional array in numpy | 38,559,676 | <p>I am trying to understand the following Python segment. </p>
<pre><code>def upsample_filt(size):
factor = (size + 1) // 2
if size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:size, :size]
return (1 - abs(og[0] - center) / factor) * \
(1 - ab... | 2 | 2016-07-25T04:21:53Z | 38,560,012 | <p>Lets make it simpler:</p>
<pre><code>In [264]: og=np.ogrid[:3,:2]
In [265]: og
Out[265]:
[array([[0],
[1],
[2]]), array([[0, 1]])]
</code></pre>
<p>The shape of these 2 is <code>(3,1)</code> and <code>(1,2)</code>. They are 2d; 'o' for 'open'.</p>
<pre><code>In [266]: og[0]*og[1]
Out[266]:
arra... | 1 | 2016-07-25T04:59:22Z | [
"python",
"numpy"
] |
How to get current available GPUs in tensorflow? | 38,559,755 | <p>I have a plan to use distributed TensorFlow, and I saw TensorFlow can use GPUs for training and testing. In a cluster environment, each machine could have 0 or 1 or more GPUs, and I want to run my TensorFlow graph into GPUs on as many machines as possible.</p>
<p>I found that when running <code>tf.Session()</code> ... | 3 | 2016-07-25T04:30:38Z | 38,580,201 | <p>There is an undocumented method called <a href="https://github.com/tensorflow/tensorflow/blob/d42facc3cc9611f0c9722c81551a7404a0bd3f6b/tensorflow/python/client/device_lib.py#L27"><code>device_lib.list_local_devices()</code></a> that enables you to list the devices available in the local process. (<strong>N.B.</stron... | 6 | 2016-07-26T02:34:21Z | [
"python",
"gpu",
"tensorflow"
] |
How can I make a Pandas data_frame column based on "If any observation in a particular column meets a condition, then True?" | 38,559,757 | <p>I have a variable that I want to define as <code>True</code> if any item in its containing group meets the condition. For example, in the below <code>.csv</code> frame, a column <code>D</code> corresponding to the condition I'm looking at would be True for all rows where <code>A==1</code> because it's true in the f... | 1 | 2016-07-25T04:30:53Z | 38,559,816 | <p>You could try</p>
<pre><code>In [7]: df.C.groupby(df.A).max()
Out[7]:
A
1 True
4 False
6 True
8 False
Name: C, dtype: bool
</code></pre>
<p>Your question didn't specify what should happen if some of the rules contradict others, e.g., if there's also a row</p>
<pre><code>1,2,False
</code></pre>
<p>... | 1 | 2016-07-25T04:37:15Z | [
"python",
"pandas"
] |
How can I make a Pandas data_frame column based on "If any observation in a particular column meets a condition, then True?" | 38,559,757 | <p>I have a variable that I want to define as <code>True</code> if any item in its containing group meets the condition. For example, in the below <code>.csv</code> frame, a column <code>D</code> corresponding to the condition I'm looking at would be True for all rows where <code>A==1</code> because it's true in the f... | 1 | 2016-07-25T04:30:53Z | 38,559,914 | <p>You can group on <code>A</code> and then use <code>transform</code> which keeps the the same shape as the original dataframe. Apply a <code>lambda</code> function where you test if any member of the corresponding group in column <code>C</code> is True.</p>
<pre><code>df['D'] = df.groupby('A').C.transform(lambda gro... | 1 | 2016-07-25T04:48:51Z | [
"python",
"pandas"
] |
Tkinter print specified item from list in loop | 38,559,778 | <p>I've code like below:</p>
<pre><code>from tkinter import *
root = Tk()
root.title("sample program")
def print_item_from_list(event):
print(variable)
list = [1, 2, 3, 4, 5]
seclist = []
print(list)
for i in range(0,5):
variable = list[i]
sample = Label(text=variable)
sample.pack()
sample.bind(... | 0 | 2016-07-25T04:32:30Z | 38,559,976 | <p>You can make use of closures:</p>
<pre><code>for i in range(0,5):
variable = list[i]
sample = Label(text=variable)
sample.pack()
def connect_callback(variable):
sample.bind('<Enter>', lambda event:print(variable))
connect_callback(variable)
</code></pre>
<p>This creates a new call... | 1 | 2016-07-25T04:55:32Z | [
"python",
"tkinter"
] |
Tkinter print specified item from list in loop | 38,559,778 | <p>I've code like below:</p>
<pre><code>from tkinter import *
root = Tk()
root.title("sample program")
def print_item_from_list(event):
print(variable)
list = [1, 2, 3, 4, 5]
seclist = []
print(list)
for i in range(0,5):
variable = list[i]
sample = Label(text=variable)
sample.pack()
sample.bind(... | 0 | 2016-07-25T04:32:30Z | 38,560,907 | <p><strong>With your code :</strong></p>
<pre><code>from tkinter import *
root = Tk()
root.title("sample program")
def print_item_from_list(event):
print(event.widget.config("text")[-1])
list = [1, 2, 3, 4, 5]
seclist = []
print(list)
for i in range(0,5):
variable = list[i]
sample = Label(text=variable... | 2 | 2016-07-25T06:21:06Z | [
"python",
"tkinter"
] |
how to scrapping all pages (page 1 until infinity) on website | 38,559,791 | <p>guys i wanna scrapping from <a href="https://n0where.net/" rel="nofollow">this link</a>
everythings its okay, my scrapping its succes</p>
<p>then i was thinking, how about if i want to scrapping all of pages (page one till infinity depends on database article)</p>
<p>i am new to using python and scrapy, before thi... | 0 | 2016-07-25T04:34:03Z | 38,562,226 | <p>The pagination is pretty tough on this website. If you inspect what your browser is doing, you'll see it's making an AJAX POST request with bunch of parameters to <a href="https://n0where.net/wp-admin/admin-ajax.php" rel="nofollow">https://n0where.net/wp-admin/admin-ajax.php</a> </p>
<p><a href="http://i.stack.imgu... | 0 | 2016-07-25T07:45:46Z | [
"python",
"xpath",
"web-scraping",
"css-selectors",
"scrapy"
] |
How to have a dictionary field in a django model and use aggregation (min/max) on that field across dictionary keys | 38,559,899 | <p>I am trying to build a model in django 1.9 that has a key, value pair (dictionary) field that also allows query set aggregation (min, mix, etc).
I've tried to use the JSONField:</p>
<pre><code>#models.py
from django.contrib.postgres import fields as pgfields
class Entry(models.Model):
pass
class Scorer(models.... | 1 | 2016-07-25T04:47:45Z | 38,580,709 | <p>You can do this with <a href="https://docs.djangoproject.com/en/1.9/ref/models/conditional-expressions/" rel="nofollow">conditional expressions</a>, using the second model structure you proposed (<code>Score</code> with a foreign key to <code>EntryScoreSet</code>).</p>
<pre><code>from django.db.models import Case, ... | 1 | 2016-07-26T03:47:18Z | [
"python",
"django",
"orm"
] |
How do you get each element of list/tuple, where list is passed as parameter to function in python? | 38,559,915 | <p>Here is the code snippet, which is unable to print items of the tuple. [Using python versions 2.6.8/2.7.10]</p>
<pre><code>def lists (var, *st):
print type(st)
for item in range(1,len(st)):
print "Items is:" + item
st = ['udf','var_udf']
lists("a",st)
</code></pre>
<p>Thanks in advance</p>
| 1 | 2016-07-25T04:48:57Z | 38,559,999 | <p>This would not be printing anything because you have used <code>item in range(1,len(st))</code> giving item the value of an integer. Instead do something like:</p>
<pre><code>for item in st:
</code></pre>
<p>CODE:</p>
<pre><code>def lists (var, *st):
print type(st)
for item in st:
print "Items is:... | 1 | 2016-07-25T04:57:53Z | [
"python",
"python-2.7"
] |
How do you get each element of list/tuple, where list is passed as parameter to function in python? | 38,559,915 | <p>Here is the code snippet, which is unable to print items of the tuple. [Using python versions 2.6.8/2.7.10]</p>
<pre><code>def lists (var, *st):
print type(st)
for item in range(1,len(st)):
print "Items is:" + item
st = ['udf','var_udf']
lists("a",st)
</code></pre>
<p>Thanks in advance</p>
| 1 | 2016-07-25T04:48:57Z | 38,560,061 | <pre><code>a = [1,2,3,4,5,6,7,8,9] #list
print (a)
def b(list):
for i in list:
print (i) #each element of the list printed here
b(a) #calling def
</code></pre>
<p>If you are passing a list as an argument to the function, the below function will print each element of the list. If you want to perform any o... | 0 | 2016-07-25T05:03:31Z | [
"python",
"python-2.7"
] |
How to apply a function to every value in a column in a pandas dataframe? | 38,559,967 | <p>I had tried doing a somewhat manual approach using a loop like below:</p>
<pre><code>data = pd.read_csv('data/training.csv')
for idx,imageString in enumerate(data.iloc[:,-1]):
# print(imageString[0:10])
data[idx,-1] = imageString.split(" ")
</code></pre>
<p>But this errors out on the last line with:</p>
<... | 1 | 2016-07-25T04:54:37Z | 38,560,006 | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow"><code>str.split</code></a>:</p>
<pre><code>data = pd.read_csv('data/training.csv')
data.iloc[:,-1] = data.iloc[:,-1].str.split(expand=False)
</code></pre>
<p>Then select first or some anothe... | 2 | 2016-07-25T04:58:30Z | [
"python",
"python-3.x",
"pandas"
] |
How to apply a function to every value in a column in a pandas dataframe? | 38,559,967 | <p>I had tried doing a somewhat manual approach using a loop like below:</p>
<pre><code>data = pd.read_csv('data/training.csv')
for idx,imageString in enumerate(data.iloc[:,-1]):
# print(imageString[0:10])
data[idx,-1] = imageString.split(" ")
</code></pre>
<p>But this errors out on the last line with:</p>
<... | 1 | 2016-07-25T04:54:37Z | 38,560,277 | <p>You are not accessing the values correctly.</p>
<p>To correct your code, the last line should be:</p>
<pre><code>df.iat[idx, -1] = imageString.split(" ")
</code></pre>
<p><code>iat</code> is used for scalar getting and setting.</p>
<p>This is probably a simpler way to accomplish your objective:</p>
<pre><code>d... | 0 | 2016-07-25T05:27:22Z | [
"python",
"python-3.x",
"pandas"
] |
Sum a column of values including letters in Python | 38,560,126 | <p>I have an input CSV file and need to add all the values in one of the columns, but the values are not plain integers and I'm not sure how to go about it.</p>
<p>The total output should be around 15k, which is the sum of the entire column. I am using pandas dataframe to store .csv file.</p>
<p>Here is the one of th... | 2 | 2016-07-25T05:11:23Z | 38,560,162 | <p>I think you need first remove <code>K</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html" rel="nofollow"><code>str.replace</code></a>, then cast to <code>float</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel=... | 3 | 2016-07-25T05:16:01Z | [
"python",
"csv",
"pandas",
"dataframe"
] |
Sum a column of values including letters in Python | 38,560,126 | <p>I have an input CSV file and need to add all the values in one of the columns, but the values are not plain integers and I'm not sure how to go about it.</p>
<p>The total output should be around 15k, which is the sum of the entire column. I am using pandas dataframe to store .csv file.</p>
<p>Here is the one of th... | 2 | 2016-07-25T05:11:23Z | 38,560,177 | <p>I'm not familiar with pandas/dataframe, but you can use simple Python logic for this. Assuming your file follows the same pattern of having the <code>"K"</code> as the last character in each line, consider the following:</p>
<pre><code>>>> float("2.0K"[:-1])
2.0
>>> float("2.0M"[:-1])
2.0
</code><... | 0 | 2016-07-25T05:17:24Z | [
"python",
"csv",
"pandas",
"dataframe"
] |
Sum a column of values including letters in Python | 38,560,126 | <p>I have an input CSV file and need to add all the values in one of the columns, but the values are not plain integers and I'm not sure how to go about it.</p>
<p>The total output should be around 15k, which is the sum of the entire column. I am using pandas dataframe to store .csv file.</p>
<p>Here is the one of th... | 2 | 2016-07-25T05:11:23Z | 38,560,970 | <p>Try this:</p>
<p>Following this pattern, you can add "B" for billions. And do nothing for values that dont have "K", or "M". </p>
<pre><code>def chgFormat(x):
newFormat = 0
if x[-1] == 'K': newFormat = float(x[:-1])
elif x[-1] == 'H': newFormat = float(x[:-1])/10
elif x[-1] =... | 3 | 2016-07-25T06:26:28Z | [
"python",
"csv",
"pandas",
"dataframe"
] |
Sum a column of values including letters in Python | 38,560,126 | <p>I have an input CSV file and need to add all the values in one of the columns, but the values are not plain integers and I'm not sure how to go about it.</p>
<p>The total output should be around 15k, which is the sum of the entire column. I am using pandas dataframe to store .csv file.</p>
<p>Here is the one of th... | 2 | 2016-07-25T05:11:23Z | 38,561,717 | <p>I'd write these functions:</p>
<pre><code>import re
mapper = dict(k=1e3, K=1e3,
m=1e6, M=1e6,
b=1e9, B=1e9)
pot = ('K', 'M', 'B')
def revmap(value):
powers_of_K = int(np.log10(value) // 3)
if powers_of_K > len(pot):
suffix = pot[-1]
else:
suffix = pot[po... | 2 | 2016-07-25T07:15:02Z | [
"python",
"csv",
"pandas",
"dataframe"
] |
Why does my function in python adds headers improperly? | 38,560,224 | <p>So, I have this function that makes files, in this case i'm doing .csv files. In the function I want to add the feature to add a header in the new written file. However, it seems that when it writes the file, the new header row is added to the previous row instead of moving that first row down to add the header row(... | -1 | 2016-07-25T05:22:49Z | 38,560,267 | <p>When you use <code>str()</code> on a list, it will return literally what you see. E.g.:</p>
<pre><code>>>> a = [1, 2, 3]
>>> str(a)
'[1, 2, 3]'
</code></pre>
<p>What you want is to use the <code>.join()</code> function with on a string and join the list:</p>
<pre><code>>>> a = ['1', '2'... | 1 | 2016-07-25T05:26:33Z | [
"python",
"csv",
"header"
] |
Parsing struct within struct in C using pycparser? | 38,560,264 | <p>I have this example c file I want to parse:</p>
<pre><code>StrcutWithinStruct.c
// simple struct within a struct example
struct A {
int a;
};
struct B {
A a;
int b;
};
</code></pre>
<p>I'm running <a href="https://github.com/eliben/pycparser" rel="nofollow">pcyparser</a> to parse it, with the following code <... | 1 | 2016-07-25T05:26:17Z | 38,560,367 | <p>Your <code>struct</code> declarations are not closed with a semicolon:</p>
<p>Additionally <code>A</code> itself is not a type name in C. In C++ <code>A</code> alone would suffice, but in C you need to add the <code>struct</code> keyword.</p>
<pre><code>struct A {
int a;
};
struct B {
struct A a;
int b;
};
</c... | 2 | 2016-07-25T05:36:11Z | [
"python",
"c++",
"c",
"parsing",
"clang"
] |
Indentation Error: unindent does not match any outer indentation level | 38,560,338 | <p>I can't seem to figure out what's going on here. When I compile I get the <em>does not match</em> error.</p>
<p>It gives me the error about indentation mismatch on the line with <code>bgB = 0;</code></p>
<pre><code>def calcBG(ftemp):
"This calculates the color value for the background"
variance = ftemp - justRight... | -4 | 2016-07-25T05:32:32Z | 38,560,755 | <p>As the interpreter tells you your indentation levels are not consistent. Be sure to indent after first line of method definitions and <code>if</code> statements, With no changes to your code other than fixing indents:</p>
<pre><code>def calcBG(ftemp):
"""This calculates the color value for the background"""
... | 0 | 2016-07-25T06:08:53Z | [
"python",
"indentation"
] |
Django select query with limited fields | 38,560,347 | <p>I want to select a object with just one return field. I can do it using values. But the problem is when not using values it returns an object and when using values it returns a dictionary. Any reason for this difference. And is there a way I can get a return of objects with just one or two fields.</p>
<pre><code> ... | 0 | 2016-07-25T05:33:28Z | 38,560,407 | <p>You can use <a href="https://docs.djangoproject.com/en/1.9/ref/models/querysets/#django.db.models.query.QuerySet.only" rel="nofollow">only()</a> method and enter fields which you need </p>
<pre><code>obj=UserProfile.objects.only('my_field').get(pk=1)
</code></pre>
| 4 | 2016-07-25T05:39:21Z | [
"python",
"django",
"django-models"
] |
python threading: max number of threads to run | 38,560,470 | <p>let's say i have something similar to:</p>
<pre><code>def worker(name):
time.sleep(10)
print name
return
thrs = []
for i in range(1000):
t1 = threading.Thread(target=worker, args=(i,))
thrs.append(t1)
for t in thrs:
t.start()
</code></pre>
<p>Is there way to specify how many threads can r... | 1 | 2016-07-25T05:44:39Z | 38,560,689 | <p>This can be done using <a href="https://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.dummy" rel="nofollow"><code>multiprocessing.dummy</code></a> which provides a threaded version of the <a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow"><code>multiprocessing</co... | 2 | 2016-07-25T06:03:36Z | [
"python",
"multithreading",
"python-2.7"
] |
How to connect my python bot to microsoft bot connector | 38,560,546 | <p>I want to write a python bot and I know if it is possible to connect my bot to microsoft bot connector ?</p>
| 0 | 2016-07-25T05:51:29Z | 39,328,480 | <p>Yes it's possible. Please checkout <a href="https://github.com/ahmadfaizalbh/Microsoft-chatbot" rel="nofollow">Microsoft bot built on Django (python web framework)</a> for implementation.</p>
<p>Here below is a python code to reply back to Microsoft bot connector</p>
<pre><code>import requests
app_client_id = `<... | 1 | 2016-09-05T10:20:19Z | [
"python",
"bots",
"connector"
] |
Good Design Principles: Where to put text processing code? | 38,560,645 | <p>I have a situation where I have to do a lot of text processing on data before I use the processed text to create an object instance. The question I have is whether it is better oop design to do the text processing first, and then create the object instance, or pass the unprocessed text to the object constructor and ... | 0 | 2016-07-25T06:00:01Z | 38,560,976 | <p>When coming up with the design, consider the separation of responsibilities. Is text processing the responsibility of <code>MyObject</code>? Does it ever need contents of <code>lots_of_text</code>, except to process it in the constructor? (Could it ever make sense to defer processing for later, e.g. for performance ... | 0 | 2016-07-25T06:27:04Z | [
"python",
"python-3.x",
"oop"
] |
Python Pandas dataframe reading exact specified range in an excel sheet | 38,560,748 | <p>I have a lot of different table (and other unstructured data in an excel sheet) .. I need to create a dataframe out of range 'A3:D20' from 'Sheet2' of Excel sheet 'data'</p>
<p>all examples that I come across drilldown up to sheet level, but not how to pick it from an exact range</p>
<pre><code>import openpyxl
imp... | 0 | 2016-07-25T06:08:37Z | 38,561,012 | <p>Use the following arguments from <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html" rel="nofollow">pandas read_excel documentation</a>:</p>
<blockquote>
<ul>
<li>skiprows : list-like
<ul>
<li>Rows to skip at the beginning (0-indexed)</li>
</ul></li>
<li>parse_cols ... | 0 | 2016-07-25T06:29:06Z | [
"python",
"excel",
"pandas"
] |
Python Pandas dataframe reading exact specified range in an excel sheet | 38,560,748 | <p>I have a lot of different table (and other unstructured data in an excel sheet) .. I need to create a dataframe out of range 'A3:D20' from 'Sheet2' of Excel sheet 'data'</p>
<p>all examples that I come across drilldown up to sheet level, but not how to pick it from an exact range</p>
<pre><code>import openpyxl
imp... | 0 | 2016-07-25T06:08:37Z | 38,561,536 | <p>One way to do this is to use the <a href="https://pypi.python.org/pypi/openpyxl/" rel="nofollow">openpyxl</a> module.</p>
<p>Here's an example:</p>
<pre><code>from openpyxl import load_workbook
wb = load_workbook(filename='data.xlsx',
read_only=True)
ws = wb['Sheet2']
# Read the cell values ... | 0 | 2016-07-25T07:03:52Z | [
"python",
"excel",
"pandas"
] |
Python: clear items from PriorityQueue | 38,560,760 | <p><a href="http://stackoverflow.com/questions/6517953/clear-all-items-from-the-queue">Clear all items from the queue </a></p>
<p>I read the above answer </p>
<p>Im using python 2.7</p>
<pre><code>import Queue
pq = Queue.PriorityQueue()
pq.clear()
</code></pre>
<p>I get the following error:</p>
<pre><code>Attribut... | 0 | 2016-07-25T06:09:05Z | 38,560,911 | <p>It's actually <code>pq.queue.clear()</code>. However, as mentioned in the answers to the question you referenced, this is not documented and potentially unsafe.</p>
<p>The cleanest way is described in <a href="http://stackoverflow.com/a/18873213/3165737">this answer</a>:</p>
<pre><code>while not q.empty():
try... | 1 | 2016-07-25T06:21:20Z | [
"python",
"python-2.7",
"priority-queue"
] |
Draw ROC curve in python using confusion matrix only | 38,560,815 | <p>I need to draw ROC curve using confusion matrix only. Actually my system was crashed ( every information was lost), therefore I am not getting data. I have only values of confusion matrix. I know how to create ROC curve (<a href="http://scikit-learn.org/stable/auto_examples/model_selection/plot_roc_crossval.html" re... | -1 | 2016-07-25T06:13:06Z | 38,566,612 | <p>Unfortunately you can't build a ROC curve from a single contingency matrix.</p>
<p>A ROC curve shows how the sensitivity and specificity vary as you change the decision threshold. In order to do that, it is necessary to calculate these values at <em>all possible thresholds</em> (at least those where the values step... | 0 | 2016-07-25T11:31:30Z | [
"python",
"roc",
"confusion-matrix"
] |
How to read 10 records each time from csv file using pandas? | 38,560,897 | <p>I want to read a csv file which having 1000 rows so, I decide to read this file in chunks. But I'm facing issues while reading this csv file. </p>
<p>I want to read first 10 records at 1st iteration and convert its specific columns to the python dictionary at 2nd iteration skip first 10 records and read next 10 rec... | 0 | 2016-07-25T06:19:51Z | 38,561,252 | <p>The first iteration should work fine, but any further iterations are problematic.</p>
<p><code>read_csv</code> has an <code>headers</code> kwarg with default value <code>infer</code> (which is basically <code>0</code>). This means that the first row in the parsed csv will be used as the columns' names in the datafr... | 1 | 2016-07-25T06:44:58Z | [
"python",
"csv",
"pandas",
"dictionary",
"dataframe"
] |
How to read 10 records each time from csv file using pandas? | 38,560,897 | <p>I want to read a csv file which having 1000 rows so, I decide to read this file in chunks. But I'm facing issues while reading this csv file. </p>
<p>I want to read first 10 records at 1st iteration and convert its specific columns to the python dictionary at 2nd iteration skip first 10 records and read next 10 rec... | 0 | 2016-07-25T06:19:51Z | 38,561,432 | <p>You can use rather <code>chunksize</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a>:</p>
<pre><code>import pandas as pd
import io
temp=u'''time,line_id,high,low,avg,total,split_counts
1468332421098000,206,50879,50879,50879,2,"[5... | 1 | 2016-07-25T06:57:07Z | [
"python",
"csv",
"pandas",
"dictionary",
"dataframe"
] |
(YouTube API v3) GET request to Search.list returns empty responses | 38,561,148 | <p>I am working on a python program to retrieve information (video id, video author, etc) on all videos that show up as result to a search (<strong>q="cancer+vlog"</strong>).</p>
<p>I have the following <strong>GET</strong> request that runs first:</p>
<pre><code> results = youtube.search().list(
order="... | 0 | 2016-07-25T06:38:07Z | 38,616,395 | <p>Actually, you make a server load on youtube data api, officially, youtube does not use this api, it is for other users like us, Python is a server side language, and by your script, you send too many query, or get request to the api, that why it shows, this type of error. I am not a python developer. I am php guy, i... | 0 | 2016-07-27T14:49:59Z | [
"python",
"youtube",
"youtube-api",
"youtube-data-api",
"youtube-api-v3"
] |
Neural network XOR gate not learning | 38,561,182 | <p>I'm trying to make a XOR gate by using 2 perceptron network but for some reason the network is not learning, when I plot the change of error in a graph the error comes to a static level and oscillates in that region. </p>
<p>I did not add any bias to the network at the moment.</p>
<pre><code>import numpy as np
de... | 0 | 2016-07-25T06:39:53Z | 38,563,035 | <p>The error calculated in each epoch should be a sum total of all sum squared errors (i.e. error for every target)</p>
<pre><code>import numpy as np
def S(x):
return 1/(1+np.exp(-x))
win = np.random.randn(2,2)
wout = np.random.randn(2,1)
eta = 0.15
# win = [[1,1], [2,2]]
# wout = [[1],[2]]
obj = [[0,0],[1,0],[0,1... | 0 | 2016-07-25T08:35:06Z | [
"python",
"numpy",
"machine-learning",
"neural-network",
"artificial-intelligence"
] |
Neural network XOR gate not learning | 38,561,182 | <p>I'm trying to make a XOR gate by using 2 perceptron network but for some reason the network is not learning, when I plot the change of error in a graph the error comes to a static level and oscillates in that region. </p>
<p>I did not add any bias to the network at the moment.</p>
<pre><code>import numpy as np
de... | 0 | 2016-07-25T06:39:53Z | 38,767,930 | <p>Here is a one hidden layer network with backpropagation which can be customized to run experiments with relu, sigmoid and other activations. After several experiments it was concluded that with relu the network performed better and reached convergence sooner, while with sigmoid the loss value fluctuated. This happen... | 0 | 2016-08-04T12:54:12Z | [
"python",
"numpy",
"machine-learning",
"neural-network",
"artificial-intelligence"
] |
Django library Unresolved Import LiClipse | 38,561,207 | <p>I am creating my first Django project from docs.djangoproject.com. After completing tutorial 4, I tried to import my project in LiClipse. But LiClipse is showing error of Unresolved Import however my projects works perfectly fine.
I have added django in external library.
Please help me with this issue.
LiClipse show... | 0 | 2016-07-25T06:42:15Z | 38,581,034 | <p>Instead of adding django package as external library, add the containing folder of django. For example if folder hierarchy is something like /site-package/django than add site-package as external library and not django.</p>
| 0 | 2016-07-26T04:29:58Z | [
"python",
"django",
"liclipse"
] |
parsing data using pandas with fixed sequence of strings | 38,561,268 | <p>I have data looked like below in file a.dat:</p>
<pre><code>01/Jul/2016 00:05:09 8438.2
01/Jul/2016 00:05:19 8422.4 g
</code></pre>
<p>I wish to parsing them into three columns: <strong>timeline, floating number, string(either None or g)</strong></p>
<p>I have tried: </p>
<pre><code>df=pd.read_csv('a.... | 2 | 2016-07-25T06:46:21Z | 38,561,323 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a>:</p>
<pre><code>import pandas as pd
import io
temp=u'''01/Jul/2016 00:05:09 8438.2
01/Jul/2016 00:05:19 8422.4 g'''
#after testing replace io.StringIO(temp) to filenam... | 2 | 2016-07-25T06:49:56Z | [
"python",
"csv",
"datetime",
"pandas",
"dataframe"
] |
How to read, manipulate and rewrite text in file using python | 38,561,344 | <p>How can I read data from a file, manipulate the data and rewrite it back to the file without wasting memory on a temp file if the file is too big to be processed in one chunk?</p>
| 0 | 2016-07-25T06:51:15Z | 38,561,345 | <p>The following code should work:</p>
<pre><code>chunksize = 64*1024 #arbitrary number
offset = 0
with open(path, 'r+b') as file:
while True:
file.seek(chunksize*offset) # sets pointer to reading spot
chunk = file.read(chunksize)
if len(chunk) == 0: # checks if EoF
break
... | 1 | 2016-07-25T06:51:15Z | [
"python",
"file",
"io"
] |
war/ear file deployment using jython/python scrpting from remote location in webspehere | 38,561,479 | <p>I'm new to jython and python scripts.</p>
<p>My new requirement is to deploy a war file from windows client to windows server, using scripts.</p>
<p>I have done using ant, in local environment completed. From remote I have done R&D but I didn't get solution.</p>
<p>That's why I moved to jython scripting, and ... | 0 | 2016-07-25T06:59:41Z | 38,561,642 | <p>Murali , refer to <a href="http://www.jroller.com/holy/entry/was_6_0_ant_tasks" rel="nofollow">http://www.jroller.com/holy/entry/was_6_0_ant_tasks</a>. Did this help. Are you getting a specific error. You can also refer : <a href="https://stackoverflow.com/questions/3117785/using-ant-to-deploy-ear-to-remote-webspher... | 0 | 2016-07-25T07:09:30Z | [
"java",
"python",
"maven",
"deployment",
"ant"
] |
war/ear file deployment using jython/python scrpting from remote location in webspehere | 38,561,479 | <p>I'm new to jython and python scripts.</p>
<p>My new requirement is to deploy a war file from windows client to windows server, using scripts.</p>
<p>I have done using ant, in local environment completed. From remote I have done R&D but I didn't get solution.</p>
<p>That's why I moved to jython scripting, and ... | 0 | 2016-07-25T06:59:41Z | 38,612,101 | <p>Every one suggesting set the class path to wasanttask.jar or com.ibm.websphere.v61_6.1.100.ws_runtime.jar</p>
<p>and get the details.</p>
<p>but there is no jars is available with that name in WAS 8.5</p>
<p>
</p>
| 0 | 2016-07-27T11:47:45Z | [
"java",
"python",
"maven",
"deployment",
"ant"
] |
Why is this basic GPA Calculator returning a KeyError? | 38,561,521 | <pre><code>Grade1 = input ('Grade for Class 1?')
Grade2 = input ('Grade for Class 2?')
Grade3 = input ('Grade for Class 3?')
Grade4 = input ('Grade for Class 4?')
Grades = (str(Grade1), str(Grade2), str(Grade3), str(Grade4))
def average(numbers):
total= sum(numbers)
return total/len(numbers)
def RealGPA(seme... | -1 | 2016-07-25T07:02:45Z | 38,561,582 | <p><code>PointValues[Grades]</code> looks for the tuple <code>(str(Grade1), str(Grade2), str(Grade3), str(Grade4))</code> in the <code>PointValues</code> dictionary, which obviously generates a <code>KeyError</code>. </p>
<p>Perhaps you meant <code>PointValues[Grade]</code>.</p>
| 0 | 2016-07-25T07:06:30Z | [
"python",
"list"
] |
Why is this basic GPA Calculator returning a KeyError? | 38,561,521 | <pre><code>Grade1 = input ('Grade for Class 1?')
Grade2 = input ('Grade for Class 2?')
Grade3 = input ('Grade for Class 3?')
Grade4 = input ('Grade for Class 4?')
Grades = (str(Grade1), str(Grade2), str(Grade3), str(Grade4))
def average(numbers):
total= sum(numbers)
return total/len(numbers)
def RealGPA(seme... | -1 | 2016-07-25T07:02:45Z | 38,561,598 | <p>A simple typo - you have written <code>Grades</code> instead of <code>Grade</code>.</p>
<p>Added a few other changes as well (have a look at the PEP8 style guide):</p>
<pre><code>grade1 = input ('Grade for Class 1?')
grade2 = input ('Grade for Class 2?')
grade3 = input ('Grade for Class 3?')
grade4 = input ('Grade... | 0 | 2016-07-25T07:07:40Z | [
"python",
"list"
] |
Why is this basic GPA Calculator returning a KeyError? | 38,561,521 | <pre><code>Grade1 = input ('Grade for Class 1?')
Grade2 = input ('Grade for Class 2?')
Grade3 = input ('Grade for Class 3?')
Grade4 = input ('Grade for Class 4?')
Grades = (str(Grade1), str(Grade2), str(Grade3), str(Grade4))
def average(numbers):
total= sum(numbers)
return total/len(numbers)
def RealGPA(seme... | -1 | 2016-07-25T07:02:45Z | 38,561,681 | <p>There is a small typo. This <code>Values=(PointValues[Grades])</code> would be <code>Values=(PointValues[Grade])</code>. And also function name and variable name should be all lower case.</p>
| 0 | 2016-07-25T07:12:47Z | [
"python",
"list"
] |
Code feedback for python guessing game | 38,561,588 | <p>I am new to Python (and coding in general) and after about a week of reading "Thinking Like a Computer Scientist: Learning with Python" I decided to try and build a version the classic "guessing game". I added some extra features such as counting the number of guesses the user takes, and playing against a simulated... | -2 | 2016-07-25T07:06:56Z | 38,562,199 | <p>In <code>get_number(level)</code>:</p>
<ul>
<li><code>elif</code> could be used for all <code>if</code> expressions after the first one. This would make the execution faster because in cases where an expression is true the later expressions must not be evaluated. (The same in <code>guess_number(level)</code> and <c... | 0 | 2016-07-25T07:43:50Z | [
"python",
"python-3.x",
"random",
"while-loop",
"feedback"
] |
find regex match individually | 38,561,643 | <p>I have variables in file as which i have to find</p>
<pre><code>#define varName (test_0x5F_u8)
#define varName1 test_0xFF_u16
</code></pre>
<p>i am unable to match below mentioned expression </p>
<pre><code>test_0xFF_u16 and (test_0x5F_u8)
</code></pre>
<ul>
<li>i want to find these variable individual... | 2 | 2016-07-25T07:09:32Z | 38,561,716 | <pre><code>re.compile(r'^#define\s+(?i)(\w+)\s+[test_0[xX][0-9a-fA-F][a-z0-9]]+')
</code></pre>
<p>there are many things missing in this regex. the opening parentheses, the underscore after 5F, and the last [a-z0-9] will only give one character while in the end you have "u8", which is 2 characters. obviously it won't ... | 0 | 2016-07-25T07:14:56Z | [
"python",
"regex"
] |
find regex match individually | 38,561,643 | <p>I have variables in file as which i have to find</p>
<pre><code>#define varName (test_0x5F_u8)
#define varName1 test_0xFF_u16
</code></pre>
<p>i am unable to match below mentioned expression </p>
<pre><code>test_0xFF_u16 and (test_0x5F_u8)
</code></pre>
<ul>
<li>i want to find these variable individual... | 2 | 2016-07-25T07:09:32Z | 38,562,713 | <p>You need to add an optional group to match the longer pattern. Also, to use optional parentheses, you need to add <code>\)?</code> and <code>\(?</code>.</p>
<pre><code>^#define\s+(\w+)\s+((?:test_0x[0-9a-f]+_[a-z0-9]+\s+or\s+)?\(?test_0x[0-9a-f]+_[a-z0-9]+\)?)
</code></pre>
<p>See <a href="https://regex101.com/r/g... | 2 | 2016-07-25T08:16:32Z | [
"python",
"regex"
] |
Remove contents in side paranthesis of data frame | 38,561,705 | <p>I am trying to remove all the contents inside parenthesis of all the columns in a data frame using the following code. But I can't figure out to do it correctly. Any help is highly appreciated</p>
<pre><code>def clean_text(data):
if data.find('(')!=-1:
st=data[data.find("(") + 1:data.find(")")])
... | 3 | 2016-07-25T07:14:32Z | 38,561,732 | <p>Solution with loop columns and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html" rel="nofollow"><code>replace</code></a>:</p>
<pre><code>import pandas as pd
data = pd.DataFrame({'A':['(1)','2','3'],
'B':['(B) 77','s gg','d'],
'C':['... | 4 | 2016-07-25T07:16:22Z | [
"python",
"pandas",
"dataframe"
] |
Remove contents in side paranthesis of data frame | 38,561,705 | <p>I am trying to remove all the contents inside parenthesis of all the columns in a data frame using the following code. But I can't figure out to do it correctly. Any help is highly appreciated</p>
<pre><code>def clean_text(data):
if data.find('(')!=-1:
st=data[data.find("(") + 1:data.find(")")])
... | 3 | 2016-07-25T07:14:32Z | 38,562,203 | <p>I'm not really familiar with panda but if data is a string type, than you should do </p>
<pre><code>data = data.replace(st, '')
</code></pre>
<p>instead of</p>
<pre><code>data.replace(st,'')
</code></pre>
<p>cf. <a href="https://docs.python.org/2/library/string.html#string.replace" rel="nofollow">https://docs.py... | 0 | 2016-07-25T07:44:00Z | [
"python",
"pandas",
"dataframe"
] |
Remove contents in side paranthesis of data frame | 38,561,705 | <p>I am trying to remove all the contents inside parenthesis of all the columns in a data frame using the following code. But I can't figure out to do it correctly. Any help is highly appreciated</p>
<pre><code>def clean_text(data):
if data.find('(')!=-1:
st=data[data.find("(") + 1:data.find(")")])
... | 3 | 2016-07-25T07:14:32Z | 38,562,413 | <p>I'd stack the entire thing into a <code>pd.Series</code></p>
<pre><code>sk = range(df.columns.nlevels)
df = df.stack(sk)
</code></pre>
<p>Then perform a <code>str.replace</code></p>
<pre><code>df = df.str.replace(r'\(.*\)', '')
</code></pre>
<p>Then unstack back</p>
<pre><code>uk = [i * -1 - 1 for i in sk]
df... | 4 | 2016-07-25T07:55:28Z | [
"python",
"pandas",
"dataframe"
] |
PyQt MainWindow closes after initialization | 38,561,760 | <p>I wanted to start a new project using PyQt5 and QtDesigner. To start, I just copied the code I had from previous projects in PyQt4 and tweaked it to the changes in PyQt5. So, the code to start the Main Window and a Timer which updates the application looks like this:</p>
<pre class="lang-python prettyprint-override... | 3 | 2016-07-25T07:18:22Z | 38,565,717 | <p>I'd try to change some lines, first try to change <code>app</code> definition to </p>
<pre><code>app = QtGui.QApplication(sys.argv)
</code></pre>
<p>Then remove <code>Ui_Window</code> init and set it to <code>self.ui = Ui_Window()</code></p>
<pre><code>class SNSMainWindow(WindowBaseClass):
def __init__(self, ... | 0 | 2016-07-25T10:47:32Z | [
"python",
"qt",
"pyqt5",
"qt-designer",
"qapplication"
] |
Beautifulsoup to extract within tags and output as a JSON | 38,561,808 | <p>As mentioned in the previous question, I am using Beautiful soup with python to retrieve weather data from a website.</p>
<p>Here's how the website looks like:</p>
<pre><code><channel>
<title>2 Hour Forecast</title>
<source>Meteorological Services Singapore</source>
<description>... | 0 | 2016-07-25T07:20:33Z | 38,562,293 | <p>Try This in your code:</p>
<pre><code>with open("nea.json",'a+') as fs:
for area in soup.find('weatherForecast').find_all('area'):
fs.write(str(area.attrs))
</code></pre>
| 0 | 2016-07-25T07:48:54Z | [
"python",
"json",
"beautifulsoup"
] |
python pandas read various dataframe from same excel sheet | 38,562,027 | <p>Currently with pandas, I could save various dataframes (of different size) to the same excel sheet, with startrow and startcol to specify the location. </p>
<pre><code>with pd.ExcelWriter(dump_excel) as writer:
dataframe1.to_excel(writer, sheet_name='sheet1', startrow=40, startcol=0)
dataframe2.to_excel(wri... | 1 | 2016-07-25T07:33:38Z | 38,562,115 | <p>Have a look at the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html" rel="nofollow">documentation</a> of <code>read_excel</code>, you will be surprised with some of its arguments (<code>skiprows</code>, <code>skip_footer</code> and <code>parse_cols</code>).</p>
| 0 | 2016-07-25T07:38:59Z | [
"python",
"excel",
"pandas",
"dataframe"
] |
Listing users for certain DB with PyMongo | 38,562,042 | <h1>What I'm trying to acheive</h1>
<p>I'm trying to fetch users for a certain database.</p>
<h1>What I did so far</h1>
<p>I was able to find function to list the databases or create users but none for listing the users, I thought about invoking an arbitrary command such as <code>show users</code> but I could find ... | 2 | 2016-07-25T07:34:19Z | 38,562,592 | <p>You can execute the <a href="https://docs.mongodb.com/manual/reference/command/usersInfo/#dbcmd.usersInfo" rel="nofollow"><code>usersInfo</code></a> command to fetch the users data. Like:</p>
<pre><code>db.command('usersInfo')
</code></pre>
<p>It will return you a result like this: (I had created the <code>testing... | 3 | 2016-07-25T08:09:00Z | [
"python",
"database",
"mongodb",
"pymongo"
] |
Simulating a logarithmic spiral galaxy in python | 38,562,144 | <p>I am simulating a logarithmic spiral galaxy using python. Using the parametric equations,</p>
<p><code>x= a*exp(b*theta)*cos(theta)</code>
and
<code>y= a*exp(b*theta)*sin(theta)</code></p>
<p>I used numpy.random for getting the random distribution of stars. The sample code is given below. </p>
<pre><code>import ... | 1 | 2016-07-25T07:40:45Z | 38,563,658 | <p>To rotate the image, I would calculate the new positions of the stars using a rotation matrix, which you have to do for each star like</p>
<pre><code>R = [ [ np.cos(phi), -np.sin(phi) ], [ np.sin(phi), np.cos(phi) ] ]
[x_new, y_new] = np.dot( [x_old, y_old], R )
</code></pre>
<p>What exactly do you mean with "radi... | 1 | 2016-07-25T09:06:28Z | [
"python",
"numpy",
"random",
"galaxy",
"spiral"
] |
Simulating a logarithmic spiral galaxy in python | 38,562,144 | <p>I am simulating a logarithmic spiral galaxy using python. Using the parametric equations,</p>
<p><code>x= a*exp(b*theta)*cos(theta)</code>
and
<code>y= a*exp(b*theta)*sin(theta)</code></p>
<p>I used numpy.random for getting the random distribution of stars. The sample code is given below. </p>
<pre><code>import ... | 1 | 2016-07-25T07:40:45Z | 38,570,946 | <p>If an approximation is good enough, try adding some noise the points before plotting them. For starters I would start with a <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.normal.html" rel="nofollow">normal (Gaussian) distribution</a>. For example, this tweaked version:</p>
<pre><code>imp... | 1 | 2016-07-25T14:49:50Z | [
"python",
"numpy",
"random",
"galaxy",
"spiral"
] |
Pandas rank based on several columns | 38,562,205 | <p>I have the following dataframe :</p>
<pre><code>event_id occurred_at user_id
19148 2015-10-01 1
19693 2015-10-05 2
20589 2015-10-12 1
20996 2015-10-15 1
20998 2015-10-15 1
23301 2015-10-23 2
23630 2015-10-26 1
25172 2015-11-0... | 2 | 2016-07-25T07:44:09Z | 38,562,820 | <p><code>sort_values('event_id')</code> prior to grouping then pass <code>method='first'</code> to <code>rank</code></p>
<p>Also note that if <code>occurred_at</code> isn't already <code>datetime</code>, make it <code>datetime</code>.</p>
<h3> </h3>
<pre><code># unnecessary if already datetime, but doesn't hurt to d... | 3 | 2016-07-25T08:22:30Z | [
"python",
"python-3.x",
"pandas"
] |
Ubuntu Package Installation via Python Code | 38,562,285 | <p>I have written the following code to install some packages. I don't want the script shows installation process messages in the output. When installation of a package finished, I want just a prompt printed in the output. How can I rewrite the following code to accomplish this task.</p>
<pre><code> def package... | -1 | 2016-07-25T07:48:41Z | 38,562,790 | <p>Fixed : </p>
<pre><code> def package_installation(self):
self.apt = "apt install -y "
self.packages = "python-pip python-sqlalchemy mongodb python-bson python-dpkt python-jinja2 python-magic python-gridfs python-libvirt python-bottle python-pefile python-chardet git build-essential autoconf automake libt... | 0 | 2016-07-25T08:21:14Z | [
"python",
"python-3.x",
"install",
"packageinstaller"
] |
Install python packages on a remote server without access to root | 38,562,310 | <p>I want to install some python packages on a remote server where I can actually log in and work on some existing python packages. Sometimes I need new python packages like easydict, then I have to install it. However, since I don't have access to the root (I mean I cannot sudo). How to solve this problem? Is it impos... | 0 | 2016-07-25T07:50:18Z | 38,562,772 | <p>There is no need for sudo if you want to install packages locally. Generally, you should always use a virtualenv; once that is activated, all packages install within that virtualenv only, with no need for admin privileges.</p>
| 1 | 2016-07-25T08:20:02Z | [
"python"
] |
How to print data with the same situation in a separate dives through a for loop in flask template | 38,562,312 | <p>There is a table like this in my database:</p>
<pre><code>-------------------------------------
. id . part . text .
-------------------------------------
. 1 . 1 . different text .
. 2 . 1 . different text .
. 3 . 1 . different text .
. 4 . 1 . different t... | 0 | 2016-07-25T07:50:20Z | 38,564,134 | <p>i'll suggest you keep your template as clean as possible, and put all the logic in your view, first use itertools.groupby to group the elements into seperate lists to make it easier for printing, the elements in result2 are already sorted so you don't need to sort them again, if they're not sorted groupby won't work... | 0 | 2016-07-25T09:29:17Z | [
"python",
"html",
"templates",
"for-loop",
"flask"
] |
MySQL Workbench Migration Wizard python error | 38,562,464 | <p>There are two bugs in bugs.mysql.com related to this same error (<a href="https://bugs.mysql.com/bug.php?id=66861" rel="nofollow">1</a> and <a href="https://bugs.mysql.com/bug.php?id=67831" rel="nofollow">2</a>). They either provide no solution (#2) or a replacement of the .py that does not solve the problem (#1).</... | 0 | 2016-07-25T07:59:10Z | 38,563,928 | <p>(not exactly a fix, but an alternative way to circumvent the error in my own question)</p>
<p>An alternative to the migration is: dump source to files -> import dump to destination db.</p>
<p>From the <a href="https://dev.mysql.com/doc/workbench/en/wb-admin-export-import-management.html" rel="nofollow">original in... | 0 | 2016-07-25T09:18:59Z | [
"python",
"mysql",
"mysql-workbench"
] |
HTTP client asynch calls with delay | 38,562,471 | <p>I'm using httpclient.HTTPRequest library to send Async requests, but need to add delay between requests.
This means lets say I configure RPS (Requests per second) = 5. Then I send a request each 0.2 but asynchronously. How can I send the requests asynchronously without waiting for each request response.</p>
<p>This... | 1 | 2016-07-25T07:59:37Z | 38,569,629 | <p>You can try:</p>
<pre><code>class WebRequest(RequestHandler):
def __init__(self, web_request):
self.delay = 0
self.web_request = web_request
@asynchronous
def post(self):
IOLoop.instance().add_timeout(self.delay, self._process)
@gen.coroutine
def _process(self):
... | 0 | 2016-07-25T13:53:03Z | [
"python",
"multithreading",
"http",
"asynchronous",
"client"
] |
python list of dictionaries group by and filter issue | 38,562,484 | <p>I have the following list of dictionaries. The list is already sorted. Now I have to group by worker and get his "prskill", but if in case there is not other option he gets None.</p>
<p>For each worker there are max two dictionaries, one with "prskill" None and one with the actual value. if there is only one dictio... | -2 | 2016-07-25T08:00:51Z | 38,563,064 | <p>You can Try Below Code:-</p>
<pre><code>filteredResult = {}
for sortedDict in sorted:
if sortedDict['worker_nick'] in filteredResult:
if None is not sortedDict['prskill']:
filteredResult[sortedDict['worker_nick']] = sortedDict
else:
filteredResult[sortedDict['worker_nick']] = sortedDict
filteredR... | 0 | 2016-07-25T08:36:49Z | [
"python",
"dictionary",
"group-by"
] |
Access class variables in functions - Django | 38,562,571 | <p>I have the following code:</p>
<pre><code>class MyView(View):
var2 = Choices.objects.get(id=1)
my_strings = ['0','1','2','3']
@login_required
def myfunction(self,request):
return render(request,
'app/submit.html',{'my_strings':my_strings, 'var2':var2})
</code></pre>
<p>I wan... | 0 | 2016-07-25T08:07:19Z | 38,562,659 | <p>You have to use self. In front of class variables.</p>
<p>Your function names in class based views should correspond to what http method you try to use(get, post etc...)</p>
<pre><code>@login_required
def get(self,request):
return render(request,
'app/submit.html',{'my_strings':self.my_strings, 'var... | 1 | 2016-07-25T08:13:22Z | [
"python",
"django"
] |
Access class variables in functions - Django | 38,562,571 | <p>I have the following code:</p>
<pre><code>class MyView(View):
var2 = Choices.objects.get(id=1)
my_strings = ['0','1','2','3']
@login_required
def myfunction(self,request):
return render(request,
'app/submit.html',{'my_strings':my_strings, 'var2':var2})
</code></pre>
<p>I wan... | 0 | 2016-07-25T08:07:19Z | 38,563,216 | <p>You don't have to write custom function to dispatch request...Django internally have the GET and POST method to do that... And also preferred way to handle login required is <code>method_decorator</code> </p>
<pre><code>from django.utils.decorators import method_decorator
@method_decorator(login_required, name='d... | 0 | 2016-07-25T08:45:24Z | [
"python",
"django"
] |
Run python file on shared drive without installing python or python frameworks | 38,562,591 | <p>I have placed a Pythonfile at a shared drive that I want any user to be able to start. I don't want the user to install python or any of the libraries needed (e.g pandas).</p>
<p>I want it to be easy for the user to start the program. How should I do that?</p>
<p>I have tried to create a bat-file (Z: is the shared... | 0 | 2016-07-25T08:08:57Z | 38,562,683 | <p><code>PyPy</code> does that out of the box.</p>
<p><code>CPython</code> has some sort of redistributable bundle which should suit your use-case.</p>
<p>Finally, there are these projects:</p>
<ul>
<li><a href="http://www.voidspace.org.uk/python/movpy/" rel="nofollow">http://www.voidspace.org.uk/python/movpy/</a></... | 0 | 2016-07-25T08:15:00Z | [
"python"
] |
Ridge Regression: Scikit-learn vs. direct calculation does not match for alpha > 0 | 38,562,701 | <p>In Ridge Regression, we are solving <code>Ax=b</code> with <code>L2</code> Regularization. The direct calculation is given by:</p>
<blockquote>
<p>x = (A<sup>T</sup>A + alpha * I)<sup>-1</sup>A<sup>T</sup>b</p>
</blockquote>
<p>I have looked at the scikit-learn code and they do implement the same calculation. Bu... | 2 | 2016-07-25T08:15:46Z | 38,584,218 | <p>This modification seems to yield the same result for the direct version and the numpy version:</p>
<pre><code>import numpy as np
A = np.asmatrix(np.random.rand(10,3))
b = np.asmatrix(np.random.rand(10,1))
I = np.identity(A.shape[1])
alpha = 1
x = np.linalg.inv(A.T*A + alpha * I)*A.T*b
print (x.T)
from sklearn.lin... | 0 | 2016-07-26T08:00:51Z | [
"python",
"scikit-learn",
"linear-regression"
] |
adding extra information to filename - python | 38,562,839 | <p>I used the following line to rename my file by adding timing and remove extra space and replace it with (-)
if i would like to add extra information like lable before the timing , </p>
<pre><code>filename = ("%s_%s.mp4" %(pfile, time.strftime("%Y-%m-%d_%H:%M:%S",time.localtime()))).replace(" ", "-")
</code></pre>
... | 0 | 2016-07-25T08:23:43Z | 38,562,918 | <p>You're using the function strftime incorrectly. Strftime only takes 2 arguments and you're passing it 3. </p>
<p>You would need to generate the string from the time and apply some string operations to append the extra info. </p>
<p>If you want to add MediaFile to the end of the filename simply do something like th... | 2 | 2016-07-25T08:28:51Z | [
"python"
] |
adding extra information to filename - python | 38,562,839 | <p>I used the following line to rename my file by adding timing and remove extra space and replace it with (-)
if i would like to add extra information like lable before the timing , </p>
<pre><code>filename = ("%s_%s.mp4" %(pfile, time.strftime("%Y-%m-%d_%H:%M:%S",time.localtime()))).replace(" ", "-")
</code></pre>
... | 0 | 2016-07-25T08:23:43Z | 38,562,937 | <pre><code>filename = ("%s_%s-%s.mp4" %(pfile, time.strftime("%Y-%m-%d_%H:%M:%S",time.localtime()), 'MediaFile')).replace(' ', '-')
# 'testfile_2016-07-25_10:29:28-MediaFile.mp4'
</code></pre>
<p>To understand better how this works and slightly improve readability, you can define your time stamp in a separate variable... | 1 | 2016-07-25T08:29:45Z | [
"python"
] |
adding extra information to filename - python | 38,562,839 | <p>I used the following line to rename my file by adding timing and remove extra space and replace it with (-)
if i would like to add extra information like lable before the timing , </p>
<pre><code>filename = ("%s_%s.mp4" %(pfile, time.strftime("%Y-%m-%d_%H:%M:%S",time.localtime()))).replace(" ", "-")
</code></pre>
... | 0 | 2016-07-25T08:23:43Z | 38,563,476 | <p>What you are looking for should be :</p>
<pre><code>filename = ("%s_%s_%s.mp4" %(pfile, time.strftime("%Y-%m-%d_%H:%M:%S",time.localtime()),"Mediafile")).replace(" ", "-")
</code></pre>
<p>In your original code, the 'Mediafile' string was not in the right place : you put it as an argument of strftime(), when you s... | 0 | 2016-07-25T08:58:21Z | [
"python"
] |
Speeding up the light processing of ~50GB CSV file | 38,562,864 | <p>I have a ~50GB csv file with which I have to</p>
<ul>
<li>Take several subsets of the columns of the CSV</li>
<li>Apply a different format string specification to each subset of columns of the CSV. </li>
<li>Output a new CSV for each subset with its own format specification. </li>
</ul>
<p>I opted to use Pandas, ... | 8 | 2016-07-25T08:25:20Z | 39,213,959 | <p>I don't think you're getting any advantage from a Panda's dataframe, so it is just adding overhead. Instead, you can use python's own <a href="https://docs.python.org/3/library/csv.html" rel="nofollow">CSV module</a> that is easy to use and nicely optimized in C.</p>
<p>Consider reading much larger chunks into mem... | 5 | 2016-08-29T19:42:57Z | [
"python",
"csv",
"pandas"
] |
Speeding up the light processing of ~50GB CSV file | 38,562,864 | <p>I have a ~50GB csv file with which I have to</p>
<ul>
<li>Take several subsets of the columns of the CSV</li>
<li>Apply a different format string specification to each subset of columns of the CSV. </li>
<li>Output a new CSV for each subset with its own format specification. </li>
</ul>
<p>I opted to use Pandas, ... | 8 | 2016-07-25T08:25:20Z | 39,215,634 | <p>I would try using the python csv module and generators.</p>
<p>I've found generators much faster than other approaches for parsing huge server logs and such.</p>
<pre><code>import csv
def reader(csv_filename):
with open(csv_filename, 'r') as f:
csvreader = csv.reader(f, delimiter=',', quotechar="'")
... | 0 | 2016-08-29T21:40:43Z | [
"python",
"csv",
"pandas"
] |
Speeding up the light processing of ~50GB CSV file | 38,562,864 | <p>I have a ~50GB csv file with which I have to</p>
<ul>
<li>Take several subsets of the columns of the CSV</li>
<li>Apply a different format string specification to each subset of columns of the CSV. </li>
<li>Output a new CSV for each subset with its own format specification. </li>
</ul>
<p>I opted to use Pandas, ... | 8 | 2016-07-25T08:25:20Z | 39,215,781 | <p>CPU is faster than disk access. One trick is to gzip your file and read from that.</p>
<pre><code>import gzip
with gzip.open('input.gz','r') as fin:
for line in fin:
print('got line', line)
</code></pre>
| 0 | 2016-08-29T21:54:26Z | [
"python",
"csv",
"pandas"
] |
Command failed: tar xzf android-sdk_r20-linux.tgz | 38,562,910 | <p>I was trying to build kivy app to android and got this error</p>
<pre><code># Check configuration tokens
# Ensure build layout
# Check configuration tokens
# Preparing build
# Check requirements for android
# Install platform
# Apache ANT found at /home/ali/.buildozer/android/platform/apache-ant-1.9.4
# Android SDK... | 6 | 2016-07-25T08:28:13Z | 38,612,319 | <p>The machine fails to properly download the android SDK.</p>
<p>You can confirm this by checking the md5 sum of the file :</p>
<pre><code>wget -O - http://dl.google.com/android/android-sdk_r20-linux.tgz | md5sum
</code></pre>
<p>This should output : 22a81cf1d4a951c62f71a8758290e9bb</p>
<p>If it doesn't, my first ... | 3 | 2016-07-27T11:58:56Z | [
"android",
"python",
"kivy",
"buildozer"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.