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
Django, tutorial - error: No module named urls
39,640,718
<p>Hi I am following the tutorial to make first web app by Django(<a href="https://docs.djangoproject.com/en/1.10/intro/tutorial01/#write-your-first-view" rel="nofollow">link</a>) But I was given this error:</p> <pre><code> File "c:\Python27\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "c:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "c:\Python27\lib\site-packages\django\core\management\base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "c:\Python27\lib\site-packages\django\core\management\base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "c:\Python27\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "c:\Python27\lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config return check_resolver(resolver) File "c:\Python27\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "c:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "c:\Python27\lib\site-packages\django\urls\resolvers.py", line 313, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "c:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "c:\Python27\lib\site-packages\django\urls\resolvers.py", line 306, in urlconf_module return import_module(self.urlconf_name) File "c:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "c:\Python27\Proj\mysite\mysite\urls.py", line 7, in &lt;module&gt; url(r'^polls/', include('polls.urls')) File "c:\Python27\lib\site-packages\django\conf\urls\__init__.py", line 50, in include urlconf_module = import_module(urlconf_module) File "c:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) ImportError: No module named urls </code></pre> <p>I have read some answers here on SO, but they suggest that this error is caused by wrong version of framework, which is not my case. My version of python is 2.7 and Djanog 1.10.1</p> <p>My urls.py</p> <pre><code>from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')) ] </code></pre> <p>Thank you.</p> <p>EDIT:</p> <p>File: polls/urls.py</p> <pre><code>from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] </code></pre> <p>EDIT 2:</p> <p>Thank all for your comments. There is my file structure of the project.</p> <p><a href="http://i.stack.imgur.com/5eYEX.png" rel="nofollow"><img src="http://i.stack.imgur.com/5eYEX.png" alt="enter image description here"></a></p>
1
2016-09-22T13:39:58Z
39,716,488
<p>OMG I am doomed. The problem was with the file " urls.py". Notice the preceding space character. Thank you everyone for your help and please forgive me for this dumb mistake:)</p>
0
2016-09-27T05:17:33Z
[ "python", "django" ]
python built-in integer object
39,640,732
<p>I read an article that python retains some number objects for better performance. For example:</p> <pre><code>x = 3 y = 3 print(id(x)) print(id(y)) </code></pre> <p>gives out same values, which means that x and y are referencing to exactly same object. The article suggested that the retained number objects are approximately in range 1~100.</p> <p>So I tested following code for getting the exact range:</p> <pre><code>for i in range(-1000,1000): x = int(str(i)) y = int(str(i)) if str(id(x)) == str(id(y)): print(i) </code></pre> <p>and the result is quite weird: it prints out -5~256.<br><br> I'm wondering how these two magic numbers came from and why they're being used. Also, will these two values change in different environment? Thanks!</p>
1
2016-09-22T13:40:26Z
39,640,855
<p>256 is a power of two and small enough that people would be using numbers to that range. </p> <p>-5 I am less sure about, perhaps as special values?</p> <p>Related: <a href="http://stackoverflow.com/questions/15171695/weird-integer-cache-inside-python">Weird Integer Cache inside Python</a></p> <p>Also a word of wisdom from that thread:</p> <blockquote> <p>this is an implementation detail, don't ever rely on it happening or not happening</p> </blockquote>
1
2016-09-22T13:46:30Z
[ "python" ]
parsing a dictionary in a pandas dataframe cell into new row cells (new columns)
39,640,936
<p>I have a Pandas Dataframe that contains one column containing cells containing a dictionary of key:value pairs, like this:</p> <pre><code>{"name":"Test Thorton","company":"Test Group","address":"10850 Test #325\r\n","city":"Test City","state_province":"CA","postal_code":"95670","country":"USA","email_address":"test@testtest.com","phone_number":"999-888-3333","equipment_description":"I'm a big red truck\r\n\r\nRSN# 0000","response_desired":"week","response_method":"email"} </code></pre> <p>I'm trying to parse the dictionary, so the resulting Dataframe contains a new column for each key and the row is populated with the resulting values for each column, like this:</p> <pre><code>//Before 1 2 3 4 5 a b c d {6:y, 7:v} //After 1 2 3 4 5 6 7 a b c d {6:y, 7:v} y v </code></pre> <p>Suggestions much appreciated.</p>
2
2016-09-22T13:49:55Z
39,641,107
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a>:</p> <pre><code>df = pd.DataFrame({1:['a','h'],2:['b','h'], 5:[{6:'y', 7:'v'},{6:'u', 7:'t'}] }) print (df) 1 2 5 0 a b {6: 'y', 7: 'v'} 1 h h {6: 'u', 7: 't'} print (df.loc[:,5].values.tolist()) [{6: 'y', 7: 'v'}, {6: 'u', 7: 't'}] df1 = pd.DataFrame(df.loc[:,5].values.tolist()) print (df1) 6 7 0 y v 1 u t print (pd.concat([df, df1], axis=1)) 1 2 5 6 7 0 a b {6: 'y', 7: 'v'} y v 1 h h {6: 'u', 7: 't'} u t </code></pre> <p><strong>Timings</strong> (<code>len(df)=2k</code>):</p> <pre><code>In [2]: %timeit (pd.concat([df, pd.DataFrame(df.loc[:,5].values.tolist())], axis=1)) 100 loops, best of 3: 2.99 ms per loop In [3]: %timeit (pir(df)) 1 loop, best of 3: 625 ms per loop df = pd.concat([df]*1000).reset_index(drop=True) print (pd.concat([df, pd.DataFrame(df.loc[:,5].values.tolist())], axis=1)) def pir(df): df[['F', 'G']] = df[5].apply(pd.Series) df.drop(5, axis=1) return df print (pir(df)) </code></pre>
2
2016-09-22T13:56:24Z
[ "python", "pandas", "dictionary", "append", "multiple-columns" ]
parsing a dictionary in a pandas dataframe cell into new row cells (new columns)
39,640,936
<p>I have a Pandas Dataframe that contains one column containing cells containing a dictionary of key:value pairs, like this:</p> <pre><code>{"name":"Test Thorton","company":"Test Group","address":"10850 Test #325\r\n","city":"Test City","state_province":"CA","postal_code":"95670","country":"USA","email_address":"test@testtest.com","phone_number":"999-888-3333","equipment_description":"I'm a big red truck\r\n\r\nRSN# 0000","response_desired":"week","response_method":"email"} </code></pre> <p>I'm trying to parse the dictionary, so the resulting Dataframe contains a new column for each key and the row is populated with the resulting values for each column, like this:</p> <pre><code>//Before 1 2 3 4 5 a b c d {6:y, 7:v} //After 1 2 3 4 5 6 7 a b c d {6:y, 7:v} y v </code></pre> <p>Suggestions much appreciated.</p>
2
2016-09-22T13:49:55Z
39,641,221
<p>consider <code>df</code></p> <pre><code>df = pd.DataFrame([ ['a', 'b', 'c', 'd', dict(F='y', G='v')], ['a', 'b', 'c', 'd', dict(F='y', G='v')], ], columns=list('ABCDE')) df </code></pre> <p><a href="http://i.stack.imgur.com/Zd89H.png" rel="nofollow"><img src="http://i.stack.imgur.com/Zd89H.png" alt="enter image description here"></a></p> <hr> <p>Use <code>apply(pd.Series)</code></p> <pre><code>df.E.apply(pd.Series) </code></pre> <p><a href="http://i.stack.imgur.com/DRAE5.png" rel="nofollow"><img src="http://i.stack.imgur.com/DRAE5.png" alt="enter image description here"></a></p> <hr> <p>Assign it like this</p> <pre><code>df[['F', 'G']] = df.E.apply(pd.Series) df.drop('E', axis=1) </code></pre> <p><a href="http://i.stack.imgur.com/6U1fP.png" rel="nofollow"><img src="http://i.stack.imgur.com/6U1fP.png" alt="enter image description here"></a></p>
1
2016-09-22T14:01:04Z
[ "python", "pandas", "dictionary", "append", "multiple-columns" ]
Do I need different MIB with those OID?
39,640,966
<p>I got this legacy <code>powershell</code> script that retrieve information via SNMP, I'm trying to port it in Python using <code>snimpy</code>.</p> <pre><code>$PrintersIP = '10.100.7.47', '10.100.7.48' Function Get-SNMPInfo ([String[]]$Printers) { Begin { $SNMP = New-Object -ComObject olePrn.OleSNMP } Process { Foreach ($IP in $Printers) { $SNMP.Open($IP,"public",2,3000) [PSCustomObject][Ordered]@{ Name = $SNMP.Get(".1.3.6.1.2.1.1.5.0") IP = $IP UpTime = [TimeSpan]::FromSeconds(($SNMP.Get(".1.3.6.1.2.1.1.3.0"))/100) Model = $SNMP.Get(".1.3.6.1.2.1.25.3.2.1.3.1") Description = $SNMP.Get(".1.3.6.1.2.1.1.1.0") #Contact = $SNMP.Get(".1.3.6.1.2.1.1.4.0") #SN = $SNMP.Get(".1.3.6.1.2.1.43.5.1.1.17.1") #Location = $SNMP.Get(".1.3.6.1.2.1.1.6.0") #TonerName = $SNMP.Get("43.11.1.1.6.1.1") } } } End { $SNMP.Close() } } Get-SNMPInfo $PrintersIP | ft -AutoSize * </code></pre> <h3>Snimpy usage</h3> <p>From the <a href="https://snimpy.readthedocs.io/en/latest/usage.html#regular-python-module" rel="nofollow">section <em>Usage</em> of the official documentation</a> they use the <code>load</code> method to load MIB a file.</p> <pre><code>from snimpy.manager import Manager as M from snimpy.manager import load load("IF-MIB") m = M("localhost") print(m.ifDescr[0]) </code></pre> <h3>Finding <em><code>OID</code> name</em></h3> <p>I can't find the <code>OID</code> name for some of the identifiers. For instance:</p> <ul> <li><a href="http://oid-info.com/get/1.3.6.1.2.1.1.5.0" rel="nofollow"><code>1.3.6.1.2.1.1.5.0</code></a> → nothing ;</li> <li><a href="http://oid-info.com/get/1.3.6.1.2.1.1.5" rel="nofollow"><code>1.3.6.1.2.1.1.5</code></a> → <code>sysName</code>.</li> </ul> <h3>Question</h3> <ul> <li>Depending on the <em><code>OID</code>'s name</em> I'm trying to use, do I need to load different MIB file ? (e.g. <code>Printer-MIB</code>, <code>IF-MIB</code>, etc.)</li> <li>Where can I find the missing <em><code>OID</code>'s name</em></li> </ul>
2
2016-09-22T13:51:14Z
39,644,523
<p>If you use the load() method then scalars and row names from it will be made available as an instance attributes hence you're able to query for 'sysContact' etc, but as the 'sysDescr' and 'sysName' are not part of the IF-MIB you will not be able to get it.</p> <p>You will need to load in the relevant MIB such as SNMPv2-MIB or attempt to get the value via the OID directly. </p> <p><strong>UPDATE:</strong> I've had a look and snimpy and it loooks like pysnmp is doing the collection, so you could always user that directly. The sample below is collecting a new different SNMP values some by OID and others via the named variable within the MIB (you will need to have the relevant MIB available if you want to get via the name). This sample is pretty much taken from the <a href="http://pysnmp.sourceforge.net/docs/tutorial.html" rel="nofollow">pySNMP documentation</a></p> <pre><code>from pysnmp.entity.rfc3413.oneliner import cmdgen cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( cmdgen.CommunityData('public'), cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)), '1.3.6.1.2.1.1.1.0', # sysDescr '1.3.6.1.2.1.1.2.0', # sysObjectId '1.3.6.1.2.1.1.3.0', # upTime '1.3.6.1.2.1.1.4.0', # Contact '1.3.6.1.2.1.1.5.0', # sysName '1.3.6.1.2.1.1.6.0', # Location cmdgen.MibVariable('SNMPv2-MIB', 'sysDescr', 0), #.1.3.6.1.2.1.1.1.0 sysDescr cmdgen.MibVariable('SNMPv2-MIB', 'sysName', 0) #.1.3.6.1.2.1.1.5.0 sysName ) # Check for errors and print out results if errorIndication: print(errorIndication) else: if errorStatus: print('%s at %s' % ( errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex)-1] or '?' ) ) else: for name, val in varBinds: print('%s = %s' % (name.prettyPrint(), val.prettyPrint())) </code></pre>
1
2016-09-22T16:40:11Z
[ "python", "powershell", "snmp", "mib", "snimpy" ]
How to pass list of function and all its arguments to be executed in another function in python?
39,641,171
<p>I have a list of functions and its arguments like this:</p> <pre><code>(func1, *arg1), (func2, *arg2),... </code></pre> <p>I want to pass them into another function to execute them like this:</p> <pre><code>for func, arg* in (list of funcs, args): func(arg*) </code></pre> <p>How to do it in python? I have tried several but it doesn't like unpacking and *arg at the same time.</p>
3
2016-09-22T13:59:02Z
39,641,355
<p>You can do like this, just use list of tuple where first is the function name, and rest are arguments. </p> <pre><code>def a(*args,**kwargs): print 1 list_f = [(a,1,2,3)] for f in list_f: f[0](f[1:]) </code></pre>
0
2016-09-22T14:07:01Z
[ "python" ]
How to pass list of function and all its arguments to be executed in another function in python?
39,641,171
<p>I have a list of functions and its arguments like this:</p> <pre><code>(func1, *arg1), (func2, *arg2),... </code></pre> <p>I want to pass them into another function to execute them like this:</p> <pre><code>for func, arg* in (list of funcs, args): func(arg*) </code></pre> <p>How to do it in python? I have tried several but it doesn't like unpacking and *arg at the same time.</p>
3
2016-09-22T13:59:02Z
39,641,425
<p>You can use the <a href="https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists" rel="nofollow">*-operator to unpack the arguments out of the tuple</a>.</p> <p>For example, suppose the format of items in your invocation list is <code>(function,arg1,arg2,...)</code>. In other words, <code>item[0]</code> is your function, while <code>item[1:]</code> are the arguments the should be given to the function.</p> <pre><code>def f1(x1): print("f1 {0}".format(x1)) def f2(x1,x2): print("f2 {0} {1}".format(x1,x2)) for data in ((f1,5),(f2,3,4)): data[0](*data[1:]) # output: # f1 5 # f2 3 4 </code></pre>
3
2016-09-22T14:10:44Z
[ "python" ]
How to pass list of function and all its arguments to be executed in another function in python?
39,641,171
<p>I have a list of functions and its arguments like this:</p> <pre><code>(func1, *arg1), (func2, *arg2),... </code></pre> <p>I want to pass them into another function to execute them like this:</p> <pre><code>for func, arg* in (list of funcs, args): func(arg*) </code></pre> <p>How to do it in python? I have tried several but it doesn't like unpacking and *arg at the same time.</p>
3
2016-09-22T13:59:02Z
39,641,684
<p>Assuming your function and arguments are separate in the tuple, </p> <pre><code>def squarer(*args): return map(lambda x: x*2, args) def subtracter(*args): return map(lambda x: x-1, args) funcAndArgs = [(squarer, [1,2,3,4]), (subtracter, [1,2,3,4])] for func, args in funcAndArgs: print func(*args) </code></pre> <p>Output:</p> <pre><code>[2, 4, 6, 8] [0, 1, 2, 3] </code></pre>
0
2016-09-22T14:21:58Z
[ "python" ]
How to find a given element in nested lists?
39,641,229
<p>This is my iterative solution:</p> <pre><code>def exists(key, arg): if not arg: return False else: for element in arg: if isinstance(element,list): for i in element: if i==key: return True elif element==key: return True return False print(exists("f", ["a", ["h", "e", "j"], ["t", "e", "s", "c", "o"]])) </code></pre> <p>However, my L.A. wants a double recursive function to solve this.</p> <p>my attempt:</p> <pre><code>def exists(key, arg): if not arg: //base case return False elif arg[0]==key: //if we find the key from the first trial return True else: return (exists(arg[0:],key)) </code></pre> <p>This doesn't work; it shouldn't, because there is no stop. Also, it does not account for lists of lists; I don't know how to do that.</p> <p>Any answer, comment, etc. is appreciated</p>
2
2016-09-22T14:01:29Z
39,641,400
<p>The logic is to iterate each element in your list and check: </p> <ul> <li><em>if list:</em> call the function again with the sub-list.</li> <li><em>if equals the key:</em> return True</li> <li><em>else:</em> return False </li> </ul> <p>Below is sample code to find whether <code>key</code> exists or not in nested list</p> <pre><code>def exists(key, my_list): for item in my_list: if isinstance(item, list): if exists(key, item): # &lt;--Recursive Call return True elif item == key: return True return False # Example &gt;&gt;&gt; my_list = [[[1, 2, 3, 4, 5], [6, 7,]], [8, 9], 10] &gt;&gt;&gt; exists(2, my_list) True &gt;&gt;&gt; exists(6, my_list) True &gt;&gt;&gt; exists(8, my_list) True &gt;&gt;&gt; exists(10, my_list) True &gt;&gt;&gt; exists(11, my_list) False </code></pre>
2
2016-09-22T14:09:29Z
[ "python", "recursion", "functional-programming" ]
How to find a given element in nested lists?
39,641,229
<p>This is my iterative solution:</p> <pre><code>def exists(key, arg): if not arg: return False else: for element in arg: if isinstance(element,list): for i in element: if i==key: return True elif element==key: return True return False print(exists("f", ["a", ["h", "e", "j"], ["t", "e", "s", "c", "o"]])) </code></pre> <p>However, my L.A. wants a double recursive function to solve this.</p> <p>my attempt:</p> <pre><code>def exists(key, arg): if not arg: //base case return False elif arg[0]==key: //if we find the key from the first trial return True else: return (exists(arg[0:],key)) </code></pre> <p>This doesn't work; it shouldn't, because there is no stop. Also, it does not account for lists of lists; I don't know how to do that.</p> <p>Any answer, comment, etc. is appreciated</p>
2
2016-09-22T14:01:29Z
39,641,852
<p>You are close. You only have to check if arg[0] is a sublist and if make a new call. Next you are missing a loop to run through all items of the list. This should work.</p> <pre><code>def exists(key, arg): for item in arg: if isinstance(item, list): # Recursive call with sublist if exists(key, item): return True else: if item == key: return True return False </code></pre>
2
2016-09-22T14:28:05Z
[ "python", "recursion", "functional-programming" ]
How to find a given element in nested lists?
39,641,229
<p>This is my iterative solution:</p> <pre><code>def exists(key, arg): if not arg: return False else: for element in arg: if isinstance(element,list): for i in element: if i==key: return True elif element==key: return True return False print(exists("f", ["a", ["h", "e", "j"], ["t", "e", "s", "c", "o"]])) </code></pre> <p>However, my L.A. wants a double recursive function to solve this.</p> <p>my attempt:</p> <pre><code>def exists(key, arg): if not arg: //base case return False elif arg[0]==key: //if we find the key from the first trial return True else: return (exists(arg[0:],key)) </code></pre> <p>This doesn't work; it shouldn't, because there is no stop. Also, it does not account for lists of lists; I don't know how to do that.</p> <p>Any answer, comment, etc. is appreciated</p>
2
2016-09-22T14:01:29Z
39,641,904
<pre><code>def exists(k, l): if not isinstance(l, list): return False if k in l: return True return any(map(lambda sublist: exists(k, sublist), l)) </code></pre>
3
2016-09-22T14:30:17Z
[ "python", "recursion", "functional-programming" ]
How to find a given element in nested lists?
39,641,229
<p>This is my iterative solution:</p> <pre><code>def exists(key, arg): if not arg: return False else: for element in arg: if isinstance(element,list): for i in element: if i==key: return True elif element==key: return True return False print(exists("f", ["a", ["h", "e", "j"], ["t", "e", "s", "c", "o"]])) </code></pre> <p>However, my L.A. wants a double recursive function to solve this.</p> <p>my attempt:</p> <pre><code>def exists(key, arg): if not arg: //base case return False elif arg[0]==key: //if we find the key from the first trial return True else: return (exists(arg[0:],key)) </code></pre> <p>This doesn't work; it shouldn't, because there is no stop. Also, it does not account for lists of lists; I don't know how to do that.</p> <p>Any answer, comment, etc. is appreciated</p>
2
2016-09-22T14:01:29Z
39,641,950
<p>If we consider these cases:</p> <ul> <li><code>my_list</code> is empty: the key isn't found</li> <li><code>my_list</code> is not a list: the key isn't found</li> <li><code>my_list</code> is a non-empty list (two cases): <ul> <li><code>my_list[0]</code> is the key: it was found</li> <li>otherwise, look for the key in both <code>my_list[0]</code> and <code>my_list[1:]</code></li> </ul></li> </ul> <p>the code would be</p> <pre><code>def exists(key, my_list): if not isinstance(my_list, list) or not my_list: return False return (my_list[0] == key or exists(key, my_list[0]) or exists(key, my_list[1:])) </code></pre> <p>or even</p> <pre><code>def exists(key, my_list): return (isinstance(my_list, list) and len(my_list) &gt; 0 and (my_list[0] == key or exists(key, my_list[0]) or exists(key, my_list[1:]))) </code></pre>
2
2016-09-22T14:32:37Z
[ "python", "recursion", "functional-programming" ]
How to find a given element in nested lists?
39,641,229
<p>This is my iterative solution:</p> <pre><code>def exists(key, arg): if not arg: return False else: for element in arg: if isinstance(element,list): for i in element: if i==key: return True elif element==key: return True return False print(exists("f", ["a", ["h", "e", "j"], ["t", "e", "s", "c", "o"]])) </code></pre> <p>However, my L.A. wants a double recursive function to solve this.</p> <p>my attempt:</p> <pre><code>def exists(key, arg): if not arg: //base case return False elif arg[0]==key: //if we find the key from the first trial return True else: return (exists(arg[0:],key)) </code></pre> <p>This doesn't work; it shouldn't, because there is no stop. Also, it does not account for lists of lists; I don't know how to do that.</p> <p>Any answer, comment, etc. is appreciated</p>
2
2016-09-22T14:01:29Z
39,648,238
<p>Thanks everyone for your help, here is the answer that I have figured out. While it does not look as elegant as most of the answers that were already provided, this answer is the only answer that my lab instructor will accept as it is a pure functional programming method meaning no side effects or for loops:</p> <pre><code>def exists(key, seq): if not seq: return False elif seq[0]==key: return True if isinstance(seq[0],list): return(exists(key,seq[0]) or exists(key,seq[1:])) else: return exists(key,seq[1:]) return False print(findkey("s", ["g","t", "e", ["s"], ["l","k","s",["d","f"],"w"], "o"])) </code></pre>
1
2016-09-22T20:23:09Z
[ "python", "recursion", "functional-programming" ]
Make an image contour black and white using open CV and Python
39,641,373
<p>I'm trying to paint part of an image as black and white using OpenCV2 and Python3. This is the code I'm trying:</p> <pre><code>(x, y, w, h) = cv2.boundingRect(c) cv2.rectangle(frame, (x,y), (x+w,y+h),0,0) sub_face = frame[y:y+h, x:x+w] # apply a gaussian blur on this new recangle image # sub_face = cv2.GaussianBlur(sub_face,(9, 9), 30, borderType = 0) sub_face = cv2.cvtColor(sub_face, cv2.COLOR_BGR2GRAY) # merge this blurry rectangle to our final image result_frame[y:y+sub_face.shape[0], x:x+sub_face.shape[1]] = sub_face </code></pre> <p>When I apply the GaussianBlur method, it works properly, but when I try the cvtColor method it fails with a message (on the last line): could not broadcast input array from shape (268,182) into shape (268,182,3). What am I doing wrong?</p> <p>The <strong><em>c</em></strong> variable in first line is a contour (from motion detection).</p> <p>I'm new into Python and OpenCV.</p> <p>Thanks!</p>
1
2016-09-22T14:07:50Z
39,641,629
<p>You converted sub_face to a single channel image, but result_frame is a 3 channel image.</p> <p>In the last line you are trying to assign a single channel array to a 3 channel slice.</p> <p>You could do this:</p> <pre><code>result_frame[y:y+sub_face.shape[0], x:x+sub_face.shape[1], 0] = sub_face result_frame[y:y+sub_face.shape[0], x:x+sub_face.shape[1], 1] = sub_face result_frame[y:y+sub_face.shape[0], x:x+sub_face.shape[1], 2] = sub_face </code></pre>
0
2016-09-22T14:19:51Z
[ "python", "opencv", "image-processing" ]
Make an image contour black and white using open CV and Python
39,641,373
<p>I'm trying to paint part of an image as black and white using OpenCV2 and Python3. This is the code I'm trying:</p> <pre><code>(x, y, w, h) = cv2.boundingRect(c) cv2.rectangle(frame, (x,y), (x+w,y+h),0,0) sub_face = frame[y:y+h, x:x+w] # apply a gaussian blur on this new recangle image # sub_face = cv2.GaussianBlur(sub_face,(9, 9), 30, borderType = 0) sub_face = cv2.cvtColor(sub_face, cv2.COLOR_BGR2GRAY) # merge this blurry rectangle to our final image result_frame[y:y+sub_face.shape[0], x:x+sub_face.shape[1]] = sub_face </code></pre> <p>When I apply the GaussianBlur method, it works properly, but when I try the cvtColor method it fails with a message (on the last line): could not broadcast input array from shape (268,182) into shape (268,182,3). What am I doing wrong?</p> <p>The <strong><em>c</em></strong> variable in first line is a contour (from motion detection).</p> <p>I'm new into Python and OpenCV.</p> <p>Thanks!</p>
1
2016-09-22T14:07:50Z
39,641,705
<p>You are trying to assign a single channel that results from your <code>cv2.cvtColor</code> call to three channels at once as <code>result_frame</code> is a RGB / three channel image. You are probably wanting to assign the single channel to all three channels. One way to do this cleanly is to exploit <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow">NumPy broadcasting</a> by creating a singleton channel in the third dimension, then broadcasting the result over all channels. Since you are using the <code>cv2</code> interface to OpenCV, the native datatype used for manipulating images is a NumPy array:</p> <pre><code># merge this blurry rectangle to our final image result_frame[y:y+sub_face.shape[0], x:x+sub_face.shape[1]] = sub_face[:,:,None] </code></pre> <p>The <code>:</code> operation in this context accesses all values in a particular dimension. In this case, we want the first and second dimensions. Therefore, <code>sub_face[:,:,None]</code> will make your single channel image 3D with the third dimension being a singleton (i.e. 1). Using NumPy broadcasting will then <strong>broadcast</strong> this single channel image to all channels simultaneously.</p> <p>Note that I didn't have to explicitly access the third dimension when assigning to <code>result_frame</code>. That is because <code>result_frame[y:y+sub_face.shape[0], x:x+sub_face.shape[1]]</code> and <code>result_frame[y:y+sub_face.shape[0], x:x+sub_face.shape[1],:]</code> are the same thing as dropping indexing after the last dimension you specify implicitly assumes <code>:</code>.</p>
1
2016-09-22T14:22:40Z
[ "python", "opencv", "image-processing" ]
Is it faster to add a key to a dictionary or append a value to a list in Python?
39,641,413
<p>I have an application where I need to build a list or a dictionary and speed is important. Normally I would just declare a list of zeros of the appropriate length and assign values one at a time but I need to be able to check the length and have it still be meaningful.</p> <p>Would it be faster to add a key value pair to a dictionary or to append a value to a list? The length of the lists and dictionary will usually be small (less than 100) but this isn't always true and in worst case could be much larger.</p> <p>I could also just have a variable to keep track of where I am in the list if both of these operations are too slow.</p>
0
2016-09-22T14:10:13Z
39,641,691
<p>Best way is to use <code>time()</code> to check your execution time.</p> <p>In following example dict is slightly faster.</p> <pre><code>from time import time st_time = time() b = dict() for i in range(1, 10000000): b[i] = i print (time() - st_time) st_time = time() a = [] for i in range(1, 10000000): a.append(i) print (time() - st_time) 1.45600008965 1.52499985695 </code></pre>
0
2016-09-22T14:22:06Z
[ "python", "performance", "cpu-speed" ]
Py2app - Add "from x import y" to setup.py
39,641,419
<p>I am using py2app to create a standalone APP from a python script however I have run into a problem which I am hoping you could help with.</p> <p>The script relies heavily on tkinter, primarily the tkinter messagebox module, which is not imported with tkinter but rather has to be imported separately using:</p> <pre><code>from tkinter import messagebox </code></pre> <p>In my setup.py file that I use to create the application, I have included all the modules that are used in the python, using this code:</p> <pre><code>from setuptools import setup APP = ['ch.py'] DATA_FILES = ['company.txt'] OPTIONS = {'argv_emulation': False, 'includes':['tkinter', 'requests', 'os'], 'iconfile': 'icon.icns'} setup( app=APP, data_files=DATA_FILES, options={'py2app': OPTIONS}, setup_requires=['py2app'], ) </code></pre> <p>However when I compile the app, everything works perfect except the tkinter messageboxes, which simply don't open. I know this is because I have not specifically imported them in the setup.py file.</p> <p>Does anyone know how I can tell the setup.py file to include "from tkinter import messagebox? </p> <p>Many thanks!</p>
0
2016-09-22T14:10:22Z
39,658,000
<p>Found an answer after about a day of searching, basically the problem isn't with the tkinter messagebox module. The problem was with the requests module that was used to contact the API which then returned information to be displayed in the messagebox. That is why the messagebox wasnt showing, because no request to the API was being made. </p> <p>To fix this you need to add the requests module to 'packages' as well as 'includes', like follows:</p> <pre><code>OPTIONS = {'argv_emulation': False, 'includes':['datetime', 'tkinter', 'requests'], 'packages':['requests'], 'iconfile':'icon.icns'} </code></pre> <p>Hope this helps anyone in the same scenario</p>
0
2016-09-23T10:02:18Z
[ "python", "tkinter", "py2app" ]
open conditional python files but read data from one
39,641,430
<p>I want to open and read a file depending on a condition, read only if condition met true. I wrote the following scriptlet: </p> <pre><code>def bb(fname, species): if species in ('yeast', 'sc'): pm = open('file.txt', 'rU') for line in pm: line = line.split() with open(fname, 'rU') as user: for e in user: e = e.split() if e[0] in line: print(line) elif species in ('human', 'hs'): pm = open('file2.txt', 'rU') for line in pm: line = line.split() with open(fname, 'rU') as user: for e in user: e = e.split() if e[0] in line: print(line) </code></pre> <p>Is there a proper pythonic way, where I don't have to repeat/write the same lines (line3 to 10) over and over again ? Thanks ! </p>
1
2016-09-22T14:10:57Z
39,641,541
<p>You can put the filename value in a variable</p> <pre><code>def bb(fname, species): if species in ('yeast', 'sc'): fname2 = 'file.txt' elif species in ('human', 'hs'): fname2 = 'file2.txt' else: raise ValueError("species received illegal value") with open(fname2, 'rU') as pm: for line in pm: line = line.split() with open(fname, 'rU') as user: for e in user: e = e.split() if e[0] in line: print(line) </code></pre> <p>or define another function</p> <pre><code>def bb(fname, species): if species in ('yeast', 'sc'): read_file('file.txt', fname) elif species in ('human', 'hs'): read_file('file2.txt', fname) def read_file(fname1, fname2): with open(fname1, 'rU') as pm: for line in pm: line = line.split() with open(fname2, 'rU') as user: for e in user: e = e.split() if e[0] in line: print(line) </code></pre>
1
2016-09-22T14:15:59Z
[ "python", "file", "if-statement" ]
open conditional python files but read data from one
39,641,430
<p>I want to open and read a file depending on a condition, read only if condition met true. I wrote the following scriptlet: </p> <pre><code>def bb(fname, species): if species in ('yeast', 'sc'): pm = open('file.txt', 'rU') for line in pm: line = line.split() with open(fname, 'rU') as user: for e in user: e = e.split() if e[0] in line: print(line) elif species in ('human', 'hs'): pm = open('file2.txt', 'rU') for line in pm: line = line.split() with open(fname, 'rU') as user: for e in user: e = e.split() if e[0] in line: print(line) </code></pre> <p>Is there a proper pythonic way, where I don't have to repeat/write the same lines (line3 to 10) over and over again ? Thanks ! </p>
1
2016-09-22T14:10:57Z
39,641,561
<p>Since you seem to be doing the exact same thing regardless of the condition, you could just collapse everything? </p> <pre><code>def bb(fname, species): if species in ['yeast', 'sc', 'human', 'hs']: pm = open('file.txt', 'rU') for line in pm: line = line.split() with open(fname, 'rU') as user: for e in user: e = e.split() if e[0] in line: print(line) </code></pre> <p>Either that or you've made a mistake copying the code. If you want to do something different depending on the case, then you could make a function that takes that argument, or do the conditional statement first and use it to set a certain string or value. </p> <p>E.g. </p> <pre><code>if species in ('yeast', 'sc'): permissions = 'rU' </code></pre> <p>etc.</p> <hr> <p>Edit: Ah, with your edited question the answer would be as above but then </p> <pre><code>if species in ('yeast', 'sc'): file_name = 'file.txt' elif species in ('human', 'hs'): file_name = 'file2.txt' </code></pre>
0
2016-09-22T14:16:49Z
[ "python", "file", "if-statement" ]
open conditional python files but read data from one
39,641,430
<p>I want to open and read a file depending on a condition, read only if condition met true. I wrote the following scriptlet: </p> <pre><code>def bb(fname, species): if species in ('yeast', 'sc'): pm = open('file.txt', 'rU') for line in pm: line = line.split() with open(fname, 'rU') as user: for e in user: e = e.split() if e[0] in line: print(line) elif species in ('human', 'hs'): pm = open('file2.txt', 'rU') for line in pm: line = line.split() with open(fname, 'rU') as user: for e in user: e = e.split() if e[0] in line: print(line) </code></pre> <p>Is there a proper pythonic way, where I don't have to repeat/write the same lines (line3 to 10) over and over again ? Thanks ! </p>
1
2016-09-22T14:10:57Z
39,641,740
<p>Just put opening of file in <code>if else</code> case rest will be done in a similar manner and same code block as well.</p> <pre><code>def bb(fname, species): if species in ('yeast', 'sc'): pm = open('file.txt', 'rU') elif species in ('human', 'hs'): pm = open('file2.txt', 'rU') for line in pm: line = line.split() with open(fname, 'rU') as user: for e in user: e = e.split() if e[0] in line: print(line) </code></pre>
0
2016-09-22T14:24:00Z
[ "python", "file", "if-statement" ]
How do I run two processes in Procfile?
39,641,568
<p>I have a Flask app where I have embedded a Bokeh server graph and I am not being able to have them both working on Heroku. I am trying to deploy on Heorku and I can either start the Bokeh app or the Flask app from the Procfile, but not both at the same time. Consequently, either the content served with Flask will show, or the Bokeh graph. </p> <p>When I deploy with the following line in Procfile, the Bokeh content shows up on the webpage, but not nothing from Flask:</p> <pre><code>web: bokeh serve --port=$PORT --host=bokehapp.herokuapp.com --host=* --address=0.0.0.0 --use-xheaders bokeh_script.py </code></pre> <p>If I deploy with the following, I only get the Flask content, not the Bokeh graph:</p> <pre><code>web: gunicorn app:app </code></pre> <p>In the second case, I am starting Bokeh inside the app.py Flask script using a subprocess:</p> <pre><code>bokeh_process = subprocess.Popen( ['bokeh', 'serve','--allow-websocket-origin=bokehapp.herokuapp.com','--log-level=debug','standard_way_with_curdoc.py'], stdout=subprocess.PIPE) </code></pre> <p>The Heroku logs don't show any errors.</p> <p>I also tried a third alternative:</p> <pre><code>web: bokeh serve --port=$PORT --host=bokehapp.herokuapp.com --host=* --address=0.0.0.0 --use-xheaders bokeh_script.py web: gunicorn app:app </code></pre> <p>And that shows Flask content only. It seems only second worker is being considered.</p> <p>So, my question is how modify the Procfile to consider both processes? Or maybe I am approaching this wrong all together? Any clue you can give would be appreciated. </p>
3
2016-09-22T14:17:00Z
39,689,556
<p>Each Heroku dyno gets allocated a single public network port, which you can get from the <code>$PORT</code> variable, pre-assigned by Heroku before launching your app. The unfortunate side effect of this is that you can have only one public web server running in a dyno.</p> <p>I think the first thing that you need to do is route all requests to your application through your Flask server. For example, you can add a <code>/bokeh/&lt;path:path&gt;</code> route to your Flask app that forwards all requests to the bokeh server using <a href="http://docs.python-requests.org/en/master/" rel="nofollow">requests</a>, then sends the response back to the client. With this change, you now have a single public web server, and the bokeh server can run as a background service without public access.</p> <p>So now you can deploy your Flask app to Heroku, and have it receive both its own requests and the requests for the bokeh server. The next step is to figure out where to deploy the bokeh server.</p> <p>The proper way to do this is to deploy bokeh on a separate dyno. The Flask dyno will know how to forward requests to bokeh because you will have a configuration item with the bokeh server URL.</p> <p>If you want to have everything hosted on a single dyno I think you can as well, though I have never tried this myself and can't confirm it is viable. The all in one configuration is less ideal and not what Heroku recommends, but according to the <a href="https://blog.heroku.com/new_dyno_networking_model#networking-improvements" rel="nofollow">dyno networking documentation</a> it appears you can privately listen on any network ports besides <code>$PORT</code>. Those are not exposed publicly, but the doc seems to suggest the processes running inside a dyno can communicate through private ports. So for example, you can start the Flask app on <code>$PORT</code>, and the bokeh server on <code>$PORT + 1</code>, and have Flask internally forward all the bokeh requests to <code>$PORT + 1</code>.</p>
4
2016-09-25T17:08:03Z
[ "python", "heroku", "flask", "bokeh", "procfile" ]
saving a numpy array as a io.BytesIO with jpg format
39,641,596
<h3>I am using xlsxwriter to insert image into excel in python code.</h3> <p>Now, I had image data(numpy array) after opencv process. I would like insert this image data to excel. But xlswriter only support io.BytesIO stream.</p> <p>question: I don't know how to convert numpy array to <a href="https://docs.python.org/2/library/io.html#io.BytesIO" rel="nofollow">io.BytesIO</a> with jpg format. </p> <p>I have trying numpy.tostring but without jpg format.</p> <p>the code working well in below: <code> _f = open('test.jpg') # I would like to insert test.jpg worksheet.insert_image('E2', 'abc.jpg', {'image_data': _f.read()}) </code></p> <p>Anybody can help me ? thank you so much.</p>
1
2016-09-22T14:18:07Z
39,674,461
<p>finally , I find out a solution. we can use <code>cv2.imencode</code> function to convert numpy array to a jpg format.</p> <p>let's close this question. </p>
1
2016-09-24T08:54:24Z
[ "python", "excel", "opencv", "numpy" ]
pexpect: How to interact() over file object using newer version of pexpect library
39,641,627
<p><code>pexpect</code> has gone through big changes since the version provided by Ubuntu 15.04 (3.2). When installing newest version of <code>pexpect</code> using <code>pip3</code>, this minimal program that previously successfully gave terminal emulation over serial console does not work any more:</p> <pre><code>#!/usr/bin/python3 import serial import pexpect.fdpexpect ser = serial.Serial("/dev/ttyS0", baudrate=115200) spawn = pexpect.fdpexpect.fdspawn(ser) spawn.interact() </code></pre> <p>The newer API is missing interact() method in class <code>pexpect.fdpexpect.fdspawn</code> which used to be there.</p> <p><strong>Question:</strong> how is the newer version of pexpect (currently 4.2.1) supposed to be used to provide free manual interaction with file object (serial port in this case)?</p> <p><strong>Alternatively, question/work-around</strong>: I recognize I am using a bit heavy machinery for such a simple use case, any suggestions for other python libraries that can do the same as earlier version of pexpect could?</p> <hr> <p>Code reading: Examples use <code>pexpect.spawn(command_str)</code> to get a <code>spawn</code> object which has <code>interact()</code> method; actually this <code>pexpect.spawn()</code> is the same as directly creating a <code>pexpect.pty_spawn.spawn</code> object which has this method. On the other hand, <code>pexpect.fdpexpect.fdspawn()</code> will construct a <code>pexpect.fdpexpect.fdspawn</code> class which is missing <code>interact()</code> method. Both of these spawn classes derive from <code>pexpect.spawnbase.SpawnBase</code> class. Based on my quick reading, this looks like regression that resulted from refactoring on the way to version 4.x.</p>
0
2016-09-22T14:19:49Z
39,651,840
<p>Browsing the <a href="https://github.com/pexpect/pexpect" rel="nofollow">pexpect</a> <a href="https://github.com/pexpect/pexpect/issues" rel="nofollow">issues</a>, found <a href="https://github.com/pexpect/pexpect/issues/351" rel="nofollow">#351</a>, <a href="https://github.com/pexpect/pexpect/issues/356" rel="nofollow">#356</a>, and the newly submitted <a href="https://github.com/pexpect/pexpect/issues/377" rel="nofollow">#377</a>. By my quick reading, it seems this is a regression that was brought by uncompleted refactoring along the way towards new major release version 4. There are three possible avenues:</p> <ol> <li><p>Make sure to install older version:</p> <p>$ pip3 install "pexpect&lt;3"</p> <p>(or make sure that the version installed by other system is 3.x).</p></li> <li><p>Fix <code>pexpect</code> by yourself.</p></li> <li>Use some other python library.</li> </ol> <p>These avenues were all more or less hinted by github user @takluyver, apparently maintainer of <code>pexpect</code> in comment to issue #351:</p> <blockquote> <p>@jquast any thoughts on what to do for this (and #356)? I feel bad that we've broken things people were doing with fdspawn, but I really don't want to make it inherit from the pty spawn class, and now that it works on Windows, I think it's important to preserve that too.</p> <p>Maybe we should just say:</p> <ul> <li>If you have legacy code that broke with Pexpect 4, downgrade to Pexpect 3.x (<code>pip install pexpect&lt;4</code>)</li> <li>If you're writing new code, use <a href="https://github.com/digidotcom/python-streamexpect" rel="nofollow">streamexpect</a> instead of pexpect.</li> </ul> </blockquote>
0
2016-09-23T02:53:33Z
[ "python", "serial-port", "pexpect" ]
How do I extract attributes from xml tags using Beautiful Soup?
39,641,630
<p>I am trying to use Beautiful Soup in Django to extract xml tags. This is a sample of the tags that I'm using:</p> <pre><code>&lt;item&gt; &lt;title&gt; Title goes here &lt;/title&gt; &lt;link&gt; Link1 goes here &lt;/link&gt; &lt;description&gt; Description goes here &lt;/description&gt; &lt;media:thumbnail url="Image URL goes here" height="222" width="300"/&gt; &lt;pubDate&gt;Thu, 15 Sep 2016 13:24:48 EDT&lt;/pubDate&gt; &lt;guid isPermaLink="true"&gt; Link2 goes here &lt;/guid&gt; &lt;/item&gt; </code></pre> <p>I have obtained strings of title,link and description tags. But I'm having trouble obtaining the URL from <code>media:thumbnail</code> tag. </p> <p>This is the snippet where I got the values of rest of the tags:</p> <pre><code>soup=BeautifulSoup(urlopen(xmllink),'xml') for items in soup.find_all('item'): listTitle.append(items.title.get_text()) listURL.append(items.link.get_text()) listDescription.append(items.description.get_text()) </code></pre> <p>Help</p>
1
2016-09-22T14:19:54Z
39,642,459
<p>The issue is because not every item has a <em>media:thumbnail</em> so you need to check first:</p> <pre><code>In [60]: import requests In [61]: from bs4 import BeautifulSoup In [62]: soup = BeautifulSoup(requests.get("https://rss.sciencedaily.com/computers_math/computer_programming.xml").content, "xml") In [63]: In [63]: for item in soup.find_all("item"): ....: thumb = item.find("thumbnail") ....: if thumb: ....: print(thumb["url"]) ....: https://images.sciencedaily.com/2016/09/160915132448.jpg https://images.sciencedaily.com/2016/09/160915090018.jpg https://images.sciencedaily.com/2016/09/160914090327.jpg https://images.sciencedaily.com/2016/09/160913134149.jpg https://images.sciencedaily.com/2016/09/160909094844.jpg https://images.sciencedaily.com/2016/09/160907125004.jpg https://images.sciencedaily.com/2016/09/160906085157.jpg https://images.sciencedaily.com/2016/08/160831085055.jpg https://images.sciencedaily.com/2016/08/160822181811.jpg https://images.sciencedaily.com/2016/08/160815134941.jpg https://images.sciencedaily.com/2016/08/160815134817.jpg https://images.sciencedaily.com/2016/08/160809095640.jpg https://images.sciencedaily.com/2016/08/160803140137.jpg https://images.sciencedaily.com/2016/07/160722104135.jpg https://images.sciencedaily.com/2016/07/160721144139.jpg https://images.sciencedaily.com/2016/07/160721103855.jpg https://images.sciencedaily.com/2016/07/160720094641.jpg https://images.sciencedaily.com/2016/07/160718133206.jpg https://images.sciencedaily.com/2016/07/160713105850.jpg https://images.sciencedaily.com/2016/07/160711151055.jpg https://images.sciencedaily.com/2016/07/160707083258.jpg https://images.sciencedaily.com/2016/06/160629125823.jpg https://images.sciencedaily.com/2016/06/160627125140.jpg https://images.sciencedaily.com/2016/06/160624101050.jpg https://images.sciencedaily.com/2016/06/160622104810.jpg </code></pre> <p>A faster alternative would be to use <em>lxml</em>:</p> <pre><code>from lxml import etree for item in tree.findall(".//item/media:thumbnail",tree.nsmap): parent = item.getparent() print(parent.xpath("title/text()")[0]) print(parent.xpath("link/text()")[0]) print(item.get("url")) </code></pre>
1
2016-09-22T14:57:12Z
[ "python", "xml", "attributes", "beautifulsoup" ]
Parallelism inside of a function?
39,641,708
<p>I have a function that counts how often a list of items appears in <code>rows</code> below:</p> <pre><code>def count(pair_list): return float(sum([1 for row in rows if all(item in row.split() for item in pair_list)])) if __name__ == "__main__": pairs = [['apple', 'banana'], ['cookie', 'popsicle'], ['candy', 'cookie'], ...] # grocery transaction data rows = ['apple cookie banana popsicle wafer', 'almond milk eggs butter bread', 'bread almonds apple', 'cookie candy popsicle pop', ...] res = [count(pair) for pair in pairs] </code></pre> <p>In reality, <code>len(rows)</code> is <code>10000</code> and there are <code>18000</code> elements in <code>pairs</code>, so the computing cost of the list comprehension in <code>count()</code> and the one in the main function is expensive.</p> <p>I tried some parallel processing:</p> <pre><code>from multiprocessing.dummy import Pool as ThreadPool import multiprocessing as mp threadpool = ThreadPool(processes = mp.cpu_count()) res = threadpool.map(count, pairs) </code></pre> <p>This doesn't run quickly, either. In fact, after 15 minutes, I just quit the job because it didn't look to be ending. Two questions: 1) how can I speed up the actualy searching that takes place in <code>count()</code>? 2) how can I check the status of the <code>threadpool.map</code> process (i.e. see how many pairs are left to iterate over)?</p>
2
2016-09-22T14:22:46Z
39,645,308
<p>1) The overall complexity of calculations is enormous, and it comes from different sources:</p> <p>a) You split row on low level of calculation, so python has to create new row split for every iteration. To avoid this, you can pre-calculate rows. Something like this will do the job (with minor changes in "count" function):</p> <pre><code>rows2 = [row.split() for row in rows] </code></pre> <p>b) You compare list items one by one, even though you only need to check existence of word in another list. Here we can tweak it more (and use rows3 instead of rows2 in "count" function):</p> <pre><code>rows3 = [set(row.split()) for row in rows] def count(pair_list): return float(sum([1 for row in rows3 if all(item in row for item in pair_list)])) </code></pre> <p>c) You check every word in pairs with every word in rows. Calculation takes 2*len(row)*len(rows) iterations per call of "count" function for original version, while it can take less. For option b) it can be down to 2*len(rows) in good case, but it's possible to make one set lookup per pair, not 2. The trick is to make preparation of all possible word*word combinations for every row and check if corresponding tuple exists in this set. So, in main function you create complex immutable search structure:</p> <pre><code>rows4 = [set((a, b) for a in row for b in row) for row in rows2] </code></pre> <p>And now "count" will look different, it takes tuple instead of list:</p> <pre><code>def count2(pair): return float(len([1 for row in rows4 if(pair in row)])) </code></pre> <p>So you call it a bit different: res = [count2(tuple(pair)) for pair in pairs]</p> <p>Note that search structure creation takes len(row.split())^2 per row in time and space, so if your row can be long, it's not optimal. After all, option b) can be better.</p> <p>2) You can predict number of calls for "count" - it's len(pairs). Count calls of "count" function and make debug print in it for, say, every 1000 calls. </p>
1
2016-09-22T17:27:34Z
[ "python", "multithreading", "list", "parallel-processing" ]
Upload CSV file in django admin list view, replacing add object button
39,641,756
<p>I want to replace the add object button in the listview of an admin page. The underlying idea is that an administrator can download data on all models in the db, use a tool to edit the data, and then reupload as a CSV file. </p> <p>In the list view I am struggling to override the form, as setting </p> <pre><code>class SomeModelForm(forms.Form): csv_file = forms.FileField(required=False, label="please select a file") class Meta: model = MyModel fields = '__all__' class SomeModel(admin.ModelAdmin): change_list_template = 'admin/my_app/somemodel/change_list.html' form = SomeModelForm other stuff </code></pre> <p>The admin change_list.html is overridden as follows:</p> <pre><code>{% extends "admin/change_list.html" %} {% load i18n admin_urls admin_static admin_list %} {% block object-tools-items %} &lt;form action="{% url 'admin:custom_submit_row' %}" method="post" enctype="multipart/form-data"&gt; {% csrf_token %} &lt;p&gt; {{ form.as_p }} &lt;/p&gt; &lt;p&gt;&lt;input type="submit" value="Upload" /&gt;&lt;input type="reset" value="Reset"&gt;&lt;/p&gt; &lt;/form&gt; {% endblock %} </code></pre> <p>Previously SomeModel was missing the class Meta, as per sebbs response this is updated. The original error has been resolved but now currently the admin page is displaying the upload and reset buttons but no field for file uploads.</p> <p>cheers</p> <p>Edited with sebb's input below. Thanks sebb. The error fixed was </p> <blockquote> <p>&lt; class ‘my_model.admin.SomeModelAdmin'>: (admin.E016) The value of 'form' must inherit from 'BaseModelForm'</p> </blockquote>
0
2016-09-22T14:24:39Z
39,641,821
<p>to your class SomeModelForm add something like this:</p> <pre><code>class Meta: model = YourModel fields = '__all__' </code></pre> <p>and change from forms.Form to forms.ModelForm</p>
0
2016-09-22T14:27:01Z
[ "python", "django", "file-upload", "admin" ]
Upload CSV file in django admin list view, replacing add object button
39,641,756
<p>I want to replace the add object button in the listview of an admin page. The underlying idea is that an administrator can download data on all models in the db, use a tool to edit the data, and then reupload as a CSV file. </p> <p>In the list view I am struggling to override the form, as setting </p> <pre><code>class SomeModelForm(forms.Form): csv_file = forms.FileField(required=False, label="please select a file") class Meta: model = MyModel fields = '__all__' class SomeModel(admin.ModelAdmin): change_list_template = 'admin/my_app/somemodel/change_list.html' form = SomeModelForm other stuff </code></pre> <p>The admin change_list.html is overridden as follows:</p> <pre><code>{% extends "admin/change_list.html" %} {% load i18n admin_urls admin_static admin_list %} {% block object-tools-items %} &lt;form action="{% url 'admin:custom_submit_row' %}" method="post" enctype="multipart/form-data"&gt; {% csrf_token %} &lt;p&gt; {{ form.as_p }} &lt;/p&gt; &lt;p&gt;&lt;input type="submit" value="Upload" /&gt;&lt;input type="reset" value="Reset"&gt;&lt;/p&gt; &lt;/form&gt; {% endblock %} </code></pre> <p>Previously SomeModel was missing the class Meta, as per sebbs response this is updated. The original error has been resolved but now currently the admin page is displaying the upload and reset buttons but no field for file uploads.</p> <p>cheers</p> <p>Edited with sebb's input below. Thanks sebb. The error fixed was </p> <blockquote> <p>&lt; class ‘my_model.admin.SomeModelAdmin'>: (admin.E016) The value of 'form' must inherit from 'BaseModelForm'</p> </blockquote>
0
2016-09-22T14:24:39Z
39,676,926
<p>OP here, solution is as follows:</p> <pre><code>class SomeModelForm(forms.Form): csv_file = forms.FileField(required=False, label="please select a file") class SomeModel(admin.ModelAdmin): change_list_template = 'admin/my_app/somemodel/change_list.html def get_urls(self): urls = super().get_urls() my_urls = patterns("", url(r"^upload_csv/$", self.upload_csv, name='upload_csv') ) return my_urls + urls urls = property(get_urls) def changelist_view(self, *args, **kwargs): view = super().changelist_view(*args, **kwargs) view.context_data['submit_csv_form'] = SomeModelForm return view def upload_csv(self, request): if request.method == 'POST': form = MineDifficultyResourceForm(request.POST, request.FILES) if form.is_valid(): do stuff </code></pre> <p>with the template overridden as so:</p> <pre><code>{% extends "admin/change_list.html" %} {% load i18n admin_urls admin_static admin_list %} {% block object-tools %} {% if has_add_permission %} &lt;div&gt; &lt;ul class="object-tools"&gt; {% block object-tools-items %} &lt;form id="upload-csv-form" action="{% url 'admin:upload_csv' %}" method="post" enctype="multipart/form-data"&gt; {% csrf_token %} &lt;p&gt;{{ form.non_field_errors }}&lt;/p&gt; &lt;p&gt;{{ submit_csv_form.as_p }}&lt;/p&gt; &lt;p&gt;{{ submit_csv_form.csv_file.errors }}&lt;/p&gt; &lt;p&gt;&lt;input type="submit" value="Upload" /&gt; &lt;input type="reset" value="Reset"&gt;&lt;/p&gt; &lt;/form&gt; {% endblock %} &lt;/ul&gt; &lt;/div&gt; {% endif %} {% endblock %} </code></pre> <p>The form needs some custom validation but otherwise this solves the difficult part of customizing the admin page.</p> <p>To elaborate what is going on here:</p> <ol> <li><p>get_urls is overridden so that an additional endpoint can be added to the admin page, this can point to any view, in this case it points upload_csv</p></li> <li><p>changelist_view is overridden to append the form info to the view</p></li> <li><p>the change_list.html template block "object-tools" is overridden with the form fields</p></li> </ol> <p>Hopefully someone else finds this helpful as well.</p>
0
2016-09-24T13:35:17Z
[ "python", "django", "file-upload", "admin" ]
can't define a udf inside pyspark project
39,641,770
<p>I have a python project that uses pyspark and i am trying to define a udf function inside the spark project (not in my python project) specifically in spark\python\pyspark\ml\tuning.py but i get pickling problems. it can't load the udf. The code:</p> <pre><code>from pyspark.sql.functions import udf, log test_udf = udf(lambda x : -x[1], returnType=FloatType()) d = data.withColumn("new_col", test_udf(data["x"])) d.show() </code></pre> <p>when i try d.show() i am getting exception of unknown attribute test_udf</p> <p>In my python project i defined many udf and it worked fine. </p>
-1
2016-09-22T14:25:10Z
39,646,290
<p>add the following to your code. It isn't recognizing the datatype.</p> <pre><code>from pyspark.sql.types import * </code></pre> <p>Let me know if this helps. Thanks.</p>
0
2016-09-22T18:23:38Z
[ "python", "pyspark", "udf", "apache-spark-ml" ]
can't define a udf inside pyspark project
39,641,770
<p>I have a python project that uses pyspark and i am trying to define a udf function inside the spark project (not in my python project) specifically in spark\python\pyspark\ml\tuning.py but i get pickling problems. it can't load the udf. The code:</p> <pre><code>from pyspark.sql.functions import udf, log test_udf = udf(lambda x : -x[1], returnType=FloatType()) d = data.withColumn("new_col", test_udf(data["x"])) d.show() </code></pre> <p>when i try d.show() i am getting exception of unknown attribute test_udf</p> <p>In my python project i defined many udf and it worked fine. </p>
-1
2016-09-22T14:25:10Z
39,646,961
<p>Found it there was 2 problems</p> <p>1) for some reason it didn't like the returnType=FloatType() i needed to convert it to just FloatType() though this was the signature</p> <p>2) The data in column x was a vector and for some reason i had to cast it to float</p> <p>The working code:</p> <pre><code>from pyspark.sql.functions import udf, log test_udf = udf(lambda x : -float(x[1]), FloatType()) d = data.withColumn("new_col", test_udf(data["x"])) d.show() </code></pre>
0
2016-09-22T19:01:19Z
[ "python", "pyspark", "udf", "apache-spark-ml" ]
Python REGEX ignore case at the beginning of the sentence and take the rest
39,641,833
<p>I have this kind of results:</p> <pre><code>ª!è[008:58:049]HTTP_CLI:0 - Line written in... </code></pre> <p>And I want to ignore all the beginning characters like <code>ª!è</code> and get only: <code>HTTP_CLI:0 - Line written in...</code> but in a simple regex line. </p> <p>I tried this: <code>^[\W0-9]*</code> but is taking the extended ASCII characters plus the time and is not ignoring it, is doing the opposite...</p> <p>Any help?</p> <p>Thanks!</p>
0
2016-09-22T14:27:24Z
39,642,129
<p>If you want to get everything after the closing square bracket, no matter what, and skip everything before that you can go with a <code>match</code> like this:</p> <pre><code>s = "ª!è[008:58:049]HTTP_CLI:0 - Line written in..." m = re.match(r'^.*?]([\S\s]*)', s) print(m.group(1)) </code></pre> <p>Print's <code>'HTTP_CLI:0 - Line written in...'</code></p> <p>This expression looks through an arbitrary number of characters before the closing bracket and matches everything after that. The matched group is available with <code>m.group(1)</code></p>
2
2016-09-22T14:40:46Z
[ "python", "regex", "ignore-case" ]
VS2015 linker error with python extension
39,641,868
<p>I'm trying to build my own python (3.5.2) c extension that depends on zlib. With gcc on linux it works perfectly but I can't seem to make it work on windows 64-bit.</p> <p>I installed zlib dll according to the instructions:</p> <pre><code>Installing ZLIB1.DLL ==================== Copy ZLIB1.DLL to the SYSTEM or the SYSTEM32 directory. Using ZLIB1.DLL with Microsoft Visual C++ ========================================= 1. Install the supplied header files "zlib.h" and "zconf.h" into a directory found in the INCLUDE path list. 2. Install the supplied library file "zdll.lib" into a directory found in the LIB path list. 3. Add "zdll.lib" to your project. </code></pre> <p>My setup.py:</p> <pre><code>from setuptools import setup, Extension from Cython.Build import cythonize setup( ext_modules=cythonize([Extension("esp", ["bethlib/esp.pyx", "bethlib/c_esp.c", "bethlib/linked_list.c"], libraries=["zdll"], include_dirs=["include"], library_dirs=["lib"])]), ) </code></pre> <p>Trying to build with <code>python setup.py bdist_wheel</code> gives the error:</p> <pre><code>c_esp.obj : error LNK2001: unresolved external symbol uncompress build\lib.win-amd64-3.5\esp.cp35-win_amd64.pyd : fatal error LNK1120: 1 unresolved externals error: command 'E:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\link.exe' failed with exit status 1120 </code></pre> <p><code>uncompress</code> is a valid function present in zlib.h. Any solutions? Thanks!</p>
0
2016-09-22T14:28:48Z
39,644,837
<p>I downloaded the static zlib lib from <a href="http://www.winimage.com/zLibDll/index.html" rel="nofollow">this website</a> and it works. It's for an older version so I'd still appreciate if I could get a more current version but for now it's enough.</p>
0
2016-09-22T16:58:06Z
[ "python", "c", "zlib" ]
Python development on private network--no pip
39,641,963
<p>The company I work for has taken measures to make our IT assets more secure. As such, I use a computer on a private network which has <strong><em>no</em></strong> access to the Internet. Developing Python software in this environment is very difficult at times. I cannot pip install anything. Downloading, copying, and installing packages locally is the only option that I have found and this is hit-and-miss as dependencies are a constant and recursive issue. I am looking for a better solution. I hope to find something like this:</p> <ol> <li>A tool that will allow for setting up an environment on a machine with Internet access and copying that environment to the isolated machine.</li> <li>A tool that will allow for a specifying a package and then will pack it and all of its dependencies for download.</li> <li>Some other clever solution.</li> </ol> <p>Has anyone solved this?</p>
0
2016-09-22T14:33:09Z
39,642,047
<p>You can install <a href="http://doc.devpi.net/latest/" rel="nofollow">devpi</a> in a server, there you can host some pypi packages or upload your own.</p> <p>It's compatible with pip, so it won't break your workflow, you just need to point your pip.conf to use your local devpi</p>
0
2016-09-22T14:36:42Z
[ "python", "pip" ]
Python CSV Error
39,641,984
<p>Hello all I keep getting this error while making a small program to sort large CSV files out, below is my code and error, what am I doing wrong?</p> <pre><code>if selection: for stuff in stuffs: try: textFile = open("output.txt",'w') mycsv = csv.reader(open(stuff)) d_reader = csv.DictReader(mycsv) headers = d_reader.fieldnames &lt;-- Error happens here if selection in headers: placeInList = headers.index(selection) #placeInList = selection.index(selection) for selection in tqdm(mycsv, desc='Extracting column values...', leave = True): textFile.write(str(selection[int(placeInList)])+'\n') print 'Done!' textFile.close() sys.exit() except IOError: print 'No CSV file present in directory' sys.exit() else: sys.exit() </code></pre> <p>And the error:</p> <pre><code>Traceback (most recent call last): File "postcodeExtractor.py", line 27, in &lt;module&gt; headers = d_reader.fieldnames File "C:\Python27\lib\csv.py", line 90, in fieldnames self._fieldnames = self.reader.next() TypeError: expected string or Unicode object, list found </code></pre>
0
2016-09-22T14:33:50Z
39,642,312
<p>instead of </p> <pre><code>mycsv = csv.reader(open(stuff)) d_reader = csv.DictReader(mycsv) </code></pre> <p>you want </p> <pre><code>d_reader = csv.DictReader(open(stuff)) </code></pre> <p>the first line is the problem.</p>
0
2016-09-22T14:49:40Z
[ "python", "python-2.7", "csv" ]
Django 1.9 URLField removing the necessary http:// prefix
39,642,003
<p>I've seen a bunch of questions about this, but havent found an answer yet. </p> <p>This is my models:</p> <pre><code>class UserProfile(models.Model): user = models.OneToOneField(User) . . . website = models.URLField(max_length=100, blank=True, null=True) </code></pre> <p>and my forms.py:</p> <pre><code>class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('website') def clean_website(self): website = self.cleaned_data['website'] if website and not website.startswith('http://'): website = 'http://' + website return website # def clean(self): # cleaned_data = self.cleaned_data # url = cleaned_data.get('url') # # if url and not url.startswith('http://'): # url = 'http://' + url # cleaned_data['url'] = url # return cleaned_data </code></pre> <p>I've tried to clean the web address, but I the way django is set up I dont have an opportunity to get to the clean functions. <a href="http://i.stack.imgur.com/jSIYV.png" rel="nofollow"><img src="http://i.stack.imgur.com/jSIYV.png" alt="enter image description here"></a></p> <p>How can I change Django to allow user the ability to not put in the http(s):// prefix?</p> <p>I don't want to initialize it with this type of code:</p> <pre><code>url = forms.URLField(max_length=200, help_text="input page URL", initial='http://') </code></pre> <p>I've seen this thread:<a href="http://stackoverflow.com/questions/16307055/django-urlfield-http-prefix">django urlfield http prefix</a> But admittedly am not sure where to put it to see if it even works.</p>
1
2016-09-22T14:34:44Z
39,642,072
<p>This validation isn't being done by Django, but by your browser itself. You can disable that by putting <code>novalidate</code> in the surrounding <code>&lt;form&gt;</code> element.</p>
2
2016-09-22T14:37:57Z
[ "python", "django", "django-models", "django-forms", "django-urls" ]
How do I group all my functions in Python into one function?
39,642,008
<p>I am using the Turtles Module where I am creating a U.S. Flag. The user decides the size of the flag and with that size I will be using it to create the width and length. </p> <p>I am trying to group/compress all of my subfunctions into one huge function so the user can simply type <code>Draw_USAFlag(t, w) ## T = turtle W = Size</code> and it will carry out the task of the 5 functions that I already have.</p> <p>For example I have 2 subfunctions: <code>draw_rectangle(t, w)</code> and <code>draw_stripes (t, w) ;</code> I want to group these two subfunctions into one function that will be called <code>Draw_USAFlag(t, w)</code> where it will use the user inputted <code>size (w)</code> throughout all of the functions. Any help is greatly appreciated! Thanks!</p>
2
2016-09-22T14:34:54Z
39,642,569
<p>Quite simply, make a function that calls the others:</p> <pre><code>def draw_rectangle(t, w): # however you do this ... def draw_rectangle(t, w): # however you do this ... def Draw_USAFlag(t, w): draw_rectangle(t, w) draw_stripes(t, w) </code></pre> <p>This assumes they don't return anything, so whatever they do works by side-effects on some other object. If e.g. they return an image, this will need changing depending on the exact structure of your system.</p>
0
2016-09-22T15:01:55Z
[ "python" ]
Robotframework: Clicking web-elemnt in loop often fails to find an element
39,642,064
<p>I have created a keyword for RF and Selenium2Library. It is supposed to wait for some element by clicking periodically on some other element which will renew the area where the element is supposed to appear. I use it for example for waiting for mails in postbox.</p> <p>The problem is that pretty often the "renew element" cannot be found and clicked on some loop iteration however it exists on the screenshot. Any ideas why it can happen?</p> <pre><code>def check_if_element_appeared(self, element_locator, renew_locator, renew_interval=10, wait_interval=300): if not self.is_visible(renew_locator): raise AssertionError("Error Message") start_time=int(time()) scan_time = start_time if not self.is_visible(element_locator): while int(time())&lt;=start_time+wait_interval: if int(time()) &gt;= scan_time + renew_interval: scan_time = int(time()) self.click_element(renew_locator) if self.is_visible(element_locator): break if not self.is_visible(element_locator): raise AssertionError("Error Message") self._info("Message") else: self._info("Current page contains element '%s'." % element_locator) </code></pre>
1
2016-09-22T14:37:27Z
39,651,575
<p>Shouldn't be using the keywords <code>Wait Until Page Contains Element</code> or <code>Wait Until Element Is Visible</code> of the <a href="http://robotframework.org/Selenium2Library/Selenium2Library.html" rel="nofollow">Selenium2Library</a> for this purpose:</p> <pre><code>*** Test cases *** Your Test Case Prerequisite steps Wait Until Page Contains Element ${locator} Succeeding steps </code></pre> <p><strong>Edit:</strong> Below is what your Python code might look like in pure Robot syntax.</p> <pre><code>${iteration}= Evaluate ${wait_interval} / ${renew_interval} : FOR ${i} IN RANGE 0 ${iteration} \ Click Element ${renew_locator} \ Sleep 1 \ ${is_visible}= Run Keyword And Return Status Element Should Be Visible ${element_locator} \ Exit For Loop If ${is_visible} \ Run Keyword If '${is_visible}' == 'False' Sleep ${renew_interval} Click Element ${element_locator} </code></pre>
0
2016-09-23T02:19:36Z
[ "python", "selenium", "robotframework" ]
keep filename while uploading an url with python response library
39,642,077
<p>I am using python to upload a file to an api with</p> <pre><code>url = 'http://domain.tld/api/upload' files = {'file': open('image.jpg', 'rb')} r = requests.post(url, files=files) </code></pre> <p>this works well and my file is uploaded to the server as <code>image.jpg</code>. Now I don't have a local files but an uri instead, so I changed my code to:</p> <pre><code>url = 'http://domain.tld/api/upload' files = {'file': urlopen('http://domain.tld/path/to/image.jpg')} r = requests.post(url, files=files) </code></pre> <p>the image is also uploaded sucessfully but it does not preserve it's name and is stored as 'file' (without extension). My question is, how can I upload an url while keeping it's filename (Of course without downloading it first)</p>
1
2016-09-22T14:38:12Z
39,645,135
<p>You can pass the name:</p> <pre><code> files = {'name': ('image.jpg', urlopen('http://domain.tld/path/to/image.jpg'))} </code></pre> <p>If you look at the post body you will see for your variation:</p> <pre><code>Content-Disposition: form-data; name="file"; filename="file" </code></pre> <p>And using the code above:</p> <pre><code>Content-Disposition: form-data; name="name"; filename="image.jpg" </code></pre> <p>You can see the name is retained in the latter.</p>
0
2016-09-22T17:16:58Z
[ "python", "python-requests" ]
Convert txt to csv python script
39,642,082
<p>I have a .txt file with this inside - 2.9,Gardena CA</p> <p>What I'm trying to do is convert that text into a .csv (table) using a python script: </p> <pre><code>import csv import itertools with open('log.txt', 'r') as in_file: stripped = (line.strip() for line in in_file) lines = (line for line in stripped if line) grouped = itertools.izip(*[lines] * 3) with open('log.csv', 'w') as out_file: writer = csv.writer(out_file) writer.writerow(('title', 'intro')) writer.writerows(grouped) </code></pre> <p>The output I get in the log.csv file is - title,intro,tagline</p> <p>What I would want the log.csv file to show is:</p> <pre><code>title,intro 2.9,Gardena CA </code></pre>
0
2016-09-22T14:38:29Z
39,642,543
<p>You need to split the line first.</p> <pre><code>import csv with open('log.txt', 'r') as in_file: stripped = (line.strip() for line in in_file) lines = (line.split(",") for line in stripped if line) with open('log.csv', 'w') as out_file: writer = csv.writer(out_file) writer.writerow(('title', 'intro')) writer.writerows(lines) </code></pre>
0
2016-09-22T15:00:51Z
[ "python", "csv", "text" ]
Convert txt to csv python script
39,642,082
<p>I have a .txt file with this inside - 2.9,Gardena CA</p> <p>What I'm trying to do is convert that text into a .csv (table) using a python script: </p> <pre><code>import csv import itertools with open('log.txt', 'r') as in_file: stripped = (line.strip() for line in in_file) lines = (line for line in stripped if line) grouped = itertools.izip(*[lines] * 3) with open('log.csv', 'w') as out_file: writer = csv.writer(out_file) writer.writerow(('title', 'intro')) writer.writerows(grouped) </code></pre> <p>The output I get in the log.csv file is - title,intro,tagline</p> <p>What I would want the log.csv file to show is:</p> <pre><code>title,intro 2.9,Gardena CA </code></pre>
0
2016-09-22T14:38:29Z
39,642,701
<p>I suposse this is the output you need:</p> <blockquote> <p>title,intro,tagline</p> <p>2.9,Gardena,CA</p> </blockquote> <p>It can be done with this changes to your code:</p> <pre><code>import csv import itertools with open('log.txt', 'r') as in_file: lines = in_file.read().splitlines() stripped = [line.replace(","," ").split() for line in lines] grouped = itertools.izip(*[stripped]*1) with open('log.csv', 'w') as out_file: writer = csv.writer(out_file) writer.writerow(('title', 'intro', 'tagline')) for group in grouped: writer.writerows(group) </code></pre>
0
2016-09-22T15:08:27Z
[ "python", "csv", "text" ]
How to Clear the window in tkinter (Python)?
39,642,102
<p>I want to hide/remove all the buttons from my window (temporarily) with the "hide_widgets" function so I can put them back after but its just not working for me, I have tried using <code>grid_hide()</code> and <code>destroy()</code> and anything I have tried so for from searching stackoverflow as not worked either.</p> <p>Here is my program so far:</p> <pre><code>from tkinter import * class Application(Frame): #GUI Application def __init__(self, master): #Initialize the Frame Frame.__init__(self,master) self.grid() self.create_widgets() def create_widgets(self): #Create new game etc... #Title self.title = Label(self,text = "Gnome") self.title.grid() #New Game self.new_game = Button(self,text = "New Game") self.new_game ["command"] = self.create_new_game self.new_game.grid() #Load Game self.load_game = Button(self,text = "Load Game") self.load_game ["command"] = self.display_saves self.load_game.grid() #Settings self.settings = Button(self,text = "Settings") self.settings ["command"] = self.display_settings self.settings.grid() #Story self.story = Button(self,text = "Story") self.story ["command"] = self.display_story self.story.grid() #Credits self.credits = Button(self,text = "Credits") self.credits ["command"] = self.display_credits self.credits.grid() def hide_widgets(self): #clear window new_game.grid_forget() def create_new_game(self): #Create new game file self.hide_widgets self.instruction = Label(self, text = "Name World:") self.instruction.grid() self.world_name = Entry(self) self.world_name.grid() def display_saves(self): #display saved games and allow to run print("saves") def display_settings(self): #display settings and allow to alter print("settings") def display_story(self): #display story print("story") def display_credits(self): #display credits print("credits") root = Tk() root.title("Welcome") width, height = root.winfo_screenwidth(), root.winfo_screenheight() root.geometry('%dx%d+0+0' % (width,height)) app = Application(root) root.mainloop() </code></pre> <p>Thank you in advance.</p>
1
2016-09-22T14:39:22Z
39,642,289
<p>You can hide the <code>Button</code>s by calling each one's <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/grid-methods.html" rel="nofollow"><code>grid_forget()</code></a> method.</p> <p>To make that easier you might want to create a <code>self.buttons</code> list or dictionary that contains them all.</p> <p>Alternatively there's also a <code>grid_slaves()</code> method you might be able to use on the <code>Application</code> instance that will give you a list of all the widgest it manages (or just the ones in a specified row or column). The <code>Button</code>s should be in one of these lists. I've never used it, so I don't know how easy it would be to identify them in the list returned however.</p>
1
2016-09-22T14:48:34Z
[ "python", "python-3.x", "user-interface", "tkinter", "clear" ]
How to Clear the window in tkinter (Python)?
39,642,102
<p>I want to hide/remove all the buttons from my window (temporarily) with the "hide_widgets" function so I can put them back after but its just not working for me, I have tried using <code>grid_hide()</code> and <code>destroy()</code> and anything I have tried so for from searching stackoverflow as not worked either.</p> <p>Here is my program so far:</p> <pre><code>from tkinter import * class Application(Frame): #GUI Application def __init__(self, master): #Initialize the Frame Frame.__init__(self,master) self.grid() self.create_widgets() def create_widgets(self): #Create new game etc... #Title self.title = Label(self,text = "Gnome") self.title.grid() #New Game self.new_game = Button(self,text = "New Game") self.new_game ["command"] = self.create_new_game self.new_game.grid() #Load Game self.load_game = Button(self,text = "Load Game") self.load_game ["command"] = self.display_saves self.load_game.grid() #Settings self.settings = Button(self,text = "Settings") self.settings ["command"] = self.display_settings self.settings.grid() #Story self.story = Button(self,text = "Story") self.story ["command"] = self.display_story self.story.grid() #Credits self.credits = Button(self,text = "Credits") self.credits ["command"] = self.display_credits self.credits.grid() def hide_widgets(self): #clear window new_game.grid_forget() def create_new_game(self): #Create new game file self.hide_widgets self.instruction = Label(self, text = "Name World:") self.instruction.grid() self.world_name = Entry(self) self.world_name.grid() def display_saves(self): #display saved games and allow to run print("saves") def display_settings(self): #display settings and allow to alter print("settings") def display_story(self): #display story print("story") def display_credits(self): #display credits print("credits") root = Tk() root.title("Welcome") width, height = root.winfo_screenwidth(), root.winfo_screenheight() root.geometry('%dx%d+0+0' % (width,height)) app = Application(root) root.mainloop() </code></pre> <p>Thank you in advance.</p>
1
2016-09-22T14:39:22Z
39,643,235
<p>Have you tried replacing <code>new_game.grid_forget()</code> with <code>self.new_game.grid_forget()</code>?</p> <p>Check <a href="http://stackoverflow.com/a/68324/6836841">this</a> answer out for an explanation as to why <code>self</code> needs to be referenced explicitly. I ran a very simple script to test this behavior and it worked fine.</p>
0
2016-09-22T15:33:32Z
[ "python", "python-3.x", "user-interface", "tkinter", "clear" ]
How to Clear the window in tkinter (Python)?
39,642,102
<p>I want to hide/remove all the buttons from my window (temporarily) with the "hide_widgets" function so I can put them back after but its just not working for me, I have tried using <code>grid_hide()</code> and <code>destroy()</code> and anything I have tried so for from searching stackoverflow as not worked either.</p> <p>Here is my program so far:</p> <pre><code>from tkinter import * class Application(Frame): #GUI Application def __init__(self, master): #Initialize the Frame Frame.__init__(self,master) self.grid() self.create_widgets() def create_widgets(self): #Create new game etc... #Title self.title = Label(self,text = "Gnome") self.title.grid() #New Game self.new_game = Button(self,text = "New Game") self.new_game ["command"] = self.create_new_game self.new_game.grid() #Load Game self.load_game = Button(self,text = "Load Game") self.load_game ["command"] = self.display_saves self.load_game.grid() #Settings self.settings = Button(self,text = "Settings") self.settings ["command"] = self.display_settings self.settings.grid() #Story self.story = Button(self,text = "Story") self.story ["command"] = self.display_story self.story.grid() #Credits self.credits = Button(self,text = "Credits") self.credits ["command"] = self.display_credits self.credits.grid() def hide_widgets(self): #clear window new_game.grid_forget() def create_new_game(self): #Create new game file self.hide_widgets self.instruction = Label(self, text = "Name World:") self.instruction.grid() self.world_name = Entry(self) self.world_name.grid() def display_saves(self): #display saved games and allow to run print("saves") def display_settings(self): #display settings and allow to alter print("settings") def display_story(self): #display story print("story") def display_credits(self): #display credits print("credits") root = Tk() root.title("Welcome") width, height = root.winfo_screenwidth(), root.winfo_screenheight() root.geometry('%dx%d+0+0' % (width,height)) app = Application(root) root.mainloop() </code></pre> <p>Thank you in advance.</p>
1
2016-09-22T14:39:22Z
39,643,376
<p>Ok I got it working now, silly me forgot "()" in <code>self.hide_widgets()</code>, i just never thought about it because there was no error as it was creating a variable instead.</p>
0
2016-09-22T15:40:37Z
[ "python", "python-3.x", "user-interface", "tkinter", "clear" ]
Selecting all records id's from Odoo Contacts listview
39,642,143
<p>I have written some python code in my .py file to display an wizard</p> <pre><code>class DisplayWindow(models.Model): _inherit = 'res.partner' wizard_id = fields.Many2one('sale.example_wizard') def result_to_search(self, cr, uid, active_ids): wizard = self.pool['sale.example_wizard'].create(cr, uid, vals={ 'partner_ids': [(6, 0, active_ids)] }) return { 'name': _('Account Search'), 'type': 'ir.actions.act_window', 'res_model': 'sale.example_wizard', 'res_id': wizard, 'view_type': 'form', 'view_mode': 'form', 'target': 'new', } </code></pre> <p>and here is my .xml file</p> <pre><code>&lt;openerp&gt; &lt;data&gt; &lt;!--This xml file is responsible for the server action of displaying the wizard--&gt; &lt;record model="ir.actions.server" id="action_search_for_result"&gt; &lt;field name="name"&gt;Account Search&lt;/field&gt; &lt;field name="model_id" ref="sale.model_res_partner"/&gt; &lt;field name="code"&gt; if context.get('active_model') == 'res.partner' and context.get('active_ids'): action = self.pool['res.partner'].result_to_search(cr, uid, context.get('active_ids')) &lt;/field&gt; &lt;/record&gt; &lt;record model="ir.values" id="search_result"&gt; &lt;field name="model_id" ref="sale.model_res_partner"/&gt; &lt;field name="name"&gt;Account Search&lt;/field&gt; &lt;field name="key2"&gt;client_action_multi&lt;/field&gt; &lt;!--automatically attach action to the dropdown button--&gt; &lt;field name="value" eval="'ir.actions.server,' +str(ref('action_search_for_result'))"/&gt; &lt;field name="key"&gt;action&lt;/field&gt; &lt;field name="model"&gt;res.partner&lt;/field&gt; &lt;/record&gt; &lt;/data&gt; &lt;/openerp&gt; </code></pre> <p>My problem is that when I am selecting all customers from cutomers' listview it's only selecting first page contacts and whatever code I have written for wizard's button it's only working for that first page's customers.But my desired result suppose to work on all the customers which I have in database. Probably I am doing something wrong with this piece of code </p> <pre><code>wizard = self.pool['sale.example_wizard'].create(cr, uid, vals={ 'partner_ids': [(6, 0, active_ids)] }) </code></pre> <p>Please help me. I can explain more if needed. Thanks</p>
0
2016-09-22T14:41:12Z
39,645,438
<p>You can get selected record by using following code.</p> <pre><code>wizard = self.pool['sale.example_wizard'].create(cr, uid, vals={ 'partner_ids': [(6, 0, self._context.get('active_ids',[]))] }) </code></pre> <p>Thanks</p>
0
2016-09-22T17:35:05Z
[ "python", "xml", "listview", "odoo-9" ]
Bind a button already on_press
39,642,263
<p>I want to change the function which is launched when my button is pressed.</p> <p>Python file:</p> <pre><code>class UpdateScreen(Screen): swimbot = {} def swimbot_connected(self): wallouh = list(AdbCommands.Devices()) if not wallouh: self.ids['text_label'].text = 'Plug your Swimbot and try again' else: for devices in AdbCommands.Devices(): output = devices.serial_number if re.match("^(.*)swimbot", output): self.ids['mylabel'].text = 'Etape 2: Do you need an update ?' self.ids['action_button'].text = 'Check' self.ids['action_button'].bind(on_press = self.check_need_update()) else: self.ids['text_label'].text = 'Plug your Swimbot and try again' </code></pre> <p>Kv file :</p> <pre><code>&lt;UpdateScreen&gt;: BoxLayout: id: update_screen_layout orientation: 'vertical' Label: id: mylabel text: "Etape 1: Connect your Swimbot" font_size: 26 Label: id: text_label text: "Truc" font_size: 24 FloatLayout: size: root.size pos: root.pos Button: id: action_button pos_hint: {'x': .05, 'y':.25} size_hint: (.9, .4) text: "Try" font_size: 24 on_press: root.swimbot_connected() </code></pre> <p>But i think It's not the right way to do that with this :</p> <pre><code>self.ids['action_button'].bind(on_press = self.check_need_update()) </code></pre> <p>With that I go directly to check_need_update(), it doesn't wait I press the button.</p>
0
2016-09-22T14:47:21Z
39,649,044
<p>When you put <code>()</code> after a function in python you execute that function. So when you type</p> <pre><code>self.ids['action_button'].bind(on_press = self.check_need_update()) </code></pre> <p>You will actually pass the result of self.check_needed_update to <code>on_press</code>. So you need:</p> <pre><code>self.ids['action_button'].bind(on_press = self.check_need_update) </code></pre> <p>This is different in kv language. There you actually need to put <code>()</code> when binding a function. You can also put arguments there that will get evaluated when the callback is called (and not when the definition get read).</p> <p>But the python code will actually not do what you want. It will bind an additional function to that button, but it will not overwrite the other function. You can unbind callbacks but it's a bit complicated (see <a href="https://kivy.org/docs/api-kivy.event.html#kivy.event.EventDispatcher.unbind" rel="nofollow">the documentation here</a>).</p> <p>Instead I would change the called function in a way that it behaves differently:</p> <pre><code>class UpdateScreen(Screen): state = 0 swimbot = {} def swimbot_connected(self): if state == 0: self._original_swimbot_connected() if state == 1: self.check_need_update </code></pre> <p>And then instead of unbinding and binding a new function to the button you can just modify <code>UpdateScreen.state</code>.</p>
0
2016-09-22T21:19:26Z
[ "python", "button", "kivy", "bind" ]
How to remove everything (except certain characters) after the last number in a string
39,642,368
<p>This is a follow-up of <a href="http://stackoverflow.com/questions/39637955/how-to-remove-everything-after-the-last-number-in-a-string">this question.</a></p> <p>There I learned how to remove all characters after the last number in a string; so I can turn</p> <pre><code>w = 'w123 o456 t789-- --' </code></pre> <p>into</p> <pre><code>w123 o456 t789 </code></pre> <p>Now I might have strings like this:</p> <pre><code>w = 'w123 o456 (t789)' </code></pre> <p>In this case, </p> <pre><code>re.sub(r'\D+$', '', w) </code></pre> <p>would give me</p> <pre><code>w123 o456 (t789 </code></pre> <p>So I have then actually two closely related questions:</p> <p>1) How can I modify the command <code>re.sub(r'\D+$', '', w)</code> in a way that certain characters are kept (e.g. parenthesis)? </p> <p>2) How can I modify the command <code>re.sub(r'\D+$', '', w)</code> so that only certain characters are removed (e.g. dashes and white spaces)?</p> <p><strong>EDIT</strong></p> <p>@Martin Bonner's answer gets very close but e.g. for </p> <pre><code>w='w123 -o456 t789--) --' </code></pre> <p>the command</p> <pre><code> re.sub('[- ]+$', '', w) </code></pre> <p>gives me <code>w123 -o456 t789--)</code> but it should also get rid of the remaining dashes.</p>
0
2016-09-22T14:52:26Z
39,642,446
<p>To keep certain characters <code>(</code> and <code>)</code> use:</p> <pre><code>re.sub('[^0-9()]+$', '', w) </code></pre> <p>to remove only certain characters from the end of the line:</p> <pre><code>re.sub('[- ]+$', '', w) </code></pre> <p>In square brackets, you can list the characters you want to match. If the first character is <code>^</code> then everything <em>except</em> the specified characters are matched. The only minor niggle is that <code>-</code> usually specifies a range (so we can specify, eg, all digits without having to list all 10 of them). That means that if we are going to specify <code>-</code> as one of the characters to match, it needs to go <em>first</em>. (If you want to specify <code>^</code>, then escape it with <code>\</code> and go back to raw strings.)</p> <p>From the comment, I think you actually meant the second challenge to be "remove all the dashes and spaces from the string that lie between the last digit, and the end of the line". That may be possible with a regular expression, but somebody who comes back to maintain the code in three months time will hate you (and it may well be you). Just remember the Jamie Zawinski quote:</p> <blockquote> <p>Some people, when confronted with a problem, think “I know, I'll use regular expressions.” Now they have two problems.</p> </blockquote>
4
2016-09-22T14:56:26Z
[ "python", "regex" ]
How to remove everything (except certain characters) after the last number in a string
39,642,368
<p>This is a follow-up of <a href="http://stackoverflow.com/questions/39637955/how-to-remove-everything-after-the-last-number-in-a-string">this question.</a></p> <p>There I learned how to remove all characters after the last number in a string; so I can turn</p> <pre><code>w = 'w123 o456 t789-- --' </code></pre> <p>into</p> <pre><code>w123 o456 t789 </code></pre> <p>Now I might have strings like this:</p> <pre><code>w = 'w123 o456 (t789)' </code></pre> <p>In this case, </p> <pre><code>re.sub(r'\D+$', '', w) </code></pre> <p>would give me</p> <pre><code>w123 o456 (t789 </code></pre> <p>So I have then actually two closely related questions:</p> <p>1) How can I modify the command <code>re.sub(r'\D+$', '', w)</code> in a way that certain characters are kept (e.g. parenthesis)? </p> <p>2) How can I modify the command <code>re.sub(r'\D+$', '', w)</code> so that only certain characters are removed (e.g. dashes and white spaces)?</p> <p><strong>EDIT</strong></p> <p>@Martin Bonner's answer gets very close but e.g. for </p> <pre><code>w='w123 -o456 t789--) --' </code></pre> <p>the command</p> <pre><code> re.sub('[- ]+$', '', w) </code></pre> <p>gives me <code>w123 -o456 t789--)</code> but it should also get rid of the remaining dashes.</p>
0
2016-09-22T14:52:26Z
39,643,015
<p>You may use another re.sub in the callback as the replacement pattern.</p> <pre><code>re.sub(r'\D+$', lambda m: re.sub(r'[^()]+','',m.group(0)), s) </code></pre> <p>Here, you match all symbols other than digits at the end of the string, pass that value to the callback, and all symbols other than <code>(</code> and <code>)</code> are removed from that value.</p>
1
2016-09-22T15:23:30Z
[ "python", "regex" ]
How to remove everything (except certain characters) after the last number in a string
39,642,368
<p>This is a follow-up of <a href="http://stackoverflow.com/questions/39637955/how-to-remove-everything-after-the-last-number-in-a-string">this question.</a></p> <p>There I learned how to remove all characters after the last number in a string; so I can turn</p> <pre><code>w = 'w123 o456 t789-- --' </code></pre> <p>into</p> <pre><code>w123 o456 t789 </code></pre> <p>Now I might have strings like this:</p> <pre><code>w = 'w123 o456 (t789)' </code></pre> <p>In this case, </p> <pre><code>re.sub(r'\D+$', '', w) </code></pre> <p>would give me</p> <pre><code>w123 o456 (t789 </code></pre> <p>So I have then actually two closely related questions:</p> <p>1) How can I modify the command <code>re.sub(r'\D+$', '', w)</code> in a way that certain characters are kept (e.g. parenthesis)? </p> <p>2) How can I modify the command <code>re.sub(r'\D+$', '', w)</code> so that only certain characters are removed (e.g. dashes and white spaces)?</p> <p><strong>EDIT</strong></p> <p>@Martin Bonner's answer gets very close but e.g. for </p> <pre><code>w='w123 -o456 t789--) --' </code></pre> <p>the command</p> <pre><code> re.sub('[- ]+$', '', w) </code></pre> <p>gives me <code>w123 -o456 t789--)</code> but it should also get rid of the remaining dashes.</p>
0
2016-09-22T14:52:26Z
39,643,040
<p>If there is always 3 groups of characters and each group start's with a single letter and has 3 digits after that, and only the last group might have brackets, this expression might be just what you need:</p> <pre><code>w = 'w123 o456 (t789)' clean = re.sub(r'^.*(\w\d{3})[ -]+(\w\d{3})[ -]+(\(?\w\d{3}\)?).*$', r'\1 \2 \3', w) </code></pre> <p><code>clean</code> now prints <code>'w123 o456 (t789)'</code> even if there are some other characters at the beginning or end of string.</p> <p>This expression look's for 3 groups of characters each consisting of a letter and 3 digits. For the last group there are optional brackets - <code>\(?</code> and <code>\)?</code>. All characters before and after the 3 groups are matched with <code>^.*</code> and <code>.*$</code>. Then we replace everything with just the 3 captured groups - <code>\1 \2 \3</code></p>
1
2016-09-22T15:25:00Z
[ "python", "regex" ]
How to remove everything (except certain characters) after the last number in a string
39,642,368
<p>This is a follow-up of <a href="http://stackoverflow.com/questions/39637955/how-to-remove-everything-after-the-last-number-in-a-string">this question.</a></p> <p>There I learned how to remove all characters after the last number in a string; so I can turn</p> <pre><code>w = 'w123 o456 t789-- --' </code></pre> <p>into</p> <pre><code>w123 o456 t789 </code></pre> <p>Now I might have strings like this:</p> <pre><code>w = 'w123 o456 (t789)' </code></pre> <p>In this case, </p> <pre><code>re.sub(r'\D+$', '', w) </code></pre> <p>would give me</p> <pre><code>w123 o456 (t789 </code></pre> <p>So I have then actually two closely related questions:</p> <p>1) How can I modify the command <code>re.sub(r'\D+$', '', w)</code> in a way that certain characters are kept (e.g. parenthesis)? </p> <p>2) How can I modify the command <code>re.sub(r'\D+$', '', w)</code> so that only certain characters are removed (e.g. dashes and white spaces)?</p> <p><strong>EDIT</strong></p> <p>@Martin Bonner's answer gets very close but e.g. for </p> <pre><code>w='w123 -o456 t789--) --' </code></pre> <p>the command</p> <pre><code> re.sub('[- ]+$', '', w) </code></pre> <p>gives me <code>w123 -o456 t789--)</code> but it should also get rid of the remaining dashes.</p>
0
2016-09-22T14:52:26Z
39,643,512
<p>Instead of Regex, why not use list comprehension (this auto keeps letters and digits if you don't want certain letters or digits we can change it too):</p> <pre><code>w = 'w123 o456 t789-- --' list_to_keep =[' '] print(''.join([x for x in w if x.isalnum() or x in list_to_keep])) &gt;&gt; w123 o456 t789 w = 'w123 o456 (t789)' list_to_keep =[' '] # add to me print(''.join([x for x in w if x.isalnum() or x in list_to_keep])) &gt;&gt; w123 o456 t789 </code></pre> <p>and for example:</p> <pre><code>w = 'w123 o456 (t789)' list_to_keep =[' ', '('] # add to me (I added '(' to keep for example) print(''.join([x for x in w if x.isalnum() or x in list_to_keep])) &gt;&gt; w123 o456 (t789 </code></pre> <p>and it works against what you edited saying Martin doesn't work:</p> <pre><code>w='w123 -o456 t789--) --' list_to_keep =[' '] # add to me (I added '(' to keep for example) print(''.join([x for x in w if x.isalnum() or x in list_to_keep])) &gt;&gt; w123 o456 t789 </code></pre>
1
2016-09-22T15:47:55Z
[ "python", "regex" ]
How to make equal space between words - python
39,642,374
<p>(SORRY FOR BAD ENGLISH) Im working at cmd. I want to do that thing:</p> <pre><code>file_name DIR file_name_3 DIR file_name_545 DIR file_name_LlK DIR </code></pre> <p>Instead of doing that thing:</p> <pre><code>file_name DIR file_name_3 DIR file_name_545 DIR file_name_LlK DIR </code></pre> <p>I tryied to do this in loop:</p> <pre><code>print data.ljust((20 - len(data) + 20)) if len(data) &lt;= 20 else (data[0:17] + '...').ljust(20)), 'DIR' </code></pre> <p>But that thing not working becase there are letters bigger then another, then 'ljust' the words makes it not possible.</p>
0
2016-09-22T14:52:38Z
39,642,568
<p>Use format strings.</p> <pre><code>"{:20}{}".format(data,"DIR") </code></pre> <p>The same with <code>ljkust()</code></p> <pre><code>data.ljust(20) + "DIR" </code></pre> <p>See <code>help(str.ljust)</code> to understand <code>ljust</code></p>
0
2016-09-22T15:01:52Z
[ "python" ]
How to make equal space between words - python
39,642,374
<p>(SORRY FOR BAD ENGLISH) Im working at cmd. I want to do that thing:</p> <pre><code>file_name DIR file_name_3 DIR file_name_545 DIR file_name_LlK DIR </code></pre> <p>Instead of doing that thing:</p> <pre><code>file_name DIR file_name_3 DIR file_name_545 DIR file_name_LlK DIR </code></pre> <p>I tryied to do this in loop:</p> <pre><code>print data.ljust((20 - len(data) + 20)) if len(data) &lt;= 20 else (data[0:17] + '...').ljust(20)), 'DIR' </code></pre> <p>But that thing not working becase there are letters bigger then another, then 'ljust' the words makes it not possible.</p>
0
2016-09-22T14:52:38Z
39,642,598
<p>First, find the widest point in your data. I assume you have a list of tuples.</p> <pre><code>col_width = max(tup[0] for tup in list_of_tuples) for tup in list_of_tuples: print(tup[0].ljust(col_width), tup[1].ljust(colwidth)) </code></pre> <p><code>ljust</code> is the function you want, but I think you are setting the columns on different lines to different widths, which is not what you want.</p>
0
2016-09-22T15:03:17Z
[ "python" ]
Python: Deadlock of a single lock in multiprocessing
39,642,399
<p>I'm using pyserial to acquire data with multiprocessing. The way I share data is very simple. So:</p> <p>I have member objects in my class:</p> <pre><code>self.mpManager = mp.Manager() self.shared_return_list = self.mpManager.list() self.shared_result_lock = mp.Lock() </code></pre> <p>I call my multiprocessing process this way:</p> <pre><code>process = mp.Process(target=do_my_stuff, args=(self.shared_stopped, self.shared_return_list, self.shared_result_lock) ) </code></pre> <p>where <code>do_my_stuff</code> is a global function.</p> <p>Now The part the fills the list in the process function:</p> <pre><code>if len(acqBuffer) &gt; acquisitionSpecs["LengthToPass"]: shared_lock.acquire() shared_return_list.extend(acqBuffer) del acqBuffer[:] shared_lock.release() </code></pre> <p>And the part that takes that to the local thread for use is:</p> <pre><code>while len(self.acqBuffer) &lt;= 0 and (not self.stopped): #copy list from shared buffer and empty it self.shared_result_lock.acquire() self.acqBuffer.extend(self.shared_return_list) del self.shared_return_list[:] self.shared_result_lock.release() </code></pre> <p><strong>The problem</strong>:</p> <p>Although there's only 1 lock, my program is occasionally ending in a deadlock somehow! After waiting some time, my program freezes. After adding prints before and after the locks, I found that it freezes at a lock and reaches a deadlock somehow.</p> <p>If I use a recursive lock, <code>RLock()</code>, it works with no problems. Not sure whether I should do that.</p> <p>How is this possible? Am I doing something wrong? I expect if both processes try to acquire the lock, they should block until the other process unlocks the lock.</p>
0
2016-09-22T14:54:13Z
39,644,957
<p>Without having a <a href="http://sscce.org/" rel="nofollow">SSCCE</a>, it's difficult to know if there's something else going on in your code or not.</p> <p>One possibility is that there is an exception thrown after a lock is acquired. Try wrapping each of your locked sections in a try/finally clause. Eg.</p> <pre><code>try: shared_lock.acquire() shared_return_list.extend(acqBuffer) del acqBuffer[:] finally: shared_lock.release() </code></pre> <p>and:</p> <pre><code>try: self.shared_result_lock.acquire() self.acqBuffer.extend(self.shared_return_list) del self.shared_return_list[:] finally: self.shared_result_lock.release() </code></pre> <p>You could even add exception clauses, and log any exceptions raised, if this turns out to be the issue.</p>
1
2016-09-22T17:05:40Z
[ "python", "thread-safety", "multiprocessing", "mutex", "python-3.4" ]
Python: Deadlock of a single lock in multiprocessing
39,642,399
<p>I'm using pyserial to acquire data with multiprocessing. The way I share data is very simple. So:</p> <p>I have member objects in my class:</p> <pre><code>self.mpManager = mp.Manager() self.shared_return_list = self.mpManager.list() self.shared_result_lock = mp.Lock() </code></pre> <p>I call my multiprocessing process this way:</p> <pre><code>process = mp.Process(target=do_my_stuff, args=(self.shared_stopped, self.shared_return_list, self.shared_result_lock) ) </code></pre> <p>where <code>do_my_stuff</code> is a global function.</p> <p>Now The part the fills the list in the process function:</p> <pre><code>if len(acqBuffer) &gt; acquisitionSpecs["LengthToPass"]: shared_lock.acquire() shared_return_list.extend(acqBuffer) del acqBuffer[:] shared_lock.release() </code></pre> <p>And the part that takes that to the local thread for use is:</p> <pre><code>while len(self.acqBuffer) &lt;= 0 and (not self.stopped): #copy list from shared buffer and empty it self.shared_result_lock.acquire() self.acqBuffer.extend(self.shared_return_list) del self.shared_return_list[:] self.shared_result_lock.release() </code></pre> <p><strong>The problem</strong>:</p> <p>Although there's only 1 lock, my program is occasionally ending in a deadlock somehow! After waiting some time, my program freezes. After adding prints before and after the locks, I found that it freezes at a lock and reaches a deadlock somehow.</p> <p>If I use a recursive lock, <code>RLock()</code>, it works with no problems. Not sure whether I should do that.</p> <p>How is this possible? Am I doing something wrong? I expect if both processes try to acquire the lock, they should block until the other process unlocks the lock.</p>
0
2016-09-22T14:54:13Z
40,110,367
<p>It turned out it's not a deadlock. My fault! The problem was that the data acquired from the device is sometimes so huge that copying the data through</p> <pre><code>shared_return_list.extend(acqBuffer) del acqBuffer[:] </code></pre> <p>Takes a very long time that the program freezes. I solved this issue by moving data in chunks and by limiting the amount of data to be pulled from the device.</p>
0
2016-10-18T14:02:21Z
[ "python", "thread-safety", "multiprocessing", "mutex", "python-3.4" ]
How to use pyparsing LineStart?
39,642,432
<p>I'm trying to use pyparsing to parse key:value pairs from the comments in a document. A key starts at the beginning of a line, and a value follows. Values may be continued on multiple lines that begin with whitespace.</p> <pre><code>import pyparsing as pp instring = """ -- This is (a) #%^&amp; comment /* name1: val name2: val2 with $*&amp;#@) junk name3: val3: with @)(*% multi- line: content */ """ comment1 = pp.Literal("--") + pp.originalTextFor(pp.SkipTo(pp.LineEnd())).setDebug() identifier = pp.Word(pp.alphanums + "_").setDebug() meta1 = pp.LineStart() + identifier + pp.Literal(":") + pp.SkipTo(pp.LineEnd()) meta2 = pp.LineStart() + pp.White() + pp.SkipTo(pp.LineEnd()) metaval = meta1 + pp.ZeroOrMore(meta2) metalist = pp.ZeroOrMore(comment1) + pp.Literal("/*") + pp.OneOrMore(metaval) + pp.Literal("*/") if __name__ == "__main__": p = metalist.parseString(instring) print(p) </code></pre> <p>Fails with:</p> <pre><code>Matched {Empty SkipTo:(LineEnd) Empty} -&gt; ['This is (a) #%^&amp; comment'] File "C:\Users\user\py3\lib\site-packages\pyparsing.py", line 2305, in parseImpl raise ParseException(instring, loc, self.errmsg, self) pyparsing.ParseException: Expected start of line (at char 32), (line:4, col:1) </code></pre> <p>The answer to <a href="http://stackoverflow.com/questions/26600333/pyparsing-whitespace-match-issues">pyparsing whitespace match issues</a> says</p> <pre><code>LineStart has always been difficult to work with, but ... </code></pre> <p>If the parser is at line 4 column 1 (the first key:value pair), then why is it not finding a start of line? What is the correct pyparsing syntax to recognize lines beginning with no whitespace and lines beginning with whitespace?</p>
1
2016-09-22T14:55:56Z
39,653,686
<p>I think the confusion I have with <code>LineStart</code> is that, for <code>LineEnd</code>, I can look for a <code>'\n'</code> character, but there is no separate character for <code>LineStart</code>. So in <code>LineStart</code> I look to see if the current parser location is positioned just after a <code>'\n'</code>; or if it is currently <em>on</em> a <code>'\n'</code>, move past it and still continue. Unfortunately, I implemented this in a place that messes up the reporting location, so you get those weird errors that read like "failed to find a start of line on line X col 1," which really does sound like it should be a successfully matched start of a line. Also, I think I need to revisit this implicit newline-skipping, or for that matter, all whitespace-skipping in general for <code>LineStart</code>. </p> <p>For now, I've gotten your code to work by expanding your line-starting expression slightly, as:</p> <pre><code>LS = pp.Optional(pp.LineEnd()) + pp.LineStart() </code></pre> <p>and replaced the LineStart references in meta1 and meta2 with LS:</p> <pre><code>comment1 = pp.Literal("--") + pp.originalTextFor(pp.SkipTo(pp.LineEnd())).setDebug() identifier = pp.Word(pp.alphanums + "_").setDebug() meta1 = LS + identifier + pp.Literal(":") + pp.SkipTo(pp.LineEnd()) meta2 = LS + pp.White() + pp.SkipTo(pp.LineEnd()) metaval = meta1 + pp.ZeroOrMore(meta2) metalist = pp.ZeroOrMore(comment1) + pp.Literal("/*") + pp.OneOrMore(metaval) + pp.Literal("*/") </code></pre> <p>If this situation with <code>LineStart</code> leaves you uncomfortable, here is another tactic you can try: using a parse-time condition to only accept identifiers that start in column 1:</p> <pre><code>comment1 = pp.Literal("--") + pp.originalTextFor(pp.SkipTo(pp.LineEnd())).setDebug() identifier = pp.Word(pp.alphanums + "_").setName("identifier") identifier.addCondition(lambda instring,loc,toks: pp.col(loc,instring) == 1) meta1 = identifier + pp.Literal(":") + pp.SkipTo(pp.LineEnd()).setDebug() meta2 = pp.White().setDebug() + pp.SkipTo(pp.LineEnd()).setDebug() metaval = meta1 + pp.ZeroOrMore(meta2, stopOn=pp.Literal('*/')) metalist = pp.ZeroOrMore(comment1) + pp.Literal("/*") + pp.LineEnd() + pp.OneOrMore(metaval) + pp.Literal("*/") </code></pre> <p>This code does away with <code>LineStart</code> completely, while I figure out just what I want this particular token to do. I also had to modify the <code>ZeroOrMore</code> repetition in <code>metaval</code> so that <code>*/</code> would not be accidentally processed as continued comment content.</p> <p>Thanks for your patience with this - I am not keen to quickly put out a patched <code>LineStart</code> change and then find that I have overlooked other compatibility or other edge cases that just put me back in the current less-than-great state on this class. But I'll put some effort into clarifying this behavior before putting out 2.1.10.</p>
1
2016-09-23T06:08:10Z
[ "python", "python-3.x", "pyparsing" ]
Riak MapReduce in single node using javascript and python
39,642,462
<p>I want to perform MapReduce job on data in Riak DB using javascript. But stuck in very begining, i couldnot understand how it is returning value.</p> <pre><code>client = riak.RiakClient() query = client.add('user') query.map(""" function(v){ var i=0; i++; return [i]; } """) for result in query.run(): print "%s" % (result); </code></pre> <p>For simplicity i have checked the above example. </p> <p>Here query is bucket and user contain five sets of data in RiakDB. i think map() returns single value but it returns array with 5 value, i think equivalent to five set of data in RiakDB. </p> <pre><code>1 1 1 1 1 </code></pre> <p>And here, why I can return only array? it treats each dataset independently, and returns for each. so i think i have five 1's. Due to this reason when i process fetched data inside map(), returns gives unexpected result for me.</p> <p>so please give me some suggestion. i think it is basic thing but i couldnot get it. i highly appreciate your help. </p>
0
2016-09-22T14:57:17Z
39,694,795
<p>When you run a MapReduce job, the map phase code is sent out to the vnodes where the data is stored and executed for each value in the data. The resulting arrays are collected and passed to a single reduce phase, which also returns an array. If there are sufficiently many results, the reduce phase may be run multiple times, with the previous reduce result and a batch of map results as input.</p> <p>The fact that you are getting 5 results implies that 5 keys were seen in your bucket. There is no global state shared between instances of the map phase function, so each will have an independent <code>i</code>, which is why each result is <code>1</code>.</p> <p>You might try returning <code>[v.key]</code> so that you have something unique for each one, or if the values are expected to be small, you could return <code>[JSON.stringify(v)]</code> so you can see the entire structure that is passed to the map.</p> <p>You should note that according to the <a href="https://docs.basho.com/riak/kv/2.1.4/developing/app-guide/advanced-mapreduce/" rel="nofollow">docs site</a> javascript Map Reduce has been officially deprecated, so you may want to use Erlang functions for new development.</p>
1
2016-09-26T04:34:06Z
[ "javascript", "python", "dictionary", "riak" ]
Sort a list where there are strings, floats and integers
39,642,490
<p>I need some help because I wanted to know if there is a way in Python to sort a list where there are strings, floats and integers in it.</p> <p>I tried to use list.sort() method but of course it did not work.</p> <p>Here is an example of a list I would like to sort :</p> <pre><code> l = [1, 2.0, "titi", True, [2, 3, 4, [3, [3, 4]], 5]] </code></pre> <p>I would like it to be sorted by value by floats and ints, and then by type : floats and ints first, then strings, then booleans and then lists. I would like to use Python 2.7 but I am not allowed to..</p>
-5
2016-09-22T14:58:25Z
39,642,636
<p>Python's comparison operators wisely refuse to work for variables of incompatible types. Decide on the criterion for sorting your list, encapsulate it in a function and pass it as the <code>key</code> option to <code>sort()</code>. For example, to sort by the <code>repr</code> of each element (a string):</p> <pre><code>l.sort(key=repr) </code></pre> <p>To sort by type first, then by the contents:</p> <pre><code>l.sort(key=lambda x: (str(type(x)), x)) </code></pre> <p>The latter has the advantage that numbers get sorted numerically, strings alphabetically, etc. It will still fail if there are two sublists that cannot be compared, but then you must decide what to do-- just extend your key function however you see fit.</p>
0
2016-09-22T15:05:09Z
[ "python", "sorting", "python-3.3" ]
python u'\u00b0' returns u'\xb0'. Why?
39,642,521
<p>I use python 2.7.10.</p> <p>On dealing with character encoding, and after reading a lot of stack-overflow etc. etc. on the subject, I encountered this behaviour which looks strange to me. Python interpreter input</p> <pre><code>&gt;&gt;&gt;u'\u00b0' </code></pre> <p>results in the following output:</p> <pre><code>u'\xb0' </code></pre> <p>I could repeat this behaviour using a dos window, the idle console, and the wing-ide python shell.</p> <p>My assumptions (correct me if I am wrong): The "degree symbol" has unicode 0x00b0, utf-8 code 0xc2b0, latin-1 code 0xb0. Python doc say, a string literal with u-prefix is encoded using unicode.</p> <p>Question: Why is the result converted to a unicode-string-literal with a byte-escape-sequence which matches the latin-1 encoding, instead of persisting the unicode escape sequence ?</p> <p>Thanks in advance for any help.</p>
0
2016-09-22T15:00:00Z
39,642,638
<p>Python uses some rules for determining what to output from <code>repr</code> for each character. The rule for Unicode character codepoints in the 0x0080 to 0x00ff range is to use the sequence <code>\xdd</code> where <code>dd</code> is the hex code, at least in Python 2. There's no way to change it. In Python 3, all printable characters will be displayed without converting to a hex code.</p> <p>As for why it looks like Latin-1 encoding, it's because Unicode started with Latin-1 as the base. All the codepoints up to 0xff match their Latin-1 counterpart.</p>
0
2016-09-22T15:05:13Z
[ "python", "unicode", "character-encoding", "python-2.x", "string-literals" ]
Setting a local bool to control flow
39,642,592
<p>I have an issue in Python where I want to do a while loop and ask the player to input number of dice and the number of sides to do random dice rolls. On the second loop and any additional loops I want to ask if they would like to continue. If they input 'n' or 'no' then the program exits.</p> <p>I was able to get this logic working with a global variable and changing that variable in my function after the first time it is called so the second time the user would be asked if they want to continue, however from my understanding using global variables like this is not a very Python-way of doing things. I would like to improve this.</p> <p>The following code works except for the fact that the user will never be prompted to exit. I know this is because they variable keeps getting set back to True at the beginning of the while loop, but I don't know how to set a flag without resorting to a global variable.</p> <p>How do I set a True/False variable locally (not-globally) and use it to control flow in the program?</p> <pre><code>import sys import random def get_user_input(first_loop): if not first_loop: another_time = input("Would you like to roll another time?") if another_time.lower() in ['n', 'no']: sys.exit() # This allows the code above to output on additional loops. first_loop = False return first_loop while True: # How do I not reset this back to True each time the program loops? first_loop = True get_user_input(first_loop) number_of_dice = int(input("Enter the number of dice you would like to roll: ")) number_of_sides = int(input("Enter the number of sides for the dice: ")) # create the dice_total list so each time we create a roll in the loop, # it can be added to a list and the total calculated dice_total = [] for die in range(number_of_dice): random_roll = random.randrange(1, number_of_sides) print("You rolled: ", random_roll) dice_total.append(random_roll) dice_total = sum(dice_total) print("The total of the dice rolled is: ", dice_total) </code></pre>
0
2016-09-22T15:03:08Z
39,642,675
<p>You're pretty close.</p> <pre><code># move this outside the loop first_loop = True while True: if not first_loop: get_user_input() first_loop = False </code></pre> <p>And no need to use <code>first_loop</code> in the <code>get_user_input</code> function itself:</p> <pre><code>def get_user_input(): another_time = input("Would you like to roll another time?") if another_time.lower() in ['n', 'no']: sys.exit() </code></pre> <hr> <p>It would be better to return <code>True</code>/<code>False</code> and act accordingly instead of using <code>sys.exit</code> in a function (gives you more control):</p> <pre><code>def get_user_input(): another_time = input("Would you like to roll another time?") return not another_time.lower() in ['n', 'no'] </code></pre> <p>And then you can do:</p> <pre><code>while True: if not first_loop: if not get_user_input(): # break out of the loop break </code></pre>
2
2016-09-22T15:07:08Z
[ "python", "python-3.x" ]
Setting a local bool to control flow
39,642,592
<p>I have an issue in Python where I want to do a while loop and ask the player to input number of dice and the number of sides to do random dice rolls. On the second loop and any additional loops I want to ask if they would like to continue. If they input 'n' or 'no' then the program exits.</p> <p>I was able to get this logic working with a global variable and changing that variable in my function after the first time it is called so the second time the user would be asked if they want to continue, however from my understanding using global variables like this is not a very Python-way of doing things. I would like to improve this.</p> <p>The following code works except for the fact that the user will never be prompted to exit. I know this is because they variable keeps getting set back to True at the beginning of the while loop, but I don't know how to set a flag without resorting to a global variable.</p> <p>How do I set a True/False variable locally (not-globally) and use it to control flow in the program?</p> <pre><code>import sys import random def get_user_input(first_loop): if not first_loop: another_time = input("Would you like to roll another time?") if another_time.lower() in ['n', 'no']: sys.exit() # This allows the code above to output on additional loops. first_loop = False return first_loop while True: # How do I not reset this back to True each time the program loops? first_loop = True get_user_input(first_loop) number_of_dice = int(input("Enter the number of dice you would like to roll: ")) number_of_sides = int(input("Enter the number of sides for the dice: ")) # create the dice_total list so each time we create a roll in the loop, # it can be added to a list and the total calculated dice_total = [] for die in range(number_of_dice): random_roll = random.randrange(1, number_of_sides) print("You rolled: ", random_roll) dice_total.append(random_roll) dice_total = sum(dice_total) print("The total of the dice rolled is: ", dice_total) </code></pre>
0
2016-09-22T15:03:08Z
39,642,770
<p>You can put the variable in a <code>list</code>. This will allow you to change its value in the <code>get_user_input()</code> function and avoid making it a global variable.</p> <pre><code>import sys import random def get_user_input(first_loop): if not first_loop[0]: # access value in the list another_time = input("Would you like to roll another time?") if another_time.lower() in ['n', 'no']: sys.exit() # This allows the code above to output on additional loops. first_loop[0] = False return first_loop[0] # access value in the list while True: # How do I not reset this back to True each time the program loops? first_loop = [True] # change to a list get_user_input(first_loop) number_of_dice = int(input("Enter the number of dice you would like to roll: ")) number_of_sides = int(input("Enter the number of sides for the dice: ")) # create the dice_total list so each time we create a roll in the loop, # it can be added to a list and the total calculated dice_total = [] for die in range(number_of_dice): random_roll = random.randrange(1, number_of_sides) print("You rolled: ", random_roll) dice_total.append(random_roll) dice_total = sum(dice_total) print("The total of the dice rolled is: ", dice_total) </code></pre>
1
2016-09-22T15:11:21Z
[ "python", "python-3.x" ]
Creating combinations from a tuple
39,642,629
<p>I take the data from the database. From the database they come in the form of a tuple:</p> <pre><code>[('test1', 'test12', 'test13', 'test14'), ('test21', 'test22', 'test23', 'test24'), ('test31', 'test32', 'test33', 'test34'), ('test41', 'test42', 'test43', 'test44'), ('test51', 'test52', 'test53', 'test54'), ('test61', 'test62', 'test63', 'test64'), ('test71', 'test72', 'test73', 'test74'), ('test81', 'test82', 'test83', 'test84'), ('test91', 'test92', 'test93', 'test94'), ('test11', 'test12', 'test13', 'test14')] </code></pre> <p>And that's what I want: make combinations of these input... so the output I had a combination of 4 parameters (such as in example) and...</p> <p><strong>1)</strong> most importantly, new combinations,the values were always in its place, i.e. if in the original combinations the values were index [1], this means that in the new combination, it should also be [1]...</p> <p><strong>2)</strong> there are no duplicate combinations</p> <p>As example:</p> <p>I got tuple:</p> <pre><code>[('test91', 'test92', 'test93', 'test94'), ('test11', 'test12', 'test13', 'test14')] </code></pre> <p>And from this I got new combinations:</p> <pre><code>[('test91', 'test12', 'test13', 'test14'), ('test11', 'test92', 'test93', 'test94')] </code></pre> <p>Maybe it's possible to do using the method of pairwise or something else. Help.</p>
-1
2016-09-22T15:04:56Z
39,643,675
<p>You need to use <a href="https://docs.python.org/3/library/itertools.html#itertools.product" rel="nofollow"><code>product</code></a> method from builtin package <a href="https://docs.python.org/3/library/itertools.html#itertools" rel="nofollow"><code>itertools</code></a> which gives cartesian product of input iterables.</p> <p>Here is code that do what you desire. <strong>But be careful</strong>, because huge list would produce a ton of combinations, try not to run out of memory.</p> <pre><code>from itertools import product data = [('test91', 'test92', 'test93', 'test94'), ('test11', 'test12', 'test13', 'test14')] b = list(zip(*a)) # making list of n-th elements # b = [('test91', 'test11'), &lt;- first elements # ('test92', 'test12'), &lt;- second elements # ('test93', 'test13'), &lt;- third elements # ('test94', 'test14')] variations = product(*b) output = set(variations) - set(a) # this is unique variations without input data # output = {('test11', 'test12', 'test13', 'test94'), # ('test11', 'test12', 'test93', 'test14'), # ('test11', 'test12', 'test93', 'test94'), # ('test11', 'test92', 'test13', 'test14'), # ('test11', 'test92', 'test13', 'test94'), # ('test11', 'test92', 'test93', 'test14'), # ('test11', 'test92', 'test93', 'test94'), # ('test91', 'test12', 'test13', 'test14'), # ('test91', 'test12', 'test13', 'test94'), # ('test91', 'test12', 'test93', 'test14'), # ('test91', 'test12', 'test93', 'test94'), # ('test91', 'test92', 'test13', 'test14'), # ('test91', 'test92', 'test13', 'test94'), # ('test91', 'test92', 'test93', 'test14')} </code></pre> <p>If you want output to be with input data you can simply </p> <pre><code>output = set(variations) </code></pre> <p>If you need a list instead of set, just do</p> <pre><code>output = list(output) </code></pre>
0
2016-09-22T15:56:07Z
[ "python", "python-3.x", "combinations" ]
time.strftime() not updaing
39,642,663
<p>I am trying to get the time when a button is pushed, but I am going to have a few pushes without starting and calling the time module. In Ipython, I tested out some code, and the time is not updating</p> <pre><code>import time t = time.strftime("%b-%d-%y at %I:%m%p") print(t) #do something else for a little t = time.strftime("%b-%d-%y at %I:%m%p") print(t) </code></pre> <p>It gives me the same time</p> <p>even if I put in a time tuple such as:</p> <pre><code>lt = time.localtime(time.time()) t = time.strftime("%b-%d-%y at %I:%m%p", lt) print(t) </code></pre> <p>I get the same time</p> <p>Even if I wait, and execute the code again (in Ipython), it gives me the same time. </p> <p>time.time() will give me a new time every time though</p> <p>I don't know if doing it in Ipython (I'm just testing code before I put it in my python file) matters</p> <p>What am I doing wrong??</p>
2
2016-09-22T15:06:39Z
39,642,802
<p>You are using <code>%m</code> at <code>%I:%m%p</code> to format your "minutes", which actually means a <strong>month</strong> in decimals. Try capital <code>%M</code>instead to get the minutes.</p> <p>So,</p> <pre><code>time.strftime("%b-%d-%y at %I:%M%p") </code></pre> <p>See <a href="https://docs.python.org/2/library/time.html#time.strftime" rel="nofollow">strftime documentation</a> for the format directives.</p>
3
2016-09-22T15:12:56Z
[ "python", "time", "module" ]
Create mask from skimage contour
39,642,680
<p>I have an image that I found contours on with <code>skimage.measure.find_contours()</code> but now I want to create a mask for the pixels fully outside the largest closed contour. Any idea how to do this? </p> <p>Modifying the example in the documentation: </p> <pre><code>import numpy as np import matplotlib.pyplot as plt from skimage import measure # Construct some test data x, y = np.ogrid[-np.pi:np.pi:100j, -np.pi:np.pi:100j] r = np.sin(np.exp((np.sin(x)**2 + np.cos(y)**2))) # Find contours at a constant value of 0.8 contours = measure.find_contours(r, 0.8) # Select the largest contiguous contour contour = sorted(contours, key=lambda x: len(x))[-1] # Display the image and plot the contour fig, ax = plt.subplots() ax.imshow(r, interpolation='nearest', cmap=plt.cm.gray) X, Y = ax.get_xlim(), ax.get_ylim() ax.step(contour.T[1], contour.T[0], linewidth=2, c='r') ax.set_xlim(X), ax.set_ylim(Y) plt.show() </code></pre> <p>Here is the contour in red:</p> <p><a href="http://i.stack.imgur.com/O2Ldt.png" rel="nofollow"><img src="http://i.stack.imgur.com/O2Ldt.png" alt="enter image description here"></a></p> <p>But if you zoom in, notice the contour is not at the resolution of the pixels.</p> <p><a href="http://i.stack.imgur.com/o1IYn.png" rel="nofollow"><img src="http://i.stack.imgur.com/o1IYn.png" alt="enter image description here"></a></p> <p>How can I create an image of the same dimensions as the original with the pixels fully outside (i.e. not crossed by the contour line) masked? E.g.</p> <pre><code>from numpy import ma masked_image = ma.array(r.copy(), mask=False) masked_image.mask[pixels_outside_contour] = True </code></pre> <p>Thanks!</p>
0
2016-09-22T15:07:25Z
39,857,243
<p>Ok, I was able to make this work by converting the contour to a path and then selecting the pixels inside:</p> <pre><code># Convert the contour into a closed path from matplotlib import path closed_path = path.Path(contour.T) # Get the points that lie within the closed path idx = np.array([[(i,j) for i in range(r.shape[0])] for j in range(r.shape[1])]).reshape(np.prod(r.shape),2) mask = closed_path.contains_points(idx).reshape(r.shape) # Invert the mask and apply to the image mask = np.invert(mask) masked_data = ma.array(r.copy(), mask=mask) </code></pre> <p>However, this is kind of slow testing <code>N = r.shape[0]*r.shape[1]</code> pixels for containment. Anyone have a faster algorithm? Thanks!</p>
0
2016-10-04T16:17:45Z
[ "python", "contour", "skimage", "masked-array" ]
Adding alpha channel to RGB array using numpy
39,642,721
<p>I have an image array in RGB space and want to add the alpha channel to be all zeros. Specifically, I have a <code>numpy</code> array with shape (205, 54, 3) and I want to change the shape to (205, 54, 4) with the additional spot in the third dimension being all 0.0's. Which numpy operation would achieve this?</p>
3
2016-09-22T15:09:08Z
39,643,014
<p>You could use one of the stack functions (<a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.stack.html" rel="nofollow">stack</a>/<a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.hstack.html" rel="nofollow">hstack</a>/<a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.vstack.html" rel="nofollow">vstack</a>/<a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.dstack.html" rel="nofollow">dstack</a>/<a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.concatenate.html" rel="nofollow">concatenate</a>) to join multiple arrays together.</p> <pre><code>numpy.dstack( ( your_input_array, numpy.zeros((25, 54)) ) ) </code></pre>
2
2016-09-22T15:23:28Z
[ "python", "numpy" ]
Adding alpha channel to RGB array using numpy
39,642,721
<p>I have an image array in RGB space and want to add the alpha channel to be all zeros. Specifically, I have a <code>numpy</code> array with shape (205, 54, 3) and I want to change the shape to (205, 54, 4) with the additional spot in the third dimension being all 0.0's. Which numpy operation would achieve this?</p>
3
2016-09-22T15:09:08Z
39,643,047
<p>If you have your current image as rgb variable then just use:</p> <pre><code>rgba = numpy.concatenate((rgb, numpy.zeros((205, 54, 1))), axis=2) </code></pre> <p>Concatenate function merge rgb and zeros array together. Zeros function creates array of zeros. We set axis to 2 what means we merge in the thirde dimensions. Note: axis are counted from 0.</p>
0
2016-09-22T15:25:12Z
[ "python", "numpy" ]
Python, list of strings, rows into columns
39,642,852
<p>So, my problem is, i want to transpose my list rows into columns for example: </p> <p>["AAA", "BBB", "CCC"] => ["ABC", "ABC", "ABC"]</p> <p>can't find an efficient way to do it.</p>
-2
2016-09-22T15:15:33Z
39,642,891
<p>You can do a simple use of <code>zip</code> and unpacking:</p> <pre><code>strs = ["AAA", "BBB", "CCC"] print zip(*strs) </code></pre> <p>Output will be tuples, though:</p> <blockquote> <p>[('A', 'B', 'C'), ('A', 'B', 'C'), ('A', 'B', 'C')]</p> </blockquote> <hr> <p>For strings you can use:</p> <pre><code>strs = ["AAA", "BBB", "CCC"] print map(''.join, zip(*strs)) # for python 3 use: list(map(''.join, zip(*strs))) # thanks @cesar </code></pre> <p>Output is now a list of strings:</p> <blockquote> <p>['ABC', 'ABC', 'ABC']</p> </blockquote> <p><code>''.join</code> is used to map tuples to strings.</p>
3
2016-09-22T15:17:36Z
[ "python" ]
Python, list of strings, rows into columns
39,642,852
<p>So, my problem is, i want to transpose my list rows into columns for example: </p> <p>["AAA", "BBB", "CCC"] => ["ABC", "ABC", "ABC"]</p> <p>can't find an efficient way to do it.</p>
-2
2016-09-22T15:15:33Z
39,642,907
<pre><code>a = ["AAA", "BBB", "CCC"] print ([''.join(i) for i in zip(*a)]) </code></pre>
2
2016-09-22T15:18:30Z
[ "python" ]
Python, list of strings, rows into columns
39,642,852
<p>So, my problem is, i want to transpose my list rows into columns for example: </p> <p>["AAA", "BBB", "CCC"] => ["ABC", "ABC", "ABC"]</p> <p>can't find an efficient way to do it.</p>
-2
2016-09-22T15:15:33Z
39,643,188
<p>So this assumes that you are dealing with strings in your example, but you could expand the algorithm for dealing with whatever data type you come across, the logic will remain the same.</p> <pre><code>listRows = ["AAA", "BBB", "CCC"] transList = [] tempString = '' for s in range(0,len(listRows)): for i in range(0, len(listRows)): tempString = tempString + listRows[i][s] transList.append(tempString) tempString = '' print(transList) </code></pre> <p>Where transList is the final list you want</p>
0
2016-09-22T15:31:16Z
[ "python" ]
create df column name by adding global variable name and a string in Python
39,642,875
<p>I have a global variable <code> split_ask_min = 'Minimum_Spend' </code></p> <p>I would like to create a new variable in my df and name it 'Minimum_Spend_Sum' and make it the sum of Minimum_Spend. </p> <p><code> var_programs['split_ask_min+ _Sum'] = var_programs[split_ask_min].groupby(X['NAME']).transform('sum') </code> I am having trouble creating the variable name. It should be </p> <p><code> split_ask_min+ '_Sum' </code> which equal to <code> Minimum_Spend_Sum </code></p> <p>But then if I code </p> <p><code>var_programs['split_ask_min+ '_Sum''] </code></p> <p>I got an error</p>
1
2016-09-22T15:16:53Z
39,642,987
<p>Unless you really need to create a variable, use a dictionary to store the value.</p> <pre><code>df = {} split_ask_min = 'Minimum_Spend' df[split_ask_min + '_Sum'] = ... print(df) </code></pre> <p>Otherwise you can use <code>globals()</code></p> <pre><code>globals[split_ask_min + '_Sum'] = ... # Minimum_Spend_Sum =&gt; ... </code></pre>
0
2016-09-22T15:21:57Z
[ "python", "python-3.x", "pandas" ]
create df column name by adding global variable name and a string in Python
39,642,875
<p>I have a global variable <code> split_ask_min = 'Minimum_Spend' </code></p> <p>I would like to create a new variable in my df and name it 'Minimum_Spend_Sum' and make it the sum of Minimum_Spend. </p> <p><code> var_programs['split_ask_min+ _Sum'] = var_programs[split_ask_min].groupby(X['NAME']).transform('sum') </code> I am having trouble creating the variable name. It should be </p> <p><code> split_ask_min+ '_Sum' </code> which equal to <code> Minimum_Spend_Sum </code></p> <p>But then if I code </p> <p><code>var_programs['split_ask_min+ '_Sum''] </code></p> <p>I got an error</p>
1
2016-09-22T15:16:53Z
39,643,222
<p>To create a new column in your df you can pass a constructed string to add a new column to your df:</p> <pre><code>In [239]: split_ask_min = 'Minimum_Spend' df = pd.DataFrame(np.random.randn(5,3), columns=list('abc')) df[split_ask_min + '_Sum'] = 0 df Out[239]: a b c Minimum_Spend_Sum 0 -0.113483 -0.487551 0.276176 0 1 0.143454 -1.322578 -2.040297 0 2 -0.100320 0.716255 1.109432 0 3 -1.260516 -0.560957 0.007871 0 4 0.497407 -2.031782 0.933199 0 </code></pre>
1
2016-09-22T15:32:52Z
[ "python", "python-3.x", "pandas" ]
How to install psycopg2 for django on mac
39,642,961
<p>I have postgresql installed (with postgresql app). When I try "pip install psycopg2", i get "unable to execute gcc-4.2: No such file or directory. How to fix?</p>
0
2016-09-22T15:21:03Z
39,643,053
<p>You will need XCode to compile with gcc on macOS. Install it with this command in the terminal:</p> <pre><code>xcode-select --install </code></pre> <p>Or you cold install it from the app store.</p>
0
2016-09-22T15:25:41Z
[ "python", "django", "postgresql", "psycopg2" ]
pip installl tsne doesn't work
39,643,043
<p>I couldn't install tsne package on my Windows machine. I followed the instruction <a href="https://github.com/danielfrg/tsne/blob/master/README.md" rel="nofollow">here</a> to install tsne packages for Python. But either <code>pip install tsne</code> or <code>pip install git+https://github.com/danielfrg/tsne.git</code> works. The error massage is </p> <pre><code> tsne/bh_sne_src/quadtree.cpp(12) : fatal error C1083: Cannot open include file: 'cblas.h': No such file or directory error: command 'C:\\Users\\hzoe\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status 2 ---------------------------------------- Failed building wheel for tsne Running setup.py clean for tsne Failed to build tsne Installing collected packages: tsne Running setup.py install for tsne: started Running setup.py install for tsne: finished with status 'error' Complete output from command C:\Users\hzoe\AppData\Local\Continuum\Anaconda\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\hzoe\\appdata\\local\\temp\\pip-build-vicxy7\\tsne\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record c:\users\hzoe\appdata\local\temp\pip-so57qk-record\install-record.txt --single-version-externally-managed --compile: !!!!!!!!!!!!! ['tsne', 'tsne.tests'] C:\Users\hzoe\AppData\Local\Continuum\Anaconda\lib\site-packages\setuptools-20.2.2-py2.7.egg\setuptools\dist.py:285: UserWarning: Normalizing 'v0.1.5' to '0.1.5' running install running build running build_py creating build creating build\lib.win-amd64-2.7 creating build\lib.win-amd64-2.7\tsne copying tsne\_version.py -&gt; build\lib.win-amd64-2.7\tsne copying tsne\__init__.py -&gt; build\lib.win-amd64-2.7\tsne creating build\lib.win-amd64-2.7\tsne\tests copying tsne\tests\test_iris.py -&gt; build\lib.win-amd64-2.7\tsne\tests copying tsne\tests\__init__.py -&gt; build\lib.win-amd64-2.7\tsne\tests UPDATING build\lib.win-amd64-2.7\tsne/_version.py set build\lib.win-amd64-2.7\tsne/_version.py to 'v0.1.5' running build_ext building 'bh_sne' extension creating build\temp.win-amd64-2.7 creating build\temp.win-amd64-2.7\Release creating build\temp.win-amd64-2.7\Release\tsne creating build\temp.win-amd64-2.7\Release\tsne\bh_sne_src C:\Users\hzoe\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -IC:\Users\hzoe\AppData\Local\Continuum\Anaconda\lib\site-packages\numpy\core\include -I/usr/local/include -Itsne/bh_sne_src/ -IC:\Users\hzoe\AppData\Local\Continuum\Anaconda\include -IC:\Users\hzoe\AppData\Local\Continuum\Anaconda\PC /Tptsne/bh_sne.cpp /Fobuild\temp.win-amd64-2.7\Release\tsne/bh_sne.obj -msse2 -O3 -fPIC -w cl : Command line warning D9025 : overriding '/W3' with '/w' cl : Command line warning D9002 : ignoring unknown option '-msse2' cl : Command line warning D9002 : ignoring unknown option '-O3' cl : Command line warning D9002 : ignoring unknown option '-fPIC' bh_sne.cpp c:\users\hzoe\appdata\local\continuum\anaconda\lib\site-packages\numpy\core\include\numpy\npy_1_7_deprecated_api.h(12) : Warning Msg: Using deprecated NumPy API, disable it by #defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION C:\Users\hzoe\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Include\xlocale(342) : warning C4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc C:\Users\hzoe\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -IC:\Users\hzoe\AppData\Local\Continuum\Anaconda\lib\site-packages\numpy\core\include -I/usr/local/include -Itsne/bh_sne_src/ -IC:\Users\hzoe\AppData\Local\Continuum\Anaconda\include -IC:\Users\hzoe\AppData\Local\Continuum\Anaconda\PC /Tptsne/bh_sne_src/quadtree.cpp /Fobuild\temp.win-amd64-2.7\Release\tsne/bh_sne_src/quadtree.obj -msse2 -O3 -fPIC -w cl : Command line warning D9025 : overriding '/W3' with '/w' cl : Command line warning D9002 : ignoring unknown option '-msse2' cl : Command line warning D9002 : ignoring unknown option '-O3' cl : Command line warning D9002 : ignoring unknown option '-fPIC' quadtree.cpp tsne/bh_sne_src/quadtree.cpp(12) : fatal error C1083: Cannot open include file: 'cblas.h': No such file or directory error: command 'C:\\Users\\hzoe\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status 2 ---------------------------------------- Command "C:\Users\hzoe\AppData\Local\Continuum\Anaconda\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\hzoe\\appdata\\local\\temp\\pip-build-vicxy7\\tsne\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record c:\users\hzoe\appdata\local\temp\pip-so57qk-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in c:\users\hzoe\appdata\local\temp\pip-build-vicxy7\tsne\ </code></pre> <p>I am using Anaconda for python and I installed Visual C++ compiler for Windows too.</p>
0
2016-09-22T15:25:07Z
39,643,483
<p>I am sorry if you've already tried this, but i couldn't see what you typed into the command prompt to get that error.</p> <p>If you dont have your path variable set to pip, then type this in (just alter the path if python is in a different directory) and remember its case sensitive!</p> <pre><code>C:\Python34\Scripts\pip install LIBRARY_NAME </code></pre>
0
2016-09-22T15:46:25Z
[ "python", "pip" ]
pip installl tsne doesn't work
39,643,043
<p>I couldn't install tsne package on my Windows machine. I followed the instruction <a href="https://github.com/danielfrg/tsne/blob/master/README.md" rel="nofollow">here</a> to install tsne packages for Python. But either <code>pip install tsne</code> or <code>pip install git+https://github.com/danielfrg/tsne.git</code> works. The error massage is </p> <pre><code> tsne/bh_sne_src/quadtree.cpp(12) : fatal error C1083: Cannot open include file: 'cblas.h': No such file or directory error: command 'C:\\Users\\hzoe\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status 2 ---------------------------------------- Failed building wheel for tsne Running setup.py clean for tsne Failed to build tsne Installing collected packages: tsne Running setup.py install for tsne: started Running setup.py install for tsne: finished with status 'error' Complete output from command C:\Users\hzoe\AppData\Local\Continuum\Anaconda\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\hzoe\\appdata\\local\\temp\\pip-build-vicxy7\\tsne\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record c:\users\hzoe\appdata\local\temp\pip-so57qk-record\install-record.txt --single-version-externally-managed --compile: !!!!!!!!!!!!! ['tsne', 'tsne.tests'] C:\Users\hzoe\AppData\Local\Continuum\Anaconda\lib\site-packages\setuptools-20.2.2-py2.7.egg\setuptools\dist.py:285: UserWarning: Normalizing 'v0.1.5' to '0.1.5' running install running build running build_py creating build creating build\lib.win-amd64-2.7 creating build\lib.win-amd64-2.7\tsne copying tsne\_version.py -&gt; build\lib.win-amd64-2.7\tsne copying tsne\__init__.py -&gt; build\lib.win-amd64-2.7\tsne creating build\lib.win-amd64-2.7\tsne\tests copying tsne\tests\test_iris.py -&gt; build\lib.win-amd64-2.7\tsne\tests copying tsne\tests\__init__.py -&gt; build\lib.win-amd64-2.7\tsne\tests UPDATING build\lib.win-amd64-2.7\tsne/_version.py set build\lib.win-amd64-2.7\tsne/_version.py to 'v0.1.5' running build_ext building 'bh_sne' extension creating build\temp.win-amd64-2.7 creating build\temp.win-amd64-2.7\Release creating build\temp.win-amd64-2.7\Release\tsne creating build\temp.win-amd64-2.7\Release\tsne\bh_sne_src C:\Users\hzoe\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -IC:\Users\hzoe\AppData\Local\Continuum\Anaconda\lib\site-packages\numpy\core\include -I/usr/local/include -Itsne/bh_sne_src/ -IC:\Users\hzoe\AppData\Local\Continuum\Anaconda\include -IC:\Users\hzoe\AppData\Local\Continuum\Anaconda\PC /Tptsne/bh_sne.cpp /Fobuild\temp.win-amd64-2.7\Release\tsne/bh_sne.obj -msse2 -O3 -fPIC -w cl : Command line warning D9025 : overriding '/W3' with '/w' cl : Command line warning D9002 : ignoring unknown option '-msse2' cl : Command line warning D9002 : ignoring unknown option '-O3' cl : Command line warning D9002 : ignoring unknown option '-fPIC' bh_sne.cpp c:\users\hzoe\appdata\local\continuum\anaconda\lib\site-packages\numpy\core\include\numpy\npy_1_7_deprecated_api.h(12) : Warning Msg: Using deprecated NumPy API, disable it by #defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION C:\Users\hzoe\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Include\xlocale(342) : warning C4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc C:\Users\hzoe\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -IC:\Users\hzoe\AppData\Local\Continuum\Anaconda\lib\site-packages\numpy\core\include -I/usr/local/include -Itsne/bh_sne_src/ -IC:\Users\hzoe\AppData\Local\Continuum\Anaconda\include -IC:\Users\hzoe\AppData\Local\Continuum\Anaconda\PC /Tptsne/bh_sne_src/quadtree.cpp /Fobuild\temp.win-amd64-2.7\Release\tsne/bh_sne_src/quadtree.obj -msse2 -O3 -fPIC -w cl : Command line warning D9025 : overriding '/W3' with '/w' cl : Command line warning D9002 : ignoring unknown option '-msse2' cl : Command line warning D9002 : ignoring unknown option '-O3' cl : Command line warning D9002 : ignoring unknown option '-fPIC' quadtree.cpp tsne/bh_sne_src/quadtree.cpp(12) : fatal error C1083: Cannot open include file: 'cblas.h': No such file or directory error: command 'C:\\Users\\hzoe\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status 2 ---------------------------------------- Command "C:\Users\hzoe\AppData\Local\Continuum\Anaconda\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\hzoe\\appdata\\local\\temp\\pip-build-vicxy7\\tsne\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record c:\users\hzoe\appdata\local\temp\pip-so57qk-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in c:\users\hzoe\appdata\local\temp\pip-build-vicxy7\tsne\ </code></pre> <p>I am using Anaconda for python and I installed Visual C++ compiler for Windows too.</p>
0
2016-09-22T15:25:07Z
39,643,572
<p>The problem looks familiar. If you haven't done so already, the most immediate thing to do is to try:</p> <pre><code>easy_install tsne </code></pre> <p>or </p> <pre><code>npm install git+https://github.com/danielfrg/tsne.git </code></pre> <p>Also try the following, but you may need homebrew or have permission denied:</p> <pre><code>apt-get install tsne </code></pre> <p>Hope these would help.</p>
0
2016-09-22T15:50:44Z
[ "python", "pip" ]
Random Odd Numbers
39,643,063
<p>My professor gave us our first assignment (Cs315), which involves dealing with some huge (odd) integers and determining if they are prime. I started to do this in c++ until I realized that even long long ints could not hold the numbers needed, so I was left with the choices of making a class of vectors in c++, or learning python in a few days. This simple piece of Python code is supposed to spit out an odd 256 bit random number. It spits out random numbers, both even and odd, and I don't know why, but my guess is a that it is a simple syntactical error that I am not seeing.</p> <pre><code>import random x = random.getrandbits(256) if x % 2 == 0: x + 1 print x </code></pre>
0
2016-09-22T15:26:00Z
39,643,121
<p>You need to assign <code>x + 1</code> back to <code>x</code>. You can either do this like this: <code>x = x+1</code> or like this: <code>x += 1</code></p>
1
2016-09-22T15:28:40Z
[ "python", "python-3.x" ]
SQLObject install without internet
39,643,082
<p>Trying to setup a python flask server in a controlled environment, no access to internet</p> <pre><code># python setup.py install Traceback (most recent call last): File "setup.py", line 9, in &lt;module&gt; use_setuptools() File "/tmp/app_dependencies/SQLObject-3.1.0/ez_setup.py", line 150, in use_setuptools version = _resolve_version(version) File "/tmp/app_dependencies/SQLObject-3.1.0/ez_setup.py", line 358, in _resolve_version resp = urlopen(meta_url) File "/usr/lib64/python2.6/urllib2.py", line 126, in urlopen return _opener.open(url, data, timeout) File "/usr/lib64/python2.6/urllib2.py", line 391, in open response = self._open(req, data) File "/usr/lib64/python2.6/urllib2.py", line 409, in _open '_open', req) File "/usr/lib64/python2.6/urllib2.py", line 369, in _call_chain result = func(*args) File "/usr/lib64/python2.6/urllib2.py", line 1198, in https_open return self.do_open(httplib.HTTPSConnection, req) File "/usr/lib64/python2.6/urllib2.py", line 1165, in do_open raise URLError(err) urllib2.URLError: &lt;urlopen error [Errno 97] Address family not supported by protocol&gt; </code></pre>
0
2016-09-22T15:27:19Z
39,662,030
<p>Was able to install from a wheel file</p> <pre><code>pip install SQLObject-version.whl </code></pre>
0
2016-09-23T13:28:47Z
[ "python", "linux", "python-2.6", "sqlobject" ]
How to add navigation bar to PyDev?
39,643,128
<p>I am trying to add navigation bar to PyDev, something like <a href="http://help.eclipse.org/kepler/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Freference%2Fref-java-editor-breadcrumb.htm" rel="nofollow">this</a>.</p> <p>Is this navigation bar Breadcrumb for Java only?</p>
0
2016-09-22T15:29:08Z
39,644,740
<p>Unfortunately, this is java only (there's nothing really on the platform to implement it, all the code is inside JDT, the java plugin).</p>
0
2016-09-22T16:52:39Z
[ "python", "pydev", "navigationbar" ]
Why get a new logger object in each new module?
39,643,146
<p>The python logging module has a common pattern (<a href="http://stackoverflow.com/a/15735146/52074">ex1</a>, <a href="https://docs.python.org/2/howto/logging.html#advanced-logging-tutorial" rel="nofollow">ex2</a>) where in each module you get a new logger object for each python module.</p> <p>I'm not a fan of blindly following patterns and so I would like to understand a little bit more.</p> <p><strong>Why get a new logger object in each new module?</strong></p> <p>Why not have everyone just use the same root logger and configure the formatter with <code>%(module)s</code>?</p> <p>Is there examples where this pattern is NECESSARY/NEEDED (i.e. because of some sort of performance reason[1])?</p> <p>[1] In a multi-threaded python program, is there some sort of hidden synchronization issues that is fixed by using multiple logging objects?</p>
0
2016-09-22T15:29:49Z
39,643,474
<p>Each logger can be configured separately. Generally, a module logger is not configured <em>at all</em> in the module itself. You create a distinct logger and use it to log messages of varying levels of detail. Whoever <em>uses</em> the logger decides what level of messages to see, where to send those messages, and even how to display them. They may want everything (<code>DEBUG</code> and up) from one module logged to a file, while another module they may only care if a serious error occurs (in which case they want it e-mailed directly to them). If every module used the same (root) logger, you wouldn't have that kind of flexibility.</p>
1
2016-09-22T15:46:02Z
[ "python", "multithreading", "performance", "logging", "instrumentation" ]
Why get a new logger object in each new module?
39,643,146
<p>The python logging module has a common pattern (<a href="http://stackoverflow.com/a/15735146/52074">ex1</a>, <a href="https://docs.python.org/2/howto/logging.html#advanced-logging-tutorial" rel="nofollow">ex2</a>) where in each module you get a new logger object for each python module.</p> <p>I'm not a fan of blindly following patterns and so I would like to understand a little bit more.</p> <p><strong>Why get a new logger object in each new module?</strong></p> <p>Why not have everyone just use the same root logger and configure the formatter with <code>%(module)s</code>?</p> <p>Is there examples where this pattern is NECESSARY/NEEDED (i.e. because of some sort of performance reason[1])?</p> <p>[1] In a multi-threaded python program, is there some sort of hidden synchronization issues that is fixed by using multiple logging objects?</p>
0
2016-09-22T15:29:49Z
39,643,502
<p>The logger name defines <em>where</em> (logically) in your application events occur. Hence, the recommended pattern</p> <pre><code>logger = logging.getLogger(__name__) </code></pre> <p>uses logger names which track the Python package hierarchy. This in turn allows whoever is configuring logging to turn verbosity up or down for specific loggers. If everything just used the root logger, one couldn't get fine grained control of verbosity, which is important when systems reach a certain size / complexity.</p> <p>The logger names don't need to exactly track the package names - you could have multiple loggers in certain packages, for example. The main deciding factor is how much flexibility is needed (if you're writing an application) and perhaps also how much flexibility your users need (if you're writing a library). </p>
1
2016-09-22T15:47:19Z
[ "python", "multithreading", "performance", "logging", "instrumentation" ]
Interactive matplotlib widget not updating with scipy ode solver
39,643,192
<p>I have been using the interactive matplotlib widgets to visualise the solution of differential equations. I have got it working with the odeint function in scipy, however have not managed to get it to update with the ode class. I would rather use the latter as it has greater control over which solver is used.</p> <p>The following code is used to solve a differential that is an exponential decay. The y0 is the amplitude of the decay. The code stops working when solver.integrate(t1) is called inside the update function. I'm not sure why this is.</p> <pre><code>from scipy.integrate import ode # solve the system dy/dt = f(t, y) def f(t, y): return -y / 10 # Array to save results to def solout(t, y): sol.append([t, *y]) solver = ode(f).set_integrator('dopri5') solver.set_solout(solout) # Initial conditions y0 = [1] # Initial amplitude t0 = 0 # Start time t1 = 20 # End time fig = plt.figure(figsize=(10, 6)) fig.subplots_adjust(left=0.25, bottom=0.4) ax = plt.subplot(111) # solve the DEs solver.set_initial_value(y0, t0) sol = [] solver.integrate(t1) sol = np.array(sol) t = sol[:, 0] y = sol[:, 1] l, = plt.plot(t, y, lw=2, color='red') plt.axis([0, 20, 0, 1.1]) plt.xlabel('Time (ms)') plt.ylabel('n1(t)') plt.grid() axcolor = 'lightgoldenrodyellow' axn1 = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor) sn1 = Slider(axn1, 'y(0)', 0, 1.0, valinit=1) def update(val): y0 = [sn1.val] solver.set_initial_value(y0, t0) sol = [] solver.integrate(t1) sol = np.array(sol) t = sol[:, 0] y = sol[:, 1] l.set_data(t, y) plt.draw() sn1.on_changed(update) </code></pre>
0
2016-09-22T15:31:23Z
39,649,575
<p><em>For next time, please post the complete code with all imports etc. such that people can actually reproduce your problem.</em></p> <p>Comming to the question: I guess it's always wise to seperate calculations from plotting. Therefore first try to solve the ODE with some given initial conditions. Once that works, try the plotting and interactive stuff.</p> <p>In your case we would build a function that solves the ODE and then use this function with different initial conditions also in the plotting updates.</p> <pre><code>import matplotlib.pyplot as plt from matplotlib.widgets import Slider import numpy as np from scipy.integrate import ode # solve the system dy/dt = f(t, y) def f(t, y): a = np.zeros((1,1)) a[0] = -y / 10. return a #define a function to solve the ODE with initial conditions def solve(t0, t1, y0, steps=210): solver.set_initial_value([y0], t0) dt = (t1 - t0) / (steps - 1) solver.set_initial_value([y0], t0) t = np.zeros((steps, 1)) Y = np.zeros((steps, 1)) t[0] = t0 Y[0] = y0 k = 1 while solver.successful() and k &lt; steps: solver.integrate(solver.t + dt) t[k] = solver.t Y[k] = solver.y[0] k += 1 return t, Y # set the ODE integrator solver = ode(f).set_integrator("dopri5") # Initial conditions y0 = 1. # Initial amplitude t0 = 0. # Start time t1 = 20. # End time #solve once for given initial amplitude t, Y = solve(t0, t1, y0) fig = plt.figure(figsize=(10, 6)) fig.subplots_adjust(left=0.25, bottom=0.4) ax = plt.subplot(111) l, = plt.plot(t, Y, lw=2, color='red') plt.axis([0, 20, 0, 1.1]) plt.xlabel('Time (ms)') plt.ylabel('n1(t)') plt.grid() axn1 = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg='#e4e4e4') sn1 = Slider(axn1, 'y(0)', 0, 1.0, valinit=1) def update(val): #solve again each time t, Y = solve(t0, t1, sn1.val) l.set_data(t, Y) plt.draw() sn1.on_changed(update) plt.show() </code></pre>
0
2016-09-22T22:04:03Z
[ "python", "matplotlib", "scipy" ]
Python Dictionary Comment Out a Line not Working
39,643,199
<p>I have a python dictionary that I import from another script. For example here is the dictionary that is in another script and loaded in:</p> <pre><code>def Log(): LogD = { 'Key': [0, 1, 2], 'Key2': [0, 1, 2], 'Key3': [0, 1, 2], # and so on for about 100 records } return LogD </code></pre> <p>And here is the line loading it in:</p> <pre><code>sys.path.append(r'C:/Whatever') import Log LogD = Log.Log() </code></pre> <p>I import it into my other script do some stuff with it and whatever. I also have a module that comments our a line in the dictionary if I want it to be deleted (ignored). That module finds the line and adds a <strong># comment</strong> to the line in the dictionary like so:</p> <pre><code>def Log(): LogD = { 'Key': [0, 1, 2], #'Key2': [0, 1, 2], 'Key3': [0, 1, 2], # and so on for about 100 records } return LogD </code></pre> <p>But when I reload the dictionary module, the commented line still appears in the dictionary. No idea why, if I don't load the dictionary as a module and include it in my running script the comment works fine. Any ideas?</p>
-2
2016-09-22T15:31:48Z
39,859,194
<p>So since no one answered this I have figured it out. Props goes to someone who commented about PYC not indexing correctly. So I added a </p> <pre><code>os.remove(whatever.pyc) </code></pre> <p>after I edit my dictionary and everything works great.</p>
0
2016-10-04T18:19:39Z
[ "python", "dictionary", "comments" ]
Is it possible to group tensorflow FLAGS by type and generate a string from them?
39,643,256
<p>Is it possible to group tensorflow FLAGS by type? E.g. Some flags are system related (e.g. # of threads) while others are model hyperparams.</p> <p>Then, is it possible to use the model hyperparams FLAGS, in order to generate a string? (the string will be used to identify the model filename)</p> <p>Thanks</p>
0
2016-09-22T15:34:35Z
39,664,586
<p>I'm guessing that you're wanting to automatically store the hyper-parameters as part of the file name in order to organize your experiments better? Unfortunately there isn't a good way to do this with TensorFlow, but you can look at some of the high-level frameworks built on top of it to see if they offer something similar.</p>
0
2016-09-23T15:33:46Z
[ "python", "machine-learning", "computer-vision", "tensorflow" ]
Python Scraping - Unable to get required data from Flipkart
39,643,390
<p>I was trying to scrape the customer reviews from Flipkart website. The following is the <a href="https://www.flipkart.com/samsung-galaxy-j5-6-new-2016-edition-white-16-gb/product-reviews/itmegmrnzqjcpfg9?pid=MOBEG4XWJG7F9A6Z" rel="nofollow">link</a>. The following was my code to scrape, but it is always returning an empty list.</p> <pre><code>&gt;&gt;&gt; from bs4 import BeautifulSoup &gt;&gt;&gt; import requests &gt;&gt;&gt; r = requests.get('https://www.flipkart.com/samsung-galaxy-j5-6-new-2016-edition-white-16-gb/product-reviews/itmegmrnzqjcpfg9?pid=MOBEG4XWJG7F9A6Z') &gt;&gt;&gt; soup = BeautifulSoup(r.content, 'lxml') # Tried with 'html.parser' also &gt;&gt;&gt; soup.find_all('div', '_3DCdKt') [] &gt;&gt;&gt; soup.find_all('div', {'class': '_3DCdKt'}) [] &gt;&gt;&gt; soup.find_all('div', {'class': 'row _3wYu6I _3BRC7L'}) [] &gt;&gt;&gt; soup.find_all('div', {'class': '_1GRhLX hFPo14'}) [] </code></pre> <p>So, I tried to get the entire section, but I was getting only the following:</p> <pre><code>&gt;&gt;&gt; soup.find_all('div', {'class': 'col-9-12'}) [&lt;div class="col-9-12" data-reactid="96"&gt;&lt;div class="row _2_xtR5" data-reactid="97"&gt;&lt;/div&gt;&lt;div class="row _3wYu6I _1KVtzT" data-reactid="98"&gt;&lt;/div&gt;&lt;/div&gt;] </code></pre> <p>I was not getting the other contents. So, next I tried with selenium, even then it was returning <code>None</code>. The following is my selenium code:</p> <pre><code>&gt;&gt;&gt; driver = webdriver.Firefox() &gt;&gt;&gt; driver.get('https://www.flipkart.com/samsung-galaxy-j5-6-new-2016-edition-white-16-gb/product-reviews/itmegmrnzqjcpfg9?pid=MOBEG4XWJG7F9A6Z') &gt;&gt;&gt; a = driver.find_elements_by_class_name("_3DCdKt") &gt;&gt;&gt; len(a) 10 &gt;&gt;&gt; for i in a: ... print i.get_attribute('value') ... None None None None None None None None None None </code></pre> <p>What might be the problem? Am I doing any mistakes in the code. Kindly help. I am new to Python.</p>
1
2016-09-22T15:41:21Z
39,643,968
<p>This seemed to work for me</p> <pre><code>from selenium import webdriver from bs4 import BeautifulSoup driver = webdriver.Firefox() driver.get('https://www.flipkart.com/samsung-galaxy-j5-6-new-2016-edition-white-16-gb/product-reviews/itmegmrnzqjcpfg9?pid=MOBEG4XWJG7F9A6Z') html = driver.page_source soup = BeautifulSoup(html, 'lxml') for entry in soup.find_all('div', '_3DCdKt'): print(entry.text) </code></pre> <p>Perhaps change <code>entry.text</code> to just <code>entry</code>, depending on your needs.</p> <p>Output was:</p> <pre><code>5★Best Smartphone by SamsungThanks to Flipkart who deliver it me with in 5 days Good Phone With Metal Body And Best front Camera With FlashBest for night Selfie I Take more than 30 pic in night mode with front flash good smartphone gold color is also superebbest ever smartphone under 15k by samsungGood BatteryGood Camera Front with Flash and Rear Also SuperbREAD MOREHappy ThakurCertified Buyer16 May, 201621776PermalinkReport Abuse 5★Must BuyThis Phone is awesome..Must BuyREAD MOREDurvank AregekarCertified Buyer10 Aug, 201680PermalinkReport Abuse 3★Good looking phone with some drawbacksHi,I got this phone from Flipkart on Friday and here is my 3 days review.Pros: * Beautiful design * Very handy, easy to handle * Battery backup is great * Back camera is good * No heating issues Cons: * If we are charging, it will not show any light or any notification whether it is charging or not. We need to on the screen and check whether it is charging or not. So every time we need to turn it on and see whether it is charging or not.* Camera issue: Once you take the picture a...READ MOREileep Certified Buyer16 May, 201615167PermalinkReport Abuse 5★Absolute Stunner and ImpressiveUpdated Review on 02-August after 3 months of usage:What I liked most:Look : 100/100 - Very good looking phone. Gold color and the finishing is super coolSize : 100/100 - 5.2 Inch is neither big nor small. I can still operate with one hand.. Battery : 100/100 - 3100 mAH is outstanding. 3G is always ON when i am out of home and Wi-Fi is always ON in home. I am charging mobile only once in every 36 hours. I use Whatsapp, instagram and Browsing mostly. Display : 90/100 - Not so bright and s...READ MORENaresh KaretiCertified Buyer13 May, 201618787PermalinkReport Abuse 5★It's very goodNice.battery backup it's goodREAD MOREFlipkart CustomerCertified Buyer17 Aug, 201660PermalinkReport Abuse 5★Good phoneIt is a good phoneREAD MORESourabh JainCertified Buyer9 Aug, 201660PermalinkReport Abuse 5★Brilliant Phone Compared to MoneySuper Amoled Display..2 GB RAM with Latest Android Marshmallow OS only for 13K....its difficult to get Samsung Phone with 2 GB ram in such a low price Range...used for 15 days....Going Smooth....Awesome Earphone Quality.....selfie and back Camera Good.....Battery last for more than a day with Continous usage or will go for two days....Free Microsoft apps and Much More...READ MOREPrashant DiasCertified Buyer7 Sep, 2016269PermalinkReport Abuse 5★very gooddelivery is in time but my phone is heat will data is on plz checkREAD MORESanthoaha m n santhuCertified Buyer12 Aug, 201681PermalinkReport Abuse 4★By Expert -Vaishnav VJGood Product by SamsungThe things from this phone is 1. Marshmellow v6.0 2. Front flash with 5mb camera not so good 3. Its design 4. Primary Camera is not so good with 13mb led flash 5. Battery life is also not so good 6. Its size is correct in its design 7. Supports OTG 9. Only 2GB RAM 10. 16GB Internal storage but only 11GB is availiable 11. 4G supports 12. Ultra power saving mode 13. S bike mode 14. Spe...READ MOREVaishnav Certified Buyer17 May, 2016155PermalinkReport Abuse 4★Look is great but camera is a bit slow.I have been using this phone for the past one month. Look is great and also has metal body. So far I have only noticed a bit slowness in the camera while capturing a photo and switching between your photo gallery and camera. Other than that, phone works fine (good battery back-up) - need to see how long it lastsREAD MOREFlipkart CustomerCertified Buyer17 Aug, 201692PermalinkReport Abuse </code></pre> <p>Selenium is slow, so if you don't need it (see Padraic Cunningham answer), I wouldn't use it.</p>
0
2016-09-22T16:10:11Z
[ "python", "selenium", "beautifulsoup" ]
Python Scraping - Unable to get required data from Flipkart
39,643,390
<p>I was trying to scrape the customer reviews from Flipkart website. The following is the <a href="https://www.flipkart.com/samsung-galaxy-j5-6-new-2016-edition-white-16-gb/product-reviews/itmegmrnzqjcpfg9?pid=MOBEG4XWJG7F9A6Z" rel="nofollow">link</a>. The following was my code to scrape, but it is always returning an empty list.</p> <pre><code>&gt;&gt;&gt; from bs4 import BeautifulSoup &gt;&gt;&gt; import requests &gt;&gt;&gt; r = requests.get('https://www.flipkart.com/samsung-galaxy-j5-6-new-2016-edition-white-16-gb/product-reviews/itmegmrnzqjcpfg9?pid=MOBEG4XWJG7F9A6Z') &gt;&gt;&gt; soup = BeautifulSoup(r.content, 'lxml') # Tried with 'html.parser' also &gt;&gt;&gt; soup.find_all('div', '_3DCdKt') [] &gt;&gt;&gt; soup.find_all('div', {'class': '_3DCdKt'}) [] &gt;&gt;&gt; soup.find_all('div', {'class': 'row _3wYu6I _3BRC7L'}) [] &gt;&gt;&gt; soup.find_all('div', {'class': '_1GRhLX hFPo14'}) [] </code></pre> <p>So, I tried to get the entire section, but I was getting only the following:</p> <pre><code>&gt;&gt;&gt; soup.find_all('div', {'class': 'col-9-12'}) [&lt;div class="col-9-12" data-reactid="96"&gt;&lt;div class="row _2_xtR5" data-reactid="97"&gt;&lt;/div&gt;&lt;div class="row _3wYu6I _1KVtzT" data-reactid="98"&gt;&lt;/div&gt;&lt;/div&gt;] </code></pre> <p>I was not getting the other contents. So, next I tried with selenium, even then it was returning <code>None</code>. The following is my selenium code:</p> <pre><code>&gt;&gt;&gt; driver = webdriver.Firefox() &gt;&gt;&gt; driver.get('https://www.flipkart.com/samsung-galaxy-j5-6-new-2016-edition-white-16-gb/product-reviews/itmegmrnzqjcpfg9?pid=MOBEG4XWJG7F9A6Z') &gt;&gt;&gt; a = driver.find_elements_by_class_name("_3DCdKt") &gt;&gt;&gt; len(a) 10 &gt;&gt;&gt; for i in a: ... print i.get_attribute('value') ... None None None None None None None None None None </code></pre> <p>What might be the problem? Am I doing any mistakes in the code. Kindly help. I am new to Python.</p>
1
2016-09-22T15:41:21Z
39,644,642
<p>The reviews etc.. are populated using <em>reactjs</em>, the data is retrieved using an ajax request which you can mimic with requests:</p> <pre><code>import requests data = {"productId": "MOBEG4XWJG7F9A6Z", # end of url pid=MOBEG4XWJG7F9A6Z "count": "15", "ratings": "ALL", "reviewerType:ALL" "sortOrder": "MOST_HELPFUL"} headers = ({"x-user-agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.92 Safari/537.36 FKUA/website/41/website/Desktop"}) data = requests.get("https://www.flipkart.com/api/3/product/reviews", params=data, headers=headers).json() print(data) </code></pre> <p>What you want is to access <code>data["RESPONSE"]["data"]</code> which is a list of dicts:</p> <pre><code>for dct in data["RESPONSE"]["data"] print(dct) </code></pre> <p>Which will give you:</p> <pre><code>{u'action': None, u'fixed': False, u'value': {u'rating': 5, u'text': u'Thanks to Flipkart who deliver it me with in 5 days \nGood Phone With Metal Body \nAnd Best front Camera With Flash\nBest for night Selfie \nI Take more than 30 pic in night mode with front flash \ngood smartphone gold color is also supereb\nbest ever smartphone under 15k by samsung\nGood Battery\nGood Camera Front with Flash and Rear Also Superb', u'reportAbuse': {u'action': {u'originalUrl': None, u'params': {u'vote': u'ABUSE', u'reviewId': u'be37810e-20fe-4417-9d88-2709288cf2ba', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 0, u'type': u'VoteValue'}, u'tracking': None}, u'totalCount': 285, u'downvote': {u'action': {u'originalUrl': None, u'params': {u'vote': u'DOWN', u'reviewId': u'be37810e-20fe-4417-9d88-2709288cf2ba', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 74, u'type': u'VoteValue'}, u'tracking': None}, u'id': u'be37810e-20fe-4417-9d88-2709288cf2ba', u'author': u'Happy Thakur', u'url': u'/reviews/be37810e-20fe-4417-9d88-2709288cf2ba', u'upvote': {u'action': {u'originalUrl': None, u'params': {u'vote': u'UP', u'reviewId': u'be37810e-20fe-4417-9d88-2709288cf2ba', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 211, u'type': u'VoteValue'}, u'tracking': None}, u'helpfulCount': 211, u'created': u'16 May, 2016', u'certifiedBuyer': True, u'title': u'Best Smartphone by Samsung', u'type': u'ProductReviewValue'}, u'tracking': None} {u'action': None, u'fixed': False, u'value': {u'rating': 5, u'text': u"Updated Review on 02-August after 3 months of usage:\nWhat I liked most:\nLook : 100/100 - Very good looking phone. Gold color and the finishing is super cool\nSize : 100/100 - 5.2 Inch is neither big nor small. I can still operate with one hand.. \nBattery : 100/100 - 3100 mAH is outstanding. 3G is always ON when i am out of home and Wi-Fi is always ON in home. I am charging mobile only once in every 36 hours. I use Whatsapp, instagram and Browsing mostly. \nDisplay : 90/100 - Not so bright and sharp as S series phones, but a real deal for the price. Impressed again. My only worry is about it is not having a Gorilla scratch proof glass. I may need to use tempered glass.\nTouch : 95/100 - So smooth and I dont see any lags as of now.\nCamera : 90/100 - Photos are good and can capture fast, but again not as great as S series phones. but at this price I believe this phone outclasses all other competitors in camera department. \n\nOne last thing is about the SAMSUNG brand and its service center coverage, which is again awesome. \nOverall I am completely satisfied with the phone and this phone reached my expectations. \nWhat I disliked:\nEarphone jack at the bottom.. I feel uncomfortable when chatting and listening to songs at same time\nLow speaker volume, not a big deal though for me, As i don't use loudspeaker for songs mostly", u'reportAbuse': {u'action': {u'originalUrl': None, u'params': {u'vote': u'ABUSE', u'reviewId': u'e786669a-024b-4ef0-b70c-1e4fcf5fe5ff', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 0, u'type': u'VoteValue'}, u'tracking': None}, u'totalCount': 272, u'downvote': {u'action': {u'originalUrl': None, u'params': {u'vote': u'DOWN', u'reviewId': u'e786669a-024b-4ef0-b70c-1e4fcf5fe5ff', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 87, u'type': u'VoteValue'}, u'tracking': None}, u'id': u'e786669a-024b-4ef0-b70c-1e4fcf5fe5ff', u'author': u'Naresh Kareti', u'url': u'/reviews/e786669a-024b-4ef0-b70c-1e4fcf5fe5ff', u'upvote': {u'action': {u'originalUrl': None, u'params': {u'vote': u'UP', u'reviewId': u'e786669a-024b-4ef0-b70c-1e4fcf5fe5ff', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 185, u'type': u'VoteValue'}, u'tracking': None}, u'helpfulCount': 185, u'created': u'13 May, 2016', u'certifiedBuyer': True, u'title': u'Absolute Stunner and Impressive', u'type': u'ProductReviewValue'}, u'tracking': None} {u'action': None, u'fixed': False, u'value': {u'rating': 3, u'text': u'Hi,\n\nI got this phone from Flipkart on Friday and here is my 3 days review.\n\nPros:\n * Beautiful design\n * Very handy, easy to handle\n * Battery backup is great\n * Back camera is good\n * No heating issues\n \nCons:\n * If we are charging, it will not show any light or any notification whether it is charging or not. We need to on the screen and check whether it is charging or not. So every time we need to turn it on and see whether it is charging or not.\n* Camera issue: Once you take the picture and then press the back button it is taking some time to come back to camera mode.\n* If you turn on the flash and take pic with back camera it is taking some time to capture the picture. With out Flash it is taking very fast.\n* Volume is very low. Not enough for a medium sized room.\n* Ear phones are not good especially for me. \n\n\nWill post my feedback after using it another 15 days.\n\nThanks', u'reportAbuse': {u'action': {u'originalUrl': None, u'params': {u'vote': u'ABUSE', u'reviewId': u'9cbcd27c-a8ad-4793-978a-5903cd086252', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 0, u'type': u'VoteValue'}, u'tracking': None}, u'totalCount': 212, u'downvote': {u'action': {u'originalUrl': None, u'params': {u'vote': u'DOWN', u'reviewId': u'9cbcd27c-a8ad-4793-978a-5903cd086252', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 67, u'type': u'VoteValue'}, u'tracking': None}, u'id': u'9cbcd27c-a8ad-4793-978a-5903cd086252', u'author': u'ileep ', u'url': u'/reviews/9cbcd27c-a8ad-4793-978a-5903cd086252', u'upvote': {u'action': {u'originalUrl': None, u'params': {u'vote': u'UP', u'reviewId': u'9cbcd27c-a8ad-4793-978a-5903cd086252', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 145, u'type': u'VoteValue'}, u'tracking': None}, u'helpfulCount': 145, u'created': u'16 May, 2016', u'certifiedBuyer': True, u'title': u'Good looking phone with some drawbacks', u'type': u'ProductReviewValue'}, u'tracking': None} {u'action': None, u'fixed': False, u'value': {u'rating': 5, u'text': u'Super Amoled Display..2 GB RAM with Latest Android Marshmallow OS only for 13K....its difficult to get Samsung Phone with 2 GB ram in such a low price Range...used for 15 days....Going Smooth....Awesome Earphone Quality.....selfie and back Camera Good.....Battery last for more than a day with Continous usage or will go for two days....Free Microsoft apps and Much More...', u'reportAbuse': {u'action': {u'originalUrl': None, u'params': {u'vote': u'ABUSE', u'reviewId': u'1546ed16-5945-4257-9f2d-0d86db7ed92e', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 0, u'type': u'VoteValue'}, u'tracking': None}, u'totalCount': 34, u'downvote': {u'action': {u'originalUrl': None, u'params': {u'vote': u'DOWN', u'reviewId': u'1546ed16-5945-4257-9f2d-0d86db7ed92e', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 9, u'type': u'VoteValue'}, u'tracking': None}, u'id': u'1546ed16-5945-4257-9f2d-0d86db7ed92e', u'author': u'Prashant Dias', u'url': u'/reviews/1546ed16-5945-4257-9f2d-0d86db7ed92e', u'upvote': {u'action': {u'originalUrl': None, u'params': {u'vote': u'UP', u'reviewId': u'1546ed16-5945-4257-9f2d-0d86db7ed92e', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 25, u'type': u'VoteValue'}, u'tracking': None}, u'helpfulCount': 25, u'created': u'7 Sep, 2016', u'certifiedBuyer': True, u'title': u'Brilliant Phone Compared to Money', u'type': u'ProductReviewValue'}, u'tracking': None} {u'action': None, u'fixed': False, u'value': {u'rating': 5, u'text': u"Nice.battery backup it's good", u'reportAbuse': {u'action': {u'originalUrl': None, u'params': {u'vote': u'ABUSE', u'reviewId': u'a9f2f6a0-2272-4187-bd37-48eb8a0a85c9', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 0, u'type': u'VoteValue'}, u'tracking': None}, u'totalCount': 5, u'downvote': {u'action': {u'originalUrl': None, u'params': {u'vote': u'DOWN', u'reviewId': u'a9f2f6a0-2272-4187-bd37-48eb8a0a85c9', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 0, u'type': u'VoteValue'}, u'tracking': None}, u'id': u'a9f2f6a0-2272-4187-bd37-48eb8a0a85c9', u'author': u'Flipkart Customer', u'url': u'/reviews/a9f2f6a0-2272-4187-bd37-48eb8a0a85c9', u'upvote': {u'action': {u'originalUrl': None, u'params': {u'vote': u'UP', u'reviewId': u'a9f2f6a0-2272-4187-bd37-48eb8a0a85c9', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 5, u'type': u'VoteValue'}, u'tracking': None}, u'helpfulCount': 5, u'created': u'17 Aug, 2016', u'certifiedBuyer': True, u'title': u"It's very good", u'type': u'ProductReviewValue'}, u'tracking': None} {u'action': None, u'fixed': False, u'value': {u'rating': 5, u'text': u'This Phone is awesome..Must Buy', u'reportAbuse': {u'action': {u'originalUrl': None, u'params': {u'vote': u'ABUSE', u'reviewId': u'cf8cf2c8-1f79-4d56-a4cd-e641ffb3551b', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 0, u'type': u'VoteValue'}, u'tracking': None}, u'totalCount': 5, u'downvote': {u'action': {u'originalUrl': None, u'params': {u'vote': u'DOWN', u'reviewId': u'cf8cf2c8-1f79-4d56-a4cd-e641ffb3551b', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 0, u'type': u'VoteValue'}, u'tracking': None}, u'id': u'cf8cf2c8-1f79-4d56-a4cd-e641ffb3551b', u'author': u'Durvank Aregekar', u'url': u'/reviews/cf8cf2c8-1f79-4d56-a4cd-e641ffb3551b', u'upvote': {u'action': {u'originalUrl': None, u'params': {u'vote': u'UP', u'reviewId': u'cf8cf2c8-1f79-4d56-a4cd-e641ffb3551b', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 5, u'type': u'VoteValue'}, u'tracking': None}, u'helpfulCount': 5, u'created': u'10 Aug, 2016', u'certifiedBuyer': True, u'title': u'Must Buy', u'type': u'ProductReviewValue'}, u'tracking': None} {u'action': None, u'fixed': False, u'value': {u'rating': 5, u'text': u'It is a good phone', u'reportAbuse': {u'action': {u'originalUrl': None, u'params': {u'vote': u'ABUSE', u'reviewId': u'ce31beb5-5c8f-4a2d-be7d-aba416592df2', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 0, u'type': u'VoteValue'}, u'tracking': None}, u'totalCount': 5, u'downvote': {u'action': {u'originalUrl': None, u'params': {u'vote': u'DOWN', u'reviewId': u'ce31beb5-5c8f-4a2d-be7d-aba416592df2', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 0, u'type': u'VoteValue'}, u'tracking': None}, u'id': u'ce31beb5-5c8f-4a2d-be7d-aba416592df2', u'author': u'Sourabh Jain', u'url': u'/reviews/ce31beb5-5c8f-4a2d-be7d-aba416592df2', u'upvote': {u'action': {u'originalUrl': None, u'params': {u'vote': u'UP', u'reviewId': u'ce31beb5-5c8f-4a2d-be7d-aba416592df2', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 5, u'type': u'VoteValue'}, u'tracking': None}, u'helpfulCount': 5, u'created': u'9 Aug, 2016', u'certifiedBuyer': True, u'title': u'Good phone', u'type': u'ProductReviewValue'}, u'tracking': None} {u'action': None, u'fixed': False, u'value': {u'rating': 5, u'text': u'delivery is in time but my phone is heat will data is on plz check', u'reportAbuse': {u'action': {u'originalUrl': None, u'params': {u'vote': u'ABUSE', u'reviewId': u'1fcf5a13-edef-4b16-8372-8732819c143c', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 0, u'type': u'VoteValue'}, u'tracking': None}, u'totalCount': 9, u'downvote': {u'action': {u'originalUrl': None, u'params': {u'vote': u'DOWN', u'reviewId': u'1fcf5a13-edef-4b16-8372-8732819c143c', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 1, u'type': u'VoteValue'}, u'tracking': None}, u'id': u'1fcf5a13-edef-4b16-8372-8732819c143c', u'author': u'Santhoaha m n santhu', u'url': u'/reviews/1fcf5a13-edef-4b16-8372-8732819c143c', u'upvote': {u'action': {u'originalUrl': None, u'params': {u'vote': u'UP', u'reviewId': u'1fcf5a13-edef-4b16-8372-8732819c143c', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 8, u'type': u'VoteValue'}, u'tracking': None}, u'helpfulCount': 8, u'created': u'12 Aug, 2016', u'certifiedBuyer': True, u'title': u'very good', u'type': u'ProductReviewValue'}, u'tracking': None} {u'action': None, u'fixed': False, u'value': {u'rating': 4, u'text': u'Good Product by Samsung\n\nThe things from this phone is\n 1. Marshmellow v6.0\n 2. Front flash with 5mb camera not so good\n 3. Its design\n 4. Primary Camera is not so good with 13mb led flash\n 5. Battery life is also not so good\n 6. Its size is correct in its design\n 7. Supports OTG\n 9. Only 2GB RAM\n 10. 16GB Internal storage but only 11GB is availiable\n 11. 4G supports\n 12. Ultra power saving mode\n 13. S bike mode\n 14. Speaker volume is not so good\n 15. 3G supports\n 16. Ultra data saving\n 17. No auto brightness\n 18. 2G supports\n 19. Top performance \n 20. Good phone at the price 14000\n *********************', u'reportAbuse': {u'action': {u'originalUrl': None, u'params': {u'vote': u'ABUSE', u'reviewId': u'958efa75-1b67-4872-9f71-b18035fafe6a', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 0, u'type': u'VoteValue'}, u'tracking': None}, u'totalCount': 20, u'downvote': {u'action': {u'originalUrl': None, u'params': {u'vote': u'DOWN', u'reviewId': u'958efa75-1b67-4872-9f71-b18035fafe6a', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 5, u'type': u'VoteValue'}, u'tracking': None}, u'id': u'958efa75-1b67-4872-9f71-b18035fafe6a', u'author': u'Vaishnav ', u'url': u'/reviews/958efa75-1b67-4872-9f71-b18035fafe6a', u'upvote': {u'action': {u'originalUrl': None, u'params': {u'vote': u'UP', u'reviewId': u'958efa75-1b67-4872-9f71-b18035fafe6a', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 15, u'type': u'VoteValue'}, u'tracking': None}, u'helpfulCount': 15, u'created': u'17 May, 2016', u'certifiedBuyer': True, u'title': u'By Expert -Vaishnav VJ', u'type': u'ProductReviewValue'}, u'tracking': None} {u'action': None, u'fixed': False, u'value': {u'rating': 4, u'text': u'Very nice device', u'reportAbuse': {u'action': {u'originalUrl': None, u'params': {u'vote': u'ABUSE', u'reviewId': u'c7177dfb-39c2-4c0b-8bbd-288f96757c3a', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 0, u'type': u'VoteValue'}, u'tracking': None}, u'totalCount': 4, u'downvote': {u'action': {u'originalUrl': None, u'params': {u'vote': u'DOWN', u'reviewId': u'c7177dfb-39c2-4c0b-8bbd-288f96757c3a', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 0, u'type': u'VoteValue'}, u'tracking': None}, u'id': u'c7177dfb-39c2-4c0b-8bbd-288f96757c3a', u'author': u'Flipkart Customer', u'url': u'/reviews/c7177dfb-39c2-4c0b-8bbd-288f96757c3a', u'upvote': {u'action': {u'originalUrl': None, u'params': {u'vote': u'UP', u'reviewId': u'c7177dfb-39c2-4c0b-8bbd-288f96757c3a', u'reviewDomain': u'PRODUCT'}, u'loginType': u'LEGACY_LOGIN', u'url': None, u'fallback': None, u'type': u'REVIEW_VOTE', u'omnitureData': None, u'screenType': None, u'tracking': {}}, u'fixed': False, u'value': {u'count': 4, u'type': u'VoteValue'}, u'tracking': None}, u'helpfulCount': 4, u'created': u'8 Sep, 2016', u'certifiedBuyer': True, u'title': u'Good quality product', u'type': u'ProductReviewValue'}, u'tracking': None} </code></pre> <p>The <code>x-user-agent</code> is required, without it you will get a 403. You can play around with the parameters to see different results, I will leave that up to you.</p>
4
2016-09-22T16:46:45Z
[ "python", "selenium", "beautifulsoup" ]
How can I make a python script change itself?
39,643,428
<p>How can I make a python script change itself?</p> <p>To boil it down, I would like to have a python script (<code>run.py</code>)like this</p> <pre><code>a = 0 b = 1 print a + b # do something here such that the first line of this script reads a = 1 </code></pre> <p>Such that the next time the script is run it would look like</p> <pre><code>a = 1 b = 1 print a + b # do something here such that the first line of this script reads a = 2 </code></pre> <p>Is this in any way possible? The script might use external resources; however, everything should work by just running the one <code>run.py</code>-file.</p> <p>EDIT: It may not have been clear enough, but the script should update itself, not any other file. Sure, once you allow for a simple configuration file next to the script, this task is trivial.</p> <p><strong>Answer:</strong></p> <p>It is actually much easier than thought. @khelwood 's suggestion works just fine, opening the script and writing it's own content to it is completely unproblematic. @Gerrat's solution also works nicely. This is how I'm having it:</p> <pre><code># -*- coding: utf-8 -*- a = 0 b = 1 print a + b content = [] with open(__file__,"r") as f: for line in f: content.append(line) with open(__file__,"w") as f: content[1] = "a = {n}\n".format(n=b) content[2] = "b = {n}\n".format(n=a+b) for i in range(len(content)): f.write(content[i]) </code></pre>
0
2016-09-22T15:43:33Z
39,643,816
<p>For an example (changing the value of <code>a</code> each time its run):</p> <pre><code>a = 0 b = 1 print a + b with open(__file__, 'r') as f: lines = f.read().split('\n') val = int(lines[0].split(' = ')[-1]) new_line = 'a = {}'.format(val+1) new_file = '\n'.join([new_line] + lines[1:]) with open(__file__, 'w') as f: f.write('\n'.join([new_line] + lines[1:])) </code></pre>
2
2016-09-22T16:02:37Z
[ "python", "runtime", "interpreter" ]
How can I make a python script change itself?
39,643,428
<p>How can I make a python script change itself?</p> <p>To boil it down, I would like to have a python script (<code>run.py</code>)like this</p> <pre><code>a = 0 b = 1 print a + b # do something here such that the first line of this script reads a = 1 </code></pre> <p>Such that the next time the script is run it would look like</p> <pre><code>a = 1 b = 1 print a + b # do something here such that the first line of this script reads a = 2 </code></pre> <p>Is this in any way possible? The script might use external resources; however, everything should work by just running the one <code>run.py</code>-file.</p> <p>EDIT: It may not have been clear enough, but the script should update itself, not any other file. Sure, once you allow for a simple configuration file next to the script, this task is trivial.</p> <p><strong>Answer:</strong></p> <p>It is actually much easier than thought. @khelwood 's suggestion works just fine, opening the script and writing it's own content to it is completely unproblematic. @Gerrat's solution also works nicely. This is how I'm having it:</p> <pre><code># -*- coding: utf-8 -*- a = 0 b = 1 print a + b content = [] with open(__file__,"r") as f: for line in f: content.append(line) with open(__file__,"w") as f: content[1] = "a = {n}\n".format(n=b) content[2] = "b = {n}\n".format(n=a+b) for i in range(len(content)): f.write(content[i]) </code></pre>
0
2016-09-22T15:43:33Z
39,643,819
<p>Make a file <code>a.txt</code> that contains one character on one line:</p> <pre><code>0 </code></pre> <p>Then in your script, open that file and retrieve the value, then immediately change it:</p> <pre><code>with open('a.txt') as f: a = int(f.read()) with open('a.txt', 'w') as output: output.write(str(a+1)) b = 1 print a+b </code></pre> <p>On the first run of the program, <code>a</code> will be <code>0</code>, and it will change the file to contain a <code>1</code>. On subsequent runs, <code>a</code> will continue to be incremented by 1 each time.</p>
0
2016-09-22T16:02:44Z
[ "python", "runtime", "interpreter" ]
How can I make a python script change itself?
39,643,428
<p>How can I make a python script change itself?</p> <p>To boil it down, I would like to have a python script (<code>run.py</code>)like this</p> <pre><code>a = 0 b = 1 print a + b # do something here such that the first line of this script reads a = 1 </code></pre> <p>Such that the next time the script is run it would look like</p> <pre><code>a = 1 b = 1 print a + b # do something here such that the first line of this script reads a = 2 </code></pre> <p>Is this in any way possible? The script might use external resources; however, everything should work by just running the one <code>run.py</code>-file.</p> <p>EDIT: It may not have been clear enough, but the script should update itself, not any other file. Sure, once you allow for a simple configuration file next to the script, this task is trivial.</p> <p><strong>Answer:</strong></p> <p>It is actually much easier than thought. @khelwood 's suggestion works just fine, opening the script and writing it's own content to it is completely unproblematic. @Gerrat's solution also works nicely. This is how I'm having it:</p> <pre><code># -*- coding: utf-8 -*- a = 0 b = 1 print a + b content = [] with open(__file__,"r") as f: for line in f: content.append(line) with open(__file__,"w") as f: content[1] = "a = {n}\n".format(n=b) content[2] = "b = {n}\n".format(n=a+b) for i in range(len(content)): f.write(content[i]) </code></pre>
0
2016-09-22T15:43:33Z
39,646,415
<p>What you're asking for would require you to manipulate files at the {sys} level; basically, you'd read the current file in, modify it, over-write it, and reload the current module. I played with this briefly because I was curious, but I ran into file locking and file permission issues. Those are <em>probably</em> solvable, but I suspect that this isn't really what you want here. </p> <p>First: realize that it's generally a good idea to maintain a separation between code and data. There are exceptions to this, but for most purposes, you'll want to make the parts of your program that can change at runtime read their configuration from a file, and write changes to that same file. </p> <p>Second: idomatically, most python projects use <a href="http://yaml.org/" rel="nofollow">YAML</a> for configuration</p> <p>Here's a simple script that uses the yaml library to read from a file called 'config.yaml', and increments the value of 'a' each time the program runs: </p> <pre><code>#!/usr/bin/python import yaml config_vals = "" with open("config.yaml", "r") as cr: config_vals = yaml.load(cr) a = config_vals['a'] b = config_vals['b'] print a + b config_vals['a'] = a + 1 with open("config.yaml", "w") as cw: yaml.dump(config_vals, cw, default_flow_style=True) </code></pre> <p>The runtime output looks like this: </p> <pre><code>$ ./run.py 3 $ ./run.py 4 $ ./run.py 5 </code></pre> <p>The initial YAML configuration file looks like this: </p> <pre><code>a: 1 b: 2 </code></pre>
0
2016-09-22T18:30:37Z
[ "python", "runtime", "interpreter" ]
How do i set django setting to a file which is outside the django tree?
39,643,436
<p>I have this python file tasks.py</p> <pre><code>import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoWebProject.settings') from django.contrib.auth.models import User from logreg.models import ActivationCode import datetime def remove_users(): print 'hello worldddddddddddddddddddddddddddddddddd' inactive_users = [] activation_codes = ActivationCode.objects.all() for activation_code in activation_codes: if datetime.datetime.date(activation_code.key_expires) &lt; datetime.datetime.date(datetime.datetime.now()): inactive_users.append(activation_code.user_id) for inactive_user in inactive_users: User.objects.filter(id=inactive_user).delete() </code></pre> <p>But this is in the root folder and when i try to execute it, it gives me the following error</p> <blockquote> <p>File "C:\Users\deybala1\AppData\Local\Continuum\Anaconda2\lib\site-packages\dj ango\apps\registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.</p> </blockquote> <p>How do i fix this?</p>
0
2016-09-22T15:44:02Z
39,646,435
<p>Note that you're trying to add a settings module inside a script that already requires it. </p> <p>Wouldn't it be easier if you add a specific django command? Thanks to it you'd be able to start your task with <code>python manage.py --settings=&lt;path_to_your_settings&gt;</code>.</p> <p>Another tip:</p> <p>Move every django import statement below </p> <pre><code>os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoWebProject.settings') </code></pre>
2
2016-09-22T18:31:56Z
[ "python", "django" ]
How do i set django setting to a file which is outside the django tree?
39,643,436
<p>I have this python file tasks.py</p> <pre><code>import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoWebProject.settings') from django.contrib.auth.models import User from logreg.models import ActivationCode import datetime def remove_users(): print 'hello worldddddddddddddddddddddddddddddddddd' inactive_users = [] activation_codes = ActivationCode.objects.all() for activation_code in activation_codes: if datetime.datetime.date(activation_code.key_expires) &lt; datetime.datetime.date(datetime.datetime.now()): inactive_users.append(activation_code.user_id) for inactive_user in inactive_users: User.objects.filter(id=inactive_user).delete() </code></pre> <p>But this is in the root folder and when i try to execute it, it gives me the following error</p> <blockquote> <p>File "C:\Users\deybala1\AppData\Local\Continuum\Anaconda2\lib\site-packages\dj ango\apps\registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.</p> </blockquote> <p>How do i fix this?</p>
0
2016-09-22T15:44:02Z
39,647,673
<p>If you're creating any script that is using your django project, it is absolutely necessary to set path to settings of your project <strong>before</strong> any import from django or your project. And you're importing user model from django in 1st line and model from your project in second.</p> <p>Also, you will need to call <code>django.setup()</code> first.</p> <p>To fix that, move <code>import os</code> and setting path to django settings to the very beginning of your script, and put django.setup() just after that (with proper import), like this:</p> <pre><code># first, set path to project settings import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoWebProject.settings') import django django.setup() # now you can import anything else from django.contrib.auth.models import User from logreg.models import ActivationCode import datetime def remove_users(): print 'hello worldddddddddddddddddddddddddddddddddd' inactive_users = [] activation_codes = ActivationCode.objects.all() for activation_code in activation_codes: if datetime.datetime.date(activation_code.key_expires) &lt; datetime.datetime.date(datetime.datetime.now()): inactive_users.append(activation_code.user_id) for inactive_user in inactive_users: User.objects.filter(id=inactive_user).delete() </code></pre>
2
2016-09-22T19:45:59Z
[ "python", "django" ]
How to create related field in odoo?
39,643,493
<p>I am trying to create related field for displaying customer's balance in sale orders. I think i am creating wrong related field. Can anybody help me how to create related field in odoo? </p> <p><strong>here this is related field i am creating</strong></p> <p><code>customer_balance = fields.Related('partner_id.credit', string='Customer Balance')</code></p> <p><strong>and other one is</strong></p> <p><code>customer_balance = fields.Char(related='partner_id.credit', store=True)</code></p>
1
2016-09-22T15:47:04Z
39,643,997
<p>Try below code. It will work for you.</p> <pre><code>customer_balance = fields.Float(related="partner_id.credit",string="Balance") </code></pre> <p>Thanks..</p>
3
2016-09-22T16:11:22Z
[ "python", "openerp", "field", "odoo-8" ]
Django AdminEmailHandler hangs when DB is not accesible
39,643,527
<p>I noticed that when my database goes down, the queries to my Django app gives timeout instead of returning 500 to the client instantaneously. </p> <p>Tracing the problem I set database connect_timeout in config to 5s (<a href="http://stackoverflow.com/questions/1084488/how-to-set-timeout-for-database-connection-in-django">explained here</a>) and the exception appears faster on the logs but after printing the exception the client does not receive the result until 30s more.</p> <pre><code>OperationalError: (2003, "Can't connect to MySQL server on 'db.example.com' (4)") </code></pre> <p>Debugging what is happening with <a href="http://stackoverflow.com/questions/1118183/how-to-debug-in-django-the-good-way">PDB</a> I found that the problem is in the <strong>django.utils.log AdminEmailHandler</strong>, when it tries to generate the mail of the exception. </p> <p>To generate the mail it calls <strong>django.views.debug ExceptionReporter.get_traceback_text()</strong> that looks for all frames on the traceback and then for all variables on each frame, and one of these variables is the <strong>queryset</strong> that triggered the exception.</p> <p>Generating the error email makes multiple accesses to the <strong>queryset</strong> that generated the DB connection timeout, generating more DB timeouts and thus the error response to the client takes so long.</p> <p>What is the best approach to avoid this problem?</p>
0
2016-09-22T15:48:30Z
39,646,550
<p>While no better alternative is given, this is the solution I have implemented.</p> <p>I have setup a custom AdminEmailHandler that inspect's the exception and in case of database OperationalError skips the exception and sends and error instead.</p> <pre><code>import logging from django.utils.log import AdminEmailHandler from django.db.utils import OperationalError logger = logging.getLogger('mylogger') class CustomAdminEmailHandler(AdminEmailHandler): # When mail is because of exception conencting to DB, avoid rendering the email, # rendering email makes connections to DB making the query hang in multiple DB # connection timeouts. if record.exc_info: exc_type, exc_value, exc_traceback = record.exc_info if exc_type == OperationalError: logger.error(exc_value, exc_info=False) return super(CustomAdminEmailHandler, self).emit(record) </code></pre> <p>And in settings.py</p> <pre><code>LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '%(asctime)s %(levelname)s %(module)s:%(funcName)s() %(message)s' }, }, 'handlers': { 'send_mail': { 'level': 'ERROR', 'class': 'myapp.handlers.CustomdAdminEmailHandler', 'include_html': False, }, }, 'loggers': { 'django': { 'handlers': ['send_mail'], 'level': 'INFO' }, 'mylogger': { 'handlers': ['send_mail'], 'level': 'INFO' }, } } </code></pre> <p>I have also set database connection timeout to 1 second, I don't want the requests to be queued in case that the database is not accessible, this may lead to a very high load when the connection returns that can get the servers down.</p>
0
2016-09-22T18:38:36Z
[ "python", "mysql", "django" ]
Identifying overlapping rows in multiple dataframes
39,643,601
<p>I have two dataframes like </p> <p>df1</p> <pre><code>Time accler 19.13.33 24 19.13.34 24 19.13.35 25 19.13.36 27 19.13.37 25 19.13.38 27 19.13.39 25 19.13.40 24 </code></pre> <p>df2</p> <pre><code> Time accler 19.13.29 24 19.13.30 24 19.13.31 25 19.13.32 27 19.13.33 25 19.13.34 27 19.13.35 25 19.13.36 24 </code></pre> <p>These two data frames overlap over column time from 19.13.33 to 19.13.36. So when ever there is a overlap I wanted only the dataframe which consists of the overlapped rows</p> <p>expected output</p> <p>df1</p> <pre><code> Time accler 19.13.33 24 19.13.34 24 19.13.35 25 19.13.36 27 </code></pre> <p>df2</p> <pre><code>Time accler 19.13.33 25 19.13.34 27 19.13.35 25 19.13.36 24 </code></pre> <p>or I can also have a <code>concat</code> of the dataframes which will be helpful for further processing. </p> <p>I tried <code>merge</code> but did not work as the dataframes are created dynamically depending on the number of csv files. I tried concatenating first all the dataframes and tried to iterate over the rows but did not find a way.</p>
1
2016-09-22T15:52:10Z
39,643,687
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a>, default parameter <code>how='inner'</code> can be omited:</p> <pre><code>df = pd.merge(df1, df2, on='Time') print (df) Time accler_x accler_y 0 19.13.33 24 25 1 19.13.34 24 27 2 19.13.35 25 25 3 19.13.36 27 24 df1 = df[['Time','accler_x']].rename(columns={'accler_x':'accler'}) print (df1) Time accler 0 19.13.33 24 1 19.13.34 24 2 19.13.35 25 3 19.13.36 27 df2 = df[['Time','accler_y']].rename(columns={'accler_y':'accler'}) print (df2) Time accler 0 19.13.33 25 1 19.13.34 27 2 19.13.35 25 3 19.13.36 24 </code></pre> <p>If you need <code>merge</code> multiple <code>DataFrames</code> use <a href="https://docs.python.org/3.0/library/functools.html#functools.reduce" rel="nofollow"><code>reduce</code></a>:</p> <pre><code>#Python 3 import functools df = functools.reduce(lambda x,y: x.merge(y,on=['Time']), [df1, df2]) #python 2 df = reduce(lambda x,y: x.merge(y,on=['Time']), [df1, df2]) </code></pre>
3
2016-09-22T15:56:38Z
[ "python", "pandas", "merge", "inner-join", "concat" ]
How can programs make Lua(or python) interpreter execute statements provided by the program?
39,643,609
<p>I am using Cent OS 7.</p> <p>I want to write a program(written in Java or other languages) that can interact with Lua interpreter. I hope that my program can feed statements to Lua interpreter, and get executed real-time, while previous variables are still available.</p> <p>For example, my program feeds <code>a = 4; print(a);</code> to Lua interpreter <code>4</code> is printed on the screen. Then the program does other work. Later it feeds <code>n = 0; for i=1,4 do n = n + i; end; print(n);</code> to the interpreter, and <code>10</code> is printed on the screen.</p> <p>Note: All I want is that Lua interpreter execute the statements when my program feeds it one, while keeping its previous status. My program does not need to access variables in Lua interpreter.</p> <p>I tried calling Lua interpreter separately, but it doesn't work as expected. Another solution is to record all previous statements, and run them before a new statement is going to run. But this is obviously not efficient.</p> <p>Is there a easy way to do this? Such as just creating sub-process and making system calls?</p>
-1
2016-09-22T15:52:30Z
39,643,937
<p>As your question is very broad (interpret Lua or Python, in any language), I can only give you some hints. </p> <p>If you write in C or C++, you can use the Lua library directly. It probably allows you to execute Lua statements, make values in C visible to the Lua code, make C function available to the Lua code, and access values of the Lua code.</p> <p>If you write in Java, you may either write a JNI wrapper for the Lua library, or use another Lua implementation. See <a href="http://stackoverflow.com/q/2113432/1314743">how can I embed lua in java?</a>.</p> <p>For other languages, you essentially have the same options: either use (if available) some other implementation in your favourite language, or find a way how you can access C library functions from your language. The latter is possible for most relevant programming languages.</p> <p>For Python, the situation is similar. See, for example, <a href="http://stackoverflow.com/q/1119696/1314743">Java Python Integration</a> and <a href="https://wiki.python.org/moin/IntegratingPythonWithOtherLanguages" rel="nofollow">Integrating Python With Other Languages</a>.</p>
0
2016-09-22T16:08:22Z
[ "java", "python", "linux", "lua" ]
How to solve an issue in a simple TR Tkinter program
39,643,748
<p>Major programming noob here, and my very first question in stackoverflow. I'm trying to make a time reaction tester, with a simplistic Tkinter GUI.</p> <p>Here's the code</p> <pre><code>#!/usr/bin/env python import tkinter as tk import time import random class TRTest(tk.Frame): def __init__(self, master = None): super().__init__() self.grid() self.canv() self.createWidgets() self.Test self.totalt = [] def createWidgets(self): self.quitbtn = tk.Button(self, text = "Quit", command=self.master.destroy) self.quitbtn.grid(row = 3, column = 3) self.label = tk.Label(self, text = "TRTest") self.label.grid(row = 1, column = 3) self.testbtn = tk.Button(self, text = "Start test", command = self.Test) self.testbtn.grid(row = 1, column = 2) def canv(self): self.scrn = tk.Canvas(self, width = 400, height = 400, bg = "#E8E8E8") self.scrn.grid(row = 2, column = 3) def fixate(self): self.scrn.create_line(190, 200, 210, 200, width = 2) self.scrn.create_line(200, 190, 200, 210, width = 2) def createCircle(self): self.scrn.create_oval(150, 150, 250, 250, fill = "red", tag = "circle") def Test(self): if len(self.totalt) == 0: self.fixate() self.update() self.bind_all("&lt;Key&gt;", self.gettime) self.after(random.randint(1000, 5000)) self.t0 = time.clock() self.createCircle() def gettime(self, event): t = time.clock() - self.t0 self.totalt.append(t) self.scrn.delete("circle") if len(self.totalt) &lt; 6: self.Test else: print(self.totalt) a = tk.Tk() b = TRTest(a) b.mainloop() </code></pre> <p>It should be making 5 trials and returning the list of the measured TR times, but it freezes before showing a second circle. Where's the problem? Thank you!!</p>
0
2016-09-22T15:58:23Z
39,644,059
<p>I think you are trying to run the method <code>Test</code> with</p> <pre><code>self.Test </code></pre> <p>Try instead </p> <pre><code>self.Test() </code></pre>
0
2016-09-22T16:14:49Z
[ "python", "python-3.x", "tkinter" ]
How to solve an issue in a simple TR Tkinter program
39,643,748
<p>Major programming noob here, and my very first question in stackoverflow. I'm trying to make a time reaction tester, with a simplistic Tkinter GUI.</p> <p>Here's the code</p> <pre><code>#!/usr/bin/env python import tkinter as tk import time import random class TRTest(tk.Frame): def __init__(self, master = None): super().__init__() self.grid() self.canv() self.createWidgets() self.Test self.totalt = [] def createWidgets(self): self.quitbtn = tk.Button(self, text = "Quit", command=self.master.destroy) self.quitbtn.grid(row = 3, column = 3) self.label = tk.Label(self, text = "TRTest") self.label.grid(row = 1, column = 3) self.testbtn = tk.Button(self, text = "Start test", command = self.Test) self.testbtn.grid(row = 1, column = 2) def canv(self): self.scrn = tk.Canvas(self, width = 400, height = 400, bg = "#E8E8E8") self.scrn.grid(row = 2, column = 3) def fixate(self): self.scrn.create_line(190, 200, 210, 200, width = 2) self.scrn.create_line(200, 190, 200, 210, width = 2) def createCircle(self): self.scrn.create_oval(150, 150, 250, 250, fill = "red", tag = "circle") def Test(self): if len(self.totalt) == 0: self.fixate() self.update() self.bind_all("&lt;Key&gt;", self.gettime) self.after(random.randint(1000, 5000)) self.t0 = time.clock() self.createCircle() def gettime(self, event): t = time.clock() - self.t0 self.totalt.append(t) self.scrn.delete("circle") if len(self.totalt) &lt; 6: self.Test else: print(self.totalt) a = tk.Tk() b = TRTest(a) b.mainloop() </code></pre> <p>It should be making 5 trials and returning the list of the measured TR times, but it freezes before showing a second circle. Where's the problem? Thank you!!</p>
0
2016-09-22T15:58:23Z
39,644,608
<p>In addition to the answer from Patrick Haugh, you aren't using the .after method correctly.</p> <p>Change this line of code</p> <pre><code>self.after(random.randint(1000, 5000)) </code></pre> <p>to</p> <pre><code>self.after(random.randint(1000, 5000),self.Test) </code></pre> <p>and move it to after</p> <pre><code>if len(selftotalt) &lt; 6: </code></pre> <p>This will call the self.Test function again after a random period of time between 1 and 5 seconds. If more 6 or more reaction times have been captures it will no longer call the function again but print out the times.</p> <p>Full code that seem to work for me</p> <pre><code>import tkinter as tk import time import random class TRTest(tk.Frame): def __init__(self, master = None): super().__init__() self.grid() self.canv() self.createWidgets() self.totalt = [] def createWidgets(self): self.quitbtn = tk.Button(self, text = "Quit", command=self.master.destroy) self.quitbtn.grid(row = 3, column = 3) self.label = tk.Label(self, text = "TRTest") self.label.grid(row = 1, column = 3) self.testbtn = tk.Button(self, text = "Start test", command = self.Test) self.testbtn.grid(row = 1, column = 2) def canv(self): self.scrn = tk.Canvas(self, width = 400, height = 400, bg = "#E8E8E8") self.scrn.grid(row = 2, column = 3) def fixate(self): self.scrn.create_line(190, 200, 210, 200, width = 2) self.scrn.create_line(200, 190, 200, 210, width = 2) def createCircle(self): self.scrn.create_oval(150, 150, 250, 250, fill = "red", tag = "circle") def Test(self): if len(self.totalt) == 0: self.fixate() self.update() self.bind_all("&lt;Key&gt;", self.gettime) self.t0 = time.clock() self.createCircle() def gettime(self, event): t = time.clock() - self.t0 self.totalt.append(t) self.scrn.delete("circle") if len(self.totalt) &lt; 6: self.after(random.randint(1000, 5000),self.Test) else: print(self.totalt) a = tk.Tk() b = TRTest(a) b.mainloop() </code></pre>
0
2016-09-22T16:44:09Z
[ "python", "python-3.x", "tkinter" ]
Python appending from previous for loop iteration
39,643,780
<p>I have a very simple but annoying problem. I am reading in a list of files one by one whose names are stored in an ascii file ("file_input.txt") and performing calculations on them. My issue is that when I print out the result of the calculation ("print peak_wv, peak_flux" in the script below) it appends the previous printout. Below is the code I have written, please help me see what I'm doing wrong here.</p> <pre><code>from math import* wv = [] flux = [] fits = [] p = open("file_input.txt","r") for line in p: fits.append(str(line.split()[0])) p.close() for j in range(len(fits)): f = open("%s"%(fits[j]),"r") for line in f: wv.append(float(line.split()[0])) flux.append(float(line.split()[1])) f.close() print "%s"%(fits[j]) for i in range(len(wv)): if 6555.0&lt;wv[i]&lt;6569.0: m1 = (flux[i+1]-flux[i])/(wv[i+1] - wv[i]) m2 = (flux[i+2]-flux[i+1])/(wv[i+2] - wv[i+1]) if m2*m1 &lt; 0: peak_wv = (wv[i+2]+wv[i+1]+wv[i])/3.0 peak_flux = flux[i+1] print peak_wv, peak_flux </code></pre>
0
2016-09-22T16:00:33Z
39,644,803
<p>Based on your comment I believe the issue is that you are appending the data with each new file. You probably want to clear wv and flux for each new file. For example:</p> <pre><code>for j in range(len(fits)): wv = [] flux = [] f = open("%s"%(fits[j]),"r") </code></pre> <hr> <p>Edit: I should also point out that you aren't actually using any math functions so you don't need that import, and there are a bunch of ways to make this code more pythonic. You can use the "with open" idiom to avoid having to manually close the file. You can also use basic for loops and/or "enumerate" to make your for loops cleaner. For example, this:</p> <pre><code>for j in range(len(fits)): f = open("%s"%(fits[j]),"r") # code f.close() </code></pre> <p>Could be this:</p> <pre><code>for file in fits: with open(file, "r") as f: # code </code></pre> <p>And this:</p> <pre><code>for i in range(len(wv)): if 6555.0&lt;wv[i]&lt;6569.0: </code></pre> <p>Could be:</p> <pre><code>for i, cur_wv in enumerate(wv): if 6555.0 &lt; cur_wv &lt; 6569.0: </code></pre>
0
2016-09-22T16:56:24Z
[ "python" ]
Python function calling
39,643,806
<p>I've only started learning Python. If I wrote:</p> <pre><code>def questions(): sentence= input(" please enter a sentence").split() </code></pre> <p>How would I end the function If the user didn't input anything and just hit enter </p>
0
2016-09-22T16:02:16Z
39,643,936
<pre><code>def questions(): sentence= input(" please enter a sentence").split() if sentence == []: #This is what happens when nothing was entered else: #This happens when something was entered </code></pre>
1
2016-09-22T16:08:19Z
[ "python" ]
Python function calling
39,643,806
<p>I've only started learning Python. If I wrote:</p> <pre><code>def questions(): sentence= input(" please enter a sentence").split() </code></pre> <p>How would I end the function If the user didn't input anything and just hit enter </p>
0
2016-09-22T16:02:16Z
39,643,940
<p>You can add exception in your code. If you want to raise an exception only on the empty string, you'll need to do that manually:</p> <p>Example</p> <pre><code> try: input = raw_input('input: ') if int(input): ...... except ValueError: if not input: raise ValueError('empty string') else: raise ValueError('not int') </code></pre> <p>try this, both empty string and non-int can be detected. </p>
0
2016-09-22T16:08:33Z
[ "python" ]
Python function calling
39,643,806
<p>I've only started learning Python. If I wrote:</p> <pre><code>def questions(): sentence= input(" please enter a sentence").split() </code></pre> <p>How would I end the function If the user didn't input anything and just hit enter </p>
0
2016-09-22T16:02:16Z
39,643,955
<p>Did you test this? The function will work properly if the user simply hits <kbd>Enter</kbd>. The <code>sentence</code> variable would be an empty list. If there was nothing else in the function, it would return <code>None</code>, the default return value. If you wanted to do further processing that requires an actual sentence with content, you can put <code>if not sentence: return</code> after that line.</p>
1
2016-09-22T16:09:32Z
[ "python" ]
gRPC client side load balancing
39,643,841
<p>I'm using gRPC with Python as client/server inside kubernetes pods... I would like to be able to launch multiple pods of the same type (gRPC servers) and let the client connect to them (randomly).</p> <p>I dispatched 10 pods of the server and setup a 'service' to target them. Then, in the client, I connected to the DNS name of the service - meaning kubernetes should do the load-balancing and direct me to a random server pod. In reality, the client calls the gRPC functions (which works well) but when I look at the logs I see that all calls going to the same server pod. </p> <p>I presume the client is doing some kind of DNS caching which leads to all calls being sent to the same server. Is this the case? Is there anyway to disable it and set the same stub client to make a "new" call and fetch a new ip by DNS with each call? </p> <p>I am aware of the overhead I might cause if it will query the DNS server each time but distributing the load is much more important for me at the moment.</p> <p><strong>EDIT</strong></p> <p>probably not a caching issue... Might just be the way gRPC works. HTTP/2 and persistent reusable connection. Any way to "disconnect" after each call?</p>
1
2016-09-22T16:03:39Z
39,644,962
<p>If you've created a vanilla Kubernetes service, the service should have its own load-balanced virtual IP (check if <code>kubectl get svc your-service</code> shows a <code>CLUSTER-IP</code> for your service). If this is the case, DNS caching should not be an issue, because that single virtual IP should be splitting traffic among the actual backends.</p> <p>Try <code>kubectl get endpoints your-service</code> to confirm that your service actually knows about all of your backends.</p> <p>If you have a <a href="http://kubernetes.io/docs/user-guide/services/#headless-services" rel="nofollow">headless service</a>, a DNS lookup will return an A record with 10 IPs (one for each of your Pods). If your client is always choosing the first IP in an A record, that would also explain the behavior you're seeing.</p>
0
2016-09-22T17:06:00Z
[ "python", "http", "dns", "kubernetes", "grpc" ]
gRPC client side load balancing
39,643,841
<p>I'm using gRPC with Python as client/server inside kubernetes pods... I would like to be able to launch multiple pods of the same type (gRPC servers) and let the client connect to them (randomly).</p> <p>I dispatched 10 pods of the server and setup a 'service' to target them. Then, in the client, I connected to the DNS name of the service - meaning kubernetes should do the load-balancing and direct me to a random server pod. In reality, the client calls the gRPC functions (which works well) but when I look at the logs I see that all calls going to the same server pod. </p> <p>I presume the client is doing some kind of DNS caching which leads to all calls being sent to the same server. Is this the case? Is there anyway to disable it and set the same stub client to make a "new" call and fetch a new ip by DNS with each call? </p> <p>I am aware of the overhead I might cause if it will query the DNS server each time but distributing the load is much more important for me at the moment.</p> <p><strong>EDIT</strong></p> <p>probably not a caching issue... Might just be the way gRPC works. HTTP/2 and persistent reusable connection. Any way to "disconnect" after each call?</p>
1
2016-09-22T16:03:39Z
39,756,233
<p>Let me take the opportunity to answer by describing how things are supposed to work.</p> <p>The way client-side LB works in the gRPC C core (the foundation for all but the Java and Go flavors or gRPC) is as follows (the authoritative doc can be found <a href="https://github.com/grpc/grpc/blob/master/doc/load-balancing.md#load-balancing-in-grpc" rel="nofollow">here</a>):</p> <p>Client-side LB is kept simple and "dumb" on purpose. The way we've chosen to implement complex LB policies is through an external LB server (as described in the aforementioned doc). You aren't concerned with this scenario. Instead, you are simply creating a channel, which will use the (default) <em>pick-first</em> LB policy.</p> <p>The input to an LB policy is a list of resolved addresses. When using DNS, if foo.com resolves to <code>[10.0.0.1, 10.0.0.2, 10.0.0.3, 10.0.0.4]</code>, the policy will try to establish a connection to all of them. The first one to successfully connect will become the chosen one <em>until it disconnects</em>. Thus the name "pick-first". A longer name could have been "pick first and stick with it for as long as possible", but that made for a very long file name :). If/when the picked one gets disconnected, the pick-first policy will move over to returning the next successfully connected address (internally referred to as a "connected subchannel"), if any. Once again, it'll continue to choose this connected subchannel for as long as it stays connected. If all of them fail, the call would fail.</p> <p>The problem here is that DNS resolution, being intrinsically pull based, is only triggered 1) at channel creation and 2) upon disconnection of the chosen connected subchannel. </p> <p>As of right now, a hacky solution would be to create a new channel for every request (very inefficient, but it'd do the trick given your setup).</p> <p>Given changes coming in Q1 2017 (see <a href="https://github.com/grpc/grpc/issues/7818" rel="nofollow">https://github.com/grpc/grpc/issues/7818</a>) will allow clients to choose a different LB policy, namely Round Robin. In addition, we may look into introducing a "randomize" bit to that client config, which would shuffle the addresses prior to doing Round-Robin over them, effectively achieving what you intend. </p>
3
2016-09-28T19:37:06Z
[ "python", "http", "dns", "kubernetes", "grpc" ]
Automatic installation of dependencies when publishing Python 3 project on pypi
39,643,861
<p>I want to publish a project using pypi. Ideally I would like the installation to be: </p> <pre><code>sudo pip3 install ProjectName </code></pre> <p>The problem is, I get:</p> <blockquote> <p>Could not find any downloads that satisfy the requirement itsdangerous (from ProjectName) Some insecure and unverifiable files were ignored (use --allow-unverified itsdangerous to allow).</p> </blockquote> <p>If I firstly install the external requirements (itsdangerous and wspy in this case), then the installation completes. </p> <p>Here is my requirements.txt:</p> <pre><code>requests&gt;=2.10.0 six&gt;=1.10.0 itsdangerous==0.24 ws4py==0.3.4 </code></pre> <p>And here is the install_requires from setup.py:</p> <pre><code>install_requires=[ "requests", "six", "ws4py", "itsdangerous" ] </code></pre> <p>One thing I think may cause the issue is that the requirements.txt is not included in MANIFEST.in, but I am not sure how to include it.</p> <p>I am using <a href="https://testpypi.python.org/pypi/" rel="nofollow">https://testpypi.python.org/pypi/</a>.</p> <p>Basically, I have the same issue as described in this <a href="http://stackoverflow.com/questions/23014238/pip-any-workaround-to-avoid-allow-external/23072180">question</a>. I do not really understand the accepted answer.</p>
0
2016-09-22T16:04:30Z
39,652,320
<h2>To install</h2> <p>Update your <code>~/.config/pip/pip.conf</code> and/or <code>/etc/pip.conf</code>. </p> <p>Append the test repository to the <code>--find-links</code> option:</p> <pre><code>[install] find-links = https://pypi.python.org/pypi https://testpypi.python.org/pypi </code></pre> <p>The order is important…</p> <p>See the <a href="https://pip.pypa.io/en/stable/user_guide/#configuration" rel="nofollow">Cofiguration</a> topic in the documentation.</p> <h2>To register and upload</h2> <p>See the <a href="https://wiki.python.org/moin/TestPyPI" rel="nofollow">TestPypi</a> wiki page.</p>
1
2016-09-23T03:54:39Z
[ "python", "pip", "pypi" ]
Python can open file, PL/Python can't
39,643,998
<p>Connected to mydb in PostgreSQL:</p> <pre><code>mydb=# CREATE FUNCTION file_test () RETURNS text AS $$ if open('mydir/myfile.xsl'): return 'success' $$ LANGUAGE plpythonu; CREATE FUNCTION mydb=# SELECT file_test(); ERROR: IOError: [Errno 2] No such file or directory: 'mydir/myfile.xsl' CONTEXT: Traceback (most recent call last): PL/Python function "file_test", line 2, in &lt;module&gt; if open('mydir/myfile.xsl'): return 'success' PL/Python function "file_test" </code></pre> <p>Over to Python:</p> <pre><code>&gt;&gt;&gt; if open('mydir/myfile.xsl'): print 'success' ... success &gt;&gt;&gt; </code></pre> <p>An absolute path didn't seem to help PL/Python. What I'd like to do is use Postgres's query_to_xml() and run an XSLT transformation on the return. But to do that I'll need to read the xsl file...</p>
0
2016-09-22T16:11:23Z
39,645,021
<p>At @hruske's suggestion I used <code>plpy.notice(os.path.abspath('mydir/myfile.xsl'))</code> to see how PL/Python was trying to resolve the path. It was <code>/var/lib/postgresql/9.5/main/mydir/myfile.xsl</code>, which was obviously not what I had in mind.</p> <p>The absolute path worked after all. Copying the file to a location that was easier to type as an absolute path fixed the "problem." </p> <p>For further reading I recommend Soko Morinaga's <a href="http://rads.stackoverflow.com/amzn/click/0861713931" rel="nofollow">Novice to Master: An Ongoing Lesson in the Extent of My Own Stupidity</a>.</p>
0
2016-09-22T17:08:58Z
[ "python", "postgresql", "xslt", "plpython" ]