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 |
|---|---|---|---|---|---|---|---|---|---|
Can't combine two strings togetger | 39,423,462 | <p>When I was doing some tricks with strings,I can't combine the string <code>word[0]</code> with word. I thought this is because they are from the same string. If so, what can I do? </p>
<pre><code>def pig_it(text):
l1 = text.split(' ')
l2 =[]
for word in l1:
first_letter = word[0]
new ... | -3 | 2016-09-10T06:54:36Z | 39,423,523 | <p>Its a little unclear about what you want to achieve with the above code but I rand it anyways and the code works according to the logic you have written the code</p>
<p>My out put was:</p>
<p>yay ameay say ranklingay </p>
<p>In case you want to do some thing specific, update the question and make it a little clea... | -1 | 2016-09-10T07:04:29Z | [
"python",
"string",
"python-2.7"
] |
How to configure Atom to autocomplete Django templates | 39,423,531 | <p>I need to find a way/package to make Atom use autocomplete for Django projects, especially Django templates.
I found this <a href="https://atom.io/packages/django-templates" rel="nofollow">package</a> in Atom's installer, but it doesn't include a shortcut for auto completion of this syntax {% %}, {{ }} which I nee... | -1 | 2016-09-10T07:06:05Z | 39,423,607 | <p>You could make your own snippets in Atom.</p>
<p>To do that go to <strong>Edit > Snippets</strong></p>
<p>In the document that open's you can paste this bit:</p>
<pre><code>'.html.django':
'Example snippet':
'prefix': '%%'
'body': '{% $1 %}$2'
</code></pre>
<p>This example would expand to <code>{% %}</... | 0 | 2016-09-10T07:14:50Z | [
"python",
"django",
"atom-editor"
] |
Python : error with importing md5 | 39,423,542 | <p>I have problem with importing md5 library
I just use the code below:</p>
<pre><code>import md5
filemd5 = md5.new(password.strip()).hexdigest()
</code></pre>
<p>I also have tried this code :</p>
<pre><code>from hashlib import md5
filemd5 = md5.new(password.strip()).hexdigest()
</code></pre>
<p>also this code :</... | 1 | 2016-09-10T07:07:44Z | 39,423,562 | <p><code>md5</code> is not a module, it is an object. But it has no <code>new</code> method. It just has to be built, like any object.</p>
<p>Use as follows:</p>
<pre><code>import hashlib
m=hashlib.md5(bytes("text","ascii")) # python 3
m=hashlib.md5("text") # python 2
print(m.hexdigest())
</code></pre>
<p>resul... | 0 | 2016-09-10T07:10:18Z | [
"python",
"md5"
] |
Writing specific value back to .csv, Python | 39,423,635 | <p>I have a .<code>csv</code> file with some data that i would like to change.
It looks like this:</p>
<pre><code>item_name,item_cost,item_priority,item_required,item_completed
item 1,11.21,2,r
item 2,411.21,3,r
item 3,40.0,1,r,c
</code></pre>
<p>My code runs most of what i need but i am unsure of how to write back ... | 3 | 2016-09-10T07:18:08Z | 39,423,802 | <p>There are several problems here</p>
<ul>
<li>you're using a <code>DictReader</code>, which is good to read data, but not as good to read and write data as the original file, since dictionaries do not ensure column order (unless you don't care, but most of the time people don't want columns to be swapped). I just re... | 1 | 2016-09-10T07:37:43Z | [
"python",
"csv",
"dictionary"
] |
Writing specific value back to .csv, Python | 39,423,635 | <p>I have a .<code>csv</code> file with some data that i would like to change.
It looks like this:</p>
<pre><code>item_name,item_cost,item_priority,item_required,item_completed
item 1,11.21,2,r
item 2,411.21,3,r
item 3,40.0,1,r,c
</code></pre>
<p>My code runs most of what i need but i am unsure of how to write back ... | 3 | 2016-09-10T07:18:08Z | 39,423,829 | <p>I guess this should do the trick:</p>
<ol>
<li>Open a file which can read and written to update it (use "+r" for that)</li>
<li>instead of opening it again write it right there using csvfilewriter, which we create at the start.</li>
</ol>
<p>file.py</p>
<pre><code>import csv
fieldnames = ["item_name","item_cost",... | 0 | 2016-09-10T07:42:24Z | [
"python",
"csv",
"dictionary"
] |
Writing specific value back to .csv, Python | 39,423,635 | <p>I have a .<code>csv</code> file with some data that i would like to change.
It looks like this:</p>
<pre><code>item_name,item_cost,item_priority,item_required,item_completed
item 1,11.21,2,r
item 2,411.21,3,r
item 3,40.0,1,r,c
</code></pre>
<p>My code runs most of what i need but i am unsure of how to write back ... | 3 | 2016-09-10T07:18:08Z | 39,427,445 | <p>Using <code>pandas</code>:</p>
<pre><code>import pandas as pd
df = pd.read_csv("items.csv")
print("Enter the item number:")
marked_item = int(input())
df.set_value(marked_item - 1, 'item_required', 'x')
# This is the extra feature you required:
df.set_value(marked_item - 1, 'item_completed', 'c')
df.to_csv("it... | 1 | 2016-09-10T15:13:32Z | [
"python",
"csv",
"dictionary"
] |
flask socketio emit to specific user | 39,423,646 | <p>I see there is a question about this topic, but the specific code is not outlined. Say I want to emit only to the first client.</p>
<p>For example (in events.py):</p>
<pre><code>clients = []
@socketio.on('joined', namespace='/chat')
def joined(message):
"""Sent by clients when they enter a room.
A status ... | 1 | 2016-09-10T07:19:27Z | 39,431,811 | <p>I'm not sure I understand the logic behind emitting to the first client, but anyway, this is how to do it:</p>
<pre><code>clients = []
@socketio.on('joined', namespace='/chat')
def joined(message):
"""Sent by clients when they enter a room.
A status message is broadcast to all people in the room."""
# ... | 1 | 2016-09-11T00:34:34Z | [
"python",
"flask",
"flask-socketio"
] |
Unable to run Python interpreter in terminal, through Anaconda3 | 39,423,671 | <p>When I try the "python" or "python3" command to run the interpreter, this is the error am getting.</p>
<pre><code>[sidgupta234@sidgupta234-Lenovo-G580 Downloads]$ python
Failed to import the site module
Traceback (most recent call last):
File "/usr/lib/python3.5/site.py", line 580, in <module>
... | 0 | 2016-09-10T07:23:12Z | 39,424,039 | <p>I guess <a href="https://ostrokach.github.io/posts/configuring_apache_django_anaconda/" rel="nofollow">configuring_apache_django_anaconda</a> is relevant, if you look at the troubleshooting section. </p>
<blockquote>
<p>This means that apache is using Python 2 instead of Python 3 to run a program that is designed... | 0 | 2016-09-10T08:11:40Z | [
"python",
"anaconda"
] |
Unable to run Python interpreter in terminal, through Anaconda3 | 39,423,671 | <p>When I try the "python" or "python3" command to run the interpreter, this is the error am getting.</p>
<pre><code>[sidgupta234@sidgupta234-Lenovo-G580 Downloads]$ python
Failed to import the site module
Traceback (most recent call last):
File "/usr/lib/python3.5/site.py", line 580, in <module>
... | 0 | 2016-09-10T07:23:12Z | 39,470,583 | <p>That is an strange situation you have gotten yourself into, and if Continuum had any part of it (where I'm an engineer) we'd like to understand what we did that led to it so we can avoid it in the future.</p>
<p>Where did you try installing Anaconda? Did you set any environment variables?</p>
<p>The "easiest-to-r... | 0 | 2016-09-13T12:51:37Z | [
"python",
"anaconda"
] |
Why the argument of recursive code in 8th line is 'string[:i] + string[i + 1:]' but not 'string' | 39,423,683 | <p>It's about a permutation problem. I tried to understand the code below but feel a little confusing finally.</p>
<p>Why the argument of recursive code in 8th line is 'string[:i] + string[i + 1:]' but not 'string'.</p>
<p>I know that 'string' argument to recursive will return RuntimeError.</p>
<p>But why?</p>
<p>... | 0 | 2016-09-10T07:24:19Z | 39,423,749 | <p>Note that <code>string[a:b]</code> means a <code>[a b)</code> (including <code>a</code> and excluding <code>b</code>) substring of the string. So <code>string[:i] + string[i + 1:]</code> means the whole string without <code>i</code>th character.</p>
| 1 | 2016-09-10T07:30:38Z | [
"python",
"algorithm",
"recursion"
] |
Why would I prefer metaclass over inheritance from a superclass in Python | 39,423,702 | <p>From what I've learned so far, metaclass and inheritance from superclass in Python serve a very similar purpose, but superclass inheritance is more powerful.</p>
<p>Why would I prefer metaclass over superclass inheritance? In what kind of case metaclass would be helpful?</p>
<p>Sorry if there is any wrong assumpti... | 0 | 2016-09-10T07:25:43Z | 39,423,820 | <p>I think you've misunderstood. Inheritance is the classic object oriented technique of reusing code by putting the commonly used stuff in a base class and deriving from that. </p>
<p>Metaclasses in a nutshell) allow you to customise the process of creation of a class (specifically the <code>__new__</code> method) so... | 1 | 2016-09-10T07:41:06Z | [
"python",
"class",
"inheritance",
"superclass",
"metaclass"
] |
How do you control user access to records in a key-value database? | 39,423,756 | <p>I have a web application that accesses large amounts of JSON data.</p>
<p>I want to use a key value database for storing JSON data owned/shared by different users of the web application (not users of the database). Each user should only be able to access the records they own or share.</p>
<p>In a relational databa... | 7 | 2016-09-10T07:31:40Z | 39,518,000 | <p>Both of the solutions you described have some limitations.</p>
<ul>
<li><p>You point yourself that including the owner ID in the key does not solve the problem of shared data. However, this solution may be acceptable, if you add another key/value pair, containing the IDs of the contents shared with this user <code>... | 2 | 2016-09-15T18:28:42Z | [
"python",
"database",
"nosql",
"authorization",
"key-value"
] |
Delete a file after reading | 39,423,763 | <p>In my code, user uploads file which is saved on server and read using the server path. I'm trying to delete the file from that path after I'm done reading it. But it gives me following error instead:</p>
<p><code>An error occurred while reading file. [WinError 32] The process cannot access the file because it is be... | 0 | 2016-09-10T07:32:39Z | 39,423,793 | <p>Instead of:</p>
<pre><code> f.closed
</code></pre>
<p>You need to say:</p>
<pre><code>f.close()
</code></pre>
<p><code>closed</code> is just a boolean property on the file object to indicate if the file is actually closed.</p>
<p><code>close()</code> is method on the file object that actually closes the file.</... | 2 | 2016-09-10T07:37:03Z | [
"python",
"file"
] |
Delete a file after reading | 39,423,763 | <p>In my code, user uploads file which is saved on server and read using the server path. I'm trying to delete the file from that path after I'm done reading it. But it gives me following error instead:</p>
<p><code>An error occurred while reading file. [WinError 32] The process cannot access the file because it is be... | 0 | 2016-09-10T07:32:39Z | 39,423,869 | <p>This</p>
<pre><code>import os
path = 'path/to/file'
with open(path) as f:
for l in f:
print l,
os.remove(path)
</code></pre>
<p>should work, with statement will automatically close the file after the nested block of code</p>
<p>if it fails, File could be in use by some external factor. you can use Redo p... | 1 | 2016-09-10T07:47:10Z | [
"python",
"file"
] |
Python: Issue with POST data in Requests | 39,423,868 | <p>I'm trying to use the <strong>Requests 2.9.1</strong> in <strong>Python 2.7</strong> to learn how to send <strong>POST</strong> data. However I feel that I'm missing something in the data I'm providing to <strong>requests</strong>, or somehow misformating something and have been banging my head at it all night.</p>... | 0 | 2016-09-10T07:47:09Z | 39,423,960 | <p>Take out all the <code>+</code> characters that you put between words. That's the URL-encoded representation of space, but the <code>requests</code> module does that for you. If you use it explicitly, it will re-encode the <code>+</code>, so the server script will see it as a literal <code>+</code>, not the space th... | 0 | 2016-09-10T08:00:24Z | [
"python",
"python-2.7",
"http-post",
"python-requests"
] |
ImportError: No module named scrapyproject.settings | 39,423,917 | <p>I have a scrapy project, the idea is to execute crawler and get the result back. I am using Flask as api end application and also using virtualenvironment.</p>
<pre><code>from scrapy.spiderloader import SpiderLoader
from scrapy.utils.project import get_project_settings
@app.route("/")
def hello():
settings = g... | 0 | 2016-09-10T07:54:07Z | 39,452,811 | <p><a href="https://twitter.com/chrisguitarguy/status/775155136452624384" rel="nofollow">Christopher Davis</a> mentioned to pass the environment copy to subprocess.</p>
<pre><code>proc = subprocess.Popen(..., env=os.environ.copy())
</code></pre>
<p>Which actually opened my eye to notice the introduction of <code>SCRA... | 0 | 2016-09-12T14:33:12Z | [
"python",
"scrapy",
"scrapy-spider"
] |
More precise time for python-bunyan logger? | 39,423,954 | <p>I've been using <code>bunyan</code> logger for <code>nodejs</code>, so when I had to program in <code>python</code> again I went out and found a compatible logger for <code>python</code>.</p>
<p><a href="https://github.com/Sagacify/logger-python" rel="nofollow">https://github.com/Sagacify/logger-python</a></p>
<p>... | 0 | 2016-09-10T07:59:22Z | 39,464,009 | <p>Milliseconds would be a bit of a hack, but you can add microseconds really easily.</p>
<p>Here:</p>
<p><a href="https://github.com/Sagacify/logger-python/blob/master/bunyan/formatter.py#L106" rel="nofollow">https://github.com/Sagacify/logger-python/blob/master/bunyan/formatter.py#L106</a></p>
<p>You would need to... | 0 | 2016-09-13T07:03:19Z | [
"python",
"logging",
"bunyan"
] |
Order of comparison for heap elements in python | 39,423,979 | <p>I'm using a heap to make a priority queue using heapq.</p>
<p>I insert an item into the queue using</p>
<p><code>heapq.heappush(h, (cost, node))</code></p>
<p>where <code>h</code> is the heap object, <code>cost</code> is the item by which I order my heap and <code>node</code> is an object of a custom defined clas... | 2 | 2016-09-10T08:02:58Z | 39,424,139 | <p>Introduce a small class that doesn't include the node in the comparison:</p>
<pre><code>class CostAndNode:
def __init__(self, cost, node):
self.cost = cost
self.node = node
# do not compare nodes
def __lt__(self, other):
return self.cost < other.cost
h = []
heapq.heappush(h... | 2 | 2016-09-10T08:25:36Z | [
"python",
"algorithm",
"python-3.x",
"sorting",
"heap"
] |
Order of comparison for heap elements in python | 39,423,979 | <p>I'm using a heap to make a priority queue using heapq.</p>
<p>I insert an item into the queue using</p>
<p><code>heapq.heappush(h, (cost, node))</code></p>
<p>where <code>h</code> is the heap object, <code>cost</code> is the item by which I order my heap and <code>node</code> is an object of a custom defined clas... | 2 | 2016-09-10T08:02:58Z | 39,424,234 | <p>If you can sensibly decide on a way to compare nodes, you could use this to break ties. For example, each node may be assigned a "label", which you can guarantee to be unique. You could break ties by comparing labels lexicographically.#</p>
<pre><code>class SearchNode:
def __init__(self, label):
self.la... | 2 | 2016-09-10T08:36:32Z | [
"python",
"algorithm",
"python-3.x",
"sorting",
"heap"
] |
Order of comparison for heap elements in python | 39,423,979 | <p>I'm using a heap to make a priority queue using heapq.</p>
<p>I insert an item into the queue using</p>
<p><code>heapq.heappush(h, (cost, node))</code></p>
<p>where <code>h</code> is the heap object, <code>cost</code> is the item by which I order my heap and <code>node</code> is an object of a custom defined clas... | 2 | 2016-09-10T08:02:58Z | 39,425,025 | <p>PQ with list and <code>bisect</code>, strings as stored objects for example. No changes in stored object required. Just construct <code>item = (cost, object)</code> and insert it in PQ.</p>
<pre><code>import bisect
# PQ of items
PQ = [
(10, 'aaa'),
(30, 'cccc'),
(40, 'dddd'),
]
def pq_insert(pq, item):... | -1 | 2016-09-10T10:14:50Z | [
"python",
"algorithm",
"python-3.x",
"sorting",
"heap"
] |
TypeError: list indicies must be integers, not str | 39,424,037 | <pre><code>foo = ("PandaBears")
l = list(foo)
random.shuffle(l)
Output = ''.join(l)
print(Output)
</code></pre>
<p>I have been at this code for ages trying to figure out the problem but I have had no luck. A few hours before it was working perfectly with absolutely no trouble - <code>I haven't even changed / upgraded ... | -4 | 2016-09-10T08:11:13Z | 39,424,130 | <p>The parenthesis are useless here:</p>
<pre><code>foo = ("PandaBears")
</code></pre>
<p>Just write:</p>
<pre><code>foo = "PandaBears" # str
</code></pre>
<p>If you want a singleton <code>tuple</code>, add a trailing comma:</p>
<pre><code>foo = ("PandaBears",) # tuple
</code></pre>
<p>If <code>foo</code> is a ... | 1 | 2016-09-10T08:24:28Z | [
"python",
"list",
"python-3.x"
] |
How to set coordinates when cropping an image with PIL? | 39,424,052 | <p>I don't know how to set the coordinates to crop an image in <code>PIL</code>s <code>crop()</code>:</p>
<pre><code>from PIL import Image
img = Image.open("Supernatural.xlsxscreenshot.png")
img2 = img.crop((0, 0, 201, 335))
img2.save("img2.jpg")
</code></pre>
<p>I tried with <code>gThumb</code> to get coordinates, b... | 1 | 2016-09-10T08:13:11Z | 39,424,357 | <h3>How to set the coordinates to crop</h3>
<p>In the line:</p>
<pre><code>img2 = img.crop((0, 0, 201, 335))
</code></pre>
<p>the first two numbers define the <em>top-left</em> coordinates of the outtake (x,y), while the last two define the <em>right-bottom</em> coordinates of the outtake.</p>
<h3>Cropping your ima... | 1 | 2016-09-10T08:53:38Z | [
"python",
"image",
"python-2.7",
"python-3.x",
"image-processing"
] |
How to get an outgoing message ID in telepot module? | 39,424,071 | <p>I'm using telepot module to create a telegram bot using python.
I need to get the message Id of an outgoing message to be able to check if the user will reply to that message or not. The piece of code below clarifies what I want to do:</p>
<pre><code>import telepot
bot = telepot.Bot('Some Token')
def handle(msg):... | 0 | 2016-09-10T08:16:39Z | 39,432,838 | <p>You should be able to get <code>message_id</code> of the sent message:</p>
<pre><code>>>> import telepot
>>> from pprint import pprint
>>> bot = telepot.Bot('TOKEN')
>>> sent = bot.sendMessage(9999999, 'Hello')
>>> pprint(sent)
{u'chat': {u'first_name': u'Nick', u'id': 9... | 1 | 2016-09-11T04:24:20Z | [
"python",
"telegram",
"telegram-bot",
"python-telegram-bot"
] |
read yelp api response | 39,424,127 | <p>Iam new to python & API searches. I am having issues reading yelp API responses in python. any help would be great. thanks.</p>
<pre><code>> params = {
> 'term': 'lunch,pancakes' }
> response=client.search('Los Angeles',**params)
</code></pre>
<p>Here is the output:</p>
<pre><code><yelp.obj... | 0 | 2016-09-10T08:23:55Z | 39,425,466 | <p><code>SearchResponse</code> contains the <code>businesses</code> list that will match your term [1].</p>
<p>Try this:</p>
<pre><code>for business in response['businesses']:
print(business['name'])
</code></pre>
<p>[1] <a href="https://www.yelp.com/developers/documentation/v2/search_api" rel="nofollow">https:... | 0 | 2016-09-10T11:14:05Z | [
"python",
"api",
"yelp"
] |
Splitting strings inside a pandas dataframe | 39,424,131 | <p>I have a dataframe with one row that has a list like structure</p>
<pre><code>import pandas as pd
df=pd.DataFrame({'Name':['Stooge, Nick','Dick, Tracy','Rick, Nike','Maw','El','Paw, Maw, Haw','Caw', 'Greep'],
'key':[2,2,2,1,1,3,1,1,],
'Lastname':['Smith, Foo','Johnson, Macy','Johnson, Sike','Simpson','Diablo','Sim... | 2 | 2016-09-10T08:24:38Z | 39,424,376 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow">apply()</a>:</p>
<pre><code>In [63]: df
Out[63]:
Lastname Name key Full
0 Smith, Foo Stooge, Nick 2 Stooge, Nick, Smit... | 0 | 2016-09-10T08:56:19Z | [
"python",
"pandas"
] |
Splitting strings inside a pandas dataframe | 39,424,131 | <p>I have a dataframe with one row that has a list like structure</p>
<pre><code>import pandas as pd
df=pd.DataFrame({'Name':['Stooge, Nick','Dick, Tracy','Rick, Nike','Maw','El','Paw, Maw, Haw','Caw', 'Greep'],
'key':[2,2,2,1,1,3,1,1,],
'Lastname':['Smith, Foo','Johnson, Macy','Johnson, Sike','Simpson','Diablo','Sim... | 2 | 2016-09-10T08:24:38Z | 39,433,920 | <pre><code>ln = df.Lastname.str.split(r',\s*', expand=True).stack()
fn = df.Name.str.split(r',\s*', expand=True).stack()
df['full'] = fn.add(' ').add(ln).groupby(level=0).apply(tuple).str.join(' and ')
df
</code></pre>
<p><a href="http://i.stack.imgur.com/wLaOT.png" rel="nofollow"><img src="http://i.stack.imgur.com/wL... | 3 | 2016-09-11T07:43:27Z | [
"python",
"pandas"
] |
Python: Elegant way to increment a global variable | 39,424,184 | <blockquote>
<p>Elegant way to increment a global variable in Python:</p>
</blockquote>
<p>This is what I have so far:</p>
<pre><code>my_i = -1
def get_next_i():
global my_i
my_i += 1
return my_i
</code></pre>
<p>with generator:</p>
<pre><code>my_iter = iter(range(100000000))
def get_next_i():
re... | 2 | 2016-09-10T08:31:46Z | 39,424,305 | <p>You can create a generator that has an infinite loop. Each call of <code>next(generator)</code> will return a next value, without limit. See <a href="http://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python?rq=1">What does the "yield" keyword do in Python?</a> </p>
<pre><code>def... | 2 | 2016-09-10T08:45:51Z | [
"python",
"python-3.x",
"for-loop",
"iterator",
"generator"
] |
Python: Elegant way to increment a global variable | 39,424,184 | <blockquote>
<p>Elegant way to increment a global variable in Python:</p>
</blockquote>
<p>This is what I have so far:</p>
<pre><code>my_i = -1
def get_next_i():
global my_i
my_i += 1
return my_i
</code></pre>
<p>with generator:</p>
<pre><code>my_iter = iter(range(100000000))
def get_next_i():
re... | 2 | 2016-09-10T08:31:46Z | 39,424,883 | <p>As others suggested, <code>itertools.count()</code> is the best option, e.g.</p>
<pre><code>import itertools
global_counter1 = itertools.count()
global_counter2 = itertools.count()
# etc.
</code></pre>
<p>And then, when you need it, simply call <code>next</code>:</p>
<pre><code>def some_func():
next_id = glo... | 1 | 2016-09-10T09:55:34Z | [
"python",
"python-3.x",
"for-loop",
"iterator",
"generator"
] |
python problam subprocess fore rub script bash | 39,424,275 | <p>i have problem in subprocess
i have this script bash which good work and is name kamel.sh</p>
<pre><code>to=$1
subject=$1
/root/Desktop/telegram/tg/bin/./telegram-cli -k /root/Desktop/telegram/tg/tg-server.pub -WR -e "msg $to $subject"
</code></pre>
<p>but i want use python fore work.is 1.sh give 2 argv fore work ... | -1 | 2016-09-10T08:41:12Z | 39,424,304 | <pre><code>import subprocess
subprocess.call("1.sh user hello", shell=True)
</code></pre>
<p>or</p>
<pre><code>import subprocess
subprocess.call(["1.sh", "user", "hello"])
</code></pre>
| 0 | 2016-09-10T08:45:36Z | [
"python"
] |
How would I make this code run completely without error so that age is assigned correctly according to the date they enter? | 39,424,329 | <pre><code>from random import randint
def main():
dob = int(input("Please enter the year you were born"))
if dob > (2005):
main()
elif dob < (2004):
main()
else:
def mob():
if dob == (2004):
month = input("Please enter the first three letters of ... | -3 | 2016-09-10T08:49:53Z | 39,424,680 | <p>Something like this does what you need, I think, though you could tidy it further to give the actual age, by using datetime.</p>
<pre><code>def main():
yob = int(input("Please enter the year you were born"))
if yob > 2005:
return "Under 11"
elif yob < 2004:
return "Over 12"
... | 2 | 2016-09-10T09:32:48Z | [
"python",
"python-3.x"
] |
nested directory appear while creating zip file | 39,424,402 | <p>I am quite new to python.Here i am trying to create zip file of "diveintomark-diveintopython3-793871b' directory.I changed the current working directory using os.chdir() function.The zip file is created but the problem is when i extract the zip file i get the the following directory</p>
<pre><code>Users/laiba/Deskt... | 0 | 2016-09-10T08:59:57Z | 39,424,500 | <p>you could use argument <code>arcname</code>: name of the item in the archive as opposed to the full path name. But here you don't need it because you already are in the correct directory. Just drop the <code>abspath</code> and you're done (and also the duplicate folder entry)</p>
<pre><code>import zipfile, os
os.c... | 1 | 2016-09-10T09:09:44Z | [
"python",
"zipfile"
] |
multi column search in django using ajax | 39,424,489 | <p>I am working on a listing in django project. The scenario is that When i click on FAQ listing page then it redirects me to the listings where i get all faq. Now i have to search using different keywords. There is total five keywords through which i can search for particular results. Code is</p>
<pre><code>questions... | 0 | 2016-09-10T09:08:32Z | 39,424,568 | <p>You can use <code>request.GET.get('filter_name')</code></p>
<p>e.g if you have a filter by title:</p>
<pre><code>query = Model.objects.all()
title = request.GET.get('title')
if title:
query = query.filter(title__icontains=title)
...and so on
</code></pre>
<p>note that your url should contain get paramete... | 0 | 2016-09-10T09:17:35Z | [
"python",
"django"
] |
multi column search in django using ajax | 39,424,489 | <p>I am working on a listing in django project. The scenario is that When i click on FAQ listing page then it redirects me to the listings where i get all faq. Now i have to search using different keywords. There is total five keywords through which i can search for particular results. Code is</p>
<pre><code>questions... | 0 | 2016-09-10T09:08:32Z | 39,424,694 | <pre><code>questions = Help.objects.all()
filters = {}
if 'question' in ajax_data:
filters['question'] = ajax_data.get('question')
if 'description' in ajax_data:
filters['description'] = ajax_data.get('description')
if 'status' in ajax_data:
filters['status'] = ajax_data.get('status')
if 'created' in ajax_d... | 3 | 2016-09-10T09:34:20Z | [
"python",
"django"
] |
See what Python module instantised a class? | 39,424,591 | <p>Is it possible in a Python class to see the name (or other identifier) of the class or module that instantises it?</p>
<p>For example:</p>
<pre><code># mymodule.py
class MyClass():
def __init__(self):
print(instantised_by)
#main.py
from mymodule import MyClass
instance = MyClass()
</code></pre>
<p... | 1 | 2016-09-10T09:20:25Z | 39,424,655 | <p>You can inspect the stack informations with <code>inspect</code> to get the caller stack from <code>__init__</code> (remember, it's just a function). From that you can get informations such as the caller function name, module name etc.</p>
<p>See this question: <a href="http://stackoverflow.com/questions/1095543/ge... | 0 | 2016-09-10T09:29:40Z | [
"python"
] |
See what Python module instantised a class? | 39,424,591 | <p>Is it possible in a Python class to see the name (or other identifier) of the class or module that instantises it?</p>
<p>For example:</p>
<pre><code># mymodule.py
class MyClass():
def __init__(self):
print(instantised_by)
#main.py
from mymodule import MyClass
instance = MyClass()
</code></pre>
<p... | 1 | 2016-09-10T09:20:25Z | 39,424,669 | <p>With <code>traceback</code> module:</p>
<pre><code>import traceback
class MyClass():
def __init__(self):
file,line,w1,w2 = traceback.extract_stack()[1]
print(w1)
</code></pre>
| 0 | 2016-09-10T09:31:04Z | [
"python"
] |
Replace input strings and integers | 39,424,693 | <p>I need to write a function that takes a string (str), and two other strings (call it replace1 and replace2), and an integer (n). The function shall return a new string, where all the string inputs from replace1 in the first string (str) and replace the new string with replace1 depending on where you want the new inp... | 0 | 2016-09-10T09:34:12Z | 39,424,786 | <p>I assume from your question that you want to replace the nth occurrence of r1 with r2.
Is this what you want?</p>
<pre><code>>>> def replaceChoice(str1, r1, r2, n):
... new_str = ""
... replaced = False
... for i in str1:
... if i==r1:
... n-=1
... if... | 1 | 2016-09-10T09:44:59Z | [
"python"
] |
How to click a button to vote with python | 39,424,703 | <p>I'm practicing with web scraping in python. I'd like to press a button on a site that votes an item.
Here is the code</p>
<pre><code><html>
<head></head>
<body role="document">
<div id="static page" class="container-fluid">
<div id="page" class="row"></div>
<div id="fauc... | 0 | 2016-09-10T09:35:22Z | 39,424,766 | <p>You might want to check out <a href="http://selenium-python.readthedocs.io/" rel="nofollow">Selenium</a>. It is a module for python that allows you to automate tasks like the one you have mentioned above. Try something like this:</p>
<pre><code>from selenium import webdriver
driver = webdriver.Firefox()
driver.get... | -1 | 2016-09-10T09:42:54Z | [
"python",
"python-3.x",
"web-scraping"
] |
which code remove the duplicate combination in permutation | 39,424,739 | <p>I didn't find the obvious difference between two functions below . So the question is , how the second funtion compare and remove duplicate characters .</p>
<p>permutation for non-duplicate characters</p>
<pre><code>def perms(s):
if(len(s)==1): return [s]
result=[]
for i,v in enumerate(s):
... | 0 | 2016-09-10T09:39:41Z | 39,424,818 | <p>The difference is very simple. The second function stores results in a set:</p>
<pre><code>result = set([string])
</code></pre>
<p>A set never contains duplicates. If you add a duplicate value to a set, noting happens:</p>
<pre><code>>>> set([1, 2, 3, 2, 3, 2, 1])
set([1, 2, 3])
</code></pre>
<p>In the ... | 2 | 2016-09-10T09:48:41Z | [
"python",
"algorithm",
"recursion"
] |
Python/Numpy array dimension confusion | 39,424,776 | <p>Suppose <code>batch_size = 64</code>.
I created a batch : <code>batch = np.zeros((self._batch_size,), dtype=np.int64)</code>. Suppose I have batch of chars such that <code>batch = ['o', 'w', ....'s']</code> of 64 size and <code>'o'</code> will be represented as <code>[0,0, .... 0]</code> 1-hot vector of size 27.
So,... | 0 | 2016-09-10T09:44:02Z | 39,426,000 | <p>In the 1st block the initialization of <code>batch</code> to <code>zeros</code> does nothing for you, because <code>batch</code> is replaced with the <code>asarray(temp1)</code> later. (Note my correction). <code>temp1</code> is a list of 1d arrays (<code>temp</code>), and produces a 2d arrray.</p>
<p>In the 2nd i... | 1 | 2016-09-10T12:18:23Z | [
"python",
"numpy"
] |
invalid request block size 21573 | 39,424,823 | <p>I was reading the tutorial provided in
<a href="http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html" rel="nofollow">http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html</a>
This very tutorial is a great tutorial. I have been able to configure django server on my raspber... | 0 | 2016-09-10T09:49:16Z | 39,454,292 | <p>With <code>--socket</code> option you have to use <a href="http://nginx.org/en/docs/http/ngx_http_uwsgi_module.html" rel="nofollow">uwsgi module</a> in nginx instead of proxy.</p>
| 0 | 2016-09-12T15:53:03Z | [
"python",
"django",
"nginx",
"uwsgi"
] |
Accessing dynamically created buttons in PyQT5 | 39,424,826 | <p>Sirs.</p>
<p>I have pretty much simple PyQT5 app.
I have dynamically created buttons and connected to some function.</p>
<pre><code> class App(QWidget):
...
def createButtons(self):
...
for param in params:
print("placing button "+param)
bu... | 2 | 2016-09-10T09:49:33Z | 39,424,884 | <p>You can use a map and save the instances of your buttons.
You can use the button text as key or the id if you want.
If you use the button text as key you cannot have two buttons with the same label.</p>
<pre><code>class App(QWidget):
def __init__(self):
super(App,self).__init__()
button_map =... | 0 | 2016-09-10T09:55:37Z | [
"python",
"pyqt5",
"qpushbutton"
] |
Chat-robot that will take input and response in Python | 39,424,853 | <p>I'm currently trying to create a small version of a chat robot that will respond to different keyword inputs in a terminal. For example, if I write <code>inv</code> it will print out its current inventory and it can look like this:</p>
<pre><code>Item: sword
Place in inventory: 1
Item: axe
Place in inventory: 2
Ite... | 1 | 2016-09-10T09:52:31Z | 39,425,187 | <p>I formatted and tested the code and it works. </p>
<pre><code>def splitIntoWords( argOne):
result = "hej"
"""
Function that splits list into words
"""
# list to keep and split up the user input
inputList = []
inputList = argOne.split()
print(str(inputList) + "splitIntoWords")
# ... | 0 | 2016-09-10T10:36:11Z | [
"python",
"list",
"python-3.x"
] |
Extracting JS variable information inside script tag | 39,424,854 | <p>I'm retrieving an HTML page from a URL and want to extract information from a <code>script</code> tag within that HTML. I am specifically looking for this particular <code>script</code> tag:</p>
<pre><code><script type="text/javascript">
var zomato = zomato || {};
zomato.menuPages = [{"url":"https:\/\... | 2 | 2016-09-10T09:52:39Z | 39,425,950 | <p>Well, a way to do that is to make use of <strong>regular expressions</strong> which of course is not the most easy thing to do but comes in handy sometimes. So what I tried is the following:</p>
<pre><code>#!/usr/bin/env python
from BeautifulSoup import BeautifulSoup
import requests
import re
# I didn't post t... | 1 | 2016-09-10T12:11:24Z | [
"javascript",
"python",
"beautifulsoup",
"html-parsing"
] |
Extracting JS variable information inside script tag | 39,424,854 | <p>I'm retrieving an HTML page from a URL and want to extract information from a <code>script</code> tag within that HTML. I am specifically looking for this particular <code>script</code> tag:</p>
<pre><code><script type="text/javascript">
var zomato = zomato || {};
zomato.menuPages = [{"url":"https:\/\... | 2 | 2016-09-10T09:52:39Z | 39,426,481 | <p>I have found <a href="https://github.com/scrapinghub/js2xml" rel="nofollow">jsxml</a> pretty effective, it parses <em>javascript</em> properties/functions into xml trees:</p>
<pre><code>import js2xml
import re
soup = BeautifulSoup(the_html,"html.parser")
tree = js2xml.parse(soup.find("script", text=re.compile("zo... | 2 | 2016-09-10T13:20:44Z | [
"javascript",
"python",
"beautifulsoup",
"html-parsing"
] |
Sending string to serial.to_bytes not working | 39,424,865 | <p>I am trying to send a string variable contains the command.</p>
<p>Like this:</p>
<pre><code>value="[0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]"
self.s.write(serial.to_bytes(value))
</code></pre>
<p>The above one fails. Won't give any error.</p>
<p>But it's working when I send a value like this:</p>
<pre><code>self.s.... | 1 | 2016-09-10T09:54:04Z | 39,425,136 | <p><a href="https://pyserial.readthedocs.io/en/latest/pyserial_api.html#serial.to_bytes" rel="nofollow">serial.to_bytes</a> takes a sequence as input. You should remove double quotes around <code>value</code> to pass a sequence of integers instead of a <code>str</code> representing the sequence you want to pass:</p>
<... | 4 | 2016-09-10T10:29:21Z | [
"python",
"pyserial"
] |
Sending string to serial.to_bytes not working | 39,424,865 | <p>I am trying to send a string variable contains the command.</p>
<p>Like this:</p>
<pre><code>value="[0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]"
self.s.write(serial.to_bytes(value))
</code></pre>
<p>The above one fails. Won't give any error.</p>
<p>But it's working when I send a value like this:</p>
<pre><code>self.s.... | 1 | 2016-09-10T09:54:04Z | 39,519,016 | <p>If passing a list of integers works for you then just convert your hexadecimal representations into integers and put them in a list.</p>
<p>Detailed steps:</p>
<ol>
<li><p>Open a python interpreter</p></li>
<li><p>Import <code>serial</code>and open a serial port, call it <code>ser</code>.</p></li>
<li><p>Copy the ... | 2 | 2016-09-15T19:35:01Z | [
"python",
"pyserial"
] |
Manually set models.DateTimeField | 39,424,903 | <p>I've created a Transaction table which I want to test, one of the most important field of this table is:</p>
<pre><code>models.DateTimeField(
default=timezone.now)
</code></pre>
<p>In order to test my app with the database, I need historical data. Currently when I create a transaction, it sets the date... | 0 | 2016-09-10T09:58:12Z | 39,424,924 | <blockquote>
<p>Currently when I create a transaction, it sets the date and time automatically</p>
</blockquote>
<p>You can always override that default value before you save the model instance, for the example below let's assume your <code>DateTimeField</code> with the default value is called <code>timestamp</code>... | 1 | 2016-09-10T10:00:41Z | [
"python",
"django"
] |
WSGI module and Django settings locations | 39,425,092 | <p>I'm using Django with uWSGI and trying to organise my web server config files as follow:</p>
<pre><code>/proj/
web_config/
docker-compose.py
...
prod/
nginx.conf
wsgi.py
uwsgi_params
uwsgi.ini
...
app/
__init__.py
... | 0 | 2016-09-10T10:24:39Z | 39,430,165 | <p>In this case, to reference to django settings, all you need to do is chdir from your <code>uwsgi.ini</code> to <code>/proj/</code> directory. Now load your <code>wsgi.py</code> file (you can keep it in your <code>app/</code> subdirectory, it doesn't contain any settings) from it using <code>module</code> uWSGI setti... | 1 | 2016-09-10T20:10:03Z | [
"python",
"django",
"wsgi",
"uwsgi"
] |
Break a shapely Linestring at multiple points | 39,425,093 | <p>This code below was modified from the one I found <a href="http://stackoverflow.com/questions/21407233/get-the-vertices-on-a-linestring-either-side-of-a-point/21419035#21419035">here</a> which splits a shapely Linestring into two segments at a point defined along the line. I have also checked other questions but the... | 0 | 2016-09-10T10:24:44Z | 39,574,007 | <p>The <code>projection</code> and <code>interpolate</code> lineString methods are usually handy for this kind of operations.</p>
<pre><code>from shapely.geometry import Point, LineString
def cut(line, distance):
# Cuts a line in two at a distance from its starting point
# This is taken from shapely manual
... | 1 | 2016-09-19T13:07:28Z | [
"python",
"shapely"
] |
Pandas naming multiple sheets according to list of lists | 39,425,111 | <p>First time I post here and I am rather a newbie. </p>
<p>Anyhow, I have been playing around with Pandas and Numpy to make some calculations from Excel.</p>
<p>Now I want to create an .xlsx file to which I can output my results and I want each sheet to be named after the name of the dataframe that is being outputte... | 0 | 2016-09-10T10:26:52Z | 39,428,340 | <p>You need to pass string literals of data frame names in your function and not actual data frame objects:</p>
<pre><code>C = ['A', 'b', 'L', 'dr', 'dx']
def save_excelB(filename, item):
w=ew(filename)
for name in item:
i=globals()[name]
i.to_excel(w, sheet_name=name, index=False, header=Fals... | 0 | 2016-09-10T16:45:17Z | [
"python",
"excel",
"pandas"
] |
Django heroku uploading files | 39,425,217 | <blockquote>
<p>[Errno 30] Read-only file system: '/static_in_env'</p>
</blockquote>
<p>I am new to heroku, when I push my django application on heroku, I can't upload files, yet it is working properly in local computer! </p>
<p>Here is the error:</p>
<pre><code>OSError at /admin/products/product/add/
[Errno 30] R... | -1 | 2016-09-10T10:40:31Z | 39,425,651 | <p>Unfortunately, Heroku does not host your application Media files. So what you need is to pick up a third party service like AWS S3 to store data in the cloud. </p>
<p>Below is the official guide of how you can deal with Django applications media files on Heroku.</p>
<p><a href="https://devcenter.heroku.com/article... | 0 | 2016-09-10T11:38:53Z | [
"python",
"html",
"css",
"django",
"heroku"
] |
Stop Scrapy spider when it meets a specified URL | 39,425,456 | <p>This question is very similar to <a href="http://stackoverflow.com/questions/4448724/force-my-scrapy-spider-to-stop-crawling">Force my scrapy spider to stop crawling</a> and some others asked several years ago. However, the suggested solutions there are either dated for Scrapy 1.1.1 or not precisely relevant. <stron... | 1 | 2016-09-10T11:13:11Z | 39,436,631 | <p>When you raise <code>close_spider() exception</code>, ideal assumption is that scrapy should stop immediately, abandoning all other activity (any future page requests, any processing in pipeline ..etc)</p>
<p>but this is not the case, When you raise <code>close_spider() exception</code>, scrapy will try to close it... | 0 | 2016-09-11T13:32:43Z | [
"python",
"scrapy"
] |
Stop Scrapy spider when it meets a specified URL | 39,425,456 | <p>This question is very similar to <a href="http://stackoverflow.com/questions/4448724/force-my-scrapy-spider-to-stop-crawling">Force my scrapy spider to stop crawling</a> and some others asked several years ago. However, the suggested solutions there are either dated for Scrapy 1.1.1 or not precisely relevant. <stron... | 1 | 2016-09-10T11:13:11Z | 39,554,040 | <p>I'd recommend to change your approach. Scrapy crawls many requests concurrently without a linear order, that's why closing the spider when you find what you're looking for won't do, since a request after that could already be processed.</p>
<p>To tackle this you could make Scrapy crawl sequentially, meaning a reque... | 1 | 2016-09-18T04:17:34Z | [
"python",
"scrapy"
] |
How to identify and switch to the frame source in Selenium? | 39,425,541 | <p>I have been using the Selenium and Python2.7, on Firefox.</p>
<p>I would like it to work like the following, but I do not know how to write code.</p>
<pre><code>Driver.get('https://video-download.online')
Url='https://www.youtube.com/watch?v=waQlR8W8aTA'
Driver.find_element_by_id("link").send_keys(Url)
Driver.find... | 0 | 2016-09-10T11:23:23Z | 39,426,014 | <p>You are able to get frame locator value in HTML code which is specified in iframes tag. u can move up from where your locator value is existed in HTML code.</p>
<p>This function is suitable:</p>
<pre><code>def frame_switch(css_selector):
driver.switch_to.frame(driver.find_element_by_css_selector(css_selector))
<... | 0 | 2016-09-10T12:19:36Z | [
"python",
"selenium",
"firefox"
] |
Receive data from client without using "dataReceived" function in Twisted | 39,425,606 | <p>How to receive the data from the client, bypassing the standard class function Protocol? For example,</p>
<pre><code>class TW(protocol.Protocol):
def get_data(delim = '\n'):
#some code
return data
</code></pre>
<p>I.e, without using the function "dataReceived", and not freezing all other the se... | 0 | 2016-09-10T11:33:42Z | 39,475,696 | <p>You can't bypass <code>dataReceived</code> unless you like doing things the hard way :D. You can do what ever you're doing in <code>get_data()</code> in <code>dataReceived()</code>. Alternatively, you could add a <code>data</code> param in your <code>get_data()</code> and do a callback form <code>dataReceived</code>... | 0 | 2016-09-13T17:21:08Z | [
"python",
"server",
"twisted",
"twisted.internet"
] |
Columns to row in python | 39,425,618 | <p>Do we have sas equivalent of proc transpose. i have the following variables</p>
<pre><code> a b c d e f g
1 3 4 5 3 2 2
2 3 3 3 2 4 2
</code></pre>
<p>i want to transpose, across columns a and b , dummy out put below:</p>
<pre><code> a b tranposed_columns transposed_value
1 3 c 4
1 3 d ... | 0 | 2016-09-10T11:34:38Z | 39,425,783 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow"><code>pd.melt</code></a> to coalesce columns into a single column. Use the <code>id_vars</code> parameter to "protect" certain columns from participating in the melt:</p>
<pre><code>In [11]: pd.melt(df, id_vars=['a',... | 2 | 2016-09-10T11:52:56Z | [
"python",
"pandas",
"python-3.4",
"transpose"
] |
Writing Non-Data Descriptor in Python | 39,425,643 | <p>I am learning about descriptors in python. I want to write a non-data descriptor but the class having the descriptor as its classmethod doesn't call the <code>__get__</code> spacial method when i call the classmethod. This is my example (without the <code>__set__</code>):</p>
<pre><code>class D(object):
"The D... | 2 | 2016-09-10T11:38:25Z | 39,425,675 | <p>You successfully created a proper non-data descriptor, but you then <em>mask</em> the <code>d</code> attribute by setting an instance attribute.</p>
<p>Because it is a <em>non</em>-data descriptor, the instance attribute wins in this case. When you add a <code>__set__</code> method, you turn your descriptor into a ... | 4 | 2016-09-10T11:41:44Z | [
"python",
"python-2.7",
"descriptor"
] |
How to modify variables in another python file? | 39,425,762 | <p><strong>windows 10 - python 3.5.2</strong></p>
<p>Hi, I have the two following python files, and I want to edit the second file's variables using the code in the first python file.</p>
<p><strong>firstfile.py</strong></p>
<pre><code>from X.secondfile import *
def edit():
#editing second file's variables by u... | 1 | 2016-09-10T11:51:03Z | 39,425,879 | <p>You can embed the <code>Language</code> in a class in the second file that has a method to change it.</p>
<h3>Module 2</h3>
<pre><code>class Language:
def __init__(self):
self.language = 'en-US'
def __str__(self):
return self.language
def change(self, lang):
assert isinstance(... | 1 | 2016-09-10T12:02:33Z | [
"python",
"variables",
"module"
] |
How to modify variables in another python file? | 39,425,762 | <p><strong>windows 10 - python 3.5.2</strong></p>
<p>Hi, I have the two following python files, and I want to edit the second file's variables using the code in the first python file.</p>
<p><strong>firstfile.py</strong></p>
<pre><code>from X.secondfile import *
def edit():
#editing second file's variables by u... | 1 | 2016-09-10T11:51:03Z | 39,425,960 | <p>This can be done to edit a variable in another file:</p>
<pre><code>import X.secondfile
X.secondfile.Language = 'en-UK'
</code></pre>
<p>However, I have two suggestions:</p>
<ol>
<li><p>Don't use <code>import *</code> - it pollutes the namespace with unexpected
names</p></li>
<li><p>Don't use such global variable... | 1 | 2016-09-10T12:12:32Z | [
"python",
"variables",
"module"
] |
Reverse accessor clashes in Django | 39,425,863 | <p>Error :
1) user.Login.password: (fields.E304) Reverse accessor for 'Login.password' clashes with reverse accessor for 'Login.username'.
2) user.Login.username: (fields.E304) Reverse accessor for 'Login.username' clashes with reverse accessor for 'Login.password'.</p>
<p>models.py</p>
<pre><code>from django.db impo... | 0 | 2016-09-10T12:00:45Z | 39,426,136 | <p>You can solve the issue by using <code>related_name</code> attribute:</p>
<pre><code>class Login(models.Model):
username = models.ForeignKey(User, on_delete=models.CASCADE, related_name="username_users")
password = models.ForeignKey(User, on_delete=models.CASCADE, related_name="password_users")
</code></p... | 1 | 2016-09-10T12:35:19Z | [
"python",
"django"
] |
Project Euler 23 - No matter what I do, my answer is far too big | 39,425,877 | <p>Problem 23 asks for the sum of all numbers "not the sum of two abundant numers". We need only check numbers smaller than 28123. An integer n is abundant if its proper divisors sum to an integer greater than n - 12 is the first abundant number since 1+2+3+4+6 = 16 > 12. This makes 24 the smallest number which is a su... | 0 | 2016-09-10T12:02:14Z | 39,425,946 | <p>The problem is that you are modifying the list <code>numbers</code> while you are iterating over it. This results in you removing less numbers than what you expect.</p>
<p>You should iterate over a copy of it:</p>
<pre><code>for i in list(numbers):
for j in range(1,i):
if is_abun(j) and is_abun(i-j):
... | 3 | 2016-09-10T12:10:48Z | [
"python"
] |
How to fork a python script in different terminal | 39,425,940 | <p>I want to fork a new process in a script, but how to interactive with the subprocess in a new terminal?
For example:</p>
<pre><code>#python
a='a'
b='b'
if os.fork():
print a
a = input('a?')
print 'a:',a
else:
print b
b = input('b?')
print 'b:',b
</code></pre>
<p>The script should print a/b ... | 0 | 2016-09-10T12:10:00Z | 39,426,304 | <p>Its probably bad practice to open a new terminal like that from a command line application, but <code>gnome-terminal</code> has an <code>-e</code> flag. E.g. <code>gnome-terminal -e python</code> will open a python interpreter.</p>
| 0 | 2016-09-10T12:58:14Z | [
"python",
"linux",
"bash",
"shell",
"subprocess"
] |
How to fork a python script in different terminal | 39,425,940 | <p>I want to fork a new process in a script, but how to interactive with the subprocess in a new terminal?
For example:</p>
<pre><code>#python
a='a'
b='b'
if os.fork():
print a
a = input('a?')
print 'a:',a
else:
print b
b = input('b?')
print 'b:',b
</code></pre>
<p>The script should print a/b ... | 0 | 2016-09-10T12:10:00Z | 39,427,040 | <h2>I finally implement it in a(maybe ugly) way.</h2>
<p>Inspired by <a href="http://unix.stackexchange.com/questions/256480/how-do-i-run-a-command-in-a-new-terminal-window-in-the-same-process-as-the-origi">http://unix.stackexchange.com/questions/256480/how-do-i-run-a-command-in-a-new-terminal-window-in-the-same-proce... | 0 | 2016-09-10T14:30:26Z | [
"python",
"linux",
"bash",
"shell",
"subprocess"
] |
Count up and down from a given letter | 39,425,966 | <p>I need to write a function "alphabet" that takes a string (n), and counts up and then down in the alphabet. I tried to solve it, but I could only write the code where it counts down and then up in integers. Somehow, these integers are supposed to represent a letter. I know that I should use char() and ord(), but I d... | -1 | 2016-09-10T12:13:38Z | 39,426,009 | <p>I think ord() gives back the ascii code in consecutive order, for instance ord('a') gives 97 and ord('b') 98 and so on, i would work on converting one from another and adding +1 in each loop</p>
| 1 | 2016-09-10T12:19:16Z | [
"python"
] |
python list columns split | 39,426,003 | <p>Could anyone help me please? It is complicated question but i will try explain it. I need interpolate two values Depths(Z) to Speed(v) for all data </p>
<pre><code>x= [55,55,55,,44,44,44,,33,33,33,] (coordinates)
z =[10,5,0,10,7,0,10,9,0] (depths)
v= [20,21,22=,23,24,25,26,27,28] (speed)
</code></pre>
<p>And resu... | 1 | 2016-09-10T12:18:38Z | 39,426,830 | <p>One possibility is to create a dictionary that maps each X coord to the list of tuples with that X coord:</p>
<pre><code>>>> tupus = [ (1,0,1), (1,13,4), (2,11,2), (2,14,5) ]
>>> from collections import defaultdict
>>> tupudict = defaultdict( lambda: [] ) # default val for a key is empty ... | 1 | 2016-09-10T14:04:22Z | [
"python",
"list",
"listview",
"interpolation"
] |
Tornado multiple processes: create multiple MySQL connections | 39,426,030 | <p>I'm running a Tornado HTTPS server across multiple processes using the first method described here <a href="http://www.tornadoweb.org/en/stable/guide/running.html" rel="nofollow">http://www.tornadoweb.org/en/stable/guide/running.html</a> (server.start(n))</p>
<p>The server is connected to a local MySQL instance and... | 0 | 2016-09-10T12:21:59Z | 39,432,345 | <p>Each child process gets a copy of the variables that existed in the parent process when <code>start(n)</code> was called. For things like connections, this will usually cause problems. When using multi-process mode, it's important to do as little as possible before starting the child processes, so don't create the m... | 1 | 2016-09-11T02:37:39Z | [
"python",
"mysql",
"multiprocessing",
"tornado",
"multiprocess"
] |
Python read particular cell value in excel | 39,426,107 | <p>I have an exel file named "123.csv" that is the output i get when running a PROM functionality, consisting of two columns "case" and "event". I want to modify this output by grouping events based on case. More specifically i want to write a python script that will group events that belong to the same case to be merg... | 2 | 2016-09-10T12:31:15Z | 39,426,204 | <p>It's easy to do with simple csv & defaultdict (python 3)</p>
<p>Your input is like</p>
<pre><code>case,event
101,A
101,X
101,Y
102,B
102,C
103,Z
</code></pre>
<p>code:</p>
<pre><code>import collections
with open("csv.csv") as f:
cr = csv.reader(f,delimiter=",")
d=collections.defaultdict(lambda : li... | 0 | 2016-09-10T12:44:17Z | [
"python",
"csv"
] |
Python read particular cell value in excel | 39,426,107 | <p>I have an exel file named "123.csv" that is the output i get when running a PROM functionality, consisting of two columns "case" and "event". I want to modify this output by grouping events based on case. More specifically i want to write a python script that will group events that belong to the same case to be merg... | 2 | 2016-09-10T12:31:15Z | 39,426,245 | <p>You can use groupby from itertools to do this for you. Example of this:</p>
<pre><code>from itertools import groupby
current = [(101, 'A'), (101, 'B'), (101, 'Y'), (102, 'C'), (102, 'D'), (102, 'U')]
desired = []
for key, group in groupby(current, lambda x: x[0]):
lst = [element[1] for element in group]
g... | 0 | 2016-09-10T12:50:44Z | [
"python",
"csv"
] |
Print only vowels in a string | 39,426,149 | <p>I am new in Python and I'm trying to print all the vowels in a string. So if someone enters "Hey there, everything alright?" , all vowels needs to be printed...but I don't know how? (so it's not about counting the vowels, its about printing the vowels)</p>
<p>For now I've got this ;</p>
<pre><code>sentence = input... | 2 | 2016-09-10T12:36:41Z | 39,426,166 | <p>Something like this?</p>
<pre><code>sentence = input('Enter your sentence: ' )
for letter in sentence:
if letter in 'aeiou':
print(letter)
</code></pre>
| 2 | 2016-09-10T12:39:29Z | [
"python",
"string",
"python-3.x",
"printing"
] |
Print only vowels in a string | 39,426,149 | <p>I am new in Python and I'm trying to print all the vowels in a string. So if someone enters "Hey there, everything alright?" , all vowels needs to be printed...but I don't know how? (so it's not about counting the vowels, its about printing the vowels)</p>
<p>For now I've got this ;</p>
<pre><code>sentence = input... | 2 | 2016-09-10T12:36:41Z | 39,426,193 | <p>Supply provide an a list comprehension to <code>print</code> and unpack it:</p>
<pre><code>>>> s = "Hey there, everything allright?" # received from input
>>> print(*[i for i in s if i in 'aeiou'])
e e e e e i a i
</code></pre>
<p>This makes a list of all vowels and supplies it as positional argu... | 0 | 2016-09-10T12:42:41Z | [
"python",
"string",
"python-3.x",
"printing"
] |
Print only vowels in a string | 39,426,149 | <p>I am new in Python and I'm trying to print all the vowels in a string. So if someone enters "Hey there, everything alright?" , all vowels needs to be printed...but I don't know how? (so it's not about counting the vowels, its about printing the vowels)</p>
<p>For now I've got this ;</p>
<pre><code>sentence = input... | 2 | 2016-09-10T12:36:41Z | 39,426,290 | <p>The two answers are good if you want to print <em>all</em> the occurrences of the vowels in the sentence -- so "Hello World" would print 'o' twice, etc.</p>
<p>If you only care about <em>distinct</em> vowels, you can instead loop over the vowels. In a sense, you're flipping the code suggested by the other answers:... | 1 | 2016-09-10T12:56:51Z | [
"python",
"string",
"python-3.x",
"printing"
] |
Print only vowels in a string | 39,426,149 | <p>I am new in Python and I'm trying to print all the vowels in a string. So if someone enters "Hey there, everything alright?" , all vowels needs to be printed...but I don't know how? (so it's not about counting the vowels, its about printing the vowels)</p>
<p>For now I've got this ;</p>
<pre><code>sentence = input... | 2 | 2016-09-10T12:36:41Z | 39,426,389 | <p>You could always use RegEx:</p>
<pre><code>import re
sentence = input("Enter your sentence: ")
vowels = re.findall("[aeiou]",sentence.lower())
if len(vowels) == 0:
for i in vowels:
print(i)
else:
print("Empty")
</code></pre>
| 0 | 2016-09-10T13:10:09Z | [
"python",
"string",
"python-3.x",
"printing"
] |
Python easier way to insert new items into XML sub sub elements using ElementTree | 39,426,162 | <p>I am editing a config file and would like to add new sub elements into the structure. The problem I am having is that in the config file the sub elements have the same name and I have not found a way to find the index the insert location with a .find command. An example of the config file is here:</p>
<pre><code>&l... | 1 | 2016-09-10T12:39:12Z | 39,426,659 | <p>Use XPath expression in the form of <strong><code>.//element_name</code></strong> to find element anywhere within context node (the root element in this case). For example, the following should return first instance of <code><Category></code> element, anywhere within <code>root</code> :</p>
<pre><code>root.fi... | 1 | 2016-09-10T13:41:59Z | [
"python",
"xml-parsing",
"elementtree"
] |
Pandas groupby method | 39,426,428 | <p>l have a 41 year dataset and l would like to do some statistical calculations by using a Pandas module. However, l have a lack of Pandas knowledge.
here is an example csv file dataset:</p>
<pre><code>date day month year pcp1 pcp2 pcp3 pcp4 pcp5 pcp6
1.01.1979 1 1 1979 0.431 2.167 ... | 3 | 2016-09-10T13:14:38Z | 39,426,661 | <p>Do not specify <code>header=None</code> in your <code>read_csv</code> calls. You are telling the function that there is no header row in the data, when according to the sample data you posted above, the first row of the file is a header. So it treats that first header row as data, thus mixing values like <code>pcp1<... | 2 | 2016-09-10T13:42:02Z | [
"python",
"pandas"
] |
Can dask be used to groupby and recode out of core? | 39,426,511 | <p>I have 8GB csv files and 8GB of RAM. Each file has two strings per row in this form:</p>
<pre><code>a,c
c,a
f,g
a,c
c,a
b,f
c,a
</code></pre>
<p>For smaller files I remove duplicates counting how many copies of each row there were in the first two columns and then recode the strings to integers <a href="http://st... | 1 | 2016-09-10T13:24:25Z | 39,428,253 | <p>Assuming that the grouped dataframe fits your memory, the change you would have to make to your code should be pretty minor. Here's my attempt:</p>
<pre><code>import pandas as pd
from dask import dataframe as dd
from sklearn.preprocessing import LabelEncoder
# import the data as dask dataframe, 100mb per partition... | 2 | 2016-09-10T16:36:23Z | [
"python",
"pandas",
"dask"
] |
Python: Json dumps escape quote | 39,426,532 | <p>There is a POST request which works perfectly when I pass the data as below:</p>
<pre><code>url = 'https://www.nnnow.com/api/product/details'
requests.post(url, data="{\"styleId\":\"BMHSUR2HTS\"}", headers=headers)
</code></pre>
<p>But when I use <code>json.dumps()</code> on a dictionary and send the response, I ... | 1 | 2016-09-10T13:26:46Z | 39,428,488 | <p>If you print the <code>json.dumps({"styleId":"BMHSUR2HTS"})</code> it'll happen 2 things:
1. your output is a string (just try <code>type(json.dumps({"styleId":"BMHSUR2HTS"}))</code>);
2. if you pay attention the output will add a space between the json name and value: '{"styleId": "BMHSURT2HTS"}'.</p>
<p>Not sure ... | 0 | 2016-09-10T17:00:18Z | [
"python",
"json"
] |
Iterating over multiIndex dataframe | 39,426,564 | <p>I have a data frame as shown below
<img src="http://i.stack.imgur.com/H6Sh0.png" alt="dataframe"></p>
<p>I have a problem in iterating over the rows. for every row fetched I want to return the key value. For example in the second row for <strong>2016-08-31 00:00:01</strong> entry df1 & df3 has compass value 4.0... | 0 | 2016-09-10T13:30:25Z | 39,427,383 | <p><strong>Update</strong></p>
<p>Okay so now I understand your question better this will work for you.
First change the shape of your dataframe with</p>
<pre><code>dfs = df.stack().swaplevel(axis=0)
</code></pre>
<p>This will make your dataframe look like:</p>
<p><a href="http://i.stack.imgur.com/UaOj7.png" rel="n... | 1 | 2016-09-10T15:07:43Z | [
"python",
"pandas",
"dataframe",
"multi-index"
] |
what kind of table widget module i should use for python 3x | 39,426,619 | <p>I was trying to use <code>tkintertable</code> for Python 3.5.2 but I got an error message at the console saying: </p>
<pre><code>File "C:\Users\issba\AppData\Local\Programs\Python\Python35-32\lib\site-packages\tkintertable\__init__.py", line 24, in <module>
from Tables import *
ImportError: No module name... | 0 | 2016-09-10T13:36:53Z | 39,427,605 | <p><a href="https://github.com/dmnfarrell/tkintertable" rel="nofollow">This</a> is the official development site of <code>tkintertable</code>. At the end of the <a href="https://github.com/dmnfarrell/tkintertable#about" rel="nofollow">about section</a> it says: </p>
<blockquote>
<p><b>This library is currently for P... | 0 | 2016-09-10T15:31:20Z | [
"python",
"tkinter"
] |
How can I implement x[i][j] = y[i+j] efficiently in numpy? | 39,426,690 | <p>Let <strong>x</strong> be a matrix with a shape of (A,B) and <strong>y</strong> be an array with a size of A+B-1.</p>
<pre><code>for i in range(A):
for j in range(B):
x[i][j] = y[i+j]
</code></pre>
<p>How can I implement equivalent code efficiently using functions in numpy?</p>
| 4 | 2016-09-10T13:45:12Z | 39,426,755 | <p><strong>Approach #1</strong> Using <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.linalg.hankel.html" rel="nofollow"><code>Scipy's hankel</code></a> -</p>
<pre><code>from scipy.linalg import hankel
x = hankel(y[:A],y[A-1:]
</code></pre>
<p><strong>Approach #2</strong> Using <a href="htt... | 7 | 2016-09-10T13:53:26Z | [
"python",
"numpy"
] |
Python - How to shorten code | 39,426,786 | <p>I've developed a Python program that I need advice on simplifying.</p>
<p>This is part of my code:</p>
<pre><code>import wx
import sys
import socket
def error_handler(c):
if c == 'canceled':
sys.exit('User canceled configuration.')
elif c == 'empty':
sys.exit('Empty value.')
def hostname... | -1 | 2016-09-10T13:57:29Z | 39,426,832 | <p>It looks you already know the answer with creating another function, <code>error_handler</code> to do the repeated work! You could wrap your error handler in a <a href="https://docs.python.org/2/tutorial/errors.html#handling-exceptions" rel="nofollow">try/except</a> block that would look something along the lines of... | 0 | 2016-09-10T14:04:35Z | [
"python",
"function"
] |
Python - How to shorten code | 39,426,786 | <p>I've developed a Python program that I need advice on simplifying.</p>
<p>This is part of my code:</p>
<pre><code>import wx
import sys
import socket
def error_handler(c):
if c == 'canceled':
sys.exit('User canceled configuration.')
elif c == 'empty':
sys.exit('Empty value.')
def hostname... | -1 | 2016-09-10T13:57:29Z | 39,426,893 | <pre><code>def funct(dlg, wx, funcCheck):
if dlg.ShowModal() == wx.ID_CANCEL:
error_handler('canceled')
else:
if dlg.GetValue() == "":
error_handler('empty')
else:
value = funcCheck()
return value
</code></pre>
<p>then you can call it this way</p>
<p... | 0 | 2016-09-10T14:11:25Z | [
"python",
"function"
] |
How can I know what is the name of the "key" in the dictionary which contain the paramaters for the HTTP POST request? | 39,426,855 | <p>I'm trying to make a Python script which make a HTTP request with a POST argument.
On this site:</p>
<p><a href="https://www.google.com/movies" rel="nofollow">google.com/movies</a></p>
<p>I'm trying to make a script which use the Google search bar and enter the name of a cinema ("Le grand Rex" is the cinema which ... | 0 | 2016-09-10T14:08:02Z | 39,455,926 | <p><a href="https://www.w3.org/TR/html4/interact/forms.html#submit-format" rel="nofollow">The <code>name</code> attribute contains the key.</a></p>
<pre><code>{'q': 'Le Grand Rex'}
</code></pre>
| 0 | 2016-09-12T17:47:32Z | [
"python",
"dictionary",
"beautifulsoup"
] |
How to add horizontal line (`Span`) to the Box plot in Bokeh? | 39,426,976 | <p>What I want is to render a <a href="http://bokeh.pydata.org/en/latest/docs/user_guide/charts.html#bar-charts" rel="nofollow">bar chart</a> with a <a href="http://stackoverflow.com/questions/28797330/infinite-horizontal-line-in-bokeh">horizontal line</a>, so I can see which values (represented by bars) exceed certain... | 0 | 2016-09-10T14:22:00Z | 39,427,333 | <p>Ok, I figured it out...</p>
<pre><code>from bokeh.charts import Bar
from bokeh.models import Span
from bokeh.io import save, output_file, show
from pandas import DataFrame
output_file('tmp_file')
rows = [(1,'2004-01-15', 10), (2,'2004-02-21', 15)]
headers = ['id', 'date', 'value']
df = DataFrame.from_records(rows... | 2 | 2016-09-10T15:02:33Z | [
"python",
"pandas",
"dataframe",
"data-visualization",
"bokeh"
] |
Difference between generators and functions returning generators | 39,426,977 | <p>I was debugging some code with generators and came to this question. Assume I have a generator function</p>
<pre><code>def f(x):
yield x
</code></pre>
<p>and a function returning a generator:</p>
<pre><code>def g(x):
return f(x)
</code></pre>
<p>They surely return the same thing. Can there be any differe... | 10 | 2016-09-10T14:22:10Z | 39,427,083 | <p>They will act the same. And about way to distinguish the two (without <code>inspect</code>). In python? Only inspect:</p>
<pre><code>import inspect
print inspect.isgeneratorfunction(g) --> False
print inspect.isgeneratorfunction(f) --> True
</code></pre>
<p>Of course you can also check it using <code>dis</c... | 1 | 2016-09-10T14:34:23Z | [
"python",
"generator"
] |
Difference between generators and functions returning generators | 39,426,977 | <p>I was debugging some code with generators and came to this question. Assume I have a generator function</p>
<pre><code>def f(x):
yield x
</code></pre>
<p>and a function returning a generator:</p>
<pre><code>def g(x):
return f(x)
</code></pre>
<p>They surely return the same thing. Can there be any differe... | 10 | 2016-09-10T14:22:10Z | 39,427,164 | <p>The best way to check it out is using <a href="https://docs.python.org/2/library/inspect.html#inspect.isgeneratorfunction" rel="nofollow">inspect.isgeneratorfunction</a>, which is quite simple function:</p>
<pre><code>def ismethod(object):
"""Return true if the object is an instance method.
Instance method... | 1 | 2016-09-10T14:43:10Z | [
"python",
"generator"
] |
Difference between generators and functions returning generators | 39,426,977 | <p>I was debugging some code with generators and came to this question. Assume I have a generator function</p>
<pre><code>def f(x):
yield x
</code></pre>
<p>and a function returning a generator:</p>
<pre><code>def g(x):
return f(x)
</code></pre>
<p>They surely return the same thing. Can there be any differe... | 10 | 2016-09-10T14:22:10Z | 39,427,547 | <p>If you want to <strong>identify</strong> what is a generator, the answer is simple. <code>f</code> is a generator because it contains the <code>yield</code> statement. <code>g</code> is not a generator because it does not contain the <code>yield</code> statement. (You can have a look at <a href="https://docs.pyth... | 1 | 2016-09-10T15:24:33Z | [
"python",
"generator"
] |
How can I convert this Python mutable function into immutable? | 39,427,027 | <p>I have a mutable Fibonacci function that mutates a list in order to return that list as a fib sequence. I want to do the same thing... but the list (or tuple in this case) should not be able to change. The return still has to send the whole list, how can I implement this, without using recursion. </p>
<p>Ex) if x =... | -1 | 2016-09-10T14:29:11Z | 39,427,699 | <p>You could create a new list for every new element.</p>
<pre><code>def fibonacci(x):
list_of_fibonaccis = []
for y in range(0,x):
if y < 2:
temp_fibonacci = [1] * (y + 1)
else:
last = list_of_fibonaccis[y-1][-1]
previous = list_of_fibonaccis[y-1][-2]
... | 0 | 2016-09-10T15:38:20Z | [
"python",
"list",
"immutability"
] |
How can I convert this Python mutable function into immutable? | 39,427,027 | <p>I have a mutable Fibonacci function that mutates a list in order to return that list as a fib sequence. I want to do the same thing... but the list (or tuple in this case) should not be able to change. The return still has to send the whole list, how can I implement this, without using recursion. </p>
<p>Ex) if x =... | -1 | 2016-09-10T14:29:11Z | 39,428,102 | <p>If I understand what you mean by "a functional approach that doesn't use recursion," it seems like the input parameter should be a list of the first n Fibonacci numbers and the output should be a list of the first n+1 Fibonacci numbers. If this is correct, then you could use</p>
<pre><code>def fibonacci(fib):
... | 0 | 2016-09-10T16:19:08Z | [
"python",
"list",
"immutability"
] |
how to click iframe using python selenium | 39,427,156 | <p>I want to click an iframe's radio button, but it doesn't work.
my code is this.</p>
<pre><code>import time
from selenium import webdriver
Url='https://www.youtube.com/watch?v=eIStvhR347g'
driver = webdriver.Firefox()
driver.get('https://video-download.online')
driver.find_element_by_id("link").send_keys(Url)
driver... | 1 | 2016-09-10T14:42:34Z | 39,429,238 | <p>(Assuming provided HTML is correct) actually your both locator is wrong to locate <code>radio button</code> element as well as <code>proceed button</code> element.</p>
<blockquote>
<p>driver.find_element_by_css_selector("136-wrapper").click()</p>
</blockquote>
<p>Using <a href="http://www.w3schools.com/cssref/cs... | 0 | 2016-09-10T18:23:43Z | [
"python",
"selenium",
"firefox"
] |
Django models's attributes correctly saved by forms, but returns None type when queried | 39,427,217 | <p>I have a model called UserProfile defined like so:</p>
<pre><code>class UserProfile(models.Model):
user = models.OneToOneField(User)
website = models.URLField(blank=True, null=True)
location = models.CharField(max_length=200, null=True)
longitude = models.FloatField(null=True)
latitude = model... | 0 | 2016-09-10T14:50:21Z | 39,427,577 | <p>In your <code>link</code> view, you're not querying for the userprofile, you're just instantiating a new (blank) one with the user set to the current user.</p>
<p>You probably meant to do:</p>
<pre><code>user_profile = UserProfile.objects.get(user=request.user)
</code></pre>
<p>but it would be even easier to do:<... | 1 | 2016-09-10T15:27:42Z | [
"python",
"django",
"views",
"nonetype",
"querying"
] |
Need help assiigning numbers to letters in python | 39,427,232 | <p><a href="http://i.stack.imgur.com/SuSs7.png" rel="nofollow">This is a a plan of what i want to do with the code.</a></p>
<p>This is all i have to offer, I'm not sure if it's correct.</p>
<pre><code>input ("What's your name?")
[A,J,S]=1
[B,K,T]=2
[C,L,U]=3
[D,M,V]=4
[E,N,W]=5
[F,O,X]=6
[G,P,Y]=7
[H,Q,Z]=8
[I,R]=9
... | -6 | 2016-09-10T14:51:47Z | 39,427,623 | <p>Firstly, the input value needs to be assigned to a variable. So instead of doing</p>
<pre><code>input ("What's your name?")
</code></pre>
<p>You should write</p>
<pre><code>input_text = input("What's your name?")
</code></pre>
<p>This will store the user's input to the string variable input_text.</p>
<p>Next, w... | 2 | 2016-09-10T15:33:10Z | [
"python",
"python-3.x"
] |
How Flask-Bootstrap works? | 39,427,256 | <p>I'm learning Flask web development, and the tutorial I'm following introduces an extension called <strong>Flask-Bootstrap</strong>. To use this extension, you must initialize it first, like this:</p>
<pre><code>from flask_bootstrap import Bootstrap
# ...
bootstrap = Bootstrap(app)
</code></pre>
<p>Weirdly enough t... | -1 | 2016-09-10T14:53:57Z | 39,427,671 | <p>As @davidism said in his comment, the <code>bootstrap = Bootstrap(app)</code> line "installs the extension on the app". The mechanism behind such installation is beyond the scope of this answer.</p>
<p>The <code>bootstrap/base.html</code> resides in the Flask-Bootstrap package. For example, on my machine it's absol... | 0 | 2016-09-10T15:36:52Z | [
"python",
"twitter-bootstrap",
"templates",
"flask",
"flask-bootstrap"
] |
Set wx.Frame size (wxPython - wxWidgets) | 39,427,319 | <p>I am new to wxPython and I am finding some issues while seting a given size for both frames and windows (widgets). I have isolated the issue to the simplest case where I try to create a Frame of 250x250 pixels.</p>
<p>Running the code I get a window of an actual size of 295 width by 307 height (taking into consider... | 0 | 2016-09-10T15:01:44Z | 39,456,255 | <p>Add this before your call to <code>app.MainLoop()</code>:</p>
<pre><code>import wx.lib.inspection
wx.lib.inspection.InspectionTool().Show()
</code></pre>
<p>That will let you easily see the actual size (and other info) for each widget in the application, like this:</p>
<p><a href="http://i.stack.imgur.com/yXaSn.p... | 0 | 2016-09-12T18:09:06Z | [
"python",
"python-2.7",
"wxpython",
"wxwidgets"
] |
condensing multiple if statements in python | 39,427,378 | <p>I'm trying to write a function to check if an object is found in multiple lists and to remove the object from any list its found in. I want to know if there is a way to make it cleaner or smarter using some form of generic variable where you predefine the format or something along those lines.
my code in its ugly f... | 6 | 2016-09-10T15:07:25Z | 39,427,440 | <p>Make your <code>list_x</code> a list of all your lists</p>
<p>Then do it this way</p>
<pre><code>for each in list_x:
if choice in each:
# if is actually not required
each.remove(choice)
</code></pre>
| 2 | 2016-09-10T15:13:16Z | [
"python",
"list",
"loops",
"if-statement"
] |
condensing multiple if statements in python | 39,427,378 | <p>I'm trying to write a function to check if an object is found in multiple lists and to remove the object from any list its found in. I want to know if there is a way to make it cleaner or smarter using some form of generic variable where you predefine the format or something along those lines.
my code in its ugly f... | 6 | 2016-09-10T15:07:25Z | 39,427,443 | <p>How about creating a list of lists and looping over that? </p>
<p>Something like: </p>
<pre><code>lists = [list_a, list_b, list_c, list_d, list_e]
for lst in lists:
if choice in lst:
lst.remove(choice)
</code></pre>
| 5 | 2016-09-10T15:13:32Z | [
"python",
"list",
"loops",
"if-statement"
] |
condensing multiple if statements in python | 39,427,378 | <p>I'm trying to write a function to check if an object is found in multiple lists and to remove the object from any list its found in. I want to know if there is a way to make it cleaner or smarter using some form of generic variable where you predefine the format or something along those lines.
my code in its ugly f... | 6 | 2016-09-10T15:07:25Z | 39,429,954 | <h3>In a one-liner</h3>
<p>If you use <code>some_list.remove(item)</code>, only the first found match of <code>item</code> is removed from the list. Therefore, it depends if the lists possibly include duplicated items, which (all) need to be removed:</p>
<h3>1. If all items in all lists are unique</h3>
<pre><code>li... | 3 | 2016-09-10T19:43:11Z | [
"python",
"list",
"loops",
"if-statement"
] |
condensing multiple if statements in python | 39,427,378 | <p>I'm trying to write a function to check if an object is found in multiple lists and to remove the object from any list its found in. I want to know if there is a way to make it cleaner or smarter using some form of generic variable where you predefine the format or something along those lines.
my code in its ugly f... | 6 | 2016-09-10T15:07:25Z | 39,439,237 | <p>An alternative to the former suggestions, which is a bit clearer, is to define a helper function. So, instead of:</p>
<pre><code>def create_newlist(choice):
if choice in list_a:
list_a.remove(choice)
if choice in list_b:
list_b.remove(choice)
if choice in list_c:
list_c.remove(c... | 0 | 2016-09-11T18:19:27Z | [
"python",
"list",
"loops",
"if-statement"
] |
Matplot Legend uncorrect names | 39,427,476 | <p>l have a 41_year_dataset and l would like to plot these data with Matplotlib and when l add legend on graph and legend shows 6 lines correctly except names. how can l fix it?</p>
<p>here is my code:</p>
<pre><code>import numpy as np
import pandas as pd
import csv
import matplotlib.pyplot as plt
import matplotlib
... | 0 | 2016-09-10T15:17:31Z | 39,427,878 | <p>A simple trick is to call <code>plot</code> once per line, each with its own <code>label</code> argument containing the text that will show up in the legend.</p>
<pre><code>plt.plot(x, y1, "ro", label='pcp1')
plt.plot(x, y2, label='pcp2')
plt.plot(x, y3, label='pcp3')
plt.plot(x, y4, label='pcp4')
plt.plot(x, y5, l... | 1 | 2016-09-10T15:57:09Z | [
"python",
"pandas",
"matplotlib"
] |
Handling missing fields when using Python lamda's | 39,427,492 | <p>I have this rethinkDB query which basically returns the documents which "basicConstraints" fields that start with "CA:FA".</p>
<p>However in some of my documents the "basicConstraints" field does not exist. </p>
<pre><code>q = r.db('scanafi').table(active_table) \
.concat_map(lambda doc: doc["certificates"]\
.conc... | 1 | 2016-09-10T15:19:29Z | 39,427,541 | <p>It seems that your <code>x</code> doesn't have methods like a regular python dict (I'm not familiar with rethinkdb). You could just use a real function here, with a try/except clause:</p>
<pre><code>def basic_constraints(x):
try:
return x["basicConstraints"]
except: # find out what the actual exce... | 0 | 2016-09-10T15:24:20Z | [
"python",
"lambda",
"rethinkdb",
"rethinkdb-python"
] |
Handling missing fields when using Python lamda's | 39,427,492 | <p>I have this rethinkDB query which basically returns the documents which "basicConstraints" fields that start with "CA:FA".</p>
<p>However in some of my documents the "basicConstraints" field does not exist. </p>
<pre><code>q = r.db('scanafi').table(active_table) \
.concat_map(lambda doc: doc["certificates"]\
.conc... | 1 | 2016-09-10T15:19:29Z | 39,462,637 | <p>You can write <code>x.has_fields('basicConstraints').not().or_(x['basicConstraints'].match("^CA:FA"))</code>.</p>
| 0 | 2016-09-13T05:19:51Z | [
"python",
"lambda",
"rethinkdb",
"rethinkdb-python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.