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 |
|---|---|---|---|---|---|---|---|---|---|
How do I resolve builtins.ConnectionRefusedError error in attempting to send email using flask-mail | 39,702,400 | <p>I am making a simple WebApp using Flask framework in python. It will take user inputs for email and name from my website (<a href="http://www.anshulbansal.esy.es" rel="nofollow">www.anshulbansal.esy.es</a>) and will check if email exists in database (here database is supposed as dictionary for now) then it will not ... | -1 | 2016-09-26T12:08:04Z | 39,714,728 | <p>You should update configuration before you initialize Mail:</p>
<pre><code>app = Flask(__name__)
app.config.update(
DEBUG = True,
MAIL_SERVER = 'smtp.gmail.com',
MAIL_PORT = 587,
MAIL_USE_TLS = True,
MAIL_USE_SSL = False,
MAIL_USERNAME = '[email protected]',
MAIL_PASSWORD = 'your_... | 1 | 2016-09-27T01:30:44Z | [
"python",
"email",
"flask",
"flask-mail"
] |
hash function that outputs integer from 0 to 255? | 39,702,457 | <p>I need a very simple hash function in Python that will convert a string to an integer from 0 to 255.</p>
<p>For example:</p>
<pre><code>>>> hash_function("abc_123")
32
>>> hash_function("any-string-value")
99
</code></pre>
<p>It does not matter what the integer is as long as I get the same integ... | 2 | 2016-09-26T12:11:09Z | 39,702,481 | <p>You could just use the modulus of the <a href="https://docs.python.org/3/library/functions.html#hash" rel="nofollow"><code>hash()</code> function</a> output:</p>
<pre><code>def onebyte_hash(s):
return hash(s) % 256
</code></pre>
<p>This is what dictionaries and sets use (hash modulus the internal table size).<... | 10 | 2016-09-26T12:12:16Z | [
"python",
"hash",
"integer"
] |
Python: Converting a queryset in a list of tuples | 39,702,538 | <p>i want to turn a queryset into a list of tuples. "result" ist what it should look like:</p>
<pre><code>queryset = [{x:'1',y:'a'}, {x:'2',y:'b'}]
result = [(1,'a'),(2,'b')]
</code></pre>
<p>So the solution i do have right now is this one, but it seems to me that there could be a way to shorten the code, and make it... | -1 | 2016-09-26T12:15:01Z | 39,702,563 | <p><code>your_tuple = [(x, y) for x, y in queryset.items()]</code></p>
<hr>
<p>EDIT</p>
<p><code>your_tuple = [(x.get('x'), x.get('y')) for x in queryset]</code></p>
| 1 | 2016-09-26T12:15:58Z | [
"python",
"django",
"performance"
] |
Python: Converting a queryset in a list of tuples | 39,702,538 | <p>i want to turn a queryset into a list of tuples. "result" ist what it should look like:</p>
<pre><code>queryset = [{x:'1',y:'a'}, {x:'2',y:'b'}]
result = [(1,'a'),(2,'b')]
</code></pre>
<p>So the solution i do have right now is this one, but it seems to me that there could be a way to shorten the code, and make it... | -1 | 2016-09-26T12:15:01Z | 39,702,671 | <p>You can use <code>dict.values()</code>:</p>
<pre><code>queryset = [{x:'1',y:'a'}, {x:'2',y:'b'}]
result = []
for i in queryset:
result.append(tuple(i.values()))
</code></pre>
<p>Or in one line:</p>
<pre><code>result = [tuple(i.values()) for i in queryset]
</code></pre>
<hr>
<p>If you want them in a particu... | 1 | 2016-09-26T12:21:08Z | [
"python",
"django",
"performance"
] |
Python: Converting a queryset in a list of tuples | 39,702,538 | <p>i want to turn a queryset into a list of tuples. "result" ist what it should look like:</p>
<pre><code>queryset = [{x:'1',y:'a'}, {x:'2',y:'b'}]
result = [(1,'a'),(2,'b')]
</code></pre>
<p>So the solution i do have right now is this one, but it seems to me that there could be a way to shorten the code, and make it... | -1 | 2016-09-26T12:15:01Z | 39,702,688 | <p>Assuming <code>queryset</code> is supposed to look like this, with <code>'x'</code> and <code>'y'</code> as string keys:</p>
<pre><code>>>> queryset = [{'x':'1', 'y':'a'}, {'x':'2', 'y':'b'}]
>>> result = [(q['x'], q['y']) for q in queryset]
>>> result
[('1', 'a'), ('2', 'b')]
>>>... | 1 | 2016-09-26T12:21:46Z | [
"python",
"django",
"performance"
] |
Python: Converting a queryset in a list of tuples | 39,702,538 | <p>i want to turn a queryset into a list of tuples. "result" ist what it should look like:</p>
<pre><code>queryset = [{x:'1',y:'a'}, {x:'2',y:'b'}]
result = [(1,'a'),(2,'b')]
</code></pre>
<p>So the solution i do have right now is this one, but it seems to me that there could be a way to shorten the code, and make it... | -1 | 2016-09-26T12:15:01Z | 39,702,727 | <p>Use list comprehension and <code>dict.values()</code></p>
<pre><code>>>> queryset = [{'x': '1', 'y': 'a'}, {'x': '2', 'y': 'b'}]
>>> result = [tuple(v.values()) for v in queryset]
>>> result
[('1', 'a'), ('2', 'b')]
</code></pre>
<p><strong>UPDATE</strong></p>
<p>as @aneroid reasona... | 2 | 2016-09-26T12:23:32Z | [
"python",
"django",
"performance"
] |
Python: Converting a queryset in a list of tuples | 39,702,538 | <p>i want to turn a queryset into a list of tuples. "result" ist what it should look like:</p>
<pre><code>queryset = [{x:'1',y:'a'}, {x:'2',y:'b'}]
result = [(1,'a'),(2,'b')]
</code></pre>
<p>So the solution i do have right now is this one, but it seems to me that there could be a way to shorten the code, and make it... | -1 | 2016-09-26T12:15:01Z | 39,702,851 | <p>If you can have multiple keys and you just want certain key values, you can use <em>itemgetter</em> with map passing the keys you want to extract:</p>
<pre><code>from operator import itemgetter
result = list(map(itemgetter("x", "y"), queryset)))
</code></pre>
| 2 | 2016-09-26T12:28:39Z | [
"python",
"django",
"performance"
] |
Python: Converting a queryset in a list of tuples | 39,702,538 | <p>i want to turn a queryset into a list of tuples. "result" ist what it should look like:</p>
<pre><code>queryset = [{x:'1',y:'a'}, {x:'2',y:'b'}]
result = [(1,'a'),(2,'b')]
</code></pre>
<p>So the solution i do have right now is this one, but it seems to me that there could be a way to shorten the code, and make it... | -1 | 2016-09-26T12:15:01Z | 39,702,885 | <p>If this is an django ORM queryset (or result of it), you can just use <code>values_list</code> method instead of <code>values</code>. That will give exactly what you want.</p>
| 2 | 2016-09-26T12:30:40Z | [
"python",
"django",
"performance"
] |
How to make my function run every hour? | 39,702,803 | <p>With the help of some online tuts (Bucky), I've managed to write a simple web scraper that just checks if some text is on a webpage. What I would like to do however, is have the code run every hour. I assume I will need to host the code also so it does this? I've done some research but can't seem to find a proper wa... | -1 | 2016-09-26T12:26:52Z | 39,703,100 | <p>The easiest way would be like this:</p>
<pre><code>import time
while True:
call_your_function()
time.sleep(3600)
</code></pre>
<p>If you wanna do this on Linux, you can just type</p>
<pre><code>nohup python -u your_script_name &
</code></pre>
<p>and then your script will run as a process.(If you don... | 4 | 2016-09-26T12:39:50Z | [
"python",
"function",
"web",
"scraper"
] |
glsl parser using pyparsing giving AttributeErrors | 39,702,882 | <p>I'm trying to update this <a href="https://github.com/rougier/glsl-parser" rel="nofollow">glsl-parser</a> which uses an old pyparsing version and python2.x to python3.x & the newest pyparsing version (2.1.9 atm). </p>
<p>I don't know which pyparsing version was using the original source code but it must be quit... | 2 | 2016-09-26T12:30:15Z | 39,704,620 | <p><code>originalTextFor</code> is not a parse action, but a helper method that attaches a parse action to a defined expression. In your example it is used in two places:</p>
<pre><code># Value
VALUE = (EXPRESSION | pyparsing.Word(pyparsing.alphanums + "_()+-/*")
).setParseAction(pyparsing.originalTextFor)
F... | 1 | 2016-09-26T13:46:06Z | [
"python",
"python-3.x",
"glsl",
"pyparsing"
] |
glsl parser using pyparsing giving AttributeErrors | 39,702,882 | <p>I'm trying to update this <a href="https://github.com/rougier/glsl-parser" rel="nofollow">glsl-parser</a> which uses an old pyparsing version and python2.x to python3.x & the newest pyparsing version (2.1.9 atm). </p>
<p>I don't know which pyparsing version was using the original source code but it must be quit... | 2 | 2016-09-26T12:30:15Z | 39,705,506 | <p>Following @Paul McGuire advices, here's a working version which uses python3.5.1 and pyparsing 2.1.9:</p>
<pre><code># -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2014, Nicolas P. Rougier
# Distributed under the (new) BSD License. See LICENSE... | 0 | 2016-09-26T14:28:16Z | [
"python",
"python-3.x",
"glsl",
"pyparsing"
] |
Query a boolean property in NDB Python | 39,702,889 | <p>I have a Greeting model</p>
<pre><code>class Greeting(ndb.Model):
author = ndb.StructuredProperty(Author)
content = ndb.TextProperty(indexed=False)
avatar = ndb.BlobProperty()
date = ndb.DateTimeProperty(auto_now_add=True)
public = ndb.BooleanProperty(default=False)
</code></pre>
<p>wherein I u... | 1 | 2016-09-26T12:30:57Z | 39,703,562 | <p>I fixed it by using this </p>
<pre><code>posts_query = Greeting.query(Greeting.public == True).order(-Greeting.date)
</code></pre>
<p>instead of </p>
<pre><code>posts_query = Greeting.query(ancestor=session_key(session_name),
Greeting.public == True).order(-Greeting.date)
</code></pre>
| 0 | 2016-09-26T12:59:31Z | [
"python",
"google-app-engine",
"app-engine-ndb"
] |
requests - fetch data from api-based website | 39,703,021 | <p>I want to get all the review from <a href="https://www.traveloka.com/hotel/singapore/mandarin-orchard-singapore-10602" rel="nofollow">this site</a>.</p>
<p>at first, I use this code:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
r = requests.get(
"https://www.traveloka.com/hotel/singapore/manda... | 0 | 2016-09-26T12:36:19Z | 39,704,516 | <p>Look at the request payload at the network tab. There is a part where <code>skip:8</code> and <code>top:8</code> and you will see those numbers increment by 8 when you click on the right arrow to get the next page of reviews. </p>
<p>You can duplicate that request and scrape the results the same way</p>
<p><strong... | -1 | 2016-09-26T13:41:39Z | [
"python",
"python-2.7",
"api",
"python-requests"
] |
SQLAlchemy: Inconsistent behaviour after commit | 39,703,044 | <p>I have a SQLAlchemy ORM, whose <code>__str__()</code> function prints a table of keys and values.
The following code commits it to the DB and prints it (attribute names changed for clarity):</p>
<pre><code>user.some_attribute = <Some integer>
session.add(user)
session.commit()
app.logger.debug("some_attribute... | -1 | 2016-09-26T12:37:24Z | 39,703,194 | <p>I found a workaround, even though I'm not really sure about the nature of the problem.</p>
<p>Quoting <a href="http://docs.sqlalchemy.org/en/latest/orm/session_api.html#sqlalchemy.orm.session.Session.commit" rel="nofollow">the manual</a>:</p>
<blockquote>
<p>By default, the Session also expires all database load... | 0 | 2016-09-26T12:43:24Z | [
"python",
"session",
"orm",
"sqlalchemy"
] |
Join dataframes by column values pandas | 39,703,165 | <p>I have two data frames <code>df1</code> and <code>df2</code> taken from different databases. Each item in the dataframes is identified by an <code>id</code>.</p>
<pre><code>df1 = pd.DataFrame({'id':[10,20,30,50,100,110],'cost':[100,0,300,570,400,140]})
df2 = pd.DataFrame({'id':[10,23,30,58,100,110],'name':['a','b'... | 1 | 2016-09-26T12:42:26Z | 39,703,204 | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a>, default parameter <code>how='inner'</code> is omited:</p>
<pre><code>print (pd.merge(df1,df2,on='id'))
cost id name
0 100 10 a
1 300 30 j
2 400 100 k
... | 2 | 2016-09-26T12:43:54Z | [
"python",
"pandas",
"dataframe",
"merge",
"inner-join"
] |
unable to run a python script from localhost via ansible | 39,703,224 | <p>I have my structure as :</p>
<pre><code>playbooks_only
|
|- read_replica_boto3.yml
|- roles
|
|-read_replica_boto3
|-defaults
|-tasks-->> main.yml
|-files-->> - rds_read_replica_ops.py
... | 1 | 2016-09-26T12:45:00Z | 39,703,412 | <p>You have a typo in this line:</p>
<pre><code> chdir: '"{{ role_path }}"/files'
</code></pre>
<p>You shouldn't surround variables with quotes. Instead, change the line to:</p>
<pre><code> chdir: '{{ role_path }}/files'
</code></pre>
<p>And that should work!</p>
| 2 | 2016-09-26T12:53:05Z | [
"python",
"ansible",
"ansible-playbook"
] |
Read and parse a file of tokens? | 39,703,241 | <p><strong>EDIT</strong>: <em>I have edited the question to correct a major mistake (which unfortunately invalidates all the answers provided so far): the command lines can contain spaces between the words, so no solution based on using spaces as delimiters between the tokens and their parameters will work! I deeply ap... | 3 | 2016-09-26T12:45:56Z | 39,703,860 | <p>As the commands may take more than one line its much easier to NOT split the text-file by newlines. I would suggest splitting by '$' instead.</p>
<p>This example code works:</p>
<pre><code>def get_params(fname, desired_command):
with open(fname,"r") as f:
content = f.read()
for element in content.s... | 2 | 2016-09-26T13:12:39Z | [
"python",
"python-2.7"
] |
Read and parse a file of tokens? | 39,703,241 | <p><strong>EDIT</strong>: <em>I have edited the question to correct a major mistake (which unfortunately invalidates all the answers provided so far): the command lines can contain spaces between the words, so no solution based on using spaces as delimiters between the tokens and their parameters will work! I deeply ap... | 3 | 2016-09-26T12:45:56Z | 39,704,405 | <p>Here is my approach: split everything based on white spaces (spaces, tabs and new lines). Then construct a dictionary with command names as keys and parameters as values. From this dictionary, you can look up parameters for any command. This approach opens and reads the file only once:</p>
<pre><code>from collectio... | 1 | 2016-09-26T13:37:00Z | [
"python",
"python-2.7"
] |
Read and parse a file of tokens? | 39,703,241 | <p><strong>EDIT</strong>: <em>I have edited the question to correct a major mistake (which unfortunately invalidates all the answers provided so far): the command lines can contain spaces between the words, so no solution based on using spaces as delimiters between the tokens and their parameters will work! I deeply ap... | 3 | 2016-09-26T12:45:56Z | 39,706,835 | <p>Here is another solution. This one uses regular expression and it does not squeeze multiple spaces within a command:</p>
<pre><code>import re
def parse_commands_file(filename):
command_pattern = r"""
(\$[A-Z _]+)* # The command, optional
([0-9 \n]+)* # The parameter which might span multiple... | 1 | 2016-09-26T15:32:09Z | [
"python",
"python-2.7"
] |
Elementwise operation on pandas series | 39,703,665 | <p>I have a pandas Series <code>x</code> with values <code>1</code>, <code>2</code> or <code>3</code>.</p>
<p>I want it to have values <code>monkey</code>, <code>gorilla</code>, and <code>tarzan</code> depending on the values.</p>
<p>I guess I should do something like</p>
<pre><code>values = ['monkey', 'gorilla', 't... | 0 | 2016-09-26T13:04:14Z | 39,703,706 | <p>Use maping by <code>dict</code> with function <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow"><code>map</code></a>.</p>
<p>Sample:</p>
<pre><code>s = pd.Series([1,2,3])
print (s)
0 1
1 2
2 3
dtype: int64
d = {1:'monkey',2:'gorilla',3:'tarzan'}
print... | 2 | 2016-09-26T13:05:50Z | [
"python",
"pandas",
"sklearn-pandas"
] |
Specify which Python version interprets an executable | 39,703,725 | <p>I developed an application with Python 3 that produces various executables. I then used <code>setuptools</code> to build and distribute this application, again all using Python 3. </p>
<p>When this application is installed in a test environment, the executables are being correctly deployed to the <code>bin</code> ... | 1 | 2016-09-26T13:06:42Z | 39,704,446 | <p>You might need to use bash <a href="http://stackoverflow.com/questions/25165808/should-i-use-a-shebang-with-bash-scripts">shebangs</a> on your scripts, which are small strings at the beginning that specifies what binary should interpret them.</p>
<p>In your case you need to add <code>#!/usr/bin/env python3</code> a... | -2 | 2016-09-26T13:38:49Z | [
"python",
"python-3.x"
] |
Specify which Python version interprets an executable | 39,703,725 | <p>I developed an application with Python 3 that produces various executables. I then used <code>setuptools</code> to build and distribute this application, again all using Python 3. </p>
<p>When this application is installed in a test environment, the executables are being correctly deployed to the <code>bin</code> ... | 1 | 2016-09-26T13:06:42Z | 39,746,982 | <p>I made sure <code>install</code> was run with Python 3 and that the resulting script included the correct header. Still I kept getting exceptions from Python 2.7.</p>
<p>Out of desperation I created a new Python 3 virtual environment and in it the scripts started working properly. There are previous reports of old ... | 0 | 2016-09-28T12:05:28Z | [
"python",
"python-3.x"
] |
input column based on conditional statement pandas | 39,703,734 | <p>I have two Pandas data frames and wish to insert day and week columns from DF2 values in DF1 where the dates match. e.g. for example below, day - 4 and week - 1 would be extracted from DF2 row 1 and inserted to all of the day and week columns in DF1.</p>
<p><strong>DF 1</strong></p>
<pre><code>montgomery year d... | 0 | 2016-09-26T13:07:09Z | 39,703,840 | <p>IIUC you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a>:</p>
<pre><code>#if empty columns in DF1, rem... | 0 | 2016-09-26T13:11:46Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
Calculate a new column with Pandas | 39,703,749 | <p>Based on <a href="http://stackoverflow.com/q/39698097/6618225">this</a> Question, I would like to know how can I use a def() to calculate a new column with Pandas and use more than one arguments (strings and integers)?</p>
<p>Concrete example:</p>
<pre><code>df_joined["IVbest"] = IV(df_joined["Saison"], df_joined[... | 1 | 2016-09-26T13:07:46Z | 39,704,712 | <p>I think in this case it would be better to use 6 masks and use these to perform the calculations just on those rows:</p>
<pre><code>sommer_laub = (df_joined['Saison'] == 'Sommer') & (df_joined['Wald_Typ'] == 'Laubwald')
sommer_nadel = (df_joined['Saison'] == 'Sommer') & (df_joined['Wald_Typ'] == 'Nadelwald'... | 0 | 2016-09-26T13:49:57Z | [
"python",
"python-2.7",
"csv",
"pandas"
] |
Disable focus for tkinter widgets? | 39,703,766 | <p>How can I make a widget that will not get the focus ever in tkinter?
For example, a button that when I will press TAB the focus will skip on him</p>
| 0 | 2016-09-26T13:08:19Z | 39,704,095 | <p>found some time to provide working example ;)</p>
<pre><code>import Tkinter
import tkMessageBox
root = Tkinter.Tk()
but1 = Tkinter.Button(root, text ="Button 1")
but1.pack()
butNoFocus = Tkinter.Button(root, text ="Button no focus", takefocus = 0)
butNoFocus.pack()
but2 = Tkinter.Button(root, text ="Button 2")
... | 1 | 2016-09-26T13:23:05Z | [
"python",
"button",
"tkinter",
"focus"
] |
Find corresponding value with maximum in a list of lists | 39,703,879 | <p>I have a list (created from a .csv file) with an output like this: </p>
<p><code>[('25.09.2016 01:00:00', 'MQ100D1_3_1_4', '225'),
('25.09.2016 02:00:00', 'MQ100D1_3_1_4', '173'),
('25.09.2016 03:00:00', 'MQ100D1_3_1_4', '106'),
('25.09.2016 04:00:00', 'MQ100D1_3_1_4', '74'),
('25.09.2016 05:00:00', 'MQ100D1_3_... | 0 | 2016-09-26T13:13:20Z | 39,703,997 | <p>Iterate on the tuples (not on the last items in each tuple) and use the <code>key</code> function in <code>max</code> to get the last item that is used to compute the maximum.</p>
<p>You can do this with a <em>list comprehension</em>:</p>
<pre><code>top_hour = [max(lst[i:i+12], key=lambda x: int(x[-1])) for i in r... | 1 | 2016-09-26T13:18:35Z | [
"python",
"list",
"python-3.x"
] |
Find corresponding value with maximum in a list of lists | 39,703,879 | <p>I have a list (created from a .csv file) with an output like this: </p>
<p><code>[('25.09.2016 01:00:00', 'MQ100D1_3_1_4', '225'),
('25.09.2016 02:00:00', 'MQ100D1_3_1_4', '173'),
('25.09.2016 03:00:00', 'MQ100D1_3_1_4', '106'),
('25.09.2016 04:00:00', 'MQ100D1_3_1_4', '74'),
('25.09.2016 05:00:00', 'MQ100D1_3_... | 0 | 2016-09-26T13:13:20Z | 39,704,232 | <p>use the lambda function is appropriate, you can do it like:</p>
<pre><code>max(finalList[i:i+12]], key=lambda x: int(x[-1]))
</code></pre>
<p>then you can process the triple further...</p>
<p>btw, in your code, the <code>i</code> is ambiguous, you should take care.</p>
| 0 | 2016-09-26T13:29:28Z | [
"python",
"list",
"python-3.x"
] |
Q: How do I concatenate str + int to = an existing variable | 39,704,072 | <p>I want to combine a str + int to equal a existing variable that I already defined. I tried looking up on how this can be done and I've only found how to concatenate a str and int together with </p>
<pre><code>print "var%d" % currentIndex
</code></pre>
<p>what I have is currentIndex being the index number of the se... | 0 | 2016-09-26T13:22:00Z | 39,704,671 | <p>You can print the list like this:</p>
<pre><code>print eval("var%d" % currentIndex)
</code></pre>
<p>But I would suggest you to use a nested list rather than 30 variables:</p>
<pre><code>var = [["a", "b", "c", "d"], ["e", "f"], ...]
print var[currentIndex]
</code></pre>
| 0 | 2016-09-26T13:48:14Z | [
"python",
"string",
"python-2.7",
"concatenation"
] |
How to write a recursive function that takes a list and return the same list without vowels? | 39,704,084 | <p>I am supposed to write a recursive function that takes a list of strings or a list of lists of strings and return the list without vowels, if found. Here is my attempt to solve it:</p>
<pre><code>def noVow(seq):
keys = ['a','i','e','o','u','u']
if not seq or not isinstance(seq, list) :
return
e... | 3 | 2016-09-26T13:22:43Z | 39,704,387 | <blockquote>
<p>return the <strong>same</strong> list without vowels</p>
</blockquote>
<p>Eh, you're <em>slicing</em> the original list in the recursive calls, so you have a <strong>copy</strong> not the same list. </p>
<p>More so, your code actually works, but since you're passing a <em>slice</em> of the list, the... | 1 | 2016-09-26T13:36:27Z | [
"python",
"recursion",
"functional-programming"
] |
How to write a recursive function that takes a list and return the same list without vowels? | 39,704,084 | <p>I am supposed to write a recursive function that takes a list of strings or a list of lists of strings and return the list without vowels, if found. Here is my attempt to solve it:</p>
<pre><code>def noVow(seq):
keys = ['a','i','e','o','u','u']
if not seq or not isinstance(seq, list) :
return
e... | 3 | 2016-09-26T13:22:43Z | 39,704,399 | <pre><code>def no_vowel(seq):
if not isinstance(seq, list):
raise ValueError('Expected list, got {}'.format(type(seq)))
if not seq:
return []
head, *tail = seq
if isinstance(head, list):
return [[no_vowel(head)]] + no_vowel(tail)
else:
if head in 'aeiou':
... | 1 | 2016-09-26T13:36:52Z | [
"python",
"recursion",
"functional-programming"
] |
How to write a recursive function that takes a list and return the same list without vowels? | 39,704,084 | <p>I am supposed to write a recursive function that takes a list of strings or a list of lists of strings and return the list without vowels, if found. Here is my attempt to solve it:</p>
<pre><code>def noVow(seq):
keys = ['a','i','e','o','u','u']
if not seq or not isinstance(seq, list) :
return
e... | 3 | 2016-09-26T13:22:43Z | 39,704,404 | <p>Your base case returns a None. So whenever you passes the empty list the None is sent up the stack of recursive calls. </p>
<p>Moreover you are not storing the characters which are not vowels, so your else case is wrong.</p>
<p>What you can have is something like this: </p>
<pre><code>>>> def noVow(seq):... | 1 | 2016-09-26T13:37:00Z | [
"python",
"recursion",
"functional-programming"
] |
How to write a recursive function that takes a list and return the same list without vowels? | 39,704,084 | <p>I am supposed to write a recursive function that takes a list of strings or a list of lists of strings and return the list without vowels, if found. Here is my attempt to solve it:</p>
<pre><code>def noVow(seq):
keys = ['a','i','e','o','u','u']
if not seq or not isinstance(seq, list) :
return
e... | 3 | 2016-09-26T13:22:43Z | 39,713,114 | <p>To work for a list of lists containing string and a flat list of strings, you need to iterate over the sequence and then check the type:</p>
<pre><code>def noVow(seq):
vowels = {'a', 'i', 'e', 'o', 'u', 'u'}
for ele in seq:
if isinstance(ele, list):
# a list so recursively process
... | 1 | 2016-09-26T22:02:28Z | [
"python",
"recursion",
"functional-programming"
] |
How to write a recursive function that takes a list and return the same list without vowels? | 39,704,084 | <p>I am supposed to write a recursive function that takes a list of strings or a list of lists of strings and return the list without vowels, if found. Here is my attempt to solve it:</p>
<pre><code>def noVow(seq):
keys = ['a','i','e','o','u','u']
if not seq or not isinstance(seq, list) :
return
e... | 3 | 2016-09-26T13:22:43Z | 39,714,563 | <p>I believe this solution correctly implements both of the criteria "a list of strings or a list of lists of strings" and "return the same list" without any external assistance:</p>
<pre><code>def noVowels(sequence, index=0):
if not (sequence and type(sequence) is list and index < len(sequence)):
retur... | 1 | 2016-09-27T01:01:58Z | [
"python",
"recursion",
"functional-programming"
] |
Parse online comma delimited text file in Python 3.5 | 39,704,096 | <p>I guess this is a combination of two questions - read online text file and then parse the result into lists. I tried the following code, which can read the file into byte file but not able to convert into list</p>
<pre><code>import urllib
CFTC_URL = r"http://www.cftc.gov/dea/newcot/FinFutWk.txt"
CFTC_url = urllib.r... | -1 | 2016-09-26T13:23:09Z | 39,704,721 | <p>Rather than attempting parse every line from the url and put it into specific rows for a csv file, you can just push it all into a text file to clean up the formating, and then read back from it, it may seem like a bit more works but this is generally my approach to comma delimited information from a URL. </p>
<pre... | 0 | 2016-09-26T13:50:13Z | [
"python",
"csv",
"urllib",
"delimited-text"
] |
Parse online comma delimited text file in Python 3.5 | 39,704,096 | <p>I guess this is a combination of two questions - read online text file and then parse the result into lists. I tried the following code, which can read the file into byte file but not able to convert into list</p>
<pre><code>import urllib
CFTC_URL = r"http://www.cftc.gov/dea/newcot/FinFutWk.txt"
CFTC_url = urllib.r... | -1 | 2016-09-26T13:23:09Z | 39,704,727 | <p>Assuming you want to interpret the file as a table you want to first get the rows by using <a href="http://stackoverflow.com/questions/172439/how-do-i-split-a-multi-line-string-into-multiple-lines">split</a>. Then you can get the columns by splitting each row again.</p>
<pre><code>import urllib.request
CFTC_URL = r... | 0 | 2016-09-26T13:50:25Z | [
"python",
"csv",
"urllib",
"delimited-text"
] |
Parse online comma delimited text file in Python 3.5 | 39,704,096 | <p>I guess this is a combination of two questions - read online text file and then parse the result into lists. I tried the following code, which can read the file into byte file but not able to convert into list</p>
<pre><code>import urllib
CFTC_URL = r"http://www.cftc.gov/dea/newcot/FinFutWk.txt"
CFTC_url = urllib.r... | -1 | 2016-09-26T13:23:09Z | 39,704,798 | <p>You can use standart <a href="https://docs.python.org/3.3/library/csv.html" rel="nofollow">csv</a> module with <a href="https://docs.python.org/3/library/io.html#text-i-o" rel="nofollow">StringIO</a> wrapper for file content (example with <a href="http://docs.python-requests.org/en/master/" rel="nofollow">requests</... | 2 | 2016-09-26T13:53:18Z | [
"python",
"csv",
"urllib",
"delimited-text"
] |
How to call django.setup() in console_script? | 39,704,298 | <p>The current django docs tell me this:</p>
<blockquote>
<p>django.setup() may only be called once.</p>
<p>Therefore, avoid putting reusable application logic in standalone scripts so that you have to import from the script elsewhere in your application. If you canât avoid that, put the call to django.setup(... | 9 | 2016-09-26T13:32:10Z | 39,791,949 | <p>had the same problem (or something similar). I solved it by doing:</p>
<p>[Warning: dirty solution]</p>
<pre><code>if not hasattr(django, 'apps'):
django.setup()
</code></pre>
<p>this way it'll be called only once even if it's imported multiple times</p>
| 5 | 2016-09-30T12:50:13Z | [
"python",
"django",
"python-import",
"hang"
] |
How to call django.setup() in console_script? | 39,704,298 | <p>The current django docs tell me this:</p>
<blockquote>
<p>django.setup() may only be called once.</p>
<p>Therefore, avoid putting reusable application logic in standalone scripts so that you have to import from the script elsewhere in your application. If you canât avoid that, put the call to django.setup(... | 9 | 2016-09-26T13:32:10Z | 39,996,838 | <p>Here <a href="https://docs.djangoproject.com/en/1.10/_modules/django/#setup" rel="nofollow">https://docs.djangoproject.com/en/1.10/_modules/django/#setup</a> we can see what <code>django.setup</code> actually does. </p>
<blockquote>
<p>Configure the settings (this happens as a side effect of accessing the
firs... | 0 | 2016-10-12T10:55:47Z | [
"python",
"django",
"python-import",
"hang"
] |
How to call django.setup() in console_script? | 39,704,298 | <p>The current django docs tell me this:</p>
<blockquote>
<p>django.setup() may only be called once.</p>
<p>Therefore, avoid putting reusable application logic in standalone scripts so that you have to import from the script elsewhere in your application. If you canât avoid that, put the call to django.setup(... | 9 | 2016-09-26T13:32:10Z | 40,081,252 | <p>Since I love condition-less code, I use this solution. It's like in the django docs, but the ulgy <code>if __name__ == '__pain__'</code> gets avoided.</p>
<p>File with code:</p>
<pre><code># utils/do_good_stuff.py
# This file contains the code
# No `django.setup()` needed
# This code can be used by web apps and co... | 0 | 2016-10-17T08:01:54Z | [
"python",
"django",
"python-import",
"hang"
] |
How to call django.setup() in console_script? | 39,704,298 | <p>The current django docs tell me this:</p>
<blockquote>
<p>django.setup() may only be called once.</p>
<p>Therefore, avoid putting reusable application logic in standalone scripts so that you have to import from the script elsewhere in your application. If you canât avoid that, put the call to django.setup(... | 9 | 2016-09-26T13:32:10Z | 40,081,707 | <p>I have worked in two production CLI python packages with explicitly calling <code>django.setup()</code> in <code>console_scripts</code>. </p>
<p>The most important thing you should note is <code>DJANGO_SETTINGS_MODULE</code> in <code>env</code> path.</p>
<p>You can set this value in shell script or even load defau... | 1 | 2016-10-17T08:29:15Z | [
"python",
"django",
"python-import",
"hang"
] |
How to call django.setup() in console_script? | 39,704,298 | <p>The current django docs tell me this:</p>
<blockquote>
<p>django.setup() may only be called once.</p>
<p>Therefore, avoid putting reusable application logic in standalone scripts so that you have to import from the script elsewhere in your application. If you canât avoid that, put the call to django.setup(... | 9 | 2016-09-26T13:32:10Z | 40,086,329 | <p>I have some scripts that are placed inside the django folder, i just placed this at the start of the script.</p>
<pre><code>import sys, os, django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "eternaltool.settings")
django.setup()
</code></pre>
| -1 | 2016-10-17T12:24:35Z | [
"python",
"django",
"python-import",
"hang"
] |
Unable to use google-cloud in a GAE app | 39,704,367 | <p>The following line in my Google App Engine app (<code>webapp.py</code>) fails to import the <a href="https://googlecloudplatform.github.io/google-cloud-python/" rel="nofollow">Google Cloud</a> library:</p>
<pre><code>from google.cloud import storage
</code></pre>
<p>With the following error:</p>
<pre><code>Import... | 3 | 2016-09-26T13:35:38Z | 39,710,086 | <p>Your appengine_config.py only needs to contain:</p>
<pre><code>from google.appengine.ext import vendor
vendor.add('lib')
</code></pre>
<p>All the rest you have posted looks fine to me.</p>
| 0 | 2016-09-26T18:41:23Z | [
"python",
"google-app-engine",
"google-cloud-storage",
"google-cloud-platform"
] |
Unable to use google-cloud in a GAE app | 39,704,367 | <p>The following line in my Google App Engine app (<code>webapp.py</code>) fails to import the <a href="https://googlecloudplatform.github.io/google-cloud-python/" rel="nofollow">Google Cloud</a> library:</p>
<pre><code>from google.cloud import storage
</code></pre>
<p>With the following error:</p>
<pre><code>Import... | 3 | 2016-09-26T13:35:38Z | 39,725,337 | <p>The package namespace seems to have been changed as pointed out in this <a href="https://github.com/GoogleCloudPlatform/google-cloud-python/pull/2264" rel="nofollow">github issue</a> and hasn't been fully fixed. You could install the older version (<code>pip install gcloud</code>) which uses a different namespace &a... | 1 | 2016-09-27T12:58:44Z | [
"python",
"google-app-engine",
"google-cloud-storage",
"google-cloud-platform"
] |
Unable to use google-cloud in a GAE app | 39,704,367 | <p>The following line in my Google App Engine app (<code>webapp.py</code>) fails to import the <a href="https://googlecloudplatform.github.io/google-cloud-python/" rel="nofollow">Google Cloud</a> library:</p>
<pre><code>from google.cloud import storage
</code></pre>
<p>With the following error:</p>
<pre><code>Import... | 3 | 2016-09-26T13:35:38Z | 39,814,684 | <p>There is an <a href="https://cloud.google.com/appengine/docs/python/googlecloudstorageclient/read-write-to-cloud-storage" rel="nofollow">App Engine specific Google Cloud Storage API</a> that ships with the App Engine SDK that you can use to work with Cloud Storage buckets.</p>
<pre><code>import cloudstorage as gcs
... | 2 | 2016-10-02T07:08:22Z | [
"python",
"google-app-engine",
"google-cloud-storage",
"google-cloud-platform"
] |
Unable to use google-cloud in a GAE app | 39,704,367 | <p>The following line in my Google App Engine app (<code>webapp.py</code>) fails to import the <a href="https://googlecloudplatform.github.io/google-cloud-python/" rel="nofollow">Google Cloud</a> library:</p>
<pre><code>from google.cloud import storage
</code></pre>
<p>With the following error:</p>
<pre><code>Import... | 3 | 2016-09-26T13:35:38Z | 39,815,014 | <p>It looks like the only thing that is required is to include <code>google-cloud</code> into your project <code>requirements.txt</code> file.</p>
<p>Check if this simple sample works for you (you shouldn't get any imports error).
Create below files and run <code>pip install -r requirements.txt -t lib</code>. Nothing... | 0 | 2016-10-02T07:58:51Z | [
"python",
"google-app-engine",
"google-cloud-storage",
"google-cloud-platform"
] |
Unable to click the linktext using selenium execute_script function using selenium python | 39,704,554 | <p>Unable to click the linktext using <strong>selenium</strong> <code>execute_script</code> function</p>
<p>This is what I am tring to do:</p>
<pre><code>self.driver.execute_script("document.getElementByLinktext('Level 1s').click;")
</code></pre>
| 0 | 2016-09-26T13:43:20Z | 39,704,800 | <p>You are <em>not calling</em> the <code>click()</code> method:</p>
<pre><code>self.driver.execute_script("document.getElementByLinktext('Level 1s').click();")
FIX HERE^
</code></pre>
<p>Note that you can also locate the element with selenium and the... | 1 | 2016-09-26T13:53:18Z | [
"python",
"selenium"
] |
How do I limit my users input to a single digit? (Python) | 39,704,616 | <p>I want my program to say 'invalid input' if 2 digits or more are entered so is there a way i can limit my users input to a single digit in python?</p>
<p>This is my code:</p>
<pre><code>print('List Maker')
tryagain = ""
while 'no' not in tryagain:
list = []
for x in range(0,10):
number = int(inpu... | 1 | 2016-09-26T13:46:00Z | 39,704,679 | <p>Use a <code>while</code> loop instead of a <code>for</code> loop, break out when you have 10 digits, and refuse to accept any number over 9:</p>
<pre><code>numbers = []
while len(numbers) < 10:
number = int(input("Enter a number: "))
if not 1 <= number <= 9:
print('Only numbers between 1 an... | 4 | 2016-09-26T13:48:32Z | [
"python"
] |
How do I limit my users input to a single digit? (Python) | 39,704,616 | <p>I want my program to say 'invalid input' if 2 digits or more are entered so is there a way i can limit my users input to a single digit in python?</p>
<p>This is my code:</p>
<pre><code>print('List Maker')
tryagain = ""
while 'no' not in tryagain:
list = []
for x in range(0,10):
number = int(inpu... | 1 | 2016-09-26T13:46:00Z | 39,705,108 | <p>There is another option for getting only one character, based on this previous <a href="http://stackoverflow.com/questions/27750536/python-input-single-character-without-enter">answer</a>:</p>
<pre><code>import termios
import sys, tty
def getch():
fd = sys.stdin.fileno()
old_settings = termi... | 0 | 2016-09-26T14:08:07Z | [
"python"
] |
Page not found (404) with Django | 39,704,623 | <p>I'm learning Django Framework and I'm following a tutorial based on Django 1.8.
I have Django 1.10 on my Mac OSX and I get an error : <code>Page not found</code></p>
<p>I started a project which is named <code>"Crepes_bretonnes"</code> and I created an app : <code>"Blog"</code>.</p>
<p>The blog urls.py looks like ... | 0 | 2016-09-26T13:46:22Z | 39,704,664 | <p>Your crepes_bretonnes urls are including blog urls, so your blog urls are only visible from <code>blog/</code> url. </p>
<p>If you want to get to your view you need to open this url:</p>
<p><code>/blog/accueil/</code></p>
| 1 | 2016-09-26T13:47:59Z | [
"python",
"django"
] |
Python: Problems with functions of imported dll | 39,704,642 | <p>A DLL for a device was imported into Python using ctypes "windll.LoadLibrary"
First, I wanted to use one function of the DLL which is to return the library version.
There came a header file with the DLL in which the function is defined like this:</p>
<pre><code> /** * \brief Returns the library version in the for... | 0 | 2016-09-26T13:47:09Z | 39,706,314 | <p>So a colleague helped me:
The function "JC_GetDllVersion()" manipulates the paramter it gets handed over and doesn't return a string.
But as a beginner I wasn't aware of that.</p>
| 0 | 2016-09-26T15:07:44Z | [
"python",
"dll",
"import"
] |
Python: For loop not working properly | 39,704,752 | <p>Why is the for loop not working properly? It's just returned only one element.</p>
<p>1.</p>
<pre><code>rx = ['abc', 'de fg', 'hg i']
def string_m(a=rx):
for i in a:
l = re.sub(" ","/",i)
r = l.split("/")
r.reverse()
rx = " ".join(r)
return rx
a=string_m(rx)
print(... | -6 | 2016-09-26T13:51:38Z | 39,705,062 | <pre><code>import re
rx = ['abc', 'de fg', 'hg i']
def string_m(a=rx):
new = []
for i in a:
l = re.sub(" ","/",i)
r = l.split("/")
#r.reverse()
rx = " ".join(r)
new.append(rx)
new.reverse()
return new
a=string_m(rx)
print(a)
</code></pre>
<p>Your biggest probl... | 0 | 2016-09-26T14:05:44Z | [
"python",
"django"
] |
Unknown format from Picamera recording | 39,704,846 | <p>I have been using my RaspberryPi 3 model B with the Picamera to record videos.
I saw in the RaspberryPi website that the default video format that you get from capturing video is h264, however when I use the camera, the file created appears as fyle type unknown.</p>
<p>To capture I tried both the basic command line... | 0 | 2016-09-26T13:55:20Z | 39,754,679 | <p>You're not specifiying the h264 extension - without that omxplayer doesn't know what type of video format it is - unless you can suggest what to try via command line</p>
<p>Try:</p>
<pre><code>raspivid -o video.h264 -t 10 #for a 10s video
</code></pre>
<p>There's plenty of online help and examples for raspivid</p... | 1 | 2016-09-28T18:05:22Z | [
"python",
"python-3.x",
"camera",
"raspberry-pi",
"raspberry-pi3"
] |
python reading in files for a specific column range | 39,704,877 | <p>I'm writing a script that reads in one file containing a list of files and performing gaussian fits on each of those files. Each of these files is made up of two columns (wv and flux in the script below). My small issue here is how do I limit the range based "wv" values? I tried using a "for" loop for this but I get... | 0 | 2016-09-26T13:56:55Z | 39,705,103 | <p>When you call <code>for wv in range(6450, 6575)</code>, <code>wv</code> is just an integer in that range, not a member of the list. I'd try taking a look at how you're using that variable. If you want to access data from the <code>list wv</code>, you would have to update the syntax to be <code>wv[wv]</code> (which i... | 0 | 2016-09-26T14:07:51Z | [
"python"
] |
How to reconstruct a list with punctuation into a sentence? In python 3.5 | 39,704,913 | <p>I have a list e.g. <code>['hello',', ','how','are','you','?']</code> and i want it to become <code>"hello, how are you?"</code>
Is there anyway at doing this?</p>
<p>I should also note that i am opening this from a text document, using the code:</p>
<pre><code> with gzip.open('task3.txt.gz', 'r+') as f:
rec... | 0 | 2016-09-26T13:58:35Z | 39,705,291 | <p>I believe, you're looking for <strong>join()</strong>:</p>
<pre><code>>>> a = ['hello',', ','how','are','you','?']
>>> " ".join(a)
'hello , how are you ?'
</code></pre>
<p>Note, that the content of quotation marks will be inserted in between of your words. So you need to decide, if you want to u... | 0 | 2016-09-26T14:16:44Z | [
"python",
"python-3.x"
] |
How to reconstruct a list with punctuation into a sentence? In python 3.5 | 39,704,913 | <p>I have a list e.g. <code>['hello',', ','how','are','you','?']</code> and i want it to become <code>"hello, how are you?"</code>
Is there anyway at doing this?</p>
<p>I should also note that i am opening this from a text document, using the code:</p>
<pre><code> with gzip.open('task3.txt.gz', 'r+') as f:
rec... | 0 | 2016-09-26T13:58:35Z | 39,705,673 | <p>You can actually properly <em>detokenize</em> the list of tokens back into a sentence with an <a href="https://github.com/nltk/nltk/pull/1282" rel="nofollow"><code>nltk</code>'s <code>moses</code> detokenizer</a> (available in the <code>nltk</code> trunk at the moment - has not been released yet):</p>
<pre><code>In... | 1 | 2016-09-26T14:35:46Z | [
"python",
"python-3.x"
] |
Regex Match equal amount of two characters | 39,704,916 | <p>I'ld like to match the parameters of any function as a string using regex. As an example lets assume the following string:</p>
<pre><code>predicate(foo(x.bar, predicate(foo(...), bar)), bar)
</code></pre>
<p>this may be part of a longer sequence</p>
<pre><code>predicate(foo(x.bar, predicate(foo(...), bar)), bar)p... | 1 | 2016-09-26T13:58:39Z | 39,705,887 |
<pre><code>import re
def parse(s):
pattern = re.compile(r'([^(),]+)|\s*([(),])\s*')
stack = []
state = 0 # 0 = before identifier, 1 = after identifier, 2 = after closing paren
current = None
args = []
for match in pattern.finditer(s):
if match.group(1):
if state != 0:
... | 1 | 2016-09-26T14:47:17Z | [
"python",
"regex",
"first-order-logic"
] |
Regex Match equal amount of two characters | 39,704,916 | <p>I'ld like to match the parameters of any function as a string using regex. As an example lets assume the following string:</p>
<pre><code>predicate(foo(x.bar, predicate(foo(...), bar)), bar)
</code></pre>
<p>this may be part of a longer sequence</p>
<pre><code>predicate(foo(x.bar, predicate(foo(...), bar)), bar)p... | 1 | 2016-09-26T13:58:39Z | 39,706,795 | <p>You can create a regex to find all of the function calls within your code. Something like this:</p>
<pre><code>([_a-zA-Z]+)(?=\()
</code></pre>
<p>Then using the <code>re</code> module, you create a data structure indexing the function calls within your code.</p>
<pre><code>import re
code = 'predicate(foo(x.bar,... | 1 | 2016-09-26T15:30:29Z | [
"python",
"regex",
"first-order-logic"
] |
Regex Match equal amount of two characters | 39,704,916 | <p>I'ld like to match the parameters of any function as a string using regex. As an example lets assume the following string:</p>
<pre><code>predicate(foo(x.bar, predicate(foo(...), bar)), bar)
</code></pre>
<p>this may be part of a longer sequence</p>
<pre><code>predicate(foo(x.bar, predicate(foo(...), bar)), bar)p... | 1 | 2016-09-26T13:58:39Z | 39,731,679 | <p>Adding the <a href="https://pypi.python.org/pypi/regex" rel="nofollow">PyPI package regex</a>, as @Tim Pietzcker suggested, you can use <a href="http://www.regular-expressions.info/recurse.html" rel="nofollow">recursive regexes</a>.</p>
<pre><code>>>> import regex
>>> s = 'predicate(foo(x.bar, pre... | 1 | 2016-09-27T18:16:57Z | [
"python",
"regex",
"first-order-logic"
] |
Disable SSL certificate check Twisted Agents | 39,704,932 | <p>I am using Twisted (16.3) and Treq (15.1) to make async requests in Python (2.7). </p>
<p>I am having issues with some requests over HTTPS.</p>
<p>Some sites have an invalid certificate and thus when making a request to them, I get this:</p>
<pre><code>twisted.python.failure.Failure OpenSSL.SSL.Error
</code></pre... | 0 | 2016-09-26T13:59:49Z | 39,709,525 | <p>I've been trying to do this too over the past few days as well. With all the effort I put into circumventing certificate verification, I could've easily just created a pair of keys and been on my merry way :D. I found <a href="https://github.com/twisted/treq/issues/65#issuecomment-249034981" rel="nofollow">this comm... | 0 | 2016-09-26T18:07:41Z | [
"python",
"ssl",
"twisted",
"twisted.web",
"twisted.internet"
] |
xlsxwriter conditional format: find the exactly value | 39,704,954 | <p>this is my code:</p>
<pre><code> import xlsxwriter
for val in arr:
sheet.conditional_format('B2:B2000', {'type': 'text',
'criteria': 'containingwith',
'value': val,
'f... | 1 | 2016-09-26T14:00:45Z | 39,707,439 | <p>Something like the following should work:</p>
<pre><code>worksheet1.conditional_format('B2:K12', {'type': 'cell',
'criteria': '==',
'value': '"aa"',
'format': format1})
</code></pre>
... | 0 | 2016-09-26T16:03:30Z | [
"python"
] |
Dictionary Print Out All Word Of What I Type In | 39,704,969 | <p>I need to create a program which prints out all the word in the dictionary that I wrote, So let's say I write house, It could come out like</p>
<blockquote>
<p>home, house, high, hollow, out, over, overrated, on, united, untitled, urgent, song, silent, silence, sorry, emotion, elf, egg, end</p>
</blockquote>
<p>... | -3 | 2016-09-26T14:01:24Z | 39,706,673 | <p>Maybe not a crisp solution, but an approach and an explanation that is longer for a comment: </p>
<p>Before you could get all the words that match a particular word someone gives to your program, you need to classify the words in your file into categories and establish mappings. That is, it should be established so... | 1 | 2016-09-26T15:24:42Z | [
"python",
"project"
] |
Looping over pandas data frame applying formula to each value | 39,705,022 | <p>I have the following pandas data frame:</p>
<pre><code> PC1 PC2 PC3 PC4 PC5 PC6 PC7
ind
NA06984 -0.0082 -0.0594 -0.0148 -0.0569 -0.1128 -0.0276 -0.0217
NA06986 -0.0131 -0.0659 -0.0426 0.0654 0.0473 0.0603 -... | 2 | 2016-09-26T14:03:33Z | 39,705,072 | <p>You can just do the following:</p>
<pre><code>In [19]:
(df - df.mean())/df.std()
Out[19]:
PC1 PC2 PC3 PC4 PC5 PC6 PC7
ind
NA06984 0.343471 -0.576088 0.439607 -0.671001 -1.859402 -1.013059 -... | 3 | 2016-09-26T14:06:29Z | [
"python",
"loops",
"pandas",
"dataframe"
] |
Combine json file with CSV- similar to vlookup | 39,705,088 | <p>In plain terms, I'm trying to combine two sets of data. I'm open to use grep/bash or python.</p>
<ol>
<li><p>Read directory /mediaid</p></li>
<li><p>Read the .json files' filename</p></li>
<li><p>if the .json file name matches a row in the .csv, copy the contents of the json file in that row (if not, just skip)</p>... | 1 | 2016-09-26T14:07:16Z | 39,705,777 | <p>This provides your required output:</p>
<pre class="lang-bsh prettyprint-override"><code>for file in /mediaid/*; do
while read -r entry fileid; do
jsonfile="$fileid.json"
if [[ -f "$jsonfile" ]]; then
text=$(jq -r 'map(.text) | join(", ")' "$jsonfile")
echo "$entry $fil... | 1 | 2016-09-26T14:41:06Z | [
"python",
"json",
"bash",
"csv",
"grep"
] |
Adjusting nested dictionary depending on provided key values | 39,705,093 | <p>I would like to create the following dictionary based on various parameters given by <code>params</code>. Now I do not want to add keys which provide no value. So for instance if <code>params['ean']</code> is blank or does not exist I want to exclude the entire line <code>"EAN": params['ean']</code>. Any suggestions... | 0 | 2016-09-26T14:07:30Z | 39,705,260 | <p>I don't think i understand the question perfectly but how about something like that:</p>
<pre><code>myitem = {}
myitem['Item'] = {"Description": "Some Text"}
for keys in ['title', 'category_id', 'isbn', 'ean']:
if params[keys]:
myitem['Item'].append({keys.upper(): params[keys]})
</code></pre>
<p>which ... | 1 | 2016-09-26T14:15:20Z | [
"python",
"dictionary",
"conditional"
] |
Adjusting nested dictionary depending on provided key values | 39,705,093 | <p>I would like to create the following dictionary based on various parameters given by <code>params</code>. Now I do not want to add keys which provide no value. So for instance if <code>params['ean']</code> is blank or does not exist I want to exclude the entire line <code>"EAN": params['ean']</code>. Any suggestions... | 0 | 2016-09-26T14:07:30Z | 39,705,334 | <p><strong>If you can change the way you create the dict</strong> just user dict comprehension:</p>
<pre><code>myitem = {k: v for k, v in params.items() if v}
</code></pre>
<p>If you already have the dict in first place and you <strong>can't change the initialization</strong> of it, you can delete the empty values li... | 1 | 2016-09-26T14:18:28Z | [
"python",
"dictionary",
"conditional"
] |
Adjusting nested dictionary depending on provided key values | 39,705,093 | <p>I would like to create the following dictionary based on various parameters given by <code>params</code>. Now I do not want to add keys which provide no value. So for instance if <code>params['ean']</code> is blank or does not exist I want to exclude the entire line <code>"EAN": params['ean']</code>. Any suggestions... | 0 | 2016-09-26T14:07:30Z | 39,705,516 | <p>I think the following code does what you are looking for.</p>
<pre><code>d = {}
def addItem(name, description, params):
d[name] = {}
if 'title' in params:
d[name]['Title'] = params['title']
if 'category_id' in params:
d[name]['PrimaryCategory'] = {"CategoryID" : params['category_id']}
... | 1 | 2016-09-26T14:28:39Z | [
"python",
"dictionary",
"conditional"
] |
Python - Merge data from multiple thread instances | 39,705,131 | <p>I am currently working on a project that involves connecting two devices to a python script, retrieving data from them and outputting the data. </p>
<p>Code outline:</p>
<p>⢠Scans for paired devices</p>
<p>⢠Paired device found creates thread instance (Two devices connected = two thread instances )</p>
... | 0 | 2016-09-26T14:09:12Z | 39,705,375 | <p>My general advice: Avoid using any of these things </p>
<ul>
<li>avoid threads</li>
<li>avoid the multiprocessing module in Python</li>
<li>avoid the futures module in Python.</li>
</ul>
<p>Use a tool like <a href="http://python-rq.org/" rel="nofollow">http://python-rq.org/</a></p>
<p>Benefit:</p>
<ul>
<li>You n... | -1 | 2016-09-26T14:20:27Z | [
"python",
"multithreading"
] |
Python - Merge data from multiple thread instances | 39,705,131 | <p>I am currently working on a project that involves connecting two devices to a python script, retrieving data from them and outputting the data. </p>
<p>Code outline:</p>
<p>⢠Scans for paired devices</p>
<p>⢠Paired device found creates thread instance (Two devices connected = two thread instances )</p>
... | 0 | 2016-09-26T14:09:12Z | 39,705,451 | <p>I assume you are using the <code>threading</code> module.</p>
<h2>Threading in Python</h2>
<p>Python is not multithreaded for CPU activity. The interpreter still uses a GIL (Global Interpreter Lock) for most operations and therefore linearizing operations in a python script. Threading is good to do IO however, as ... | 3 | 2016-09-26T14:24:46Z | [
"python",
"multithreading"
] |
loss function as min of several points, custom loss function and gradient | 39,705,175 | <p>I am trying to predict quality of metal coil. I have the metal coil with width 10 meters and length from 1 to 6 kilometers. As training data I have ~600 parameters measured each 10 meters, and final quality control mark - good/bad (for whole coil). Bad means there is at least 1 place there is coil is bad, there is n... | 2 | 2016-09-26T14:11:10Z | 39,712,223 | <p>What you are considering here is known in machine learning community as <strong>superset learning</strong>, meaning, that instead of typical supervised setting where you have training set in the form of {(x_i, y_i)} you have {({x_1, ..., x_N}, y_1)} such that you know that at least one element from the set has prope... | 1 | 2016-09-26T20:55:14Z | [
"python",
"machine-learning",
"scikit-learn",
"gradient-descent"
] |
Add annotation in an interactive plot | 39,705,211 | <p>I m trying to add an annotation at the middle of my interactive plot
I would like to see my <em>i</em> value of the loop generating my <em>test</em> list
with all my data. For each imshow plot, i would like to see my <em>i</em> value,
i add an ax.annotate but it doesnt work.</p>
<pre><code>import numpy as np
import... | 0 | 2016-09-26T14:12:32Z | 39,752,300 | <p>I have found a way out. I added a "set_text" inside my update function and i return picture and text : </p>
<pre><code> test = []
test2 = []
for i in range(3,27,3):
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(i,i))
res = (cv2.morphologyEx(mask2,cv2.MORPH_OPEN,kernel))
#plt.imshow(res,cmap=plt.cm.gray... | 0 | 2016-09-28T15:53:39Z | [
"python",
"numpy",
"matplotlib",
"annotations",
"interactive"
] |
Django REST framework without model | 39,705,370 | <p>I want to use Django REST framework to create an API to call different methods. I read the guide of [django-rest-framework][1] to work with this framework, but I still have some questions.</p>
<p>I have no model I get my data from an external database. I want to try first something simple:</p>
<ul>
<li>Get all lis... | -1 | 2016-09-26T14:20:09Z | 39,708,239 | <p>From docs <a href="http://www.django-rest-framework.org/tutorial/1-serialization/#creating-a-serializer-class" rel="nofollow">here</a>.You don't have to have a model for create a Serializer class.You can define some serializers field then use them. You should not import CPUProjectsViewSet and also define it in below... | 0 | 2016-09-26T16:49:35Z | [
"python",
"django",
"django-rest-framework"
] |
Searching two of the three characters in python | 39,705,378 | <pre><code> info=('x','y','z')
info2=('x','Bob','y')
match=False
if any(all x in info for x in info2):
match=True
print("True")
else:
print("False")
</code></pre>
<p>Is that is there a way I can make it work so that it only prints <code>True</code> when <code>x</code> and either <code>y</code> or <cod... | 0 | 2016-09-26T14:20:31Z | 39,705,467 | <p>The way I read this you want the first element in <code>info</code> (<code>info[0]</code>), and at least one other element in <code>info</code> to be in <code>info2</code></p>
<pre><code> if info[0] in info2 and any(i in info2 for i in info[1:]):
# do stuff
</code></pre>
| 2 | 2016-09-26T14:25:39Z | [
"python",
"python-3.4"
] |
python urllib2.urlopen returns error 500 while Chrome loads the page | 39,705,579 | <p>I have a web-page (<a href="http://rating.chgk.info/api/tournaments/3506/" rel="nofollow">http://rating.chgk.info/api/tournaments/3506/</a>) I want to open in Python 2 via urllib2. It opens perfectly well in my browser but when I do this:</p>
<pre><code>import urllib2
url = 'http://rating.chgk.info/api/tournaments/... | 0 | 2016-09-26T14:31:48Z | 39,705,891 | <p>You need to first visit the page on the site to get the session cookie set:</p>
<pre><code>In [7]: import requests
In [8]: requests.get("http://rating.chgk.info/api/tournaments/3506")
Out[8]: <Response [500]>
In [9]: with requests.Session() as session:
...: session.get("http://rating.chgk.info/index... | 1 | 2016-09-26T14:47:25Z | [
"python",
"web-scraping",
"urllib2"
] |
How to get __lt__() to sort | 39,705,660 | <pre><code>class City:
def __init__(self, string):
self._string = string.split(',')
self._name = self._string[0]
self._state = self._string[1]
self._latitude = self._string[2]
self._longitude = self._string[3]
self._location = [self._latitude, self._longitude]
de... | 0 | 2016-09-26T14:35:11Z | 39,705,829 | <p>You are comparing your longitude and latitude as <em>strings</em>, not numbers. They are therefor compared lexicographically, not numerically, so <code>'104'</code> will sort <em>before</em> <code>'80'</code> because <code>'1'</code> comes before <code>'8'</code> in the ASCII table (it doesn't matter what other char... | 6 | 2016-09-26T14:43:33Z | [
"python",
"python-3.x",
"sorting"
] |
Yielding multiple starting point requests with scrapy | 39,705,692 | <p>I am working with the following code ( simplified):</p>
<pre><code>def parse(self, response):
print('hello')
for x in xrange(8):
print x
random_form_page = session.query(....
PR = Request(
'htp://my-api',
headers=self.headers,
meta={'newreques... | 0 | 2016-09-26T14:36:44Z | 39,705,732 | <p>You should be using <a href="http://doc.scrapy.org/en/latest/topics/spiders.html#scrapy.spiders.Spider.start_requests" rel="nofollow"><code>start_requests()</code> method</a> instead of <code>parse()</code>:</p>
<pre><code>def start_requests(self):
for x in xrange(8):
random_form_page = session.query(.... | 2 | 2016-09-26T14:38:56Z | [
"python",
"scrapy"
] |
Checking user group membership in permission_required | 39,705,707 | <p>How would I check if a user is a part of a group inside the <code>permission_required</code> decorator?</p>
<p>This is what I have currently but it doesn't seem to check it..</p>
<pre><code>@permission_required(['user.is_super_user', "'NormalUser' in user.groups.all"], raise_exception=True)
</code></pre>
<p>This ... | 0 | 2016-09-26T14:37:24Z | 39,705,953 | <p>You should use <a href="https://docs.djangoproject.com/en/1.10/topics/auth/default/#django.contrib.auth.decorators.user_passes_test" rel="nofollow"><code>user_passes_test</code></a> for this. The <code>permission_required</code> decorator checks permissions. It doesn't make sense to use it here.</p>
<p>First, you n... | 1 | 2016-09-26T14:50:04Z | [
"python",
"django",
"python-2.7",
"django-admin",
"django-views"
] |
Checking user group membership in permission_required | 39,705,707 | <p>How would I check if a user is a part of a group inside the <code>permission_required</code> decorator?</p>
<p>This is what I have currently but it doesn't seem to check it..</p>
<pre><code>@permission_required(['user.is_super_user', "'NormalUser' in user.groups.all"], raise_exception=True)
</code></pre>
<p>This ... | 0 | 2016-09-26T14:37:24Z | 39,706,004 | <p>I don't believe you can pass a perm check like the latter in your list, that's essentially trying to execute some python code, which won't work.</p>
<p>It would be handy to understand what your use case actually is, but if you strictly only want to use the permission_required decorator (instead of very simply creat... | 1 | 2016-09-26T14:52:49Z | [
"python",
"django",
"python-2.7",
"django-admin",
"django-views"
] |
Using third-party Python module that blocks Flask application | 39,705,729 | <p>My application that uses websockets also makes use of several third-party Python modules that appear to be written in way that blocks the rest of the application when called. For example, I use <b>xlrd</b> to parse Excel files a user has uploaded.</p>
<p>I've monkey patched the builtins like this in the first lines... | 1 | 2016-09-26T14:38:46Z | 39,723,635 | <ul>
<li>First you should try thread pool [1].</li>
<li>If that doesn't work as well as you want, please submit an issue [2] and go with multiprocessing as workaround.</li>
</ul>
<p><code>eventlet.tpool.execute(xlrd_read, file_path, other=arg)</code></p>
<blockquote>
<p>Execute meth in a Python thread, blocking the... | 0 | 2016-09-27T11:36:02Z | [
"python",
"flask",
"eventlet",
"flask-socketio"
] |
Iterate over Python list and convert Python date to human readable string | 39,705,756 | <p>I have a python list that stores IP addresses, hostnames and dates.</p>
<p>I need to iterate over this list and convert the python dates to human readable dates.</p>
<p>How can I iterate over the list and convert the dates to human readable strings?</p>
<p>List:</p>
<pre><code>{'_id': '192.168.1.5', '192.168.1.5... | -1 | 2016-09-26T14:40:24Z | 39,705,821 | <p>Simply iterate by the list and modify / add datetime to human-readable:</p>
<pre><code>for row_id, row in enumerate(your_list):
your_list[row_id]['human_readable_date'] = row['u_updated_timestamp'].strftime("specify-your-format")
</code></pre>
<p>You can find datetime formats <a href="https://docs.python.org/2... | 1 | 2016-09-26T14:43:05Z | [
"python"
] |
Iterate over Python list and convert Python date to human readable string | 39,705,756 | <p>I have a python list that stores IP addresses, hostnames and dates.</p>
<p>I need to iterate over this list and convert the python dates to human readable dates.</p>
<p>How can I iterate over the list and convert the dates to human readable strings?</p>
<p>List:</p>
<pre><code>{'_id': '192.168.1.5', '192.168.1.5... | -1 | 2016-09-26T14:40:24Z | 39,705,861 | <p>If those are real python datetime.date objects you can simply call</p>
<pre><code>date.isoformat()
</code></pre>
<p>This should return '2016-26-09' (today).
Your 'list' does not look like a list tho...</p>
| 0 | 2016-09-26T14:45:42Z | [
"python"
] |
Scrapy - running spider from a python script | 39,705,892 | <p>I am trying to run scrapy from a <code>python</code> script according to documentation <a href="http://scrapy.readthedocs.io/en/0.16/topics/practices.html" rel="nofollow">http://scrapy.readthedocs.io/en/0.16/topics/practices.html</a></p>
<pre><code>def CrawlTest():
spider = PitchforkSpider(domain='"pitchfork.c... | 0 | 2016-09-26T14:47:26Z | 39,705,942 | <p>You are looking at Scrapy 0.16 docs but using Scrapy 1.1.2. </p>
<p>Here is the <a href="http://scrapy.readthedocs.io/en/latest/topics/practices.html#run-scrapy-from-a-script" rel="nofollow">correct documentation page</a>.</p>
<p>FYI, you should now be using <code>CrawlerProcess</code> or <code>CrawlerRunner</code... | 0 | 2016-09-26T14:49:38Z | [
"python",
"web-scraping",
"scrapy"
] |
CrawlerProcess vs CrawlerRunner | 39,706,005 | <p><a href="http://scrapy.readthedocs.io/en/latest/topics/practices.html#run-scrapy-from-a-script" rel="nofollow">Scrapy 1.x documentation</a> explains that there are two ways to <em>run a Scrapy spider from a script</em>:</p>
<ul>
<li>using <a href="http://scrapy.readthedocs.io/en/latest/topics/api.html#scrapy.crawle... | 3 | 2016-09-26T14:52:58Z | 39,706,311 | <p>CrawlerRunner:</p>
<blockquote>
<p>This class shouldnât be needed (since Scrapy is responsible of using it accordingly) unless writing scripts that manually handle the crawling process. See Run Scrapy from a script for an example.</p>
</blockquote>
<p>CrawlerProcess:</p>
<blockquote>
<p>This utility should ... | 0 | 2016-09-26T15:07:40Z | [
"python",
"web-scraping",
"scrapy"
] |
CrawlerProcess vs CrawlerRunner | 39,706,005 | <p><a href="http://scrapy.readthedocs.io/en/latest/topics/practices.html#run-scrapy-from-a-script" rel="nofollow">Scrapy 1.x documentation</a> explains that there are two ways to <em>run a Scrapy spider from a script</em>:</p>
<ul>
<li>using <a href="http://scrapy.readthedocs.io/en/latest/topics/api.html#scrapy.crawle... | 3 | 2016-09-26T14:52:58Z | 39,708,960 | <p>Scrapy's documentation does a pretty bad job at giving examples on real applications of both.</p>
<p><code>CrawlerProcess</code> assumes that scrapy is the only thing that is going to use twisted's reactor. If you are using threads in python to run other code this isn't always true. Let's take this as an example.</... | 2 | 2016-09-26T17:31:26Z | [
"python",
"web-scraping",
"scrapy"
] |
input output floating number issue python | 39,706,011 | <p>Python seems to do funny things to floating point numbers, it produces different floating point numbers from the input i give it, i would like the floating numbers to stay the same as the input. </p>
<p>here i have a small test dataset:</p>
<pre><code>import pandas as pd
df = {'ID': ['H1','H2','H3','H4','H5','H6'... | 1 | 2016-09-26T14:53:22Z | 39,706,083 | <p>Floats are weird: <a href="https://ece.uwaterloo.ca/~dwharder/NumericalAnalysis/02Numerics/Double/paper.pdf" rel="nofollow">https://ece.uwaterloo.ca/~dwharder/NumericalAnalysis/02Numerics/Double/paper.pdf</a></p>
<p>It's not uncommon to see peculiar looking behavior out of them. If you're not doing any calculations... | 0 | 2016-09-26T14:57:01Z | [
"python",
"floating-point"
] |
Database query count | 39,706,074 | <p>I am trying to create a program that will iterate through a data base to match a query for "_75" and set the count to 0 when that match is made. For every records in a database that does not match the query I would like for it to accumulate a negative 1 count. No matter how I try the code I get either the total reco... | -1 | 2016-09-26T14:56:43Z | 39,706,677 | <p>Change your query to return a count rather than counting in the python code
For example</p>
<pre><code>SELECT COUNT(CustomerID) AS OrdersFromCustomerID7 FROM Orders WHERE CustomerID=7;
</code></pre>
<p><a href="http://www.w3schools.com/sql/sql_func_count.asp" rel="nofollow">Source</a></p>
<p>Query to count the nu... | 0 | 2016-09-26T15:24:58Z | [
"python",
"python-3.x",
"sqlite3"
] |
Return 400 when login to a website using python requests | 39,706,134 | <p>I am trying to write a python script to login to a website using the requests library.
This is the login form.</p>
<pre><code><form action="/login" method="POST"><input type="hidden" name="post_key" value="b762c617d52cf987fdb40d74c6a04e07"><input type="hidden" name="return_to" value="http://www.pixiv... | 1 | 2016-09-26T14:58:51Z | 39,706,266 | <p>When I log in and look into browser developer tools I see much more POST request parameters being sent after clicking "log in":</p>
<p><a href="http://i.stack.imgur.com/dmaNZm.png" rel="nofollow"><img src="http://i.stack.imgur.com/dmaNZm.png" alt="enter image description here"></a> </p>
<p><code>requests</code> wo... | 1 | 2016-09-26T15:05:41Z | [
"python",
"http",
"login",
"python-requests"
] |
I can send emails, but not replies with smtplib and GMail | 39,706,158 | <p>I'm making a program that replies automatically to emails on my GMail account. I can send mails just fine, but I can't seem to reply to them. I'm using <code>smtplib</code>.</p>
<p>This is the code I use for sending plain mails (suppose that <code>[email protected]</code> is my personal email):</p>
<pre><code># par... | 0 | 2016-09-26T15:00:31Z | 39,707,698 | <p>The options are not to be passed as an argument, but for whatever reason they actually belong in the message. Here is an example:</p>
<pre><code>msg = MIMEMultipart("mixed")
body = MIMEMultipart("alternative")
body.attach(MIMEText(text, "plain"))
body.attach(MIMEText("<html>" + text + "</html>", "html")... | 0 | 2016-09-26T16:18:27Z | [
"python",
"email",
"smtp",
"gmail"
] |
i'm trying to make a 2 players racing game with pygame and event.key don't work | 39,706,164 | <p>I'm trying to make a 2-player racing game, and when I try to add the <code>event.key == pygame.K_LEFT</code> it says <code>AttributeError: 'Event' object has no attribute 'key'</code>.</p>
<p>I have tried many things as adding <code>()</code>, but nothing fixed it and I have no clue about it.</p>
<p>Code:</p>
<pr... | 3 | 2016-09-26T15:00:42Z | 39,706,264 | <pre><code>if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
xone_change = -5
elif event.key == pygame.K_RIGHT: #indented to be part of the keydown events
xone_change = 5
</code></pre>
<p>You want this. Your indentation was wrong. </p>
<p>You had <code>elif event.key == pygame.K_... | 1 | 2016-09-26T15:05:35Z | [
"python",
"pygame"
] |
i'm trying to make a 2 players racing game with pygame and event.key don't work | 39,706,164 | <p>I'm trying to make a 2-player racing game, and when I try to add the <code>event.key == pygame.K_LEFT</code> it says <code>AttributeError: 'Event' object has no attribute 'key'</code>.</p>
<p>I have tried many things as adding <code>()</code>, but nothing fixed it and I have no clue about it.</p>
<p>Code:</p>
<pr... | 3 | 2016-09-26T15:00:42Z | 39,712,446 | <p>The reason why you're getting an error is because different events have different attributes. You can check which event has which attributes at the <a class='doc-link' href="http://stackoverflow.com/documentation/pygame/5110/event-handling/18046/event-loop#t=201609262052092301037">Stackoverflow pygame documentation<... | 1 | 2016-09-26T21:10:26Z | [
"python",
"pygame"
] |
Update a null values in countrycode column in a data frame by matching substring of country name using python | 39,706,194 | <p>I have two data frames: Disaster, CountryInfo Disaster has a column country code which has some null values for example: </p>
<p>Disaster:</p>
<pre><code> 1.**Country** - **Country_code**
2.India - Null
3.Afghanistan (the) - AFD
4.India - IND
... | 0 | 2016-09-26T15:02:17Z | 39,709,167 | <p>This should do it. You need to change the column names with <code>rename</code> so that both <code>dataframes</code> have the same column names. Then, the <code>difflib</code> module and its <code>get_close_matches</code> method can be used to do a fuzzy match and replace of <code>Country</code> names. Then it is a ... | 0 | 2016-09-26T17:44:01Z | [
"python",
"python-2.7",
"pandas"
] |
Unable to create disk from snapshot using google cloud engine API | 39,706,233 | <p>I'm trying to create a disk from a snapshot using google cloud python API:</p>
<pre><code>def createDisk(compute, project, zone):
config = {
'name': disk_name
}
return compute.disks().insert(
project=project,
zone=zone,
sourceSnapshot='global/snapshots/' + snap_name,
body=config).execute(... | 0 | 2016-09-26T15:04:25Z | 39,851,976 | <p>It came out that <code>sourceSnapshot</code> should be part of the body request, not an argument. So that would work:</p>
<pre><code>def createDisk(compute, project, zone):
config = {
'name': disk_name,
'sourceSnapshot': 'global/snapshots/' + snap_name,
}
return compute.disks().insert(
project=pr... | 0 | 2016-10-04T12:11:15Z | [
"python",
"google-cloud-platform"
] |
P value for Normality test very small despite normal histogram | 39,706,242 | <p>I've looked over the normality tests in scipy stats for both <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.stats.mstats.normaltest.html" rel="nofollow">scipy.stats.mstats.normaltest</a> as well as <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.shapiro.html" rel="... | 2 | 2016-09-26T15:04:45Z | 39,717,961 | <p>If the numbers on the vertical axis are the number of observations for the respective class, then the sample size is about 1500. For such a large sample size goodness-of-fit tests are rarely useful. But is it really necessary that your data is perfectly normally distributed? If you want to analyze the data with a st... | 0 | 2016-09-27T06:55:31Z | [
"python",
"numpy",
"scipy",
"statistics"
] |
Custom list of lists into dictionary | 39,706,256 | <p>I have list of lists and I wish to create a dictionary with length of each element as values. I tried the following:</p>
<pre><code>tmp = [['A', 'B', 'E'], ['B', 'E', 'F'], ['A', 'G']]
tab = []
for line in tmp:
tab.append(dict((k, len(tmp)) for k in line))
</code></pre>
<p>But it gives the output as:</p>
<pre... | 0 | 2016-09-26T15:05:11Z | 39,706,326 | <p>You can't use <code>list</code> objects as dictionary keys, they are mutable and unhashable. You can convert them to tuple. Also note that you are looping over each sub list. You can use a generator expression by only looping over the main list:</p>
<pre><code>In [3]: dict((tuple(sub), len(sub)) for sub in tmp)
Out... | 3 | 2016-09-26T15:08:15Z | [
"python",
"python-2.7",
"dictionary"
] |
Custom list of lists into dictionary | 39,706,256 | <p>I have list of lists and I wish to create a dictionary with length of each element as values. I tried the following:</p>
<pre><code>tmp = [['A', 'B', 'E'], ['B', 'E', 'F'], ['A', 'G']]
tab = []
for line in tmp:
tab.append(dict((k, len(tmp)) for k in line))
</code></pre>
<p>But it gives the output as:</p>
<pre... | 0 | 2016-09-26T15:05:11Z | 39,706,482 | <pre><code>{tuple(t):len(t) for t in tmp}
</code></pre>
<p>Input : </p>
<pre><code>[['A', 'B', 'E'], ['B', 'E', 'F'], ['A', 'G']]
</code></pre>
<p>Output :</p>
<pre><code>{('A', 'G'): 2, ('A', 'B', 'E'): 3, ('B', 'E', 'F'): 3}
</code></pre>
<p>Dictionnary does not accept list as key, but tuple</p>
| 1 | 2016-09-26T15:15:04Z | [
"python",
"python-2.7",
"dictionary"
] |
Numpy: Why is difference of a (2,1) array and a vertical matrix slice not a (2,1) array | 39,706,277 | <p>Consider the following code:</p>
<pre><code>>>x=np.array([1,3]).reshape(2,1)
array([[1],
[3]])
>>M=np.array([[1,2],[3,4]])
array([[1, 2],
[3, 4]])
>>y=M[:,0]
>>x-y
array([[ 0, 2],
[-2, 0]])
</code></pre>
<p>I would intuitively feel this should give a (2,1) vector of zeros.</p>... | 1 | 2016-09-26T15:06:06Z | 39,706,689 | <p>Look at the shape of <code>y</code>. It is <code>(2,)</code>; 1d. The source array is (2,2), but you are selecting one column. <code>M[:,0]</code> not only selects the column, but removes that singleton dimension.</p>
<p>So we have for the 2 operations, this change in shape:</p>
<pre><code>M[:,0]: (2,2) => (... | 1 | 2016-09-26T15:25:42Z | [
"python",
"arrays",
"numpy"
] |
Numpy: Why is difference of a (2,1) array and a vertical matrix slice not a (2,1) array | 39,706,277 | <p>Consider the following code:</p>
<pre><code>>>x=np.array([1,3]).reshape(2,1)
array([[1],
[3]])
>>M=np.array([[1,2],[3,4]])
array([[1, 2],
[3, 4]])
>>y=M[:,0]
>>x-y
array([[ 0, 2],
[-2, 0]])
</code></pre>
<p>I would intuitively feel this should give a (2,1) vector of zeros.</p>... | 1 | 2016-09-26T15:06:06Z | 39,707,276 | <p><code>numpy.array</code> indexes such that a single value in any position collapses that dimension, while slicing retains it, even if the slice is only one element wide. This is completely consistent, for any number of dimensions:</p>
<pre><code>>> A = numpy.arange(27).reshape(3, 3, 3)
>> A[0, 0, 0].sha... | 1 | 2016-09-26T15:54:32Z | [
"python",
"arrays",
"numpy"
] |
Python MySQLdb connection to online database | 39,706,278 | <p>While I have no problems to connect to my localhost database that way:</p>
<pre><code>import MySQLdb
localdb = MySQLdb.connect( host="127.0.0.1",
user="root",
passwd="password",
db="events")
</code></pre>
<p>I... | 0 | 2016-09-26T15:06:07Z | 39,706,480 | <p>It sounds like <code>212.227.000.000/phpmyadmin</code> is the URL of PHPMyAdmin (the thing you open in the browser). If so, the database may not be hosted on the machine with IP 212.227.000.000. You should check how PHPMyAdmin connects to the database. If PHPMyAdmin connects to 127.0.0.1, that probably means the dat... | 1 | 2016-09-26T15:15:02Z | [
"python",
"mysql"
] |
Django-haystack search static content | 39,706,302 | <p>My Django 1.10 app provides a search functionality using Haystack + Elastic Search. It works great for models data, but I need to make it work for static content too (basically HTML files). </p>
<p>I was thinking on scrapping the content from the HTML files (BeautifulSoup?) and save them to the database, this way t... | 1 | 2016-09-26T15:07:14Z | 39,753,461 | <p>I forked the module haystack-static-pages and adapted it to my needs. Now is compatible with Django 1.10 + haystack 2.5 and support login to scrap logged pages :)</p>
<p>Updated version:
<a href="https://github.com/pisapapiros/haystack-static-pages" rel="nofollow">https://github.com/pisapapiros/haystack-static-page... | 0 | 2016-09-28T16:54:40Z | [
"python",
"django",
"django-haystack",
"static-files",
"html-content-extraction"
] |
How to delete record from table where field is equal to header? | 39,706,344 | <p>I have a sqlite table which contains duplicate headers which I would like to remove. This is my current statement.</p>
<pre><code>DELETE FROM table WHERE FIELD = "FIELD"
</code></pre>
<p>This statement, when executed, deletes the entire table.</p>
| 0 | 2016-09-26T15:08:54Z | 39,706,365 | <p>Don't use double quotes for strings!</p>
<pre><code>delete from table where field = 'field';
</code></pre>
<p>The SQL standard for string delimiters is single quotes. Sometimes double quotes are used, but they are also used as escape characters for column names. So your code was just <code>where field = field</c... | 5 | 2016-09-26T15:09:29Z | [
"python",
"sql",
"sqlite",
"sql-delete"
] |
Open a file in Sublime Text and wait until it is closed while Python script is running | 39,706,394 | <p>I want to open a file in Sublime Text while my Python script waits until I have <em>closed</em> the editor. I have tried <code>subprocess.check_call</code> and <code>subprocess.Popen</code>. However, the call ends after the file is opened, rather than waiting for the file to close. How can I wait until the file is... | 3 | 2016-09-26T15:10:59Z | 39,710,409 | <p>When you just call <code>subl parameters.py</code> it does not block the thread, but you can use the <code>-w</code> flag to do so. I.e. just call</p>
<pre class="lang-py prettyprint-override"><code>subprocess.Popen(["subl", "-w", "parameters.py"]).wait()
</code></pre>
<p>and it should work as requested.</p>
| 3 | 2016-09-26T19:01:53Z | [
"python",
"subprocess",
"sublimetext",
"popen"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.