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
TypeError: Can't convert 'int' object to str implicity
38,702,403
<p>I'm trying to read the last line of a file. And then grab the first two digits in the file and add one to them so I can write that to a file with a new product. </p> <pre><code>with io.open('/home/jake/Projects/Stock','r+', encoding='utf8' as f: for line in f: if NewProduct == line[3:]: print ("You already sell this product, if you wish to add more stock please return to the menu") else: ProductPrice = input("Input A Price For This Product &gt;&gt; ") ProductAmount = input("How Many Do We Have In Stock &gt;&gt; ") last_line = f.readlines() New = last_line[-1]+int(1) Together = (New, NewProduct) TogetherV2 = (New, ProductPrice) TogetherV3 = (New, ProductAmount) </code></pre> <p>The file I'm reading and appending to is in this format</p> <pre><code>01 Tomatos 02 Chocolate </code></pre> <p>etc... I know I haven't added the part to grab the first two numbers from the file yet, I'm currently trying to grab the whole line and then adapt it to the first two numbers but haven't managed to. I know this is a possible duplicate I just couldn't understand or make a solution to work. Thanks in advance.</p>
0
2016-08-01T15:14:18Z
38,702,711
<p>The contents of your <code>last_line</code> is a string, like <code>"03 Apples"</code>. You're trying to add the integer <code>1</code> to that string, which raises the conversion error.</p> <p>To slice the value portion, and explicitly convert it to <code>int</code> type (which will allow you to add with other integer, do this:</p> <pre><code>New = int(last_line[-1][:1]) + 1 </code></pre>
0
2016-08-01T15:30:22Z
[ "python" ]
Seperate multi-line scraped text into seperate lists
38,702,410
<p>I am using BS4 to scrape text. My current output of the text has 7 different fields that I would like to put into 7 different lists. My code is as follows:</p> <pre><code>from bs4 import BeautifulSoup import requests urlYears = ['2012'] for year in urlYears: soup = BeautifulSoup(requests.get("https://en.wikipedia.org/wiki/" + "2012" + "_NFL_Draft").content,"html.parser") table = soup.select_one("table.wikitable.sortable") for row in table.select("tr + tr"): tds=row.text print (tds) </code></pre> <p>The printed output will show up like this:</p> <pre><code>7^ 252 St. Louis Rams Richardson, DarylDaryl Richardson  RB Abilene Christian Lone Star 7^ 253 Indianapolis Colts Harnish, ChandlerChandler Harnish  QB NIU MAC </code></pre> <p>How can I create lists from each of these? The ultimate goal is to export as a CSV.</p>
0
2016-08-01T15:14:32Z
38,702,690
<p>A trivial approach would be to just <a href="https://docs.python.org/2/library/stdtypes.html#str.split" rel="nofollow"><code>split()</code></a> the text at the newlines?</p> <pre><code>import os from bs4 import BeautifulSoup import requests soup = BeautifulSoup(requests.get("https://en.wikipedia.org/wiki/2012_NFL_Draft").content, "html.parser") table = soup.select_one("table.wikitable.sortable") for row in table.select("tr + tr"): tds=row.text.split(os.linesep) print tds </code></pre> <p>Yields</p> <pre><code>[u'', u'', u'1', u'1', u'Indianapolis Colts', u'Luck, AndrewAndrew Luck\xa0\u2020', u'QB', u'Stanford', u'Pac-12', u'', u''] [u'', u'', u'1', u'2', u'Washington Redskins', u'Griffin III, RobertRobert Griffin III\xa0\u2020', u'QB', u'Baylor', u'Big 12', u'from St. Louis\xa0[R1 - 1];', u'2011 Heisman Trophy winner\xa0[N 2]', u''] [u'', u'', u'1', u'3', u'Cleveland Browns', u'Richardson, TrentTrent Richardson\xa0', u'RB', u'Alabama', u'SEC', u'from Minnesota\xa0[R1 - 2]', u''] [u'', u'', u'1', u'4', u'Minnesota Vikings', u'Kalil, MattMatt Kalil\xa0\u2020', u'OT', u'USC', u'Pac-12', u'from Cleveland\xa0[R1 - 3]', u''] [u'', u'', u'1', u'5', u'Jacksonville Jaguars', u'Blackmon, JustinJustin Blackmon\xa0', u'WR', u'Oklahoma State', u'Big 12', u'from Tampa Bay\xa0[R1 - 4]', u''] ... </code></pre> <p>Hth dtk</p> <p><strong>Edit:</strong> you can actually just <a href="https://docs.python.org/2/library/stdtypes.html#unicode.splitlines" rel="nofollow"><code>.splitlines()</code></a> to have Python handle the newlines correctly. Saves the <code>os</code> import as well.</p>
0
2016-08-01T15:29:32Z
[ "python", "csv", "web-scraping", "beautifulsoup" ]
add a new path to PTYHONPATH and use it for program that is doing it using NSIS
38,702,470
<p><strong>Platform</strong>: Windows 7<br> <strong>Python</strong>: 2.7.3</p> <pre class="lang-nsis prettyprint-override"><code>StrCpy $NETWORK_PATH "\\someserver\network\path\here" DetailPrint "$\n" DetailPrint "Setting up paths required" Push "SETX PYTHONPATH $NETWORK_PATH;$NETWORK_PATH\lib" Call Execute Push '"C:\Python27\python.exe" setup.py deploy' Call Execute Function Execute Exch $0 # execution of the command and return success or failure FunctionEnd </code></pre> <p>This above is compiled as NSIS installer and run on multiple machines.</p> <p><strong>Problem</strong> <code>"C:\Python27\python.exe" setup.py deploy</code> depends on that $NETWORK_PATH for successful execution.</p> <p>First time when we run it, $NETWORK_PATH is appended to PYTHONPATH environmental variable, but <code>"C:\Python27\python.exe" setup.py deploy</code> fails as new PYTHONPATH will be effective only either in new command prompt or in next run.</p> <p>Is there a way to make the appended PYTHONPATH effective in the same run itself?</p> <p>Currently, we are running it twice - once for setting PYTHONPATH and accepting the failure, second time it runs successfully.</p> <p>Another alternative approach we tried is - we made 2 executables, one for setting PYTHONPATH and another for Python Script to run. Then we put both of them in batch script to run.</p> <p>But my preference is to achieve whole of this in one file and in one run.</p>
0
2016-08-01T15:18:08Z
38,703,620
<p>You can update the installers environment, it will be inherited by child processes:</p> <pre><code>System::Call 'Kernel32::SetEnvironmentVariable(t "PYTHONPATH", t "$NETWORK_PATH;$NETWORK_PATH\lib")i.r0' ; $0 will be != "0" on success Push '"C:\Python27\python.exe" setup.py deploy' Call Execute </code></pre>
1
2016-08-01T16:21:18Z
[ "python", "python-2.7", "nsis" ]
Invalid file error when trying to open file - Requests and Django
38,702,560
<p>I'm using requests module with Django and trying to send a file from a form but when I do I get "<em>invalid file :</em>" error when I try to open the file. I think that it's only trying to open the filename as a string instead of opening the actual file. How can I go about opening the actual file from the form instead of just trying to open the filename, so I can send it as a payload?</p> <pre><code>class AddDocumentView(LoginRequiredMixin, SuccessMessageMixin, CreateView): login_url = reverse_lazy('users:login') form_class = FileUploadForm template_name = 'docman/forms/add-document.html' success_message = 'Document was successfully added' def form_valid(self, form): pk = self.kwargs['pk'] user = get_object_or_404(User, pk=pk) file = form.save(commit=False) file.user = user if not self.post_to_server(file, user.id): file.delete() return super(AddDocumentView, self).form_valid(form) def post_to_server(self, file, cid): url = 'https://example.herokuapp.com/api/files/' headers = {'token': '333334wsfSecretToken'} # I get error here when trying to open file payload = {'file': open(file, 'rb'), 'client_id': cid} r = requests.post(url, data=payload, headers=headers) print(r.text) if r.status_code == requests.codes.ok: return True else: return False </code></pre>
0
2016-08-01T15:23:13Z
38,702,708
<p><code>open(file, 'rb')</code> receiving django model object from <code>file = form.save(commit=False)</code> line, not file. send original file. You can do something like</p> <pre><code>file = self.request.FILES.get('name') self.post_to_server(file, user.id) </code></pre> <p>Edit:</p> <p>No need to call open on the file, it's already open. <code>open(file, 'rb')</code> takes file path. the file is already open from above lines just use that. best practice</p> <pre><code>files = {'file': file} r = requests.post(url, files=files, data=payload) </code></pre>
1
2016-08-01T15:30:03Z
[ "python", "django", "python-requests" ]
Differentiation, .diff() doesn't give expected output
38,702,594
<p>I writing a bit of code, but the problem is found here:</p> <pre><code>[IN&gt;] from sympy import* [IN&gt;] t= Symbol('t') x1 = Function('x1')(t) x2 = Function('x2')(t) y1 = Function('y1')(t) y2 = Function('y2')(t) </code></pre> <p>I define my expression:</p> <pre><code>[IN&gt;] f = (x1.diff(t)*y2.diff(t)- x2.diff(t)*y1.diff(t)) </code></pre> <p>Then, when differentiating the expresion <code>f</code> wrt. the factors of the first summand I get the <em>unexpected</em> output:</p> <pre><code>[IN&gt;] f.diff(y2.diff(t)) [OUT&gt;] Subs(Derivative(x1(t), t), (_xi_2,), (Derivative(y2(t), t),)) </code></pre> <p>but if I differentiate wrt. the second summand factors</p> <pre><code>[IN&gt;] f.diff(y1.diff(t)) [OUT&gt;] -Derivative(x2(t), t) </code></pre> <p>I get the desired and <em>expected</em> result. I'm totally baffled by this. Still more, if I change the order of the summands, I get the same result:</p> <pre><code>[IN&gt;] (-x2.diff(t)*y1.diff(t)+x1.diff(t)*y2.diff(t) ).diff(y2.diff(t)) [OUT&gt;] Subs(Derivative(x1(t), t), (_xi_2,), (Derivative(y2(t), t),)) [IN&gt;] (-x2.diff(t)*y1.diff(t)+x1.diff(t)*y2.diff(t) ).diff(y1.diff(t)) [OUT&gt;] -Derivative(x2(t), t) </code></pre> <p>But if I exchange the minus `-``sign, the propeblem is now in the other pair of functions:</p> <pre><code>[IN&gt;] (+x2.diff(t)*y1.diff(t)-x1.diff(t)*y2.diff(t) ).diff(y1.diff(t)) [OUT&gt;] Subs(Derivative(x2(t), t), (_xi_2,), (Derivative(y1(t), t),)) </code></pre>
2
2016-08-01T15:24:51Z
38,705,907
<p>Ok, to get the <em>desired</em> result I only had to ad <code>.doit()</code>, as it was returning my the <code>Subs()</code> function.</p> <pre><code>(+x2.diff(t)*y1.diff(t)-x1.diff(t)*y2.diff(t) ).diff(y1.diff(t)).doit() Derivative(x2(t), t) </code></pre>
0
2016-08-01T18:41:45Z
[ "python", "math", "sympy", "differentiation" ]
Sorting a dict...efficient way to do it?
38,702,682
<p>I've have the problem where I have a dict of the passengers like this:</p> <pre><code>passengers = { 1: {'name': 'Foo', 'lastname': 'Bar', 'exclusive': True}, 2: {'name': 'John', 'lastname': 'Doe'}, 3: {'name': 'Rocky', 'lastname': 'Balboa', 'exclusive': True}, 4: {'name': 'Mohammed', 'lastname': 'Smith'} } </code></pre> <p>And I need to print the results like this items with exclusive first then the rest:<br> <strong>THIS IS THE DESIRED OUTPUT</strong> </p> <pre class="lang-none prettyprint-override"><code>List of passengers: =================== 1.- Foo Bar 2.- Rocky Balboa 3.- John Doe 4.- Mohammed Smith </code></pre> <p>I tried with <code>collections.deque</code>, and I haven't found anything that works for me, until I came up with this function:</p> <pre><code>def prioritize_passengers(dictionary): priority_list = [] normal_list = [] sorted_list = [] for key, item in dictionary.iteritems(): if 'exclusive' in item: priority_list.append(key) else: normal_list.append(key) sorted_list = priority_list + normal_list return sorted_list </code></pre> <p>And then I use it on my data like this:</p> <pre><code># Assuming passenger is the same var as above sorted_list = prioritize_passengers(passengers) print "List of passengers:\n===================" for elem in sorted_list: passenger = passengers[elem] print "{} {}".format(passenger['name'], passenger['lastname'] </code></pre> <p>Is that the only way to do it or is there a more clear/efficient way to achieve it? Again, the second paragraph is the desired output.</p>
-1
2016-08-01T15:29:07Z
38,702,901
<p>Yes, there are other ways to sort that list. Here is one:</p> <pre><code>passengers = { 1: {'name': 'Foo', 'lastname': 'Bar', 'exclusive': True}, 2: {'name': 'John', 'lastname': 'Doe'}, 3: {'name': 'Rocky', 'lastname': 'Balboa', 'exclusive': True}, 4: {'name': 'Mohammed', 'lastname': 'Smith'} } list_of_passengers = sorted( passengers.items(), key=lambda x: (('exclusive' not in x[1]), x[0])) for i, (_, passenger) in enumerate(list_of_passengers, 1): print '{}. - {} {}'.format(i, passenger['name'], passenger['lastname']) </code></pre> <p>Since you don't care about the order other than the <code>exclusive</code>-ness, then you this might work for you:</p> <pre><code>passengers = { 1: {'name': 'Foo', 'lastname': 'Bar', 'exclusive': True}, 2: {'name': 'John', 'lastname': 'Doe'}, 3: {'name': 'Rocky', 'lastname': 'Balboa', 'exclusive': True}, 4: {'name': 'Mohammed', 'lastname': 'Smith'} } list_of_passengers = sorted( passengers.values(), key=lambda x: 'exclusive' not in x) for i, passenger in enumerate(list_of_passengers, 1): print '{}. - {} {}'.format(i, passenger['name'], passenger['lastname']) </code></pre> <p>Finally, if what you really want to do is to create two separate lists, you can use the <code>filter()</code> builtin funciton:</p> <pre><code>upper_crust = filter(lambda x: 'exclusive' in x, passengers.values()) riff_raff = filter(lambda x: 'exclusive' not in x, passengers.values()) </code></pre>
5
2016-08-01T15:40:03Z
[ "python", "list", "python-2.7", "dictionary" ]
How to assign dataframe to panel from a function return
38,702,725
<p>I have a function which returns a panel and a dataframe. For example,</p> <pre><code>def fo(pn,df) some update on pn,df return pn, df </code></pre> <p>Then I need to call fo function to update pn4 and pn3 like below,</p> <pre><code>pn4.loc[0], pn3.loc[0] = fo(pn,df) </code></pre> <p>where pn4 is a Panel4 structure and pn3 is a Panel. As far as I know, pn4.loc[0] should be a panel and pn3.loc[0] should be a dataframe. But I recieved a error message when I run such code</p> <blockquote> <p>NotImplementedError: cannot set using an indexer with a Panel yet!</p> </blockquote> <p>So how can I address this error? Thanks in advance.</p> <p>For futher information, I post my codes below:</p> <pre><code>def update(x, UC, SC, A, U): # accelerated version, examined on 07/15 for a in A: UC_old = UC.copy() for u in U: UC.loc[a,:,u] = UC_old.loc[a,:,u] - UC_old.loc[a,:,x] * UC_old.loc[a,x,u] SC_old = SC.copy() SC.loc[:,a] = SC_old.loc[:,a] + UC_old.loc[a,x,:] * (1 - SC_old.loc[x,a]) return UC, SC def Streaming(UC, Au, k, U, A): ep = 0.01 SC = pd.DataFrame(0.0, index = U, columns = A) max_mg = 0 for x in U: mg = computeMG(x, UC, SC, Au, A, U) max_mg = mg if mg &gt; max_mg else max_mg del SC C = [] S = {} m = max_mg while (m &lt;= k*max_mg): C.append(m) S[m] = [] m = m * (1+ep) print len(C) UCC = pd.Panel4D(dict([(c, UC.copy()) for c in C])) SCC = pd.Panel(0., items = C, major_axis = U, minor_axis = A) for x in U: for c in C: if (computeMG(x, UCC.loc[c], SCC.loc[c], Au, A, U) &gt; c/float(2*k)) and (len(S[c])&lt;k): S[c].append(x) UCC.loc[c], SCC.loc[c] = update(x, UCC.loc[c], SCC.loc[c], A, U) # where the error happens max_val = 0 for c in C: val = 0 for u in U: Tsu = 0 for a in A: Tsu += SCC.loc[c,u,a] Tsu = Tsu / float(Au.loc[u]) val += Tsu if val &gt; max_val: S = S[c] max_val = val return S, max_val </code></pre>
1
2016-08-01T15:31:05Z
38,703,395
<p>The return type in <code>fo</code> is dataframe; however in the last line of your code you assign <code>pn4.loc[0]</code> and <code>pn3.loc[0]</code> to dataframe objects. <code>pn.4loc[0]</code> and <code>pn3.loc[0]</code> can be Pandas Series, that's why you saw the error because indexing is .</p> <p>Make your return command as <code>return pn.loc[0], df.loc[0]</code> and you probably can solve the issue.</p> <p>Below is the part of source code in <a href="http://pydoc.net/Python/pandas/0.15.1/pandas.core.indexing/" rel="nofollow">Pandas 0.15.1</a> describing NonImplementError you confronted:</p> <pre><code>def _align_panel(self, indexer, df): is_frame = self.obj.ndim == 2 is_panel = self.obj.ndim &gt;= 3 raise NotImplementedError("cannot set using an indexer with a Panel yet!") </code></pre> <p>As you can see if dimension of frame and panel doesn't match it will raise the error.</p>
0
2016-08-01T16:06:47Z
[ "python", "pandas", "dataframe", "panel" ]
How to assign dataframe to panel from a function return
38,702,725
<p>I have a function which returns a panel and a dataframe. For example,</p> <pre><code>def fo(pn,df) some update on pn,df return pn, df </code></pre> <p>Then I need to call fo function to update pn4 and pn3 like below,</p> <pre><code>pn4.loc[0], pn3.loc[0] = fo(pn,df) </code></pre> <p>where pn4 is a Panel4 structure and pn3 is a Panel. As far as I know, pn4.loc[0] should be a panel and pn3.loc[0] should be a dataframe. But I recieved a error message when I run such code</p> <blockquote> <p>NotImplementedError: cannot set using an indexer with a Panel yet!</p> </blockquote> <p>So how can I address this error? Thanks in advance.</p> <p>For futher information, I post my codes below:</p> <pre><code>def update(x, UC, SC, A, U): # accelerated version, examined on 07/15 for a in A: UC_old = UC.copy() for u in U: UC.loc[a,:,u] = UC_old.loc[a,:,u] - UC_old.loc[a,:,x] * UC_old.loc[a,x,u] SC_old = SC.copy() SC.loc[:,a] = SC_old.loc[:,a] + UC_old.loc[a,x,:] * (1 - SC_old.loc[x,a]) return UC, SC def Streaming(UC, Au, k, U, A): ep = 0.01 SC = pd.DataFrame(0.0, index = U, columns = A) max_mg = 0 for x in U: mg = computeMG(x, UC, SC, Au, A, U) max_mg = mg if mg &gt; max_mg else max_mg del SC C = [] S = {} m = max_mg while (m &lt;= k*max_mg): C.append(m) S[m] = [] m = m * (1+ep) print len(C) UCC = pd.Panel4D(dict([(c, UC.copy()) for c in C])) SCC = pd.Panel(0., items = C, major_axis = U, minor_axis = A) for x in U: for c in C: if (computeMG(x, UCC.loc[c], SCC.loc[c], Au, A, U) &gt; c/float(2*k)) and (len(S[c])&lt;k): S[c].append(x) UCC.loc[c], SCC.loc[c] = update(x, UCC.loc[c], SCC.loc[c], A, U) # where the error happens max_val = 0 for c in C: val = 0 for u in U: Tsu = 0 for a in A: Tsu += SCC.loc[c,u,a] Tsu = Tsu / float(Au.loc[u]) val += Tsu if val &gt; max_val: S = S[c] max_val = val return S, max_val </code></pre>
1
2016-08-01T15:31:05Z
38,703,713
<p>For dataframes and series, you can use <code>loc</code> and <code>iloc</code> (and <code>at</code> and <code>iat</code> also) to get and set. This requires coding to make happen. The error you are seeing</p> <blockquote> <p>NotImplementedError: cannot set using an indexer with a Panel yet!</p> </blockquote> <p>Means that someone hasn't gotten around to make it happen for panels yet.</p> <p>you should be able to make the assignment with </p> <pre><code>pn4[0], pn3[0] = fo(pn,df) </code></pre>
0
2016-08-01T16:26:50Z
[ "python", "pandas", "dataframe", "panel" ]
How to do transactions in python with asyncio and postgres?
38,702,756
<p>There are two operations in my RPC method:</p> <pre><code>async def my_rpc(self, data): async with self.Engine() as conn: await conn.execute("SELECT ... FROM MyTable"); ... # It seems the table MyTable can be changed by another RPC await conn.execute("UPDATA MyTable ..."); </code></pre> <p>Another RPC method can change DB before operation "my_rpc" will be done (between two awaits of SQL queries). How to avoid this situation?</p> <p>Code of self.Engine (calls with engine <code>aiopg.sa.create_engine</code>):</p> <pre><code>class ConnectionContextManager(object): def __init__(self, engine): self.conn = None self.engine = engine async def __aenter__(self): if self.engine: self.conn = await self.engine.acquire() return self.conn async def __aexit__(self, exc_type, exc, tb): try: self.engine.release(self.conn) self.conn.close() finally: self.conn = None self.engine = None </code></pre>
2
2016-08-01T15:32:51Z
38,703,699
<p>It looks like the only way to avoid confusion is to have each transaction to take place in a separate database connection (Python side cursors won't do) The way to do that is to have a connection pool - and have your Engine method deliver a different connection for each "async thread".</p> <p>That would be easier if the connector to the Postgresql itself would be async-aware (which driver are you using, btw?). Or a database-wrapper layer above it. If it is not, you will have to implement this connection pool yourself. I think Sqlalchemy connection pools will work just right fot that case, as, independent of being used in a co-routine, a connection will only be freed at the end of the <code>async with</code> block. </p>
1
2016-08-01T16:26:03Z
[ "python", "postgresql", "transactions", "async-await", "python-asyncio" ]
How to do transactions in python with asyncio and postgres?
38,702,756
<p>There are two operations in my RPC method:</p> <pre><code>async def my_rpc(self, data): async with self.Engine() as conn: await conn.execute("SELECT ... FROM MyTable"); ... # It seems the table MyTable can be changed by another RPC await conn.execute("UPDATA MyTable ..."); </code></pre> <p>Another RPC method can change DB before operation "my_rpc" will be done (between two awaits of SQL queries). How to avoid this situation?</p> <p>Code of self.Engine (calls with engine <code>aiopg.sa.create_engine</code>):</p> <pre><code>class ConnectionContextManager(object): def __init__(self, engine): self.conn = None self.engine = engine async def __aenter__(self): if self.engine: self.conn = await self.engine.acquire() return self.conn async def __aexit__(self, exc_type, exc, tb): try: self.engine.release(self.conn) self.conn.close() finally: self.conn = None self.engine = None </code></pre>
2
2016-08-01T15:32:51Z
38,737,618
<p>Firstly, <code>aiopg</code> works in autocommit mode, meaning that you have to use transaction in manual mode. <a href="http://aiopg.readthedocs.io/en/stable/core.html#transactions" rel="nofollow">Read more details</a>.</p> <p>Secondly, you have to use SELECT FOR UPDATE for lock row that you read in first statement. SELECT FOR UPDATE locks select rows while until the transaction completes. <a href="https://www.postgresql.org/docs/9.0/static/sql-select.html#SQL-FOR-UPDATE-SHARE" rel="nofollow">Read more details</a>.</p> <pre><code>async def my_rpc(self, data): async with self.Engine() as conn: await conn.execute("BEGIN") await conn.execute("SELECT ... FROM MyTable WHERE some_clause = some_value FOR UPDATE") ... # It seems the table MyTable can be changed by another RPC await conn.execute("UPDATE MyTable SET some_clause=...") await conn.execute("""COMMIT""") </code></pre>
2
2016-08-03T07:54:56Z
[ "python", "postgresql", "transactions", "async-await", "python-asyncio" ]
Manipulating websites: Pressing buttons and reading elements
38,702,865
<p>I'm trying to navigate through a website's directory by pressing buttons on the page (or directly calling the functions tied to them) and skim data from the respective pages. What language/environment would be best suited for this? I've tried python, java, selenium, and javascript. I would like to use javascript, but I don't know the proper approach. I tried making a simple website with script tags in which I can load another website (var win = window.open()) but cannot access elements from it (win.buttonFunc() or win.document.form[0].submit()). Is this the wrong approach? If so, what's the best way to use javascript here (if possible)?</p>
-1
2016-08-01T15:38:24Z
38,702,934
<p>Maybe I am misunderstanding, but I think you should be using Javascript with JQuery if you are wanting to manipulate page elements. If you check out JQuery, and still have questions, try editing the post.</p>
0
2016-08-01T15:41:24Z
[ "javascript", "jquery", "python", "html", "selenium" ]
How to do assignment in Pandas without warning?
38,702,886
<p>I'm trying to port this code in R to Python using Pandas.</p> <p>This is my R code (assume data is a <code>data.frame</code>):</p> <pre><code>transform &lt;- function(data) { baseValue &lt;- data$baseValue na.base.value &lt;- is.na(baseValue) baseValue[na.base.value] &lt;- 1 zero.base.value &lt;- baseValue == 0 baseValue[zero.base.value] &lt;- 1 data$adjustedBaseValue &lt;- data$baseRatio * baseValue baseValue[na.base.value] &lt;- -1 baseValue[zero.base.value] &lt;- 0 data$baseValue &lt;- baseValue return(data) } </code></pre> <p>This is my attempt to port the R code in Python (assume data is <code>pandas.DataFrame</code>):</p> <pre><code>import pandas as pd def transform(data): base_value = data['baseValue'] na_base_value = base_value.isnull() base_value.loc[na_base_value] = 1 zero_base_value = base_value == 0 base_value.loc[zero_base_value] = 1 data['adjustedBaseValue'] = data['baseRatio'] * base_value base_value.loc[na_base_value] = -1 base_value.loc[zero_base_value] = 0 return data </code></pre> <p>But then I got this warning:</p> <blockquote> <p>A value is trying to be set on a copy of a slice from a DataFrame</p> <p>See the caveats in the documentation: <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy</a> self._setitem_with_indexer(indexer, value)</p> </blockquote> <p>I have read through and don't understand how to fix it. What should I do to fix the code so that there is no more warning? I don't want to suppress the warning though.</p>
1
2016-08-01T15:39:15Z
38,702,971
<p>If you want to modify the same object that was passed to the function, then this should work so long as what's passed in as <code>data</code> isn't already a view of another dataframe.</p> <pre><code>def transform(data): base_value = data['baseValue'] na_base_value = base_value.isnull() data.loc[na_base_value, 'baseValue'] = 1 zero_base_value = base_value == 0 data.loc[zero_base_value, 'baseValue'] = 1 data['adjustedBaseValue'] = data['baseRatio'] * base_value data.loc[na_base_value, 'baseValue'] = -1 data.loc[zero_base_value, 'baseValue'] = 0 return data </code></pre> <p>If you want to work with a copy and return that manipulated copied data then this is your answer.</p> <pre><code>def transform(data): data = data.copy() base_value = data['baseValue'].copy() na_base_value = base_value.isnull() base_value.loc[na_base_value] = 1 zero_base_value = base_value == 0 base_value.loc[zero_base_value] = 1 data['adjustedBaseValue'] = data['baseValue'] * base_value base_value.loc[na_base_value] = -1 base_value.loc[zero_base_value] = 0 return data </code></pre>
2
2016-08-01T15:43:09Z
[ "python", "pandas" ]
What is the replacement for DateModifierNode in new versions of Django
38,703,016
<p>I want to do a query based on two fields of a model, a date, offset by an int, used as a timedelta</p> <pre><code>model.objects.filter(last_date__gte=datetime.now()-timedelta(days=F('interval'))) </code></pre> <p>is a no-go, as a F() expression cannot be passed into a timedelta</p> <p>A little digging, and I discovered <code>DateModifierNode</code> - though it seems it was removed in this commit: <a href="https://github.com/django/django/commit/cbb5cdd155668ba771cad6b975676d3b20fed37b" rel="nofollow">https://github.com/django/django/commit/cbb5cdd155668ba771cad6b975676d3b20fed37b</a> (from this now-outdated SO question <a href="http://stackoverflow.com/questions/24133829/django-using-f-arguments-in-datetime-timedelta-inside-a-query/24135138?s=1|0.2211#24135138">Django: Using F arguments in datetime.timedelta inside a query</a>)</p> <p>the commit mentions: </p> <blockquote> <p>The .dates() queries were implemented by using custom Query, QuerySet, and Compiler classes. Instead implement them by using expressions and database converters APIs.</p> </blockquote> <p>which sounds sensible, and like there should still be a quick easy way - but I've been fruitlessly looking for how to do that for a little too long - anyone know the answer?</p>
1
2016-08-01T15:45:05Z
38,703,183
<p>Ah, answer from the docs: <a href="https://docs.djangoproject.com/en/1.9/ref/models/expressions/#using-f-with-annotations" rel="nofollow">https://docs.djangoproject.com/en/1.9/ref/models/expressions/#using-f-with-annotations</a></p> <pre><code>from django.db.models import DateTimeField, ExpressionWrapper, F Ticket.objects.annotate( expires=ExpressionWrapper( F('active_at') + F('duration'), output_field=DateTimeField())) </code></pre> <p>which should make my original query look like</p> <pre><code>model.objects.annotate(new_date=ExpressionWrapper(F('last_date') + F('interval'), output_field=DateTimeField())).filter(new_date__gte=datetime.now()) </code></pre>
3
2016-08-01T15:55:39Z
[ "python", "django", "django-models", "orm", "django-orm" ]
expand strings as algebraic expressions
38,703,140
<p>I have a set of simple strings, that represents some DSL:</p> <pre><code>my_str = ['("word 1" + "word 2") * "word 3"', '("word 1" + "word 2") * ("word 3" + "word 4")', '(("word 1" + "word 2") * ("word 3" + "word 4")) * "word 5"', ] </code></pre> <p>I was trying (and failing badly) to change these to a more straight forward form such as </p> <pre><code>a = foo(my_str) a= [ '("word 1" * "word 3") + ("word 2" * "word 3")', '("word 1" * "word 3") + ("word 1" * "word 4") + ("word 2" * "word 3") + ("word 2" * "word 4")', '("word 1" * "word 3" * "word 5") + ("word 1" * "word 4" * "word 5") + ("word 2" * "word 3" * "word 5") + ("word 2" * "word 4" * "word 5")', ] </code></pre> <p>May be its something simple but I can't seem to get my head around the logic.</p>
1
2016-08-01T15:53:14Z
39,613,551
<p>Ok In the end I used a combination of sympy and pyparsing. I used pyparsing to understand the relationships and hierarchies between variables, and then sympy to create and expand the expression.</p> <p>Some one interested in a bit over-done code can have a look at the <a href="https://gist.github.com/fahaddaniyal/1a1ec377c3a02903d400cb3de88899e9" rel="nofollow">gist</a> here.</p>
0
2016-09-21T10:09:28Z
[ "python", "string" ]
How can I sort this dictionary like the original string?
38,703,238
<p>I can't see a pattern for the results that I'm having on the print. And I've already tried other solutions for this, but can't get it right =(</p> <pre><code>s = "hi hi hi, how are you? you you" print(s) s = s.replace('?','') s = s.replace('!','') s = s.replace(',','') s = s.replace('.','') l = s.split() d = {} for i, termo in enumerate(l): if not d.get(termo): d[termo] = [] d[termo].append(i+1) print ('d:', d) </code></pre> <p>An example output: </p> <pre><code>d: {'you': [6, 7, 8], 'how': [4], 'are': [5], 'hi': [1, 2, 3]} d: {'are': [5], 'hi': [1, 2, 3], 'how': [4], 'you': [6, 7, 8]} </code></pre>
0
2016-08-01T15:58:22Z
38,704,971
<p>A Dictionary is an unordered collection. Use a <code>collections.OrderedDict</code>, instead:</p> <pre><code>from collections import OrderedDict s = "hi hi hi, how are you? you you" s = s.translate(None, '?!,.') l = s.split() d = OrderedDict() for i, termo in enumerate(l): d.setdefault(termo, []).append(i) print ('d:', d) </code></pre> <p>Notes: </p> <ul> <li><p><code>collectins.OrderedDict</code> remembers the order in which data are added. Subsequently iteration of the dictionary occurs in the same order.</p></li> <li><p><code>str.translate()</code> is a quick way to delete a class of characters from a string.</p></li> <li><p><code>dict.setdefault()</code> returns a value of a dictionary if the key exists, or creates the value otherwise. It replaces the <code>if x not in d: d[x] = y</code> pattern.</p></li> </ul>
0
2016-08-01T17:39:50Z
[ "python" ]
How to parse logs and extract lines containing specific text strings?
38,703,250
<p>I've got several hundred log files that I need to parse searching for text strings. What I would like to be able to do is run a Python script to open every file in the current folder, parse it and record the results in a new file with the original_name_parsed_log_file.txt. I had the script working on a single file but now I'm having some issues doing all files in the directory.</p> <p>Below is what I have so far but it's not working atm. Disregard the first def... I was playing around with changing font colors.</p> <pre><code>import os import string from ctypes import * title = ' Log Parser ' windll.Kernel32.GetStdHandle.restype = c_ulong h = windll.Kernel32.GetStdHandle(c_ulong(0xfffffff5)) def display_title_bar(): windll.Kernel32.SetConsoleTextAttribute(h, 14) print '\n' print '*' * 75 + '\n' windll.Kernel32.SetConsoleTextAttribute(h, 13) print title.center(75, ' ') windll.Kernel32.SetConsoleTextAttribute(h, 14) print '\n' + '*' * 75 + '\n' windll.Kernel32.SetConsoleTextAttribute(h, 11) def parse_files(search): for filename in os.listdir(os.getcwd()): newname=join(filename, '0_Parsed_Log_File.txt') with open(filename) as read: read.seek(0) # Search line for values if found append line with spaces replaced by tabs to new file. with open(newname, 'ab') as write: for line in read: for val in search: if val in line: write.write(line.replace(' ', '\t')) line = line[5:] read.close() write.close() print'\n\n'+'Parsing Complete.' windll.Kernel32.SetConsoleTextAttribute(h, 15) display_title_bar() search = raw_input('Please enter search terms separated by commas: ').split(',') parse_files(search) </code></pre>
0
2016-08-01T15:59:13Z
38,703,535
<p>This line is wrong:</p> <pre><code> newname=join(filename, '0_Parsed_Log_File.txt') </code></pre> <p>use:</p> <pre><code> newname= "".join([filename, '0_Parsed_Log_File.txt']) </code></pre> <p><code>join</code> is a string method which requires a list of strings to be joined</p>
1
2016-08-01T16:15:31Z
[ "python", "string", "parsing" ]
split list comprehension into nested lists based on a rule
38,703,273
<p>I have a simple list splitting question:</p> <p>given a nested list like this:</p> <pre><code>x = [[1,4,3],[2,3,5,1,3,52,3,5,2,1],[2]] </code></pre> <p>I want to further split any element(sub-list) longer than 3, and whose length is a multiple of 3 or 3n+1 into sub-lists of length 3, except for the last chunk, so the result I want is:</p> <pre><code>x2 = [[1,4,3], [2,3,5],[1,3,52],[3,5,2,1],[2]] </code></pre> <p>I think it can be done with itertools.groupby and/or yield functions... but couldn't put together the details >> a_function(x)... </p> <pre><code> splits = [ a_function(x) if len(x)&gt;3 and (len(x) % 3 == 0 or len(x) % 3 == 1) else x for x in x] </code></pre> <p>Could anyone kindly give me some pointers? Thanks so much.</p>
0
2016-08-01T16:00:14Z
38,703,379
<p>Sometimes, when the requirements for a list comprehension are unusual or complicated, I use a generator function, like so:</p> <pre><code>def gen(l): for sublist in l: if len(sublist)%3 == 0: for i in range(0, len(sublist), 3): yield sublist[i:i+3] elif len(sublist)%3 == 1: for i in range(0, len(sublist)-4, 3): yield sublist[i:i+3] yield sublist[-4:] else: yield sublist # OP's data: x = [[1,4,3],[2,3,5,1,3,52,3,5,2],[2]] y = [[1,4,3],[2,3,5,1,3,52,3,5,2,1],[2]] # Using either list comprehension or list constructor: newx = [item for item in gen(x)] newy = list(gen(y)) # Result: assert newx == [[1, 4, 3], [2, 3, 5], [1, 3, 52], [3, 5, 2], [2]] assert newy == [[1, 4, 3], [2, 3, 5], [1, 3, 52], [3, 5, 2, 1], [2]] </code></pre>
0
2016-08-01T16:05:43Z
[ "python", "list" ]
split list comprehension into nested lists based on a rule
38,703,273
<p>I have a simple list splitting question:</p> <p>given a nested list like this:</p> <pre><code>x = [[1,4,3],[2,3,5,1,3,52,3,5,2,1],[2]] </code></pre> <p>I want to further split any element(sub-list) longer than 3, and whose length is a multiple of 3 or 3n+1 into sub-lists of length 3, except for the last chunk, so the result I want is:</p> <pre><code>x2 = [[1,4,3], [2,3,5],[1,3,52],[3,5,2,1],[2]] </code></pre> <p>I think it can be done with itertools.groupby and/or yield functions... but couldn't put together the details >> a_function(x)... </p> <pre><code> splits = [ a_function(x) if len(x)&gt;3 and (len(x) % 3 == 0 or len(x) % 3 == 1) else x for x in x] </code></pre> <p>Could anyone kindly give me some pointers? Thanks so much.</p>
0
2016-08-01T16:00:14Z
38,704,313
<pre><code># Create the list x = [[1,4,3],[2,3,5,1,3,52,3,5,2,1],[2]] test = [] # Loop through each index of the list for i in range(len(x)): #if the length of the specific index is 3 then go do this loop. if len(x[i]) &gt; 3: j = len(x[i]) # This cuts through the loop every 3 steps and makes it a new list. test = ([x[i][j:j+3] for j in range(0, len(x[i]), 3)]) # If the length of the last index is 1 then add it to the previous index of the new list. if len(test[-1]) == 1: test[-2] = test[-2] + test[-1] # pop deletes the last entry test.pop(-1) x[i] = test else: x[i] = test </code></pre> <p>You then get the output: </p> <pre><code>[[1, 4, 3], [[2, 3, 5], [1, 3, 52], [3, 5, 2, 1]], [2]] </code></pre>
0
2016-08-01T17:01:15Z
[ "python", "list" ]
Counting the number of words in string?
38,703,308
<p>I have written this function.</p> <pre><code># Function to count words in a string. def word_count(string): tokens = string.split() n_tokens = len(tokens) print (n_tokens) # Test the code. print(word_count("Hello World!")) print(word_count("The quick brown fox jumped over the lazy dog.")) </code></pre> <p>but the output is</p> <pre><code>2 None 9 None </code></pre> <p>instead of just </p> <pre><code>2 9 </code></pre>
-1
2016-08-01T16:02:08Z
38,703,371
<p><code>word_count</code> does not have a <code>return</code> statement, so it implicitly returns <code>None</code>. Your function prints the number of tokens <code>print (n_tokens)</code> and then your function call <code>print(word_count("Hello World!"))</code> prints <code>None</code>.</p>
1
2016-08-01T16:05:12Z
[ "python" ]
Counting the number of words in string?
38,703,308
<p>I have written this function.</p> <pre><code># Function to count words in a string. def word_count(string): tokens = string.split() n_tokens = len(tokens) print (n_tokens) # Test the code. print(word_count("Hello World!")) print(word_count("The quick brown fox jumped over the lazy dog.")) </code></pre> <p>but the output is</p> <pre><code>2 None 9 None </code></pre> <p>instead of just </p> <pre><code>2 9 </code></pre>
-1
2016-08-01T16:02:08Z
38,703,377
<p>Apart from what Brian said, this code illustrates how to get what you want:</p> <pre><code># Function to count words in a string. def word_count(string): tokens = string.split() n_tokens = len(tokens) return n_tokens # &lt;-- here is the difference print(word_count("Hello World!")) print(word_count("The quick brown fox jumped over the lazy dog.")) </code></pre>
0
2016-08-01T16:05:38Z
[ "python" ]
Odoo: set select item from many2many_tags widget
38,703,367
<p>I have a button inside my customer refund form.When i click on it, i loop through all invoice lines to update the column "tax" to display the corresponding tax. I'm able to get the id of the associated tax (the tax column is a many2many_tags widget )for the product. Now i want to display the item with that ID using python. Please any suggestions.</p> <p><a href="http://i.stack.imgur.com/iJVdo.png" rel="nofollow"><img src="http://i.stack.imgur.com/iJVdo.png" alt="enter image description here"></a></p> <pre><code>res['value']['invoice_line_tax_id']=mytaxeid doesn't work </code></pre>
1
2016-08-01T16:05:06Z
38,704,441
<p>You need to use <a href="https://github.com/odoo/odoo/blob/9.0/openerp/models.py#L3772" rel="nofollow">triplets</a> for many2many fields.</p> <p>2 examples:</p> <ol> <li>Replace all taxes with taxes IDs 2 and 4</li> </ol> <pre class="lang-py prettyprint-override"><code>res['value']['invoice_line_tax_id'] = [(6, 0, [2, 4])] </code></pre> <ol start="2"> <li>Add the tax with ID 7</li> </ol> <pre class="lang-py prettyprint-override"><code>res['value']['invoice_line_tax_id'] = [(4, 7)] </code></pre>
0
2016-08-01T17:09:24Z
[ "python", "openerp", "odoo-8" ]
2D matrix value difference
38,703,374
<p>I have 2 columns in excel, parameter <code>A1</code>:<code>A5</code> and value <code>D1</code>:<code>D5</code>:</p> <pre><code>1 2.0 2 1.5 3 3.5 4 2.3 5 7.7 </code></pre> <p>Please let me know how to create a 2D matrix using iPython notebook. For both rows and columns the parameter (column A) should be used, and the cells should have the difference of the values. E.g.:</p> <pre><code> 1 2 3 1 0.0 0.5 -1.5 2 -0.5 0.0 -2.0 3 1.5 2.0 0.0 </code></pre> <p>Or can be just one sided matrix.</p> <p>Or if this is easier to do with excel, please suggest.</p>
0
2016-08-01T16:05:32Z
38,703,583
<p>I suggest using one of the scientific python distributions, see scipy.org, Install section. I use Anaconda. If you use the IPython notebook installed from one of the scientific python distributions, then you are ready to use it right away.</p> <p>You get many useful packages, specifically, pandas package.</p> <p>You do</p> <pre><code>import pandas as pd </code></pre> <p>then</p> <pre><code>data = pd.read_excel(filename) </code></pre> <p>you get a data frame, with all the data. You can set the data frame column names by supplying a list of names with the keyword argument 'names' in the above function.</p> <p>See here: <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html" rel="nofollow">pd.read_excel</a></p>
0
2016-08-01T16:18:56Z
[ "python", "excel", "matrix" ]
Error Installing OpenCV with Python on OS X
38,703,388
<p>I have been trying to install Open CV 3 on my mac using this <a href="http://www.pyimagesearch.com/2015/06/15/install-opencv-3-0-and-python-2-7-on-osx/" rel="nofollow">tutorial</a> but I cannot get past step three. </p> <p>So after I do </p> <pre><code>brew install python </code></pre> <p>I do </p> <pre><code>nano ~/.bash_profile </code></pre> <p>And the at the bottom of the script I paste</p> <pre><code># Homebrew export PATH=/usr/local/bin:$PATH </code></pre> <p>After that I reload the file like this </p> <pre><code>source ~/.bash_profile </code></pre> <p>Finally I check the python like this</p> <pre><code>which python </code></pre> <p>And it prints</p> <pre><code>/usr/bin/python </code></pre> <p>instead of </p> <pre><code>/usr/local/bin/python </code></pre> <p>I have also tried edited the file in TextEdit but it has the same result. </p> <p>Am I doing something wrong or is this just a bad tutorial?</p> <p>Thank You in Advance!</p> <p>Edit:</p> <pre><code># Setting PATH for Python 3.5 # The orginal version is saved in .bash_profile.pysave PATH="/Library/Frameworks/Python.framework/Versions/3.5/bin:${PATH}" export PATH ## # Your previous /Users/UserName/.bash_profile file was backed up as /Users/UserName/.bash_profile.macports-saved_2016-07-26_at_12:50:19 ## # MacPorts Installer addition on 2016-07-26_at_12:50:19: adding an appropriate PATH variable for use with MacPorts. export PATH="/opt/local/bin:/opt/local/sbin:$PATH" # Finished adapting your PATH environment variable for use with MacPorts. # Homebrew export PATH=/usr/local/bin:$PATH </code></pre> <p>pydoc3.5 python3 python3-32 python3-config python3.5 python3.5-32 python3.5-config python3.5m python3.5m-config</p>
2
2016-08-01T16:06:17Z
38,754,193
<p>Okay so one brute force solution could be this one <a href="http://stackoverflow.com/a/9821036/128517">http://stackoverflow.com/a/9821036/128517</a></p> <p>But maybe you could check the value of your $PATH after <code>source ~/.bash_profile</code> typing </p> <pre><code>&gt; echo $PATH </code></pre> <p>and see if <code>/usr/local/bin</code> is indeed at the beginning.</p> <p>if it's not, you might need to check if there's another export before yours or maybe you need to edit <code>.profile</code> instead.</p>
1
2016-08-03T21:48:37Z
[ "python", "osx", "opencv", "homebrew" ]
Error Installing OpenCV with Python on OS X
38,703,388
<p>I have been trying to install Open CV 3 on my mac using this <a href="http://www.pyimagesearch.com/2015/06/15/install-opencv-3-0-and-python-2-7-on-osx/" rel="nofollow">tutorial</a> but I cannot get past step three. </p> <p>So after I do </p> <pre><code>brew install python </code></pre> <p>I do </p> <pre><code>nano ~/.bash_profile </code></pre> <p>And the at the bottom of the script I paste</p> <pre><code># Homebrew export PATH=/usr/local/bin:$PATH </code></pre> <p>After that I reload the file like this </p> <pre><code>source ~/.bash_profile </code></pre> <p>Finally I check the python like this</p> <pre><code>which python </code></pre> <p>And it prints</p> <pre><code>/usr/bin/python </code></pre> <p>instead of </p> <pre><code>/usr/local/bin/python </code></pre> <p>I have also tried edited the file in TextEdit but it has the same result. </p> <p>Am I doing something wrong or is this just a bad tutorial?</p> <p>Thank You in Advance!</p> <p>Edit:</p> <pre><code># Setting PATH for Python 3.5 # The orginal version is saved in .bash_profile.pysave PATH="/Library/Frameworks/Python.framework/Versions/3.5/bin:${PATH}" export PATH ## # Your previous /Users/UserName/.bash_profile file was backed up as /Users/UserName/.bash_profile.macports-saved_2016-07-26_at_12:50:19 ## # MacPorts Installer addition on 2016-07-26_at_12:50:19: adding an appropriate PATH variable for use with MacPorts. export PATH="/opt/local/bin:/opt/local/sbin:$PATH" # Finished adapting your PATH environment variable for use with MacPorts. # Homebrew export PATH=/usr/local/bin:$PATH </code></pre> <p>pydoc3.5 python3 python3-32 python3-config python3.5 python3.5-32 python3.5-config python3.5m python3.5m-config</p>
2
2016-08-01T16:06:17Z
38,754,842
<p>Is there a </p> <pre><code>/usr/local/Cellar/python/2.7.12/ </code></pre> <p>directory? (Version number might differ.)</p> <p>Is there a </p> <pre><code>/usr/local/bin/python </code></pre> <p>file?</p> <p>If the Cellar directory is present, but the file isn't, then Homebrew decided to be careful and not put Python in <code>/usr/local/bin/</code> immediately.<br> You could manually do</p> <pre><code>brew link python </code></pre> <p>and see if there's now a</p> <pre><code>/usr/local/bin/python </code></pre> <p>file.</p> <hr> <p>In your case, it appears you have some files related to Python (they might be from a Python 3 installation, can't tell), such as <code>2to3</code>. You can safely overwrite them, since Python 2 also has this. Thus:</p> <pre><code>brew link --overwrite python </code></pre> <p>is fine.</p> <p>Note:</p> <p>Specific Python versions will always exist as <code>python2.7</code>, <code>python3.5</code> etc (including the full path as necessary). Thus, even overwriting the <code>python</code> executable is safe (provided it's not the system one in <code>/usr/bin</code>): you should then simply be explicit which python executable to use.</p> <p>Also, when using a tool like <code>pip</code>, you can make sure you're using the correct version by running it e.g. as </p> <pre><code>/usr/local/bin/pythnon2.7 -m pip &lt;...&gt; </code></pre> <p>or whatever python executable you want to install things for.</p>
1
2016-08-03T22:44:53Z
[ "python", "osx", "opencv", "homebrew" ]
Opens same registry twice?
38,703,394
<p>I am trying to get all installed programs of my windows computer, therefore I read out the registry.</p> <p>But somehow python reads the 32bit programs out twice (even though I give him another registry entry)</p> <p>Here is the code snipped:</p> <pre><code>def get_programs(registry): reg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) programList = [] key = OpenKey(reg, registry) print(QueryInfoKey(key)) for i in range(0, QueryInfoKey(key)[0]): programList.append(EnumKey(key, i)) CloseKey(key) CloseKey(reg) return programList </code></pre> <p>I call this function like this:</p> <pre><code>registry32bit = "SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall" registry64bit = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" programs32bit = get_programs(registry32bit) programs64bit = get_programs(registry64bit) </code></pre> <p>Why does python open and read out the same registry (for 32 bit) twice and return the exactly same list?</p>
1
2016-08-01T16:06:38Z
38,710,144
<p>This appears to work and uses @eryksun suggestion in a comment below about just letting the redirection happen and not explicitly referencing the <code>Wow6432Node</code> registry key. The central idea is to just specify either the <code>KEY_WOW64_32KEY</code> or <code>KEY_WOW64_64KEY</code> flag when opening the uninstall subkey and let the magic happen.</p> <p>Note: I also <em>Pythonized</em> the code in the <code>get_programs()</code> function some. This made it shorter and more readable in my opinion.</p> <pre><code>import sys from _winreg import * # Assure registry handle objects with context manager protocol implemented. if sys.version_info.major*10 + sys.version_info.minor &lt; 26: raise AssertionError('At least Python 2.6 is required.') def get_programs(subkey, regBitView): with ConnectRegistry(None, HKEY_LOCAL_MACHINE) as hive: with OpenKey(hive, subkey, 0, regBitView | KEY_READ) as key: return [EnumKey(key, i) for i in range(QueryInfoKey(key)[0])] UNINSTALL_REG_KEY = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall' programs32bit = get_programs(UNINSTALL_REG_KEY, KEY_WOW64_32KEY) programs64bit = get_programs(UNINSTALL_REG_KEY, KEY_WOW64_64KEY) print('32-bit programs:\n{}'.format(programs32bit)) print('') print('64-bit programs:\n{}'.format(programs64bit)) </code></pre> <p>Many thanks to @eryksun for the clues and many implementation strategy suggestions.</p>
1
2016-08-02T00:43:37Z
[ "python", "windows", "python-2.7" ]
select subarrays delimited by zeros in python
38,703,403
<p>Given a list like:</p> <pre><code>A = [18, 7, 0, 0, 0, 9, 12, 0, 0, 11, 2, 3, 3, 0, 0, 7, 8] </code></pre> <p>is there a simple way to create subarrays, with those elements that are separated by zeros (or at least by NaNs)? I mean, like:</p> <pre><code>A1 = [18, 7] A2 = [9, 12] A3 = [11, 2, 3, 3] A4 = [7, 8] </code></pre> <p>I've written:</p> <pre><code>q=0 for i in range(0,len(A)): if A[i]-A[i-1] &lt; 1: q=q+1 </code></pre> <p>to retrieve the number of zeros-packets present in the list. But I need to populate subarrays, as long as I encounter them through the list... maybe something with the <code>split</code> function? Thank you in advance.</p>
0
2016-08-01T16:07:13Z
38,703,558
<p>Try this:</p> <pre><code>import itertools as it A = [18, 7, 0, 0, 0, 9, 12, 0, 0, 11, 2, 3, 3, 0, 0, 7, 8] [list(v) for k, v in it.groupby(A, lambda x: not x) if not k] =&gt; [[18, 7], [9, 12], [11, 2, 3, 3], [7, 8]] </code></pre>
1
2016-08-01T16:17:09Z
[ "python", "list", "zero", "sub-array" ]
select subarrays delimited by zeros in python
38,703,403
<p>Given a list like:</p> <pre><code>A = [18, 7, 0, 0, 0, 9, 12, 0, 0, 11, 2, 3, 3, 0, 0, 7, 8] </code></pre> <p>is there a simple way to create subarrays, with those elements that are separated by zeros (or at least by NaNs)? I mean, like:</p> <pre><code>A1 = [18, 7] A2 = [9, 12] A3 = [11, 2, 3, 3] A4 = [7, 8] </code></pre> <p>I've written:</p> <pre><code>q=0 for i in range(0,len(A)): if A[i]-A[i-1] &lt; 1: q=q+1 </code></pre> <p>to retrieve the number of zeros-packets present in the list. But I need to populate subarrays, as long as I encounter them through the list... maybe something with the <code>split</code> function? Thank you in advance.</p>
0
2016-08-01T16:07:13Z
38,703,599
<p>Well, <code>itertools</code> has the solution for you: <code>groupby(list, filter)</code>.</p> <p>If you want to group by zeroes, start with doing:</p> <pre><code>B = itertools.groupby(A, lambda x:x == 0) </code></pre> <p>The lambda expression "decides" which of the values should be a separator. You could separate by <code>None</code>s using <code>lambda x: x == None</code> (for example). That will return you an iterable object. So, using a list comprehension, let's iterate through it (every iteration gives us a 2 values tuple):</p> <pre><code>C = [(i, list(j)) for i, j in B] # j is cast to a list because it's originally an object, not a list. </code></pre> <p>Output will be something like:</p> <blockquote> <p><code>[(False, [18, 7]), (True, [0]), (True, [0]), (True, [0]), ... ]</code></p> </blockquote> <p>Now, every list <code>j</code> that is the separator has a value <code>True</code> for i. So we can filter it:</p> <pre><code>C = [list(j) for i, j in B if not i] </code></pre> <p>Now, the result is a 2d list:</p> <blockquote> <p><code>[[18, 7], [9, 12], [11, 2, 3, 3], [7, 8]]</code></p> </blockquote> <p>So a one liner function:</p> <pre><code>def splitArr(): return [list(j) for i, j in itertools.groupby(A, lambda x:x == 0) if not i] </code></pre>
3
2016-08-01T16:19:58Z
[ "python", "list", "zero", "sub-array" ]
select subarrays delimited by zeros in python
38,703,403
<p>Given a list like:</p> <pre><code>A = [18, 7, 0, 0, 0, 9, 12, 0, 0, 11, 2, 3, 3, 0, 0, 7, 8] </code></pre> <p>is there a simple way to create subarrays, with those elements that are separated by zeros (or at least by NaNs)? I mean, like:</p> <pre><code>A1 = [18, 7] A2 = [9, 12] A3 = [11, 2, 3, 3] A4 = [7, 8] </code></pre> <p>I've written:</p> <pre><code>q=0 for i in range(0,len(A)): if A[i]-A[i-1] &lt; 1: q=q+1 </code></pre> <p>to retrieve the number of zeros-packets present in the list. But I need to populate subarrays, as long as I encounter them through the list... maybe something with the <code>split</code> function? Thank you in advance.</p>
0
2016-08-01T16:07:13Z
38,703,705
<p>naive solution:</p> <pre><code>A = [18, 7, 0, 0, 0, 9, 12, 0, 0, 11, 2, 3, 3, 0, 0, 7, 8] b = [] c = [] for i in A: if i == 0: if len(c): b.append(c) c = [] continue c.append(i) if len(c): b.append(c) </code></pre>
0
2016-08-01T16:26:28Z
[ "python", "list", "zero", "sub-array" ]
Python - How to take input from command line and pipe it into socket.gethostbyaddr("")
38,703,423
<p>I have been scouring the internet looking for the answer to this. Please not my python coding skills are not all that great. I am trying to create a command line script that will take the input from the command line like this:</p> <pre><code>$python GetHostID.py serverName.com </code></pre> <p>the last part is what I am wanting to pass on as a variable to socket.gethostbyaddr("") module. this is the code that I have so far. can someone help me figure out how to put that variable into the (" "). I think the "" is creating problems with using a simple variable name as it is trying to treat it as a string of text as appose to a variable name. here is the code I have in my script:</p> <pre><code>#!/bin/python # import sys, os import optparse import socket remoteServer = input("Enter a remote host to scan: ") remoteServerIP = socket.gethostbyaddr(remoteServer) socket.gethostbyaddr('remoteServer')[0] os.getenv('remoteServer') print (remoteServerIP) </code></pre> <p>any help would be welcome. I have been racking my brain over this... thanks </p>
0
2016-08-01T16:08:22Z
38,703,748
<p>os.getenv('remoteserver') does not use the variable remoteserver as an argument. Instead it uses a string 'remoteserver'.</p> <p>Also, are you trying to take input as a command line argument? Or are you trying to take it as user input? Your problem description and implementation differ here. The easiest way would be to run your script using</p> <pre><code>python GetHostID.py </code></pre> <p>and then in your code include</p> <pre><code>remoteServer = raw_input().strip().split() </code></pre> <p>to get the input you want for remoteserver.</p>
0
2016-08-01T16:28:53Z
[ "python", "sockets", "input", "gethostbyaddr" ]
Python - How to take input from command line and pipe it into socket.gethostbyaddr("")
38,703,423
<p>I have been scouring the internet looking for the answer to this. Please not my python coding skills are not all that great. I am trying to create a command line script that will take the input from the command line like this:</p> <pre><code>$python GetHostID.py serverName.com </code></pre> <p>the last part is what I am wanting to pass on as a variable to socket.gethostbyaddr("") module. this is the code that I have so far. can someone help me figure out how to put that variable into the (" "). I think the "" is creating problems with using a simple variable name as it is trying to treat it as a string of text as appose to a variable name. here is the code I have in my script:</p> <pre><code>#!/bin/python # import sys, os import optparse import socket remoteServer = input("Enter a remote host to scan: ") remoteServerIP = socket.gethostbyaddr(remoteServer) socket.gethostbyaddr('remoteServer')[0] os.getenv('remoteServer') print (remoteServerIP) </code></pre> <p>any help would be welcome. I have been racking my brain over this... thanks </p>
0
2016-08-01T16:08:22Z
38,703,796
<p>you can use <a href="https://docs.python.org/3/library/sys.html#sys.argv" rel="nofollow">sys.argv</a> </p> <p>for</p> <pre><code>$python GetHostID.py serverName.com </code></pre> <p><code>sys.argv</code> would be </p> <pre><code>['GetHostID.py', 'serverName.com'] </code></pre> <p>but for being friendly to the user have a look at the <a href="https://docs.python.org/3/howto/argparse.html" rel="nofollow">argparse Tutorial</a></p>
0
2016-08-01T16:31:04Z
[ "python", "sockets", "input", "gethostbyaddr" ]
Python - How to take input from command line and pipe it into socket.gethostbyaddr("")
38,703,423
<p>I have been scouring the internet looking for the answer to this. Please not my python coding skills are not all that great. I am trying to create a command line script that will take the input from the command line like this:</p> <pre><code>$python GetHostID.py serverName.com </code></pre> <p>the last part is what I am wanting to pass on as a variable to socket.gethostbyaddr("") module. this is the code that I have so far. can someone help me figure out how to put that variable into the (" "). I think the "" is creating problems with using a simple variable name as it is trying to treat it as a string of text as appose to a variable name. here is the code I have in my script:</p> <pre><code>#!/bin/python # import sys, os import optparse import socket remoteServer = input("Enter a remote host to scan: ") remoteServerIP = socket.gethostbyaddr(remoteServer) socket.gethostbyaddr('remoteServer')[0] os.getenv('remoteServer') print (remoteServerIP) </code></pre> <p>any help would be welcome. I have been racking my brain over this... thanks </p>
0
2016-08-01T16:08:22Z
38,703,820
<p>The command line arguments are available as the list <code>sys.argv</code>, whose first element is the path to the program. There are a number of libraries you can use (argparse, optparse, etc.) to analyse the command line, but for your simple application you could do something like this:</p> <pre><code>import sys import sys, os import optparse import socket remoteServer = sys.argv[1] remoteServerIP = socket.gethostbyaddr(remoteServer) print (remoteServerIP) </code></pre> <p>Running this program with the command line</p> <pre><code>$ python GetHostID.py holdenweb.com </code></pre> <p>gives the output</p> <pre><code>('web105.webfaction.com', [], ['108.59.9.144']) </code></pre>
1
2016-08-01T16:32:10Z
[ "python", "sockets", "input", "gethostbyaddr" ]
Python - How to take input from command line and pipe it into socket.gethostbyaddr("")
38,703,423
<p>I have been scouring the internet looking for the answer to this. Please not my python coding skills are not all that great. I am trying to create a command line script that will take the input from the command line like this:</p> <pre><code>$python GetHostID.py serverName.com </code></pre> <p>the last part is what I am wanting to pass on as a variable to socket.gethostbyaddr("") module. this is the code that I have so far. can someone help me figure out how to put that variable into the (" "). I think the "" is creating problems with using a simple variable name as it is trying to treat it as a string of text as appose to a variable name. here is the code I have in my script:</p> <pre><code>#!/bin/python # import sys, os import optparse import socket remoteServer = input("Enter a remote host to scan: ") remoteServerIP = socket.gethostbyaddr(remoteServer) socket.gethostbyaddr('remoteServer')[0] os.getenv('remoteServer') print (remoteServerIP) </code></pre> <p>any help would be welcome. I have been racking my brain over this... thanks </p>
0
2016-08-01T16:08:22Z
38,704,199
<p>In Python 2, <code>input</code> reads text <em>and evaluates it as a Python expression in the current context</em>. This is almost never what you want; you want <code>raw_input</code> instead. However, in Python 3, <code>input</code> does what <code>raw_input</code> did in version 2, and <code>raw_input</code> is not available.</p> <p>So, if you need your code to work in <em>both</em> Python 2 and 3, you should do something like this after your imports block:</p> <pre><code># Apply Python 3 semantics to input() if running under v2. try: input = raw_input def raw_input(*a, **k): raise NameError('use input()') except NameError: pass </code></pre> <p>This has no effect in Python 3, but in v2 it replaces the stock <code>input</code> with <code>raw_input</code>, and <code>raw_input</code> with a function that always throws an exception (so you notice if you accidentally use <code>raw_input</code>).</p> <p>If you find yourself needing to smooth over <em>lots</em> of differences between v2 and v3, the <a href="http://python-future.org/" rel="nofollow">python-future</a> library will probably make your life easier.</p>
0
2016-08-01T16:54:33Z
[ "python", "sockets", "input", "gethostbyaddr" ]
How to search for discontinuous characters in Python list?
38,703,432
<p>I am trying to search a list (DB) for possible matches of fragments of text. For instance, I have a DB with text "evilman". I want to use user inputs to search for any possible matches in the DB and give the answer with a confidence. If the user inputs "hello", then there are no possible matches. If the user inputs "evil", then the possible match is evilman with a confidence of 57% (4 out of 7 alphabets match) and so on.</p> <p>However, I also want a way to match input text such as "evxxman". 5 out of 7 characters of evxxman match the text "evilman" in the DB. But a simple check in python will say no match since it only outputs text that matches consecutively. I hope it makes sense. Thanks</p> <p>Following is my code:</p> <pre><code>db = [] possible_signs = [] db.append("evilman") text = raw_input() for s in db: if text in s: if len(text) &gt;= len(s)/2: possible_signs.append(s) count += 1 confidence = (float(len(text)) / float(len(s))) * 100 print "Confidence:", '%.2f' %(confidence), "&lt;possible match:&gt;", possible_signs[0] </code></pre>
1
2016-08-01T16:09:15Z
38,703,607
<p>For finding matches with a quality-estimation, have a look at <a href="https://docs.python.org/3/library/difflib.html#difflib.SequenceMatcher.ratio" rel="nofollow">difflib.SequenceMatcher.ratio</a> and friends - these functions might not be the fastest match-checkers but they are easy to use.</p> <p>Example copied from difflib docs</p> <pre><code>&gt;&gt;&gt; s = SequenceMatcher(None, "abcd", "bcde") &gt;&gt;&gt; s.ratio() 0.75 &gt;&gt;&gt; s.quick_ratio() 0.75 &gt;&gt;&gt; s.real_quick_ratio() 1.0 </code></pre>
1
2016-08-01T16:20:19Z
[ "python" ]
How to search for discontinuous characters in Python list?
38,703,432
<p>I am trying to search a list (DB) for possible matches of fragments of text. For instance, I have a DB with text "evilman". I want to use user inputs to search for any possible matches in the DB and give the answer with a confidence. If the user inputs "hello", then there are no possible matches. If the user inputs "evil", then the possible match is evilman with a confidence of 57% (4 out of 7 alphabets match) and so on.</p> <p>However, I also want a way to match input text such as "evxxman". 5 out of 7 characters of evxxman match the text "evilman" in the DB. But a simple check in python will say no match since it only outputs text that matches consecutively. I hope it makes sense. Thanks</p> <p>Following is my code:</p> <pre><code>db = [] possible_signs = [] db.append("evilman") text = raw_input() for s in db: if text in s: if len(text) &gt;= len(s)/2: possible_signs.append(s) count += 1 confidence = (float(len(text)) / float(len(s))) * 100 print "Confidence:", '%.2f' %(confidence), "&lt;possible match:&gt;", possible_signs[0] </code></pre>
1
2016-08-01T16:09:15Z
38,703,618
<p>Based on your description and examples, it seems to me that you're actually looking for something like the <a href="https://en.wikipedia.org/wiki/Levenshtein_distance" rel="nofollow">Levenshtein (or edit) distance</a>. Note that it does not quite give the scores you specify, but I think it gives the scores you actually want.</p> <p>There are several packages implementing this efficiently, e.g., <a href="https://pypi.python.org/pypi/Distance/" rel="nofollow"><code>distance</code></a>:</p> <pre><code>In [1]: import distance In [2]: distance.levenshtein('evilman', 'hello') Out[2]: 6L In [3]: distance.levenshtein('evilman', 'evil') Out[3]: 3L In [4]: distance.levenshtein('evilman', 'evxxman') Out[4]: 2L </code></pre> <p>Note that the library contains several measures of similarity, e.g., jaccard and sorensen return a normalized value per default:</p> <pre><code>&gt;&gt;&gt; distance.sorensen("decide", "resize") 0.5555555555555556 &gt;&gt;&gt; distance.jaccard("decide", "resize") 0.7142857142857143 </code></pre>
1
2016-08-01T16:21:11Z
[ "python" ]
How to search for discontinuous characters in Python list?
38,703,432
<p>I am trying to search a list (DB) for possible matches of fragments of text. For instance, I have a DB with text "evilman". I want to use user inputs to search for any possible matches in the DB and give the answer with a confidence. If the user inputs "hello", then there are no possible matches. If the user inputs "evil", then the possible match is evilman with a confidence of 57% (4 out of 7 alphabets match) and so on.</p> <p>However, I also want a way to match input text such as "evxxman". 5 out of 7 characters of evxxman match the text "evilman" in the DB. But a simple check in python will say no match since it only outputs text that matches consecutively. I hope it makes sense. Thanks</p> <p>Following is my code:</p> <pre><code>db = [] possible_signs = [] db.append("evilman") text = raw_input() for s in db: if text in s: if len(text) &gt;= len(s)/2: possible_signs.append(s) count += 1 confidence = (float(len(text)) / float(len(s))) * 100 print "Confidence:", '%.2f' %(confidence), "&lt;possible match:&gt;", possible_signs[0] </code></pre>
1
2016-08-01T16:09:15Z
38,703,666
<p>Create a while loop and track two iterators, one for your key word ("evil") and one for your query word ("evilman"). Here is some pseudocode:</p> <pre><code>key = "evil" query = "evilman" key_iterator = 0 query_iterator = 0 confidence_score = 0 while( key_iterator &lt; key.length &amp;&amp; query_iterator &lt; query.length ) { if (key[key_iterator] == query[query_iterator]) { confidence_score++ key_iterator++ } query_iterator++ } // If we didnt reach the end of the key if (key_iterator != key.length) { confidence_score = 0 } print ("Confidence: " + confidence_score + " out of " + query.length) </code></pre>
1
2016-08-01T16:23:56Z
[ "python" ]
How to search for discontinuous characters in Python list?
38,703,432
<p>I am trying to search a list (DB) for possible matches of fragments of text. For instance, I have a DB with text "evilman". I want to use user inputs to search for any possible matches in the DB and give the answer with a confidence. If the user inputs "hello", then there are no possible matches. If the user inputs "evil", then the possible match is evilman with a confidence of 57% (4 out of 7 alphabets match) and so on.</p> <p>However, I also want a way to match input text such as "evxxman". 5 out of 7 characters of evxxman match the text "evilman" in the DB. But a simple check in python will say no match since it only outputs text that matches consecutively. I hope it makes sense. Thanks</p> <p>Following is my code:</p> <pre><code>db = [] possible_signs = [] db.append("evilman") text = raw_input() for s in db: if text in s: if len(text) &gt;= len(s)/2: possible_signs.append(s) count += 1 confidence = (float(len(text)) / float(len(s))) * 100 print "Confidence:", '%.2f' %(confidence), "&lt;possible match:&gt;", possible_signs[0] </code></pre>
1
2016-08-01T16:09:15Z
38,715,829
<p>This first version seems to comply with your exemples. It make the strings "slide" against each other, and count the number of identical characters. The ratio is made by dividing the character count by the reference string length. Add a max and voila. Call it for each string in your DB.</p> <pre><code>def commonChars(txt, ref): txtLen = len(txt) refLen = len(ref) r = 0 for i in range(refLen + (txtLen - 1)): rStart = abs(min(0, txtLen - i - 1)) tStart = txtLen -i - 1 if i &lt; txtLen else 0 l = min(txtLen - tStart, refLen - rStart) c = 0 for j in range(l): if txt[tStart + j] == ref[rStart + j]: c += 1 r = max(r, c / refLen) return r print(commonChars('evxxman', 'evilman')) # 0.7142857142857143 print(commonChars('evil', 'evilman')) # 0.5714285714285714 print(commonChars('man', 'evilman')) # 0.42857142857142855 print(commonChars('batman', 'evilman')) # 0.42857142857142855 print(commonChars('batman', 'man')) # 1.0 </code></pre> <p>This second version produces the same results, but using the difflib mentioned in other answers. It computes matching blocks, sum their lengths, and computes the ratio against the reference length.</p> <pre><code>import difflib def commonBlocks(txt, ref): matcher = difflib.SequenceMatcher(a=txt, b=ref) matchingBlocks = matcher.get_matching_blocks() matchingCount = sum([b.size for b in matchingBlocks]) return matchingCount / len(ref) print(commonBlocks('evxxman', 'evilman')) # 0.7142857142857143 print(commonBlocks('evxxxxman', 'evilman')) # 0.7142857142857143 </code></pre> <p>As shown by the calls above, the behavior is slightly different. "holes" between matching blocks are ignored, and do not change the final ratio.</p>
1
2016-08-02T08:49:44Z
[ "python" ]
One time click and delete button state persistance
38,703,468
<p>Let's say I have the following scenario. I have a page full of posts. For each post I have a button that adds a point to the model's points variable through an ajax request. I want the user to click that button, add the point, delete the button from the DOM using jQuery and make that removal persistent throughout the session. So a refresh doesn't make the button reappear.</p> <p>My problem is the last part, making that button 'stay removed'. I know http is stateless and I've got to maintain the state somewhere so I've thought about adding a field in the database, using localstorage/localsession or django session. </p> <p>Which method would be the most appropriate ? Are there other ways? </p> <p>Thank you for your time and please tell me if I may have missed any similar question and I'll delete this one right away.</p>
0
2016-08-01T16:11:34Z
38,709,703
<p>Here is one option, though I don't claim it is the best!</p> <p>Using the javascript library simplestorage for cross browser compatibility: <a href="https://github.com/andris9/simpleStorage" rel="nofollow">https://github.com/andris9/simpleStorage</a></p> <p>Give each of your buttons a unique id and the same class, eg:</p> <pre><code>&lt;button id="points_123" class="add_points"&gt;Add Point&lt;/button&gt; </code></pre> <p>Then in your javascript: // make record of buttons clicked $(".add_points").on("click", function() {</p> <pre><code> simpleStorage.set(this.id, 1); }); // when loading page, hide buttons already clicked // (even to hide everything by default and then show ones not clicked) $(".add_points").each(function() { var clicked = simpleStorage.get(this.id); if (clicked &gt; 0) { $(this).hide(); } }); </code></pre> <p>Fiddle here: <a href="https://jsfiddle.net/phoebebright/73bv7b6r/" rel="nofollow">https://jsfiddle.net/phoebebright/73bv7b6r/</a></p>
0
2016-08-01T23:44:32Z
[ "jquery", "python", "ajax", "django" ]
Python PyQt and Psycopg2 with TableWidget
38,703,529
<p>Im trying to add data from a query to the table widget in pyqt but im having trouble getting it to put all the rows in. Right now my code only returns the first and third columns with data in them! Could really use some help in this! there are a total of 5 columns and 7055 rows</p> <p>My code:</p> <pre><code>import psycopg2 from PyQt4 import QtCore, QtGui def populate(self): con = psycopg2.connect("dbname=postgres user=username host=servername password=passowrd") cur = con.cursor() cur.execute("""SELECT * FROM doarni.bins_v2""") data = cur.fetchall() a = len(data) #rows b = len(data[0]) #columns self.ui.tableWidget.setSortingEnabled(True) self.ui.tableWidget.setRowCount(a) self.ui.tableWidget.setColumnCount(b) self.ui.tableWidget.setHorizontalHeaderLabels(['column1', 'column2', 'column3', 'column4', 'column5']) i = 1 #row j = 0 #column for j in range(a): for i in range(b): item = QtGui.QTableWidgetItem(data[j][i]) self.ui.tableWidget.setItem(j, i, item) self.ui.tableWidget.sortByColumn(0, QtCore.Qt.DescendingOrder) </code></pre>
0
2016-08-01T16:15:03Z
39,391,994
<p>try this code which also is configured to show Unicode strings:</p> <pre><code>rows = cur.fetchall() self.tableWidget.setRowCount(len(rows)) qs=QtCore.QString() r=0 for row in rows: r=r+1 col= 0 for itm in row: if type(itm)==type('a'): item = qs.fromUtf8(itm, size=-1) qs=QtCore.QString() else: item = str(itm) self.tableWidget.setItem(r, col, QtGui.QTableWidgetItem(item)) col = col+1 </code></pre>
-1
2016-09-08T13:15:29Z
[ "python", "pyqt", "psycopg2", "qtablewidget" ]
Unpacking Python's Type Annotations
38,703,556
<p>I'm trying to generate some JavaScript based on the type annotations I have provided in on some Python functions by using the <code>signature()</code> function in the <code>inspect</code> module.</p> <p>This part works as I expect when the type is a simple builtin class:</p> <pre><code>import inspect def my_function() -&gt; dict: pass signature = inspect.signature(my_function) signature.return_annotation is dict # True </code></pre> <p>Though I'm not sure how to unwrap and inspect more complex annotations e.g:</p> <pre><code>from typing import List import inspect def my_function() -&gt; List[int]: pass signature = inspect.signature(my_function) signature.return_annotation is List[int] # False </code></pre> <p>Again similar problem with forward referencing a custom class:</p> <pre><code>def my_function() -&gt; List['User']: pass ... signature.return_annotation # typing.List[_ForwardRef('User')] </code></pre> <p>What I'm looking to get out is something like this - so I can branch appropriately while generating the JavaScript:</p> <pre><code>type = signature.return_annotation... # list member_type = signature.return_annotation... # int / 'User' </code></pre> <p>Thanks. </p>
4
2016-08-01T16:16:42Z
38,846,882
<p><code>List</code> is not a map of types to <code>GenericMeta</code>, despite the syntax. Each access to it generates a new instance:</p> <pre><code>&gt;&gt;&gt; [ id(List[str]) for i in range(3) ] [33105112, 33106872, 33046936] </code></pre> <p>This means that even <code>List[int] is not List[int]</code>. To compare two instances, you have multiple options:</p> <ul> <li>Use <code>==</code>, i.e., <code>signature.return_annotation == List[int]</code>.</li> <li><p>Store an instance of your type in a global variable and check against that, i.e.,</p> <pre><code>a = List[int] def foo() -&gt; a: pass inspect.signature(foo).return_annotation is a </code></pre></li> <li><p>Use <code>issubclass</code>. The typing module defines that. Note that this might do more than you'd like, make sure to read the <code>_TypeAlias</code> documentation if you use this.</p></li> <li>Check against <code>List</code> only and read the contents yourself. Though the property is internal, it is unlikely that the implementation will change soon: <code>List[int].__args__[0]</code> contains the type argument starting from Python 3.5.2, and in earlier versions, its <code>List[int].__parameters__[0]</code>.</li> </ul> <p>If you'd like to write generic code for your exporter, then the last option is probably best. If you only need to cover a specific use case, I'd personally go with using <code>==</code>.</p>
1
2016-08-09T09:26:34Z
[ "python", "python-3.x", "annotations", "inspect", "type-hinting" ]
Unpacking Python's Type Annotations
38,703,556
<p>I'm trying to generate some JavaScript based on the type annotations I have provided in on some Python functions by using the <code>signature()</code> function in the <code>inspect</code> module.</p> <p>This part works as I expect when the type is a simple builtin class:</p> <pre><code>import inspect def my_function() -&gt; dict: pass signature = inspect.signature(my_function) signature.return_annotation is dict # True </code></pre> <p>Though I'm not sure how to unwrap and inspect more complex annotations e.g:</p> <pre><code>from typing import List import inspect def my_function() -&gt; List[int]: pass signature = inspect.signature(my_function) signature.return_annotation is List[int] # False </code></pre> <p>Again similar problem with forward referencing a custom class:</p> <pre><code>def my_function() -&gt; List['User']: pass ... signature.return_annotation # typing.List[_ForwardRef('User')] </code></pre> <p>What I'm looking to get out is something like this - so I can branch appropriately while generating the JavaScript:</p> <pre><code>type = signature.return_annotation... # list member_type = signature.return_annotation... # int / 'User' </code></pre> <p>Thanks. </p>
4
2016-08-01T16:16:42Z
38,847,250
<h3>Take note, this applies to Python 3.5.1</h3> <p><strong><em>For Python 3.5.2 take a look at phillip's answer.</em></strong></p> <p>You shouldn't be checking with the identity operator as Phillip stated, use equality to get this right.</p> <p>To check if a hint is a subclass of a <code>list</code> you could use <code>issubclass</code> checks (even though you should take note that this can be quirky in certain cases and is currently worked on):</p> <pre><code>issubclass(List[int], list) # True </code></pre> <p>To get the members of a type hint you generally have two watch out for the cases involved.</p> <p>If it has a simple type, as in <code>List[int]</code> the value of the argument is located in the <code>__parameters__</code> value:</p> <pre><code>signature.return_annotation.__parameters__[0] # int </code></pre> <p>Now, in more complex scenarios i.e a class supplied as an argument with <code>List[User]</code> you must again extract the <code>__parameter__[0]</code> and then get the <code>__forward_arg__</code>. This is because Python wraps the argument in a special <code>ForwardRef</code> class:</p> <pre><code>d = signature.return_annotation.__parameter__[0] d.__forward_arg__ # 'User' </code></pre> <p><em>Take note</em>, you don't need to actually use <code>inspect</code> here, <code>typing</code> has a helper function named <code>get_type_hints</code> that returns the type hints as a dictionary (it uses the function objects <code>__annotations__</code> attribute).</p>
1
2016-08-09T09:42:01Z
[ "python", "python-3.x", "annotations", "inspect", "type-hinting" ]
Matching Angles between Edges
38,703,572
<p>I'm scripting in python for starters. Making this example simple, I have one edge, with uv Coordinates of ([0,0],[1,1]), so its a 45 degree angle. I have another edge that is ([0,0],[0,1]) so its angle is 0/360 degrees. My goal is to compare the angles of those two edges in order to get the difference so I can modify the angle of the second edge to match the angle of the first edge. Is there a way to do this via vector math?</p>
-2
2016-08-01T16:17:58Z
38,725,287
<p>Easiest to reconstruct and thus constructively remember is IMO the complex picture. To compute the angle from <code>a=a.x+i*a.y</code> to <code>b=b.x+i*b.y</code> rotate <code>b</code> back by multiplying with the conjugate of <code>a</code> to get an angle from the zero angle resp. the positive real axis, </p> <pre><code>arg((a.x-i*a.y)*(b.x+i*b.y)) =arg((a.x*b.x+a.y*b.y)+i*(a.x*b.y-a.y*b.x)) =atan2( a.x*b.y-a.y*b.x , a.x*b.x+a.y*b.y ) </code></pre> <p>Note that screen coordinates use the opposite orientation to the Cartesian/complex plane, thus change use a sign switch as from <code>atan2(y,x)</code> to <code>atan2(-y,x)</code> to get an angle in the usual direction.</p> <hr> <p>To produce a vector <code>b</code> rotated angle (in radians) <code>w</code> from <code>a</code>, multiply by <code>cos(w)+i*sin(w)</code> to obtain</p> <pre><code>b.x = cos(w)*a.x - sin(w)*a.y b.y = cos(w)*a.y + sin(w)*a.x </code></pre> <p>You will have to rescale to get a specified length of <code>b</code>.</p>
0
2016-08-02T15:56:07Z
[ "python", "math", "vector" ]
If statement not continuing
38,703,608
<p>This code won't continue after it checks if the variable x is an integer or not. It gives out a ValueError, if x is not an int. How do I make the program ignore this error? I've tried to invert the statement like so:</p> <pre><code>elif x is isinstance(x, int): </code></pre> <p>but then, if I give it an integer, it immediately jumps to the else statement.</p> <pre><code>from tkinter import * root = Tk() root.wm_title("InOut") root.geometry('500x500') greetings = ["hello", "Hello", "greetings", "Greetings"] def out(event): x = ent.get() if x in greetings: lr.configure(text=x + ",\n is there\n anything\n I can do\n for you?") elif x is isinstance(x, int): if int(x) == 0: lr.configure(text="This is 0") elif int(x) % 2 == 0: lr.configure(text="This is a even number") elif int(x) % 2 != 0: lr.configure(text="This is an odd number") elif x is "": lr.configure(text="Well") else: print("Closing") root.destroy() ent = Entry(root) ent.grid(row=0, column=0, sticky=NW) lr = Label(root, text="Output") lr.grid(row=0, column=2, columnspan=2) btn = Button(root, text="Process") btn.grid(row=0, column=1, sticky=NW) btn.bind("&lt;Button-1&gt;", out) root.mainloop() </code></pre>
-3
2016-08-01T16:20:24Z
38,703,675
<p>isinstance() returns a boolean, so you don't need the extra x is. Go straight to</p> <pre><code>elif isinstance(x, int): </code></pre>
2
2016-08-01T16:24:23Z
[ "python", "python-3.x" ]
If statement not continuing
38,703,608
<p>This code won't continue after it checks if the variable x is an integer or not. It gives out a ValueError, if x is not an int. How do I make the program ignore this error? I've tried to invert the statement like so:</p> <pre><code>elif x is isinstance(x, int): </code></pre> <p>but then, if I give it an integer, it immediately jumps to the else statement.</p> <pre><code>from tkinter import * root = Tk() root.wm_title("InOut") root.geometry('500x500') greetings = ["hello", "Hello", "greetings", "Greetings"] def out(event): x = ent.get() if x in greetings: lr.configure(text=x + ",\n is there\n anything\n I can do\n for you?") elif x is isinstance(x, int): if int(x) == 0: lr.configure(text="This is 0") elif int(x) % 2 == 0: lr.configure(text="This is a even number") elif int(x) % 2 != 0: lr.configure(text="This is an odd number") elif x is "": lr.configure(text="Well") else: print("Closing") root.destroy() ent = Entry(root) ent.grid(row=0, column=0, sticky=NW) lr = Label(root, text="Output") lr.grid(row=0, column=2, columnspan=2) btn = Button(root, text="Process") btn.grid(row=0, column=1, sticky=NW) btn.bind("&lt;Button-1&gt;", out) root.mainloop() </code></pre>
-3
2016-08-01T16:20:24Z
38,703,687
<p>The following line is not doing what you think.</p> <pre><code>elif x is isinstance(x, int): </code></pre> <p><code>isinstance</code> is going to return <code>True</code>/<code>False</code> depending on the data type of <code>x</code>. So the statement <code>x is isinstance(x, int)</code> will return false always since it cannot be both an <code>int</code> and a <code>bool</code>.</p> <p>You just want:</p> <pre><code>elif isinstance(x, int): </code></pre>
3
2016-08-01T16:25:30Z
[ "python", "python-3.x" ]
If statement not continuing
38,703,608
<p>This code won't continue after it checks if the variable x is an integer or not. It gives out a ValueError, if x is not an int. How do I make the program ignore this error? I've tried to invert the statement like so:</p> <pre><code>elif x is isinstance(x, int): </code></pre> <p>but then, if I give it an integer, it immediately jumps to the else statement.</p> <pre><code>from tkinter import * root = Tk() root.wm_title("InOut") root.geometry('500x500') greetings = ["hello", "Hello", "greetings", "Greetings"] def out(event): x = ent.get() if x in greetings: lr.configure(text=x + ",\n is there\n anything\n I can do\n for you?") elif x is isinstance(x, int): if int(x) == 0: lr.configure(text="This is 0") elif int(x) % 2 == 0: lr.configure(text="This is a even number") elif int(x) % 2 != 0: lr.configure(text="This is an odd number") elif x is "": lr.configure(text="Well") else: print("Closing") root.destroy() ent = Entry(root) ent.grid(row=0, column=0, sticky=NW) lr = Label(root, text="Output") lr.grid(row=0, column=2, columnspan=2) btn = Button(root, text="Process") btn.grid(row=0, column=1, sticky=NW) btn.bind("&lt;Button-1&gt;", out) root.mainloop() </code></pre>
-3
2016-08-01T16:20:24Z
38,703,741
<p>I think you might be trying to see if a string is an integer. Instead of that if statement, I would just use a try/except block:</p> <pre><code>def is_int(x): try: x = int(x) return True except: return False </code></pre> <p>Put that in your code and use it instead of the call to isinstance. As it is now, even if x was an integer, right now you're asking if x is (True or False), which is always going to return False. But if x is a string that could be turned into an integer, then isinstance(x,int) is never going to return True even if x could be converted to an int.</p>
3
2016-08-01T16:28:35Z
[ "python", "python-3.x" ]
Google Drive API POST requests?
38,703,710
<p>I'm trying to interact with the Google Drive API and while their example is working, I'd like to learn how to make the POST requests in python instead of using their pre-written methods. For example, in python how would I make the post request to insert a file? <a href="https://developers.google.com/drive/v2/reference/files/insert" rel="nofollow">Insert a File</a></p> <p>How do I add requests and parameters to the body? </p> <p>Thanks!</p> <p>UPDATE 1: </p> <pre><code> headers = {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + 'my auth token'} datax = {'name': 'upload.xlsx', 'parents[]': ['0BymNvEruZwxmWDNKREF1cWhwczQ']} r = requests.post('https://www.googleapis.com/upload/drive/v3/files/', headers=headers, data=json.dumps(datax)) response = json.loads(r.text) fileID = response['id'] headers2 = {'Authorization': 'Bearer ' + 'my auth token'} r2 = requests.patch('https://www.googleapis.com/upload/drive/v3/files/' + fileID + '?uploadType=media', headers=headers2) </code></pre>
0
2016-08-01T16:26:46Z
38,750,241
<p>To insert a file:</p> <ol> <li>Create a file in Google drive and get its <em>Id</em> in response</li> <li>Insert a file using <em>Id</em></li> </ol> <p>Here are the POST parameters for both operations:</p> <pre><code>URL: 'https://www.googleapis.com/drive/v3/files' headers: 'Authorization Bearer &lt;Token&gt;' Content-Type: application/json body: { "name": "temp", "mimeType": "&lt;Mime type of file&gt;" } </code></pre> <p>In python you can use "Requests"</p> <pre><code>import requests import json headers = {'Content-Type': 'application/json','Authorization': 'Bearer &lt;Your Oauth token' } data = {'name': 'testing', 'mimeType': 'application/vnd.google-apps.document'} r = requests.post(url,headers=headers,data=json.dumps(data)) r.text </code></pre> <p>Above POST response will give you an id. To insert in file use <em>PATCH</em> request with following parameters</p> <pre><code>url: 'https://www.googleapis.com/upload/drive/v3/files/'&lt;ID of file created&gt; '?uploadType=media' headers: 'Authorization Bearer &lt;Token&gt;' Content-Type: &lt;Mime type of file created&gt; body: &lt;Your text input&gt; </code></pre> <p>I hope you can convert it in python requests.</p>
0
2016-08-03T17:33:29Z
[ "python", "google-drive-sdk", "http-post" ]
how do I place the pygame screen in the middle?
38,703,791
<p>I made a game using pygame which includes an init. In other ".py" file I created another init which I run from the main game. But, the second init opened on the [0,0] place of the main init, and I want to move it. the part that marked in a red frame at the photo, is the visual part from the second init.</p> <p>i'm using Python 2.7, thanks!!</p> <p><a href="http://i.stack.imgur.com/tQ3Rb.png" rel="nofollow"><img src="http://i.stack.imgur.com/tQ3Rb.png" alt=""></a></p>
-1
2016-08-01T16:30:48Z
38,704,594
<p>I belive what you are looking for is this: <code>os.environ['SDL_VIDEO_CENTERED'] = '1'</code>. Put the line before you call <code>pygame.init()</code>. The line of code tries to center your window the best it can. If you wan to position the window your self, you can use this line: <code>os.environ['SDL_VIDEO_WINDOW_POS'] = str(position[0]) + "," + str(position[1])</code> where you put the x value in the <code>0</code>'s place and the y value in the <code>1</code>'s place. For more info about pygame/SDL environment variables, see here: <a href="https://www.libsdl.org/release/SDL-1.2.15/docs/html/sdlenvvars.html" rel="nofollow">https://www.libsdl.org/release/SDL-1.2.15/docs/html/sdlenvvars.html</a>.</p> <p>~Mr.Python </p>
0
2016-08-01T17:18:28Z
[ "python", "python-2.7", "pygame" ]
Speedup GPU vs CPU for matrix operations
38,703,810
<p>I am wondering how much GPU computing would help me speed up my simulations.</p> <p>The critical part of my code is matrix multiplication. Basically the code looks like the following python code with matrices of order 1000 and long for loops.</p> <pre><code>import numpy as np Msize = 1000 simulationLength = 50 a = np.random.rand(Msize,Msize) b = np.random.rand(Msize,Msize) for j in range(simulationLength): result = np.dot(a,b) </code></pre> <p>Note: My matrices are dense, mostly random and for loops are compiled with cython.</p> <p>My naive guess would be that I have two factors:</p> <ul> <li>More parallel threads (Currently of order 1 thread, GPUs of order 100 threads?) --> Speedup of order 100? [<a href="http://gamedev.stackexchange.com/a/17255">Source</a> is quite outdated, from 2011]</li> <li>Lower processor frequency (Currently 3Ghz, GPUs typically 2 Ghz) --> Neglect</li> </ul> <p>I expect that this viewpoint is to naive, so what am I missing?</p>
3
2016-08-01T16:31:37Z
38,703,970
<p>Generally speaking GPUs are much faster than CPU at highly parallel simple tasks (that is what they are made for) like multiplying big matrices but there are some problems coming with GPU computation:</p> <ul> <li>transfering data between normal RAM and graphics RAM takes time</li> <li>loading/starting GPU programs takes some time</li> </ul> <p>so while multiplication itself may be 100 (or more) times faster, you might experience an actually much smaller speedup or even a slowdown</p> <p>There are more issues with GPUs being "stupid" in comparison to CPUs like massive slowdowns on branching code, having to handle caching by hand and others which can make writing fast programs for GPUs quite challenging.</p>
4
2016-08-01T16:41:15Z
[ "python", "gpu", "gpgpu", "matrix-multiplication" ]
Speedup GPU vs CPU for matrix operations
38,703,810
<p>I am wondering how much GPU computing would help me speed up my simulations.</p> <p>The critical part of my code is matrix multiplication. Basically the code looks like the following python code with matrices of order 1000 and long for loops.</p> <pre><code>import numpy as np Msize = 1000 simulationLength = 50 a = np.random.rand(Msize,Msize) b = np.random.rand(Msize,Msize) for j in range(simulationLength): result = np.dot(a,b) </code></pre> <p>Note: My matrices are dense, mostly random and for loops are compiled with cython.</p> <p>My naive guess would be that I have two factors:</p> <ul> <li>More parallel threads (Currently of order 1 thread, GPUs of order 100 threads?) --> Speedup of order 100? [<a href="http://gamedev.stackexchange.com/a/17255">Source</a> is quite outdated, from 2011]</li> <li>Lower processor frequency (Currently 3Ghz, GPUs typically 2 Ghz) --> Neglect</li> </ul> <p>I expect that this viewpoint is to naive, so what am I missing?</p>
3
2016-08-01T16:31:37Z
38,704,336
<h2>Matrix multiplication performance</h2> <p>If you use <code>numpy</code>, you are probably using one of the BLAS libraries as computational backend, such as ATLAS, OpenBLAS, MKL, etc. When you are using the fastest one MKL, you can find a recent performance benchmark here, between a recent Nvidia GPU K40m and Intel Xeon 12-core E5-2697 v2 @ 2.70GHz</p> <p><a href="https://developer.nvidia.com/cublas" rel="nofollow">https://developer.nvidia.com/cublas</a></p> <p>where K40m is 6x faster than 12-thread E5-2697. Considering MKL scales well on multi-core CPU. K40m is ~72x faster than 1-thread E5-2697. Please also note 1000-dim is almost the lower bound to fully utilise both the GPU and CPU. Smaller matrix size usually leads to more performance degrade on GPU.</p> <p>If you are using slower BLAS backend for <code>numpy</code>, say the GNU-licensed ATLAS. You could then find the comparison between MKL and ATLAS here</p> <p><a href="https://software.intel.com/en-us/intel-mkl/benchmarks#DGEMM-ATLAS" rel="nofollow">https://software.intel.com/en-us/intel-mkl/benchmarks#DGEMM-ATLAS</a></p> <p>where MKL is 2~4x faster than ATLAS.</p> <p>For Nvidia GPUs, the only widely used backend is CUDA's cuBLAS, so the performance won't change a lot like ATLAS vs. MKL.</p> <h2>Data transfer</h2> <p>As @janbrohl says, data transfer between host RAM and GPU device memory is an important factor that affect the overall performance. Here's a benchmark of the data transfer speed.</p> <p><a href="http://stackoverflow.com/questions/17729351/cuda-how-much-slower-is-transferring-over-pci-e/17745946#17745946">CUDA - how much slower is transferring over PCI-E?</a></p> <p>Given the matrix size, you can actually calculate out the absolute time for computation and data transfer, respectively. These could help you evaluate the performance better.</p> <p>To maximise the performance on GPU, you probably need re-design you program to minimise the data transfer, by moving all the computational operations to GPU, rather than matrix multiplication only. </p>
4
2016-08-01T17:02:30Z
[ "python", "gpu", "gpgpu", "matrix-multiplication" ]
Speedup GPU vs CPU for matrix operations
38,703,810
<p>I am wondering how much GPU computing would help me speed up my simulations.</p> <p>The critical part of my code is matrix multiplication. Basically the code looks like the following python code with matrices of order 1000 and long for loops.</p> <pre><code>import numpy as np Msize = 1000 simulationLength = 50 a = np.random.rand(Msize,Msize) b = np.random.rand(Msize,Msize) for j in range(simulationLength): result = np.dot(a,b) </code></pre> <p>Note: My matrices are dense, mostly random and for loops are compiled with cython.</p> <p>My naive guess would be that I have two factors:</p> <ul> <li>More parallel threads (Currently of order 1 thread, GPUs of order 100 threads?) --> Speedup of order 100? [<a href="http://gamedev.stackexchange.com/a/17255">Source</a> is quite outdated, from 2011]</li> <li>Lower processor frequency (Currently 3Ghz, GPUs typically 2 Ghz) --> Neglect</li> </ul> <p>I expect that this viewpoint is to naive, so what am I missing?</p>
3
2016-08-01T16:31:37Z
39,086,315
<p>Using opencl api, I tried 8k X 8k by 8k X 8k multiplication on a 1280-core HD7870(not even a mainstream desktop grade gpu) and it took about 0.99 seconds which means about 540 billion additions and 540 billion multiplications which also means 1.1 Tflops(%40 of its peak value said in its advertisements). High-end desktop grade CPUs have only 0.2 - 0.3 Tflops(peak value) excluding their integrated gpus. So best cpus cannot even reach a low-mid gpu in both performance and performance per watt and performance per dollar. </p> <p>Key options for performance:</p> <ul> <li><ol> <li>calculations in patches like 32x32 or 48x48 (for each compute unit having a group of threads so each thread computing a part of patch or sum of all patches of a column/row)</li> </ol></li> <li><ol start="2"> <li>doing exponentially faster ways like Strassen's algorithm.</li> </ol></li> <li><ol start="3"> <li>pipelining read,write and compute oprations so consecutive iterations stack gainfully.</li> </ol></li> <li><ol start="4"> <li>optimizing for hardware differencies</li> </ol></li> <li><ol start="5"> <li>using a library that has options from 1 to 4</li> </ol></li> </ul>
1
2016-08-22T18:26:04Z
[ "python", "gpu", "gpgpu", "matrix-multiplication" ]
Ordering of rows in Pandas to_sql
38,703,823
<p>I have a Pandas Dataframe which is ordered.</p> <pre><code> a0 b0 c0 d0 370025442 370020440 370020436 \ 1 31/08/2014 First Yorkshire 53 05:10 0 0.8333 1.2167 2 31/08/2014 First Yorkshire 53 07:10 0 0.85 1.15 3 31/08/2014 First Yorkshire 53 07:40 0 0.5167 0.7833 4 31/08/2014 First Yorkshire 53 08:10 0 0.7 1 5 31/08/2014 First Yorkshire 53 08:40 NaN NaN NaN 6 31/08/2014 First Yorkshire 53 09:00 0 0.5 0.7667 7 31/08/2014 First Yorkshire 53 09:20 0 0.5833 1 8 31/08/2014 First Yorkshire 53 09:40 0 0.4 0.7 9 31/08/2014 First Yorkshire 53 10:20 0 0.5333 1.0333 10 31/08/2014 First Yorkshire 53 10:40 0 0.4833 1 11 31/08/2014 First Yorkshire 53 11:00 0 0.3667 0.7 12 31/08/2014 First Yorkshire 53 11:20 0 0.5333 1.15 13 31/08/2014 First Yorkshire 53 11:40 0 0.3333 0.7667 14 31/08/2014 First Yorkshire 53 12:00 0 1.0167 1.5 15 31/08/2014 First Yorkshire 53 12:40 0 0.75 1.0333 .. ... ... .. ... ... ... ... 737 25/10/2014 First Yorkshire 53 21:40 0 1.0167 1.3 738 25/10/2014 First Yorkshire 53 22:40 0 0.5667 1 </code></pre> <p>However, when I convert this to SQL, the ordering is altered (row 13 onwards) and becomes:</p> <pre><code> a0 b0 c0 d0 370025442 370020440 370020436 \ 0 31/08/2014 First Yorkshire 53 05:10 0 0.8333 1.2167 1 31/08/2014 First Yorkshire 53 07:10 0 0.85 1.15 2 31/08/2014 First Yorkshire 53 07:40 0 0.5167 0.7833 3 31/08/2014 First Yorkshire 53 08:10 0 0.7 1 4 31/08/2014 First Yorkshire 53 08:40 None None None 5 31/08/2014 First Yorkshire 53 09:00 0 0.5 0.7667 6 31/08/2014 First Yorkshire 53 09:20 0 0.5833 1 7 31/08/2014 First Yorkshire 53 09:40 0 0.4 0.7 8 31/08/2014 First Yorkshire 53 10:20 0 0.5333 1.0333 9 31/08/2014 First Yorkshire 53 10:40 0 0.4833 1 10 31/08/2014 First Yorkshire 53 11:00 0 0.3667 0.7 11 31/08/2014 First Yorkshire 53 11:20 0 0.5333 1.15 12 31/08/2014 First Yorkshire 53 14:00 0 0.4833 1.0167 13 31/08/2014 First Yorkshire 53 16:20 0 0.6833 1.15 14 31/08/2014 First Yorkshire 53 23:10 None None None .. ... ... .. ... ... ... ... 736 25/10/2014 First Yorkshire 53 21:40 0 1.0167 1.3 737 25/10/2014 First Yorkshire 53 22:40 0 0.5667 1 </code></pre> <p>The data is correct, it's just the ordering of the rows which has been altered (this is confirmed looking at the SQL table from within SQL Server Management Studio). I checked the input table both before and after the operation and it remains unaltered, so the ordering issue must be when it is converted to SQL.</p> <p>The code used to create the SQL table is:</p> <pre><code>engine = sqlalchemy.create_engine("mssql+pyodbc://*server*?driver=SQL+Server+Native+Client+10.0?trusted_connection=yes") conn = engine.connect() art_array.to_sql(theartsql, engine, if_exists="replace", index=False) </code></pre> <p>(where the server is actually specified)</p> <p>What might be causing this and how might I resolve it? Any help would be really appreciated...</p> <p>edit: I should mention that the versions I am using are:</p> <p>Python version: <code>2.7.8</code></p> <p>Pandas version: <code>0.15.1</code></p> <p>SQLalchemy version: <code>1.0.12</code></p> <p>These are required to be maintained to be compatible with other software.</p>
2
2016-08-01T16:32:28Z
38,706,217
<p>That is <strong>Normal</strong>. <strong>Sql tables do not maintain row order</strong>. You need to "order by" to get the correct order. You could include a row id (or index) prior to moving data to SQL. So, then you can "order by" in Sql. </p> <p>Try something like this: </p> <pre><code>df a 0 1.00 1 2.00 2 0.67 3 1.34 print df.reset_index().to_sql(xxxx) index a 0 0 1.00 1 1 2.00 2 2 0.67 3 3 1.34 </code></pre> <p>Then in SQL, you can "order by" index.. "order by" syntax can vary depending on SQL database. </p> <pre><code>​ </code></pre>
1
2016-08-01T18:59:59Z
[ "python", "pandas" ]
Split a string on an integer
38,703,827
<p>I need to take a string 'list' as input and format it accordingly. Here is some example input:</p> <p><code>string = "This is the input:1. A list element;2. Another element;3. And another one."</code></p> <p>And I'd like the output to be a list in the following format:</p> <p><code>list " ["This is the input:", "A list element;", "Another element;", "And another one."]</code></p> <p>I have tried doing the following:</p> <p><code>list = string.split('(\d+). ')</code></p> <p>Hoping that it would split on all integers followed by a full stop and a space, but that doesn't seem to work: only a single element list is returned, indicating that none of the split criteria is found.</p> <p>Anyone see what I'm doing wrong?</p>
1
2016-08-01T16:32:51Z
38,703,914
<p>You can use the <a href="https://docs.python.org/2/library/re.html#re.split" rel="nofollow"><code>re.split()</code> method</a> splitting by <code>:</code> or <code>;</code> followed by one or more digits followed by a dot and a space:</p> <pre><code>&gt;&gt;&gt; re.split(r"[:;]\d+\.\s", s) ['This is the input', 'A list element', 'Another element', 'And another one.'] </code></pre> <p>To keep the <code>:</code> and <code>;</code> inside the splits, you can use a <a href="http://www.regular-expressions.info/lookaround.html" rel="nofollow">positive lookbehind check</a>:</p> <pre><code>&gt;&gt;&gt; re.split(r"(?&lt;=:|;)\d+\.\s", s) ['This is the input:', 'A list element;', 'Another element;', 'And another one.'] </code></pre>
2
2016-08-01T16:38:09Z
[ "python", "regex", "string", "list" ]
Using Google Forms to write to multiple tables?
38,703,892
<p>I am creating a web project where I take in Form data and write to a SQL database. The forms will be a questionnaire with logic branching. Due to the nature of the form, and the fact that this is an MVP project, I've opted to use an existing form service (e.g Google Forms/Typeform). </p> <p>I was wondering if it's feasible to have form data submitted to multiple different tables (e.g CustomerInfo, FormDataA, FormDataB, etc.). While this might be possible with a custom form application, I do not think it's possible with Google Forms and/or Typeform. </p> <p><strong>Does anyone have any suggestions on how to parse user submitted Form data into multiple tables when using Google Forms or Typeform?</strong></p>
0
2016-08-01T16:37:02Z
39,074,108
<p>You can add a script in the Google spreadsheet with an onsubmit trigger. Then you can do whatever you want with the submitted data.</p>
0
2016-08-22T07:59:06Z
[ "python", "sql", "google-form" ]
Modify a list in Multiprocessing pool's manager dict
38,703,907
<p>I have a list of elements which I am processing in a multiprocessing <code>apply_async</code> task and updating elements processed one by one with a key in manager dict on which I want to map whole list.</p> <p>I tried following code:</p> <pre><code>#!/usr/bin/python from multiprocessing import Pool, Manager def spammer_task(d, my_list): #Initialize manager dict d['task'] = { 'processed_list': [] } for ele in my_list: #process here d['task']['processed_list'].append(ele) return p = Pool() m = Manager() d = m.dict() my_list = ["one", "two", "three"] p.apply_async(spammer_task (d, my_list)) print d </code></pre> <p>At the end it simply posts empty list in dict. Output:</p> <blockquote> <p>{'task': {'processed_list': []}}</p> </blockquote> <p>Now after researching a bit, I got to know that elements inside manager dict become immutable so you have to re-initialize whole dict with new data in order to update it. SO i tried following code and it gives a weird error.</p> <pre><code>#!/usr/bin/python from multiprocessing import Pool, Manager def spammer_task(d, my_list): #Initialize manager dict d['task'] = { 'processed_list': [] } for ele in my_list: #process here old_list = d['task']['processed_list'] new_list = old_list.append(ele) #Have to do it this way since elements inside a manager dict become #immutable so d['task'] = { 'processed_list': new_list } return p = Pool() m = Manager() d = m.dict() my_list = ["one", "two", "three"] p.apply_async(spammer_task (d, my_list)) print d </code></pre> <p>Output:</p> <blockquote> <p>Traceback (most recent call last): File "./a.py", line 29, in p.apply_async(spammer_task (d, my_list)) File "./a.py", line 14, in spammer_task new_list = old_list.append(ele) AttributeError: 'NoneType' object has no attribute 'append'</p> </blockquote> <p>Somehow it seems to be appending <code>None</code> to the list which I cant figure out why.</p>
0
2016-08-01T16:37:55Z
38,705,319
<p>Accoridng to solution at <a href="https://bugs.python.org/issue6766" rel="nofollow">https://bugs.python.org/issue6766</a></p> <p>Following code fixes it, by copying whole task dict and then modifying it and recopying it</p> <pre><code>#!/usr/bin/python from multiprocessing import Pool, Manager def spammer_task(d, my_list): #Initialize manager dict d['task'] = { 'processed_list': [] } for ele in my_list: #process here foo = d['task'] foo['processed_list'].append(ele) d['task'] = foo return p = Pool() m = Manager() d = m.dict() my_list = ["one", "two", "three"] p.apply_async(spammer_task (d, my_list)) print d </code></pre> <p>Output:</p> <blockquote> <p>{'task': {'processed_list': ['one', 'two', 'three']}}</p> </blockquote>
0
2016-08-01T18:02:26Z
[ "python", "dictionary", "multiprocessing", "python-multiprocessing", "multiprocessing-manager" ]
Modify a list in Multiprocessing pool's manager dict
38,703,907
<p>I have a list of elements which I am processing in a multiprocessing <code>apply_async</code> task and updating elements processed one by one with a key in manager dict on which I want to map whole list.</p> <p>I tried following code:</p> <pre><code>#!/usr/bin/python from multiprocessing import Pool, Manager def spammer_task(d, my_list): #Initialize manager dict d['task'] = { 'processed_list': [] } for ele in my_list: #process here d['task']['processed_list'].append(ele) return p = Pool() m = Manager() d = m.dict() my_list = ["one", "two", "three"] p.apply_async(spammer_task (d, my_list)) print d </code></pre> <p>At the end it simply posts empty list in dict. Output:</p> <blockquote> <p>{'task': {'processed_list': []}}</p> </blockquote> <p>Now after researching a bit, I got to know that elements inside manager dict become immutable so you have to re-initialize whole dict with new data in order to update it. SO i tried following code and it gives a weird error.</p> <pre><code>#!/usr/bin/python from multiprocessing import Pool, Manager def spammer_task(d, my_list): #Initialize manager dict d['task'] = { 'processed_list': [] } for ele in my_list: #process here old_list = d['task']['processed_list'] new_list = old_list.append(ele) #Have to do it this way since elements inside a manager dict become #immutable so d['task'] = { 'processed_list': new_list } return p = Pool() m = Manager() d = m.dict() my_list = ["one", "two", "three"] p.apply_async(spammer_task (d, my_list)) print d </code></pre> <p>Output:</p> <blockquote> <p>Traceback (most recent call last): File "./a.py", line 29, in p.apply_async(spammer_task (d, my_list)) File "./a.py", line 14, in spammer_task new_list = old_list.append(ele) AttributeError: 'NoneType' object has no attribute 'append'</p> </blockquote> <p>Somehow it seems to be appending <code>None</code> to the list which I cant figure out why.</p>
0
2016-08-01T16:37:55Z
38,717,759
<p>Apart from making sure that <code>d</code> actually contains something when printed, the result is still <code>{'task': {'processed_list': ['one', 'two', 'three']}}</code></p> <pre><code>#!/usr/bin/python from multiprocessing import Pool def spammer_task(my_list): #Initialize manager dict out= { 'processed_list': [] } for ele in my_list: #process here out['processed_list'].append(ele) return 'task',out my_list = ["one", "two", "three"] if __name__=="__main__": p = Pool() d=dict(p.imap_unordered(spammer_task, [my_list])) #this line blocks until finished print d </code></pre>
0
2016-08-02T10:20:16Z
[ "python", "dictionary", "multiprocessing", "python-multiprocessing", "multiprocessing-manager" ]
What is the difference between Hypothesis Testing (Property Based Testing) and Mutation testing?
38,704,037
<p>My context for this question is in Python. </p> <p>Hypothesis Testing Library: <a href="https://hypothesis.readthedocs.io/en/latest/" rel="nofollow">https://hypothesis.readthedocs.io/en/latest/</a></p> <p>Mutation Testing Library: <a href="https://github.com/sixty-north/cosmic-ray" rel="nofollow">https://github.com/sixty-north/cosmic-ray</a></p>
1
2016-08-01T16:45:34Z
38,704,078
<p>These are very different beasts but both would <em>improve the value and quality of your tests</em>. Both tools contribute to and make the "My code coverage is N%" statement more meaningful. </p> <hr> <p><strong><a href="https://hypothesis.readthedocs.io/en/latest/" rel="nofollow">Hypothesis</a> would help you to generate all sorts of test inputs in the defined scope for a function under test.</strong> </p> <p>Usually, when you need to test a function, you provide multiple example values trying to cover all the use cases and edge cases driven by the code coverage reports - this is so called <em>"Example based testing"</em>. Hypothesis on the other hand implements a property-based testing generating a whole bunch of different inputs and input combinations helping to catch different common errors like division by zero, <code>None</code>, 0, off-by-one errors etc and helping to find hidden bugs. </p> <p><strong><a href="https://en.wikipedia.org/wiki/Mutation_testing" rel="nofollow">Mutation testing</a> is all about changing your code under test on the fly while executing your tests against a modified version of your code.</strong></p> <p>This really helps to see if your tests are actually testing what are they supposed to be testing, to understand the value of your tests. Mutation testing would really shine if you already have a rich test code base and a good code coverage.</p> <hr> <p>What helped me to get ahold of these concepts were these Python Podcasts:</p> <ul> <li><a href="https://talkpython.fm/episodes/show/67/property-based-testing-with-hypothesis" rel="nofollow">Property-based Testing with Hypothesis</a></li> <li><a href="https://talkpython.fm/episodes/show/63/validating-python-tests-with-mutation-testing" rel="nofollow">Validating Python tests with mutation testing</a></li> <li><a href="http://pythonpodcast.com/david-maciver-hypothesis.html" rel="nofollow">Hypothesis with David MacIver</a> </li> </ul>
2
2016-08-01T16:48:39Z
[ "python", "testing", "mutation-testing", "hypothesis-test", "property-based-testing" ]
Is there a better way of doing this?
38,704,044
<p>Is there another way of checking if something is first?</p> <p>I've been using <code>for i,f in enumerate(read_files)</code> where I enumerate a list of files, and use an if statement to check if i==0. I'm curious is there is a different (better, faster, less typed) way to do this?</p> <pre><code>read_files = glob.glob("post_stats_*.tsv") with open("result.tsv", "w") as outfile: for i,f in enumerate(read_files): with open(f, "r") as infile: metric_name = (f.strip(".tsv").split("_")[2]) if i == 0: outfile.write(metric_name.upper() + "\n" + infile.read()) else: outfile.write("\n" + metric_name.upper() + "\n" + infile.read()) </code></pre>
0
2016-08-01T16:45:58Z
38,704,124
<p>Since it seems the only use of the <code>if</code> is to avoid a blank line at the start of the output file, how about putting the blank line <em>after</em> the file's contents? That will lead to a blank line at the end of the file where it's unlikely to hurt:</p> <pre><code>read_files = glob.glob("post_stats_*.tsv") with open("result.tsv", "w") as outfile: for f in read_files: with open(f, "r") as infile: metric_name = (f.strip(".tsv").split("_")[2]) outfile.write(metric_name.upper() + "\n" + infile.read() + "\n") </code></pre>
3
2016-08-01T16:50:46Z
[ "python", "enumerate" ]
Why does the code work for all the images, except for the first one?
38,704,093
<p>I'm working on a memory game. I want to display images of cards in two rows. All cards are displayed correctly, except for the 1st one in the second row. running this code requires using CodeSkulptor. The entire program is here: <a href="http://www.codeskulptor.org/#user41_a22429Vx58_2.py" rel="nofollow">http://www.codeskulptor.org/#user41_a22429Vx58_2.py</a></p> <pre><code>def draw(canvas): global deck, cards, WIDTH, HEIGHT num_start = 10 w = 67 h = 100 center_source = [w // 2, h // 2] center_dest = [w // 2, h // 2] for c in deck: for card in cards: if card == c: if center_dest[0] &lt;= WIDTH: canvas.draw_image(cards[card], (center_source), (w , h), (center_dest), (w, h)) center_dest[0] += w + 2 elif center_dest[0] &gt; WIDTH: center_dest = [w // 2, h // 2 + h] canvas.draw_image(cards[card], (center_source), (w , h), (center_dest), (w, h *2)) center_dest[0] += w + 2 </code></pre>
0
2016-08-01T16:49:32Z
38,705,101
<p>Your elif condition only triggers 1 time when <code>center_dest</code> needs to reset its horizontal position. This is when <code>canvas.draw_image(cards[card], (center_source), (w , h), (center_dest), (w, h *2))</code> gets called where the <code>h * 2</code> causes the improper draw.</p> <p>If you remove the <code>*2</code> it will work. You could also restructure the logic as follows so you are not duplicating the draw:</p> <pre><code>if center_dest[0] &gt; WIDTH: center_dest = [w // 2, h // 2 + h] canvas.draw_image(cards[card], (center_source), (w , h), (center_dest), (w, h)) center_dest[0] += w + 2 </code></pre> <p>To make it extensible to an arbitrary number of rows change the update to:</p> <pre><code>if center_dest[0] &gt; WIDTH: center_dest[0] = w // 2 center_dest[1] += h </code></pre>
1
2016-08-01T17:48:24Z
[ "python", "list", "python-2.7" ]
How to Sort Two Columns by Descending Order in Pandas?
38,704,153
<p>I have this dataframe <code>df</code> consisting of two columns <code>ID</code> and <code>Date</code>:</p> <pre><code>ID Date 4 1/1/2008 3 1/1/2007 2 9/23/2010 2 6/3/1998 2 1/1/2001 # Note this date should be before "6/3/1998" for ID# 2 1 4/30/2003 </code></pre> <p>I want to sort <code>df</code> by <code>ID</code> and <code>Date</code> in descending order (largest --> smallest), but this seems not working when I tried the following script:</p> <pre><code>print df.sort_values(by=["ID", "Date"], ascending=["False", "False"]) </code></pre> <p>The output should in this descending order:</p> <pre><code>ID Date 4 1/1/2008 3 1/1/2007 2 9/23/2010 2 1/1/2001 2 6/3/1998 1 4/30/2003 </code></pre> <p>Any idea how can I sort the date in the correct descending order?</p>
0
2016-08-01T16:52:16Z
38,704,661
<p>You will first need to convert type of Date column from String to Date.</p> <pre><code>df['Date'] = pd.to_datetime(df['Date'], format="%m/%d/%Y") </code></pre> <p>Now you can use <strong>df.sort_values</strong></p> <pre><code>print df.sort_values(by=["ID", "Date"], ascending=[False, False]) </code></pre> <p><strong>Output :</strong> </p> <pre><code> ID Date 0 4 2008-01-01 1 3 2007-01-01 2 2 2010-09-23 4 2 2001-01-01 3 2 1998-06-03 5 1 2003-04-30 </code></pre> <p>In your code, for ascending argument you are passing string <code>"False"</code> , but it should be bool <code>False</code></p>
1
2016-08-01T17:22:29Z
[ "python", "sorting", "pandas", "dataframe" ]
How do I list hosts using Ansible 1.x API
38,704,173
<p>Ansible-playbook has a <code>--list-hosts</code> cli switch that just outputs the hosts affected by each play in a playbook. I am looking for a way to access to same information through the python API.</p> <p>The (very) basic script I am using to test right now is</p> <pre><code>#!/usr/bin/python import ansible.runner import ansible.playbook import ansible.inventory from ansible import callbacks from ansible import utils import json # hosts list hosts = ["127.0.0.1"] # set up the inventory, if no group is defined then 'all' group is used by default example_inventory = ansible.inventory.Inventory(hosts) pm = ansible.runner.Runner( module_name = 'command', module_args = 'uname -a', timeout = 5, inventory = example_inventory, subset = 'all' # name of the hosts group ) out = pm.run() print json.dumps(out, sort_keys=True, indent=4, separators=(',', ': ')) </code></pre> <p>I just can't figure out what to add to <code>ansible.runner.Runner()</code> to make it output affected hosts and exit.</p>
0
2016-08-01T16:53:21Z
38,704,480
<p>I'm not sure what are you trying to achieve, but <code>ansible.runner.Runner</code> is actually one task and not playbook.<br> Your script is a more kind of <a href="https://github.com/ansible/ansible/blob/v1.9.6-1/bin/ansible" rel="nofollow">ansible</a> CLI and not <a href="https://github.com/ansible/ansible/blob/v1.9.6-1/bin/ansible-playbook" rel="nofollow">ansible-playbook</a>.<br> And <code>ansible</code> doesn't have any kind of <code>--list-hosts</code>, while <code>ansible-playbook</code> does.<br> You can see how listhosts is done <a href="https://github.com/ansible/ansible/blob/v1.9.6-1/bin/ansible-playbook#L217" rel="nofollow">here</a>.</p>
0
2016-08-01T17:12:03Z
[ "python", "ansible" ]
How to sum integers stored in json
38,704,289
<p>How can I sum the count values? My json data is as following.</p> <pre><code>{ "note":"This file contains the sample data for testing", "comments":[ { "name":"Romina", "count":97 }, { "name":"Laurie", "count":97 }, { "name":"Bayli", "count":90 } ] } </code></pre>
-3
2016-08-01T16:59:43Z
38,704,373
<p>If the JSON is currently a string and not been loaded into a python object you'll need to:</p> <pre><code>import json loaded_json = json.loads(json_string) comments = loaded_json['comments'] sum(c['count'] for c in comments) </code></pre>
-1
2016-08-01T17:05:15Z
[ "python", "json" ]
How to sum integers stored in json
38,704,289
<p>How can I sum the count values? My json data is as following.</p> <pre><code>{ "note":"This file contains the sample data for testing", "comments":[ { "name":"Romina", "count":97 }, { "name":"Laurie", "count":97 }, { "name":"Bayli", "count":90 } ] } </code></pre>
-3
2016-08-01T16:59:43Z
38,713,316
<p>This is how i did it eventually. </p> <pre><code>import urllib import json mysumcnt = 0 input = urllib.urlopen('url').read() info = json.loads(input) myinfo = info['comments'] for item in myinfo: mycnt = item['count'] mysumcnt += mycnt print mysumcnt </code></pre>
1
2016-08-02T06:38:21Z
[ "python", "json" ]
Working out dependent groups
38,704,332
<p>Using the following function I can generate some test data.</p> <pre><code>import random, string a = list(string.ascii_lowercase) def gen_test_data(): s = [] for i in xrange(15): p = random.randint(1,3) xs = [random.choice(a) for i in xrange(p)] s.append(xs) return s </code></pre> <p>This is my test data.</p> <pre><code>[ ['a', 's'], ['f', 'c'], ['w', 'z'], ['z', 'p'], ['z', 'u', 'g'], ['v', 'q', 'w'], ['y', 'w'], ['d', 'x', 'i'], ['l', 'f', 's'], ['z', 'g'], ['h', 'x', 'k'], ['b'], ['t'], ['s', 'd', 'c'], ['s', 'w', 'd'] ] </code></pre> <p>If a letter shares the list with another letter it is dependent on that letter, and any of that letters other dependencies. For example</p> <p><code>x</code> is dependant on <code>['a','c','d','g','f','i','h','k','l','q','p','s','u','w','v','y', 'x','z']</code></p> <p>These dependencies are also two way. <code>k</code> is dependent on everything including <code>x</code></p> <p>but <code>x</code> is not dependant on <code>b</code> or <code>t</code>. These can be placed in separate groups.</p> <p>I need to divide the list into as MANY non dependant groups as possible.</p> <p>Each group will be a set of all letters that the group depends on. Non dependent letters will be a set of one.</p> <p>An example output to the one above is</p> <pre><code>[ ['t'], ['b'], ['a','c','d','g','f','i','h','k','l','q','p','s','u','w','v','y', 'x','z'] ] </code></pre> <p>I am trying to write a function to do this but can't figure out the right way to group everything correctly.</p>
2
2016-08-01T17:02:04Z
38,704,505
<p>This is a classic <a href="https://en.wikipedia.org/wiki/Connected_component_(graph_theory)" rel="nofollow">connected components</a> problem. There are a number of efficient linear-time or nearly-linear-time algorithms to solve it, such as with a graph search algorithm like depth-first search or with a union-find data structure.</p> <hr> <p>For a search-based algorithm, you would set up a graph based on your input, with nodes in the input sublists connected, then run a search of the graph to find which nodes are reachable from each other. Graph libraries like <a href="https://networkx.github.io/" rel="nofollow">NetworkX</a> can handle most of the implementation for you, or you could write it yourself. For example,</p> <pre><code>import collections def build_graph(data): graph = collections.defaultdict(list) for sublist in data: # It's enough to connect each sublist element to the first element. # No need to connect each sublist element to each other sublist element. for item in sublist[1:]: graph[sublist[0]].append(item) graph[item].append(sublist[0]) if len(sublist) == 1: # Make sure we add nodes even if they don't have edges. graph.setdefault(sublist[0], []) return graph def dfs_connected_component(graph, node): frontier = [node] visited = set() while frontier: frontier_node = frontier.pop() if frontier_node in visited: continue visited.add(frontier_node) frontier.extend(graph[frontier_node]) return visited def dependent_groups(data): graph = build_graph(data) components = [] nodes_with_component_known = set() for node in graph: if node in nodes_with_component_known: continue component = dfs_connected_component(graph, node) components.append(component) nodes_with_component_known.update(component) return components </code></pre> <p>This would have runtime linear in the size of the input.</p> <hr> <p>You could also use a <a href="https://en.wikipedia.org/wiki/Disjoint-set_data_structure" rel="nofollow">union-find data structure</a>. A union-find data structure associates items with sets, each set represented by a representative element. They support two operations: <em>find</em>, which finds the representative for an element, and <em>union</em>, which takes two elements and joins their sets into one set.</p> <p>You can set up a union-find data structure, and for each sublist in your input, union each element of the sublist with the first element of the sublist. This will efficiently group all dependent elements without joining any independent elements together.</p> <p>With the standard implementation of a union-find data structure as a disjoint-set forest with union by rank and path compression, the runtime would be essentially linear in the size of the input. It'd be slower by a factor of the <a href="https://en.wikipedia.org/wiki/Ackermann_function#Inverse" rel="nofollow">inverse Ackermann function</a> of the input, which is essentially constant for all practical input sizes.</p>
1
2016-08-01T17:13:48Z
[ "python", "set" ]
Working out dependent groups
38,704,332
<p>Using the following function I can generate some test data.</p> <pre><code>import random, string a = list(string.ascii_lowercase) def gen_test_data(): s = [] for i in xrange(15): p = random.randint(1,3) xs = [random.choice(a) for i in xrange(p)] s.append(xs) return s </code></pre> <p>This is my test data.</p> <pre><code>[ ['a', 's'], ['f', 'c'], ['w', 'z'], ['z', 'p'], ['z', 'u', 'g'], ['v', 'q', 'w'], ['y', 'w'], ['d', 'x', 'i'], ['l', 'f', 's'], ['z', 'g'], ['h', 'x', 'k'], ['b'], ['t'], ['s', 'd', 'c'], ['s', 'w', 'd'] ] </code></pre> <p>If a letter shares the list with another letter it is dependent on that letter, and any of that letters other dependencies. For example</p> <p><code>x</code> is dependant on <code>['a','c','d','g','f','i','h','k','l','q','p','s','u','w','v','y', 'x','z']</code></p> <p>These dependencies are also two way. <code>k</code> is dependent on everything including <code>x</code></p> <p>but <code>x</code> is not dependant on <code>b</code> or <code>t</code>. These can be placed in separate groups.</p> <p>I need to divide the list into as MANY non dependant groups as possible.</p> <p>Each group will be a set of all letters that the group depends on. Non dependent letters will be a set of one.</p> <p>An example output to the one above is</p> <pre><code>[ ['t'], ['b'], ['a','c','d','g','f','i','h','k','l','q','p','s','u','w','v','y', 'x','z'] ] </code></pre> <p>I am trying to write a function to do this but can't figure out the right way to group everything correctly.</p>
2
2016-08-01T17:02:04Z
38,704,669
<p>This simple algorithm merges groups until there are no more merges possible.</p> <pre><code>def grouper(a): d = {tuple(t): set(t) for t in a} while True: for tuple_, set1 in d.items(): try: match = next(k for k, set2 in d.iteritems() if k != tuple_ and set1 &amp; set2) except StopIteration: # no match for this key - keep looking continue else: d[tuple_] = set1 | d.pop(match) break else: # no match for any key - we are done! break output = sorted(tuple(s) for s in d.itervalues()) return output </code></pre>
1
2016-08-01T17:22:46Z
[ "python", "set" ]
Working out dependent groups
38,704,332
<p>Using the following function I can generate some test data.</p> <pre><code>import random, string a = list(string.ascii_lowercase) def gen_test_data(): s = [] for i in xrange(15): p = random.randint(1,3) xs = [random.choice(a) for i in xrange(p)] s.append(xs) return s </code></pre> <p>This is my test data.</p> <pre><code>[ ['a', 's'], ['f', 'c'], ['w', 'z'], ['z', 'p'], ['z', 'u', 'g'], ['v', 'q', 'w'], ['y', 'w'], ['d', 'x', 'i'], ['l', 'f', 's'], ['z', 'g'], ['h', 'x', 'k'], ['b'], ['t'], ['s', 'd', 'c'], ['s', 'w', 'd'] ] </code></pre> <p>If a letter shares the list with another letter it is dependent on that letter, and any of that letters other dependencies. For example</p> <p><code>x</code> is dependant on <code>['a','c','d','g','f','i','h','k','l','q','p','s','u','w','v','y', 'x','z']</code></p> <p>These dependencies are also two way. <code>k</code> is dependent on everything including <code>x</code></p> <p>but <code>x</code> is not dependant on <code>b</code> or <code>t</code>. These can be placed in separate groups.</p> <p>I need to divide the list into as MANY non dependant groups as possible.</p> <p>Each group will be a set of all letters that the group depends on. Non dependent letters will be a set of one.</p> <p>An example output to the one above is</p> <pre><code>[ ['t'], ['b'], ['a','c','d','g','f','i','h','k','l','q','p','s','u','w','v','y', 'x','z'] ] </code></pre> <p>I am trying to write a function to do this but can't figure out the right way to group everything correctly.</p>
2
2016-08-01T17:02:04Z
38,704,762
<p>Here is one way to do it (using a recursive algorithm):</p> <pre><code>lst = [ ['a', 's'], ['f', 'c'], ['w', 'z'], ['z', 'p'], ['z', 'u', 'g'], ['v', 'q', 'w'], ['y', 'w'], ['d', 'x', 'i'], ['l', 'f', 's'], ['z', 'g'], ['h', 'x', 'k'], ['b'], ['t'], ['s', 'd', 'c'], ['s', 'w', 'd'] ] def find_deps(letter, lst, already_done=set()): if letter in already_done: return already_done already_done = already_done.union(set([letter])) to_do = set() ## First scan the list to see what's there to process for sublist in lst: if letter in sublist: newset = set(x for x in sublist if x != letter) to_do = to_do.union(newset) ## Process first-dependents out = to_do.copy() for lll in to_do: out = out.union(find_deps(lll, lst, already_done=already_done)) return out.union(set([letter])) print find_deps('a', lst) # set(['a', 'c', 'd', 'g', 'f', 'i', 'h', 'k', 'l', 'q', 'p', 's', 'u', 'w', 'v', 'y', 'x', 'z']) print find_deps('b', lst) # set(['b']) print find_deps('t', lst) # set(['t']) </code></pre>
0
2016-08-01T17:27:37Z
[ "python", "set" ]
Uploading grayscale image Python
38,704,363
<p>I am trying to upload an image that has been converted to grayscale, like this:</p> <pre><code>blob_path = os.path.join(os.path.split(__file__)[0], 'static/img/blob-masks/1.png') blob = Image.open(blob_path).convert('L') buffer = StringIO() blob.save(buffer) upload_image(buffer.getvalue(),"foo.png") </code></pre> <p>But it just seem to upload a black square.</p> <p>If I got to the command line python and run:</p> <pre><code>col = Image.open("/static/img/blob-masks/5.png") col.convert('L') col.save("result_bw.png") </code></pre> <p><code>result_bw.png</code> is perfect. What is going wrong?</p>
0
2016-08-01T17:04:40Z
38,792,265
<p>Is there a reason you can't just upload the greyscale image after you convert it? Like:</p> <pre><code>image = Image.open('static/img/blob-masks/1.png') image.convert('L') image.save("temp/bw.png") upload_image("temp/bw.png") # maybe delete the temporary file when you're done import os os.remove("temp/bw.png") </code></pre> <p>I'm not sure how your upload_image() function works, but when I upload using django if I do any manipulations I write a temporary file and then re-import. If I don't manipulate the image at all I can just upload it directly.</p>
0
2016-08-05T14:56:38Z
[ "python", "image", "upload", "mask", "pillow" ]
os.fork exit the script if the child fails to run command
38,704,387
<p>I am a novice in python trying to use multi-process with fork. What I wanted to do is to run a command on few hosts. I am able to do with the below code but I also want to stop execution if any of the child fails to run the command or the command itself fails.</p> <pre><code>def runCommand(host,comp): if os.system("ssh "+host+" 'somecommand'") != 0: print "somecommand failed on "+host+" for "+comp sys.exit(-1) def runMulti(): children = [] for comp,host in conHosts.iteritems(): pid = os.fork() if pid: children.append(pid) else: sleep(5) runCommand(host,comp) os._exit(0) for i, child in enumerate(children): os.waitpid(child, 0) </code></pre>
0
2016-08-01T17:06:03Z
38,704,535
<p>You can just check the return value of <a href="https://docs.python.org/3.5/library/os.html#os.waitpid" rel="nofollow"><code>waitpid</code></a> and see if the child process exited with a status different from <code>0</code>:</p> <pre><code>had_error = any(os.waitpid(child, 0)[1] for child in children) if had_error: sys.exit(1) </code></pre> <hr> <p>Note: since you are checking the return value of <code>os.fork</code> the list <code>children</code> will be empty in the child processes and so <code>any</code> will always return <code>False</code>, i.e. only the master process will eventually call <code>sys.exit</code>.</p>
0
2016-08-01T17:15:27Z
[ "python" ]
os.fork exit the script if the child fails to run command
38,704,387
<p>I am a novice in python trying to use multi-process with fork. What I wanted to do is to run a command on few hosts. I am able to do with the below code but I also want to stop execution if any of the child fails to run the command or the command itself fails.</p> <pre><code>def runCommand(host,comp): if os.system("ssh "+host+" 'somecommand'") != 0: print "somecommand failed on "+host+" for "+comp sys.exit(-1) def runMulti(): children = [] for comp,host in conHosts.iteritems(): pid = os.fork() if pid: children.append(pid) else: sleep(5) runCommand(host,comp) os._exit(0) for i, child in enumerate(children): os.waitpid(child, 0) </code></pre>
0
2016-08-01T17:06:03Z
38,704,604
<p><code>os.fork()</code> returns <code>0</code> in the child process. So you can do:</p> <pre><code>if not os.fork(): # we now know we're the child process execute_the_work() if failed: sys.exit() </code></pre> <p><code>sys.exit()</code> is the pythonic way to exit a python program. Don't forget to <code>import sys</code>. </p> <p>Since you seem to be a beginner, replace <code>failed</code> with the condition to judge if the task failed.</p>
0
2016-08-01T17:19:14Z
[ "python" ]
os.fork exit the script if the child fails to run command
38,704,387
<p>I am a novice in python trying to use multi-process with fork. What I wanted to do is to run a command on few hosts. I am able to do with the below code but I also want to stop execution if any of the child fails to run the command or the command itself fails.</p> <pre><code>def runCommand(host,comp): if os.system("ssh "+host+" 'somecommand'") != 0: print "somecommand failed on "+host+" for "+comp sys.exit(-1) def runMulti(): children = [] for comp,host in conHosts.iteritems(): pid = os.fork() if pid: children.append(pid) else: sleep(5) runCommand(host,comp) os._exit(0) for i, child in enumerate(children): os.waitpid(child, 0) </code></pre>
0
2016-08-01T17:06:03Z
38,801,243
<p>I have achieved this by using ThreadPool.</p> <pre><code> pool = ThreadPool(len(hosts)) try: pool.map(runMulti(), 'True') pool.close() pool.join() except: os.system('touch /tmp/failed') commands.getoutput("killall -q ssh") os.kill(os.getpid(),9) </code></pre> <p>I have created a temp file, when a thread in the pool exists with different status.Thank you all :)</p>
0
2016-08-06T06:26:06Z
[ "python" ]
How to call variables from an imported parameter-dependent script?
38,704,390
<p>I've just begun to use python as a scripting language, but I'm having difficulty understanding how I should call objects from another file. This is probably just because I'm not too familiar on using attributes and methods.</p> <p>For example, I created this simple quadratic formula script.</p> <p>qf.py</p> <pre><code>#script solves equation of the form a*x^2 + b*x + c = 0 import math def quadratic_formula(a,b,c): sol1 = (-b - math.sqrt(b**2 - 4*a*c))/(2*a) sol2 = (-b + math.sqrt(b**2 - 4*a*c))/(2*a) return sol1, sol2 </code></pre> <p>So accessing this script in the python shell or from another file is fairly simple. I can get the script to output as a set if I import the function and call on it.</p> <pre><code>&gt;&gt;&gt; import qf &gt;&gt;&gt; qf.quadratic_formula(1,0,-4) (-2.0, 2.0) </code></pre> <p>But I cannot simply access variables from the imported function, e.g. the first member of the returned set.</p> <pre><code>&gt;&gt;&gt; print qf.sol1 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'module' object has no attribute 'sol1' </code></pre> <p>The same happens if I merge namespaces with the imported file</p> <pre><code>&gt;&gt;&gt; from qf import * &gt;&gt;&gt; quadratic_formula(1,0,-4) (-2.0, 2.0) &gt;&gt;&gt; print sol1 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'sol1' is not defined </code></pre> <p>Is there a better way call on these variables from the imported file? I think the fact that sol1 &amp; sol2 are dependent upon the given parameters (a,b,c) makes it more difficult to call them.</p>
0
2016-08-01T17:06:12Z
38,704,487
<p>I think it is because <code>sol1</code> and <code>sol2</code> are the local variables defined only in the function. What you can do is something like </p> <pre><code>import qf sol1,sol2 = qf.quadratic_formula(1,0,-4) # sol1 = -2.0 # sol2 = 2.0 </code></pre> <p>but this <code>sol1</code> and <code>sol2</code> are not the same variables in <code>qf.py</code>.</p>
1
2016-08-01T17:12:39Z
[ "python", "function", "import", "scripting", "python-import" ]
how to use multiple models in one view django?
38,704,461
<p>Actually guys, i don't know if thats correct, but someone told me that django is limitless, so...</p> <p><strong>in views.py</strong></p> <pre><code>class SelfieList(ListView): template_name = "SelfieList.html" model = Selfie, Outfit </code></pre> <p>Can that be posible?</p>
0
2016-08-01T17:10:34Z
38,704,633
<p>This is not possible. Listview accepts only one model and performs a <code>model.objects.all()</code> in <code>self.get_queryset()</code> method. One thing you can do is to inherit from <code>View</code> and then <code>pass querysets of multiple models as context data</code></p>
1
2016-08-01T17:20:44Z
[ "python", "django" ]
How to determine if a non-empty string exists in a dictionary?
38,704,520
<p>I often find myself checking dictionaries in python to see if a key is in the dictionary and if the key has useful information (in my case, a nonzero-length string). For instance, I seem to often need to check kwargs for data like this:</p> <pre><code>if ('partition' not in kwargs or kwargs['partition'] is None or kwargs['partition'] == ""): raise Exception("Need 'partition' for this method") </code></pre> <p>Is there a simpler, straightforward way to do this that I am missing?</p>
1
2016-08-01T17:14:00Z
38,704,657
<p>Use the dictionary object's <code>get()</code> method and let Python determine its <a href="https://en.wikipedia.org/wiki/Truthiness" rel="nofollow">truthiness</a> automatically:</p> <pre><code>if not d.get('partition'): raise Exception("Need 'partition' for this method") </code></pre>
1
2016-08-01T17:21:52Z
[ "python", "dictionary", "kwargs" ]
How to determine if a non-empty string exists in a dictionary?
38,704,520
<p>I often find myself checking dictionaries in python to see if a key is in the dictionary and if the key has useful information (in my case, a nonzero-length string). For instance, I seem to often need to check kwargs for data like this:</p> <pre><code>if ('partition' not in kwargs or kwargs['partition'] is None or kwargs['partition'] == ""): raise Exception("Need 'partition' for this method") </code></pre> <p>Is there a simpler, straightforward way to do this that I am missing?</p>
1
2016-08-01T17:14:00Z
38,704,734
<p>Which approach is Pythonic might depend on whether the dictionary contents are an internal or external interface. </p> <p>If you're writing a library, working with dictionary contents read from the command line or files, or something similar where you the programmer are not in charge of the contents, you'd want to do something like what you've written in the OP as good defensive programming practice. If this is a common enough idiom in your code, you may want to write a function that provides similar handling while generalizing over the specific key that you're looking for, such as:</p> <pre><code>def key_contains_contents(user_dict, key): return (key in user_dict) and user_dict[key] and len(user_dict[key]) &gt; 0 </code></pre> <p>Add additional clauses as necessary.</p> <p>If the contents of the dict are created by your program itself, you might as well come up with a standard way to express whether a key contains meaningful data and stick to that. The specific problem you're solving may suggest one way or another that makes the code creating the dict simpler. Absent any other constraints though, just not having the key set in the first place seems the simplest.</p>
1
2016-08-01T17:25:51Z
[ "python", "dictionary", "kwargs" ]
How to binarize the values in a pandas DataFrame?
38,704,545
<p>I have the following DataFrame:</p> <pre><code>df = pd.DataFrame(['Male','Female', 'Female', 'Unknown', 'Male'], columns = ['Gender']) </code></pre> <p>I want to convert this to a DataFrame with columns 'Male','Female' and 'Unknown' the values 0 and 1 indicated the Gender. </p> <pre><code>Gender Male Female Male 1 0 Female 0 1 . . . . </code></pre> <p>To do this, I wrote a function and called the function using map.</p> <pre><code>def isValue(x , value): if(x == value): return 1 else: return 0 for value in df['Gender'].unique(): df[str(value)] = df['Gender'].map( lambda x: isValue(str(x) , str(value))) </code></pre> <p>Which works perfectly. But is there a better way to do this? Is there an inbuilt function in any of sklearn package that I can use? </p>
4
2016-08-01T17:15:57Z
38,704,643
<p>Yes, there is a better way to do this. It's called <code>pd.get_dummies</code></p> <pre><code>pd.get_dummies(df) </code></pre> <p><a href="http://i.stack.imgur.com/kG6CP.png" rel="nofollow"><img src="http://i.stack.imgur.com/kG6CP.png" alt="enter image description here"></a></p> <p>To replicate what you have:</p> <pre><code>order = ['Gender', 'Male', 'Female', 'Unknown'] pd.concat([df, pd.get_dummies(df, '', '').astype(int)], axis=1)[order] </code></pre> <p><a href="http://i.stack.imgur.com/Addwl.png" rel="nofollow"><img src="http://i.stack.imgur.com/Addwl.png" alt="enter image description here"></a></p>
5
2016-08-01T17:21:08Z
[ "python", "pandas", "scikit-learn" ]
How to binarize the values in a pandas DataFrame?
38,704,545
<p>I have the following DataFrame:</p> <pre><code>df = pd.DataFrame(['Male','Female', 'Female', 'Unknown', 'Male'], columns = ['Gender']) </code></pre> <p>I want to convert this to a DataFrame with columns 'Male','Female' and 'Unknown' the values 0 and 1 indicated the Gender. </p> <pre><code>Gender Male Female Male 1 0 Female 0 1 . . . . </code></pre> <p>To do this, I wrote a function and called the function using map.</p> <pre><code>def isValue(x , value): if(x == value): return 1 else: return 0 for value in df['Gender'].unique(): df[str(value)] = df['Gender'].map( lambda x: isValue(str(x) , str(value))) </code></pre> <p>Which works perfectly. But is there a better way to do this? Is there an inbuilt function in any of sklearn package that I can use? </p>
4
2016-08-01T17:15:57Z
38,705,943
<p>My preference is <code>pd.get_dummies()</code>. Yes, there is sklearn method. </p> <p>From Docs: </p> <pre><code>&gt;&gt;&gt; from sklearn.preprocessing import OneHotEncoder &gt;&gt;&gt; enc = OneHotEncoder() &gt;&gt;&gt; enc.fit([[0, 0, 3], [1, 1, 0], [0, 2, 1], [1, 0, 2]]) OneHotEncoder(categorical_features='all', dtype=&lt;... 'float'&gt;, handle_unknown='error', n_values='auto', sparse=True) &gt;&gt;&gt; enc.n_values_ array([2, 3, 4]) &gt;&gt;&gt; enc.feature_indices_ array([0, 2, 5, 9]) &gt;&gt;&gt; enc.transform([[0, 1, 1]]).toarray() array([[ 1., 0., 0., 1., 0., 0., 1., 0., 0.]]) </code></pre> <p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html" rel="nofollow">http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html</a></p>
2
2016-08-01T18:43:56Z
[ "python", "pandas", "scikit-learn" ]
Running an action x times during t seconds uniformly
38,704,554
<p>I want to repeat a task several times during an interval of time and I want to do that in an uniform way so if I want to do the task 4 times in 1 second it should be executed at t = 0, 0.25, 0.5 and 0.75. </p> <p>So now I am doing:</p> <pre><code>import math import socket s = socket.socket(...) #not important time_step = 1./num_times_executed for _ in num_times_executed: now = time.time() s.sendto(...) #action i do time.sleep(max(0,time_step-(time.time()-now))) </code></pre> <p>However there is a lot of overhead, the bigger the loop is the more drift I get. For example with num_times_executed = 800, it takes 1.1 seconds so ~ 10% wrong...</p> <p>Is there a way to do that with a good precision ?</p>
2
2016-08-01T17:16:22Z
38,704,687
<pre><code>time_step = 1./num_times_executed start = time.time() for i in num_times_executed: s.sendto(...) #action i do next_send_time = start + (i+1) * time_step time.sleep(max(0,next_send_time - time.time())) </code></pre> <p>Now you're not going to get any drift because the time steps are firmly set values off of a start time. Previously the little calculations happening before setting now = time.time() would cause a tiny drift, but now so long as your time_step is long enough to execute the s.sendto(...) command, you shouldn't have any drift.</p>
2
2016-08-01T17:23:24Z
[ "python", "sockets", "time" ]
Anaconda As Python in Debian Linux Terminal
38,704,586
<p>I am working on a project in python on a Debian 8 VM. To work on the project further I need to install matplotlib 1.5.1. When I attempt to upgrade the current version (obtained through apt-get) or install I am told that I need freetype and png. When I go to install freetype using this link:</p> <p><a href="http://www.linuxfromscratch.org/blfs/view/svn/general/freetype2.html" rel="nofollow">http://www.linuxfromscratch.org/blfs/view/svn/general/freetype2.html</a></p> <p>After installing and entering the proper commands, I go to try to install matplotlib again and receive the same error.</p> <p>I tried to install Anaconda3 because it comes with freetype and basically every package that I need for my project. But after running the .sh file I was unable to change my python to use anaconda as the interpreter. How can I do this?</p> <p>Thanks!</p> <p>[UPDATE] I am having to go into my anaconda3 file, then run <code>source bin/activate ~/anaconda3/</code> Is there anyway to create an alias that would do all this?</p>
0
2016-08-01T17:18:01Z
38,705,016
<p>You have to first create a conda python environment:</p> <pre><code>/path/to/conda/bin/conda create --name myenv python=3 </code></pre> <p>(see <a href="http://conda.pydata.org/docs/using/envs.html" rel="nofollow">http://conda.pydata.org/docs/using/envs.html</a>)</p> <p>When the environment has been created you simply activate it as follows:</p> <pre><code>/path/to/conda/bin/source activate myenv </code></pre> <p>Thereafter the system will run python from the conda environment you specified and not from the standard location.</p>
0
2016-08-01T17:42:32Z
[ "python", "linux", "matplotlib", "anaconda" ]
Structuring an XHR request properly with Requests [python]
38,704,592
<p>I'm trying to do some web scraping of a site that generates it's data via Javascript. I've done enough reading on here to know by now that the way to scrape these is to:</p> <ol> <li>Watch the network tab in Firebug for what happens when you make the request</li> <li>Isolate the XHR requests and recreate them in a script.</li> </ol> <p>So, when I do 1, a POST request is sent to the link visible in this screenshot: <a href="http://i.stack.imgur.com/7unC4.png" rel="nofollow"><img src="http://i.stack.imgur.com/7unC4.png" alt="enter image description here"></a> and you can also see the response it gets. Looks great, right? </p> <p>But when I try and recreate that request &amp; response, with the payload that I see under the Post tab in Firebug, in Python like so:</p> <pre><code>import requests from bs4 import BeautifulSoup payload = {"Max":999,"RectCoord":"89,-179,-89,179","Source":"","SortField":"NEWID()","OfficeName":"","FirstName" :"","LastName":"da","CityName":"","ZipCode":"","Category":"S","SecLanguageReq":"","OfficeCode":""} r = requests.post('http://search.cnyrealtor.com/MyAjaxService.asmx/MemberSearch', data=payload) print(r.content) </code></pre> <p>I get a page that displays an error message: <code>Request format is unrecognized for URL unexpectedly ending in \'/MemberSearch\'</code></p> <p>So, my question is - why am I getting that response when the response in Firebug works fine? Am I missing something in my <code>requests.post(url)</code> line in the Python script?</p>
1
2016-08-01T17:18:13Z
38,704,977
<p>You need to dump the dictionary into JSON and send as a payload. It is important to set the <code>Content-Type</code> request header as well:</p> <pre><code>import json import requests payload = {"Max": 999, "RectCoord": "89,-179,-89,179", "Source": "", "SortField": "NEWID()", "OfficeName": "", "FirstName": "", "LastName": "", "CityName": "", "ZipCode": "", "Category": "S", "SecLanguageReq": "", "OfficeCode": ""} with requests.Session() as session: session.get("http://search.cnyrealtor.com/SiteContent/SYR/MemberSearchSYR.aspx") r = session.post('http://search.cnyrealtor.com/MyAjaxService.asmx/MemberSearch', data=json.dumps(payload), headers={"Content-Type": "application/json; charset=UTF-8"}) print(r.content) </code></pre>
1
2016-08-01T17:40:02Z
[ "javascript", "python" ]
Get kwargs passed to url_for in Flask view
38,704,629
<p>I am passing some kwargs to <code>url_for</code>, but <code>**kwargs</code> in the view function isn't getting them. How do I get the extra data?</p> <h3>File <code>admin.py</code></h3> <pre><code>@admin_bp.route('/alerts', methods=['GET']) def display_alerts(**kwargs): print kwargs alert_sorted = Alert.query.filter_by(**kwargs).all() </code></pre> <pre class="lang-html prettyprint-override"><code>index.html &lt;a href="{{ url_for('admin.display_alerts', {'user_id':val.user_id} )}}"&gt;Show User Alerts&lt;/a&gt; </code></pre> <h3>File <code>models.py</code></h3> <pre><code>class Alert(db.Model): __tablename__ = 'alert' __table_args__ = {'extend_existing': True} alert_id = db.Column(db.Integer, primary_key=True, autoincrement=True) user_id = db.Column(db.BigInteger, db.ForeignKey('users.user_id'), nullable=False) name = db.Column(db.String(ALERT_NAME_MAX_SIZE), nullable=False) </code></pre> <p>I cannot modify the function <code>display_alerts(**kwargs)</code> because it is used by a lot of other functions. My issue is to understand how to send <code>kwargs</code> arguments into the <code>url_for()</code> function in HTML.</p>
1
2016-08-01T17:20:40Z
38,704,913
<p>You're looking for <code>request.args</code>. Any unknown keywords arguments passed to <code>url_for</code> will be used to populate the query string. The query string is then exposed through <code>request.args</code>.</p> <pre><code>@admin_bp.route('/alerts') @admin_auth def display_alerts(): print(request.args) </code></pre>
1
2016-08-01T17:36:05Z
[ "python", "flask" ]
How to fix Numpy REFS_OK flag error?
38,704,648
<p>I have the following code:</p> <pre><code>import cv2 import numpy as np image = cv2.imread('pic1.png', cv2.IMREAD_GRAYSCALE) height = 0 count = 0 it = np.nditer(image) for(x) in it: count += 1 if count == 80: count = 0 height += 1 if x &gt; 400: print("Height is: " + height) break </code></pre> <p>When I try to run the code I get the following error message:</p> <pre><code>TypeError: Iterator operand or requested dtype holds references, but the REFS_OK flag was not enabled </code></pre> <p>Why do I get this error? When I tried looking it up it seems like people just work around it instead of fixing it.</p>
2
2016-08-01T17:21:20Z
38,704,896
<p>Check that the returned <code>image</code> variable isn't <code>None</code>. Perhaps the image is not in the path your script is run from. OpenCV doesn't raise an exception when it can't read/load the image, but, rather, returns <code>None</code>, in which case weird exceptions you will meet, when you try to operate on that <code>None</code>... like the exception posted.</p> <p>(Sorry for speaking like Yoda... :-) )</p>
0
2016-08-01T17:35:03Z
[ "python", "opencv", "numpy" ]
Save and restore window size and position when using HeaderBar
38,704,662
<p>In my application, I’d like to restore the position and sizes of my application windows after restart. Currently, I’m using <code>Gtk.Window.get_size()</code> and <code>Gtk.Window.get_position()</code> to obtain the size and position, and <code>Gtk.Window.resize()</code> and <code>Gtk.Window.move()</code> to restore them.</p> <p>This worked at first, but now, I’ve changed the application to use <code>Gtk.HeaderBar</code>, and neither position nor size are correct anymore.</p> <p>The documentation for <code>Gtk.Window.get_position()</code> <a href="http://lazka.github.io/pgi-docs/Gtk-3.0/classes/Window.html#Gtk.Window.get_position" rel="nofollow">states</a> that this is expected behavior. It says</p> <blockquote> <p>The correct mechanism is to support the session management protocol (see the “GnomeClient” object in the GNOME libraries for example) and allow the window manager to save your window sizes and positions.</p> </blockquote> <p>but I don‘t know how that works or how to implement it.</p> <p>So, how do I save and restore the window position and size when using <code>HeaderBar</code>? A portable solution would be best, but at least X11 and probably Wayland should be supportable.</p>
2
2016-08-01T17:22:32Z
38,718,875
<p>There have been various issues with <code>gtk_window_get_size()</code>, <code>gtk_window_set_size()</code> and client side decorations that have been recently fixed for GTK+ 3.20 — see <a href="https://developer.gnome.org/gtk3/unstable/ch32s10.html" rel="nofollow">the release notes for the 3.20 version</a>.</p> <p>Make sure you're using the latest stable version of GTK+ if you want to restore the size of the window, and that you never use the allocated size, but the size returned by <code>gtk_window_get_size()</code>. It's also important to note that you should not query the window's state during destruction, but whenever the state itself changes. See, for instance, the <a href="https://wiki.gnome.org/HowDoI/SaveWindowState" rel="nofollow">Saving window state page on the GNOME wiki</a>.</p> <p>As for the position: you should be aware that global coordinate systems are not available on Wayland (and Mir), and thus you cannot query the position of your window on the screen, nor set it manually on that windowing system.</p> <p>The GnomeClient API has long since been deprecated, and state saving as part of the session management does not really work. The documentation needs to be fixed.</p>
4
2016-08-02T11:13:22Z
[ "python", "gtk3" ]
Remove item from a list element?
38,704,705
<p>This may seem odd, but I am trying to remove a part of an item contained in a list. Basically, I am trying to remove a specific character from multiple list elements. For example</p> <pre><code>list = ['c1','c2','c3','d1','s1'] list.remove('c') </code></pre> <p>I know that doing that wouldn't work, but is there any way to remove the "c"s in the list, and only the "c"s in Python 3?</p>
1
2016-08-01T17:24:23Z
38,704,736
<pre><code>lst = [s.replace('c','') for s in lst] # ['1','2','3','d1','s1'] </code></pre> <p>List comprehensions are your friend. Also note the "list" is a keyword in Python, so I highly recommend you <em>do not</em> use it as a variable name.</p>
4
2016-08-01T17:25:56Z
[ "python", "list", "python-3.x" ]
Remove item from a list element?
38,704,705
<p>This may seem odd, but I am trying to remove a part of an item contained in a list. Basically, I am trying to remove a specific character from multiple list elements. For example</p> <pre><code>list = ['c1','c2','c3','d1','s1'] list.remove('c') </code></pre> <p>I know that doing that wouldn't work, but is there any way to remove the "c"s in the list, and only the "c"s in Python 3?</p>
1
2016-08-01T17:24:23Z
38,704,766
<p>Use list comprehensions,</p> <pre><code>list = ['c1','c2','c3','d1','s1'] list_ = [ x for x in list if "c" not in x ] # removes elements which has "c" print list_ # ['d1', 's1'] </code></pre>
2
2016-08-01T17:27:49Z
[ "python", "list", "python-3.x" ]
Remove item from a list element?
38,704,705
<p>This may seem odd, but I am trying to remove a part of an item contained in a list. Basically, I am trying to remove a specific character from multiple list elements. For example</p> <pre><code>list = ['c1','c2','c3','d1','s1'] list.remove('c') </code></pre> <p>I know that doing that wouldn't work, but is there any way to remove the "c"s in the list, and only the "c"s in Python 3?</p>
1
2016-08-01T17:24:23Z
38,705,022
<pre><code>list1 = ['c1','c2','c3','d1','d2'] list2 = [] for i in range (len(list1)): if 'c' not in list1[i]: list2.append(list1[i]) print (list2) #['d1', 'd2'] </code></pre> <p>and also this link may helpful </p> <p><a href="http://stackoverflow.com/questions/3416401/removing-elements-from-a-list-containing-specific-characters">Link one</a></p>
0
2016-08-01T17:42:59Z
[ "python", "list", "python-3.x" ]
Why does this code pass a parameter to a constructor when there is no __init__ method?
38,704,718
<p>So, I am reading some code online and I came across the following class definition and I'm a little confused;</p> <pre><code>class MyClass(OrderedDict): def __hash__(self): return hash(tuple(self.iteritems())) </code></pre> <p>Elsewhere in the code there is the following line;</p> <pre><code>MyClass(my_OD) </code></pre> <p>Where <code>my_OD</code> is an ordered dictionary. My question is, how can you pass an argument to this class when there is no <code>__init__</code> method? Where is this variable being assigned within the class? I'm coming from Java and I'm fairly certain that in Java you cannot pass an argument to a class without a constructor so this behavior is foreign to me. </p>
3
2016-08-01T17:25:05Z
38,704,796
<p>The class <code>MyClass</code> inherits from <code>OrderedDict</code>:</p> <pre><code>class MyClass(OrderedDict): </code></pre> <p>Since <code>MyClass</code> doesn't have an <code>__init__</code> method specified, it calls the init method of the OrderedDict class. So the <code>my_OD</code> argument to the constructor gets passed on to the OrderedDict. Btw, <code>__init__</code> is not technically the <em>constructor</em>.</p> <p>The purpose of this <code>MyClass</code> is to be an OrderedDict which computes the <code>hash</code> of its instances in a different way than OrderedDict does. Specifically, <code>OrderedDict</code> doesn't have a <code>__hash__</code>, that's defined on <code>dict</code>s and in that case, the hash is defined as <code>None</code> - so dicts are un-hashable. <code>MyClass</code> changes that adds a way to get the hash, while the rest of the functionality is the same <code>OrderedDict</code>s and <code>dict</code>s.</p>
6
2016-08-01T17:29:32Z
[ "python" ]
How to watch xvfb session that's inside a docker on remote server from my local browser?
38,704,735
<p>I'm running a docker (That I built on my own), that's docker running E2E tests. The browser is up and running but I want to have another nice to have feature, I want the ability of watching the session online.</p> <p>My <code>docker run</code> command is:</p> <pre><code>docker run -p 4444:4444 --name ${DOCKER_TAG_NAME} -e Some_ENVs -v Volume:Volume --privileged -d "{docker-registry}" &gt;&gt; /dev/null 2&gt;&amp;1 </code></pre> <p>I'm able to export screenshots but in some cases it's not enough and the ability of watching what is the exact state of the test would be amazing. I tried a lot of options but I came to a dead end, Any help would be great.</p> <ul> <li>My tests are in <code>Python 2.7</code></li> <li>My Docker base is <code>ubuntu:14.04</code></li> <li>My environment is in AWS (If that's matter)</li> <li><p>The docker run inside a server which run a our system's dockers (Part of them).</p></li> <li><p>I know it a duplicate of <a href="http://stackoverflow.com/questions/37567285/connect-to-a-vnc-inside-a-docker-which-is-on-remote-server">this</a> but no one answered him so...</p></li> </ul>
3
2016-08-01T17:25:54Z
38,724,743
<p>I have faced the same issue before with vnc, you need to know your xvfb/vnc in which port is using then open that port on you aws secuirty group once you done with that then you should be able to connect.</p> <p>On my case i was starting selenium docker "<a href="https://github.com/elgalu/docker-selenium" rel="nofollow">https://github.com/elgalu/docker-selenium</a>" and used this command to start the docker machine "docker run -d --name=grid -p 4444:24444 -p 5900:25900 \ -v /dev/shm:/dev/shm -e VNC_PASSWORD=hola \ -e SCREEN_WIDTH=1920 -e SCREEN_HEIGHT=1480 \ elgalu/selenium"</p> <p>The VNC port as per the command is "5900" so i opened that port on instance security group, and connected using VNC viewer on port 5900</p>
0
2016-08-02T15:31:22Z
[ "python", "selenium", "docker", "selenium-chromedriver", "xvfb" ]
How can I associate a specific dictionary key to an object in a list of classes?
38,704,774
<pre><code>class SpreadsheetRow(object): def __init__(self,Account1): self.Account1=Account1 self.Account2=0 </code></pre> <p>I have a while loop that fills a list of objects (called listofSpreadsheetRowObjects) ,and another loop that fills a dictionary associating Var1:Account2 (called dict_var1_to_account_2). But, I need to get that dictionary's value into each object, if the key matches the object's Account1.</p> <p>So basically, I have:</p> <pre><code>listofSpreadsheetRowObjects=[SpreadsheetRow1, SpreadsheetRow2, SpreadsheetRow3] dict_var1_to_account2={1234:888, 1991:646, 90802:5443} </code></pre> <p>I've tried this:</p> <pre><code>for k, v in dict_var1_to_account2.iteritems(): if k in listOfSpreadsheetRowObjects: if account1=k: account2=v </code></pre> <p>But, it's not working, and I suspect it's my first "if" statement, because listOfSpreadsheetRowObjects is just a list of those objects, I don't think it's actually talking to the attributes of those objects in that list. But, I've tried if any(k == item.account1 for item in listOfSpreadsheetRows): , and that doesn't seem to pull anything at all either. </p> <p>How would I access account1 of each object, so I can match them as needed?</p> <p>Eventually, I should have three objects with the following information: </p> <pre><code>SpreadsheetRow self.Account1=Account1 self.Account2=(v from my dictionary, if account1 matches the key in my dictionary) </code></pre>
0
2016-08-01T17:28:28Z
38,704,822
<p>It looks like it would be easier to iterate over the row objects first, and then for each one check if its <code>account1</code> is in the dict:</p> <pre><code>for row in listofSpreadsheetRowObjects: if row.Account1 in dict_var1_to_account2: row.Account2 = dict_var1_to_account2[row.Account1] </code></pre>
0
2016-08-01T17:30:56Z
[ "python", "dictionary" ]
Install Scrapy-Deltafetch: Can't find local Berkeley DB
38,704,883
<p>I'm trying to install scrapy-deltafetch in a virtual-environment (as described <a href="http://docs.python-guide.org/en/latest/dev/virtualenvs/" rel="nofollow">here</a>) on my new raspberry pi 3 with Raspbian. </p> <p>When I'm running <code>pip install scrapy-deltafetch</code> in my virtualenv, I'm getting something like this:</p> <blockquote> <p>python setup.py egg_info: Can't find a local Berkeley DB installation</p> <p>Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-ib6d93/bsddb3/</p> </blockquote> <p>However when I'm running <code>sudo pip install scrapy-deltafetch</code> outside of my virtual-environment everything works fine.</p> <p>Does anybody has an idea of how to install scrapy-deltafetch in the virtualenvironment?</p>
0
2016-08-01T17:34:20Z
38,709,482
<p>Your system is missing Berkeley DB, which is used by DeltaFetch to store requests data.</p> <p>So, first install Berkeley DB in your system (found <a href="http://www.linuxfromscratch.org/blfs/view/svn/server/db.html" rel="nofollow">this tutorial</a> in a quick search).</p> <p>After that, you have to install the <code>bsddb3</code> Python package (you can follow the instructions from <a href="http://stackoverflow.com/a/17213338/1084647">this answer</a>).</p>
0
2016-08-01T23:15:14Z
[ "python", "scrapy", "virtualenv", "raspbian", "raspberry-pi3" ]
how to create rectangles by getting scale values at the time in tkinter?
38,704,903
<p>I want to get the value of a scale and create rectangles as many as the value is. For example, if I adjust the scale to number 7, 7 rectangles would be created next to each other, and after that if I adjust the scale value to 3, the rectangles shown in the canvas decreases to three at that moment. I had used the code below:</p> <pre><code>from tkinter import * from tkinter import ttk class rect: def __init__(self, root): self.root = root self.size = IntVar() self.canvas = Canvas(self.root, width=800, height=300) self.scale = Scale(self.root, orient=HORIZONTAL, from_=3, to=20, tickinterval=1, variable=self.size) self.show() def show(self): x = 50 y = 50 for i in range(self.scale.get()): self.canvas.create_rectangle(x, y, x + 50, y + 50, fill='red') x += 50 self.canvas.pack() self.scale.pack() root = Tk() a = rect(root) root.mainloop() </code></pre> <p>I guess I have to use <code>trace</code> method, But I don't know how to. Can anyone fix the code I used in the way which I explained. Thank you.</p>
0
2016-08-01T17:35:29Z
38,706,732
<p>One solution is to bind to <code>&lt;ButtonRelease&gt;</code>, and call your <code>show</code> method there. Since event bindings pass an object representing the event, you'll need to make that an optional argument if you also want to call <code>show</code> without any arguments.</p> <p>For example:</p> <pre><code>class rect: def __init__(self, root): ... self.scale = Scale(...) self.scale.bind("&lt;ButtonRelease&gt;", self.show) </code></pre> <p>I'm guessing you'll want to remove any previously drawn rectangles, so you'll need to call <code>delete</code> before creating the rectangles:</p> <pre><code>def show(...): self.canvas.delete("all") ... </code></pre>
0
2016-08-01T19:33:01Z
[ "python", "tkinter", "tkinter-canvas" ]
print words between two particular words in a given string
38,704,933
<p>if one particular word does not end with another particular word, leave it. here is my string:</p> <pre><code>x = 'john got shot dead. john with his .... ? , john got killed or died in 1990. john with his wife dead or died' </code></pre> <p>i want to print and count all words between <code>john</code> and <code>dead or death or died.</code> if <code>john</code> does not end with any of the <code>died or dead or death</code> words. leave it. start again with john word.</p> <p>my code :</p> <pre><code>x = re.sub(r'[^\w]', ' ', x) # removed all dots, commas, special symbols for i in re.findall(r'(?&lt;=john)' + '(.*?)' + '(?=dead|died|death)', x): print i print len([word for word in i.split()]) </code></pre> <p>my output:</p> <pre><code> got shot 2 with his john got killed or 6 with his wife 3 </code></pre> <p>output which i want:</p> <pre><code>got shot 2 got killed or 3 with his wife 3 </code></pre> <p>i don't know where i am doing mistake. it is just a sample input. i have to check with 20,000 inputs at a time.</p>
3
2016-08-01T17:37:16Z
38,705,092
<p>I assume, you want to start over, when there is another <code>john</code> following in your string before <code>dead|died|death</code> occur.</p> <p>Then, you can split your string by the word <code>john</code> and start matching on the resulting parts afterwards:</p> <pre><code>x = 'john got shot dead. john with his .... ? , john got killed or died in 1990. john with his wife dead or died' x = re.sub('\W+', ' ', re.sub('[^\w ]', '', x)).strip() for e in x.split('john'): m = re.match('(.+?)(dead|died|death)', e) if m: print(m.group(1)) print(len(m.group(1).split())) </code></pre> <p>yields:</p> <pre><code> got shot 2 got killed or 3 with his wife 3 </code></pre> <p>Also, note that after the replacements I propose here (before splitting and matching), the string looks like this:</p> <pre><code>john got shot dead john with his john got killed or died in 1990 john with his wife dead or died </code></pre> <p>I.e., there are no multiple whitespaces left in a sequence. You manage this by splitting by a whitespace later, but I feel this is a bit cleaner.</p>
2
2016-08-01T17:47:53Z
[ "python", "regex", "python-2.7" ]
print words between two particular words in a given string
38,704,933
<p>if one particular word does not end with another particular word, leave it. here is my string:</p> <pre><code>x = 'john got shot dead. john with his .... ? , john got killed or died in 1990. john with his wife dead or died' </code></pre> <p>i want to print and count all words between <code>john</code> and <code>dead or death or died.</code> if <code>john</code> does not end with any of the <code>died or dead or death</code> words. leave it. start again with john word.</p> <p>my code :</p> <pre><code>x = re.sub(r'[^\w]', ' ', x) # removed all dots, commas, special symbols for i in re.findall(r'(?&lt;=john)' + '(.*?)' + '(?=dead|died|death)', x): print i print len([word for word in i.split()]) </code></pre> <p>my output:</p> <pre><code> got shot 2 with his john got killed or 6 with his wife 3 </code></pre> <p>output which i want:</p> <pre><code>got shot 2 got killed or 3 with his wife 3 </code></pre> <p>i don't know where i am doing mistake. it is just a sample input. i have to check with 20,000 inputs at a time.</p>
3
2016-08-01T17:37:16Z
38,705,227
<p>You can use this negative lookahead regex:</p> <pre><code>&gt;&gt;&gt; for i in re.findall(r'(?&lt;=john)(?:(?!john).)*?(?=dead|died|death)', x): ... print i.strip() ... print len([word for word in i.split()]) ... got shot 2 got killed or 3 with his wife 3 </code></pre> <p>Instead of your <code>.*?</code> this regex is using <code>(?:(?!john).)*?</code> which will lazily match 0 or more of any characters only when <code>john</code> is not present in this match.</p> <p>I also suggest using word boundaries to make it match complete words:</p> <pre><code>re.findall(r'(?&lt;=\bjohn\b)(?:(?!\bjohn\b).)*?(?=\b(?:dead|died|death)\b)', x) </code></pre> <p><a href="http://ideone.com/5TlGf9" rel="nofollow"><strong>Code Demo</strong></a></p>
2
2016-08-01T17:57:03Z
[ "python", "regex", "python-2.7" ]
Nested indexing in python
38,704,936
<p>I have a python dict, and some (but not all) of its values are also dicts.</p> <p>For example:</p> <pre><code> d = {'a' : 1, 'b' : {'c' : 3, 'd' : 'target_value'} } </code></pre> <p>What would be the best way to pass in keys to reach any target value? Something like <code>retrieve(d, (key, nested_key, ...))</code> where <code>retrieve(d, ('b','d'))</code> would return <code>target value</code>.</p>
2
2016-08-01T17:37:33Z
38,705,058
<p>The better option here is to find a way to normalize your data structure, but if you can't for some reason, you can just access each key in order.</p> <p>For example:</p> <pre><code>def nested_getter(dictionary, *keys): val = dictionary[keys[0]] for key in keys[1:]: val = val[key] return val d = {'a' : 1, 'b' : {'c' : 3, 'd' : 'target_value'} } print(nested_getter(d, 'b', 'd')) </code></pre> <p>You could also do it recursively:</p> <pre><code>def nested_getter(dictionary, *keys): val = dictionary[keys[0]] if isinstance(val, dict): return nested_getter(val, *keys[1:]) else: return val </code></pre>
2
2016-08-01T17:45:25Z
[ "python", "dictionary", "nested", "key" ]
Read the last N lines of a CSV file in Python with numpy / pandas
38,704,949
<p>Is there a quick way to read the last N lines of a CSV file in Python, using <code>numpy</code> or <code>pandas</code>?</p> <ol> <li><p>I cannot do <code>skip_header</code> in <code>numpy</code> or <code>skiprow</code> in <code>pandas</code> because the length of the file varies, and I would always need the last N rows.</p></li> <li><p>I know I can use pure Python to read line by line from the last row of the file, but that would be very slow. I can do that if I have to, but a more efficient way with <code>numpy</code> or <code>pandas</code> (which is essentially using C) would be really appreciated.</p></li> </ol>
1
2016-08-01T17:38:26Z
38,705,069
<p><strong>Option 1</strong></p> <p>You can read the entire file with <code>numpy.genfromtxt</code>, get it as a numpy array, and take the last N rows:</p> <pre><code>a = np.genfromtxt('filename', delimiter=',') lastN = a[-N:] </code></pre> <p><strong>Option 2</strong></p> <p>You can do a similar thing with the usual file reading:</p> <pre><code>with open('filename') as f: lastN = list(f)[-N:] </code></pre> <p>but this time you will get the list of last N lines, as strings.</p> <p><strong>Option 3 - without reading the entire file to memory</strong></p> <p>We use a list of at most N items to hold each iteration the last N lines:</p> <pre><code>lines = [] N = 10 with open('csv01.txt') as f: for line in f: lines.append(line) if len(lines) &gt; 10: lines.pop(0) </code></pre> <p>A real csv requires a minor change:</p> <pre><code>import csv ... with ... for line in csv.reader(f): ... </code></pre>
3
2016-08-01T17:46:06Z
[ "python", "csv", "pandas", "numpy" ]
Read the last N lines of a CSV file in Python with numpy / pandas
38,704,949
<p>Is there a quick way to read the last N lines of a CSV file in Python, using <code>numpy</code> or <code>pandas</code>?</p> <ol> <li><p>I cannot do <code>skip_header</code> in <code>numpy</code> or <code>skiprow</code> in <code>pandas</code> because the length of the file varies, and I would always need the last N rows.</p></li> <li><p>I know I can use pure Python to read line by line from the last row of the file, but that would be very slow. I can do that if I have to, but a more efficient way with <code>numpy</code> or <code>pandas</code> (which is essentially using C) would be really appreciated.</p></li> </ol>
1
2016-08-01T17:38:26Z
38,705,169
<p>Use <code>skiprows</code> parameter of <code>pandas</code> <code>read_csv()</code>, the tougher part is finding the number of lines in the csv. here's a possible solution:</p> <pre><code>with open('filename',"r") as f: reader = csv.reader(f,delimiter = ",") data = list(reader) row_count = len(data) df = pd.read_csv('filename', skiprows = row_count - N) </code></pre>
1
2016-08-01T17:52:46Z
[ "python", "csv", "pandas", "numpy" ]
Read the last N lines of a CSV file in Python with numpy / pandas
38,704,949
<p>Is there a quick way to read the last N lines of a CSV file in Python, using <code>numpy</code> or <code>pandas</code>?</p> <ol> <li><p>I cannot do <code>skip_header</code> in <code>numpy</code> or <code>skiprow</code> in <code>pandas</code> because the length of the file varies, and I would always need the last N rows.</p></li> <li><p>I know I can use pure Python to read line by line from the last row of the file, but that would be very slow. I can do that if I have to, but a more efficient way with <code>numpy</code> or <code>pandas</code> (which is essentially using C) would be really appreciated.</p></li> </ol>
1
2016-08-01T17:38:26Z
38,706,752
<p>With a small 10 line test file I tried 2 approaches - parse the whole thing and select the last N lines, versus load all lines, but only parse the last N:</p> <pre><code>In [1025]: timeit np.genfromtxt('stack38704949.txt',delimiter=',')[-5:] 1000 loops, best of 3: 741 µs per loop In [1026]: %%timeit ...: with open('stack38704949.txt','rb') as f: ...: lines = f.readlines() ...: np.genfromtxt(lines[-5:],delimiter=',') 1000 loops, best of 3: 378 µs per loop </code></pre> <p>This was tagged as a duplicate of <a href="http://stackoverflow.com/questions/17108250/efficiently-read-last-n-rows-of-csv-into-dataframe">Efficiently Read last &#39;n&#39; rows of CSV into DataFrame</a>. The accepted answer there used</p> <pre><code>from collections import deque </code></pre> <p>and collected the last N lines in that structure. It also used <code>StringIO</code> to feed the lines to the parser, which is an unnecessary complication. <code>genfromtxt</code> takes input from anything that gives it lines, so a list of lines is just fine.</p> <pre><code>In [1031]: %%timeit ...: with open('stack38704949.txt','rb') as f: ...: lines = deque(f,5) ...: np.genfromtxt(lines,delimiter=',') 1000 loops, best of 3: 382 µs per loop </code></pre> <p>Basically the same time as <code>readlines</code> and slice.</p> <p><code>deque</code> may have an advantage when the file is very large, and it gets costly to hang onto all the lines. I don't think it saves any file reading time. Lines still have to be read one by one.</p> <p>timings for the <code>row_count</code> followed by <code>skip_header</code> approach are slower; it requires reading the file twice. <code>skip_header</code> still has to read lines.</p> <pre><code>In [1046]: %%timeit ...: with open('stack38704949.txt',"r") as f: ...: ...: reader = csv.reader(f,delimiter = ",") ...: ...: data = list(reader) ...: ...: row_count = len(data) ...: np.genfromtxt('stack38704949.txt',skip_header=row_count-5,delimiter=',') The slowest run took 5.96 times longer than the fastest. This could mean that an intermediate result is being cached. 1000 loops, best of 3: 760 µs per loop </code></pre> <p>For purposes of counting lines we don't need to use <code>csv.reader</code>, though it doesn't appear to cost much extra time.</p> <pre><code>In [1048]: %%timeit ...: with open('stack38704949.txt',"r") as f: ...: lines=f.readlines() ...: row_count = len(data) ...: np.genfromtxt('stack38704949.txt',skip_header=row_count-5,delimiter=',') 1000 loops, best of 3: 736 µs per loop </code></pre>
3
2016-08-01T19:34:05Z
[ "python", "csv", "pandas", "numpy" ]
Anchors (<a href="URL">URL</a>) instead of text (<p>URL</p>)
38,704,980
<p>Trying to achieve the following logic:</p> <p>If URL in text is surrounded by paragraph tags (Example: <code>&lt;p&gt;URL&lt;/p&gt;</code>), replace it in place to become a link instead: <code>&lt;a href="URL"&gt;Click Here&lt;/a&gt;</code></p> <p>The original file is a database dump (sql, UTF-8). Some URLs already exist in the desired format. I need to fix the missing links.</p> <p>I am working on a script, which uses Beautifulsoup. If other solutions are make more sense (regex, etc.), I am open to suggestions. </p>
0
2016-08-01T17:40:10Z
38,705,009
<p>You can search for all <code>p</code> elements that has a text starting with <code>http</code>. Then, <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#replace-with" rel="nofollow">replace it with</a> a link:</p> <pre><code>for elm in soup.find_all("p", text=lambda text: text and text.startswith("http")): elm.replace_with(soup.new_tag("a", href=elm.get_text())) </code></pre> <p>Example working code:</p> <pre><code>from bs4 import BeautifulSoup data = """ &lt;div&gt; &lt;p&gt;http://google.com&lt;/p&gt; &lt;p&gt;https://stackoverflow.com&lt;/p&gt; &lt;/div&gt; """ soup = BeautifulSoup(data, "html.parser") for elm in soup.find_all("p", text=lambda text: text and text.startswith("http")): elm.replace_with(soup.new_tag("a", href=elm.get_text())) print(soup.prettify()) </code></pre> <p>Prints:</p> <pre><code>&lt;div&gt; &lt;a href="http://google.com"&gt;&lt;/a&gt; &lt;a href="https://stackoverflow.com"&gt;&lt;/a&gt; &lt;/div&gt; </code></pre> <p>I can imagine this approach break, but it should be a good start for you.</p> <hr> <p>If you additionally want to add texts to your links, set the <code>.string</code> property:</p> <pre><code>soup = BeautifulSoup(data, "html.parser") for elm in soup.find_all("p", text=lambda text: text and text.startswith("http")): a = soup.new_tag("a", href=elm.get_text()) a.string = "link" elm.replace_with(a) </code></pre>
0
2016-08-01T17:42:04Z
[ "python", "beautifulsoup" ]
Unexpected results with betweenness_centrality
38,705,001
<p>Below is code to create a very simple graph in networkx using Python 2.7 with a call to return betweenness_centrality:</p> <pre><code>import networkx as nx G = nx.Graph() G.add_nodes_from([1,3]) G.add_edge(1,2) G.add_edge(2,3) G.add_edge(1,3) G[1][2]['weight']=4400 G[2][3]['weight']=4100 G[1][3]['weight']=1500 print nx.betweenness_centrality(G,weight='weight') </code></pre> <p>I expected to see weights essentially as assigned, but the weights are all zero:</p> <p>{1: 0.0, 2: 0.0, 3: 0.0}</p> <p>I am clearly missing something simple, and cannot see what it is from the on-line documentation. Thank you.</p>
1
2016-08-01T17:41:20Z
38,706,386
<p>The default for <code>networkx.betweenness_centrality()</code> (and arguably the standard definition) does not include counting the endpoints. So with your K3 graph the betweenness on each node is 0. If you want to count endpoints use</p> <pre><code>In [1]: import networkx as nx In [2]: G = nx.Graph() In [3]: G.add_nodes_from([1,3]) In [4]: G.add_edge(1,2) In [5]: G.add_edge(2,3) In [6]: G.add_edge(1,3) In [7]: G[1][2]['weight']=4400 In [8]: G[2][3]['weight']=4100 In [9]: G[1][3]['weight']=1500 In [10]: print(nx.betweenness_centrality(G,weight='weight',endpoints=True)) {1: 2.0, 2: 2.0, 3: 2.0} </code></pre> <p>Note that the 'weight' attribute is used to find the shortest path and not counted directly in the betweenness score. For example with nonsymmetric paths in a loop:</p> <pre><code>In [1]: import networkx as nx In [2]: G = nx.cycle_graph(4) In [3]: nx.set_edge_attributes(G,'weight',1) In [4]: print(nx.betweenness_centrality(G,weight='weight')) {0: 0.16666666666666666, 1: 0.16666666666666666, 2: 0.16666666666666666, 3: 0.16666666666666666} In [5]: G[0][1]['weight']=5 In [6]: print(nx.betweenness_centrality(G,weight='weight')) {0: 0.0, 1: 0.0, 2: 0.6666666666666666, 3: 0.6666666666666666} </code></pre>
1
2016-08-01T19:10:21Z
[ "python", "networkx" ]
Losing JSON value from Python to PHP?
38,705,037
<p>I am struggling with a weird issue. I have a Python script that is accessed from a page via PHP and returns a JSON object with about 20 variables. All of them work all of the time except one that always returns an empty value. Directly running the Python script on the server returns a value every time, but php never sees it. I have tried output as a string, as an int, and even a string combined with a preset value. The posted code has only two shown, most of the functional values are omitted for length. ("cpul" is the one not working.)</p> <p>PythonScript.py:</p> <pre><code>#!/usr/bin/python2.7 import os, json def getCPUtemperature(): res = os.popen('vcgencmd measure_temp').readline() tmp = (1.8 * float(res.replace("temp=","").replace("'C\n",""))) + 32 return(tmp) # Return % of CPU used by user as a character string def getCPUuse(): val = str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip(\ )[2:4]) return(val) result = {'cput': CPU_temp, 'cpul': CPU_usage} print json.dumps(result) </code></pre> <p>OUTPUT FROM SSH TERMINAL: {"cpul": "9", "cput": 106.16000000000001}</p> <p>phpScript.php just passes the result on to the browser:</p> <pre><code>&lt;?php session_start(); try { $result = exec('/usr/bin/python /scripts/PyhtonScript.py'); echo $result; } catch (Exception $e) { echo '{"res" : "ERROR", "msg" : "Caught exception: ' . $e-&gt;getMessage() . '"}'; } ?&gt; </code></pre> <p>OUTPUT FROM BROWSER: {"cpul": "", "cput": 106.16000000000001}</p> <p>If I change PythonScript.py 'result' to say:</p> <pre><code>result = {'cput': CPU_temp, 'cpul': 'foo'} </code></pre> <p>OUTPUT FROM BROWSER: {"cpul": "foo", "cput": 106.16000000000001}</p> <p>and if I change PythonScript.py 'result' to say:</p> <pre><code>result = {'cput': CPU_temp, 'cpul': 'foo' + CPU_usage} </code></pre> <p>OUTPUT FROM BROWSER: {"cpul": "foo", "cput": 106.16000000000001}</p> <p>If I modify the function to output an int rather than a string I get the same results without the quotes:</p> <p>OUTPUT FROM SSH TERMINAL: {"cpul": 9, "cput": 106.16000000000001}</p> <p>OUTPUT FROM BROWSER: {"cpul": "", "cput": 106.16000000000001}</p> <p>The value is a percentage, so I would love to multiply it by 100 before sending, but if I modify the function as:</p> <pre><code>def getCPUuse(): val = str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip(\ )) mod = int(val) * 100 return(mod) </code></pre> <p>OUTPUT FROM SSH TERMINAL: {"cpul": 90, "cput": 106.16000000000001}</p> <p>OUTPUT FROM BROWSER: Nothing, blank screen</p> <p>APACHE2/error.log:</p> <pre><code>Traceback (most recent call last): File "/var/www/html/assets/scripts/info_lkp.py", line 49, in &lt;module&gt; CPU_usage = getCPUuse() File "/var/www/html/assets/scripts/info_lkp.py", line 29, in getCPUuse mod2 = int(mod)*10 ValueError: invalid literal for int() with base 10: '' 'unknown': I need something more specific. </code></pre> <p>Any idea what I am missing before I run out of hair to pull out? As stated, posted code is truncated to remove unrelated working similar functions and their associated outputs.</p>
3
2016-08-01T17:44:13Z
38,705,146
<p>This is a <strong>Python</strong> error</p> <p>When you multiply it by 100 before sending it, in your python script, error happens there.</p> <p>And value is being lost, well, not because of the PHP. It's because your python script does not return valid JSON.</p> <p>Read about this error here <a href="http://stackoverflow.com/questions/1841565/valueerror-invalid-literal-for-int-with-base-10">ValueError: invalid literal for int() with base 10: &#39;&#39;</a></p>
0
2016-08-01T17:51:17Z
[ "php", "python", "json" ]
RQ scheduler sending multiple emails
38,705,042
<p>I am using <a href="https://github.com/ui/rq-scheduler" rel="nofollow">Django RQ scheduler</a></p> <p>scheduled_tasks.py</p> <pre><code>from redis import Redis from rq_scheduler import Scheduler from datetime import datetime scheduler = Scheduler(connection=Redis()) # Get a scheduler for the "default" queue # scheduler = django_rq.get_scheduler("default") now = datetime.now() start = now.replace(hour=8, minute=00, second=0, microsecond=0) scheduler.schedule( scheduled_time=start, # Time for first execution, in UTC timezone func=broadcast_approved_jobs, # Function to be queued interval=86400 # Time before the function is called again, in seconds repeat=None # Repeat this number of times (None means repeat forever) ) </code></pre> <p>I need to run this scheduler only once in a day.</p> <p>But its sending mails repeatedly. I think this scheduler is calling broadcast_approved_jobs multiple times. Any idea why? </p>
0
2016-08-01T17:44:25Z
38,705,206
<p>(take 2) This is the function I'm using, not written by me, but I forget where I found it. Even if your scheduler is being called multiple times, it will at least remove any existing jobs.</p> <pre><code> def schedule_once(scheduled_time, func, args=None, kwargs=None, interval=None, repeat=None, result_ttl=None, timeout=None, queue_name=None): """ Schedule job once or reschedule when interval changes """ if not func in functions or not interval in functions[func] \ or len(functions[func]) &gt; 1: # clear all scheduled jobs for this function map(scheduler.cancel, filter(lambda x: x.func == func, jobs)) # schedule with new interval scheduler.schedule(scheduled_time, func, interval=interval, repeat=repeat) schedule_once( scheduled_time=datetime.utcnow(), # Time for first execution, in UTC timezone func=readmail, # Function to be queued interval=120, # Time before the function is called again, in seconds repeat=0 # Repeat this number of times (None means repeat forever) ) </code></pre>
1
2016-08-01T17:56:06Z
[ "python", "django" ]
Python, Matplotlib: Drawing vertical lines in 3d plot, when data is independent
38,705,055
<p>I have a random walker in the (x,y) plane and a -log(bivariate gaussian) in the (x,y,z) plane. These two datasets are essentially independent. </p> <p>I want to sample, say 5 (x,y) pairs of the random walker and draw vertical lines up the z-axis and terminate the vertical line when it "meets" the bivariate gaussian. </p> <p>This is my code so far:</p> <pre><code>import matplotlib as mpl import matplotlib.pyplot as plt import random import numpy as np import seaborn as sns import scipy from mpl_toolkits.mplot3d import Axes3D from matplotlib.mlab import bivariate_normal %matplotlib inline # Data for random walk def randomwalk(): mpl.rcParams['legend.fontsize'] = 10 xyz = [] cur = [0, 0] for _ in range(40): axis = random.randrange(0, 2) cur[axis] += random.choice([-1, 1]) xyz.append(cur[:]) # Get density x, y = zip(*xyz) data = np.vstack([x,y]) kde = scipy.stats.gaussian_kde(data) density = kde(data) # Data for bivariate gaussian a = np.linspace(-7.5, 7.5, 40) b = a X,Y = np.meshgrid(a, b) Z = bivariate_normal(X, Y) surprise_Z = -np.log(Z) # Get random points from walker and plot up z-axis to the gaussian M = data[:,np.random.choice(20,5)].T # Plot figure fig = plt.figure(figsize=(10, 7)) ax = fig.gca(projection='3d') ax.plot(x, y, 'grey', label='Random walk') # Walker ax.scatter(x[-1], y[-1], c='k', marker='o') # End point ax.legend() surf = ax.plot_surface(X, Y, surprise_Z, rstride=1, cstride=1, cmap = plt.cm.gist_heat_r, alpha=0.1, linewidth=0.1) #fig.colorbar(surf, shrink=0.5, aspect=7, cmap=plt.cm.gray_r) for i in range(5): ax.plot([M[i,0], M[i,0]],[M[i,1], M[i,1]], [0,10],'k--',alpha=0.8, linewidth=0.5) ax.set_zlim(0, 50) ax.set_xlim(-10, 10) ax.set_ylim(-10, 10) </code></pre> <p>Which produces</p> <p><a href="http://i.stack.imgur.com/vKTvA.png" rel="nofollow"><img src="http://i.stack.imgur.com/vKTvA.png" alt="enter image description here"></a></p> <p>As you can see the only thing I'm struggling with is how to terminate the vertical lines when they meet the appropriate Z-value. Any ideas are welcome!</p>
1
2016-08-01T17:45:15Z
38,705,484
<p>You're currently only letting those lines get to a height of 10 by using <code>[0,10]</code> as the z coordinates. You can change your loop to the following:</p> <pre><code>for i in range(5): x = [M[i,0], M[i,0]] y = [M[i,1], M[i,1]] z = [0,-np.log(bivariate_normal(M[i,0],M[i,1]))] ax.plot(x,y,z,'k--',alpha=0.8, linewidth=0.5) </code></pre> <p>This takes the x and y coordinates for each point you loop over and calculates the height of overlying Gaussian for that point and plots to there. Here is a plot with the linestyle changed to emphasize the lines relevant to the question:</p> <p><a href="http://i.stack.imgur.com/ewvLJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/ewvLJ.png" alt="enter image description here"></a></p>
0
2016-08-01T18:14:47Z
[ "python", "matplotlib", "plot", "3d" ]
How do I save 100 binary images into a single file?
38,705,061
<p>So if I have 100 binary images that are type .bmp I was wondering if there is a library I can use to save it into a single file then later read in that file and iterate through each image in python.</p> <p>If there is no library I was planning on reading all of the 100 binary images then save them into an array in python then save that array into a file like <code>100_images.format</code>. </p> <p>I was wondering in what format I can save the file to make it as small as possible? Since the images are all binary 32 by 32 pixels how can I do this efficiently?</p> <p>I was thinking I could save the 100 images into an array like so:</p> <pre><code>array index 0 0 or 1 for if image 1 pixel at (0, 0) is white(0) or black(1) 1 0 or 1 for if image 1 pixel at (0, 1) is white(0) or black(1) ... 1023 0 or 1 for if image 1 pixel at (31, 31) is white(0) or black(1) 1024 0 or 1 for if image 2 pixel at (0, 0) is white(0) or black(1) ... </code></pre> <p>Then write this into a file in python. But I don't know what type of file I should make it. Then in the code that reads through the 100 binary images I would want it work something like:</p> <pre><code>binary_images_manager = new BinaryImagesManager('100_images.format') for i in range(number_of_images_to_see): int[][] binary_image = binary_images_manager.readImage(i) </code></pre>
1
2016-08-01T17:45:36Z
38,716,062
<p>I would do run length encoding: <a href="https://en.wikipedia.org/wiki/Run-length_encoding" rel="nofollow">https://en.wikipedia.org/wiki/Run-length_encoding</a></p> <p>You can use one of the implementation for python: <a href="https://www.rosettacode.org/wiki/Run-length_encoding#Python" rel="nofollow">https://www.rosettacode.org/wiki/Run-length_encoding#Python</a></p> <p>Encoding:</p> <ol> <li>For each image matrix flatten it using np.flatten</li> <li>Run length encode the image</li> <li>Add the code to a list</li> <li>After all images were encoded pickle the list</li> </ol> <p>Decoding:</p> <ol> <li>Unpickle the list</li> <li>For each item in the list decode run length code</li> <li>reshape the resulted vector back to the desired matrix shape</li> </ol>
0
2016-08-02T09:00:50Z
[ "python", "image-processing", "binary", "save", "binary-data" ]