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 |
|---|---|---|---|---|---|---|---|---|---|
UDP Packet received okay in Java but corrupted in Python | 39,914,553 | <p>I am trying to record audio from an Android tablet and send it to a python server. At the start of the byte packet, I include some relevant information about the state of the Android app (A byte array called "actives" -- but considering it's receiving fine by a Java server, this should not be relevant). The android ... | 0 | 2016-10-07T10:01:17Z | 39,915,112 | <p>Decoding is the right approach. In your android app explicitly mention the character encoding. <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/charset/StandardCharsets.html#UTF_8" rel="nofollow">UTF-8</a> is the standard Charset that is used.</p>
<p>Your log is pretty clear. You are trying to decode the... | 1 | 2016-10-07T10:28:18Z | [
"java",
"android",
"python",
"udp",
"datagram"
] |
UDP Packet received okay in Java but corrupted in Python | 39,914,553 | <p>I am trying to record audio from an Android tablet and send it to a python server. At the start of the byte packet, I include some relevant information about the state of the Android app (A byte array called "actives" -- but considering it's receiving fine by a Java server, this should not be relevant). The android ... | 0 | 2016-10-07T10:01:17Z | 39,923,615 | <p>This was pretty brutal to attack head-on. I tried specifying the encoding in Java (before sending) like another SO post suggested, but that didn't help. So I side-stepped the problem by converting my Android byte array into a comma-separated string, then converting the string back into UTF-8 bytes.</p>
<pre><code>s... | 0 | 2016-10-07T18:21:51Z | [
"java",
"android",
"python",
"udp",
"datagram"
] |
How to add an object to already existing json object if a key from csv already exists? | 39,914,598 | <p>I have a <code>csv</code> file that looks like this:</p>
<pre><code>NDB_No,Seq,Amount,Msre_Desc,Gm_Wgt,Num_Data_Pts,Std_Dev
01001,1,1,pat (1" sq, 1/3" high),5,,
01001,2,1,tbsp,14.2,,
01001,3,1,cup,227,,
01001,4,1,stick,113,,
01002,1,1,pat (1" sq, 1/3" high),3.8,,
01002,2,1,tbsp,9.4,,
01002,3,1,cup,151,,
01002,4,1,s... | -1 | 2016-10-07T10:03:01Z | 39,915,827 | <p>You have two keys and a dictionary of data.
To make things simpler change <code>{"NDB_No": [{key1: {key2: data}}]}</code> to <code>{key1: {key2: data}}</code>.
This is as you're just making noise.</p>
<p>Make <code>key1</code>, <code>key2</code> and <code>data</code>:</p>
<pre><code>key1, key2 = row['NDB_No'], 'Se... | 1 | 2016-10-07T11:11:37Z | [
"python",
"json",
"python-3.x",
"csv"
] |
What's the best way to get continuous data from another program in Django? | 39,914,635 | <p>Here's the setup: On a single-board computer with a very rudimentary linux I'm running a <code>Django app</code>. This app is, when a button is pressed or as a response to the data described below, supposed to call either a function from a library written in <code>C</code>, or a compiled <code>C</code> program, to w... | 1 | 2016-10-07T10:04:57Z | 39,918,938 | <p>I wanted to add a comment but not enough space... anyway</p>
<p>You can write a native extension in C for Python that could do what you need, check <a href="https://docs.python.org/2/extending/extending.html" rel="nofollow">this</a>.</p>
<p>Now for the fact of <em>displaying data continuously</em> this is kind of ... | 0 | 2016-10-07T13:51:42Z | [
"python",
"django",
"shared-memory",
"web-frameworks"
] |
Change global variable to value in entry field | 39,914,640 | <p>How can I change a global variable to a value inputted by a user in an entry field?</p>
<pre><code>card_no = 0
def cardget():
global card_no
card_no = e1.get()
print(card_no)
def menu():
global card_no
root = Tk()
e1 = Entry(root).pack()
Label(root, text= "Enter card number").pack(an... | 0 | 2016-10-07T10:05:10Z | 39,914,797 | <p>Don't use global variables. Tkinter apps work much better with OOP.</p>
<pre><code>import tkinter as tk
class App:
def __init__(self, parent):
self.e1 = tk.Entry(parent)
self.e1.pack()
self.l = tk.Label(root, text="Enter card number")
self.l.pack(anchor=tk.NW)
self.b = t... | 1 | 2016-10-07T10:12:58Z | [
"python",
"tkinter"
] |
Change global variable to value in entry field | 39,914,640 | <p>How can I change a global variable to a value inputted by a user in an entry field?</p>
<pre><code>card_no = 0
def cardget():
global card_no
card_no = e1.get()
print(card_no)
def menu():
global card_no
root = Tk()
e1 = Entry(root).pack()
Label(root, text= "Enter card number").pack(an... | 0 | 2016-10-07T10:05:10Z | 39,914,889 | <p>You can pass the card no to the function called when the button is clicked:</p>
<pre><code>import tkinter as tk
def cardget(card_no):
print(card_no)
def menu():
root = tk.Tk()
tk.Label(root, text="Enter card number").pack(anchor=tk.NW)
e1 = tk.Entry(root)
e1.pack()
tk.Button(root, text="Co... | -1 | 2016-10-07T10:18:13Z | [
"python",
"tkinter"
] |
How to put a Label/unique ID on Date-time in Database or when analyzing data with R/Python? | 39,914,736 | <p>I am looking for a general solution in the database.It could be oracle or SQL server or the operation could be done in R/Python when I will import the data to R/Python. I have a Date-time(D-M-YY) column I want to put a label on it according to month. Day part is static it is trimmed by first day of the month. the mo... | 0 | 2016-10-07T10:09:56Z | 39,915,760 | <p>Finally my friend help me to find a solution in R, which is very simple,</p>
<p>date_sample <-c('1-1-2016','1-2-2016','1-3-2016','1-4-2016')</p>
<p>format(as.Date(date_sample,format = '%d-%m-%Y'),"%m")</p>
<p>It gives me output:
"01" "02" "03" "04"</p>
| 0 | 2016-10-07T11:07:52Z | [
"python",
"sql"
] |
Converting list to dictionary with list elements as index - Python | 39,914,744 | <p>From <a href="http://stackoverflow.com/questions/7974959/python-create-dict-from-list-and-auto-gen-increment-the-keys-list-is-the-actua">Python: create dict from list and auto-gen/increment the keys (list is the actual key values)?</a>, it's possible to create a <code>dict</code> from a <code>list</code> using <code... | 0 | 2016-10-07T10:10:23Z | 39,914,756 | <p>How about simply:</p>
<pre><code>>>> x = ['a', 'b', 'c']
>>> {j:i for i,j in enumerate(x)}
{'a': 0, 'c': 2, 'b': 1}
</code></pre>
| -1 | 2016-10-07T10:10:44Z | [
"python",
"list",
"dictionary"
] |
Execute function at specific GMT time daily | 39,914,796 | <p>How can I implement what is described in the tittle in python, regardless of when the initial script will be run?<br>
For example if I run the script at 2 am in a <code>"GMT +2"</code> timezone or at 8 pm at a <code>"GMT -1"</code> timezone, this script must schedule a function to run every day at <code>GMT 00:00</c... | -2 | 2016-10-07T10:12:58Z | 39,914,908 | <p>You can just use <code>strftime</code> and <code>gmtime</code> (GMT):</p>
<pre><code>from time import strftime, gmtime
def foo():
if strftime("%H%M", gmtime()) == "0000": # Gets time in this format: HHMM
# Do stuff
</code></pre>
<p>For more information, go to <a href="https://docs.python.org/2/library/... | -1 | 2016-10-07T10:18:57Z | [
"python",
"time"
] |
python 2.7 â getting this timer object right | 39,914,853 | <p>I'm making a text-based game to practice python.<br><br></p>
<p>The following is the code of the Trap scene. In the scene, the player falls into a hole, and if he doesn't react in time (5 seconds), he dies. After starting the timer, I ask for input inside a while loop. I'm seeing, that this code somehow redundant â... | 1 | 2016-10-07T10:16:02Z | 39,915,126 | <p><code>raw_input</code> is a blocking function that effectively halts the program until the input is received (waits for a new line/carriage return).</p>
<p>There are two ways around this:</p>
<ul>
<li>Record the time before and after the <code>raw_input</code>. If the latter is less than five seconds after the for... | 0 | 2016-10-07T10:29:03Z | [
"python",
"python-2.7",
"time"
] |
Recursive Generator Function Python Nested JSON Data | 39,914,906 | <p>I'm attempting to write a recursive generator function to flatten a nested json object of mixed types, lists and dictionaries. I am doing this partly for my own learning so have avoided grabbing an example from the internet to ensure I better understand what's happening, but have got stuck, with what I think is the ... | 0 | 2016-10-07T10:18:49Z | 39,967,882 | <p>In lieu of any response on this I just wanted to post my updated solution in case it proves useful for anyone else.</p>
<p>I need to add additional yield statements to the function so the result of each recursive call of the generator function can be handed off to be used by the next, at least that's how I've under... | 0 | 2016-10-10T22:46:25Z | [
"python",
"json",
"function",
"yield"
] |
PyQt - Load SQL in QAbstractTableModel (QTableView) using pandas DataFrame - editing datas in a GUI | 39,914,926 | <p>I'm quite new to python and using <code>WinPython-32bit-2.7.10.3</code> (including <code>QTDesigner 4.8.7</code>). I'm trying to program an interface for using a sqlite database on two separates projects, using QtableViews.</p>
<p>The algorithm is roughly so :<br>
- connect to database and convert datas to <code>pa... | 0 | 2016-10-07T10:19:43Z | 39,971,773 | <p>I finally figured it... But I still don't know why pandas worked differently just by changing the SQL request (must be something inside the read_sql_query process...)</p>
<p>For the class to work, I had to change the code of "PANDAS_TO_PYQT.py", replacing the</p>
<pre><code>self._data.values[index.row()][index.col... | 0 | 2016-10-11T06:48:59Z | [
"python",
"python-2.7",
"pandas",
"pyqt",
"qtableview"
] |
If number comparison too slow | 39,914,950 | <p>I have a buffer and I need to make sure I don't exceed certain size. If I do, I want to append the buffer to a file and empty it.</p>
<p>My code:</p>
<pre><code>import sys
MAX_BUFFER_SIZE = 4 * (1024 ** 3)
class MyBuffer(object):
b = ""
def append(self, s):
if sys.getsizeof(self.b) > MAX_BUFF... | 0 | 2016-10-07T10:20:47Z | 39,915,039 | <p>Undeleting and editing my answer based on edits to the question.</p>
<p>It's incorrect to assume that the comparision is slow. In fact the comparision is fast. Really, really fast. </p>
<p>Why don't you avoid re inventing the wheel by using buffered IO?</p>
<blockquote>
<p>The optional buffering argument specif... | 1 | 2016-10-07T10:24:21Z | [
"python"
] |
Getting slightly different input in each data fetch operation | 39,915,120 | <p>I am following the <a href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/models/image/cifar10" rel="nofollow">cifar10 tutorial</a> and fetch my data using <a href="https://github.com/tensorflow/tensorflow/blob/r0.11/tensorflow/models/image/cifar10/cifar10_input.py#L197" rel="nofollow">inputs()</a>... | 0 | 2016-10-07T10:28:47Z | 39,923,120 | <p>The queue runners you are starting there are multiple threads loading data from disk and adding it to the queue. <a href="https://github.com/tensorflow/tensorflow/blob/r0.11/tensorflow/models/image/cifar10/cifar10_input.py#L117" rel="nofollow">There are 16 of them by default</a>. </p>
<p>The queue itself is thread-... | 2 | 2016-10-07T17:45:39Z | [
"python",
"io",
"tensorflow"
] |
Print unicode character in Python 3 | 39,915,296 | <p>How can I print unicode strings within Python 3?</p>
<pre><code>myString = 'My unicode character: \ufffd'
print(myString)
</code></pre>
<p>The Output should be: "My unicode character: ü"</p>
<blockquote>
<p>File "C:\Program Files (x86)\Python35-32\lib\encodings\cp850.py", line
19, in encode return
codecs.c... | 0 | 2016-10-07T10:39:34Z | 39,915,371 | <p>It seems that you are doing this using Windows command line.</p>
<pre><code>chcp 65001
set PYTHONIOENCODING=utf-8
</code></pre>
<p>You can try to run above command first before running <code>python3</code>. It will set the console encoder to utf-8 that can represent your data.</p>
| 0 | 2016-10-07T10:43:48Z | [
"python",
"unicode"
] |
Python function returning string which is function name, need to execute the returned statement | 39,915,320 | <p>1) Function 1 encodes the string</p>
<p>def Encode(String):<br>
..<br>
..code block<br>
..<br>
return String</p>
<p>2) Function 2 return the string, which actually forms function call of Function 1</p>
<p>def FunctionReturningEncodeFuntionCall(String):<br>
..<br>
..code block<br>
..<br>
re... | 0 | 2016-10-07T10:40:34Z | 39,915,440 | <p>Consider using the <a href="https://docs.python.org/2.0/ref/exec.html" rel="nofollow">exec statement</a></p>
| 0 | 2016-10-07T10:48:40Z | [
"python",
"string"
] |
Python function returning string which is function name, need to execute the returned statement | 39,915,320 | <p>1) Function 1 encodes the string</p>
<p>def Encode(String):<br>
..<br>
..code block<br>
..<br>
return String</p>
<p>2) Function 2 return the string, which actually forms function call of Function 1</p>
<p>def FunctionReturningEncodeFuntionCall(String):<br>
..<br>
..code block<br>
..<br>
re... | 0 | 2016-10-07T10:40:34Z | 39,918,138 | <p>I think the safest way is to use a dictionary where the key is the function's name and the value is the function itself.</p>
| 0 | 2016-10-07T13:11:16Z | [
"python",
"string"
] |
Combine a list of pairs (tuples)? | 39,915,402 | <p>From a list of linked pairs, I want to combine the pairs into groups of common IDs, so that I can then write group_ids back to the database, eg:</p>
<pre><code>UPDATE table SET group = n WHERE id IN (...........);
</code></pre>
<p>Example:</p>
<pre><code>[(1,2), (3, 4), (1, 5), (6, 3), (7, 8)]
</code></pre>
<p>b... | 1 | 2016-10-07T10:46:18Z | 39,915,554 | <p>With:</p>
<pre><code>def make_equiv_classes(pairs):
groups = {}
for (x, y) in pairs:
xset = groups.get(x, set([x]))
yset = groups.get(y, set([y]))
jset = xset | yset
for z in jset:
groups[z] = jset
return set(map(tuple, groups.values()))
</code></pre>
<p>you ... | 1 | 2016-10-07T10:55:50Z | [
"python",
"list"
] |
Speed up code that doesn't use groupby()? | 39,915,454 | <p>I have two pieces of code (doing the same job) which takes in array of <code>datetime</code> and produces clusters of <code>datetime</code> which have difference of 1 hour.</p>
<p>First piece is:</p>
<pre><code>def findClustersOfRuns(data):
runClusters = []
for k, g in groupby(itertools.izip(data[0:-1], da... | -1 | 2016-10-07T10:49:47Z | 39,915,992 | <p>Based on the size, it looks you are having a huge <code>list</code> of elements i.e. huge <code>len</code>. Your second code is having just one <code>for</code> loop where as your first approach has many. You see just one right? They are in the form of <code>map()</code>, <code>groupby()</code>. Multiple iteration o... | 1 | 2016-10-07T11:21:25Z | [
"python",
"lambda"
] |
Add a value to a column and print results | 39,915,904 | <p>I have a file like this</p>
<pre><code>Daniel 400 411 f
Mark 976 315 g
</code></pre>
<p>I would like to add 20 to line[2] and subtract 20 from line[1] and print new results overwriting this lines or to a new file.This is my try.</p>
<pre><code>f=open('w', 'r')
r = open('w2','a')
lines=f.readlines()
for line in li... | 0 | 2016-10-07T11:16:28Z | 39,916,027 | <pre><code>f=open('w', 'r')
r=open('w2','a')
lines=f.readlines()
for line in lines:
new_list = line.rstrip('\r\n').split('\t')
new_list[1] = str(int(new_list[1]) - 20)
new_list[2] = str(int(new_list[2]) + 20)
r.write("\t".join(new_list)+"\n")
f.close()
r.close()
</code></pre>
<p>This should works. Ba... | 4 | 2016-10-07T11:23:40Z | [
"python"
] |
Add a value to a column and print results | 39,915,904 | <p>I have a file like this</p>
<pre><code>Daniel 400 411 f
Mark 976 315 g
</code></pre>
<p>I would like to add 20 to line[2] and subtract 20 from line[1] and print new results overwriting this lines or to a new file.This is my try.</p>
<pre><code>f=open('w', 'r')
r = open('w2','a')
lines=f.readlines()
for line in li... | 0 | 2016-10-07T11:16:28Z | 39,916,090 | <p>There's really no need to read in all the lines into memory, then loop over them. It just lengthens the code and is less efficient. Instead, try</p>
<pre><code>with open('w2','w') as out:
for line in open('w', 'r'):
new_list = line.rstrip('\r\n').split('\t')
q_start=int(new_list[1]) - 20
... | 3 | 2016-10-07T11:26:08Z | [
"python"
] |
Add a value to a column and print results | 39,915,904 | <p>I have a file like this</p>
<pre><code>Daniel 400 411 f
Mark 976 315 g
</code></pre>
<p>I would like to add 20 to line[2] and subtract 20 from line[1] and print new results overwriting this lines or to a new file.This is my try.</p>
<pre><code>f=open('w', 'r')
r = open('w2','a')
lines=f.readlines()
for line in li... | 0 | 2016-10-07T11:16:28Z | 39,916,343 | <p>I see that you have already accepted an answer, but still, here is my comment. There are a couple of mistakes in your code. The first is that even though you calculate the values correctly, you store them into two variable(<code>q_start</code> and <code>q_end</code>) that are not used afterwards.</p>
<p>The second ... | 1 | 2016-10-07T11:38:56Z | [
"python"
] |
Make navbar item active in Django Template | 39,916,348 | <p>i'm creating menu with forloop and i need to add active class after click. </p>
<pre><code>{% for menu in TopMenu %}
<li><a href="/content/{{menu.slug_link}}">{{menu.title}}</a></li>
{% endfor %}
</code></pre>
<p>i tried to use django template inheritance but it didn't work. any solut... | 1 | 2016-10-07T11:39:23Z | 39,916,526 | <p>You don't need <code>{{ }}</code> when using the <code>if</code> tag.</p>
<p>Try:</p>
<pre><code>{% if activeflag == menu.slug_link %} class="active" {% endif %}
</code></pre>
| 1 | 2016-10-07T11:49:04Z | [
"python",
"django"
] |
Django Rest: Correct data isn't sent to serializer with M2M model | 39,916,480 | <p>I have a simple relational structure with projects containing several sequences with an intermediate meta model.</p>
<p>I can perform a GET request easily enough and it formats the data correctly. However, when I want to post the validated_data variable does not contain data formatted correctly, so I can't write a ... | 0 | 2016-10-07T11:46:43Z | 39,919,250 | <p>As you see in the <code>ProjectMetaSerializer</code>, the fields <code>id</code> and <code>name</code> are ReadOnlyFields. So you can't use them in <code>post</code> request.</p>
<pre><code>class ProjectMetaSerializer(serializers.ModelSerializer):
seqrecords = SeqRecordSerializer(many=True)
class Meta:
... | 1 | 2016-10-07T14:07:01Z | [
"python",
"django",
"django-rest-framework"
] |
Django Rest: Correct data isn't sent to serializer with M2M model | 39,916,480 | <p>I have a simple relational structure with projects containing several sequences with an intermediate meta model.</p>
<p>I can perform a GET request easily enough and it formats the data correctly. However, when I want to post the validated_data variable does not contain data formatted correctly, so I can't write a ... | 0 | 2016-10-07T11:46:43Z | 39,957,118 | <p>To return the correct data format the function "to_internal" can be overridden in the ProjectSerializer, like this:</p>
<pre><code>class ProjectSerializer(serializers.HyperlinkedModelSerializer):
seqrecords = ProjectMetaSerializer(source='projectmeta_set', many=True)
class Meta:
model = Project
... | 0 | 2016-10-10T11:22:22Z | [
"python",
"django",
"django-rest-framework"
] |
how to reconnect after autobahn websocket timeout? | 39,916,500 | <p>I'm using Autobahn to connect to a websocket like this.</p>
<pre><code>class MyComponent(ApplicationSession):
@inlineCallbacks
def onJoin(self, details):
print("session ready")
def oncounter(*args, **args2):
print("event received: args: {} args2: {}".format(args, args2))
try:
yiel... | 0 | 2016-10-07T11:48:00Z | 39,925,529 | <p>You can use a <code>ReconnectingClientFactory</code> if you're using Twisted. <a href="https://github.com/crossbario/autobahn-python/blob/master/examples/twisted/websocket/echo_variants/client_reconnecting.py" rel="nofollow">There's a simple example by the autobahn developer on github</a>. Unfortunately there doesn'... | 0 | 2016-10-07T20:44:30Z | [
"python",
"twisted",
"autobahn"
] |
how to reconnect after autobahn websocket timeout? | 39,916,500 | <p>I'm using Autobahn to connect to a websocket like this.</p>
<pre><code>class MyComponent(ApplicationSession):
@inlineCallbacks
def onJoin(self, details):
print("session ready")
def oncounter(*args, **args2):
print("event received: args: {} args2: {}".format(args, args2))
try:
yiel... | 0 | 2016-10-07T11:48:00Z | 40,019,926 | <p>Here is an <a href="https://github.com/crossbario/autobahn-python/blob/master/examples/twisted/wamp/basic/client_using_apprunner.py" rel="nofollow">example</a> of an automatically reconnecting ApplicationRunner. The important line to enable auto-reconnect is:</p>
<pre><code>runner.run(session, auto_reconnect=True)
... | 0 | 2016-10-13T11:38:27Z | [
"python",
"twisted",
"autobahn"
] |
python + Sqlite: How to save the changes into a new db file? | 39,916,558 | <p>After the changes were made to a db file, I want to save the data into a new db file. </p>
<pre><code>import sqlite3
conn = sqlite3.connect('Original.db')
cur = conn.cursor()
# make changes here.
conn.close() #Close without save
connA = sqlite3.connect('NewFile.db')
connA.commit() # Here is my problem. How to save... | 0 | 2016-10-07T11:50:23Z | 39,916,856 | <p>Each databases have their own table, data, schema, etc. If you just commit those changes on a brand new file, errors will occur.</p>
<p>If you want to save the changed data into a new database, you can make a copy of current database file by using <code>shutil.copyfile</code> and then operate on the new database.</... | 1 | 2016-10-07T12:05:17Z | [
"python",
"sqlite"
] |
TypeError: only length-1 arrays can be converted to Python scalars, while using Kfold cross Validation | 39,916,655 | <p>I am trying to use <code>Kfold</code> cross valiadtion for my model, but get this error while doing so. I know that <code>KFold</code> only accepts 1D arrays but even after converting the length input to an array its giving me this problem.</p>
<pre><code>from sklearn.ensemble import ExtraTreesClassifier, RandomFor... | 0 | 2016-10-07T11:55:03Z | 39,916,807 | <p>From <a href="http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.KFold.html#sklearn.model_selection.KFold" rel="nofollow">its doc</a>, <code>KFold()</code> does not expect <code>y</code> as an input, but only the number of splits (n_folds). </p>
<p>Once you have an instance of <code>KFold</cod... | 1 | 2016-10-07T12:02:47Z | [
"python",
"arrays",
"pandas",
"scikit-learn",
"cross-validation"
] |
"ImportError: cannot import name Browser" with python mechanize | 39,916,657 | <p>I am unable to use a <a href="https://docs.google.com/document/d/1hEAMNvbPgNzVxNmmDnLdGlVvQwypKhcpjAUAif1Jdkk/" rel="nofollow">mechanize code</a> ). The part that lead to the error is </p>
<pre><code>#!/usr/bin/python
import re
from mechanize import
br = Browser()
</code></pre>
<p>I also tried </p>
<p>When execu... | 0 | 2016-10-07T11:55:13Z | 39,916,717 | <p>Have you tried mechanize.Browser()?</p>
| 0 | 2016-10-07T11:58:13Z | [
"python",
"html",
"linux",
"forms",
"mechanize"
] |
"ImportError: cannot import name Browser" with python mechanize | 39,916,657 | <p>I am unable to use a <a href="https://docs.google.com/document/d/1hEAMNvbPgNzVxNmmDnLdGlVvQwypKhcpjAUAif1Jdkk/" rel="nofollow">mechanize code</a> ). The part that lead to the error is </p>
<pre><code>#!/usr/bin/python
import re
from mechanize import
br = Browser()
</code></pre>
<p>I also tried </p>
<p>When execu... | 0 | 2016-10-07T11:55:13Z | 39,917,035 | <p>The <code>python</code> version has to be at least <code>3.0</code> (<a href="http://wwwsearch.sourceforge.net/mechanize/faq.html" rel="nofollow">reference</a>)</p>
<p>Check your python version with</p>
<pre><code>readlink -f $(which python) | xargs -I % sh -c 'echo -n "%: "; % -V'
</code></pre>
<p>But the error ... | 0 | 2016-10-07T12:13:48Z | [
"python",
"html",
"linux",
"forms",
"mechanize"
] |
Replacing a \t with something in a list | 39,916,674 | <pre><code>>>>user_sentence = "hello \t how are you?"
>>>import re
>>>user_sentenceSplit = re.findall(r"([\s]|[\w']+|[.,!?;])",user_sentence)
>>>print user_sentenceSplit
</code></pre>
<p>I get <code>['hello', '\t', 'how', 'are', 'you', '?']</code></p>
<p>I don't know how to create ... | 0 | 2016-10-07T11:56:02Z | 39,916,882 | <p>I think <code>str.replace</code> would do the job.</p>
<pre class="lang-py prettyprint-override"><code>user_sentence.replace('\t', 'tab')
</code></pre>
<p>Do this before splitting the string.</p>
| 1 | 2016-10-07T12:06:33Z | [
"python",
"regex"
] |
Replacing a \t with something in a list | 39,916,674 | <pre><code>>>>user_sentence = "hello \t how are you?"
>>>import re
>>>user_sentenceSplit = re.findall(r"([\s]|[\w']+|[.,!?;])",user_sentence)
>>>print user_sentenceSplit
</code></pre>
<p>I get <code>['hello', '\t', 'how', 'are', 'you', '?']</code></p>
<p>I don't know how to create ... | 0 | 2016-10-07T11:56:02Z | 39,916,884 | <p>It is behavior of Python's compiler. You should not be worrying about it. Pyhton's Compiler store <code>tab</code> as <code>\t</code>. You need not to do anything on it as it will treat it as tab while performing any action over it. For example:</p>
<pre><code>>>> my_string = 'Yes Hello So?' # <- ... | 0 | 2016-10-07T12:06:34Z | [
"python",
"regex"
] |
Replacing a \t with something in a list | 39,916,674 | <pre><code>>>>user_sentence = "hello \t how are you?"
>>>import re
>>>user_sentenceSplit = re.findall(r"([\s]|[\w']+|[.,!?;])",user_sentence)
>>>print user_sentenceSplit
</code></pre>
<p>I get <code>['hello', '\t', 'how', 'are', 'you', '?']</code></p>
<p>I don't know how to create ... | 0 | 2016-10-07T11:56:02Z | 39,917,486 | <p>I do not believe that replacing <code>\t</code> in the original string will ever work, you have two issues:</p>
<ul>
<li>Your code also outputs spaces as tokens, but you do not want to have them</li>
<li>The <code>\t</code> in between letters will become a part of a word token.</li>
</ul>
<p>So, you need to replac... | 1 | 2016-10-07T12:36:39Z | [
"python",
"regex"
] |
How can I replicate similar behaviour in python 3 as seen in python 2 | 39,916,676 | <p>I have this operation done in <code>python 2</code>:</p>
<p>python 2:</p>
<pre><code>garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX"
message = filter(lambda x: x != 'X', garbled)
print message
</code></pre>
<p>result:</p>
<pre><code>'I am another secret message!'
</cod... | -1 | 2016-10-07T11:56:08Z | 39,916,714 | <p>In python 3.X <code>filter()</code> returns an iterator and when you convert it to list you'll get a list of your characters. Thus, instead you can pass the iterator to <code>str.join()</code> method in order to join the filtered result together:</p>
<pre><code>In [1]: garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX ... | 2 | 2016-10-07T11:58:06Z | [
"python",
"python-2.7",
"python-3.x"
] |
Group by multiple columns in sqlalchemy | 39,916,678 | <p>I have written this python function to query a database using the SQLAlchemy package:</p>
<pre><code>def group_by_one_var(start_date, end_date, groupby):
data = db.session.query(
groupby,
MyModel.SnapDate,
func.count(MyModel.CustomerID).label("TotalCustomers")
)\
.filter(
... | 0 | 2016-10-07T11:56:19Z | 39,917,425 | <p>This is how you can parse a dynamic number of groupby arguments and have SQLAlchemy include them all in the query:</p>
<pre><code>def group_by_n_vars(start_date, end_date, *groupby):
data = db.session.query(
*groupby,
MyModel.BookingDateLocal,
func.count(MyModel.BookingId).label("TotalCu... | 0 | 2016-10-07T12:33:21Z | [
"python",
"sqlalchemy"
] |
Error in acorr_ljungbox from statsmodel | 39,916,771 | <p>So I am trying to do a box-ljung test on a resudual, but I am getting a strange error and am not able to figure out why.</p>
<pre><code>x = diag.acorr_ljungbox(np.random.random(20))
</code></pre>
<p>I tried doing the same with a random array also, still the same error:</p>
<pre class="lang-none prettyprint-overri... | 0 | 2016-10-07T12:00:49Z | 39,919,347 | <p>This looks like a bug in the default lag setting, which is set to 40 independent of the length of the data.</p>
<p>As a workaround and to get a proper statistic, the <code>lags</code> needs to be restricted, e.g. using 5 lags below.</p>
<pre><code>>>> from statsmodels.stats import diagnostic as diag
>... | 0 | 2016-10-07T14:12:29Z | [
"python",
"statsmodels"
] |
Making a real time application which uses same python code continuously on a server, libraries import on each run and consume memory and time | 39,916,811 | <p>I am developing a real time navigation application on Android, what it does is collects relevant data from user's smartphone and pings a python code on server with the data. The python code then returns the real time location of the user. Now given that I need to run the same python code again and again, the same ex... | 0 | 2016-10-07T12:02:55Z | 39,916,917 | <p>You usually have a web API that responds to the Android apps. These APIs are usually provided by a Python App behind a web server. One way of doing a Python app behind a webserver is by using <a href="https://www.fullstackpython.com/wsgi-servers.html" rel="nofollow">WSGI</a>. All available WSGI implementation do the... | 2 | 2016-10-07T12:08:21Z | [
"python",
"amazon-web-services",
"server",
"real-time",
"libraries"
] |
Matplotlib updating live plot | 39,916,824 | <p>I want to update a line plot with matplotlib and wonder, if there is a good modification of the code, such that the line plotted simply gets updated instead of getting redrawn every time. Here is a sample code:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
matplotlib.style.us... | -1 | 2016-10-07T12:03:41Z | 39,916,933 | <p>Yes.</p>
<pre><code>x = np.arange(10)
y = np.random.rand(10)
line, = plt.plot(x,y)
line.set_data(x,np.random.rand(10))
plt.draw()
</code></pre>
<p>However, your plotting gets slower because your are extending your data frame and each append operation presumably copies that frame in memory to a new location. As yo... | 1 | 2016-10-07T12:09:11Z | [
"python",
"matplotlib",
"plot",
"while-loop"
] |
Difference between 2 datetimes in a data frame lose ns precision | 39,916,845 | <p>I have a data frame with 2 columns Event_A / Event_B that looks like this :</p>
<pre class="lang-none prettyprint-override"><code>In [8]: print (df)
Event_A Event_B
0 2016-10-03 02:00:09.123456789 2016-10-03 02:00:09.123456547
</code></pre>
<p>Both columns contain date... | 2 | 2016-10-07T12:04:36Z | 39,917,008 | <p>This looks like a display issue, if you access <code>dt.nanoseconds</code> then it will show the difference in nanosecond resolution:</p>
<pre><code>In [85]:
(df['Event_A']- df['Event_B']).dt.nanoseconds
Out[85]:
0 242
dtype: int64
</code></pre>
| 1 | 2016-10-07T12:12:39Z | [
"python",
"pandas",
"dataframe"
] |
How to extract all href content from a page using scrapy | 39,916,940 | <p>I am trying to crawl <a href="https://www.goodreads.com/list/show/19793.I_Marked_My_Calendar_For_This_Book_s_Release" rel="nofollow">https://www.goodreads.com/list/show/19793.I_Marked_My_Calendar_For_This_Book_s_Release</a>.</p>
<p>I want to get all links from a given website using Scrapy</p>
<p>I am trying to thi... | 0 | 2016-10-07T12:09:32Z | 39,917,070 | <p>I think your xpath is worng. Try this-</p>
<pre><code>for href in response.xpath('//div[@id="all_votes"]/table[@class="tableList js-dataTooltip"]/tr/td[2]/div[@class="js-tooltipTrigger tooltipTrigger"]/a/@href'):
full_url = response.urljoin(href.extract())
print full_url
</code></pre>... | 1 | 2016-10-07T12:15:14Z | [
"python",
"scrapy"
] |
pyspark: StructField(..., ..., False) always returns `nullable=true` instead of `nullable=false` | 39,917,075 | <p>I'm new to pyspark and am facing a strange problem. I'm trying to set some column to non-nullable while loading a CSV dataset. I can reproduce my case with a very small dataset (<code>test.csv</code>):</p>
<pre><code>col1,col2,col3
11,12,13
21,22,23
31,32,33
41,42,43
51,,53
</code></pre>
<p>There is a null value a... | 0 | 2016-10-07T12:15:24Z | 39,917,782 | <p>While Spark behavior (switch from <code>False</code> to <code>True</code> here is confusing there is nothing fundamentally wrong going on here. <code>nullable</code> argument is not a constraint but a reflection of the source and type semantics which enables certain types of optimization</p>
<p>You state that you w... | 1 | 2016-10-07T12:52:25Z | [
"python",
"apache-spark",
"pyspark",
"spark-dataframe"
] |
Implement delayed Slack slash response | 39,917,272 | <p>I want to implement slack slash command that has to process fucntion <code>pipeline</code> which takes roughly 30 seconds to process. Now since <a href="https://api.slack.com/slash-commands#responding_to_a_command" rel="nofollow">Slack</a> slash commands only allows 3 seconds to respond, how to go about implementing... | 1 | 2016-10-07T12:25:19Z | 39,918,072 | <p>Something like this:</p>
<pre><code>from boto import sqs
@route('/action', method='POST')
def action():
#retrieving all the required request example
params = request.forms.get('response_url')
sqs_queue = get_sqs_connection(queue_name)
message_object = sqs.message.Message()
message_object.set_bo... | 2 | 2016-10-07T13:07:19Z | [
"python",
"response",
"slack-api",
"slack",
"slash"
] |
Implement delayed Slack slash response | 39,917,272 | <p>I want to implement slack slash command that has to process fucntion <code>pipeline</code> which takes roughly 30 seconds to process. Now since <a href="https://api.slack.com/slash-commands#responding_to_a_command" rel="nofollow">Slack</a> slash commands only allows 3 seconds to respond, how to go about implementing... | 1 | 2016-10-07T12:25:19Z | 39,921,127 | <p>You have an option or two for doing this in a single process, but it's fraught with peril. If you spin up a new <code>Thread</code> to handle the long process, you might end up deploying or crashing in the middle and losing it.</p>
<p>If durability is important to you, look into background-task workers like SQS, La... | 0 | 2016-10-07T15:42:42Z | [
"python",
"response",
"slack-api",
"slack",
"slash"
] |
Why doesnt this regex work? | 39,917,569 | <p>Here is the code in question:</p>
<pre><code>import subprocess
import re
import os
p = subprocess.Popen(["nc -zv 8.8.8.8 53"], stdout=subprocess.PIPE, shell = True)
out, err = p.communicate()
regex = re.search("succeeded", out)
if not regex:
print ("test")
</code></pre>
<p>What i want it to do is to print out... | 0 | 2016-10-07T12:41:01Z | 39,917,623 | <p>The output is coming out stderr not stdout:</p>
<pre><code>stderr=subprocess.PIPE
</code></pre>
<p>You can simplify to using in and you don't need shell=True:</p>
<pre><code>p = subprocess.Popen(["nc", "-zv", "8.8.8.8", "53"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
if "succeed... | 3 | 2016-10-07T12:44:01Z | [
"python",
"regex",
"netcat"
] |
When trying to log in using requests module, I get an error because the User/Password fields are blank | 39,917,676 | <p>I've been trying to make a scraper to get my grades from my schools website. Unfortunately i cannot log in. When i try to run the program, the return page validates the user/password fields, and since they are blank, it's not letting me proceed.</p>
<p>Also, i am not really sure if I am even coding this correctly.<... | 0 | 2016-10-07T12:47:16Z | 39,917,792 | <p>Your payload uses the wrong keys, try</p>
<pre><code>ctl00$cphMainContent$lgnEaglesNest$UserName
ctl00$cphMainContent$lgnEaglesNest$Password
</code></pre>
<p>You can check the names by watching the network traffic in your browser (e.g. in Firefox: inspect element --> network --> post --> params)</p>
<p>In additio... | 0 | 2016-10-07T12:52:53Z | [
"python",
"web-scraping",
"python-requests"
] |
When trying to log in using requests module, I get an error because the User/Password fields are blank | 39,917,676 | <p>I've been trying to make a scraper to get my grades from my schools website. Unfortunately i cannot log in. When i try to run the program, the return page validates the user/password fields, and since they are blank, it's not letting me proceed.</p>
<p>Also, i am not really sure if I am even coding this correctly.<... | 0 | 2016-10-07T12:47:16Z | 39,919,164 | <p>First, make sure you are setting the cookies that you need to set correctly. I'd recommend setting them on the session-object:</p>
<pre><code>s = requests.Session()
s.cookies.set("key", "value", domain=".site.com") # the domain is optional
</code></pre>
<p>There are a couple of ways to inspect the results of your ... | -1 | 2016-10-07T14:02:52Z | [
"python",
"web-scraping",
"python-requests"
] |
Add new version scikit-learn to spyder | 39,917,683 | <p>I have downloaded the newest version of scikit-learn (0.18), however, spyder keeps on using the previous version (0.17). How do I make the two compatible? </p>
<p>I have updated both distributions using Anaconda: </p>
<pre><code>conda update spyder
conda update scikit-learn
</code></pre>
| 0 | 2016-10-07T12:47:29Z | 39,918,040 | <p>You may have different versions of sklearn installed (via pip and conda), and spyder using your /usr/bin/python instead of anaconda/bin/python: make sure that the interpreter selected in Spyder preferences is the anaconda one.</p>
| 0 | 2016-10-07T13:06:04Z | [
"python",
"scikit-learn",
"anaconda",
"spyder"
] |
How to search and treat the result with Tweepy | 39,917,708 | <p>I 'm was looking for a module to make research in tweeter (the research bar) and take the profile id/username of all the profile in link with the research.</p>
<p>I have seen the api tweepy, i think the answer i'm looking for is hide in thes 2 fonction :
search_users
_lookup_users</p>
<pre><code>#!/usr/bin/env p... | 0 | 2016-10-07T12:48:24Z | 39,918,189 | <p>You linked to the source code, not to the doc. The doc can be found <a href="http://docs.tweepy.org/en/v3.5.0/api.html" rel="nofollow">here</a>; be careful though, as it is not very up-to-date.</p>
<p>You can just do:</p>
<pre><code>import tweepy
CONSUMER_KEY = "#"
CONSUMER_SECRET = "#"
ACCESS_KEY = "#"
ACCESS_SE... | 0 | 2016-10-07T13:14:16Z | [
"python",
"tweepy"
] |
Pythonic way of writing multiple regex tests | 39,917,765 | <p>How to write in a Pythonic way when there are multiple regex patterns to test with and extract matched groups if a test succeeds?</p>
<p>That is to say, what is the Pythonic equivalent of the following code snippet?</p>
<pre><code>if re.match(pattern1, string):
m = re.match(pattern1, string)
grps = m.group... | 1 | 2016-10-07T12:51:29Z | 39,917,826 | <pre><code>patterns = [pattern1, pattern2, pattern3]
for pattern in patterns:
m = re.match(pattern, string)
if m:
grps = m.groups()
...
break
</code></pre>
| 4 | 2016-10-07T12:54:43Z | [
"python"
] |
Regex and returning two lists as a tuple | 39,917,965 | <p>I have this function, that I would like to see if can be done more pythonic.
The function explains it self what it is trying to achieve.</p>
<p>My concern is that I'm using two regex expressions for <code>content</code> and <code>expected</code> that gives room for error creeping in, best would be if these two vari... | 1 | 2016-10-07T13:01:33Z | 39,918,365 | <p>You can match both groups at the same time:</p>
<pre><code>def custom_steps(self, test_names):
regex = 'tests\["(.*)(?::|"\]).* = (.+)(?::|;)'
for match in re.finditer(regex, test_names):
content, expected = match.groups()
if '===' in expected:
expected = expected[expected.index(... | 1 | 2016-10-07T13:24:48Z | [
"python",
"regex",
"python-2.7"
] |
Django 1.9 to 1.10 raises NoReverseMatch: u'en-gb' is not a registered namespace | 39,917,987 | <p>I am trying to update my 1.9 application to 1.10 and I am getting the following error on running all my unit tests:</p>
<pre><code>Traceback (most recent call last): File "/home/â¦/tests/views/test_configurator.py", line 261, in test_view_configurator_post
args=[self.configurator.id]), File "/home/â¦/.vir... | 2 | 2016-10-07T13:02:48Z | 39,918,791 | <p>Your <code>LANGUAGE_CODE</code> setting is set to <code>en_gb</code>.. Notice the underscore character.. It should be<code>en-gb</code>.</p>
| -1 | 2016-10-07T13:45:04Z | [
"python",
"django",
"internationalization"
] |
Understanding variable types, names and assignment | 39,917,988 | <p>In Python, if you want to define a variable, you don't have to specify the type of it, unlike other languages such as C and Java.</p>
<p>So how can the Python interpreter distinguish between variables and give it the required space in memory like <code>int</code> or <code>float</code>?</p>
| 3 | 2016-10-07T13:02:58Z | 39,918,038 | <p>In Python all values are objects with built-in type info. Variables are references to these values. So their type is 'dynamic', just equal to the type of what they happen to refer to (point to) at a particular moment.</p>
<p>Whenever memory is allocated for the contents of a variable, a value is available. Since it... | 7 | 2016-10-07T13:06:02Z | [
"python"
] |
Understanding variable types, names and assignment | 39,917,988 | <p>In Python, if you want to define a variable, you don't have to specify the type of it, unlike other languages such as C and Java.</p>
<p>So how can the Python interpreter distinguish between variables and give it the required space in memory like <code>int</code> or <code>float</code>?</p>
| 3 | 2016-10-07T13:02:58Z | 39,918,089 | <p>Python is dynamically typed language which means that the type of variables are decided in running time. As a result python interpreter will distinguish the variable's types (in running time) and give the exact space in memory needed. Despite being dynamically typed, Python is strongly typed, forbidding operations... | 2 | 2016-10-07T13:08:05Z | [
"python"
] |
Understanding variable types, names and assignment | 39,917,988 | <p>In Python, if you want to define a variable, you don't have to specify the type of it, unlike other languages such as C and Java.</p>
<p>So how can the Python interpreter distinguish between variables and give it the required space in memory like <code>int</code> or <code>float</code>?</p>
| 3 | 2016-10-07T13:02:58Z | 39,918,342 | <p>Dynamically typed languages typically use boxed representation, which includes runtime type information. E.g. instead of storing direct pointers to a value, the system uses a box struct that contains the value (or pointer to it) as well as some additional metainformation. You can see how he standard Python implemen... | 6 | 2016-10-07T13:23:45Z | [
"python"
] |
Understanding variable types, names and assignment | 39,917,988 | <p>In Python, if you want to define a variable, you don't have to specify the type of it, unlike other languages such as C and Java.</p>
<p>So how can the Python interpreter distinguish between variables and give it the required space in memory like <code>int</code> or <code>float</code>?</p>
| 3 | 2016-10-07T13:02:58Z | 39,918,601 | <p>The Python interpreter analyzes each variable when the program runs. Before running, it doesn't know whether you've got an integer, a float, or a string in any of your variables.</p>
<p>When you have a statically typed language background (Java in my case), it's a bit unusual. Dynamic typing saves you a lot of time... | 1 | 2016-10-07T13:35:49Z | [
"python"
] |
Pandas dataframe rearrangement stack to two value columns (for factorplots) | 39,918,053 | <p>I have been trying to rearrange my dataframe to use it as input for a factorplot. The raw data would look like this:</p>
<pre><code> A B C D
1 0 1 2 "T"
2 1 2 3 "F"
3 2 1 0 "F"
4 1 0 2 "T"
...
</code></pre>
<p>My question is how can I rearrange it into this form:</p>
<pre><code> col val val2
1 A 0 "T"
1 B... | 3 | 2016-10-07T13:06:39Z | 39,918,391 | <p>consider your dataframe <code>df</code></p>
<pre><code>df = pd.DataFrame([
[0, 1, 2, 'T'],
[1, 2, 3, 'F'],
[2, 1, 3, 'F'],
[1, 0, 2, 'T'],
], [1, 2, 3, 4], list('ABCD'))
</code></pre>
<p><a href="http://i.stack.imgur.com/XtqBK.png" rel="nofollow"><img src="http://i.stack.imgur.c... | 2 | 2016-10-07T13:25:56Z | [
"python",
"pandas",
"stack",
"cumsum"
] |
Pandas dataframe rearrangement stack to two value columns (for factorplots) | 39,918,053 | <p>I have been trying to rearrange my dataframe to use it as input for a factorplot. The raw data would look like this:</p>
<pre><code> A B C D
1 0 1 2 "T"
2 1 2 3 "F"
3 2 1 0 "F"
4 1 0 2 "T"
...
</code></pre>
<p>My question is how can I rearrange it into this form:</p>
<pre><code> col val val2
1 A 0 "T"
1 B... | 3 | 2016-10-07T13:06:39Z | 39,918,511 | <p>I would use melt, and you can sort it how ever you like</p>
<pre><code>pd.melt(df.reset_index(),id_vars=['index','D'], value_vars=['A','B','C']).sort_values(by='index')
Out[40]:
index D variable value
0 1 T A 0
4 1 T B 1
8 1 T C 2
1 2 F A... | 3 | 2016-10-07T13:31:29Z | [
"python",
"pandas",
"stack",
"cumsum"
] |
What is the pythonic way to skip parent method? | 39,918,071 | <pre><code>class A:
def open_spider(self, spider):
#do some hacking
class B(A):
def open_spider(self, spider):
super(B, self).open_spider(spider)
#something else
</code></pre>
<p>Now I want C to call A's method but not B's, which can be done at least in two ways:</p>
<pre><code> class C(B):
def ... | 1 | 2016-10-07T13:07:19Z | 39,918,219 | <p>Use the second method; this is one reason why <code>super</code> <em>takes</em> a class as its first argument. </p>
| 0 | 2016-10-07T13:15:42Z | [
"python",
"inheritance"
] |
What is the pythonic way to skip parent method? | 39,918,071 | <pre><code>class A:
def open_spider(self, spider):
#do some hacking
class B(A):
def open_spider(self, spider):
super(B, self).open_spider(spider)
#something else
</code></pre>
<p>Now I want C to call A's method but not B's, which can be done at least in two ways:</p>
<pre><code> class C(B):
def ... | 1 | 2016-10-07T13:07:19Z | 39,918,526 | <p>You can do it using the second way. But I must say that part where child skips parent method and call grandparent instead is wrong and you should take a look on your design once again and think about it.</p>
| 3 | 2016-10-07T13:32:16Z | [
"python",
"inheritance"
] |
Pandas, filter max values by row and columns | 39,918,262 | <p>I have this dataframe.</p>
<pre><code>In [6]: df
Out[6]:
Beam Pos Comb As
0 B1 1 1 3
1 B1 1 1 2
2 B1 2 1 5
3 B1 2 1 8
4 B1 1 2 10
5 B1 1 2 1
6 B1 2 2 3
7 ... | -1 | 2016-10-07T13:18:21Z | 39,918,343 | <p>you have to use the <code>groupby</code> method on the multi level index:</p>
<pre><code>d = df.groupby(by= [ "Beam", "Pos", "Comb"])
g=d.agg({"As":"max"})
g.reset_index(inplace=True)
</code></pre>
<p>the first line groups together the items that have the same <code>(Beam,Pos,Comb)</code> index,
the second line s... | 2 | 2016-10-07T13:23:47Z | [
"python",
"pandas",
"filter",
"group"
] |
Pandas, filter max values by row and columns | 39,918,262 | <p>I have this dataframe.</p>
<pre><code>In [6]: df
Out[6]:
Beam Pos Comb As
0 B1 1 1 3
1 B1 1 1 2
2 B1 2 1 5
3 B1 2 1 8
4 B1 1 2 10
5 B1 1 2 1
6 B1 2 2 3
7 ... | -1 | 2016-10-07T13:18:21Z | 39,918,558 | <p>How about this?</p>
<pre><code>groups = df.groupby(by=['Beam', "Pos"])
idx = []
for group in groups:
idx += [group[1].As.argmax()]
</code></pre>
<p>than show
<code>df.iloc[idx]</code></p>
| 0 | 2016-10-07T13:33:33Z | [
"python",
"pandas",
"filter",
"group"
] |
Pandas, filter max values by row and columns | 39,918,262 | <p>I have this dataframe.</p>
<pre><code>In [6]: df
Out[6]:
Beam Pos Comb As
0 B1 1 1 3
1 B1 1 1 2
2 B1 2 1 5
3 B1 2 1 8
4 B1 1 2 10
5 B1 1 2 1
6 B1 2 2 3
7 ... | -1 | 2016-10-07T13:18:21Z | 39,922,599 | <p>You should be using the native pandas functions instead of recreating the wheel to make this extremely simple and easy to remember:</p>
<pre><code>df.groupby(['Beam', 'Pos', 'Comb']).max()
</code></pre>
| 0 | 2016-10-07T17:07:21Z | [
"python",
"pandas",
"filter",
"group"
] |
cleaning a txt. Best way to delete recuring beginning code line | 39,918,322 | <p>I have to clean a csv file that has this structure:</p>
<pre>Schema Compare Sync Script
06/10/2016 11:05:03 Page 1
1 --------------------------------------------------------------------------
2 -- Play this script in ASIA@COG2 to make it look like ASIA@TSTCOG2
3 --
4 -- Please review the script before using it to m... | 0 | 2016-10-07T13:22:39Z | 39,919,001 | <p>Digits at start of line can be used for filtering:</p>
<pre><code>with open("delta.txt", "r") as infile, open('delta_fil2.txt', 'w') as outfile:
for line in infile:
sline = line.split(" ")
if len(sline) < 2 : continue
if sline[0].isdigit() and sline[1] != "--":
outfile.write(line[len(sline[... | 0 | 2016-10-07T13:54:35Z | [
"python",
"parsing",
"itertools"
] |
How to use the subprocess.check_output comand correctly | 39,918,331 | <p>I want to execute the the shell script <code>generateLicense.sh</code> with different arguments. I do it like that:</p>
<pre><code>License = subprocess.check_output(['./generateLicense.sh -firstargument 1 -secondargument 2 -thirdargument 3'])
</code></pre>
<p>The shell script is in the same folder as the file that... | 0 | 2016-10-07T13:23:02Z | 39,918,409 | <p>Using <a href="https://docs.python.org/3/library/subprocess.html#subprocess.check_output" rel="nofollow">check_output</a> the way you are trying to, each command has to be an item in the list you are passing. So, what you should have is: </p>
<pre><code>License = subprocess.check_output(['./generateLicense.sh', '-f... | 0 | 2016-10-07T13:26:37Z | [
"python",
"shell",
"subprocess"
] |
Split string based on number of commas | 39,918,386 | <p>I have a text which is splited with commas.</p>
<p>e.g.:</p>
<pre><code>FOO( something, BOO(tmp, temp), something else)
</code></pre>
<p>It could be that <em>something else</em> contain as well a string with commas...</p>
<p>I would like to split the text inside the brakets of FOO to its elements and then pasrse... | 0 | 2016-10-07T13:25:49Z | 39,918,505 | <p>Take a look at the python CSV library: </p>
<p><a href="https://docs.python.org/2/library/csv.html" rel="nofollow">https://docs.python.org/2/library/csv.html</a> (python 2)</p>
<p><a href="https://docs.python.org/3/library/csv.html" rel="nofollow">https://docs.python.org/3/library/csv.html</a> (python 3)</p>
<p>I... | -1 | 2016-10-07T13:31:16Z | [
"python",
"regex"
] |
Split string based on number of commas | 39,918,386 | <p>I have a text which is splited with commas.</p>
<p>e.g.:</p>
<pre><code>FOO( something, BOO(tmp, temp), something else)
</code></pre>
<p>It could be that <em>something else</em> contain as well a string with commas...</p>
<p>I would like to split the text inside the brakets of FOO to its elements and then pasrse... | 0 | 2016-10-07T13:25:49Z | 39,918,942 | <p>Assuming that the string is Python code you can use <strong>parser</strong> for this. If you look carefully at the result you might agree that it's not as bad as it first appears to be.</p>
<pre><code>>>> from parser import *
>>> source="FOO( something, BOO(tmp, temp), something)"
>>> st=... | 0 | 2016-10-07T13:51:47Z | [
"python",
"regex"
] |
Split string based on number of commas | 39,918,386 | <p>I have a text which is splited with commas.</p>
<p>e.g.:</p>
<pre><code>FOO( something, BOO(tmp, temp), something else)
</code></pre>
<p>It could be that <em>something else</em> contain as well a string with commas...</p>
<p>I would like to split the text inside the brakets of FOO to its elements and then pasrse... | 0 | 2016-10-07T13:25:49Z | 39,918,951 | <p>You may use this regex</p>
<pre><code>,(?=(?:(?:\([^)]*\))?[^)]*)+\)$)
</code></pre>
<p>to split your string in the comas, bot not inside BOO(...)</p>
<p><a href="https://eval.in/657163" rel="nofollow">sample</a></p>
| 0 | 2016-10-07T13:52:14Z | [
"python",
"regex"
] |
Split string based on number of commas | 39,918,386 | <p>I have a text which is splited with commas.</p>
<p>e.g.:</p>
<pre><code>FOO( something, BOO(tmp, temp), something else)
</code></pre>
<p>It could be that <em>something else</em> contain as well a string with commas...</p>
<p>I would like to split the text inside the brakets of FOO to its elements and then pasrse... | 0 | 2016-10-07T13:25:49Z | 39,919,721 | <p>You can do it with the <a href="https://pypi.python.org/pypi/regex" rel="nofollow">regex module</a> that supports recursion (useful to deal with nested structures):</p>
<pre><code>import regex
s = 'FOO( something, BOO(tmp, temp), something else)'
pat = regex.compile(r'''(?(DEFINE) # inside a definition group
... | 0 | 2016-10-07T14:30:10Z | [
"python",
"regex"
] |
Split string based on number of commas | 39,918,386 | <p>I have a text which is splited with commas.</p>
<p>e.g.:</p>
<pre><code>FOO( something, BOO(tmp, temp), something else)
</code></pre>
<p>It could be that <em>something else</em> contain as well a string with commas...</p>
<p>I would like to split the text inside the brakets of FOO to its elements and then pasrse... | 0 | 2016-10-07T13:25:49Z | 39,922,023 | <p>Assuming that you need a list of elements inside <code>FOO</code>, so pre-processing it first</p>
<pre><code>>>> s = 'FOO( something, BOO(tmp, temp), something else)'
>>> s
'FOO( something, BOO(tmp, temp), something else)'
>>> s = re.sub(r'^[^(]+\(|\)\s*$','',s)
>>> s
' something... | 0 | 2016-10-07T16:32:14Z | [
"python",
"regex"
] |
Seaborn/Matplotlib - Only Showing Certain X Values in FacetGrid | 39,918,424 | <p>I am trying to create a facet of charts that show total scores over time, in seconds. X axis is the time in seconds and y axis is the total score.</p>
<p>As you can see, I am restricting the output to 2 1/2 minutes via xlim . </p>
<p>What I would like to do is to only show values on the xaxis for every 30 second... | 1 | 2016-10-07T13:27:10Z | 39,921,257 | <p>This will solve your problem:</p>
<pre><code>g = (g.map(sns.pointplot, "timeinseconds", "totalscore", scale=.7)
.set(xticks=[3, 5, 6, 7, 9], xticklabels=[30, 60, 90, 120, 150]))
</code></pre>
<p>The <code>xticks</code> indicate the positions where you want to place the labels (numbered from <code>0</code> to ... | 1 | 2016-10-07T15:49:35Z | [
"python",
"pandas",
"matplotlib",
"seaborn",
"facet"
] |
How to print a div data-reactid? | 39,918,436 | <p>I'm doing a project in my spare time where I have hit a problem with getting data from a webpage into the program.</p>
<p>This is my current code:</p>
<pre><code>import urllib
import re
htmlfile = urllib.urlopen("http://www.superliga.dk/klub/aab?sub=squad")
htmltext = htmlfile.read()
regex = r'<div data-reac... | 2 | 2016-10-07T13:27:44Z | 39,918,761 | <p>You are trying to match a tag you saw on the on the developer console of you browser, right?
Unfortunately the html you saw is only the "final form" of a dynamic page: what you did download with <code>urlopen</code> is only the skeleton of the webpage, which in the browser is then dynamically filled with other eleme... | 1 | 2016-10-07T13:43:43Z | [
"python",
"html",
"regex"
] |
Python Pandas_How to select data after using drop_duplicates()? | 39,918,483 | <p>I am learning python pandas to processing data. </p>
<ol>
<li>I firstly using <code>drop_duplicates()</code> method to treat <code>db_new</code> and get <code>a</code>;</li>
<li>Then I'd like to find what kind of data in a using <code>print</code>;</li>
<li>I try to find if a data is in a using <code>for...in</code... | -2 | 2016-10-07T13:30:15Z | 39,919,475 | <p>Here <code>a</code> is a dataframe, so when you iterate over <code>a</code> you iterate over column names, hence the result, <code>E</code>.</p>
<p>If you want to iterate over values, you need to make <code>a</code> a series, which you can do using <code>squeeze</code>:</p>
<pre><code>for x in a.squeeze():
pri... | 1 | 2016-10-07T14:19:34Z | [
"python",
"pandas"
] |
BeautifulSoup: get text from some tag | 39,918,563 | <p>I have data</p>
<pre><code><span class="label">ÐÑивод:</span> пеÑедний<br/>
<span class="label">Тип кÑзова:</span> Ñедан<br/>
<span class="label">ЦвеÑ:</span> ÑеÑÑй<br/>
<span class="label">ÐÑобег по РоÑÑиÐ... | 0 | 2016-10-07T13:33:48Z | 39,918,596 | <p>In the first code snippet, you are trying to get the text of the <code>br</code> element but it does not have any.</p>
<p>In the second code snippet you have a typo - it is not <code>next_subling</code>, it is <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#next-sibling-and-previous-sibling" rel="no... | 3 | 2016-10-07T13:35:32Z | [
"python",
"beautifulsoup"
] |
replacing value with median in python | 39,918,769 | <pre><code>lat
50.63757782
50.6375742
50.6375742
50.6374077762
50.63757782
50.6374077762
50.63757782
50.63757782
</code></pre>
<p>I have plotted a graph with these latitude values and noticed that there was sudden spike in the graph (outlier). I want to replace every lat value with median of last three values so that ... | 1 | 2016-10-07T13:43:58Z | 39,918,926 | <p>Just go thought second to second to last elements and put save the median out of this, previous and next element. Note that first and last elements are left as they were.</p>
<p>Try this:</p>
<pre><code>lat = [50.63757782, 50.6375742, 50.6375742, 50.6374077762, 50.63757782, 50.6374077762, 50.63757782, 50.63757782]... | 0 | 2016-10-07T13:51:25Z | [
"python",
"numpy",
"replace",
"median",
"imputation"
] |
replacing value with median in python | 39,918,769 | <pre><code>lat
50.63757782
50.6375742
50.6375742
50.6374077762
50.63757782
50.6374077762
50.63757782
50.63757782
</code></pre>
<p>I have plotted a graph with these latitude values and noticed that there was sudden spike in the graph (outlier). I want to replace every lat value with median of last three values so that ... | 1 | 2016-10-07T13:43:58Z | 39,919,540 | <p>You seem to be using <code>pandas</code>' <code>Dataframe</code> structures, so:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'lat' : [50.63757782,
50.6375742,
50.6375742,
50.6374077762,
... | 0 | 2016-10-07T14:22:29Z | [
"python",
"numpy",
"replace",
"median",
"imputation"
] |
NetworkX: plotting the same graph first intact and then with a few nodes removed | 39,918,821 | <p>Say I have a graph with <code>10</code> nodes, and I want to plot it when:</p>
<ol>
<li>It is intact</li>
<li>It has had a couple of nodes removed</li>
</ol>
<p><strong>How can I make sure that the second plot has exactly the same positions as the first one?</strong></p>
<p>My attempt generates two graphs that ar... | 0 | 2016-10-07T13:46:33Z | 39,925,948 | <p>The drawing commands for networkx accept an argument <code>pos</code>. </p>
<p>So before creating <code>fig1</code>, define <code>pos</code> The two lines should be</p>
<pre><code>pos = nx.spring_layout(G) #other layout commands are available.
fig1 = nx.draw_networkx(G, pos = pos)
</code></pre>
<p>later you wil... | 2 | 2016-10-07T21:18:50Z | [
"python",
"matplotlib",
"networkx"
] |
NetworkX: plotting the same graph first intact and then with a few nodes removed | 39,918,821 | <p>Say I have a graph with <code>10</code> nodes, and I want to plot it when:</p>
<ol>
<li>It is intact</li>
<li>It has had a couple of nodes removed</li>
</ol>
<p><strong>How can I make sure that the second plot has exactly the same positions as the first one?</strong></p>
<p>My attempt generates two graphs that ar... | 0 | 2016-10-07T13:46:33Z | 39,927,005 | <p>The following works for me:</p>
<pre><code>import networkx as nx
import matplotlib.pyplot as plt
from random import random
figure = plt.figure()
#Intact
G=nx.barabasi_albert_graph(10,3)
node_pose = {}
for i in G.nodes_iter():
node_pose[i] = (random(),random())
plt.subplot(121)
fig1 = nx.draw_networkx(G,pos=... | 1 | 2016-10-07T23:17:23Z | [
"python",
"matplotlib",
"networkx"
] |
Data extraction: Creating dictionary of dictionaries with lists in python | 39,918,972 | <p>I have data similar to the following in a file:</p>
<pre><code>Name, Age, Sex, School, height, weight, id
Joe, 10, M, StThomas, 120, 20, 111
Jim, 9, M, StThomas, 126, 22, 123
Jack, 8, M, StFrancis, 110, 15, 145
Abel, 10, F, StFrancis, 128, 23, 166
</code></pre>
<p>The actual data might be 100 columns and a mil... | 1 | 2016-10-07T13:53:13Z | 39,919,171 | <p>The easiest way to do this within the standard library is using existing tools, <a href="https://docs.python.org/3/library/csv.html#csv.DictReader" rel="nofollow"><code>csv.DictReader</code></a> and <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow"><code>collections.... | 1 | 2016-10-07T14:03:12Z | [
"python",
"dictionary"
] |
Django/Python: Show pdf in a template | 39,919,012 | <p>I'm using django 1.8 in python 2.7.</p>
<p>I want to show a pdf in a template.</p>
<p>Up to know, thanks to <a href="http://stackoverflow.com/a/29718326/1395874">MKM's answer</a> I render it in a full page. </p>
<p>Do you know how to render it?</p>
<p>Here is my code:</p>
<pre><code>def userManual(request):
... | 1 | 2016-10-07T13:55:09Z | 39,934,037 | <p>The ability to embed a PDF in a page is out of the scope of Django itself, you are already doing all you can do with Django by successfully generating the PDF, so you should look at how to embed PDFs in webpages instead:</p>
<p>Therefore, please check:</p>
<p><a href="http://stackoverflow.com/questions/291813/reco... | 1 | 2016-10-08T15:18:00Z | [
"python",
"django",
"pdf"
] |
Column appended in a pandas dataframe malfunctions | 39,919,020 | <p>I have a dataframe named df1</p>
<pre><code> df1.columns
Out[55]: Index(['TowerLon', 'TowerLat'], dtype='object')
df1.shape
Out[56]: (1141, 2)
df1.head(3)
Out[57]:
TowerLon TowerLat
0 -96.709417 32.731611
1 -96.709500 32.731722
2 -96.910389 32.899944
</code></pre>
<p>I also hav... | 0 | 2016-10-07T13:55:37Z | 39,973,962 | <p>The <code>AttributeError</code> occurs due to the fact that <code>labels</code> is not part of the original <code>DataFrame</code>. You can however access the data by using the following method:</p>
<pre><code>df1['labels']
</code></pre>
<p>This will give you the following output:</p>
<pre><code>0 1
1 1
2 ... | 0 | 2016-10-11T09:13:28Z | [
"python"
] |
Duplicate tweet removal from csv file | 39,919,041 | <p>With the part of code shown below i fetch tweets from twitter and store them initially in "backup.txt". I also create a file "tweets3.csv"and save some specific fields of each tweets. But i realized some tweets have exactly the same text (duplicates). How could i remove those from my csv file?</p>
<pre><code>from t... | 0 | 2016-10-07T13:56:36Z | 39,920,097 | <p>I wrote this code that makes a list, and every time that it gets over a tweet, it checks that list. If the text doesn't exists, add it to the list.</p>
<pre><code># Defines a list - It stores all unique tweets
tweetChecklist = [];
# All your tweets. I represent them as a list to test the code
AllTweets = ["Hello",... | 1 | 2016-10-07T14:50:03Z | [
"python",
"tweepy"
] |
Calculate moving average in numpy array with NaNs | 39,919,050 | <p>I am trying to calculate the moving average in a large numpy array that contains NaNs. Currently I am using:</p>
<pre><code>import numpy as np
def moving_average(a,n=5):
ret = np.cumsum(a,dtype=float)
ret[n:] = ret[n:]-ret[:-n]
return ret[-1:]/n
</code></pre>
<p>When calculating with a masked ar... | 2 | 2016-10-07T13:56:59Z | 39,919,275 | <p>You could create a temporary array and use np.nanmean() (new in version 1.8 if I'm not mistaken):</p>
<pre><code>import numpy as np
temp = np.vstack([x[i:-(5-i)] for i in range(5)]) # stacks vertically the strided arrays
means = np.nanmean(temp, axis=0)
</code></pre>
<p>and put original nan back in place with <cod... | 0 | 2016-10-07T14:07:55Z | [
"python",
"numpy",
"masked-array"
] |
Calculate moving average in numpy array with NaNs | 39,919,050 | <p>I am trying to calculate the moving average in a large numpy array that contains NaNs. Currently I am using:</p>
<pre><code>import numpy as np
def moving_average(a,n=5):
ret = np.cumsum(a,dtype=float)
ret[n:] = ret[n:]-ret[:-n]
return ret[-1:]/n
</code></pre>
<p>When calculating with a masked ar... | 2 | 2016-10-07T13:56:59Z | 39,919,618 | <p>If I understand correctly, you want to create a moving average and then populate the resulting elements as <code>nan</code> if their index in the original array was <code>nan</code>.</p>
<pre><code>import numpy as np
>>> inc = 5 #the moving avg increment
>>> x = np.array([1.,3,np.nan,7,8,1,2,4,... | 0 | 2016-10-07T14:26:02Z | [
"python",
"numpy",
"masked-array"
] |
Calculate moving average in numpy array with NaNs | 39,919,050 | <p>I am trying to calculate the moving average in a large numpy array that contains NaNs. Currently I am using:</p>
<pre><code>import numpy as np
def moving_average(a,n=5):
ret = np.cumsum(a,dtype=float)
ret[n:] = ret[n:]-ret[:-n]
return ret[-1:]/n
</code></pre>
<p>When calculating with a masked ar... | 2 | 2016-10-07T13:56:59Z | 39,919,709 | <p>Here's an approach using strides -</p>
<pre><code>w = 5 # Window size
n = x.strides[0]
avgs = np.nanmean(np.lib.stride_tricks.as_strided(x, \
shape=(x.size-w+1,w), strides=(n,n)),1)
x_rem = np.append(x[-w+1:],np.full(w-1,np.nan))
avgs_rem = np.nanmean(np.lib.stride_tricks.as_strided(x... | 0 | 2016-10-07T14:29:39Z | [
"python",
"numpy",
"masked-array"
] |
Calculate moving average in numpy array with NaNs | 39,919,050 | <p>I am trying to calculate the moving average in a large numpy array that contains NaNs. Currently I am using:</p>
<pre><code>import numpy as np
def moving_average(a,n=5):
ret = np.cumsum(a,dtype=float)
ret[n:] = ret[n:]-ret[:-n]
return ret[-1:]/n
</code></pre>
<p>When calculating with a masked ar... | 2 | 2016-10-07T13:56:59Z | 39,920,628 | <p>I'll just add to the great answers before that you could still use cumsum to achieve this:</p>
<pre><code>import numpy as np
def moving_average(a, n=5):
ret = np.cumsum(a.filled(0))
ret[n:] = ret[n:] - ret[:-n]
counts = np.cumsum(~a.mask)
counts[n:] = counts[n:] - counts[:-n]
ret[~a.mask] /= co... | 1 | 2016-10-07T15:15:35Z | [
"python",
"numpy",
"masked-array"
] |
django gunicorn sock file not created by wsgi | 39,919,053 | <p>I have a basic django rest application in my digital ocean server (Ubuntu 16.04) with a local virtual environment.
The basic wsgi.py is:</p>
<pre><code>import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "workout_rest.settings")
# This application object is used by any WSGI server configured to use this
# f... | 1 | 2016-10-07T13:57:02Z | 39,924,519 | <p>I had to change the permissions of my sock folder:</p>
<pre><code>sudo chown ben:www-data /home/ben/myproject/
</code></pre>
<p>Another thing is that I have changed the sock location after reading in many post that it's not a good pratice to keep the sock file in the django project.
My new location is:</p>
<pre><... | 0 | 2016-10-07T19:27:11Z | [
"python",
"django",
"nginx",
"gunicorn"
] |
IndexError: index is out of bounds for axis 0 with size | 39,919,181 | <p>I have array <code>x_train</code> and <code>targets_train</code>. I want to shuffle the training data and split it into smaller batches and use the batches as training data. My original data has 1000 rows and each time I try to use 250 rows of them :</p>
<pre><code> x_train = np.memmap('/home/usr/train', dtype='... | 0 | 2016-10-07T14:03:38Z | 39,920,080 | <p>The problem is in this line in the function definition:</p>
<pre><code>idxs = train_idxs[start:start + batch_size]
</code></pre>
<p>Change it to:</p>
<pre><code>idxs = train_idxs[start: newstart]
</code></pre>
<p>Then it should work as expected!</p>
<p>Also, please change the variable names in the <code>for</co... | 1 | 2016-10-07T14:49:11Z | [
"python",
"arrays",
"list",
"numpy",
"machine-learning"
] |
IndexError: index is out of bounds for axis 0 with size | 39,919,181 | <p>I have array <code>x_train</code> and <code>targets_train</code>. I want to shuffle the training data and split it into smaller batches and use the batches as training data. My original data has 1000 rows and each time I try to use 250 rows of them :</p>
<pre><code> x_train = np.memmap('/home/usr/train', dtype='... | 0 | 2016-10-07T14:03:38Z | 39,922,558 | <p>(edit - first guess about <code>newstart</code> deleted)</p>
<p>In this line:</p>
<pre><code>x_train, targets_train, newstart = next_batch(i*batch_size, x_train, targets_train, batch_size=250)
</code></pre>
<p>you change the size of <code>x_train</code> with each iteration, yet you continue to use the <code>train... | 0 | 2016-10-07T17:04:37Z | [
"python",
"arrays",
"list",
"numpy",
"machine-learning"
] |
kivy - save user input into a python list | 39,919,218 | <p>I`m having some difficulties understanding the interrelation between kivy and python.</p>
<p>I`m trying to do something super simple, as a first step, and it would be great if anybody could show an example:
How can I store input data into a python list once the user feeds-in data and press "enter"?
Thanks</p>
| 0 | 2016-10-07T14:05:28Z | 39,919,298 | <p>An example of this. User can input 3 things and they get stored in an array. If you want the user to input one thing and store it in an array you will have to split the input.</p>
<pre><code>result = []
for i in range(3):
answer = input()
result.append(answer)
print(result)
</code></pre>
<p>NOTE: <code>in... | 1 | 2016-10-07T14:09:08Z | [
"python",
"kivy",
"kivy-language"
] |
Etree returns a "random" string instead of attribute name | 39,919,308 | <p>I am new to python and trees at all, and have encountered some problems.</p>
<p>I have the following dataset structured as:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns">
<node id="someNode">
<data key="label">someNode<... | 0 | 2016-10-07T14:09:56Z | 39,920,145 | <p>If you want to output your root and children nodes as xml text, instead of the default representation, use <code>xml.etree.ElementTree.tostring(root)</code> and</p>
<pre><code>for child in root:
xml.etree.ElementTree.tostring(child)
</code></pre>
<p>official doc here: <a href="https://docs.python.org/2/library... | 1 | 2016-10-07T14:52:10Z | [
"python",
"xml",
"tree",
"elementtree",
"graphml"
] |
How to check and encode input emojis from Facebook messenger? | 39,919,314 | <p>I'm building a Facebook messenger bot in Python. And everything works fine. But if I send <code>emojis</code> as text from Facebook chat to API, then it goes wrong.
This is an example when I send <code>emojis</code> from Facebook.</p>
<pre><code>{'message': {'mid': 'mid.1475846223244:e7eea53884', 'seq': 10863, 'te... | 0 | 2016-10-07T14:10:16Z | 39,919,614 | <p>You may use a mapping between unicode code-points and ASCII representation. See this kind of table here: <a href="http://lolhug.com/facebook-emoticons/" rel="nofollow">http://lolhug.com/facebook-emoticons/</a></p>
<p>The official Emoticons table is here: <a href="http://unicode-table.com/en/blocks/emoticons/" rel="... | 1 | 2016-10-07T14:25:55Z | [
"python",
"facebook",
"encoding",
"emoji"
] |
How to check and encode input emojis from Facebook messenger? | 39,919,314 | <p>I'm building a Facebook messenger bot in Python. And everything works fine. But if I send <code>emojis</code> as text from Facebook chat to API, then it goes wrong.
This is an example when I send <code>emojis</code> from Facebook.</p>
<pre><code>{'message': {'mid': 'mid.1475846223244:e7eea53884', 'seq': 10863, 'te... | 0 | 2016-10-07T14:10:16Z | 39,920,668 | <p>You should use the escaped version of the corresponding code point. This is a technique that allow you to express the whole Unicode range using only ASCII characters.</p>
<p>EG. The Emoji í ½í²© can be represented in Java as <code>"\uD83D\uDCA9"</code> or in Python as <code>u"\U0001F4A9"</code>. <a href="http://www... | 0 | 2016-10-07T15:17:18Z | [
"python",
"facebook",
"encoding",
"emoji"
] |
How do you preserve precision when scaling a Decimal? | 39,919,432 | <p>How can you scale a <a href="https://docs.python.org/library/decimal.html#decimal.Decimal" rel="nofollow"><code>Decimal</code></a>, but keep its original precision? E.g.,</p>
<pre><code>>>> from decimal import Decimal
>>> Decimal('0.1230')
Decimal('0.1230') # Precision is 4.
</code></pre>
<p>Mult... | 1 | 2016-10-07T14:17:11Z | 39,919,747 | <p>From the answer, <a href="http://stackoverflow.com/a/33948596/47078">http://stackoverflow.com/a/33948596/47078</a>, you could do something like the following. I'm not sure, though, if what you want is possible without additional code: namely to have a Decimal that preserves precision automatically.</p>
<pre><code>&... | 0 | 2016-10-07T14:31:07Z | [
"python",
"python-2.7"
] |
How do you preserve precision when scaling a Decimal? | 39,919,432 | <p>How can you scale a <a href="https://docs.python.org/library/decimal.html#decimal.Decimal" rel="nofollow"><code>Decimal</code></a>, but keep its original precision? E.g.,</p>
<pre><code>>>> from decimal import Decimal
>>> Decimal('0.1230')
Decimal('0.1230') # Precision is 4.
</code></pre>
<p>Mult... | 1 | 2016-10-07T14:17:11Z | 39,920,314 | <p>Use <a href="https://docs.python.org/2/library/decimal.html#decimal.setcontext" rel="nofollow">setcontext</a>:</p>
<pre><code>>>> mycontext=decimal.Context(prec=4)
>>> decimal.setcontext(mycontext)
>>> decimal.Decimal('0.1230')*decimal.Decimal('100')
Decimal('12.30')
</code></pre>
<p>If ... | 1 | 2016-10-07T15:00:29Z | [
"python",
"python-2.7"
] |
How do you preserve precision when scaling a Decimal? | 39,919,432 | <p>How can you scale a <a href="https://docs.python.org/library/decimal.html#decimal.Decimal" rel="nofollow"><code>Decimal</code></a>, but keep its original precision? E.g.,</p>
<pre><code>>>> from decimal import Decimal
>>> Decimal('0.1230')
Decimal('0.1230') # Precision is 4.
</code></pre>
<p>Mult... | 1 | 2016-10-07T14:17:11Z | 39,920,543 | <p>The <a href="https://docs.python.org/library/decimal.html#decimal.Decimal.scaleb" rel="nofollow"><code>.scaleb()</code></a> method will scale a decimal number while preserving its precision. From the documentation:</p>
<blockquote>
<p>scaleb(other[, context])</p>
<blockquote>
<p>Return the first operand ... | 0 | 2016-10-07T15:11:25Z | [
"python",
"python-2.7"
] |
CSV data causes error when uploading to SQL table via Python | 39,919,459 | <p>So I've been struggling with this problem for the last couple of days. I need to upload a CSV file with about 25 columns & 50K rows into a SQL Server table (<code>zzzOracle_Extract</code>) which also contains 25 columns, same Column names & in the same order.</p>
<p>This is what a row looks like from the CS... | 0 | 2016-10-07T14:18:32Z | 39,921,143 | <blockquote>
<p>How do join the [ ] to each column in my code?</p>
</blockquote>
<p>So you have something like </p>
<pre class="lang-python prettyprint-override"><code>>>> columns = ['ID','Last Name','First Name']
</code></pre>
<p>and you're currently using </p>
<pre class="lang-python prettyprint-over... | 1 | 2016-10-07T15:43:45Z | [
"python",
"sql-server",
"python-3.x",
"pymssql"
] |
Pandas: calculating the mean values of duplicate entries in a dataframe | 39,919,570 | <p>I have been working with a dataframe in python and pandas that contains duplicate entries in the first column. The dataframe looks something like this:</p>
<pre><code> sample_id qual percent
0 sample_1 10 20
1 sample_2 20 30
2 sample_1 50 60
3 sample_2 10 ... | 1 | 2016-10-07T14:23:35Z | 39,919,681 | <p><code>groupby</code> the <code>sample_id</code> column and use <code>mean</code></p>
<p><code>df.groupby('sample_id').mean().reset_index()</code><br>
<strong><em>or</em></strong><br>
<code>df.groupby('sample_id', as_index=False).mean()</code></p>
<p>get you </p>
<p><a href="http://i.stack.imgur.com/nw7e9.png" rel... | 2 | 2016-10-07T14:28:38Z | [
"python",
"pandas"
] |
Pandas: calculating the mean values of duplicate entries in a dataframe | 39,919,570 | <p>I have been working with a dataframe in python and pandas that contains duplicate entries in the first column. The dataframe looks something like this:</p>
<pre><code> sample_id qual percent
0 sample_1 10 20
1 sample_2 20 30
2 sample_1 50 60
3 sample_2 10 ... | 1 | 2016-10-07T14:23:35Z | 39,919,791 | <p>Groupby will work. </p>
<pre><code>data.groupby('sample_id').mean()
</code></pre>
<p>You can then use reset_index() to make look exactly as you want.</p>
| 0 | 2016-10-07T14:33:43Z | [
"python",
"pandas"
] |
How to do calculation on pandas dataframe that require processing multiple rows? | 39,919,672 | <p>I have a dataframe from which I need to calculate a number of features from. The dataframe <code>df</code> looks something like this for a object and an event:</p>
<pre><code>id event_id event_date age money_spent rank
1 100 2016-10-01 4 150 2
2 100 2016-09-30... | 1 | 2016-10-07T14:28:29Z | 39,920,750 | <p>I came up with the following solution:</p>
<pre><code>df1= df.sort_values(by="event_date",ascending = False)
g = df1.groupby(by=["id"])
df1["total_money_spent","count"]= g.agg({"money_spent":["cumsum","cumcount"]})
df1["avg_money_spent"]=df1["total_money_spent"]/(df1["count"]+1)
</code></pre>
| 0 | 2016-10-07T15:22:08Z | [
"python",
"python-2.7",
"pandas"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.