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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Pandas + SQLite "cannot use index" error | 38,579,515 | <p>I am using pandas, sqlite, and sqlalchemy to search a bunch of strings for substrings. This project is inspired by <a href="https://plot.ly/python/big-data-analytics-with-pandas-and-sqlite/" rel="nofollow">this tutorial.</a></p>
<p>First, I create a sqlite database with one column of strings. Then I iterate through a separate file of strings and search for those strings in the database.</p>
<p>I have found the process to be slow, so I did some research and found that I needed to build an index on my column. When I followed the instructions provided <a href="http://stackoverflow.com/questions/3418127/text-search-too-slow-on-sqlite-db-on-tableview-on-iphone">here</a> in the sqlite shell, everything seemed to work just fine. </p>
<p>However, when I try to make an index in my python script, I get the "cannot use index" error.</p>
<pre><code>import pandas as pd
from sqlalchemy import create_engine # database connection
import datetime as dt
def load_kmer_db(disk_engine, chunk_size, encoding='utf-8'):
start = dt.datetime.now()
j = 0
index_start = 1
for df in pd.read_csv('fake.kmers.csv', chunksize=chunk_size, iterator=True, encoding=encoding):
df.index += index_start
j += 1
df.to_sql('data', disk_engine.raw_connection(), if_exists='append', index=True, index_label='kmer_index')
index_start = df.index[-1] + 1
def search_db_for_subsequence(disk_engine, sequence):
"""
:param disk_engine: Disk engine for database containing query sequences
:param sequence: Sequence for finding subsequences in the database
:return: A data frame with the subsequences of sequence
"""
return pd.read_sql_query("SELECT kmer FROM data INDEXED BY kmer_index WHERE '" + sequence + "' LIKE '%' || kmer || '%'", disk_engine)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('kmers', type=str, metavar='<kmer_file.txt>', help='text file with kmers')
parser.add_argument('reads', type=str, metavar='<reads.fastq>', help='Reads to filter by input kmers')
# Get the command line arguments.
args = parser.parse_args()
kmer_file = args.kmers
reads_file = args.reads
# Initialize database with filename 311_8M.db
disk_engine = create_engine('sqlite:///311_8M.db') # This requires ipython to be installed
load_kmer_db(disk_engine, 200)
#****** Try explicitly calling the create index command
#****** using the sqlite module.
import sqlite3
conn = sqlite3.connect('311_8M.db')
c = conn.cursor()
c.execute("CREATE INDEX kmer_index ON data(kmer);")
reads = SeqReader(reads_file)
for read in reads.parse_fastq():
count += 1
sequence = read[1]
df = search_db_for_subsequence(
disk_engine,
sequence
)
</code></pre>
<p>One can see that I first tried to create an index by passing the proper keyword arguments to the to_sql method. When I did that alone, I got an error stating that the index could not be found. Then I explicitly made the index through the sqlite3 module, which yielded the "cannot use index" error.</p>
<p>So now it appears that I have made my index, but for some reason, I am not able to use it. Why would that be? And how does one create an index using the pandas api instead of having to use the sqlite3 module?</p>
| 1 | 2016-07-26T00:50:16Z | 38,580,088 | <p>That error message "cannot use index" seems to relate to the <code>pd.read_sql_query()</code> call and not the part where you create the index directly using the sqlite3 module.</p>
<p>A query with <code>some_col LIKE '%[some term]%'</code> cannot use an index on <code>some_col</code>. Queries with <code>some_col LIKE '[some_term]%'</code> on the other hand can make use of an index on <code>some_col</code>.</p>
| 1 | 2016-07-26T02:16:42Z | [
"python",
"sqlite",
"pandas",
"sqlite3"
] |
nested dictionary sorting | 38,579,518 | <p>I've been trying to figure out how to sort these dictionaries: <code>d1</code> and <code>d2</code>inside the dictionary <code>d3</code>.</p>
<pre><code>d1 = {'eggs':1, 'cheese':1}
d2 = {'cake':1, 'cream':1}
d3 = {'breakfast':{},'dessert':{}}
d3['breakfast'] = d1
d3['dessert'] = d2
for k,v in sorted(d3.items()):
for k,v in sorted(d3['breakfast'].items()):
for k,v in sorted(d3.items()):
print(k,v)
</code></pre>
<p>This is the output:</p>
<pre><code>breakfast {'eggs': 1, 'cheese': 1}
dessert {'cream': 1, 'cake': 1}
breakfast {'eggs': 1, 'cheese': 1}
dessert {'cream': 1, 'cake': 1}
breakfast {'eggs': 1, 'cheese': 1}
dessert {'cream': 1, 'cake': 1}
breakfast {'eggs': 1, 'cheese': 1}
dessert {'cream': 1, 'cake': 1}
</code></pre>
<p>It sorts the two <code>breakfast</code> and <code>dessert</code> correctly, then inside <code>dessert</code>, <code>'cream'</code> and <code>'eggs'</code> are in the wrong order.</p>
<p>It should be:</p>
<pre><code>dessert {'cake':1, 'cream':1}
</code></pre>
<p>and it also prints the "sorted" dictionary <code>d3</code> four times, and I'm not exactly sure why. </p>
<p>For all I know, there could be a more effective way to be doing this, so any information is welcome.</p>
| 0 | 2016-07-26T00:50:32Z | 38,579,555 | <p>So your algorithm has a few problems, mostly that you're nesting way too many times and looping over the same thing each time. Here's a better algorithm:</p>
<pre><code>for k,v in sorted(d3.items()):
print(k + ":")
for k2,v2 in sorted(v.items()):
print("\t" + k2 + ", " + str(v2))
</code></pre>
<p>It formats the answer like this:</p>
<pre><code>breakfast:
cheese, 1
eggs, 1
dessert:
cake, 1
cream, 1
</code></pre>
<p>I wasn't sure what your intended format is - hopefully you can modify it to be what you'd like. As you can see, this time the loop iterates first over d3, <strong>then over the elements of d3</strong>, rather than d3 again. This means that you'll go another level deep in the nested dictionary, rather than what you were doing before which was printing the same dictionary multiple times.</p>
| 2 | 2016-07-26T00:55:48Z | [
"python",
"sorting",
"python-3.x",
"dictionary"
] |
nested dictionary sorting | 38,579,518 | <p>I've been trying to figure out how to sort these dictionaries: <code>d1</code> and <code>d2</code>inside the dictionary <code>d3</code>.</p>
<pre><code>d1 = {'eggs':1, 'cheese':1}
d2 = {'cake':1, 'cream':1}
d3 = {'breakfast':{},'dessert':{}}
d3['breakfast'] = d1
d3['dessert'] = d2
for k,v in sorted(d3.items()):
for k,v in sorted(d3['breakfast'].items()):
for k,v in sorted(d3.items()):
print(k,v)
</code></pre>
<p>This is the output:</p>
<pre><code>breakfast {'eggs': 1, 'cheese': 1}
dessert {'cream': 1, 'cake': 1}
breakfast {'eggs': 1, 'cheese': 1}
dessert {'cream': 1, 'cake': 1}
breakfast {'eggs': 1, 'cheese': 1}
dessert {'cream': 1, 'cake': 1}
breakfast {'eggs': 1, 'cheese': 1}
dessert {'cream': 1, 'cake': 1}
</code></pre>
<p>It sorts the two <code>breakfast</code> and <code>dessert</code> correctly, then inside <code>dessert</code>, <code>'cream'</code> and <code>'eggs'</code> are in the wrong order.</p>
<p>It should be:</p>
<pre><code>dessert {'cake':1, 'cream':1}
</code></pre>
<p>and it also prints the "sorted" dictionary <code>d3</code> four times, and I'm not exactly sure why. </p>
<p>For all I know, there could be a more effective way to be doing this, so any information is welcome.</p>
| 0 | 2016-07-26T00:50:32Z | 38,581,095 | <pre><code>d1 = {'eggs':1, 'cheese':1}
d2 = {'cake':1, 'cream':1}
d3 = {'breakfast':{},'dessert':{}}
d3['breakfast'] = d1
d3['dessert'] = d2
for key,val in sorted(d3.items()):
print(key,val)
</code></pre>
| 0 | 2016-07-26T04:37:06Z | [
"python",
"sorting",
"python-3.x",
"dictionary"
] |
pandas equivalent of np.where | 38,579,532 | <p><code>np.where</code> has the semantics of a vectorized if/else (similar to Apache Spark's <code>when</code>/<code>otherwise</code> DataFrame method). I know that I can use <code>np.where</code> on pandas <code>Series</code>, but <code>pandas</code> often defines its own API to use instead of raw <code>numpy</code> functions, which is usually more convenient with <code>pd.Series</code>/<code>pd.DataFrame</code>.</p>
<p>Sure enough, I found <code>pandas.DataFrame.where</code>. However, at first glance, it has a completely different semantics. I could not find a way to rewrite the most basic example of <code>np.where</code> using pandas <code>where</code>:</p>
<pre><code># df is pd.DataFrame
# how to write this using df.where?
df['C'] = np.where((df['A']<0) | (df['B']>0), df['A']+df['B'], df['A']/df['B'])
</code></pre>
<p>Am I missing something obvious? Or is pandas <code>where</code> intended for a completely different use case, despite same name as <code>np.where</code>? </p>
| 6 | 2016-07-26T00:52:45Z | 38,579,700 | <p>Try:</p>
<pre><code>(df['A'] + df['B']).where((df['A'] < 0) | (df['B'] > 0), df['A'] / df['B'])
</code></pre>
<p>The difference between the <code>numpy</code> <code>where</code> and <code>DataFrame</code> <code>where</code> is that the default values are supplied by the <code>DataFrame</code> that the <code>where</code> method is being called on (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.where.html">docs</a>).</p>
<p>I.e.</p>
<pre><code>np.where(m, A, B)
</code></pre>
<p>is roughly equivalent to</p>
<pre><code>A.where(m, B)
</code></pre>
<p>If you wanted a similar call signature using pandas, you could take advantage of <a href="https://docs.python.org/3/tutorial/classes.html#method-objects">the way method calls work in Python</a>:</p>
<pre><code>pd.DataFrame.where(cond=(df['A'] < 0) | (df['B'] > 0), self=df['A'] + df['B'], other=df['A'] / df['B'])
</code></pre>
<p>or without kwargs (Note: that the positional order of arguments is different from the <code>numpy</code> <code>where</code> <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html">argument order</a>):</p>
<pre><code>pd.DataFrame.where(df['A'] + df['B'], (df['A'] < 0) | (df['B'] > 0), df['A'] / df['B'])
</code></pre>
| 7 | 2016-07-26T01:15:44Z | [
"python",
"numpy",
"pandas"
] |
How to supply a mock class method for python unit test? | 38,579,535 | <p>Let's say I have a class like this.</p>
<pre><code> class SomeProductionProcess(CustomCachedSingleTon):
def loaddata():
"""
Uses an iterator over a large file in Production for the Data pipeline.
"""
pass
</code></pre>
<p>Now at test time I want to change the logic inside the <code>loaddata()</code> method. It would be a simple custom logic that doesn't process large data.</p>
<p>How do we supply custom implementation of <code>loaddata()</code> at testtime using Python Mock UnitTest framework?</p>
| 2 | 2016-07-26T00:53:00Z | 38,579,804 | <p>Lets say you have a module named <strong>awesome.py</strong> and in it, you had:</p>
<pre><code>import time
class SomeProductionProcess(CustomCachedSingleTon):
def loaddata(self):
time.sleep(30) # simulating a long running process
return 2
</code></pre>
<p>Then your unittest where you mock <code>loaddata</code> could look like this:</p>
<pre><code>import unittest
import awesome # your application module
class TestSomeProductionProcess(unittest.TestCase):
"""Example of direct monkey patching"""
def test_loaddata(self):
some_prod_proc = awesome.SomeProductionProcess()
some_prod_proc.loaddata = lambda x: 2 # will return 2 every time called
output = some_prod_proc.loaddata()
expected = 2
self.assertEqual(output, expected)
</code></pre>
<p>Or it could look like this:</p>
<pre><code>import unittest
from mock import patch
import awesome # your application module
class TestSomeProductionProcess(unittest.TestCase):
"""Example of using the mock.patch function"""
@patch.object(awesome.SomeProductionProcess, 'loaddata')
def test_loaddata(self, fake_loaddata):
fake_loaddata.return_value = 2
some_prod_proc = awesome.SomeProductionProcess()
output = some_prod_proc.loaddata()
expected = 2
self.assertEqual(output, expected)
</code></pre>
<p>Now when you run your test, <code>loaddata</code> wont take 30 seconds for those test cases.</p>
| 0 | 2016-07-26T01:34:20Z | [
"python",
"unit-testing",
"mocking"
] |
How to supply a mock class method for python unit test? | 38,579,535 | <p>Let's say I have a class like this.</p>
<pre><code> class SomeProductionProcess(CustomCachedSingleTon):
def loaddata():
"""
Uses an iterator over a large file in Production for the Data pipeline.
"""
pass
</code></pre>
<p>Now at test time I want to change the logic inside the <code>loaddata()</code> method. It would be a simple custom logic that doesn't process large data.</p>
<p>How do we supply custom implementation of <code>loaddata()</code> at testtime using Python Mock UnitTest framework?</p>
| 2 | 2016-07-26T00:53:00Z | 38,579,823 | <p>To easily mock out a class method with a structured return_value, can use <code>unittest.mock.Mock</code>.</p>
<pre><code>from unittest.mock import Mock
mockObject = SomeProductionProcess
mockObject.loaddata = Mock(return_value=True)
</code></pre>
<p>EDIT:</p>
<p>Since you want to mock out the method with a custom implementation, you could just create a custom mock method object and swap out the original method at testing runtime.</p>
<pre><code>def custom_method(*args, **kwargs):
# do custom implementation
SomeProductionProcess.loaddata = custom_method
</code></pre>
| 0 | 2016-07-26T01:37:05Z | [
"python",
"unit-testing",
"mocking"
] |
How to supply a mock class method for python unit test? | 38,579,535 | <p>Let's say I have a class like this.</p>
<pre><code> class SomeProductionProcess(CustomCachedSingleTon):
def loaddata():
"""
Uses an iterator over a large file in Production for the Data pipeline.
"""
pass
</code></pre>
<p>Now at test time I want to change the logic inside the <code>loaddata()</code> method. It would be a simple custom logic that doesn't process large data.</p>
<p>How do we supply custom implementation of <code>loaddata()</code> at testtime using Python Mock UnitTest framework?</p>
| 2 | 2016-07-26T00:53:00Z | 38,579,854 | <p>Here is a simple way to do it using mock</p>
<pre><code>import mock
def new_loaddata(cls, *args, **kwargs):
# Your custom testing override
return 1
def test_SomeProductionProcess():
with mock.patch.object(SomeProductionProcess, 'loaddata', new=new_loaddata):
obj = SomeProductionProcess()
obj.loaddata() # This will call your mock method
</code></pre>
<p>I'd recommend using <code>pytest</code> instead of the <code>unittest</code> module if you're able. It makes your test code a lot cleaner and reduces a lot of the boilerplate you get with <code>unittest.TestCase</code>-style tests.</p>
| 0 | 2016-07-26T01:41:43Z | [
"python",
"unit-testing",
"mocking"
] |
Python 3 Dice Sim issue | 38,579,560 | <p>I am BRAND new to python because my new school requires it. I am used to c++ so I'm still learning the ropes. I'm trying to make a dice rolling simulator and I thought i was doing everything right but my code just won't work. Any tips or guides to help me learn would be greatly appreciated. Here is my code:</p>
<pre><code>import random
def roll(sides=6):
num_rolled = random.randint(l,sides)
return num_rolled
def main():
sides = 6
rolling = True
while rolling:
roll_again = input("Ready to roll? ENTER=Roll. Q=Quit. ")
if roll_again.lower() != "q":
num_rolled = roll(sides)
print("You rolled a", num_rolled)
else:
rolling = False
print("Thanks for playing!")
main()
</code></pre>
<p>This is the error I get: </p>
<blockquote>
<p>Traceback (most recent call last): File "C:\Users\nomor\AppData\Local\Programs\Python\Python35-32\DiceRollingSim.py", line 20, in main() File "C:\Users\nomor\AppData\Local\Programs\Python\Python35-32\DiceRollingSim.py", line 13, in main num_rolled = roll(sides) File "C:\Users\nomor\AppData\Local\Programs\Python\Python35-32\DiceRollingSim.py", line 4, in roll num_rolled = random.randint(l,sides) NameError: name 'l' is not defined</p>
</blockquote>
| 0 | 2016-07-26T00:56:19Z | 38,579,603 | <p>For the first issue...</p>
<pre><code>num_rolled = random.randint(l,sides)
</code></pre>
<p><code>l != 1</code>. You put an "l" instead of the number 1. Python thinks this is a variable which you haven't defined anywhere -> the error you get.</p>
<p>From the <a href="https://docs.python.org/3/library/random.html" rel="nofollow">documentation</a> randint takes two ints as parameters:</p>
<blockquote>
<p>random.randint(a, b)
Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).</p>
</blockquote>
<p>Next, look at these lines in your code.</p>
<pre><code> while rolling:
roll_again = input("Ready to roll? ENTER=Roll. Q=Quit. ")
if roll_again.lower() != "q":
num_rolled = roll(sides)
print("You rolled a", num_rolled)
else:
rolling = False
</code></pre>
<p>The <code>if-else</code> part needs to be indented inside of the while loop:</p>
<pre><code>while rolling:
roll_again = input("Ready to roll? ENTER=Roll. Q=Quit. ")
if roll_again.lower() != "q":
num_rolled = roll(sides)
print("You rolled a", num_rolled)
else:
rolling = False
</code></pre>
| 1 | 2016-07-26T01:01:23Z | [
"python",
"python-3.x"
] |
Trying to create a login page using tkinter in python, doesn't seem to work | 38,579,711 | <p>The below code is what i am working on, I am trying to create a login page and validate username and password. Ideally loginValidate function should be invoked when i click on the submit button, but it is invoked even before i do so. Also the user_login and pwd_login values doesn't seems to be passed to the function loginvalidate. Kindly help me in resolving the issue.</p>
<pre><code>import tkinter as tk
import tkinter.messagebox as tm
from tkinter import *
import sys
FONTT = ("Times", "12", "bold italic")
class myApp(tk.Tk):
def __init__(self,*args,**kwargs):
tk.Tk.__init__(self,*args,**kwargs)
container = tk.Frame(self)
container.pack(side = "top", fill = "both", expand = True)
container.grid_rowconfigure(0,weight = 1)
container.grid_columnconfigure(0,weight = 1)
self.frames = {}
frame = LoginPage(container,self)
self.frames[LoginPage] = frame
frame.grid(row = 0,column = 0,sticky = "nsew")
self.show_frame(LoginPage)
def show_frame(self,cont):
frame = self.frames[cont]
frame.tkraise()
def loginValidate(user,pwd):
if(user == "yogesh" and pwd == "123456"):
print("1")
else:
print("2")
tm.showerror("Login error", "Incorrect username or password")
class LoginPage(tk.Frame):
def __init__(self,parent,controller):
tk.Frame.__init__(self,parent)
usr_login = StringVar()
pwd_login = StringVar()
userLabel = tk.Label(self,text = "Name",font = FONTT )
passwordLabel = tk.Label(self,text = "Password", font = FONTT)
userEntry = tk.Entry(self, textvariable = usr_login, bd=5)
passwordEntry = tk.Entry(self, textvariable=pwd_login,bd=5,show = "*")
submitButton = tk.Button(self,text = "Login",command = lambda: loginValidate(usr_login.get(),pwd_login.get()))
quitButton = tk.Button(self,text = "Quit",command =lambda: app.destroy)
userLabel.grid(row = 0,sticky = "E",padx =10,pady =10)
passwordLabel.grid(row =1,sticky = "E",padx =10,pady =10)
userEntry.grid(row=0,column=1,padx =10,pady =10)
passwordEntry.grid(row=1,column=1,padx =10,pady =10)
submitButton.grid(row =2,column =1,padx =10,pady =10)
quitButton.grid(row=2,column=2,padx =10,pady =10)
app = myApp()
app.mainloop()
</code></pre>
| 0 | 2016-07-26T01:17:23Z | 38,579,723 | <p>Look at what you've passed for the command:</p>
<pre><code>loginValidate(usr_login.get(),pwd_login.get())
</code></pre>
<p>You're <em>calling</em> the function and passing what this function <em>returns</em> as the command.</p>
<p>Simple fix = use <code>lambda</code></p>
<pre><code>lambda: loginValidate(usr_login.get(), pwd_login.get())
</code></pre>
| 0 | 2016-07-26T01:19:03Z | [
"python",
"class",
"object",
"tkinter",
"call-by-value"
] |
return string with first match Regex | 38,579,725 | <p>I want to get the first match of a regex.</p>
<p>In this case, I got a list:</p>
<pre><code>text = 'aa33bbb44'
re.findall('\d+',text)
</code></pre>
<blockquote>
<p>['33', '44']</p>
</blockquote>
<p>I could extract the first element of the list:</p>
<pre><code>text = 'aa33bbb44'
re.findall('\d+',text)[0]
</code></pre>
<blockquote>
<p>'33'</p>
</blockquote>
<p>But that only works if there is at least one match, otherwise I'll get an error:</p>
<pre><code>text = 'aazzzbbb'
re.findall('\d+',text)[0]
</code></pre>
<blockquote>
<p>IndexError: list index out of range</p>
</blockquote>
<p>In which case I could define a function:</p>
<pre><code>def return_first_match(text):
try:
result = re.findall('\d+',text)[0]
except Exception, IndexError:
result = ''
return result
</code></pre>
<p>Is there a way of obtaining that result without defining a new function?</p>
| 1 | 2016-07-26T01:19:34Z | 38,579,772 | <p>You can do:</p>
<pre><code>x = re.findall('\d+', text)
result = x[0] if len(x) > 0 else ''
</code></pre>
<p>Note that your question isn't exactly related to regex. Rather, how do you safely find an element from an array, if it has none.</p>
| 1 | 2016-07-26T01:28:53Z | [
"python",
"regex"
] |
return string with first match Regex | 38,579,725 | <p>I want to get the first match of a regex.</p>
<p>In this case, I got a list:</p>
<pre><code>text = 'aa33bbb44'
re.findall('\d+',text)
</code></pre>
<blockquote>
<p>['33', '44']</p>
</blockquote>
<p>I could extract the first element of the list:</p>
<pre><code>text = 'aa33bbb44'
re.findall('\d+',text)[0]
</code></pre>
<blockquote>
<p>'33'</p>
</blockquote>
<p>But that only works if there is at least one match, otherwise I'll get an error:</p>
<pre><code>text = 'aazzzbbb'
re.findall('\d+',text)[0]
</code></pre>
<blockquote>
<p>IndexError: list index out of range</p>
</blockquote>
<p>In which case I could define a function:</p>
<pre><code>def return_first_match(text):
try:
result = re.findall('\d+',text)[0]
except Exception, IndexError:
result = ''
return result
</code></pre>
<p>Is there a way of obtaining that result without defining a new function?</p>
| 1 | 2016-07-26T01:19:34Z | 38,579,778 | <p>Maybe this would perform a bit better in case greater amount of input data does not contain your wanted piece because except has greater cost. </p>
<pre><code>def return_first_match(text):
result = re.findall('\d+',text)
result = result[0] if result else ""
return result
</code></pre>
| 1 | 2016-07-26T01:29:37Z | [
"python",
"regex"
] |
return string with first match Regex | 38,579,725 | <p>I want to get the first match of a regex.</p>
<p>In this case, I got a list:</p>
<pre><code>text = 'aa33bbb44'
re.findall('\d+',text)
</code></pre>
<blockquote>
<p>['33', '44']</p>
</blockquote>
<p>I could extract the first element of the list:</p>
<pre><code>text = 'aa33bbb44'
re.findall('\d+',text)[0]
</code></pre>
<blockquote>
<p>'33'</p>
</blockquote>
<p>But that only works if there is at least one match, otherwise I'll get an error:</p>
<pre><code>text = 'aazzzbbb'
re.findall('\d+',text)[0]
</code></pre>
<blockquote>
<p>IndexError: list index out of range</p>
</blockquote>
<p>In which case I could define a function:</p>
<pre><code>def return_first_match(text):
try:
result = re.findall('\d+',text)[0]
except Exception, IndexError:
result = ''
return result
</code></pre>
<p>Is there a way of obtaining that result without defining a new function?</p>
| 1 | 2016-07-26T01:19:34Z | 38,579,881 | <p>You could embed the <code>''</code> default in your regex by adding <code>|$</code>:</p>
<pre><code>>>> re.findall('\d+|$', 'aa33bbb44')[0]
'33'
>>> re.findall('\d+|$', 'aazzzbbb')[0]
''
>>> re.findall('\d+|$', '')[0]
''
</code></pre>
<p>Also works with <code>re.search</code> pointed out by others:</p>
<pre><code>>>> re.search('\d+|$', 'aa33bbb44').group()
'33'
>>> re.search('\d+|$', 'aazzzbbb').group()
''
>>> re.search('\d+|$', '').group()
''
</code></pre>
| 3 | 2016-07-26T01:46:47Z | [
"python",
"regex"
] |
return string with first match Regex | 38,579,725 | <p>I want to get the first match of a regex.</p>
<p>In this case, I got a list:</p>
<pre><code>text = 'aa33bbb44'
re.findall('\d+',text)
</code></pre>
<blockquote>
<p>['33', '44']</p>
</blockquote>
<p>I could extract the first element of the list:</p>
<pre><code>text = 'aa33bbb44'
re.findall('\d+',text)[0]
</code></pre>
<blockquote>
<p>'33'</p>
</blockquote>
<p>But that only works if there is at least one match, otherwise I'll get an error:</p>
<pre><code>text = 'aazzzbbb'
re.findall('\d+',text)[0]
</code></pre>
<blockquote>
<p>IndexError: list index out of range</p>
</blockquote>
<p>In which case I could define a function:</p>
<pre><code>def return_first_match(text):
try:
result = re.findall('\d+',text)[0]
except Exception, IndexError:
result = ''
return result
</code></pre>
<p>Is there a way of obtaining that result without defining a new function?</p>
| 1 | 2016-07-26T01:19:34Z | 38,579,883 | <p>If you only need the first match, then use <a href="https://docs.python.org/3.4/library/re.html#re.regex.search" rel="nofollow"><code>re.search</code></a> instead of <code>re.findall</code>:</p>
<pre><code>>>> m = re.search('\d+',text)
>>> m.group()
'33'
>>> m = re.search('\d+','aazzzbbb')
>>> m.group()
Traceback (most recent call last):
File "<pyshell#281>", line 1, in <module>
m.group()
AttributeError: 'NoneType' object has no attribute 'group'
</code></pre>
<p>Then you can use <code>m</code> as a checking condition as:</p>
<pre><code>>>> m = re.search('\d+',text)
>>>
>>> if m:
print('First number found = {}'.format(m.group()))
else:
print('Not Found')
First number found = 33
</code></pre>
| 3 | 2016-07-26T01:47:19Z | [
"python",
"regex"
] |
return string with first match Regex | 38,579,725 | <p>I want to get the first match of a regex.</p>
<p>In this case, I got a list:</p>
<pre><code>text = 'aa33bbb44'
re.findall('\d+',text)
</code></pre>
<blockquote>
<p>['33', '44']</p>
</blockquote>
<p>I could extract the first element of the list:</p>
<pre><code>text = 'aa33bbb44'
re.findall('\d+',text)[0]
</code></pre>
<blockquote>
<p>'33'</p>
</blockquote>
<p>But that only works if there is at least one match, otherwise I'll get an error:</p>
<pre><code>text = 'aazzzbbb'
re.findall('\d+',text)[0]
</code></pre>
<blockquote>
<p>IndexError: list index out of range</p>
</blockquote>
<p>In which case I could define a function:</p>
<pre><code>def return_first_match(text):
try:
result = re.findall('\d+',text)[0]
except Exception, IndexError:
result = ''
return result
</code></pre>
<p>Is there a way of obtaining that result without defining a new function?</p>
| 1 | 2016-07-26T01:19:34Z | 38,579,898 | <p>You shouldn't be using <code>.findall()</code> at all - <code>.search()</code> is what you want. It finds the leftmost match, which is what you want (or returns <code>None</code> if no match exists).</p>
<pre><code>m = re.search(pattern, text)
result = m.group(0) if m else ""
</code></pre>
<p>Whether you want to put that in a function is up to you. It's <em>unusual</em> to want to return an empty string if no match is found, which is why nothing like that is built in. It's impossible to get confused about whether <code>.search()</code> on its own finds a match (it returns <code>None</code> if it didn't, or an <code>SRE_Match</code> object if it did).</p>
| 1 | 2016-07-26T01:48:58Z | [
"python",
"regex"
] |
return string with first match Regex | 38,579,725 | <p>I want to get the first match of a regex.</p>
<p>In this case, I got a list:</p>
<pre><code>text = 'aa33bbb44'
re.findall('\d+',text)
</code></pre>
<blockquote>
<p>['33', '44']</p>
</blockquote>
<p>I could extract the first element of the list:</p>
<pre><code>text = 'aa33bbb44'
re.findall('\d+',text)[0]
</code></pre>
<blockquote>
<p>'33'</p>
</blockquote>
<p>But that only works if there is at least one match, otherwise I'll get an error:</p>
<pre><code>text = 'aazzzbbb'
re.findall('\d+',text)[0]
</code></pre>
<blockquote>
<p>IndexError: list index out of range</p>
</blockquote>
<p>In which case I could define a function:</p>
<pre><code>def return_first_match(text):
try:
result = re.findall('\d+',text)[0]
except Exception, IndexError:
result = ''
return result
</code></pre>
<p>Is there a way of obtaining that result without defining a new function?</p>
| 1 | 2016-07-26T01:19:34Z | 38,579,905 | <p>I'd go with:</p>
<pre><code> r = re.search("\d+", ch)
result = return r.group(0) if r else ""
</code></pre>
<p>re.search only looks for the first match in the string anyway, so I think it makes your intent slightly more clear than using findall.</p>
| 1 | 2016-07-26T01:49:48Z | [
"python",
"regex"
] |
Could I get [variable name, value] table from javascript code using python? | 38,579,757 | <p>I have a JavaScript file called <code>index.js</code>.
I'm developing a tool, written in Python, that it navigates JavaScript code statically to check if a certain API is defined or not.
In order to develop it, I need a data structure (table) which stores
<code>[variable, value]</code>.</p>
<p>Here is the example of JavaScript code.</p>
<pre><code>var a = "hello";
var b = "hi";
a = "world";
var c= certainAPI.method(parameter_1, parameter_2);
</code></pre>
<p>After using a tool, here is the table that I want to get.</p>
<pre><code>---------------------------------------------------------
variable | value
---------------------------------------------------------
a | "world"
---------------------------------------------------------
b | "hi"
---------------------------------------------------------
c | certainAPI.method(parameter_1, parameter_2)
---------------------------------------------------------
</code></pre>
<p>Are there any tools or modules that navigate JavaScript code and make such a table automatically? The structure type of table doesn't matter. <code>list</code>, <code>dict</code>... all types are fine. I just want to get (var, value) matching set.</p>
| 0 | 2016-07-26T01:27:12Z | 38,580,323 | <p>Yes, there is a popular parser for JavaScript written in JavaScript. Its called <a href="http://esprima.org" rel="nofollow">Esprima</a></p>
<p>It helps you obtain the full syntax tree.</p>
<p>I found a port of it in Python. It is not popular, but you can check it out.</p>
<p><a href="https://github.com/int3/pyesprima" rel="nofollow">github.com/int3/pyesprima</a></p>
| 2 | 2016-07-26T02:55:04Z | [
"javascript",
"python",
"lexer"
] |
Python & Pandas: How to return a copy of a dataframe? | 38,579,921 | <p>Here is the problem. I use a function to return a randomized data, </p>
<pre><code>data1 = [3,5,7,3,2,6,1,6,7,8]
data2 = [1,5,2,1,6,4,3,2,7,8]
df = pd.DataFrame(data1, columns = ['c1'])
df['c2'] = data2
def randomize_data(df):
df['c1_ran'] = df['c1'].apply(lambda x: (x + np.random.uniform(0,1)))
df['c1']=df['c1_ran']
# df.drop(['c1_ran'], 1, inplace=True)
return df
temp_df = randomize_data(df)
display(df)
display(temp_df)
</code></pre>
<p>However, the <code>df</code> (source data) and the <code>temp_df</code> (randomized_data) is the same. Here is the result:</p>
<p><a href="http://i.stack.imgur.com/TaBta.png" rel="nofollow"><img src="http://i.stack.imgur.com/TaBta.png" alt="enter image description here"></a></p>
<p>How can I make the <code>temp_df</code> and <code>df</code> different from each other?</p>
<hr>
<p>I find I can get rid of the problem by adding <code>df.copy()</code> at the beginning of the function </p>
<pre><code>def randomize_data(df):
df = df.copy()
</code></pre>
<p>But I'm not sure if this is the right way to deal with it?</p>
| 1 | 2016-07-26T01:52:51Z | 38,579,987 | <p>I think you are right, and DataFrame.copy() have an optional argument 'deep'. You can find details in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.copy.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.copy.html</a></p>
| 0 | 2016-07-26T02:02:31Z | [
"python",
"pandas"
] |
Python & Pandas: How to return a copy of a dataframe? | 38,579,921 | <p>Here is the problem. I use a function to return a randomized data, </p>
<pre><code>data1 = [3,5,7,3,2,6,1,6,7,8]
data2 = [1,5,2,1,6,4,3,2,7,8]
df = pd.DataFrame(data1, columns = ['c1'])
df['c2'] = data2
def randomize_data(df):
df['c1_ran'] = df['c1'].apply(lambda x: (x + np.random.uniform(0,1)))
df['c1']=df['c1_ran']
# df.drop(['c1_ran'], 1, inplace=True)
return df
temp_df = randomize_data(df)
display(df)
display(temp_df)
</code></pre>
<p>However, the <code>df</code> (source data) and the <code>temp_df</code> (randomized_data) is the same. Here is the result:</p>
<p><a href="http://i.stack.imgur.com/TaBta.png" rel="nofollow"><img src="http://i.stack.imgur.com/TaBta.png" alt="enter image description here"></a></p>
<p>How can I make the <code>temp_df</code> and <code>df</code> different from each other?</p>
<hr>
<p>I find I can get rid of the problem by adding <code>df.copy()</code> at the beginning of the function </p>
<pre><code>def randomize_data(df):
df = df.copy()
</code></pre>
<p>But I'm not sure if this is the right way to deal with it?</p>
| 1 | 2016-07-26T01:52:51Z | 38,669,915 | <p>Use <code>DataFrame.assign()</code>: </p>
<pre><code>def randomize_data(df):
return df.assign(c1=df.c1 + np.random.uniform(0, 1, df.shape[0]))
</code></pre>
| 2 | 2016-07-30T02:48:46Z | [
"python",
"pandas"
] |
pygame - blitting a moving background image causes extreme fps drop? | 38,579,948 | <p>I'm making a Flappy Bird clone in PyGame and I'm trying to add a moving background image. I'm using a 800x600 image right now, and for some reason, when I blit the image, the performance suffers terribly. Is there something I'm doing wrong that is taking up a lot of resources?</p>
<pre><code>import pygame, sys
import random
from pygame import *
pygame.init()
red = (255, 0, 0)
white = (255, 255, 255)
black = (0, 0, 0)
blue = (0, 0, 255)
green = (0, 255, 0)
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("flap it up")
clock = pygame.time.Clock()
MAX_VEL = 5
GAP = 175
WALLSPEED = -2
WALLEVENT = pygame.USEREVENT+1
SCOREEVENT = pygame.USEREVENT+2
pygame.time.set_timer(WALLEVENT, 5000)
pygame.time.set_timer(SCOREEVENT, 2500)
myfont = pygame.font.SysFont("monospace", 18)
class Player(object):
def __init__(self):
self.rect = pygame.Rect(384, 284, 32, 32)
self.xvel = 0
self.yvel = MAX_VEL
self.xcel = 0
self.ycel = 1
def move(self):
self.rect.top += self.yvel
if self.yvel < MAX_VEL:
self.yvel += self.ycel
else:
self.yvel = MAX_VEL
def jump(self):
self.yvel = -15
def draw(self):
pygame.draw.rect(screen, red, self.rect)
class Wall(object):
def __init__(self, y):
self.rect1 = pygame.Rect(800, y, 32, 600-y)
self.rect2 = pygame.Rect(800, 0, 32, y-GAP)
self.xvel = WALLSPEED
def move(self, walls):
self.rect1.x += self.xvel
self.rect2.x += self.xvel
if self.rect1.x < -31:
walls.remove(self)
def draw(self):
pygame.draw.rect(screen, green, self.rect1)
pygame.draw.rect(screen, green, self.rect2)
class BG(object):
def __init__(self, x):
self.x = x
self.xvel = WALLSPEED
self.img = pygame.image.load("bg.jpg")
def move(self, bg):
self.x += self.xvel
if self.x < -799:
bg.remove(self)
bg.append(BG(self.x+1600))
screen.blit(self.img, (self.x, 0))
def lose():
pygame.quit()
quit()
def main(player, walls, bg, score, playing):
while playing:
for event in pygame.event.get():
if event.type == KEYDOWN:
player.jump()
if event.type == WALLEVENT:
numbo = random.randrange(GAP, 600, 25)
walls.append(Wall(numbo))
if event.type == SCOREEVENT:
score += 1
for b in bg:
b.move(bg)
label = myfont.render("Score: " + str(score), 1, (0, 0, 0))
screen.blit(label, (30, 20))
player.move()
player.draw()
for w in walls:
w.move(walls)
w.draw()
if player.rect.colliderect(w.rect1) or player.rect.colliderect(w.rect2):
lose()
playing = False
clock.tick(60)
pygame.display.update()
player = Player()
walls = []
bg = []
score = 0
walls.append(Wall(300))
bg.append(BG(0))
bg.append(BG(800))
playing = True
main(player, walls, bg, score, playing)
</code></pre>
| 0 | 2016-07-26T01:56:11Z | 38,580,417 | <p>Typically, this should not be a problem. You should try to set the FPS manually and see if there is a difference</p>
<pre><code># Create a clock
clock = pygame.time.Clock()
# Set FPS (frames per second)
clock.tick(50)
</code></pre>
| 0 | 2016-07-26T03:07:32Z | [
"python",
"pygame"
] |
Flask error when connecting to mysql using pymysql | 38,579,992 | <p>So I am using pymysql to conenct mysql to flask. When I was developing a website on my local computer everything was fine, later when I uploaded my website to digital ocean trying to connect gives me an error:</p>
<blockquote>
<p>'NoneType' object is not iterable</p>
</blockquote>
<p>The view I get the error in:</p>
<pre><code>@app.route('/test/')
def test_page():
try:
c, conn = connection()
return("okay")
except Exception as e:
return(str(e))
</code></pre>
<p>The connection file looks like this:</p>
<pre><code>import pymysql
def connection():
try:
conn = pymysql.connect(host="localhost", port=3306, user="root", passwd="my_password",db="db_name",charset='utf8')
c = conn.cursor()
return conn, c
except Exception as e:
print (str(e))
</code></pre>
<p>I am stuck with this problem for like couple of hours, cant find a solution. Thank you in advance.</p>
| 2 | 2016-07-26T02:03:49Z | 38,582,050 | <p>Your pymysql.connection is trying to connect to a database running on the local machine.</p>
<p>Evidently there is no database on your Digital Ocean server, or if there is it's not accessible on port 3306 with the credentials provided.</p>
| 0 | 2016-07-26T05:59:47Z | [
"python",
"mysql",
"flask",
"pymysql"
] |
Flask error when connecting to mysql using pymysql | 38,579,992 | <p>So I am using pymysql to conenct mysql to flask. When I was developing a website on my local computer everything was fine, later when I uploaded my website to digital ocean trying to connect gives me an error:</p>
<blockquote>
<p>'NoneType' object is not iterable</p>
</blockquote>
<p>The view I get the error in:</p>
<pre><code>@app.route('/test/')
def test_page():
try:
c, conn = connection()
return("okay")
except Exception as e:
return(str(e))
</code></pre>
<p>The connection file looks like this:</p>
<pre><code>import pymysql
def connection():
try:
conn = pymysql.connect(host="localhost", port=3306, user="root", passwd="my_password",db="db_name",charset='utf8')
c = conn.cursor()
return conn, c
except Exception as e:
print (str(e))
</code></pre>
<p>I am stuck with this problem for like couple of hours, cant find a solution. Thank you in advance.</p>
| 2 | 2016-07-26T02:03:49Z | 38,587,412 | <p>Found a mistake. All I need was a fresh reinstall of mysql :)</p>
| 0 | 2016-07-26T10:31:13Z | [
"python",
"mysql",
"flask",
"pymysql"
] |
Transfer files with sockets in Python 3 | 38,580,012 | <p>I have the following client-server socket app to upload a file to a server. </p>
<h2>Server code:</h2>
<pre><code> import socket,sys,SocketServer
class EchoRequestHandler(SocketServer.BaseRequestHandler):
def setup(self):
print self.client_address, 'connected!'
self.request.send('hi ' + str(self.client_address) + '\n')
def handle(self):
while 1:
myfile = open('test.txt', 'w')
data = self.request.recv(1024)
myfile.write(data)
print 'writing file ....'
myfile.close()
def finish(self):
print self.client_address, 'disconnected!'
self.request.send('bye ' + str(self.client_address) + '\n')
if __name__=='__main__':
server = SocketServer.ThreadingTCPServer(('localhost', 50000), EchoRequestHandler)
server.serve_forever()
</code></pre>
<hr>
<h2>Client code:</h2>
<pre><code>import socket
import sys
HOST, PORT = "localhost", 50000
# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to server and send data
sock.connect((HOST, PORT))
# Receive data from the server and shut down
received = sock.recv(1024)
date = open('file_t.txt').read()
sock.sendall(data + "\n")
finally:
sock.close()
print "Sent: {}".format(data)
print "Received: {}".format(received)
</code></pre>
<p>However at the server side the console output is non stop "writing file ...." and in the end the file is not stored, It is an empty test.txt file</p>
| 1 | 2016-07-26T02:05:48Z | 38,580,113 | <p>You could improve your loop quite a bit.</p>
<ol>
<li>Use <code>while True</code> rather than <code>while 1</code>. Sure it works and is less typing, but if you really wanted less typing then you should be using Perl. <code>while True</code> is easy enough that nearly anyone could guess at the meaning - <code>while 1</code> is just a holdover from when Python had no <code>True</code> or <code>False</code></li>
<li><code>socket.recv</code> returns an empty string when there's nothing more to read. Use that.</li>
<li>You're opening the file each time through the loop. That truncates it every time through the loop.</li>
</ol>
<p>Here's what a better approach could look like:</p>
<pre><code>def handle(self):
# With block handles closing - even on exceptions!
with open('test.txt', 'w') as outfile:
data = 'fnord' # just something to be there for the first comparison
while data:
data = self.request.recv(1024)
print('writing {!r} to file ....'.format(data))
outfile.write(data)
</code></pre>
<p>No break is necessary with this approach - because rather than a <code>while True</code> it's <code>while data</code>. Strings will evaluate to <code>True</code> as long as they are non-empty, so this will continue to write data as long as there is data to write. Eventually, the sender will stop sending any data, the socket will close and data will be an empty string, which evaluates to False, and your loop will exit.</p>
| 1 | 2016-07-26T02:20:43Z | [
"python",
"sockets",
"python-sockets"
] |
Vectorizing with variable array indices | 38,580,015 | <p>I'm running python with numpy, and I have a loop which, stripped down, looks like this:</p>
<pre><code>result = np.zeros(bins)
for i in xrange(bins):
result[f(i)] += source[i]
</code></pre>
<p>Here, both result and source are numpy arrays, and f is a mildly complicated set of arithmetic operations. For example, one simplified example of f might look like</p>
<pre><code>f = lambda x: min(int(width*pow(x, 3)), bins-1)
</code></pre>
<p>though f is generally not monotonic in its argument.</p>
<p>This loop is currently the bottleneck in my program. I managed to vectorize everything else, but I'm currently stumped on how to do it here. How can this loop be vectorized?</p>
| 1 | 2016-07-26T02:06:19Z | 38,580,354 | <p>To vectorize <code>f</code>
the main idea is to replace scalar operations with numpy vector-based functions.
For example, if originally we have</p>
<pre><code>def f(x):
return min(int(width*pow(x, 3)), bins-1)
</code></pre>
<p>then we could instead use </p>
<pre><code>def fvec(x):
return np.minimum((width*np.power(x, 3)).astype(int), bins-1)
</code></pre>
<p>There is a natural correspondence between some Python scalar functions and NumPy
vectorized functions:</p>
<pre><code>| pow | np.power |
| min | np.minimum |
| max | np.maximum |
| floor | np.floor |
| log | np.log |
| < | np.less |
| > | np.greater |
</code></pre>
<p>The vectorized functions take an array of inputs and returns an array of the same shape.
However, there are other constructs which may not be so obvious. For example the
vectorized equivalent of <code>x if condition else y</code> is <code>np.where(condition, x, y)</code>. </p>
<p>Unfortunately, in general there is no simple shortcut. Translating from
scalar function to vectorized function may require any one of the many
NumPy functions available, as well NumPy concepts like broadcasting and advanced
indexing. </p>
<hr>
<p>For example, it is tempting at this point to replace</p>
<pre><code>for i in range(bins):
result[f(i)] += source[i]
</code></pre>
<p>with the <a href="http://docs.scipy.org/doc/numpy/user/basics.indexing.html#assigning-values-to-indexed-arrays" rel="nofollow">integer-array indexed assignment</a>:</p>
<pre><code>result[fvec(np.arange(bins))] += source
</code></pre>
<p>but this produces an incorrect result if <code>fvec(np.arange(bins))</code> has repeated values. Instead use
<a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html" rel="nofollow"><code>np.bincount</code></a> since this correctly accumulates multiple <code>source</code> values when <code>fvec(np.arange(bins))</code> indicates the same bin:</p>
<pre><code>result = np.bincount(fvec(np.arange(bins)), weights=source, minlength=bins)
</code></pre>
<hr>
<pre><code>import numpy as np
import pandas as pd
bins = 1000
width = 1.5
source = np.random.random(bins)
def fvec(x):
return np.minimum((width*np.power(x, 3)).astype(int), bins-1)
def f(x):
return min(int(width*pow(x, 3)), bins-1)
def orig():
result = np.zeros(bins)
for i in range(bins):
result[f(i)] += source[i]
return result
def alt():
result = np.bincount(fvec(np.arange(bins)), weights=source, minlength=bins)
return result
assert np.allclose(orig(), alt())
</code></pre>
<hr>
<p>For the example above with <code>bins=1000</code>, <code>alt</code> is about 62x faster than <code>orig</code> (on my machine):</p>
<pre><code>In [194]: %timeit orig()
1000 loops, best of 3: 1.37 ms per loop
In [195]: %timeit alt()
10000 loops, best of 3: 21.8 µs per loop
</code></pre>
<p>The speed advantage of <code>alt</code> over <code>orig</code> will increase as the number of iterations required by <code>orig</code>'s <code>for-loop</code> increases -- that is, as <code>bins</code> increases.</p>
| 3 | 2016-07-26T02:58:36Z | [
"python",
"numpy",
"vectorization"
] |
Initializing form input fields from url parameters in Django | 38,580,058 | <p>I am building my own projects based on the instructions from 'Django by Example' book. </p>
<p>However I got stuck on <strong>how does django initialize input form fields using URL parameters</strong>?</p>
<pre><code>#models.py
class Image(models.Model):
title = models.CharField(max_length=200)
description = models.TextField(blank=True)
url = models.URLField()
(...)
#views.py
def image_create(request):
if request.method == 'POST':
form = ImageCreateForm(data=request.POST)
(...)
else:
form = ImageCreateForm(data=request.GET)
return render(request,
'create.html',
{'form': form})
#forms.py
class ImageCreateForm(forms.ModelForm):
class Meta:
model = Image
fields = ('title', 'url', 'description')
widgets = {
'url': forms.HiddenInput,
}
#create.html
{% extends "base.html" %}
{% block content %}
<h1>Bookmark an image</h1>
<img src="{{ request.GET.url }}" class="image-preview">
<form action="." method="post">
{{ form.as_p }}
{% csrf_token %}
<input type="submit" value="Bookmark it!">
</form>
{% endblock content %}
</code></pre>
<p>I could not find any specific line of code which would explicitly tell to get request.GET parameters and assign each of them to corresponding input field.
I assume that all of this has to do with the form initialization on line: <code>form = ImageCreateForm(data=request.GET)</code> in views.py</p>
<h2>Questions:</h2>
<ol>
<li>Can someone please explain me how does django use request.GET parameters to initialize input fields values(assigns them URL parameters' values)?
Does it simply match, for every request.GET key, the corresponding input field 'name' attribute, and then assigns to that particular input field the value corresponding to the key in request.GET?</li>
<li>Also can someone confirm if there is a relationship between the model/form(which one?) field names to the URL parameters?</li>
<li><p>What is the difference between these two(as both of them seems to work the same way, except the latter returns list in the input field values):</p>
<p><code>form = ImageCreateForm(data=request.GET)</code></p>
<p><code>form = ImageCreateForm(initial=request.GET)</code></p></li>
</ol>
| 0 | 2016-07-26T02:12:56Z | 38,581,673 | <p>1) Yes - request.GET is simply a fancy dictionary (technically a QueryDict), and the form "data" argument expects a dict with keys corresponding to the fields in the form. You could technically pass the form any dictionary if it had the right keys representing the fields. </p>
<p>2) Generally speaking, there is no relation between model/form fields and url parameters. However, if you are using certain Class Based Views (such as a DetailView) if you set a slug or id in your url, it will pass the value along to the view and map it to the objects slug or id. The get_object() method in the link below has an example.</p>
<p><a href="https://ccbv.co.uk/projects/Django/1.9/django.views.generic.detail/DetailView/" rel="nofollow">https://ccbv.co.uk/projects/Django/1.9/django.views.generic.detail/DetailView/</a></p>
<p>3) The data attribute to a form is what is submitted (usually POSTed) to the form whereas the initial value is what is passed to the form upon first page load. For example, if you were editing an object, typically the existing object data would populate the initial value. Then, if you POSTed edits to the form, it would be passed in as data.</p>
| 0 | 2016-07-26T05:30:34Z | [
"python",
"django",
"forms",
"django-forms"
] |
Getting the desired datetime value from x axis in bokeh | 38,580,063 | <p>I have read the documentation and have searched Google and StackOverflow for answers but none the wiser yet. </p>
<p>I have a bokeh graph with circle glyphs for two variables 'score' and 'stress', and a third variable 'date' as a datetime x axis (picture <a href="http://i.stack.imgur.com/EYgKY.png" rel="nofollow">here</a>). I want the users to be able to click on the circles and be taken to a URL showing a detailed view of that particular data point which is identified by its corresponding date. </p>
<p>I have enabled a tap tool with openURL callback which appends the datetime value at the end of the URL. The problem is that once a data point is clicked, the datetime value passed is not in the desired format: <strong><code>'2016-07-20'</code></strong>. What I get instead is the following value: '1468969200000'. So, the user gets re-directed to 'url/1468969200000/' instead of 'url/2016-07-20/'. </p>
<p>Is there a way to change the format of the date value that gets passed once a data point is clicked? </p>
<p>Here is my code (run in jupyter notebook): </p>
<pre><code>import datetime
from bokeh.plotting import figure, output_notebook, show
from bokeh.models import Range1d, OpenURL, TapTool, HoverTool, ColumnDataSource, DatetimeTickFormatter
data = {'score': [4.33, 2.66, 4.66, 2.66, 2.66, 1.66, 1.0, 4.33],
'stress': [3.66, 3.0, 3.0, 1.33, 3.66, 3.33, 1.0, 4.33],
'date': [
datetime.date(2016, 7, 17),
datetime.date(2016, 7, 18),
datetime.date(2016, 7, 19),
datetime.date(2016, 7, 20),
datetime.date(2016, 7, 21),
datetime.date(2016, 7, 22),
datetime.date(2016, 7, 23),
datetime.date(2016, 7, 24)
]
}
source = ColumnDataSource(data=data)
TOOLS = ['hover', 'pan', 'tap']
plot = figure(x_axis_type='datetime', plot_height=250, tools=TOOLS)
plot.circle('date', 'score', legend='score', size=15, color='red', source=source)
plot.circle('date', 'stress', legend='stress', size=10, color='orange', source=source)
plot.y_range = Range1d(1, 5, bounds=(1,5))
plot.x_range = Range1d(datetime.date(2016, 7, 17), datetime.date(2016, 7, 23))
hover = plot.select(type=HoverTool)
hover.tooltips = [
("score", "@score"),
("stress", "@stress"),
("date", "@date")
]
url = 'url/@date/'
taptool = plot.select(type=TapTool)
taptool.callback = OpenURL(url=url)
show(plot)
</code></pre>
| 2 | 2016-07-26T02:13:33Z | 38,585,825 | <p>A simple workaround would be to provide date in string format in addition.</p>
<pre><code>dateStr= {'dateStr': [x.isoformat() for x in data['date']]}
data.update(dateStr)
</code></pre>
<p>then, you can use dateStr in your hover.tooltips and to generate the url</p>
<pre><code>hover.tooltips = [
("score", "@score"),
("stress", "@stress"),
("date", "@dateStr")
]
url = 'url/@dateStr/'
</code></pre>
| 0 | 2016-07-26T09:19:11Z | [
"python",
"datetime",
"bokeh"
] |
How to get indexes of values in a Pandas DataFrame? | 38,580,073 | <p>I am sure there must be a very simple solution to this problem, but I am failing to find it (and browsing through previously asked questions, I didn't find the answer I wanted or didn't understand it).</p>
<p>I have a dataframe similar to this (just much bigger, with many more rows and columns):</p>
<pre><code> x val1 val2 val3
0 0.0 10.0 NaN NaN
1 0.5 10.5 NaN NaN
2 1.0 11.0 NaN NaN
3 1.5 11.5 NaN 11.60
4 2.0 12.0 NaN 12.08
5 2.5 12.5 12.2 12.56
6 3.0 13.0 19.8 13.04
7 3.5 13.5 13.3 13.52
8 4.0 14.0 19.8 14.00
9 4.5 14.5 14.4 14.48
10 5.0 15.0 19.8 14.96
11 5.5 15.5 15.5 15.44
12 6.0 16.0 19.8 15.92
13 6.5 16.5 16.6 16.40
14 7.0 17.0 19.8 18.00
15 7.5 17.5 17.7 NaN
16 8.0 18.0 19.8 NaN
17 8.5 18.5 18.8 NaN
18 9.0 19.0 19.8 NaN
19 9.5 19.5 19.9 NaN
20 10.0 20.0 19.8 NaN
</code></pre>
<p>In the next step, I need to compute the derivative dVal/dx for each of the value columns (in reality I have more than 3 columns, so I need to have a robust solution in a loop, I can't select the rows manually each time). But because of the NaN values in some of the columns, I am facing the problem that x and val are not of the same dimension. I feel the way to overcome this would be to only select only those x intervals, for which the val is <code>notnull</code>. But I am not able to do that. I am probably making some very stupid mistakes (I am not a programmer and I am very untalented, so please be patient with me:) ).</p>
<p>Here is the code so far (now that I think of it, I may have introduced some mistakes just by leaving some old pieces of code because I've been messing with it for a while, trying different things):</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.read_csv('H:/DocumentsRedir/pokus/dataframe.csv', delimiter=',')
vals = list(df.columns.values)[1:]
for i in vals:
V = np.asarray(pd.notnull(df[i]))
mask = pd.notnull(df[i])
X = np.asarray(df.loc[mask]['x'])
derivative=np.diff(V)/np.diff(X)
</code></pre>
<p>But I am getting this error:</p>
<pre><code>ValueError: operands could not be broadcast together with shapes (20,) (15,)
</code></pre>
<p>So, apparently, it did not select only the notnull values...</p>
<p>Is there an obvious mistake that I am making or a different approach that I should adopt? Thanks!</p>
<p>(And another less important question: is np.diff the right function to use here or had I better calculated it manually by finite differences? I'm not finding numpy documentation very helpful.)</p>
| 4 | 2016-07-26T02:15:13Z | 38,580,158 | <p>To calculate dVal/dX:</p>
<pre><code>dVal = df.iloc[:, 1:].diff() # `x` is in column 0.
dX = df['x'].diff()
>>> dVal.apply(lambda series: series / dX)
val1 val2 val3
0 NaN NaN NaN
1 1 NaN NaN
2 1 NaN NaN
3 1 NaN NaN
4 1 NaN 0.96
5 1 NaN 0.96
6 1 15.2 0.96
7 1 -13.0 0.96
8 1 13.0 0.96
9 1 -10.8 0.96
10 1 10.8 0.96
11 1 -8.6 0.96
12 1 8.6 0.96
13 1 -6.4 0.96
14 1 6.4 3.20
15 1 -4.2 NaN
16 1 4.2 NaN
17 1 -2.0 NaN
18 1 2.0 NaN
19 1 0.2 NaN
20 1 -0.2 NaN
</code></pre>
<p>We difference all columns (except the first one), and then apply a lambda function to each column which divides it by the difference in column <code>X</code>.</p>
| 3 | 2016-07-26T02:28:35Z | [
"python",
"numpy",
"pandas"
] |
Threads stops at Beautifulsoup command - unable to interrupt | 38,580,110 | <p>I'm working on a python code to scrape a blog that looks a bit like this:</p>
<pre><code>def main():
thread=threading.Thread(target=blogthread,args=(path,username))
thread.start()
threads.append(thread)
...
def blogthread(path,username,steem):
s=site_scraper.userposts(username)
...
def userposts(username):
f = urllib.request.urlopen(url,timeout=200)
soup = BeautifulSoup(f,'html.parser')
...
</code></pre>
<p>If I call userposts(username) directly, it works just fine. When threads are involved, my main() finishes, but every other thread gets stuck exactly at the "Beautifulsoup" line. It never continues, even when the main thread is done.</p>
<p>By playing with the code, I've notice that if I add an error at the end of the main thread (like an undefined variable), I get an error message, but my threads suddenly start to pick up again and output the required results.</p>
<p>I'm really confused, thanks for your help.</p>
| 1 | 2016-07-26T02:20:00Z | 38,580,465 | <p>The main thread finishes but the other threads are still running. I dont know why they get stuck at the BeautifulSoup line. However you can fix it by exiting the program if the main thread is done. Simply do a "quit(0)" command at the end of the main thread. </p>
| -1 | 2016-07-26T03:15:28Z | [
"python",
"multithreading",
"web-scraping",
"beautifulsoup"
] |
IndexError: string index out of range python | 38,580,148 | <p>I have the following list: </p>
<pre><code>url_sims1=[('http://bp.velocityfrequentflyer.com/',
[(2, 0.90452874),
(1, 0.83522302),
(4, 0.77591574),
(0, 0.72705799),
(3, 0.52282226)]),
('http://cartrawler.virginaustralia.com/',
[(3, 0.79298556),
(1, 0.78112978),
(2, 0.76006395),
(0, 0.58570701),
(4, 0.40093967)]),
('https://cartrawler.virginaustralia.com/book',
[(2, 0.9549554),
(1, 0.71705657),
(0, 0.58731651),
(3, 0.43987277),
(4, 0.38266104)]),
('https://fly.virginaustralia.com/SSW2010/VAVA/webqtrip.html',
[(2, 0.96805269),
(4, 0.68034023),
(1, 0.66391909),
(0, 0.64251828),
(3, 0.50730866)]),
('http://www.magicmillions.com.au/',
[(2, 0.84748113),
(4, 0.8338449),
(1, 0.61795002),
(0, 0.60271078),
(3, 0.20899911)])]
</code></pre>
<p>I want to replace this order </p>
<pre><code>(2,...)
(1,...)
(4,...)
(0,...)
(3,...)
</code></pre>
<p>with the following strings: categories=['arts and entertainment', 'points of passion', 'active lifestyle', 'consumer habits', 'travel savvy']. so for example, '2' will be replaced by categories[2]</p>
<p>I have written the following code:</p>
<pre><code>for i in xrange(0, len(unique_url)):
for j in xrange(0, len(sims1)):
for k in xrange(0,len(categories)):
url_sims1[i][j][k][1]+=categories[k]
</code></pre>
<p>But I am getting this error: IndexError: string index out of range</p>
<pre><code>unique_url=['http://bp.velocityfrequentflyer.com/',
'http://cartrawler.virginaustralia.com/',
'https://cartrawler.virginaustralia.com/book',
'https://fly.virginaustralia.com/SSW2010/VAVA/webqtrip.html',
'http://www.magicmillions.com.au/']
sims1=[[(2, 0.90452874),(1, 0.83522302),(4, 0.77591574),(0, 0.72705799),(3, 0.52282226)],
[(3, 0.79298556),(1, 0.78112978),(2, 0.76006395),(0, 0.58570701),(4, 0.40093967)],
[(2, 0.9549554),(1, 0.71705657),(0, 0.58731651),(3, 0.43987277),(4, 0.38266104)],
[(2, 0.96805269),(4, 0.68034023),(1, 0.66391909),(0, 0.64251828),(3, 0.50730866)],
[(2, 0.84748113),(4, 0.8338449),(1, 0.61795002),(0, 0.60271078),(3, 0.20899911)]]
</code></pre>
| 1 | 2016-07-26T02:26:14Z | 38,580,252 | <p>Given that you have <code>url_sims1</code> and <code>categories</code>, then try:</p>
<pre><code>In [4]: [(url, [(categories[i], x) for i,x in lst]) for url,lst in url_sims1]
Out[4]:
[('http://bp.velocityfrequentflyer.com/',
[('active lifestyle', 0.9045),
('points of passion', 0.8352),
('travel savvy', 0.7759),
('arts and entertainment', 0.7271),
('consumer habits', 0.5228)]),
('http://cartrawler.virginaustralia.com/',
[('consumer habits', 0.793),
('points of passion', 0.7811),
('active lifestyle', 0.7601),
('arts and entertainment', 0.5857),
('travel savvy', 0.4009)]),
('https://cartrawler.virginaustralia.com/book',
[('active lifestyle', 0.955),
('points of passion', 0.7171),
('arts and entertainment', 0.5873),
('consumer habits', 0.4399),
('travel savvy', 0.3827)]),
('https://fly.virginaustralia.com/SSW2010/VAVA/webqtrip.html',
[('active lifestyle', 0.9681),
('travel savvy', 0.6803),
('points of passion', 0.6639),
('arts and entertainment', 0.6425),
('consumer habits', 0.5073)]),
('http://www.magicmillions.com.au/',
[('active lifestyle', 0.8475),
('travel savvy', 0.8338),
('points of passion', 0.618),
('arts and entertainment', 0.6027),
('consumer habits', 0.209)])]
</code></pre>
<p>Alternatively, if your starting point is <code>unique_url</code> and <code>sims1</code>, then try:</p>
<pre><code> [(url, [(categories[i], x) for i,x in lst]) for url,lst in zip(unique_url, sims1)]
</code></pre>
| 1 | 2016-07-26T02:42:32Z | [
"python",
"for-loop",
"indexing"
] |
Python: string in string check fails | 38,580,272 | <p>I've been banging my head against this for hours, researching and refactoring, but I cannot get it to work.</p>
<pre><code>import paramiko
import sys
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
ssh.connect(switch, username='user',
password='pass')
stdin,stdout,stderr = ssh.exec_command("show interfaces descriptions")
line = stdout.readline()
while line != "":
if ("UNIT " + unit) in line:
switchPort = line [:9]
switchPort.strip()
line = stdout.readline()
print (switchPort)
command = "show vlans"
stdin,stdout,stderr = ssh.exec_command(command)
line = stdout.readline()
while line != "":
if acronym + "-s" in line or acronym + "-r" in line or ("subscribed" in line and "un" not in line and "pvlan" not in line):
line.strip(' ')
subscribedVlan = ''.join([i for i in line if i.isdigit()])
line=stdout.readline()
if switchPort in line:
portVlan = "Subscribed"
elif "un" in line and "pvlan" not in line:
unsubscribedVlan = ''.join([i for i in line if i.isdigit()])
if switchPort in line:
portVlan = "Unsubscribed"
else:
line=stdout.readline()
print ("SwitchPort: " + switchPort)
print ("line: " + line)
if switchPort in line:
portVlan = "Unsubscribed"
print ("In Unsubscribed")
else:
print("Check Failed")
</code></pre>
<p>The output:</p>
<p>SwitchPort: ge-0/0/3 <br/>
line: ge-0/0/3.0*, ge-0/0/47.0, ge-0/1/3.0*</p>
<p>Check Failed</p>
<p>The main part that I am having issues with failing is in the elif portion. I had it matching the if in syntax and logic, almost exactly, except for the other instances. What is throwing me for a loop is that switchPort printed matches a piece of the string of line. Does anyone have any idea what might be tripping this up?</p>
<p>I tried converting both variables to strings before the check, and that did not work. </p>
| 0 | 2016-07-26T02:45:48Z | 38,580,341 | <p>Sometimes there are small differences between strings that can't easily be seen in the console. Try this:</p>
<pre><code>print('SwitchPort: {!r}'.format(switchPort))
print('line: {!r}'.format(line))
</code></pre>
<p>It will likely make the difference easier to spot.</p>
<p>Per discussion above, the actual issue here was a trailing space. The fix is to change:</p>
<pre><code>switchPort.strip()
</code></pre>
<p>to</p>
<pre><code>switchPort = switchPort.strip()
</code></pre>
<p>(<code>str.strip</code> doesn't modify anything; it returns a new, stripped, string.)</p>
| 0 | 2016-07-26T02:56:57Z | [
"python",
"string",
"compare"
] |
How to Save file names and their directories path in a text file using Python | 38,580,290 | <p>I am trying to find a string that is contained in files under a directory. Then make it to store it's file names and directories under a new text file or something.
I got upto where it is going through a directory and finding a string, then printing a result. But not sure of the next step. </p>
<p>Please help, I'm completely new to coding and python. </p>
<pre><code>import glob, os
#Open a source as a file and assign it as source
source = open('target.txt').read()
filedirectories = []
#locating the source file and printing the directories.
os.chdir("/Users/a1003584/desktop")
for root, dirs, files in os.walk(".", topdown=True):
for name in files:
print(os.path.join(root, name))
if source in open(os.path.join(root, name)).read():
print 'treasure found.'
</code></pre>
| 0 | 2016-07-26T02:48:32Z | 38,580,414 | <p>Don't do a string comparison if your looking for a dictionary. Instead use the json module. Like this.</p>
<pre><code>import json
import os
filesFound = []
def searchDir(dirName):
for name in os.listdir(dirName):
# If it is a file.
if os.isfile(dirName+name):
try:
fileCon = json.load(dirName+name)
except:
print("None json file.")
if "KeySearchedFor" in fileCon:
filesFound.append(dirName+name)
# If it is a directory.
else:
searchDir(dirName+name+'/')
# Change this to the directory your looking in.
searchDir("~/Desktop")
open("~/Desktop/OutFile.txt",'w').write(filesFound)
</code></pre>
| 0 | 2016-07-26T03:07:09Z | [
"python",
"string-comparison",
"file-comparison"
] |
How to Save file names and their directories path in a text file using Python | 38,580,290 | <p>I am trying to find a string that is contained in files under a directory. Then make it to store it's file names and directories under a new text file or something.
I got upto where it is going through a directory and finding a string, then printing a result. But not sure of the next step. </p>
<p>Please help, I'm completely new to coding and python. </p>
<pre><code>import glob, os
#Open a source as a file and assign it as source
source = open('target.txt').read()
filedirectories = []
#locating the source file and printing the directories.
os.chdir("/Users/a1003584/desktop")
for root, dirs, files in os.walk(".", topdown=True):
for name in files:
print(os.path.join(root, name))
if source in open(os.path.join(root, name)).read():
print 'treasure found.'
</code></pre>
| 0 | 2016-07-26T02:48:32Z | 38,580,422 | <p>This should write the output to a csv file</p>
<pre><code>import csv
import os
with open('target.txt') as infile: source = infile.read()
with open("output.csv", 'w') as fout:
outfile = csv.writer(fout)
outfile.writerow("Directory FileName FilePath".split())
for root, dirnames, fnames in os.walk("/Users/a1003584/desktop", topdown=True):
for fname in fnames:
with open(os.path.join(root, fname)) as infile:
if source not in infile.read(): continue
outfile.writerow(root, fname, os.path.join(root, fname))
</code></pre>
| 0 | 2016-07-26T03:08:11Z | [
"python",
"string-comparison",
"file-comparison"
] |
pandas calculate the counts and sum group by each category | 38,580,327 | <p>i have a dataframe:</p>
<pre><code> category num1 num2 mark
1 A 2 2 0
2 B 3 3 1
3 C 4 2 2
4 C 3 5 2
5 D 6 8 0
6 E 7 5 1
7 D 8 1 1
</code></pre>
<p>i want to calculate the counts number for each category group by the mark(as the columns), like:</p>
<pre><code>the counts:
catgory mark_0 mark_1 mark_2
A 1 0 0
B 0 1 0
C 0 0 2
D 0 2 0
E 0 1 0
</code></pre>
<p>another is calculate the sum of the number for each category group by the mark(as the columns), like:</p>
<pre><code>the sum:
category numsum_0 numsum_1 numsum_2
A 2 0 0
B 0 3 0
C 0 0 7
D 0 14 0
E 0 7 0
</code></pre>
<p>and my method is ï¼</p>
<pre><code>df_z[df_z['mark']==0]['category'].value_counts()
df_z[df_z['mark']==0].groupby(['category'], sort=False).sum()
</code></pre>
<p>but it is inefficient</p>
| 2 | 2016-07-26T02:55:39Z | 38,580,452 | <pre><code>>>> pd.pivot_table(df,index=['category'],columns=['mark'],aggfunc=len).fillna(0)
num
mark 0 1 2
category
A 1.0 0.0 0.0
B 0.0 1.0 0.0
C 0.0 0.0 2.0
D 1.0 1.0 0.0
E 0.0 1.0 0.0
>>> pd.pivot_table(df,index=['category'],columns=['mark'],aggfunc=np.sum).fillna(0)
num
mark 0 1 2
category
A 2.0 0.0 0.0
B 0.0 3.0 0.0
C 0.0 0.0 7.0
D 6.0 8.0 0.0
E 0.0 7.0 0.0
</code></pre>
| 3 | 2016-07-26T03:13:25Z | [
"python",
"pandas"
] |
pandas calculate the counts and sum group by each category | 38,580,327 | <p>i have a dataframe:</p>
<pre><code> category num1 num2 mark
1 A 2 2 0
2 B 3 3 1
3 C 4 2 2
4 C 3 5 2
5 D 6 8 0
6 E 7 5 1
7 D 8 1 1
</code></pre>
<p>i want to calculate the counts number for each category group by the mark(as the columns), like:</p>
<pre><code>the counts:
catgory mark_0 mark_1 mark_2
A 1 0 0
B 0 1 0
C 0 0 2
D 0 2 0
E 0 1 0
</code></pre>
<p>another is calculate the sum of the number for each category group by the mark(as the columns), like:</p>
<pre><code>the sum:
category numsum_0 numsum_1 numsum_2
A 2 0 0
B 0 3 0
C 0 0 7
D 0 14 0
E 0 7 0
</code></pre>
<p>and my method is ï¼</p>
<pre><code>df_z[df_z['mark']==0]['category'].value_counts()
df_z[df_z['mark']==0].groupby(['category'], sort=False).sum()
</code></pre>
<p>but it is inefficient</p>
| 2 | 2016-07-26T02:55:39Z | 38,580,643 | <p>Use <code>agg</code>.</p>
<pre><code>idx_cols = ['category', 'mark']
agg_dict = {'num1': {'Sum': 'sum'}, 'num2': {'Count': 'count'}}
df.set_index(idx_cols).groupby(level=[0, 1]).agg(agg_dict).unstack()
</code></pre>
<p><a href="http://i.stack.imgur.com/i0zwv.png" rel="nofollow"><img src="http://i.stack.imgur.com/i0zwv.png" alt="enter image description here"></a></p>
| 3 | 2016-07-26T03:40:04Z | [
"python",
"pandas"
] |
To remove an element and assign the list in one line | 38,580,337 | <p>So as the question says, is it possible to remove an element and return the list in one line?</p>
<p>So if lets say</p>
<pre><code>a = [1, 3, 2, 4]
b = a.remove(1)
</code></pre>
<p>This would set b to be NoneType, so I was wondering if there's a way to do this.</p>
| -1 | 2016-07-26T02:56:40Z | 38,580,371 | <p>I suppose this would work:</p>
<pre><code>a = [1, 3, 2, 4]
b = (a.remove(1), a)[1]
</code></pre>
<p>This is assuming that you want to do both things:</p>
<ol>
<li>Modify the original list by removing the element, and</li>
<li>Return the (now modified) list.</li>
</ol>
<p><strong>EDIT</strong></p>
<p>Another alternative:</p>
<pre><code>b = a.remove(1) or a
</code></pre>
<p>Both are fairly confusing; I'm not sure I would use either in code.</p>
<p><strong>EDIT 2</strong></p>
<p>Since you mentioned wanting to use this in a lambda... are you aware that you can use an actual named function any time you would otherwise use a lambda?</p>
<p>E.g. instead of something like this:</p>
<pre><code>map(lambda x: x.remove(1) and x, foo)
</code></pre>
<p>You can do this:</p>
<pre><code>def remove_and_return(x):
x.remove(1)
return x
map(remove_and_return, foo)
</code></pre>
| 2 | 2016-07-26T03:01:15Z | [
"python",
"list"
] |
To remove an element and assign the list in one line | 38,580,337 | <p>So as the question says, is it possible to remove an element and return the list in one line?</p>
<p>So if lets say</p>
<pre><code>a = [1, 3, 2, 4]
b = a.remove(1)
</code></pre>
<p>This would set b to be NoneType, so I was wondering if there's a way to do this.</p>
| -1 | 2016-07-26T02:56:40Z | 38,580,386 | <p>Since <code>remove</code> returns <code>None</code>, you could just <code>or a</code> to it:</p>
<pre><code>>>> a = [1, 3, 2, 4]
>>> a.remove(1) or a
[3, 2, 4]
</code></pre>
| 2 | 2016-07-26T03:02:29Z | [
"python",
"list"
] |
To remove an element and assign the list in one line | 38,580,337 | <p>So as the question says, is it possible to remove an element and return the list in one line?</p>
<p>So if lets say</p>
<pre><code>a = [1, 3, 2, 4]
b = a.remove(1)
</code></pre>
<p>This would set b to be NoneType, so I was wondering if there's a way to do this.</p>
| -1 | 2016-07-26T02:56:40Z | 38,580,875 | <p>List <code>a</code> assign to <code>b</code>:</p>
<pre><code>b = a.remove(1) or a
a is b # True
</code></pre>
<p>Using <code>b</code> is the same to use <code>a</code>, and it's dangerous if you get a final object like <code>[b, c, d]</code>, because if you update one of this list element, the all elements will <em>update</em> too. </p>
<p>Compare to:</p>
<pre><code>import copy
b = a.remove(1) or copy.copy(a)
</code></pre>
<p>I think this way should be safer.</p>
| 0 | 2016-07-26T04:09:59Z | [
"python",
"list"
] |
Python - TypeError: Error when calling the metaclass bases int() takes at most 2 arguments (3 given) | 38,580,579 | <p>My code doesn't work in Sublime Text 3 and the error is shown below. However, it does work in IDLE and so I am rather confused. I have read similar questions but it seems that they are not exactly the same as my problem. Could anyone tell me what have I done wrong? Thank you.</p>
<pre><code>class Animal(object):
def __init__(self, name):
self.name = name
zebra = Animal("Jeffrey")
print zebra.name
TypeError: Error when calling the metaclass bases
int() takes at most 2 arguments (3 given)
</code></pre>
| -1 | 2016-07-26T03:32:11Z | 38,580,984 | <p>I suspect you had redefined <code>object</code> when you were getting the error. If <code>object</code> was bound to an integer (e.g. after <code>object = 3</code> or similar), any <code>class</code> statement that explicitly names <code>object</code> as a base will cause exactly the exception you describe.</p>
<p>This is a good example of why it's a bad idea to use the names of builtin objects (like <code>object</code> itself) for your own variables. It's <em>legal</em> to use the names, but doing so can cause very confusing errors in other parts of your code if you don't remember that the name has been shadowed.</p>
| 0 | 2016-07-26T04:24:06Z | [
"python",
"sublimetext3"
] |
CanWeMakeIt function python, it doesn´t return anything | 38,580,602 | <p>I have to write a function that should return the bool value True if you can spell out myWord using only the letters in myLetters, and return the bool value False if it cannot.<br>
To do this I need my letterPoints dictionary which is:</p>
<pre><code>global letterPoints
letterPoints = {"A": 1, "B": 3, "C": 3, "D": 2, "E": 1, "F": 4, "G": 2, "H": 4, "I": 1, "J":8, "K": 5, "L": 1, "M": 3, "N": 1, "O": 1, "P": 3, "Q": 10, "R": 1, "S": 1, "T": 1, "U": 1, "V": 4, "W": 4, "X": 8, "Y": 4, "Z": 10}
def canWeMakeIt(myWord, myLetters):
canMake = True
letterPoints= list(myLetters)
length=len(myWord)
for i in range(length):
i=i+1
letter=myWord[i]
if letter not in letterPoints:
canMake = False
else:
letterPoints.remove(letter)
return canMake
</code></pre>
| -3 | 2016-07-26T03:34:07Z | 38,580,726 | <p>Here is your function</p>
<pre><code>def canWeMakeIt(my_word, letters):
allowed = list(letters):
for i in my_word:
if i not in allowed:
return False
return True
#NOTICE HOW YOU MUST CALL IT TO DO SOMETHING
print(canWeMakeIt("cat","tack"))
</code></pre>
<p>Now let's analize your code : </p>
<ul>
<li>Your indentation is not correct</li>
<li>You don't have to increase i in for loop</li>
<li>You don't need to use dict if you don't know how, and it's unnecessary </li>
</ul>
<p>Basicly it's work like this:</p>
<pre><code>def canWeMakeIt(myWord, myLetters):
canMake = True
letterPoints = list(myLetters)
length = len(myWord)
for i in range(length):
letter = myWord[i]
if letter not in letterPoints:
canMake = False
return canMake
print(canWeMakeIt("cat","tac"))
</code></pre>
<p>You notice the difference ;)</p>
| 1 | 2016-07-26T03:49:51Z | [
"python"
] |
CanWeMakeIt function python, it doesn´t return anything | 38,580,602 | <p>I have to write a function that should return the bool value True if you can spell out myWord using only the letters in myLetters, and return the bool value False if it cannot.<br>
To do this I need my letterPoints dictionary which is:</p>
<pre><code>global letterPoints
letterPoints = {"A": 1, "B": 3, "C": 3, "D": 2, "E": 1, "F": 4, "G": 2, "H": 4, "I": 1, "J":8, "K": 5, "L": 1, "M": 3, "N": 1, "O": 1, "P": 3, "Q": 10, "R": 1, "S": 1, "T": 1, "U": 1, "V": 4, "W": 4, "X": 8, "Y": 4, "Z": 10}
def canWeMakeIt(myWord, myLetters):
canMake = True
letterPoints= list(myLetters)
length=len(myWord)
for i in range(length):
i=i+1
letter=myWord[i]
if letter not in letterPoints:
canMake = False
else:
letterPoints.remove(letter)
return canMake
</code></pre>
| -3 | 2016-07-26T03:34:07Z | 38,586,434 | <p>You could count the letters in <code>word</code> through a <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow"><code>collections.Counter</code></a> and then compare those letters and the number of occurrences to the keys and values of the dictionary <code>available_letters</code> you pass to the function:</p>
<pre><code>from collections import Counter
def can_we_make_it(word, available_letters):
letter_counter = Counter(word.upper())
for letter, count in letter_counter.items():
if count > available_letters.get(letter, 0):
return False
return True
</code></pre>
<p>In the example you provided the keys of the dictionary passed to the function are in upper case. I'm making the same assumption here, i.e. the keys of <code>available_letters</code> are <strong>capital letters</strong>. It is important to note that as Python is case sensitive, it is necessary to convert <code>word</code> to upper case through <code>word.upper()</code> in order to avoid <code>KeyError</code>exceptions when <code>word</code> contains lower case letters. </p>
<p>It is also worth pointing out that you should check the condition <code>count > available_letters.get(letter, 0)</code> rather than <code>count > available_letters[letter]</code> to avoid a <code>KeyError</code> exception when <code>word</code> contains a letter that is not present in <code>available_letters</code>.</p>
<p>Demo:</p>
<pre><code>In [275]: can_we_make_it('one', {'O': 1, 'N': 1, 'E': 1})
Out[275]: True
In [276]: can_we_make_it('Zone', {'O': 1, 'N': 1, 'E': 1})
Out[276]: False
In [277]: can_we_make_it('Zone', {'O': 1, 'N': 1, 'E': 1, 'Z': 1})
Out[277]: True
In [278]: can_we_make_it('ozone', {'O': 1, 'N': 1, 'E': 1, 'Z': 1})
Out[278]: False
In [279]: can_we_make_it('ozone', {'O': 2, 'N': 1, 'E': 1, 'Z': 1})
Out[279]: True
</code></pre>
<p>NOTE: I've taken the liberty to change the identifiers to make them more pythonic.</p>
| 0 | 2016-07-26T09:45:22Z | [
"python"
] |
Checking if Pyro remote objects are reachable | 38,580,646 | <p>I have a one Pyro server running in each of my VMs. These are all the same objects, and I'm just running them to ensure reliability. I'd like to be able to monitor whether these objects are "alive" and reachable or not. </p>
<p>Assuming I have their URIs, how can I check that without trying to run a method of the actual object to see if it runs? </p>
<p>One option is to write a simple <code>noop</code> method in these objects, call it remotely and if there's a connection issue I'd know the object is not reachable.</p>
<p>Is there a built-in way to do this in Pyro? Seems like a common enough use-case.</p>
| 0 | 2016-07-26T03:40:37Z | 38,674,487 | <p>You don't have to add a <code>noop</code> / <code>ping</code> method to your objects, because you can use the <code>_pyroBind()</code> method on a proxy object for this. It will raise a CommunicationError if the object is not reachable. For example to see if the name server is running on port 9999:</p>
<pre><code>import Pyro4
import Pyro4.errors
with Pyro4.Proxy("PYRO:Pyro.NameServer@localhost:9999") as p:
try:
p._pyroBind()
print("YEP IT IS RUNNING!")
except Pyro4.errors.CommunicationError:
print("NOPE IT IS NOT REACHABLE!")
</code></pre>
| 1 | 2016-07-30T13:32:02Z | [
"python",
"pyro"
] |
Synchronize two element values in PyQt5 | 38,580,702 | <p>I have a slider and a text box that contains an integer (is there a dedicated integer box?) in PyQt5 shown side by side.</p>
<p>I need these two values to be synchronized, and the way I am doing it right now is with a QtTimer and if statements detecting if one value has changed more recently than the other, and then updating the opposite element. I was told this was "hacky" and was wondering if there was a proper way to do this.</p>
<p>You can see the text box values and sliders that I need to synchronize in the clear areas of the image below.</p>
<p><a href="http://i.stack.imgur.com/Vnx3U.png" rel="nofollow"><img src="http://i.stack.imgur.com/Vnx3U.png" alt="Interface example"></a></p>
| 0 | 2016-07-26T03:46:41Z | 38,584,101 | <p>You can just connect each of the sliders to the other one, straight-forward. I don't know the exact connection you want between the sliders, but it could look something like this.</p>
<pre><code>max_player_slider.valueChanged.connect(self.slider1_fu)
npc_stream_slider.valueChanged.conenct(self.slider2_fu)
def slider1_fu(self):
# do stuff with the npc_stream_slider
def slider2_fu(self):
# do stuff with the max_player_slider
</code></pre>
<p>Edit: Here is a <a href="https://www.youtube.com/watch?v=lhCQAngt7ys" rel="nofollow">Tutorial on YouTube</a> that might be helpful.</p>
| 1 | 2016-07-26T07:55:31Z | [
"python",
"python-3.x",
"pyqt",
"synchronization",
"pyqt5"
] |
Synchronize two element values in PyQt5 | 38,580,702 | <p>I have a slider and a text box that contains an integer (is there a dedicated integer box?) in PyQt5 shown side by side.</p>
<p>I need these two values to be synchronized, and the way I am doing it right now is with a QtTimer and if statements detecting if one value has changed more recently than the other, and then updating the opposite element. I was told this was "hacky" and was wondering if there was a proper way to do this.</p>
<p>You can see the text box values and sliders that I need to synchronize in the clear areas of the image below.</p>
<p><a href="http://i.stack.imgur.com/Vnx3U.png" rel="nofollow"><img src="http://i.stack.imgur.com/Vnx3U.png" alt="Interface example"></a></p>
| 0 | 2016-07-26T03:46:41Z | 38,589,896 | <p>The simple solution is to connect the <code>valueChanged</code> for each slider/number box to a slot which synchronises the values</p>
<pre><code>self.slider1.valueChanged.connect(self.handleSlider1ValueChange)
self.numbox1.valueChanged.connect(self.handleNumbox1ValueChange)
@QtCore.pyqtSlot(int)
def handleSlider1ValueChange(self, value):
self.numbox1.setValue(value)
@QtCore.pyqtSlot(int)
def handleNumbox1ValueChange(self.value):
self.slider1.setValue(value)
</code></pre>
<p>A better solution is to define a custom slider class that handles everything internally. This way you only have to handle the synchronisation once.</p>
<pre><code>from PyQt5 import QtCore, QtWidgets
class CustomSlider(QtWidgets.QWidget):
def __init__(self, *args, **kwargs):
super(CustomSlider, self).__init__(*args, **kwargs)
self.slider = QtWidgets.QSlider(QtCore.Qt.Horizontal)
self.slider.valueChanged.connect(self.handleSliderValueChange)
self.numbox = QtWidgets.QSpinBox()
self.numbox.valueChanged.connect(self.handleNumboxValueChange)
layout = QtWidgets.QHBoxLayout(self)
layout.addWidget(self.numbox)
layout.addWidget(self.slider)
@QtCore.pyqtSlot(int)
def handleSliderValueChange(self, value):
self.numbox.setValue(value)
@QtCore.pyqtSlot(int)
def handleNumboxValueChange(self, value):
# Prevent values outside slider range
if value < self.slider.minimum():
self.numbox.setValue(self.slider.minimum())
elif value > self.slider.maximum():
self.numbox.setValue(self.slider.maximum())
self.slider.setValue(self.numbox.value())
app = QtWidgets.QApplication([])
slider1 = CustomSlider()
slider2 = CustomSlider()
window = QtWidgets.QWidget()
layout = QtWidgets.QVBoxLayout(window)
layout.addWidget(slider1)
layout.addWidget(slider2)
window.show()
app.exec_()
</code></pre>
<hr>
<p><strong>Edit</strong>: With regard to comments from ekhumoro, the above class can be simplified to</p>
<pre><code>class CustomSlider(QtWidgets.QWidget):
def __init__(self, *args, **kwargs):
super(CustomSlider, self).__init__(*args, **kwargs)
self.slider = QtWidgets.QSlider(QtCore.Qt.Horizontal)
self.numbox = QtWidgets.QSpinBox()
self.numbox.setRange(self.slider.minimum(), self.slider.maximum())
self.slider.valueChanged.connect(self.numbox.setValue)
self.slider.rangeChanged.connect(self.numbox.setRange)
self.numbox.valueChanged.connect(self.slider.setValue)
layout = QtWidgets.QHBoxLayout(self)
layout.addWidget(self.numbox)
layout.addWidget(self.slider)
</code></pre>
<p>You'll probably also want to mimic some of the <code>QSlider</code> methods to change the range and value. Note we don't need to explicitly set anything on <code>self.numbox</code> as the signal/slot connections made above take care of it.</p>
<pre><code> @QtCore.pyqtSlot(int)
def setMinimum(self, minval):
self.slider.setMinimum(minval)
@QtCore.pyqtSlot(int)
def setMaximum(self, maxval):
self.slider.setMaximum(maxval)
@QtCore.pyqtSlot(int, int)
def setRange(self, minval, maxval):
self.slider.setRange(minval, maxval)
@QtCore.pyqtSlot(int)
def setValue(self, value):
self.slider.setValue(value)
</code></pre>
| 2 | 2016-07-26T12:26:40Z | [
"python",
"python-3.x",
"pyqt",
"synchronization",
"pyqt5"
] |
redirect in loadhook in web.py | 38,580,816 | <p>I'm making a web.py app. I'm using a unloadhook function to check if a certain var is in the session for each call.</p>
<p>I need to redirect (to index) if it's not there. However, firefox gives me the message that the redirect will never terminate when I call web.seeother in the unloadhook function. I can correctly detect both cases in the unloadhook and treat the case with the var in the session, but not the second.</p>
<p><code>
def xCheck():
if 'x' in session:
print >> sys.stderr, "x in"
print >> sys.stderr, str(dict(session))
return
else:
print >> sys.stderr, "x out"
return web.seeother('/')</p>
<p>app.add_processor(web.unloadhook(sessionCheck))
</code></p>
| 0 | 2016-07-26T04:00:53Z | 38,581,743 | <p>I think redirection is in dead loop. Maybe your certain <code>var</code> doesn't be saved in session after calling <code>web.seeother</code></p>
| 0 | 2016-07-26T05:35:39Z | [
"python",
"http",
"web.py"
] |
Python Loop through dictionary | 38,580,839 | <p>I have a file that I wish to parse. It has data in the json format, but the file is not a json file. I want to loop through the file, and pull out the ID where totalReplyCount is greater than 0.</p>
<pre><code> { "totalReplyCount": 0,
"newLevel":{
"main":{
"url":"http://www.someURL.com",
"name":"Ronald Whitlock",
"timestamp":"2016-07-26T01:22:03.000Z",
"text":"something great"
},
"id":"z12wcjdxfqvhif5ee22ys5ejzva2j5zxh04"
}
},
{ "totalReplyCount": 4,
"newLevel":{
"main":{
"url":"http://www.someUR2L.com",
"name":"other name",
"timestamp":"2016-07-26T01:22:03.000Z",
"text":"something else great"
},
"id":"kjsdbesd2wd2eedd23rf3r3r2e2dwe2edsd"
}
},
</code></pre>
<p>My initial attempt was to do the following</p>
<pre><code>def readCsv(filename):
with open(filename, 'r') as csvFile:
for row in csvFile["totalReplyCount"]:
print row
</code></pre>
<p>but I get an error stating </p>
<blockquote>
<p>TypeError: 'file' object has no attribute '<strong>getitem</strong>'</p>
</blockquote>
<p>I know this is just an attempt at printing and not doing what I want to do, but I am a novice at python and lost as to what I am doing wrong. What is the correct way to do this? My end result should look like this for the ids:</p>
<pre><code>['insdisndiwneien23e2es', 'lsndion2ei2esdsd',....]
</code></pre>
<p><em>EDIT 1- 7/26/16</em></p>
<p>I saw that I made a mistake in my formatting when I copied the code (it was late, I was tired..). I switched it to a proper format that is more like JSON. This new edit properly matches file I am parsing. I then tried to parse it with JSON, and got the <code>ValueError: Extra data: line 2 column 1 - line X column 1</code>:, where line X is the end of the line.</p>
<pre><code> def readCsv(filename):
with open(filename, 'r') as file:
data=json.load(file)
pprint(data)
</code></pre>
<p>I also tried DictReader, and got a <code>KeyError: 'totalReplyCount'</code>. Is the dictionary un-ordered?</p>
<p><em>EDIT 2 -7/27/16</em></p>
<p>After taking a break, coming back to it, and thinking it over, I realized that what I have (after proper massaging of the data) is a CSV file, that contains a proper JSON object on each line. So, I have to parse the CSV file, then parse each line which is a top level, whole and complete JSON object. The code I used to try and parse this is below but all I get is the first string character, an open curly brace '{' :</p>
<pre><code>def readCsv(filename):
with open(filename, 'r') as csvfile:
for row in csv.DictReader(csvfile):
for item in row:
print item[0]
</code></pre>
<p>I am guessing that the DictReader is converting the json object to a string, and that is why I am only getting a curly brace as opposed to the first key. If I was to do <code>print item[0:5]</code> I would get a mish mash of the first 4 characters in an un-ordered fashion on each line, which I assume is because the format has turned into an un-ordered list? I think I understand my problem a little bit better, but still wrapping my head around the data structures and the methods used to parse them. What am I missing?</p>
| 0 | 2016-07-26T04:04:57Z | 38,580,914 | <p>As the error stated, Your <code>csvFile</code> is a <code>file</code> object, it is not a <code>dict</code> object, so you can't get an item out of it.</p>
<p>if your <code>csvFile</code> is in CSV format, you can use the <a href="https://docs.python.org/2/library/csv.html" rel="nofollow" title="csv">csv</a> module to read each line of the csv into a dict :</p>
<pre><code>import csv
with open(filename) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print row['totalReplyCount']
</code></pre>
<p>note the <code>DictReader</code> method from the csv module, it will read your csv line and parse it into dict object</p>
| 0 | 2016-07-26T04:14:51Z | [
"python",
"json"
] |
Python Loop through dictionary | 38,580,839 | <p>I have a file that I wish to parse. It has data in the json format, but the file is not a json file. I want to loop through the file, and pull out the ID where totalReplyCount is greater than 0.</p>
<pre><code> { "totalReplyCount": 0,
"newLevel":{
"main":{
"url":"http://www.someURL.com",
"name":"Ronald Whitlock",
"timestamp":"2016-07-26T01:22:03.000Z",
"text":"something great"
},
"id":"z12wcjdxfqvhif5ee22ys5ejzva2j5zxh04"
}
},
{ "totalReplyCount": 4,
"newLevel":{
"main":{
"url":"http://www.someUR2L.com",
"name":"other name",
"timestamp":"2016-07-26T01:22:03.000Z",
"text":"something else great"
},
"id":"kjsdbesd2wd2eedd23rf3r3r2e2dwe2edsd"
}
},
</code></pre>
<p>My initial attempt was to do the following</p>
<pre><code>def readCsv(filename):
with open(filename, 'r') as csvFile:
for row in csvFile["totalReplyCount"]:
print row
</code></pre>
<p>but I get an error stating </p>
<blockquote>
<p>TypeError: 'file' object has no attribute '<strong>getitem</strong>'</p>
</blockquote>
<p>I know this is just an attempt at printing and not doing what I want to do, but I am a novice at python and lost as to what I am doing wrong. What is the correct way to do this? My end result should look like this for the ids:</p>
<pre><code>['insdisndiwneien23e2es', 'lsndion2ei2esdsd',....]
</code></pre>
<p><em>EDIT 1- 7/26/16</em></p>
<p>I saw that I made a mistake in my formatting when I copied the code (it was late, I was tired..). I switched it to a proper format that is more like JSON. This new edit properly matches file I am parsing. I then tried to parse it with JSON, and got the <code>ValueError: Extra data: line 2 column 1 - line X column 1</code>:, where line X is the end of the line.</p>
<pre><code> def readCsv(filename):
with open(filename, 'r') as file:
data=json.load(file)
pprint(data)
</code></pre>
<p>I also tried DictReader, and got a <code>KeyError: 'totalReplyCount'</code>. Is the dictionary un-ordered?</p>
<p><em>EDIT 2 -7/27/16</em></p>
<p>After taking a break, coming back to it, and thinking it over, I realized that what I have (after proper massaging of the data) is a CSV file, that contains a proper JSON object on each line. So, I have to parse the CSV file, then parse each line which is a top level, whole and complete JSON object. The code I used to try and parse this is below but all I get is the first string character, an open curly brace '{' :</p>
<pre><code>def readCsv(filename):
with open(filename, 'r') as csvfile:
for row in csv.DictReader(csvfile):
for item in row:
print item[0]
</code></pre>
<p>I am guessing that the DictReader is converting the json object to a string, and that is why I am only getting a curly brace as opposed to the first key. If I was to do <code>print item[0:5]</code> I would get a mish mash of the first 4 characters in an un-ordered fashion on each line, which I assume is because the format has turned into an un-ordered list? I think I understand my problem a little bit better, but still wrapping my head around the data structures and the methods used to parse them. What am I missing?</p>
| 0 | 2016-07-26T04:04:57Z | 38,580,936 | <p>If your input file is JSON why not just use the JSON library to parse it and then run a for loop over that data. Then it is just a matter of iterating over the keys and extracting data.</p>
<pre><code>import json
from pprint import pprint
with open('data.json') as data_file:
data = json.load(data_file)
pprint(data)
</code></pre>
<p><a href="http://stackoverflow.com/questions/2835559/parsing-values-from-a-json-file-in-python">Parsing values from a JSON file in Python</a></p>
<p>Look at Justin Peel's answer. It should help.</p>
| 0 | 2016-07-26T04:18:25Z | [
"python",
"json"
] |
Python Loop through dictionary | 38,580,839 | <p>I have a file that I wish to parse. It has data in the json format, but the file is not a json file. I want to loop through the file, and pull out the ID where totalReplyCount is greater than 0.</p>
<pre><code> { "totalReplyCount": 0,
"newLevel":{
"main":{
"url":"http://www.someURL.com",
"name":"Ronald Whitlock",
"timestamp":"2016-07-26T01:22:03.000Z",
"text":"something great"
},
"id":"z12wcjdxfqvhif5ee22ys5ejzva2j5zxh04"
}
},
{ "totalReplyCount": 4,
"newLevel":{
"main":{
"url":"http://www.someUR2L.com",
"name":"other name",
"timestamp":"2016-07-26T01:22:03.000Z",
"text":"something else great"
},
"id":"kjsdbesd2wd2eedd23rf3r3r2e2dwe2edsd"
}
},
</code></pre>
<p>My initial attempt was to do the following</p>
<pre><code>def readCsv(filename):
with open(filename, 'r') as csvFile:
for row in csvFile["totalReplyCount"]:
print row
</code></pre>
<p>but I get an error stating </p>
<blockquote>
<p>TypeError: 'file' object has no attribute '<strong>getitem</strong>'</p>
</blockquote>
<p>I know this is just an attempt at printing and not doing what I want to do, but I am a novice at python and lost as to what I am doing wrong. What is the correct way to do this? My end result should look like this for the ids:</p>
<pre><code>['insdisndiwneien23e2es', 'lsndion2ei2esdsd',....]
</code></pre>
<p><em>EDIT 1- 7/26/16</em></p>
<p>I saw that I made a mistake in my formatting when I copied the code (it was late, I was tired..). I switched it to a proper format that is more like JSON. This new edit properly matches file I am parsing. I then tried to parse it with JSON, and got the <code>ValueError: Extra data: line 2 column 1 - line X column 1</code>:, where line X is the end of the line.</p>
<pre><code> def readCsv(filename):
with open(filename, 'r') as file:
data=json.load(file)
pprint(data)
</code></pre>
<p>I also tried DictReader, and got a <code>KeyError: 'totalReplyCount'</code>. Is the dictionary un-ordered?</p>
<p><em>EDIT 2 -7/27/16</em></p>
<p>After taking a break, coming back to it, and thinking it over, I realized that what I have (after proper massaging of the data) is a CSV file, that contains a proper JSON object on each line. So, I have to parse the CSV file, then parse each line which is a top level, whole and complete JSON object. The code I used to try and parse this is below but all I get is the first string character, an open curly brace '{' :</p>
<pre><code>def readCsv(filename):
with open(filename, 'r') as csvfile:
for row in csv.DictReader(csvfile):
for item in row:
print item[0]
</code></pre>
<p>I am guessing that the DictReader is converting the json object to a string, and that is why I am only getting a curly brace as opposed to the first key. If I was to do <code>print item[0:5]</code> I would get a mish mash of the first 4 characters in an un-ordered fashion on each line, which I assume is because the format has turned into an un-ordered list? I think I understand my problem a little bit better, but still wrapping my head around the data structures and the methods used to parse them. What am I missing?</p>
| 0 | 2016-07-26T04:04:57Z | 38,580,958 | <p>Parsing values from a JSON file in Python , this link has it all @ <a href="http://stackoverflow.com/questions/2835559/parsing-values-from-a-json-file-in-python">Parsing values from a JSON file in Python</a> via stackoverflow.</p>
| 0 | 2016-07-26T04:21:19Z | [
"python",
"json"
] |
Python Loop through dictionary | 38,580,839 | <p>I have a file that I wish to parse. It has data in the json format, but the file is not a json file. I want to loop through the file, and pull out the ID where totalReplyCount is greater than 0.</p>
<pre><code> { "totalReplyCount": 0,
"newLevel":{
"main":{
"url":"http://www.someURL.com",
"name":"Ronald Whitlock",
"timestamp":"2016-07-26T01:22:03.000Z",
"text":"something great"
},
"id":"z12wcjdxfqvhif5ee22ys5ejzva2j5zxh04"
}
},
{ "totalReplyCount": 4,
"newLevel":{
"main":{
"url":"http://www.someUR2L.com",
"name":"other name",
"timestamp":"2016-07-26T01:22:03.000Z",
"text":"something else great"
},
"id":"kjsdbesd2wd2eedd23rf3r3r2e2dwe2edsd"
}
},
</code></pre>
<p>My initial attempt was to do the following</p>
<pre><code>def readCsv(filename):
with open(filename, 'r') as csvFile:
for row in csvFile["totalReplyCount"]:
print row
</code></pre>
<p>but I get an error stating </p>
<blockquote>
<p>TypeError: 'file' object has no attribute '<strong>getitem</strong>'</p>
</blockquote>
<p>I know this is just an attempt at printing and not doing what I want to do, but I am a novice at python and lost as to what I am doing wrong. What is the correct way to do this? My end result should look like this for the ids:</p>
<pre><code>['insdisndiwneien23e2es', 'lsndion2ei2esdsd',....]
</code></pre>
<p><em>EDIT 1- 7/26/16</em></p>
<p>I saw that I made a mistake in my formatting when I copied the code (it was late, I was tired..). I switched it to a proper format that is more like JSON. This new edit properly matches file I am parsing. I then tried to parse it with JSON, and got the <code>ValueError: Extra data: line 2 column 1 - line X column 1</code>:, where line X is the end of the line.</p>
<pre><code> def readCsv(filename):
with open(filename, 'r') as file:
data=json.load(file)
pprint(data)
</code></pre>
<p>I also tried DictReader, and got a <code>KeyError: 'totalReplyCount'</code>. Is the dictionary un-ordered?</p>
<p><em>EDIT 2 -7/27/16</em></p>
<p>After taking a break, coming back to it, and thinking it over, I realized that what I have (after proper massaging of the data) is a CSV file, that contains a proper JSON object on each line. So, I have to parse the CSV file, then parse each line which is a top level, whole and complete JSON object. The code I used to try and parse this is below but all I get is the first string character, an open curly brace '{' :</p>
<pre><code>def readCsv(filename):
with open(filename, 'r') as csvfile:
for row in csv.DictReader(csvfile):
for item in row:
print item[0]
</code></pre>
<p>I am guessing that the DictReader is converting the json object to a string, and that is why I am only getting a curly brace as opposed to the first key. If I was to do <code>print item[0:5]</code> I would get a mish mash of the first 4 characters in an un-ordered fashion on each line, which I assume is because the format has turned into an un-ordered list? I think I understand my problem a little bit better, but still wrapping my head around the data structures and the methods used to parse them. What am I missing?</p>
| 0 | 2016-07-26T04:04:57Z | 38,581,307 | <p>Here is a shell one-liner, should solve your problem, though it's not python.</p>
<pre><code>egrep -o '"(?:totalReplyCount|id)":(.*?)$' filename | awk '/totalReplyCount/ {if ($2+0 > 0) {getline; print}}' | cut -d: -f2
</code></pre>
<p>output:
</p>
<pre><code>"kjsdbesd2wd2eedd23rf3r3r2e2dwe2edsd"
</code></pre>
| 0 | 2016-07-26T04:59:26Z | [
"python",
"json"
] |
Python Loop through dictionary | 38,580,839 | <p>I have a file that I wish to parse. It has data in the json format, but the file is not a json file. I want to loop through the file, and pull out the ID where totalReplyCount is greater than 0.</p>
<pre><code> { "totalReplyCount": 0,
"newLevel":{
"main":{
"url":"http://www.someURL.com",
"name":"Ronald Whitlock",
"timestamp":"2016-07-26T01:22:03.000Z",
"text":"something great"
},
"id":"z12wcjdxfqvhif5ee22ys5ejzva2j5zxh04"
}
},
{ "totalReplyCount": 4,
"newLevel":{
"main":{
"url":"http://www.someUR2L.com",
"name":"other name",
"timestamp":"2016-07-26T01:22:03.000Z",
"text":"something else great"
},
"id":"kjsdbesd2wd2eedd23rf3r3r2e2dwe2edsd"
}
},
</code></pre>
<p>My initial attempt was to do the following</p>
<pre><code>def readCsv(filename):
with open(filename, 'r') as csvFile:
for row in csvFile["totalReplyCount"]:
print row
</code></pre>
<p>but I get an error stating </p>
<blockquote>
<p>TypeError: 'file' object has no attribute '<strong>getitem</strong>'</p>
</blockquote>
<p>I know this is just an attempt at printing and not doing what I want to do, but I am a novice at python and lost as to what I am doing wrong. What is the correct way to do this? My end result should look like this for the ids:</p>
<pre><code>['insdisndiwneien23e2es', 'lsndion2ei2esdsd',....]
</code></pre>
<p><em>EDIT 1- 7/26/16</em></p>
<p>I saw that I made a mistake in my formatting when I copied the code (it was late, I was tired..). I switched it to a proper format that is more like JSON. This new edit properly matches file I am parsing. I then tried to parse it with JSON, and got the <code>ValueError: Extra data: line 2 column 1 - line X column 1</code>:, where line X is the end of the line.</p>
<pre><code> def readCsv(filename):
with open(filename, 'r') as file:
data=json.load(file)
pprint(data)
</code></pre>
<p>I also tried DictReader, and got a <code>KeyError: 'totalReplyCount'</code>. Is the dictionary un-ordered?</p>
<p><em>EDIT 2 -7/27/16</em></p>
<p>After taking a break, coming back to it, and thinking it over, I realized that what I have (after proper massaging of the data) is a CSV file, that contains a proper JSON object on each line. So, I have to parse the CSV file, then parse each line which is a top level, whole and complete JSON object. The code I used to try and parse this is below but all I get is the first string character, an open curly brace '{' :</p>
<pre><code>def readCsv(filename):
with open(filename, 'r') as csvfile:
for row in csv.DictReader(csvfile):
for item in row:
print item[0]
</code></pre>
<p>I am guessing that the DictReader is converting the json object to a string, and that is why I am only getting a curly brace as opposed to the first key. If I was to do <code>print item[0:5]</code> I would get a mish mash of the first 4 characters in an un-ordered fashion on each line, which I assume is because the format has turned into an un-ordered list? I think I understand my problem a little bit better, but still wrapping my head around the data structures and the methods used to parse them. What am I missing?</p>
| 0 | 2016-07-26T04:04:57Z | 38,581,394 | <p>After reading the question and all the above answers, please check if this is useful to you.</p>
<p>I have considered input file as simple file not as csv or json file.</p>
<p>Flow of code is as follow:</p>
<ul>
<li>Open and read a file in reverse order.</li>
<li>Search for ID in line. Extract ID and store in temp variable.</li>
<li>Go on reading file line by line and search totalReplyCount.</li>
<li>Once you got totalReplyCount, check it if it greater than 0.</li>
<li>If yes, then store temp ID in id_list and re-initialize temp variable.</li>
</ul>
<blockquote>
<pre><code>import re
tmp_id_to_store = ''
id_list = []
for line in reversed(open("a.txt").readlines()):
m = re.search('"id":"(\w+)"', line.rstrip())
if m:
tmp_id_to_store = m.group(1)
n = re.search('{ "totalReplyCount": (\d+),', line.rstrip())
if n:
fou = n.group(1)
if int(fou) > 0:
id_list.append(tmp_id_to_store)
tmp_id_to_store = ''
print id_list
</code></pre>
</blockquote>
<p>More check points can be added.</p>
| 1 | 2016-07-26T05:07:09Z | [
"python",
"json"
] |
Need help on a program that generate 1000 random integers between 0 and 9 and use count | 38,580,845 | <p>How to code a program that will generate 1000 random integers between 0 and 9 and displays the count for each # say counts, to store the counts for the number 0s 1s ...... 9s</p>
<p>Here's my code</p>
<pre><code>i = list(range(0,1000,9))
print (i)
i = len(i)
print (i)
</code></pre>
| -6 | 2016-07-26T04:05:53Z | 38,580,889 | <p>Use the <code>randint</code> function from random to generate an integer and store it in a <code>Counter</code>.</p>
<p>Documentation on the <code>Counter</code> collection is here: <a href="https://docs.python.org/2/library/collections.html" rel="nofollow">https://docs.python.org/2/library/collections.html</a></p>
<pre><code>from collections import counter
from random import randint
c = Counter()
for i in range(1000):
rint = randint(0,9)
c[rint] += 1
print c
</code></pre>
| 1 | 2016-07-26T04:10:52Z | [
"python"
] |
Need help on a program that generate 1000 random integers between 0 and 9 and use count | 38,580,845 | <p>How to code a program that will generate 1000 random integers between 0 and 9 and displays the count for each # say counts, to store the counts for the number 0s 1s ...... 9s</p>
<p>Here's my code</p>
<pre><code>i = list(range(0,1000,9))
print (i)
i = len(i)
print (i)
</code></pre>
| -6 | 2016-07-26T04:05:53Z | 38,583,385 | <pre><code>from random import randint
dic = {k: 0 for k in range(10)}
for i in range(1000):
num = randint(0, 9)
dic[num] += 1
print dic
</code></pre>
<p>You can use a dictionary to keep the count as well</p>
| 0 | 2016-07-26T07:15:58Z | [
"python"
] |
How can I get around this try except block? | 38,580,881 | <p>I wrote a try except block that I now realize was a bad idea because it keep throwing 'blind' exceptions that are hard to debug. The problem is that I do not know how to go about writing it another way besides going through each of the methods that are called and manually reading all the exceptions and making a case for each.</p>
<p>How would you structure this code?</p>
<pre><code>def get_wiktionary_audio(self):
'''function for adding audio path to a definition, this is meant to be run before trying to get a specific URL'''
#this path is where the audio will be saved, only added the kwarg for testing with a different path
path="study_audio/%s/words" % (self.word.language.name)
try:
wiktionary_url = "http://%s.wiktionary.org/wiki/FILE:en-us-%s.ogg" % (self.word.language.wiktionary_prefix, self.word.name)
wiktionary_page = urllib2.urlopen(wiktionary_url)
wiktionary_page = fromstring(wiktionary_page.read())
file_URL = wiktionary_page.xpath("//*[contains(concat(' ', @class, ' '), ' fullMedia ')]/a/@href")[0]
file_number = len(self.search_existing_audio())
relative_path = '%s/%s%s.ogg' % (path, self.word.name, file_number)
full_path = '%s/%s' % (settings.MEDIA_ROOT, relative_path)
os.popen("wget -q -O %s 'http:%s'" % (full_path, file_URL))
except:
return False
WordAudio.objects.create(word=self.word, audio=relative_path, source=wiktionary_url)
return True
</code></pre>
| -2 | 2016-07-26T04:10:30Z | 38,580,911 | <p>Often, exceptions come with error strings which can be used to pinpoint the problem. You can access this value like so:</p>
<pre><code>try:
# code block
except Exception as e:
print str(e)
</code></pre>
<p>You can also print what class of exception it is along with any error messages by using the <code>repr</code> method:</p>
<pre><code>try:
# code block
except Exception as e:
print repr(e)
</code></pre>
| 1 | 2016-07-26T04:13:57Z | [
"python",
"django"
] |
How can I get around this try except block? | 38,580,881 | <p>I wrote a try except block that I now realize was a bad idea because it keep throwing 'blind' exceptions that are hard to debug. The problem is that I do not know how to go about writing it another way besides going through each of the methods that are called and manually reading all the exceptions and making a case for each.</p>
<p>How would you structure this code?</p>
<pre><code>def get_wiktionary_audio(self):
'''function for adding audio path to a definition, this is meant to be run before trying to get a specific URL'''
#this path is where the audio will be saved, only added the kwarg for testing with a different path
path="study_audio/%s/words" % (self.word.language.name)
try:
wiktionary_url = "http://%s.wiktionary.org/wiki/FILE:en-us-%s.ogg" % (self.word.language.wiktionary_prefix, self.word.name)
wiktionary_page = urllib2.urlopen(wiktionary_url)
wiktionary_page = fromstring(wiktionary_page.read())
file_URL = wiktionary_page.xpath("//*[contains(concat(' ', @class, ' '), ' fullMedia ')]/a/@href")[0]
file_number = len(self.search_existing_audio())
relative_path = '%s/%s%s.ogg' % (path, self.word.name, file_number)
full_path = '%s/%s' % (settings.MEDIA_ROOT, relative_path)
os.popen("wget -q -O %s 'http:%s'" % (full_path, file_URL))
except:
return False
WordAudio.objects.create(word=self.word, audio=relative_path, source=wiktionary_url)
return True
</code></pre>
| -2 | 2016-07-26T04:10:30Z | 38,581,017 | <p>First your code is un-pythonic. You are using <code>'self'</code> for a function. "<code>self"</code> is usually reserved for a class. So in reading your code, it feels unnatural. Second, my style is to line up <code>"="</code> signs for readability. My advice is to start over -- Use standard pythonic conventions. You can get this by going through python tutorials. </p>
<p>Throw exception early and often -ONLY when the code stops running. You could also move some of the naming outside the <code>try/except</code> block. </p>
<pre><code>def get_wiktionary_audio(self):
'''function for adding audio path to a definition, this is meant to be run before trying to get a specific URL'''
#this path is where the audio will be saved, only added the kwarg for testing with a different path
path = "study_audio/%s/words" % (self.word.language.name)
try:
wiktionary_url = "http://%s.wiktionary.org/wiki/FILE:en-us-%s.ogg" % (self.word.language.wiktionary_prefix, self.word.name)
wiktionary_page = urllib2.urlopen(wiktionary_url)
wiktionary_page = fromstring(wiktionary_page.read())
file_URL = wiktionary_page.xpath("//*[contains(concat(' ', @class, ' '), ' fullMedia ')]/a/@href")[0]
file_number = len(self.search_existing_audio())
relative_path = '%s/%s%s.ogg' % (path, self.word.name, file_number)
full_path = '%s/%s' % (settings.MEDIA_ROOT, relative_path)
os.popen("wget -q -O %s 'http:%s'" % (full_path, file_URL))
except Exception as e : print e
WordAudio.objects.create(word=self.word, audio=relative_path, source=wiktionary_url)
return True
</code></pre>
| -1 | 2016-07-26T04:27:31Z | [
"python",
"django"
] |
How can I get around this try except block? | 38,580,881 | <p>I wrote a try except block that I now realize was a bad idea because it keep throwing 'blind' exceptions that are hard to debug. The problem is that I do not know how to go about writing it another way besides going through each of the methods that are called and manually reading all the exceptions and making a case for each.</p>
<p>How would you structure this code?</p>
<pre><code>def get_wiktionary_audio(self):
'''function for adding audio path to a definition, this is meant to be run before trying to get a specific URL'''
#this path is where the audio will be saved, only added the kwarg for testing with a different path
path="study_audio/%s/words" % (self.word.language.name)
try:
wiktionary_url = "http://%s.wiktionary.org/wiki/FILE:en-us-%s.ogg" % (self.word.language.wiktionary_prefix, self.word.name)
wiktionary_page = urllib2.urlopen(wiktionary_url)
wiktionary_page = fromstring(wiktionary_page.read())
file_URL = wiktionary_page.xpath("//*[contains(concat(' ', @class, ' '), ' fullMedia ')]/a/@href")[0]
file_number = len(self.search_existing_audio())
relative_path = '%s/%s%s.ogg' % (path, self.word.name, file_number)
full_path = '%s/%s' % (settings.MEDIA_ROOT, relative_path)
os.popen("wget -q -O %s 'http:%s'" % (full_path, file_URL))
except:
return False
WordAudio.objects.create(word=self.word, audio=relative_path, source=wiktionary_url)
return True
</code></pre>
| -2 | 2016-07-26T04:10:30Z | 38,581,156 | <p>One way I like to go about it is configure Python logging and log the output. This gives you a lot of flexibility in what you do with the log output. The below example logs the exception traceback. </p>
<pre><code>import traceback
import logging
logger = logging.getLogger(__name__)
try:
...
except Exception as e:
logger.exception(traceback.format_exc()) # the traceback
logger.exception(e) # just the exception message
</code></pre>
| 0 | 2016-07-26T04:44:39Z | [
"python",
"django"
] |
The comments argument of genfromtxt in numpy | 38,580,927 | <p>I am learning the I/O functions of genfromtxt in numpy.
I tried an example from the user guide of numpy. It is about the comments argument of genfromtxt.</p>
<p><strong>Here is the example from the user guide of numpy:</strong></p>
<pre><code>>>> data = """#
... # Skip me !
... # Skip me too !
... 1, 2
... 3, 4
... 5, 6 #This is the third line of the data
... 7, 8
... # And here comes the last line
... 9, 0
... """
>>> np.genfromtxt(StringIO(data), comments="#", delimiter=",")
[[ 1. 2.]
[ 3. 4.]
[ 5. 6.]
[ 7. 8.]
[ 9. 0.]]
</code></pre>
<p><strong>I tried below:</strong></p>
<pre><code>data = """# \
# Skip me ! \
# Skip me too ! \
1, 2 \
3, 4 \
5, 6 #This is the third line of the data \
7, 8 \
# And here comes the last line \
9, 0 \
"""
a = np.genfromtxt(io.BytesIO(data.encode()), comments = "#", delimiter = ",")
print (a)
</code></pre>
<p><strong>Result comes out:</strong></p>
<p>genfromtxt: Empty input file: "<_io.BytesIO object at 0x0000020555DC5EB8>"
warnings.warn('genfromtxt: Empty input file: "%s"' % fname)</p>
<p>I know the problem is with data. Anyone can teach me how to set the data as shown in the example?
Thanks a lot.</p>
| 1 | 2016-07-26T04:16:32Z | 38,581,134 | <p>Try below. First, dont use <code>"\"</code>. Second, why are you using <code>.BytesIO()</code> use <code>StringIO()</code></p>
<pre><code>import numpy as np
from StringIO import StringIO
data = """#
# Skip me !
# Skip me too !
1, 2
3, 4
5, 6 #This is the third line of the data
7, 8
# And here comes the last line
9, 0
"""
np.genfromtxt(StringIO(data), comments="#", delimiter=",")
array([[ 1., 2.],
[ 3., 4.],
[ 5., 6.],
[ 7., 8.],
[ 9., 0.]])
</code></pre>
| 0 | 2016-07-26T04:41:22Z | [
"python",
"python-3.x",
"numpy",
"genfromtxt"
] |
The comments argument of genfromtxt in numpy | 38,580,927 | <p>I am learning the I/O functions of genfromtxt in numpy.
I tried an example from the user guide of numpy. It is about the comments argument of genfromtxt.</p>
<p><strong>Here is the example from the user guide of numpy:</strong></p>
<pre><code>>>> data = """#
... # Skip me !
... # Skip me too !
... 1, 2
... 3, 4
... 5, 6 #This is the third line of the data
... 7, 8
... # And here comes the last line
... 9, 0
... """
>>> np.genfromtxt(StringIO(data), comments="#", delimiter=",")
[[ 1. 2.]
[ 3. 4.]
[ 5. 6.]
[ 7. 8.]
[ 9. 0.]]
</code></pre>
<p><strong>I tried below:</strong></p>
<pre><code>data = """# \
# Skip me ! \
# Skip me too ! \
1, 2 \
3, 4 \
5, 6 #This is the third line of the data \
7, 8 \
# And here comes the last line \
9, 0 \
"""
a = np.genfromtxt(io.BytesIO(data.encode()), comments = "#", delimiter = ",")
print (a)
</code></pre>
<p><strong>Result comes out:</strong></p>
<p>genfromtxt: Empty input file: "<_io.BytesIO object at 0x0000020555DC5EB8>"
warnings.warn('genfromtxt: Empty input file: "%s"' % fname)</p>
<p>I know the problem is with data. Anyone can teach me how to set the data as shown in the example?
Thanks a lot.</p>
| 1 | 2016-07-26T04:16:32Z | 38,581,227 | <p>In a <code>ipython3</code> (py3) interactive session I can do:</p>
<pre><code>In [326]: data = b"""#
...: ... # Skip me !
...: ... # Skip me too !
...: ... 1, 2
...: ... 3, 4
...: ... 5, 6 #This is the third line of the data
...: ... 7, 8
...: ... # And here comes the last line
...: ... 9, 0
...: ... """
In [327]:
In [327]: data
Out[327]: b'#\n# Skip me !\n# Skip me too !\n1, 2\n3, 4\n5, 6 #This is the third line of the data\n7, 8\n# And here comes the last line\n9, 0\n'
In [328]: np.genfromtxt(data.splitlines(),comments='#', delimiter=',')
Out[328]:
array([[ 1., 2.],
[ 3., 4.],
[ 5., 6.],
[ 7., 8.],
[ 9., 0.]])
</code></pre>
<p>In Python3, the string needs to be bytes; in Py2 that's the default.</p>
<p>With multiline string input (triple quotes) don't use <code>\</code>. That's a line continuation. You want to keep the <code>\n</code></p>
<pre><code>data = b"""
one
two
"""
</code></pre>
<p>Notice I could have also used:</p>
<pre><code>data = '#\n# Skip me\n...'
</code></pre>
<p>with explicit <code>\n</code>.</p>
<p><code>genfromtxt</code> works with any iterable that gives it lines. So I gave it a list of lines - produced with splitlines. The <code>StringIO</code> (or <code>ByteIO</code> in Py3) also works but it extra work.</p>
<p>Of course another option is to copy those lines to a text editor and save them as a simple text file. The copy-n-paste into the interactive session is a handy short cut, but not necessary.</p>
<pre><code>In [329]: data.splitlines()
Out[329]:
[b'#',
b'# Skip me !',
b'# Skip me too !',
b'1, 2',
b'3, 4',
b'5, 6 #This is the third line of the data',
b'7, 8',
b'# And here comes the last line',
b'9, 0']
</code></pre>
| 0 | 2016-07-26T04:51:31Z | [
"python",
"python-3.x",
"numpy",
"genfromtxt"
] |
how to know if https server is one way ssl or two way ssl | 38,581,008 | <p>Since I am new to this SSL I am asking this question. I googled and got this below mentioned HTTPS server python script. May I please know if its one way SSL or Two way SSL? And also how do I take dump to see the communication between client and server?</p>
<p>My requirement is to have one way SSL.</p>
<pre><code>import BaseHTTPServer, SimpleHTTPServer
import ssl
httpd = BaseHTTPServer.HTTPServer(('localhost', 4443), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket (httpd.socket, certfile='path/to/localhost.pem', server_side=True)
httpd.serve_forever()
</code></pre>
| 0 | 2016-07-26T04:26:44Z | 38,582,081 | <blockquote>
<p>May I please know if its one way SSL or Two way SSL</p>
</blockquote>
<p>This is one-way, i.e. the server is sending its certificate but not requesting a certificate from the client. The server could request a client certificate by adding <code>cert_reqs=ssl.CERT_REQUIRED</code> to the call of <code>ssl_wrap</code>.</p>
<blockquote>
<p>And also how do I take dump to see the communication between client and server?</p>
</blockquote>
<p>Use the packet capture tool of your choice and which is supported on your unknown platform. <a href="https://www.wireshark.org/" rel="nofollow">wireshark</a> is a good choice and you will find plenty of documentation about how to use it.</p>
| 0 | 2016-07-26T06:01:45Z | [
"java",
"python",
"ssl",
"https",
"openssl"
] |
how to make srollable candelstick plot in Python? | 38,581,078 | <p>I have following candlestick plot. I want to make it scrollable so that I can see more details. The current plot is too long to see details.
I have found examples for making a line plot scrollable at here:
<a href="http://stackoverflow.com/questions/38559270/matplotlib-scrolling-plot">Matplotlib: scrolling plot</a></p>
<p>However, updating a candlestick seems way more complicated than updating a line chart. The candlestick plot returns lines and patches. Can you help?</p>
<pre><code>from pandas.io.data import get_data_yahoo
import matplotlib.pyplot as plt
from matplotlib import dates as mdates
from matplotlib import ticker as mticker
from matplotlib.finance import candlestick_ohlc
import datetime as dt
symbol = "GOOG"
data = get_data_yahoo(symbol, start = '2011-9-01', end = '2015-10-23')
data.reset_index(inplace=True)
data['Date']=mdates.date2num(data['Date'].astype(dt.date))
fig = plt.figure()
ax1 = plt.subplot2grid((1,1),(0,0))
plt.title('How to make it scrollable')
plt.ylabel('Price')
ax1.xaxis.set_major_locator(mticker.MaxNLocator(6))
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
candlestick_ohlc(ax1,data.values,width=0.2)
</code></pre>
| 1 | 2016-07-26T04:35:16Z | 38,680,083 | <p>For what you want, I'd recommend using Plotly, which allows for interactive data visualization (including scroll, zoom, panning, etc), and has a nice Python API.</p>
<p>Here are two different ways to do it (in both cases, you will need to <code>pip install plotly</code>)</p>
<ol>
<li><p>Using the Plotly website API (requires that you <a href="https://plot.ly/feed/" rel="nofollow">create an account here</a> and get your username and API key. You'll need to be connected to Internet to generate the plot.)</p>
<pre><code>from pandas.io.data import get_data_yahoo
import matplotlib.pyplot as plt
from matplotlib import dates as mdates
from matplotlib import ticker as mticker
from matplotlib.finance import candlestick_ohlc
import datetime as dt
# Imports for Plotly
import plotly.plotly as py
import plotly.tools as tls
from plotly.tools import FigureFactory as FF
# Put your credentials here
tls.set_credentials_file(username='YourUserName', api_key='YourAPIKey')
# Getting the data
symbol = "GOOG"
data = get_data_yahoo(symbol, start = '2011-9-01', end = '2015-10-23')
data.reset_index(inplace=True)
# Not needed anymore, we'll use the string-formatted dates.
#data['Date']=mdates.date2num(data['Date'].astype(dt.date))
# Creating the Plotly Figure
fig = FF.create_candlestick(data.Open, data.High, data.Low, data.Close, dates=data.Date)
lay = fig.layout
# Formatting the ticks.
lay.xaxis.nticks = 6
lay.xaxis.tickformat = "%Y-%m-%d"
# Removing the hover annotations Plotly adds by default, but this is optional.
lay.hovermode = False
# A nice title...
lay.title = "See, I made it scrollable :)"
py.iplot(fig)
</code></pre></li>
<li><p>Using Plotly's offline mode. I assume that you will be using the Jupyter (IPython notebook). You won't need to be connected to the Internet.</p>
<pre><code>from pandas.io.data import get_data_yahoo
import matplotlib.pyplot as plt
from matplotlib import dates as mdates
from matplotlib import ticker as mticker
from matplotlib.finance import candlestick_ohlc
import datetime as dt
# Imports for Plotly
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
import plotly.tools as tls
from plotly.tools import FigureFactory as FF
init_notebook_mode() # Inject Plotly.js into the notebook
# Getting the data
symbol = "GOOG"
data = get_data_yahoo(symbol, start = '2011-9-01', end = '2015-10-23')
data.reset_index(inplace=True)
# Not needed anymore, we'll use the string-formatted dates.
#data['Date']=mdates.date2num(data['Date'].astype(dt.date))
# Creating the Plotly Figure
fig = FF.create_candlestick(data.Open, data.High, data.Low, data.Close, dates=data.Date)
lay = fig.layout
# Formatting the ticks.
lay.xaxis.nticks = 6
lay.xaxis.tickformat = "%Y-%m-%d"
# Removing the hover annotations Plotly adds by default, but this is optional.
lay.hovermode = False
# A nice title...
lay.title = "See, I made it scrollable :)"
iplot(fig)
</code></pre></li>
</ol>
<p>The result before zoom...</p>
<p><a href="http://i.stack.imgur.com/nIqGG.png" rel="nofollow"><img src="http://i.stack.imgur.com/nIqGG.png" alt="Before"></a></p>
<p>... And after zooming on a specific region.</p>
<p><a href="http://i.stack.imgur.com/kM952.png" rel="nofollow"><img src="http://i.stack.imgur.com/kM952.png" alt="After"></a></p>
<p>If you have any other question, please let me know. Hope the answer will suit you!</p>
| 1 | 2016-07-31T01:57:22Z | [
"python",
"matplotlib",
"scroll",
"finance",
"candlestick-chart"
] |
how to make srollable candelstick plot in Python? | 38,581,078 | <p>I have following candlestick plot. I want to make it scrollable so that I can see more details. The current plot is too long to see details.
I have found examples for making a line plot scrollable at here:
<a href="http://stackoverflow.com/questions/38559270/matplotlib-scrolling-plot">Matplotlib: scrolling plot</a></p>
<p>However, updating a candlestick seems way more complicated than updating a line chart. The candlestick plot returns lines and patches. Can you help?</p>
<pre><code>from pandas.io.data import get_data_yahoo
import matplotlib.pyplot as plt
from matplotlib import dates as mdates
from matplotlib import ticker as mticker
from matplotlib.finance import candlestick_ohlc
import datetime as dt
symbol = "GOOG"
data = get_data_yahoo(symbol, start = '2011-9-01', end = '2015-10-23')
data.reset_index(inplace=True)
data['Date']=mdates.date2num(data['Date'].astype(dt.date))
fig = plt.figure()
ax1 = plt.subplot2grid((1,1),(0,0))
plt.title('How to make it scrollable')
plt.ylabel('Price')
ax1.xaxis.set_major_locator(mticker.MaxNLocator(6))
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
candlestick_ohlc(ax1,data.values,width=0.2)
</code></pre>
| 1 | 2016-07-26T04:35:16Z | 38,718,928 | <p>You can plot the whole plot, and then use the slider widget to modify the axes area.</p>
<p>I couldn't reproduce your data because I don't have the <code>pandas.io.data</code> library, so I modified <a href="http://matplotlib.org/examples/pylab_examples/finance_demo.html" rel="nofollow">the candlestick example from here</a>, and added the slider.</p>
<pre><code>import matplotlib.pyplot as plt
import datetime
from matplotlib.widgets import Slider
from matplotlib.finance import quotes_historical_yahoo_ohlc, candlestick_ohlc
from matplotlib.dates import DateFormatter, WeekdayLocator,\
DayLocator, MONDAY
# (Year, month, day) tuples suffice as args for quotes_historical_yahoo
date1 = (2004, 2, 1)
date2 = (2004, 4, 12)
mondays = WeekdayLocator(MONDAY) # major ticks on the mondays
alldays = DayLocator() # minor ticks on the days
weekFormatter = DateFormatter('%b %d') # e.g., Jan 12
dayFormatter = DateFormatter('%d') # e.g., 12
quotes = quotes_historical_yahoo_ohlc('INTC', date1, date2)
if len(quotes) == 0:
raise SystemExit
fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2)
ax.xaxis.set_major_locator(mondays)
ax.xaxis.set_minor_locator(alldays)
ax.xaxis.set_major_formatter(weekFormatter)
#ax.xaxis.set_minor_formatter(dayFormatter)
#plot_day_summary(ax, quotes, ticksize=3)
candlestick_ohlc(ax, quotes, width=0.6)
ax.xaxis_date()
ax.autoscale_view()
plt.axis([datetime.date(*date1).toordinal(), datetime.date(*date1).toordinal()+10, 18.5, 22.5])
plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
axcolor = 'lightgoldenrodyellow'
axpos = plt.axes([0.2, 0.05, 0.65, 0.03], axisbg=axcolor)
spos = Slider(axpos, 'Position', datetime.date(*date1).toordinal(), datetime.date(*date2).toordinal())
def update(val):
pos = spos.val
ax.axis([pos,pos+10, 18.5, 22.5])
fig.canvas.draw_idle()
spos.on_changed(update)
plt.show()
</code></pre>
<p>I hardcoded some values of the axes sizes and positions, please be careful when adapting to your code.</p>
<p>Also same idea can be implemented to add a vertical scroll if needed.</p>
| 1 | 2016-08-02T11:16:00Z | [
"python",
"matplotlib",
"scroll",
"finance",
"candlestick-chart"
] |
Tkinter Gui stops while copying files with shutil | 38,581,084 | <p>My tkinter GUI program runs fine until it reaches to the funtion that copies specified files to destination. After that it freezes and I can't do anything with my program until the copying finishes. It works fine for small files but irritates for larger files. </p>
<p>How can I make my GUI respond while copying files?</p>
<p>Here is my sample of program</p>
<pre><code>from Tkinter import *
root = Tk()
def copy():
copy(src, dst)
if something:
copy()
else:
something...
.....
....
root.mainloop()
</code></pre>
| -2 | 2016-07-26T04:35:44Z | 38,583,138 | <p>Pff, hard to tell without real code, but it seems that your problem is that tkinter GUIs usually need their mainloop running to be fully operational.
When you use a heavy callback, tkinter stops event-loop waiting for callback to return, and file copying is heavy and long-taking operation.</p>
<p>So the solution is to detach it from mainloop as possible. The common practice is to spawn copy operation in separate thread. You could do so with _thread or threading, the 2nd seems to be simpler:</p>
<pre><code>def copy_callback(from_, to, lock):
th = threading.Thread(target=copy_thread, args=(from_, to, lock))
th.start()
def copy_thread(from_, to, lockobj):
with lockobj:
shutil.copy(from_, to)
root = tkinter.Tk()
lock = threading.Lock() # this one monitores finish of copy operation
tkinter.Button(root, text='start copy', command=lambda: copy_callback(src, dst, lock)).pack()
root.mainloop()
</code></pre>
<p>Something like this, it doesn't handle copy exceptions (you could add your own logic as needed). And you should check lock's state somewhere else to signal the end of operation to GUI (for example a check callback using tkiter's after method)</p>
<pre><code>def check_callback(inst, lock, waittime):
def check():
if lock.acquire(blocking=False):
inst['text'] = 'Success!'
lock.release()
else:
inst.after(waittime, func=check)
return check
l = tkinter.Label(root, text='Copying...')
l.pack()
check_callback(l, lock, 100)()
</code></pre>
| 0 | 2016-07-26T07:03:57Z | [
"python",
"tkinter"
] |
parsing the output of an executable | 38,581,152 | <p>I am trying to run an executable and parse its output,match the line with <code>QDLoader 9008</code> and then get the COM port value,output of the script should be<code>COM75</code> .
My script below doesn't print the line with matched string,why is that?</p>
<pre><code>import os
import re
import subprocess
'''
C:\Dropbox\h_loader>lsusb.exe
Communications Port (COM1)
Intel(R) Active Management Technology - SOL (COM3)
COMPANY HS-USB QDLoader 9008 (COM75)
COMPANY HS-USB Diagnostics 9025 (COM64)
COMPANY HS-USB NMEA 9025 (COM63)
COMPANY HS-USB Diagnostics 9091 (COM81)
'''
cmd = 'lsusb.exe'
proc = subprocess.Popen(cmd.split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(output, error) = proc.communicate()
QD_line = re.search('QDLoader 9008',output)
print QD_line
EXPECTED OUTPUT:-
COM75
</code></pre>
| 0 | 2016-07-26T04:44:01Z | 38,581,276 | <p><code>re.search</code> returns a <a href="https://docs.python.org/2/library/re.html#match-objects" rel="nofollow">match object</a>, not a string. Even if it <em>did</em> return a string, it couldn't possibly return <code>COM75</code> - regex can't read your mind, how is it supposed to know what output you're expecting?</p>
<p>You need to change your pattern to <a class='doc-link' href="http://stackoverflow.com/documentation/regex/660/capture-groups#t=201607260454209104832">capture</a> the part of the output that you're interested in:</p>
<pre><code>match= re.search(r'QDLoader 9008 \((\w*)\)',output)
</code></pre>
<p>and then access the captured string:</p>
<pre><code>print match.group(1)
</code></pre>
| 2 | 2016-07-26T04:56:44Z | [
"python"
] |
Avoiding creating new method object | 38,581,161 | <p>According to the Python 2.7.12 Documentation,</p>
<blockquote>
<p>When the attribute is a user-defined method object, a new method
object is only created if the class from which it is being retrieved
is the same as, or a derived class of, the class stored in the
original method object; <strong>otherwise, the original method object is
used as it is.</strong></p>
</blockquote>
<p>I'm trying to understand this paragraph by writing code:</p>
<pre><code># Parent: The class stored in the original method object
class Parent(object):
# func: The underlying function of original method object
def func(self):
pass
func2 = func
# Child: A derived class of Parent
class Child(Parent):
# Parent.func: The original method object
func = Parent.func
# AnotherClass: Another different class, neither subclasses nor subclassed
class AnotherClass(object):
# Parent.func: The original method object
func = Parent.func
a = Parent.func
b = Parent.func2
c = Child.func
d = AnotherClass.func
print b is a
print c is a
print d is a
</code></pre>
<p>The output is:</p>
<pre><code>False
False
False
</code></pre>
<p>I expect it to be:</p>
<pre><code>False
False
True
</code></pre>
| 2 | 2016-07-26T04:45:03Z | 38,581,377 | <p>Every time you write <code>Parent.func</code>, you are getting a new unbound method object. So <code>AnotherClass.func</code> never changes, but <code>Parent.func</code> does. You can see this if you do something like this:</p>
<pre><code>a = Parent.func
a2 = Parent.func
b = Parent.func2
c = Child.func
d = AnotherClass.func
d2 = AnotherClass.func
</code></pre>
<p>Then:</p>
<pre><code>>>> a is a2
False
>>> d is d2
True
</code></pre>
<p>So your comments referring to "the original method object" are somewhat misleading. Each part of your code that evaluates <code>Parent.func</code> is getting a different method object. (Note that the quotation you gave does not apply to <code>Parent.func</code>, because <code>func</code> as written in <code>Parent</code> is not a method object; it is a function object. It is only when you access the attribute by writing <code>Parent.func</code> that you get a method object.)</p>
<p>I'm adding a bit here to clarify the quotation you gave.</p>
<p>I think you are misunderstanding what that quotation is saying. This may be because the quotation is somewhat vague about the distinction between "the attribute" and the value retrieved by getting that attribute.</p>
<p>Let me clarify by separating two notions. In an expression like <code>something.attr</code> I'll use "the raw value" to refer to the actual value stored in the class/object dictionary, i.e., the value of <code>something.__dict__['attr']</code>. I'll use "the evaluated value" to refer to the actual result of evaluating <code>something.attr</code>. The difference between the two is that the <a href="https://docs.python.org/2/reference/datamodel.html#implementing-descriptors" rel="nofollow">descriptor protocol</a> is activated on the raw value to get the evaluated value.</p>
<p>The documentation you quoted is describing a situation where the <em>raw</em> value is a method object. This is the case in your definitions of Child and AnotherClass. The quotation does <em>not</em> apply to <code>func</code> inside Parent, because in that case the raw value is not a method; it is a function. In that case, the following paragraph of the documentation applies:</p>
<blockquote>
<p>When a user-defined method object is created by retrieving a user-defined function object...</p>
</blockquote>
<p>In other words, the documentation you quoted ("When the attribute is a user-defined method object") applies to cases like this:</p>
<pre><code>obj = [a method object]
class Foo(object):
attr = obj
</code></pre>
<p>Your quoted documentation does not apply to the following case. In this case, the attribute is "a user-defined function object":</p>
<pre><code>func = [a function object]
class Foo(object):
attr = func
</code></pre>
<p>In your example, there is no "original method object". You can only get a method object <em>after</em> the class is defined. The "original" object is a function object. When you write <code>func</code> in the class body, you are defining a function; it is only when you <em>access</em> <code>Parent.func</code> that you get a method object.</p>
| 3 | 2016-07-26T05:05:45Z | [
"python",
"python-2.7",
"object",
"inheritance",
"methods"
] |
Tkinter : How to bind parentheses key | 38,581,279 | <p>I have a program that needs to handle whenever the user enter a parentheses. I have tried:</p>
<pre><code>root.bind("<Shift-KP_9>")
</code></pre>
<p>But it didn't work, the same with </p>
<pre><code>root.bind("<Shift-9>")
</code></pre>
<p>How can I bind parentheses events into Tkinter ? Please help me </p>
| 1 | 2016-07-26T04:56:53Z | 38,581,366 | <p>No need to overthink it. <code>root.bind("<(>")</code> will work just fine.</p>
| 1 | 2016-07-26T05:05:08Z | [
"python",
"tkinter",
"bind",
"parentheses"
] |
Problems with creating a python function "getWordPoints" --Python | 38,581,387 | <p>Alright, so I need help, because i need to créate a function that calculates and returns the total point value (as an int) of myWord using the letterPoints dictionary which consists of letter:pointValue pairs. Its for a Scrabble Word Finder. I already created a dictionary with the letters. The function needs one parameter: "MyWords":</p>
<pre><code> global letterPoints
letterPoints = {"A": 1, "B": 3, "C": 3, "D": 2, "E": 1, "F": 4, "G": 2, "H": 4, "I": 1, "J":8, "K": 5, "L": 1, "M": 3, "N": 1, "O": 1, "P": 3, "Q": 10, "R": 1, "S": 1, "T": 1, "U": 1, "V": 4, "W": 4, "X": 8, "Y": 4, "Z": 10}
</code></pre>
| -5 | 2016-07-26T05:06:33Z | 38,581,652 | <pre><code>global letterPoints
letterPoints = {"A": 1, "B": 3, "C": 3, "D": 2, "E": 1, "F": 4, "G": 2, "H": 4, "I": 1, "J":8, "K": 5, "L": 1, "M": 3, "N": 1, "O": 1, "P": 3, "Q": 10, "R": 1, "S": 1, "T": 1, "U": 1, "V": 4, "W": 4, "X": 8, "Y": 4, "Z": 10}
def GetValues( MyWord ):
total = 0
for letter in MyWord:
if letter in letterPoints.keys():
total = total + letterPoints[letter]
return total
</code></pre>
| 0 | 2016-07-26T05:28:36Z | [
"python",
"function",
"variables",
"global"
] |
Using multiprocessing on a function fails with - string indices must be integers | 38,581,389 | <p>I have a function, that works in a single thread. Here's a simplified example. Basically I'm wanting to verify a few dead links and store the result in each item in a list of dictionaries.</p>
<pre><code>import requests
import sys
import logging
def main():
urls_to_check = [{'url': 'http://example.com'},
{'url': 'http://example.com'},
{'url': 'http://example.com'}]
print check_for_404(urls_to_check)
def check_for_404(urls_to_check):
for item in urls_to_check:
r = requests.get(item['url'])
item.update({'responseCode': r.status_code})
return urls_to_check
if __name__ == '__main__':
try:
main()
except:
logging.error("Unexpected error:" + str(sys.exc_info()))
</code></pre>
<p>Outputs: </p>
<pre><code>[{'url': 'http://example.com', 'responseCode': 200}, {'url': 'http://example.com', 'responseCode': 200}, {'url': 'http://example.com', 'responseCode': 200}]
</code></pre>
<p>And I'm happy with that</p>
<p>Now if I implement multiprocessing, which I understand is to split up an iterable across multiple cores and run parts of the iterable through the function...</p>
<pre><code>import requests
import sys
import logging
from multiprocessing import Pool
def main():
urls_to_check = [{'url': 'http://example.com'},
{'url': 'http://example.com'},
{'url': 'http://example.com'}]
p = Pool(5)
print p.map(check_for_404, urls_to_check)
def check_for_404(urls_to_check):
for item in urls_to_check:
r = requests.get(item['url'])
item.update({'responseCode': r.status_code})
return urls_to_check
if __name__ == '__main__':
try:
main()
except:
logging.error("Unexpected error:" + str(sys.exc_info()))
</code></pre>
<p>I get the error <code>TypeError('string indices must be integers, not str',), <traceback object at 0x10ad6c128>)</code></p>
<p>How can I implement multiprocessing so that I can process a long list of urls more quickly?</p>
<p>This is the tutorial I'm looking at:
<a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow">https://docs.python.org/2/library/multiprocessing.html</a></p>
| 0 | 2016-07-26T05:06:38Z | 38,581,559 | <p>You need to change your "check for 404's" function to accept a single url rather than a list; the map function passes the list elements in one at a time (to separate subprocesses in the pool), then reassembles them back into a list at the end:</p>
<pre><code>def check_for_404(item):
r = requests.get(item['url'])
item.update({'responseCode': r.status_code})
return item
</code></pre>
| 2 | 2016-07-26T05:20:19Z | [
"python",
"multithreading"
] |
boto3 Get a resource from a client | 38,581,465 | <p>The AWS Library for python (boto) has two different types of interfaces for working with AWS, a low level <code>client</code> and a higher level more pythonic <code>resource</code>.</p>
<p>Parts of my code use one, while other parts use the other.</p>
<p>Getting a <code>resource</code> from a <code>client</code> is found from the docs.</p>
<pre><code># Create the resource
sqs_resource = boto3.resource('sqs')
# Get the client from the resource
sqs = sqs_resource.meta.client
</code></pre>
<p>My questions is if have the client <code>sqs</code>, how do I get a <code>boto3.resource</code> from this?</p>
<p>(I can't simply just call <code>boto3.resource('sqs')</code> because the client has other things, such as credentials already attached to it, the resource for some design reason tries to fetch the AWS credentials from a bunch of places I don't want it to, I'd like it to use whatever credentials/account is set on the client)</p>
| 0 | 2016-07-26T05:12:31Z | 38,581,635 | <p>I think you should create resource and client separately as below:</p>
<pre><code>import boto3
sqs_resource = boto3.resource("sqs")
sqs_client = boto3.client("sqs")
print dir(sqs_resource)
print dir(sqs_client)
</code></pre>
<p>Output:</p>
<pre><code>[u'Message', u'Queue', '__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', u'create_queue', 'get_available_subresources', u'get_queue_by_name', 'meta', u'queues']
['_PY_TO_OP_NAME', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_cache', '_client_config', '_convert_to_request_dict', '_endpoint', '_force_path_style_s3_addressing', '_force_virtual_style_s3_addressing', '_get_waiter_config', '_loader', '_make_api_call', '_register_handlers', '_register_s3_specific_handlers', '_request_signer', '_response_parser', '_serializer', '_service_model', u'add_permission', 'can_paginate', u'change_message_visibility', u'change_message_visibility_batch', u'create_queue', u'delete_message', u'delete_message_batch', u'delete_queue', 'generate_presigned_url', 'get_paginator', u'get_queue_attributes', u'get_queue_url', 'get_waiter', u'list_dead_letter_source_queues', u'list_queues', 'meta', u'purge_queue', u'receive_message', u'remove_permission', u'send_message', u'send_message_batch', u'set_queue_attributes', 'waiter_names']
</code></pre>
<p>From above output, you will always get client from resource as sqs_resource.meta.client.</p>
<p>But vice-versa is not possible.</p>
<p>Instead, create resource and client both and use whatever you required.
Please let me know if this is useful.</p>
| 1 | 2016-07-26T05:27:13Z | [
"python",
"amazon-web-services",
"boto3"
] |
boto3 Get a resource from a client | 38,581,465 | <p>The AWS Library for python (boto) has two different types of interfaces for working with AWS, a low level <code>client</code> and a higher level more pythonic <code>resource</code>.</p>
<p>Parts of my code use one, while other parts use the other.</p>
<p>Getting a <code>resource</code> from a <code>client</code> is found from the docs.</p>
<pre><code># Create the resource
sqs_resource = boto3.resource('sqs')
# Get the client from the resource
sqs = sqs_resource.meta.client
</code></pre>
<p>My questions is if have the client <code>sqs</code>, how do I get a <code>boto3.resource</code> from this?</p>
<p>(I can't simply just call <code>boto3.resource('sqs')</code> because the client has other things, such as credentials already attached to it, the resource for some design reason tries to fetch the AWS credentials from a bunch of places I don't want it to, I'd like it to use whatever credentials/account is set on the client)</p>
| 0 | 2016-07-26T05:12:31Z | 38,595,104 | <p>There is no way to do this. If you want to use both, you should create a resource and use the embedded client. You can instantiate a resource with the exact same configuration as a client. The underlying client for the resource is created in the exact same way. The only difference between a resource's client and a client created with the exact same parameters is that the resource client adds 'Resource' to the user-agent.</p>
| 2 | 2016-07-26T16:19:16Z | [
"python",
"amazon-web-services",
"boto3"
] |
Issue with null character in Cython | 38,581,589 | <p>The following Cython code is not working as expected. </p>
<pre><code>cdef char* char_tester():
py_str = "a\0b\0c".encode("UTF-8")
cdef char* c_str = py_str
return c_str
def test():
print(char_tester())
cdef char* my_str = char_tester()
for i in range(5):
print(my_str[i])
>>> test()
b'a'
97
55
10
0
99
</code></pre>
<p>I would expect the code to be printing out the byte string 'a b c', and the ASCII values 97, 0, 98, 0, 99, in that order. Moreover, when I add the for loop for printing the characters inside the for loop, I get the expected ASCII values as output. Apparently, the <code>char*</code>returned by <code>char_tester</code>is being truncated somehow in the <code>test()</code>function. How do I prevent this from happening, and get the expected output?</p>
| 1 | 2016-07-26T05:22:40Z | 38,583,006 | <p>Assigment <code>cdef char * s = py_str</code> points to a memory location that is invalid after <code>char_tester()</code> returns. It is like a the case when a C function returns an address to local stack allocated variable, undefined behaviour.</p>
<p>With the following function</p>
<pre><code>from libc.stdlib cimport malloc
from libc.string cimport memcpy
cdef char* char_tester():
py_str = "a\0b\0c".encode("UTF-8")
cdef char* c_str
cdef char * s = py_str
cdef ssize_t slen = len(py_str)
c_str = <char *>malloc((slen+1)*sizeof(char))
memcpy(c_str, s, slen)
c_str[slen] = '\0'
return c_str
</code></pre>
<p>the test code will print (python 3.4)</p>
<pre><code>b'a'
97
0
98
0
99
</code></pre>
| 2 | 2016-07-26T06:57:22Z | [
"python",
"cython"
] |
Spline interpolation over 3 variables for scattered data in Python? | 38,581,649 | <p>With other words I got a set of data-points (x,y,z) associated to a value b and I would like to interpolate this data as accurate as possible.
Scipy.interpolate.griddata only can do a linear interpolation, what are the other options?</p>
| 0 | 2016-07-26T05:28:31Z | 38,605,726 | <p>How about interpolating x, y, z separatly? I modified <a href="http://matplotlib.org/mpl_examples/mplot3d/lines3d_demo.py" rel="nofollow">this</a> tutorial example and added interpolation to it:</p>
<pre class="lang-python prettyprint-override"><code>import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import InterpolatedUnivariateSpline
mpl.rcParams['legend.fontsize'] = 10
# let's take only 20 points for original data:
n = 20
fig = plt.figure()
ax = fig.gca(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, n)
z = np.linspace(-2, 2, n)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x, y, z, label='rough curve')
# this variable represents distance along the curve:
t = np.arange(n)
# now let's refine it to 100 points:
t2 = np.linspace(t.min(), t.max(), 100)
# interpolate vector components separately:
x2 = InterpolatedUnivariateSpline(t, x)(t2)
y2 = InterpolatedUnivariateSpline(t, y)(t2)
z2 = InterpolatedUnivariateSpline(t, z)(t2)
ax.plot(x2, y2, z2, label='interpolated curve')
ax.legend()
plt.show()
</code></pre>
<p>The result looks like this:
<a href="http://i.stack.imgur.com/JZXXz.png" rel="nofollow"><img src="http://i.stack.imgur.com/JZXXz.png" alt="3d line plot"></a></p>
<p><strong>UPDATE</strong></p>
<p>Didn't understand the question at the first time, sorry. </p>
<p>You are probably looking for tricubic interpolation. Try <a href="https://github.com/danielguterding/pytricubic" rel="nofollow">this</a>.</p>
| 0 | 2016-07-27T06:52:54Z | [
"python",
"scipy",
"interpolation",
"n-dimensional"
] |
Django Cannot find module i'm importing my model from | 38,581,952 | <p>I'm trying to import a model from another Django app in my project. However, when I try to import, I keep getting an error for: </p>
<blockquote>
<p>ImportError No module named trunk.profiles.models.</p>
</blockquote>
<p>However, when I cmnd click on the model on my IDE it takes me to the model. So it recognizes where the model is coming from, but I think for some reason Django is not recognizing the path. </p>
<p>Here is my code from my <code>models.py</code> which I'm trying to import another model, Profiles from a different Django app:</p>
<pre><code>from django.db import models
from trunk.profiles.models import Profiles # source of error
class ContentObject(models.Model):
course_name = models.CharField(max_length15)
course_topic = models.CharField(max_length = 30)
op_UserName = models.ForeignKey(Profiles)
</code></pre>
| -1 | 2016-07-26T05:53:02Z | 38,582,656 | <p>Add <code>trunk.profiles</code> to Your <code>INSTALLED_APPS</code></p>
<p><strong>settings.py</strong></p>
<pre><code>INSTALLED_APPS = [
...
'trunk.profiles'
]
</code></pre>
<p><strong>TIP</strong></p>
<p>Instead of import model, specify a model with the full application label</p>
<pre><code>from django.db import models
class ContentObject(models.Model):
course_name = models.CharField(max_length15)
course_topic = models.CharField(max_length = 30)
op_UserName = models.ForeignKey('trunk.profiles.Profiles')
</code></pre>
| 1 | 2016-07-26T06:38:53Z | [
"python",
"django",
"module",
"models"
] |
Python insert node function | 38,582,008 | <p>I am having a really hard time understanding how to properly fix my insert node function. I am not receiving any errors but I am also not displaying the list.</p>
<pre><code>class Node:
def __init__(self, data):
self.data = data
self.next = None
class Solution:
def display(self, head):
current = head
while current:
print current.data,
current = current.next
def insert(self, head, data):
self.head = head
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
mylist = Solution()
T = int(input())
head = None
for i in range(T):
data = int(input())
head = mylist.insert(head, data)
mylist.display(head)
</code></pre>
| 0 | 2016-07-26T05:56:53Z | 38,582,102 | <p>Your insert() didn't return anything. So head will be None if you assign returned value to it.</p>
| 0 | 2016-07-26T06:03:32Z | [
"python",
"python-2.7"
] |
Python insert node function | 38,582,008 | <p>I am having a really hard time understanding how to properly fix my insert node function. I am not receiving any errors but I am also not displaying the list.</p>
<pre><code>class Node:
def __init__(self, data):
self.data = data
self.next = None
class Solution:
def display(self, head):
current = head
while current:
print current.data,
current = current.next
def insert(self, head, data):
self.head = head
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
mylist = Solution()
T = int(input())
head = None
for i in range(T):
data = int(input())
head = mylist.insert(head, data)
mylist.display(head)
</code></pre>
| 0 | 2016-07-26T05:56:53Z | 38,582,233 | <p>I think this is you want</p>
<pre><code>class Node:
def __init__(self, data):
self.data = data
self.next = None
class Solution:
def __init__(self):
self.head = None
def display(self):
current = self.head
while current:
print current.data,
current = current.next
def insert(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
mylist = Solution()
T = int(input())
for i in range(T):
data = int(input())
mylist.insert(data)
mylist.display()
</code></pre>
| 0 | 2016-07-26T06:12:59Z | [
"python",
"python-2.7"
] |
How to get contents of file in Sublime Text 3 Python API | 38,582,019 | <p>I'm very new to Python and Sublime Text API dev... so this may be easy?</p>
<p>I want to display the contents of a file (that sits next to the currently open file) to a new panel window. </p>
<p>I can create a new panel no problem and get it to display a string using </p>
<pre><code>def newLogWindow(self, output):
window = self.view.window()
new_view = window.create_output_panel("log")
new_view.run_command('erase_view')
new_view.run_command('append', {'characters': output})
window.run_command("show_panel", {"panel": "output.log"})
sublime.status_message('Metalang')
pass
</code></pre>
<p>But what I need is a function to get contents of file to pass to that function.</p>
<pre><code>content = xxxx.open_file("filename.txt")
// somehow get contents of this file?
// pass it to log window
self.newLogWindow(content);
</code></pre>
<p>Thanks for your help!</p>
| 0 | 2016-07-26T05:57:35Z | 38,582,451 | <p>In Sublime Text, the built in API to open a file is tied to the <code>Window</code> and will return a <code>View</code> that corresponds to a tab. In your case, you want to update a panel (an existing <code>View</code> that doesn't relate to a tab) with the contents of the file, so the Sublime Text API can't be used for this.</p>
<p>Instead you can do it directly in Python using the <a href="https://docs.python.org/3/library/functions.html#open" rel="nofollow"><code>open</code> method</a>:</p>
<pre><code>with open('filename.txt', 'r') as myfile:
content = myfile.read()
self.newLogWindow(content)
</code></pre>
| 2 | 2016-07-26T06:27:00Z | [
"python",
"sublimetext3",
"sublimetext",
"sublime-text-plugin"
] |
How to filter data from a data frame when the number of columns are dynamic? | 38,582,127 | <p>I have a data frame like below </p>
<pre><code> A_Name B_Detail Value_B Value_C Value_D ......
0 AA X1 1.2 0.5 -1.3 ......
1 BB Y1 0.76 -0.7 0.8 ......
2 CC Z1 0.7 -1.3 2.5 ......
3 DD L1 0.9 -0.5 0.4 ......
4 EE M1 1.3 1.8 -1.3 ......
5 FF N1 0.7 -0.8 0.9 ......
6 GG K1 -2.4 -1.9 2.1 ......
</code></pre>
<p>This is just a sample of data frame, I can have n number of columns like (Value_A, Value_B, Value_C, ........... Value_N)</p>
<p>Now i want to filter all rows where absolute value of all columns (Value_A, Value_B, Value_C, ....) is less than 1.</p>
<p>If you have limited number of columns, you can filter the data by simply putting 'and' condition on columns in dataframe, but I am not able to figure out what to do in this case. </p>
<p>I don't know what would be number of such columns, the only thing I know that such columns would be prefixed with 'Value'.</p>
<p>In above case output should be like </p>
<pre><code> A_Name B_Detail Value_B Value_C Value_D ......
1 BB Y1 0.76 -0.7 0.8 ......
3 DD L1 0.9 -0.5 0.4 ......
5 FF N1 0.7 -0.8 0.9 ......
</code></pre>
| 4 | 2016-07-26T06:05:23Z | 38,582,173 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html" rel="nofollow"><code>filter</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.abs.html" rel="nofollow"><code>abs</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.all.html" rel="nofollow"><code>all</code></a> for creating <code>mask</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p>
<pre><code>mask = (df.filter(like='Value').abs() < 1).all(axis=1)
print (mask)
0 False
1 True
2 False
3 True
4 False
5 True
6 False
dtype: bool
print (df[mask])
A_Name B_Detail Value_B Value_C Value_D
1 BB Y1 0.76 -0.7 0.8
3 DD L1 0.90 -0.5 0.4
5 FF N1 0.70 -0.8 0.9
</code></pre>
<p>All combination in <strong>timings</strong>:</p>
<pre><code>#len df = 70k, 5 columns
df = pd.concat([df]*10000).reset_index(drop=True)
In [47]: %timeit (df[(df.filter(like='Value').abs() < 1).all(axis=1)])
100 loops, best of 3: 7.48 ms per loop
In [48]: %timeit (df[df.filter(regex=r'Value').abs().lt(1).all(1)])
100 loops, best of 3: 7.02 ms per loop
In [49]: %timeit (df[df.filter(like='Value').abs().lt(1).all(1)])
100 loops, best of 3: 7.02 ms per loop
In [50]: %timeit (df[(df.filter(regex=r'Value').abs() < 1).all(axis=1)])
100 loops, best of 3: 7.3 ms per loop
</code></pre>
<hr>
<pre><code>#len df = 70k, 5k columns
df = pd.concat([df]*10000).reset_index(drop=True)
df = pd.concat([df]*1000, axis=1)
#only for testing, create unique columns names
df.columns = df.columns.str[:-1] + [str(col) for col in list(range(df.shape[1]))]
print (df)
In [75]: %timeit ((df[(df.filter(like='Value').abs() < 1).all(axis=1)]))
1 loop, best of 3: 10.3 s per loop
In [76]: %timeit ((df[(df.filter(regex=r'Value').abs() < 1).all(axis=1)]))
1 loop, best of 3: 10.3 s per loop
In [77]: %timeit (df[df.filter(regex=r'Value').abs().lt(1).all(1)])
1 loop, best of 3: 10.4 s per loop
In [78]: %timeit (df[df.filter(like='Value').abs().lt(1).all(1)])
1 loop, best of 3: 10.1 s per loop
</code></pre>
| 4 | 2016-07-26T06:08:53Z | [
"python",
"numpy",
"pandas",
"dataframe"
] |
How to filter data from a data frame when the number of columns are dynamic? | 38,582,127 | <p>I have a data frame like below </p>
<pre><code> A_Name B_Detail Value_B Value_C Value_D ......
0 AA X1 1.2 0.5 -1.3 ......
1 BB Y1 0.76 -0.7 0.8 ......
2 CC Z1 0.7 -1.3 2.5 ......
3 DD L1 0.9 -0.5 0.4 ......
4 EE M1 1.3 1.8 -1.3 ......
5 FF N1 0.7 -0.8 0.9 ......
6 GG K1 -2.4 -1.9 2.1 ......
</code></pre>
<p>This is just a sample of data frame, I can have n number of columns like (Value_A, Value_B, Value_C, ........... Value_N)</p>
<p>Now i want to filter all rows where absolute value of all columns (Value_A, Value_B, Value_C, ....) is less than 1.</p>
<p>If you have limited number of columns, you can filter the data by simply putting 'and' condition on columns in dataframe, but I am not able to figure out what to do in this case. </p>
<p>I don't know what would be number of such columns, the only thing I know that such columns would be prefixed with 'Value'.</p>
<p>In above case output should be like </p>
<pre><code> A_Name B_Detail Value_B Value_C Value_D ......
1 BB Y1 0.76 -0.7 0.8 ......
3 DD L1 0.9 -0.5 0.4 ......
5 FF N1 0.7 -0.8 0.9 ......
</code></pre>
| 4 | 2016-07-26T06:05:23Z | 38,582,185 | <ul>
<li>Use <code>filter</code> to get the columns you care about.</li>
<li><code>abs().lt(1)</code> to get find cells less than 1.</li>
<li><code>all(1)</code> to find rows where all <code>Value</code>'s are less than 1.</li>
</ul>
<hr>
<pre><code>df[df.filter(regex=r'Value').abs().lt(1).all(1)]
</code></pre>
<p><a href="http://i.stack.imgur.com/SU8jz.png"><img src="http://i.stack.imgur.com/SU8jz.png" alt="enter image description here"></a></p>
<hr>
<h3>Timing</h3>
<p><strong>conclusion</strong></p>
<p><code>like</code> is faster than <code>regex</code>
<code>lt</code> is faster than <code><</code></p>
<p>fastest solution is combining best of both:</p>
<pre><code>df[df.filter(like='Value').abs().lt(1).all(1)]
</code></pre>
<p><a href="http://i.stack.imgur.com/Vh4Ls.png"><img src="http://i.stack.imgur.com/Vh4Ls.png" alt="enter image description here"></a></p>
<p><strong>breakdown</strong></p>
<p><a href="http://i.stack.imgur.com/DKarb.png"><img src="http://i.stack.imgur.com/DKarb.png" alt="enter image description here"></a></p>
| 5 | 2016-07-26T06:09:35Z | [
"python",
"numpy",
"pandas",
"dataframe"
] |
How to filter data from a data frame when the number of columns are dynamic? | 38,582,127 | <p>I have a data frame like below </p>
<pre><code> A_Name B_Detail Value_B Value_C Value_D ......
0 AA X1 1.2 0.5 -1.3 ......
1 BB Y1 0.76 -0.7 0.8 ......
2 CC Z1 0.7 -1.3 2.5 ......
3 DD L1 0.9 -0.5 0.4 ......
4 EE M1 1.3 1.8 -1.3 ......
5 FF N1 0.7 -0.8 0.9 ......
6 GG K1 -2.4 -1.9 2.1 ......
</code></pre>
<p>This is just a sample of data frame, I can have n number of columns like (Value_A, Value_B, Value_C, ........... Value_N)</p>
<p>Now i want to filter all rows where absolute value of all columns (Value_A, Value_B, Value_C, ....) is less than 1.</p>
<p>If you have limited number of columns, you can filter the data by simply putting 'and' condition on columns in dataframe, but I am not able to figure out what to do in this case. </p>
<p>I don't know what would be number of such columns, the only thing I know that such columns would be prefixed with 'Value'.</p>
<p>In above case output should be like </p>
<pre><code> A_Name B_Detail Value_B Value_C Value_D ......
1 BB Y1 0.76 -0.7 0.8 ......
3 DD L1 0.9 -0.5 0.4 ......
5 FF N1 0.7 -0.8 0.9 ......
</code></pre>
| 4 | 2016-07-26T06:05:23Z | 38,582,662 | <p>In case you don't want to filter on the column name (even if they're prefixed), you can also use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</code></a> :</p>
<pre><code>>>> df[df.ix[:,2:].abs().lt(1).all(1)]
A_Name B_Detail Value_B Value_C Value_D
1 BB Y1 0.76 -0.7 0.8
3 DD L1 0.90 -0.5 0.4
5 FF N1 0.70 -0.8 0.9
</code></pre>
<p>This supposes all your "value" columns are after your "detail" columns.</p>
<p>And since everyone's benchmarking, this is even faster :</p>
<pre><code>In [7]: %timeit df[df.ix[:,2:].abs().lt(1).all(1)]
1000 loops, best of 3: 803 µs per loop
In [8]: %timeit df[df.filter(like='Value').abs().lt(1).all(1)]
1000 loops, best of 3: 939 µs per loop
</code></pre>
| 0 | 2016-07-26T06:39:19Z | [
"python",
"numpy",
"pandas",
"dataframe"
] |
How to filter data from a data frame when the number of columns are dynamic? | 38,582,127 | <p>I have a data frame like below </p>
<pre><code> A_Name B_Detail Value_B Value_C Value_D ......
0 AA X1 1.2 0.5 -1.3 ......
1 BB Y1 0.76 -0.7 0.8 ......
2 CC Z1 0.7 -1.3 2.5 ......
3 DD L1 0.9 -0.5 0.4 ......
4 EE M1 1.3 1.8 -1.3 ......
5 FF N1 0.7 -0.8 0.9 ......
6 GG K1 -2.4 -1.9 2.1 ......
</code></pre>
<p>This is just a sample of data frame, I can have n number of columns like (Value_A, Value_B, Value_C, ........... Value_N)</p>
<p>Now i want to filter all rows where absolute value of all columns (Value_A, Value_B, Value_C, ....) is less than 1.</p>
<p>If you have limited number of columns, you can filter the data by simply putting 'and' condition on columns in dataframe, but I am not able to figure out what to do in this case. </p>
<p>I don't know what would be number of such columns, the only thing I know that such columns would be prefixed with 'Value'.</p>
<p>In above case output should be like </p>
<pre><code> A_Name B_Detail Value_B Value_C Value_D ......
1 BB Y1 0.76 -0.7 0.8 ......
3 DD L1 0.9 -0.5 0.4 ......
5 FF N1 0.7 -0.8 0.9 ......
</code></pre>
| 4 | 2016-07-26T06:05:23Z | 38,583,338 | <p>You can match the columns using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow">str.contains</a> then use <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.Series.apply.html" rel="nofollow">apply()</a> with <code>lambda</code> :</p>
<pre><code>cols = df.columns[df.columns.str.contains('Value')]
df[df[cols].apply(lambda x: abs(x) < 1).sum(axis=1) == len(cols)]
</code></pre>
<p>Output:</p>
<pre><code> A_Name B_Detail Value_B Value_C Value_D
1 BB Y1 0.76 -0.7 0.8
3 DD L1 0.90 -0.5 0.4
5 FF N1 0.70 -0.8 0.9
</code></pre>
| 0 | 2016-07-26T07:14:06Z | [
"python",
"numpy",
"pandas",
"dataframe"
] |
How to write to file the values returned by a function | 38,582,238 | <p>Here;s the <code>calc_property_statistics</code> function which returns maximum, minimum, and average values. I need to write them to a file. </p>
<pre><code>def calc_property_statistics(prop, realisation=0):
values = prop.get_values(realisation)
maximum = np.max(values)
minimum = np.min(values)
average = np.average(values)
print("maximum: {}, minimum: {}, average: {} for property {}".format(
maximum,
minimum,
average,
prop))
return (maximum, minimum, average)
</code></pre>
| -4 | 2016-07-26T06:13:34Z | 38,582,377 | <p>this is the example of function to write return values from other function to file:</p>
<pre><code>def my_func():
"""
this function return some value
:return:
"""
return 'This is some value'
def write_file(data):
"""
this function write data to file
:param data:
:return:
"""
file_name = r'D:\log.txt'
with open(file_name, 'wb') as x_file:
x_file.write(data)
def run():
data = my_func()
write_file(data)
run()
</code></pre>
| 1 | 2016-07-26T06:22:54Z | [
"python"
] |
How to write to file the values returned by a function | 38,582,238 | <p>Here;s the <code>calc_property_statistics</code> function which returns maximum, minimum, and average values. I need to write them to a file. </p>
<pre><code>def calc_property_statistics(prop, realisation=0):
values = prop.get_values(realisation)
maximum = np.max(values)
minimum = np.min(values)
average = np.average(values)
print("maximum: {}, minimum: {}, average: {} for property {}".format(
maximum,
minimum,
average,
prop))
return (maximum, minimum, average)
</code></pre>
| -4 | 2016-07-26T06:13:34Z | 38,582,827 | <pre><code>f=open('abc.txt','w')
def calc_property_statistics(prop, realisation=0):
values = prop.get_values(realisation)
maximum = np.max(values)
minimum = np.min(values)
average = np.average(values)
return (maximum, minimum, average)
#--------------------------------------------------------------
# Main script body
x = calc_property_statistics(project.grid_models['Heterogeneity'].properties['Poro'])
f.write("%s Maximum\n %s Minimum \n %s Average \n" %x)
f.close()
</code></pre>
| -1 | 2016-07-26T06:48:15Z | [
"python"
] |
How to write to file the values returned by a function | 38,582,238 | <p>Here;s the <code>calc_property_statistics</code> function which returns maximum, minimum, and average values. I need to write them to a file. </p>
<pre><code>def calc_property_statistics(prop, realisation=0):
values = prop.get_values(realisation)
maximum = np.max(values)
minimum = np.min(values)
average = np.average(values)
print("maximum: {}, minimum: {}, average: {} for property {}".format(
maximum,
minimum,
average,
prop))
return (maximum, minimum, average)
</code></pre>
| -4 | 2016-07-26T06:13:34Z | 38,583,519 | <p>at first it depends from format of file you need to use.</p>
<p>this is example how to write into simple text file with values separated by newline.</p>
<pre><code>x = calc_property_statistics(prop, realisation)
out_file = open('results.txt', 'wb')
out_file.write(x[0]) # maximum
out_file.write('\n')
out_file.write(x[1]) # minimum
out_file.write('\n')
out_file.write(x[2]) # average
out_file.write('\n')
out_file.close()
</code></pre>
<p>or it can be done with one "write"</p>
<pre><code>...
out_file.write('{}\n{}\n{}\n'.format(x[0], x[1], x[2]))
...
</code></pre>
| 0 | 2016-07-26T07:23:14Z | [
"python"
] |
Game doesn't stop from event-loop | 38,582,285 | <p>I got this far and it kind of got all confusing and I can't figure out one simple problem with the code.</p>
<pre><code>while not gameExit:
while gameOver == True:
pygame.display.flip()
gameDisplay.fill(white)
display_message("OVER. C to continue, Q to quit", red)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameOver = False
gameExit = True
if event.key == pygame.K_c:
gameLoop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
lead_x_change = -10
lead_y_change = 0
elif event.key == pygame.K_RIGHT:
lead_x_change = 10
lead_y_change = 0
elif event.key == pygame.K_UP:
lead_y_change = -10
lead_x_change = 0
elif event.key == pygame.K_DOWN:
lead_y_change = 10
lead_x_change = 0
if ( lead_x < 0 ) or (lead_x >= 600) or ( lead_y < 0 ) or ( lead_y >= 800):
gameOver = True
</code></pre>
<p>So when I run this code, and when the snake goes over the boundary, the C for continue and Q for quit thing doesn't come <strong>UNTIL</strong> I press a button on the keyboard or move my mouse. Why is that?</p>
| -2 | 2016-07-26T06:16:25Z | 38,582,440 | <p>Move: </p>
<pre><code>if ( lead_x < 0 ) or (lead_x >= 600) or ( lead_y < 0 ) or ( lead_y >= 800):
gameOver = True
</code></pre>
<p>out of the <code>pygame.event.get</code>-loop because it will only run if events have taken place (mouse moved, key pressed). Otherwise the code will not reach the check without your action.</p>
| 0 | 2016-07-26T06:26:03Z | [
"python",
"pygame"
] |
Pandas concatenate alternating columns | 38,582,356 | <p>I have two dataframes as follows:</p>
<pre><code>df2 = pd.DataFrame(np.random.randn(5,2),columns=['A','C'])
df3 = pd.DataFrame(np.random.randn(5,2),columns=['B','D'])
</code></pre>
<p>I wish to get the columns in an alternating fashion such that I get the result below:</p>
<pre><code>df4 = pd.DataFrame()
for i in range(len(df2.columns)):
df4[df2.columns[i]]=df2[df2.columns[i]]
df4[df3.columns[i]]=df3[df3.columns[i]]
df4
A B C D
0 1.056889 0.494769 0.588765 0.846133
1 1.536102 2.015574 -1.279769 -0.378024
2 -0.097357 -0.886320 0.713624 -1.055808
3 -0.269585 -0.512070 0.755534 0.855884
4 -2.691672 -0.597245 1.023647 0.278428
</code></pre>
<p>I think I'm being really inefficient with this solution. What is the more pythonic/ pandic way of doing this?</p>
<p>p.s. In my specific case the column names are not A,B,C,D and aren't alphabetically arranged. Just so know which two dataframes I want to combine.</p>
| 3 | 2016-07-26T06:21:04Z | 38,582,428 | <p>How about this?</p>
<pre><code>df4 = pd.concat([df2, df3], axis=1)
</code></pre>
<p>Or do they have to be in a specific order? Anyway, you can always reorder them:</p>
<pre><code>df4 = df4[['A','B','C','D']]
</code></pre>
<p>And without writing out the columns:</p>
<pre><code>df4 = df4[[item for items in zip(df2.columns, df3.columns) for item in items]]
</code></pre>
| 1 | 2016-07-26T06:25:21Z | [
"python",
"pandas"
] |
Pandas concatenate alternating columns | 38,582,356 | <p>I have two dataframes as follows:</p>
<pre><code>df2 = pd.DataFrame(np.random.randn(5,2),columns=['A','C'])
df3 = pd.DataFrame(np.random.randn(5,2),columns=['B','D'])
</code></pre>
<p>I wish to get the columns in an alternating fashion such that I get the result below:</p>
<pre><code>df4 = pd.DataFrame()
for i in range(len(df2.columns)):
df4[df2.columns[i]]=df2[df2.columns[i]]
df4[df3.columns[i]]=df3[df3.columns[i]]
df4
A B C D
0 1.056889 0.494769 0.588765 0.846133
1 1.536102 2.015574 -1.279769 -0.378024
2 -0.097357 -0.886320 0.713624 -1.055808
3 -0.269585 -0.512070 0.755534 0.855884
4 -2.691672 -0.597245 1.023647 0.278428
</code></pre>
<p>I think I'm being really inefficient with this solution. What is the more pythonic/ pandic way of doing this?</p>
<p>p.s. In my specific case the column names are not A,B,C,D and aren't alphabetically arranged. Just so know which two dataframes I want to combine.</p>
| 3 | 2016-07-26T06:21:04Z | 38,582,575 | <p>If you need something more dynamic, first zip both columns names of both DataFrames and then flat it:</p>
<pre><code>df5 = pd.concat([df2, df3], axis=1)
print (df5)
A C B D
0 0.874226 -0.764478 1.022128 -1.209092
1 1.411708 -0.395135 -0.223004 0.124689
2 1.515223 -2.184020 0.316079 -0.137779
3 -0.554961 -0.149091 0.179390 -1.109159
4 0.666985 1.879810 0.406585 0.208084
#http://stackoverflow.com/a/10636583/2901002
print (list(sum(zip(df2.columns, df3.columns), ())))
['A', 'B', 'C', 'D']
print (df5[list(sum(zip(df2.columns, df3.columns), ()))])
A B C D
0 0.874226 1.022128 -0.764478 -1.209092
1 1.411708 -0.223004 -0.395135 0.124689
2 1.515223 0.316079 -2.184020 -0.137779
3 -0.554961 0.179390 -0.149091 -1.109159
4 0.666985 0.406585 1.879810 0.208084
</code></pre>
| 5 | 2016-07-26T06:33:23Z | [
"python",
"pandas"
] |
Pandas concatenate alternating columns | 38,582,356 | <p>I have two dataframes as follows:</p>
<pre><code>df2 = pd.DataFrame(np.random.randn(5,2),columns=['A','C'])
df3 = pd.DataFrame(np.random.randn(5,2),columns=['B','D'])
</code></pre>
<p>I wish to get the columns in an alternating fashion such that I get the result below:</p>
<pre><code>df4 = pd.DataFrame()
for i in range(len(df2.columns)):
df4[df2.columns[i]]=df2[df2.columns[i]]
df4[df3.columns[i]]=df3[df3.columns[i]]
df4
A B C D
0 1.056889 0.494769 0.588765 0.846133
1 1.536102 2.015574 -1.279769 -0.378024
2 -0.097357 -0.886320 0.713624 -1.055808
3 -0.269585 -0.512070 0.755534 0.855884
4 -2.691672 -0.597245 1.023647 0.278428
</code></pre>
<p>I think I'm being really inefficient with this solution. What is the more pythonic/ pandic way of doing this?</p>
<p>p.s. In my specific case the column names are not A,B,C,D and aren't alphabetically arranged. Just so know which two dataframes I want to combine.</p>
| 3 | 2016-07-26T06:21:04Z | 38,582,597 | <p>Append even indices to <code>df2</code> columns and odd indices to <code>df3</code> columns. Use these new levels to sort.</p>
<pre><code>df2_ = df2.T.set_index(np.arange(len(df2.columns)) * 2, append=True).T
df3_ = df3.T.set_index(np.arange(len(df3.columns)) * 2 + 1, append=True).T
df = pd.concat([df2_, df3_], axis=1).sort_index(1, 1)
df.columns = df.columns.droplevel(1)
df
</code></pre>
<p><a href="http://i.stack.imgur.com/EAhtd.png" rel="nofollow"><img src="http://i.stack.imgur.com/EAhtd.png" alt="enter image description here"></a></p>
| 2 | 2016-07-26T06:35:01Z | [
"python",
"pandas"
] |
Pandas concatenate alternating columns | 38,582,356 | <p>I have two dataframes as follows:</p>
<pre><code>df2 = pd.DataFrame(np.random.randn(5,2),columns=['A','C'])
df3 = pd.DataFrame(np.random.randn(5,2),columns=['B','D'])
</code></pre>
<p>I wish to get the columns in an alternating fashion such that I get the result below:</p>
<pre><code>df4 = pd.DataFrame()
for i in range(len(df2.columns)):
df4[df2.columns[i]]=df2[df2.columns[i]]
df4[df3.columns[i]]=df3[df3.columns[i]]
df4
A B C D
0 1.056889 0.494769 0.588765 0.846133
1 1.536102 2.015574 -1.279769 -0.378024
2 -0.097357 -0.886320 0.713624 -1.055808
3 -0.269585 -0.512070 0.755534 0.855884
4 -2.691672 -0.597245 1.023647 0.278428
</code></pre>
<p>I think I'm being really inefficient with this solution. What is the more pythonic/ pandic way of doing this?</p>
<p>p.s. In my specific case the column names are not A,B,C,D and aren't alphabetically arranged. Just so know which two dataframes I want to combine.</p>
| 3 | 2016-07-26T06:21:04Z | 38,583,754 | <p>You could <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex_axis.html" rel="nofollow"><code>reindex_axis</code></a>.</p>
<pre><code>df = pd.concat([df2, df3], axis=1)
df.reindex_axis(df.columns[::2].tolist() + df.columns[1::2].tolist(), axis=1)
</code></pre>
| 2 | 2016-07-26T07:37:27Z | [
"python",
"pandas"
] |
How to save a global variable in flask? | 38,582,400 | <p>I want to save a global variable in flask, and after reading some documentation I know that 'flask.g' can do what I want, but during the test I found that the variable 'g' can't be saved like session, if I change the page in the same application, the variable 'g' miss it's attribute, after reading some documents, I found that in the previous version of flask, variable 'g' is only on the request context, but <a href="http://flask.pocoo.org/docs/0.10/api/#flask.g" rel="nofollow">'Starting with Flask 0.10 this is stored on the application context and no longer on the request context which means it becomes available if only the application context is bound and not yet a request.'</a></p>
<p>So I want to know why variable 'g' can't be saved in all the pages of my application, and if I want to save a global variable which can be used in all pages, how should I do it?</p>
<p>thx!</p>
| 0 | 2016-07-26T06:23:59Z | 38,586,105 | <p>You can save those type of variables in a separate config.py in the form of class variable and access that variable in any page by simply importing that class variable</p>
<p>app.py</p>
<pre><code>from config import GetConfig
print GetConfig.var
</code></pre>
<p>config.py</p>
<pre><code>class GetConfig:
var=10
def __init__(self):
pass
</code></pre>
| 0 | 2016-07-26T09:30:58Z | [
"python",
"flask"
] |
How to save a global variable in flask? | 38,582,400 | <p>I want to save a global variable in flask, and after reading some documentation I know that 'flask.g' can do what I want, but during the test I found that the variable 'g' can't be saved like session, if I change the page in the same application, the variable 'g' miss it's attribute, after reading some documents, I found that in the previous version of flask, variable 'g' is only on the request context, but <a href="http://flask.pocoo.org/docs/0.10/api/#flask.g" rel="nofollow">'Starting with Flask 0.10 this is stored on the application context and no longer on the request context which means it becomes available if only the application context is bound and not yet a request.'</a></p>
<p>So I want to know why variable 'g' can't be saved in all the pages of my application, and if I want to save a global variable which can be used in all pages, how should I do it?</p>
<p>thx!</p>
| 0 | 2016-07-26T06:23:59Z | 38,586,116 | <p>An alternative you could use is browser caching, you should keep you web server as stateless as possible meaning each request to the server should be totally independent hence not sharing any state.</p>
| 0 | 2016-07-26T09:31:21Z | [
"python",
"flask"
] |
Autoreconf failing when installing (py)COMPSs in a clusters | 38,582,513 | <p>I tried to install pyCOMPSs (v1.4) on a Cluster system using the
installation script for Supercomputers.
The script terminates with the following error:</p>
<pre><code>libtool: link: ranlib .libs/libcbindings.a
libtool: link: ( cd ".libs" && rm -f "libcbindings.la" && ln -s
"../libcbindings.la" "libcbindings.la" )
make[1]: Entering directory
`/home/xxx/repos/pycompss/COMPSs/Bindings/c/src/bindinglib'
/usr/bin/mkdir -p
'/home/cramonco/svn/compss/framework/trunk/builders/specs/deb/compss-c-binding/tmp/opt/COMPSs/Bindings/c/lib'
/usr/bin/mkdir: cannot create directory â/home/cramoncoâ: Permission denied
make[1]: *** [install-libLTLIBRARIES] Error 1
make[1]: Leaving directory
`/home/xxx/xxx/repos/pycompss/COMPSs/Bindings/c/src/bindinglib'
make: *** [install-am] Error 2
BindingLib Installation failed, please check errors above!
</code></pre>
| 5 | 2016-07-26T06:30:15Z | 38,582,647 | <p>Seems the error is due to the package includes a previous configuration
and in your case the autoreconf is not overwritting the Makefile and
other files produced by autotools. try with
running </p>
<pre><code>cd /home/xxx/repos/pycompss/COMPSs/Bindings/c/src/bindinglib
make maintainer-clean
</code></pre>
<p>After this run again the install command</p>
| 5 | 2016-07-26T06:38:17Z | [
"java",
"python",
"distributed-computing",
"compss",
"pycompss"
] |
How not to choose blank rows in python? | 38,582,579 | <p>I wrote the following code in python to choose only selected rows. However 'activity_url.csv' has blank rows. Hence it is giving me an error. So how do I skip the blank rows?</p>
<pre><code>data = pd.read_csv('activity_url.csv', delimiter=';')
x="http"
url_data=np.array(data[data.iloc[:,1].str.contains(x, na=False)])[:,1]
</code></pre>
| 0 | 2016-07-26T06:33:32Z | 38,586,795 | <p>you can try this code:</p>
<pre><code>import pandas as pd
df=pd.read_csv('activity_url.csv')
df=df.dropna()
</code></pre>
<p>After execution, you will get dataframe without any blank row.</p>
| 0 | 2016-07-26T10:01:32Z | [
"python",
"csv",
"pandas",
"blank-line"
] |
Python: Not all environment variables present in os.environ | 38,582,598 | <p>In the python shell, using </p>
<pre><code>import os
print os.environ
</code></pre>
<p>prints the complete list of environment variables with nothing missing. However when I call the interpreter with a filename: </p>
<pre><code>sudo python file.py
</code></pre>
<p>and use </p>
<pre><code>import os
print os.environ
</code></pre>
<p>I see that some of the environment variables are missing in the dict.</p>
<p>Why do they behave differently? </p>
<p>Operating system: Ubuntu 14.04</p>
| 0 | 2016-07-26T06:35:03Z | 38,604,229 | <p> I realised that the difference was because I was using sudo during the execution for the second where the environment was not preserved. I need to add
those environment variables to my sudoers file or preserve them during execution. </p>
| 0 | 2016-07-27T05:15:36Z | [
"python",
"environment"
] |
Editing a Row using Django Forms | 38,582,695 | <p>I wanted to edit a row in Django 1.9 using Django forms:</p>
<p>So what I did is</p>
<p>For the get request I initialized the form instance (views.py)</p>
<pre><code>def get(self, request):
myModel = model.myModel.objects.get(user=request.user)
form_instance = MyForm(initial=myModel.__dict__)
return render(request, 'mytemplate.html', {'form': form_instance} )
def post(self, request):
form_instance = MyForm(request.POST)
if form_instance.is_valid():
form_instance.save()
return redirect('..')
return render(request, 'mytemplate.html', {'form': form_instance} )
</code></pre>
<p>This is my models.py</p>
<pre><code>class MyModel(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
Booth = models.OneToOneField(BoothLocation)
class BoothLocation(models.Model):
LocationID = models.CharField(max_length = 25)
</code></pre>
<p>and I have a forms.py</p>
<pre><code>class MyForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ('Booth')
labels = {'Booth':_('Booth Chosen')}
</code></pre>
<p>My problem is that my model have a one to one field, therefore whenever I execute </p>
<pre><code>form_instance = MyForm(request.POST)
</code></pre>
<p>it will return an error stating that the onetoonefield must be unique, but I'm just updating it. Is there a way to override this validation?</p>
<p>And by the way, the field really needs to be one on one.</p>
| 1 | 2016-07-26T06:41:54Z | 38,583,704 | <p>Doing this bit wrong</p>
<pre><code>form_instance = MyForm(initial=myModel.__dict__)
</code></pre>
<p>it should be</p>
<pre><code>form_instance = MyForm(instance=myModel)
</code></pre>
<p>Oops, forgot to add, in order to handle the situation where the form validation fails, your post meethod might need something like this:</p>
<pre><code>form_instance = MyForm(request.POST, instance=myModel)
</code></pre>
<p>you would need to fetch the instance again. As a side note, your code can be greatly simplified by combining your two functions into one and adding if else inside it</p>
<pre><code>if request.method == 'POST':
else:
</code></pre>
| 0 | 2016-07-26T07:34:13Z | [
"python",
"django",
"django-models",
"django-forms"
] |
Delete points in scatter plot | 38,582,947 | <p>I plotted a scatter plot using python by importing data from text files and I want to delete points with x axis values 0. This is the program I have written</p>
<pre><code>mat0 = genfromtxt("herbig0.txt");
mat1 = genfromtxt("coup1.txt");
pyplot.xlim([-2,6])
pyplot.ylim([26,33])
colors=['red', 'blue','green']
pyplot.scatter(mat0[:,13], mat0[:,4], label = "herbig stars", color=colors[0]);
if mat1[:,2] != 0:
pyplot.scatter(mat1[:,2], mat1[:,9], label = "COUP data of SpT F5-M6 ", color=colors[1]);
pyplot.scatter(mat1[:,2], mat1[:,10], label = "COUP data of SpT B0-F5", color=colors[2]);
pyplot.legend();
pyplot.xlabel('Log(Lbol) (sol units)')
pyplot.ylabel('Log(Lx) (erg/s)')
pyplot.title('Lx vs Lbol')
pyplot.show();
</code></pre>
<p>This is my output <a href="http://i.stack.imgur.com/JPEAe.png" rel="nofollow">graph</a> when I don't use the if statements.
I want to delete all the blue points which have an x axis value of zero. Please suggest changes. If I use the if statement and all the points vanished.</p>
<p><a href="http://i.stack.imgur.com/JPEAe.png" rel="nofollow"><img src="http://i.stack.imgur.com/JPEAe.png" alt="enter image description here"></a></p>
| 1 | 2016-07-26T06:54:32Z | 38,583,201 | <p>As your data is stored in <code>numpy</code> arrays you could always just filter them out:</p>
<p>Using either <code>nonzero</code>, or setting some small threshhold value that you filter out:</p>
<pre><code>#Either
mat_filter = np.nonzero(mat1[:,2])
#or
mat_filter = np.abs(mat1[:,2])>1e-12
</code></pre>
<p>Then you can use that filter on the affected arrays:</p>
<pre><code>mat1mod2 = mat1[:,2][mat_filter]
mat1mod9 = mat1[:,9][mat_filter]
mat1mod10 = mat1[:,10][mat_filter]
</code></pre>
<p>And plot them instead of the original arrays.</p>
| 3 | 2016-07-26T07:07:04Z | [
"python",
"matplotlib"
] |
gaierror: [Errno 8] nodename nor servname provided, or not known | 38,582,990 | <p>Hello I am new to python , I am writing a code which generates dns requests </p>
<pre><code> from socket import error as socket_error
import threading
from random import randint
from time import sleep
def task(number):
try :
HOST = Random_website.random_website().rstrip() # fetches url
PORT = 80 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
print(str(number) +":"+HOST +"Connected")
except socket_error as serr:
if serr.errno != errno.ECONNREFUSED:
# Not the error we are looking for, re-raise
raise serr
thread_list = []
for i in range(1, 100):
t = threading.Thread(target=task, args=(i,))
thread_list.append(t)
for thread in thread_list:
thread.start()
</code></pre>
<p>Executing above code throws this error, can anyone help me out of this
I am pulling out my hair from one day </p>
<p>Thanks in advance </p>
| 0 | 2016-07-26T06:56:32Z | 38,583,829 | <p><strong>Like this:</strong></p>
<pre><code>Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "copyright", "credits" or "license()" for more information.
>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> s.connect(("www.google.com",80))
>>> s.connect(("http://www.google.com",80))
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
s.connect(("http://www.google.com",80))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
gaierror: [Errno -2] Name or service not known
>>>
</code></pre>
<p><strong>Socket not a <code>HTTP</code> connection !</strong> </p>
<p><strong>Remove <code>HTTP://</code> tag before sending a request !</strong></p>
<p>EDIT: </p>
<pre><code>>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> s.connect(("digan.net",80))
>>> s.connect(("digan.net/hahaha/hihihi/etc",80))
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
s.connect(("digan.net/hahaha/hihihi/etc",80))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
gaierror: [Errno -2] Name or service not known
>>>
</code></pre>
<p><strong>Socket can't send request to additional path. Only talk with server !</strong></p>
| 1 | 2016-07-26T07:41:54Z | [
"python",
"sockets"
] |
Using any and all (euler # 7) | 38,583,167 | <p>Trying to find the 10,001st prime. This is what I had:</p>
<pre><code>def seven(count):
desired_count = count
actual_count = 6
number = 15
while desired_count > actual_count:
factors_in_number = range(int((number**.5)+1))
_factors_in_number = factors_in_number[2:]
print "prime count:"
print actual_count
print "current number:"
print number
print "factors:"
print _factors_in_number
if number % any(_factors_in_number) == 0:
number += 2
break
elif number % all(_factors_in_number) != 0:
actual_count += 1
number += 2
return number
</code></pre>
<p>I'm trying to short circuit the search through the list of factors with "any" and I was trying an else, but then did elif. Idk.
Here's what I get:</p>
<pre><code>seven(10001)
prime count:
6
current number:
15
factors:
[2, 3]
prime count:
6
current number:
17
factors:
[2, 3, 4]
prime count:
6
current number:
19
factors:
[2, 3, 4]
prime count:
6
current number:
21
factors:
[2, 3, 4]
prime count:
6
current number:
23
factors:
[2, 3, 4]
prime count:
6
current number:
25
factors:
[2, 3, 4, 5]
prime count:
6
current number:
27
factors:
[2, 3, 4, 5]
</code></pre>
<p>So, the list factors increase correctly, the number increases, but the prime counts don't, and it has something to do with the any's and all's. So how am I using the any and all wrong? </p>
<p>I know there are definitely faster ways, but I'm trying to just get my monster off of the ground. Thanks! Cheers</p>
| 0 | 2016-07-26T07:05:00Z | 38,583,293 | <p>You do not get the <code>actual_count</code> because your <code>any</code> and <code>all</code> were not used as intended. In fact, the following <code>elif</code> block is never executed:</p>
<pre><code>elif number % all(_factors_in_number) != 0:
actual_count += 1
number += 2
</code></pre>
<p>Because <code>all(_factors_in_number)</code> is always <code>True</code> when applied in this way and <em>any_number mod True</em> is always Zero, since <code>True</code> is coerced as 1. So the condition is never passed. The <code>any</code> block instead is always passed as long your <em>container</em> is <em>non-empty</em>.</p>
<hr>
<p>You probably intend to have the check performed as:</p>
<pre><code>elif all(number % some_integer!=0 for number in _factors_in_number):
actual_count += 1
number += 2
</code></pre>
<p>which ensures that the <code>mod</code> operation is performed on all members of the container and <code>all</code> enforces that the condition is passed for all the members. The same update should be applied to <code>any</code>.</p>
| 4 | 2016-07-26T07:11:41Z | [
"python",
"python-2.7"
] |
Using any and all (euler # 7) | 38,583,167 | <p>Trying to find the 10,001st prime. This is what I had:</p>
<pre><code>def seven(count):
desired_count = count
actual_count = 6
number = 15
while desired_count > actual_count:
factors_in_number = range(int((number**.5)+1))
_factors_in_number = factors_in_number[2:]
print "prime count:"
print actual_count
print "current number:"
print number
print "factors:"
print _factors_in_number
if number % any(_factors_in_number) == 0:
number += 2
break
elif number % all(_factors_in_number) != 0:
actual_count += 1
number += 2
return number
</code></pre>
<p>I'm trying to short circuit the search through the list of factors with "any" and I was trying an else, but then did elif. Idk.
Here's what I get:</p>
<pre><code>seven(10001)
prime count:
6
current number:
15
factors:
[2, 3]
prime count:
6
current number:
17
factors:
[2, 3, 4]
prime count:
6
current number:
19
factors:
[2, 3, 4]
prime count:
6
current number:
21
factors:
[2, 3, 4]
prime count:
6
current number:
23
factors:
[2, 3, 4]
prime count:
6
current number:
25
factors:
[2, 3, 4, 5]
prime count:
6
current number:
27
factors:
[2, 3, 4, 5]
</code></pre>
<p>So, the list factors increase correctly, the number increases, but the prime counts don't, and it has something to do with the any's and all's. So how am I using the any and all wrong? </p>
<p>I know there are definitely faster ways, but I'm trying to just get my monster off of the ground. Thanks! Cheers</p>
| 0 | 2016-07-26T07:05:00Z | 38,583,335 | <p>Using <code>all(_factors_in_number)</code> or <code>any(_factors_in_number)</code> is definitely not giving the result you are thinking it is:</p>
<pre><code>>>> any([1,2,3,4])
True
>>> 7 % any([1,2,3,4]) #True is treated like 1
0
</code></pre>
<p>Prehaps take a look at <code>help(any)</code> to see how it actually works:</p>
<pre><code>>>> help(any)
Help on built-in function any in module builtins:
any(iterable, /)
Return True if bool(x) is True for any x in the iterable.
If the iterable is empty, return False.
</code></pre>
<p>So to correctly use the function the conditional needs to be in a loop inside the call, something like this:</p>
<pre><code>if any(number%i == 0 for i in _factors_in_num):
#and then
if all(number%i != 0 for i in _factors_in_num):
</code></pre>
| 2 | 2016-07-26T07:14:04Z | [
"python",
"python-2.7"
] |
Extracting data with BeautifulSoup and output to CSV | 38,583,263 | <p>As mentioned in the previous questions, I am using Beautiful soup with python to retrieve weather data from a website.</p>
<p>Here's how the website looks like:</p>
<pre><code><channel>
<title>2 Hour Forecast</title>
<source>Meteorological Services Singapore</source>
<description>2 Hour Forecast</description>
<item>
<title>Nowcast Table</title>
<category>Singapore Weather Conditions</category>
<forecastIssue date="18-07-2016" time="03:30 PM"/>
<validTime>3.30 pm to 5.30 pm</validTime>
<weatherForecast>
<area forecast="TL" lat="1.37500000" lon="103.83900000" name="Ang Mo Kio"/>
<area forecast="SH" lat="1.32100000" lon="103.92400000" name="Bedok"/>
<area forecast="TL" lat="1.35077200" lon="103.83900000" name="Bishan"/>
<area forecast="CL" lat="1.30400000" lon="103.70100000" name="Boon Lay"/>
<area forecast="CL" lat="1.35300000" lon="103.75400000" name="Bukit Batok"/>
<area forecast="CL" lat="1.27700000" lon="103.81900000" name="Bukit Merah"/>`
<channel>
</code></pre>
<p>I managed to retrieve the information I need using these codes :</p>
<pre><code>import requests
from bs4 import BeautifulSoup
import urllib3
#getting the ValidTime
r = requests.get('http://www.nea.gov.sg/api/WebAPI/?
dataset=2hr_nowcast&keyref=781CF461BB6606AD907750DFD1D07667C6E7C5141804F45D')
soup = BeautifulSoup(r.content, "xml")
time = soup.find('validTime').string
print "validTime: " + time
#getting the date
for currentdate in soup.find_all('item'):
element = currentdate.find('forecastIssue')
print "date: " + element['date']
#getting the time
for currentdate in soup.find_all('item'):
element = currentdate.find('forecastIssue')
print "time: " + element['time']
for area in soup.find('weatherForecast').find_all('area'):
area_attrs_li = [area.attrs for area in soup.find('weatherForecast').find_all('area')]
print area_attrs_li
</code></pre>
<p>Here are my results :</p>
<pre><code>{'lat': u'1.34039000', 'lon': u'103.70500000', 'name': u'Jurong West',
'forecast': u'LR'}, {'lat': u'1.31200000', 'lon': u'103.86200000', 'name':
u'Kallang', 'forecast': u'LR'},
</code></pre>
<ol>
<li>How do I remove u' from the result? I tried using the method I found while googling but it doesn't seem to work</li>
</ol>
<p>I'm not strong in Python and have been stuck at this for quite a while.</p>
<p><strong>EDIT</strong> : I tried doing this :</p>
<pre><code>f = open("C:\\scripts\\nea.csv" , 'wt')
try:
for area in area_attrs_li:
writer = csv.writer(f)
writer.writerow( (time, element['date'], element['time'], area_attrs_li))
finally:
f.close()
print open("C:/scripts/nea.csv", 'rt').read()
</code></pre>
<p>It worked however, I would like to split the area apart as the records are duplicates in the CSV :</p>
<p><a href="http://i.stack.imgur.com/EPrUr.png" rel="nofollow"><img src="http://i.stack.imgur.com/EPrUr.png" alt="records in the CSV"></a></p>
<p>Thank you.</p>
| 0 | 2016-07-26T07:09:56Z | 38,583,912 | <p>EDIT 1 -Topic:</p>
<p>You're missing escape characters: </p>
<pre><code>C:\scripts>python neaweather.py
File "neaweather.py", line 30
writer.writerow( ('time', 'element['date']', 'element['time']', 'area_attrs_li') )
writer.writerow( ('time', 'element[\'date\']', 'element[\'time\']', 'area_attrs_li')
^
</code></pre>
<p>SyntaxError: invalid syntax</p>
<p>EDIT 2:</p>
<p>if you want to insert values:</p>
<pre><code>writer.writerow( (time, element['date'], element['time'], area_attrs_li) )
</code></pre>
<p>EDIT 3:</p>
<p>to split the result to different lines:</p>
<pre><code>for area in area_attrs_li:
writer.writerow( (time, element['date'], element['time'], area)
</code></pre>
<p>EDIT 4:
The splitting is not correct at all, but it shall give a better understanding of how to parse and split data to change it for your needs.
<a href="http://i.stack.imgur.com/EPrUr.png" rel="nofollow"><img src="http://i.stack.imgur.com/EPrUr.png" alt="enter image description here"></a>
to split the area element again as you show in your image, you can parse it</p>
<pre><code>for area in area_attrs_li:
# cut off the characters you don't need
area = area.replace('[','')
area = area.replace(']','')
area = area.replace('{','')
area = area.replace('}','')
# remove other characters
area = area.replace("u'","\"").replace("'","\"")
# split the string into a list
areaList = area.split(",")
# create your own csv-seperator
ownRowElement = ';'.join(areaList)
writer.writerow( (time, element['date'], element['time'], ownRowElement)
</code></pre>
<p>Offtopic:
This works for me:</p>
<pre><code>import csv
import json
x="""[
{'lat': u'1.34039000', 'lon': u'103.70500000', 'name': u'Jurong West','forecast': u'LR'}
]"""
jsontxt = json.loads(x.replace("u'","\"").replace("'","\""))
f = csv.writer(open("test.csv", "w+"))
# Write CSV Header, If you dont need that, remove this line
f.writerow(['lat', 'lon', 'name', 'forecast'])
for jsontext in jsontxt:
f.writerow([jsontext["lat"],
jsontext["lon"],
jsontext["name"],
jsontext["forecast"],
])
</code></pre>
| 1 | 2016-07-26T07:46:14Z | [
"python",
"csv"
] |
Odoo Missing Error while running a cron job for sending scheduled mail | 38,583,288 | <p>I have the following code. When the scheduler runs I am getting the error message. Some one help me to resolve the error in the code</p>
<blockquote>
<p>MissingError
One of the documents you are trying to access has been deleted, please try again after refreshing.</p>
</blockquote>
<pre><code>def send_followup_mail(self, cr, uid, context=None):
quot_ids=self.search(cr, uid, [('state','=','amend_quote')])
for quot_id in quot_ids:
if quot_id:
quot_obj=self.browse(cr, uid, quot_id ,context=context)
quotation_since=quot_obj.quotation_since
for email_template_line in quot_obj.temp_tag_id.crm_campaign_id.email_template_ids:
if quotation_since==email_template_line.delay_days:
mail_pool = self.pool.get('mail.mail')
mail_id = self.pool.get('email.template').send_mail(cr, uid, email_template_line.id, 1, force_send=True, context=context)
if email_template_line.send_mail_to=='to_client':
mail_pool.write(cr, uid, mail_id, {'email_to':quot_obj.email_from}, context=context)
elif email_template_line.send_mail_to=='to_sale_rep':
mail_pool.write(cr, uid, mail_id, {'email_to':quot_obj.sale_rep_id.email}, context=context)
if mail_id:
mail_pool.send(cr, uid, mail_id, context=context)
self.write(cr, uid, quot_id,{'quotation_since':quotation_since+1}, context=None)
return True
</code></pre>
| 0 | 2016-07-26T07:11:25Z | 38,585,798 | <p>First of all write code using <strong>new api</strong>.</p>
<p>For getting template use <code>obj = self.env.ref('template_record_id')</code> then send <code>obj.send_mail(model.obj.id, force_send=True)</code>, if you want to set mail then before send <code>obj.email_to = 'test@example.com'</code></p>
<p>Final code:</p>
<p>Somewhere in xml:</p>
<pre><code> <record id="email_template_record_id" model="email.template">
<field name="name">Name</field>
<field name="email_from">noreply@example.com</field>
<field name="subject">Subject</field>
<field name="email_to">False</field>
<field name="auto_delete" eval="True"/>
<field name="model_id" ref="model_model_name"/>
<field name="body_html">
<![CDATA[
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Custom title</title>
</head>
<body>
<p>Dear Sir,</p>
<p>Text body.</p>
<p>This is automated mail, don't reply.</p>
</body>
</html>
]]>
</field>
</record>
</code></pre>
<p>in python code:</p>
<pre><code> template = self.env.ref('email_template_record_id')
template.email_to = some_obj.obj_related_field.email
try:
template.send_mail(ombject_id, force_send=True)
except Exception:
_logger.error("Custom Error Message")
template.email_to = False
</code></pre>
| 0 | 2016-07-26T09:17:43Z | [
"python",
"cron",
"openerp",
"scheduler",
"odoo-8"
] |
Odoo Missing Error while running a cron job for sending scheduled mail | 38,583,288 | <p>I have the following code. When the scheduler runs I am getting the error message. Some one help me to resolve the error in the code</p>
<blockquote>
<p>MissingError
One of the documents you are trying to access has been deleted, please try again after refreshing.</p>
</blockquote>
<pre><code>def send_followup_mail(self, cr, uid, context=None):
quot_ids=self.search(cr, uid, [('state','=','amend_quote')])
for quot_id in quot_ids:
if quot_id:
quot_obj=self.browse(cr, uid, quot_id ,context=context)
quotation_since=quot_obj.quotation_since
for email_template_line in quot_obj.temp_tag_id.crm_campaign_id.email_template_ids:
if quotation_since==email_template_line.delay_days:
mail_pool = self.pool.get('mail.mail')
mail_id = self.pool.get('email.template').send_mail(cr, uid, email_template_line.id, 1, force_send=True, context=context)
if email_template_line.send_mail_to=='to_client':
mail_pool.write(cr, uid, mail_id, {'email_to':quot_obj.email_from}, context=context)
elif email_template_line.send_mail_to=='to_sale_rep':
mail_pool.write(cr, uid, mail_id, {'email_to':quot_obj.sale_rep_id.email}, context=context)
if mail_id:
mail_pool.send(cr, uid, mail_id, context=context)
self.write(cr, uid, quot_id,{'quotation_since':quotation_since+1}, context=None)
return True
</code></pre>
| 0 | 2016-07-26T07:11:25Z | 38,587,657 | <p>This is the modified code and works fine</p>
<pre><code>def send_followup_mail(self, cr, uid, context=None):
quot_ids=self.search(cr, uid, [('state','=','amend_quote')])
for quot_id in quot_ids:
if quot_id:
quot_obj=self.browse(cr, uid, quot_id ,context=context)
quotation_since=quot_obj.quotation_since
for email_template_line in quot_obj.temp_tag_id.crm_campaign_id.email_template_ids:
if quotation_since==email_template_line.delay_days:
mail_pool = self.pool.get('mail.mail')
template_id = email_template_line.id
template_pool = self.pool.get('email.template')
sale_id=self.pool.get('sale.order').search(cr, uid, [], limit=1, context=context)
mail_id = template_pool.send_mail(cr, uid, template_id, sale_id[0], force_send=True, context=context)
if email_template_line.send_mail_to=='to_client':
mail_pool.write(cr, uid, mail_id, {'email_to':quot_obj.email_from}, context=context)
elif email_template_line.send_mail_to=='to_sale_rep':
mail_pool.write(cr, uid, mail_id, {'email_to':quot_obj.sale_rep_id.email}, context=context)
if mail_id:
mail_pool.send(cr, uid, mail_id, context=context)
self.write(cr, uid, quot_id,{'quotation_since':quotation_since+1}, context=None)
return True
</code></pre>
| 0 | 2016-07-26T10:41:23Z | [
"python",
"cron",
"openerp",
"scheduler",
"odoo-8"
] |
Django's NotImplementedError: annotate() + distinct(fields) is not implemented | 38,583,295 | <p>There are 2 simple models:</p>
<pre><code>class Question(TimeStampedModel):
text = models.CharField(max_length=40)
class Answer(TimeStampedModel):
question = models.ForeignKey(Question, related_name='answers')
is_agreed = models.BooleanField()
author = models.ForeingKey(User, related_name='answers')
</code></pre>
<p>And now, I will describe my problem.</p>
<pre><code>In [18]: Question.objects.count()
Out[18]: 3
</code></pre>
<p>I need to annotate queryset with 'is_user_agreed' and 'answers_amount' fields:</p>
<pre><code>In [18]: user = User.objects.first()
In [19]: qs = Question.objects.annotate(
...: is_user_agreed=Case(
...: When(answers__in=user.answers.filter(is_agreed=True), then=Value(True)),
...: When(answers__in=user.answers.filter(is_agreed=False), then=Value(False)),
...: default=Value(None),
...: output_field=NullBooleanField(),
...: ),
...: ).annotate(answers_amount=Count('answers'))
...: qs.count()
Out[19]: 4
</code></pre>
<p><strong>^ here count is 4, but I have only 3 questions in db</strong> :(
So, I've tried with <code>distinct()</code></p>
<pre><code>In [20]: qs.distinct().count()
Out[20]: 4 # but distinct doesn't work
In [21]: qs.distinct('id').count()
</code></pre>
<p>And after last line of code I've got this exception:</p>
<pre><code>NotImplementedError: annotate() + distinct(fields) is not implemented.
</code></pre>
<p>I've also tried to use this trick <code>annotate(Count('id')).filter(id__count__gt=1)</code></p>
<p>But in this case I'm losing all duplicate rows, and qs.count() is 2.</p>
<p><strong>UPDATE:</strong> The problem is duplicated rows in queryset.</p>
<p><strong>SOLUTION:</strong> (Extended variant of Vladimir's second approach) </p>
<pre><code>user = User.objects.first()
user_agreed_questions = user.answers.filter(
is_agreed=True).values_list('question_id', flat=True).distinct()
user_not_agreed_questions = user.answers.filter(
is_agreed=False).values_list('question_id', flat=True).distinct()
Question.objects.annotate(
answer_amount=Count('answers'),
is_user_agreed=Case(
When(id__in=user_agreed_questions, then=True),
When(id__in=user_not_agreed_questions, then=False),
default=None,
output_field=NullBooleanField(),
),
)
</code></pre>
| 1 | 2016-07-26T07:11:42Z | 38,586,709 | <p>Try this:</p>
<pre><code>Question.objects.annotate(
answer_amount=Count('answers'),
is_user_agreed=F('answers__is_agreed'),
).order_by('id', '-answers__is_agreed').distinct('id')
</code></pre>
<p>If <code>question</code> has no <code>answers</code>, then <code>question.is_user_agreed</code> is <code>None</code>. If <code>question</code> has at least one <code>answer</code> with <code>answer.is_agreed=True</code>, then <code>question.is_agreed</code> is <code>True</code>. Otherwise, <code>is_user_agreed</code> is <code>False</code>.</p>
<p>Or this:</p>
<pre><code>agreed_questons = Answer.objects.filter(
is_agreed=True,
).values_list('question_id', flat=True).distinct()
Question.objects.annotate(
answer_amount=Count('answers'),
is_agreed=Case(
When(id__in=agreed_questions, then=True),
When(answers__isnull=True, then=None),
default=False,
output_field=NullBooleanField(),
),
)
</code></pre>
<p><code>agreed_questons</code> is list of <code>id</code> of <code>questions</code>, that have at least one <code>answer</code> with <code>answer.is_agreed=True</code>.</p>
| 1 | 2016-07-26T09:57:46Z | [
"python",
"django",
"postgresql"
] |
How do I Login to A site using Python for scraping purposes | 38,583,357 | <p>I'm relatively new to python and programming generally. I've tried to follow steps provided from similar questions here but My program is unable to successfully Log in. The latest code I got from <a href="http://stackoverflow.com/questions/23102833/how-to-scrape-a-website-which-requires-login-using-python-and-beautifulsoup/23103784#">How to scrape a website which requires login using python and beautifulsoup?</a>
Below is my attempted code: and the response I get</p>
<pre><code>import mechanize
import BeautifulSoup
import urllib2
import cookielib
cj = cookielib.CookieJar()
br = mechanize.Browser()
br.set_cookiejar(cj)
br.open("http://www.bbnplace.com/accounts_v2/?do=signin&service=prepaidsms&returnto=http%3A%2F%2Fsms.bbnplace.com%2Fsentdir.php")
br.select_form('blogin')
br.form['busername'] = 'my_username'
br.form['passwd'] = 'my_password'
response = br.submit()
print br.response().read()
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="keywords" content="bulksms, bulk sms, bulk sms gateway, cheap bulk sms, bulk sms provider, bulk sms to nigeria, send bulk sms, personalized bulk sms, bulk sms nigeria, best sms site in nigeria, nigerian bulks sms gateway, web to mobile sms" />
<meta http-equiv="description" content="Send bulk sms with personalized sender name to all GSM networks in Nigeria and over 800 networks in 160 countries. Nigeria's Best SMS Gateway." />
<title>BBN SMS Messenger: Retail Web to Mobile Bulk SMS Messaging Utility</title>
<link rel="stylesheet" href="http://www.bbnplace.com/accounts_v2/style/layout.css" type="text/css" media="screen" />
<script type="text/javascript" async src="http://www.bbnplace.com/accounts_v2/bbjs/un.js"></script>
<script type="text/javascript">var L;var C;var bw=0;var G;var eD;var am;var eE=0;var method;var url;var J;var be;var fp='';var eY='';var dW=0;var eH='dG';var eG;var action='sent';var bS=0;var eC='';var eW=new Number();var bP='';var ft='save';var host=document.domain=='localhost'?'localhost/smsmessenger/':'sms.bbnplace.com';var protocol='http';var fc;var eA=protocol+"://"+host+"/source/";var dR=0;var responseText;var response=new Array();var bs;var bV=new Number();var H;var request;var fl;var aB;var aQ;var aL=window.innerWidth;var ab=window.innerHeight;var ca=new Array();var aK=new Array();var cv=new Array();var bb=new Array();var dN=new Array();aB=document.getElementById('aD');var et=110;aQ=document.getElementById('bx');if(request=='gocheck'){ad();}function ak(v){var k=document.getElementById(v);k.style.visibility='hidden';k.style.height='0px';};function aE(v){var k=document.getElementById(v);k.style.visibility='inherit';k.style.height='auto';};function bJ(v,ba){var ids=new Array();var aw=new String();aw=ba;ids=aw.split(',');for(var i=0;i<ids.length;i++){ak(ids[i]);}ids='';aE(v);return;};function ay(bF,cF,dw,bH,bi,aq,bN,aA){be=bi;C=bH;G=aq;H=aA;J=dw;method=bF;url=cF;am=bN;L=bO();if(L){if(method=='post'){try{L.open(method,url,true);L.onreadystatechange=bg;L.setRequestHeader('Content-Type','application/x-www-form-urlencoded');L.setRequestHeader('Content-Length',J.length);L.setRequestHeader('Connection','close');L.send(J);}catch(e){alert("Error connecting to server: "+e.toString());}}else{try{J.length>1?aG=url+'?'+J:aG=url;L.open(method,aG,true);L.onreadystatechange=bg;L.send(null);}catch(e){alert("Could not connect to server: "+e.toString());}}}};function bg(){var d;if(C.length>0){d=document.getElementById(C);}if(L.readyState==4){if(L.status==200){try{var response=dO();if(C.length>0){d.style.visibility='hidden';}bw=0;}catch(e){d.innerHTML="Error reading server response: "+e.toString();}}else{if(C.length>0){if(L.status){d.innerHTML='Server Response: '+L.status+' - '+L.statusText;d.style.visibility='visible';}else{d.innerHTML='Connection to server failed. Retrying...';d.style.visibility='visible';bQ=setTimeout('bz()',5000);}}}}else{if(C.length>0){d.innerHTML='<img border="0" src="style/29.gif" align="absmiddle" /> <b>Loading...</b>';d.style.visibility='visible';ap=setTimeout('dK()',(be*1000));}}return response;};function dK(){if(L.readyState!=4){clearTimeout(ap);document.getElementById(C).innerHTML='Connection is too slow. Retrying...';bQ=setTimeout('bD()',5000);}};function bD(){clearTimeout(bQ);if(L.readyState!=4){L.abort();ay(method,url,J,C,be,G,H);}};function bz(){clearTimeout(bQ);if(!L.status){L.abort();ay(method,url,J,C,be,G,H);}};function df(){x=document.getElementById(C);x.style.visibility='hidden';};function dO(){var responseText,cp;var doctype=L.getResponseHeader('Content-Type').toString();var l=document.getElementById(G);if(H.length){var aJ=document.getElementById(H);}l.innerHTML='';response['type']=doctype;if(doctype=='text/plain'||doctype=='text/html'){responseText=L.responseText;if(responseText.substr(0,4)=='Err:'){l.innerHTML=responseText.substr(5);l.style.visibility='inherit';l.style.height='auto';if(responseText.substr(5)==''){if(bS>0){l.innerHTML='<span style="color:red;">'+bP+'</span>';}}}else if(responseText.substr(0,3)=='OK:'){var aH=responseText.substr(4);switch(request){case 'newpost':document.forms[request].es.value=aH;bs.innerHTML='Saved';eu();break;}}else{if(H.length){aJ.innerHTML=responseText;}else if(request=='gocheck'){l.innerHTML=responseText;y=document.forms.di;if(responseText=='available'){y.cf.value=1;y.ds.value=y.username.value;l.innerHTML='Available';l.style.fontWeight='bold';l.style.color='green';ad();}}else{if(responseText=='successful'){switch(request){case 'newRequest':bJ('h','h,j');break;}}else if(responseText=='denied'){bf=protocol+'://'+host+'/accounts';window.location=bf;}else{alert(responseText);}}}}};function bO(){try{L=new XMLHttpRequest();}catch(e){var aI=new Array('MSXML2.XMLHTTP.6.0','MSXML2.XMLHTTP.5.0','MSXML2.XMLHTTP.4.0','MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP','Microsoft.XMLHTTP');for(var i=0;i<aI.length&& !L;i++){try{L=new ActiveXObject(aI[i]);}catch(e){}}}if(!L){alert('Please Upgrade your web browser');}else{return L;}};function aN(){var x=document.forms['t'];request='newRequest';aq='V';var bp,ao,aW,az;bp=x.ag.value;ao=x.bI.value;aW=x.aR.value;dr=x.an.value;az=x.av.value;aZ='eml='+encodeURIComponent(ao)+'&f='+encodeURIComponent(bp)+'&p='+encodeURIComponent(aW)+'&m='+encodeURIComponent(az)+'&p2='+encodeURIComponent(dr);al=document.getElementById('V');al.style.visibility='hidden';al.style.height=0;dP='source/contact.php';ay('post',dP,aZ,'',30,'V','','');};function cu(){dJ();};function cl(){ce();};function bB(aX){var x=document.getElementById('bh');if(!x){var x=document.createElement('div');x.setAttribute('id','bh');x.style.backgroundColor='#000';x.style.top='0px';x.style.left='0px';x.style.position='fixed';x.style.zIndex=99999;x.style.opacity=0.5;}x.style.width=aL+'px';x.style.height=ab+'px';x.style.visibility='visible';document.body.appendChild(x);if(aX==null){var T=document.getElementById('t');T.style.visibility='visible';T.style.height='auto';T.style.position='fixed';T.style.left=(aL/2-250)+'px';T.style.width='500px';T.style.zIndex=10000001;bJ('j','h,j');}else{var T=document.getElementById('ax');T.style.visibility='visible';bV=aX;}};function ar(){var bE=document.getElementById('bh');bE.style.width='0px';bE.style.height='0px';bE.style.visibility='hidden';if(bV==0){ak('h');ak('j');ak('t');document.forms['t'].reset();}else{var T=document.getElementById('ax');T.style.visibility='hidden';bV=0;}};function cU(i){var aY=document.getElementById('bA');aY.innerHTML='<b>Message:</b><br />'+aK[i];aY.innerHTML+='<br /><br /><b>Broadcasted:</b> '+bb[i];document.getElementById('as').style.visibility='visible';ez(ca[i]);};function dA(){document.getElementById('as').style.visibility='hidden';document.getElementById('ae').innerHTML='';}</script>
</head>
<body><div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=174240488183";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script><div id="ppbd"></div><div id="ppbdc"></div><div id="logoholder"></div>
<div id="app_header">
<div id="line1_left"><img src="http://www.bbnplace.com/accounts_v2/style/smlogo.png" align="absmiddle" title="BBN SMS Messenger: Retail Web to Mobile Bulk SMS Messaging Utility" /></div>
<div id="line1_right"><a href="#">Hi Buddie!</a> | <a href="http://sms.bbnplace.com">Messaging Solutions</a> | <a href="http://www.bbnplace.com">BBN</a> &nbsp; </div>
</div>
<div id="cK" align="right">&nbsp;</div><div id="workarea" align="center">
<div id="frm_right">
<div id="note_panel"><div align="left">
<!-- <div style="margin: 0 0 40px; font-size: 22px; line-height: 27px;">
manage your contacts &bull; send sms to <b style="color: red;">groups</b>
&bull; from personal computer and <b style="color: red;">mobile</b>
</div> -->
<div style="font-size: 28px; line-height: 35px; margin: 35px 0 0;">
Send bulk sms &bull; <b style="color: red;">confidently!</b>
</div>
<div id="bslogin_nav">
<img alt="How to Recharge" src="style/cc_icon.png" align="absmiddle" />
<b><a href="#how_to_recharge">Learn How to Recharge</a></b> &nbsp; <img
alt="Bundles and Pricing" align="absmiddle" src="style/cog_icon.png" />
<b><a
href="http://www.bbnplace.com/documentation/?service=prepaidsms&article=networks&returnto="
target="_blank">See our Network Coverage</a></b>
</div>
<script type="text/javascript">function dJ(){var x=document.forms['aN'];var V=new Number(x.df.value);var v=new Number(0);if(isNaN(V)){document.getElementById("J").innerHTML="<span style='color: red;'>waiting...</span>";document.getElementById("hBp").innerHTML="<span style='color: red;'>waiting...</span>";document.getElementById("T").innerHTML="<span style='color: red;'>waiting...</span>";if(document.forms.F){document.forms.F.bJ.disabled=true;}if(document.getElementById("statMsg")){document.getElementById("statMsg").innerHTML="<span style='color: red;'><strong>Please Enter a Numberic Value</strong></span>";}}if(V<50){document.getElementById("J").innerHTML="<span style='color: red;'>waiting...</span>";document.getElementById("hBp").innerHTML="<span style='color: red;'>waiting...</span>";document.getElementById("T").innerHTML="<span style='color: red;'>waiting...</span>";if(document.forms.F){document.forms.F.bJ.disabled=true;}if(document.getElementById("statMsg")){document.getElementById("statMsg").innerHTML="<span style='color: red;'><strong>Please specify a minimum of 50</strong></span>";}}else if(V>=50&&V< 1000){document.getElementById("J").innerHTML="Teams & Groups";document.getElementById("hBp").innerHTML="NGN 3.50";v=V* 3.50;v=v.toFixed(2);document.getElementById("T").innerHTML='NGN '+v;if(document.forms.F){document.forms.F.bJ.disabled=false;}if(document.getElementById("statMsg")){document.getElementById("statMsg").innerHTML='';}if(document.forms.F){document.forms.F.J.value='Teams & Groups';document.forms.F.hBp.value= 3.50;document.forms.F.T.value=v;}}else if(V>= 1000 &&V< 10000){document.getElementById("J").innerHTML="Business Standard";document.getElementById("hBp").innerHTML="NGN 2.20";v=V* 2.20;v=v.toFixed(2);document.getElementById("T").innerHTML='NGN '+v;if(document.forms.F){document.forms.F.bJ.disabled=false;}if(document.getElementById("statMsg")){document.getElementById("statMsg").innerHTML='';}if(document.forms.F){document.forms.F.J.value='Business Standard';document.forms.F.hBp.value= 2.20;document.forms.F.T.value=v;}}else if(V>= 10000 &&V< 50000){document.getElementById("J").innerHTML="Business Professional";document.getElementById("hBp").innerHTML="NGN 2.00";v=V* 2.00;v=v.toFixed(2);document.getElementById("T").innerHTML='NGN '+v;if(document.forms.F){document.forms.F.bJ.disabled=false;}if(document.getElementById("statMsg")){document.getElementById("statMsg").innerHTML='';}if(document.forms.F){document.forms.F.J.value='Business Professional';document.forms.F.hBp.value= 2.00;document.forms.F.T.value=v;}}else if(V>= 50000){document.getElementById("J").innerHTML="Business Premium";document.getElementById("hBp").innerHTML="NGN 1.85";v=V* 1.85;v=v.toFixed(2);document.getElementById("T").innerHTML='NGN '+v;if(document.forms.F){document.forms.F.bJ.disabled=false;}if(document.getElementById("statMsg")){document.getElementById("statMsg").innerHTML='';}if(document.forms.F){document.forms.F.J.value='Business Premium';document.forms.F.hBp.value= 1.85;document.forms.F.T.value=v;}}} </script>
<div align="left" id="pricelist">
<div align="right"><div id="price_tag"><img src="http://www.bbnplace.com/accounts_v2/style/price_tag.png" align="top" /> Bundles &amp; Pricing</div></div>
<form id="aN" name="aN" method="post" action="">
<div style="margin: 0 0 5px;">
<label for="select"></label> <b>Currency</b> <select
name="aD" id="aD" onchange="ck(this.value)" disabled="disabled">
<option value="ngn" selected="selected" >NGN</option>
<option value="usd" >USD</option>
<option value="eur" >EUR</option>
</select>
</div>
<div>
<table cellpadding="3" cellspacing="0" width="100%" id="price_tags">
<tr>
<th align="left">Bundle</th>
<th width="120" align="right">Min. Volume</th>
<th width="80" align="right">Unit Price</th>
</tr> <tr>
<td style="background-color: #FFF; white-space:nowrap; overflow:hidden; text-overflow: clip;">Teams & Groups</td>
<td align="right" style="background-color: #FFF;">50</td>
<td align="right" style="background-color: #FFF;">3.50</td>
</tr> <tr>
<td style="background-color: #FAFAFA; white-space:nowrap; overflow:hidden; text-overflow: clip;">Business Standard</td>
<td align="right" style="background-color: #FAFAFA;">1,000</td>
<td align="right" style="background-color: #FAFAFA;">2.20</td>
</tr> <tr>
<td style="background-color: #FFF; white-space:nowrap; overflow:hidden; text-overflow: clip;">Business Professional</td>
<td align="right" style="background-color: #FFF;">10,000</td>
<td align="right" style="background-color: #FFF;">2.00</td>
</tr> <tr>
<td style="background-color: #FAFAFA; white-space:nowrap; overflow:hidden; text-overflow: clip;">Business Premium</td>
<td align="right" style="background-color: #FAFAFA;">50,000</td>
<td align="right" style="background-color: #FAFAFA;">1.85</td>
</tr> </table>
</div>
<div style="margin: 30px 0;">
Specify sms volume in the space below to get pricing <br />
<div>
<table width="100%" border="0" cellpadding="2" cellspacing="0"
id="aH">
<tr>
<th width="80">Volume</th>
<th width="">Bundle</th>
<th width="80" align="right">Unit Price</th>
<th width="" align="right">Price</th>
</tr>
<tr>
<td bgcolor="#FEFEFE"><input name="df" type="text" value=""
size="10" maxlength="10" onkeyup="dJ()" /></td>
<td bgcolor="#FEFEFE"><div id="J">
&nbsp; <input name="J" type="hidden" id="J" value="" />
</div></td>
<td align="right"><div id="hBp">
&nbsp; <input name="hBp" type="hidden" id="hBp" value="" />
</div></td>
<td align="right"><div id="T"><a name="how_to_recharge"></a>
&nbsp; <input name="T" type="hidden" id="T" value="" />
</div></td>
</tr>
</table>
</div>
</div>
</form>
IMPORTANT: *<strong>Business Premium bundle</strong> is the only <span
style="color: red; font-weight: bold;">negotiable</span> bundle.
</div><div align="left" style="margin: 50px 0 0;">
<h2>How to Recharge</h2>
<p>Pay online with any Nigerian debit/credit card, or at any branch of the listed banks:</p>
<div>
<img alt="web payment" src="http://www.bbnplace.com/checkout/image/webpaymentgateways.gif" height="55" />
</div>
<div style="font-size: 14px;">
Account Name: <b>Browser Based Nigeria</b>
</div>
<div style="clear: both; width: 100%;">
<div id="bM" align="center">
<img src="http://www.bbnplace.com/sms/media/images/zenith.jpeg"
alt="Zenith Bank" width="50" height="50" /><br />1012259075
</div>
<div id="bM" align="center">
<img src="http://www.bbnplace.com/sms/media/images/gtblogo.gif"
alt="Guaranty Trust Bank" width="50" height="50" /><br />0008382123
</div>
<div id="bM" align="center">
<img src="http://www.bbnplace.com/sms/media/images/diamondbank.jpg"
alt="Diamond Bank Plc" width="50" height="50" /><br />0010549507
</div>
<div id="ibM" align="center">
<img src="http://www.bbnplace.com/sms/media/images/accessbank_logo.png"
alt="Access Bank Plc" height="30" style="padding: 5px 0;" /><br />0049632011</div>
</div>
</div></div></div>
<div id="form_pane">
<div id="form_panel"><div align="left" id="signup">
<form name="signup_init" method="post" onsubmit = "return false;" autocomplete="off">
<div align="right"><h2>Get Started!</h2></div>
<div id="signup_init_error_message"></div>
<div><b>Email</b></div>
<div>
<input name="new_user_email" type="email" id="new_user_email" onkeypress="quickSubmit(event, 'signup_init', 'signup_init_error_message')" title="Type Email" size="45" style="width:100%" />
<span style="display: none;">User Email</span>
</div>
<div>
<input type="hidden" name="validemail" value="0" />
<input type="hidden" name="bservice" value="prepaidsms" />
<input type="button" name="button2" id="aC" value="Sign Up" onclick="processFrm('signup_init', 'signup_init_error_message');" />
</div>
</form>
</div></div>
<div id="forms_seperator">OR</div>
<div id="form_panel"><div>
<form name="blogin" method="post" onsubmit="return false;" autocomplete="off">
<div align="right"> <h2>Login</h2> </div>
<div id="errormsg"></div>
<div align="left">Email<br />
<label for="username"></label>
<input type="email" name="busername" id="busername" class="frmfield" value="" onkeypress="quickSubmit(event, 'blogin', 'errormsg')" title="This should be your email" />
</div>
<div align="left">Password<br />
<input type="password" name="passwd" id="passwd" class="frmfield" value="" onkeypress="quickSubmit(event, 'blogin', 'errormsg')" />
</div>
<div>
<input type="hidden" name="bservice" id="bservice" value="prepaidsms" />
<input type="hidden" name="returnto" id="returnto" value="http://sms.bbnplace.com/sentdir.php" />
<input type="hidden" name="errordiv" id="errordiv" value="errormsg" />
<input type="hidden" name="ipaddress" id="ipaddress" value="41.58.242.131" />
</div>
<div align="left">
<label><input name="rememberme" type="checkbox" id="rememberme" value="1" /> Remember Me!</label>
<input type="button" name="button" id="button" class="K" value="Login" onclick="processFrm('blogin','errormsg')" />
</div>
<div style="padding: 5px 0;"><a href="http://www.bbnplace.com/accounts_v2?do=login_failure&service=prepaidsms&returnto=http://sms.bbnplace.com/sentdir.php">Can't access my account</a></div>
</form>
</div></div>
<div style="margin: 18px 0;">
<div style="margin: 0 0 5px;">Join our social conversation</div>
<div class="fb-like" data-href="http://www.facebook.com/bbnsms"
data-send="false" data-layout="button_count" data-width="250"
data-show-faces="false"></div>
</div>
</div>
</div></div>
<div style="clear:both;">&nbsp;</div><div id="statsbar"></div>
</div>
<div id="aj" align="center"></div>
<div align="center" id="bn">
<a href="//bs.bbnplace.com" title="Business Solutions">Business
Solutions</a> | <a href="//dev.bbnplace.com">Developers</a> | <a
href="//www.bbnplace.com/documentation">Documentation</a>
| <a href="//newsroom.bbnplace.com">Newsroom</a>
| <a href="//bbnplace.wordpress.com">Blog</a> | <a
href="//www.bbnplace.com?entry=contact" target="_blank">Contact
Us</a> <a href="//twitter.com/bbnplace" title="on Twitter"
target="_blank"><img src="//www.bbnplace.com/accounts_v2/style/twitter.png" alt="on Twitter"
width="16" height="16" border="0" /></a> <a
href="//www.facebook.com/bbnplace" title="on Facebook"
target="_blank"><img src="//www.bbnplace.com/accounts_v2/style/facebook.png" alt="on Facebook"
width="16" height="16" border="0" /></a> <a
href="//www.linkedin.com/groups?gid=4620527" title="at LinkedIn"
target="_blank"><img src="//www.bbnplace.com/accounts_v2/style/linkedin.png" alt="at LinkedIn"
width="16" height="16" border="0" /></a> <a
href="//www.youtube.com/user/bbnplace" title="on Youtube"
target="_blank"><img src="//www.bbnplace.com/accounts_v2/style/youtube.png" alt="on Youtube"
width="16" height="16" border="0" /></a> <a
href="//newsroom.bbnplace.com" title="at the Newsroom"
target="_blank"><img src="//www.bbnplace.com/accounts_v2/style/radio.png" alt="Newsroom" width="16"
height="16" border="0" /></a>
<br /> Copyright &copy; 2008 - 2016 <a
href="//www.bbnplace.com" title="Browser Based Network Ltd">Browser
Based Network Ltd</a>. <img src="//www.bbnplace.com/accounts_v2/style/ngr.png" align="absmiddle"
alt="Nigeria" /> Nigeria. All rights reserved.
<br /><a href="//docs.bbnplace.com/?article=legals" target="_blank">Terms of Service</a> &bull; <a href="//docs.bbnplace.com/?article=privacy_policy" target="_blank">Privacy Policy Statement</a>
<br /> <b>Desktop | <a
href="//m.sms.bbnplace.com">Mobile</a> Edition
</b>
</div>
<div
style="float: right; position: fixed; z-index: 100000; top: 230px; right: 0px;">
<img src="//www.bbnplace.com/accounts_v2/style/feedback_button.png" onclick="bB()"
style="cursor: pointer;" />
</div><div id="t">
<div id="j">
<form name="t" action="return false;" method="post">
<input type="hidden" name="an" value="Mobile Messaging Solutions" />
<h1 style="color: #555;">Send Us Feedback</h1>
<div>If you notice something is not working properly or you have a
suggestions. We appreciate hearing from you</div>
<div id="V"></div>
<div>
<b>Full Name:</b><br /> <input type="text" name="ag"
style="width: 95%;" />
</div>
<div>
<b>Email:</b><br /> <input type="text" name="bI" style="width: 95%;" />
</div>
<div>
<b>Phone:</b> <i>(optional)</i><br /> <input type="text" name="aR"
style="width: 200px;" />
</div>
<div>
<b>Suggestion:</b><br />
<textarea name="av" rows="10"
style="width: 95%; min-width: 95%; max-width: 95%; height: 100px; max-height: 100px;"></textarea>
</div>
<div>
Read our <a href="http://docs.bbnplace.com/?article=privacy_policy"
target="_blank">Privacy Policy</a> statement
</div>
<div style="margin: 10px 0 0;">
<span id="aC" onclick="aN()">Submit Feedback</span> <span class="K"
onclick="ar()">Cancel</span>
</div>
</form>
</div>
<div id="h">
<div id="bv">
<img src="style/correct_marking.gif" align="absmiddle" /> Your
feedback has been received. Thank you for the time taken
</div>
<div style="margin: 50px 0 0;">
<span class="K" onclick="ar()">Close</span>
</div>
</div>
</div><div id="cs"><div style="text-align:center;white-space:nowrap;"> <div><a href="http://livechat.boldchat.com/aid/4518259610467392165/bc.chat?cwdid=2945491719484839364" target="_blank" onclick="window.open((window.cl&&cl.link||function(link){return link;})(this.href+(this.href.indexOf('?')>=0?'&amp;':'?')+'url='+escape(document.location.href)),'Chat1609025529230970721','toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=520,height=360,left=190,top=250');return false;"><img alt="Live chat" src="https://cbi.boldchat.com/aid/4518259610467392165/bc.cbi?cbdid=6794783422064795815" border="0"/></a></div></div></div></body>
</html></code></pre>
</div>
</div>
</p>
| 2 | 2016-07-26T07:14:54Z | 38,585,838 | <p>You just need to post to the correct url, once successfully logged in you will be able to get whatever page you like, this is a working example using <a href="http://docs.python-requests.org/en/master/" rel="nofollow">requests</a>:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
post = "http://www.bbnplace.com/accounts_v2/source/loginp.php"
data = {"eml": "your_email",
"p": "your_pass"}
# use a Session to persist cookies.
with requests.Session() as s:
r = s.post(post, data=data) # log us in
print(r.content) # will output "successful" for correct login
r = s.get("http://sms.bbnplace.com/account.php") # get account page
soup = BeautifulSoup(r.content)
print(soup.title.text)
</code></pre>
| 0 | 2016-07-26T09:19:42Z | [
"python",
"beautifulsoup"
] |
Timer without threading in python? | 38,583,559 | <p>I am new to programming and would like to add a counter that deducts 1 from your score every two seconds. (so that I have to answer quickly to make my score increase)</p>
<pre><code>chr
import random
import time
radians2 = None
ans = None
score = 0
radians1 = ['0', 'Ï/6', 'Ï/3', 'Ï/4', 'Ï/2', '2Ï/3', '3Ï/4', '5Ï/6', 'Ï', '7Ï/6', '4Ï/3', '5Ï/4', '3Ï/2', '5Ï/3', '7Ï/4', '11Ï/6', '2Ï']
while radians2 == ans or ans == None:
radians3 = (random.choice(radians1))
ans = input(radians3)
if radians3 == '0':
radians2 = 0
elif radians3 == 'Ï/6':
radians2 = 30
elif radians3 == 'Ï/3':
radians2 = 60
elif radians3 == 'Ï/4':
radians2 = 45
elif radians3 == 'Ï/2':
radians2 = 90
elif radians3 == '2Ï/3':
radians2 = 120
elif radians3 == '3Ï/4':
radians2 = 135
elif radians3 == '5Ï/6':
radians2 = 150
elif radians3 == 'Ï':
radians2 = 180
elif radians3 == '7Ï/6':
radians2 = 210
elif radians3 == '4Ï/3':
radians2 = 240
elif radians3 == '5Ï/4':
radians2 = 225
elif radians3 == '3Ï/2':
radians2 = 270
elif radians3 == '5Ï/3':
radians2 = 300
elif radians3 == '7Ï/4':
radians2 = 315
elif radians3 == '11Ï/6':
radians2 = 330
elif radians3 == '2Ï':
radians2 = 360
score = score + 1
if radians2 == ans:
print('Correct!')
print "You've got %d in a row" % score
print "You lose, the correct answer was %d" % radians2
</code></pre>
<p>Sorry if the code is messy/long
I figured out that I want to basically run something like:</p>
<pre><code>while 1:
time.sleep(2)
score = score - 1
</code></pre>
<p>The only problem is that won't run simultaneously with the rest of the program, and threading (which is what seems to be the alternative) is very confusing to me. </p>
| 3 | 2016-07-26T07:25:12Z | 38,583,933 | <p>You can start new thread , by using following code and write whatever your functional logic in it's run() method.</p>
<pre><code>import threading
import time
class RepeatEvery(threading.Thread):
def __init__(self, interval):
threading.Thread.__init__(self)
self.interval = interval # seconds between calls
self.runable = True
def run(self):
global score # make score global for this thread context
while self.runable:
time.sleep(self.interval)
if self.runable:
score = score - 1
self.runable = False
def stop(self):
self.runable = False
</code></pre>
<p>The above code will iterate until thread is runnable(self.runable = True), so after 2 seconds score will decremented by 1. and loop inside the run method will break, and will be terminated.</p>
<p>So, in order to call above thread do this.</p>
<pre><code>score_thread = RepeatEvery(2)
score_thread.start()
</code></pre>
<p>this will call the thread constructor <strong>init</strong> and will initialize the interval variable with 2 seconds or whatever value passed from here.</p>
<p>In order to stop the thread meanwhile, just call the stop() method.</p>
<pre><code>score_thread.stop()
</code></pre>
<p>You can also call join() method , to wait until thread completes it's execution.</p>
<pre><code>score_thread.join()
</code></pre>
<p>Doesn't looks so confusing :)</p>
| 1 | 2016-07-26T07:47:07Z | [
"python",
"multithreading"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.