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 |
|---|---|---|---|---|---|---|---|---|---|
Dstream output to Rabbitmq | 40,112,170 | <p>I am using spark 2.0 (python). I am trying to send the output stream to Rabbitmq. Following is my implemetation, </p>
<pre><code>def sendPartition(iter):
connection = pika.BlockingConnection(pika.URLParameters('amqp://user:pass@ip:5672/'))
channel = connection.channel()
for record in iter:
chann... | 1 | 2016-10-18T15:23:58Z | 40,114,972 | <p>What you have right now is probably close to the optimum in a general case. Python workers don't share state so you cannot reuse connections between partitions in the same batch.</p>
<p>It should be possible to reuse connections for each worker between batches by creating a singleton wrapping a connection pool (the... | 0 | 2016-10-18T17:56:17Z | [
"python",
"apache-spark",
"rabbitmq",
"spark-streaming"
] |
EOF Error with ftplib only when connecting to GoDaddy hosted server | 40,112,202 | <p>I'm having problems with FTP_TLS (ftplib) in Python 2.7.3.</p>
<p>Summary of findings (all connection attempts performed over the internet):</p>
<ul>
<li>FileZilla to home web server - works</li>
<li>FileZilla to GoDaddy shared hosting server - works</li>
<li>Python to home web server - works</li>
<li>Python to Go... | 1 | 2016-10-18T15:25:48Z | 40,112,354 | <p>I think you need to set the FTP mode to passive, here's a <a href="http://www.perlmonks.org/?node_id=175281" rel="nofollow">similar error but in Perl</a></p>
<p>The difference is explained in <a href="http://stackoverflow.com/questions/1699145/what-is-the-difference-between-active-and-passive-ftp">what-is-the-diffe... | 0 | 2016-10-18T15:32:20Z | [
"python",
"python-2.7",
"ftplib"
] |
panda dataframe iterate and adding to set issue | 40,112,223 | <p>I have a dataframe that looks like this:</p>
<pre><code> name
0 [somename1, somename2, n...
1 [name1, someothername, ...
2 [name, name, s...
3 [somename1, name3, s...
4 [name2, name2, s...
5 [somename2, name2, s...
6 [somename1, somename, s...
</code></pre>
<p>I am trying to iterate th... | 0 | 2016-10-18T15:26:51Z | 40,115,924 | <p>A <code>set</code> in python is an </p>
<blockquote>
<p>unordered collection of <strong>unique</strong> elements.</p>
</blockquote>
<p>It does not allow duplicates.</p>
<p>You should define <code>event</code> as a <code>list</code> instead.</p>
<pre><code>events = []
for index, row in datarame.iterrows():
... | 1 | 2016-10-18T18:53:03Z | [
"python",
"dataframe",
"set",
"iteration"
] |
creating package with setuptools not installing properly | 40,112,269 | <p>I'm using setuptools to try and create a module for python.</p>
<p>I have tried installing locally and from git with pip (version 3.5). pip says that the package is installed and it is listed in the installed packages with "pip list" and "pip freeze". When I try to import the module in my script I get an import err... | 0 | 2016-10-18T15:28:46Z | 40,112,574 | <p>Seems to work for me:</p>
<pre><code>pip3 install git+git://github.com/BebeSparkelSparkel/jackedCodeTimerPY.git@master
Cloning git://github.com/BebeSparkelSparkel/jackedCodeTimerPY.git (to master) to /tmp/pip-lq07iup9-build
Collecting tabulate==0.7.5 (from jackedCodeTimerPY==0.0.0)
Downloading tabulate-0.7.5.tar... | 0 | 2016-10-18T15:41:33Z | [
"python",
"setuptools",
"setup.py"
] |
Accelerate or decelerate a movie clip | 40,112,284 | <p>I am trying to accelerate and/or decelerate a movie clip with the help of Python's moviepy module, but I can't seem to work it out properly. The script runs quite smoothly, and without any errors, but I do not see any effects. Might be my script is wrong and I can't detect the problem. Looking for help/tips from you... | 0 | 2016-10-18T15:29:22Z | 40,136,932 | <p>I think the best way of accelerating and decelerating clip objects is using <strong>easing functions</strong>.</p>
<p>Some reference sites:</p>
<ul>
<li><a href="http://easings.net" rel="nofollow">http://easings.net</a></li>
<li><a href="http://www.gizma.com/easing/" rel="nofollow">http://www.gizma.com/easing/</a>... | 1 | 2016-10-19T16:29:18Z | [
"python",
"numpy",
"moviepy"
] |
How can I make automatize fetchall() calling in pyodbc without exception handling? | 40,112,321 | <p>I want to do automatic results fetching after every <strong>pyodbc</strong> query. In usual situation <code>cursor.fetchall()</code> calling raises a <code>ProgrammingError</code> exception if no SQL has been executed or if it did not return a result set (e.g. was not a SELECT statement). I want to do something like... | 1 | 2016-10-18T15:31:11Z | 40,119,325 | <p>Here's an example that might work for you, with a list of samples queries to run:</p>
<pre><code>sql_to_run = [
"SELECT 10000",
"SELECT 2 + 2",
"",
"SELECT 'HELLO WORLD'",
]
for sql in sql_to_run:
rows = cursor.execute(sql)
if cursor.rowcount:
for row in rows:
print(row... | 1 | 2016-10-18T22:47:40Z | [
"python",
"pyodbc"
] |
Python Create List of Words Per Sentence and Calculate Mean and Place in CSV File | 40,112,365 | <p>I'm looking to count the number of words per sentence, calculate the mean words per sentence, and put that info into a CSV file. Here's what I have so far. I probably just need to know how to count the number of words before a period. I might be able to figure it out from there.</p>
<pre><code>#Read the data in the... | 0 | 2016-10-18T15:32:28Z | 40,112,538 | <p>You might be interested in the split() function for strings. It seems like you're editing your text to make sure all sentences end in a period and every period ends a sentence.</p>
<p>Thus,</p>
<pre><code>pnp.split('.')
</code></pre>
<p>is going to give you a list of all sentences. Once you have that list, for ... | 0 | 2016-10-18T15:39:38Z | [
"python",
"csv"
] |
Python Create List of Words Per Sentence and Calculate Mean and Place in CSV File | 40,112,365 | <p>I'm looking to count the number of words per sentence, calculate the mean words per sentence, and put that info into a CSV file. Here's what I have so far. I probably just need to know how to count the number of words before a period. I might be able to figure it out from there.</p>
<pre><code>#Read the data in the... | 0 | 2016-10-18T15:32:28Z | 40,112,548 | <p>To split a string into a list of strings on some character:</p>
<pre><code>pnp = pnp.split('.')
</code></pre>
<p>Then we can split each of those sentences into a list of strings (words)</p>
<pre><code>pnp = [sentence.split() for sentence in pnp]
</code></pre>
<p>Then we get the number of words in each sentence</... | 2 | 2016-10-18T15:40:00Z | [
"python",
"csv"
] |
Python Create List of Words Per Sentence and Calculate Mean and Place in CSV File | 40,112,365 | <p>I'm looking to count the number of words per sentence, calculate the mean words per sentence, and put that info into a CSV file. Here's what I have so far. I probably just need to know how to count the number of words before a period. I might be able to figure it out from there.</p>
<pre><code>#Read the data in the... | 0 | 2016-10-18T15:32:28Z | 40,112,960 | <p>You can try the code below.</p>
<pre><code>numbers_per_sentence = [len(element) for element in (element.split() for element in pnp.split("."))]
mean = sum(numbers_per_sentence)/len(numbers_per_sentence)
</code></pre>
<p>However, for real natural language processing I would probably recommend a more robust solutio... | 0 | 2016-10-18T16:01:18Z | [
"python",
"csv"
] |
How to classify new documents with tf-idf? | 40,112,373 | <p>If I use the <code>TfidfVectorizer</code> from <code>sklearn</code> to generate feature vectors as:</p>
<p><code>features = TfidfVectorizer(min_df=0.2, ngram_range=(1,3)).fit_transform(myDocuments)</code></p>
<p>How would I then generate feature vectors to classify a new document? Since you cant calculate the tf-i... | 0 | 2016-10-18T15:32:44Z | 40,122,073 | <p>You need to save the instance of the TfidfVectorizer, it will remember the term frequencies and vocabulary that was used to fit it. It may make things clearer sense if rather than using <code>fit_transform</code>, you use <code>fit</code> and <code>transform</code> separately:</p>
<pre><code>vec = TfidfVectorizer(m... | 0 | 2016-10-19T04:21:12Z | [
"python",
"scikit-learn",
"text-mining",
"tf-idf",
"text-analysis"
] |
How do I access request metadata for a java grpc service I am defining? | 40,112,374 | <p>For some background, I am attempting to use <a href="http://www.grpc.io/docs/guides/auth.html#authenticate-with-google-4" rel="nofollow">grpc auth</a> in order to provide security for some services I am defining.</p>
<p>Let's see if I can ask this is a way that makes sense. For my python code, it was pretty easy to... | 0 | 2016-10-18T15:32:58Z | 40,113,309 | <p>Use a <code>ServerInterceptor</code> and then propagate the identity via <code>Context</code>. This allows you to have a central policy for authentication.</p>
<p>The interceptor can retrieve the identity from <code>Metadata headers</code>. It <em>should then validate</em> the identity. The validated identity can t... | 2 | 2016-10-18T16:17:35Z | [
"java",
"python",
"request",
"metadata",
"grpc"
] |
Django KeyError kwargs.pop('pk') | 40,112,448 | <p>I'm using CBV in Django 1.9 and in CreateView when I try to pass an additional parameter ('pk') to my form using self.kwargs.pop('pk') i got "Key Error" but if I get the parameter by index it works, here is my code:</p>
<pre><code>def get_form(self, form_class=None, **kwargs):
self.project_version_pk = self.kwa... | -1 | 2016-10-18T15:35:52Z | 40,112,767 | <p>Firstly, you shouldn't be overriding <code>get</code>. In a CreateView, Django already calls <code>get_form</code> for you - inside <code>get_context_data</code>. This is the cause of the issue you are having; you call <code>get_form</code> and pop the pk so that it is no longer in kwargs; but Django calls it again ... | 1 | 2016-10-18T15:51:04Z | [
"python",
"django",
"django-class-based-views",
"class-based-views"
] |
AttributeError: 'numpy.ndarray' object has no attribute 'median' | 40,112,487 | <p>I can perform a number of statistics on a numpy array but "median" returns an attribute error. When I do a "dir(np)" I do see the median method listed.</p>
<pre><code>(newpy2) 7831c1c083a2:src scaldara$ python
Python 2.7.12 |Continuum Analytics, Inc.| (default, Jul 2 2016, 17:43:17)
[GCC 4.2.1 (Based on Apple ... | 2 | 2016-10-18T15:37:21Z | 40,112,611 | <p>Although <code>numpy.ndarray</code> has a <code>mean</code>, <code>max</code>, <code>std</code> etc. method, it does not have a <code>median</code> method. For a list of all methods available for an <code>ndarray</code>, see the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html" rel="n... | 3 | 2016-10-18T15:43:24Z | [
"python",
"numpy"
] |
TypeError: 'float' object is not callable (finding averages of a list of numbers) | 40,112,537 | <pre><code>sales = [49.99, 20, 155.20, 71.65, 91.07]
length = len(sales)
max_value = max(sales)
min_value = min(sales)
sum_of_values = sum(sales)
print(length, max_value, min_value, sum_value)
average = float(sum_of_values/length)
answer = round(average,2)
print(answer)
</code></pre>
<p>I'm trying to get a sum of... | -1 | 2016-10-18T15:39:34Z | 40,112,692 | <p>Your code is working fine on my machine.</p>
<p>But as a suggestion:
In Python 3.4 the statistics module was introduced, which enables you to do</p>
<pre><code>>>> from statistics import mean
>>> mean([1, 2, 3, 4, 4])
2.8
>>> mean([49.99, 20, 155.20, 71.65, 91.07])
77.582
</code></pre>
... | 0 | 2016-10-18T15:47:25Z | [
"python"
] |
Using nested dictionaries to store user defined graph | 40,112,545 | <p>I am trying to get the user to enter a graph manually as opposed to using it 'pre-existing' in the code, for use in my Dijkstra's Algorithm. </p>
<p>I have done this but would like some feedback on its implementation and user friendliness. In addition is there a more efficient way of entering a graph into a nested ... | 1 | 2016-10-18T15:39:51Z | 40,112,814 | <p>You really only want users to enter every edge once, then you can just store it twice.</p>
<pre><code>edges = {}
while True:
edge = input('Enter an edge as Node names separated by a space followed by a number ("exit" to exit): ')
if edge == 'exit':
break
node1, node2, weight = edge.split()
w... | 0 | 2016-10-18T15:53:15Z | [
"python",
"dictionary"
] |
Using nested dictionaries to store user defined graph | 40,112,545 | <p>I am trying to get the user to enter a graph manually as opposed to using it 'pre-existing' in the code, for use in my Dijkstra's Algorithm. </p>
<p>I have done this but would like some feedback on its implementation and user friendliness. In addition is there a more efficient way of entering a graph into a nested ... | 1 | 2016-10-18T15:39:51Z | 40,112,860 | <p><a href="https://www.khanacademy.org/computing/computer-science/algorithms/graph-representation/a/representing-graphs" rel="nofollow">Khanacademy</a> has a pretty good page on different ways to represent graphs.</p>
<p>For an undirected graph (a => b and b => a) I would personally look at using an edge list. It can... | 0 | 2016-10-18T15:55:27Z | [
"python",
"dictionary"
] |
Using nested dictionaries to store user defined graph | 40,112,545 | <p>I am trying to get the user to enter a graph manually as opposed to using it 'pre-existing' in the code, for use in my Dijkstra's Algorithm. </p>
<p>I have done this but would like some feedback on its implementation and user friendliness. In addition is there a more efficient way of entering a graph into a nested ... | 1 | 2016-10-18T15:39:51Z | 40,112,980 | <p>You could be more modular in your source, as in "add_node" should only add a node. I think entering all neighbors with costs immediately in one line would be more user friendly, so using the data structure you insist on:</p>
<pre><code>from itertools import tee #For pairwise iteration
from collection impor... | 0 | 2016-10-18T16:02:03Z | [
"python",
"dictionary"
] |
removing a number from a list | 40,112,774 | <p>I'm stuck on a part of a looping question. I have to remove from list1 all instances of "number". So lets say list1 is (1,2,3) and num is 2. The list I would have to return would be (1,3)</p>
<pre><code>def remove(list1,num)
list1=list1
num = num
</code></pre>
<p>This is what is given.
So far, I have thi... | -2 | 2016-10-18T15:51:36Z | 40,112,866 | <p>Use list comprehension:</p>
<pre><code>list1 = [1,2,3]
num = 2
new_list = [i for i in list1 if i != num]
print(new_list)
>> [1,3]
</code></pre>
| 1 | 2016-10-18T15:55:35Z | [
"python",
"loops",
"for-loop"
] |
removing a number from a list | 40,112,774 | <p>I'm stuck on a part of a looping question. I have to remove from list1 all instances of "number". So lets say list1 is (1,2,3) and num is 2. The list I would have to return would be (1,3)</p>
<pre><code>def remove(list1,num)
list1=list1
num = num
</code></pre>
<p>This is what is given.
So far, I have thi... | -2 | 2016-10-18T15:51:36Z | 40,112,892 | <pre><code>def remove(item,given_list):
new_list = []
for each in given_list:
if item != each:
new_list.append(each)
return new_list
print(remove(2,[1,2,3,1,2,1,2,2,4]))
#outputs [1, 3, 1, 1, 4]
</code></pre>
<p>While my answer as strong as others, I feel this is the fundamental way of... | 0 | 2016-10-18T15:56:46Z | [
"python",
"loops",
"for-loop"
] |
removing a number from a list | 40,112,774 | <p>I'm stuck on a part of a looping question. I have to remove from list1 all instances of "number". So lets say list1 is (1,2,3) and num is 2. The list I would have to return would be (1,3)</p>
<pre><code>def remove(list1,num)
list1=list1
num = num
</code></pre>
<p>This is what is given.
So far, I have thi... | -2 | 2016-10-18T15:51:36Z | 40,112,900 | <p>Taking into account:</p>
<pre><code>list=[1,2,3,2]
</code></pre>
<p>You can check if the element is in the list with:</p>
<pre><code>if num in list
</code></pre>
<p>And then remove with:</p>
<pre><code>list.remove(num)
</code></pre>
<p>And iterate through it</p>
<p>Example:</p>
<pre><code>>>> list=[... | 0 | 2016-10-18T15:57:16Z | [
"python",
"loops",
"for-loop"
] |
removing a number from a list | 40,112,774 | <p>I'm stuck on a part of a looping question. I have to remove from list1 all instances of "number". So lets say list1 is (1,2,3) and num is 2. The list I would have to return would be (1,3)</p>
<pre><code>def remove(list1,num)
list1=list1
num = num
</code></pre>
<p>This is what is given.
So far, I have thi... | -2 | 2016-10-18T15:51:36Z | 40,112,990 | <p>It sounds like this is a homework problem, especially since you can't use <code>.remove</code>.</p>
<p>Given that, your teacher probably wants you to take a manual approach that looks something like this:</p>
<ol>
<li>Create a new list</li>
<li>For each item in the previous list...
<ol>
<li>If it's not the value ... | 2 | 2016-10-18T16:02:31Z | [
"python",
"loops",
"for-loop"
] |
removing a number from a list | 40,112,774 | <p>I'm stuck on a part of a looping question. I have to remove from list1 all instances of "number". So lets say list1 is (1,2,3) and num is 2. The list I would have to return would be (1,3)</p>
<pre><code>def remove(list1,num)
list1=list1
num = num
</code></pre>
<p>This is what is given.
So far, I have thi... | -2 | 2016-10-18T15:51:36Z | 40,113,176 | <p>To go with pure loops and delete with list index:</p>
<pre><code>#!/usr/bin/env python
from __future__ import print_function
def remove(item, old_list):
while True:
try:
# find the index of the item
index = old_list.index(item)
# remove the item found
del... | 0 | 2016-10-18T16:11:02Z | [
"python",
"loops",
"for-loop"
] |
Different output after decode and encode data (base64) | 40,112,796 | <p>If i run:</p>
<pre><code>import base64
data = open('1.dat', 'rb').read()
decoded = base64.b64decode(data)
encoded = base64.b64encode(decoded)
data == encoded
</code></pre>
<p>I get "False" as result?
How to decode/encode to get the original result?</p>
| 0 | 2016-10-18T15:52:35Z | 40,112,912 | <p>You have to <code>b64encode()</code> the data before you <code>b64decode()</code> it:</p>
<pre><code>>>> import base64
>>> data = b"qwertzuiop"
>>> encoded = base64.b64encode(data)
>>> decoded = base64.b64decode(encoded)
>>> data == decoded
True
</code></pre>
<p>If your... | 0 | 2016-10-18T15:58:14Z | [
"python",
"base64"
] |
Different output after decode and encode data (base64) | 40,112,796 | <p>If i run:</p>
<pre><code>import base64
data = open('1.dat', 'rb').read()
decoded = base64.b64decode(data)
encoded = base64.b64encode(decoded)
data == encoded
</code></pre>
<p>I get "False" as result?
How to decode/encode to get the original result?</p>
| 0 | 2016-10-18T15:52:35Z | 40,112,940 | <p>Base64 is not base64 unfortunately. There may be differences in the implementations. Some implementation for example insert line breaks every 76 characters when encoding, some don't.</p>
| 1 | 2016-10-18T15:59:55Z | [
"python",
"base64"
] |
Different output after decode and encode data (base64) | 40,112,796 | <p>If i run:</p>
<pre><code>import base64
data = open('1.dat', 'rb').read()
decoded = base64.b64decode(data)
encoded = base64.b64encode(decoded)
data == encoded
</code></pre>
<p>I get "False" as result?
How to decode/encode to get the original result?</p>
| 0 | 2016-10-18T15:52:35Z | 40,113,080 | <p>There is some flexibility in the way base64 is encoded, for example the insertion of newlines. There may also be some alternate characters which the <a href="https://docs.python.org/2/library/base64.html" rel="nofollow"><code>base64</code> module</a> allows you to specify when encoding and decoding. It's up to you t... | 0 | 2016-10-18T16:06:28Z | [
"python",
"base64"
] |
How can I append a numpy array of N-Length to another array of N-dimensions? | 40,113,072 | <p><strong>Situation</strong></p>
<p>I assumed this would be easy - but turns out there are a few restrictions.
I have an empty array, that at this point, is empty and has unknown dimensions.</p>
<pre><code>mainArray = np.array([])
</code></pre>
<p>later on, I want to append arrays to my main array, which are of di... | 2 | 2016-10-18T16:06:08Z | 40,113,201 | <p>Your starting array is not empty (ok, it does have 0 elements), and not of unknown dimensions. It has a well defined shape and number of dimensions (1d).</p>
<pre><code>In [704]: a=np.array([])
In [705]: a.shape
Out[705]: (0,)
In [706]: a.ndim
Out[706]: 1
</code></pre>
<p>Some examples on concatenate that work wi... | 4 | 2016-10-18T16:12:22Z | [
"python",
"arrays",
"numpy"
] |
How can I append a numpy array of N-Length to another array of N-dimensions? | 40,113,072 | <p><strong>Situation</strong></p>
<p>I assumed this would be easy - but turns out there are a few restrictions.
I have an empty array, that at this point, is empty and has unknown dimensions.</p>
<pre><code>mainArray = np.array([])
</code></pre>
<p>later on, I want to append arrays to my main array, which are of di... | 2 | 2016-10-18T16:06:08Z | 40,117,273 | <p>One of the key concepts of numpy's ndarray is that it is rectangular: all elements at a given depth have the same length. This allows simple indexing with a tuple of positions in each dimension to be mapped onto a single flat array:</p>
<pre><code>array[x,y,z] #where array.shape = (a,b,c)
#is equivalent to:
array.f... | 1 | 2016-10-18T20:13:46Z | [
"python",
"arrays",
"numpy"
] |
Django rest framework pagination | 40,113,089 | <p>I am trying to add pagination into my project, couldn't find any clear documentation or tutorial.</p>
<p>I have a list of offices</p>
<p>models
Office.py</p>
<pre><code>class Office(Model):
name = CharField(_("name"), default=None, max_length=255, null=True)
email = EmailField(_("email"), default=None, ma... | 0 | 2016-10-18T16:06:58Z | 40,113,418 | <p><a href="http://www.django-rest-framework.org/api-guide/pagination/" rel="nofollow">http://www.django-rest-framework.org/api-guide/pagination/</a></p>
<pre><code>GET https://api.example.org/accounts/?limit=100&offset=400
</code></pre>
<p>Response:</p>
<pre><code>HTTP 200 OK
{
"count": 1023
"next": "ht... | 0 | 2016-10-18T16:24:13Z | [
"python",
"django",
"pagination",
"django-rest-framework"
] |
Django rest framework pagination | 40,113,089 | <p>I am trying to add pagination into my project, couldn't find any clear documentation or tutorial.</p>
<p>I have a list of offices</p>
<p>models
Office.py</p>
<pre><code>class Office(Model):
name = CharField(_("name"), default=None, max_length=255, null=True)
email = EmailField(_("email"), default=None, ma... | 0 | 2016-10-18T16:06:58Z | 40,114,426 | <p><a href="http://www.django-rest-framework.org/api-guide/pagination/" rel="nofollow">http://www.django-rest-framework.org/api-guide/pagination/</a></p>
<blockquote>
<p>Pagination is only performed automatically if you're using the generic
views or viewsets. If you're using a regular APIView, you'll need to
cal... | 0 | 2016-10-18T17:24:27Z | [
"python",
"django",
"pagination",
"django-rest-framework"
] |
Python - asking the user for a text and printing out specific number of times | 40,113,128 | <p>We've been doing python in school so the stuff that we've done so far is pretty basic but we got this homework and we're meant to ask the user to input a text and then a number and then print out the text the number of times the user requested.
I though it'd be something like this, </p>
<pre><code>text=input("Enter... | -3 | 2016-10-18T16:08:43Z | 40,113,376 | <pre><code>text=raw_input("Enter your text: ")
number=input("Enter the times you want the text to be printed: ")
for i in range(number):
print (text)
</code></pre>
<p>This code is written in python2.7.
raw_input() take strings wherein input() take integers.</p>
| -1 | 2016-10-18T16:21:19Z | [
"python",
"input",
"range"
] |
Do i have to use try: and except ValueError? | 40,113,217 | <p>I'm still new to python.
Do I have to use try: and except ValueError?
If not when would and should I use them?
Some parts work with and without it
E.g</p>
<pre><code>Def Main_Menu():
Main_menu_op = input("A.Start \nB.Options \nC.Exit")
Try:
if Main_menu_op == "A" or "a":
Start()
... | -2 | 2016-10-18T16:13:14Z | 40,113,355 | <p>You should only use <code>try</code> and <code>except ...Error</code> (<a href="https://docs.python.org/2.7/tutorial/errors.html" rel="nofollow">documentation</a>) when you know you can safely handle a specific known error.</p>
<p>So if you are expecting a certain error, like a <code>ValueError</code>, you can catc... | 0 | 2016-10-18T16:20:35Z | [
"python"
] |
Do i have to use try: and except ValueError? | 40,113,217 | <p>I'm still new to python.
Do I have to use try: and except ValueError?
If not when would and should I use them?
Some parts work with and without it
E.g</p>
<pre><code>Def Main_Menu():
Main_menu_op = input("A.Start \nB.Options \nC.Exit")
Try:
if Main_menu_op == "A" or "a":
Start()
... | -2 | 2016-10-18T16:13:14Z | 40,113,433 | <p><code>try</code> <code>except</code> blocks are to enclose code that might produce a runtime error. The optional argument of Error type (in this case you have input <code>ValueError</code>) will change the block so that it will only catch that type of exception. In your example it looks like you are trying to produc... | 1 | 2016-10-18T16:24:58Z | [
"python"
] |
Return last character of string in python | 40,113,223 | <p>I want to print the last character of string in python reading from the file. I am calling as <code>str[-1]</code> But not working. </p>
<p><strong>t.txt contains</strong></p>
<pre><code>Do not laugh please! 9
Are you kidding me? 4
</code></pre>
<p>My code is </p>
<pre><code>with open('t.txt', 'r') a... | 1 | 2016-10-18T16:13:40Z | 40,113,264 | <p>The last character of every line is a <em>newline character</em>. You can <a href="https://docs.python.org/2/library/string.html#string.strip" rel="nofollow">strip</a> it:</p>
<pre><code>print(line.strip()[-1])
# or print(line.rstrip()[-1])
</code></pre>
| 6 | 2016-10-18T16:15:15Z | [
"python"
] |
Return last character of string in python | 40,113,223 | <p>I want to print the last character of string in python reading from the file. I am calling as <code>str[-1]</code> But not working. </p>
<p><strong>t.txt contains</strong></p>
<pre><code>Do not laugh please! 9
Are you kidding me? 4
</code></pre>
<p>My code is </p>
<pre><code>with open('t.txt', 'r') a... | 1 | 2016-10-18T16:13:40Z | 40,113,366 | <p>Simple take the string and clear it's leading and trailing spaces. Then return the last character in your case. Otherwise simply return last character.</p>
<pre><code>line=line.strip()
return line[-1]
</code></pre>
| 0 | 2016-10-18T16:20:57Z | [
"python"
] |
How to check if file is currently existing using os.path | 40,113,224 | <p>I am currently having a problem while checking if a file name entered by user already exists. This is the code that i am currently running, however when i run the code properly and go to save the data with a name that already exists. It prints the correct error caption "This file already exists" and returns them bac... | 0 | 2016-10-18T16:13:40Z | 40,113,378 | <p>If you want a quick answer, I would use a <code>while</code> loop until the name is correct.</p>
<p>For example:</p>
<pre><code>while os.path.isfile(filename1):
print("This file already exists")
filename1=input("what would you like to call your file?")
</code></pre>
<p>Keep in mind though that you should ... | 1 | 2016-10-18T16:21:29Z | [
"python"
] |
Producing multi-level dictionary from word and part-of-speech | 40,113,276 | <p>Given some Penn Treebank tagged text in this format:</p>
<p>"David/NNP Short/NNP will/MD chair/VB the/DT meeting/NN ./. The/DT boy/NN sits/VBZ on/IN the/DT chair/NN ./."</p>
<p>I would like to produce a multi-level dictionary that has the word as a key and counts the frequency it appears tagged as each POS so we h... | 1 | 2016-10-18T16:15:48Z | 40,113,387 | <p>You don't have to use regular expressions in this case.</p>
<p>What you can do is to split by space and then by slash collecting the results into a <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a> of <code>defaultdict</code> of <code>in... | 2 | 2016-10-18T16:22:11Z | [
"python",
"regex",
"dictionary",
"part-of-speech"
] |
How do I run a single function over a loop parallely? Python 2.7.12 | 40,113,343 | <p>I'm trying to parallelize a program which uses a single function in a for loop which updates a global list/variable parallely. How do I go about this and how can I pass values to the function?</p>
<p>The sample code looks like this,</p>
<pre><code>#python 2.7.12
import random
sum=0
#sample function to take a rand... | 0 | 2016-10-18T16:19:40Z | 40,113,774 | <p>You can use multiprocessing.dummy.Pool, which takes the function followed by your parameters (see below).</p>
<p>You'll also need to worry about synchronization on your global variable (see below for an example of how to use Lock).</p>
<p>Also, unless you use "global sum" the sum inside your function is referring ... | 1 | 2016-10-18T16:45:02Z | [
"python",
"parallel-processing"
] |
How do I run a single function over a loop parallely? Python 2.7.12 | 40,113,343 | <p>I'm trying to parallelize a program which uses a single function in a for loop which updates a global list/variable parallely. How do I go about this and how can I pass values to the function?</p>
<p>The sample code looks like this,</p>
<pre><code>#python 2.7.12
import random
sum=0
#sample function to take a rand... | 0 | 2016-10-18T16:19:40Z | 40,113,825 | <p>Pass the parameters as a tuple to the args kwarg of the Process function: Here is the example from the docs:</p>
<pre><code>if __name__ == '__main__':
p = Process(target=f, args=('bob',))
p.start()
p.join()
</code></pre>
<p><a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow"... | 0 | 2016-10-18T16:47:23Z | [
"python",
"parallel-processing"
] |
UnicodeEncodeError in python3 | 40,113,507 | <p>Some of my application's libraries are depending on being able to print UTF-8 characters to stdout and stderr. Therefore this must not fail:</p>
<pre><code>print('\u2122')
</code></pre>
<p>On my local machine it works, but on my remote server it raises <code>UnicodeEncodeError: 'ascii' codec can't encode character... | 0 | 2016-10-18T16:29:39Z | 40,114,051 | <p>I'm guessing you're on a UNIX-like system, and your environment set <code>LANG</code> (or <code>LC_ALL</code> or whatever) to <code>C</code>.</p>
<p>Try editing your default shell's startup file to set <code>LANG</code> to something like <code>en_US.utf-8</code> (or whatever locale makes sense for you)? For example... | 0 | 2016-10-18T16:59:36Z | [
"python",
"python-3.x",
"unicode",
"utf-8",
"locale"
] |
UnicodeEncodeError in python3 | 40,113,507 | <p>Some of my application's libraries are depending on being able to print UTF-8 characters to stdout and stderr. Therefore this must not fail:</p>
<pre><code>print('\u2122')
</code></pre>
<p>On my local machine it works, but on my remote server it raises <code>UnicodeEncodeError: 'ascii' codec can't encode character... | 0 | 2016-10-18T16:29:39Z | 40,114,882 | <p>From @ShadowRanger's comment on my question,</p>
<blockquote>
<p><code>PYTHONIOENCODING=utf8</code> won't work unless you <code>export</code> it (or prefix the Python launch with it). Otherwise, it's a local variable in <code>bash</code> that isn't inherited in the environment of child processes. <code>export PYT... | 1 | 2016-10-18T17:50:34Z | [
"python",
"python-3.x",
"unicode",
"utf-8",
"locale"
] |
Setting up proxy with selenium / python | 40,113,514 | <p>I am using selenium with python.
I need to configure a proxy.</p>
<p>It is working for HTTP but not for HTTPS.</p>
<p>The code I am using is:</p>
<pre><code># configure firefox
profile = webdriver.FirefoxProfile()
profile.set_preference("network.proxy.type", 1)
profile.set_preference("network.proxy.http", '11.111... | 0 | 2016-10-18T16:29:58Z | 40,113,706 | <p>Check out <a href="https://github.com/AutomatedTester/browsermob-proxy-py" rel="nofollow">browsermob proxy</a> for setting up a proxies for use with <code>selenium</code></p>
<pre><code>from browsermobproxy import Server
server = Server("path/to/browsermob-proxy")
server.start()
proxy = server.create_proxy()
from ... | 0 | 2016-10-18T16:41:35Z | [
"python",
"selenium",
"proxy"
] |
Find missing data indices using python | 40,113,520 | <p>What is the optimum way to return indices where 1-d array has missing data. The missing data is represented by zeros. The data may be genuinely zero but not missing. We only want to return indices where data is zero for more than or equal to 3 places at a time. For example for array [1,2,3,4,0,1,2,3,0,0,0,1,2,3] the... | -3 | 2016-10-18T16:30:14Z | 40,113,890 | <p>Keep track of the count of zeros in the current run. Then if a run finishes that has at least three zeros calculate the indexes.</p>
<pre><code>def find_dx_of_missing(a):
runsize = 3 # 3 or more, change to 4 if your need "more than 3"
zcount = 0
for i, n in enumerate(a):
if n == 0:
... | 0 | 2016-10-18T16:50:38Z | [
"python",
"python-2.7"
] |
Pandas: Create another column while splitting each row from the first column | 40,113,552 | <p>Goal create a second column from the first column</p>
<pre><code>column1, column2
Hello World, #HelloWord
US Election, #USElection
</code></pre>
<p>I have a simple file that has a one column</p>
<pre><code>columnOne
Hello World
US Election
Movie Night
</code></pre>
<p>I wrote following function</p>
<pre><code>&... | 3 | 2016-10-18T16:32:01Z | 40,113,775 | <p>This should do the trick</p>
<pre><code>df['new_column'] = df['old_column'].apply(lambda x: "#"+x.replace(' ', ''))
</code></pre>
<p>Example</p>
<pre><code>>>> names = ['Hello World', 'US Election', 'Movie Night']
>>> df = pd.DataFrame(data = names, columns=['Names'])
>>> df
Names
... | 3 | 2016-10-18T16:45:02Z | [
"python",
"pandas"
] |
Pandas: Create another column while splitting each row from the first column | 40,113,552 | <p>Goal create a second column from the first column</p>
<pre><code>column1, column2
Hello World, #HelloWord
US Election, #USElection
</code></pre>
<p>I have a simple file that has a one column</p>
<pre><code>columnOne
Hello World
US Election
Movie Night
</code></pre>
<p>I wrote following function</p>
<pre><code>&... | 3 | 2016-10-18T16:32:01Z | 40,113,784 | <p>Try a list comprehesion:</p>
<pre><code>df = pandas.DataFrame({'columnOne': ['Hello World', 'US Election', 'Movie Night']})
df['column2'] = ['#' + item.replace(' ', '') for item in df.columnOne]
In [2]: df
</code></pre>
<p><a href="https://i.stack.imgur.com/iiwuK.png" rel="nofollow"><img src="https://i.stack.img... | 2 | 2016-10-18T16:45:25Z | [
"python",
"pandas"
] |
Pandas: Create another column while splitting each row from the first column | 40,113,552 | <p>Goal create a second column from the first column</p>
<pre><code>column1, column2
Hello World, #HelloWord
US Election, #USElection
</code></pre>
<p>I have a simple file that has a one column</p>
<pre><code>columnOne
Hello World
US Election
Movie Night
</code></pre>
<p>I wrote following function</p>
<pre><code>&... | 3 | 2016-10-18T16:32:01Z | 40,114,137 | <p>Your general approach is totally fine, you just have a few problems. When you use apply on an entire dataframe, it will pass either a row or a column to the function it is applying. In your case, you don't want a row or a column - you want the string that is within each cell in the first column. So, instead of runni... | 3 | 2016-10-18T17:04:34Z | [
"python",
"pandas"
] |
Pandas: Create another column while splitting each row from the first column | 40,113,552 | <p>Goal create a second column from the first column</p>
<pre><code>column1, column2
Hello World, #HelloWord
US Election, #USElection
</code></pre>
<p>I have a simple file that has a one column</p>
<pre><code>columnOne
Hello World
US Election
Movie Night
</code></pre>
<p>I wrote following function</p>
<pre><code>&... | 3 | 2016-10-18T16:32:01Z | 40,114,562 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html" rel="nofollow"><code>str.replace</code></a> as commented <a href="http://stackoverflow.com/questions/40113552/pandas-create-another-column-while-splitting-each-row-from-the-first-column/40114562#comment67498560... | 3 | 2016-10-18T17:32:39Z | [
"python",
"pandas"
] |
finding new line characters in a text file | 40,113,785 | <p>I have an assignment that involves creating a tail to find the last <code>K</code> lines in a file. We have been given a buffer to use for this. For now, I'm trying to write small things and search for <code>"\n"</code> characters within a file. I am running into a few problems. In <code>python</code> my code spits ... | 0 | 2016-10-18T16:45:28Z | 40,113,878 | <p><code>for i in f:</code> isn't doing what you think it is. The default iterator for a file gives you <code>lines</code>, not <code>characters</code>. So you're saying "Does the entire line equal just a return?"</p>
<p>Try instead doing <code>if i[-1] == "\n":</code> as this says "Is the last character in the line a... | 1 | 2016-10-18T16:49:41Z | [
"python",
"file",
"newline"
] |
finding new line characters in a text file | 40,113,785 | <p>I have an assignment that involves creating a tail to find the last <code>K</code> lines in a file. We have been given a buffer to use for this. For now, I'm trying to write small things and search for <code>"\n"</code> characters within a file. I am running into a few problems. In <code>python</code> my code spits ... | 0 | 2016-10-18T16:45:28Z | 40,113,895 | <p>A much simpler approach would be to</p>
<ul>
<li>use Python's built-in ability to split a file into a list of lines</li>
<li>create your tail from the last K elements of that list</li>
</ul>
<p>If keeping the whole file in an array is a problem, you could instead read the file line-by-line, but only retain the las... | 0 | 2016-10-18T16:51:14Z | [
"python",
"file",
"newline"
] |
finding new line characters in a text file | 40,113,785 | <p>I have an assignment that involves creating a tail to find the last <code>K</code> lines in a file. We have been given a buffer to use for this. For now, I'm trying to write small things and search for <code>"\n"</code> characters within a file. I am running into a few problems. In <code>python</code> my code spits ... | 0 | 2016-10-18T16:45:28Z | 40,113,896 | <p>Why not simplify the logic and use a Python built-in?</p>
<pre><code>def new(): # not a good function name!
try:
with open('data1.txt') as f:
return f.read().count('\n')
except FileNotFoundError:
print ("No file")
</code></pre>
| 0 | 2016-10-18T16:51:21Z | [
"python",
"file",
"newline"
] |
Django ImportError: No module named... but module is visible in Project Interpreter settings | 40,113,835 | <p>I am developing a Django app and I am experiencing a strange problem. I've installed a few modules using pip and I can see them in "project interpreter settings":</p>
<p><a href="https://i.stack.imgur.com/NWeYS.png" rel="nofollow"><img src="https://i.stack.imgur.com/NWeYS.png" alt="enter image description here"></a... | 0 | 2016-10-18T16:47:51Z | 40,116,359 | <p>Did u activate your virtualenv, with the command:</p>
<pre><code>source <virtualenv_name>/bin/ativate
</code></pre>
| 0 | 2016-10-18T19:20:40Z | [
"python",
"django",
"python-2.7",
"python-import",
"python-module"
] |
Bind Key to Stop Script | 40,113,868 | <p>I have a URL in a while loop which repeats the process. Is it possible to bind a key to stop a selenium python script from running while still keeping chromedriver open?</p>
| 0 | 2016-10-18T16:49:12Z | 40,113,918 | <p>You can use a try/except block that catches a <code>KeyboardInterrupt</code> exception (IE when you input <code>ctrl + c</code> to the terminal/command prompt)</p>
<pre><code>try:
while True:
#dostuff
except KeyboardInterrupt:
print("Loop stopped!")
</code></pre>
<p>You may also want to consider la... | 1 | 2016-10-18T16:52:38Z | [
"python",
"selenium",
"webdriver",
"selenium-chromedriver"
] |
Build successive condition to when | 40,113,905 | <p>I'm trying to build a sql request of consecutive <code>when</code>.</p>
<pre><code>def build_modify_function(df, ids_colname, modified_colname, modification_list):
if len(modification_list) == 0:
pass
# Small optimization
id_col = df[ids_colname]
modif_col = df[modified_colname]
# There is no "identity e... | 0 | 2016-10-18T16:52:02Z | 40,114,735 | <p>I believe that the problem is here:</p>
<pre><code>if ret == None:
...
</code></pre>
<p>In general you should never use equality operators to compare to singleton objects in Python and always use <code>is</code> or <code>is not</code>:</p>
<pre><code>if ret is None:
...
</code></pre>
<p>In this particular... | 0 | 2016-10-18T17:42:07Z | [
"python",
"apache-spark",
"apache-spark-sql"
] |
Issue adding request headers for Django Tests | 40,113,921 | <p>I need to add a header to a request in a Django test. I have browsed a few pages on both Stack Overflow and elsewhere, following various suggestions. I can add the headers to PUTs and GETs successfully, but having an issue with POSTs. Any advice would be greatly appreciated.</p>
<p>For PUT and GET I have used the f... | 0 | 2016-10-18T16:52:39Z | 40,127,734 | <p>For anybody that finds themselves looking at this page with a similar issue, I was able to get this working with the following:</p>
<pre><code>resp = self.client.post(resource_url, data=res_params, content_type='application/json', HTTP_SSL_CLIENT_CERT=self.client_cert)
</code></pre>
| 0 | 2016-10-19T09:44:32Z | [
"python",
"django",
"django-testing"
] |
Python - creating multiple objects for a class | 40,113,998 | <p>In python I need to create 43 instances of a class 'Student' that includes the variables first_name, middle_name, last_name, student_id by reading in a file (Students.txt) and parsing it. The text file appears like this: </p>
<pre><code>Last Name Midle Name First Name Student ID
------------------------------... | 0 | 2016-10-18T16:57:00Z | 40,114,173 | <pre><code>list_of_students = []
with open('students.txt') as f:
for line in f:
data = line.split()
if len(data) == 3:
firstname, lastname, id = data
list_of_students.append(Student(firstname, '', lastname, id))
elif len(data) == 4:
list_of_students.append... | 0 | 2016-10-18T17:06:15Z | [
"python",
"class",
"object",
"object-oriented-analysis"
] |
Python - creating multiple objects for a class | 40,113,998 | <p>In python I need to create 43 instances of a class 'Student' that includes the variables first_name, middle_name, last_name, student_id by reading in a file (Students.txt) and parsing it. The text file appears like this: </p>
<pre><code>Last Name Midle Name First Name Student ID
------------------------------... | 0 | 2016-10-18T16:57:00Z | 40,115,729 | <h2>Step by step tutorial</h2>
<p>To read the file content, use <code>io.open</code>. Don't forget to specify the file encoding if any name has accentuated characters.</p>
<pre><code>with io.open('students.txt', mode="r", encoding="utf8") as fd:
content = fd.read()
</code></pre>
<p>Here, you read the whole conte... | 0 | 2016-10-18T18:41:54Z | [
"python",
"class",
"object",
"object-oriented-analysis"
] |
Precise Python 2.7 calculation including Pi | 40,114,115 | <p>I am working on a small program that calculates different things related to orbital mechanics, such as the semi-major axis of an orbit, velocity etc. (No experience in this subject is required to answer this).</p>
<p>Everything worked out well, until I tried to calculate the orbital period (a formula where I had to... | -2 | 2016-10-18T17:03:39Z | 40,114,664 | <p><code>math.pi</code> is a float with 15 decimals: 3.141592653589793</p>
<p>As per chepners comment to your original post, that equates to about the size of an atom when calculating spheres the size of the earth. </p>
<p>So to answer your question: it's not <code>math.pi</code></p>
| 1 | 2016-10-18T17:38:09Z | [
"python",
"python-2.7",
"math"
] |
Precise Python 2.7 calculation including Pi | 40,114,115 | <p>I am working on a small program that calculates different things related to orbital mechanics, such as the semi-major axis of an orbit, velocity etc. (No experience in this subject is required to answer this).</p>
<p>Everything worked out well, until I tried to calculate the orbital period (a formula where I had to... | -2 | 2016-10-18T17:03:39Z | 40,114,815 | <p>Okay - seems like I have found the solution to my problem; while editing my question to include my calculation for the variable <em>semiMajor</em>, I realized I forgot to include parentheses around <code>bodyDia + ap + pe</code>, which caused faulty prioritizing, leading to the not-very-precise calculation.</p>
<p>... | 0 | 2016-10-18T17:46:48Z | [
"python",
"python-2.7",
"math"
] |
Extract a seris of tar files into self titled directories | 40,114,156 | <p>I have a series of tar files that I wish to extract their containing data into a new directory. I want this directory to be an edited version of the original tar file name. </p>
<pre><code>import tarfile
import glob
import os
for file in glob.glob("*.tar"):
# Open file
tar = tarfile.open(file, "r:")
# ... | 0 | 2016-10-18T17:05:14Z | 40,115,347 | <p>new_dir = "path"</p>
<p><code>tar.extractall(path=new_dir)</code></p>
| 0 | 2016-10-18T18:20:32Z | [
"python",
"tar"
] |
Mapping csv file to nested json | 40,114,225 | <p>I have data in a csv in the form of </p>
<pre><code>"category1", 2010, "deatil1"
"category1", 2010, "deatil2"
"category1", 2011, "deatil3"
"category2", 2011, "deatil4"
</code></pre>
<p>I need to map it to json in form of </p>
<pre><code> {
"name": "Data",
"children": [{
"name": "catego... | 1 | 2016-10-18T17:10:32Z | 40,116,288 | <p>Starting from your <code>dict</code> structure, it's a matter of building up the new data structure. I am using here mostly list comprehensions where <code>dict</code> are created:</p>
<pre><code>import json
rows = [
("category1", 2010, "deatil1"),
("category1", 2010, "deatil2"),
("category1", 2011, "d... | 2 | 2016-10-18T19:16:19Z | [
"python",
"json",
"csv",
"dictionary"
] |
Extract part of data from JSON file using python | 40,114,248 | <p>I have been trying to extract only certain data from a JSON file using python.I wanted to create an array from my json which has some entries as below</p>
<pre><code>[{"Device Name":"abc", "Device Caps":["a1", "b1", "c1"]},
{"Device Name":"def", "Device Caps":["a2", "b2", "c2"]},
{"Device Name":"ghi", "Device Caps"... | -1 | 2016-10-18T17:11:44Z | 40,114,291 | <p>If that is literally your input file, then the following code will produce the output you want:</p>
<pre><code>import json
with open("input.json") as input_file:
data = json.load(input_file)
data = [d["Device Caps"][0] for d in data]
print(data)
</code></pre>
| 1 | 2016-10-18T17:14:56Z | [
"python",
"json",
"extract",
"decode"
] |
PyCharm template for python class __init__ function | 40,114,251 | <p>I have a python class with several init variables:</p>
<pre><code>class Foo(object):
def __init__(self, d1, d2):
self.d1 = d1
self.d2 = d2
</code></pre>
<p>Is there a way to create this code automatically in PyCharm, so I don't have to type explicitly:</p>
<pre><code>self.dn = dn
</code></pre>... | 1 | 2016-10-18T17:11:52Z | 40,114,374 | <p>You can start by making a custom <a href="https://www.jetbrains.com/help/pycharm/2016.2/live-templates.html" rel="nofollow">Live Template</a>. I'm not sure about whether you can auto-generate variable number of arguments this way, but, for two constructor arguments the live template may look like:</p>
<pre><code>cl... | 3 | 2016-10-18T17:20:28Z | [
"python",
"class",
"attributes",
"pycharm"
] |
How can I insert a Series into a DataFrame row? | 40,114,327 | <p>I have a DataFrame like this:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame(columns=['a','b','c','d'], index=['x','y','z'])
df
a b c d
x NaN NaN NaN NaN
y NaN NaN NaN NaN
z NaN NaN NaN NaN
</code></pre>
<p>I also have a Series like this</p>
<pre><code>s = pd.Ser... | 2 | 2016-10-18T17:17:10Z | 40,114,444 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow"><code>iloc</code></a> if need select <code>index</code> of <code>df</code> by position:</p>
<pre><code>#select second row (python counts from 0)
df.iloc[1] = s
print (df)
a b c ... | 3 | 2016-10-18T17:25:29Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
Scrapy opening html in editor , not browser | 40,114,350 | <p><a href="https://i.stack.imgur.com/LWxmP.png" rel="nofollow"><img src="https://i.stack.imgur.com/LWxmP.png" alt="enter image description here"></a></p>
<p>I am working on some code which returns an <code>HTML</code> string (<code>my_html</code>). I want to see how this looks in a browser using <a href="https://doc.... | 1 | 2016-10-18T17:18:59Z | 40,114,448 | <p>Look at how the <a href="https://github.com/scrapy/scrapy/blob/129421c7e31b89b9b0f9c5f7d8ae59e47df36091/scrapy/utils/response.py#L63" rel="nofollow"><code>open_in_browser()</code></a> function is defined:</p>
<pre><code>if isinstance(response, HtmlResponse):
if b'<base' not in body:
repl = '<head&... | 1 | 2016-10-18T17:25:47Z | [
"python",
"scrapy"
] |
finding different words in two lists | 40,114,385 | <p>i have two list and i want to delete the matching one and keep the different.
here is the code:</p>
<pre><code>def check_synonym(text):
tokens=regexp_tokenize(text, r'[ØØ!.Ø\s+]\s*', gaps=True)
based_text= ' '.join(cursor.execute('SELECT request FROM Male_Conversation_Engine WHERE request REGEXP?',[tok... | 0 | 2016-10-18T17:21:09Z | 40,114,442 | <p>You can use a combination of sets and list comprehensions</p>
<pre><code>s1 = set(tokens)
s2 = set(based_tokens)
tokens = [t for t in tokens if t not in s2]
based_tokes = [t for t in based_tokens if t not in s1]
</code></pre>
<p>The only reason I am using sets is because for large lists it is much faster to check... | 0 | 2016-10-18T17:25:22Z | [
"python"
] |
finding different words in two lists | 40,114,385 | <p>i have two list and i want to delete the matching one and keep the different.
here is the code:</p>
<pre><code>def check_synonym(text):
tokens=regexp_tokenize(text, r'[ØØ!.Ø\s+]\s*', gaps=True)
based_text= ' '.join(cursor.execute('SELECT request FROM Male_Conversation_Engine WHERE request REGEXP?',[tok... | 0 | 2016-10-18T17:21:09Z | 40,114,739 | <pre><code> set1=set(tokens)
set2=set(based_tokens)
tokens = set1-set2
based_tokens = set2-set1
</code></pre>
| 0 | 2016-10-18T17:42:19Z | [
"python"
] |
regex to match several string in Python | 40,114,423 | <p>I have questions with regex in Python.</p>
<p>Possible variations can be </p>
<p>10 hours, 12 weeks or 7 business days.</p>
<p>I want to have my regex something like </p>
<pre><code>string = "I have an 7 business day trip and 12 weeks vacation."
re.findall(r'\d+\s(business)?\s(hours|weeks|days)', string)
</code>... | 0 | 2016-10-18T17:24:18Z | 40,114,493 | <p>You need to tweak your regex to this:</p>
<pre><code>>>> string = "I have an 7 business day trip and 12 weeks vacation."
>>> print re.findall(r'(\d+)\s*(?:business day|hour|week)s?', string)
['7', '12']
</code></pre>
<p>This matches any number that is followed by <code>business day</code> or <cod... | 1 | 2016-10-18T17:28:00Z | [
"python",
"regex"
] |
regex to match several string in Python | 40,114,423 | <p>I have questions with regex in Python.</p>
<p>Possible variations can be </p>
<p>10 hours, 12 weeks or 7 business days.</p>
<p>I want to have my regex something like </p>
<pre><code>string = "I have an 7 business day trip and 12 weeks vacation."
re.findall(r'\d+\s(business)?\s(hours|weeks|days)', string)
</code>... | 0 | 2016-10-18T17:24:18Z | 40,114,543 | <pre><code>string = "I have an 7 business day trip and 12 weeks vacation."
print re.findall(r'\d+\s(?:business\s)?(?:hour|week|day)s?', string)
['7 business day', '12 weeks']
\d+\s(?:business\s)?(?:hour|week|day)s?
</code></pre>
<p><a href="https://www.debuggex.com/r/Ytu1HFfbmsd3BpFV" rel="nofollow">Debuggex Demo</a>... | 2 | 2016-10-18T17:30:57Z | [
"python",
"regex"
] |
regex to match several string in Python | 40,114,423 | <p>I have questions with regex in Python.</p>
<p>Possible variations can be </p>
<p>10 hours, 12 weeks or 7 business days.</p>
<p>I want to have my regex something like </p>
<pre><code>string = "I have an 7 business day trip and 12 weeks vacation."
re.findall(r'\d+\s(business)?\s(hours|weeks|days)', string)
</code>... | 0 | 2016-10-18T17:24:18Z | 40,114,676 | <p>Similar to @anubhava's answer but matches "7 business day" rather than just "7". Just move the closing parenthesis from after \d+ to the end:</p>
<pre><code>re.findall(r'(\d+\s*(?:business day|hour|week)s?)', string)
</code></pre>
| 0 | 2016-10-18T17:38:41Z | [
"python",
"regex"
] |
regex to match several string in Python | 40,114,423 | <p>I have questions with regex in Python.</p>
<p>Possible variations can be </p>
<p>10 hours, 12 weeks or 7 business days.</p>
<p>I want to have my regex something like </p>
<pre><code>string = "I have an 7 business day trip and 12 weeks vacation."
re.findall(r'\d+\s(business)?\s(hours|weeks|days)', string)
</code>... | 0 | 2016-10-18T17:24:18Z | 40,114,778 | <p>I've matched " trip and " between "7 business day" and "12 weeks"</p>
<pre><code>import re
string = "I have an 7 business days trip and 12 weeks vacation."
print(re.findall(r'(\d+\sbusiness\sdays?)\strip\sand\s(\d+\s(?:hours?|weeks?|days?))\svacation', string))
</code></pre>
| -1 | 2016-10-18T17:44:09Z | [
"python",
"regex"
] |
regex to match several string in Python | 40,114,423 | <p>I have questions with regex in Python.</p>
<p>Possible variations can be </p>
<p>10 hours, 12 weeks or 7 business days.</p>
<p>I want to have my regex something like </p>
<pre><code>string = "I have an 7 business day trip and 12 weeks vacation."
re.findall(r'\d+\s(business)?\s(hours|weeks|days)', string)
</code>... | 0 | 2016-10-18T17:24:18Z | 40,114,814 | <p>\d+\s+(business\s)?(hour|week|day)s?</p>
| -2 | 2016-10-18T17:46:43Z | [
"python",
"regex"
] |
Python method calls in constructor and variable naming conventions inside a class | 40,114,431 | <p>I try to process some data in Python and I defined a class for a sub-type of data. You can find a very simplified version of the class definition below. </p>
<pre><code>class MyDataClass(object):
def __init__(self, input1, input2, input3):
"""
input1 and input2 are a 1D-array
input3 is a... | 0 | 2016-10-18T17:24:44Z | 40,114,971 | <p>In Python, you do not need getter and setter functions. Use properties instead. This is why you can access attributes directly in Python, unlike other languages like Java where you absolutely need to use getters and setters and to protect your attributes.</p>
<p>Consider the following example of a <code>Circle</cod... | 0 | 2016-10-18T17:56:13Z | [
"python"
] |
Numpy 4d array slicing | 40,114,534 | <p>Why does slicing a 4d array give me a 3d array? I expected a 4d array with extent 1 in one of the dimensions.</p>
<p>Example:</p>
<pre><code>print X.shape
(1783, 1, 96, 96)
</code></pre>
<p>Slice array:</p>
<pre><code>print X[11,:,:,:].shape
</code></pre>
<p>or</p>
<pre><code>print X[11,:].shape
</code></pre>
... | 0 | 2016-10-18T17:29:49Z | 40,114,756 | <p>Per <a href="https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html" rel="nofollow">the docs</a>:</p>
<blockquote>
<p>An integer, <code>i</code>, returns the same values as <code>i:i+1</code> <strong>except</strong> the dimensionality of the returned object is reduced by <code>1</code>. In particular, a ... | 1 | 2016-10-18T17:43:21Z | [
"python",
"numpy"
] |
Why is this piece of code not working? | 40,114,605 | <p>I am currently doing a project for school in which I am supposed to make a dice game. Here is the code:</p>
<pre><code>Roll = input("Do you want to Roll or Stick?")
if Roll in ("Roll" , "roll"):
print("Your new numbers are," , +number10 , +number20 , +number30 , +number40 , +number50)
KeepDelete = input("Would... | -3 | 2016-10-18T17:34:57Z | 40,115,023 | <p>Just taking a section of your code: </p>
<pre><code>print("Your final score is," , number10+number20+number30+number40+number50)
if KeepDelete in("Delete", "delete"):
Delete = int(input("What number would you like to delete?"))
if Delete == (number10):
del(number10)
Score1 = int("Your numbers are" , numb... | 0 | 2016-10-18T17:59:29Z | [
"python",
"python-3.x"
] |
list_objects_v2() sometimes returns first key value incorrectly | 40,114,736 | <p>I am currently writing a Python script using boto3 that opens an S3 folder (the prefix) in a bucket and prints out the contents of that folder (XML pointer filenames). The code I have for that is this:</p>
<pre><code>def getXMLFileName(self, bucketName, prefix):
session = boto3.Session(profile_name=self.profil... | 0 | 2016-10-18T17:42:08Z | 40,114,805 | <p>Directories aren't real in S3, however, when you create your S3 dataset many tools will create a metadata construct that roughly maps to a directory on a regular file system. </p>
<p>When you query using boto you will see those metadata constructs if they were created by the tool you used to upload.</p>
| 1 | 2016-10-18T17:46:14Z | [
"python",
"amazon-s3",
"boto3"
] |
can't find ipython notebook in the app list of anaconda launcher | 40,114,836 | <p>I download anaconda launcher and successfully launched the Ipython notebook, then the next time I open the anaconda launcher I couldn't find the ipython notebook in the app list </p>
| 0 | 2016-10-18T17:47:55Z | 40,135,824 | <p>I reinstall the program again, the problem was that I accidentally have 2 version of the same program</p>
| 0 | 2016-10-19T15:32:23Z | [
"python",
"anaconda",
"launcher"
] |
Python - Return Average of Word Length In Sentences | 40,114,839 | <p>I have a question very similar to this one: <a href="http://stackoverflow.com/questions/12761510/python-how-can-i-calculate-the-average-word-length-in-a-sentence-using-the-spl">Python: How can I calculate the average word length in a sentence using the .split command?</a></p>
<p>I need the average word length for m... | -1 | 2016-10-18T17:48:04Z | 40,114,919 | <pre><code>sentences = words.split('.')
sentences = [sentence.split() for sentence in sentences if len(sentence)]
averages = [sum(len(word) for word in sentence)/len(sentence) for sentence in sentences]
</code></pre>
| -1 | 2016-10-18T17:52:49Z | [
"python",
"string"
] |
Python - Return Average of Word Length In Sentences | 40,114,839 | <p>I have a question very similar to this one: <a href="http://stackoverflow.com/questions/12761510/python-how-can-i-calculate-the-average-word-length-in-a-sentence-using-the-spl">Python: How can I calculate the average word length in a sentence using the .split command?</a></p>
<p>I need the average word length for m... | -1 | 2016-10-18T17:48:04Z | 40,115,275 | <p>Try this:</p>
<pre><code>data = "This is great. Just great."
sentences = data.split('.')[:-1] #you need to account for the empty string as a result of the split
num_words = [len(sentence.split(' ')) for sentence in sentences]
average = sum(num for num in num_words)/(len(sentences))
print(num_words)
print(len(sen... | -1 | 2016-10-18T18:16:52Z | [
"python",
"string"
] |
Python - Return Average of Word Length In Sentences | 40,114,839 | <p>I have a question very similar to this one: <a href="http://stackoverflow.com/questions/12761510/python-how-can-i-calculate-the-average-word-length-in-a-sentence-using-the-spl">Python: How can I calculate the average word length in a sentence using the .split command?</a></p>
<p>I need the average word length for m... | -1 | 2016-10-18T17:48:04Z | 40,115,959 | <p>lets look at this line </p>
<pre><code>average = sum(len(word) for word in words)/len(words)
</code></pre>
<p>here the len(words) = 2 this is not the len of words . it is the len of sentence</p>
<pre><code>average = sum(len(word) for word in words)/(len(words[0])+len(words[1]))
</code></pre>
<p>hope you get the ... | 0 | 2016-10-18T18:55:16Z | [
"python",
"string"
] |
Python help (computer guess number) | 40,114,859 | <p>Im learning how to programme in python and i found 2 tasks that should be pretty simple but second one is very hard for me and dont know how to make it work.</p>
<p>Basically i need to make program where computer guesses my number. So i enter number and than computer try's to guess it and everytime he picks number ... | 0 | 2016-10-18T17:49:04Z | 40,115,218 | <p>You may want to put in a case for if it doesn't match you input, also I think you need a case for when the guess finally equals the number, you may want to allow an input for "Found it!" or something like that.</p>
<pre><code>from random import randint
number = int(input("Number? "))
attempts = 0
guess = 0
min = ... | 0 | 2016-10-18T18:13:07Z | [
"python"
] |
Python help (computer guess number) | 40,114,859 | <p>Im learning how to programme in python and i found 2 tasks that should be pretty simple but second one is very hard for me and dont know how to make it work.</p>
<p>Basically i need to make program where computer guesses my number. So i enter number and than computer try's to guess it and everytime he picks number ... | 0 | 2016-10-18T17:49:04Z | 40,115,555 | <pre><code>from random import randit
attempts = 0
guess = 0
min = 0
max = 100
while guess != number:
number = int(input("Number? "))
guess = randint(min,max)
print(guess,"?")
if guess < number:
print("Higher")
min = guess
elif guess > number:
print("Lower")
max = guess
a... | 0 | 2016-10-18T18:32:06Z | [
"python"
] |
Validating a Django model field based on another field's value? | 40,114,876 | <p>I have a Django app with models accessible by both Django REST Framework and a regular form interface. The form interface has some validation checks before saving changes to the model, but not using any special Django framework, just a simple local change in the view.</p>
<p>I'd like to apply the same validation to... | 1 | 2016-10-18T17:50:23Z | 40,115,532 | <p>The validation per-field doesn't get sent any information about other fields, when it is defined like this:</p>
<pre><code>def validate_myfield(self, value):
...
</code></pre>
<p>However, if you have a method defined like this:</p>
<pre><code>def validate(self, data):
...
</code></pre>
<p>Then you get al... | 1 | 2016-10-18T18:30:47Z | [
"python",
"django",
"forms",
"validation"
] |
How do I arrange multiple arguments with string formatting in python | 40,114,911 | <p>I have this piece of code and I'm trying to figure out how to have multiple arguments in that second set of brackets. I want the number to be right aligned in 6 places and rounded to 2 decimal points. I get the error 'invalid format specifier' every time. </p>
<pre><code>print("{0:>5} {1:>6, 6.2f}".format(p... | 2 | 2016-10-18T17:52:29Z | 40,115,065 | <p>If you read the <a href="https://docs.python.org/3/library/string.html#format-specification-mini-language" rel="nofollow">Format Specification Mini-Language</a>, you'll notice that one can only specify the format width <em>once</em> and <em>precision</em> appears after the <code>'.'</code>:</p>
<pre><code>>>&... | 0 | 2016-10-18T18:02:50Z | [
"python"
] |
How to use python in a JS based app | 40,114,977 | <p>I have created an app using meteor.js framework. I need to run some python code for some important data crunching that will be used in the app. How can I do that? I am really new to Javascript and cant figure this out. I will be running python code on server. All I need is, as soon as I click a particular button, a ... | 0 | 2016-10-18T17:56:49Z | 40,115,033 | <p>You'll need to expose your Python code over some sort of API. Since your Python is "running on the server" as you mentioned.</p>
<p>The fastest way I can think of doing it is to setup an AWS Lambda function (<a href="https://aws.amazon.com/lambda/" rel="nofollow">https://aws.amazon.com/lambda/</a>), then expose it ... | 0 | 2016-10-18T18:00:02Z | [
"javascript",
"python"
] |
Python dataset update - TypeError: update() takes at most 2 positional arguments (3 given) | 40,115,187 | <p>When trying to update database with data from a dict where uuident = uuident, i'm receiving this error</p>
<h3>Error:</h3>
<pre><code>TypeError: update() takes at most 2 positional arguments (3 given)
</code></pre>
<p>The error happens only in this update. If insert there is no errors at all.</p>
<p>I'm a beginn... | -1 | 2016-10-18T18:11:00Z | 40,117,523 | <p>The builtin dict update method accepts other keywords=values and updates the dict with that, or another dictionary and updates the dict with <strong>all</strong> keys from the second dict.</p>
<p>What your probably want to do is:</p>
<pre><code>produto_precificado[product['uuident']] = product
</code></pre>
<p>to... | 0 | 2016-10-18T20:30:30Z | [
"python",
"python-2.7",
"dataset",
"parameter-passing"
] |
Python dataset update - TypeError: update() takes at most 2 positional arguments (3 given) | 40,115,187 | <p>When trying to update database with data from a dict where uuident = uuident, i'm receiving this error</p>
<h3>Error:</h3>
<pre><code>TypeError: update() takes at most 2 positional arguments (3 given)
</code></pre>
<p>The error happens only in this update. If insert there is no errors at all.</p>
<p>I'm a beginn... | -1 | 2016-10-18T18:11:00Z | 40,117,803 | <p>I'm sorry for my terrible mistake here.</p>
<p>Well, just in case somebody goes through the same:</p>
<p>produto_precificado is a row from table precificado.</p>
<p>So that was the error.</p>
<p>I changed:</p>
<pre><code>produto_precificado.update(product,['uuident'])
</code></pre>
<p>for</p>
<pre><code>preci... | 0 | 2016-10-18T20:47:55Z | [
"python",
"python-2.7",
"dataset",
"parameter-passing"
] |
Generate a lot of random strings | 40,115,278 | <p>I have a method that will generate 50,000 <em>random</em> strings, save them all to a file, and then run through the file, and delete all duplicates of the strings that occur. Out of those 50,000 random strings, after using <code>set()</code> to generate unique ones, on average 63 of them are left. </p>
<p>Function... | 2 | 2016-10-18T18:17:01Z | 40,115,439 | <p>You can use <em>set</em> from the start</p>
<pre><code>created = set()
while len(created) < 50000:
created.add(random_strings())
</code></pre>
<p>And save once outside the loop</p>
| 3 | 2016-10-18T18:25:41Z | [
"python",
"string",
"python-2.7",
"random"
] |
Generate a lot of random strings | 40,115,278 | <p>I have a method that will generate 50,000 <em>random</em> strings, save them all to a file, and then run through the file, and delete all duplicates of the strings that occur. Out of those 50,000 random strings, after using <code>set()</code> to generate unique ones, on average 63 of them are left. </p>
<p>Function... | 2 | 2016-10-18T18:17:01Z | 40,116,320 | <p>You could guarantee unique strings by generating unique numbers, starting with a random number is a range that is 1/50000<sup>th</sup> of the total number of possibilities (62<sup>8</sup>). Then generate more random numbers, each time determining the window in which the next number can be selected. This is not <em>p... | 0 | 2016-10-18T19:18:44Z | [
"python",
"string",
"python-2.7",
"random"
] |
Calculate set difference using jinja2 (in ansible) | 40,115,323 | <p>I have two lists of strings in my ansible playbook, and I'm trying to find the elements in list A that aren't in list B - a set difference. However, I don't seem to be able to access the python <code>set</code> data structure. Here's what I was trying to do:</p>
<pre><code>- set_fact:
difference: "{{ (set(listA... | 2 | 2016-10-18T18:19:00Z | 40,116,111 | <p>Turns out there is a <a href="http://docs.ansible.com/ansible/playbooks_filters.html#set-theory-filters" rel="nofollow">built-in filter for this in ansible</a> (not in generic jinja) called <code>difference</code>.</p>
<p>This accomplishes what I was trying to do in my question:</p>
<pre><code>"{{ (listA | differe... | 0 | 2016-10-18T19:04:55Z | [
"python",
"ansible",
"jinja2"
] |
Contains function in Pandas | 40,115,346 | <p>I am performing matching (kind of fuzzy matching) between the company names of two data frames. For doing so, first I am performing full merge between all the company names, where the starting alphabet matches. Which means all the companies starting with 'A' would be matched to all the companies starting with 'A' in... | 1 | 2016-10-18T18:20:32Z | 40,115,373 | <p>I think you need <code>|</code> with <code>join</code> for generating all values separated by <code>|</code> (or in <a href="http://stackoverflow.com/questions/8609597/python-regular-expressions-or">regex</a>) for <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="no... | 0 | 2016-10-18T18:22:02Z | [
"python",
"pandas",
"fuzzywuzzy"
] |
imgurpython.helpers.error.ImgurClientRateLimitError: Rate-limit exceeded | 40,115,380 | <p>I have the following error:</p>
<pre><code>/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more informatio... | 0 | 2016-10-18T18:22:19Z | 40,115,661 | <p>The rate limit refers to how frequently you're hitting the API, not how many calls you're allowed. To prevent hammering, most APIs have a rate limit (eg: 30 requests per minute, 1 every 2 seconds). Your script is making requests as quickly possible, hundreds or even thousands of times faster than the limit.</p>
<p>... | 1 | 2016-10-18T18:38:42Z | [
"python",
"api",
"http",
"imgur",
"rate-limiting"
] |
How can I store a file path in Mysql database using django? | 40,115,404 | <p>I need to store a file path in db using django via ajax form submission . </p>
<p>Here is my view:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>def dashboard(requ... | 1 | 2016-10-18T18:23:41Z | 40,115,726 | <p>From your code it's not 100% clear whether you're intending to handle file uploads from the client, or simply store strings that happen to be a file path (potentially for locating a file on some remote filesystem).</p>
<p><strong>1. File uploads</strong></p>
<p>Consider using the <a href="https://docs.djangoprojec... | 0 | 2016-10-18T18:41:51Z | [
"python",
"mysql",
"ajax",
"django"
] |
Error in getting the running median | 40,115,452 | <p>I am trying to get a running median for a number of integers. For example: 6 elements will come one by one, let say 12,4,5,3,8,7 for which running median at each input is 12,8,5,4.5,6,5 respectively. I wrote a python code but it seems to give incorrect answer. Help is appreciated .</p>
<pre><code>n = int(raw_input... | 0 | 2016-10-18T18:26:50Z | 40,115,700 | <pre><code>n = int(raw_input().strip())
s=[]
for i in xrange(n):
a=int(raw_input())
if len(s)==0:
s.append(a)
print "%.1f" % a
else:
for j in xrange(len(s)):
if a<s[j]:
s.insert(j,a)
break # inserted this break
if a>=s[-1]:
... | 1 | 2016-10-18T18:40:46Z | [
"python",
"python-2.7"
] |
Error in getting the running median | 40,115,452 | <p>I am trying to get a running median for a number of integers. For example: 6 elements will come one by one, let say 12,4,5,3,8,7 for which running median at each input is 12,8,5,4.5,6,5 respectively. I wrote a python code but it seems to give incorrect answer. Help is appreciated .</p>
<pre><code>n = int(raw_input... | 0 | 2016-10-18T18:26:50Z | 40,115,786 | <p>Read the comments embedded in the code below - </p>
<pre><code>n = int(raw_input().strip())
s=[]
for i in xrange(n):
a=int(raw_input())
if len(s)==0:
s.append(a)
print "%.1f" % a
else:
for j in xrange(len(s)):
if a<s[j]:
s.insert(j,a)
... | 1 | 2016-10-18T18:44:24Z | [
"python",
"python-2.7"
] |
Concisely adding variables to Django context dictionary | 40,115,565 | <p>The Django documentation suggests adding variables to the context dictionary in class based views as follows:</p>
<pre><code>def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(PublisherDetail, self).get_context_data(**kwargs)
# Add in ... | 0 | 2016-10-18T18:32:36Z | 40,115,625 | <p>Use <code>locals</code> is such a bad idea. Just add to the context directly</p>
<pre><code>def get_context_data(self, **kwargs):
context = super(PublisherDetail, self).get_context_data(**kwargs)
c = 75 # temp variable, not wanted in context dict
context['a'] = 2
context['b'] = 'hello'
context[... | 0 | 2016-10-18T18:36:22Z | [
"python",
"django",
"dictionary"
] |
Gathering the default landing page URL for a large ip hostlist on a single port | 40,115,588 | <h2>So here is the requirement breakdown:</h2>
<ul>
<li>Parse NMAP output to define a hostlist that is serving web services.</li>
<li>Use a hostlist to define the default landing page URL for each listening protocol.</li>
<li>Compile a master web services list to include IP:URL.</li>
</ul>
<h2>What I have done so far... | 0 | 2016-10-18T18:33:43Z | 40,121,997 | <p>Why bother with all the extra parsing and tools if you're already scanning with Nmap? The <a href="https://nmap.org/book/nse.html" rel="nofollow">Nmap Scripting Engine</a> can do what you want easily for each HTTP port discovered. You can even use an existing script: <a href="https://nmap.org/nsedoc/scripts/http-tit... | 0 | 2016-10-19T04:13:30Z | [
"python",
"linux",
"bash",
"nmap",
"penetration-testing"
] |
Multiple Pandas DataFrame Bar charts on the same chart | 40,115,598 | <p>How to plot Multiple DataFrame Bar charts on the same chart? </p>
<p>I want to plot top three scores (or top five). Since I know 1st >= 2nd >= 3rd, I want to plot the top three (or five) in the chart on the same bar, instead of spreading them out in three (or five) bars.</p>
<p>The visual effect will be exactly li... | 0 | 2016-10-18T18:34:25Z | 40,137,120 | <p>Is this what you are looking for? </p>
<pre><code>import pandas
import matplotlib.pyplot as plt
import numpy as np
Scores = [
{"TID":7,"ScoreRank":1,"Score":834,"Average":690},
{"TID":7,"ScoreRank":2,"Score":820,"Average":690},
{"TID":7,"ScoreRank":3,"Score":788,"Average":690},
{"TID":8,"ScoreRank":1,"Score":617,"A... | 1 | 2016-10-19T16:40:26Z | [
"python",
"matplotlib",
"dataframe",
"charts",
"bar-chart"
] |
How to turn a 1D radial profile into a 2D array in python | 40,115,608 | <p>I have a list that models a phenomenon that is a function of radius. I want to convert this to a 2D array. I wrote some code that does exactly what I want, but since it uses nested for loops, it is quite slow.</p>
<pre><code>l = len(profile1D)/2
critDim = int((l**2 /2.)**(1/2.))
profile2D = np.empty([critDim, crit... | 1 | 2016-10-18T18:34:59Z | 40,115,736 | <p>Here's a vectorized approach using <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> -</p>
<pre><code>a = np.arange(critDim)**2
r2D = np.sqrt(a[:,None] + a)
out = profile1D[(l+r2D).astype(int)]
</code></pre>
<p>If there are many repeated indices g... | 0 | 2016-10-18T18:42:12Z | [
"python",
"performance",
"numpy",
"multidimensional-array",
"vectorization"
] |
vectorize and parallelize if it's add compute? | 40,115,612 | <p>What's the most efficient technique and Why?</p>
<pre><code>min_dist = 999999999999999999999999999999999999999999
for i in range(len(self.data)):
data = self.data[i]
dist = MySuperLongFunction(data)
if dist < min_dist:
min_dist = dist
return min_dist
</code></pre>
<p>... | 0 | 2016-10-18T18:35:45Z | 40,115,722 | <p>You need to generate the function value for each input data in self.data, hence, <code>DARRAY = [MySuperLongFunction(x) for x in self.data]</code> has to be computed no matter what.
As you already pointed out, computing <code>DARRAY</code> could be parallelized, hence, we are left with returning the <code>min</code>... | 1 | 2016-10-18T18:41:45Z | [
"python",
"multithreading",
"vectorization"
] |
How to add additional tick labels, formatted differently, in matplotlib | 40,115,650 | <p>I'm having real problems plotting a 2nd line of tick labels on x-axis directly underneath the original ones. I'm using seaborn so I need to add these extra labels after the plot is rendered.</p>
<p>Below is <a href="http://content.screencast.com/users/cmardiros/folders/Jing/media/51a8b412-e3db-4030-81c9-cd389336f62... | 0 | 2016-10-18T18:37:44Z | 40,117,351 | <p>One possibility would be to create a second x-axis on top of the first, and adjust the position and xtickslabels of the second x-axis. Check <a href="http://matplotlib.org/examples/axes_grid/demo_parasite_axes2.html" rel="nofollow">this example</a> in the documentation as a starting point.</p>
| 0 | 2016-10-18T20:18:44Z | [
"python",
"matplotlib"
] |
Sort a list of lists based on an if/else condition in Python 3.5 | 40,115,654 | <p>I need to sort a list containing nested lists based on a condition. The condition is: if first index is 0, sort on index nr 7. Then if second index is 0, sort on index nr 8. So the below list (unsorted):</p>
<pre><code>[[11, 37620, 'mat', 'xxx', 1, 28.5, 0, 11, 37620, 'Arp', 'xxx', 1, 28],
[10, 24210, 'Skatt', 'xx... | 0 | 2016-10-18T18:38:22Z | 40,115,739 | <p>Write a function to contain your logic for finding which column to sort on:</p>
<pre><code>def sort_col_value(row):
# if first index is 0, sort on index nr 7.
if row[0] == 0:
return row[7]
# Then if second index is 0, sort on index nr 8
if row[1] == 0:
return row[8]
return row[0... | 2 | 2016-10-18T18:42:24Z | [
"python",
"list",
"sorting",
"python-3.5"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.