title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
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:]: pri...
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 int...
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.wikip...
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...
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:\...
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 inst...
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 ...
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.d...
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}, ...
-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':...
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 str...
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 re...
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 str...
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...
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>...
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 i...
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>...
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...
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, bu...
-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;-...
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_bas...
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 disc...
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...
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 c...
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/...
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 = {} ...
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) p...
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 fil...
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...
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...
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...
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 ...
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>...
-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>...
-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...
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 ...
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...
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...
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>Y...
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>na...
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 i...
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>na...
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 Py...
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(No...
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 un...
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] </co...
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] </co...
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 separat...
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] </co...
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 ...
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 b...
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 ...
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 th...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 actua...
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 ...
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; que...
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 ...
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 commonCha...
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 th...
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,...
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>impor...
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=Qt...
-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_funct...
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 compa...
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_funct...
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 <...
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 mod...
-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> <pr...
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, i...
-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, i...
-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...
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, i...
-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 is...
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/referen...
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;' Co...
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...
-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...
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 ...
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...
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 ...
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...
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 ...
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 des...
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 Yor...
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.0...
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:", "...
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 ...
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 ...
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...
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...
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...
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= { '...
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.co...
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 ...
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...
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...
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....
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 <cod...
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>...
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><st...
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.r...
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/v...
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 } ] } ...
-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 } ] } ...
-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...
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 da...
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...
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) ...
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...
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',...
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> ...
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") </co...
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.sys...
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:...
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.sys...
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 ...
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.sys...
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...
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>...
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 n...
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 ...
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 ...
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...
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 Mal...
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...
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 Mal...
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='a...
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 t...
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 va...
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://w...
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 s...
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...
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": "", "FirstNa...
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.q...
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.arg...
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("Heigh...
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...
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 res...
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> <...
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 an...
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 an...
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 an...
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-cont...
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(m...
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 construc...
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_...
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="nofo...
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_t...
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></pr...
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 somethin...
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 <...
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 cod...
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...
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>de...
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 ...
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>de...
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>...
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, ne...
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 ...
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 ...
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 usu...
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 ...
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 ...
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 ...
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 ...: w...
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 alread...
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...
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 prin...
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...
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...
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://stac...
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 # s...
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, resu...
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...
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-...
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 ...
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.r...
0
2016-08-02T09:00:50Z
[ "python", "image-processing", "binary", "save", "binary-data" ]