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 |
|---|---|---|---|---|---|---|---|---|---|
django views - hyperlinks with thumbnails | 39,027,560 | <p>I'm brand new to django front-end web development. </p>
<p>I have an <code>index.html</code> in my templates folder which has two thumbnails for sign up or login, and clicking on them directs you to <code>signup.html</code> and <code>login.html</code>. I have included the respective urls for those in <code>urls.py<... | 0 | 2016-08-18T21:09:28Z | 39,030,935 | <p>I'm not sure if i follow what you are asking exactly, but if its just the directing the user in the urls then you should use the url template tag with something like this</p>
<pre><code><a href="{% url 'signup' %}" class="thumbnail">
<img src="/static/img/signup.jpg" alt = "Sign Up as New User">
&l... | 1 | 2016-08-19T04:06:23Z | [
"python",
"html",
"django",
"twitter-bootstrap"
] |
django views - hyperlinks with thumbnails | 39,027,560 | <p>I'm brand new to django front-end web development. </p>
<p>I have an <code>index.html</code> in my templates folder which has two thumbnails for sign up or login, and clicking on them directs you to <code>signup.html</code> and <code>login.html</code>. I have included the respective urls for those in <code>urls.py<... | 0 | 2016-08-18T21:09:28Z | 39,033,493 | <p>Please avoid hard-coding urls in Django. You can use the power of reverse url matching here. Since you already have name assigned to your urls, you can have <code>container</code> in your <code>index.html</code> like this:</p>
<pre><code><div class = "container">
<div class="row">
<div clas... | 0 | 2016-08-19T07:33:56Z | [
"python",
"html",
"django",
"twitter-bootstrap"
] |
Some element.tail attributes are empty although they shouldn't | 39,027,618 | <p>I am trying to parse rather <a href="https://mcepl.fedorapeople.org/tmp/Mat-old.xml" rel="nofollow">large XML file</a> (with one biblical book) using xml.etree.ElementTree from python 3.4 (for compatibility with Windows I would prefer to stay with the standard library modules), and the relevant methods are here.</p>... | 0 | 2016-08-18T21:13:12Z | 39,057,700 | <p>This is PEBKAC ... I have assumed that there are no milestoned elements inside of other elements. So, I need to rewrite whole function as a recursive one. Oh well.</p>
| 0 | 2016-08-20T18:59:12Z | [
"python",
"xml",
"elementtree"
] |
Scrapy - How to avoid Pagination Blackhole? | 39,027,680 | <p>I was recently working on a website spider and noticed it was requesting an infinite number of pages because a site hadn't coded their pagination to ever stop.</p>
<p>So while they only had a few pages of content, it still would generate a next link and a url ...?page=400, ...?page=401, etc.</p>
<p>The content did... | 0 | 2016-08-18T21:18:52Z | 39,034,235 | <p>If the content doesn't change you can compare the content of the current page with the previous page and if it's the same, break the crawl.</p>
<p>for example:</p>
<pre><code>def parse(self, response):
product_urls = response.xpath("//a/@href").extract()
# check last page
if response.meta.get('prev_url... | 1 | 2016-08-19T08:16:19Z | [
"python",
"pagination",
"scrapy",
"web-crawler"
] |
Same code inserts data into one database but not into another | 39,027,681 | <p>I am facing a strange problem right now. I am using pypyodbc to insert data into a test database hosted by AWS. This database that I created was by hand and did not imitate all relations and whatnot between tables. All I did was create a table with the same columns and the same datatypes as the original (let's call ... | 0 | 2016-08-18T21:18:54Z | 39,027,828 | <p>It sounds like it's not pointing to the correct database. Have you made sure the connection information changes to point to the correct DB? So the server name is correct, the login credentials are good, etc.?</p>
| 2 | 2016-08-18T21:31:54Z | [
"python",
"sql-server",
"pypyodbc"
] |
pyqt with native python thread qpixmap and parent error | 39,027,837 | <p>I'm using python native thread with pyqt default thread. When I want show qmessagebox in native thread, my program is crashed.
Here is my code:</p>
<pre><code>.........
self.serverSoc.listen(5)
self.status="Server listening on %s:%s" % serveraddr
self.serverStatus = 1
thread.start_new_thread(self.listenClients, ())... | 0 | 2016-08-18T21:32:19Z | 39,043,812 | <p>Qt requires that all GUI operations are done in the main thread.</p>
<p>Why not use a <a href="http://doc.qt.io/qt-5/qtcpsocket.html" rel="nofollow">QTcpSocket</a> instead which nicely integrates into Qt's mainloop instead of requiring a thread?</p>
| 0 | 2016-08-19T16:28:04Z | [
"python",
"multithreading",
"pyqt"
] |
Python: change "\" to "\\" | 39,028,037 | <p>I have an entry field that allows the user to enter their own directory/path structure when saving a file, if the user just copies their directory from windows explorer you can get text like "c:\directory\file.ext" how can I take text entered like that and replace it with the necessary "\" for the os module to use?... | 0 | 2016-08-18T21:50:07Z | 39,028,200 | <p>maybe <code>os.path.normpath()</code> would be helpful to you - and the documentation <a href="https://docs.python.org/2/library/os.path.html" rel="nofollow">here</a></p>
| 0 | 2016-08-18T22:04:15Z | [
"python",
"replace"
] |
Python: change "\" to "\\" | 39,028,037 | <p>I have an entry field that allows the user to enter their own directory/path structure when saving a file, if the user just copies their directory from windows explorer you can get text like "c:\directory\file.ext" how can I take text entered like that and replace it with the necessary "\" for the os module to use?... | 0 | 2016-08-18T21:50:07Z | 39,028,549 | <p>Use a raw string to get the backslashes</p>
<pre><code>>>> path = r"c:\test\123"
>>> path
'c:\\test\\123'
>>> print path
c:\test\123
</code></pre>
| 0 | 2016-08-18T22:36:44Z | [
"python",
"replace"
] |
How do I ask all of the questions in the list without repeating the lines of code? | 39,028,103 | <pre><code>question = ["1 â Which seven-a-side ball game is played in a swimming pool?",
"2 - When was the Olympics last held in London?",
"3 - What is the world record time of the men's 100m sprint?",
"4 - The latest Bond song was sung by whom?",
"5 - Who won the Euro 2016 Final?",
"6... | 0 | 2016-08-18T21:54:49Z | 39,028,250 | <p>I am assuming that this is what you want. I see a lot of improvisations that can be made to the code. But still, I am presenting my answers here, for starters.</p>
<pre><code>question = ["1 â Which seven-a-side ball game is played in a swimming pool?","2 - When was the Olympics last held in London?",
"3 - Wha... | 0 | 2016-08-18T22:09:27Z | [
"python",
"python-3.x"
] |
How do I ask all of the questions in the list without repeating the lines of code? | 39,028,103 | <pre><code>question = ["1 â Which seven-a-side ball game is played in a swimming pool?",
"2 - When was the Olympics last held in London?",
"3 - What is the world record time of the men's 100m sprint?",
"4 - The latest Bond song was sung by whom?",
"5 - Who won the Euro 2016 Final?",
"6... | 0 | 2016-08-18T21:54:49Z | 39,028,252 | <p>One way would be to turn your questions into individual Class objects. </p>
<pre><code>class Question():
def __init__(self, id, question, answers, correct_answer):
self.id = id
self.question = question
self.answers = answers
self.correct_answer = correct_answer
question_one = Q... | 2 | 2016-08-18T22:09:29Z | [
"python",
"python-3.x"
] |
How do I ask all of the questions in the list without repeating the lines of code? | 39,028,103 | <pre><code>question = ["1 â Which seven-a-side ball game is played in a swimming pool?",
"2 - When was the Olympics last held in London?",
"3 - What is the world record time of the men's 100m sprint?",
"4 - The latest Bond song was sung by whom?",
"5 - Who won the Euro 2016 Final?",
"6... | 0 | 2016-08-18T21:54:49Z | 39,028,315 | <p>To answer your question simply: you could iterate over each question in the list of questions with a foreach loop.</p>
<pre><code>for q in question:
#do something with q, the for loop will do this for every q in your list 'question'
</code></pre>
<p>The problem with this is you don't have access to the corresp... | 0 | 2016-08-18T22:14:39Z | [
"python",
"python-3.x"
] |
How to get the original name of a function after it is wrapped by function decorator? | 39,028,124 | <h1>The Code</h1>
<pre><code>def blahblah(func):
def wrapper(*args):
pass # blah blah blah....
return wrapper
@blahblah
def func1(arg1):
pass # blah blah blah
@blahblah
def func2(arg1):
pass # blah blah blah
functions = [func1, func2]
for func in functions:
print(func.__name__, func(0))... | 2 | 2016-08-18T21:57:23Z | 39,028,167 | <p>You can use the <code>functools.wraps</code> helper function as follows which'll preserve the original name and doc string of the wrapped function, eg:</p>
<pre><code>from functools import wraps
def blahblah(func):
@wraps(func)
def wrapper(*args):
pass # blah blah blah....
return wrapper
@blah... | 5 | 2016-08-18T22:01:28Z | [
"python"
] |
How do you use index with words from nltk.corpus? | 39,028,160 | <p>If I were to want to get the 1252nd word from words.words() how would I do it? Of course I could do something like this, but it's so ugly I can barely look at it. </p>
<pre><code>random_word = 1252
counter = 0
for i in words.words():
if counter == random_word:
print(i)
counter +=... | 0 | 2016-08-18T22:01:00Z | 39,028,230 | <p>words.words() from NLTK should be a list. With lists you can just do indexing.</p>
<p>So if you'd like to get the 1252nd word in the list (assuming you're counting pythonically, so 1st position starts at 0), just do <code>words.words()[1251]</code></p>
<p>If you need to access many words from that list at one tim... | 1 | 2016-08-18T22:07:16Z | [
"python",
"nltk"
] |
How do I hide pandas to_datetime NaT in when I write to CSV? | 39,028,197 | <p>I am a little bit perplexed as to why NaT are showing up in my CSV...usually they show up as "". Here is my date formatting:</p>
<pre><code>df['submitted_on'] = pd.to_datetime(df['submitted_on'], errors='coerce').dt.to_period('d')
df['resolved_on'] = pd.to_datetime(df['resolved_on'], errors='coerce').dt.to_period(... | 2 | 2016-08-18T22:04:00Z | 39,028,412 | <p>Your problem lies in that you are converting to <code>periods</code>. The <code>NaT</code> you see is actually a <code>period</code> object.</p>
<p>One way around this is to convert to strings instead.</p>
<p>Use</p>
<pre><code>.dt.strftime('%Y-%m-%d')
</code></pre>
<p>Instead of </p>
<pre><code>.dt.to_period(... | 3 | 2016-08-18T22:23:31Z | [
"python",
"date",
"pandas"
] |
Using unittest to test argparse - exit errors | 39,028,204 | <p>Going off of <a href="http://stackoverflow.com/questions/5943249">Greg Haskin's answer in this question</a>, I tried to make a unittest to check that argparse is giving the appropriate error when I pass it some args that are not present in the <code>choices</code>. However, <code>unittest</code> generates a false po... | 1 | 2016-08-18T22:04:31Z | 39,028,444 | <p>If you look in the error log, you can see that a <code>argparse.ArgumentError</code> is raised and not an <code>AttributeError</code>. your code should look like this:</p>
<pre><code>#!/usr/bin/env python3
import argparse
import unittest
from argparse import ArgumentError
class sweep_test_case(unittest.TestCase):... | 1 | 2016-08-18T22:26:33Z | [
"python",
"unit-testing",
"python-3.x",
"argparse",
"python-unittest"
] |
Using unittest to test argparse - exit errors | 39,028,204 | <p>Going off of <a href="http://stackoverflow.com/questions/5943249">Greg Haskin's answer in this question</a>, I tried to make a unittest to check that argparse is giving the appropriate error when I pass it some args that are not present in the <code>choices</code>. However, <code>unittest</code> generates a false po... | 1 | 2016-08-18T22:04:31Z | 39,029,904 | <p>While the parser may raise an ArgumentError during parsing a specific argument, that is normally trapped, and passed to <code>parser.error</code> and <code>parse.exit</code>. The result is that the usage is printed, along with an error message, and then <code>sys.exit(2)</code>.</p>
<p>So <code>asssertRaises</code... | 1 | 2016-08-19T01:45:00Z | [
"python",
"unit-testing",
"python-3.x",
"argparse",
"python-unittest"
] |
Using unittest to test argparse - exit errors | 39,028,204 | <p>Going off of <a href="http://stackoverflow.com/questions/5943249">Greg Haskin's answer in this question</a>, I tried to make a unittest to check that argparse is giving the appropriate error when I pass it some args that are not present in the <code>choices</code>. However, <code>unittest</code> generates a false po... | 1 | 2016-08-18T22:04:31Z | 39,029,963 | <p>If you look into the source code of argparse, in <code>argparse.py</code>, around line 1732 (my python version is 3.5.1), there is a method of <code>ArgumentParser</code> called <code>parse_known_args</code>. The code is:</p>
<pre><code># parse the arguments and exit if there are any errors
try:
namespace, args... | 0 | 2016-08-19T01:52:57Z | [
"python",
"unit-testing",
"python-3.x",
"argparse",
"python-unittest"
] |
Send scheduled emails with pyramid_mailer and apscheduler | 39,028,210 | <p>I've tried getting this to work but there must be a better way, any input is welcome.</p>
<p>I'm trying to send scheduled emails in my python pyramid app using pyramid_mailer (settings stored in .ini file), and apscheduler to set the schedule.</p>
<p>I also use the SQLAlchemyJobStore so jobs can be restarted if th... | 2 | 2016-08-18T22:05:10Z | 39,071,976 | <p>Generally, you cannot pickle <code>request</code> object as it contains references to things like open sockets and other liveful objects. </p>
<p>Some useful patterns here are that</p>
<ul>
<li><p>You pregenerate email id in the database and then pass id (int, UUID) over scheduler</p></li>
<li><p>You generate temp... | 2 | 2016-08-22T05:34:38Z | [
"python",
"pyramid",
"mailer",
"apscheduler"
] |
Tensorflow execution in a virtual machine with no GPUs | 39,028,218 | <p>I had a question regarding tensorflow that is, somewhat critical to what task I'm trying to accomplish.</p>
<p>My scenario is as follows,
1. I have a tensorflow script that has been set-up, trained and tested. It is working well.</p>
<ol start="2">
<li><p>The training and testing was done on a devBox with 2 Titan... | 0 | 2016-08-18T22:05:50Z | 39,028,775 | <p>Testing with <code>CUDA_VISIBLE_DEVICES</code> set to empty string will make sure that you don't have anything that depends on GPU being present, and theoretically it should be enough. In practice, there are some bugs in GPU codepath which can get triggered when there are no GPUs (like <a href="https://github.com/te... | 0 | 2016-08-18T23:03:52Z | [
"python",
"machine-learning",
"tensorflow",
"conv-neural-network"
] |
Pandas DataFrame: Compute values based on column min/max | 39,028,237 | <p>I have an NxN DataFrame with values I need to scale to a range of values that signify importance, where 0 is irrelevant and 3 is very important.</p>
<p>The formula I'm using to scale of course depends on the min and max values in each column, which are different for each column: Col A's range could be 1-12 while Co... | 0 | 2016-08-18T22:07:58Z | 39,042,038 | <p>min-max normalization can be done with:</p>
<pre><code>(df - df.min()) / (df.max() - df.min())
Out:
Body: retail price Body: sensor resolution
Body name
Nikon D500 0.464643 0.477651
Nikon D7000 ... | 0 | 2016-08-19T14:52:20Z | [
"python",
"dataframe"
] |
Why does del (x) with parentheses around the variable name work? | 39,028,249 | <p>Why does this piece of code work the way it does?</p>
<pre><code>x = 3
print(dir()) #output indicates that x is defined in the global scope
del (x)
print(dir()) #output indicates that x is not defined in the global scope
</code></pre>
<p>My understanding is that <code>del</code> is a keyword in Python, and wha... | 0 | 2016-08-18T22:09:21Z | 39,028,426 | <p>The definition of the <a href="https://docs.python.org/3/reference/simple_stmts.html#the-del-statement" rel="nofollow"><code>del</code> statemant</a> is:</p>
<blockquote>
<p>del_stmt ::= "del" target_list</p>
</blockquote>
<p>and from the definition of <a href="https://docs.python.org/3/reference/simple_stmts.h... | 2 | 2016-08-18T22:25:00Z | [
"python"
] |
python: convert pywintyptes.datetime to datetime.datetime | 39,028,290 | <p>I am using pywin32 to read/write to an Excel file. I have some dates in Excel, stored in format yyyy-mm-dd hh:mm:ss. I would like to import those into Python as datetime.datetime objects. Here is the line of code I started with:</p>
<pre><code>prior_datetime = datetime.strptime(excel_ws.Cells(2, 4).Value, '%Y-%m-%d... | 1 | 2016-08-18T22:12:51Z | 39,028,464 | <p>So the problem is the <code>+00:00</code> timezone offset. <a href="https://stackoverflow.com/questions/20194496/iso-to-datetime-object-z-is-a-bad-directive">Looking into this there's not an out of the box solution for Python</a></p>
<pre><code>datetime.datetime.strptime("2016-04-01 17:29:25+00:00", '%Y-%m-%d %H:%M... | 1 | 2016-08-18T22:28:38Z | [
"python",
"excel",
"pywin32"
] |
Mismatch in feature_names in xgboost sklearn during multi-class text classification | 39,028,385 | <p>I am trying to perform a multiclass text classification using xgboost in python (sklearn edition), but at times it errors out telling me that there is a mismatch in feature names. The odd thing is that at times it does work (perhaps 1 out of 4 times), but the uncertainty is making it difficult for me to rely on this... | 1 | 2016-08-18T22:21:33Z | 39,030,902 | <p>You need to make sure that you are only scoring the model with features that it has been trained on. The usual way to do this is to use a <code>Pipeline</code> to package the vectoriser and the model together. That way they will both be trained at the same time, and if a new feature is encountered in the test data, ... | 0 | 2016-08-19T04:00:43Z | [
"python",
"machine-learning",
"scikit-learn",
"text-classification",
"xgboost"
] |
Difference between UDP server and UDP client: sock.bind((host, port)) is on the client or server side? | 39,028,505 | <p>The UDP server:</p>
<pre><code># -*- coding: utf-8 -*-
#!/usr/bin/python3
#server UDP
from socket import *
def main():
# Cria host e port number
host = ""
port = 5000
# Cria socket #UDP
server = socket(AF_INET, SOCK_DGRAM)
# Indica que o servidor foi iniciado
print("... | 1 | 2016-08-18T22:32:37Z | 39,065,914 | <p>As @VPfB answered, see: <a href="http://stackoverflow.com/questions/6189831/whats-the-purpose-of-using-sendto-recvfrom-instead-of-connect-send-recv-with-ud">What's the purpose of using sendto/recvfrom instead of connect/send/recv with UDP sockets?</a></p>
<p>The model server/client :</p>
<p>client is the part ... | 1 | 2016-08-21T15:34:06Z | [
"python",
"python-3.x"
] |
2to3 - how to keep newline characters from input file? | 39,028,517 | <p>I'm attempting to run <code>2to3</code> on Windows machine where *.py files has Unix-style end-line characters. Running <code>2to3</code> modifies newline characters in output file.</p>
<p>MCVE:</p>
<p><strong>print2.py content before</strong></p>
<pre><code>print "Hello, world!"\n
</code></pre>
<p>Executed comm... | 2 | 2016-08-18T22:33:59Z | 39,028,615 | <p>On Windows, the system line separator is <code>\r\n</code>, as we can see in <code>os.py</code>:</p>
<pre><code>if 'posix' in _names:
...
linesep = '\n'
...
elif 'nt' in _names:
...
linesep = '\r\n'
...
</code></pre>
<p>This line separator is used in <code>lib2to3.refactor</code>:</p>
<pre... | 0 | 2016-08-18T22:46:20Z | [
"python",
"python-3.x",
"python-2.x",
"2to3"
] |
2to3 - how to keep newline characters from input file? | 39,028,517 | <p>I'm attempting to run <code>2to3</code> on Windows machine where *.py files has Unix-style end-line characters. Running <code>2to3</code> modifies newline characters in output file.</p>
<p>MCVE:</p>
<p><strong>print2.py content before</strong></p>
<pre><code>print "Hello, world!"\n
</code></pre>
<p>Executed comm... | 2 | 2016-08-18T22:33:59Z | 39,094,236 | <p>Since there seems to be no standard way to change this behavior in command line usage, I've prepared very simple Python script, which runs code and patches unwanted behavior.</p>
<p>Here's an example for <code>python modernize</code>, but any 2to3-based tool will do just fine.</p>
<pre><code># to access function t... | 1 | 2016-08-23T06:53:59Z | [
"python",
"python-3.x",
"python-2.x",
"2to3"
] |
How to use multiple nodes in a cluster to process huge data - python | 39,028,535 | <p>I have a 15 node cluster which I am planning to use for processing data in the range of 90 million rows(Hive table) / per day. The data is present in one of the nodes as a hive table and I am using something like the following command,</p>
<pre><code>with hive.connect(host = 'hostname of that node', port= 10000, au... | 0 | 2016-08-18T22:35:42Z | 39,174,021 | <p>Distributed systems is a large and complex topic that's best left to experts. You're using Pyhon, Pandas, and Hive. You should just switch to Spark, which has its own <code>DataFrame</code> abstraction similar to Pandas and supports reading from Hive tables but will handle distributing the data across your servers f... | 1 | 2016-08-26T20:12:32Z | [
"python",
"python-2.7",
"hadoop",
"hive",
"distributed-computing"
] |
Python Scrabble challenge find valid words | 39,028,548 | <p>I'm trying to complete a python project that basically takes an input and goes through a list of valid scrabble words and determines which of those words can be made given the input.</p>
<p>The first part was somewhat easy, but the part that actually matters is giving me issues.</p>
<p>Here's what I have so far:</... | 0 | 2016-08-18T22:36:29Z | 39,028,740 | <p>The easiest way to check if words are valid is to use a <code>collections.Counter</code>. You take the occurrences of each letter in the rack, and the occurrences of each letter for each scrabble word then take the difference. If there's nothing left of the scrabble word after removing the letters from the rack, the... | 1 | 2016-08-18T23:00:04Z | [
"python",
"python-3.x"
] |
Change a parent variable in subclass, then use new value in parent class? | 39,028,550 | <p>I'm just getting to grips with python, and am currently trying to change the value of a Parent class variable using a subclass method. A basic example of my code is below. </p>
<pre><code>from bs4 import BeautifulSoup
import requests
import urllib.request as req
class Parent(object):
url = "http://www.google.c... | 0 | 2016-08-18T22:36:45Z | 39,028,575 | <p>Because when you use <code>Parent.url</code> it uses the static value set inside the class Parent, not the value from the instance of the class.</p>
| 0 | 2016-08-18T22:40:53Z | [
"python"
] |
Change a parent variable in subclass, then use new value in parent class? | 39,028,550 | <p>I'm just getting to grips with python, and am currently trying to change the value of a Parent class variable using a subclass method. A basic example of my code is below. </p>
<pre><code>from bs4 import BeautifulSoup
import requests
import urllib.request as req
class Parent(object):
url = "http://www.google.c... | 0 | 2016-08-18T22:36:45Z | 39,028,583 | <pre><code>class Parent(object):
url = "http://www.google.com"
r = requests.get(url)
soup = BeautifulSoup(r.content, "lxml")
print(url)
</code></pre>
<p>The code to assign the <code>soup</code> is run once, at time of class <em>definition</em>. </p>
<p>Therefore no changes to <code>Parent.url</code> ... | 0 | 2016-08-18T22:42:08Z | [
"python"
] |
TypeError: __init__() got an unexpected keyword argument 'columns' | 39,028,568 | <p>I am trying to create a plugin in wxpython and running into below error,can any one help understand why I am running into this error and how to fix this?</p>
<pre><code>import wx
from wx.lib.agw import ultimatelistctrl as ULC
class TestFrame(wx.App):
def __init__(self):
wx.App.__init__(self)
... | -1 | 2016-08-18T22:40:12Z | 39,028,591 | <p>If you look at <a href="https://wxpython.org/Phoenix/docs/html/wx.lib.agw.ultimatelistctrl.UltimateListCtrl.html#wx.lib.agw.ultimatelistctrl.UltimateListCtrl.__init__" rel="nofollow">the documentation for the class's <code>__init__</code></a>, you can see that it has no <a href="https://docs.python.org/2/tutorial/co... | 1 | 2016-08-18T22:44:05Z | [
"python",
"wxpython"
] |
Find string greater than (x) in length | 39,028,590 | <p>How can I search through a variable and look for a word/string that is greater than 20 in length?</p>
<pre><code>var = '''this is my example and I want
no find the following
string jakjajsiwjsjwijaksjdfjaiwjalskdjfiajwlajfklajsdfwi
from this variable'''
</code></pre>
<p>Thanks</p>
| 0 | 2016-08-18T22:44:03Z | 39,028,673 | <p>Iterate through a list of the words using <code>split</code> and check the <code>len</code> of each word.</p>
<pre><code>for x in var.split():
if len(x) > 20:
print(x)
</code></pre>
<p>Or of course you can use a <a href="https://docs.python.org/3.4/tutorial/datastructures.html#list-comprehensions" r... | 2 | 2016-08-18T22:52:55Z | [
"python"
] |
Find string greater than (x) in length | 39,028,590 | <p>How can I search through a variable and look for a word/string that is greater than 20 in length?</p>
<pre><code>var = '''this is my example and I want
no find the following
string jakjajsiwjsjwijaksjdfjaiwjalskdjfiajwlajfklajsdfwi
from this variable'''
</code></pre>
<p>Thanks</p>
| 0 | 2016-08-18T22:44:03Z | 39,028,695 | <p>Using a list comprehension:</p>
<pre><code>print [x for x in var.split() if len(x) > 20]
</code></pre>
| 4 | 2016-08-18T22:55:22Z | [
"python"
] |
Find string greater than (x) in length | 39,028,590 | <p>How can I search through a variable and look for a word/string that is greater than 20 in length?</p>
<pre><code>var = '''this is my example and I want
no find the following
string jakjajsiwjsjwijaksjdfjaiwjalskdjfiajwlajfklajsdfwi
from this variable'''
</code></pre>
<p>Thanks</p>
| 0 | 2016-08-18T22:44:03Z | 39,028,711 | <pre><code>var_split = var.split(' ')
long_word = ''
for word in var_split:
if len(word) > 20:
long_word = word
</code></pre>
| 0 | 2016-08-18T22:56:31Z | [
"python"
] |
Unable to set psycopg2 autocommit after shp2pgsql import | 39,028,663 | <p>I am loading a shapefile into a postGIS database using shp2pgsql, piped via psql, wrapped in a python subprocess like this:</p>
<pre><code>command = "shp2pgsql -s 4269 -a -D -W LATIN1 file.shp table | psql -h host -d db -U user"
p=subprocess.Popen(command, shell=True)
p.communicate()
</code></pre>
<p>This works pe... | 1 | 2016-08-18T22:51:56Z | 39,043,073 | <p>I can't see where this is happening, but according to <a href="http://initd.org/psycopg/docs/faq.html" rel="nofollow">this</a>, <a href="https://news.ycombinator.com/item?id=4269241" rel="nofollow">this</a>, and <a href="https://dba.stackexchange.com/questions/75395/are-transactions-in-postgresql-via-psycopg2-per-cu... | 0 | 2016-08-19T15:44:25Z | [
"python",
"postgresql",
"psycopg2",
"psql"
] |
How can I have Python read variables from a browser? | 39,028,675 | <p>On a school project, I am trying to code an AI to a simple game.
The problem is that the game is a javascript code running in a browser, while the AI is to be coded with Python.</p>
<p>I have isolated the useful real-time variables (like position, speed...) in the .js file, and I was able to output them in the brow... | 0 | 2016-08-18T22:53:20Z | 39,028,821 | <p>Two solutions come through my mind:</p>
<ol>
<li>The game's server code may expose API (e.g. REST API) via which your AI could query parameters and execute commands.</li>
<li>Make your AI interact with game just like human would using <a href="http://selenium-python.readthedocs.io/" rel="nofollow">selenium-python</... | 0 | 2016-08-18T23:08:41Z | [
"javascript",
"python",
"browser"
] |
Flask-SQLAlchemy: CircularDependencyError where same row in many-to-one relationship can be in one-to-many relationship with same table | 39,028,722 | <p>I'm using Flask-SQLAlchemy 2.1 with SQLAlchemy 1.0.13, and I have two tables, <code>Address</code> and <code>Customer</code> that have multiple relationships to each other, as follows:</p>
<pre><code>class Address(db.Model):
id = db.Column(db.Integer, primary_key=True)
... # Other rows including first_name... | 0 | 2016-08-18T22:58:05Z | 39,028,803 | <p>Setting <code>post_update=True</code> on both sides of the relationship appears to solve the problem:</p>
<pre><code>class Address(db.Model):
...
customer_id = db.Column(db.Integer, db.ForeignKey('customers.id'))
customer = db.relationship(
'Customer',
foreign_keys=customer_id,
b... | 0 | 2016-08-18T23:06:43Z | [
"python",
"sqlalchemy",
"relationship",
"flask-sqlalchemy",
"circular-dependency"
] |
How to create a lambda for assignment? | 39,028,791 | <p>I just to pass something like:</p>
<pre><code>def ___(x):
x.a=0
return x
</code></pre>
<p>or </p>
<pre><code>def ___(x):
x.a=0
</code></pre>
<p>into a function. How to make it happen?</p>
| -3 | 2016-08-18T23:05:14Z | 39,028,813 | <p>A lambda can only be an expression, and assignment isn't an expression in Python. Fortunately, there is another way to set an attribute in Python: the function <code>setattr()</code>. So you can write:</p>
<pre><code>lambda x: setattr(x, "a", 0)
</code></pre>
<p>This isn't very good Python, though, because it make... | 3 | 2016-08-18T23:07:53Z | [
"python"
] |
How to create a lambda for assignment? | 39,028,791 | <p>I just to pass something like:</p>
<pre><code>def ___(x):
x.a=0
return x
</code></pre>
<p>or </p>
<pre><code>def ___(x):
x.a=0
</code></pre>
<p>into a function. How to make it happen?</p>
| -3 | 2016-08-18T23:05:14Z | 39,028,820 | <pre><code>x.a=0
</code></pre>
<p>The line above is a <em><a href="https://docs.python.org/3/reference/simple_stmts.html#assignment-statements" rel="nofollow">statement</a></em>, and lambda functions can not contain statements (only <em><a href="https://docs.python.org/3/reference/expressions.html" rel="nofollow">exp... | 0 | 2016-08-18T23:08:33Z | [
"python"
] |
JSON Dump of raw SQL query returning empty dictionary | 39,028,870 | <p>I am sending a string through http get request to my views.py and then send back to my javascript but I am not getting my desired data, and instead, I am getting an empty dict. I am on Django 1.8 as well.</p>
<p><strong>views.py:</strong></p>
<pre><code>def getData(request):
some_data = request.GET.get('selecti... | 0 | 2016-08-18T23:14:29Z | 39,044,821 | <p>Okay after playing around for a bit, I finally fixed it. My problem was that I needed to search for an exact string name in one of the tables and columns in my database but I was retrieving my sent data in views.py as a query dictionary. The thing is that this query dictionary had my single string that I passed in t... | 0 | 2016-08-19T17:35:54Z | [
"javascript",
"python",
"json",
"django"
] |
JSON Dump of raw SQL query returning empty dictionary | 39,028,870 | <p>I am sending a string through http get request to my views.py and then send back to my javascript but I am not getting my desired data, and instead, I am getting an empty dict. I am on Django 1.8 as well.</p>
<p><strong>views.py:</strong></p>
<pre><code>def getData(request):
some_data = request.GET.get('selecti... | 0 | 2016-08-18T23:14:29Z | 39,046,203 | <p>Have you tried to print "row" variable? Is there any result?
Because maybe this is not a problem from the query, but the problem is that row data is not json serializable, and so JsonResponse can't render it.</p>
<p>i. e., I believe cursor.fetchall() will deliver your data in the following format: [(1,),(5,),(7,)],... | 0 | 2016-08-19T19:10:54Z | [
"javascript",
"python",
"json",
"django"
] |
Transforming column dataframe pandas into sequence | 39,028,903 | <p>I have data and convert into dataframe</p>
<pre><code>d = [
(1,70399,0.988375133622),
(1,33919,0.981573492596),
(1,62461,0.981426807114),
(579,1,0.983018778374),
(745,1,0.995580488899),
(834,1,0.980942505189)
]
df = pd.DataFrame(d, columns=['source', 'target', 'weight'])
>>> df
source tar... | 0 | 2016-08-18T23:17:20Z | 39,029,014 | <p>Something like this?</p>
<pre><code>df['source_code'] = df.source.astype('category').cat.codes
>>> df
source target weight source_code
0 1 70399 0.988375 0
1 1 33919 0.981573 0
2 1 62461 0.981427 0
3 579 1 0.983019 1... | 0 | 2016-08-18T23:30:21Z | [
"python",
"pandas"
] |
Transforming column dataframe pandas into sequence | 39,028,903 | <p>I have data and convert into dataframe</p>
<pre><code>d = [
(1,70399,0.988375133622),
(1,33919,0.981573492596),
(1,62461,0.981426807114),
(579,1,0.983018778374),
(745,1,0.995580488899),
(834,1,0.980942505189)
]
df = pd.DataFrame(d, columns=['source', 'target', 'weight'])
>>> df
source tar... | 0 | 2016-08-18T23:17:20Z | 39,032,937 | <p>You can use:</p>
<pre><code>#remember original values
source_old = df.source.copy()
df.source = (df.source.diff() != 0).cumsum() - 1
#series for maping
ser = pd.Series(df.source.values, index=source_old).drop_duplicates()
print (ser)
source
1 0
579 1
745 2
834 3
dtype: int32
#map where values exist... | 0 | 2016-08-19T07:02:02Z | [
"python",
"pandas"
] |
What precisely does DEPTH_LIMIT refer to? Is the current depth referencable? | 39,028,908 | <p>Scrapy indicates it has a <a href="http://doc.scrapy.org/en/latest/topics/settings.html#depth-limit" rel="nofollow"><code>DEPTH_LIMIT</code> setting</a>, but doesn't specifically say what it considers 'depth'. In terms of scraping pages, I've seen 'depth' refer to 'depth of the url', or <code>http://somedomain.com/t... | 1 | 2016-08-18T23:17:50Z | 39,029,055 | <p>Scrapy uses a DFS approach for traversal and the current depth can be accessed via the response meta data: <code>response.meta['depth']</code>.</p>
| 1 | 2016-08-18T23:35:09Z | [
"python",
"scrapy",
"scrapy-spider"
] |
WebSockets Client Connections Time Out When Trying to Open a Connection with Tornado Server | 39,028,935 | <p>I have a Tornado server with a WebSocketHandler, and when I connect to the handler on localhost everything works correctly. However, the server is being moved to a new environment and now must run on <code>wss</code> instead of <code>ws</code> protocol. Since moving to the new environment, all client connections to ... | 1 | 2016-08-18T23:20:17Z | 39,041,012 | <p>The issue was with ProxyPass settings and the post used in my <code>wss</code> url.</p>
<p>Tornado Update:</p>
<p>The ssl cert and key files were removed from Tornado configuration.</p>
<p>ProxyPass Update:</p>
<pre><code>ProxyPass /resource/<resource_name> ws://127.0.0.1:8930/resource/<resource_name>... | 0 | 2016-08-19T14:02:49Z | [
"python",
"ssl",
"websocket",
"tornado",
"proxypass"
] |
Copying nested custom objects: alternatives to deepcopy | 39,028,978 | <p>I'm looking to make a deep copy of a class object that contains a list of class objects, each with their own set of stuff. The objects don't contain anything more exciting than ints and lists (no dicts, no generators waiting to yield, etc). I'm performing the deep copy on between 500-800 objects a loop, and it's rea... | 0 | 2016-08-18T23:25:19Z | 39,029,350 | <p>One of the first things that <code>copy.deepcopy</code> looks for is if the object defines <a href="https://github.com/tadhgmister/cpython/blob/master/Lib/copy.py#L159" rel="nofollow">it's own <code>__deepcopy__</code> method</a> So instead of having it figure out how to copy object every time just define your own p... | 2 | 2016-08-19T00:17:18Z | [
"python",
"python-3.x"
] |
Copying nested custom objects: alternatives to deepcopy | 39,028,978 | <p>I'm looking to make a deep copy of a class object that contains a list of class objects, each with their own set of stuff. The objects don't contain anything more exciting than ints and lists (no dicts, no generators waiting to yield, etc). I'm performing the deep copy on between 500-800 objects a loop, and it's rea... | 0 | 2016-08-18T23:25:19Z | 39,414,002 | <p>Based on cherish's answers <a href="http://stackoverflow.com/questions/24756712/deepcopy-is-extremely-slow/29385667#29385667">here</a>, <code>pickle.loads(pickle.dumps(first))</code> works about twice as fast per call. I had written it off initially because of an unrelated error when testing it, but on retesting it,... | 1 | 2016-09-09T14:32:34Z | [
"python",
"python-3.x"
] |
Reading string as text in an equation | 39,029,068 | <p>I want to be able to execute the following code:</p>
<pre><code>import numpy
z=numpy.zeros(4)
k="z[i-1]"
for i in range(len(b)):
z[i]=k
</code></pre>
<p>Which should return the same output as:</p>
<pre><code>z=numpy.zeros(4)
for i in range(6):
z[i]=z[i-1]
</code></pre>
<p>If I execute the first code bloc... | 0 | 2016-08-18T23:37:27Z | 39,029,137 | <p>Do it as following:</p>
<pre><code>import numpy
z=numpy.zeros(4)
k="z[i-1]"
for i in range(len(b)):
z[i]=eval(k)
</code></pre>
<p>But note eval can be a security problem: <a href="http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html" rel="nofollow">http://nedbatchelder.com/blog/201206/eval_really... | 1 | 2016-08-18T23:46:05Z | [
"python",
"string",
"for-loop",
"text"
] |
Reading string as text in an equation | 39,029,068 | <p>I want to be able to execute the following code:</p>
<pre><code>import numpy
z=numpy.zeros(4)
k="z[i-1]"
for i in range(len(b)):
z[i]=k
</code></pre>
<p>Which should return the same output as:</p>
<pre><code>z=numpy.zeros(4)
for i in range(6):
z[i]=z[i-1]
</code></pre>
<p>If I execute the first code bloc... | 0 | 2016-08-18T23:37:27Z | 39,029,139 | <p>I think you're looking for the <a href="https://docs.python.org/2/library/functions.html#eval" rel="nofollow">builtin <code>eval()</code></a></p>
<p>Consider:</p>
<pre><code>>>> z = numpy.zeros(4)
>>> k = "10 + z[i-1]"
>>> for i in range(1, 4):
... z[i] = eval(k)
...
>>> z
a... | 3 | 2016-08-18T23:46:19Z | [
"python",
"string",
"for-loop",
"text"
] |
Reading string as text in an equation | 39,029,068 | <p>I want to be able to execute the following code:</p>
<pre><code>import numpy
z=numpy.zeros(4)
k="z[i-1]"
for i in range(len(b)):
z[i]=k
</code></pre>
<p>Which should return the same output as:</p>
<pre><code>z=numpy.zeros(4)
for i in range(6):
z[i]=z[i-1]
</code></pre>
<p>If I execute the first code bloc... | 0 | 2016-08-18T23:37:27Z | 39,029,286 | <p>Other then <code>eval</code> which is highly discouraged in production code, You can just as easily define a function that returns a specific item based on the array and index:</p>
<pre><code>def k(arr,idx):
return arr[idx-1]
for i in range(len(b)):
z[i]= k(z,i)
</code></pre>
<p>If this rule needs to be ap... | 1 | 2016-08-19T00:06:50Z | [
"python",
"string",
"for-loop",
"text"
] |
pycparser.plyparser.ParseError on complex struct | 39,029,209 | <p>I'm trying to use <code>pycparser</code> to parse this C code:</p>
<p><a href="https://github.com/nbeaver/mx-trunk/blob/0b80678773582babcd56fe959d5cfbb776cc0004/libMx/d_adsc_two_theta.c" rel="nofollow">https://github.com/nbeaver/mx-trunk/blob/0b80678773582babcd56fe959d5cfbb776cc0004/libMx/d_adsc_two_theta.c</a></p>... | 3 | 2016-08-18T23:55:39Z | 39,496,991 | <p>The cause appears to be the <code>offsetof()</code> function. The minimal working examples are fixed by recent commits, however:</p>
<p><a href="https://github.com/eliben/pycparser/issues/87" rel="nofollow">https://github.com/eliben/pycparser/issues/87</a></p>
| 0 | 2016-09-14T18:09:13Z | [
"python",
"c",
"ply",
"pycparser"
] |
How to detect uncertainty of text in NLTK Python? | 39,029,244 | <p>I am a beginner at NLTK and machine learning with the goal of giving uncertainty ratings to sentences.
For example, a sentence like <code>This is likely caused by a..</code> would receive a certainty score of say 6, where as <code>There is definitely something wrong with me</code> would receive a 10 and <code>I thi... | 1 | 2016-08-19T00:00:16Z | 39,058,248 | <p>As far as I know, existing nlp toolkits do not have such feature. </p>
<p>You have to train your own model and for that you need training data. If you have a dataset that contains uncertainty labels for each sentence, then you can train a text classification model on that.</p>
<p>If you don't have labeled data, th... | 3 | 2016-08-20T20:05:53Z | [
"python",
"nlp",
"artificial-intelligence",
"nltk"
] |
How to detect uncertainty of text in NLTK Python? | 39,029,244 | <p>I am a beginner at NLTK and machine learning with the goal of giving uncertainty ratings to sentences.
For example, a sentence like <code>This is likely caused by a..</code> would receive a certainty score of say 6, where as <code>There is definitely something wrong with me</code> would receive a 10 and <code>I thi... | 1 | 2016-08-19T00:00:16Z | 39,072,951 | <p>Instead of NLP problem, this is more like a text categorization problem.</p>
<p>You can define pre existing set of tags like:</p>
<pre><code>HIGHEST, HIGH , MEDIUM , LOW , NIL
</code></pre>
<p>You can then use any algorithm e.g Naive Bayes classifier or K nearest neighbours to classify your text in one of these t... | 2 | 2016-08-22T06:51:20Z | [
"python",
"nlp",
"artificial-intelligence",
"nltk"
] |
Most efficient way to merge two partially inclusive lists of files and their properties | 39,029,305 | <p>I have a system that runs a custom cli with a variation of the <code>ls</code> or <code>dir</code> command, returning a list of files and folders in your working directory.</p>
<p>The problem is, I can either run the command with a flag that returns the files and their time stamps (date created and last modified), ... | 0 | 2016-08-19T00:10:08Z | 39,029,471 | <p>Sounds like a good use case for Sqlite.
Python has <a href="https://docs.python.org/2/library/sqlite3.html" rel="nofollow">good support</a> for it. Instead of creating a disk file based DB you could use a pure in-memory based database by passing the right arguments. First I'd create a 2 tables - tblFileNTimeStamp (... | 0 | 2016-08-19T00:36:28Z | [
"python",
"performance",
"list",
"dictionary"
] |
Most efficient way to merge two partially inclusive lists of files and their properties | 39,029,305 | <p>I have a system that runs a custom cli with a variation of the <code>ls</code> or <code>dir</code> command, returning a list of files and folders in your working directory.</p>
<p>The problem is, I can either run the command with a flag that returns the files and their time stamps (date created and last modified), ... | 0 | 2016-08-19T00:10:08Z | 39,031,526 | <p>It is hard to tell from your question what your desired result is. If you want all files in both lists even if they only appear in one or the other just make one pass through both files and create a dictionary using <code>collections.defaultdict</code></p>
<pre><code>from collections import defaultdict
d = default... | 1 | 2016-08-19T05:11:33Z | [
"python",
"performance",
"list",
"dictionary"
] |
How can I use urllib.request.urlretrieve with python 2.7 | 39,029,356 | <p>I am trying to get images dowloaded from image-net.org so that I can create a haar cascade classifier. I am following this tutorial <a href="https://www.youtube.com/watch?v=z_6fPS5tDNU&list=PLQVvvaa0QuDdttJXlLtAJxJetJcqmqlQq&index=18" rel="nofollow">https://www.youtube.com/watch?v=z_6fPS5tDNU&list=PLQVvv... | 0 | 2016-08-19T00:18:36Z | 39,029,399 | <p>You just need to import urllib without '2'</p>
<pre><code>import urllib
urllib.urlretrieve(i, "Negatives/"+str(num)+".jpg")
</code></pre>
| 2 | 2016-08-19T00:25:51Z | [
"python",
"python-2.7",
"urllib2",
"urllib"
] |
How can I use urllib.request.urlretrieve with python 2.7 | 39,029,356 | <p>I am trying to get images dowloaded from image-net.org so that I can create a haar cascade classifier. I am following this tutorial <a href="https://www.youtube.com/watch?v=z_6fPS5tDNU&list=PLQVvvaa0QuDdttJXlLtAJxJetJcqmqlQq&index=18" rel="nofollow">https://www.youtube.com/watch?v=z_6fPS5tDNU&list=PLQVvv... | 0 | 2016-08-19T00:18:36Z | 39,029,538 | <p>on this <a href="http://stackoverflow.com/questions/17449904/python-urllib-urlretrieve-behind-proxy">Python urllib urlretrieve behind proxy</a></p>
<pre><code>import urllib2
download = opener.urlretrieve(URL, "Negatives/"+str(num)+".jpg")
</code></pre>
<p>the code can be transformed to</p>
<pre><code>import urll... | 0 | 2016-08-19T00:46:54Z | [
"python",
"python-2.7",
"urllib2",
"urllib"
] |
Scraping next page XHR request | 39,029,382 | <p>I want to scrape the second page of this user <a href="https://www.tripadvisor.com/members/1happykat" rel="nofollow">reviews</a>. </p>
<p>However the next button executes a XHR request, and while I can see it using Chrome developer tools, I cannot replicate it. </p>
| 0 | 2016-08-19T00:23:14Z | 39,030,263 | <p>It's not so easy task. First of all you should install this
<a href="https://chrome.google.com/webstore/detail/request-maker/kajfghlhfkcocafkcjlajldicbikpgnp" rel="nofollow">extension</a>.
It helps you to test own requests based on captured data, i.e. catch and simulate requests with captured data.</p>
<p>As I see ... | 0 | 2016-08-19T02:33:11Z | [
"python",
"ajax",
"scrape"
] |
Call imported function in python using string | 39,029,428 | <p>I have a list of the names of imported functions, which I can call as follows:</p>
<pre><code>from myfile import function1
from myfile import function2
function1()
function2()
</code></pre>
<p>How would I call the functions from a list of names? For example:</p>
<pre><code>fns = ['function1', 'function2']
for fn... | 2 | 2016-08-19T00:29:33Z | 39,029,447 | <p>You can access to function objects from <code>globals()</code> namespace, but note that this is not a general approach, since first of all your imported objects should be callable (have <code>__call__</code> attribute) and they should be present in global name space.:</p>
<pre><code>for fn in fns:
try:
... | 2 | 2016-08-19T00:32:40Z | [
"python"
] |
Call imported function in python using string | 39,029,428 | <p>I have a list of the names of imported functions, which I can call as follows:</p>
<pre><code>from myfile import function1
from myfile import function2
function1()
function2()
</code></pre>
<p>How would I call the functions from a list of names? For example:</p>
<pre><code>fns = ['function1', 'function2']
for fn... | 2 | 2016-08-19T00:29:33Z | 39,029,462 | <p>don't use a list of strings, just store the functions in the list:</p>
<pre><code>fns = [function1, function2]
for fn in fns:
fn()
</code></pre>
| 4 | 2016-08-19T00:35:35Z | [
"python"
] |
BeautifulSoup: findAll doesn't find the tags | 39,029,430 | <p>I'm sorry about the many questions I post, but I have no idea what to do about this bug: when testing this <a href="http://www.wired.com/2016/08/cape-watch-99/" rel="nofollow">page</a>, with simple <code>p</code>s</p>
<pre><code>ab=soup.find("article", {"itemprop":"articleBody"})
p=ab.findAll("p")
print(len(p)) #g... | 1 | 2016-08-19T00:29:47Z | 39,030,583 | <p>Your code is giving only one p because when your are parsing soup and trying to see what it has parsed,it is getting only one paragraph
see below code</p>
<pre><code>ab = soup.find("article", {"itemprop": "articleBody"})
print ab
</code></pre>
<p>the output is </p>
<pre><code><article class="content link-unde... | 1 | 2016-08-19T03:17:58Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
BeautifulSoup: findAll doesn't find the tags | 39,029,430 | <p>I'm sorry about the many questions I post, but I have no idea what to do about this bug: when testing this <a href="http://www.wired.com/2016/08/cape-watch-99/" rel="nofollow">page</a>, with simple <code>p</code>s</p>
<pre><code>ab=soup.find("article", {"itemprop":"articleBody"})
p=ab.findAll("p")
print(len(p)) #g... | 1 | 2016-08-19T00:29:47Z | 39,036,620 | <p>The issue is the parser:</p>
<pre><code>In [21]: req = requests.get("http://www.wired.com/2016/08/cape-watch-99/")
In [22]: soup = BeautifulSoup(req.content, "lxml")
In [23]: len(soup.select("article[itemprop=articleBody] p"))
Out[23]: 26
In [24]: soup = BeautifulSoup(req.content, "html.parser")
In [25]: len(so... | 1 | 2016-08-19T10:23:04Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
(Python) How can I turn a csv file with thousands of 10 digit numbers into decimal? (10dig -> 3dig+7decimal) | 39,029,468 | <p>I am working with large data of GPS coordinates. These coordinates are coming in as 10 digit numbers (<code>1234567890</code>) from a csv file.</p>
<p>I have two 25,000 columns of 10 digit numbers for both Latitude and Longitude.</p>
<p>How can I turn <code>1234567890</code> into <code>123.4567890</code>?</p>
<p>... | 0 | 2016-08-19T00:36:18Z | 39,029,533 | <p>So if your content is string and you need to divide by <code>10**7</code>, you could simply do this:</p>
<pre><code>def to_float(s):
return float(s)/10**7
</code></pre>
<p>then do <code>df.apply(to_float)</code></p>
| 0 | 2016-08-19T00:44:49Z | [
"python",
"pandas",
"numpy"
] |
(Python) How can I turn a csv file with thousands of 10 digit numbers into decimal? (10dig -> 3dig+7decimal) | 39,029,468 | <p>I am working with large data of GPS coordinates. These coordinates are coming in as 10 digit numbers (<code>1234567890</code>) from a csv file.</p>
<p>I have two 25,000 columns of 10 digit numbers for both Latitude and Longitude.</p>
<p>How can I turn <code>1234567890</code> into <code>123.4567890</code>?</p>
<p>... | 0 | 2016-08-19T00:36:18Z | 39,042,720 | <p>If you want to convert the csv file itself (instead of the in-memory data read from the csv file), you could use the regular expression library.</p>
<pre><code>import re
with open('input.csv') as input_file, open('output.csv', 'w') as output_file:
for line in input_file:
line = re.sub(r'(\d{3})(\d{7})'... | 0 | 2016-08-19T15:25:15Z | [
"python",
"pandas",
"numpy"
] |
Pandas Python - Finding Time Series Not Covered | 39,029,480 | <p>Hoping someone can help me out with this one because I don't even know where to start.</p>
<p>Given a data frame that contains a series of start and end times, such as:</p>
<pre><code>Order Start Time End Time
1 2016-08-18 09:30:00.000 2016-08-18 09:30:05.000
1 2016-08-18 09:30:00.005 20... | 1 | 2016-08-19T00:37:10Z | 39,040,021 | <h3>Setup</h3>
<pre><code>from StringIO import StringIO
import pandas as pd
text = """Order Start Time End Time
1 2016-08-18 09:30:00.000 2016-08-18 09:30:05.000
1 2016-08-18 09:30:00.005 2016-08-18 09:30:25.001
1 2016-08-18 09:30:30.001 2016-08-18 09:30:56.002
1 2016-08-18 ... | 1 | 2016-08-19T13:14:27Z | [
"python",
"pandas",
"time-series"
] |
Subtrees of Phylogenetic Trees in BioPython | 39,029,517 | <p>I have a phylogenetic tree in newick format. I want to pull out a subtree based on the labels of the terminal nodes (so based on a list of species). A copy of the tree I am using can be found here: <a href="http://hgdownload.soe.ucsc.edu/goldenPath/dm6/multiz27way/dm6.27way.nh" rel="nofollow">http://hgdownload.soe.u... | 1 | 2016-08-19T00:41:47Z | 39,029,641 | <p>Ok yeah, assuming you want the smallest tree that has all the species in your species list you want the root node of this tree to be the most recent common ancestor (MRCA) of all the species in the list which is thankfully already implemented in Phylo:</p>
<pre><code>from Bio import Phylo
#read in Phylogenetic Tre... | 3 | 2016-08-19T01:01:41Z | [
"python",
"tree",
"bioinformatics",
"biopython"
] |
Subtrees of Phylogenetic Trees in BioPython | 39,029,517 | <p>I have a phylogenetic tree in newick format. I want to pull out a subtree based on the labels of the terminal nodes (so based on a list of species). A copy of the tree I am using can be found here: <a href="http://hgdownload.soe.ucsc.edu/goldenPath/dm6/multiz27way/dm6.27way.nh" rel="nofollow">http://hgdownload.soe.u... | 1 | 2016-08-19T00:41:47Z | 39,029,850 | <p>Instead of using BioPython, use <code>ete3</code>.</p>
<pre><code>from ete3 import Tree
t = Tree('dm6.27way.nh')
t.prune(species_list, preserve_branch_length=True)
t.write()
</code></pre>
<p>From the documentation,</p>
<p>From version 2.2, this function includes also the preserve_branch_length flag, which allows ... | 0 | 2016-08-19T01:35:57Z | [
"python",
"tree",
"bioinformatics",
"biopython"
] |
NameError: name 'name' is not defined | 39,029,555 | <p>Currently working through Python Crash course and this example is giving me trouble</p>
<pre><code>class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
""" initializing name and cuisine attributes"""
self.restaurant_name = name
self.cuisine_type = c_type
def greeti... | -3 | 2016-08-19T00:49:43Z | 39,029,565 | <p>Looks like a small mistake, just modify it in your <code>__init__</code></p>
<pre><code>self.name = restaurant_name
</code></pre>
| 2 | 2016-08-19T00:52:01Z | [
"python",
"class"
] |
NameError: name 'name' is not defined | 39,029,555 | <p>Currently working through Python Crash course and this example is giving me trouble</p>
<pre><code>class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
""" initializing name and cuisine attributes"""
self.restaurant_name = name
self.cuisine_type = c_type
def greeti... | -3 | 2016-08-19T00:49:43Z | 39,029,592 | <pre><code>class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
""" initializing name and cuisine attributes"""
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
</code></pre>
<p>name is not part of your class init. It should be <code>restaurant_name<... | 0 | 2016-08-19T00:54:51Z | [
"python",
"class"
] |
NameError: name 'name' is not defined | 39,029,555 | <p>Currently working through Python Crash course and this example is giving me trouble</p>
<pre><code>class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
""" initializing name and cuisine attributes"""
self.restaurant_name = name
self.cuisine_type = c_type
def greeti... | -3 | 2016-08-19T00:49:43Z | 39,029,598 | <p>Your problem is in your <code>__init__</code> method in your <code>Restaurant</code> class.</p>
<pre><code>class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
""" initializing name and cuisine attributes"""
self.restaurant_name = name
self.cuisine_type = c_type
</code>... | 1 | 2016-08-19T00:55:59Z | [
"python",
"class"
] |
NameError: name 'name' is not defined | 39,029,555 | <p>Currently working through Python Crash course and this example is giving me trouble</p>
<pre><code>class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
""" initializing name and cuisine attributes"""
self.restaurant_name = name
self.cuisine_type = c_type
def greeti... | -3 | 2016-08-19T00:49:43Z | 39,029,608 | <p>Just a small mistake, from mixing variable names. Change your <code>__init__</code> function to</p>
<pre><code>def __init__(self, name, cuisine_type):
""" initializing name and cuisine attributes"""
self.name = name
self.cuisine_type = c_type
</code></pre>
| 1 | 2016-08-19T00:57:07Z | [
"python",
"class"
] |
Saving List of Tuples in XML | 39,029,570 | <p>I have a list of lists as such:</p>
<pre><code>[[value A, Value B, Value C], [value D, value E, Value F]]
</code></pre>
<p>I've got XML structure as follows:</p>
<pre><code><root>
<data>
</data>
</root>
</code></pre>
<p>I'm trying to understand the best way to write the list into ... | 1 | 2016-08-19T00:52:29Z | 39,029,649 | <p>use <code>lxml</code></p>
<pre><code>from lxml import etree
var = [["value A", "Value B", "Value C"], ["value D", "value E", "Value F"]]
for j in var:
root = etree.Element('root')
for m in j:
data = etree.Element('data')
data.text = m
root.append(data)
out = etree.tostring(root... | 1 | 2016-08-19T01:03:34Z | [
"python",
"xml",
"list",
"nested-lists"
] |
Finding nested dynamically generated elements with Selenium | 39,029,575 | <p>I'm working with Selenium and the Chrome Driver, But I haven't been able to find an element by ID. However, this element is visible in the web inspector of the browser. I think this is because the element is dynamically generated (all the time I see the same URL in the Browser Url Bar, but content changes dynamicall... | 0 | 2016-08-19T00:53:01Z | 39,031,925 | <p>Actually you are going wrong, you are going to find element then use wait for WebElement. You should try using By locator instead as below :-</p>
<pre><code>button_a = driver.find_element_by_id('button_a')
button_a.click()
button_b = WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.ID, 'button_... | 0 | 2016-08-19T05:49:45Z | [
"python",
"selenium",
"selenium-webdriver",
"selenium-chromedriver"
] |
Finding nested dynamically generated elements with Selenium | 39,029,575 | <p>I'm working with Selenium and the Chrome Driver, But I haven't been able to find an element by ID. However, this element is visible in the web inspector of the browser. I think this is because the element is dynamically generated (all the time I see the same URL in the Browser Url Bar, but content changes dynamicall... | 0 | 2016-08-19T00:53:01Z | 39,032,568 | <blockquote>
<p>It seems that the driver is keeping a reference to the old DOM and
doesn't keep track of new elements added to the DOM, the page is not
reloaded after the click on button_a but I just get the classic Spin
Wheel where the client is dynamically generating new content.
Actually Selenium detects a... | 0 | 2016-08-19T06:38:21Z | [
"python",
"selenium",
"selenium-webdriver",
"selenium-chromedriver"
] |
While loop not properly breaking, script hangs | 39,029,596 | <p>The problem is that it is not detecting a draw and just hangs if noone wins. I understand that it isn't a good practice to paste the whole script here and ask for help but I'm all out of ideas. I got this TicTacToe script off of github and am trying to implement random moves between two AI players (both making only ... | -3 | 2016-08-19T00:55:42Z | 39,029,667 | <p>Player block</p>
<pre><code> while count == 0:
player_move = int(random.randint(1, 9))
if player_move not in board.available_moves():
continue
</code></pre>
<p>Computer block</p>
<pre><code> while count == 1:
computer_move = int(random.randint(1, 9))
if computer_m... | 0 | 2016-08-19T01:06:35Z | [
"python",
"python-2.7"
] |
While loop not properly breaking, script hangs | 39,029,596 | <p>The problem is that it is not detecting a draw and just hangs if noone wins. I understand that it isn't a good practice to paste the whole script here and ask for help but I'm all out of ideas. I got this TicTacToe script off of github and am trying to implement random moves between two AI players (both making only ... | -3 | 2016-08-19T00:55:42Z | 39,029,970 | <p>This is a very poor way to select an available move:</p>
<pre><code>while count == 0:
player_move = int(random.randint(1, 9))
if player_move not in board.available_moves():
continue
</code></pre>
<p>It will work OK when there are lots of available moves. But when there are very few available moves,... | 1 | 2016-08-19T01:53:28Z | [
"python",
"python-2.7"
] |
Reading a pre-formatted binary file in Python | 39,029,615 | <p>So, I created a simple binary file using MATLAB that has the following structure:</p>
<pre><code>file.test
--------
[record_type] = 1 % 'int', 4 bytes, record_type = 1 means a string is read next
[string_length] = len(str) % 'int', 4 bytes, tells us how many bytes to read
[string] = '...' % 'char', the number of by... | 0 | 2016-08-19T00:57:39Z | 39,029,729 | <p>You can use <a href="https://construct.readthedocs.io/en/latest/" rel="nofollow">Construct</a>:</p>
<pre><code>from construct import *
MyData = Struct(
"MyData",
SBInt32("record_type"),
Switch("value", lambda ctx: ctx.record_type,
{
1: Embed(Struct(
'string_data',
SB... | 0 | 2016-08-19T01:18:03Z | [
"python",
"matlab",
"file",
"numpy",
"binary"
] |
Printing color to the python command line | 39,029,635 | <p>I was working away on a project in python, and I was wondering how to pront with color. I know of colorama, and termcolor, but they are not working.
When I run this code in my python interpreter (PyCharm: <a href="https://www.jetbrains.com/pycharm/" rel="nofollow">https://www.jetbrains.com/pycharm/</a>) the colors w... | -1 | 2016-08-19T01:00:36Z | 39,029,679 | <p>Call <code>colorama.init()</code> before <code>print()</code>:</p>
<pre><code>import colorama
colorama.init(autoreset=True)
print(colorama.Fore.GREEN + 'Green text')
</code></pre>
| 0 | 2016-08-19T01:08:23Z | [
"python",
"printing",
"colors",
"command-line-interface"
] |
pandas dataframe look ahead value | 39,029,709 | <p>What's the best way to do this with pandas dataframe? I want to loop through a dataframe, and compute the difference between the current value and the next value which is different than the current value.
For example:
[13, 13, 13, 14, 13, 12]
will create a new column with this
[-1, -1, -1, 1, 1]</p>
| 0 | 2016-08-19T01:13:33Z | 39,030,005 | <p>How about use <code>diff</code> to calculate the difference and then back fill 0 with the next non zero value:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({"S": [13, 13, 13, 14, 13, 12]})
df.S.diff(-1).replace(0, np.nan).bfill() # replace zero with nan and apply back fill.
# 0 -1
#... | 1 | 2016-08-19T01:57:45Z | [
"python",
"pandas",
"dataframe"
] |
Sprite duplicating itself..? | 39,029,712 | <p>While doing some test in python, one of the sprites in a Player class randomly started duplicating itself.. I can't figure it out.. (I realize it's probally something really simple)</p>
<p>Here's the code:</p>
<pre><code>import pygame
from pygame.locals import *
import time
pygame.font.init()
myfont = pygame.font... | -1 | 2016-08-19T01:14:05Z | 39,029,774 | <p>Turns out my original answer was close - your problem is that you're simply drawing the image - you never fill the screen even though you've declared <code>black = (0, 0, 0)</code>. You need to put <code>screen.fill(black)</code> before you start drawing everything else.</p>
<hr>
<p>For the record, here is what a ... | 0 | 2016-08-19T01:25:27Z | [
"python",
"pygame"
] |
Python + kivy: How to display multi language in one label (Unicode)? | 39,029,719 | <p>Using the following code I want to display letters from some languages into <strong>one label</strong>. </p>
<p>These languages are: <strong>English, German, Japanese, Chinese, Russian, French, Spanish, Arabic.</strong> </p>
<p>I tried with some Windows system fonts, but none of them could display <strong>ALL</str... | 0 | 2016-08-19T01:15:26Z | 39,034,644 | <p>For many technical and social reasons you won't find a single font of good quality that covers all the locales you want to target.</p>
<p>Good software achieves what you intend to do by composing different fonts (and the labels need to be annotated with the target locale, codepoint is not enough, Japanese and Chine... | 1 | 2016-08-19T08:39:35Z | [
"python",
"unicode",
"character-encoding",
"kivy"
] |
Flask CORS and Flask Limiter | 39,029,767 | <p>I am using flask cors, flask limiter and AngularJS for my web-app.. Everything is working fine but what I want is too return a 429 too many request message on the front-end but I can't seem to do that because the OPTIONS methods blocks everything once it returns a 429</p>
<p>My AngularJS error response code: </p>
... | 0 | 2016-08-19T01:24:48Z | 39,030,577 | <p>I got it now! Just put a methods parameter</p>
<pre><code>@limiter.limit("20/15minute", methods=['POST'])
</code></pre>
| 0 | 2016-08-19T03:17:02Z | [
"python",
"angularjs",
"flask",
"flask-cors"
] |
Does "%" divide the length of the word? If so, why does only 'why' come up? | 39,029,785 | <p>I hope to turn this into an app to remind myself to think every once in a while. I would like to ask 'why'/'why not' every time I put an input in. I wanna make the determinant factor whether or not the length of the <code>notoriginal</code>/<code>alsonotoriginal</code> is even or odd. </p>
<pre><code>print ('Have y... | -3 | 2016-08-19T01:26:51Z | 39,030,146 | <h2>The % Operand</h2>
<blockquote>
<p>The % (modulo) operator yields the remainder from the division of the
first argument by the second. The numeric arguments are first
converted to a common type. A zero right argument raises the
ZeroDivisionError exception. The arguments may be floating point
numbers, e.g... | 2 | 2016-08-19T02:16:07Z | [
"python",
"loops",
"division"
] |
PIP doesn't seem to be installing correctly | 39,029,810 | <p>I have updated my path for python 3.5.2 to its installation folder and installed pip manually through the get-pip.py file.</p>
<p>PIP is saying "Requirement already up-to-date: pip in c:\users\MyName\appdata\local\programs\python\python35-32\lib\site-packages"</p>
<p>When typing pip into CMD, it is saying that it ... | 0 | 2016-08-19T01:30:30Z | 39,029,839 | <p>Pip is not in your Path. The path variable is a place that holds directories for all your commands. Including commands like python. Right now it searches in all the directories listed in the Path variable, and when not found it will output a command not recognized error.</p>
<p>Windows: </p>
<p><a href="http://w... | 0 | 2016-08-19T01:34:16Z | [
"python",
"pip",
"python-3.5"
] |
PIP doesn't seem to be installing correctly | 39,029,810 | <p>I have updated my path for python 3.5.2 to its installation folder and installed pip manually through the get-pip.py file.</p>
<p>PIP is saying "Requirement already up-to-date: pip in c:\users\MyName\appdata\local\programs\python\python35-32\lib\site-packages"</p>
<p>When typing pip into CMD, it is saying that it ... | 0 | 2016-08-19T01:30:30Z | 39,029,852 | <p>You need adding pip.exe directory (C:\Pythonxxx\Scripts) to PATH Environment Variable in Windows.</p>
| 1 | 2016-08-19T01:36:03Z | [
"python",
"pip",
"python-3.5"
] |
Python - using re.compile with re.split | 39,029,811 | <p>I am trying to extract specific data from a text file. Each line of the file has strings separated by tabs. I would like to separate each word and keep it as whole word. Is it possible to combine re.split and re.compile.findall to do this? </p>
<p>An example is shown below. </p>
<p>Original line in file: </p>
<pr... | -2 | 2016-08-19T01:30:39Z | 39,029,871 | <p>Just use a single <code>findall</code> and search for the characters you're interested in.</p>
<pre><code>>>> import re
>>> s = 'Name Charlie Blue Bird ******Grade:5****** ****** ****** ****** '
>>> re.findall(r'[A-Za-z0-9:]+', s)
['Name', 'Charlie', 'Blue', 'Bird', 'Grade... | 0 | 2016-08-19T01:39:18Z | [
"python",
"regex"
] |
setting GDB breakpoint for C++ class member function written using template | 39,029,908 | <p>I'm trying to set a breakpoint at a C++ class member function which is defined using template. I've looked for the solution in stackoverflow but couldn't find the same problem. Below is a sample code showing the function definition(from py-faster-rcnn caffe code, Dtype is defined as float outside).</p>
<pre><code>t... | 2 | 2016-08-19T01:45:49Z | 39,175,405 | <p>I have never tried this but have you considered using nm to determine how it is defined within the shared library? You might be able to use that information to help ddd/gdb consistently find the template method.</p>
| 0 | 2016-08-26T22:23:09Z | [
"python",
"c++",
"templates",
"gdb",
"breakpoints"
] |
How to best extract sub dictionaries by value in this object? | 39,029,939 | <p>I am dealing with a database in which someone created a PHP ArrayObject that had virtually no checks in place before being created. </p>
<p>I am able to extract this as a dictionary of dictionaries using the
python phpserialize library's unserialize module, so that it looks like this:</p>
<pre><code>{0: '{"0": {"... | 0 | 2016-08-19T01:49:52Z | 39,030,122 | <p>I'm assuming you want a grouping of the sub-dictionaries by the value of their key '0', i.e. by 'location', 'environmental_stewardship', etc. But actually, you don't have subdictionaries at all, you have strings that are dictionary literals. If your dictionary were named <code>horrible_mess</code>, you could use thi... | 2 | 2016-08-19T02:13:36Z | [
"python",
"dictionary",
"serialization",
"key-value",
"arrayobject"
] |
How to best extract sub dictionaries by value in this object? | 39,029,939 | <p>I am dealing with a database in which someone created a PHP ArrayObject that had virtually no checks in place before being created. </p>
<p>I am able to extract this as a dictionary of dictionaries using the
python phpserialize library's unserialize module, so that it looks like this:</p>
<pre><code>{0: '{"0": {"... | 0 | 2016-08-19T01:49:52Z | 39,030,125 | <p>Please let me know if this is the output you expect, if not could you please include expected output in your question? I apologize that the code is ugly, but it basically just loops through all of the sub-dictionaries and only considers values that can't be converted to int (this is a hack) and uses those as keys in... | 1 | 2016-08-19T02:13:41Z | [
"python",
"dictionary",
"serialization",
"key-value",
"arrayobject"
] |
python 2.7 replacing a raw_input string with a value from a dictionary | 39,030,037 | <p>I am very new to programming (6 weeks, self taught on the net with "codecademy" and "python the hard way"). I decided it was time I started experimenting at writing code without direction and I hit a wall with my second project.</p>
<p>I am trying to make a "secret coder" that takes a raw_input string and replaces ... | 2 | 2016-08-19T02:01:54Z | 39,030,103 | <pre><code>def encode(entry, letters):
for k, v in letters.iteritems():
if k in alpha:
entry = entry.replace(k, v)
return entry
print encode(entry, alpha)
</code></pre>
<p>Calling <code>encode(entry, alpha)</code> in your print function, you pass the <code>encode()</code> function the <code... | 0 | 2016-08-19T02:11:32Z | [
"python",
"python-2.7",
"function",
"dictionary",
"raw-input"
] |
python 2.7 replacing a raw_input string with a value from a dictionary | 39,030,037 | <p>I am very new to programming (6 weeks, self taught on the net with "codecademy" and "python the hard way"). I decided it was time I started experimenting at writing code without direction and I hit a wall with my second project.</p>
<p>I am trying to make a "secret coder" that takes a raw_input string and replaces ... | 2 | 2016-08-19T02:01:54Z | 39,030,105 | <p>The problem is that since you're iterating over the dictionary instead of the string you might replace original character many times. For example with given input of <code>'ab'</code> the first replace will result to <code>'bb'</code> and second to <code>'cc'</code> in case that <a href="https://docs.python.org/2/li... | 2 | 2016-08-19T02:11:37Z | [
"python",
"python-2.7",
"function",
"dictionary",
"raw-input"
] |
python 2.7 replacing a raw_input string with a value from a dictionary | 39,030,037 | <p>I am very new to programming (6 weeks, self taught on the net with "codecademy" and "python the hard way"). I decided it was time I started experimenting at writing code without direction and I hit a wall with my second project.</p>
<p>I am trying to make a "secret coder" that takes a raw_input string and replaces ... | 2 | 2016-08-19T02:01:54Z | 39,030,138 | <p>Dictionaries aren't ordered, so you are replacing some letters ('a' -> 'b') and others are getting skipped over.</p>
<p>For your edification what you are doing is called a <code>rot</code> (rotation). The most well-known one is <code>rot13</code>.</p>
<p>Writing things yourself is helpful when you first start out,... | 0 | 2016-08-19T02:15:00Z | [
"python",
"python-2.7",
"function",
"dictionary",
"raw-input"
] |
python 2.7 replacing a raw_input string with a value from a dictionary | 39,030,037 | <p>I am very new to programming (6 weeks, self taught on the net with "codecademy" and "python the hard way"). I decided it was time I started experimenting at writing code without direction and I hit a wall with my second project.</p>
<p>I am trying to make a "secret coder" that takes a raw_input string and replaces ... | 2 | 2016-08-19T02:01:54Z | 39,030,162 | <p>Xetnus is correct you need to loop through entry variable instead of the letters. maybe something like this</p>
<pre><code>def encode(entry, letters):
new_entry = ''
for letter in entry:
if letter in letters:
new_entry += letters[letter]
return new_entry
print encode(entry, alpha)
</... | 2 | 2016-08-19T02:17:46Z | [
"python",
"python-2.7",
"function",
"dictionary",
"raw-input"
] |
python 2.7 replacing a raw_input string with a value from a dictionary | 39,030,037 | <p>I am very new to programming (6 weeks, self taught on the net with "codecademy" and "python the hard way"). I decided it was time I started experimenting at writing code without direction and I hit a wall with my second project.</p>
<p>I am trying to make a "secret coder" that takes a raw_input string and replaces ... | 2 | 2016-08-19T02:01:54Z | 39,030,167 | <p>Others have pointed out how to do this correctly using a dictionary as lookup. However, you can also use the <code>str.translate</code> method which avoids having to do the look up and rebuilding a string.</p>
<pre><code>import string
trans = string.maketrans(
'abcdefghijklmnopqrstuvwxyz', # from...
'bcdef... | 0 | 2016-08-19T02:18:26Z | [
"python",
"python-2.7",
"function",
"dictionary",
"raw-input"
] |
Capture interactive Python shell output along with input | 39,030,061 | <p>I want to capture the Python shell output along with the input sent to it. For example, in the following use case, help() should also be present in Line 4 of capture.log:</p>
<pre><code>$ echo "help()" | python3 -i > capture.log 2>&1
$ cat capture.log
Python 3.4.2 (default, Oct 8 2014, 10:45:20)
[GCC ... | 4 | 2016-08-19T02:06:49Z | 39,030,729 | <p>Assuming a Unix-like environment, you can capture all <code>tty</code> input and output with the <code>script</code> command:</p>
<pre><code>$ script capture.log
Script started, output file is capture.log
$ python3
# python interactive session here
$ exit
Script done, output file is capture.log
$ cat capture.log
Sc... | 5 | 2016-08-19T03:37:11Z | [
"python",
"bash",
"shell",
"stdout",
"stdin"
] |
sort out dataframe where index meet certain conditions | 39,030,075 | <p>I have a data frame like this:</p>
<pre><code> name pe outstanding totals totalAssets
code
300533 abc 30.04 2500.00 10000.00 82066.80
300532 def 31.27 2100.00 8400.00 77945.25
603986 ... | 1 | 2016-08-19T02:08:13Z | 39,030,175 | <p>You can use <code>str</code> to extract the first 3 characters from index:</p>
<pre><code>df[df.index.str[:3].isin(['300', '000'])]
# name pe outstanding totals totalAssets
# code
#300533 abc 30.04 2500.00 10000.00 82066.80
#300532 def 31.27 2100.00 ... | 2 | 2016-08-19T02:19:33Z | [
"python",
"pandas"
] |
code from black hat python runs forever? | 39,030,080 | <p>The code in this pastebin link <a href="http://pastebin.com/E98XChyU" rel="nofollow">here</a> is from the Black Hat Python Book, It's a great book but I've been having a lot of problems with the code because I couldn't simply copy and paste the code to my ide which meant hours of rewriting because of errors.</p>
<p... | 0 | 2016-08-19T02:09:08Z | 39,030,931 | <p>Here are some insights : </p>
<p>First using pastebin you can click 'raw' link to get the code properly : <a href="http://pastebin.com/raw/E98XChyU" rel="nofollow">http://pastebin.com/raw/E98XChyU</a></p>
<p>Didn't test, but it seems correct.</p>
<p>Anyway, your problem is in this function : <code>client_sender(b... | 0 | 2016-08-19T04:05:52Z | [
"python",
"python-2.7",
"hacking"
] |
pandas: Add row from one data frame to another data frame? | 39,030,164 | <p>I have two dataframes with identical column headers.</p>
<p>I am iterating over the rows in df1, splitting one of the columns, and then using those split columns to create multiple rows to add to the other dataframe.</p>
<pre><code>for index, row in df1.iterrows():
curr_awards = row['AWARD'].split(" ")
for... | -2 | 2016-08-19T02:18:12Z | 39,030,413 | <p>I figured it out.</p>
<pre><code>for index, row in df1.iterrows():
curr_awards = row['AWARD'].split(" ")
for award in curr_awards:
new_line = row
new_line['AWARD'] = award.strip()
df2.loc[len(df2)] = new_line
</code></pre>
| 0 | 2016-08-19T02:53:30Z | [
"python",
"python-3.x",
"pandas"
] |
How to return a dictionary using field function in Odoo | 39,030,185 | <p>I got an error in my field function.
In my function, I want to return a float value from my variable <code>total</code>. And I already searched it and I found an answer <a href="http://stackoverflow.com/questions/27628039/valueerror-dictionary-update-sequence-element-0-has-length-1-2-is-required">here</a> but still ... | 0 | 2016-08-19T02:21:43Z | 39,031,116 | <p>You have mixed up both api, you have declared field with old api and function written in new api. You should try following.</p>
<pre><code>@api.multi
@api.depends('total_eec', 'total_tec')
def _consumption_actual_value(self):
for i in self:
total = i.total_eec + i.total_tec
i.consumption_actual ... | 1 | 2016-08-19T04:26:15Z | [
"python",
"openerp",
"odoo-8"
] |
Crazy but minor issue in grid-based game | 39,030,278 | <p>This has been really bugging me. I'm creating a game where a hero moves on a grid and part of it involves a collision check. The collision check stops the hero from moving in a direction if something already occupies the grid there.</p>
<p>It works for all directions except down. I can't see why?! It's the same str... | -1 | 2016-08-19T02:34:36Z | 39,031,491 | <p>An <code>else</code> block goes with an <code>if</code> and optionally any number of <code>elif</code> blocks. Since you used only <code>if</code> blocks, the <code>else</code> is really with only the <code>Down</code> option. Let's say you hit down. Your <code>if ... == "DOWN":</code> block will be entered. If ... | 0 | 2016-08-19T05:08:48Z | [
"python",
"python-3.x",
"oop",
"pygame"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.