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 |
|---|---|---|---|---|---|---|---|---|---|
Change the values of string in parenthesis which starts with Varchar | 39,489,971 | <p>I have a python variable (type unicode), which holds a query statement:</p>
<pre><code>CREATE TABLE afg_temp (tadm1_code INTEGER NOT NULL, tadm1_name VARCHAR(10) NOT NULL, test VARCHAR(4));
</code></pre>
<p>I need to replace all the values in each VARCHAR occurence with 254.
Initially I thought it would be enough ... | -2 | 2016-09-14T12:03:00Z | 39,490,059 | <p>with regexp:</p>
<pre><code>import re
query = 'CREATE TABLE afg_temp (tadm1_code INTEGER NOT NULL, tadm1_name VARCHAR(10) NOT NULL, test VARCHAR(4));'
print re.sub(r'VARCHAR\([0-9]*\)','VARCHAR(254)',query)
</code></pre>
| 4 | 2016-09-14T12:07:50Z | [
"python",
"regex"
] |
Change the values of string in parenthesis which starts with Varchar | 39,489,971 | <p>I have a python variable (type unicode), which holds a query statement:</p>
<pre><code>CREATE TABLE afg_temp (tadm1_code INTEGER NOT NULL, tadm1_name VARCHAR(10) NOT NULL, test VARCHAR(4));
</code></pre>
<p>I need to replace all the values in each VARCHAR occurence with 254.
Initially I thought it would be enough ... | -2 | 2016-09-14T12:03:00Z | 39,490,083 | <pre><code>import re
s='''CREATE TABLE afg_temp (tadm1_code INTEGER NOT NULL, tadm1_name VARCHAR(10) NOT NULL, test VARCHAR(4));'''
re.sub('VARCHAR\([0-9]{1,3}\)','VARCHAR(254)',s)
</code></pre>
<p>There are plenty of other solutions and you don't even need python for this. The easiest would be to use sed.</p>
| 1 | 2016-09-14T12:09:00Z | [
"python",
"regex"
] |
Kivy - My ScrollView doesn't scroll | 39,489,980 | <p>I'm having problems in my Python application with Kivy library. In particular I'm trying to create a scrollable list of elements in a TabbedPanelItem, but I don't know why my list doesn't scroll.</p>
<p>Here is my kv file:</p>
<pre><code>#:import sm kivy.uix.screenmanager
ScreenManagement:
transition: sm.Fade... | 0 | 2016-09-14T12:03:22Z | 39,490,992 | <p>I Myself haven't used kivy for a while but if I remember exacly:
Because layout within ScrollView should be BIGGER than scroll view
ex ScrollView width: 1000px, GridView 1100px.
So it will be possible to scroll it by 100px</p>
| 1 | 2016-09-14T12:54:43Z | [
"android",
"python",
"scroll",
"kivy",
"kivy-language"
] |
How to make any method from view/model as celery task | 39,490,052 | <p>I have some of the analytics methods in <code>models.py</code> under <code>class Analytics</code> (e.g: <code>Analytics.record_read_analytics()</code>). And we are calling those methods for recording analytics, which doesn't need to be synchronous. Currently it's affecting rendering of each request so decided to add... | 0 | 2016-09-14T12:07:36Z | 39,490,279 | <p>You may achieve it like:</p>
<pre><code>analytics = Analytics() # Object of Analytics class
Analytics.record_read_analytics.delay()
</code></pre>
<p>Also, you need to add <code>@task</code> decorator with the <code>record_read_analytics</code> function</p>
| 0 | 2016-09-14T12:18:43Z | [
"python",
"django",
"celery",
"django-celery"
] |
How to make any method from view/model as celery task | 39,490,052 | <p>I have some of the analytics methods in <code>models.py</code> under <code>class Analytics</code> (e.g: <code>Analytics.record_read_analytics()</code>). And we are calling those methods for recording analytics, which doesn't need to be synchronous. Currently it's affecting rendering of each request so decided to add... | 0 | 2016-09-14T12:07:36Z | 39,490,334 | <p>You can create tasks out of <a href="http://docs.celeryproject.org/en/latest/reference/celery.contrib.methods.html" rel="nofollow">methods</a>. The bad thing about this is that the object itself gets passed around (because the state of the object in worker has to be same as the state of the caller) in order for it t... | 1 | 2016-09-14T12:20:45Z | [
"python",
"django",
"celery",
"django-celery"
] |
Manipulating copied numpy array without changing the original | 39,490,068 | <p>I am trying to manipulate a numpy array that contains data stored in an other array. So far, when I change a value in my array, both of the arrays get values changed:</p>
<pre><code> import numpy as np
from astropy.io import fits
image = fits.getdata("randomImage.fits")
fft = np.fft.fft2(image)
fftMod = np.cop... | 0 | 2016-09-14T12:08:09Z | 39,490,284 | <p>You misunderstood the usage of the .all() method.
It yields True if all elements of an array are not 0. This seems to be the case in both your arrays or in neither of them. </p>
<p>Since one is the double of the other, they definetly give the same result to the .all() method (both True or both False)</p>
<p><stro... | 3 | 2016-09-14T12:18:50Z | [
"python",
"arrays",
"numpy"
] |
Pandas fuzzy detect duplicates | 39,490,190 | <p>How can use fuzzy matching in pandas to detect duplicate rows (efficiently) </p>
<p><a href="http://i.stack.imgur.com/yZxK6.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/yZxK6.jpg" alt="enter image description here"></a></p>
<p>How to find duplicates of one column vs. all the other ones without a gigantic... | 1 | 2016-09-14T12:13:46Z | 39,553,585 | <p>Not pandas specific, but within the python ecosystem the <a href="https://github.com/datamade/dedupe" rel="nofollow">dedupe python library</a> would seem to do what you want. In particular, it allows you to compare each column of a row separately and then combine the information into a single probability score of a ... | 1 | 2016-09-18T02:52:09Z | [
"python",
"pandas",
"fuzzy-search",
"locality-sensitive-hash"
] |
How can we use a loop to create checkbuttons from an array and print the values of the selected checkbutton(s)? | 39,490,247 | <p>I have an array of strings, and I want to be able to use a loop to quickly create a lot of checkbuttons for them, because the idea is that the user can later add/delete items in the array, so it should be adaptable. </p>
<p>I'm not even sure if this is possible with the method I'm trying to use. The problem with th... | 1 | 2016-09-14T12:17:00Z | 39,492,563 | <p>You can create for each <code>CheckBox</code> a <code>StringVar</code> and save them in a list then Use <code>get</code> method on <code>StringVar</code> to get its value (<code>lambda</code> is used to passe the index in array list): </p>
<pre><code>from Tkinter import *
Window = Tk()
class Test:
def __ini... | 0 | 2016-09-14T14:08:05Z | [
"python",
"tkinter"
] |
Sort multiple dictionaries identically, based on a specific order defined by a list | 39,490,257 | <p>I had a special case where multiple existing dictionaries had to be sorted based on the exact order of items in a list (not alphabetical). So for example the dictionaries were:</p>
<pre><code>dict_one = {"LastName": "Bar", "FirstName": "Foo", "Address": "Example Street 101", "Phone": "012345678"}
dict_two = {"Phone... | 1 | 2016-09-14T12:17:27Z | 39,490,258 | <p>I had a bit of hard time to find any good answers in Stack Overflow for this case, but eventually I got the sorting working, which I could use to create the file. The header row can simply be taken directly from the <code>data_order</code> list below. Here's how I did it - hope it helps someone:</p>
<pre><code>from... | 0 | 2016-09-14T12:17:27Z | [
"python",
"python-3.x",
"sorting"
] |
Sort multiple dictionaries identically, based on a specific order defined by a list | 39,490,257 | <p>I had a special case where multiple existing dictionaries had to be sorted based on the exact order of items in a list (not alphabetical). So for example the dictionaries were:</p>
<pre><code>dict_one = {"LastName": "Bar", "FirstName": "Foo", "Address": "Example Street 101", "Phone": "012345678"}
dict_two = {"Phone... | 1 | 2016-09-14T12:17:27Z | 39,492,882 | <p>This can be achieved in a one liner, although it is harder to read. In case it is useful for someone:</p>
<pre><code>print [OrderedDict([(key, d[key]) for key in data_order]) for d in [dict_one, dict_two, dict_three]]
</code></pre>
| 0 | 2016-09-14T14:22:52Z | [
"python",
"python-3.x",
"sorting"
] |
Sort multiple dictionaries identically, based on a specific order defined by a list | 39,490,257 | <p>I had a special case where multiple existing dictionaries had to be sorted based on the exact order of items in a list (not alphabetical). So for example the dictionaries were:</p>
<pre><code>dict_one = {"LastName": "Bar", "FirstName": "Foo", "Address": "Example Street 101", "Phone": "012345678"}
dict_two = {"Phone... | 1 | 2016-09-14T12:17:27Z | 39,492,922 | <p>This is a classic use case for <a href="https://docs.python.org/3/library/csv.html#csv.DictWriter" rel="nofollow"><code>csv.DictWriter</code></a>, because your expected output is CSV-like (semi-colon delimiters instead of commas is supported) which would handle all of this for you, avoiding the need for ridiculous w... | 0 | 2016-09-14T14:24:48Z | [
"python",
"python-3.x",
"sorting"
] |
Python objects in other classes or separate? | 39,490,657 | <p>I have an application I'm working on in <strong>Python 2.7</strong> which has several classes that need to interact with each other before returning everything back to the main program for output. </p>
<p>So a brief example of the code would be:</p>
<pre><code>class foo_network():
"""Handles all network funct... | -1 | 2016-09-14T12:38:18Z | 39,491,190 | <p>You can use modules. And have every class in one module.
and then you can use import to import only a particular method from that class.
And all you need to do for that is create a directory with the name same as you class name and put a <strong>init</strong>.py file in that directory which tells python to consider ... | 0 | 2016-09-14T13:03:25Z | [
"python",
"oop",
"memory-management",
"python-performance"
] |
runserver.py giving Module Error while setup MDM server code | 39,490,673 | <p>I am trying to setup this git code on Ubuntu server
<a href="https://github.com/jessepeterson/commandment" rel="nofollow">https://github.com/jessepeterson/commandment</a></p>
<p>I have managed to install the required packages
<a href="https://github.com/jessepeterson/commandment/blob/master/requirements.txt" rel="n... | 1 | 2016-09-14T12:39:05Z | 39,490,814 | <p>Please check if apns module is installed by <code>pip list</code></p>
<p>If it is not installed, Please install apns module by <code>pip install apns</code></p>
<p>If already part installed, check if it is part of your virtualenv PYTHONPATH, if you are using virtualenv</p>
| 1 | 2016-09-14T12:45:55Z | [
"python",
"ios",
"mdm"
] |
How to iterate each word through nltk synsets and store misspelled words in separate list? | 39,490,777 | <p>I am trying to take a text file with messages and iterate each word through NLTK wordnet synset function. I want to do this because I want to create a list of mispelled words. For example if I do: </p>
<pre><code>wn.synsets('dog')
</code></pre>
<p>I get output:</p>
<pre><code>[Synset('dog.n.01'),
Synset('frump.n... | 1 | 2016-09-14T12:44:14Z | 39,718,953 | <p>You already have the pseudocode in your explanation, you can just code it as you have explained, as follows:</p>
<pre><code>misspelled_words = [] # The list to store misspelled words
for word in chat_messages_tokenized: # loop through each word
if not wn.synset(word): # if there is no... | 1 | 2016-09-27T07:45:49Z | [
"python",
"iteration",
"nltk",
"python-3.5",
"wordnet"
] |
Django submit form using Request Module, CSRF Verification failed | 39,490,782 | <p>I am trying to submit a form of django application using Python request module, however it gives me the following error</p>
<blockquote>
<p>Error Code: 403<br>
Message: CSRF verification failed. Request aborted.</p>
</blockquote>
<p>I tried to convert the in JSON using <code>json.dumps()</code> and sent the re... | 0 | 2016-09-14T12:44:21Z | 39,491,919 | <p>I was providing the other arguments in the header and I think this is creating the issue. I removed all other arguments and kept only referrer and now it's working. </p>
<pre><code>import requests
session = requests.session()
session.get("http://localhost:8000/autoflex/addresult/")
csrf_token = session.cookies["csr... | 0 | 2016-09-14T13:35:20Z | [
"python",
"django",
"python-2.7",
"django-forms",
"request"
] |
Searching JSON, Returning String within the JSON Structure | 39,490,838 | <p>I have a set of JSON data that looks simular to this:</p>
<pre><code>{"executions": [
{
"id": 17,
"orderId": 16,
"executionStatus": "1",
"cycleId": 5,
"projectId": 15006,
"issueId": 133038,
"issueKey": "QTCMP-8",
"label": "",
"component": "",
"projectKey": "QTCMP",
"executionDefectCount": 0,
... | 1 | 2016-09-14T12:46:52Z | 39,490,944 | <p>A simple iteration with a condition will do the job:</p>
<pre><code>for execution in data['executions']:
if "QTCMP" in execution['issueKey']:
print(execution["id"])
# -> 17
# -> 14
</code></pre>
| 0 | 2016-09-14T12:52:13Z | [
"python",
"json"
] |
Searching JSON, Returning String within the JSON Structure | 39,490,838 | <p>I have a set of JSON data that looks simular to this:</p>
<pre><code>{"executions": [
{
"id": 17,
"orderId": 16,
"executionStatus": "1",
"cycleId": 5,
"projectId": 15006,
"issueId": 133038,
"issueKey": "QTCMP-8",
"label": "",
"component": "",
"projectKey": "QTCMP",
"executionDefectCount": 0,
... | 1 | 2016-09-14T12:46:52Z | 39,490,956 | <p>You can't do this in computational order of O(1), at least with what it is like now. The following is a solution with O(n) complexity for each search.</p>
<pre><code>id = None
for dic in executions:
if dic['issueKey'] == query:
id = dic['id']
break
</code></pre>
<p>Doing this in O(1), need a pr... | 1 | 2016-09-14T12:53:11Z | [
"python",
"json"
] |
Searching JSON, Returning String within the JSON Structure | 39,490,838 | <p>I have a set of JSON data that looks simular to this:</p>
<pre><code>{"executions": [
{
"id": 17,
"orderId": 16,
"executionStatus": "1",
"cycleId": 5,
"projectId": 15006,
"issueId": 133038,
"issueKey": "QTCMP-8",
"label": "",
"component": "",
"projectKey": "QTCMP",
"executionDefectCount": 0,
... | 1 | 2016-09-14T12:46:52Z | 39,491,098 | <p>You can get the list of all ids as:</p>
<pre><code>>>> [item['id'] for item in my_json['executions'] if item['issueKey'].startswith('QTCMP')]
[17, 14]
</code></pre>
<p>where <code>my_json</code> is the variable storing your JSON structure</p>
<p><strong>Note:</strong> I am using <code>item['issueKey'].st... | 0 | 2016-09-14T12:59:16Z | [
"python",
"json"
] |
Django: app level variables | 39,490,843 | <p>I've created a Django-rest-framework app. It exposes some API which does some get/set operations in the MySQL DB. </p>
<p>I have a requirement of making an HTTP request to another server and piggyback this response along with the usual response. I'm trying to use a self-made HTTP connection pool to make HTTP reques... | 1 | 2016-09-14T12:46:57Z | 39,491,806 | <p>A possible solution is to implement a custom Django middleware, as described in <a href="https://docs.djangoproject.com/ja/1.9/topics/http/middleware/" rel="nofollow">https://docs.djangoproject.com/ja/1.9/topics/http/middleware/</a>.</p>
<p>You could initialize the HTTP connection pool in the middleware's <strong>_... | 0 | 2016-09-14T13:30:24Z | [
"python",
"django",
"django-rest-framework",
"global-variables"
] |
Drawing sine curve in Memory-Used view of Task Manager on Windows 10? | 39,490,934 | <p>I am trying to write a simple proof-of-concept script on Windows 10 that let's me draw the absolute of a sin curve in the task manager memory window.</p>
<p>My code is as follows:</p>
<pre><code>import time
import math
import gc
import sys
x = 1
string_drawer = []
while True:
#Formula for the eqaution (sin ... | 3 | 2016-09-14T12:51:59Z | 39,520,004 | <pre><code>sys.getsizeof(string_drawer)
</code></pre>
<blockquote>
<p>Return the size of an object in bytes. The object can be any type of
object. All built-in objects will return correct results, but this
does not have to hold true for third-party extensions as it is
implementation specific.</p>
<p><stro... | 1 | 2016-09-15T20:39:56Z | [
"python",
"memory-management",
"garbage-collection"
] |
how to stop multiple python script running if any script has error | 39,490,989 | <p>I have python script (installer.py) which runs multiple python and shell programs:</p>
<pre><code>print "Going to run Script1"
os.system("python script1.py")
print "Going to run Script2"
os.system("python script2.py")
</code></pre>
<p>But I found that even if script1.py is not run because of its error, it simpl... | 1 | 2016-09-14T12:54:40Z | 39,491,071 | <p><code>os.system</code> will return the exit status of the system call. Just check to see if your command executed correctly.</p>
<pre><code>ret = os.system('python script1.py')
if ret != 0:
# call failed
raise Exception("System call failed with error code %d" % ret)
ret = os.system('python script2.py')
if... | 0 | 2016-09-14T12:58:25Z | [
"python",
"linux"
] |
Naturaltime with minutes, hours, days and weeks | 39,491,030 | <p>I use naturaltime in my Django application.</p>
<p>How can I display only time in minutes, then hours, then days, then weeks?</p>
<p>Here is my code:</p>
<pre><code>{{ obj.pub_date|naturaltime }}
</code></pre>
| 0 | 2016-09-14T12:56:49Z | 39,491,547 | <p>I use two custom filters to solve a very similar problem using babel and pytz. I write "Today" or "Yesterday" plus the time. You're welcome to use my code any way you like. </p>
<p>My template code is two usages, one for writing "Today", "Yesterday", or the date if it was even earlier. </p>
<p><code>{{ scored_docu... | 0 | 2016-09-14T13:19:01Z | [
"python",
"django"
] |
Replacing characters of string in a list | 39,491,132 | <p>I am replacing the character and/or string in l3 by comparing it with l1 and l2 . What output I am getting and what output I like to get is shown below.</p>
<p>my code </p>
<pre><code>l1 = ["Jai","Sharath","Ravi","Aditya"]
l2 = ["Singh","Kumar","Sharma","Rao"]
l3 = ["J.Singh","Sharath_K","R-Sharma","Rao_Aditya"]
f... | 0 | 2016-09-14T13:01:01Z | 39,491,156 | <p>Strings are immutable. <code>replace</code> does not work in-place, it returns a new string. You need to reallocate that new string to the original name.</p>
<pre><code>if x in z:
z = z.replace(x,"Firstname")
</code></pre>
<p>(Also, please use more than one space indentation.)</p>
| 0 | 2016-09-14T13:02:14Z | [
"python",
"python-3.x"
] |
Replacing characters of string in a list | 39,491,132 | <p>I am replacing the character and/or string in l3 by comparing it with l1 and l2 . What output I am getting and what output I like to get is shown below.</p>
<p>my code </p>
<pre><code>l1 = ["Jai","Sharath","Ravi","Aditya"]
l2 = ["Singh","Kumar","Sharma","Rao"]
l3 = ["J.Singh","Sharath_K","R-Sharma","Rao_Aditya"]
f... | 0 | 2016-09-14T13:01:01Z | 39,491,558 | <p>Consider your use of <code>elif</code>. If your first condition triggers, replacing the first name, will the last condition trigger to replace the last name? You may want to try two <code>if</code> <code>else</code> structures. </p>
<p>Consider the following:</p>
<pre><code>z = 'abc'
if z[0] == 'a':
z = z.r... | 0 | 2016-09-14T13:19:29Z | [
"python",
"python-3.x"
] |
Python Pandas get_dummies() limitation. Doesnt convert all columns | 39,491,225 | <p>I have 6 columns in my dataframe. 2 of them have about 3K unique values. When I use <code>get_dummies()</code> on the entire dataframe or just one those 2 columns what gets returned is the exact same column with 3k values. <code>get_dummies</code> fails to dummy-fy the bigger columns.
Some columns do get one-hot en... | 1 | 2016-09-14T13:05:12Z | 39,492,784 | <p>It appears to work as intended for me.</p>
<p>Consider the series <code>s</code> of random 3 character strings</p>
<pre><code>import pandas as pd
import numpy as np
from string import lowercase
np.random.seed([3,1415])
s = pd.DataFrame(np.random.choice(list(lowercase), (10000, 3))).sum(1)
s.nunique()
7583
</cod... | 1 | 2016-09-14T14:18:06Z | [
"python",
"pandas",
"one-hot-encoding"
] |
Pandas + Python: More efficient code | 39,491,259 | <p>This is my code:</p>
<pre><code>import pandas as pd
import os
import glob as g
archivos = g.glob('C:\Users\Desktop\*.csv')
for archiv in archivos:
nombre = os.path.splitext(archiv)[0]
df = pd.read_csv(archiv, sep=",")
d = pd.to_datetime(df['DATA_LEITURA'], format="%Y%m%d")
df['FECHA_LECTURA'... | -2 | 2016-09-14T13:06:53Z | 39,492,970 | <p>Generally you want to <a href="http://stackoverflow.com/a/7837947/12663">avoid for loops in pandas</a>.
For example, the first loop where you calculate total consumption and days could be rewritten as a groupby apply something like:</p>
<pre><code>def last_minus_first(df):
columns_of_interest = df[['VALOR_LEITU... | 1 | 2016-09-14T14:26:55Z | [
"python",
"pandas"
] |
What is the range of valid dates for the datetime module? | 39,491,327 | <p>I'm playing with the Python <a href="https://docs.python.org/2/library/datetime.html" rel="nofollow"><code>datetime</code></a> module. I'm using it to determine the day of the week for a given date. Python conveniently raises a <code>ValueError</code> when the date is invalid; e.g., for February 29 on non-leap years... | -1 | 2016-09-14T13:09:58Z | 39,491,365 | <p>Check <a href="https://docs.python.org/2/library/datetime.html#datetime.date.min"><code>date.min</code></a> and <a href="https://docs.python.org/2/library/datetime.html#datetime.date.max"><code>date.max</code></a>:</p>
<pre><code>>>> from datetime import date
>>> date.min
datetime.date(1, 1, 1)
&g... | 5 | 2016-09-14T13:11:36Z | [
"python",
"date",
"datetime",
"calendar"
] |
map() is returning only part of arguments | 39,491,355 | <p>I have the following code:</p>
<pre><code>a = '0'
b = '256'
mod_add = ['300', '129', '139']
list(map(lambda a, b, x: (a < x) and (x < b), a, b, mod_add))
</code></pre>
<p>I'd like to check every element in mod_add, but </p>
<pre><code>list(map(lambda a, b, x: (a < x) and (x < b), a, b, mod_add))
</cod... | 1 | 2016-09-14T13:11:17Z | 39,491,491 | <p><code>a</code> and <code>b</code> are strings, they will be rightly treated as <em>iterables</em> by <code>map</code>, not constants as you intend. You should either use a list comprehension or not pass <code>a</code> and <code>b</code> as parameters to <code>map</code>:</p>
<pre><code>>>> [a < x < b... | 2 | 2016-09-14T13:16:47Z | [
"python",
"python-3.x"
] |
map() is returning only part of arguments | 39,491,355 | <p>I have the following code:</p>
<pre><code>a = '0'
b = '256'
mod_add = ['300', '129', '139']
list(map(lambda a, b, x: (a < x) and (x < b), a, b, mod_add))
</code></pre>
<p>I'd like to check every element in mod_add, but </p>
<pre><code>list(map(lambda a, b, x: (a < x) and (x < b), a, b, mod_add))
</cod... | 1 | 2016-09-14T13:11:17Z | 39,491,528 | <p>If you really have to use <code>map</code>:</p>
<pre><code>list(map(lambda x: (a < x) and (x < b), mod_add))
</code></pre>
<p>Edit:</p>
<p>In response to the desire to <code>map</code> only one element from the list, it really doesn't make such sense to me to do that. But if that's what you wish to do, you ... | 2 | 2016-09-14T13:18:31Z | [
"python",
"python-3.x"
] |
map() is returning only part of arguments | 39,491,355 | <p>I have the following code:</p>
<pre><code>a = '0'
b = '256'
mod_add = ['300', '129', '139']
list(map(lambda a, b, x: (a < x) and (x < b), a, b, mod_add))
</code></pre>
<p>I'd like to check every element in mod_add, but </p>
<pre><code>list(map(lambda a, b, x: (a < x) and (x < b), a, b, mod_add))
</cod... | 1 | 2016-09-14T13:11:17Z | 39,491,659 | <p>This is really the kind of thing you should prefer list comprehensions for.</p>
<pre><code>min_, max_ = '0', '256'
# do you mean for these to be compared lexicographically?!
# be aware that '0' < '1234567890' < '256' is True
mod_add = ['300', '129', '139']
result = [min_ < mod < max_ for mod in mod_ad... | 0 | 2016-09-14T13:23:41Z | [
"python",
"python-3.x"
] |
map() is returning only part of arguments | 39,491,355 | <p>I have the following code:</p>
<pre><code>a = '0'
b = '256'
mod_add = ['300', '129', '139']
list(map(lambda a, b, x: (a < x) and (x < b), a, b, mod_add))
</code></pre>
<p>I'd like to check every element in mod_add, but </p>
<pre><code>list(map(lambda a, b, x: (a < x) and (x < b), a, b, mod_add))
</cod... | 1 | 2016-09-14T13:11:17Z | 39,491,749 | <pre><code>a = '0'
b = '256'
mod_add['300', '129', '139']
map(lambda x: int(a)<int(x)<int(b), mod_add)
</code></pre>
<p>Output :</p>
<pre><code>[False, True, True]
</code></pre>
| 0 | 2016-09-14T13:27:40Z | [
"python",
"python-3.x"
] |
Python/Json:Expecting property name enclosed in double quotes | 39,491,420 | <p>I've been trying to figure out a good way to load JSON objects in Python.
I send this json data:</p>
<pre><code>{'http://example.org/about': {'http://purl.org/dc/terms/title': [{'type': 'literal', 'value': "Anna's Homepage"}]}}
</code></pre>
<p>to the backend where it will be received as a string then I used <code... | 0 | 2016-09-14T13:13:52Z | 39,491,599 | <p>Quite simply, that string is not valid JSON. As the error says, JSON documents need to use double quotes.</p>
<p>You need to fix the source of the data.</p>
| 1 | 2016-09-14T13:21:19Z | [
"python",
"json",
"parsing"
] |
Python/Json:Expecting property name enclosed in double quotes | 39,491,420 | <p>I've been trying to figure out a good way to load JSON objects in Python.
I send this json data:</p>
<pre><code>{'http://example.org/about': {'http://purl.org/dc/terms/title': [{'type': 'literal', 'value': "Anna's Homepage"}]}}
</code></pre>
<p>to the backend where it will be received as a string then I used <code... | 0 | 2016-09-14T13:13:52Z | 39,491,607 | <p>JSON strings must use double quotes. The JSON python library enforces this so you are unable to load your string. Your data needs to look like this:</p>
<pre><code>{"http://example.org/about": {"http://purl.org/dc/terms/title": [{"type": "literal", "value": "Anna's Homepage"}]}}
</code></pre>
<p>If that's not so... | 0 | 2016-09-14T13:21:32Z | [
"python",
"json",
"parsing"
] |
Python/Json:Expecting property name enclosed in double quotes | 39,491,420 | <p>I've been trying to figure out a good way to load JSON objects in Python.
I send this json data:</p>
<pre><code>{'http://example.org/about': {'http://purl.org/dc/terms/title': [{'type': 'literal', 'value': "Anna's Homepage"}]}}
</code></pre>
<p>to the backend where it will be received as a string then I used <code... | 0 | 2016-09-14T13:13:52Z | 39,491,613 | <p>This:</p>
<pre><code>{'http://example.org/about': {'http://purl.org/dc/terms/title': [{'type': 'literal', 'value': "Anna's Homepage"}]}}
</code></pre>
<p>is not JSON.<br>
This:</p>
<pre><code>{"http://example.org/about": {"http://purl.org/dc/terms/title": [{"type": "literal", "value": "Anna's Homepage"}]}}
</code... | 2 | 2016-09-14T13:21:43Z | [
"python",
"json",
"parsing"
] |
Python/Json:Expecting property name enclosed in double quotes | 39,491,420 | <p>I've been trying to figure out a good way to load JSON objects in Python.
I send this json data:</p>
<pre><code>{'http://example.org/about': {'http://purl.org/dc/terms/title': [{'type': 'literal', 'value': "Anna's Homepage"}]}}
</code></pre>
<p>to the backend where it will be received as a string then I used <code... | 0 | 2016-09-14T13:13:52Z | 39,491,618 | <p>I've checked your JSON data </p>
<pre><code>{'http://example.org/about': {'http://purl.org/dc/terms/title': [{'type': 'literal', 'value': "Anna's Homepage"}]}}
</code></pre>
<p>in <a href="http://jsonlint.com/" rel="nofollow">http://jsonlint.com/</a> and the results were:</p>
<pre><code>Error: Parse error on line... | 1 | 2016-09-14T13:21:51Z | [
"python",
"json",
"parsing"
] |
Python/Json:Expecting property name enclosed in double quotes | 39,491,420 | <p>I've been trying to figure out a good way to load JSON objects in Python.
I send this json data:</p>
<pre><code>{'http://example.org/about': {'http://purl.org/dc/terms/title': [{'type': 'literal', 'value': "Anna's Homepage"}]}}
</code></pre>
<p>to the backend where it will be received as a string then I used <code... | 0 | 2016-09-14T13:13:52Z | 39,491,628 | <p>As it clearly says in error, names should be enclosed in double quotes instead of single quotes. The string you pass is just not a valid JSON. It should look like</p>
<pre><code>{"http://example.org/about": {"http://purl.org/dc/terms/title": [{"type": "literal", "value": "Anna's Homepage"}]}}
</code></pre>
| 1 | 2016-09-14T13:22:23Z | [
"python",
"json",
"parsing"
] |
Clustering points based on their function values and proximity | 39,491,440 | <p>I have many points <code>X</code> and their function values <code>f</code> stored in <code>numpy</code> arrays. I want to find <strong>all points</strong> in <code>X</code> that don't have a better point (smaller <code>f</code> value) within a distance <code>r</code>.</p>
<p><code>X</code> is hundreds of thousands ... | 1 | 2016-09-14T13:14:30Z | 39,491,598 | <p>You could partition the space so that you could ignore partitions wholly outside the radius for the point being tested.</p>
<p>You could also order the points by f, so you don't need to scan those with smaller values.</p>
| 2 | 2016-09-14T13:21:14Z | [
"python",
"numpy",
"scipy",
"cluster-analysis"
] |
Clustering points based on their function values and proximity | 39,491,440 | <p>I have many points <code>X</code> and their function values <code>f</code> stored in <code>numpy</code> arrays. I want to find <strong>all points</strong> in <code>X</code> that don't have a better point (smaller <code>f</code> value) within a distance <code>r</code>.</p>
<p><code>X</code> is hundreds of thousands ... | 1 | 2016-09-14T13:14:30Z | 39,493,588 | <p>I think one can sum this up as:</p>
<p>Use k-nearest neighbor to build a kdtree. Query the tree for points close to your query point with radius, check their function values.</p>
<pre><code>x=scipy.random.rand(10000,2) # sample data
f = exp(-x[:,0]**2) # sample function values
K=scipy.spatial.KDTree(x) # generate ... | 1 | 2016-09-14T14:53:22Z | [
"python",
"numpy",
"scipy",
"cluster-analysis"
] |
Clustering points based on their function values and proximity | 39,491,440 | <p>I have many points <code>X</code> and their function values <code>f</code> stored in <code>numpy</code> arrays. I want to find <strong>all points</strong> in <code>X</code> that don't have a better point (smaller <code>f</code> value) within a distance <code>r</code>.</p>
<p><code>X</code> is hundreds of thousands ... | 1 | 2016-09-14T13:14:30Z | 39,501,444 | <p>You can significantly reduce the number of distance computation by keeping a record. For instance, if j is a neighbor of a center i and it has a larger f value, then j can never be a center since one of its neighbors is i which has a smaller f value. Please check the following and let me know if you need clarificati... | 1 | 2016-09-15T00:15:19Z | [
"python",
"numpy",
"scipy",
"cluster-analysis"
] |
Identify string in dataframe and replace content using Python | 39,491,482 | <p>I have a csv file and I loaded using Pandas. Firstly I decide to rename the columns. The dataframe is this:</p>
<p><a href="http://i.stack.imgur.com/oFXmJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/oFXmJ.png" alt="enter image description here"></a></p>
<p>My goal is to check if all the columns of each ... | 1 | 2016-09-14T13:16:30Z | 39,492,104 | <p>IIUC, you can use <code>applymap</code> with <code>str.split</code> to split on <code>\n</code> char and take the last split:</p>
<pre><code>df['E'] = df['E'].astype(str)
df.applymap(lambda x: x.split('\n')[-1])
</code></pre>
<p><a href="http://i.stack.imgur.com/26rXK.png" rel="nofollow"><img src="http://i.stack.i... | 3 | 2016-09-14T13:44:33Z | [
"python",
"pandas",
"replace",
"identity"
] |
Identify string in dataframe and replace content using Python | 39,491,482 | <p>I have a csv file and I loaded using Pandas. Firstly I decide to rename the columns. The dataframe is this:</p>
<p><a href="http://i.stack.imgur.com/oFXmJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/oFXmJ.png" alt="enter image description here"></a></p>
<p>My goal is to check if all the columns of each ... | 1 | 2016-09-14T13:16:30Z | 39,492,166 | <p>You can use a regular expression to remove anything before a '\n' (or any other character you specify) from a string:</p>
<pre><code>import re
str="onetwo\nthree"
print(str)
test = re.search('(?<=\\n)\w+', str)
print(test.group(0))
</code></pre>
| 3 | 2016-09-14T13:47:01Z | [
"python",
"pandas",
"replace",
"identity"
] |
Identify string in dataframe and replace content using Python | 39,491,482 | <p>I have a csv file and I loaded using Pandas. Firstly I decide to rename the columns. The dataframe is this:</p>
<p><a href="http://i.stack.imgur.com/oFXmJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/oFXmJ.png" alt="enter image description here"></a></p>
<p>My goal is to check if all the columns of each ... | 1 | 2016-09-14T13:16:30Z | 39,492,991 | <p><strong><em>Solution</em></strong><br>
Use <code>str</code> accessor with <code>split</code> after <code>stack</code> to get a series.</p>
<pre><code>df.astype(str).stack().str.split('\n').str[-1].unstack()
</code></pre>
<p><a href="http://i.stack.imgur.com/EWhBg.png" rel="nofollow"><img src="http://i.stack.imgur.... | 3 | 2016-09-14T14:27:50Z | [
"python",
"pandas",
"replace",
"identity"
] |
Pointers vs garbage collection in Python | 39,491,706 | <p>I understand in Python that assigning a name to an object creates a reference to the object, and that when an objects' ref count goes to zero it is garbage collected. I want to understand whether I should be using pointers in my code or if allowing regular garbage collection is better.</p>
<pre><code>import time
w... | 0 | 2016-09-14T13:25:48Z | 39,491,998 | <p>There is no notion of pointer in pure Python. What you are referring to is the <code>ctypes</code> module, it is meant to interact with code actually written and compiled in a C compatible language (where pointers actually exist).</p>
<p>So your question is invalid.</p>
| 0 | 2016-09-14T13:39:04Z | [
"python",
"pointers",
"garbage-collection",
"ctypes"
] |
get infinity input PIL (python) | 39,491,724 | <p>I'm writing a program that converts image to png and converts size to 512,
I want to get more input. </p>
<pre><code>from PIL import Image
import string
import random
put = input("enter your image path:")
im = Image.open(put)
size = (512,512)
if im.size > size:
im.thumbnail(size,Image.ANTIALIAS)
el... | 0 | 2016-09-14T13:26:24Z | 39,491,869 | <p>This will loop, asking for another image path to resize, until you enter an empty string:</p>
<pre><code>from PIL import Image
import string
import random
while True:
put = input("enter your image path:")
if not put.strip(): break
im = Image.open(put)
size = (512,512)
if im.size > size:
... | 0 | 2016-09-14T13:33:06Z | [
"python",
"input",
"python-imaging-library",
"pillow"
] |
get infinity input PIL (python) | 39,491,724 | <p>I'm writing a program that converts image to png and converts size to 512,
I want to get more input. </p>
<pre><code>from PIL import Image
import string
import random
put = input("enter your image path:")
im = Image.open(put)
size = (512,512)
if im.size > size:
im.thumbnail(size,Image.ANTIALIAS)
el... | 0 | 2016-09-14T13:26:24Z | 39,491,968 | <p>You have been mislead by the "input() function. Its does not do what you would hope a function called input will do. input executes what you type as code.</p>
<p>This is so misleading that python3 changed "input()" to do the obvious and removed raw_input().</p>
<p>To read a line from the standard input you can use... | 0 | 2016-09-14T13:37:46Z | [
"python",
"input",
"python-imaging-library",
"pillow"
] |
SWIG Python C++ output array giving 'unknown type' error | 39,491,861 | <p>I am trying to use swig to wrap some c++ code to pass a numpy array back to python. I am following some examples I have seen online to use numpy.i. Here is what my code looks like.</p>
<p>I am using this as the function definition in my class header file:</p>
<pre><code>bool grabFrame(int buf_size, unsigned char *... | 0 | 2016-09-14T13:32:42Z | 39,509,531 | <p>Looks like I did not look closely enough at the answer for this post (<a href="https://stackoverflow.com/questions/36222455/swigcpython-passing-and-receiving-c-arrays">SWIG+c+Python: Passing and receiving c arrays</a>). I did not notice that swig adds the output array to the return list and just wants the size of th... | 0 | 2016-09-15T11:06:20Z | [
"python",
"c++",
"numpy",
"swig"
] |
How to clear Chrome HSTS-Cache? | 39,491,918 | <p>Bg: I am developing a host management tool recently, and I want to realize such a function: auto-delete HSTS cache of chrome-browser by click a btn.
I run <a href="https://github.com/craSH/Chrome-STS" rel="nofollow">python scripts</a> to delete HSTS-cache file of chrome. But... after I finished delete that file, I m... | 0 | 2016-09-14T13:35:18Z | 39,493,396 | <p>Easiest option would be to configure a page on your webserver with a Strict-Transport-Security header with max-age=0. Then visit that page through Chrome to clear the HSTS cache.l for that site.</p>
<p>Note some pages preload the HSTS header into Chrome's source code so cannot be cleared. But for sites you own whic... | 0 | 2016-09-14T14:44:25Z | [
"python",
"node.js",
"google-chrome",
"hsts"
] |
assign series values based on index | 39,491,956 | <p>having a simple series:</p>
<pre><code>>>> s = pd.Series(index=pd.date_range('2016-09-01','2016-09-05'))
>>> s
2016-09-01 NaN
2016-09-02 NaN
2016-09-03 NaN
2016-09-04 NaN
2016-09-05 NaN
Freq: D, dtype: float64
</code></pre>
<p>Am I able to set series values based on its index?
Let's s... | 1 | 2016-09-14T13:36:54Z | 39,492,011 | <p>You can do it like this:</p>
<pre><code>s[s.index] = s.index.dayofweek
s
Out:
2016-09-01 3
2016-09-02 4
2016-09-03 5
2016-09-04 6
2016-09-05 0
Freq: D, dtype: int32
</code></pre>
| 2 | 2016-09-14T13:39:38Z | [
"python",
"pandas",
"series"
] |
assign series values based on index | 39,491,956 | <p>having a simple series:</p>
<pre><code>>>> s = pd.Series(index=pd.date_range('2016-09-01','2016-09-05'))
>>> s
2016-09-01 NaN
2016-09-02 NaN
2016-09-03 NaN
2016-09-04 NaN
2016-09-05 NaN
Freq: D, dtype: float64
</code></pre>
<p>Am I able to set series values based on its index?
Let's s... | 1 | 2016-09-14T13:36:54Z | 39,492,223 | <p>When using <code>apply</code> on a series, you cannot access the index values. However, you can when using <code>apply</code> on a dataframe. So, convert to a dataframe first.</p>
<pre><code>s.to_frame().apply(lambda x: x.name.dayofweek, axis=1)
2016-09-01 3
2016-09-02 4
2016-09-03 5
2016-09-04 6
201... | 0 | 2016-09-14T13:50:31Z | [
"python",
"pandas",
"series"
] |
Python virtualenv ImportError: No module named _vendor | 39,492,165 | <p>I installed virtualenv on my system but when I want to actually create a virtual environment I get the following error:</p>
<pre><code>...
Successfully installed virtualenv-15.0.3
$ virtualenv venv
New python executable in /Users/.../venv/bin/python
Installing setuptools, pip, wheel...
Complete output from comman... | 0 | 2016-09-14T13:46:58Z | 39,499,763 | <p>This seems to be a problem with <code>pip</code> in combination with the native OS X version of Python. I downloaded python from <a href="https://www.python.org/" rel="nofollow">https://www.python.org/</a> and was able to install <code>pip</code> and <code>virtualenv</code> properly.</p>
| 0 | 2016-09-14T21:17:14Z | [
"python",
"pip",
"virtualenv"
] |
Scikit dendrogram: How to disable ouput? | 39,492,171 | <p>If I run <code>dendrogram</code> from the scikit libary:</p>
<pre><code>from scipy.cluster.hierarchy import linkage, dendrogram
# ...
X = np.asarray(X)
Z = linkage(X, 'single', 'correlation')
plt.figure(figsize=(16,8))
dendrogram(Z, color_threshold=0.7)
</code></pre>
<p>I get <em>a ton</em> of <code>print</code> o... | 1 | 2016-09-14T13:47:24Z | 39,492,212 | <p>to redirect print to nothing:</p>
<pre><code>import os
import sys
f = open(os.devnull, 'w')
temp = sys.stdout
sys.stdout = f
# print is disabled here
sys.stdout = temp
# print works again!
</code></pre>
| 1 | 2016-09-14T13:50:08Z | [
"python",
"scikit-learn"
] |
how to use an open file for reuse it in severals functions? | 39,492,250 | <p>I am a beginner in python and not completely bilingual, so I hope you understand me. I'm trying to develop a code where anyone can open a file, in order to display its contents in a graph matplotlib, to do this using a function called <code>read_file()</code> with which I get the data and insert a <code>Listbox</cod... | 0 | 2016-09-14T13:52:10Z | 39,492,414 | <p>You can use a global variable to keep it, declaring it as global before the variable name (f in your case). However, I don't recommend it if you are modifying the file.</p>
| 0 | 2016-09-14T14:00:11Z | [
"python",
"tkinter"
] |
how to use an open file for reuse it in severals functions? | 39,492,250 | <p>I am a beginner in python and not completely bilingual, so I hope you understand me. I'm trying to develop a code where anyone can open a file, in order to display its contents in a graph matplotlib, to do this using a function called <code>read_file()</code> with which I get the data and insert a <code>Listbox</cod... | 0 | 2016-09-14T13:52:10Z | 39,492,744 | <p>Is this the lasreader you use?
<a href="https://scipy.github.io/old-wiki/pages/Cookbook/LASReader.html" rel="nofollow">https://scipy.github.io/old-wiki/pages/Cookbook/LASReader.html</a></p>
<p>Then you should not need to give it a file handle. Just give the filename an this should do the trick. The reader will clos... | 0 | 2016-09-14T14:16:21Z | [
"python",
"tkinter"
] |
python, pandas, dataframe, rows to columns | 39,492,251 | <p>I've got a dataframe I pulled from a poorly organized SQL table. That table has unique rows for every channel
I can extract that info to a python dataframe, and intend to do further processing, but for now just want to get it to a more usable format</p>
<p>sample input:</p>
<pre><code>C = pd.DataFrame()
A = np.ar... | 1 | 2016-09-14T13:52:19Z | 39,492,419 | <p>Use <code>set_index</code> then <code>unstack</code> to pivot</p>
<pre><code>C.set_index(['date', 'chNum', 'chNam'])['value'].unstack(['chNam', 'chNum'])
</code></pre>
<p><a href="http://i.stack.imgur.com/EWjS7.png" rel="nofollow"><img src="http://i.stack.imgur.com/EWjS7.png" alt="enter image description here"></a... | 2 | 2016-09-14T14:00:20Z | [
"python",
"pandas",
"dataframe"
] |
Django Capturing multiple url parameters in request.GET | 39,492,393 | <p>i am trying to get all query parameters out of an request</p>
<pre><code>url/?animal__in=dog,cat&countries__in=france
</code></pre>
<p>I tried</p>
<pre><code>animals = request.GET.get('animal__in','')
countries = request.GET.get('countries__in','')
</code></pre>
<p>but then animals and countries are not list... | 0 | 2016-09-14T13:59:20Z | 39,492,436 | <p>Send the parameters in the proper HTTP format:</p>
<pre><code>?animal__in=dog&animal__in=cat&countries__in=france
</code></pre>
<p>and do </p>
<pre><code>request.GET.getlist('animal__in')
</code></pre>
| 0 | 2016-09-14T14:01:12Z | [
"python",
"django",
"django-admin",
"django-urls"
] |
Django Capturing multiple url parameters in request.GET | 39,492,393 | <p>i am trying to get all query parameters out of an request</p>
<pre><code>url/?animal__in=dog,cat&countries__in=france
</code></pre>
<p>I tried</p>
<pre><code>animals = request.GET.get('animal__in','')
countries = request.GET.get('countries__in','')
</code></pre>
<p>but then animals and countries are not list... | 0 | 2016-09-14T13:59:20Z | 39,492,439 | <p>request.GET.getlist('some_list_field')</p>
| 0 | 2016-09-14T14:01:24Z | [
"python",
"django",
"django-admin",
"django-urls"
] |
Django Capturing multiple url parameters in request.GET | 39,492,393 | <p>i am trying to get all query parameters out of an request</p>
<pre><code>url/?animal__in=dog,cat&countries__in=france
</code></pre>
<p>I tried</p>
<pre><code>animals = request.GET.get('animal__in','')
countries = request.GET.get('countries__in','')
</code></pre>
<p>but then animals and countries are not list... | 0 | 2016-09-14T13:59:20Z | 39,493,634 | <p>split(',') works fine, not really django though</p>
<pre><code>animals = request.GET.get('animal__in','').split(',')
countries = request.GET.get('countries__in','').split(',')
</code></pre>
| 0 | 2016-09-14T14:55:30Z | [
"python",
"django",
"django-admin",
"django-urls"
] |
Can you use self.assertRaises as an async context manager? | 39,492,402 | <p>I'd like to test that a python 3 coro fails with a particular exception, but this functionality doesn't seem to be implemented.</p>
<pre><code>async with self.assertRaises(TestExceptionType):
await my_func()
</code></pre>
<p>as the unit test fails like this:</p>
<pre><code>...
File "/Users/...../tests.py", li... | 1 | 2016-09-14T13:59:42Z | 39,494,567 | <p>Just use classic old good <code>with</code> around <code>await</code> call:</p>
<pre><code>with self.assertRaises(TestExceptionType):
await my_func()
</code></pre>
<p>It works.</p>
| 1 | 2016-09-14T15:39:33Z | [
"python",
"unit-testing",
"python-3.x",
"python-asyncio"
] |
Splitting numpy array field values that are matrices into column vectors | 39,492,405 | <p>I have the following numpy structured array:</p>
<pre><code>x = np.array([(22, 2, -1000000000.0, [1000,2000.0]), (22, 2, 400.0, [1000,2000.0])],
dtype=[('f1', '<i4'), ('f2', '<i4'), ('f3', '<f4'), ('f4', '<f4',2)])
</code></pre>
<p>As you can see, field 'f4' is a matrix:</p>
<pre><code>In [63]: x['f4'... | 5 | 2016-09-14T13:59:50Z | 39,493,124 | <p>You can do this by creating a new view (<a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.view.html" rel="nofollow">np.view</a>) of the array, which will not copy:</p>
<pre><code>import numpy as np
x = np.array([(22, 2, -1000000000.0, [1000,2000.0]),
(22, 2, 400.0, [1000,2000... | 3 | 2016-09-14T14:33:07Z | [
"python",
"numpy",
"structured-array"
] |
How to extend the logger.Logging Class? | 39,492,471 | <p>I would like to start with a basic logging class that inherits from Python's <code>logging.Logger</code> class. However, I am not sure about how I should be constructing my class so that I can establish the basics needed for customising the inherited logger.</p>
<p>This is what I have so far in my <code>logger.py</... | 0 | 2016-09-14T14:02:58Z | 39,492,759 | <p>This line</p>
<pre><code>self.logger = logging.getLogger("myApp")
</code></pre>
<p>always retrieves a reference to the same logger, so you are adding an additional handler to it every time you instantiate <code>MyLogger</code>. The following would fix your current instance, since you call <code>MyLogger</code> wit... | 1 | 2016-09-14T14:17:11Z | [
"python",
"logging"
] |
How to extend the logger.Logging Class? | 39,492,471 | <p>I would like to start with a basic logging class that inherits from Python's <code>logging.Logger</code> class. However, I am not sure about how I should be constructing my class so that I can establish the basics needed for customising the inherited logger.</p>
<p>This is what I have so far in my <code>logger.py</... | 0 | 2016-09-14T14:02:58Z | 39,509,253 | <p>At this stage, I believe that the research I have made so far and the example provided with the intention to wrap up the solution is sufficient to serve as an answer to my question. In general, there are many approaches that may be utilised to wrap a logging solution. This particular question aimed to focus on a sol... | 0 | 2016-09-15T10:52:05Z | [
"python",
"logging"
] |
how can sync clients connect to twisted server | 39,492,507 | <p>I'm new to twisted. I was wondering if I can use multiple sync clients to connect to a twisted server? Or I have to make the client twisted as well?
Thanks in advance.</p>
| 1 | 2016-09-14T14:05:16Z | 39,492,575 | <p>Clients do not have to be written w/ twisted (they don't even have to be written in Python); they just have to use a protocol that your server supports.</p>
| 2 | 2016-09-14T14:08:42Z | [
"python",
"twisted"
] |
scipy.odr output intercept and slope | 39,492,513 | <p>I'm trying to plot ad odr regression. I used the code from this post as an example:
<a href="http://stackoverflow.com/questions/27276951/linear-regression-using-scipy-odr-fails-not-full-rank-at-solution.">sample code</a>
this is my code:</p>
<pre><code># regressione ODR
import scipy.odr as odr
def funzione(B,x):
... | 0 | 2016-09-14T14:05:32Z | 39,492,978 | <p>The attribute <code>output.beta</code> holds the coefficients, which you called <code>B</code> in your code. So the slope is <code>output.beta[0]</code> and the intercept is <code>output.beta[1]</code>.</p>
<p>To draw a line, you could do something like:</p>
<pre><code># xx holds the x limits of the line to draw.... | 0 | 2016-09-14T14:27:14Z | [
"python",
"scipy",
"regression"
] |
os.path.isfile() returns false for file on network drive | 39,492,524 | <p>I am trying to test if a file exists on the network drive using os.path.isfile however it returns false even when the file is there. Any ideas why this might be or any other methods I could use to check for this file?</p>
<p>I am using Python2.7 and Windows10</p>
<p>This returns true as it should:</p>
<pre><code>... | 1 | 2016-09-14T14:05:58Z | 39,492,755 | <p>From python <a href="https://docs.python.org/2/library/os.path.html" rel="nofollow">https://docs.python.org/2/library/os.path.html</a>: </p>
<blockquote>
<p>The os.path module is always the path module suitable for the operating system Python is running on, and therefore usable for <strong>local paths</strong></p... | 1 | 2016-09-14T14:16:57Z | [
"python",
"python-2.7"
] |
Read json file and get output values using python | 39,492,541 | <p>i want to fetch the output of below json file using python </p>
<p>Json file </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-js lang-js prettyprint-override"><code>{
"Name": [
{
"n... | -10 | 2016-09-14T14:07:06Z | 39,493,905 | <p>How to print the score of Harry with python 3</p>
<pre><code>import json
from pprint import pprint
with open('test.json') as data_file:
data = json.load(data_file)
for l in data["Name"]:
if (str(l['name']) == 'Harry'):
pprint(l['Avg'])
</code></pre>
| 0 | 2016-09-14T15:06:44Z | [
"python",
"json"
] |
Python - asyncio - Wait for a future inside a callback | 39,492,549 | <p>Here is my code, I want <code>my_reader</code> to wait maximum 5 seconds for a future then do something with the <code>my_future.result()</code>. Please note that <code>my_reader</code> is <strong>not</strong> a <strong>coroutine</strong>, it is a <strong>callback</strong>.</p>
<pre><code>import asyncio, socket
so... | 1 | 2016-09-14T14:07:28Z | 39,494,263 | <p>Sorry, waiting in <strong>callbacks</strong> is impossible.
Callback should be executed instantly by definition -- otherwise event loop hangs on callback execution period.</p>
<p>Your logic should be built on <strong>coroutines</strong> but low-level <em>on_read</em> callback may inform these coroutines by setting ... | 2 | 2016-09-14T15:25:55Z | [
"python",
"python-3.5",
"python-asyncio"
] |
Python - asyncio - Wait for a future inside a callback | 39,492,549 | <p>Here is my code, I want <code>my_reader</code> to wait maximum 5 seconds for a future then do something with the <code>my_future.result()</code>. Please note that <code>my_reader</code> is <strong>not</strong> a <strong>coroutine</strong>, it is a <strong>callback</strong>.</p>
<pre><code>import asyncio, socket
so... | 1 | 2016-09-14T14:07:28Z | 39,495,380 | <p>You should run the coroutine separately and send data to it from the callback via Queue.</p>
<p>Look on this answer:</p>
<p><a href="http://stackoverflow.com/a/29475218/1112457">http://stackoverflow.com/a/29475218/1112457</a></p>
| 0 | 2016-09-14T16:24:49Z | [
"python",
"python-3.5",
"python-asyncio"
] |
How to turn an string into an integer? | 39,492,631 | <p>I am doing a little code for my programming class and we need to make a program that calculates the cost of building a desk. I need help changing my DrawerAmount to an integer, not a string!</p>
<pre><code>def Drawers():
print("How many drawers are there?")
DrawerAmount = input(int)
print("Okay, I accept that the t... | -6 | 2016-09-14T14:11:15Z | 39,492,748 | <blockquote>
<p>I need help changing my DrawerAmount to an integer, not a string!</p>
</blockquote>
<p>Try this:</p>
<pre><code>v = int(DrawerAmount)
</code></pre>
| 0 | 2016-09-14T14:16:30Z | [
"python",
"python-3.x"
] |
How to turn an string into an integer? | 39,492,631 | <p>I am doing a little code for my programming class and we need to make a program that calculates the cost of building a desk. I need help changing my DrawerAmount to an integer, not a string!</p>
<pre><code>def Drawers():
print("How many drawers are there?")
DrawerAmount = input(int)
print("Okay, I accept that the t... | -6 | 2016-09-14T14:11:15Z | 39,493,375 | <pre><code>def Drawers():
draweramount = input("How many drawers are there?")
print("Okay, I accept that the total amount of drawers is " + draweramount + ".")
return int(draweramount)
def Desk():
desktype = input("What type of wood is your desk?")
print("Alright, your desk is made of " + deskt... | 0 | 2016-09-14T14:43:39Z | [
"python",
"python-3.x"
] |
pyodbc module does not work with Python3 | 39,492,762 | <p>I have just transitioned to a Mac (from Win) and I cannot find the proper way to make a script work (it did on Win).</p>
<p>I am using <code>import pyodbc</code> on the first line and I get the "No module .." error.</p>
<p><em>Later Edit</em>: I changed the first line to <code>import pypyodbc</code></p>
<p>If I e... | 0 | 2016-09-14T14:17:26Z | 39,492,910 | <p>Module pyobdc is distributed for Python3. You can check that on its <a href="https://pypi.python.org/pypi/pyodbc" rel="nofollow">PyPi page</a>.</p>
<p>Did you actually install it for Python3?</p>
<p>Python packages are installed separately for each Python instance on your machine. (In fact, you may even use virtua... | 0 | 2016-09-14T14:24:18Z | [
"python",
"pyodbc"
] |
Odoo delegation inheritance delete corresponding records of inherited class | 39,492,821 | <p>I've extended a default class using _inherits. I am using Odoo v9.</p>
<pre><code>class new_product_uom(models.Model):
_inherits = {'product.uom':'uomid', }
_name = "newproduct.uom"
uomid = fields.Many2one('product.uom',ondelete='cascade', required=True).
#declare variables and functions specific to new_produ... | 0 | 2016-09-14T14:19:47Z | 39,496,144 | <p>In your parent class override unlink. Not sure if I have the correct class name. Delete the child record and then delete the current record.</p>
<pre><code>@api.multi
def unlink(self):
self.uom_id.unlink()
return super(new_product_uom, self).unlink()
</code></pre>
| 1 | 2016-09-14T17:11:30Z | [
"python",
"inheritance",
"openerp",
"odoo-9"
] |
simplest way to override Django admin inline to request formfield_for_dbfield for each instance | 39,492,839 | <p>I would like to provide different widgets to input form fields for the same type of model field in a Django admin inline.</p>
<p>I have implemented a version of the Entity-Attribute-Value paradigm in my shop application (I tried eav-django and it wasn't flexible enough). In my model it is Product-Parameter-Value (s... | 0 | 2016-09-14T14:20:42Z | 39,747,701 | <p>The way I eventually solved this is using the <code>form =</code> attribute of the Admin Inline. This skips the form generation code of the ModelAdmin:</p>
<pre><code>class SpecificationValueForm(ModelForm):
class Meta:
model = SpecificationValue
def __init__(self, instance=None, **kwargs):
... | 0 | 2016-09-28T12:34:38Z | [
"python",
"django",
"django-admin"
] |
Python formating all values in list of lists | 39,492,886 | <p>I am so sorry that I asking so silly question
but could you help me please format list of lists ("%.2f") for example:</p>
<pre><code>a=[[1.343465432, 7.423334343], [6.967997797, 4.5522577]]
</code></pre>
<p>I used:</p>
<pre><code> for x in a:
a = ["%.2f" % i for i in x]
print (a)
</code></pre>
<p>OUT:... | 0 | 2016-09-14T14:23:04Z | 39,492,924 | <p>In a simpler way, you may achieve the same using list comprehension as:</p>
<pre><code>>>> a=[[1.343465432, 7.423334343], [6.967997797, 4.5522577]]
>>> [["%.2f" % i for i in l] for l in a]
[['1.34', '7.42'], ['6.97', '4.55']]
</code></pre>
<p>Infact even your code is fine. Instead of print, you n... | 2 | 2016-09-14T14:24:49Z | [
"python",
"list",
"format"
] |
Python formating all values in list of lists | 39,492,886 | <p>I am so sorry that I asking so silly question
but could you help me please format list of lists ("%.2f") for example:</p>
<pre><code>a=[[1.343465432, 7.423334343], [6.967997797, 4.5522577]]
</code></pre>
<p>I used:</p>
<pre><code> for x in a:
a = ["%.2f" % i for i in x]
print (a)
</code></pre>
<p>OUT:... | 0 | 2016-09-14T14:23:04Z | 39,494,470 | <p>A more general solution requires just a few lines. It recursively formats numbers, lists, lists of lists of any nesting depth.</p>
<pre><code>def fmt(data):
if isinstance(data, list):
return [fmt(x) for x in data]
try:
return "%.2f" % data
except TypeError:
return data
a=[[1.34... | 1 | 2016-09-14T15:35:01Z | [
"python",
"list",
"format"
] |
create a main function in python and passing arguments | 39,492,907 | <p>Iam new with python and I did my first program in Python with jupyter notebook.
Here my tutor, said to me that I have to converti it into a script .py with passing arguments.
I try to do this byte per byte .</p>
<p>Can you just help me how to begin the script and passing New1 and New as arguments.</p>
<pre><code>d... | 0 | 2016-09-14T14:24:11Z | 39,492,983 | <p>Here is an example from <a href="http://www.tutorialspoint.com/python/python_functions.htm" rel="nofollow">Pythion Tutorials</a></p>
<pre><code>def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme("I'm first call to user defined... | 0 | 2016-09-14T14:27:34Z | [
"python"
] |
create a main function in python and passing arguments | 39,492,907 | <p>Iam new with python and I did my first program in Python with jupyter notebook.
Here my tutor, said to me that I have to converti it into a script .py with passing arguments.
I try to do this byte per byte .</p>
<p>Can you just help me how to begin the script and passing New1 and New as arguments.</p>
<pre><code>d... | 0 | 2016-09-14T14:24:11Z | 39,493,078 | <p>Try this <a href="http://www.pythonforbeginners.com/system/python-sys-argv" rel="nofollow">tutorial for using sys.argv</a>. When you are ready to be more robust about argument parsing, look into this <a href="https://docs.python.org/3/howto/argparse.html" rel="nofollow">argparse tutorial</a>.</p>
| 1 | 2016-09-14T14:31:15Z | [
"python"
] |
How to show the trajectory of a projectile using python? | 39,492,972 | <p>I'm fairly new to stack overflow and programming on the whole, so I apologize in advance if this question has already been asked or is a stupid question on the whole.
How could I visually show the trajectory of a projectile after doing the calculations in python? Like a module? PyGame? Are there other languages tha... | 1 | 2016-09-14T14:26:59Z | 39,493,181 | <p>You can use whatever graphic module you'd like.</p>
<p>Pygame is one, right, but I believe matplotlib is probably simpler.</p>
<p>Check this :</p>
<pre><code>import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches
verts = [
(0., 0.), # P0
(0.2, 1.), # P1
... | 2 | 2016-09-14T14:35:30Z | [
"python",
"pygame"
] |
How to show the trajectory of a projectile using python? | 39,492,972 | <p>I'm fairly new to stack overflow and programming on the whole, so I apologize in advance if this question has already been asked or is a stupid question on the whole.
How could I visually show the trajectory of a projectile after doing the calculations in python? Like a module? PyGame? Are there other languages tha... | 1 | 2016-09-14T14:26:59Z | 39,493,205 | <p>I suggest matplotlib. Here's <a href="http://matplotlib.org/users/pyplot_tutorial.html" rel="nofollow">a tutorial</a>.</p>
| 0 | 2016-09-14T14:36:16Z | [
"python",
"pygame"
] |
Spark: fetch data from complex dataframe schema with map | 39,493,076 | <p>I've got a following structure</p>
<pre><code>json.select($"comments").printSchema
root
|-- comments: array (nullable = true)
| |-- element: struct (containsNull = true)
| | |-- comment: struct (nullable = true)
| | | |-- date: string (nullable = true)
| | | |-- score: string (null... | 0 | 2016-09-14T14:31:13Z | 39,494,209 | <p>How about using statically typed <code>Dataset</code> instead?</p>
<pre><code>case class Comment(
date: String, score: String,
shouts: Seq[String], tags: Seq[String],
text: String, username: String
)
df
.select(explode($"comments.comment").alias("comment"))
.select("comment.*")
.as[Comment]
.ma... | 2 | 2016-09-14T15:23:20Z | [
"python",
"scala",
"apache-spark",
"pyspark"
] |
"lambdas can't have assignment statements" - so why is "foo = lambda x: x * 2" legal? | 39,493,159 | <p>I am reading Functional Python Programming by Steven Lott, a book about using Python 'functionally' instead of in a more object oriented fashion and which focuses on exploratory data analysis for most of its examples.</p>
<p>Lott says that Lamda's can't have assignment statements. But on the same page he assigned a... | 0 | 2016-09-14T14:34:40Z | 39,493,221 | <p>You can't have assignments inside the "lambda" function, but the lambda itself can be used in assignments.</p>
<p>So you can't say something like <code>lambda x: y = x*2; return y</code>, but you can say <code>foo = lambda x: x*2</code></p>
| 4 | 2016-09-14T14:36:49Z | [
"python",
"lambda",
"variable-assignment"
] |
"lambdas can't have assignment statements" - so why is "foo = lambda x: x * 2" legal? | 39,493,159 | <p>I am reading Functional Python Programming by Steven Lott, a book about using Python 'functionally' instead of in a more object oriented fashion and which focuses on exploratory data analysis for most of its examples.</p>
<p>Lott says that Lamda's can't have assignment statements. But on the same page he assigned a... | 0 | 2016-09-14T14:34:40Z | 39,493,355 | <p>It's not not an assignment.</p>
<p>A lambda in Python cannot <em>contain</em> an assignment. But this is pretty much the only aspect of Python which enforces a functional paradigm. The rest of the language has some unescapable procedural features; it is hard to imagine a Python program which didn't contain <em>any<... | 0 | 2016-09-14T14:42:52Z | [
"python",
"lambda",
"variable-assignment"
] |
How to delete multiple tables in SQLAlchemy | 39,493,174 | <p>Inspired by this question: <a href="http://stackoverflow.com/questions/35918605/how-to-delete-a-table-in-sqlalchemy">How to delete a table in SQLAlchemy?</a>, I ended up with the question: How to delete multiple tables.</p>
<p>Say I have 3 tables as seen below and I want to delete 2 tables (imagine a lot more table... | 0 | 2016-09-14T14:35:15Z | 39,493,548 | <p>The error you get is perfectly clear:</p>
<pre><code>AttributeError: 'str' object has no attribute '__table__'
</code></pre>
<p>You are not iterating on Table objects, but on table names (aka <strong>strings</strong>!), so of course a string has not an attribute <code>__table__</code>, so your statement:</p>
<pre... | 1 | 2016-09-14T14:51:27Z | [
"python",
"sqlalchemy"
] |
Regular expressions not splitten Python | 39,493,176 | <p>Using python I'm trying to divide a text file in blocks using regular expression. The text file looks like this:</p>
<pre><code>Block1
u 0.00 2.00
0.11 2.11
Block2
v 0.00 2.01
0.01 2.11
Block3
a 1.01 2.02
0.01 2.11
</code></pre>
<p>my regular expression</p>
<pre><code>re.split("(\bBlock1\b\n\s\s[u].*\... | 1 | 2016-09-14T14:35:20Z | 39,493,416 | <p>You don't necessarily need regular expressions and can approach it line by line checking if a line starts with <code>Block</code> collecting the results into a dictionary:</p>
<pre><code>from collections import defaultdict
data = defaultdict(list)
with open("input.txt") as f:
for line in f:
if line.sta... | 0 | 2016-09-14T14:44:59Z | [
"python",
"regex"
] |
Regular expressions not splitten Python | 39,493,176 | <p>Using python I'm trying to divide a text file in blocks using regular expression. The text file looks like this:</p>
<pre><code>Block1
u 0.00 2.00
0.11 2.11
Block2
v 0.00 2.01
0.01 2.11
Block3
a 1.01 2.02
0.01 2.11
</code></pre>
<p>my regular expression</p>
<pre><code>re.split("(\bBlock1\b\n\s\s[u].*\... | 1 | 2016-09-14T14:35:20Z | 39,493,437 | <p>Always, <em>ALWAYS</em> use raw strings when working with regular expressions in Python. <code>\b</code> means backslash inside a string, it gets evaluated and your regex gets damaged. Just add an 'r' in front of string.
This will do the trick:</p>
<pre><code>re.split(r"(\bBlock1\b\n\s\s[u].*\n.*)", open('Blockfile... | 0 | 2016-09-14T14:45:44Z | [
"python",
"regex"
] |
Regular expressions not splitten Python | 39,493,176 | <p>Using python I'm trying to divide a text file in blocks using regular expression. The text file looks like this:</p>
<pre><code>Block1
u 0.00 2.00
0.11 2.11
Block2
v 0.00 2.01
0.01 2.11
Block3
a 1.01 2.02
0.01 2.11
</code></pre>
<p>my regular expression</p>
<pre><code>re.split("(\bBlock1\b\n\s\s[u].*\... | 1 | 2016-09-14T14:35:20Z | 39,493,442 | <p><code>Split</code> only splits on the argument with its speech marks, for example:</p>
<p>Splitting <em>"this string"</em> with <code>.split(" ")</code> results in:</p>
<pre><code>["this","string"]
</code></pre>
<p>But splitting it with <code>.split("s ")</code> results in:</p>
<pre><code>["thi", "string"]
</co... | 0 | 2016-09-14T14:45:56Z | [
"python",
"regex"
] |
Two lists of JSON values -- do operation on some key | 39,493,182 | <p>I have 2 lists of dictionaries which look like this:</p>
<pre><code>x = [{'id':1,'num':5,'den':8},
{'id':2,'num':3,'den':5},
{'id':4,'num':11,'den':18},
{'id':3,'num':2,'den':81},
{'id':7,'num':10,'den':33}]
y = [{'id':1,'num':4,'den':9},
{'id':6,'num':5,'den':11},
{'id':3,'num':13,'d... | -1 | 2016-09-14T14:35:30Z | 39,493,327 | <p>You may achieve it using <code>list comprehension</code> as:</p>
<pre><code>>>> [{'id': i['id'], 'num': i['num'] + j['num'], 'den': i['den'] + j['den']} for i in x for j in y if i['id'] == j['id']]
[{'num': 9, 'id': 1, 'den': 17}, {'num': 18, 'id': 2, 'den': 33}, {'num': 15, 'id': 3, 'den': 164}, {'num': 1... | 1 | 2016-09-14T14:41:28Z | [
"python",
"json",
"list",
"dictionary"
] |
Two lists of JSON values -- do operation on some key | 39,493,182 | <p>I have 2 lists of dictionaries which look like this:</p>
<pre><code>x = [{'id':1,'num':5,'den':8},
{'id':2,'num':3,'den':5},
{'id':4,'num':11,'den':18},
{'id':3,'num':2,'den':81},
{'id':7,'num':10,'den':33}]
y = [{'id':1,'num':4,'den':9},
{'id':6,'num':5,'den':11},
{'id':3,'num':13,'d... | -1 | 2016-09-14T14:35:30Z | 39,493,668 | <p>a somehow more readable solution : </p>
<pre><code>import collections
result = collections.defaultdict(lambda: {'num': 0,'den': 0})
for data in x + y:
match = result[data['id']]
match['num'] += data['num']
match['den'] += data['den']
match['id'] = data['id']
z = list(result.values())
</code></pre>
| 0 | 2016-09-14T14:56:50Z | [
"python",
"json",
"list",
"dictionary"
] |
How to use tf.nn.max_pool_with_argmax correctly | 39,493,229 | <p>currently I play a little bit around with tensorflow to create a better understanding of machine learning an tensorflow itself. Therefore I want to visualize the methods (as much as possible) of tensorflow. To visualize max_pool I loaded an image and perform the method. After that I displayed both: input and output ... | 0 | 2016-09-14T14:37:22Z | 39,495,311 | <p>From a look at <a href="https://github.com/tensorflow/tensorflow/blob/bc64f05d4090262025a95438b42a54bfdc5bcc80/tensorflow/core/kernels/maxpooling_op.cc#L672" rel="nofollow">the implementation</a>, it appears that the <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/nn.html#max_pool_with_argmax" rel... | 1 | 2016-09-14T16:20:08Z | [
"python",
"tensorflow"
] |
Extrapolate 2d numpy array in one dimension | 39,493,231 | <p>I have numpy.array data set from a simulation, but I'm missing the point at the edge (x=0.1), how can I interpolate/extrapolate the data in z to the edge? I have:</p>
<pre><code>x = [ 0. 0.00667 0.02692 0.05385 0.08077]
y = [ 0. 10. 20. 30. 40. 50.]
# 0. 0.00667 0.02692 0.05385 0... | 0 | 2016-09-14T14:37:29Z | 39,493,832 | <p>Have you had a look at scipy.interpolate2d.interp2d (which uses splines)?</p>
<pre><code>from scipy.interpolate import interp2d
fspline = interp2d(x,y,z) # maybe need to switch x and y around
znew = fspline([0.1], y)
z = np.c_[[z, znew] # to join arrays
</code></pre>
<p><strong>EDIT</strong>:</p>
<p>The method th... | 1 | 2016-09-14T15:03:32Z | [
"python",
"arrays",
"numpy",
"interpolation",
"extrapolation"
] |
Checking "encryption" and "decryption" of Caesar Cipher using strings in python | 39,493,347 | <p>I was supposed to create strings in my python function to show that the encryption and decryption of my code was working properly. Below is my code. </p>
<pre><code>def encrypt1():
plain1 = input('Enter plain text message: ')
cipher = ''
for each in plain1:
c = (ord(each)+3) % 126
if c... | -2 | 2016-09-14T14:42:27Z | 39,493,715 | <p>Your code is mostly fine but there are a few issues that I've pointed out:</p>
<ol>
<li>Your indenting is off. The line <code>cipher += chr(c)</code> should be indented to match the things in the for loop</li>
<li>The function encypt1() shouldn't take a parameter; you are setting plain1 in the method itself so you ... | 1 | 2016-09-14T14:58:50Z | [
"python",
"encryption",
"caesar-cipher"
] |
Convert a str typed series to numeric where I can | 39,493,348 | <p>Consider the str type series <code>s</code></p>
<pre><code>s = pd.Series(['a', '1'])
</code></pre>
<hr>
<pre><code>pd.to_numeric(s, 'ignore')
0 a
1 1
dtype: object
</code></pre>
<hr>
<pre><code>pd.to_numeric(s, 'ignore').apply(type)
0 <type 'str'>
1 <type 'str'>
dtype: object
</code></... | 1 | 2016-09-14T14:42:29Z | 39,493,426 | <p>This is what I am using:</p>
<pre><code>pd.to_numeric(s, errors='coerce').fillna(s)
Out:
0 a
1 1
dtype: object
</code></pre>
<hr>
<pre><code>pd.to_numeric(s, errors='coerce').fillna(s).apply(type)
Out:
0 <class 'str'>
1 <class 'float'>
dtype: object
</code></pre>
| 3 | 2016-09-14T14:45:24Z | [
"python",
"pandas"
] |
Python RSA Decryption is throwing TypeErrors | 39,493,368 | <p>My RSA decrypt function:</p>
<pre><code>def decrypt(ctext,private_key):
key,n = private_key
text = [chr(pow(char,key)%n) for char in ctext]
return "".join(text)
</code></pre>
<p>is sometimes throwing a <code>TypeError</code> which tells that <code>pow(char,key)%n</code> provides a <code>float</code>. W... | 0 | 2016-09-14T14:43:21Z | 39,521,781 | <p>It's hard to figure out much from a tiny fragment of code. You are getting float results because your variable <code>key</code> is negative number. It is clear from the description of <a href="https://docs.python.org/3/library/functions.html#pow" rel="nofollow">pow</a> that you will get float results, which is not w... | 0 | 2016-09-15T23:28:33Z | [
"python",
"python-3.x",
"rsa",
"typeerror",
"precision"
] |
Regular Expression to get only words from file starting with letter and removing words with only numbers and punctuation in python | 39,493,399 | <p>I have a text file which i am reading in python through nltk functions.
I need to get only only words from file starting with letter and removing words with only numbers and punctuation.
For ex :-</p>
<pre><code>['Osteama pranay@123 123 !']
</code></pre>
<p>so the desired output is</p>
<pre><code>Osteama pranay@... | -2 | 2016-09-14T14:44:31Z | 39,494,105 | <pre><code>import re
' '.join(re.findall(r'\b[a-z][^\s]*\b', 'Osteama pranay@123 123 !', re.I))
</code></pre>
<p>the same regexp used with nltk.RegexpTokenizer</p>
<pre><code>import nltk
tokenizer = RegexpTokenizer(r'[a-zA-Z][^\s]*\b')
nltk.tokenize('Osteama pranay@123 123 !')
</code></pre>
| -1 | 2016-09-14T15:17:58Z | [
"python",
"regex",
"nltk",
"regex-negation"
] |
Regular Expression to get only words from file starting with letter and removing words with only numbers and punctuation in python | 39,493,399 | <p>I have a text file which i am reading in python through nltk functions.
I need to get only only words from file starting with letter and removing words with only numbers and punctuation.
For ex :-</p>
<pre><code>['Osteama pranay@123 123 !']
</code></pre>
<p>so the desired output is</p>
<pre><code>Osteama pranay@... | -2 | 2016-09-14T14:44:31Z | 39,495,701 | <p>To use regular expression you need to >>>import re first</p>
<pre><code>import nltk,re,pprint
from __future__ import division
from nltk import word_tokenize
def openbook(self,book):
file = open(book)
raw = file.read()
tokens = nltk.wordpunct_tokenize(raw)
text = nltk.Text(tokens)
words = [w.low... | 0 | 2016-09-14T16:42:45Z | [
"python",
"regex",
"nltk",
"regex-negation"
] |
length python multidimensional list | 39,493,455 | <p>I have a strange error in the following code:</p>
<pre><code>s = MyClass()
f = open(filename, 'r')
nbline = f.readline()
for line in iter(f):
linesplit = line.split()
s.add(linesplit)
f.close()
print(len(s.l))
print(nbline)
</code></pre>
<p>the two print don't give me the same result. Why?</p>
<p... | 0 | 2016-09-14T14:46:48Z | 39,493,508 | <p>Try something the lines of:</p>
<p>(len(list[first dimension]) + len(list[second dimension])) etc...</p>
<p>A bit clunky but I think it will do what you want</p>
| 0 | 2016-09-14T14:49:30Z | [
"python",
"list",
"variable-length"
] |
length python multidimensional list | 39,493,455 | <p>I have a strange error in the following code:</p>
<pre><code>s = MyClass()
f = open(filename, 'r')
nbline = f.readline()
for line in iter(f):
linesplit = line.split()
s.add(linesplit)
f.close()
print(len(s.l))
print(nbline)
</code></pre>
<p>the two print don't give me the same result. Why?</p>
<p... | 0 | 2016-09-14T14:46:48Z | 39,494,228 | <p>The file probably has a trailing newline or two. If <code>len(s.l) == nbline + 1</code> or just print <code>s.l[-3:]</code> to check.</p>
| 0 | 2016-09-14T15:24:03Z | [
"python",
"list",
"variable-length"
] |
length python multidimensional list | 39,493,455 | <p>I have a strange error in the following code:</p>
<pre><code>s = MyClass()
f = open(filename, 'r')
nbline = f.readline()
for line in iter(f):
linesplit = line.split()
s.add(linesplit)
f.close()
print(len(s.l))
print(nbline)
</code></pre>
<p>the two print don't give me the same result. Why?</p>
<p... | 0 | 2016-09-14T14:46:48Z | 39,494,488 | <p>First, thanks for the edit.</p>
<p>Here is a better looking and more pythonic code:</p>
<pre><code>s = MyClass()
with open(filename, 'r') as f:
nbline = f.readline()
for line in f:
linesplit = line.split()
s.add(linesplit)
</code></pre>
<p>Then make sure you are setting <code>self.l = []</... | 0 | 2016-09-14T15:36:00Z | [
"python",
"list",
"variable-length"
] |
length python multidimensional list | 39,493,455 | <p>I have a strange error in the following code:</p>
<pre><code>s = MyClass()
f = open(filename, 'r')
nbline = f.readline()
for line in iter(f):
linesplit = line.split()
s.add(linesplit)
f.close()
print(len(s.l))
print(nbline)
</code></pre>
<p>the two print don't give me the same result. Why?</p>
<p... | 0 | 2016-09-14T14:46:48Z | 39,494,910 | <p>Ok the problem is that s.l is a class variable shared by all instances!!!</p>
| 0 | 2016-09-14T15:58:24Z | [
"python",
"list",
"variable-length"
] |
Python - psql prompt for password even if it got it | 39,493,486 | <p>I'm working on a small code, which have to: </p>
<ul>
<li>Connect with SFTP</li>
<li>execute command on PostgreSQL (password protected)</li>
</ul>
<p>I am willing to use password as a plain text.</p>
<p>For the moment my code is:</p>
<pre><code>import pysftp
command = "... some SQL command"
sftp= pysftp.Connec... | 0 | 2016-09-14T14:48:25Z | 39,493,615 | <p><code>psql</code> has a <code>--no-password</code> option, which can also be specified as <code>-w</code>.</p>
<p>It looks like you might have misspelled <code>-w</code> as <code>-W</code>, which has the opposite effect.</p>
| 1 | 2016-09-14T14:54:36Z | [
"python",
"postgresql",
"pysftp"
] |
Program design of a timetable creator | 39,493,520 | <p>For fun, I want to write a timetable creator in python for schools. I.e. a program where schools can input their rooms, teachers, classes and subjects and some preferences and which will output a timetable for each class/teacher/room. I don't have a problem with the logic behind this (because that is the part I am m... | 0 | 2016-09-14T14:50:05Z | 39,494,086 | <p>One difficult part of this problem is that there are numerous relations that make up a schedule. I would think very carefully about how a teacher T teaches a class and she teaches it in room X at 1:30 pm.</p>
<p>For example, in your program, you may want to know when room X is available. To do this, you will want t... | 1 | 2016-09-14T15:16:40Z | [
"python",
"design-patterns",
"design"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.