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
Deleting row from database if value =? in SQLAlchemy
38,920,791
<p>I have 2 separate SQL tables in the same <code>.db</code> file. This is using SQLite.</p> <p><strong>table 1</strong></p> <pre><code>column1 column2 ggg values ttt values yyy values hhh values ddd values jjj values </code></pre> <p><strong>table 2</strong></p> <pre><code>column1 column2 column3 column4 ggg values s_values words zzz values s_values words aaa values s_values words qqq values s_values words hyh values s_values words jjj values s_values words </code></pre> <p>Using table 1 as the base, if table 2 has items from table 1, how do I delete the entire row in table 2?</p> <pre><code>test1 = pandas.read_sql_table('table 1', con=engine)['column1'] test2 = pandas.read_sql_table('table 2', con=engine)['column1'] for each_item in test1: if each_item in test2['column1'].unique(): connection.execute('DELETE FROM "table2" WHERE column1=?', column1=each_item) </code></pre> <p>I have read most of the posts on stackoverflow and checked the documentations regarding this, but I'm still getting errors to deleting <code>row</code> in <code>table2</code>.</p>
1
2016-08-12T14:47:52Z
38,921,048
<p>Thanks to Jon CLements, I realized my mistake of not opening the engine.. Thus getting errors for it. :( </p>
0
2016-08-12T15:02:17Z
[ "python", "sqlite", "sqlalchemy" ]
GNU/Linux - Python3 - PySerial: How to send data over USB connection?
38,920,876
<p>I have 2 questions about Python3 and PySerial (serial module).</p> <p>I must send data over USB port to my IC's stand-alone ATMega32. A possible snippet code:</p> <pre><code>import serial data=serial.Serial(port, speed) first_data=99.7 # Float point data. second_data=100 # Only int data like 10, 345, 2341 and so on. third_data=56.7 # Float data ValueToWrite=????? # How to convert it? send=data.write(ValueToWrite) </code></pre> <p>Now if I try to send "first_data" with "ValueToWrite=firts_data" I have this error:</p> <pre><code>TypeError: 'float' object is not iterable </code></pre> <p>Well. Reading documentation about method <strong>write</strong> (class <strong>serial.Serial</strong> - <a href="http://pyserial.readthedocs.io/en/latest/pyserial_api.html" rel="nofollow">http://pyserial.readthedocs.io/en/latest/pyserial_api.html</a>) I see:</p> <blockquote> <p>Write the bytes data to the port. This should be of type bytes (or compatible such as bytearray or memoryview). Unicode strings must be encoded (e.g. 'hello'.encode('utf-8').</p> </blockquote> <ol> <li>My first question: I don't understand how to send my float and int data. How to convert them into string?</li> <li><p>My second question: I'd like to send data all together, a unique value like this:</p> <p>99.7F100S56.7T</p></li> </ol> <p>In this case, using ATMega's Firmware, I can split and update data in the corresponding variables, when encountered "F" character for the first data, "S" character for the second data and so on.</p> <p>How to do this in Python3 using pyserial?</p>
1
2016-08-12T14:52:51Z
38,921,081
<ol> <li>converting float, int or most other non-strings to strings by using the <a href="https://docs.python.org/3/library/functions.html#func-str" rel="nofollow">string function</a>, e.g. in your case </li> </ol> <p><code>str(first_data)</code></p> <p>would output '99.7' (a string).</p> <ol start="2"> <li>by using the <a href="https://docs.python.org/3.1/library/string.html#string-formatting" rel="nofollow">string format method</a>, e.g. </li> </ol> <p><code>'{0}F{1}S{2}T'.format(first_data, second_data, third_data)</code></p> <p>would output '99.7F100S56.7T'</p> <p>These strings you can use as parameters to serial.send</p>
1
2016-08-12T15:04:22Z
[ "python", "linux", "python-3.x", "pyserial" ]
Using the SuiteCRM/SugarCRM REST endpoint version 4.1
38,920,889
<p>I'm having a bad time trying to get the REST API to behave. Yes, the code is Python, but if you know PHP or anything else, I suspect you'll be able to help.</p> <p>I wrote two functions. 1 is a helper.</p> <pre><code>def post(self, method, parameters): args = collections.OrderedDict() args['method'] = method args['input_type'] = 'json' args['response_type'] = 'json' args['rest_data'] = json.dumps(parameters) res = requests.post(self.url, data=args, verify=False) if res.ok == False: return None return res.json() </code></pre> <p>In the implementation below of get_module_entries, I only ever get the first 20 records. No matter what I set skip or take to, I only get the first 20 records.</p> <pre><code>def get_module_entries(self, module, skip=0, take=1): args = collections.OrderedDict() args['session'] = self.session_id args['module_name'] = module args['query'] = '' args['order_by'] = '' args['select_fields'] = '' args['link_name_to_fields_array'] = '' args['offset'] = str(skip) args['max_results'] = str(take) args['deleted'] = 0 args['Favorites'] = 0 res = self.post('get_entry_list', args) return res </code></pre> <p>When I comment out <code>select_fields</code> and <code>link_name_to_fields_array</code>, it does honor skip and take. So, I can keep hitting the fuction to get all the records. However, the objects returned only have the id and are missing all the other fields. They look like this:</p> <p><code>{"module_name": "Accounts", "name_value_list": [], "id": "&lt;snipped out&gt;"}</code></p> <p>Here I am commenting out those two lines.</p> <pre><code>def get_module_entries(self, module, skip=0, take=1): args = collections.OrderedDict() args['session'] = self.session_id args['module_name'] = module args['query'] = '' args['order_by'] = '' #args['select_fields'] = '' #args['link_name_to_fields_array'] = '' args['offset'] = str(skip) args['max_results'] = str(take) args['deleted'] = 0 args['Favorites'] = 0 res = self.post('get_entry_list', args) return res </code></pre> <p>The behavior is very strange. I just want all the fields and I want it to honor skip and take. It doesn't behave if I comment out one line and not the other in either order. How do I fix this?</p>
0
2016-08-12T14:53:35Z
38,931,338
<p>The reason for limit by 20 results is because it is limit on the list view of SuiteCRM and the list view is paginated for performance concerns. </p> <p>Typically, you would want to paginate. you really should only pull through the fields you need, as this reduces the bandwidth required to pull the data across. The result back from this call contains a next_offset key to help to request the next 20 rows. <strong>However, you can set the limit and the offset to -1 in order to get all the beans based on your query.</strong></p> <p>The implementation of 'get_entry_list' is in service/core/SugarWebServiceImpl.php:162. It utilises the process_list_query method which is found in data/SugarBean.php:3482. It is used by all modules of SuiteCRM to get a list of SugarBeans (models).</p> <p><code>process_list_query($query, $row_offset, $limit = -1, $max_per_page = -1, $where = ''</code>)</p> <p>in service/core/SugarWebServiceImpl.php:201 there is a check which determines the offset = 0 when you passing in -1</p>
0
2016-08-13T09:35:23Z
[ "php", "python", "sugarcrm", "suitecrm" ]
How to Access Each Item in A Delimited String to Find its Matching Item in a List?
38,920,896
<p>I have this list:</p> <pre><code>box = ["apple","orange","banana", "water"] </code></pre> <p>And this string: </p> <pre><code>CheckList = "1, orange | 2, apple | 3, banana | 4, milk" </code></pre> <p><strong>Note:</strong> The string has <code>"|"</code> and <code>","</code> delimiters. The <code>|</code> delimiters seperate each item and the <code>,</code> delimiters seperate between an item and its key (i.e. <code>key</code>,<code>item</code> <code>|</code> <code>key</code>,<code>item</code>, etc) </p> <p><strong>Problem:</strong> I want to iterate through each item in the <code>box</code> list and find the corespoinding <code>key</code> in the string <code>CheckList</code>. </p> <p>The output should be like this:</p> <pre><code>foundItems = ["2","1","3", "water"] </code></pre> <p>I am a begginer to text processing and programming in general, any idea how to solve this?</p> <p>I tried this but it is not helping.</p> <pre><code>for i in CheckList.split("|"): for j in box: if i.split(",")[0] == j </code></pre>
0
2016-08-12T14:53:54Z
38,921,175
<p>If the spaces in <code>CheckList</code> are not going to be consistent (as indeed they are not in the example you gave), I would recommend first running <code>CheckList = CheckList.replace(" ","")</code> to eliminate all spaces. Otherwise be sure to <code>split</code> using <code>" | "</code> or <code>", "</code>.</p> <p>Other than that, your code should work fine. If you initialize using <code>foundItems = box.copy()</code>, then your loop can look like</p> <pre><code>for i in CheckList.split("|"): # or " | " for j in range(len(box)): if i.split(",")[1] == box[j]: foundItems[j] = i.split(",")[0] </code></pre> <p>Using <code>j in range(len(box))</code> instead of <code>j in box</code> means that it will be easy to access the corresponding elements of <code>foundItems</code>.</p>
1
2016-08-12T15:09:03Z
[ "python", "string", "list", "for-loop", "replace" ]
How to Access Each Item in A Delimited String to Find its Matching Item in a List?
38,920,896
<p>I have this list:</p> <pre><code>box = ["apple","orange","banana", "water"] </code></pre> <p>And this string: </p> <pre><code>CheckList = "1, orange | 2, apple | 3, banana | 4, milk" </code></pre> <p><strong>Note:</strong> The string has <code>"|"</code> and <code>","</code> delimiters. The <code>|</code> delimiters seperate each item and the <code>,</code> delimiters seperate between an item and its key (i.e. <code>key</code>,<code>item</code> <code>|</code> <code>key</code>,<code>item</code>, etc) </p> <p><strong>Problem:</strong> I want to iterate through each item in the <code>box</code> list and find the corespoinding <code>key</code> in the string <code>CheckList</code>. </p> <p>The output should be like this:</p> <pre><code>foundItems = ["2","1","3", "water"] </code></pre> <p>I am a begginer to text processing and programming in general, any idea how to solve this?</p> <p>I tried this but it is not helping.</p> <pre><code>for i in CheckList.split("|"): for j in box: if i.split(",")[0] == j </code></pre>
0
2016-08-12T14:53:54Z
38,921,252
<p>First of all, it looks like you're checking the wrong index in <code>i.split(",")</code>. Python is 0-indexed, so when you reference <code>i.split(",")[0]</code>, you are checking the left side of the comma (the key in this case), when it looks like you want it to check the right side (the fruit). </p> <p>Second, make sure you are stripping whitespace when parsing strings like this. For example, the first item in CheckList is "1, orange ". When you split this on "," you get an array consisting of <code>["1"," orange "]</code>. Note the spaces before and after the string orange. If you try to compare <code>"orange"</code> with <code>" orange "</code>, you will see they are not equal. You can call <code>i.split(",")[1].strip()</code> to remove any leading and trailing whitespace.</p> <p>Lastly, this function is not very efficient. When you have a for loop inside of another for loop, you are checking each element in CheckList for each element in box. This is O(n^2) complexity. This is not that big of a deal for 4 items, but if these lists were larger, the time would increase quickly. Here is how I would write this function:</p> <pre><code>box = ["apple","orange","banana", "water"] CheckList = "1, orange | 2, apple | 3,banana | 4,milk" CheckDict = {} for i in CheckList.split("|"): j = i.split(",") CheckDict[j[1].strip()] = j[0].strip() foundItems = [] for i in box: if i in CheckDict: foundItems.append(CheckDict[i]) else: foundItems.append(i) </code></pre>
1
2016-08-12T15:13:39Z
[ "python", "string", "list", "for-loop", "replace" ]
How to Access Each Item in A Delimited String to Find its Matching Item in a List?
38,920,896
<p>I have this list:</p> <pre><code>box = ["apple","orange","banana", "water"] </code></pre> <p>And this string: </p> <pre><code>CheckList = "1, orange | 2, apple | 3, banana | 4, milk" </code></pre> <p><strong>Note:</strong> The string has <code>"|"</code> and <code>","</code> delimiters. The <code>|</code> delimiters seperate each item and the <code>,</code> delimiters seperate between an item and its key (i.e. <code>key</code>,<code>item</code> <code>|</code> <code>key</code>,<code>item</code>, etc) </p> <p><strong>Problem:</strong> I want to iterate through each item in the <code>box</code> list and find the corespoinding <code>key</code> in the string <code>CheckList</code>. </p> <p>The output should be like this:</p> <pre><code>foundItems = ["2","1","3", "water"] </code></pre> <p>I am a begginer to text processing and programming in general, any idea how to solve this?</p> <p>I tried this but it is not helping.</p> <pre><code>for i in CheckList.split("|"): for j in box: if i.split(",")[0] == j </code></pre>
0
2016-08-12T14:53:54Z
38,921,707
<p>First, get a mapping from <code>CheckList</code>, then look up it from <code>box</code>:</p> <pre><code>box = ["apple","orange","banana", "water"] CheckList = "1, orange | 2, apple | 3,banana | 4,milk" d = dict(reversed(items.split(',')) for items in CheckList.replace(' ', '').split('|')) foundItems = [d[x] if x in d else x for x in box] print foundItems </code></pre> <p>Pay attention to the <strong>spaces</strong> in the string.</p>
2
2016-08-12T15:37:28Z
[ "python", "string", "list", "for-loop", "replace" ]
How to Access Each Item in A Delimited String to Find its Matching Item in a List?
38,920,896
<p>I have this list:</p> <pre><code>box = ["apple","orange","banana", "water"] </code></pre> <p>And this string: </p> <pre><code>CheckList = "1, orange | 2, apple | 3, banana | 4, milk" </code></pre> <p><strong>Note:</strong> The string has <code>"|"</code> and <code>","</code> delimiters. The <code>|</code> delimiters seperate each item and the <code>,</code> delimiters seperate between an item and its key (i.e. <code>key</code>,<code>item</code> <code>|</code> <code>key</code>,<code>item</code>, etc) </p> <p><strong>Problem:</strong> I want to iterate through each item in the <code>box</code> list and find the corespoinding <code>key</code> in the string <code>CheckList</code>. </p> <p>The output should be like this:</p> <pre><code>foundItems = ["2","1","3", "water"] </code></pre> <p>I am a begginer to text processing and programming in general, any idea how to solve this?</p> <p>I tried this but it is not helping.</p> <pre><code>for i in CheckList.split("|"): for j in box: if i.split(",")[0] == j </code></pre>
0
2016-08-12T14:53:54Z
38,922,181
<p>Good answers here, thought I'd offer this two-liner.</p> <pre><code>&gt;&gt;&gt; d = {i.split(',')[1].strip():i.split(',')[0] for i in checkList.split('|')} &gt;&gt;&gt; print [d[key].strip() if key in d else key for key in box] ['2', '1', '3', 'water'] </code></pre>
1
2016-08-12T16:02:14Z
[ "python", "string", "list", "for-loop", "replace" ]
How to only get the last directory from readlink
38,920,908
<p>I'm doing a project at work were I need to get the version of Java for 100's of servers. I been using readlink, but that gives me full path for the link. I'm trying to figured out a way to only get the last directory using Python.</p> <pre><code>&gt;&gt;&gt; f = os.system('readlink /dir/dir/dir/java') /dir/dir/dir/dir/jdk </code></pre> <p>I need the output to only be <code>JDK</code>.</p>
0
2016-08-12T14:54:26Z
38,923,715
<p>After some further research I figured it out. Once I got the output from <code>os.readlink</code> I then took the output and got the basename:</p> <pre><code>&gt;&gt;&gt; f = os.readlink('/dir/dir/dir/java') &gt;&gt;&gt; java_version = os.path.basename(f) 'java' </code></pre>
0
2016-08-12T17:43:16Z
[ "python", "readlink" ]
Changing numpy structured array dtype names and formats
38,920,939
<p>I am doing some work with structured arrays in numpy (that I will eventually convert to a pandas dataframe).</p> <p>Now, I generate this structured array by reading in some data (actually memmapping some data) and then filtering it by user specified constraints. I then want to convert this data out of the form that I read it in as (everything is an int to conserve space in the file I read it from) into a more useable format so I can do some unit conversions (i.e. upconvert it to a float).</p> <p>I noticed an interesting artifact (or something) along the way which changing a structured data type. Say that reading in the data results in the same structured array as is created by the following (note that in the actual code the dtype is much longer and much more complex but this suffices for a mwe):</p> <pre><code>import numpy as np names = ['foo', 'bar'] formats = ['i4', 'i4'] dtype = np.dtype({'names': names, 'formats': formats}) data = np.array([(1, 2), (3, 4)], dtype=dtype) print(data) print(data.dtype) </code></pre> <p>This creates</p> <pre><code>[(1, 2) (3, 4)] [('foo', '&lt;i4'), ('bar', '&lt;i4')] </code></pre> <p>as the structured array</p> <p>Now, say I want to upconvert both of these dtypes to double while also renaming the second component. That seems like it should be easy</p> <pre><code>names[1] = 'baz' formats[0] = np.float formats[1] = np.float dtype_new = np.dtype({'names': names, 'formats': formats}) data2 = data.copy().astype(dtype_new) print(data2) print(data2.dtype) </code></pre> <p>but the result is unexpected</p> <pre><code>(1.0, 0.0) (3.0, 0.0)] [('foo', '&lt;f8'), ('baz', '&lt;f8')] </code></pre> <p>What happened to the data from the second component? We can do this conversion however if we split things up</p> <pre><code>dtype_new3 = np.dtype({'names': names, 'formats': formats}) data3 = data.copy().astype(dtype_new3) print(data3) print(data3.dtype) names[1] = 'baz' data4 = data3.copy() data4.dtype.names = names print(data4) print(data4.dtype) </code></pre> <p>which results in the correct output</p> <pre><code>[(1.0, 2.0) (3.0, 4.0)] [('foo', '&lt;f8'), ('bar', '&lt;f8')] [(1.0, 2.0) (3.0, 4.0)] [('foo', '&lt;f8'), ('baz', '&lt;f8')] </code></pre> <p>It appears that when <code>astype</code> is called with a structured dtype, numpy matches the names for each component and then applies the specified type to the contents (just guessing here, didn't look at the source code). Is there anyway to do this conversion all at once (i.e. the name and the upconversion of the format) or does it simply need to be done it steps. (It's not a huge deal if it needs to be done in steps, but it seems odd to me that there's not a single step way to do this.)</p>
2
2016-08-12T14:55:46Z
38,922,842
<p>There is a library of functions designed to work with <code>recarray</code> (and thus structured arrays). It's kind of hidden so I'll have do a search to find it. It has functions for renaming fields, adding and deleting fields, etc. The general pattern of action is to make a new array with the target dtype, and then copy fields one by one. Since an array usually has many elements and a small number of fields, this doesn't slow things down much.</p> <p>It looks like this <code>astype</code> method is using some of that code, or maybe compiled code that behaves the same way.</p> <p>So yes, it does look like we need change field dtypes and names in separate steps.</p> <pre><code>In [1279]: data=np.array([(1,2),(3,4)],dtype='i,i') In [1280]: data Out[1280]: array([(1, 2), (3, 4)], dtype=[('f0', '&lt;i4'), ('f1', '&lt;i4')]) In [1281]: dataf=data.astype('f8,f8') # change dtype, same default names In [1282]: dataf Out[1282]: array([(1.0, 2.0), (3.0, 4.0)], dtype=[('f0', '&lt;f8'), ('f1', '&lt;f8')]) </code></pre> <p>Easy name change:</p> <pre><code>In [1284]: dataf.dtype.names=['one','two'] In [1285]: dataf Out[1285]: array([(1.0, 2.0), (3.0, 4.0)], dtype=[('one', '&lt;f8'), ('two', '&lt;f8')]) In [1286]: data.astype(dataf.dtype) Out[1286]: array([(0.0, 0.0), (0.0, 0.0)], dtype=[('one', '&lt;f8'), ('two', '&lt;f8')]) </code></pre> <p>The <code>astype</code> with no match in names produces a <code>zero</code> array, same as <code>np.zeros(data.shape,dataf.dtype)</code>. By matching names, rather than position in the dtype, I can reorder values, and even add fields.</p> <pre><code>In [1291]: data.astype([('f1','f8'),('f0','f'),('f3','i')]) Out[1291]: array([(2.0, 1.0, 0), (4.0, 3.0, 0)], dtype=[('f1', '&lt;f8'), ('f0', '&lt;f4'), ('f3', '&lt;i4')]) </code></pre>
1
2016-08-12T16:41:58Z
[ "python", "python-3.x", "numpy", "structured-array" ]
How to use broadcasting to speed up this code?
38,920,957
<p>I have the following multi-dimensional array. The first axis denotes a 3-dimensional vector. I want to calculate the 3-by-3 matrix x⋅x' for each of those.</p> <p>My current solution:</p> <pre><code>arr.shape # (3, 64, 64, 33, 187) dm = arr.reshape(3,-1) dm.shape # (3, 25276416) cov = np.empty((3,3,dm.shape[1])) cov.shape # (3, 3, 25276416) </code></pre> <p>this for-loop iterates over all 25,276,416 elements and takes around 1 or 2 min.</p> <pre><code>for i in range(dm.shape[1]): cov[...,i] = dm[:,i].reshape(3,1).dot(dm[:,i].reshape(1,3)) cov = cov.reshape((3,) + arr.shape) cov.shape # (3, 3, 64, 64, 33, 187) </code></pre>
0
2016-08-12T14:56:46Z
38,921,145
<p>Well you are not really reducing any axes with that matrix-multiplication using <code>np.dot</code> and it's just broadcasted elementwise multiplication there. So, you can simply use <code>NumPy broadcasting</code> for the whole thing, like so -</p> <pre><code>cov = dm[:,None]*dm </code></pre> <p>Or use it directly on <code>arr</code> to avoid creating <code>dm</code> and all that reshaping, like so -</p> <pre><code>cov = arr[:,None]*arr </code></pre>
1
2016-08-12T15:07:27Z
[ "python", "numpy", "numpy-broadcasting" ]
django - python: failed using reverse : no reverse match
38,921,087
<p>I have the following Views:</p> <pre><code>def default_new (request): if request.method == "POST": post = EquipmentForm(request.POST) if form.is_valid(): post.save() return HttpResponseRedirect(reverse('calbase:default_detail', args=(id,))) else: form = EquipmentForm() return render(request, 'calbase/default_edit.html', {'form':form}) class default_detail (generic.DetailView): model = Equipment template_name = 'calbase/default_detail.html' </code></pre> <p>And urls:</p> <pre><code>urlpatterns = [ url(r'^$', views.default, name = 'default'), url(r'^default/((?P&lt;id&gt;\d+)/$)', views.default_detail.as_view(), name = 'default_detail'), url(r'^default/new/$', views.default_new, name = 'default_new'), ] </code></pre> <p>What I would like to do here is just to take in a form input, save it, and then redirect to its detail view. However, although the form is correctly saved, it always give me errors like:</p> <pre><code>NoReverseMatch at /calbase/default/new/ Reverse for 'default_detail' with arguments '(&lt;built-in function id&gt;,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['calbase/default/((?P&lt;id&gt;\\d+)/$)'] </code></pre> <p>Could somebody help me figuring out what's wrong here pls?</p>
1
2016-08-12T15:04:36Z
38,921,225
<p>The problem is you are using <a href="https://docs.python.org/3.5/library/functions.html#id" rel="nofollow"><code>id</code></a>, which is a built in function.</p> <p>When you call <code>form.save()</code>, it will return the <code>Post</code> instance. Use <code>post.id</code> (or <code>post.pk</code> if you prefer) to get the id of the post.</p> <pre><code>def default_new(request): if request.method == "POST": form = EquipmentForm(request.POST) if form.is_valid(): post = form.save() return HttpResponseRedirect(reverse('calbase:default_detail', args=(post.id,))) </code></pre> <p>You also have too many parentheses in your url pattern. It should be:</p> <pre><code>url(r'^default/(?P&lt;id&gt;\d+)/$', views.default_detail.as_view(), name = 'default_detail'), </code></pre>
3
2016-08-12T15:12:19Z
[ "python", "django", "django-urls" ]
How to get a object from a view while using a django.test TestCase
38,921,202
<p>I am trying to access the object 'wines' that would be sent to a template. Basicaly, in this example I have wines that are sold by bottles, glasses or both. The first test I am on should be able to retrieve all 3 wines in a object called 'wines' that is sent to the template. (create_wine() is a custom Wine.objects.create() method).</p> <p>If you notice, I am using django.test import TestCase so I have a self.client object to use. Also, if you notice, I am showing you where I am trying to degub at the '(debug)' text. </p> <p>What I really want to get is the prerendered json. It seems to me that view renders the html using the object to create what html it needs and returns that. So how do I access this prerendered object?</p> <p>The thing is I am going to be using the same view to render these wine objects. I would like to use the same template if possible, which would mean sending data to the view and rewriting it so it grabs the correct wines before rendering. I think this is ok. If this breaks django methodology, I am all ears.</p> <p>Is there another way to go aboutt this or am I very close? <br></p> <h1>Code</h1> <h3>VIEWs</h3> <pre><code>def wine_list(request): wines = Wine.objects.filter(is_active=True) return render(request, 'wine/wine_list.html', {'wines': wines}) </code></pre> <h3>URLs</h3> <pre><code>urlpatterns = [ url(r'^$', 'wine.views.wine_list', name='wine_list'), url(r'^bottle/$', 'wine.views.wine_list', name='wine_list_bottle'), url(r'^glass/$', 'wine.views.wine_list', name='wine_list_glass'), url(r'^([0-9]+)/$', 'wine.views.wine_details', name='wine_detail'), ] </code></pre> <h3>UT</h3> <pre><code> from django.test import TestCase def test_both_wine_glass_and_bottle_pull_different_objects(self): # Todo: how to pull object info from view self.create_wine(container="bottle") self.create_wine(container="glass") self.create_wine(container="both") request = self.client.get("/wine/") from wine.views import wine_list result = wine_list(request) (debug) result # assert wine/ wine is both glass and bottle # assert wine/glass/ wine is only both or glass wines # assert wine/bottle/ wine is only both or bottle wines self.fail("finish the test") </code></pre> <h3>'result' at (debug)</h3> <pre><code>result = {HttpResponse} &lt;HttpResponse status_code=200, "text/html; charset=utf-8"&gt; _charset = {NoneType} None _closable_objects = {list} &lt;class 'list'&gt;: [] _container = {list} &lt;class 'list'&gt;: [b'&lt;!DOCTYPE html&gt;\n&lt;html lang="en"&gt;\n&lt;head&gt;\n &lt;meta charset="UTF-8"&gt;\n &lt;title&gt;Wine List&lt;/title&gt;\n \n &lt;link rel="stylesheet" href="/static/wine/reset.css"&gt;\n &lt;link rel="stylesheet" href="/static/wine/menu.css"&gt;\n&lt;/head&gt;\n&lt;bod _handler_class = {NoneType} None _headers = {dict} {'content-type': ('Content-Type', 'text/html; charset=utf-8')} _reason_phrase = {NoneType} None charset = {str} 'utf-8' closed = {bool} False content = {bytes} b'&lt;!DOCTYPE html&gt;\n&lt;html lang="en"&gt;\n&lt;head&gt;\n &lt;meta charset="UTF-8"&gt;\n &lt;title&gt;Wine List&lt;/title&gt;\n \n &lt;link rel="stylesheet" href="/static/wine/reset.css"&gt;\n &lt;link rel="stylesheet" href="/static/wine/menu.css"&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;header c cookies = {SimpleCookie} reason_phrase = {str} 'OK' status_code = {int} 200 streaming = {bool} False </code></pre> <h3>Other passing unit tests (if these help at all)</h3> <pre><code> self.create_wine(container="both") bottle = Wine.bottle.all() glass = Wine.glass.all() both = Wine.objects.all() self.assertEqual(2, len(bottle)) self.assertEqual(2, len(glass)) self.assertEqual(3, len(both)) def test_both_wine_glass_and_bottle_pull_the_same_template(self): bottle_list = self.client.get('/wine/bottle/') glass_list = self.client.get('/wine/glass/') both_list = self.client.get('/wine/') self.assertTemplateUsed(both_list, 'wine/wine_list.html') self.assertTemplateUsed(bottle_list, 'wine/wine_list.html') self.assertTemplateUsed(glass_list, 'wine/wine_list.html') </code></pre> <h2>simple template wine_list.html</h2> <pre><code>{% extends 'wine/base.html' %} {% block content %} &lt;section id="wine_content"&gt; &lt;div class="cards"&gt; {% for wine in wines %} &lt;div class="card"&gt; &lt;a href="/wine/{{ wine.id }}"&gt; &lt;h4&gt;{{ wine.name }}&lt;/h4&gt; &lt;p&gt;{{ wine.vintage }}&lt;/p&gt; &lt;p&gt;{{ wine.description}}&lt;/p&gt; &lt;/a&gt; &lt;/div&gt; {% endfor %} &lt;/div&gt; &lt;/section&gt; {% endblock %} </code></pre>
1
2016-08-12T15:10:49Z
38,921,658
<p>You've misunderstood how the test client works. When you call <code>self.client.get("/wine/")</code>, it simulates a request to <code>/wine/</code>, and calls your <code>wine_list</code> view. You don't have to call <code>wine_list</code> manually.</p> <p>The <code>client.get()</code> call returns a response. You can then make test assertions using the response, and fetch items from <a href="https://docs.djangoproject.com/en/1.9/topics/testing/tools/#django.test.Response.context" rel="nofollow"><code>response.context</code></a>.</p> <pre><code> response = self.client.get("/wine/") self.assertEqual(response.status_code, 200) # check 200 OK response wines = response.context['wines'] # this is the list of wines you included in the context # check that wines is as you expected. for wine in wines: # All wines should be active self.assertTrue(wine.is_active) ... </code></pre>
2
2016-08-12T15:34:57Z
[ "python", "django", "unit-testing", "templates", "views" ]
Python Sockets - Keeping a connection to a server alive from the client
38,921,219
<p>I'm currently working with python's socket library for the first time and i'm not very experienced with computer networking.</p> <p>I'm able to connect to the server and the tcp handshake has happened as viewed by wireshark. After establishing a connection to the server(I have no control over the server), the connection stays open for a while, but after a small amount of time, the server sends a "FIN, ACK" and the connection is terminated. I'm trying to understand how I can keep this connection alive while the client is capable of reaching the server.</p> <p>Looking at a tcp connection, it seems a packet can be sent every so often. Maybe a sort of keep alive message. I had thought using <code>socket.send('hello')</code> every 5 seconds in another thread would keep the connection with the server open, but I still get the "FIN, ACK" after some time.</p> <p>In the documentation I found a <code>setsockopt()</code> but using this made no noticeable difference. I've tried <code>client.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)</code> both before and after the connection is made. I don't completely understand how this method is supposed to work, so maybe I used it incorrectly. There isn't much mention of this. I read somewhere about it being broken on windows. I don't know the truth in that.</p> <p>What am I missing? The documentation for sockets doesn't seem to have anything about this unless I may have missed something.</p> <pre><code>import socket import time import threading SERVER_IP = 'THE SERVER' SERVER_PORT = SERVER_PORT SOURCE_IP = socket.gethostname() SOURCE_PORT = 57004 KEEP_ALIVE_INTERVAL = 5 client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def keep_alive(interval): data = 'hello' while True: client.send(data) time.sleep(interval) client.connect((SERVER_IP, SERVER_PORT)) t = threading.Thread(target=keep_alive, args = (KEEP_ALIVE_INTERVAL,)) t.start() while True: data = client.recv(1024) if not data: break print data client.close() </code></pre>
1
2016-08-12T15:12:02Z
38,921,589
<p>For enabling keep alive there is a duplicate question at <a href="http://stackoverflow.com/questions/12248132/how-to-change-tcp-keepalive-timer-using-python-script">How to change tcp keepalive timer using python script?</a></p> <p>Keep in mind some servers and intermediate proxies forcibly close long lived connections regardless of keep alives being used or not, in which case you will see a FIN,ACK after X amount of time no matter what.</p>
0
2016-08-12T15:31:38Z
[ "python", "sockets", "tcp", "network-programming", "tcp-ip" ]
How to disable showing visibility symbols in Tagbar for a specific filetype?
38,921,220
<p>I want <a href="https://github.com/majutsushi/tagbar/blob/master/doc/tagbar.txt" rel="nofollow"><code>g:tagbar_show_visibility</code></a> be set to <code>'0'</code> for Python files as there's no public/protected/private in Python. How can I configure Vim this way?</p>
2
2016-08-12T15:12:05Z
38,922,949
<p>To perform the operation manually execute this:</p> <pre><code>:TagbarClose :let g:tagbar_show_visibility = 0 :TagbarOpen </code></pre> <p>you can add the following line to your vimrc to make it automatically:</p> <pre><code>au BufRead *.py :let g:tagbar_show_visibility = 0 </code></pre> <p>The autocommand (au) execute a command on specific events. With this particular example it sets the variable to 0 for buffers .py at the moment vim read them.</p> <p><strong>EDIT</strong></p> <p>My solution does not work very well. Since the variable g:tagbar_show_bisibility is global. The Tagbar plugin seems to read it when TagbarOpen is called. So a better approach will be to use a function to open Tagbar, say TagbarOpen2 or something. The function would check the filetype of the current buffer and set the visibility variable accordingly.</p> <p><strong>EDIT2</strong></p> <p>I made a script that will set the visibility each time you enter a buffer. Then to refresh the Tagbar I use TagbarToggle two time in a row. It is a little anoying, but its the best I got. Maybe you could come up with something better avoiding the flikering if you spend some time.</p> <p>Please share if improve this script.</p> <pre><code>function! TagbarUpdate() if (&amp;ft == 'tagbar') return endif let g:tagbar_show_visibility = 1 if (&amp;ft == 'python') let g:tagbar_show_visibility = 0 endif exec ":TagbarToggle" exec ":TagbarToggle" endfunction au! BufEnter * :call TagbarUpdate() </code></pre>
0
2016-08-12T16:50:05Z
[ "python", "vim", "tags", "tagbar" ]
How to disable showing visibility symbols in Tagbar for a specific filetype?
38,921,220
<p>I want <a href="https://github.com/majutsushi/tagbar/blob/master/doc/tagbar.txt" rel="nofollow"><code>g:tagbar_show_visibility</code></a> be set to <code>'0'</code> for Python files as there's no public/protected/private in Python. How can I configure Vim this way?</p>
2
2016-08-12T15:12:05Z
38,926,322
<p>You can customize <code>ctagsargs</code> for a particular filetype, making <code>ctags</code> not output the 'visibility' information for tags in the first place, e.g.:</p> <pre><code>let g:tagbar_type_python = { \ 'ctagsargs' : '-f - --excmd=pattern --fields=nksSmt' \ } </code></pre> <p>The important bit here is the <code>--fields</code> option, which specifies the fields to be included for each tag.</p>
1
2016-08-12T20:54:49Z
[ "python", "vim", "tags", "tagbar" ]
Define a function or loop, which restarts if given integer-parameter is less than X, or refuses to accept value less than 3
38,921,331
<p>I'm writing a simple program where a person can go on a trip, but the trip has to last <code>3</code> days <em>minimum</em>. The whole program has more parts which all work well, and the whole program works, but now I want to enhance it and set the minimal parameter value of function <code>hotel_cost(days)</code> to <code>3</code></p> <p>In it's most basic form, my function is:</p> <pre><code>def hotel_cost(days): # hotel costs 140$ per day return 140 * int(days) </code></pre> <p>And the above obviously works, but I want to change it so that it does not accept less than 3.</p> <p>I'm experimenting with while and a boolean but it gives me <code>None</code>, and I've also faced accidental infinite recursion. Sorry if this question is too basic, it's my first one. I tried searching but to no avail.</p>
1
2016-08-12T15:18:17Z
38,921,607
<p>From my understanding of the question, you can do this: </p> <pre><code>def hotel_cost(days): if int(days) &gt;= 3: return 140 * int(days) else: return False </code></pre> <p>And then you can do:</p> <pre class="lang-py prettyprint-override"><code>while not hotel_cost(days): print("How many days are you staying?") days = input() </code></pre> <p>Once it gets out of the while, the days amount will be valid, as well as the cost.</p> <p><strong>EDIT :</strong><br><br> I wrote the code inside the while loop, to be more clear about what I suggested.</p> <p>I hope it helps. Cheers.</p>
0
2016-08-12T15:32:31Z
[ "python", "python-2.x" ]
Define a function or loop, which restarts if given integer-parameter is less than X, or refuses to accept value less than 3
38,921,331
<p>I'm writing a simple program where a person can go on a trip, but the trip has to last <code>3</code> days <em>minimum</em>. The whole program has more parts which all work well, and the whole program works, but now I want to enhance it and set the minimal parameter value of function <code>hotel_cost(days)</code> to <code>3</code></p> <p>In it's most basic form, my function is:</p> <pre><code>def hotel_cost(days): # hotel costs 140$ per day return 140 * int(days) </code></pre> <p>And the above obviously works, but I want to change it so that it does not accept less than 3.</p> <p>I'm experimenting with while and a boolean but it gives me <code>None</code>, and I've also faced accidental infinite recursion. Sorry if this question is too basic, it's my first one. I tried searching but to no avail.</p>
1
2016-08-12T15:18:17Z
38,921,860
<p>Your can condense asking the user for the number of days, and giving them there price in in one function.</p> <pre><code>def ask_num_hotel_days(): i = int(input("Enter nuber of days: ")) while(i &lt; 3): print(str(i) + " is not a valid number of days") i = int(input("Enter nuber of days: ")) return 140 * i </code></pre>
0
2016-08-12T15:45:04Z
[ "python", "python-2.x" ]
Python - Display one line for each unique word
38,921,364
<p>I'm trying to write a python code that counts the frequency of each word in a text file. The code should display one line per unique word. The code I wrote is displaying duplicate words. </p> <pre><code>import string text = open('mary.txt','r') textr = text.read() for punc in string.punctuation: textr = textr.replace(punc, "") wordlist = textr.split() for word in wordlist: count = wordlist.count(word) print word,':',count </code></pre> <p>My current output is... </p> <pre><code>are : 1 around : 1 as : 1 at : 2 at : 2 away : 1 back : 1 be : 2 be : 2 because : 1 below : 1 between : 1 both : 1 but : 1 by : 2 by : 2 </code></pre> <p>The output should only display <code>at : 2</code>,<code>be : 2</code>, and <code>by : 2</code> once. What should I change in my code for that to happen? </p>
1
2016-08-12T15:20:01Z
38,921,409
<p>The issue with your code is that you're creating a list of all the words and then looping over them. You want to create some sort of data structure that only stores unique words. A <code>dict</code> is a good way to do this, but it turns out there's a specialized collection in Python called a <code>Counter</code> that's built for exactly this purpose.</p> <p>Give this a try (untested):</p> <pre><code>from collections import Counter import string text = open('mary.txt','r') textr = text.read() for punc in string.punctuation: textr = textr.replace(punc, "") counts = Counter(textr.split()) for word, count in counts.items(): print word,':',count </code></pre>
2
2016-08-12T15:22:53Z
[ "python", "python-2.7" ]
Python - Display one line for each unique word
38,921,364
<p>I'm trying to write a python code that counts the frequency of each word in a text file. The code should display one line per unique word. The code I wrote is displaying duplicate words. </p> <pre><code>import string text = open('mary.txt','r') textr = text.read() for punc in string.punctuation: textr = textr.replace(punc, "") wordlist = textr.split() for word in wordlist: count = wordlist.count(word) print word,':',count </code></pre> <p>My current output is... </p> <pre><code>are : 1 around : 1 as : 1 at : 2 at : 2 away : 1 back : 1 be : 2 be : 2 because : 1 below : 1 between : 1 both : 1 but : 1 by : 2 by : 2 </code></pre> <p>The output should only display <code>at : 2</code>,<code>be : 2</code>, and <code>by : 2</code> once. What should I change in my code for that to happen? </p>
1
2016-08-12T15:20:01Z
38,922,090
<p>As another way to implement this, you could have taken your solution, added all of the entries as (word, count) tuples to a set, then printed the set. You should probably rethink your implementation anyway like @smarx points out but this will fix the issue using your native code.</p>
0
2016-08-12T15:57:17Z
[ "python", "python-2.7" ]
Python - Display one line for each unique word
38,921,364
<p>I'm trying to write a python code that counts the frequency of each word in a text file. The code should display one line per unique word. The code I wrote is displaying duplicate words. </p> <pre><code>import string text = open('mary.txt','r') textr = text.read() for punc in string.punctuation: textr = textr.replace(punc, "") wordlist = textr.split() for word in wordlist: count = wordlist.count(word) print word,':',count </code></pre> <p>My current output is... </p> <pre><code>are : 1 around : 1 as : 1 at : 2 at : 2 away : 1 back : 1 be : 2 be : 2 because : 1 below : 1 between : 1 both : 1 but : 1 by : 2 by : 2 </code></pre> <p>The output should only display <code>at : 2</code>,<code>be : 2</code>, and <code>by : 2</code> once. What should I change in my code for that to happen? </p>
1
2016-08-12T15:20:01Z
39,030,802
<p>You can try something like this: </p> <pre><code>import string frequency = {} text = open('mary.txt','r') textr = text.read() for punc in string.punctuation: textr = textr.replace(punc, "") wordlist = textr.split() for word in wordlist: count = frequency.get(word,0) frequency[word] = count + 1 frequency_list = frequency.keys() for words in frequency_list: print words,':', frequency[words] </code></pre>
0
2016-08-19T03:48:36Z
[ "python", "python-2.7" ]
PyQT : Transfer between two TableView
38,921,398
<p>I would like to transfer data between two QtTableView. To do that, I first select the row to transfer then click on "to_X_table".</p> <p>But I don't understand how to fill the second tableview with the first one. I tried :</p> <pre><code>self.to_X_table.clicked.connect(self.to_X_tableView) def to_X_tableView(self): self.proxy = QtCore.QSortFilterProxyModel() self.proxy.setSourceModel(self.tableWidget_Input_Col.selectionModel()) self.tableView_X.setModel(self.proxy) self.tableView_X.resizeColumnsToContents() </code></pre> <p>I get this message :</p> <pre><code>TypeError : setSourceModel(self,‌​QAbstractItemModel) : 1 argument unexpected type QItemSelectionModel </code></pre> <p>I'dont really know what self.tableWidget_Input_Col.selectionModel() return. I guess it was a model. But seems not.</p> <p>I also tried to create my own model like this (following this post <a href="http://stackoverflow.com/questions/21280061/get-data-from-every-cell-from-a-qtableview">Get data from every cell from a QTableView</a>)</p> <pre><code>def to_X_tableView(self): indexes = self.tableWidget_Input_Col.selectionModel().selectedRows() self.model = QtGui.QStandardItemModel() for index in sorted(indexes): print('Row %d is selected' % index.row()) self.model.invisibleRootItem().appendRow( QtGui.QStandardItem(self.tableWidget_Input_Col.model.index(index.row, 0))) self.proxy = QtCore.QSortFilterProxyModel() self.proxy.setSourceModel(self.tableWidget_Input_Col.selectionModel()) self.tableView_X.setModel(self.proxy) self.tableView_X.resizeColumnsToContents() </code></pre> <p>but I get this error :</p> <pre><code>Traceback (most recent call last): File "ChartGUI.py", line 151, in to_X_tableView QtGui.QStandardItem(self.tableWidget_Input_Col.model.index(index.row, 0) AttributeError: 'builtin_function_or_method' object has no attribute 'index' </code></pre>
0
2016-08-12T15:22:09Z
39,017,619
<p>Finaly, I solve my problem. I didn't consider the model the first time. Here :</p> <pre><code> self.modelX = QtGui.QStandardItemModel() indexes = self.tableWidget_Input_Col.selectionModel().selectedIndexes() temp=self.tableWidget_Input_Col.selectionModel().model() # need to consider the model ! for index in sorted(indexes): self.modelX.invisibleRootItem().appendRow( QtGui.QStandardItem(str(temp.data(index)))) self.proxy = QtCore.QSortFilterProxyModel() self.proxy.setSourceModel(self.modelX) self.tableView_X.setModel(self.proxy) self.tableView_X.resizeColumnsToContents() </code></pre>
0
2016-08-18T11:56:51Z
[ "python", "pyqt5" ]
Create and write to new csv file during 'for' loop
38,921,486
<p>The code below is intended to create a csv file called 'file-0.csv' and start writing lines by iterating through the for loop until it reaches 100 lines. When the limit is reached, it should stop writing to 'file-0.csv', create 'file-1.csv', and <strong>continuing the for loop where it left off</strong>, start writing to 'file-1.csv' until it reaches 100 lines, and so on until the for loop is complete.</p> <p>The actual behavior of the code below (complete, and executable) is that it creates the new files as expected (4 total), but it continues to write all lines to 'file-0'....</p> <pre><code>##### Python 3.5 ##### import csv rowCounter = 0 fileCounter = 0 List_A = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] List_B = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] List_C = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] def new_file(): global fileCounter fileCounter += 1 with open('file-' + str(fileCounter) + '.csv', 'w') as csvfile: rowWriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_NONE) with open('file-' + str(fileCounter) + '.csv', 'w') as csvfile: rowWriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_NONE) for word1 in List_A: for word2 in List_B: for word3 in List_C: sentence = word1 + word2 + word3 rowWriter.writerow ([sentence]) rowCounter += 1 if rowCounter == 100: new_file() rowCounter = 0 else: continue </code></pre> <p>Same code as above, but heavily commented:</p> <pre><code>##### Python 3.5 ##### ###################### ####### Setup ######## ###################### ### Use the CSV library import csv ### Initialize counters rowCounter = 0 fileCounter = 0 ### Create three lists of 'words' List_A = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] List_B = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] List_C = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] ### Function/subroutine that creates new CSV file with incremented filename def new_file(): ### Make the variable 'fileCounter' usable by the function global fileCounter ### Add 1 to 'fileCounter' fileCounter += 1 ### Create new CSV file using the value of 'fileCounter' as part of the name with open('file-' + str(fileCounter) + '.csv', 'w') as csvfile: rowWriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_NONE) ###################### #### Main Program #### ###################### ### Create initial CSV file using the value of 'fileCounter' as part of the name with open('file-' + str(fileCounter) + '.csv', 'w') as csvfile: ### Create writer object and define how it should behave rowWriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_NONE) ### Create &amp; Write lines ### ### Nested 'for' loops to iterate through all combinations of words for word1 in List_A: for word2 in List_B: for word3 in List_C: ### Build our 'sentence' from the current iteration sentence = word1 + word2 + word3 ### Write 'sentence' to file rowWriter.writerow ([sentence]) ### Increment row counter rowCounter += 1 ### Check if value of rowCounter is 100 and if so, execute ### 'new_file' and reset rowCounter to 0. If not, continue. if rowCounter == 100: new_file() rowCounter = 0 else: continue </code></pre> <p>I suspect the problem is 'rowWriter' not getting updated or passed back to the main loop properly, but I can't seem to figure out how to do it (and anyway, I'm not even sure if that's it).</p> <p>I've tried to document and make the code "generic" so others can get some use out of any answers. Any help is greatly appreciated.</p>
2
2016-08-12T15:26:45Z
38,921,779
<p>Leaving the <code>with</code> block closes with file. Therefore, the <code>new_file</code> function just opens and immediately closes a file.</p> <p>You could do somthing like the following:</p> <pre><code>import csv rowCounter = 0 fileCounter = 0 List_A = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] List_B = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] List_C = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] # create file handle csvfile = open('file-' + str(fileCounter) + '.csv', 'w') rowWriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_NONE) for word1 in List_A: for word2 in List_B: for word3 in List_C: sentence = word1 + word2 + word3 rowWriter.writerow ([sentence]) rowCounter += 1 if rowCounter == 100: # close current filehandle csvfile.close() fileCounter += 1 # open new file csvfile = open('file-' + str(fileCounter) + '.csv', 'w') rowWriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_NONE) rowCounter = 0 # close file csvfile.close() </code></pre> <p>or with defining a function:</p> <pre><code>import csv rowCounter = 0 fileCounter = 0 List_A = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] List_B = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] List_C = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] def new_writer( csvfile, counter ): if csvfile: csvfile.close() # open new file csvfile = open('file-' + str(counter) + '.csv', 'w') rowWriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_NONE) counter += 1 return rowWriter,csvfile,counter rowWriter, csvFile, fileCounter = new_writer( None, fileCounter ) for word1 in List_A: for word2 in List_B: for word3 in List_C: sentence = word1 + word2 + word3 rowWriter.writerow ([sentence]) rowCounter += 1 if rowCounter == 100: # close current file and open a new one rowWriter, csvfile, counter = new_writer( csvfile, fileCounter ) rowCounter = 0 # close file csvFile.close() </code></pre>
2
2016-08-12T15:41:01Z
[ "python", "python-3.x", "csv", "for-loop" ]
Create and write to new csv file during 'for' loop
38,921,486
<p>The code below is intended to create a csv file called 'file-0.csv' and start writing lines by iterating through the for loop until it reaches 100 lines. When the limit is reached, it should stop writing to 'file-0.csv', create 'file-1.csv', and <strong>continuing the for loop where it left off</strong>, start writing to 'file-1.csv' until it reaches 100 lines, and so on until the for loop is complete.</p> <p>The actual behavior of the code below (complete, and executable) is that it creates the new files as expected (4 total), but it continues to write all lines to 'file-0'....</p> <pre><code>##### Python 3.5 ##### import csv rowCounter = 0 fileCounter = 0 List_A = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] List_B = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] List_C = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] def new_file(): global fileCounter fileCounter += 1 with open('file-' + str(fileCounter) + '.csv', 'w') as csvfile: rowWriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_NONE) with open('file-' + str(fileCounter) + '.csv', 'w') as csvfile: rowWriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_NONE) for word1 in List_A: for word2 in List_B: for word3 in List_C: sentence = word1 + word2 + word3 rowWriter.writerow ([sentence]) rowCounter += 1 if rowCounter == 100: new_file() rowCounter = 0 else: continue </code></pre> <p>Same code as above, but heavily commented:</p> <pre><code>##### Python 3.5 ##### ###################### ####### Setup ######## ###################### ### Use the CSV library import csv ### Initialize counters rowCounter = 0 fileCounter = 0 ### Create three lists of 'words' List_A = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] List_B = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] List_C = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] ### Function/subroutine that creates new CSV file with incremented filename def new_file(): ### Make the variable 'fileCounter' usable by the function global fileCounter ### Add 1 to 'fileCounter' fileCounter += 1 ### Create new CSV file using the value of 'fileCounter' as part of the name with open('file-' + str(fileCounter) + '.csv', 'w') as csvfile: rowWriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_NONE) ###################### #### Main Program #### ###################### ### Create initial CSV file using the value of 'fileCounter' as part of the name with open('file-' + str(fileCounter) + '.csv', 'w') as csvfile: ### Create writer object and define how it should behave rowWriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_NONE) ### Create &amp; Write lines ### ### Nested 'for' loops to iterate through all combinations of words for word1 in List_A: for word2 in List_B: for word3 in List_C: ### Build our 'sentence' from the current iteration sentence = word1 + word2 + word3 ### Write 'sentence' to file rowWriter.writerow ([sentence]) ### Increment row counter rowCounter += 1 ### Check if value of rowCounter is 100 and if so, execute ### 'new_file' and reset rowCounter to 0. If not, continue. if rowCounter == 100: new_file() rowCounter = 0 else: continue </code></pre> <p>I suspect the problem is 'rowWriter' not getting updated or passed back to the main loop properly, but I can't seem to figure out how to do it (and anyway, I'm not even sure if that's it).</p> <p>I've tried to document and make the code "generic" so others can get some use out of any answers. Any help is greatly appreciated.</p>
2
2016-08-12T15:26:45Z
38,922,010
<p>Thanks @desiato!</p> <p>I accepted your answer, but ended up using lines 23-29 of your code and ended up with this (it works great!):</p> <pre><code>import csv rowCounter = 0 fileCounter = 0 List_A = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] List_B = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] List_C = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] with open('file-' + str(fileCounter) + '.csv', 'w') as csvfile: rowWriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_NONE) for word1 in List_A: for word2 in List_B: for word3 in List_C: sentence = word1 + word2 + word3 rowWriter.writerow ([sentence]) rowCounter += 1 if rowCounter == 100: csvfile.close() fileCounter += 1 csvfile = open('file-' + str(fileCounter) + '.csv', 'w') rowWriter = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_NONE) rowCounter = 0 else: continue </code></pre>
0
2016-08-12T15:53:22Z
[ "python", "python-3.x", "csv", "for-loop" ]
Twitter data pull: How do i specify a range of date for Twitter data pull with specified keywords
38,921,489
<p>How do I search and pull data from Twitter containg specific keywords (or search terms) and in a specific data range.</p> <p>I see that I can use </p> <pre><code>import tweepy #override tweepy.StreamListener to add logic to on_status class MyStreamListener(tweepy.StreamListener): def on_status(self, status): print(status.text) myStreamListener = MyStreamListener() myStream = tweepy.Stream(auth = api.auth, listener=myStreamListener()) myStream.filter(track=['olympics']) </code></pre> <p>But here how do i specify the range of dates, like Jan 1 2016 to august 4, 2016,</p> <p>Other way would be to use the api.searh</p> <pre><code>auth = tweepy.OAuthHandler(TwitterAuth.consumer_key, TwitterAuth.consumer_secret) auth.set_access_token(TwitterAuth.access_token, TwitterAuth.access_token_secret) rawParser = RawParser() api = tweepy.API(auth_handler=auth, parser=rawParser) result=api.search(count=100,q='olympics',result_type="recent") </code></pre> <p>Here ho do i pass the start date and stop date, and how to proceed if there is a list of keywords. I am using Python for programming.</p>
0
2016-08-12T15:27:03Z
38,989,823
<p>I searched in the web and found this library to be very useful <a href="https://github.com/Jefferson-Henrique/GetOldTweets-python" rel="nofollow">https://github.com/Jefferson-Henrique/GetOldTweets-python</a>. </p> <p>In Python,</p> <pre><code>tweetCriteria = got.manager.TweetCriteria().setQuerySearch('olympics').setSince("2016-01-01").setUntil("2016-08-04").setMaxTweets(10000) tweet = got.manager.TweetManager.getTweets(tweetCriteria)[0] print tweet.text </code></pre> <p>Or,</p> <pre><code>python Exporter.py --querysearch 'olympics' --since 2016-01-01 --until 2016-08-04 --maxtweets 10000 </code></pre>
0
2016-08-17T06:45:36Z
[ "python", "api", "twitter" ]
how to throttle a large number of task with out using all workers
38,921,531
<p>Imagine I have a dask grid with 10 workers &amp; 40 cores totals. This is a shared grid, so I don't want to fully saturate it with my work. I have 1000 tasks to do, and I want to submit (and have actively running) a maximum of 20 tasks at a time.</p> <p>To be concrete, </p> <pre><code>from time import sleep from random import random def inc(x): from random import random sleep(random() * 2) return x + 1 def double(x): from random import random sleep(random()) return 2 * x &gt;&gt;&gt; from distributed import Executor &gt;&gt;&gt; e = Executor('127.0.0.1:8786') &gt;&gt;&gt; e &lt;Executor: scheduler=127.0.0.1:8786 workers=10 threads=40&gt; </code></pre> <p>If I setup a system of Queues</p> <pre><code>&gt;&gt;&gt; from queue import Queue &gt;&gt;&gt; input_q = Queue() &gt;&gt;&gt; remote_q = e.scatter(input_q) &gt;&gt;&gt; inc_q = e.map(inc, remote_q) &gt;&gt;&gt; double_q = e.map(double, inc_q) </code></pre> <p>This will work, BUT, this will just dump ALL of my tasks to the grid, saturating it. Ideally I could:</p> <pre><code>e.scatter(input_q, max_submit=20) </code></pre> <p>It seems that the example from the docs <a href="http://distributed.readthedocs.io/en/latest/queues.html#example" rel="nofollow">here</a> would allow me to use a <code>maxsize</code> queue. But that looks like from a user-perspective I would still have to deal with the backpressure. Ideally <code>dask</code> would automatically take care of this. </p>
4
2016-08-12T15:28:41Z
38,921,763
<h3>Use <code>maxsize=</code></h3> <p>You're very close. All of <code>scatter</code>, <code>gather</code>, and <code>map</code> take the same <code>maxsize=</code> keyword argument that <code>Queue</code> takes. So a simple workflow might be as follows:</p> <h3>Example</h3> <pre><code>from time import sleep def inc(x): sleep(1) return x + 1 your_input_data = list(range(1000)) from queue import Queue # Put your data into a queue q = Queue() for i in your_input_data: q.put(i) from dask.distributed import Executor e = Executor('127.0.0.1:8786') # Connect to cluster futures = e.map(inc, q, maxsize=20) # Map inc over data results = e.gather(futures) # Gather results L = [] while not q.empty() or not futures.empty() or not results.empty(): L.append(results.get()) # this blocks waiting for all results </code></pre> <p>All of <code>q</code>, <code>futures</code>, and <code>results</code> are Python Queue objects. The <code>q</code> and <code>results</code> queues don't have a limit, so they'll greedily pull in as much as they can. The <code>futures</code> queue however has a maximum size of 20, so it will only allow 20 futures in flight at any given time. Once the leading future is complete it will immediately be consumed by the gather function and its result will be placed into the <code>results</code> queue. This frees up space in <code>futures</code> and causes another task to be submitted.</p> <p>Note that this isn't exactly what you wanted. These queues are ordered so futures will only get popped off when they're in the front of the queue. If all of the in-flight futures have finished except for the first they'll still stay in the queue, taking up space. Given this constraint you might want to choose a <code>maxsize=</code> slightly more than your desired <code>20</code> items.</p> <h3>Extending this</h3> <p>Here we do a simple <code>map-&gt;gather</code> pipeline with no logic in between. You could also put other <code>map</code> computations in here or even pull futures out of the queues and do custom work with them on your own. It's easy to break out of the mold provided above.</p>
3
2016-08-12T15:40:15Z
[ "python", "dask" ]
Numpy choose shape mismatch
38,921,558
<p>I have a numpy problem with choose. I would like to choose certain indices as decribed in array a from array b.</p> <pre><code>a Out[54]: array([[3, 2, 2], [0, 0, 2]], dtype=int64) b Out[55]: array([[[ 6., 1., 8., 9., 3., 8., 5.], [ 6., 1., 5., 8., 2., 2., 10.], [ 6., 1., 1., 0., 9., 3., 6.]], [[ 11., 3., 8., 9., 3., 8., 5.], [ 12., 7., 5., 8., 2., 2., 10.], [ 8., 9., 1., 0., 9., 3., 6.]]]) np.choose(a,b) ValueError: shape mismatch: objects cannot be broadcast to a single shap </code></pre> <p>In the documentation of numpy it says: Choice arrays. a and all of the choices must be broadcastable to the same shape. If choices is itself an array (not recommended), then its outermost dimension (i.e., the one corresponding to choices.shape[0]) is taken as defining the “sequence”.</p> <p>I see that it is not recommended to choose from a ndarray but is there an elegant numpy way to get this to work anyway? Any suggestions are appreciated.</p> <p>Expected output is:</p> <pre><code>[[9,5,1], [11,12,1]] </code></pre>
2
2016-08-12T15:29:58Z
38,922,018
<p>It looks you want to use <code>choose</code> to select values from the dimension of length 7 in <code>b</code> (which is sized (2,3,7)). Your choosing array <code>a</code> will work for this, but only if the sequence dimension is the outermost dimension (as you quoted). The outermost dimension in Numpy is the <em>first</em> dimension. What you need to do, then, is roll <code>b</code> so that it has dimensions (7,2,3).</p> <pre><code>np.choose(a, np.rollaxis(b, 2, 0)) </code></pre>
2
2016-08-12T15:53:46Z
[ "python", "numpy" ]
exporting a matrix to a text file in python
38,921,604
<p>I have a list of lists(matrix) in python and I want to export it to a text file. the inner lists have 3 elements. my file would have 3 columns. in other word, the first column would have the first element of inner list, the 2nd column would have the 2nd element of inner lists and the 3rd column would have the 3rd elements. I tried to make it but all elements would be in a single column. here is a small example: input:</p> <pre><code>[['ENSG00000137288.5', 0.16721311, 0.13442624], ['ENSG00000116032.5', 0.094311371, 0.1444611], ['ENSG00000167578.12', 0.062894806, 0.10162043]] </code></pre> <p>output(which would be a text file):</p> <pre><code>ENSG00000137288.5 0.16721311 0.13442624 ENSG00000116032.5 0.094311371 0.1444611 ENSG00000167578.12 0.062894806 0.10162043 </code></pre> <p>do you guys know how to do that? thanks</p>
0
2016-08-12T15:32:25Z
38,921,790
<p>The easiest way without using numpy, pandas or any other external package would be something like this:</p> <pre><code>data = [ ['ENSG00000137288.5', 0.16721311, 0.13442624], ['ENSG00000116032.5', 0.094311371, 0.1444611], ['ENSG00000167578.12', 0.062894806, 0.10162043] ] # builtin python functions data_file = "\n".join([" ".join(map(lambda x: str(x),row)) for row in data]) print data_file </code></pre>
0
2016-08-12T15:41:33Z
[ "python", "file" ]
exporting a matrix to a text file in python
38,921,604
<p>I have a list of lists(matrix) in python and I want to export it to a text file. the inner lists have 3 elements. my file would have 3 columns. in other word, the first column would have the first element of inner list, the 2nd column would have the 2nd element of inner lists and the 3rd column would have the 3rd elements. I tried to make it but all elements would be in a single column. here is a small example: input:</p> <pre><code>[['ENSG00000137288.5', 0.16721311, 0.13442624], ['ENSG00000116032.5', 0.094311371, 0.1444611], ['ENSG00000167578.12', 0.062894806, 0.10162043]] </code></pre> <p>output(which would be a text file):</p> <pre><code>ENSG00000137288.5 0.16721311 0.13442624 ENSG00000116032.5 0.094311371 0.1444611 ENSG00000167578.12 0.062894806 0.10162043 </code></pre> <p>do you guys know how to do that? thanks</p>
0
2016-08-12T15:32:25Z
38,921,867
<p>Try the <code>csv.writer</code>:</p> <pre><code>import csv your_data=[['ENSG00000137288.5', 0.16721311, 0.13442624], ['ENSG00000116032.5', 0.094311371, 0.1444611], ['ENSG00000167578.12', 0.062894806, 0.10162043]] with open('output.txt', 'wb') as csvfile: w = csv.writer(csvfile, delimiter=' ') for row in your_data: w.writerow(row) </code></pre> <p>You can specify any delimiter you want (comma,tab,space etc.) and there can be any number of columns and rows in the matrix.</p> <p>If you want to open the file in excel, then use comma <code>,</code> as delimeter and change file name to <code>.csv</code> :</p> <pre><code>import csv your_data=[['ENSG00000137288.5', 0.16721311, 0.13442624], ['ENSG00000116032.5', 0.094311371, 0.1444611], ['ENSG00000167578.12', 0.062894806, 0.10162043]] with open('output.csv', 'wb') as csvfile: w = csv.writer(csvfile, delimiter=',') for row in your_data: w.writerow(row) </code></pre> <p>or using <code>tab</code> with <code>dialect='excel'</code>:</p> <pre><code>import csv your_data=[['ENSG00000137288.5', 0.16721311, 0.13442624], ['ENSG00000116032.5', 0.094311371, 0.1444611], ['ENSG00000167578.12', 0.062894806, 0.10162043]] with open('output.xls', 'wb') as csvfile: w = csv.writer(csvfile, delimiter='\t', dialect='excel') for row in your_data: w.writerow(row) </code></pre>
0
2016-08-12T15:45:29Z
[ "python", "file" ]
Python model targeting n variable prediction equation
38,921,636
<p>I am looking to build a predictive model and am working with our current JMP model. Our current approach is to guess an nth degree polynomial and then look at which terms are not significant model effects. Polynomials are not always the best and this leads to a lot of confusion and bad models. Our data can have between 2 and 7 effects and always has one response.</p> <p>I want to use python for this, but package documentation or online guides for something like this are hard to find. I know how to fit a specific nth degree polynomial or do a linear regression in python, but not how to 'guess' the best function type for the data set.</p> <p>Am I missing something obvious or should I be writing something that probes through a variety of function types? Precision is the most important. I am working with a small (~2000x100) data set.</p> <p>Potentially I can do regression on smaller training sets, test them against the validation set, then rank the models and choose the best. Is there something better?</p>
1
2016-08-12T15:33:40Z
38,922,083
<p><a href="http://statsmodels.sourceforge.net/stable/anova.html" rel="nofollow">ANOVA (analysis of variance)</a> uses covariance to determine which effects are statistically significant... you shouldn't have to choose terms at random.</p> <p>However, if you are saying that your data is inhomogenous (i.e., you shouldn't fit a single model to all the data), then you might consider using the <a href="http://scikit-learn.org/stable/index.html" rel="nofollow">scikit-learn</a> toolkit to build a classifier that could choose a subset of the data to fit.</p>
0
2016-08-12T15:56:55Z
[ "python", "pandas", "scikit-learn", "non-linear-regression" ]
Python model targeting n variable prediction equation
38,921,636
<p>I am looking to build a predictive model and am working with our current JMP model. Our current approach is to guess an nth degree polynomial and then look at which terms are not significant model effects. Polynomials are not always the best and this leads to a lot of confusion and bad models. Our data can have between 2 and 7 effects and always has one response.</p> <p>I want to use python for this, but package documentation or online guides for something like this are hard to find. I know how to fit a specific nth degree polynomial or do a linear regression in python, but not how to 'guess' the best function type for the data set.</p> <p>Am I missing something obvious or should I be writing something that probes through a variety of function types? Precision is the most important. I am working with a small (~2000x100) data set.</p> <p>Potentially I can do regression on smaller training sets, test them against the validation set, then rank the models and choose the best. Is there something better?</p>
1
2016-08-12T15:33:40Z
39,363,619
<p>Try using other regression models instead of the vanilla Linear Model.</p> <p>You can use something like this for polynomial regression:</p> <pre><code>poly = PolynomialFeatures(degree=2) X_ = poly.fit_transform(input_data) </code></pre> <p>And you can constraint the weights through the Lasso Regression </p> <pre><code>clf = linear_model.Lasso(alpha = 0.5, positive = True) clf.fit(X_,Y_) </code></pre> <p>where Y_ is the output you want to train against.</p> <p>Setting alpha to 0 turns it into a simple linear regression. alpha is basically the penalty imposed for smaller weights. You can also make the weights strictly positive. Check this out <a href="http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Lasso.html" rel="nofollow">here.</a></p> <p>Run it with a small degree and perform a cross-validation to check how good it fits.</p> <p>Increasing the degree of the polynomial generally leads to over-fitting. So if you are forced to use degree 4 or 5, that means you should look for other models.</p> <p>You should also take a look at this <a href="http://stackoverflow.com/questions/23004374/how-to-calculate-the-likelihood-of-curve-fitting-in-scipy">question.</a> This explains how you can curve fit.</p>
1
2016-09-07T07:21:42Z
[ "python", "pandas", "scikit-learn", "non-linear-regression" ]
Is there an accepted way to have a function pop a value from a parameter?
38,921,705
<p>Essentially, I would like to know if I should be attempting to avoid side effects in functions if possible, or if side effects are acceptable in certain situations. I would like to have a function which <code>pop</code>s and returns a key from a dictionary and am curious if the function should return just the key:</p> <pre><code>def popkey(d): k, v = d.popitem() return k mykey = popkey(d) </code></pre> <p>or if it should also return the modified dictionary:</p> <pre><code>def popkey(d): k, v = d.popitem() return k, d mykey, d = popkey(d) </code></pre> <p>More specifically, I have something like the following, where I need keep looking through the dictionary, so I wanted to <code>pop</code> the keys as they are paired with the elements from a list.</p> <pre><code>def pop_nearest(d, pt): """Pops the key in `d` which is nearest to pt.""" to_pop = min(d.iterkeys(), key=lambda a: abs(a - pt)) d.pop(to_pop) pts = [1,3,5,7,9] for pt in pts: nearest_pt = pop_nearest(d, pt) # do some other stuff </code></pre>
1
2016-08-12T15:37:25Z
38,921,823
<p>There is no need to return the parameter, since you already have a reference to it at the call site.</p> <p>If you choose to implement <code>pop_nearest</code> as a method in a <code>dict</code> subclass, then it's sometimes a good idea (depending on what you are trying to achieve) to return <code>self</code> so you can chain calls.</p> <pre><code>class MyDict(dict): ... def pop_nearest(self, pt): ... return self ... x = mydict.pop_nearest(1).pop_nearest(2) </code></pre>
1
2016-08-12T15:43:18Z
[ "python", "dictionary", "side-effects" ]
Is there an accepted way to have a function pop a value from a parameter?
38,921,705
<p>Essentially, I would like to know if I should be attempting to avoid side effects in functions if possible, or if side effects are acceptable in certain situations. I would like to have a function which <code>pop</code>s and returns a key from a dictionary and am curious if the function should return just the key:</p> <pre><code>def popkey(d): k, v = d.popitem() return k mykey = popkey(d) </code></pre> <p>or if it should also return the modified dictionary:</p> <pre><code>def popkey(d): k, v = d.popitem() return k, d mykey, d = popkey(d) </code></pre> <p>More specifically, I have something like the following, where I need keep looking through the dictionary, so I wanted to <code>pop</code> the keys as they are paired with the elements from a list.</p> <pre><code>def pop_nearest(d, pt): """Pops the key in `d` which is nearest to pt.""" to_pop = min(d.iterkeys(), key=lambda a: abs(a - pt)) d.pop(to_pop) pts = [1,3,5,7,9] for pt in pts: nearest_pt = pop_nearest(d, pt) # do some other stuff </code></pre>
1
2016-08-12T15:37:25Z
38,922,011
<p>You don't need to return the modified dictionary. It is modified in the function like you would think since it is a reference/pointer to the actual object and not a deep copy and will exist in its modified form in the calling function after pop is called. Returning the key should be sufficient and work how you want it to.</p>
1
2016-08-12T15:53:23Z
[ "python", "dictionary", "side-effects" ]
Python - args an **kargs
38,921,813
<p>I have this global <code>function</code>:</p> <pre><code>def filterBelowThreshold(name, feature, tids, xsongs, **kwargs): print (name, 'PLAYLIST') for i, x in enumerate(feature): if x &lt; value: track_name = sp.track(tids[i])['name'] xsongs.append(track_name) print(name, ":", "{} - feature: {}".format(track_name, x)) </code></pre> <p>I want to call it inside a <code>class</code> <code>function</code> passing the following parameters (whose variables are declared locally):</p> <pre><code>filterBelowThreshold('myname', energy, tids, xsongs, value=0.650) </code></pre> <p>inside the <code>class function</code>, prior to the function call, I declare the following variables: </p> <p><code>energy = [item 1, item2, item3, ...]</code></p> <p><code>tids = []</code></p> <p><code>xsongs = []</code></p> <p>what is the proper syntax for the GLOBAL function? </p>
0
2016-08-12T15:43:01Z
38,922,047
<p><strong>test.py</strong></p> <pre><code>def filterBelowThreshold(name, feature, tids, xsongs, **kwargs): print kwargs['value'] class Test(object): def __init__(self): energy = ['item 1', 'item2', 'item3' ] tids = [] xsongs = [] filterBelowThreshold('myname', energy, tids, xsongs, value=0.650) a = Test() </code></pre> <p><code>python test.py</code> will print <code>0.65</code></p> <p>You already defined it right, there is no problem. What is the problem you are facing?</p>
0
2016-08-12T15:55:38Z
[ "python", "args", "kwargs" ]
Python - args an **kargs
38,921,813
<p>I have this global <code>function</code>:</p> <pre><code>def filterBelowThreshold(name, feature, tids, xsongs, **kwargs): print (name, 'PLAYLIST') for i, x in enumerate(feature): if x &lt; value: track_name = sp.track(tids[i])['name'] xsongs.append(track_name) print(name, ":", "{} - feature: {}".format(track_name, x)) </code></pre> <p>I want to call it inside a <code>class</code> <code>function</code> passing the following parameters (whose variables are declared locally):</p> <pre><code>filterBelowThreshold('myname', energy, tids, xsongs, value=0.650) </code></pre> <p>inside the <code>class function</code>, prior to the function call, I declare the following variables: </p> <p><code>energy = [item 1, item2, item3, ...]</code></p> <p><code>tids = []</code></p> <p><code>xsongs = []</code></p> <p>what is the proper syntax for the GLOBAL function? </p>
0
2016-08-12T15:43:01Z
38,922,347
<p>You should not use <code>**kwargs</code> if you call the function with a explicit parameter <code>value</code>, just use normal arguments:</p> <pre><code>def filterBelowThreshold(name, feature, tids, xsongs, value): print(name, 'PLAYLIST') for tid, x in zip(tids, feature): if x &lt; value: track_name = sp.track(tid)['name'] xsongs.append(track_name) print("{} : {} - feature: {}".format(name, track_name, x)) </code></pre> <p>and call it like</p> <pre><code>filterBelowThreshold('myname', energy, tids, xsongs, value=0.650) </code></pre> <p>or</p> <pre><code>filterBelowThreshold('myname', energy, tids, xsongs, 0.650) </code></pre>
0
2016-08-12T16:11:13Z
[ "python", "args", "kwargs" ]
Unable to return a generator instance. why?
38,921,815
<p>I am using python 3.5. When I tried to return a generator function instance and i am getting a StopIteration error. Why?</p> <p>here is my code:</p> <pre><code>&gt;&gt;&gt; def gen(start, end): ... '''generator function similar to range function''' ... while start &lt;= end: ... yield start ... start += 1 ... &gt;&gt;&gt; def check(ingen, flag=None): ... if flag: ... for n in ingen: ... yield n*2 ... else: ... return ingen ... &gt;&gt;&gt; # Trigger else clause in check function &gt;&gt;&gt; a = check(gen(1,3)) &gt;&gt;&gt; next(a) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; StopIteration: &lt;generator object gen at 0x7f37dc46e828&gt; </code></pre> <p>It looks like the generator is somehow exhausted before the else clause is returns the generator.</p> <p>It works fine with this function:</p> <pre><code>&gt;&gt;&gt; def check_v2(ingen): ... return ingen ... &gt;&gt;&gt; b = check_v2(gen(1, 3)) &gt;&gt;&gt; next(b) 1 &gt;&gt;&gt; next(b) 2 &gt;&gt;&gt; next(b) 3 </code></pre>
0
2016-08-12T15:43:05Z
38,921,937
<p>When a generator hits its <code>return</code> statement (explicit or not) it raises <code>StopIteration</code>. So when you <code>return ingen</code> you end the iteration.</p> <p><code>check_v2</code> is not a generator, since it does not contain the <code>yield</code> statement, that's why it works.</p>
2
2016-08-12T15:49:31Z
[ "python", "python-3.x", "if-statement", "generator" ]
Unable to return a generator instance. why?
38,921,815
<p>I am using python 3.5. When I tried to return a generator function instance and i am getting a StopIteration error. Why?</p> <p>here is my code:</p> <pre><code>&gt;&gt;&gt; def gen(start, end): ... '''generator function similar to range function''' ... while start &lt;= end: ... yield start ... start += 1 ... &gt;&gt;&gt; def check(ingen, flag=None): ... if flag: ... for n in ingen: ... yield n*2 ... else: ... return ingen ... &gt;&gt;&gt; # Trigger else clause in check function &gt;&gt;&gt; a = check(gen(1,3)) &gt;&gt;&gt; next(a) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; StopIteration: &lt;generator object gen at 0x7f37dc46e828&gt; </code></pre> <p>It looks like the generator is somehow exhausted before the else clause is returns the generator.</p> <p>It works fine with this function:</p> <pre><code>&gt;&gt;&gt; def check_v2(ingen): ... return ingen ... &gt;&gt;&gt; b = check_v2(gen(1, 3)) &gt;&gt;&gt; next(b) 1 &gt;&gt;&gt; next(b) 2 &gt;&gt;&gt; next(b) 3 </code></pre>
0
2016-08-12T15:43:05Z
38,921,939
<p>In Python, if <code>yield</code> is present in a function, then Python treats it as a generator. In a generator, any return will raise <code>StopIteration</code> with the returned value. This is a new feature in Python 3.3: see <a href="https://www.python.org/dev/peps/pep-0380/" rel="nofollow">PEP 380</a> and <a href="http://stackoverflow.com/a/16780113/2097780">here</a>. <code>check_v2</code> works because it doesn't contain a <code>yield</code> and is therefore a normal function.</p> <p>There are two ways to accomplish what you want:</p> <ul> <li>Change the <code>return</code> to a <code>yield</code> in <code>check</code>.</li> <li><p>Have the caller trap <code>StopIteration</code>, as shown below</p> <pre><code>try: next(a) except StopIteration as ex: print(ex.value) </code></pre></li> </ul>
3
2016-08-12T15:49:33Z
[ "python", "python-3.x", "if-statement", "generator" ]
Unable to return a generator instance. why?
38,921,815
<p>I am using python 3.5. When I tried to return a generator function instance and i am getting a StopIteration error. Why?</p> <p>here is my code:</p> <pre><code>&gt;&gt;&gt; def gen(start, end): ... '''generator function similar to range function''' ... while start &lt;= end: ... yield start ... start += 1 ... &gt;&gt;&gt; def check(ingen, flag=None): ... if flag: ... for n in ingen: ... yield n*2 ... else: ... return ingen ... &gt;&gt;&gt; # Trigger else clause in check function &gt;&gt;&gt; a = check(gen(1,3)) &gt;&gt;&gt; next(a) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; StopIteration: &lt;generator object gen at 0x7f37dc46e828&gt; </code></pre> <p>It looks like the generator is somehow exhausted before the else clause is returns the generator.</p> <p>It works fine with this function:</p> <pre><code>&gt;&gt;&gt; def check_v2(ingen): ... return ingen ... &gt;&gt;&gt; b = check_v2(gen(1, 3)) &gt;&gt;&gt; next(b) 1 &gt;&gt;&gt; next(b) 2 &gt;&gt;&gt; next(b) 3 </code></pre>
0
2016-08-12T15:43:05Z
38,921,984
<p>As others have said, if you return from a generator, it means the the generator has stopped yielding items, which raises a <code>StopIteration</code> whatever you return. </p> <p>This means that <code>check</code> actually returns an empty iterator.</p> <p>If you want to return the results of another generator, you can use <code>yield from</code> :</p> <pre><code>def check(ingen, flag=None): if flag: for n in ingen: yield n*2 else: yield from ingen </code></pre>
2
2016-08-12T15:52:17Z
[ "python", "python-3.x", "if-statement", "generator" ]
Unable to return a generator instance. why?
38,921,815
<p>I am using python 3.5. When I tried to return a generator function instance and i am getting a StopIteration error. Why?</p> <p>here is my code:</p> <pre><code>&gt;&gt;&gt; def gen(start, end): ... '''generator function similar to range function''' ... while start &lt;= end: ... yield start ... start += 1 ... &gt;&gt;&gt; def check(ingen, flag=None): ... if flag: ... for n in ingen: ... yield n*2 ... else: ... return ingen ... &gt;&gt;&gt; # Trigger else clause in check function &gt;&gt;&gt; a = check(gen(1,3)) &gt;&gt;&gt; next(a) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; StopIteration: &lt;generator object gen at 0x7f37dc46e828&gt; </code></pre> <p>It looks like the generator is somehow exhausted before the else clause is returns the generator.</p> <p>It works fine with this function:</p> <pre><code>&gt;&gt;&gt; def check_v2(ingen): ... return ingen ... &gt;&gt;&gt; b = check_v2(gen(1, 3)) &gt;&gt;&gt; next(b) 1 &gt;&gt;&gt; next(b) 2 &gt;&gt;&gt; next(b) 3 </code></pre>
0
2016-08-12T15:43:05Z
38,922,065
<p>See <a href="https://www.python.org/dev/peps/pep-0380/#formal-semantics" rel="nofollow">PEP 380</a>:</p> <blockquote> <p>In a generator, the statement</p> <pre><code>return value </code></pre> <p>is semantically equivalent to</p> <pre><code>raise StopIteration(value) </code></pre> <p>except that, as currently, the exception cannot be caught by <code>except</code> clauses within the returning generator.</p> </blockquote> <p>This is a new feature in Python 3.3.</p>
0
2016-08-12T15:56:04Z
[ "python", "python-3.x", "if-statement", "generator" ]
python binary executable fails to execute on OS x: importerror no module named PyQt4
38,921,869
<p>I created a binary executable on Mac for a python script using <code>pyinstaller</code> and the following command:</p> <blockquote> <p>pyinstaller --onefile --windowed chatEdit.py</p> </blockquote> <p>also tried this:</p> <blockquote> <p>pyinstaller --windowed chatEdit.py</p> </blockquote> <p>In each case the executable fails to run.</p> <p>A terminal screen opens up and displays the following message:</p> <pre><code>Failed to execute script chatEdit Traceback (most recent call last): File "chatEdit.py", line 3, in &lt;module&gt; ImportError: No module named PyQt4 logout </code></pre> <p>Please help!</p> <p>My .spec file:</p> <pre><code># -*- mode: python -*- block_cipher = None a = Analysis(['chatEdit.py'], pathex=['/Users/Shubhi/Documents/vin'], binaries=None, datas=None, hiddenimports=[], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, exclude_binaries=True, name='chatEdit', debug=False, strip=False, upx=True, console=False ) coll = COLLECT(exe, a.binaries, a.zipfiles, a.datas, strip=False, upx=True, name='chatEdit') app = BUNDLE(coll, name='chatEdit.app', icon=None, bundle_identifier=None) </code></pre>
0
2016-08-12T15:45:41Z
38,922,611
<p>It seems you missed PyQt in .spec file</p> <p>I hope my app.spec will help you. Pay attention to <strong>'PyQt4.QtCore', 'PyQt4.QtGui'</strong> in <em>hiddenimports</em> </p> <pre><code># -*- mode: python -*- a = Analysis(['app.py'], pathex=['d:\\4com\\consultant\\consultant'], hiddenimports=['grab.transport.curl', 'pycurl', 'weblib.user_agent', 'grab.response','openpyxl', 'openpyxl.styles', 'cookielib','_LWPCookieJar','_MozillaCookieJar','PyQt4.QtCore', 'PyQt4.QtGui', 'gui'], hookspath=None, runtime_hooks=None) pyz = PYZ(a.pure) exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, name='documents.exe', debug=False, strip=None, upx=True, console=True ) </code></pre>
0
2016-08-12T16:26:19Z
[ "python", "osx", "pyqt4", "pyinstaller" ]
Setting Max Results in API v4 (python)
38,921,882
<p>In v3 of the API I'm seeing that there was a max-results parameter that could be passed to get more than 1000 records. I haven't been able to figure out how to pass that parameter in v4 of the API using python. </p> <p>My code looks something like below. I've commented out my best guess at max_result.</p> <pre><code>def get_report(analytics): # Use the Analytics Service Object to query the Analytics Reporting API V4. return analytics.reports().batchGet( body={ 'reportRequests': [ { 'viewId': VIEW_ID, #'max_results': 100000, 'dateRanges': [{'startDate': '2016-04-01', 'endDate': '2016-08-09'}], 'dimensions': [{'name':'ga:date'}, {'name': 'ga:channelGrouping'}], 'metrics': [{'expression': 'ga:sessions'}, {'expression': 'ga:newUsers'}, {'expression': 'ga:goal15Completions'}, {'expression': 'ga:goal9Completions'}, {'expression': 'ga:goal10Completions'}] }] } ).execute() </code></pre>
0
2016-08-12T15:46:34Z
38,922,925
<p>The correct name of the parameter you are looking for is: <a href="https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet#ReportRequest.FIELDS.page_size" rel="nofollow"><code>pageSize</code></a>. The <a href="https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet" rel="nofollow">Reference Docs</a> provide the full API specifications.</p> <pre><code>def get_report(analytics): # Use the Analytics Service Object to query the Analytics Reporting API V4. return analytics.reports().batchGet( body={ 'reportRequests': [ { 'viewId': VIEW_ID, 'pageSize': 10000, 'dateRanges': [{'startDate': '2016-04-01', 'endDate': '2016-08-09'}], 'dimensions': [{'name':'ga:date'}, {'name': 'ga:channelGrouping'}], 'metrics': [{'expression': 'ga:sessions'}, {'expression': 'ga:newUsers'}, {'expression': 'ga:goal15Completions'}, {'expression': 'ga:goal9Completions'}, {'expression': 'ga:goal10Completions'}] }] } ).execute() </code></pre> <p>Note: the API returns a maximum of <strong>10,000</strong> rows per request, no matter how many you ask for. As you attempted <code>max_results</code> this tells me you are trying to migrate from the Core Reporting API V3, check out the <a href="https://developers.google.com/analytics/devguides/reporting/core/v4/migration#pagination" rel="nofollow">Migration Guide - Pagination documentation</a> to understand how to request the next 10,000 rows.</p> <p>Stack Overflow extra tip. Include your error responses in your question, as it will likely improve your chances of someone being able to help.</p>
1
2016-08-12T16:47:28Z
[ "python", "google-analytics", "google-analytics-api", "google-analytics-v4" ]
Only show certain number of emails in imaplib
38,921,933
<p>The code I have below is working great but I am testing this on a test email and it only have around 5 emails. On my actual email account I have atleast 4k emails on my inbox.</p> <p>Is there a way for me to show for a certain number of emails. For example, only show the first 20 most recent emails? And then after that say when a button is clicked it will show the next 20 emails...</p> <pre><code>import sys import imaplib import getpass import email import email.header import datetime email_address = "email@company.net" password = "123456" M = imaplib.IMAP4('mail.company.net') rows = [] try: M.login(email_address, password) print "LOGIN SUCCESS!" except imaplib.IMAP4.error: print "LOGIN FAILED!!" rv, data = M.select("INBOX") rv, data = M.search(None, "ALL") for num in data[0].split(): rv, data = M.fetch(num, '(RFC822)') msg = email.message_from_string(data[0][1]) subj = msg['Subject'] to = msg['To'] frm = msg['From'] body = msg.get_payload() print subj, " ", to, " ", frm, " ", body M.close() M.logout() </code></pre> <p>I'm sorry but I'm really having a hard time trying to figure this out. Most recent I learned is that I can get the total number of emails</p> <pre><code>num_msgs = int(data[0]) print 'You have a total of %d messages' % num_msgs </code></pre> <p>And if <code>id_list[-1]</code> can get the latest email id, can i do something like <code>id_list[-1] + 19</code> or something so it can get the 20 most recent email?</p> <p>I would really appreciate any help on how to achieve my desired output. Thank You.</p> <p>So far I have</p> <pre><code>ids = data[0] id_list = ids.split() latest_email_id = id_list[-1] #gets most recent email for i in latest_email_id: if i &gt; 21: rv, data = M.fetch(num, '(RFC822)') msgrecent = email.message_from_string(data[0][1]) subjs = msgrecent['Subject'] print "only print 20 most recent email" print subjs else: print "none" </code></pre> <p>How can i modify this to get the output i need? Thank you</p> <hr> <p>Latest update:</p> <p>I updated the code to the following:</p> <pre><code>ids = data[0] id_list = ids.split() for num in id_list[0:10]: rv, data = M.fetch(num, '(RFC822)') msg = email.message_from_string(data[0][1]) subj = msg['Subject'] to = msg['To'] frm = msg['From'] body = msg.get_payload() print subj </code></pre> <p>This outputs in ascending order</p> <pre><code>first second third fourth . . . . tenth </code></pre> <p>so i figured i add <code>-1</code> so that it will sort in descending order</p> <pre><code>ids = data[0] id_list = ids.split() for num in id_list[0:10:-1]: rv, data = M.fetch(num, '(RFC822)') msg = email.message_from_string(data[0][1]) subj = msg['Subject'] to = msg['To'] frm = msg['From'] body = msg.get_payload() print subj </code></pre> <p>but when i did that, i didn't get any output.</p> <p>Any idea on how i can fix this? Thank You</p>
0
2016-08-12T15:49:16Z
39,083,374
<p>I just realized that I already have the output that I want, which is to only output a specified number of emails.</p> <pre><code>ids = data[0] id_list = ids.split() for num in id_list[0:10]: rv, data = M.fetch(num, '(RFC822)') msg = email.message_from_string(data[0][1]) subj = msg['Subject'] to = msg['To'] frm = msg['From'] body = msg.get_payload() print subj </code></pre> <p>Wherein <code>id_list[0:10]:</code> will output the first 10 email in my inbox. If i need to output 20, it can be modified to <code>id_list[0:20]</code> I have another issue but I will ask that on a different post. But so far, I have half of what I need so I will post my solution here.</p>
0
2016-08-22T15:26:11Z
[ "python", "email", "count", "imaplib" ]
Passing data mid-function back to function Python
38,921,940
<p>The below script works fine, until I added in "def test", I am trying to get rid of all global variables my programming in general and as I'm not a great programmer, I hope there is a way to do this. </p> <p>I want to pass "foo" from function "test" back to Function "work" but this does not work as its not a global variable. Any ideas?</p> <pre><code>bar = "bar" barnone = "barnone" def function_A(): data = 5 data1 = 15 if host == 1: work(data, data1) else: function_B() def function_B(): data = 3 data1 = 13 work(data, data1) test(data) print foo def work(data,data1): print data print data1 test(data) print foo def test(data): if data == 3:foo = bar elif data == 5:foo = barnone if __name__ == '__main__': host = 11 function_A() </code></pre> <p><strong>EDIT:</strong></p> <p>Thank you, this works... I appreciate all the feedback as I am a novice, keep in mind this was just a test script I put together to understand passing parameters to different functions. Before this I was using globals and I'm trying to get rid of them.</p> <p>Thank you, any advice is helpful. </p> <pre><code>bar = "bar" barnone = "barnone" def function_A(): data = 5 data1 = 15 if host == 1: work(data, data1) else: function_B() def function_B(): data = 3 data1 = 13 work(data, data1) test(data) def work(data,data1): print data print data1 test(data) print test(data) def test(data): if data == 3:foo = bar elif data == 5:foo = barnone return foo if __name__ == '__main__': host = 11 function_A() </code></pre>
1
2016-08-12T15:49:33Z
38,922,005
<p>Add the following to the end of your <code>test()</code> function:</p> <pre><code>`return foo` </code></pre> <p>then you can print the variable in <code>work()</code> like this</p> <pre><code>print test(data) </code></pre>
4
2016-08-12T15:53:08Z
[ "python" ]
Passing data mid-function back to function Python
38,921,940
<p>The below script works fine, until I added in "def test", I am trying to get rid of all global variables my programming in general and as I'm not a great programmer, I hope there is a way to do this. </p> <p>I want to pass "foo" from function "test" back to Function "work" but this does not work as its not a global variable. Any ideas?</p> <pre><code>bar = "bar" barnone = "barnone" def function_A(): data = 5 data1 = 15 if host == 1: work(data, data1) else: function_B() def function_B(): data = 3 data1 = 13 work(data, data1) test(data) print foo def work(data,data1): print data print data1 test(data) print foo def test(data): if data == 3:foo = bar elif data == 5:foo = barnone if __name__ == '__main__': host = 11 function_A() </code></pre> <p><strong>EDIT:</strong></p> <p>Thank you, this works... I appreciate all the feedback as I am a novice, keep in mind this was just a test script I put together to understand passing parameters to different functions. Before this I was using globals and I'm trying to get rid of them.</p> <p>Thank you, any advice is helpful. </p> <pre><code>bar = "bar" barnone = "barnone" def function_A(): data = 5 data1 = 15 if host == 1: work(data, data1) else: function_B() def function_B(): data = 3 data1 = 13 work(data, data1) test(data) def work(data,data1): print data print data1 test(data) print test(data) def test(data): if data == 3:foo = bar elif data == 5:foo = barnone return foo if __name__ == '__main__': host = 11 function_A() </code></pre>
1
2016-08-12T15:49:33Z
38,922,040
<p>Your <code>test</code> function should be written like</p> <pre><code>def test(data): if data == 3: return 'bar' elif data == 5: return 'barnone' </code></pre> <p>In a function that calls <code>test</code>, assign the result</p> <pre><code>something = test(data) </code></pre> <p>Note that your code has some unrelated problems, e.g., what should happen if <code>data</code> is neither 3 nor 5?</p>
1
2016-08-12T15:55:06Z
[ "python" ]
Passing data mid-function back to function Python
38,921,940
<p>The below script works fine, until I added in "def test", I am trying to get rid of all global variables my programming in general and as I'm not a great programmer, I hope there is a way to do this. </p> <p>I want to pass "foo" from function "test" back to Function "work" but this does not work as its not a global variable. Any ideas?</p> <pre><code>bar = "bar" barnone = "barnone" def function_A(): data = 5 data1 = 15 if host == 1: work(data, data1) else: function_B() def function_B(): data = 3 data1 = 13 work(data, data1) test(data) print foo def work(data,data1): print data print data1 test(data) print foo def test(data): if data == 3:foo = bar elif data == 5:foo = barnone if __name__ == '__main__': host = 11 function_A() </code></pre> <p><strong>EDIT:</strong></p> <p>Thank you, this works... I appreciate all the feedback as I am a novice, keep in mind this was just a test script I put together to understand passing parameters to different functions. Before this I was using globals and I'm trying to get rid of them.</p> <p>Thank you, any advice is helpful. </p> <pre><code>bar = "bar" barnone = "barnone" def function_A(): data = 5 data1 = 15 if host == 1: work(data, data1) else: function_B() def function_B(): data = 3 data1 = 13 work(data, data1) test(data) def work(data,data1): print data print data1 test(data) print test(data) def test(data): if data == 3:foo = bar elif data == 5:foo = barnone return foo if __name__ == '__main__': host = 11 function_A() </code></pre>
1
2016-08-12T15:49:33Z
38,922,050
<p><code>foo</code> is only defined in the "scope" of the function <code>test()</code>, since that is where you created it. The function <code>work()</code> has no knowledge of the variable <code>foo</code>, as it is <em>undefined</em> outside of the function <code>test()</code>. So, <code>test()</code> has to <em>return</em> the variable <code>foo</code> to the place that <em>called</em> <code>test()</code>, which is the line <code>test(data)</code> in <code>work()</code>. </p> <p>So, yes, add <code>return foo</code> to the end of <code>test()</code>. </p> <p><strong>Edit:</strong></p> <p>When you say <code>test(data)</code>, that is basically saying <code>sum([1,2,3])</code>. You've called a function, but you're not doing anything with the result, you're not <em>assigning</em> it. You have to say <code>new_variable = test(data)</code>. This means, from the perspective of <code>work()</code>: "call the function <code>test()</code> and have it do its thing. I don't care what's going on inside of <code>test()</code>, but I am expecting to it to spit something out at me when it is done. I will assign that something to a variable in <em>my</em> scope so I can use it later".</p> <p>It is just like saying <code>x = sum([1,2,3])</code>. <code>sum</code> is a <em>function</em> that does something inside of it, you don't really care what, you just know that it should return a sensible value that you will assign to <code>x</code> to use later. </p> <p><strong>Edit2:</strong> Also, as it stands, <code>test()</code> is going to return a <code>boolean</code> for <code>foo</code>, since you use the <code>==</code> operator rather than the assignment operator <code>=</code>. </p>
2
2016-08-12T15:55:42Z
[ "python" ]
Virtualenv Includes Global Packages / How do I clear my PYTHONPATH?
38,921,967
<p>I'm running a Virtualenv like this:</p> <pre><code>$ virtualenv --no-site-packages venv New python executable in .../venv/bin/python Installing setuptools, pip, wheel...done. $ source venv/bin/activate </code></pre> <p>But when I <code>pip freeze -l</code>, I don't get anything. So I double-checked my <a href="http://stackoverflow.com/questions/1382925/virtualenv-no-site-packages-and-pip-still-finding-global-packages">PYTHONPATH</a>: </p> <pre><code>$ python import sys for i in sys.path: ... print i </code></pre> <p>Which gave this output:</p> <pre><code>/home/... /usr/local/lib/python2.7/site-packages /usr/local/lib/python2.7/dist-packages /usr/lib/python2.7/site-packages /usr/lib/python2.7/dist-packages /home/.../venv/lib/python2.7 /home/.../venv/lib/python2.7/plat-x86_64-linux-gnu /home/.../venv/lib/python2.7/lib-tk /home/.../venv/lib/python2.7/lib-old /home/.../venv/lib/python2.7/lib-dynload /usr/lib/python2.7 /usr/lib/python2.7/plat-x86_64-linux-gnu /usr/lib/python2.7/lib-tk /home/.../venv/local/lib/python2.7/dist-packages /home/.../venv/lib/python2.7/site-packages /home/.../venv/local/lib/python2.7/dist-packages </code></pre> <p>In the directories, I used <code>...</code> to denote the path to my project/working directory.</p> <p>It seems to me that what I really need to do is ensure that in my virtual environment, the <code>/usr/</code> paths don't show up. But how can I do that? How do I clear these extraneous paths?</p>
0
2016-08-12T15:51:20Z
38,922,666
<p>I don't know if this is a good fix, but I found a few statements in my .bashrc:</p> <pre><code>export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python2.7/site-packages export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python2.7/dist-packages export PYTHONPATH=$PYTHONPATH:/usr/lib/python2.7/site-packages export PYTHONPATH=$PYTHONPATH:/usr/lib/python2.7/dist-packages </code></pre> <p>Which I commented out, and then those paths no longer showed up in <code>sys.path</code>. Now my virtualenv is working as desired, though I'd be curious to understand why this actually fixes the problem.</p>
0
2016-08-12T16:29:28Z
[ "python", "linux", "path", "virtualenv", "pythonpath" ]
How can I implement a dictionary with a NumPy array?
38,921,975
<p>I need to write a huge amount number-number pairs into a NumPy array. Since a lot of these pairs have a second value of 0, I thought of making something akin to a dictionary. The problem is that I've read through the NumPy documentation on structured arrays and it seems like dictionaries built like those on the page can only use strings as keys.</p> <p>Other than that, I need insertion and searching to have log(N) complexity. I thought of making my own Red-black tree structure using a regular NumPy array as storage, but I'm fairly certain there's an easier way to go about this.</p> <p>Language is Python 2.7.12.</p>
1
2016-08-12T15:51:53Z
38,924,069
<p>So you have an <code>(N,2)</code> array, and many values in <code>x[:,1]</code> are 0.</p> <p>What do you mean by <code>insertion</code>? Adding a value to the array to make it <code>(N+1,2)</code>? Or just changing <code>x[i,:]</code> to something new?</p> <p>And what about the search? <code>numpy</code> array are great for finding the ith values, <code>x[i,:]</code>, but not that good for finding the values that match <code>z</code>. <a href="http://stackoverflow.com/questions/38910258/python-numpy-filter-two-dimentional-array-by-condition">python numpy filter two dimentional array by condition</a></p> <p><code>scipy.sparse</code> implements various forms of sparse matrix, which are useful if less than a tenth of the possible values are non-zero. One format is <code>dok</code>, a dictionary of keys. It is actually a <code>dict</code> subclass, and the keys are a 2d index tuple <code>(i,j)</code>. Other formats store their values as arrays,e.g. row, cols and data.</p> <p><code>structured arrays</code> are meant for cases with a modest number of named fields, and each field can hold a different type of data. But I don't think it helps to turn a <code>(N,2)</code> array into a <code>(N,)</code> array with 2 fields.</p> <p>================</p> <p>Your comments suggest that you aren't familiar with how <code>numpy</code> arrays are stored or accessed.</p> <p>An array consists of a flat 1d <code>data buffer</code> (just a <code>c</code> array of bytes), and attributes like <code>shape</code>, <code>strides</code>, <code>itemsize</code> and <code>dtype</code>.</p> <p>Let's say it is <code>np.arange(100)</code>.</p> <pre><code>In [1324]: np.arange(100).__array_interface__ Out[1324]: {'data': (163329128, False), 'descr': [('', '&lt;i4')], 'shape': (100,), 'strides': (4,) 'typestr': '&lt;i4', 'version': 3} </code></pre> <p>So if I ask for <code>x[50]</code>, it calculates the strides, 4 bypes/element, * 50 elements = 200 bytes, and asks, in <code>c</code> code for the 4 bytes at <code>163329128+200</code>, and it returns them as an integer (object of <code>np.int32</code> type actually).</p> <p>For a structured array the type descr and bytes per element will be larger, but access will be the same. For a 2d array it will take the shape and strides tuples into account to find the appropriate index. </p> <p>Strides for a (N,2) integer array is (8,4). So access to the <code>x[10,1]</code> element is with a <code>10*8 + 1*4 = 84</code> offset. And access to <code>x[:,1]</code> is with <code>i*8 for i in range...</code> offsets.</p> <p>But in all cases it relies on the values being arranged in a rectangular predicable pattern. There's nothing fancy about the <code>numpy</code> data structures. They are relatively fast simply because many operations are coded in compiled code.</p> <p>Sorting, accessing items by value, and rearranging elements are possible with arrays, but are not a strong point. More often than not these actions will produce a new array, with values copied from old to new in some new pattern.</p> <p>There are just a few builtin <code>numpy</code> array subclasses, mainly <code>np.matrix</code> and <code>np.masked_array</code>, and they don't extend the access methods. Subclassing isn't as easy as with regular Python classes, since it <code>numpy</code> has some much of its own compiled code. A subclass has to have a <code>__new__</code> method rather than regular <code>__init__</code>.</p> <p>There are Python modules that maintain sorted lists, <code>bisect</code> and <code>heapq</code>. But I don't see how they will help you with the large out-of-ram memory issue.</p>
0
2016-08-12T18:07:45Z
[ "python", "arrays", "numpy", "dictionary", "red-black-tree" ]
How can I implement a dictionary with a NumPy array?
38,921,975
<p>I need to write a huge amount number-number pairs into a NumPy array. Since a lot of these pairs have a second value of 0, I thought of making something akin to a dictionary. The problem is that I've read through the NumPy documentation on structured arrays and it seems like dictionaries built like those on the page can only use strings as keys.</p> <p>Other than that, I need insertion and searching to have log(N) complexity. I thought of making my own Red-black tree structure using a regular NumPy array as storage, but I'm fairly certain there's an easier way to go about this.</p> <p>Language is Python 2.7.12.</p>
1
2016-08-12T15:51:53Z
38,924,162
<p>The most basic form of a dictionary is a structure called a <code>HashMap</code>. Implementing a hashmap relies on turning your key into a value that can be quickly looked up. A pathological example would be using <code>int</code>s as keys: The value for key <code>1</code> would go in <code>array[1]</code>, the value for key <code>2</code> would go in <code>array[2]</code>, the Hash Function is simply the identity function. You can easily implement that using a numpy array.</p> <p>If you want to use other types, it's just a case of writing a good hash function to turn those keys into <em>unique</em> indexes into your array. For example, if you know you've got a <code>(int, int)</code> tuple, and the first value will never be more than 100, you can do <code>100*key[1] + key[0]</code>.</p> <p>The implementation of your hash function is what will make or break your dictionary replacement.</p>
0
2016-08-12T18:14:53Z
[ "python", "arrays", "numpy", "dictionary", "red-black-tree" ]
I have a list of lists. I would like to make a new list of lists, but each new list will have the same indices of the old list
38,921,985
<p>Imagine my old list is:</p> <pre><code>old = [[card, towel, bus], [mouse, eraser, laptop], [pad, pen, bar]] </code></pre> <p>goal:</p> <pre><code>new = [[card, mouse, pad], [towel, eraser, pen], [bus, laptop, bar]] </code></pre> <p>Things I've tried:</p> <pre><code>new = dict(zip(old[i] for i in range(len(old)))) new = [old[i][0] for i in old] #trying just to get a list of first indices, and then go from there </code></pre> <p>I feel like this is a trivial problem, but I'm having trouble. Thanks in advance for pointing me in the right direction!</p> <p>Also: Imagine I have another list:</p> <pre><code>list_names = ['list1', 'list2', 'list3'] </code></pre> <p>I would like to set the elements of this list to each one of the new lists:</p> <pre><code>list1 = [card, mouse, pad] </code></pre> <p>and so on.</p> <p>Any ideas?</p>
1
2016-08-12T15:52:20Z
38,922,042
<p>For your first question, this is the basic usage of <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow"><code>zip</code></a>:</p> <pre><code>&gt;&gt;&gt; old = [['card', 'towel', 'bus'], ['mouse', 'eraser', 'laptop'], ['pad', 'pen', 'bar']] &gt;&gt;&gt; zip(*old) [('card', 'mouse', 'pad'), ('towel', 'eraser', 'pen'), ('bus', 'laptop', 'bar')] </code></pre> <p>I can't understand your second question. </p>
3
2016-08-12T15:55:10Z
[ "python", "list" ]
I have a list of lists. I would like to make a new list of lists, but each new list will have the same indices of the old list
38,921,985
<p>Imagine my old list is:</p> <pre><code>old = [[card, towel, bus], [mouse, eraser, laptop], [pad, pen, bar]] </code></pre> <p>goal:</p> <pre><code>new = [[card, mouse, pad], [towel, eraser, pen], [bus, laptop, bar]] </code></pre> <p>Things I've tried:</p> <pre><code>new = dict(zip(old[i] for i in range(len(old)))) new = [old[i][0] for i in old] #trying just to get a list of first indices, and then go from there </code></pre> <p>I feel like this is a trivial problem, but I'm having trouble. Thanks in advance for pointing me in the right direction!</p> <p>Also: Imagine I have another list:</p> <pre><code>list_names = ['list1', 'list2', 'list3'] </code></pre> <p>I would like to set the elements of this list to each one of the new lists:</p> <pre><code>list1 = [card, mouse, pad] </code></pre> <p>and so on.</p> <p>Any ideas?</p>
1
2016-08-12T15:52:20Z
38,922,257
<p><strong>Method 1:</strong> If you want reach your first goal in one line and want to use list comprehensions try:</p> <pre><code>old = [[1,2,3],[4,5,6],[7,8,9]] new = [[sublist[i] for sublist in old ] for i in (0,1,2)] </code></pre> <p>leads to <code>new = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]</code>.</p> <p><strong>Method 2:</strong> However you can also use the <code>zip</code>-function like this:</p> <pre><code>new = [list for list in zip(*old)] </code></pre> <p>will lead to <code>new = [(1, 4, 7), (2, 5, 8), (3, 6, 9)]</code>. Note that this is a list of tuples as opposed to the first example.</p>
0
2016-08-12T16:05:55Z
[ "python", "list" ]
I have a list of lists. I would like to make a new list of lists, but each new list will have the same indices of the old list
38,921,985
<p>Imagine my old list is:</p> <pre><code>old = [[card, towel, bus], [mouse, eraser, laptop], [pad, pen, bar]] </code></pre> <p>goal:</p> <pre><code>new = [[card, mouse, pad], [towel, eraser, pen], [bus, laptop, bar]] </code></pre> <p>Things I've tried:</p> <pre><code>new = dict(zip(old[i] for i in range(len(old)))) new = [old[i][0] for i in old] #trying just to get a list of first indices, and then go from there </code></pre> <p>I feel like this is a trivial problem, but I'm having trouble. Thanks in advance for pointing me in the right direction!</p> <p>Also: Imagine I have another list:</p> <pre><code>list_names = ['list1', 'list2', 'list3'] </code></pre> <p>I would like to set the elements of this list to each one of the new lists:</p> <pre><code>list1 = [card, mouse, pad] </code></pre> <p>and so on.</p> <p>Any ideas?</p>
1
2016-08-12T15:52:20Z
38,923,097
<p>Thanks so much for the input everyone! zip(*old) worked like a charm, though I'm not entirely sure how...</p> <p>For the second problem, I used this: (I know this is not a good solution, but it worked)</p> <pre><code>for name in range(input_num): exec(list_names[name] + ' = arranged_list[name]') </code></pre>
0
2016-08-12T17:00:30Z
[ "python", "list" ]
how to pass askopenfilename() return value as a parameter to the builtin python function open
38,922,095
<p>I am a new user to Python.</p> <p><code>filename = askopenfilenames()</code> This prompts the user to select a file I want to use <code>file_selection = open(filename, "r")</code> with the file selected above.</p> <p>The issue I am running into is that when you use the <code>askopenfilenames()</code> (I think) the string is surrounded by <code>()</code> therefore the open command doesn't work. Can someone please help me with this?</p> <p>EDIT: When I try and replace: filename.replace(",","") I get error message: AttributeError: 'tuple' object has no attribute 'replace'</p>
1
2016-08-12T15:57:29Z
38,924,797
<p><code>askopenfilenames()</code> allows the user to select multiple files; thus it returns a tuple of all the filenames selected.</p> <p>If you want to allow the user to select multiple files, just iterate over the returned tuple:</p> <pre><code>filenames = askopenfilenames() #filenames is a tuple of strings! for filename in filenames: with open(filename, "r") as f: #Do stuff with open file f. </code></pre> <p>If you want to allow the user to select only one file, look into <code>askopenfilename()</code>.</p> <pre><code>filename = askopenfilename() #filename is a string! with open(filename, "r") as f: #do stuff with open file f </code></pre> <p>Also, there are methods <code>askopenfile()</code> and <code>askopenfiles()</code> that do the same thing as <code>askopenfilename()</code> and <code>askopenfilenames()</code> respectively, except instead of returning filenames, they return files open for reading.</p> <pre><code>f = askopenfile() #f is an open file. #do stuff with f f.close() </code></pre> <p>and</p> <pre><code>open_files = askopenfiles() #open_files is a tuple of open files. for f in open_files: #do stuff with f f.close() </code></pre>
2
2016-08-12T18:58:42Z
[ "python", "user-interface", "tkinter" ]
In Python, is it preferred to declare local variables to extract data from an object, or to just deal with the object directly?
38,922,101
<p>For example, say you have an object Dog with 3 different string attributes (bark, sleep, eat). Also assume you have a function where you will be accessing these variables several times repeatedly (dog.bark, dog.bark, dog.sleep). Is it preferred to declare these at the beginning of the function (bark = dog.bark) or just use the dog object directly?</p> <p>Example:</p> <pre><code>def print_dog_actions(dog): print dog.bark if dog.bark == 'loud': print 'dog bark is loud! {bark}'.format(bark=dog.bark) print dog.sleep print dog.eat print dog.sleep + dog.eat </code></pre> <p>Versus:</p> <pre><code>def print_dog_actions(dog): bark = dog.bark sleep = dog.sleep eat = dog.eat print sleep print sleep + eat print bark + eat </code></pre> <p>May be a silly question, but I am having trouble finding what certain standards/conventions are in Python and this is just one of many questions I have.</p>
0
2016-08-12T15:57:48Z
38,922,174
<p>The first one is the one that you will see more often, but it depends on what your overall goal is. But more often than not, you are going to want to do it this way. </p> <p>I can't really think of a reason to do it the second way, other than sometimes it might make it more readable for you, if the variables get hairy.</p> <p>Both ways are completely valid though. First way is more standard.</p>
0
2016-08-12T16:01:37Z
[ "python", "coding-style" ]
In Python, is it preferred to declare local variables to extract data from an object, or to just deal with the object directly?
38,922,101
<p>For example, say you have an object Dog with 3 different string attributes (bark, sleep, eat). Also assume you have a function where you will be accessing these variables several times repeatedly (dog.bark, dog.bark, dog.sleep). Is it preferred to declare these at the beginning of the function (bark = dog.bark) or just use the dog object directly?</p> <p>Example:</p> <pre><code>def print_dog_actions(dog): print dog.bark if dog.bark == 'loud': print 'dog bark is loud! {bark}'.format(bark=dog.bark) print dog.sleep print dog.eat print dog.sleep + dog.eat </code></pre> <p>Versus:</p> <pre><code>def print_dog_actions(dog): bark = dog.bark sleep = dog.sleep eat = dog.eat print sleep print sleep + eat print bark + eat </code></pre> <p>May be a silly question, but I am having trouble finding what certain standards/conventions are in Python and this is just one of many questions I have.</p>
0
2016-08-12T15:57:48Z
38,922,396
<p>If you're not going to use an attribute of the object, say <code>dog.bark</code>, more than once, then there is no point declaring an additional variable in order to do just one thing - except for readibility.</p> <p>This question can lead onto memory management topics; take a look at the "heap" and the "stack" and how Python deals with storing variables.</p>
0
2016-08-12T16:14:02Z
[ "python", "coding-style" ]
Infinite sequencing number generator not work in python?
38,922,122
<p>I am trying to implement a nature number generator which can generator infinite numbers, my code:</p> <pre><code>def nature(): s = 0 while True: yield s s += 1 </code></pre> <p>when I use <code>next(nature())</code>, I get a sequence of 0s, why this? and how to fix it?</p> <pre><code>&gt;&gt;&gt; next(nature()) 0 &gt;&gt;&gt; next(nature()) 0 &gt;&gt;&gt; next(nature()) 0 &gt;&gt;&gt; next(nature()) 0 </code></pre>
1
2016-08-12T15:58:34Z
38,922,153
<p>You create a new generator every time you recall it like so; so it starts from the initial value. What you want is:</p> <pre><code>&gt;&gt;&gt; n = nature() &gt;&gt;&gt; next(n) 0 &gt;&gt;&gt; next(n) 1 &gt;&gt;&gt; next(n) 2 &gt;&gt;&gt; next(n) 3 </code></pre>
1
2016-08-12T16:00:44Z
[ "python", "generator" ]
Infinite sequencing number generator not work in python?
38,922,122
<p>I am trying to implement a nature number generator which can generator infinite numbers, my code:</p> <pre><code>def nature(): s = 0 while True: yield s s += 1 </code></pre> <p>when I use <code>next(nature())</code>, I get a sequence of 0s, why this? and how to fix it?</p> <pre><code>&gt;&gt;&gt; next(nature()) 0 &gt;&gt;&gt; next(nature()) 0 &gt;&gt;&gt; next(nature()) 0 &gt;&gt;&gt; next(nature()) 0 </code></pre>
1
2016-08-12T15:58:34Z
38,922,154
<p>You are creating a new generator each time, try creating it once and passing it to each next call</p>
1
2016-08-12T16:00:45Z
[ "python", "generator" ]
Infinite sequencing number generator not work in python?
38,922,122
<p>I am trying to implement a nature number generator which can generator infinite numbers, my code:</p> <pre><code>def nature(): s = 0 while True: yield s s += 1 </code></pre> <p>when I use <code>next(nature())</code>, I get a sequence of 0s, why this? and how to fix it?</p> <pre><code>&gt;&gt;&gt; next(nature()) 0 &gt;&gt;&gt; next(nature()) 0 &gt;&gt;&gt; next(nature()) 0 &gt;&gt;&gt; next(nature()) 0 </code></pre>
1
2016-08-12T15:58:34Z
38,922,171
<p>Every time you call <code>nature()</code> you create a new generator. Instead do this:</p> <pre><code>n = nature() next(n) next(n) next(n) </code></pre>
6
2016-08-12T16:01:27Z
[ "python", "generator" ]
Infinite sequencing number generator not work in python?
38,922,122
<p>I am trying to implement a nature number generator which can generator infinite numbers, my code:</p> <pre><code>def nature(): s = 0 while True: yield s s += 1 </code></pre> <p>when I use <code>next(nature())</code>, I get a sequence of 0s, why this? and how to fix it?</p> <pre><code>&gt;&gt;&gt; next(nature()) 0 &gt;&gt;&gt; next(nature()) 0 &gt;&gt;&gt; next(nature()) 0 &gt;&gt;&gt; next(nature()) 0 </code></pre>
1
2016-08-12T15:58:34Z
38,922,226
<p>Don't instance your generator over and over, for example, instance one and use it several times like this:</p> <pre><code>def nature(): s = 0 while True: yield s s += 1 n = nature() for i in range(10): print next(n) print "Doing another stuff... Resuming the counting" for i in range(10): print next(n) </code></pre>
0
2016-08-12T16:04:46Z
[ "python", "generator" ]
Specify download location in Django
38,922,176
<p>Is there a way to specify a download location in Django?</p> <p>My page allows the user to</p> <ul> <li>Click a button run to a EXE in the background</li> <li>Then gives the user a new page where the download option is available</li> <li>User clicks the download, and it downloads the latest file it generated</li> </ul> <p>I read in a HTML <a href="http://stackoverflow.com/questions/33612566/how-to-specify-download-location-in-html-using-javascript">post</a> that you cannot force the browser to download a specific location. I am wondering if Django has an option that lets you do this.</p> <pre><code>def DownloadZip(request, zipname, prodVersID): print(zipname) zip_path = "C:/fbw/firmware/main/sys/" + zipname zip_file = open(zip_path, 'rb') response = HttpResponse(zip_file, content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=%s' %zipname response['Content-Length'] = os.path.getsize(zip_path) zip_file.close() return response </code></pre>
1
2016-08-12T16:01:43Z
40,116,344
<p>After further research, I concluded that the reference <a href="http://stackoverflow.com/a/33612619/5104387">post</a> also reflects on Django. Django does not offer such feature, it is a security feature of the web browser that does not allow you to specify download location.</p> <p>Credit to <a href="http://Darren%20Willows" rel="nofollow">Darren</a></p> <blockquote> <p>Whether the browser asks the user or not is down to the preferences in the browser.</p> <p>You can't bypass those preference, otherwise it would violate user's security.</p> </blockquote>
0
2016-10-18T19:20:11Z
[ "python", "django-1.9" ]
Remove string starting from specific characters in python
38,922,225
<p>I have the following data in a file:</p> <pre><code>Neighbor V TblVer InQ OutQ Up/Down State/PfxRcd 10.230.2.91 4 136041 0 0 35w6d 1178 CHN_RAY_901_1AC_CASR903R004# exit Neighbor V TblVer InQ OutQ Up/Down State/PfxRcd 10.229.5.239 4 890585 0 0 7w5d 1177 10.229.6.239 4 890585 0 0 7w5d 1173 CHN_MAR_905_1AC_CASR903R066# exit 10.229.30.110 </code></pre> <p>I have to remove the lines starting from CHN and have the output like:</p> <pre><code>Neighbor V TblVer InQ OutQ Up/Down State/PfxRcd 10.230.2.91 4 136041 0 0 35w6d 1178 Neighbor V TblVer InQ OutQ Up/Down State/PfxRcd 10.229.5.239 4 890585 0 0 7w5d 1177 10.229.6.239 4 890585 0 0 7w5d 1173 10.229.30.110 </code></pre> <p>I have tried: </p> <pre><code>b = ' '.join(word for word in content.split(' ') if not word.startswith('CHN')) </code></pre> <p>where content is my data I want to remove CHN from, but it's not working. </p> <p>Could you suggest ways to achieve this. Can this be done without using regular expressions? Thanks in advance.</p>
1
2016-08-12T16:04:42Z
38,922,308
<p>It may be easier to work with individual lines instead of whole file contents:</p> <pre><code>with open("file") as f: lines = [line for line in f if not line.startswith("CHN")] filtered = "".join(lines) </code></pre>
2
2016-08-12T16:08:56Z
[ "python", "string" ]
Remove string starting from specific characters in python
38,922,225
<p>I have the following data in a file:</p> <pre><code>Neighbor V TblVer InQ OutQ Up/Down State/PfxRcd 10.230.2.91 4 136041 0 0 35w6d 1178 CHN_RAY_901_1AC_CASR903R004# exit Neighbor V TblVer InQ OutQ Up/Down State/PfxRcd 10.229.5.239 4 890585 0 0 7w5d 1177 10.229.6.239 4 890585 0 0 7w5d 1173 CHN_MAR_905_1AC_CASR903R066# exit 10.229.30.110 </code></pre> <p>I have to remove the lines starting from CHN and have the output like:</p> <pre><code>Neighbor V TblVer InQ OutQ Up/Down State/PfxRcd 10.230.2.91 4 136041 0 0 35w6d 1178 Neighbor V TblVer InQ OutQ Up/Down State/PfxRcd 10.229.5.239 4 890585 0 0 7w5d 1177 10.229.6.239 4 890585 0 0 7w5d 1173 10.229.30.110 </code></pre> <p>I have tried: </p> <pre><code>b = ' '.join(word for word in content.split(' ') if not word.startswith('CHN')) </code></pre> <p>where content is my data I want to remove CHN from, but it's not working. </p> <p>Could you suggest ways to achieve this. Can this be done without using regular expressions? Thanks in advance.</p>
1
2016-08-12T16:04:42Z
38,922,323
<pre><code>for line in file: if not line[0:3] == "CHN": write_line else: remove_line </code></pre>
1
2016-08-12T16:09:38Z
[ "python", "string" ]
Remove string starting from specific characters in python
38,922,225
<p>I have the following data in a file:</p> <pre><code>Neighbor V TblVer InQ OutQ Up/Down State/PfxRcd 10.230.2.91 4 136041 0 0 35w6d 1178 CHN_RAY_901_1AC_CASR903R004# exit Neighbor V TblVer InQ OutQ Up/Down State/PfxRcd 10.229.5.239 4 890585 0 0 7w5d 1177 10.229.6.239 4 890585 0 0 7w5d 1173 CHN_MAR_905_1AC_CASR903R066# exit 10.229.30.110 </code></pre> <p>I have to remove the lines starting from CHN and have the output like:</p> <pre><code>Neighbor V TblVer InQ OutQ Up/Down State/PfxRcd 10.230.2.91 4 136041 0 0 35w6d 1178 Neighbor V TblVer InQ OutQ Up/Down State/PfxRcd 10.229.5.239 4 890585 0 0 7w5d 1177 10.229.6.239 4 890585 0 0 7w5d 1173 10.229.30.110 </code></pre> <p>I have tried: </p> <pre><code>b = ' '.join(word for word in content.split(' ') if not word.startswith('CHN')) </code></pre> <p>where content is my data I want to remove CHN from, but it's not working. </p> <p>Could you suggest ways to achieve this. Can this be done without using regular expressions? Thanks in advance.</p>
1
2016-08-12T16:04:42Z
38,922,327
<pre><code>file = """ Neighbor V TblVer InQ OutQ Up/Down State/PfxRcd 10.230.2.91 4 136041 0 0 35w6d 1178 CHN_RAY_901_1AC_CASR903R004# exit Neighbor V TblVer InQ OutQ Up/Down State/PfxRcd 10.229.5.239 4 890585 0 0 7w5d 1177 10.229.6.239 4 890585 0 0 7w5d 1173 CHN_MAR_905_1AC_CASR903R066# exit 10.229.30.110 """ output = [line for line in file.splitlines() if not line.startswith('CHN')] print "\n".join(output) </code></pre>
2
2016-08-12T16:09:48Z
[ "python", "string" ]
How to delete an object from a list inside a list?
38,922,291
<p>Let's say there are three lists, the third being a list containing the first two:</p> <pre><code>Friendly_List = list() Enemy_List = list() Battle_Space = list([Friendly_List, Enemy_List]) </code></pre> <p>And a goblin class:</p> <pre><code>class Goblin(object): def __init__(self): self.Name = "Goblin" self.HP = random.randint(15,20) self.Damage = random.randint(5,10) </code></pre> <p>I create an instance of the Goblin class:</p> <pre><code>x = Goblin() </code></pre> <p>Then put it into Friendly_List:</p> <pre><code>Friendly_List.append(x) </code></pre> <p>Now let's say the goblin dies heroically and must be removed from the battlefield. If I do Friendly_List.remove(x), the goblin is removed without issue. </p> <p>If I do Battle_Space.remove(x), it says that x is not in the list - even though x is in one of the lists that is part of the Battle_Space list.</p> <p>I guess what I'm trying to ask really is: what is the proper way to achieve the desired behavior of Battle_Space.remove(x)? To remove an instance that is a layer deep?</p>
2
2016-08-12T16:08:15Z
38,922,355
<p>If you know the index of the nested list, you can index from the parent list and call <code>remove</code>:</p> <pre><code>Battle_Space[0].remove(x) </code></pre> <p>To remove <code>x</code> from anywhere it appears, you can use a list comprehension:</p> <pre><code>Battle_Space = [[j for j in innerlist if j!=x] for innerlist in Battle_Space] </code></pre>
1
2016-08-12T16:11:44Z
[ "python", "python-3.x", "oop", "object" ]
How to delete an object from a list inside a list?
38,922,291
<p>Let's say there are three lists, the third being a list containing the first two:</p> <pre><code>Friendly_List = list() Enemy_List = list() Battle_Space = list([Friendly_List, Enemy_List]) </code></pre> <p>And a goblin class:</p> <pre><code>class Goblin(object): def __init__(self): self.Name = "Goblin" self.HP = random.randint(15,20) self.Damage = random.randint(5,10) </code></pre> <p>I create an instance of the Goblin class:</p> <pre><code>x = Goblin() </code></pre> <p>Then put it into Friendly_List:</p> <pre><code>Friendly_List.append(x) </code></pre> <p>Now let's say the goblin dies heroically and must be removed from the battlefield. If I do Friendly_List.remove(x), the goblin is removed without issue. </p> <p>If I do Battle_Space.remove(x), it says that x is not in the list - even though x is in one of the lists that is part of the Battle_Space list.</p> <p>I guess what I'm trying to ask really is: what is the proper way to achieve the desired behavior of Battle_Space.remove(x)? To remove an instance that is a layer deep?</p>
2
2016-08-12T16:08:15Z
38,922,381
<p>The simple but maybe not-so-clean way is <code>Battle_Space[0].remove(x)</code>. You would have to ensure that the first list is the friendly list.</p> <p>My suggestion for readability would be to consider putting <code>friendly_list</code> and <code>enemy_list</code> in a <code>BattleSpace</code> object so you can refer to them by name. You can also create a method in that object to remove a target from any child list:</p> <pre><code>class BattleSpace(object): def __init__(self): self.friendly_list = [] self.enemy_list = [] def remove(self, target): if target in self.friendly_list: self.friendly_list.remove(target) if target in self.enemy_list: self.enemy_list.remove(target) battle_space = BattleSpace() battle_space.friendly_list.append(x) battle_space.remove(x) # can also do battle_space.friendly_list.remove(x) </code></pre> <p><strong>Edit:</strong> Just read the OP's comment that the desire is to remove anywhere in the list. Modified code.</p>
4
2016-08-12T16:13:27Z
[ "python", "python-3.x", "oop", "object" ]
How to delete an object from a list inside a list?
38,922,291
<p>Let's say there are three lists, the third being a list containing the first two:</p> <pre><code>Friendly_List = list() Enemy_List = list() Battle_Space = list([Friendly_List, Enemy_List]) </code></pre> <p>And a goblin class:</p> <pre><code>class Goblin(object): def __init__(self): self.Name = "Goblin" self.HP = random.randint(15,20) self.Damage = random.randint(5,10) </code></pre> <p>I create an instance of the Goblin class:</p> <pre><code>x = Goblin() </code></pre> <p>Then put it into Friendly_List:</p> <pre><code>Friendly_List.append(x) </code></pre> <p>Now let's say the goblin dies heroically and must be removed from the battlefield. If I do Friendly_List.remove(x), the goblin is removed without issue. </p> <p>If I do Battle_Space.remove(x), it says that x is not in the list - even though x is in one of the lists that is part of the Battle_Space list.</p> <p>I guess what I'm trying to ask really is: what is the proper way to achieve the desired behavior of Battle_Space.remove(x)? To remove an instance that is a layer deep?</p>
2
2016-08-12T16:08:15Z
38,922,481
<p>Just filter those damm goblins out, for instance:</p> <pre><code>import random class Goblin(object): def __init__(self): self.Name = "Goblin" self.HP = random.randint(15, 20) self.Damage = random.randint(5, 10) x = Goblin() Friendly_List = list() Enemy_List = list() Battle_Space = list([Friendly_List, Enemy_List]) Friendly_List.append(x) Friendly_List.append(x) Friendly_List.append(x) Enemy_List.append(x) print Battle_Space for index, army in enumerate(Battle_Space): Battle_Space[index] = filter(lambda entity: entity != x, army) print Battle_Space </code></pre> <p>The code will remove that damm duplicated goblin from all armies of your intergalactic battle.</p> <p>I'm not a big fan of galactic battles, can goblins replicate themselves magically? :')</p> <p><strong>EDIT</strong></p> <p>If you wanted a more OOP approach, you'd transform the above code in something more like this:</p> <pre><code>import random class Goblin(object): def __init__(self): self.Name = "Goblin" self.HP = random.randint(15, 20) self.Damage = random.randint(5, 10) class Army(object): def __init__(self): self.entities = [] def remove(self, target): if target in self.entities: self.entities.remove(target) def filter(self, target): self.entities = filter( lambda entity: self.entities != entity, self.entities) class BattleSpace(object): def __init__(self): self.armies = [] def remove(self, target): for index, army in enumerate(self.armies): army.remove(target) def filter(self, target): for index, army in enumerate(self.armies): army.filter(target) x = Goblin() battle_space = BattleSpace() Friendly_List = Army() Enemy_List = Army() battle_space.armies = [Friendly_List, Enemy_List] Enemy_List.entities.append(x) print "Initial setup" print Enemy_List.entities print Friendly_List.entities print "After removing" battle_space.remove(x) print Enemy_List.entities print Friendly_List.entities </code></pre> <p>This way you could extend easily your BattleSpace to zillion of intergalactic armies from different planets</p>
1
2016-08-12T16:18:49Z
[ "python", "python-3.x", "oop", "object" ]
Ubuntu 16.04 default python environment in my user profile is Anaconda Python2, unable to run guake "anaconda2/bin/python2: No module named guake"
38,922,328
<p>I recently installed Ubuntu 16.04 and for ease of developing Machine Learning and other AI programs using Python2, I installed the Anaconda Python2 full distribution.</p> <p>I always use 'guake' terminal emulator which I find best for productivity. So I installed Guake in my Ubuntu and when I try to run it, I get the following error:</p> <pre><code>/home/enlighter/anaconda2/bin/python2: No module named guake </code></pre> <p>I deleted all <code>*.pyc</code> files in <code>/usr/lib/python2.7/dist-packages/guake/</code> folder, but that didn't help.</p> <p>I am guessing this is an python environment issue. The <code>/usr/bin/guake</code> script contains only these rwo lines:</p> <pre><code>PYTHON="/usr/bin/env python2" exec $PYTHON -m guake.main "$@" </code></pre> <p>Can anybody please tell me how to resolve this?</p>
0
2016-08-12T16:09:50Z
38,958,052
<p>you don't execute the right Python execute: <code>/home/enlighter/anaconda2/bin/python2</code> while you installed in <code>/usr/lib/python2.7/dist-packages/guake/</code>.</p> <p>Use <code>/usr/bin/python2</code> as default interpreter or install in <code>/home/enlighter/anaconda2/lib/python2.7/dist-packages/guake/</code>.</p> <p>To install within anaconda python environment, clone the guake github repository and then build and install guake.</p>
0
2016-08-15T15:23:49Z
[ "python", "ubuntu", "anaconda", "environment" ]
python print 3 first elements of list in reverse mode
38,922,333
<p>suppose i have a list like this:</p> <pre><code>my_list = [0,1,2,3,4,5] # range(5) </code></pre> <p>i want to print this:</p> <pre><code>[2,1,0] </code></pre> <p>my python script is:</p> <pre><code>print(my_list[2:-1:-1]) </code></pre> <p>but it <strong>prints an empty list!</strong></p> <p>is this a bug in python(2 and 3!)?</p> <p>i wont use any trick like:</p> <pre><code>num_of_elems_i_want = 3 print(my_list[::-1][len(my_list) - num_of_elems_i_want:]) </code></pre> <p>or third party modules..</p>
2
2016-08-12T16:10:26Z
38,922,363
<p>You could slice the <code>list</code> as shown:</p> <pre><code>print(my_list[2::-1]) # L[start:end:step] </code></pre> <p><strong>EDIT :</strong></p> <p>The result that you had obtained is not a <em>Bug</em>. </p> <p>Remember that traversal of the <code>list</code> elements takes place from left to right and there are no elements till <code>end=-4</code>[<em>viz</em> <em>elements</em>: 5 → 0 → 1 → 2] from <code>start=2</code>. So, an <em>empty</em> <code>list</code> is returned as a result.</p> <p>For the same reason, you could also do <code>print(my_list[2:-7:-1])</code> </p>
5
2016-08-12T16:12:13Z
[ "python", "list" ]
python print 3 first elements of list in reverse mode
38,922,333
<p>suppose i have a list like this:</p> <pre><code>my_list = [0,1,2,3,4,5] # range(5) </code></pre> <p>i want to print this:</p> <pre><code>[2,1,0] </code></pre> <p>my python script is:</p> <pre><code>print(my_list[2:-1:-1]) </code></pre> <p>but it <strong>prints an empty list!</strong></p> <p>is this a bug in python(2 and 3!)?</p> <p>i wont use any trick like:</p> <pre><code>num_of_elems_i_want = 3 print(my_list[::-1][len(my_list) - num_of_elems_i_want:]) </code></pre> <p>or third party modules..</p>
2
2016-08-12T16:10:26Z
38,922,364
<p>You can also invert your list permanently for other uses:</p> <pre><code>my_list.reverse() print(my_list[-4:-1]) </code></pre>
1
2016-08-12T16:12:15Z
[ "python", "list" ]
New to Python (and programming) can't see where I'm going wrong
38,922,387
<p>I'm learning a bit of Phython in my spare time. Trying to make a phonebook, found one on this site; <a href="http://stackoverflow.com/questions/28910134/python-assignment-for-a-phonebook">Python assignment for a phonebook</a>. Have used that as a template but left out the print_menu function. That's the only difference that I can see but when I add a number it gets stuck in that part. Just asking to enter name and number, not escaping the if loop. If anyone can tell me why I get stuck like this I would appreciate it.</p> <pre><code>phoneBook = {} def main(): action = input("What would you like to do? \n 1. Add \n 2. Delete \n 3. Print \n 4. Quit \n") while action != 4: if action == '1': name = input("Enter name: ") num = input("Enter number: ") phoneBook[name] = num elif action == '2': name = input("Delete who?") if name in phoneBook: del phoneBook[name] else: print("Name not found") elif action == '3': print("Telephone numbers: ") for x in phoneBook.keys(): print("Name: ", x, "\tNumber: ", phoneBook[x]) elif action == '4': print("Application closed.") main() </code></pre>
3
2016-08-12T16:13:38Z
38,922,419
<p><code>input()</code> returns a string, not an integer.</p> <p>So</p> <pre><code>while action != 4: </code></pre> <p>should become:</p> <pre><code>while action != '4': </code></pre>
6
2016-08-12T16:15:14Z
[ "python" ]
New to Python (and programming) can't see where I'm going wrong
38,922,387
<p>I'm learning a bit of Phython in my spare time. Trying to make a phonebook, found one on this site; <a href="http://stackoverflow.com/questions/28910134/python-assignment-for-a-phonebook">Python assignment for a phonebook</a>. Have used that as a template but left out the print_menu function. That's the only difference that I can see but when I add a number it gets stuck in that part. Just asking to enter name and number, not escaping the if loop. If anyone can tell me why I get stuck like this I would appreciate it.</p> <pre><code>phoneBook = {} def main(): action = input("What would you like to do? \n 1. Add \n 2. Delete \n 3. Print \n 4. Quit \n") while action != 4: if action == '1': name = input("Enter name: ") num = input("Enter number: ") phoneBook[name] = num elif action == '2': name = input("Delete who?") if name in phoneBook: del phoneBook[name] else: print("Name not found") elif action == '3': print("Telephone numbers: ") for x in phoneBook.keys(): print("Name: ", x, "\tNumber: ", phoneBook[x]) elif action == '4': print("Application closed.") main() </code></pre>
3
2016-08-12T16:13:38Z
38,922,490
<p>You have two problems here. As Padraic and Leistungsabfall mention, <code>input</code> returns a string, but you <em>also</em> are only getting the input one time. If you want to continue getting input, you're going to need to put that inside your loop:</p> <pre><code>action = None while action != '4': action = input('What action would you like? ') # the rest of your code here </code></pre>
5
2016-08-12T16:19:24Z
[ "python" ]
Error using python and sqlite3
38,922,391
<p>I have a directory (/home/usuario/Desktop/Example) with one database (MyBBDD.db) and the file (script.py) that run the command "UPDATE". If in the terminal I'm in the directory "Example", script.py work fine but if Im not in the directory "Example" and I execute script.py like this: "<code>python /home/usuario/Desktop/Example/script.py</code>" doesnt work fine, the error is: "no such table: name_table". Somebody know what is the problem? Thanks in advance.</p> <p>Best regards.</p> <hr> <p>code as of comments <em>script.py</em></p> <pre><code>import urllib import sqlite3 conn = sqlite3.connect('MyBBDD.db') c = conn.cursor() c.execute ("UPDATE...") conn.commit() c.close() conn.close() </code></pre>
1
2016-08-12T16:13:46Z
38,922,476
<p>When you create a connection object with <code>sqlite3</code> in script.py, use the absolute file path, i.e. </p> <pre><code>con = sqlite3.connect('/home/usuario/Desktop/Example/MyBBDD.db') </code></pre>
3
2016-08-12T16:18:19Z
[ "python", "sqlite3" ]
Import lxml module cause PyImport_ImportModule failed
38,922,394
<p>I wrote python test code which uses the module <code>lxml</code>.</p> <p>I want to call <code>foo</code> in c++. </p> <p>It will fail in step <code>PyImport_ImportModule</code> if I add the <code>from lxml import html</code> but works well when I remove it</p> <p>Test.py</p> <pre><code>import os import sys import requests from lxml import html #it will cause failed def foo(): host = "http://www.baidu.com" s = requests.session() res = s.get(host) return res </code></pre> <p>c++ code: </p> <pre><code>Py_Initialize(); PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('./')"); PyObject* pModule = PyImport_ImportModule("Test"); //failed if (pModule == NULL || PyErr_Occurred()) { PyErr_Print(); } PyObject* pDict = PyModule_GetDict(pModule); PyObject *pFunHi = PyDict_GetItemString(pDict, "foo"); PyObject *ret = PyObject_CallFunction(pFunHi,NULL); Py_DECREF(pFunHi); Py_Finalize(); </code></pre> <p>The error msg is :</p> <pre><code>Traceback (most recent call last): File "C:\Users\Administrator\Desktop\test\Test\Debug\Test.py", line 4, in &lt;module&gt; from lxml import html File "E:\python27\lib\site-packages\lxml\html\__init__.py", line 54, in &lt;module&gt; from .. import etree ImportError: DLL load failed: Unable to find the specified module。 </code></pre> <p>how to use lxml module correct?</p>
0
2016-08-12T16:13:54Z
38,926,401
<p>Your code will crash at</p> <pre><code>PyObject* pModule = PyImport_ImportModule("Test"); PyObject* pDict = PyModule_GetDict(pModule); //will crash </code></pre> <p>if <code>pModule == NULL</code>. You should check the return values, for example</p> <pre><code>if (pModule == NULL || PyErr_Occurred()) { PyErr_Print(); } </code></pre> <p>The question states that the filename for the module is test.py but then in the code the module name is Test i.e. <code>PyImport_ImportModule("Test")</code>. The case should match.</p> <p>To verify that lxml is correctly installed:</p> <pre><code>import lxml # does not fail if lxml has been partially installed import lxml.etree # fails if C extension part of lxml has not been installed </code></pre> <p>If the latter import fails, lxml may not have been installed correctly.</p>
0
2016-08-12T21:00:55Z
[ "python", "html", "c++", "import", "lxml" ]
Import lxml module cause PyImport_ImportModule failed
38,922,394
<p>I wrote python test code which uses the module <code>lxml</code>.</p> <p>I want to call <code>foo</code> in c++. </p> <p>It will fail in step <code>PyImport_ImportModule</code> if I add the <code>from lxml import html</code> but works well when I remove it</p> <p>Test.py</p> <pre><code>import os import sys import requests from lxml import html #it will cause failed def foo(): host = "http://www.baidu.com" s = requests.session() res = s.get(host) return res </code></pre> <p>c++ code: </p> <pre><code>Py_Initialize(); PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('./')"); PyObject* pModule = PyImport_ImportModule("Test"); //failed if (pModule == NULL || PyErr_Occurred()) { PyErr_Print(); } PyObject* pDict = PyModule_GetDict(pModule); PyObject *pFunHi = PyDict_GetItemString(pDict, "foo"); PyObject *ret = PyObject_CallFunction(pFunHi,NULL); Py_DECREF(pFunHi); Py_Finalize(); </code></pre> <p>The error msg is :</p> <pre><code>Traceback (most recent call last): File "C:\Users\Administrator\Desktop\test\Test\Debug\Test.py", line 4, in &lt;module&gt; from lxml import html File "E:\python27\lib\site-packages\lxml\html\__init__.py", line 54, in &lt;module&gt; from .. import etree ImportError: DLL load failed: Unable to find the specified module。 </code></pre> <p>how to use lxml module correct?</p>
0
2016-08-12T16:13:54Z
38,928,226
<p>I resolved it , it's the lxml installer's fault.</p> <p>I download version 3.6.0 from <a href="https://pypi.python.org/pypi/lxml/3.6.0" rel="nofollow">https://pypi.python.org/pypi/lxml/3.6.0</a> (lxml-3.6.0.win32-py2.7.exe) ,because it had no version 3.6.1 installer. and it caused the question i mentioned.</p> <p>so I download a new whl installer from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml</a> (lxml-3.6.1-cp27-cp27m-win32.whl) and update the old one. All is ok.</p>
0
2016-08-13T01:03:12Z
[ "python", "html", "c++", "import", "lxml" ]
Python: Writing multiple json object to a file; Later to be open and load via json.load
38,922,442
<p>I have constructed a json object from a data stream where each user will have a json object. </p> <pre><code>{ "entities": { "description": { "urls": [] } }, "utc_offset": -10800, "id" "name": "Tom", "hit_count": 7931, "private": false, "active_last_month": false, "location": "", "contacted": false, "lang": "en", } </code></pre> <p>Objective: I want to construct a json file where each json object become a line in a file with the indentation. And when it comes to reading back the JSON file it can be read using with open:</p> <p>for example: Following File</p> <pre><code>[ { "entities": { "description": { "urls": [] } }, "utc_offset": -10800, "id" "name": "Tom", "hit_count": 7931, "private": false, "active_last_month": false, "location": "", "contacted": false, "lang": "en", } , { "entities": { "description": { "urls": [] } }, "utc_offset": -10500, "id" "name": "Mary", "hit_count": 554, "private": false, "active_last_month": false, "location": "", "contacted": false, "lang": "en", } ] </code></pre> <p>Above file can easily read by: </p> <pre><code>with open(pathToFile) as json_file: json_data = json.load(json_file) for key in json_data: print key["id"] </code></pre> <p>But at the moment here is how I am writing constructing the json file: </p> <pre><code>with open(root + filename + '.txt', 'w+') as json_file: # convert from Python dict-like structure to JSON format jsoned_data = json.dumps(data) json_file.write(jsoned_data) json_file.write('\n') </code></pre> <p>This gives me</p> <pre><code>{ indented json data } { indented json data } </code></pre> <p>PS: notice brackets <code>[]</code> are not there along with <code>,</code></p> <p>When you try to read this same code structure as </p> <pre><code>with open(pathToFile) as json_file: json_data = json.load(json_file) for key in json_data: print key["id"] </code></pre> <p>you end up getting errors: <code>ValueError: Extra data: line 101 column 1 - line 1889 column 1</code></p>
1
2016-08-12T16:16:16Z
38,922,908
<p>I think you should add the new JSON data to a list containing the previous data:</p> <pre><code>newData = {"entities": { "description": { "urls": [] } }, "utc_offset": -10500, "id": 3, "name": "Mary", "hit_count": 554, "private": False, "active_last_month": False, "location": "", "contacted": False, "lang": "en" } def readFile(): with open('testJson', 'r') as json_file: json_data = json.load(json_file) for key in json_data: print key["id"] def writeFile(): with open('testJson', 'r') as json_file: oldData = json.load(json_file) with open('testJson', 'w+') as json_file: # convert from Python dict-like structure to JSON format data = oldData.append(newData) jsoned_data = json.dumps(oldData, indent=True) json_file.write(jsoned_data) if __name__ == '__main__': readFile() writeFile() readFile() </code></pre>
-1
2016-08-12T16:46:07Z
[ "python", "json" ]
Making pairs of a string and an element in a list
38,922,589
<p>I have a single string that I would like to make pair with each element in a list. </p> <pre><code>str = "era" list = ["we", "st"] </code></pre> <p>With the code:</p> <pre><code>zip(str, list) </code></pre> <p>I obtain</p> <pre><code> [('e', 'we'), ('r', 'st')] </code></pre> <p>What I would like to achieve is a list of tuples of the pairs:</p> <pre><code> [('era', 'we'), ('era', 'st')] </code></pre> <p>Is there a simple way to get around with the split of the string? Thank you!!</p>
0
2016-08-12T16:24:52Z
38,922,633
<p>How about a list comprehension?</p> <pre><code>str = 'era' list = ['we', 'st'] packed = [(str,str2) for str2 in list] </code></pre>
7
2016-08-12T16:27:24Z
[ "python", "string", "zip" ]
Making pairs of a string and an element in a list
38,922,589
<p>I have a single string that I would like to make pair with each element in a list. </p> <pre><code>str = "era" list = ["we", "st"] </code></pre> <p>With the code:</p> <pre><code>zip(str, list) </code></pre> <p>I obtain</p> <pre><code> [('e', 'we'), ('r', 'st')] </code></pre> <p>What I would like to achieve is a list of tuples of the pairs:</p> <pre><code> [('era', 'we'), ('era', 'st')] </code></pre> <p>Is there a simple way to get around with the split of the string? Thank you!!</p>
0
2016-08-12T16:24:52Z
38,922,671
<pre><code>str = 'era' list = ['we', 'st'] res = [(str,list[0]), (str, list[1])] </code></pre>
-1
2016-08-12T16:30:11Z
[ "python", "string", "zip" ]
Making pairs of a string and an element in a list
38,922,589
<p>I have a single string that I would like to make pair with each element in a list. </p> <pre><code>str = "era" list = ["we", "st"] </code></pre> <p>With the code:</p> <pre><code>zip(str, list) </code></pre> <p>I obtain</p> <pre><code> [('e', 'we'), ('r', 'st')] </code></pre> <p>What I would like to achieve is a list of tuples of the pairs:</p> <pre><code> [('era', 'we'), ('era', 'st')] </code></pre> <p>Is there a simple way to get around with the split of the string? Thank you!!</p>
0
2016-08-12T16:24:52Z
38,922,746
<p>Use <code>itertools.product</code>:</p> <pre><code>import itertools ss = "era" lst = ["we", "st"] print list(itertools.product([ss], lst)) </code></pre> <p>Avoid using keyword as variables, such as <strong>list</strong>.</p>
2
2016-08-12T16:36:05Z
[ "python", "string", "zip" ]
Making pairs of a string and an element in a list
38,922,589
<p>I have a single string that I would like to make pair with each element in a list. </p> <pre><code>str = "era" list = ["we", "st"] </code></pre> <p>With the code:</p> <pre><code>zip(str, list) </code></pre> <p>I obtain</p> <pre><code> [('e', 'we'), ('r', 'st')] </code></pre> <p>What I would like to achieve is a list of tuples of the pairs:</p> <pre><code> [('era', 'we'), ('era', 'st')] </code></pre> <p>Is there a simple way to get around with the split of the string? Thank you!!</p>
0
2016-08-12T16:24:52Z
38,922,883
<p>Thought I'd offer an alternative to @<em>jphollowed</em>'s simple and concise answer.</p> <pre><code>s = "era" l = ["we", "st"] print([tuple(i.split(',')) for i in map(lambda x: x+','+s, l)]) </code></pre>
1
2016-08-12T16:44:52Z
[ "python", "string", "zip" ]
click-and-run docker image (or VM) with web interface?
38,922,616
<p>I am in a position to deliver an application to a user, however it requires quite a few programs and components installed, which represents some overhead and explanation that I'd prefer to avoid. One method that I thought of that would be quite nice would be to simply supply a VM or Docker image. In this idea, the deliverable would be an image, and the user ideally would just double-click on the docker image and pop up a web interface showing a convenient front-end. (In this case I am imagining it would run Jupyter to allow interaction with a Python script I am developing.)</p> <p>However, I'm still a bit confused by how Docker works. Instead of being able to send a double-clickable image, it seems you have to run <code>docker pull ..</code> and it downloads ... a bunch of stuff.. and installs them.. somewhere. Then you have to run a command, <code>docker run ...</code></p> <p>Is there a simpler, more file-oriented interface to Docker or some similar VM solution? Why does it have to manage things in such a weird way?</p> <p>(I prefer Docker because it now has very good Windows and Mac support, and its images can be quite a bit smaller than a VM image, from what I understand.)</p> <p>Edit: By "weird way", what I mean is, what would be more clear to me is that I simply download some kind of file <code>my-docker-thing.image</code> and run it with like, <code>docker run my-docker-thing.image</code>. Instead a single <code>docker pull</code> seems to be filling up my harddrive quickly in <code>/var/lib/docker</code> with a bunch of files named something <code>..*ImageBlob*</code> and I have no idea what it is actually doing. I assume these files contain "pieces" that can be composed into an image, but is there a way to represent this in a single file?</p>
0
2016-08-12T16:26:44Z
38,922,789
<p>In order for a Docker container to run you need a Docker-engine. If your customer wants to run the container on her host, then she needs docker installed.</p> <p>Quick example: One of you component is Nginx:</p> <pre><code>docker pull ngnix:latest docker run --name webInterface --host web -it ngnix:latest </code></pre> <p>With the above you create a container and can be installed on your customers machine when ready.</p> <p>If you want to use docker for a specific environment, then I suggest to mount a volume and do the work on docker (compile or other stuff) then put the result in the mounted volume that way you benefit from not polluting your system and guaranteeing the same result everytime</p>
1
2016-08-12T16:37:54Z
[ "python", "docker", "virtual-machine", "software-distribution" ]
click-and-run docker image (or VM) with web interface?
38,922,616
<p>I am in a position to deliver an application to a user, however it requires quite a few programs and components installed, which represents some overhead and explanation that I'd prefer to avoid. One method that I thought of that would be quite nice would be to simply supply a VM or Docker image. In this idea, the deliverable would be an image, and the user ideally would just double-click on the docker image and pop up a web interface showing a convenient front-end. (In this case I am imagining it would run Jupyter to allow interaction with a Python script I am developing.)</p> <p>However, I'm still a bit confused by how Docker works. Instead of being able to send a double-clickable image, it seems you have to run <code>docker pull ..</code> and it downloads ... a bunch of stuff.. and installs them.. somewhere. Then you have to run a command, <code>docker run ...</code></p> <p>Is there a simpler, more file-oriented interface to Docker or some similar VM solution? Why does it have to manage things in such a weird way?</p> <p>(I prefer Docker because it now has very good Windows and Mac support, and its images can be quite a bit smaller than a VM image, from what I understand.)</p> <p>Edit: By "weird way", what I mean is, what would be more clear to me is that I simply download some kind of file <code>my-docker-thing.image</code> and run it with like, <code>docker run my-docker-thing.image</code>. Instead a single <code>docker pull</code> seems to be filling up my harddrive quickly in <code>/var/lib/docker</code> with a bunch of files named something <code>..*ImageBlob*</code> and I have no idea what it is actually doing. I assume these files contain "pieces" that can be composed into an image, but is there a way to represent this in a single file?</p>
0
2016-08-12T16:26:44Z
38,923,154
<p>Yes, you can import and export Docker images as simple TAR files. To export an existing image into a tar file, use the following <code>docker save</code> command:</p> <pre><code>docker save your_image &gt; your_image.tar </code></pre> <p>The TAR file created this way is self-contained and you can distribute it any way you like. On another host (with an already installed Docker engine), you can then import the TAR file using the <code>docker load</code> command (and subsequently start it with <code>docker run</code>):</p> <pre><code>docker load &lt; your_image.tar docker run your_image </code></pre> <hr> <p>Some background notes (because you've asked why Docker works with images the way it does):</p> <p>The layer filesystem allows Docker to work with images and containers very efficiently, in terms of diskspace and container creation time. For example, you might have multiple local images that are all built on a common base image (like, for example, the <code>ubuntu:16.04</code> image). The layer filesystem will recognize this and only download the base image <em>once</em> when doing a <code>docker pull</code>.</p> <p>Using exported image files, you give up this advantage, as an image saved as a file will always contain all filesystem layers that the image is built of. Consider an example, in which you're working with a 200MB base image and 10MB of custom application data (the latter changing frequently when releasing new versions of your application). Using <code>docker save</code> and <code>docker load</code> will always result in a new 210MB-sized tarball that you need to distribute for each build of your application. Using <code>docker push</code> and <code>docker pull</code> together with a centralized registry, you'll need to transfer only the 10MB of changed image layers to and from the registry.</p>
1
2016-08-12T17:04:31Z
[ "python", "docker", "virtual-machine", "software-distribution" ]
Select pandas columns by several strings
38,922,632
<p>I have tried to select several rows of dataframe by specific partial string. </p> <p>The dataframe below is the original example data: </p> <pre><code>CODE DATA AA2016 47518 BB2016 47518 CC2014 47518 AA2014 47518 EE2015 47518 BB2015 47518 FF2016 47518 AA2013 47518 </code></pre> <p>I want to select the rows by the first two words in <code>Code</code> Column. </p> <p>For example, I want to choose the rows containing "AA","BB","CC" in the "Code" column. </p> <p>The result should represent like this: </p> <p><a href="http://i.stack.imgur.com/8k54b.png" rel="nofollow"><img src="http://i.stack.imgur.com/8k54b.png" alt="enter image description here"></a> </p> <p>I use the code like this: </p> <pre><code>Select_list = ["AA","BB", "CC"] df = pd.read_clipboard() df1 = df[df.CODE.str[0:2] isin Select_list] </code></pre> <p>But there would be error appear like <code>SyntaxError: invalid syntax</code></p>
1
2016-08-12T16:27:23Z
38,922,863
<p>As @ayhan notes in the comment, you can use <code>df[df.CODE.str[0:2].isin(Select_list)]</code>.</p> <p>Alternatively, note that you can use regular expressions via <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow"><code>pd.Series.str.contains</code></a>:</p> <pre><code>In [6]: df = pd.DataFrame({'CODE': ['AA2016', 'BB2015', 'AB2015']}) In [7]: df.CODE.str.contains(r'AA.*|BB.*|CC.*') Out[7]: 0 True 1 True 2 False Name: CODE, dtype: bool </code></pre> <p>(For this specific pattern, though, the slicing is probably simpler.)</p>
1
2016-08-12T16:43:15Z
[ "python", "python-2.7", "pandas", "dataframe" ]
How to add an item to a list in python and save it
38,922,664
<p>My program is set up so I can add items to the lists from terminal but whenever I do this for example <code>myFile.append('hello')</code> it keeps it there but when I exit terminal and do it again <code>'hello'</code> is deleted. Please help. Thank you!</p> <p>Code</p> <pre><code>elif userInput in command: print("Okay, Initializing new command.\n\n") command1 = raw_input("Which command would you like to add?\nKeyword\nLater Versions\n ").lower() if command1 == 'keyword': print('You selected keyword, to exit press enter') command2 = raw_input("Which Keyword would you like to edit? ") if command2 == 'calc': command3 = raw_input("Which Keyword would you like to add? ") calc.append(command3) print(calc) </code></pre>
-1
2016-08-12T16:29:22Z
38,922,698
<p>Try something like:</p> <pre><code>with open(myFile, 'a') as f: f.write('hello') </code></pre> <p>You can append to a list with<code>.append</code> but not a file. Instead, you can use the 'a' flag as above to append to the file <code>myFile</code> where <code>myFile</code> is a file path.</p> <h1>Update:</h1> <p>Based on your existing code and what you want to achieve, try this:</p> <pre><code>... elif userInput in command: print("Okay, Initializing new command.\n\n") command1 = raw_input("Which command would you like to add?\nKeyword\nLater Versions\n ").lower() if command1 == 'keyword': print('You selected keyword, to exit press enter') command2 = raw_input("Which Keyword would you like to edit? ") if command2 == 'calc': command3 = raw_input("Which Keyword would you like to add? ") calc = 'path/to/file' with open(calc, 'a+') as f: f.write(command3 + '\n') f.seek(0) #This brings you back to the start of the file, because appending will bring it to the end print(f.readlines()) </code></pre> <p>Basically, you are writing to a file, and printing back a list of all the words written to that file. The <code>'a+'</code> flag will let you open a file for reading and writing. Also, instead of/in addition to printing the "list" with <code>print(f.readlines())</code>, you could assign it to a variable and have an actual python <code>list</code> object for manipulating later, if that is what you want: <code>wordlist = f.readlines()</code>.</p> <p>Also, to improve your fundamental understanding of the issue, you should probably check out <a href="https://docs.python.org/2/library/persistence.html" rel="nofollow">this</a> and <a href="https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files" rel="nofollow">this</a>.</p> <h1>Update 2</h1> <p>If you need to have a Python <code>list</code> of keywords earlier in your code you could add:</p> <pre><code> with open('wordlist.txt', 'a+') as f: #wordlist.txt can be changed to be another file name or a path to a file f.seek(0) #opening with `'a+'` because it will create the file if it does not exist, # and seeking because `'a+'` moves to the end of the file calc = f.readlines() </code></pre> <p>This will read a list of words from <code>wordlist.txt</code> and save them to an Python <code>list</code> called <code>calc</code>. Now since <code>calc</code> is an actual Python <code>list</code> object, you can use <code>calc.append('whatever')</code>. Later in your code, when you want to save all the keywords back to the persistent "list" (which is actually just a text file with words separated by newline (<code>'\n'</code>), you can do:</p> <pre><code>with open('wordlist.txt', 'w+') as f: for word in calc: f.write(word) f.seek(0) print(f.readlines()) </code></pre> <p>This will overwrite your wordlist file with all the words currently in the <code>calc</code> list, and print out all the values to the console. </p> <p>This is as good as I can do without really understanding how your program is supposed to work or writing it myself. Try to improve your understanding of Python file I/O; it is not so complicated with some practice, and will serve you well in the future for simple persistent data. I would also suggest going through a Python tutorial like <a href="https://www.codecademy.com/learn/python" rel="nofollow">this one</a> on Codecademy to improve your general understanding of how Python works. I don't mean that as an insult; I did this tutorial myself a while ago, and it really helped me to create a good foundation of Python fundamentals. It also includes <a href="https://www.codecademy.com/courses/python-intermediate-en-OGNHh/0/1?curriculum_id=4f89dab3d788890003000096" rel="nofollow">a lesson on file I/O</a>. Good luck!</p>
3
2016-08-12T16:32:48Z
[ "python" ]
Tasks that throw exceptions block IPython-Parallel queue
38,922,764
<p>I am using IPython-Parallel's <code>load_balanced_view</code> and map to perform some simulations. I use the asynchronous version of the view so it doesn't block.</p> <p>Whenever the function applied by <code>map</code>throws an exception, the <code>error</code> property of the asynchronous map is set correctly. If this happens however the errorous tasks stays in the queue forever. Is there any possibility to cancel/abort it?</p> <p>As far as I understand it <code>cancel</code> and <code>abort</code> only work on jobs that are not yet running (waiting in queue).</p> <p>Any Ideas how to cancel the job so the engine becomes free again?</p> <p>Thanks, Martin</p>
0
2016-08-12T16:36:51Z
38,991,657
<p>This was a bug in <code>ipyparallel</code> and is fixed in master. </p> <p>The related GitHub issue is <a href="https://github.com/ipython/ipyparallel/issues/184" rel="nofollow">here</a>.</p>
0
2016-08-17T08:28:28Z
[ "python", "ipython", "jupyter", "ipython-parallel" ]
In python how can I make data ready for garbage collection to free memory?
38,922,850
<p>I have function that uses numpy to return an array with 4 fields. I use that function in a loop extract data from multiple sources. However my processing only is on 1 out of 4 fields. How do I reasonably make sure that the 3/4 fields I do not need will not be in memory before the next loop iteration? Here is my current approach: </p> <pre><code>data = [] for source in SOURCES: data_buff = read_source(source) # data_buff has 4 fields ('a','b','c','d') data_buff = data_buff['a'] # only select required field data.append(data_buff) </code></pre>
0
2016-08-12T16:42:18Z
38,923,216
<p>I am not really sure but i guess memory in python can't be freed, mean the memory occupied by some array or any object cannot be added to free memory pool programmatically even if you delete the reference variable. it will be deleted by the <code>GC</code> when the time comes.Try <a href="http://stackoverflow.com/questions/14865075/numpy-array-memory-management">link</a> for example </p>
0
2016-08-12T17:08:51Z
[ "python", "numpy", "memory", "garbage-collection" ]
In python how can I make data ready for garbage collection to free memory?
38,922,850
<p>I have function that uses numpy to return an array with 4 fields. I use that function in a loop extract data from multiple sources. However my processing only is on 1 out of 4 fields. How do I reasonably make sure that the 3/4 fields I do not need will not be in memory before the next loop iteration? Here is my current approach: </p> <pre><code>data = [] for source in SOURCES: data_buff = read_source(source) # data_buff has 4 fields ('a','b','c','d') data_buff = data_buff['a'] # only select required field data.append(data_buff) </code></pre>
0
2016-08-12T16:42:18Z
38,926,018
<p>It looks like you have a structured array; at least that's consistent with how you are accessing fields.</p> <p>In my current ipython session I have a structured array with 3 fields, and 64 elements.</p> <pre><code>In [1383]: data1.shape Out[1383]: (64,) In [1384]: data1.dtype Out[1384]: dtype([('f0', 'u1'), ('f1', 'u1'), ('f2', 'u1')]) In [1385]: data1.__array_interface__ Out[1385]: {'data': (163303000, False), 'descr': [('f0', '|u1'), ('f1', '|u1'), ('f2', '|u1')], 'shape': (64,), 'strides': None, 'typestr': '|V3', 'version': 3} </code></pre> <p>If I index one field, I get a <code>view</code> - same <code>data</code> buffer pointer:</p> <pre><code>In [1386]: data1['f0'].__array_interface__ Out[1386]: {'data': (163303000, False), 'descr': [('', '|u1')], 'shape': (64,), 'strides': (3,), 'typestr': '|u1', 'version': 3} </code></pre> <p>But if I use <code>copy</code>, then I get a new data buffer.</p> <pre><code>In [1387]: data1['f0'].copy().__array_interface__ Out[1387]: {'data': (166164152, False), 'descr': [('', '|u1')], 'shape': (64,), 'strides': None, 'typestr': '|u1', 'version': 3} </code></pre> <p>So if I did <code>data1=data1['f0'].copy()</code>, and there aren't any other <code>views</code> of the original <code>data1</code>, that data buffer space will be recycled.</p> <p>Most of the space used by an array is in the data buffer. It's numpy itself that manages that, not the Python GC. Obviously in one way or other they interact. So I think the best thing is to just make sure you collect copies, not views.</p>
0
2016-08-12T20:30:10Z
[ "python", "numpy", "memory", "garbage-collection" ]
How to Replace All the "nan" Strings with Empty String in My DataFrame?
38,922,952
<p>I have <code>"None"</code> and <code>"nan"</code> strings scattered in my dataframe. Is there a way to replace all of those with empty string <code>""</code> or <code>nan</code> so they do not show up when I export the dataframe as excel sheet?</p> <p>Simplified Example:</p> <p><strong>Note:</strong> <code>nan</code> in <code>col4</code> are not strings </p> <pre><code>ID col1 col2 col3 col4 1 Apple nan nan nan 2 None orange None nan 3 None nan banana nan </code></pre> <p>The output should be like this after removing all the <code>"None"</code> and <code>"nan"</code> strings when we replaced them by empty strings <code>""</code>:</p> <pre><code>ID col1 col2 col3 col4 1 Apple nan 2 orange nan 3 banana nan </code></pre> <p>Any idea how to solve this problem?</p> <p>Thanks,</p>
0
2016-08-12T16:50:11Z
38,923,035
<p>Use pandas' NaN. Those cells will be empty in Excel (you will be able to use 'select empty cells' command for example. You cannot do that with empty strings). </p> <pre><code>import numpy as np df.replace(['None', 'nan'], np.nan, inplace=True) </code></pre> <p><a href="http://i.stack.imgur.com/y7yZA.png" rel="nofollow"><img src="http://i.stack.imgur.com/y7yZA.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/9NXSp.png" rel="nofollow"><img src="http://i.stack.imgur.com/9NXSp.png" alt="enter image description here"></a></p>
1
2016-08-12T16:56:15Z
[ "python", "string", "pandas", "dataframe", null ]
How to Replace All the "nan" Strings with Empty String in My DataFrame?
38,922,952
<p>I have <code>"None"</code> and <code>"nan"</code> strings scattered in my dataframe. Is there a way to replace all of those with empty string <code>""</code> or <code>nan</code> so they do not show up when I export the dataframe as excel sheet?</p> <p>Simplified Example:</p> <p><strong>Note:</strong> <code>nan</code> in <code>col4</code> are not strings </p> <pre><code>ID col1 col2 col3 col4 1 Apple nan nan nan 2 None orange None nan 3 None nan banana nan </code></pre> <p>The output should be like this after removing all the <code>"None"</code> and <code>"nan"</code> strings when we replaced them by empty strings <code>""</code>:</p> <pre><code>ID col1 col2 col3 col4 1 Apple nan 2 orange nan 3 banana nan </code></pre> <p>Any idea how to solve this problem?</p> <p>Thanks,</p>
0
2016-08-12T16:50:11Z
38,923,089
<p>Use a list of strings to replace with blanks strings that won't affect actual <code>nan</code>'s...</p> <pre><code>df.replace(['nan', 'None'], '') </code></pre> <p>Which'll give you a new dataframe of:</p> <pre><code>ID col1 col2 col3 col4 1 Apple NaN 2 orange NaN 3 banana NaN </code></pre>
0
2016-08-12T17:00:02Z
[ "python", "string", "pandas", "dataframe", null ]
How to Replace All the "nan" Strings with Empty String in My DataFrame?
38,922,952
<p>I have <code>"None"</code> and <code>"nan"</code> strings scattered in my dataframe. Is there a way to replace all of those with empty string <code>""</code> or <code>nan</code> so they do not show up when I export the dataframe as excel sheet?</p> <p>Simplified Example:</p> <p><strong>Note:</strong> <code>nan</code> in <code>col4</code> are not strings </p> <pre><code>ID col1 col2 col3 col4 1 Apple nan nan nan 2 None orange None nan 3 None nan banana nan </code></pre> <p>The output should be like this after removing all the <code>"None"</code> and <code>"nan"</code> strings when we replaced them by empty strings <code>""</code>:</p> <pre><code>ID col1 col2 col3 col4 1 Apple nan 2 orange nan 3 banana nan </code></pre> <p>Any idea how to solve this problem?</p> <p>Thanks,</p>
0
2016-08-12T16:50:11Z
38,923,174
<p>You can compare each column to the numpy object dtype (which is basically text columns), and then only do replacements for those columns.</p> <pre><code>for col in df: if df[col] == np.dtype('O'): # Object df.col1.replace(['None', 'NaN', np.nan], "", inplace=True) </code></pre>
1
2016-08-12T17:05:51Z
[ "python", "string", "pandas", "dataframe", null ]
How to Replace All the "nan" Strings with Empty String in My DataFrame?
38,922,952
<p>I have <code>"None"</code> and <code>"nan"</code> strings scattered in my dataframe. Is there a way to replace all of those with empty string <code>""</code> or <code>nan</code> so they do not show up when I export the dataframe as excel sheet?</p> <p>Simplified Example:</p> <p><strong>Note:</strong> <code>nan</code> in <code>col4</code> are not strings </p> <pre><code>ID col1 col2 col3 col4 1 Apple nan nan nan 2 None orange None nan 3 None nan banana nan </code></pre> <p>The output should be like this after removing all the <code>"None"</code> and <code>"nan"</code> strings when we replaced them by empty strings <code>""</code>:</p> <pre><code>ID col1 col2 col3 col4 1 Apple nan 2 orange nan 3 banana nan </code></pre> <p>Any idea how to solve this problem?</p> <p>Thanks,</p>
0
2016-08-12T16:50:11Z
38,924,953
<p>All those loop-de-loop solutions...</p> <pre><code>replacers = [None, np.nan, "None", "NaN", "nan"] # and everything else that needs replacing. df.loc[:, df.dtypes == 'object'].replace(replacers, '', inplace=True) </code></pre>
0
2016-08-12T19:10:00Z
[ "python", "string", "pandas", "dataframe", null ]
Django AttributeError: 'InterestsForm' object has no attribute '_errors'
38,922,969
<p>I am trying to use a Django form to allow a Django User to input their three favourite interests. The error occurs during the template rendering where it says <code>{{form.as_ul}}</code>.</p> <p>Here is the code:</p> <p><strong>reg_interests.html</strong></p> <pre><code>{% block content %} &lt;br&gt;&lt;br&gt; &lt;h1&gt;Choose the 3 things that interest you most!&lt;/h1&gt; &lt;form method="post" action="/reg_interests/"&gt; {% csrf_token %} {{form.as_ul}} &lt;br&gt; &lt;p class="submit"&gt;&lt;input class="btn btn-default" type="submit" name="commit" value="Continue"&gt;&lt;/p&gt; &lt;/form&gt; {% endblock %} </code></pre> <p><strong>views.py</strong></p> <pre><code>def reg_interests_view(request): if request.POST: form = InterestsForm(request.POST, request=request) if form.is_valid(): form.save(request) return redirect('/reg_video/') args = {} args['form'] = InterestsForm(request=request) return render(request, 'login/reg_interests.html', args) </code></pre> <p><strong>forms.py</strong></p> <pre><code>class InterestsForm(RequestModelForm): interest1 = forms.ChoiceField(choices=[(1, "Option 1"), (2, "Option 2")]) interest2 = forms.ChoiceField(choices=[(1, "Option 1"), (2, "Option 2")]) interest3 = forms.ChoiceField(choices=[(1, "Option 1"), (2, "Option 2")]) class Meta: model = Interest fields = ('interest1', 'interest2', 'interest3') def __init__(self, request): self.user = request.user def save(self, commit=True): interest = super(InterestsForm, self).save(commit=False) interest.user = self.user interest.interest1 = self.cleaned_data['interest1'] interest.interest2 = self.cleaned_data['interest2'] interest.interest3 = self.cleaned_data['interest3'] if commit: interest.save() return interest </code></pre> <p>I think there is a problem with the form, but I don't know how or why I need to define <code>_errors</code>. Should Django itself not take care of that? If not, how do I define <code>_errors</code>?</p>
1
2016-08-12T16:51:44Z
38,923,171
<p>This code can't possibly work at all, because you override the <code>__init__</code> method of the form so that a) you only accept a <code>request</code> argument - and not any of the other things a form is expecting, like <code>data</code> or <code>initial</code> - and b) you never call the superclass init method to initialise the things the rest of the form code expects. You need to preserve the signature and call super.</p> <pre><code>def __init__(self, *args, **kwargs): request = kwargs.pop('request') self.user = request.user super(InterestsForm, self).__init__(*args, **kwargs) </code></pre>
1
2016-08-12T17:05:47Z
[ "python", "django", "django-1.10" ]
Django unit test query against production database
38,923,002
<p>I am trying to write some unit tests for an asynchronous method in my Django app. Essentially, when a user does a certain POST, this method is kicked off so the application doesn't hang. What I want to test is the ability to cancel this request as it is running (in this case via celery). The only problem with doing this is because Celery is running independent of the web application, it pushes the results to the real database, not the test database that is created by Django Unit Tests. So what I'm wondering is how would I be able to do something like </p> <pre><code>Results.objects.get(id=some_id) </code></pre> <p>and tell it to point to the actual database. I've already tried the following:</p> <pre><code>Results.objects.using('default').get(id=some_id) </code></pre> <p>Thinking that maybe this would solve the problem, but it didn't find the result (again because it was pushing the information to the actual database, not the test DB). I did some searching around and found this link: <a href="http://stackoverflow.com/questions/2589147/how-do-i-run-a-unit-test-against-the-production-database">How do I run a unit test against the production database?</a> but the answers on here say things like "You shouldn't test against production." I completely understand this is not good practice but I need to hit the live database. Everything is being run on a VM so it's all a test database anyways. Does anyone know of a way to hit the real database?</p> <p>Thanks,</p>
1
2016-08-12T16:53:58Z
38,934,925
<p>I'm not sure if testing against your prod is a better solution than running your celery workers in dev mode against your test database. How are you starting your celery workers ?? I imagine you're starting your celery workers external of the test using your prod/real settings, then you're running your tests using the test settings. For an integration test, it would probably be more repeatable/maintainable if you had an integration environment. </p> <p>a common test strategy for this would be:</p> <ul> <li>unit test your view to make sure that it calls the correct celery task with the correct arguments, you could stub out the celery task dependency, or you could run the celery task syncronously using CELERY_ALWAYS_EAGER=True, and an in memory Queue.</li> <li>if you stub out the celery dependency, then there should be a separate unit test exercising its logic</li> </ul> <p>Your original scenario is not super well suited for django unit test framework because of the inter process dependency of the celery broker. An integration test between your app and celery would probably be valuable, but for it to be maintainable, repeatable, and reliable celery broker process startup, cleanup, etc should probably be managed in an automated way.</p>
0
2016-08-13T16:48:39Z
[ "python", "django", "unit-testing", "celery", "integration-testing" ]
Iterating a list of lists and modifying values backwards
38,923,061
<p>I have a list of lists, like so.</p> <pre><code>[[1, 2, 3], [4, 2, 7], [9, 5, 6]] </code></pre> <p>I want to subtract the first element of each sublist by the first element of the previous sublist, and afterwards, I also want to set the first element of the first sublist to zero. Yielding</p> <pre><code>[[0, 2, 3], [3, 2, 7], [5, 5, 6]] </code></pre> <p>I have tried writing a function for this a few times and i can't figure out how i would iterate through - because if I want the subtraction to be with all of the original values, for example, after I subtract 4 by 1 and get 3 for the first element of the second list, i would still want to subtract 9 (first element of the third list) by 4 (original value of the second list), not 3.</p> <p>At first it seems like i would need to iterate through the list backwards but i have no idea how to do this. Any help is greatly appreciated.</p>
-1
2016-08-12T16:58:02Z
38,923,239
<p>If I got the question right, you want to only modify the first element of the sub lists, right? You could do something like this-</p> <pre><code>li = [[1, 2, 3], [4, 2, 7], [9, 5, 6]] for i in range(2, 0, -1): li[i][0] = li[i][0] - li[i-1][0] li[0][0] = 0 </code></pre> <p>Starting from the back, you subtract from it the first element of the previous sublist and finally set the first element of the first list 0. Of course you can use len(li)-1 instead of just using 2 in case its for a different array.</p>
2
2016-08-12T17:11:20Z
[ "python", "list", "iteration" ]
Iterating a list of lists and modifying values backwards
38,923,061
<p>I have a list of lists, like so.</p> <pre><code>[[1, 2, 3], [4, 2, 7], [9, 5, 6]] </code></pre> <p>I want to subtract the first element of each sublist by the first element of the previous sublist, and afterwards, I also want to set the first element of the first sublist to zero. Yielding</p> <pre><code>[[0, 2, 3], [3, 2, 7], [5, 5, 6]] </code></pre> <p>I have tried writing a function for this a few times and i can't figure out how i would iterate through - because if I want the subtraction to be with all of the original values, for example, after I subtract 4 by 1 and get 3 for the first element of the second list, i would still want to subtract 9 (first element of the third list) by 4 (original value of the second list), not 3.</p> <p>At first it seems like i would need to iterate through the list backwards but i have no idea how to do this. Any help is greatly appreciated.</p>
-1
2016-08-12T16:58:02Z
38,923,240
<p>You can use the old zip-the-list-with-itself trick:</p> <pre><code>lists= [[1, 2, 3], [4, 2, 7], [9, 5, 6]] i= reversed(lists) # iterate backwards next(i) # drop the first (last) list j= reversed(lists) # create another reversed iterator, but don't drop the 1st list for list1, list2 in zip(i, j): # zip the two iterators list2[0]-= list1[0] lists[0][0]= 0 # set first value to 0 </code></pre>
0
2016-08-12T17:11:24Z
[ "python", "list", "iteration" ]
Iterating a list of lists and modifying values backwards
38,923,061
<p>I have a list of lists, like so.</p> <pre><code>[[1, 2, 3], [4, 2, 7], [9, 5, 6]] </code></pre> <p>I want to subtract the first element of each sublist by the first element of the previous sublist, and afterwards, I also want to set the first element of the first sublist to zero. Yielding</p> <pre><code>[[0, 2, 3], [3, 2, 7], [5, 5, 6]] </code></pre> <p>I have tried writing a function for this a few times and i can't figure out how i would iterate through - because if I want the subtraction to be with all of the original values, for example, after I subtract 4 by 1 and get 3 for the first element of the second list, i would still want to subtract 9 (first element of the third list) by 4 (original value of the second list), not 3.</p> <p>At first it seems like i would need to iterate through the list backwards but i have no idea how to do this. Any help is greatly appreciated.</p>
-1
2016-08-12T16:58:02Z
38,923,485
<pre><code>lst = [ [1, 2, 3], [4, 2, 7], [9, 5, 6] ] # print(lst) t = [ lst[0] ] for i in range( 1, len(lst) ): x = [ lst[i][0] - lst[i-1][0] ] x.extend( lst[i][1:] ) t.append( x ) t[0][0] = 0 print(t) </code></pre> <p>Result will be:</p> <p><code>[[0, 2, 3], [3, 2, 7], [5, 5, 6]]</code></p>
0
2016-08-12T17:27:13Z
[ "python", "list", "iteration" ]
good style to introduce python variables within a loop
38,923,091
<p>I have a C++ background and I'm learning Python. I am writing code which needs to extract a particular value from a <code>for</code> loop:</p> <pre><code>seventh_value = None # ** my question is about this line for index in range(1, 10): value = f(index) # we have a special interest in the seventh value if index == 7: seventh_value = value # (do other things with value here) # make use of seventh_value here </code></pre> <p>In C++ I'd need to declare seventh_value before the for loop to ensure its scope is not limited to the for loop. In Python I do not need to do this. My question is whether it's good style to omit the initial assignment to seventh_value.</p> <p>I understand that if the loop doesn't iterate at least 7 times then I can avoid a NameError by assigning to seventh_value prior to the loop. Let's assume that it is clear it will iterate at least 7 times (as in the above example where I've hard-coded 10 iterations).</p> <p>I also understand that there may be other ways to extract a particular value from an iteration. I'm really just wondering about whether it's good style to introduce variables before a loop if they will be used after the loop.</p> <p>The code I wrote above looks clear to me, but I think I'm just seeing it with C++ eyes.</p>
10
2016-08-12T17:00:02Z
38,923,169
<p>It's only partially a matter of style. You need to do <em>something</em> to ensure your code doesn't raise an (uncaught) <code>NameError</code> following the loop, so your two choices are</p> <ol> <li><p>Ensure that the <code>NameError</code> cannot happen by making an unconditional assignment to <code>seventh_value</code>.</p></li> <li><p>Wrap the code that accesses <code>seventh_value</code> in a <code>try</code> block to catch and (presumably) ignore the possible <code>NameError</code>.</p></li> </ol> <p>View from this perspective, and without knowing more about your code, I think you would agree that #1 is preferable.</p>
1
2016-08-12T17:05:42Z
[ "python" ]
good style to introduce python variables within a loop
38,923,091
<p>I have a C++ background and I'm learning Python. I am writing code which needs to extract a particular value from a <code>for</code> loop:</p> <pre><code>seventh_value = None # ** my question is about this line for index in range(1, 10): value = f(index) # we have a special interest in the seventh value if index == 7: seventh_value = value # (do other things with value here) # make use of seventh_value here </code></pre> <p>In C++ I'd need to declare seventh_value before the for loop to ensure its scope is not limited to the for loop. In Python I do not need to do this. My question is whether it's good style to omit the initial assignment to seventh_value.</p> <p>I understand that if the loop doesn't iterate at least 7 times then I can avoid a NameError by assigning to seventh_value prior to the loop. Let's assume that it is clear it will iterate at least 7 times (as in the above example where I've hard-coded 10 iterations).</p> <p>I also understand that there may be other ways to extract a particular value from an iteration. I'm really just wondering about whether it's good style to introduce variables before a loop if they will be used after the loop.</p> <p>The code I wrote above looks clear to me, but I think I'm just seeing it with C++ eyes.</p>
10
2016-08-12T17:00:02Z
38,923,189
<p>This is a fine approach to set the value to <code>None</code> before the for-loop. Do not worry too much. Personally, I feel as long as code is readable by someone who has no idea at all -- it is fine.</p> <p>That being said, there's a slightly better (pythonic) way to avoid the problem altogether. <strong>Note</strong> that the following will <strong>not</strong> do anything with the value at every iteration -- just the "special interest" part. Further, I am assuming <code>f(..)</code> does not cause any side-effects (like changes states of variables outside (like global variables). If it does, the line below is definitely not for you.</p> <pre><code>seventh_value = next(f(i) for i in range(1,10) if i == 7) </code></pre> <p>The above construct run until i==7, and calls <code>f(i)</code> only when i=7 never else.</p>
2
2016-08-12T17:06:33Z
[ "python" ]
good style to introduce python variables within a loop
38,923,091
<p>I have a C++ background and I'm learning Python. I am writing code which needs to extract a particular value from a <code>for</code> loop:</p> <pre><code>seventh_value = None # ** my question is about this line for index in range(1, 10): value = f(index) # we have a special interest in the seventh value if index == 7: seventh_value = value # (do other things with value here) # make use of seventh_value here </code></pre> <p>In C++ I'd need to declare seventh_value before the for loop to ensure its scope is not limited to the for loop. In Python I do not need to do this. My question is whether it's good style to omit the initial assignment to seventh_value.</p> <p>I understand that if the loop doesn't iterate at least 7 times then I can avoid a NameError by assigning to seventh_value prior to the loop. Let's assume that it is clear it will iterate at least 7 times (as in the above example where I've hard-coded 10 iterations).</p> <p>I also understand that there may be other ways to extract a particular value from an iteration. I'm really just wondering about whether it's good style to introduce variables before a loop if they will be used after the loop.</p> <p>The code I wrote above looks clear to me, but I think I'm just seeing it with C++ eyes.</p>
10
2016-08-12T17:00:02Z
38,923,472
<p>If you are sure that <code>seventh_value</code> should be set and you count on it in your program logic, you might even want your code to crash with <code>NameError</code> and write it without prior <code>seventh_value</code> definition.</p> <p>If you are sure that <code>seventh_value</code> might not be set when all code works just fine, you should probably define <code>seventh_value</code> as you do in the example and check later if it was set at all.</p>
1
2016-08-12T17:26:14Z
[ "python" ]
good style to introduce python variables within a loop
38,923,091
<p>I have a C++ background and I'm learning Python. I am writing code which needs to extract a particular value from a <code>for</code> loop:</p> <pre><code>seventh_value = None # ** my question is about this line for index in range(1, 10): value = f(index) # we have a special interest in the seventh value if index == 7: seventh_value = value # (do other things with value here) # make use of seventh_value here </code></pre> <p>In C++ I'd need to declare seventh_value before the for loop to ensure its scope is not limited to the for loop. In Python I do not need to do this. My question is whether it's good style to omit the initial assignment to seventh_value.</p> <p>I understand that if the loop doesn't iterate at least 7 times then I can avoid a NameError by assigning to seventh_value prior to the loop. Let's assume that it is clear it will iterate at least 7 times (as in the above example where I've hard-coded 10 iterations).</p> <p>I also understand that there may be other ways to extract a particular value from an iteration. I'm really just wondering about whether it's good style to introduce variables before a loop if they will be used after the loop.</p> <p>The code I wrote above looks clear to me, but I think I'm just seeing it with C++ eyes.</p>
10
2016-08-12T17:00:02Z
38,923,477
<p>You can do it exactly how you suggest, and if you try it, you will find it works exactly how you want.</p> <p>However, there is a better, (imho more pythonic) way, that totally avoids the need to pre-initialize the variable.</p> <pre><code>results = [] for index in range(1, 10): value = f(index) # (do other things with value here) results.append(value) seventh_value = results[6] #6 because index 1 is at location 0 in the list. # make use of seventh_value here </code></pre> <p>Now that you have a simple <code>for</code> loop, it can easily be refactored into a <a class='doc-link' href="http://stackoverflow.com/documentation/python/196/comprehensions/737/list-comprehensions#t=201608121724177242799">list comprehension</a>: </p> <pre><code>results = [f(index) for index in range(1, 10)] for value in results: # (do other things with value here) seventh_value = results[7] # make use of seventh_value here </code></pre> <p>Whether you decide to go that far will depend on how complex your <code>(do other things with value here)</code> is.</p>
0
2016-08-12T17:26:38Z
[ "python" ]
How can I combine (or make operations) between attributes of different classes (without specifying instances yet)?
38,923,102
<p>First of all, I am a total newbie. Thanks for your patience.</p> <p>I am designing a piece of software to calculate insulation materials and amounts on different houses. </p> <p>I have a <code>class House()</code>, which holds attributes like roof_area and wall_area.</p> <p>I have a <code>class Insulator()</code>, which holds attributes like thickness and area (the area the packaged material covers)</p> <p>Now I want to know how many packages of the insulator I should buy in order to cover the whole roof area.</p> <p>So, the operation would be:</p> <pre><code>House.roof_area / Insulator.area = insulator_packages_needed_for_roof </code></pre> <p>The thing is I can't do that operation:</p> <pre><code>AttributeError: type object 'House' has no attribute 'roof_area'. </code></pre> <p>Of course I could do it a an instance scope, but I don't want to specify an instance yet, as this operation should be done for any instance of the Class that gets build in the future. Should I use inheritance? My feeling is that, given that Insulator and House are totally different things, they shouldn't be mixed by inheritance, but I am just a beginner.</p>
0
2016-08-12T17:00:50Z
38,923,267
<p>If you want to use attributes without creating an instance you should use class attributes.</p> <pre><code>class House(object): roof_area = 10 # Or whatever you see fit. roof_surface = 20 class Insulator(object): thickness = 10 # Or whatever you see fit. surface = 20 </code></pre> <p>This way you can access the attributes by typing 'House.roof_area' for example.</p> <p>Although, I don't see why you cannot create an instance. It would prevent harcoding in class attributes and would in your case be much easier.</p> <p>Also, your operation is not valid syntax, but maybe you just showed pseudo-code. Proper syntax would be:</p> <pre><code>insulator_packages_needed_for_roof = House.roof_area / Insulator.area </code></pre>
0
2016-08-12T17:13:07Z
[ "python", "class", "instances" ]
How can I combine (or make operations) between attributes of different classes (without specifying instances yet)?
38,923,102
<p>First of all, I am a total newbie. Thanks for your patience.</p> <p>I am designing a piece of software to calculate insulation materials and amounts on different houses. </p> <p>I have a <code>class House()</code>, which holds attributes like roof_area and wall_area.</p> <p>I have a <code>class Insulator()</code>, which holds attributes like thickness and area (the area the packaged material covers)</p> <p>Now I want to know how many packages of the insulator I should buy in order to cover the whole roof area.</p> <p>So, the operation would be:</p> <pre><code>House.roof_area / Insulator.area = insulator_packages_needed_for_roof </code></pre> <p>The thing is I can't do that operation:</p> <pre><code>AttributeError: type object 'House' has no attribute 'roof_area'. </code></pre> <p>Of course I could do it a an instance scope, but I don't want to specify an instance yet, as this operation should be done for any instance of the Class that gets build in the future. Should I use inheritance? My feeling is that, given that Insulator and House are totally different things, they shouldn't be mixed by inheritance, but I am just a beginner.</p>
0
2016-08-12T17:00:50Z
38,924,429
<p>It doesn't make any sense to try to compute the number of insulation packages you need to cover the roof of a house, without using any instances of your <code>House</code> or <code>Insulator</code> classes. It only makes sense if you have one instance of each.</p> <p>You can, however, write the code to do the calculation before you've created the instances. Just put it in a function that takes the instances as arguments:</p> <pre><code>def roof_insulation_packages(house, insulator): # args are instances of House and Insulator return house.roof_area / insulator.area # do the calculation and return it </code></pre> <p>It might make more sense for the function to be a method of one of the classes. I'd even suggest that <code>Insulator</code> instances might be a good candidates to be instance attributes of the <code>House</code>. That would look something like this:</p> <pre><code>class House(): def __init__(self, roof_area, roof_insulator, wall_area, wall_insulator): self.roof_area = roof_area self.roof_insulator = roof_insulator self.wall_area = wall_area self.wall_insulator = wall_insulator def calculate_roof_insulation_packages(self): return self.roof_area / self.roof_insulator.area def calculate_wall_insulation_packages(self, insulator): return self.wall_area / self.wall_insulator.area </code></pre> <p>You'd create the house instance with something like this (I'm making up the arguments to the <code>Insulator</code> class, so don't pay too much attention to that part):</p> <pre><code>good_roof_insulation = Insulator(4, 5) # nonsense args cheap_wall_insulation = Insulator(5, 12) my_house = House(100, good_roof_insulation, 87, cheap_wall_insulation) </code></pre>
1
2016-08-12T18:34:32Z
[ "python", "class", "instances" ]
Why are my ZenDesk macros being updated, but no change actually going through?
38,923,106
<p>I was trying to bulk edit the signature of my personal macros on ZenDesk, and the only way to do that is via the API. So I wrote this quick Python script to try to do it:</p> <pre><code>import sys import time import logging import requests import re start_time = time.time() # Set up logging logger = logging.getLogger() log_handler = logging.StreamHandler(sys.stdout) log_handler.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s - %(funcName)s - line %(lineno)d")) log_handler.setLevel(logging.DEBUG) logger.addHandler(log_handler) logger.setLevel(logging.DEBUG) def doTheGet(url, user, pwd): response = requests.get(url, auth=(user + "/token", pwd)) if response.status_code != 200: logger.error("Status: %s (%s) Problem with the request. Exiting. %f seconds elapsed" % (response.status_code, response.reason, time.time() - start_time)) exit() data = response.json() return data def doThePut(url, updated_data, user, pwd): response = requests.put(url, json="{'macro': {'actions': %r}}" % updated_data, headers={"Content-Type": "application/json"}, auth=(user + "/token", pwd)) if response.status_code != 200: logger.error("Status: %s (%s) Problem with the request. Exiting. %f seconds elapsed" % (response.status_code, response.reason, time.time() - start_time)) exit() data = response.json() return data def getMacros(): macros = {} data = doTheGet("https://mydomain.zendesk.com/api/v2/macros.json", "me@mydomain.com", "111tokenZZZ") def getMacros(macro_list, page, page_count): if not page: for macro in macro_list: if macro["restriction"] and macro["active"]: if macro["restriction"]["type"] == "User": macros[macro["id"]] = macro["actions"] else: for macro in macro_list: if macro["restriction"] and macro["active"]: if macro["restriction"]["type"] == "User": macros[macro["id"]] = macro["actions"] page_count += 1 new_data = doTheGet(page, "me@mydomain.com", "111tokenZZZ") new_macs = new_data["macros"] new_next_page = new_data["next_page"] getMacros(new_macs, new_next_page, page_count) macs = data["macros"] current_page = 1 next_page = data["next_page"] getMacros(macs, next_page, current_page) return macros def updateMacros(): macros = getMacros() regular = "RegEx to match signature to be replaced$" #since some macros already have the updated signature for macro in macros: for action in macros[macro]: if action["field"] == "comment_value": if re.search(regular, action["value"][1]): ind = action["value"][1].rfind("\n") action["value"][1] = action["value"][1][:ind] + "\nNew signature" return macros macs = updateMacros() for mac in macs: doThePut("https://mydomain.zendesk.com/api/v2/macros/%d.json" % (mac), macs[mac], "me@mydomain.com", "111tokenZZZ") </code></pre> <p>Now, everything's running as expected, and I get no errors. When I go to my macros on ZenDesk and sort them by last updated, I do see that the script did something, since they show as being last updated today. However, nothing changes on them. I made sure the data I'm sending over <em>is</em> edited (<code>updateMacros</code> <em>is</em> doing its job). I made sure the requests send back an OK response. So I'm sending updated data, getting back a 200 response, but <a href="https://developer.zendesk.com/rest_api/docs/core/macros#update-macro" rel="nofollow">the response sent back</a> shows me the macros as they were before, with zero changes.</p> <p>The only thing that occurs to me as maybe being wrong in some way is the format of the data I'm sending over, or something of the sort. But even then, I'd expect the response to not be a 200, then... </p> <p>What am I missing here?</p>
2
2016-08-12T17:01:16Z
38,929,858
<p>Looks like you're double-encoding the JSON data in your PUT request:</p> <pre><code>response = requests.put(url, json="{'macro': {'actions': %r}}" % updated_data, headers={"Content-Type": "application/json"}, auth=(user + "/token", pwd)) </code></pre> <p>The json parameter expects an object, which it then dutifully encodes as JSON and sends as the body of the request; this is merely a convenience; the implementation is simply,</p> <pre><code> if not data and json is not None: # urllib3 requires a bytes-like body. Python 2's json.dumps # provides this natively, but Python 3 gives a Unicode string. content_type = 'application/json' body = complexjson.dumps(json) if not isinstance(body, bytes): body = body.encode('utf-8') </code></pre> <p>(source: <a href="https://github.com/kennethreitz/requests/blob/master/requests/models.py#L424" rel="nofollow">https://github.com/kennethreitz/requests/blob/master/requests/models.py#L424</a>)</p> <p>Since the value is <em>always</em> passed through <code>json.dumps()</code>, if you pass a string representing already-encoded JSON it will itself be encoded:</p> <pre><code>"{\'macro\': {\'actions\': [{\'field\': \'comment_value\', \'value\': [\'channel:all\', \'Spiffy New Sig that will Never Be Saved\']}]}}" </code></pre> <p>ZenDesk, upon being given JSON it doesn't expect, updates the <code>updated_at</code> field and... Does nothing else. You can verify this by passing an empty string - same result.</p> <p>Note that you're also relying on Python's repr formatting to fill in your JSON; that's probably a bad idea too. Instead, let's just reconstruct our macro object and let requests encode it:</p> <pre><code>response = requests.put(url, json={'macro': {'actions': updated_data}}, headers={"Content-Type": "application/json"}, auth=(user + "/token", pwd)) </code></pre> <p>This should do what you expect. </p>
3
2016-08-13T06:22:07Z
[ "python", "python-2.7", "zendesk-api" ]