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 |
|---|---|---|---|---|---|---|---|---|---|
How can I declare a Column as a categorical feature in a DataFrame for use in ml | 37,473,380 | <p>How can I declare that a given Column in my <code>DataFrame</code> contains categorical information?</p>
<p>I have a Spark SQL <code>DataFrame</code> which I loaded from a database. Many of the columns in this <code>DataFrame</code> have categorical information, but they are encoded as Longs (for privacy). </p>
<p... | 1 | 2016-05-27T01:25:33Z | 37,548,419 | <p>Hey zero323 I used the same technique to look at the metadata and I coded up this <code>Transformer</code>.</p>
<pre><code>def _transform(self, data):
maxValues = self.getOrDefault(self.maxValues)
categoricalCols = self.getOrDefault(self.categoricalCols)
new_schema = types.StructType(data.schema.fields... | 0 | 2016-05-31T14:25:32Z | [
"python",
"apache-spark",
"pyspark",
"apache-spark-ml"
] |
Python Random Number Generator numpy_rng.random_integers(1e10)) OverflowError | 37,473,473 | <p>I am trying to generate random numbers in Python 2.7 on 64-bit Windows system through the following line of code:</p>
<pre><code>random_state=numpy_rng.random_integers(1e10)
</code></pre>
<p>But I am getting the following error.</p>
<pre><code>OverflowError: Python int too large to convert to C long.
</code></pre... | 2 | 2016-05-27T01:40:06Z | 37,473,640 | <p>The following should work, using NumPy.</p>
<pre><code>from numpy.random import randint
randint(1e10)
# 6073545190
</code></pre>
<p>You may also use the built-in <code>random.randint</code> to accomplish the same task, with differences between this and the <code>numpy.random.randint</code> function described <a h... | 1 | 2016-05-27T02:00:25Z | [
"python",
"numpy",
"random"
] |
Python Random Number Generator numpy_rng.random_integers(1e10)) OverflowError | 37,473,473 | <p>I am trying to generate random numbers in Python 2.7 on 64-bit Windows system through the following line of code:</p>
<pre><code>random_state=numpy_rng.random_integers(1e10)
</code></pre>
<p>But I am getting the following error.</p>
<pre><code>OverflowError: Python int too large to convert to C long.
</code></pre... | 2 | 2016-05-27T01:40:06Z | 37,475,382 | <p>Max integer in your Python is:</p>
<pre><code>import sys
sys.maxint
Out[61]: 2147483647
</code></pre>
<p>Or appr. <code>2.1e9</code>. That's limitation of Windows. From <a href="http://stackoverflow.com/a/3411134/5510499">this</a> post:</p>
<blockquote>
<p>In their infinitive wisdom Microsoft has decided to ma... | 2 | 2016-05-27T05:19:01Z | [
"python",
"numpy",
"random"
] |
Python 2.7: Thread local storage's instantiation when first accessed? | 37,473,523 | <p>Complete code here: <a href="https://gist.github.com/mnjul/82151862f7c9585dcea616a7e2e82033" rel="nofollow">https://gist.github.com/mnjul/82151862f7c9585dcea616a7e2e82033</a></p>
<p>Environment is Python 2.7.6 on an up-to-date Ubuntu 14.04 x64.</p>
<p><strong>Prologue:</strong>
Well, I got this strange piece of co... | 2 | 2016-05-27T01:45:52Z | 37,473,601 | <p>That's part of the contract (from <a href="http://svn.python.org/projects/python/tags/r27a1/Lib/_threading_local.py" rel="nofollow">http://svn.python.org/projects/python/tags/r27a1/Lib/_threading_local.py</a>):</p>
<blockquote>
<p>Note that if you define an <strong>init</strong> method, it will be
called each t... | 2 | 2016-05-27T01:55:52Z | [
"python",
"multithreading",
"python-2.7"
] |
Python 2.7: Thread local storage's instantiation when first accessed? | 37,473,523 | <p>Complete code here: <a href="https://gist.github.com/mnjul/82151862f7c9585dcea616a7e2e82033" rel="nofollow">https://gist.github.com/mnjul/82151862f7c9585dcea616a7e2e82033</a></p>
<p>Environment is Python 2.7.6 on an up-to-date Ubuntu 14.04 x64.</p>
<p><strong>Prologue:</strong>
Well, I got this strange piece of co... | 2 | 2016-05-27T01:45:52Z | 37,474,028 | <p>The first piece of information to consider is what is a thread-local? They are independently initialized instances of a particular type that are tied to a particular thread. With that in mind I would expect that <em>some</em> initialization code would be called multiple times. While in some languages like Java the i... | 2 | 2016-05-27T02:46:35Z | [
"python",
"multithreading",
"python-2.7"
] |
Turning a list of coordinates into a set of list/grid references | 37,473,525 | <p>I have a list which will get the top left section of a grid that is 2n+1 size.</p>
<pre><code>n = 1
section = [[x, y] for x in range (n+1) for y in range (n+1)]
</code></pre>
<p>which looks like: <code>[[0, 0], [0, 1], [1, 0], [1, 1]]</code> and will get the coordinates of the top left hand corner of the 3x3(2n+1)... | 1 | 2016-05-27T01:46:10Z | 37,473,687 | <p>You can write a helper function: </p>
<pre><code>def gL(gridList, values):
return gridlist[values[0]][values[1]]
</code></pre>
<p>Then, your </p>
<pre><code>gridTL = map(lambda m: gl(gridList, m), section)
</code></pre>
<p>Where, <code>section</code> is any of the sections you want ...</p>
<p>Note:</p>
<p... | 1 | 2016-05-27T02:06:32Z | [
"python"
] |
why does simulating keypresses not work for alt+tab and ctrl+alt+del? | 37,473,536 | <p>so i wanted to try and simulate some key presses and i used the scripts found here: </p>
<p><a href="http://stackoverflow.com/questions/11906925/python-simulate-keydown">Python simulate keydown</a></p>
<p>and </p>
<p><a href="http://stackoverflow.com/questions/13564851/generate-keyboard-events">Generate keyboard... | 0 | 2016-05-27T01:47:24Z | 37,474,271 | <pre><code>import ctypes,time
KEYEVENTF_UNICODE = 0x0004
KEYEVENTF_KEYUP = 0x0002
def PressKey(KeyUnicode):
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput( 0, KeyUnicode, KEYEVENTF_UNICODE, 0, ctypes.pointer(extra) )
x = Input( ctypes.c_ulong(1), ii_ )
ctypes.windll.user32.SendInpu... | 0 | 2016-05-27T03:15:30Z | [
"python",
"keyboard"
] |
Change IP address in selenium | 37,473,580 | <p>I am in Canada and want to use Selenium to scrape data from a Chinese website. However, since my IP is in Canada, I was always redirected to the Canada site which is different from its orginal Chinese site. How could I visit the original version of the site (which is shown to Chinese)? In other words, how can I pret... | 1 | 2016-05-27T01:52:37Z | 37,473,604 | <p>You can use proxy settings if you have access to a proxy you can connect to.</p>
<p><a href="http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp#using-a-proxy" rel="nofollow">http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp#using-a-proxy</a></p>
<pre><code>String PROXY = "localhost:8080";
org.openqa.... | -1 | 2016-05-27T01:56:11Z | [
"python",
"selenium",
"ip-address",
"vpn"
] |
Applying multiple functions on each row using Numba | 37,473,595 | <p>I have a big 2D NumPy array, let's say 5M rows and 10 columns. I want to build a few more columns according to some stateful logic implemented using Numba <code>@jitclass</code>. Let's say there are 50 such new columns to create. The idea is to iterate over all the rows of 10 columns in a Numba <code>@jit</code> ... | 1 | 2016-05-27T01:54:54Z | 37,475,656 | <p>To get a homogeneous list, you could construct a list of the <code>transform</code> functions of all filters. In this case, all list elements would would have type <code>method</code>.</p>
<pre><code># filters = list of filters
transforms = [x.transform for x in filters]
</code></pre>
<p>Then pass <code>transforms... | 0 | 2016-05-27T05:42:44Z | [
"python",
"numpy",
"optimization",
"numba"
] |
Applying multiple functions on each row using Numba | 37,473,595 | <p>I have a big 2D NumPy array, let's say 5M rows and 10 columns. I want to build a few more columns according to some stateful logic implemented using Numba <code>@jitclass</code>. Let's say there are 50 such new columns to create. The idea is to iterate over all the rows of 10 columns in a Numba <code>@jit</code> ... | 1 | 2016-05-27T01:54:54Z | 37,760,026 | <p>You originally asked about doing this with a single function that loops over rows, and applies a list of filters to each row. A challenge with this approach is that numba needs to know or be able to infer the input/output types of each function. I'm not aware of a way to satisfy numba's requirement in this situation... | 2 | 2016-06-11T04:48:54Z | [
"python",
"numpy",
"optimization",
"numba"
] |
Remove Weird Characters using python | 37,473,597 | <p>I have this large SQL file with about 1 milllion inserts in it, some of the inserts are corrupted (about 6000) with weird characters that i need to remove so i can insert them into my DB. </p>
<p>Ex:
INSERT INTO <code>BX-Books</code> VALUES ('2268032019','Petite histoire de la d̮?̩̉sinformation','Vladimi... | -1 | 2016-05-27T01:55:01Z | 37,473,681 | <pre><code> import string
strg = "'2268032019', Petite histoire de la d̮?̩̉sinformation','Vladimir Volkoff',1999,'Editions du Rocher','http://images.amazon.com/images/P/2268032019.01.THUMBZZZ.jpg','http://images.amazon.com/images/P/2268032019.01.MZZZZZZZ.jpg','http://images.amazon.com/images/P/2268032019.... | 0 | 2016-05-27T02:05:52Z | [
"python",
"sql",
"string",
"ascii",
"non-ascii-characters"
] |
Remove Weird Characters using python | 37,473,597 | <p>I have this large SQL file with about 1 milllion inserts in it, some of the inserts are corrupted (about 6000) with weird characters that i need to remove so i can insert them into my DB. </p>
<p>Ex:
INSERT INTO <code>BX-Books</code> VALUES ('2268032019','Petite histoire de la d̮?̩̉sinformation','Vladimi... | -1 | 2016-05-27T01:55:01Z | 37,473,779 | <p>You can use regular expressions sub() to do simple string replacements.
<a href="https://docs.python.org/2/library/re.html#re.sub" rel="nofollow">https://docs.python.org/2/library/re.html#re.sub</a></p>
<pre><code># -*- coding: utf-8 -*-
import re
dirty_string = u'̩̉sinformation'
# in first param, put a r... | -1 | 2016-05-27T02:16:31Z | [
"python",
"sql",
"string",
"ascii",
"non-ascii-characters"
] |
Convert a pandas data frame to a pandas data frame with another style | 37,473,599 | <p>I have data frame containing the IDs of animals and types they belong to as given below</p>
<pre><code>ID Class
1 1
2 1
3 0
4 4
5 3
6 2
7 1
8 0
</code></pre>
<p>I want convert it to a new style with the classes on the header row as follows.</p>
<pre><code>ID 0 1 2 3 4
1 1 ... | 0 | 2016-05-27T01:55:39Z | 37,473,717 | <p>See <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html" rel="nofollow"><code>get_dummies()</code></a>:</p>
<pre><code>>>> print df
ID Class
0 1 1
1 2 1
2 3 0
3 4 4
4 5 3
5 6 2
6 7 1
7 8 0
>>> df2 = pd... | 1 | 2016-05-27T02:10:27Z | [
"python",
"pandas",
"dataframe",
"ipython"
] |
Adding github libraries to python requirements file | 37,473,684 | <p>How can I add libraries in <code>requirements.txt</code>? For example <code>jenks</code> library is installable like this:</p>
<pre><code>pip install -e "git+https://github.com/perrygeo/jenks.git#egg=jenks"
</code></pre>
<p>However, if I just write <code>jenks</code> in <code>requirements.txt</code>, then <code>pi... | 1 | 2016-05-27T02:06:20Z | 37,473,819 | <p>You can add it to your <code>requirements.txt</code> like this:</p>
<pre><code>-e git://github.com/perrygeo/jenks.git#egg=jenks
</code></pre>
<p>See <a href="https://pip.pypa.io/en/stable/reference/pip_install/?highlight=requirements%20format#git" rel="nofollow">Git Support</a> for details.</p>
| 1 | 2016-05-27T02:21:12Z | [
"python",
"pip",
"requirements"
] |
Python: How do I fill an array with a range of numbers? | 37,473,697 | <p>So I have an array of 100 elements:</p>
<pre><code>a = np.empty(100)
</code></pre>
<p>How do I fill it with a range of numbers? I want something like this:</p>
<pre><code>b = a.fill(np.arange(1, 4, 0.25))
</code></pre>
<p>So I want it to keep filling <code>a</code> with that values of that range on and on until ... | 2 | 2016-05-27T02:08:00Z | 37,473,832 | <p>updating solution to fit description</p>
<pre><code>a = np.empty(100)
filler = np.arange(1,4,0.25)
index = np.arange(a.size)
np.put(a,index,filler)
</code></pre>
| 1 | 2016-05-27T02:23:20Z | [
"python",
"arrays",
"numpy",
"fill"
] |
Python: How do I fill an array with a range of numbers? | 37,473,697 | <p>So I have an array of 100 elements:</p>
<pre><code>a = np.empty(100)
</code></pre>
<p>How do I fill it with a range of numbers? I want something like this:</p>
<pre><code>b = a.fill(np.arange(1, 4, 0.25))
</code></pre>
<p>So I want it to keep filling <code>a</code> with that values of that range on and on until ... | 2 | 2016-05-27T02:08:00Z | 37,473,969 | <p><a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.put.html" rel="nofollow"><code>np.put</code></a> places values from <code>b</code> into <code>a</code> at the target indices, <code>ind</code>. If <code>v</code> is shorter than <code>ind</code>, its values are repeated as necessary:</p>
<pre... | 3 | 2016-05-27T02:39:29Z | [
"python",
"arrays",
"numpy",
"fill"
] |
set render images path in maya by python | 37,473,712 | <p>I want to render images in specific location in Maya 2015.</p>
<p>for that i want to set the image output path by python (pymel or cmds).</p>
<pre><code>import maya.cmds as cmds
import pymel.core as pm
path = r"D:\my_renderpath"
pm.mel.eval(r' setProject "{}"'.format(path))
</code></pre>
<p>with above code i am ... | -2 | 2016-05-27T02:10:01Z | 37,476,956 | <p>To change the Image path in maya project window i found this way. </p>
<p>create a workspace.mel file and set project.</p>
<pre><code>import pymel.core as pm
# Create a workspace MEL file
path = "D:\\my_renderpath"
workspace = '//Custom Maya Project Definition' \
'\n' \
'workspace -fr ... | 2 | 2016-05-27T07:07:54Z | [
"python",
"maya",
"maya-api"
] |
set render images path in maya by python | 37,473,712 | <p>I want to render images in specific location in Maya 2015.</p>
<p>for that i want to set the image output path by python (pymel or cmds).</p>
<pre><code>import maya.cmds as cmds
import pymel.core as pm
path = r"D:\my_renderpath"
pm.mel.eval(r' setProject "{}"'.format(path))
</code></pre>
<p>with above code i am ... | -2 | 2016-05-27T02:10:01Z | 37,489,041 | <p>You want the <a href="https://knowledge.autodesk.com/search-result/caas/CloudHelp/cloudhelp/2016/ENU/Maya-Tech-Docs/CommandsPython/workspace-html.html" rel="nofollow">workspace()</a> command</p>
| 2 | 2016-05-27T17:14:02Z | [
"python",
"maya",
"maya-api"
] |
set render images path in maya by python | 37,473,712 | <p>I want to render images in specific location in Maya 2015.</p>
<p>for that i want to set the image output path by python (pymel or cmds).</p>
<pre><code>import maya.cmds as cmds
import pymel.core as pm
path = r"D:\my_renderpath"
pm.mel.eval(r' setProject "{}"'.format(path))
</code></pre>
<p>with above code i am ... | -2 | 2016-05-27T02:10:01Z | 39,329,080 | <pre><code>import pymel.core as pm
pm.mel.setProject( r"D:\my_renderpath")
</code></pre>
| 1 | 2016-09-05T10:53:57Z | [
"python",
"maya",
"maya-api"
] |
Processing lines of text file between two marker lines | 37,473,770 | <p>My code processes lines read from a text file (see "Text Processing Details" at end). I need to amend my code so that it carries out the same task, but only with words in between certain points.</p>
<blockquote>
<p>Code should not bother about this text. Skip it.</p>
<p>*****This is the marker to say where ... | 0 | 2016-05-27T02:15:33Z | 37,473,891 | <p>I recommend using regular expressions.</p>
<pre><code>from re import compile, findall
exp = compile(r'\*{5}([^\*]+)\*{3}|"([^"]+)"')
infile = open(filename, 'r', encoding="utf-8")
text = infile.read().lower() # Notice, no .split()
text_exclusive = ' '.join([''.join(block) for block in findall(exp, text)])
# us... | 0 | 2016-05-27T02:30:19Z | [
"python",
"file-io",
"text-processing"
] |
Processing lines of text file between two marker lines | 37,473,770 | <p>My code processes lines read from a text file (see "Text Processing Details" at end). I need to amend my code so that it carries out the same task, but only with words in between certain points.</p>
<blockquote>
<p>Code should not bother about this text. Skip it.</p>
<p>*****This is the marker to say where ... | 0 | 2016-05-27T02:15:33Z | 37,473,964 | <p>You can get only the text between your asterisks with regex:</p>
<pre><code>import re
betweenAstericks = re.search(r"\*{5}.+?\*{3}(.+?)\*{3}", text, re.DOTALL).group(1)
</code></pre>
| 0 | 2016-05-27T02:38:40Z | [
"python",
"file-io",
"text-processing"
] |
Processing lines of text file between two marker lines | 37,473,770 | <p>My code processes lines read from a text file (see "Text Processing Details" at end). I need to amend my code so that it carries out the same task, but only with words in between certain points.</p>
<blockquote>
<p>Code should not bother about this text. Skip it.</p>
<p>*****This is the marker to say where ... | 0 | 2016-05-27T02:15:33Z | 37,508,163 | <p>What appears to be one task, "count the words between two marker lines", is actually several. Separate the different tasks and decisions into separate functions and generators, and it will be <em>vastly</em> easier.</p>
<p>Step 1: Separate the file I/O from the word counting. Why should the word-counting code ca... | 0 | 2016-05-29T09:17:45Z | [
"python",
"file-io",
"text-processing"
] |
How do I submit data to a web form in python? | 37,473,861 | <p>I'm trying to automate the process of creating an account for something, lets call it X, but I cant figure out what to do.</p>
<p>I saw this code somewhere,</p>
<pre><code>import urllib
import urllib2
import webbrowser
data = urllib.urlencode({'q': 'Python'})
url = 'http://duckduckgo.com/html/'
full_url = url + '... | 0 | 2016-05-25T19:34:11Z | 37,476,982 | <p>I would highly recommend utilizing Selenium+Webdriver for this, since your question appears UI and browser-based. You can install Selenium via 'pip install selenium' in most cases. Here are a couple of good references to get started.
- <a href="http://selenium-python.readthedocs.io/" rel="nofollow">http://selenium-p... | 1 | 2016-05-27T07:09:19Z | [
"python",
"automation",
"python-3.x",
"bots",
"webforms"
] |
Assigning multiple values to multiple variables in a single line | 37,473,901 | <p>I'm trying to write the Java equivalent of the following Python Inversion-Sort algorithm:</p>
<pre><code>import numpy as np
def main(items):
for i in range(1, len(items)):
j = i
while j > 0 and items[j] < items[j-1]:
items[j], items[j-1] = items[j-1], items[j]
j -... | 1 | 2016-05-27T02:31:57Z | 37,473,950 | <p>That's because you need to use a <code>temp</code> variable to store one of the values when you swap between the items[j] with items[j-1]. It should be something like that:</p>
<pre><code>int temp = items[j];
items[j] = items[j-1];
items[j-1] = temp;
</code></pre>
<p>What happens is that you lose the original valu... | 4 | 2016-05-27T02:37:49Z | [
"java",
"python",
"insertion-sort"
] |
Assigning multiple values to multiple variables in a single line | 37,473,901 | <p>I'm trying to write the Java equivalent of the following Python Inversion-Sort algorithm:</p>
<pre><code>import numpy as np
def main(items):
for i in range(1, len(items)):
j = i
while j > 0 and items[j] < items[j-1]:
items[j], items[j-1] = items[j-1], items[j]
j -... | 1 | 2016-05-27T02:31:57Z | 37,473,959 | <p>So basically you want to swap the two indexes. You can do it like this
<code>
int tmp = items[j];
items[j] = items[j-1];
items[j-1] = tmp;
</code></p>
| 2 | 2016-05-27T02:38:30Z | [
"java",
"python",
"insertion-sort"
] |
JSON output from Google Drive admin SDK activity.list() | 37,473,967 | <p>I'm working on collecting users activity logs from Google Drive's Admin SDK. So far I did a python script and I'm getting some activity results in JSON format. But still, the format itself is not the one I'm looking for and here is an example:</p>
<p>{u'nextPageToken': u'A:6165487685465:-68949849879703739:3... | 0 | 2016-05-27T02:39:18Z | 37,474,212 | <p>Don't let the <a href="http://stackoverflow.com/questions/13940272/python-json-loads-returns-items-prefixing-with-u">unicode prefix</a> scare you: </p>
<p>To get you json formatted, just use json.dumps(arg, indent=2)
and the layout will be indented and spaced accordingly.</p>
<p>Ex:</p>
<pre><code>import json
pri... | 0 | 2016-05-27T03:08:50Z | [
"python",
"json",
"google-admin-sdk",
"drive"
] |
Converting list in panda dataframe into columns | 37,474,001 | <pre><code>city state neighborhoods categories
Dravosburg PA [asas,dfd] ['Nightlife']
Dravosburg PA [adad] ['Auto_Repair','Automotive']
</code></pre>
<p>I have above dataframe I want to convert each element of a list into column for eg:</p>
<pre><code>city state... | 0 | 2016-05-27T02:43:47Z | 37,474,423 | <p>Use this instead</p>
<pre><code>def list2columns(df):
"""
to convert list in the columns
of a dataframe
"""
df = df.copy()
columns=['categories','neighborhoods']
for col in columns:
for i in range(len(df)):
for element in eval(df.loc[i,"categories"]):
... | 2 | 2016-05-27T03:36:38Z | [
"python",
"list",
"pandas",
"dataframe",
"data-analysis"
] |
Converting list in panda dataframe into columns | 37,474,001 | <pre><code>city state neighborhoods categories
Dravosburg PA [asas,dfd] ['Nightlife']
Dravosburg PA [adad] ['Auto_Repair','Automotive']
</code></pre>
<p>I have above dataframe I want to convert each element of a list into column for eg:</p>
<pre><code>city state... | 0 | 2016-05-27T02:43:47Z | 37,491,179 | <p>Since you're using <code>eval()</code>, I assume each column has a string representation of a list, rather than a list itself. Also, unlike your example above, I'm assuming there are quotes around the items in the lists in your <code>neighborhoods</code> column (<code>df.iloc[0, 'neighborhoods'] == "['asas','dfd']"<... | 1 | 2016-05-27T19:45:41Z | [
"python",
"list",
"pandas",
"dataframe",
"data-analysis"
] |
SyntaxError: invalid syntax about dict.fromkeys usage | 37,474,042 | <p>the original code that works.</p>
<pre><code>tbl = dict.fromkeys(i for i in xrange(sys.maxunicode) if unicodedata.category(unichr(i)).startswith('P'))
</code></pre>
<p>but when I want to see what is it in the <code>()</code>, I got the error message. </p>
<pre><code>i for i in xrange(sys.maxunicode) if unicodedat... | 0 | 2016-05-27T02:48:29Z | 37,474,070 | <p>You have a <a href="https://docs.python.org/2/tutorial/classes.html#generator-expressions" rel="nofollow"><em>generator expression</em></a>, which normally must be surrounded by parentheses:</p>
<pre><code>(i for i in xrange(sys.maxunicode) if unicodedata.category(unichr(i)).startswith('P'))
</code></pre>
<p>The p... | 3 | 2016-05-27T02:51:38Z | [
"python"
] |
how to execute the output of print statement in python? | 37,474,080 | <pre><code>def BeersAll(request):
print request.COOKIES
attrib_list = dir(request)
print attrib_list
xyz = 'request.'+str(attrib_list[0])
print xyz
beers = Beer.objects.all().order_by('name')
context = {'beers': beers}
return render_to_response('index.html', context, context_instance=Req... | -2 | 2016-05-27T02:52:49Z | 37,474,511 | <pre><code>req_data = {'request': []}
for attr in attrib_list:
req_data['request'].append(attr)
</code></pre>
<p>and render it to templates. but I dont understand why you would need this</p>
| 0 | 2016-05-27T03:47:28Z | [
"python",
"django"
] |
Python 3.5 ctypes libc printf() only prints first byte of string Windows 7/10 | 37,474,192 | <p>I'm trying to follow one of the Gray Hat Python examples and it works fine in Python 2.7, but in Python 3.5 the result is truncated. </p>
<pre><code>from ctypes import *
msvcrt = cdll.msvcrt
message_string = "Hello World!\n"
msvcrt.printf("Testing: %s\n", message_string)
</code></pre>
<p>You can see below the th... | 1 | 2016-05-27T03:06:17Z | 37,474,272 | <p>The command should be <code>msvcrt.printf("Testing: %s\n" % message_string)</code> - you have a comma in place of the <code>%</code> symbol</p>
| 0 | 2016-05-27T03:15:39Z | [
"python",
"c",
"windows",
"pydev"
] |
Python 3.5 ctypes libc printf() only prints first byte of string Windows 7/10 | 37,474,192 | <p>I'm trying to follow one of the Gray Hat Python examples and it works fine in Python 2.7, but in Python 3.5 the result is truncated. </p>
<pre><code>from ctypes import *
msvcrt = cdll.msvcrt
message_string = "Hello World!\n"
msvcrt.printf("Testing: %s\n", message_string)
</code></pre>
<p>You can see below the th... | 1 | 2016-05-27T03:06:17Z | 37,487,108 | <p>Got it to work! Needed to add the <code>b</code> in the variable declaration too. Such a small detail too...See adjusted code below:</p>
<pre><code>from ctypes import *
msvcrt = CDLL('msvcrt')
message_string = b"Hello World!\n"
msvcrt.printf(b"Testing: %s\n", message_string)
</code></pre>
<p>Tested on Windows 7 ... | 2 | 2016-05-27T15:20:36Z | [
"python",
"c",
"windows",
"pydev"
] |
Changing while loop to for loop | 37,474,251 | <p>I was wondering if this same code could be made with a <code>for loop</code> instead of a <code>while</code></p>
<pre><code>d = 0.6
b = 0.0
h = 0.0
t = 0.0
count = 0
h = float(input("enter height: "))
b = float(input("enter a number of bounces: "))
t = h
while count < b:
if count == b - 1:
t += h... | 0 | 2016-05-27T03:12:47Z | 37,474,285 | <p>As GLHF reminded me, the <code>b</code> should be an int in order for the code below to work.<br>
I see no reason for a variable <code>b</code>, representing a number of bounces to be a float. Moreover, in your original code you have a comparison between <code>count</code> (an int) and <code>b</code> (float from use... | 1 | 2016-05-27T03:17:21Z | [
"python"
] |
Changing while loop to for loop | 37,474,251 | <p>I was wondering if this same code could be made with a <code>for loop</code> instead of a <code>while</code></p>
<pre><code>d = 0.6
b = 0.0
h = 0.0
t = 0.0
count = 0
h = float(input("enter height: "))
b = float(input("enter a number of bounces: "))
t = h
while count < b:
if count == b - 1:
t += h... | 0 | 2016-05-27T03:12:47Z | 37,474,528 | <p>Since you don't change your variables from <code>float</code> type to <code>integer</code> you can't do it, because you need <code>range()</code> function and <code>range()</code> only accepts integer type.</p>
<p>If you set your variables to an integer instead of float, you can use it in a for loop like;</p>
<pre... | 0 | 2016-05-27T03:49:43Z | [
"python"
] |
What arguments are available for the Python Tk() constructor? | 37,474,280 | <p>I'm trying to make a python tkinter application and I'm having a lot of trouble finding a list of what arguments are available for creating a <code>Tk</code> object.</p>
<p>example:</p>
<pre><code>from tkinter import *
root = Tk(<args>)
root.mainloop()
</code></pre>
<p>Where can I find a full list of the ar... | -5 | 2016-05-27T03:16:57Z | 37,474,369 | <p>I used the documentation, which can be accessed via IDLE, Is this what you looking for?</p>
<p><a href="http://i.stack.imgur.com/vVNtR.png" rel="nofollow"><img src="http://i.stack.imgur.com/vVNtR.png" alt="enter image description here"></a></p>
| 1 | 2016-05-27T03:27:52Z | [
"python",
"constructor",
"tkinter",
"arguments",
"tk"
] |
pyspark: type object 'Row' has no attribute 'fromSeq' | 37,474,359 | <p>I have the following code:</p>
<pre><code>from pyspark.sql import Row
z1=["001",1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,30,41,42,43]
print z1
r1 = Row.fromSeq(z1)
print (r1)
</code></pre>
<p>Then I got error:</p>
<pre><code>AttributeError ... | -1 | 2016-05-27T03:26:30Z | 37,482,820 | <p>If you don't provide names just use <code>tuple</code>:</p>
<pre><code>tuple(z1)
</code></pre>
<p>This is all what is needed to build correct DataFrame</p>
| 0 | 2016-05-27T11:51:40Z | [
"python",
"dataframe",
"pyspark"
] |
How to edit QTreeWidgetItem when it is editable | 37,474,397 | <p><a href="http://i.stack.imgur.com/6nY9z.png" rel="nofollow"><img src="http://i.stack.imgur.com/6nY9z.png" alt="enter image description here"></a></p>
<p>When the item is double-clicked and the user enters a new item name I want this text value to be assigned to the <code>item._name</code> attribute which is printed... | 0 | 2016-05-27T03:32:38Z | 37,474,690 | <p><a href="http://i.stack.imgur.com/oGbx8.png" rel="nofollow"><img src="http://i.stack.imgur.com/oGbx8.png" alt="enter image description here"></a></p>
<p>Subclass <code>QTreeWidgetItem</code>. Define <code>setData</code> method to assign the value to the attribute <code>_name</code>.</p>
<pre><code>from PyQt4 impor... | 0 | 2016-05-27T04:06:57Z | [
"python",
"qt",
"pyqt",
"qtreewidget",
"qtreewidgetitem"
] |
How can you avoid lots of os.pardir in a row when constructing upward paths using os.path.join? | 37,474,545 | <p>I'm trying to avoid this kind of thing:</p>
<pre><code>sibling_location = os.path.join(leaf_dir, os.pardir, os.pardir, os.pardir, sibling_name)
</code></pre>
<p>I thought it would be cool to say</p>
<pre><code>sibling_location = os.path.join(leaf_dir, *[os.pardir]*3, sibling_name)
</code></pre>
<p>but unfortunat... | 2 | 2016-05-27T03:51:56Z | 37,474,576 | <p>Heh - found a way.</p>
<pre><code>sibling_location = os.path.join(leaf_dir, *([os.pardir]*3 + [sibling_name]))
</code></pre>
<p>It doesn't read wildly well, but it is concise. Happy to accept other better answers :)</p>
| 1 | 2016-05-27T03:54:29Z | [
"python",
"python-2.7",
"path",
"filesystems"
] |
How can you avoid lots of os.pardir in a row when constructing upward paths using os.path.join? | 37,474,545 | <p>I'm trying to avoid this kind of thing:</p>
<pre><code>sibling_location = os.path.join(leaf_dir, os.pardir, os.pardir, os.pardir, sibling_name)
</code></pre>
<p>I thought it would be cool to say</p>
<pre><code>sibling_location = os.path.join(leaf_dir, *[os.pardir]*3, sibling_name)
</code></pre>
<p>but unfortunat... | 2 | 2016-05-27T03:51:56Z | 37,474,671 | <p>How about using <a href="https://pypi.python.org/pypi/pathlib2/" rel="nofollow"><code>pathlib2</code></a> (backport of Python 3 standard library module <a href="http://docs.python.org/3/library/pathlib.html" rel="nofollow"><code>pathlib</code></a>)?</p>
<pre><code>>>> leaf_dir = '/path/to/some/deep/deeper/... | 2 | 2016-05-27T04:04:44Z | [
"python",
"python-2.7",
"path",
"filesystems"
] |
Python: change "- hrs - min - sec' string into minutes decimal | 37,474,558 | <p>I am currently working on a project in Python (had to self-teach myself Python, still currently learning) that takes data from a csv file given to me. </p>
<p>I am currently stuck on how I would loop through the list to translate a string from a list such as "2 hrs 5 min 15 sec" into a decimal and saves it as anoth... | 1 | 2016-05-27T03:53:19Z | 37,474,659 | <p>Function :</p>
<pre><code>def hms_to_mins(t):
h, m, s = [int(i) for i in t.split(' ')]
return float(60*h + m + (s/60))
hms_to_mins('5 30 0')
</code></pre>
<p>Output: <code>330.0</code></p>
<p>You may add few more things to validate input & check that there are 3 inputs(hrs, mins & secs).</p>
<p>... | 1 | 2016-05-27T04:04:04Z | [
"python",
"list",
"csv",
"time"
] |
Python: change "- hrs - min - sec' string into minutes decimal | 37,474,558 | <p>I am currently working on a project in Python (had to self-teach myself Python, still currently learning) that takes data from a csv file given to me. </p>
<p>I am currently stuck on how I would loop through the list to translate a string from a list such as "2 hrs 5 min 15 sec" into a decimal and saves it as anoth... | 1 | 2016-05-27T03:53:19Z | 37,474,667 | <p>There are multiple options to parse these time strings. Here is one way to do it (probably not the most short one, but an easy to understand) - using <a href="https://docs.python.org/2/library/time.html#time.strptime" rel="nofollow"><code>time.strptime()</code></a> to load the time string by trial and error using 3 ... | 0 | 2016-05-27T04:04:42Z | [
"python",
"list",
"csv",
"time"
] |
Python: change "- hrs - min - sec' string into minutes decimal | 37,474,558 | <p>I am currently working on a project in Python (had to self-teach myself Python, still currently learning) that takes data from a csv file given to me. </p>
<p>I am currently stuck on how I would loop through the list to translate a string from a list such as "2 hrs 5 min 15 sec" into a decimal and saves it as anoth... | 1 | 2016-05-27T03:53:19Z | 37,474,919 | <pre><code>def str2dig(s):
nline = s.split(' ')
if len(nline) == 6:
minutes = int(nline[0])*60+int(nline[2])+ float(nline[4])/60
elif len(nline) == 4:
minutes = int(nline[0]) + float(nline[2])/60
else:
minutes = float(nline[0])/60
return round(minutes,2)
s =... | 0 | 2016-05-27T04:34:16Z | [
"python",
"list",
"csv",
"time"
] |
R's equivalent to Python's importing mechanism | 37,474,585 | <p>In Python, suppose we have:</p>
<pre><code>lib.py:
def myFunction():
...
main.py:
import lib
lib.myFunction()
</code></pre>
<p>so that <code>myFunction</code> is in module <code>lib</code> and is not going to pollute the global environment.</p>
<p>However, in R, to use <code>myFunction</code>:</p>
<pre><c... | 0 | 2016-05-27T03:55:24Z | 37,475,040 | <p>If you import two libraries with same function name, you can use <code>libraryname::function(...)</code>.</p>
<p>This won't solve your problem, but will ensure you're using the correct function from the correct library.</p>
| 0 | 2016-05-27T04:46:28Z | [
"python",
"import"
] |
Need help sorting data and computing averages | 37,474,593 | <p>I need to create a code that will run like this when executed : </p>
<pre><code>What would you like to do: s
You have selected Statistics
This option is for viewing statistics sorted by the year of student.
Please select one of the following options:
a for ALL YEARS
b for FRESHMAN
c for SOPHMORES
d for JUNIORS
e... | 0 | 2016-05-27T03:56:48Z | 37,474,840 | <pre><code>ablao = [3,74,96,72,88,71 ,80 ,83 ,77 ,90 ,88 ,95 ,71 ,76 ,94 ,80 ,74 ,98 ,77]
anderson = [3,76 ,92 ,98 ,95 ,92 ,76 ,93 ,97 ,85 ,76 ,85 ,93 ,82 ,88 ,75 ,84 ,92 ,77]
aspinwall = [1,86 ,74 ,78 ,97 ,86 ,94 ,73 ,95 ,74 ,91 ,75 ,94 ,83 ,99 ,83 ,78 ,88 ,96]
for dat1,dat2,dat3 in zip (ablao,anderson,aspinwall):
... | 0 | 2016-05-27T04:25:57Z | [
"python",
"list",
"file",
"sorting"
] |
Need help sorting data and computing averages | 37,474,593 | <p>I need to create a code that will run like this when executed : </p>
<pre><code>What would you like to do: s
You have selected Statistics
This option is for viewing statistics sorted by the year of student.
Please select one of the following options:
a for ALL YEARS
b for FRESHMAN
c for SOPHMORES
d for JUNIORS
e... | 0 | 2016-05-27T03:56:48Z | 37,474,980 | <p>To read the file of student information do</p>
<pre><code>with open('/path/to/scores.txt', 'r') as f:
lines = f.readlines()
</code></pre>
<p>You can then loop through all lines you just read from the file and extract the relevant information. <code>line.split()</code> splits a line into a list of strings at th... | 0 | 2016-05-27T04:40:44Z | [
"python",
"list",
"file",
"sorting"
] |
selecting an item from listbox and using the name of the item later | 37,474,609 | <p>I'm making a small project using Python 3.4/5 in conjunction with Tkinter. I have make a list box that shows all items in a directory. I can't seem to find a way to select an item and then save the name in a variable for later use.</p>
<pre><code>listnotes = Listbox(notebox, selectmode=SINGLE)
listnotes.pack(side=L... | 1 | 2016-05-27T03:58:34Z | 37,475,018 | <p>You have to use <a href="http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm" rel="nofollow">Bindings</a> to do so, </p>
<p>For Ex:</p>
<pre><code>listnotes.bind("<Return>", dosomething) #to bind to your enterkey
</code></pre>
<p>and then the curselection method associated to the <a href="http:/... | 2 | 2016-05-27T04:44:19Z | [
"python",
"list",
"tkinter"
] |
Read .tar.gz file in Python | 37,474,767 | <p>I have a text file of 25GB. so i compressed it to tar.gz and it became 450 MB. now i want to read that file from python and process the text data.for this i referred <a href="http://stackoverflow.com/questions/2018512/reading-tar-file-contents-without-untarring-it-in-python-script">question</a> . but in my case code... | 3 | 2016-05-27T04:17:45Z | 37,474,813 | <p>The <a href="https://docs.python.org/2.7/library/tarfile.html#tarfile.TarFile.extractfile">docs</a> tell us that <em>None</em> is returned by <em>extractfile()</em> if the member is a not a regular file or link.</p>
<p>One possible solution is to skip over the <em>None</em> results:</p>
<pre><code>tar = tarfile.op... | 6 | 2016-05-27T04:22:13Z | [
"python",
"file"
] |
Read .tar.gz file in Python | 37,474,767 | <p>I have a text file of 25GB. so i compressed it to tar.gz and it became 450 MB. now i want to read that file from python and process the text data.for this i referred <a href="http://stackoverflow.com/questions/2018512/reading-tar-file-contents-without-untarring-it-in-python-script">question</a> . but in my case code... | 3 | 2016-05-27T04:17:45Z | 37,474,827 | <p><a href="https://docs.python.org/3/library/tarfile.html#tarfile.TarFile.extractfile" rel="nofollow"><code>tarfile.extractfile()</code></a> can return <code>None</code> if the member is neither a file nor a link. For example your tar archive might contain directories or device files. To fix:</p>
<pre><code>import ta... | 2 | 2016-05-27T04:24:41Z | [
"python",
"file"
] |
Read .tar.gz file in Python | 37,474,767 | <p>I have a text file of 25GB. so i compressed it to tar.gz and it became 450 MB. now i want to read that file from python and process the text data.for this i referred <a href="http://stackoverflow.com/questions/2018512/reading-tar-file-contents-without-untarring-it-in-python-script">question</a> . but in my case code... | 3 | 2016-05-27T04:17:45Z | 37,474,942 | <p>You may try this one</p>
<pre><code>t = tarfile.open("filename.gz", "r")
for filename in t.getnames():
try:
f = t.extractfile(filename)
Data = f.read()
print filename, ':', f.read()
except :
print 'ERROR: Did not find %s in tar archive' % filename
</code></pre>
| 1 | 2016-05-27T04:36:37Z | [
"python",
"file"
] |
Read .tar.gz file in Python | 37,474,767 | <p>I have a text file of 25GB. so i compressed it to tar.gz and it became 450 MB. now i want to read that file from python and process the text data.for this i referred <a href="http://stackoverflow.com/questions/2018512/reading-tar-file-contents-without-untarring-it-in-python-script">question</a> . but in my case code... | 3 | 2016-05-27T04:17:45Z | 37,502,758 | <p>You cannot "read" the content of some special files such as links yet tar supports them and tarfile will extract them alright. When <code>tarfile</code> extracts them, it does not return a file-like object but None. And you get an error because your tarball contains such a special file.</p>
<p>One approach is to de... | 1 | 2016-05-28T18:57:12Z | [
"python",
"file"
] |
Query DateTime with PyMongo | 37,474,784 | <p>In my database i have "createTime" value like this : </p>
<pre><code>{
"_id" : ObjectId("5744041be1db9cc2fc942660"),
"_class" : "vn.cdt.entity.db.AccessLog",
"url" : "/bo-trang-diem/bo-phan-trang-diem-make-up-kit-a-d-s-208242816346",
"userAgent" : "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/53... | 0 | 2016-05-27T04:19:53Z | 37,474,946 | <p>Using pymongo this can be done using:</p>
<pre><code>from datetime import date, timedelta
db.collection.find({'createTime':{'$lt':datetime.datetime.now(), '$gt':datetime.datetime.now() - timedelta(hours=24)}})
</code></pre>
| 0 | 2016-05-27T04:36:45Z | [
"python",
"mongodb",
"pymongo"
] |
Efficient list copying | 37,474,809 | <p>I have some code that works, but I'm concerned its really inefficient. Is there a more performant way of chunking/batching a list of dict's into a sort of buffer.</p>
<pre><code>rowA = {1:"a",2:"b",3:"c"} # Random dict
rowB = {4:"d",5:"e",6:"f"} # Random dict
rowC = {7:"g",8:"h",9:"i"} # Ran... | 2 | 2016-05-27T04:21:42Z | 37,474,878 | <p>To split a list A into two :</p>
<pre><code>Part1=A[:len(A)/2]
Part2=A[len(A)/2:]
</code></pre>
<p>I think this is all you need :</p>
<pre><code>>>> for row in rows: # Iterate over the list
... A.append(list(row.values()))
...
>>> A=row_chunk
>>> B=A[:len(A)... | 2 | 2016-05-27T04:30:16Z | [
"python",
"python-3.x"
] |
How to train a model in C++ with tensorflow? | 37,474,832 | <p>I tried to trained a experiment with deep learning model.
I found that tensorflow is the best way to do this.
But there is problem that tensorflow need to be writen in python.
And my program contain many loops.Like this..</p>
<pre><code>for i=1~2000
for j=1~2000
</code></pre>
<p>I know this is a big drawback for ... | 4 | 2016-05-27T04:25:05Z | 37,498,417 | <p>It's not so easy, but it is possible.
First, you need to create tensorflow graph in python and save it in file.
This article may help you<br>
<a href="https://medium.com/jim-fleming/loading-a-tensorflow-graph-with-the-c-api-4caaff88463f#.krslipabt" rel="nofollow">https://medium.com/jim-fleming/loading-a-tensorflow-g... | 1 | 2016-05-28T11:28:25Z | [
"python",
"c++",
"tensorflow"
] |
HTTPS authentication in Python 2.7 | 37,474,875 | <p>we are trying to pass the Virustotal API through our proxy which is getting denied. HTTP websites are accessible using the code but HTTPS is not going through. Request any of you to post few sample codes which would help us. </p>
<pre><code>import postfile
host = "www.virustotal.com"
selector = "https://www.virust... | 0 | 2016-05-27T04:29:38Z | 37,616,595 | <p>Two ideas to try</p>
<p>1) without HTTPS you can post to <a href="http://www.virustotal.com/vtapi/v2/file/scan" rel="nofollow">http://www.virustotal.com/vtapi/v2/file/scan</a></p>
<p>2) try the python requests library</p>
<pre><code>import requests
params = {'apikey': '-YOUR API KEY HERE-'}
files = {'file': ('my... | 0 | 2016-06-03T14:08:51Z | [
"python",
"authentication",
"https"
] |
Persist Session Cookie in Scrapy | 37,474,939 | <p>I am scraping a site that has an accept terms form that I need to click through. When I click the button I am redirected to the resource that needs to be scraped. I have the basic mechanics working, that is the initial click through works and I get a session and all goes well until the session times out. Then for so... | -1 | 2016-05-27T04:36:31Z | 37,486,018 | <p>Cookies are enabled by default and passed through every callback, make sure you have it enabled with <a href="http://doc.scrapy.org/en/latest/topics/downloader-middleware.html#cookies-enabled" rel="nofollow"><code>COOKIES_ENABLED=True</code></a> in <code>settings.py</code>.</p>
<p>you can also enable debugging logs... | 1 | 2016-05-27T14:27:45Z | [
"python",
"cookies",
"web-scraping",
"scrapy",
"scrapy-spider"
] |
how to slice a subset of numpy arrays | 37,475,050 | <p>Given this array:</p>
<pre><code>>>> a
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
</code></pre>
<p>How can I select <code>[[4,5], [7,8]]</code>? <code>a[0::2, 1:;2]</code> doesn't work</p>
| 1 | 2016-05-27T04:47:35Z | 37,475,069 | <pre><code>>>> a
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
>>> a[1:3,1:3]
array([[4, 5],
[7, 8]])
</code></pre>
<p>The first <code>1:3</code> is to select row 1 & 2. The second <code>1:3</code> is to select column 1 & 2.</p>
| 3 | 2016-05-27T04:48:57Z | [
"python",
"numpy"
] |
Scrape information from challenging website with no guiding HTML structure | 37,475,110 | <p>I need to scrape some information from a very challenging website</p>
<p>This is an example: </p>
<pre><code><div class="overview">
<span class="course_titles">Courses:</span>
<a href="/schools/courses/173/" class="course_name">Math101</a> (Math; Monday; Room 10);
... | 2 | 2016-05-27T04:54:02Z | 37,475,315 | <p>If you could modify your question to let us know what you're looking for exactly. But, here's a basic example of how you could grab the data from this page.</p>
<pre><code>from bs4 import BeautifulSoup
import re
html = '''<div class="overview">
<span class="course_titles">Courses:</span> ... | 0 | 2016-05-27T05:12:52Z | [
"python",
"regex",
"web-scraping",
"beautifulsoup"
] |
Scrape information from challenging website with no guiding HTML structure | 37,475,110 | <p>I need to scrape some information from a very challenging website</p>
<p>This is an example: </p>
<pre><code><div class="overview">
<span class="course_titles">Courses:</span>
<a href="/schools/courses/173/" class="course_name">Math101</a> (Math; Monday; Room 10);
... | 2 | 2016-05-27T04:54:02Z | 37,475,365 | <p>You can do it mostly BeautifulSoup then a tiny bit of regex to get the the student age that isn't inside any html tags</p>
<pre><code>soup = BeautifulSoup(html, "html.parser")
allA = soup.find("div", {"class" : "overview"}).find_all("a")
classInfo = {}
currentClass = None
for item in allA:
if item['class'] == ... | 1 | 2016-05-27T05:17:43Z | [
"python",
"regex",
"web-scraping",
"beautifulsoup"
] |
Scrape information from challenging website with no guiding HTML structure | 37,475,110 | <p>I need to scrape some information from a very challenging website</p>
<p>This is an example: </p>
<pre><code><div class="overview">
<span class="course_titles">Courses:</span>
<a href="/schools/courses/173/" class="course_name">Math101</a> (Math; Monday; Room 10);
... | 2 | 2016-05-27T04:54:02Z | 37,483,939 | <p>You don't need a regex, you can simply parse the anchor tags to get the name and call <code>next_sibling</code> to get the age text splitting and stripping to get the age text, finding the <code>course_name</code> previous to the <code>coursestudent</code> will also give you the relevant course:</p>
<pre><code>h =... | 0 | 2016-05-27T12:45:19Z | [
"python",
"regex",
"web-scraping",
"beautifulsoup"
] |
Where is the _socket file? | 37,475,151 | <p>I'm looking through python built in library modules, and for example in <code>socket.py</code> I see the line:</p>
<pre><code>import _socket
</code></pre>
<p>I understand that the socket module acts as a wrapper for <code>_socket</code>. I want to read through some of the source code files within <code>_socket</c... | 2 | 2016-05-27T04:58:18Z | 37,475,200 | <p>You can use the <code>__file__</code> attribute:</p>
<pre><code>In [11]: _socket.__file__
Out[11]: '/Users/andy/.miniconda3/lib/python3.5/lib-dynload/_socket.cpython-35m-darwin.so'
</code></pre>
<p>In python packages you can also use the <code>__path__</code> attribute (for the directory):</p>
<pre><code>In [12]:... | 1 | 2016-05-27T05:02:06Z | [
"python",
"sockets"
] |
Where is the _socket file? | 37,475,151 | <p>I'm looking through python built in library modules, and for example in <code>socket.py</code> I see the line:</p>
<pre><code>import _socket
</code></pre>
<p>I understand that the socket module acts as a wrapper for <code>_socket</code>. I want to read through some of the source code files within <code>_socket</c... | 2 | 2016-05-27T04:58:18Z | 37,475,227 | <p><code>_socket</code> is a C extension. The <code>socket.py</code> module wraps this with some additional information that doesn't need the speed boost or access to OS-level C APIs.</p>
<p>If you are versed in C, you can read the <a href="https://hg.python.org/cpython/file/3.5/Modules/socketmodule.c" rel="nofollow">... | 1 | 2016-05-27T05:04:30Z | [
"python",
"sockets"
] |
Why can't I find my repo after Git Clone into SSH? | 37,475,158 | <p>I am a beginning programmer going through this <a href="http://chimera.labs.oreilly.com/books/1234000000754/ch08.html#_adjusting_the_database_location" rel="nofollow">Test-Driven-Development tutorial</a>. I've reached the chapter where I need to spin up a server and register some domain names that I can then use wit... | 0 | 2016-05-27T04:58:58Z | 37,475,254 | <p>The problem is that you are escaping the <code>~</code> in the destination path, so it is being treated literally instead of expanding to your home directory (you will now have a directory called <code>~</code> the root of your filesystem!).</p>
<p>This should work:</p>
<pre><code>$ git clone https://github.com/us... | 3 | 2016-05-27T05:07:28Z | [
"python",
"django",
"git",
"ssh",
"git-clone"
] |
splitting ND arrays using numpy | 37,475,309 | <p>I have a 3D numpy array and I want to partition it by the first 2 dimensions (and select all elements in the last one). Is there a simple way I can do that using numpy?</p>
<p>Example: given array</p>
<pre><code>a = array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[... | 0 | 2016-05-27T05:12:13Z | 37,475,488 | <pre><code>In [179]: np.array_split(a,2,0)
Out[179]:
[array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]]]),
array([[[18, 19, 20],
[21, 22, 23],
[24, 25, 26]]])]
</code></pre>
<p>is the same as <code>[a[:2,:,:],... | 0 | 2016-05-27T05:29:05Z | [
"python",
"numpy"
] |
splitting ND arrays using numpy | 37,475,309 | <p>I have a 3D numpy array and I want to partition it by the first 2 dimensions (and select all elements in the last one). Is there a simple way I can do that using numpy?</p>
<p>Example: given array</p>
<pre><code>a = array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[... | 0 | 2016-05-27T05:12:13Z | 37,475,590 | <p>A quick list comprehension will do the trick</p>
<pre><code>[np.array_split(arr, 2, axis=1)
for arr in np.array_split(a, 2, axis=0)]
</code></pre>
<p>This will result in a list of lists, the items of which contain the arrays you're looking for.</p>
| 0 | 2016-05-27T05:38:31Z | [
"python",
"numpy"
] |
Connect Hive Kerberos authentication using pyhs2 python | 37,475,362 | <p>I am trying to connect to Hive with Kerberos authentication. But I am getting an error 'NotImplementedError: authMechanism is either not supported or not implemented'</p>
<p>I guess I need to set authMechanism to Kerberos somehow.</p>
<pre><code>import pyhs2
with pyhs2.connect(host='wx0000',
p... | 0 | 2016-05-27T05:17:27Z | 37,510,251 | <p>From the source authMechanism is case sensitive, so you'll need it to be "KERBEROS".</p>
| 0 | 2016-05-29T13:02:50Z | [
"python",
"hadoop",
"hive",
"kerberos"
] |
Connect Hive Kerberos authentication using pyhs2 python | 37,475,362 | <p>I am trying to connect to Hive with Kerberos authentication. But I am getting an error 'NotImplementedError: authMechanism is either not supported or not implemented'</p>
<p>I guess I need to set authMechanism to Kerberos somehow.</p>
<pre><code>import pyhs2
with pyhs2.connect(host='wx0000',
p... | 0 | 2016-05-27T05:17:27Z | 39,711,269 | <p>This connection string will work as long as the user running the script has a valid kerberos ticket or key tab:</p>
<pre><code>import pyhs2
with pyhs2.connect(host='beeline_hostname',
port=10000,
authMechanism="KERBEROS") as conn:
with conn.cursor() as cur:
... | 0 | 2016-09-26T19:53:22Z | [
"python",
"hadoop",
"hive",
"kerberos"
] |
Rate limiting generator wrapper? | 37,475,549 | <p>Lets say I have something like</p>
<pre><code>for user in users:
send_email(user)
</code></pre>
<p>But since I want to reduce congestion, I want something like</p>
<pre><code>for user in rate_limit(per_min=50, users):
send_email(user)
</code></pre>
<p>Where the <code>rate_limit</code> function simply s... | 0 | 2016-05-27T05:34:39Z | 37,475,654 | <p>You're probably looking for <a href="https://docs.python.org/3/library/time.html#time.sleep" rel="nofollow"><code>time.sleep()</code></a>:</p>
<ol>
<li>Yield an object</li>
<li>Sleep</li>
<li>Repeat from step 1</li>
</ol>
<p>For example:</p>
<pre><code>import time
def rate_limit(objects, per_min=None):
sleep... | 2 | 2016-05-27T05:42:37Z | [
"python",
"python-3.x"
] |
Rate limiting generator wrapper? | 37,475,549 | <p>Lets say I have something like</p>
<pre><code>for user in users:
send_email(user)
</code></pre>
<p>But since I want to reduce congestion, I want something like</p>
<pre><code>for user in rate_limit(per_min=50, users):
send_email(user)
</code></pre>
<p>Where the <code>rate_limit</code> function simply s... | 0 | 2016-05-27T05:34:39Z | 37,475,666 | <p>Just use <a href="https://docs.python.org/2/library/time.html#time.sleep" rel="nofollow"><code>time.sleep</code></a> this will suspend the current thread for a given number of seconds.</p>
| 1 | 2016-05-27T05:43:12Z | [
"python",
"python-3.x"
] |
why won't my if elif statement work for my django production environment? | 37,475,573 | <p>I'm trying to set up a local and a production settings for my django project I've tried this</p>
<pre><code>from .my_pass import LOCAL
from .base import *
if LOCAL == 'local':
from .local import *
elif not LOCAL == 'production':
from .production import *
</code></pre>
<p>and it wont work. If I do this ... | 0 | 2016-05-27T05:36:35Z | 37,475,798 | <p>You are using <code>elif not LOCAL == 'production'</code> there, which i guess is wrong, because you have to import from production if <code>LOCAL == 'production'</code>, right? Then change the <code>elif not LOCAL == 'production'</code> to <code>elif LOCAL == 'production'</code></p>
| 2 | 2016-05-27T05:54:22Z | [
"python",
"django",
"development-environment"
] |
Django Rest Framework How to update SerializerMethodField | 37,475,829 | <p>I have a serializer like this:</p>
<pre><code>class PersonSerializer(serializers.ModelSerializer):
gender = serializers.SerializerMethodField()
bio = BioSerializer()
class Meta:
model = Person
fields = UserSerializer.Meta.fields + ('gender', 'bio',)
def get_gender(self, obj):
... | 1 | 2016-05-27T05:57:02Z | 37,477,424 | <p>So if I understand you correctly, you want to send {'gender': 'Male'} in your PATCH request.</p>
<p>Therefor, you have to tell your serializer how to convert your representation i.e. 'Male' into the internal value.</p>
<p>As you can <a href="https://github.com/tomchristie/django-rest-framework/blob/master/rest_fra... | 3 | 2016-05-27T07:31:11Z | [
"python",
"django",
"django-rest-framework",
"django-serializer"
] |
python create dictionary from list of strings and list of integers | 37,475,846 | <p>I have two lists: one contain the name of pages like <code>['Barrel - Part 1', 'Petit Trees (sketch)', 'Island (sketch)']</code> and the other list contain the corresponding page number like <code>[1, 2, 3]</code></p>
<p>I want to create a dictionary from two lists such that the splitted words from list one as a ke... | -1 | 2016-05-27T05:58:20Z | 37,475,906 | <p>You might be surprised that the results are out of order, but that's because dicts in python don't have an order. If you want them ordered you'll need to use something other than a vanilla dict.</p>
<pre><code>titles = ['Barrel - Part 1', 'Petit Trees (sketch)', 'Island (sketch)']
pages = [1, 2, 3]
finalDict = {... | 0 | 2016-05-27T06:02:30Z | [
"python",
"list",
"dictionary"
] |
python create dictionary from list of strings and list of integers | 37,475,846 | <p>I have two lists: one contain the name of pages like <code>['Barrel - Part 1', 'Petit Trees (sketch)', 'Island (sketch)']</code> and the other list contain the corresponding page number like <code>[1, 2, 3]</code></p>
<p>I want to create a dictionary from two lists such that the splitted words from list one as a ke... | -1 | 2016-05-27T05:58:20Z | 37,476,065 | <p>You can use <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow"><code>zip()</code></a> to loop through the two lists simultaneously. If you don't need the dict to be in order, it's much easier to use <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="n... | 6 | 2016-05-27T06:13:29Z | [
"python",
"list",
"dictionary"
] |
python create dictionary from list of strings and list of integers | 37,475,846 | <p>I have two lists: one contain the name of pages like <code>['Barrel - Part 1', 'Petit Trees (sketch)', 'Island (sketch)']</code> and the other list contain the corresponding page number like <code>[1, 2, 3]</code></p>
<p>I want to create a dictionary from two lists such that the splitted words from list one as a ke... | -1 | 2016-05-27T05:58:20Z | 37,476,440 | <p>List comprehension approach. </p>
<p>Basically double iteration in list comprehension is used here (look more pythonic to me). Another way of iterating would be using <code>itertools.chain</code>. </p>
<pre><code>from collections import defaultdict
d = defaultdict(list)
page_names = ['Barrel - Part 1', 'Petit Tre... | -1 | 2016-05-27T06:36:57Z | [
"python",
"list",
"dictionary"
] |
Resize the height of the header in QTableWidget in PyQt | 37,475,963 | <p>I am trying to include a <code>QTableWidget</code> in my app with four columns and I need the columns in the header to <code>stretch</code> according to the window size. Currently, the columns occupy only a certain width and doesn't stretch to the window.</p>
<p>Here is a minimum verifiable example of my problem:</... | -2 | 2016-05-27T06:06:19Z | 37,603,152 | <p>If you are re-implementing a <code>QTableWidget</code> this is the instruction you need to give to achieve the stretch effect:</p>
<pre><code>self.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)
</code></pre>
<p>You call the <code>QHeaderView</code> from the <code>QTableWidget</code> and giv... | -1 | 2016-06-02T22:27:55Z | [
"python",
"pyqt",
"pyqt5"
] |
ValueError: No JSON object could be decoded using Python | 37,475,969 | <p>I have a valid json that I'm unable to read using Python and getting the error,</p>
<pre><code>ValueError: No JSON object could be decoded using Python
</code></pre>
<p>The code is as following, </p>
<pre><code>import json, requests
page = "http://www.zillow.com/search/GetResults.htm?spt=homes&status=110001... | 0 | 2016-05-27T06:06:39Z | 37,477,333 | <p>If you are using requests as a lib, you can do the following:</p>
<pre><code>import requests as req
page = "http://www.zillow.com/search/GetResults.htm?spt=homes&status=110001&lt=001000&ht=111111&pr=,&mp=,&bd=2%2C&ba=0%2C&sf=,&lot=,&yr=,&pho=0&pets=0&parking=0&am... | 0 | 2016-05-27T07:26:05Z | [
"python",
"json"
] |
How to store indeces of a row if the row element exist in another list? | 37,476,225 | <p>I am reading a row in file in which each word is a long code but I need only 9 or 10 first letters( it could be of 9 or 10 letters) to compare with another list of codes.
Moreover I have to store indices of row each time the code exist in the two list.</p>
<pre><code>list_to_compare=open(file,'rb').readlines()
with... | 0 | 2016-05-27T06:23:50Z | 37,476,415 | <p>Your use of <code>and</code> is wrong. <code>and</code> is an boolean operator.
Since <code>F.append</code> returns <code>None</code> the second append is never executed.
With more readable variable names, I get this:</p>
<pre><code>with open('file', 'rb') as lines:
indices = []
codes = []
for line in l... | 1 | 2016-05-27T06:35:20Z | [
"python",
"indexing",
"compare"
] |
Function returning none- Trying to find highest number in a set without using x | 37,476,392 | <p>Hey so I am just starting out on python. I am trying to find the largest number among 4 numbers using a function with return. For whatever reason the function keeps returning only value d and only if it the highest int. Other set of numbers I put in yeild none. I solved it originally using max, but I cant use max fo... | 2 | 2016-05-27T06:33:57Z | 37,476,672 | <p>You may not have encountered <a href="https://wiki.python.org/moin/ForLoop" rel="nofollow">for-loops</a> yet, but you will. My suggestion is to try and use one here:</p>
<pre><code>def compare_numbers(a, b, c, d):
# To start out, we'll assume the
# first number is the largest, but
# we'll be double chec... | 2 | 2016-05-27T06:51:30Z | [
"python",
"function",
"return"
] |
Function returning none- Trying to find highest number in a set without using x | 37,476,392 | <p>Hey so I am just starting out on python. I am trying to find the largest number among 4 numbers using a function with return. For whatever reason the function keeps returning only value d and only if it the highest int. Other set of numbers I put in yeild none. I solved it originally using max, but I cant use max fo... | 2 | 2016-05-27T06:33:57Z | 37,477,355 | <p>You can try finding the max with this method:</p>
<pre><code> num1=int(input("Enter 1st number: "))
num2=int(input("Enter 2nd number: "))
num3=int(input("Enter 3rd number: "))
num4=int(input("Enter 4th number: "))
numlist = [num1, num2, num3, num4]
def compare_numbers(numlist):
... | -1 | 2016-05-27T07:27:08Z | [
"python",
"function",
"return"
] |
Passing around parsed arguments makes no fun | 37,476,417 | <p>I use <a href="https://docs.python.org/2/howto/argparse.html" rel="nofollow">arparse</a> in Python to parse arguments from the command line:</p>
<pre><code>def main():
parser = argparse.ArgumentParser(usage=usage)
parser.add_argument('-v', '--verbose', dest='verbose', action='store_true')
parser.add_arg... | 1 | 2016-05-27T06:35:32Z | 37,476,625 | <p>Converting my comment to answer. I'd suggest not condition in your <code>third_level(..)</code> at all. There are mechanisms to let the logging module take care of that -- and those mechanisms can be controlled from outside of those 3 functions.</p>
<p>Something like:</p>
<pre><code>def first_level(args):
seco... | 2 | 2016-05-27T06:48:24Z | [
"python",
"design-patterns",
"argparse"
] |
Passing around parsed arguments makes no fun | 37,476,417 | <p>I use <a href="https://docs.python.org/2/howto/argparse.html" rel="nofollow">arparse</a> in Python to parse arguments from the command line:</p>
<pre><code>def main():
parser = argparse.ArgumentParser(usage=usage)
parser.add_argument('-v', '--verbose', dest='verbose', action='store_true')
parser.add_arg... | 1 | 2016-05-27T06:35:32Z | 37,488,342 | <p>A common module structure is something like:</p>
<pre><code> imports ...
<constants>
options = {verbose=0, etc}
# alt options = argparse.Namespace(logging=False,....)
def levelone(args, **kwargs):
....
def leveltwo(...):
def levelthree(...):
<use constant>
<use options>
de... | 2 | 2016-05-27T16:28:11Z | [
"python",
"design-patterns",
"argparse"
] |
Kivy window goes blank after being resized | 37,476,505 | <p>I'm still relatively new to Python and Kivy (much more so for Kivy). I'm running Python 3.5 and Kivy 1.9.1 on OS X. I installed Kivy using pip install, and I was never really able to get Kivy to work using the download and putting in my Applications folder like the instructions were asking. Everything seems to work ... | 0 | 2016-05-27T06:41:04Z | 37,493,470 | <p>The problem was caused because Kivy was using Pygame. I had to brew install the SDL2 dependencies and reinstall Kivy. This fixed the problem.</p>
| 1 | 2016-05-27T23:04:14Z | [
"python",
"kivy"
] |
I would like to use selenium to select a frame using python | 37,476,509 | <p>I can successfully login to web pages but I need to click/select the frame. here is my code so far:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("URL")
Login = driver.find_element_by_name('login')
Login.send_keys("USER NAME")
... | 0 | 2016-05-27T06:41:09Z | 37,476,740 | <p>Try performing click() operation via jQuery or JavaScript using execute_script method of selenium. Below is the sample code that will perform the click operation. </p>
<pre><code>driver.execute_script('elem = document.getElementById("Test_topic"); a = elem.getElementsByTagName("a")[0]; a.click()')
</code></pre>
<b... | 0 | 2016-05-27T06:55:22Z | [
"python",
"selenium"
] |
I would like to use selenium to select a frame using python | 37,476,509 | <p>I can successfully login to web pages but I need to click/select the frame. here is my code so far:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("URL")
Login = driver.find_element_by_name('login')
Login.send_keys("USER NAME")
... | 0 | 2016-05-27T06:41:09Z | 37,483,274 | <p>The link text is not "Test" but "Test Spec". Try this:</p>
<pre><code>driver.find_element_by_link_text('Test Spec')
</code></pre>
<p>Also, since there is one, it would be better if you find the element by it's id:</p>
<pre><code>driver.find_element_by_link_id('Test_topic').find_element_by_tag_name('a').click()
<... | 0 | 2016-05-27T12:12:07Z | [
"python",
"selenium"
] |
How to print with different colours with Python using termcolor inside an array? | 37,476,511 | <p>I am fairly new to python, and wrote my second game, as I feel this is the best way to learn a new language. My code is as follows:</p>
<p><strong>The Code:</strong></p>
<pre><code>#!/usr/bin/env python
from random import randint
from termcolor import colored
import os
import sys
import time
clear = lambda : os.s... | 2 | 2016-05-27T06:41:13Z | 37,476,843 | <p>You are going to want to update the print_board method.</p>
<pre><code>def print_board(board):
for row in board:
print colored(" ".join(row),"cyan")
</code></pre>
<p>Without writing the exact code you'll need to write, you'll need to change this to:</p>
<pre><code>def print_board(board):
for row i... | 1 | 2016-05-27T07:01:10Z | [
"python",
"colors",
"terminal"
] |
How to print with different colours with Python using termcolor inside an array? | 37,476,511 | <p>I am fairly new to python, and wrote my second game, as I feel this is the best way to learn a new language. My code is as follows:</p>
<p><strong>The Code:</strong></p>
<pre><code>#!/usr/bin/env python
from random import randint
from termcolor import colored
import os
import sys
import time
clear = lambda : os.s... | 2 | 2016-05-27T06:41:13Z | 37,476,926 | <p>The problem code is:</p>
<pre><code>print colored(" ".join(row),"cyan")
</code></pre>
<p>You need:</p>
<pre><code>print ' '.join(colored(element, 'cyan') if element != 'X'
else colored(element, 'red')
for element in row)
</code></pre>
<p><strong>edit</strong></p>
<p>More generally,... | 2 | 2016-05-27T07:06:08Z | [
"python",
"colors",
"terminal"
] |
Dynamically do a join on pandas dataframes | 37,476,525 | <p>I want to filter on a column and then dynamically join resulting dataframes. My naive approach is; given a dataframe, write a function that filters based on values in a column to get smaller then join. But I don't know how to join dynamically. Any better way of doing this?</p>
<pre><code>data = {'name': ['Jason', '... | 1 | 2016-05-27T06:42:09Z | 37,477,642 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.factorize.html" rel="nofollow"><code>factorize</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a>, <code>df</code> is sorted by col... | 1 | 2016-05-27T07:41:51Z | [
"python",
"pandas"
] |
Dynamically do a join on pandas dataframes | 37,476,525 | <p>I want to filter on a column and then dynamically join resulting dataframes. My naive approach is; given a dataframe, write a function that filters based on values in a column to get smaller then join. But I don't know how to join dynamically. Any better way of doing this?</p>
<pre><code>data = {'name': ['Jason', '... | 1 | 2016-05-27T06:42:09Z | 37,477,751 | <p>If you absolutely need the output in this repeated saleX, nameX format, @jezrael nailed it I think.</p>
<p>But you might want to do a simpler<code>pivot</code> instead, it'll be a lot less awkward to work with.</p>
<pre><code>In [1]: pivot = df.pivot(index='name',columns='year', values='sale')
print(pivot)... | 0 | 2016-05-27T07:46:57Z | [
"python",
"pandas"
] |
Subprocess returns exit status 1 | 37,476,924 | <p>When I run a command through subprocess I get exit status 1 without my print or the error raised.</p>
<p>here is my code: </p>
<pre><code> def generate_model(self):
if not ((self.username == None) or (self.password == None) or (self.database == None)):
cmd = "python -m pwiz -e %s -H %s -u %s... | 1 | 2016-05-27T07:05:44Z | 37,480,678 | <p><code>subprocess.check_call()</code> does not run the shell by default and therefore the redirection operator <code>></code> won't work. To redirect stdout, pass <code>stdout</code> parameter instead:</p>
<pre><code>with open(filename, 'wb', 0) as file:
check_call([sys.executable, '-m', 'pwiz', '-e', ...], s... | 2 | 2016-05-27T10:08:08Z | [
"python",
"subprocess",
"peewee"
] |
Why is pymongo not returning index information of the collection? | 37,476,954 | <p>If I run the getIndexes method in the shell :</p>
<pre><code>xyz:PRIMARY> db.my_collection.count()
26672
xyz:PRIMARY> db.my_collection.getIndexes()
// Prints indexes and their info
</code></pre>
<p>However, <code>index_information</code> method in pymongo is returning a blank
dict for all collections in pyth... | 0 | 2016-05-27T07:07:50Z | 37,477,175 | <p>According to <a href="https://docs.mongodb.com/ecosystem/drivers/driver-compatibility-reference/#python-driver-compatibility" rel="nofollow">Python Driver Compatibility</a> section in MongoDB documentation, PyMongo 2.5 does not fully support MongoDB 3.0:</p>
<p><a href="http://i.stack.imgur.com/L8i0E.png" rel="nofo... | 2 | 2016-05-27T07:18:26Z | [
"python",
"mongodb",
"pymongo"
] |
Interval tree usage to find out overlapping regions | 37,476,999 | <p>I am trying to use interval tree to solve this <a href="https://www.hackerrank.com/challenges/x-and-his-shots" rel="nofollow">problem</a>. Below is my try but understandably it is not working i.e. it is not returning all the intervals.</p>
<p>A cricket match is going to be held. The field is represented by a 1D pla... | 1 | 2016-05-27T07:10:09Z | 37,490,323 | <p>The key to solving the problem is to realize that there's no need to compare single fielding range to a single shot range since only the total number intersecting ranges needs to be known. In order to achieve this in O(n log n) time following algorithm can be used.</p>
<p>Take the shot ranges and create two ordered... | 1 | 2016-05-27T18:40:04Z | [
"python",
"algorithm",
"tree"
] |
Interval tree usage to find out overlapping regions | 37,476,999 | <p>I am trying to use interval tree to solve this <a href="https://www.hackerrank.com/challenges/x-and-his-shots" rel="nofollow">problem</a>. Below is my try but understandably it is not working i.e. it is not returning all the intervals.</p>
<p>A cricket match is going to be held. The field is represented by a 1D pla... | 1 | 2016-05-27T07:10:09Z | 37,513,548 | <p>I did some homework and tried to solve it with interval tree.But as you have realized,traditional interval tree may not be suitable for this problem.This is because there is only one match returned when searching an interval tree,but we need to find all matches.More exactly,we just need to count all matches,it's not... | 0 | 2016-05-29T18:38:59Z | [
"python",
"algorithm",
"tree"
] |
How can I improve the reducebykey part of my spark app? | 37,477,167 | <p>I have 64 spark cores. I have over 80 Million rows of data which amount to 4.2 GB in my cassandra cluster. I now need 82 seconds to process this data. I want this reduced to 8 seconds. Any thoughts on this? Is this even possible? Thanks.</p>
<p>This is the part of my spark app I want to improve:</p>
<pre><code>axe... | -2 | 2016-05-27T07:17:58Z | 37,507,116 | <p><strong>Issues</strong>:</p>
<p>(<em>Why this code cannot work correctly assuming unmodified Spark distribution</em>)</p>
<p>Step-by-step:</p>
<ol>
<li><p>These two lines should create a Spark <code>DataFrame</code>. So far so good:</p>
<pre><code>sqlContext.read.format("org.apache.spark.sql.cassandra")
.optio... | 2 | 2016-05-29T06:57:42Z | [
"python",
"apache-spark",
"cassandra",
"datastax",
"datastax-enterprise"
] |
How to fit an int list to a desired function | 37,477,224 | <p>I have an int list <code>x</code>, like <code>[43, 43, 46, ....., 487, 496, 502]</code>(just for example)<br>
<code>x</code> is a list of word count, I want change a list of word count to a list penalty score when training a text classification model.</p>
<p>I'd like use a <strong>curve</strong> function(maybe like... | -2 | 2016-05-27T07:20:34Z | 37,478,129 | <p>How about this way?</p>
<p>EDIT: added weights. If you don't need to put your end points exactly on the curve you could use weights:</p>
<pre><code>import scipy.optimize as opti
import numpy as np
xdata = np.array([43, 56, 234, 502], float)
ydata = np.linspace(0.8, 0.08, len(xdata))
weights = np.ones_like(xdata, ... | 1 | 2016-05-27T08:06:18Z | [
"python",
"numpy",
"pandas",
"scipy",
"curve-fitting"
] |
Writing multiple JSON objects into one .json file | 37,477,230 | <p>I'm writing a python script to run through a csv file and convert it into one .json file. That would mean the .json file would have multiple json objects inside it. I've got most of the script working but the part I am confused with (and I've looked online for a while now) is how multiple JSON objects should be stor... | 0 | 2016-05-27T07:20:44Z | 37,478,714 | <p>Looks pritty close to the solution. May you should use a list:</p>
<pre><code>{
"data":[
{
"_index": "jobs",
"_id": 119556,
"_type": "2014_jobs"
},
{
"_index": "jobs",
"_id": 119700,
"_type": "2014_jobs"
},
{
"_index": "jobs",
... | 0 | 2016-05-27T08:36:20Z | [
"python",
"json"
] |
Python for .NET compilation for .NET3.5 and Python3.x | 37,477,439 | <p>Recently I've been working on a project which needs to use a <code>.NET 3.5</code> Dll library, and the team is using Python3.x environment. </p>
<p>So I went to the <a href="https://github.com/pythonnet/pythonnet/releases" rel="nofollow">Python for .NET's github repo</a> and downloaded the source code and tried co... | 0 | 2016-05-27T07:31:59Z | 37,493,025 | <p>Latest pythonnet is using <code>HashSet</code> from CLR 4.0 and also <code>dynamic</code> from DLR which cannot be easily backported to older .NET versions.</p>
<p>What you can do is redirect your other DLLs from .NET 3.5 to CLR 4.0 using app.config:</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<... | 1 | 2016-05-27T22:16:17Z | [
"python",
".net",
"python-3.x",
".net-3.5",
"python.net"
] |
AWS Lambda python Resetting dropped connection | 37,477,464 | <p>I've an AWS Python Lambda which manages resources tags(many calls on the AWS API with boto3) for my infrastructure. The function, executed on my laptop works well and also under Lambda. But when I execute it under Lambda, all my logs(debug or error level) are not send to cloudwatch logs. Instead of I've multiple log... | 1 | 2016-05-27T07:33:12Z | 37,521,398 | <p>AWS clodwatch logs will not "overwrite" your own logs. Please <strong>do not sleep in the lambda function</strong> since you will be paying for this as well. Also if the request rate is too high, you will get <code>RequestLimitExceeded</code> errors.</p>
<p>There are some ways to avoid this:</p>
<ol>
<li>Check and... | 0 | 2016-05-30T08:49:28Z | [
"python",
"amazon-web-services",
"aws-lambda",
"boto3"
] |
AWS Lambda python Resetting dropped connection | 37,477,464 | <p>I've an AWS Python Lambda which manages resources tags(many calls on the AWS API with boto3) for my infrastructure. The function, executed on my laptop works well and also under Lambda. But when I execute it under Lambda, all my logs(debug or error level) are not send to cloudwatch logs. Instead of I've multiple log... | 1 | 2016-05-27T07:33:12Z | 37,529,814 | <p>Ok, finally it works. Indeed I was too aggressive on the retry process but I need to do each operation ASAP(ex: attach an EBS when it is available). In boto3, there is a cleaner way to wait until a resource become ready, than to put time.sleep(xx) in your code. </p>
<p>The solution is to use a <a href="http://boto3... | 0 | 2016-05-30T16:02:30Z | [
"python",
"amazon-web-services",
"aws-lambda",
"boto3"
] |
Indexing and selecting only found columns in Pandas python | 37,477,509 | <p>I am facing a basic problem while using Pandas Python. For example my Dataframe " a " has following columns q,w,e,r. Now I want to take a subset of a.</p>
<pre><code>b=a[[w,e,r,z]]
</code></pre>
<p>but it will not create a subset, since z is not there in a, Please help how I can take care of this problem that desp... | 1 | 2016-05-27T07:35:28Z | 37,477,685 | <p>You can do manual filtering before indexing:</p>
<pre><code>filtered_col = [col for col in [w,e,r,z] if col in a.columns]
b = a[filtered_col]
</code></pre>
| 0 | 2016-05-27T07:43:51Z | [
"python",
"pandas",
"dataframe"
] |
Indexing and selecting only found columns in Pandas python | 37,477,509 | <p>I am facing a basic problem while using Pandas Python. For example my Dataframe " a " has following columns q,w,e,r. Now I want to take a subset of a.</p>
<pre><code>b=a[[w,e,r,z]]
</code></pre>
<p>but it will not create a subset, since z is not there in a, Please help how I can take care of this problem that desp... | 1 | 2016-05-27T07:35:28Z | 37,477,737 | <p>IIUC you could do it with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow"><code>isin</code></a> approach for <code>a</code> columns:</p>
<pre><code>mask = a.columns[a.columns.isin([w, e, r, z])]
b = a[mask]
</code></pre>
<p><strong>Example:</strong></p>
<pre>... | 0 | 2016-05-27T07:46:16Z | [
"python",
"pandas",
"dataframe"
] |
Indexing and selecting only found columns in Pandas python | 37,477,509 | <p>I am facing a basic problem while using Pandas Python. For example my Dataframe " a " has following columns q,w,e,r. Now I want to take a subset of a.</p>
<pre><code>b=a[[w,e,r,z]]
</code></pre>
<p>but it will not create a subset, since z is not there in a, Please help how I can take care of this problem that desp... | 1 | 2016-05-27T07:35:28Z | 37,477,905 | <p>It appears that using <code>isin</code> method isn't the most efficient way to do it:</p>
<pre><code>% timeit a[a.columns[a.columns.isin(['w', 'e', 'r', 'z'])]]
out : 1000 loops, best of 3: 528 µs per loop
</code></pre>
<p>When you just use a filter:</p>
<pre><code>%timeit a[[col for col in ['w','e','r','z'] if ... | 1 | 2016-05-27T07:55:42Z | [
"python",
"pandas",
"dataframe"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.