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
sequence
Change color when button is sunken Tkinter
40,023,841
<p>How could I make it, so when any button in my program is sunken (so being clicked) that button gets a certain background color (white) for 1 sec.</p> <p>I was thinking of something like this:</p> <p>Whenever ButtonClicked = Sunken, ButtonClicked['bg'] = 'white' for 1 sec</p> <p>But I have lots of buttons, and every button has a different function. So what is an easy to implement program so this happens to all buttons?</p>
0
2016-10-13T14:29:00Z
40,024,740
<p>The simplest solution is to create your own custom button class, and add the behavior to that class.</p> <p>You can use <code>after</code> to arrange for the color to be restored after some amount of time.</p> <p>For example:</p> <pre><code>class CustomButton(tk.Button): def __init__(self, *args, **kwargs): self.altcolor = kwargs.pop("altcolor", "pink") tk.Button.__init__(self, *args, **kwargs) self.bind("&lt;ButtonPress&gt;", self.twinkle) def twinkle(self, event): # get the current activebackground... bg = self.cget("activebackground") # change it ... self.configure(activebackground=self.altcolor) # and then restore it after a second self.after(1000, lambda: self.configure(activebackground=bg)) </code></pre> <p>You would use it like you would any other <code>Button</code>. It takes one new argument, <code>altcolor</code>, which is the extra color you want to use:</p> <pre><code>b1 = CustomButton(root, text="Click me!", altcolor="pink") b2 = CustomButton(root, text="No, Click me!", altcolor="blue") </code></pre>
1
2016-10-13T15:09:28Z
[ "python", "button", "tkinter", "click" ]
Having trouble navigating file explorer with python
40,023,890
<p>I am building an automated browser with selenium and it is working flawlessly! (thank you selenium (: ) But I am having trouble uploading a file. One of the steps I need to execute is to upload a file.</p> <p>The code I use to upload, and seems like it works for many people, is:</p> <pre><code>file_input = driver.find_element_by_id('ImageUploadButton') file_input.send_keys('C:\\image.jpg') </code></pre> <p>Also tried:</p> <pre><code>driver.find_element_by_id('ImageUploadButton').click() driver.find_element_by_css_selector('input[type="file"]').clear() driver.find_element_by_css_selector('input[type="file"]').send_keys('C:\\image.jpg') </code></pre> <p>This seems to work for a lot of people, but for me, it just opens the file explorer for me to pick the file I want to upload, and that is it. No error message, just continues to execute the code.</p> <p>Is anyone aware of maybe another module that I can use to navigate the file explorer and submit the file?</p> <p>Or am I using selenium inappropriately? </p> <p>----------- edit ---------------</p> <p>Added DIV from website:</p> <pre><code> &lt;div id="FileInputWrapper" class="file-input-wrapper"&gt; &lt;input id="FileUploadInput" type="hidden" name="file"&gt; &lt;button id="ImageUploadButton" class="button-update-cancel short file-upload-button" type="button" style="position: relative; z-index: 1;"&gt; Select Images&lt;/button&gt; &lt;/div&gt; &lt;input type="hidden" name="images"&gt; &lt;div id="html5_1auv7g94u187l1qdq108d1ue5qve3_container" class="moxie-shim moxie-shim-html5" style="position: absolute; top: 518px; left: 0px; width: 155px; height: 45px; overflow: hidden; z-index: 0;"&gt; &lt;input id="html5_1auv7g94u187l1qdq108d1ue5qve3" type="file" accept="image/jpeg,image/png,image/gif,image/bmp" multiple="" style="font-size: 999px; opacity: 0; position: absolute; top: 0px; left: 0px; width: 100%; height: 100%;"&gt; &lt;/div&gt; </code></pre>
1
2016-10-13T14:31:12Z
40,024,204
<p>Seems that you use wrong locator to upload file. You should handle <code>input</code> element, not <code>button</code>:</p> <pre><code>file_input = driver.find_element_by_xpath('//input[@type="file"]') file_input.send_keys('C:\\image.jpg') </code></pre>
2
2016-10-13T14:44:46Z
[ "python", "selenium" ]
Php : read output from exec
40,023,925
<p>I'm launching a Python script from PHP and I'd like to get the line printed from that Python:</p> <pre><code>exec( "python plotModule.py $myArray[0] $myArray[1]", $output, $ret_code); $fp = fopen('logDisp.txt', 'w'); fwrite($fp, "$output"); fclose($fp); </code></pre> <p>In Python I have a <code>print("hello")</code> in order to test if it's working. Nothing is written in logDisp.txt file.</p> <p>Can you tell me why?</p>
0
2016-10-13T14:32:28Z
40,024,037
<p>You try write $output as string, but it`s an array</p> <p>Use foreach or $output[0]</p>
0
2016-10-13T14:37:17Z
[ "php", "python" ]
Php : read output from exec
40,023,925
<p>I'm launching a Python script from PHP and I'd like to get the line printed from that Python:</p> <pre><code>exec( "python plotModule.py $myArray[0] $myArray[1]", $output, $ret_code); $fp = fopen('logDisp.txt', 'w'); fwrite($fp, "$output"); fclose($fp); </code></pre> <p>In Python I have a <code>print("hello")</code> in order to test if it's working. Nothing is written in logDisp.txt file.</p> <p>Can you tell me why?</p>
0
2016-10-13T14:32:28Z
40,073,428
<pre><code>exec( "python plotModule.py $myArray[0] $myArray[1]", $output, $ret_code); $fp = fopen('logDisp.txt', 'w'); fwrite($fp, json_encode($output)); fclose($fp); </code></pre> <p>Here you can see the jsonified response</p>
1
2016-10-16T17:48:26Z
[ "php", "python" ]
How to get real estate data with Idealista API?
40,023,931
<p>I've been trying to use the API of the website Idealista (<a href="https://www.idealista.com/" rel="nofollow">https://www.idealista.com/</a>) to retrieve information of real estate data. </p> <p>Since I'm not familiarized with OAuth2 I haven't been able to obtain the token so far. I have just been provided with the api key, the secret and some basic info of how to mount the http request. </p> <p>I would appreciate an example (preferably in Python) of the functioning of this API, or else some more generic info about dealing with OAuth2 and Python.</p>
0
2016-10-13T14:32:36Z
40,106,540
<p>After some days of research I came up with a basic python code to retrieve real estate data from the Idealista API.</p> <pre><code>def get_oauth_token(): http_obj = Http() url = "https://api.idealista.com/oauth/token" apikey= urllib.parse.quote_plus('Provided_API_key') secret= urllib.parse.quote_plus('Provided_API_secret') auth = base64.encode(apikey + ':' + secret) body = {'grant_type':'client_credentials'} headers = {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8','Authorization' : 'Basic ' + auth} resp, content = http_obj.request(url,method='POST',headers=headers, body=urllib.parse.urlencode(body)) return content </code></pre> <p>This function would return a JSON with the OAuth2 token and the session time in seconds. Afterwards, to query the API, it would be as simple as:</p> <pre><code>def search_api(token): http_obj = Http() url = "http://api.idealista.com/3.5/es/search?center=40.42938099999995,-3.7097526269835726&amp;country=es&amp;maxItems=50&amp;numPage=1&amp;distance=452&amp;propertyType=bedrooms&amp;operation=rent" headers = {'Authorization' : 'Bearer ' + token} resp, content = http_obj.request(url,method='POST',headers=headers) return content </code></pre> <p>This time the we would find in the content var the data we were looking for, again as a JSON. </p>
0
2016-10-18T11:05:08Z
[ "python", "oauth2" ]
Kivy Python: Accordion inside an accordion, using a variable
40,023,979
<p>I am trying to create an accordion menu (no.1), in which there is another accordion menu (no.2). The size of accordion no.2 will be defined by the user (an example of the outcome is shown in this image). <a href="https://i.stack.imgur.com/VDjs6.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/VDjs6.jpg" alt="enter image description here"></a></p> <p>The issue is that though I have managed to create a class that creates accordion no.2 following users input - I can`t seem to find the way to display it on the screen. </p> <p>This is my py code:</p> <pre><code>from kivy.app import App from kivy.uix.label import Label from kivy.uix.gridlayout import GridLayout from kivy.uix.textinput import TextInput from kivy.uix.accordion import Accordion, AccordionItem from kivy.properties import NumericProperty wide = 0 long = 0 class AccordionClass(): def calc(val): number = val root = Accordion(size= (200,700), pos = (50,80), orientation= 'vertical') for x in range(number): print ('x = ',x) item = AccordionItem(title='Title %d' % x) item.add_widget(Label(text='Very big content\n' * 10)) root.add_widget(item) print ('END') return root class LoginScreen(GridLayout): numOfStories = NumericProperty() def printTxt(self, text, TextInputId): pass def addFloor(self,text): self.numOfStories = int(text) print ('self.numOfStories = ', self.numOfStories) rootAc = AccordionClass.calc(self.numOfStories) return rootAc pass class screen2(App): def build(self): self.root = GridLayout() return LoginScreen() if __name__ == "__main__": screen2().run() </code></pre> <p>and my kv code:</p> <pre><code>&lt;TextInput&gt;: multiline: False size:150,23 font_size: 12 padding: [5, ( self.height - self.line_height ) / 2] &lt;Label&gt;: size:120,18 font_size: 12 padding: [5, ( self.height - self.line_height ) / 2] &lt;LoginScreen&gt;: canvas: Color: rgb: (0.93, 0.93, 0.93,1) Rectangle: pos: self.pos size: self.size GridLayout: size:root.size cols:2 Accordion: size_hint: (1.0,0.2) orientation: 'vertical' AccordionItem: title: 'Plot' GridLayout: AccordionItem: title: 'Number' GridLayout: Label: text: "Number" color: [0, 0, 0, 1] pos:root.x, root.top-self.height-100 TextInput: pos:root.x+120, root.top-self.height-100 id: NumOfStories on_text_validate: root.addFloor(NumOfStories.text) AccordionItem: title: 'Another number' Button: background_color: (5,5,5,1) </code></pre> <p>Any idea how to solve this issue? Thanks</p>
0
2016-10-13T14:34:37Z
40,039,164
<p>It isn't displaying because of you returning an instance of <code>Accordion</code> into nothing in <code>addFloor</code>/<code>calc</code> in <code>on_text_validate</code>. To create a widget you have to call <code>&lt;parent&gt;.add_widget(&lt;widget&gt;)</code>, so let's do that:</p> <pre><code>on_text_validate: root.add_widget(root.addFloor(NumOfStories.text)) </code></pre> <p>Then there's the thing your <code>calc()</code> is a class method for now and you either need to use <code>self</code> as an additional parameter (and have even more mess), or use the <code>@staticmethod</code> decorator, which makes the <code>calc()</code> free of class stuff and let you use it this way <code>Class.method(...)</code></p> <pre><code>@staticmethod def calc(val): </code></pre> <p>After that a new <code>Accordion</code> will show up, but the sizing and positioning is up to you. Also, by default there's probably no background for that widget, so you'll end up with putting it there via <a href="https://kivy.org/docs/api-kivy.graphics.html" rel="nofollow">canvas instructions</a>.</p>
1
2016-10-14T09:04:00Z
[ "python", "kivy", "kivy-language" ]
Is decorators in python example of monkey patching technique?
40,023,987
<p>Recently I was reading about monkey patching technique and wondered if it can be said.</p>
0
2016-10-13T14:35:02Z
40,024,454
<p>Decorator = a function that takes a function as an argument and returns a function</p> <p>Monkey patching = replacing a value of a field on an object with a different value (not necessarly functions)</p> <p>In case of functions monkey patching can be performed via a decorator. So I guess decorator might be thought as an example of monkey patching. However commonly monkey patching refers to altering behaviour of a 3rd party library. In that case decorators are less useful.</p>
3
2016-10-13T14:55:08Z
[ "python", "monkeypatching" ]
Is decorators in python example of monkey patching technique?
40,023,987
<p>Recently I was reading about monkey patching technique and wondered if it can be said.</p>
0
2016-10-13T14:35:02Z
40,024,979
<p>I suppose on some grammatical level they may be equivalent. However, decorators are applied at the time a function or class is defined, and monkeypatching modifies an object at runtime, making them very different both in spirit and in actual use. </p>
1
2016-10-13T15:19:52Z
[ "python", "monkeypatching" ]
Multithreading to handling multiple incoming requests
40,024,016
<p>I am new to python. And I have to write a listener/server which will handle requests coming from same network. So I am using <code>socket</code>. I will be getting request json from client, server/listener will do processing and return the result. Thats all what is going to happen. And there will be no back and forth communication between server and client.</p> <p>The code looks something like this:</p> <pre><code>sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('localhost', 10000) sock.bind(server_address) sock.listen(1) while True: connection, client_address = sock.accept() while True: #read request data #process request #reply response to **connection** object break #continue waiting for new request </code></pre> <p>Now the issue is that until the current request's processing is done, server will not accept new request. I somehow have to perform processing and sending response reply in separate concurrent thread. I tried by encapsulating the processing logic in separate class <code>RequestHandler</code> extending the <code>Thread</code> class. I passed <code>connection</code> object to the instance of my custom class <code>RequestHandler</code>. I did something like this:</p> <pre><code>requestHandler = RequestHandler(deepcopy(connection)) requestHandler.daemon = True requestHandler.start() </code></pre> <p>However here is where I have stuck. Can I pass same <code>connection</code> object to new instances <code>RequestHandler</code> spawned each time I receive new request? Deep copying as in above code gave me following error:</p> <pre><code>TypeError: Cannot serialize socket object </code></pre> <p>I am doing something absolutely wrong? Should I follow some different approach? </p>
0
2016-10-13T14:36:39Z
40,024,179
<p>No need to extend <code>Thread</code> class. The simpliest version is this:</p> <pre><code>import threading def client_handler(connection): #read request data #process request #reply response to **connection** object sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('localhost', 10000) sock.bind(server_address) sock.listen(1) while True: connection, client_address = sock.accept() threading.Thread(target=client_handler, args=(connection,)).start() </code></pre> <p>Now you may wrap your socket object into <code>RequestHandler</code> class if you wish, that's fine. But you can't copy sockets. Just pass a reference instead: <code>RequestHandler(connection)</code>. Why would you copy it anyway?</p> <p>The reason it is not copyable is because it represents some system resource (i.e. the socket). If there were 2 objects pointing at the same resource then they would conflict with each other. And at C level it is extremely hard to synchronize pure file descriptors (sockets are simply numbers at C level) if there are multiple owners. So socket object is a sort of a unique "gateway" to the underlying file descriptor.</p>
0
2016-10-13T14:43:47Z
[ "python", "multithreading", "sockets" ]
How does Django's `url` template tag reverse a Regex?
40,024,017
<p>How does Django's <code>url</code> template tag work? What magic does it use under the covers to "reverse" a regex?</p> <p>You give it a regex like this:</p> <pre><code>urlpatterns = [ # ex: /polls/5/ url(r'^(?P&lt;question_id&gt;[0-9]+)/$', views.detail, name='detail'), ] </code></pre> <p>... and then in your template you can generate a URL that matches that pattern like this:</p> <pre><code>&lt;a href="{% url 'detail' question.id %}"&gt;{{ question.question_text }}&lt;/a&gt; </code></pre> <p>How does that work? Normally a regex is used to <strong>parse</strong> text, not <strong>generate</strong> it. Are there built-in tools in the <code>re</code> module that provide this functionality?</p> <p>My question is not about how to use Django, or how to parse text with a Regex. Instead I'm interested in learning how I can use regular expressions in this "string template" way elsewhere.</p>
2
2016-10-13T14:36:46Z
40,024,499
<p>The key to reversing the regex is the <a href="https://github.com/django/django/blob/master/django/utils/regex_helper.py#L50" rel="nofollow"><code>normalize()</code></a> function, which takes a regex and returns a list of possibilities. Each possibility is a tuple of a placeholder string and a list of parameters. </p> <p>The <code>reverse()</code> function first checks if the parameters match the list of parameters for the placeholder. If it matches, the placeholder string is formatted with the arguments passed to <code>reverse()</code> (with a simple <code>'string' % parameters</code>). This string is then matched against the original regex. That's necessary because the parameters for the placeholder string don't have any restrictions, so checking against the original regex ensures that e.g. a group with <code>\d+</code> only contains numbers. </p> <p>If a string formatted with the passed parameters matches the original regex, it's a valid url, and returned. </p>
2
2016-10-13T14:57:22Z
[ "python", "regex", "django" ]
Finding Max Shape of Multiple .npz files
40,024,118
<p>I have a number of .npz files that potentially vary in shape and I'd like to find which file has the larges shape. The npzs have 2 arrays within in them, and I'm looking for the largest of the 2nd. The following snippet works, but it takes longer than I expected to return shapes. Is this the most efficient way of achieving this? I'm worried about scaling because it currently takes a couple seconds to find the max shape[1] and I'm only looping through 4 arrays</p> <pre><code>frameMax =0 for f in npzs: d = np.load(f,mmap_mode='r') if d['arr_0'].shape[1]&gt;frameMax: frameMax = d['arr_0'].shape[1] d=None </code></pre>
1
2016-10-13T14:41:13Z
40,024,277
<p>Bear in mind that I/O operations might be relatively slow. That said, you can reduce the logic for finding the maximum to the following using the builtin <a href="https://docs.python.org/2/library/functions.html#max" rel="nofollow"><code>max</code></a> which will run in <a href="http://stackoverflow.com/questions/5454030/how-efficient-is-pythons-max-function">O(n)</a> time, and removes the need for the assignments you did:</p> <pre><code>frameMax = max([np.load(f,mmap_mode='r')['arr_0'].shape[1] for f in npzs]) </code></pre>
1
2016-10-13T14:47:30Z
[ "python", "numpy" ]
Creating dynamic URLS by concatenating strings rises UnicodeEncodeError
40,024,266
<p>I am trying to build my urls dynamically upon my project execution, it retrieves all my projects and concatenates the strings to create the urls like following:</p> <pre><code>for project in projects: domain = Settings.objects.get(id_project=project).site_domain urlpatterns += patterns('', (r'^'+project.type+r'/'+project.name+r'/', include('apps.'+project.type+'.urls'))) </code></pre> <p>The problem is that django is generating me this error: </p> <blockquote> <p>UnicodeEncodeError: 'ascii' codec can't encode character u'\xf3' in position 144: ordinal not in range(128)</p> </blockquote> <p>and when I take a look at the stack, there is nowhere pointing to my code.. I believe it has a relation to the <code>r'^'</code> which could be a different type of encoding, but I couldn't find resources to draw any conclusion.</p> <p>Any help is extremely appreciated</p>
0
2016-10-13T14:47:05Z
40,024,660
<p>Is that <code>patterns</code> a typo? </p> <pre><code>for project in projects: domain = Settings.objects.get(id_project=project).site_domain urlpatterns += url(r'^'+project.type+r'/'+project.name+r'/', include('apps.'+project.type+'.urls')) </code></pre>
1
2016-10-13T15:05:40Z
[ "python", "django", "django-urls", "url-pattern" ]
Pandas data frame combine rows
40,024,294
<p>My problem is a large data frame which I would like to clear out. The two main problems for me are: </p> <ol> <li><p>The whole data frame is time-based. That means I can not shift rows around, otherwise, the timestamp wouldn't fit anymore.</p></li> <li><p>The data is not always in the same order.</p></li> </ol> <p>Here is an example to clarify</p> <pre><code>index a b c d x1 x2 y1 y2 t 0 1 2 0.2 1 1 2 0.4 2 2 4 0.6 3 1 2 1.8 4 2 3 2.0 5 1 2 3.8 6 2 3 4.0 7 2 5 4.2 </code></pre> <p>The result should be looking like this</p> <pre><code>index a b c d x1 x2 y1 y2 t 0 1 2 2 4 0.2 1 1 2 0.4 3 1 2 2 3 1.8 5 1 2 2 3 3.8 7 2 5 4.2 </code></pre> <p>This means I would like, to sum up, the right half of the df and keep the timestamp of the first entry. The second problem is, there might be different data from the left half of the df in between. </p>
2
2016-10-13T14:48:10Z
40,026,199
<p>This may not be the most general solution, but it solves your problem:</p> <p><strong>First</strong>, isolate the right half:</p> <pre><code>r = df[['x1', 'x2', 'y1', 'y2']].dropna(how='all') </code></pre> <p><strong>Second</strong>, use <code>dropna</code> applied column by column to compress the data:</p> <pre><code>r_compressed = r.apply( lambda g: g.dropna().reset_index(drop=True), axis=0 ).set_index(r.index[::2]) </code></pre> <p>You need to drop the index otherwise pandas will attempt to realign the data. The original index is reapplied at the end (but only with every second index label) to facilitate reinsertion of the left half and the <code>t</code> column.</p> <p>Output (note the index values):</p> <pre><code> x1 x2 y1 y2 0 1.0 2.0 2.0 4.0 3 1.0 2.0 2.0 3.0 5 1.0 2.0 2.0 3.0 </code></pre> <p><strong>Third</strong>, isolate left half:</p> <pre><code>l = df[['a', 'b', 'c', 'd']].dropna(how='all') </code></pre> <p><strong>Fourth</strong>, incorporate the left half and <code>t</code> column to compressed right half:</p> <pre><code>out = r_compressed.combine_first(l) out['t'] = df['t'] </code></pre> <p>Output:</p> <pre><code> a b c d x1 x2 y1 y2 t 0 NaN NaN NaN NaN 1.0 2.0 2.0 4.0 0.2 1 1.0 2.0 NaN NaN NaN NaN NaN NaN 0.4 3 NaN NaN NaN NaN 1.0 2.0 2.0 3.0 1.8 5 NaN NaN NaN NaN 1.0 2.0 2.0 3.0 3.8 7 NaN NaN 2.0 5.0 NaN NaN NaN NaN 4.2 </code></pre>
0
2016-10-13T16:19:57Z
[ "python", "python-3.x", "pandas", "dataframe", "spyder" ]
Keeping columns in the specified order when using UseCols in Pandas Read_CSV
40,024,406
<p>I have a csv file with 50 columns of data. I am using Pandas read_csv function to pull in a subset of these columns, using the usecols parameter to choose the ones I want:</p> <pre><code>cols_to_use = [0,1,5,16,8] df_ret = pd.read_csv(filepath, index_col=False, usecols=cols_to_use) </code></pre> <p>The trouble is df_ret contains the correct columns, but not in the order I specified. They are in ascending order, so [0,1,5,8,16]. (By the way the column numbers can change from run to run, this is just an example.) This is a problem because the rest of the code has arrays which are in the "correct" order and I would rather not have to reorder all of them. </p> <p>Is there any clever pandas way of pulling in the columns in the order specified? Any help would be much appreciated!</p>
2
2016-10-13T14:53:12Z
40,024,462
<p>you can reuse the same <code>cols_to_use</code> list for selecting columns in desired order:</p> <pre><code>df_ret = pd.read_csv(filepath, index_col=False, usecols=cols_to_use)[cols_to_use] </code></pre>
3
2016-10-13T14:55:27Z
[ "python", "pandas", "dataframe" ]
Ordered/Prioritized return of a regular expression
40,024,526
<p>I have the following group of possible values that can appear in a field of a DataFrame (extract from a database):</p> <p>(N2|N1|N11|N12|N3|N4|N6|N10|N13|N5|N7|N8|N9)</p> <p>The field can contain any of the above in any combination, for example:</p> <p>"N1, N6, N9"</p> <p>I want to extract from every element of the field <strong>only</strong> the one with highest "rank" meaning N9>N8>N7>N5... according to the order of my group above.</p> <p>So from the example it would return "N9". For "N1, N3, N11" it would return "N3".</p> <p>Is this possible with RegEx? I am using Python/Pandas on this.</p> <p>Thanks a lot in advance!</p>
1
2016-10-13T14:59:10Z
40,025,075
<p>Considering you have a dataframe <code>df</code> with your column of data named <code>data</code>, here is a simple way without using regex. Split the strings into columns, then sort the resulting list and take the first element:</p> <pre><code>df.data.str.split(',').apply(lambda l: sorted(l, reverse=True)[0]) Out[7]: 0 N9 1 N3 Name: data, dtype: object </code></pre>
1
2016-10-13T15:24:25Z
[ "python", "regex", "pandas" ]
Pairing Elements w/o Repeating
40,024,544
<p>I am close to figuring out this problem but am hung on one one thing in particular. I am trying to pair/zip together elements in a list pair by pair, and then checking which value is greater. I just can't figure out how to pair these elements without repeating values. </p> <pre><code>[35,10,5,3,1,26,15] </code></pre> <p>I do NOT want:</p> <pre><code>[35,10], [10,5] </code></pre> <p>I DO want:</p> <pre><code>[35,10], [5,3] </code></pre> <p>Here is my code:</p> <pre><code>def queue_time(customers, n): time_left = 0 max_val = max(customers[:n]) total_time = int(max_val) other_customers = list(customers) other_customers.remove(max_val) for idx, el in enumerate(other_customers): if max_val &gt; 0: nxt_till_times = other_customers[idx:idx+n-1] max_other_tills = max(nxt_till_times) max_val -= max_other_tills print nxt_till_times elif max_val == 0: max_val = max(customers[idx:idx+n]) total_time += max_val elif max_val &lt; 0: time_left = [-1*(max_val)] others_still = time_left + customers[idx+1:] max_val = max(others_still[:n]) total_time += max_val #print total_time return total_time queue_time([35,10,5,3,1,26,15], 3) </code></pre>
0
2016-10-13T15:00:10Z
40,024,738
<pre><code>l = [35,10,5,3,1,26,15] g = (i for i in l) output = [(next(g), next(g)) for i in range(len(l)//2)] </code></pre> <p><code>g</code> is a generator. This doesn't do anything with the last element of odd-length lists. That element is available at <code>next(g)</code></p>
0
2016-10-13T15:09:13Z
[ "python", "indexing", "pair" ]
Pairing Elements w/o Repeating
40,024,544
<p>I am close to figuring out this problem but am hung on one one thing in particular. I am trying to pair/zip together elements in a list pair by pair, and then checking which value is greater. I just can't figure out how to pair these elements without repeating values. </p> <pre><code>[35,10,5,3,1,26,15] </code></pre> <p>I do NOT want:</p> <pre><code>[35,10], [10,5] </code></pre> <p>I DO want:</p> <pre><code>[35,10], [5,3] </code></pre> <p>Here is my code:</p> <pre><code>def queue_time(customers, n): time_left = 0 max_val = max(customers[:n]) total_time = int(max_val) other_customers = list(customers) other_customers.remove(max_val) for idx, el in enumerate(other_customers): if max_val &gt; 0: nxt_till_times = other_customers[idx:idx+n-1] max_other_tills = max(nxt_till_times) max_val -= max_other_tills print nxt_till_times elif max_val == 0: max_val = max(customers[idx:idx+n]) total_time += max_val elif max_val &lt; 0: time_left = [-1*(max_val)] others_still = time_left + customers[idx+1:] max_val = max(others_still[:n]) total_time += max_val #print total_time return total_time queue_time([35,10,5,3,1,26,15], 3) </code></pre>
0
2016-10-13T15:00:10Z
40,024,835
<p>Even simpler:</p> <pre><code>&gt;&gt;&gt; l = [35,10,5,3,1,26,15] &gt;&gt;&gt; [l[i:i+2] for i in range(0, len(l)-1, 2)] [[35, 10], [5, 3], [1, 26]] </code></pre> <p>This will cut off any odd-numbered elements of the list.</p>
1
2016-10-13T15:14:19Z
[ "python", "indexing", "pair" ]
Optimize a transformation from a 2-dim numpy array with day of the year values (doy) into an array with date values
40,024,548
<p>Does anyone know how to optimize a transformation from a 2-dim numpy array with day of the year values (doy) into an array with date values? The function below works but unfortunately in an very inelegant way. I would be very happy if anyone has a good idea how to avoid the loop over the 2-dim array which should make the calculation faster for large datesets. </p> <pre><code>import datetime from datetime import date #test 2-dim array with doy values doy = np.array([[272, 272], [274, 274]]) #define start and end date startdat = datetime.datetime.strptime('2012 10 01 0000', '%Y %m %d %H%M') year_start = int(startdat.strftime('%Y')) enddat = datetime.datetime.strptime('2013 09 30 0000', '%Y %m %d %H%M') year_end = int(enddat.strftime('%Y')) #initialise an tmp array res_date = np.zeros([2,2]) #transform doy into date for x in range(2): for y in range(2): if doy[x,y] &gt;= 274 and doy[x,y] &lt;= 365: datum = date.fromordinal(date(year_start, 1, 1).toordinal() + doy[x,y]) datum = datum.strftime('%Y%m%d') res_date[x,y]= datum else: datum = date.fromordinal(date(year_end, 1, 1).toordinal() + doy[x,y]) datum = datum.strftime('%Y%m%d') res_date[x,y]= datum #that's my result #res_date = array([[ 20130930., 20130930.], #[ 20121001., 20121001.]]) </code></pre>
1
2016-10-13T15:00:13Z
40,032,051
<p>you can do this kind of thing</p> <pre><code>offset = (datetime.datetime(2013, 9, 30) - datetime.datetime(2012, 12, 31)).days yearlen = (datetime.datetime(2013, 1, 1) - datetime.datetime(2012, 1, 1)).days doy[doy &gt;= offset] -= yearlen dates = np.datetime64('2013-01-01') + doy </code></pre> <p>but to extract YMD from the datetime64 values is a bit tricky. The consensus is to use pandas. Why do you need the array to be in that format?</p> <p>EDIT, I've added the calculation yearlen but I haven't thought through all the permutations, you probably need to check that with a calendar!</p> <p>Further EDIT. From your next phrasing of the question your doy looks to be simply days from 2011,9,30 (or from 2011,10,1 minus 1). i.e.</p> <pre><code>import numpy as np import datetime #counting the doys from the 1. of October to the 30 of September doy = np.array([[152, 4], [7, 93]]) #read start and enddat startdat = datetime.datetime(2011,10,1) dates = np.datetime64(startdat).astype('datetime64[D]') + doy - 1 print(dates) #array([['2012-02-29', '2011-10-04'], # ['2011-10-07', '2012-01-01']], dtype='datetime64[D]') </code></pre>
0
2016-10-13T22:26:49Z
[ "python", "arrays", "datetime" ]
Keras - Generator for large dataset of Images and Masks
40,024,619
<p>I'm trying to build a Model that has Images for both its Inputs and Outputs (masks). Because of the size of the Dataset and my limited Memory, I tried using <a href="https://keras.io/preprocessing/image/" rel="nofollow">the Generator Approach introduced in the Keras Documentation</a>:</p> <pre><code># Provide the same seed and keyword arguments to the fit and flow methods seed = 1 image_generator = image_datagen.flow_from_directory( 'data/images', class_mode=None, seed=seed) mask_generator = mask_datagen.flow_from_directory( 'data/masks', class_mode=None, seed=seed) # combine generators into one which yields image and masks train_generator = zip(image_generator, mask_generator) model.fit_generator( train_generator, samples_per_epoch=2000, nb_epoch=50) </code></pre> <p>Everything seems to work except when the code gets to this line:</p> <pre><code>train_generator = zip(image_generator, mask_generator) </code></pre> <p>it seems the process of zipping the two lists explicitly makes them generate their content and the system starts consuming lots of RAM until it runs out of Memory. </p> <p>The point of using Generators is to avoid running out of RAM while this piece of code is exactly doing the opposite.</p> <p>Is there any way to fix this problem?</p>
1
2016-10-13T15:03:38Z
40,025,498
<p>You can user <code>itertools.izip()</code> to return an iterator instead of a list.</p> <pre><code>itertools.izip(*iterables) Make an iterator that aggregates elements from each of the iterables. Like zip() except that it returns an iterator instead of a list. Used for lock-step iteration over several iterables at a time. </code></pre>
2
2016-10-13T15:44:54Z
[ "python", "machine-learning", "computer-vision", "theano", "keras" ]
Logic to jump weekends Django/python
40,024,627
<p>I got this function. What I need is to make some changes in my model depending on the day. As my if statements shown below, if the "ddate" is today or tomorrow make some changes in my "pull_ins" column and set it up as "Ready to ship" but if is the day after tomorrow and the next day, set "Not yet". This is working but my problem is that I need to jump weekends and keep the 4 days logic, any ideas? </p> <p>As an example if today is Thrusday to get the ddate from today, tomorrow(friday) -----jump weekend --- monday, tuesday.</p> <p>This is what I got:</p> <pre><code>def Ship_status(): week = {0, 1, 2, 3, 4} deltaday = timedelta(days=1) today = datetime.now().date() day = today day1 = day + deltaday day2 = day1 + deltaday day3 = day2 + deltaday for i in Report.objects.all(): if i.ddate.weekday() in week: if i.ddate == day: i.pull_ins = "Ready to ship" i.save() if i.date == day1: i.pull_ins = "Ready to ship" i.save() if i.date == day2: i.pull_ins = "Not yet" i.save() if i.date == day3: i.pull_ins = "not yet" i.save() </code></pre> <p>Thanks for your time.</p>
0
2016-10-13T15:04:08Z
40,025,448
<p><a href="http://labix.org/python-dateutil#head-470fa22b2db72000d7abe698a5783a46b0731b57" rel="nofollow"><code>dateutil.rrule</code></a> is library you could leverage. To get the next weekday:</p> <pre><code>from dateutil import rrule next_weekday = rrule.rrule(rrule.DAILY, count=3, byweekday=(0, 1, 2, 3, 4), dtstart=dt)) </code></pre> <p>So, in your query, you could do something like this:</p> <pre><code>def compute_shipping(dt=datetime.datetime.date(), count=2): next_weekdays = rrule.rrule(rrule.DAILY, count=count, byweekday=(0, 1, 2, 3, 4), dtstart=dt)) return list(next_weekdays) #Ready to ship Report.objects.filter(ddate__in=compute_shipping()).update(pull_ins="Ready to ship") #For Not yet #Query would be similar - just set the appropriate start date </code></pre>
1
2016-10-13T15:42:10Z
[ "python", "django", "python-2.7", "datetime", "weekday" ]
Regular expression to match a specific pattern
40,024,643
<p>I have the following string:</p> <pre><code>s = "&lt;X&gt; First &lt;Y&gt; Second" </code></pre> <p>and I can match any text right after <code>&lt;X&gt;</code> and <code>&lt;Y&gt;</code> (in this case "First" and "Second"). This is how I already did it:</p> <pre><code>import re s = "&lt;X&gt; First &lt;Y&gt; Second" pattern = r'\&lt;([XxYy])\&gt;([^\&lt;]+)' # lower and upper case X/Y will be matched items = re.findall(pattern, s) print items &gt;&gt;&gt; [('X', ' First '), ('Y', ' Second')] </code></pre> <p>What I am now trying to match is the case without <code>&lt;&gt;</code>:</p> <pre><code>s = "X First Y Second" </code></pre> <p>I tried this:</p> <pre><code>pattern = r'([XxYy]) ([^\&lt;]+)' &gt;&gt;&gt; [('X', ' First Y Second')] </code></pre> <p>Unfortunately it's not producing the right result. What am I doing wrong? I want to match X or x or Y or y PLUS one whitespace (for instance "X "). How can I do that?</p> <p>EDIT: this is a possible string too:</p> <pre><code>s = "&lt;X&gt; First one &lt;Y&gt; Second &lt;X&gt; More &lt;Y&gt; Text" </code></pre> <p>Output should be:</p> <pre><code> &gt;&gt;&gt; [('X', ' First one '), ('Y', ' Second '), ('X', ' More '), ('Y', ' Text')] </code></pre> <p>EDIT2:</p> <pre><code>pattern = r'([XxYy]) ([^ ]+)' s = "X First text Y Second" </code></pre> <p>produces:</p> <pre><code>[('X', 'First'), ('Y', 'Second')] </code></pre> <p>but it should be:</p> <pre><code>[('X', 'First text'), ('Y', 'Second')] </code></pre>
1
2016-10-13T15:04:39Z
40,024,784
<p>If you know which whitespace char to match, you can just add it to your expression. If you want any whitespace to match, you can use \s</p> <pre><code>pattern = r'\&lt;([XxYy])\&gt;([^\&lt;]+)' </code></pre> <p>would then be</p> <pre><code>pattern = r'\&lt;([XxYy])\&gt;\s([^\&lt;]+)' </code></pre> <p>Always keep in mind the the expression within the () is what will be returned as your result.</p>
1
2016-10-13T15:11:36Z
[ "python", "regex" ]
Regular expression to match a specific pattern
40,024,643
<p>I have the following string:</p> <pre><code>s = "&lt;X&gt; First &lt;Y&gt; Second" </code></pre> <p>and I can match any text right after <code>&lt;X&gt;</code> and <code>&lt;Y&gt;</code> (in this case "First" and "Second"). This is how I already did it:</p> <pre><code>import re s = "&lt;X&gt; First &lt;Y&gt; Second" pattern = r'\&lt;([XxYy])\&gt;([^\&lt;]+)' # lower and upper case X/Y will be matched items = re.findall(pattern, s) print items &gt;&gt;&gt; [('X', ' First '), ('Y', ' Second')] </code></pre> <p>What I am now trying to match is the case without <code>&lt;&gt;</code>:</p> <pre><code>s = "X First Y Second" </code></pre> <p>I tried this:</p> <pre><code>pattern = r'([XxYy]) ([^\&lt;]+)' &gt;&gt;&gt; [('X', ' First Y Second')] </code></pre> <p>Unfortunately it's not producing the right result. What am I doing wrong? I want to match X or x or Y or y PLUS one whitespace (for instance "X "). How can I do that?</p> <p>EDIT: this is a possible string too:</p> <pre><code>s = "&lt;X&gt; First one &lt;Y&gt; Second &lt;X&gt; More &lt;Y&gt; Text" </code></pre> <p>Output should be:</p> <pre><code> &gt;&gt;&gt; [('X', ' First one '), ('Y', ' Second '), ('X', ' More '), ('Y', ' Text')] </code></pre> <p>EDIT2:</p> <pre><code>pattern = r'([XxYy]) ([^ ]+)' s = "X First text Y Second" </code></pre> <p>produces:</p> <pre><code>[('X', 'First'), ('Y', 'Second')] </code></pre> <p>but it should be:</p> <pre><code>[('X', 'First text'), ('Y', 'Second')] </code></pre>
1
2016-10-13T15:04:39Z
40,024,857
<p>Assuming that a the whitespace token to match is a single space character, the pattern is:</p> <pre><code>pattern = r'([XxYy]) ([^ ]+)' </code></pre>
1
2016-10-13T15:15:12Z
[ "python", "regex" ]
Regular expression to match a specific pattern
40,024,643
<p>I have the following string:</p> <pre><code>s = "&lt;X&gt; First &lt;Y&gt; Second" </code></pre> <p>and I can match any text right after <code>&lt;X&gt;</code> and <code>&lt;Y&gt;</code> (in this case "First" and "Second"). This is how I already did it:</p> <pre><code>import re s = "&lt;X&gt; First &lt;Y&gt; Second" pattern = r'\&lt;([XxYy])\&gt;([^\&lt;]+)' # lower and upper case X/Y will be matched items = re.findall(pattern, s) print items &gt;&gt;&gt; [('X', ' First '), ('Y', ' Second')] </code></pre> <p>What I am now trying to match is the case without <code>&lt;&gt;</code>:</p> <pre><code>s = "X First Y Second" </code></pre> <p>I tried this:</p> <pre><code>pattern = r'([XxYy]) ([^\&lt;]+)' &gt;&gt;&gt; [('X', ' First Y Second')] </code></pre> <p>Unfortunately it's not producing the right result. What am I doing wrong? I want to match X or x or Y or y PLUS one whitespace (for instance "X "). How can I do that?</p> <p>EDIT: this is a possible string too:</p> <pre><code>s = "&lt;X&gt; First one &lt;Y&gt; Second &lt;X&gt; More &lt;Y&gt; Text" </code></pre> <p>Output should be:</p> <pre><code> &gt;&gt;&gt; [('X', ' First one '), ('Y', ' Second '), ('X', ' More '), ('Y', ' Text')] </code></pre> <p>EDIT2:</p> <pre><code>pattern = r'([XxYy]) ([^ ]+)' s = "X First text Y Second" </code></pre> <p>produces:</p> <pre><code>[('X', 'First'), ('Y', 'Second')] </code></pre> <p>but it should be:</p> <pre><code>[('X', 'First text'), ('Y', 'Second')] </code></pre>
1
2016-10-13T15:04:39Z
40,024,973
<p>How about something like: <code>&lt;?[XY]&gt;? ([^&lt;&gt;XY$ ]+)</code></p> <p>Example in javascript:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const re = /&lt;?[XY]&gt;? ([^&lt;&gt;XY$ ]+)/ig console.info('&lt;X&gt; First &lt;Y&gt; Second'.match(re)) console.info('X First Y Second'.match(re))</code></pre> </div> </div> </p>
3
2016-10-13T15:19:38Z
[ "python", "regex" ]
Regular expression to match a specific pattern
40,024,643
<p>I have the following string:</p> <pre><code>s = "&lt;X&gt; First &lt;Y&gt; Second" </code></pre> <p>and I can match any text right after <code>&lt;X&gt;</code> and <code>&lt;Y&gt;</code> (in this case "First" and "Second"). This is how I already did it:</p> <pre><code>import re s = "&lt;X&gt; First &lt;Y&gt; Second" pattern = r'\&lt;([XxYy])\&gt;([^\&lt;]+)' # lower and upper case X/Y will be matched items = re.findall(pattern, s) print items &gt;&gt;&gt; [('X', ' First '), ('Y', ' Second')] </code></pre> <p>What I am now trying to match is the case without <code>&lt;&gt;</code>:</p> <pre><code>s = "X First Y Second" </code></pre> <p>I tried this:</p> <pre><code>pattern = r'([XxYy]) ([^\&lt;]+)' &gt;&gt;&gt; [('X', ' First Y Second')] </code></pre> <p>Unfortunately it's not producing the right result. What am I doing wrong? I want to match X or x or Y or y PLUS one whitespace (for instance "X "). How can I do that?</p> <p>EDIT: this is a possible string too:</p> <pre><code>s = "&lt;X&gt; First one &lt;Y&gt; Second &lt;X&gt; More &lt;Y&gt; Text" </code></pre> <p>Output should be:</p> <pre><code> &gt;&gt;&gt; [('X', ' First one '), ('Y', ' Second '), ('X', ' More '), ('Y', ' Text')] </code></pre> <p>EDIT2:</p> <pre><code>pattern = r'([XxYy]) ([^ ]+)' s = "X First text Y Second" </code></pre> <p>produces:</p> <pre><code>[('X', 'First'), ('Y', 'Second')] </code></pre> <p>but it should be:</p> <pre><code>[('X', 'First text'), ('Y', 'Second')] </code></pre>
1
2016-10-13T15:04:39Z
40,025,288
<p>So i came up with this solution:</p> <pre><code>pattern = r"([XxYy]) (.*?)(?= [XxYy] |$)" </code></pre>
0
2016-10-13T15:34:37Z
[ "python", "regex" ]
if statment not responding (python)
40,024,656
<p>the if statement is not responding. I'm trying to get the <code>gcd(20,6)</code> the program outputs: <code>gcd(20,6): 20=6(4) + -3</code>, I need it to be if the last number(-3) is less than 0 the the program should output <code>20=6(3) + 3</code>,but the if statement isn't responding. thanks</p> <pre><code>rnumtup = (20, 6) if rnumtup[0] &gt; rnumtup[1]: x= rnumtup[1] y =rnumtup[0] w = x / y w = round(w) z = x - (y*w) z = round(z) while z != 0: x = y y = z w = x / y w = round(w) z = x - (y*w) z = round(z) if z &gt; 0: #not responding #some statements if z &lt; 0: #not responding #some statements </code></pre>
-1
2016-10-13T15:05:24Z
40,024,774
<p><code>z</code> is equal to <code>0</code>, so your <code>if</code> statements aren't doing anything.</p> <p>Explanation in the code comments</p> <pre><code>rnumtup = (20, 6) if rnumtup[0] &gt; rnumtup[1]: x= rnumtup[1] #x = 20 y =rnumtup[0] #y = 6 w = x / y #w = 3 w = round(w) # Does nothing z = x - (y*w) # z = 2 z = round(z) # Does nothing while z != 0: x = y # x = 6 y = z # y = 2 w = x / y # w = 3 w = round(w) # Does nothing z = x - (y*w) # z = 0 --&gt; If statements don't work, while loop ends after first iteration z = round(z) if z &gt; 0: #not responding, because z == 0 #some statements if z &lt; 0: #not responding, because z == 0 #some statements </code></pre> <p>Note that in python <code>20/6</code> equals <code>3</code>, but <code>20.0/6</code> equals <code>3.33333..</code></p>
0
2016-10-13T15:11:11Z
[ "python" ]
if statment not responding (python)
40,024,656
<p>the if statement is not responding. I'm trying to get the <code>gcd(20,6)</code> the program outputs: <code>gcd(20,6): 20=6(4) + -3</code>, I need it to be if the last number(-3) is less than 0 the the program should output <code>20=6(3) + 3</code>,but the if statement isn't responding. thanks</p> <pre><code>rnumtup = (20, 6) if rnumtup[0] &gt; rnumtup[1]: x= rnumtup[1] y =rnumtup[0] w = x / y w = round(w) z = x - (y*w) z = round(z) while z != 0: x = y y = z w = x / y w = round(w) z = x - (y*w) z = round(z) if z &gt; 0: #not responding #some statements if z &lt; 0: #not responding #some statements </code></pre>
-1
2016-10-13T15:05:24Z
40,025,016
<p>You would think that z cannot be 0 because of </p> <pre><code>while z!=0: </code></pre> <p>but when your program reaches the statement</p> <pre><code>z= round(z) </code></pre> <p>z can be 0 and you program checks only for strictly positive or negative numbers since 0>0 is false, a better gdc function would be <a href="https://en.wikipedia.org/wiki/Euclidean_algorithm" rel="nofollow">euclid's algorithm</a>, here is the python 3 version</p> <pre><code>def gdc(a,b): while a!=b: if a&gt;b: a=a-b else: b=b-a return a print(gdc(20,6)) </code></pre>
0
2016-10-13T15:21:38Z
[ "python" ]
if statment not responding (python)
40,024,656
<p>the if statement is not responding. I'm trying to get the <code>gcd(20,6)</code> the program outputs: <code>gcd(20,6): 20=6(4) + -3</code>, I need it to be if the last number(-3) is less than 0 the the program should output <code>20=6(3) + 3</code>,but the if statement isn't responding. thanks</p> <pre><code>rnumtup = (20, 6) if rnumtup[0] &gt; rnumtup[1]: x= rnumtup[1] y =rnumtup[0] w = x / y w = round(w) z = x - (y*w) z = round(z) while z != 0: x = y y = z w = x / y w = round(w) z = x - (y*w) z = round(z) if z &gt; 0: #not responding #some statements if z &lt; 0: #not responding #some statements </code></pre>
-1
2016-10-13T15:05:24Z
40,025,463
<p>I figured out an alternative, thanks guys :)</p> <pre><code>rnumtup = (20, 6) if rnumtup[0] &gt; rnumtup[1]: x= rnumtup[1] y =rnumtup[0] w = x / y w = round(w) # Does nothing z = x - (y*w) z = round(z) if z&lt; 0: w = x / y w = round(w) w = w-1 z = x - (y*w) z = round(z) while z != 0: x = y # x = 6 y = z # y = 2 w = x / y # w = 3 w = round(w) # Does nothing z = x - (y*w) if z&lt; 0: w = x / y w = round(w) w = w-1 z = x - (y*w) z = round(z) </code></pre>
0
2016-10-13T15:42:55Z
[ "python" ]
Pandas distinct count as a DataFrame
40,024,666
<p>Suppose I have a Pandas DataFrame called <code>df</code> with columns <code>a</code> and <code>b</code> and what I want is the number of distinct values of <code>b</code> per each <code>a</code>. I would do:</p> <pre><code>distcounts = df.groupby('a')['b'].nunique() </code></pre> <p>which gives the desidered result, but it is as Series object rather than another DataFrame. I'd like a DataFrame instead. In regular SQL, I'd do:</p> <pre><code>SELECT a, COUNT(DISTINCT(b)) FROM df </code></pre> <p>and haven't been able to emulate this query in Pandas exactly. How to?</p>
2
2016-10-13T15:05:53Z
40,024,699
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a>:</p> <pre><code>distcounts = df.groupby('a')['b'].nunique().reset_index() </code></pre> <p>Sample:</p> <pre><code>df = pd.DataFrame({'a':[7,8,8], 'b':[4,5,6]}) print (df) a b 0 7 4 1 8 5 2 8 6 distcounts = df.groupby('a')['b'].nunique().reset_index() print (distcounts) a b 0 7 1 1 8 2 </code></pre>
4
2016-10-13T15:07:10Z
[ "python", "sql", "pandas", "count", "distinct" ]
Pandas distinct count as a DataFrame
40,024,666
<p>Suppose I have a Pandas DataFrame called <code>df</code> with columns <code>a</code> and <code>b</code> and what I want is the number of distinct values of <code>b</code> per each <code>a</code>. I would do:</p> <pre><code>distcounts = df.groupby('a')['b'].nunique() </code></pre> <p>which gives the desidered result, but it is as Series object rather than another DataFrame. I'd like a DataFrame instead. In regular SQL, I'd do:</p> <pre><code>SELECT a, COUNT(DISTINCT(b)) FROM df </code></pre> <p>and haven't been able to emulate this query in Pandas exactly. How to?</p>
2
2016-10-13T15:05:53Z
40,024,829
<p>Another alternative using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.agg.html" rel="nofollow"><code>Groupby.agg</code></a> instead:</p> <pre><code>df.groupby('a', as_index=False).agg({'b': 'nunique'}) </code></pre>
3
2016-10-13T15:13:57Z
[ "python", "sql", "pandas", "count", "distinct" ]
Possible to switch between python 2 and 3 in Sublime Text 3 build systems? (Windows)
40,024,713
<p>All my current coding has been in python 3, which I've installed via the Anaconda package. However I need to work on some code simultaneously in python 2. Is there a way I can add a build system in Sublime so I can switch between the two fluidly? I have both python 2 and 3 installed, however can't see a way of simply editing the build system slightly to switch between the two languages. The build system I'm using for python 3 is:</p> <pre><code>{ "cmd": ["python", "-u", "$file"], "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)", "selector": "source.python", "shell": true } </code></pre> <p>Thanks very much!</p>
1
2016-10-13T15:08:12Z
40,031,389
<p>Specify the absolute path to the version of Python. For example, if Python version 3 is located at <code>/usr/bin/python3</code> and Python version 2 is located at <code>/usr/bin/python2</code>:</p> <p>Python 3 Build Configuration:</p> <pre><code>{ "cmd": ["/usr/bin/python3", "-u", "$file"], "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)", "selector": "source.python", "shell": true } </code></pre> <p>Python 2 Build Configuration:</p> <pre><code>{ "cmd": ["/usr/bin/python2", "-u", "$file"], "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)", "selector": "source.python", "shell": true } </code></pre> <p>Find the location of Python via <code>which</code>:</p> <pre><code>$ which python /usr/bin/python $ which python3 /usr/bin/python3 $ which python2 /usr/bin/python2 </code></pre> <p>See <a href="http://stackoverflow.com/a/40004464/934739">Build system of Sublime Text 3 executes a different version of PHP</a>, it is the same principal.</p>
0
2016-10-13T21:34:15Z
[ "python", "sublimetext3" ]
pandas slicing multiindex dataframe
40,024,721
<p>I want to slice a multi-index pandas dataframe</p> <p>here is the code to obtain my test data: </p> <pre><code>import pandas as pd testdf = { 'Name': { 0: 'H', 1: 'H', 2: 'H', 3: 'H', 4: 'H'}, 'Division': { 0: 'C', 1: 'C', 2: 'C', 3: 'C', 4: 'C'}, 'EmployeeId': { 0: 14, 1: 14, 2: 14, 3: 14, 4: 14}, 'Amt1': { 0: 124.39, 1: 186.78, 2: 127.94, 3: 258.35000000000002, 4: 284.77999999999997}, 'Amt2': { 0: 30.0, 1: 30.0, 2: 30.0, 3: 30.0, 4: 60.0}, 'Employer': { 0: 'Z', 1: 'Z', 2: 'Z', 3: 'Z', 4: 'Z'}, 'PersonId': { 0: 14, 1: 14, 2: 14, 3: 14, 4: 15}, 'Provider': { 0: 'A', 1: 'A', 2: 'A', 3: 'A', 4: 'B'}, 'Year': { 0: 2012, 1: 2012, 2: 2013, 3: 2013, 4: 2012}} testdf = pd.DataFrame(testdf) testdf grouper_keys = [ 'Employer', 'Year', 'Division', 'Name', 'EmployeeId', 'PersonId'] testdf2 = pd.pivot_table(data=testdf, values='Amt1', index=grouper_keys, columns='Provider', fill_value=None, margins=False, dropna=True, aggfunc=('sum', 'count'), ) print(testdf2) </code></pre> <p>gives:</p> <p><a href="https://i.stack.imgur.com/FKUWq.png"><img src="https://i.stack.imgur.com/FKUWq.png" alt="enter image description here"></a></p> <p>Now I can get only <code>sum</code> for <code>A</code> or <code>B</code> using </p> <pre><code>testdf2.loc[:, slice(None, ('sum', 'A'))] </code></pre> <p>which gives </p> <p><a href="https://i.stack.imgur.com/kKrZS.png"><img src="https://i.stack.imgur.com/kKrZS.png" alt="enter image description here"></a></p> <p>How can I get <strong>both</strong> <code>sum</code> <strong>and</strong> <code>count</code> for only <code>A</code> or <code>B</code></p>
5
2016-10-13T15:08:27Z
40,024,825
<p>You can use:</p> <pre><code>idx = pd.IndexSlice df = testdf2.loc[:, idx[['sum', 'count'], 'A']] print (df) sum count Provider A A Employer Year Division Name EmployeeId PersonId Z 2012 C H 14 14 311.17 2.0 15 NaN NaN 2013 C H 14 14 386.29 2.0 </code></pre> <p>Another solution:</p> <pre><code>df = testdf2.loc[:, (slice('sum','count'), ['A'])] print (df) sum count Provider A A Employer Year Division Name EmployeeId PersonId Z 2012 C H 14 14 311.17 2.0 15 NaN NaN 2013 C H 14 14 386.29 2.0 </code></pre>
4
2016-10-13T15:13:46Z
[ "python", "pandas", "pivot-table", "data-manipulation", "multi-index" ]
pandas slicing multiindex dataframe
40,024,721
<p>I want to slice a multi-index pandas dataframe</p> <p>here is the code to obtain my test data: </p> <pre><code>import pandas as pd testdf = { 'Name': { 0: 'H', 1: 'H', 2: 'H', 3: 'H', 4: 'H'}, 'Division': { 0: 'C', 1: 'C', 2: 'C', 3: 'C', 4: 'C'}, 'EmployeeId': { 0: 14, 1: 14, 2: 14, 3: 14, 4: 14}, 'Amt1': { 0: 124.39, 1: 186.78, 2: 127.94, 3: 258.35000000000002, 4: 284.77999999999997}, 'Amt2': { 0: 30.0, 1: 30.0, 2: 30.0, 3: 30.0, 4: 60.0}, 'Employer': { 0: 'Z', 1: 'Z', 2: 'Z', 3: 'Z', 4: 'Z'}, 'PersonId': { 0: 14, 1: 14, 2: 14, 3: 14, 4: 15}, 'Provider': { 0: 'A', 1: 'A', 2: 'A', 3: 'A', 4: 'B'}, 'Year': { 0: 2012, 1: 2012, 2: 2013, 3: 2013, 4: 2012}} testdf = pd.DataFrame(testdf) testdf grouper_keys = [ 'Employer', 'Year', 'Division', 'Name', 'EmployeeId', 'PersonId'] testdf2 = pd.pivot_table(data=testdf, values='Amt1', index=grouper_keys, columns='Provider', fill_value=None, margins=False, dropna=True, aggfunc=('sum', 'count'), ) print(testdf2) </code></pre> <p>gives:</p> <p><a href="https://i.stack.imgur.com/FKUWq.png"><img src="https://i.stack.imgur.com/FKUWq.png" alt="enter image description here"></a></p> <p>Now I can get only <code>sum</code> for <code>A</code> or <code>B</code> using </p> <pre><code>testdf2.loc[:, slice(None, ('sum', 'A'))] </code></pre> <p>which gives </p> <p><a href="https://i.stack.imgur.com/kKrZS.png"><img src="https://i.stack.imgur.com/kKrZS.png" alt="enter image description here"></a></p> <p>How can I get <strong>both</strong> <code>sum</code> <strong>and</strong> <code>count</code> for only <code>A</code> or <code>B</code></p>
5
2016-10-13T15:08:27Z
40,024,904
<p>Use <code>xs</code> for cross section</p> <pre><code>testdf2.xs('A', axis=1, level=1) </code></pre> <p><a href="https://i.stack.imgur.com/nx1np.png"><img src="https://i.stack.imgur.com/nx1np.png" alt="enter image description here"></a></p> <p>Or keep the column level with <code>drop_level=False</code></p> <pre><code>testdf2.xs('A', axis=1, level=1, drop_level=False) </code></pre> <p><a href="https://i.stack.imgur.com/tNenr.png"><img src="https://i.stack.imgur.com/tNenr.png" alt="enter image description here"></a></p>
5
2016-10-13T15:17:13Z
[ "python", "pandas", "pivot-table", "data-manipulation", "multi-index" ]
How to add more space in `__str__` method of Django model?
40,024,769
<p>I want to add more spaces to <code>__str__</code> method, but method cut off spaces to 1.</p> <p>For example:</p> <pre><code>class Spam(models.Model): foo = models.IntegerField() bar = models.IntegerField() def __str__(self): return 'more spaces {} {}!'.format(self.foo, self.bar) </code></pre> <p>This output in Django admin: <code>more spaces 1 2</code></p> <p>I want : <code>more spaces 1 2</code></p> <p>How do this?</p>
1
2016-10-13T15:11:04Z
40,024,838
<p>If you use the print method it prints ok.</p> <p>I guess you have a problem with html? Replace whitespaces with &nbsp; (but then it looks like crap in the shell) or try a more explicit representation in admin...</p> <p>Or you could try wrapping the string in the <code>&lt;pre&gt;</code> tag</p>
0
2016-10-13T15:14:29Z
[ "python", "django" ]
How to add more space in `__str__` method of Django model?
40,024,769
<p>I want to add more spaces to <code>__str__</code> method, but method cut off spaces to 1.</p> <p>For example:</p> <pre><code>class Spam(models.Model): foo = models.IntegerField() bar = models.IntegerField() def __str__(self): return 'more spaces {} {}!'.format(self.foo, self.bar) </code></pre> <p>This output in Django admin: <code>more spaces 1 2</code></p> <p>I want : <code>more spaces 1 2</code></p> <p>How do this?</p>
1
2016-10-13T15:11:04Z
40,025,355
<p>I am not familiar with django, but you are checking the results at web-page, indeed.</p> <p>So full answer for your question will be: You should use special HTML symbols for HTML-page to indent your second part of text. You can check special symbols here: <a href="http://www.wikihow.com/Insert-Spaces-in-HTML" rel="nofollow">http://www.wikihow.com/Insert-Spaces-in-HTML</a></p> <p>To use '&amp;nbsp' you can do:</p> <pre><code>def __str__(self): space_sym = "&amp;nbsp"*10 # hardcode magic-number of indent spaces return 'more spaces {}{}{}!'.format(self.foo, space_sym, self.bar) </code></pre>
0
2016-10-13T15:37:38Z
[ "python", "django" ]
Developing a scatter plot in Python using Turtle
40,024,789
<p>I am working on the "How to think like a computer scientist" course, and am stuck on this question:</p> <p>Interpret the data file labdata.txt such that each line contains a an x,y coordinate pair. Write a function called plotRegression that reads the data from this file and uses a turtle to plot those points and a best fit line according to the following formulas:</p> <p>y=y¯+m(x−x¯)</p> <p>m=∑xiyi−nx¯y¯∑x2i−nx¯2</p> <p>Your program should analyze the points and correctly scale the window using setworldcoordinates so that that each point can be plotted. Then you should draw the best fit line, in a different color, through the points.</p> <p>Here's what I have so far, but I keep getting an 'int' does not support indexing error. I've been using various online resources and a few solutions on here, but can't seem to get this working properly. </p> <p>Could anyone help me figure out what to correct? </p> <pre><code>import turtle def plotRegression(data): win = turtle.Screen() win.bgcolor('pink') t = turtle.Turtle() t.shape('circle') # t.turtlesize(0.2) x_list, y_list = [int(i[0]) for i in plot_data], [int(i[1]) for i in plot_data] x_list, y_list = [float(i) for i in x_list], [float(i) for i in y_list] x_sum, y_sum = sum(x_list), sum(y_list) x_bar, y_bar = x_sum / len(x_list), y_sum / len(y_list) x_list_square = [i ** 2 for i in x_list] x_list_square_sum = sum(x_list_square) xy_list = [x_list[i] * y_list[i] for i in range(len(x_list))] xy_list_sum = sum(xy_list) m = (xy_list_sum - len(x_list) * x_bar * y_bar) / (x_list_square_sum - len(x_list) * x_bar ** 2) # best y y_best = [(y_bar + m * (x_list[i] - x_bar)) for i in range(len(x_list))] # plot points max_x = max(x_list) max_y = max(y_list) win.setworldcoordinates(0, 0, max_x, max_y) for i in range(len(x_list)): t.penup() t.setposition(x_list[i], y_list[i]) t.stamp() # plot best y t.penup() t.setposition(0, 0) t.color('blue') for i in range(len(x_list)): t.setposition(x_list[i], y_best[i]) t.pendown() win.exitonclick() f = open("labdata.txt", "r") for aline in f: plot_data = map(int, aline.split()) plotRegression(plot_data) </code></pre>
-1
2016-10-13T15:11:45Z
40,033,773
<p>I think your turtle graphics is a secondary issue -- you're not reading your data in correctly. You're tossing all but the last x, y pair. And <code>map()</code> isn't your friend here as you'll want to index the result inside <code>plotRegression()</code>. Also you're accessing <code>plot_data</code> directly in the function instead of the formal parameter <code>data</code> and other details.</p> <p>Here's my rework of your code, see if it gets you heading in a better direction:</p> <pre><code>from turtle import Turtle, Screen def plotRegression(data): x_list, y_list = [int(i[0]) for i in data], [int(i[1]) for i in data] x_list, y_list = [float(i) for i in x_list], [float(i) for i in y_list] x_sum, y_sum = sum(x_list), sum(y_list) x_bar, y_bar = x_sum / len(x_list), y_sum / len(y_list) x_list_square = [i ** 2 for i in x_list] x_list_square_sum = sum(x_list_square) xy_list = [x_list[i] * y_list[i] for i in range(len(x_list))] xy_list_sum = sum(xy_list) m = (xy_list_sum - len(x_list) * x_bar * y_bar) / (x_list_square_sum - len(x_list) * x_bar ** 2) # best y y_best = [(y_bar + m * (x_list[i] - x_bar)) for i in range(len(x_list))] # plot points turtle = Turtle(shape = 'circle') for i in range(len(x_list)): turtle.penup() turtle.setposition(x_list[i], y_list[i]) turtle.stamp() # plot best y turtle.penup() turtle.setposition(0, 0) turtle.color('blue') for i in range(len(x_list)): turtle.setposition(x_list[i], y_best[i]) turtle.pendown() return (min(x_list), min(y_list), max(x_list), max(y_list)) screen = Screen() screen.bgcolor('pink') f = open("labdata.txt", "r") plot_data = [] for aline in f: x, y = aline.split() plot_data.append((x, y)) # This next line should be something like: # screen.setworldcoordinates(*plotRegression(plot_data)) # but setworldcoordinates() is so tricky to work with # that I'm going to leave it at: print(*plotRegression(plot_data)) # and suggest you trace a rectangle with the return # values to get an idea what's going to happen to # your coordinate system screen.exitonclick() </code></pre>
0
2016-10-14T02:02:22Z
[ "python", "plot", "statistics", "turtle-graphics", "introduction" ]
What is regex for website domain to use in tokenizing while keeping punctuation apart from words?
40,024,874
<p>This is normal output: <a href="https://i.stack.imgur.com/fFfnQ.png" rel="nofollow"><img src="https://i.stack.imgur.com/fFfnQ.png" alt="enter image description here"></a></p> <p>What I want is to keep domain names as single tokens. For ex: "<a href="https://www.twitter.com" rel="nofollow">https://www.twitter.com</a>" should remain as a single token. </p> <p>My code:</p> <pre><code>import nltk from nltk.tokenize.regexp import RegexpTokenizer line="My website: http://www.cartoon.com is not accessible." pattern = r'^(((([A-Za-z0-9]+){1,63}\.)|(([A-Za-z0-9]+(\-)+[A-Za-z0-9]+){1,63}\.))+){1,255}$' tokeniser=RegexpTokenizer(pattern) print (tokeniser.tokenize(line)) </code></pre> <p>Output:</p> <pre><code>[] </code></pre> <p>What am I doing wrong? Any better regex for domain names?</p> <p>Edit: The special character must remain as a separate token, like from above example, tokenization must separate ('website' , ':').</p>
1
2016-10-13T15:15:58Z
40,025,011
<p>Use a 'standard' domain regex</p> <pre><code>import re line="My website: http://www.cartoon.com is not accessible." print(re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&amp;+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', line)) </code></pre> <p>Returns: ['<a href="http://www.cartoon.com" rel="nofollow">http://www.cartoon.com</a>']</p> <p>Also works for like 99% of domain names</p>
0
2016-10-13T15:21:24Z
[ "python", "regex", "nltk", "tokenize" ]
What is regex for website domain to use in tokenizing while keeping punctuation apart from words?
40,024,874
<p>This is normal output: <a href="https://i.stack.imgur.com/fFfnQ.png" rel="nofollow"><img src="https://i.stack.imgur.com/fFfnQ.png" alt="enter image description here"></a></p> <p>What I want is to keep domain names as single tokens. For ex: "<a href="https://www.twitter.com" rel="nofollow">https://www.twitter.com</a>" should remain as a single token. </p> <p>My code:</p> <pre><code>import nltk from nltk.tokenize.regexp import RegexpTokenizer line="My website: http://www.cartoon.com is not accessible." pattern = r'^(((([A-Za-z0-9]+){1,63}\.)|(([A-Za-z0-9]+(\-)+[A-Za-z0-9]+){1,63}\.))+){1,255}$' tokeniser=RegexpTokenizer(pattern) print (tokeniser.tokenize(line)) </code></pre> <p>Output:</p> <pre><code>[] </code></pre> <p>What am I doing wrong? Any better regex for domain names?</p> <p>Edit: The special character must remain as a separate token, like from above example, tokenization must separate ('website' , ':').</p>
1
2016-10-13T15:15:58Z
40,025,530
<p>You may use</p> <pre><code>tokeniser=RegexpTokenizer(r'\b(?:http|ftp)s?://\S*\w|\w+|[^\w\s]+') </code></pre> <p>See the <a href="https://regex101.com/r/HazY6N/1" rel="nofollow">regex demo</a></p> <p><strong>Details</strong>:</p> <ul> <li><code>\b</code> - leading word boundary (there must be a non-word char before...)</li> <li><code>(?:http|ftp)s?://</code> - a protocol, <code>http</code>/<code>https</code>, <code>ftp</code>/<code>ftps</code></li> <li><code>\S*</code> - 0+ non-whitespace symbols</li> <li><code>\w</code> - a word char (=letter/digit/<code>_</code>)</li> <li><code>|</code> - or</li> <li><code>\w+</code> - 1 or more word chars</li> <li><code>|</code> - or </li> <li><code>[^\w\s]+</code> - 1 or more non-word chars excluding whitespaces.</li> </ul>
2
2016-10-13T15:46:23Z
[ "python", "regex", "nltk", "tokenize" ]
how to export a dictionary into a csv file in python
40,024,925
<p>I have a very big dictionary and want to export into a text or csv file in such a way that keys would be in the first column and values in the 2nd column. could anyone help to do so?</p>
-5
2016-10-13T15:18:01Z
40,025,105
<p>Simply iterate through the dictionary and output:</p> <pre><code>with open 'my_csv.csv' as f: for k, v in my_dict.items(): # or iteritems in python 2 f.write("%s,%s\n" % (k, v)) # or whatever format code of your data types </code></pre>
0
2016-10-13T15:25:39Z
[ "python" ]
Is there a way to overlay figures or to get figure handles in bokeh, python
40,024,952
<p>I created two figures with bokeh and python wich are plotted side by side, then I created another two figures. These are now plotted underneath the first two. What I want is to replace the first two with the new ones. Is there a way to clear the old ones and overlay them with the new ones or at least to get their handles?</p> <p>Here a simple example</p> <pre><code># test.py from bokeh.layouts import Row from bokeh.layouts import column from bokeh.plotting import figure, curdoc # new plots s1 = figure(title="my data 1", x_axis_label='x', y_axis_label='y') s2 = figure(title="my data 2", x_axis_label='x', y_axis_label='y') # my data x = [1, 2, 3, 4, 5] y1 = [1, 2, 3, 4, 5] y2 = [3, 5, 7, 9, 11] # plot lines s1.line(x, y1, legend="data1", line_width=2) s2.line(x, y2, legend="data2", line_width=3) p = Row(s1, s2) curdoc().add_root(column(p)) print "plot 1 done" # plot lines again s1 = figure(title="my data 1", x_axis_label='x', y_axis_label='y') s2 = figure(title="my data 2", x_axis_label='x', y_axis_label='y') s1.line(x, y1, legend="data1", line_width=2) s2.line(x, y2, legend="data2", line_width=3) p = Row(s1, s2) curdoc().add_root(column(p)) print "plot 2 done" </code></pre> <p><a href="https://i.stack.imgur.com/6p3ol.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/6p3ol.jpg" alt="output"></a></p>
0
2016-10-13T15:18:55Z
40,079,664
<p>I found the answer. For this simple example one needs to add</p> <pre><code>curdoc().clear() </code></pre> <p>before the second <code>curdoc().add_root(column(p))</code></p> <p>If you want to do it while keeping buttons or other features alive (because clear deletes everything) here is an example how to deal with it:</p> <p><a href="http://stackoverflow.com/questions/38548442/dynamically-add-remove-plot-using-bokeh-serve-bokeh-0-12-0">Dynamically add/remove plot using &#39;bokeh serve&#39; (bokeh 0.12.0)</a></p>
0
2016-10-17T06:20:06Z
[ "python", "bokeh", "figure" ]
Keras: how to set learning phase after model loading
40,025,013
<p>I faced with problem when I try to train pre-trained model loaded from json config + weights file.</p> <p>I use following code (simplified):</p> <pre><code>from keras.utils.layer_utils import layer_from_config with open("config.json", "rb") as f: config = json.loads(f.read()) model = layer_from_config(config) model.load_weights("weights.net") history = model.fit(batch, target, verbose=1, validation_data=(test_batch, test_target), shuffle=True) </code></pre> <p>And I got following exception:</p> <blockquote> <p>theano.gof.fg.MissingInputError: ("An input of the graph, used to compute DimShuffle{x,x}(keras_learning_phase), was not provided and not given a value.Use the Theano flag exception_verbosity='high',for more information on this error.", keras_learning_phase)</p> </blockquote> <p>I think it makes sense since I have dropout layers in model so it should know current learning phase. How can I set learning phase to 'train'? Or may be different problem here?</p> <p>Thanks in advance! </p>
0
2016-10-13T15:21:29Z
40,045,129
<p>Let me answer to this question by myself.</p> <p>This issue is related only to keras 1.0.0 version and it was fixed in 1.0.2. So code snippet above is perfectly work on newer version of keras, no need to explicitly set learning phase. </p> <p>More details in <a href="https://github.com/fchollet/keras/issues/2281" rel="nofollow">github issue tread</a>.</p>
0
2016-10-14T14:03:11Z
[ "python", "theano", "keras" ]
How to get number of dimensions in OneHotEncoder in Scikit-learn
40,025,102
<p>I am using the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html" rel="nofollow"><code>OneHotEncoder</code></a> from Scikit-learn in my project. And I need to know what would be the size of each one-hot vector when the <code>n_value</code> is set to be <code>auto</code>. I thought <code>n_value_</code> would show that but it seems I have no way other than trying out training samples. I made this toy example code to show the problem. Do you know any other solution?</p> <pre><code>from sklearn.preprocessing import OneHotEncoder data = [[1], [3], [5]] # 3 different features encoder = OneHotEncoder() encoder.fit(data) print(len(encoder.transform([data[0]]).toarray()[0])) # 3 number of dimensions in one-hot-vector print(encoder.n_values_) # [6] == len(range(5)) </code></pre>
1
2016-10-13T15:25:36Z
40,026,253
<p>Is this what you are looking for?</p> <pre><code>&gt;&gt;&gt; encoder.active_features_ array([1, 3, 5]) &gt;&gt;&gt; len(encoder.active_features_) 3 </code></pre>
1
2016-10-13T16:22:41Z
[ "python", "machine-learning", "scikit-learn", "one-hot-encoding" ]
How to get number of dimensions in OneHotEncoder in Scikit-learn
40,025,102
<p>I am using the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html" rel="nofollow"><code>OneHotEncoder</code></a> from Scikit-learn in my project. And I need to know what would be the size of each one-hot vector when the <code>n_value</code> is set to be <code>auto</code>. I thought <code>n_value_</code> would show that but it seems I have no way other than trying out training samples. I made this toy example code to show the problem. Do you know any other solution?</p> <pre><code>from sklearn.preprocessing import OneHotEncoder data = [[1], [3], [5]] # 3 different features encoder = OneHotEncoder() encoder.fit(data) print(len(encoder.transform([data[0]]).toarray()[0])) # 3 number of dimensions in one-hot-vector print(encoder.n_values_) # [6] == len(range(5)) </code></pre>
1
2016-10-13T15:25:36Z
40,028,873
<p>I think the better solution is to define the vector size in <code>n_values</code>. Because the automatic option creates odd behavior with missing features comparing to out of range feature numbers. Trying this example again, it produces zero vector for missing numbers:</p> <pre><code>from sklearn.preprocessing import OneHotEncoder data = [[1], [3], [5]] encoder = OneHotEncoder() encoder.fit(data) print(encoder.transform([ [0], [1], [2], [3], [4], [5] ]).toarray()) </code></pre> <p>The result is as following:</p> <pre><code>[[ 0. 0. 0.] [ 1. 0. 0.] [ 0. 0. 0.] [ 0. 1. 0.] [ 0. 0. 0.] [ 0. 0. 1.]] </code></pre> <p>And if I try <code>6</code>it just throws errors:</p> <pre><code>print(encoder.transform([[6]]).toarray()) </code></pre> <p>result:</p> <pre><code>ValueError: unknown categorical feature present [6] during transform. </code></pre> <p>As I mentioned earlier, the best practice is to define the size of vectors from the beginning:</p> <pre><code>from sklearn.preprocessing import OneHotEncoder data = [[1], [3], [5]] encoder = OneHotEncoder(n_values=50) # maximum size for my vocabulary, fits for my memory and my future development. encoder.fit(data) </code></pre> <p>Keep in mind that in this case, there won't be any <code>active_features_</code> attribute for <code>encoder</code> anymore.</p>
0
2016-10-13T18:57:33Z
[ "python", "machine-learning", "scikit-learn", "one-hot-encoding" ]
VisualStudio django.conf.urls
40,025,208
<p>This is my first question ever. I am working in VisualStudio to create a django/python application for smartshopping AI. This is also my first python/django technology application. I have trouble with the urls.py and have read that django versions do not include urlpatterns. I've changed my url patterns to reflect the advice online and have changed my django.conf.urls import url section of my code. It is still not working. Please help. </p> <p>I've followed the advices online to get here:</p> <pre><code>from datetime import datetime from django.conf.urls import url from app.forms import BootstrapAuthenticationForm # Uncomment the next lines to enable the admin: from django.conf.urls import include from django.contrib import admin admin.autodiscover() urlpatterns = [ # Examples: url(r'^$', 'app.views.home', name='home'), url(r'^contact$', 'app.views.contact', name='contact'), url(r'^about', 'app.views.about', name='about'), url(r'^login/$', 'django.contrib.auth.views.login', { 'template_name': 'app/login.html', 'authentication_form': BootstrapAuthenticationForm, 'extra_context': { 'title':'Log in', 'year':datetime.now().year, } }, name='login'), url(r'^logout$', 'django.contrib.auth.views.logout', { 'next_page': '/', }, name='logout'), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), ] </code></pre> <p>I want an easy fix not to change all the views to add include - these were autogenerated by visual studio. I want to keep autogeneraton working and just add a line of code to reference the url.py</p> <pre><code>from django.shortcuts import render from django.http import HttpRequest from django.template import RequestContext from datetime import datetime def home(request): """Renders the home page.""" assert isinstance(request, HttpRequest) return render( request, 'app/index.html', context_instance = RequestContext(request, { 'title':'Home Page', 'year':datetime.now().year, }) ) def contact(request): """Renders the contact page.""" assert isinstance(request, HttpRequest) return render( request, 'app/contact.html', context_instance = RequestContext(request, { 'title':'Contact', 'message':'Your contact page.', 'year':datetime.now().year, }) ) def about(request): """Renders the about page.""" assert isinstance(request, HttpRequest) return render( request, 'app/about.html', context_instance = RequestContext(request, { 'title':'About', 'message':'Your application description page.', 'year':datetime.now().year, }) ) </code></pre> <p>Based on the responses and the stack overflow answer to a similar question (<a href="http://stackoverflow.com/questions/38744285/django-urls-error-view-must-be-a-callable-or-a-list-tuple-in-the-case-of-includ">Django URLs error: view must be a callable or a list/tuple in the case of include()</a>) I have tried this approach (which still does not work). </p> <pre><code>from datetime import datetime from django.conf.urls import url from app.forms import BootstrapAuthenticationForm from django.contrib.auth import views as auth_views from SmartShopper import views as SmartShopper_views # Uncomment the next lines to enable the admin: # from django.conf.urls import include # from django.contrib import admin # admin.autodiscover() urlpatterns = [ # Examples: url(r'^$', SmartShopper_views.home, name='home'), url(r'^contact$', SmartShopper_views.contact, name='contact'), url(r'^about', SmartShopper_views.about, name='about'), url(r'^login/$', 'django.contrib.auth.views.login', { 'template_name': 'app/login.html', 'authentication_form': BootstrapAuthenticationForm, 'extra_context': { 'title':'Log in', 'year':datetime.now().year, } }, name='login'), url(r'^logout$', 'django.contrib.auth.views.logout', { 'next_page': '/', }, name='logout'), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), </code></pre> <p>[what my solution contains - I'm coming from an asp.net MVC background and django is a bit different with its MVC type structure still getting used to it, just help me make thisthing run! HELPPP please. thanks <a href="https://i.stack.imgur.com/93SJQ.jpg" rel="nofollow">1</a></p>
0
2016-10-13T15:30:58Z
40,025,805
<p>You don't need to change your views. The problem is still in your urls.py. Instead of referring to eg <code>"app.views.home"</code> as a string, you need to import the view and refer to <code>views.home</code> directly.</p>
0
2016-10-13T16:00:27Z
[ "python", "django", "django-urls" ]
VisualStudio django.conf.urls
40,025,208
<p>This is my first question ever. I am working in VisualStudio to create a django/python application for smartshopping AI. This is also my first python/django technology application. I have trouble with the urls.py and have read that django versions do not include urlpatterns. I've changed my url patterns to reflect the advice online and have changed my django.conf.urls import url section of my code. It is still not working. Please help. </p> <p>I've followed the advices online to get here:</p> <pre><code>from datetime import datetime from django.conf.urls import url from app.forms import BootstrapAuthenticationForm # Uncomment the next lines to enable the admin: from django.conf.urls import include from django.contrib import admin admin.autodiscover() urlpatterns = [ # Examples: url(r'^$', 'app.views.home', name='home'), url(r'^contact$', 'app.views.contact', name='contact'), url(r'^about', 'app.views.about', name='about'), url(r'^login/$', 'django.contrib.auth.views.login', { 'template_name': 'app/login.html', 'authentication_form': BootstrapAuthenticationForm, 'extra_context': { 'title':'Log in', 'year':datetime.now().year, } }, name='login'), url(r'^logout$', 'django.contrib.auth.views.logout', { 'next_page': '/', }, name='logout'), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), ] </code></pre> <p>I want an easy fix not to change all the views to add include - these were autogenerated by visual studio. I want to keep autogeneraton working and just add a line of code to reference the url.py</p> <pre><code>from django.shortcuts import render from django.http import HttpRequest from django.template import RequestContext from datetime import datetime def home(request): """Renders the home page.""" assert isinstance(request, HttpRequest) return render( request, 'app/index.html', context_instance = RequestContext(request, { 'title':'Home Page', 'year':datetime.now().year, }) ) def contact(request): """Renders the contact page.""" assert isinstance(request, HttpRequest) return render( request, 'app/contact.html', context_instance = RequestContext(request, { 'title':'Contact', 'message':'Your contact page.', 'year':datetime.now().year, }) ) def about(request): """Renders the about page.""" assert isinstance(request, HttpRequest) return render( request, 'app/about.html', context_instance = RequestContext(request, { 'title':'About', 'message':'Your application description page.', 'year':datetime.now().year, }) ) </code></pre> <p>Based on the responses and the stack overflow answer to a similar question (<a href="http://stackoverflow.com/questions/38744285/django-urls-error-view-must-be-a-callable-or-a-list-tuple-in-the-case-of-includ">Django URLs error: view must be a callable or a list/tuple in the case of include()</a>) I have tried this approach (which still does not work). </p> <pre><code>from datetime import datetime from django.conf.urls import url from app.forms import BootstrapAuthenticationForm from django.contrib.auth import views as auth_views from SmartShopper import views as SmartShopper_views # Uncomment the next lines to enable the admin: # from django.conf.urls import include # from django.contrib import admin # admin.autodiscover() urlpatterns = [ # Examples: url(r'^$', SmartShopper_views.home, name='home'), url(r'^contact$', SmartShopper_views.contact, name='contact'), url(r'^about', SmartShopper_views.about, name='about'), url(r'^login/$', 'django.contrib.auth.views.login', { 'template_name': 'app/login.html', 'authentication_form': BootstrapAuthenticationForm, 'extra_context': { 'title':'Log in', 'year':datetime.now().year, } }, name='login'), url(r'^logout$', 'django.contrib.auth.views.logout', { 'next_page': '/', }, name='logout'), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), </code></pre> <p>[what my solution contains - I'm coming from an asp.net MVC background and django is a bit different with its MVC type structure still getting used to it, just help me make thisthing run! HELPPP please. thanks <a href="https://i.stack.imgur.com/93SJQ.jpg" rel="nofollow">1</a></p>
0
2016-10-13T15:30:58Z
40,029,342
<p>After learning more about the Django framework from this youtube tutorial I was able to fix my code (<a href="https://www.youtube.com/watch?v=nAn1KpPlN2w&amp;index=3&amp;list=PL6gx4Cwl9DGBlmzzFcLgDhKTTfNLfX1IK#t=4.759461" rel="nofollow">https://www.youtube.com/watch?v=nAn1KpPlN2w&amp;index=3&amp;list=PL6gx4Cwl9DGBlmzzFcLgDhKTTfNLfX1IK#t=4.759461</a>) </p> <p>What I learned was that each "app" is a segment of the program with associated views. All I had to do was import all the views from my_app or app or whatever else you are calling your new "app" in Django. Besides the slight change to the urlpatterns from () to [] all I did was modify the url call to pull from the app_views I set up above. Here is functional code. I have a "Server error (500)" which is something else I'll figure out but yea please explain things more for devs who are simply new to the django framework. Visualstudio is a good tool. use it for python. Reach out if you have any questions I'd be happy to help the newbie. Here is my functional code. </p> <pre><code>from datetime import datetime from django.conf.urls import url from app.forms import BootstrapAuthenticationForm from django.contrib.auth import views as auth_views from app import views as app_views # Uncomment the next lines to enable the admin: # from django.conf.urls import include # from django.contrib import admin # admin.autodiscover() urlpatterns = [ # Examples: url(r'^$', app_views.home, name='home'), url(r'^contact$', app_views.contact, name='contact'), url(r'^about', app_views.about, name='about'), url(r'^login/$', auth_views.login, { 'template_name': 'app/login.html', 'authentication_form': BootstrapAuthenticationForm, 'extra_context': { 'title':'Log in', 'year':datetime.now().year, } }, name='login'), url(r'^logout$', auth_views.logout, { 'next_page': '/', }, name='logout'), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), ] </code></pre>
0
2016-10-13T19:26:19Z
[ "python", "django", "django-urls" ]
Given only source file, what files does it import?
40,025,238
<p>I'm building a dependency graph in python3 using the <code>ast</code> module. How do I know what file(s) will be imported if that import statement were to be executed?</p>
3
2016-10-13T15:32:05Z
40,025,403
<p>Not a complete answer, but here are some bits you should be aware of:</p> <ul> <li>Imports might happen in conditional or try-catch blocks. So depending on a setting of an environment variable, module A might or might not import module B.</li> <li>There's a wide variety of import syntax: <code>import A</code>, <code>from A import B</code>, <code>from A import *</code>, <code>from . import A</code>, <code>from .. import A</code>, <code>from ..A import B</code> as well as their versions with <code>A</code> replaced with sub-modules.</li> <li>Imports can happen in any executable context - the top-level of the file, in a function, in a class definition etc.</li> <li><code>eval</code> can evaluate code with imports. Up to you if you consider such code to be a dependency.</li> </ul> <p>The standard library <a href="https://docs.python.org/3.5/library/modulefinder.html" rel="nofollow">modulefinder</a> module might help.</p>
1
2016-10-13T15:40:03Z
[ "python", "python-3.x", "python-import", "abstract-syntax-tree" ]
Given only source file, what files does it import?
40,025,238
<p>I'm building a dependency graph in python3 using the <code>ast</code> module. How do I know what file(s) will be imported if that import statement were to be executed?</p>
3
2016-10-13T15:32:05Z
40,040,710
<p>As suggested in a comment: the other answers are valid, but one of the fundamental problems is that your examples only work for 'simple' scripts or files: A lot of more complex code will use things like dynamic imports: consider the following:</p> <pre><code>path, task_name = "module.function".rsplit(".", 1); module = importlib.import_module(path); real_func = getattr(module, task_name); real_func(); </code></pre> <p>The actual original string could be obfuscated, or pulled from a DB, or a file or...</p> <p>There are alternatives to importlib, but this is on top of the exec type stuff you might see in @horia's good answer.</p>
0
2016-10-14T10:17:07Z
[ "python", "python-3.x", "python-import", "abstract-syntax-tree" ]
Inherit from scikit-learn's LassoCV model
40,025,406
<p>I tried to extend scikit-learn's RidgeCV model using inheritance:</p> <pre><code>from sklearn.linear_model import RidgeCV, LassoCV class Extended(RidgeCV): def __init__(self, *args, **kwargs): super(Extended, self).__init__(*args, **kwargs) def example(self): print 'Foo' x = [[1,0],[2,0],[3,0],[4,0], [30, 1]] y = [2,4,6,8, 60] model = Extended(alphas = [float(a)/1000.0 for a in range(1, 10000)]) model.fit(x,y) print model.predict([[5,1]]) </code></pre> <p>It worked perfectly fine, but when I tried to inherit from LassoCV, it yielded the following traceback:</p> <pre><code>Traceback (most recent call last): File "C:/Python27/so.py", line 14, in &lt;module&gt; model.fit(x,y) File "C:\Python27\lib\site-packages\sklearn\linear_model\coordinate_descent.py", line 1098, in fit path_params = self.get_params() File "C:\Python27\lib\site-packages\sklearn\base.py", line 214, in get_params for key in self._get_param_names(): File "C:\Python27\lib\site-packages\sklearn\base.py", line 195, in _get_param_names % (cls, init_signature)) RuntimeError: scikit-learn estimators should always specify their parameters in the signature of their __init__ (no varargs). &lt;class '__main__.Extended'&gt; with constructor (&lt;self&gt;, *args, **kwargs) doesn't follow this convention. </code></pre> <p>Can somebody explain how to fix this?</p>
1
2016-10-13T15:40:12Z
40,027,200
<p>You probably want to make scikit-learn compatible model, to use it further with available scikit-learn functional. If you do - you need to read this first: <a href="http://scikit-learn.org/stable/developers/contributing.html#rolling-your-own-estimator" rel="nofollow">http://scikit-learn.org/stable/developers/contributing.html#rolling-your-own-estimator</a></p> <p>Shortly: scikit-learn has many features like estimator cloning (clone() function), meta algorithms like <code>GridSearch</code>, <code>Pipeline</code>, Cross validation. And all these things have to be able to get values of fields inside of your estimator, and change value of these fields (For example <code>GridSearch</code> has to change parameters inside of your estimator before each evaluation), like parameter <code>alpha</code> in <code>SGDClassifier</code>. To change value of some parameter it has to know its name. To get names of all fields in every classifier method <code>get_params</code> from <code>BaseEstimator</code> class (Which you're inheriting implicitly) requires all parameters to be specified in <code>__init__</code> method of a class, because it's easy to introspect all parameter names of <code>__init__</code> method (Look at <code>BaseEstimator</code>, this is the class which throws this error).</p> <p>So it just wants you to remove all varargs like</p> <pre><code>*args, **kwargs </code></pre> <p>from <code>__init__</code> signature. You have to list all parameters of your model in <code>__init__</code> signature, and initialise all internal fields of an object.</p> <p>Here is example of <code>__init__</code> method of <a href="https://github.com/scikit-learn/scikit-learn/blob/412996f/sklearn/linear_model/stochastic_gradient.py#L548" rel="nofollow">SGDClassifier</a>, which is inherited from <code>BaseSGDClassifier</code>:</p> <pre><code>def __init__(self, loss="hinge", penalty='l2', alpha=0.0001, l1_ratio=0.15, fit_intercept=True, n_iter=5, shuffle=True, verbose=0, epsilon=DEFAULT_EPSILON, n_jobs=1, random_state=None, learning_rate="optimal", eta0=0.0, power_t=0.5, class_weight=None, warm_start=False, average=False): super(SGDClassifier, self).__init__( loss=loss, penalty=penalty, alpha=alpha, l1_ratio=l1_ratio, fit_intercept=fit_intercept, n_iter=n_iter, shuffle=shuffle, verbose=verbose, epsilon=epsilon, n_jobs=n_jobs, random_state=random_state, learning_rate=learning_rate, eta0=eta0, power_t=power_t, class_weight=class_weight, warm_start=warm_start, average=average) </code></pre>
1
2016-10-13T17:16:59Z
[ "python", "scikit-learn" ]
Python Threading With Excel Com Object
40,025,495
<p>I am trying to open a workbook using a pre-opened excel com object within a python thread. Using the below code:</p> <pre><code>from multiprocessing import Process, Queue def open_workbook(excel,iSub_Loc,q): p = Process(target = open_workbook_helper, args = (excel,iSub_Loc)) p.daemon = True p.start() def open_workbook_helper(excel,iSub_Locq,): wb = excel.Workbooks.Open(iSub_Loc) ws = wb.Sheets(1) q.put((wb,ws)) </code></pre> <p>but i get the following error</p> <p><code>Can't pickle &lt;type PyIDispatch'&gt;: it's not found as __builtin__.PyIDispatch</code></p> <p>any suggestions? </p>
1
2016-10-13T15:44:32Z
40,026,072
<p>"multiprocessing" is not "threading" - Use <code>from threading import Thread, Queue</code> instead. WHat happnes is that for inter-process comunication the dtaa is serialized to make the calls to the code on the other process, and COM objects use system resources that are not serializable.</p> <p>If the operations you need to perform on your data are IOBound, just using threads will fit you. If you have code that would take advantage of multiple cores in pure Python - with sheer computation, then you can a separate process with just your data - already on Python side - not the COM objects. </p>
0
2016-10-13T16:13:04Z
[ "python", "excel", "multithreading", "com-object" ]
multithreading from a tkinter app
40,025,616
<p>I have a tkinter application that runs on the main thread. After receiving some input from the user, a new thread is created to perform functions in a separate class. The main thread continues to a Toplevel progress window. </p> <p>My question is, how can I communicate to the main thread when the second thread has finished its tasks, in order to close the progress window?</p> <pre><code>import tkinter as tk from tkinter import ttk from threading import Thread import time class Application: def __init__(self, master): # set main window frame = tk.Frame(master, width=300, height=100) frame.pack(fill=tk.BOTH) # button widget run_button = tk.Button(frame, text="GO", command=self.do_something) run_button.pack() # simulate some gui input from user self.user_input = "specified by user" def do_something(self): thread1 = Thread(target=FunctionClass, args=(self.user_input,)) thread1.start() # launch thread ProgressWindow() # main thread continues to new tkinter window class ProgressWindow(tk.Toplevel): """ displays progress """ def __init__(self): super().__init__() self.progress = ttk.Progressbar( self, orient="horizontal", length=300, mode="indeterminate") self.progress.pack() self.note = "Processing data..." self.p_label = tk.Label(self, text=self.note) self.p_label.pack() self.progress.start(50) class FunctionClass: """ thread1 works on this class """ def __init__(self, user_data): self.user_data = user_data self.do_something_else() def do_something_else(self): # simulate thread 1 working time.sleep(3) print("Thread1 job done") if __name__ == "__main__": root = tk.Tk() Application(root) root.mainloop() </code></pre> <p><strong>* UPDATE *</strong></p> <p>tkinter's <code>event_generate</code> as suggested by iCart works well. See code update below.</p> <pre><code>import tkinter as tk from tkinter import ttk, messagebox from threading import Thread import time class Application: def __init__(self, master): # set main window frame = tk.Frame(master, width=300, height=100) frame.pack(fill=tk.BOTH) # button widget run_button = tk.Button(frame, text="GO", command=self.do_something) run_button.pack() # simulate some gui input from user self.user_input = "specified by user" def do_something(self): thread1 = Thread(target=FunctionClass, args=(self.user_input,)) thread1.start() # launch thread ProgressWindow() # main thread continues to new tkinter window class ProgressWindow(tk.Toplevel): """ displays progress """ def __init__(self): super().__init__() self.progress = ttk.Progressbar(self, orient="horizontal", length=300, mode="indeterminate") self.progress.pack() self.note = "Processing data..." self.p_label = tk.Label(self, text=self.note) self.p_label.pack() self.progress.start(50) class FunctionClass: """ thread1 works on this class """ def __init__(self, user_data): self.user_data = user_data self.do_something_else() def do_something_else(self): # simulate thread 1 working time.sleep(3) print("Thread1 job done") # call &lt;&lt;stop&gt;&gt; virtual event (unsure if 'tail' is necessary here) root.event_generate("&lt;&lt;stop&gt;&gt;", when="tail") def end_program(*args): """ called with tkinter event_generate command after thread completion """ messagebox.showinfo("Complete", "Processing Complete") root.destroy() if __name__ == "__main__": root = tk.Tk() Application(root) root.bind("&lt;&lt;stop&gt;&gt;", end_program) # bind to event root.mainloop() </code></pre>
2
2016-10-13T15:51:14Z
40,025,789
<p>I'm not too familiar with tkinter so i can't show you ze code, but you should look at tkinter's event system, particularly firing custom events.</p> <p><a href="http://stackoverflow.com/questions/270648/tkinter-invoke-event-in-main-loop">This question</a> may help you get started</p>
2
2016-10-13T15:59:41Z
[ "python", "multithreading", "tkinter", "python-3.4" ]
multithreading from a tkinter app
40,025,616
<p>I have a tkinter application that runs on the main thread. After receiving some input from the user, a new thread is created to perform functions in a separate class. The main thread continues to a Toplevel progress window. </p> <p>My question is, how can I communicate to the main thread when the second thread has finished its tasks, in order to close the progress window?</p> <pre><code>import tkinter as tk from tkinter import ttk from threading import Thread import time class Application: def __init__(self, master): # set main window frame = tk.Frame(master, width=300, height=100) frame.pack(fill=tk.BOTH) # button widget run_button = tk.Button(frame, text="GO", command=self.do_something) run_button.pack() # simulate some gui input from user self.user_input = "specified by user" def do_something(self): thread1 = Thread(target=FunctionClass, args=(self.user_input,)) thread1.start() # launch thread ProgressWindow() # main thread continues to new tkinter window class ProgressWindow(tk.Toplevel): """ displays progress """ def __init__(self): super().__init__() self.progress = ttk.Progressbar( self, orient="horizontal", length=300, mode="indeterminate") self.progress.pack() self.note = "Processing data..." self.p_label = tk.Label(self, text=self.note) self.p_label.pack() self.progress.start(50) class FunctionClass: """ thread1 works on this class """ def __init__(self, user_data): self.user_data = user_data self.do_something_else() def do_something_else(self): # simulate thread 1 working time.sleep(3) print("Thread1 job done") if __name__ == "__main__": root = tk.Tk() Application(root) root.mainloop() </code></pre> <p><strong>* UPDATE *</strong></p> <p>tkinter's <code>event_generate</code> as suggested by iCart works well. See code update below.</p> <pre><code>import tkinter as tk from tkinter import ttk, messagebox from threading import Thread import time class Application: def __init__(self, master): # set main window frame = tk.Frame(master, width=300, height=100) frame.pack(fill=tk.BOTH) # button widget run_button = tk.Button(frame, text="GO", command=self.do_something) run_button.pack() # simulate some gui input from user self.user_input = "specified by user" def do_something(self): thread1 = Thread(target=FunctionClass, args=(self.user_input,)) thread1.start() # launch thread ProgressWindow() # main thread continues to new tkinter window class ProgressWindow(tk.Toplevel): """ displays progress """ def __init__(self): super().__init__() self.progress = ttk.Progressbar(self, orient="horizontal", length=300, mode="indeterminate") self.progress.pack() self.note = "Processing data..." self.p_label = tk.Label(self, text=self.note) self.p_label.pack() self.progress.start(50) class FunctionClass: """ thread1 works on this class """ def __init__(self, user_data): self.user_data = user_data self.do_something_else() def do_something_else(self): # simulate thread 1 working time.sleep(3) print("Thread1 job done") # call &lt;&lt;stop&gt;&gt; virtual event (unsure if 'tail' is necessary here) root.event_generate("&lt;&lt;stop&gt;&gt;", when="tail") def end_program(*args): """ called with tkinter event_generate command after thread completion """ messagebox.showinfo("Complete", "Processing Complete") root.destroy() if __name__ == "__main__": root = tk.Tk() Application(root) root.bind("&lt;&lt;stop&gt;&gt;", end_program) # bind to event root.mainloop() </code></pre>
2
2016-10-13T15:51:14Z
40,025,975
<p>You can use <code>Queue</code>, from <code>Queue</code> module.</p> <pre><code>def get_queue(self, queue): status = queue.get() if status: self.do_your_action() self.master.after(1000, self.get_queue) </code></pre> <p>And in the progress bar window, You pass queue and put something in it when progress bar finishes.</p>
1
2016-10-13T16:08:36Z
[ "python", "multithreading", "tkinter", "python-3.4" ]
looking for API to scan formated textfiles for specific information
40,025,724
<p>I have a a bunch of textfiles formated like this:</p> <p>material Material.138_39BE7F6A_c.bmp.002 { receive_shadows on </p> <pre><code>technique { pass Material.138_39BE7F6A_c.bmp.002 { ambient 0.800000011920929 0.800000011920929 0.800000011920929 1.0 diffuse 0.6400000190734865 0.6400000190734865 0.6400000190734865 1.0 specular 0.5 0.5 0.5 1.0 12.5 emissive 0.0 0.0 0.0 1.0 alpha_to_coverage off colour_write on cull_hardware clockwise depth_check on depth_func less_equal depth_write on illumination_stage light_clip_planes off light_scissor off lighting on normalise_normals off polygon_mode solid scene_blend one zero scene_blend_op add shading gouraud transparent_sorting on texture_unit { texture 39BE7F6A_c.png tex_address_mode wrap scale 1.0 1.0 colour_op modulate } } } </code></pre> <p>}</p> <p>And I need to convert them into a more modern format using a script, sort of like this: </p> <pre><code>material test{ diffuse 0 1 0 diffuse_map file:xxx.png glow 0 0 1 etc... } </code></pre> <p>Now I wonder, is there an API for Phyton or any other scripting language that would allow me to do this? </p> <pre><code>technique </code></pre> <p>{ pass %title { ambient %ambient diffuse %diffuse specular %specualr emissive %emmissive</p> <pre><code> alpha_to_coverage off colour_write on cull_hardware clockwise depth_check on depth_func less_equal depth_write on illumination_stage light_clip_planes off light_scissor off lighting on normalise_normals off polygon_mode solid scene_blend one zero scene_blend_op add shading gouraud transparent_sorting on texture_unit { texture %texture tex_address_mode wrap scale 1.0 1.0 colour_op modulate } } </code></pre> <p>}</p> <p>Bucause I have seen somethng like this before but I don't remember it exactly.<br> So is there a tool or API that orks with a scripting language that lets me write templates for the scan to extract data from multiple files?</p>
0
2016-10-13T15:56:18Z
40,025,804
<p>Since your input data actually has a <em>structure</em> and is constructed and can be parsed based on some <em>rules</em>. There are a number of parsers to choose from:</p> <ul> <li><a href="http://pyparsing.wikispaces.com/" rel="nofollow"><code>pyparsing</code></a></li> <li><a href="http://www.dabeaz.com/ply/ply.html" rel="nofollow"><code>PLY</code></a></li> <li><a href="https://github.com/vlasovskikh/funcparserlib" rel="nofollow"><code>funcparserlib</code></a></li> </ul> <p>They, of course, all have their differences and use cases they are more suitable for. Also see these great overviews and comparison tables:</p> <ul> <li><a href="https://github.com/webmaven/python-parsing-tools" rel="nofollow">A list of Python parsing tools</a></li> <li><a href="http://nedbatchelder.com/text/python-parsers.html" rel="nofollow">Python parsing tools</a></li> </ul>
0
2016-10-13T16:00:21Z
[ "python", "scanning", "data-extraction" ]
After installation of vtk with brew (macosx): "import vtk" aborts python console
40,025,812
<p>I tried to install vtk with homebrew but, now when I <code>import vtk</code> on Python, my python session is aborted...</p> <p>I work on MacOSX and I ran this line:</p> <pre><code>brew install vtk --with-qt --with-python --with-pyqt </code></pre> <p>It returns:</p> <pre class="lang-none prettyprint-override"><code>.... [ 29%] Built target vtkFiltersCore make: *** [all] Error 2 READ THIS: https://git.io/brew-troubleshooting If reporting this issue please do so at (not Homebrew/brew): https://github.com/Homebrew/homebrew-science/issues .... </code></pre> <p>After that I read that I should use this line:</p> <pre><code>HOMEBREW_MAKE_JOBS=1 VERBOSE=1 brew install vtk --qt --python --pyqt </code></pre> <p>After a long time, it returns:</p> <pre class="lang-none prettyprint-override"><code>.... ==&gt; Caveats Even without the --with-qt option, you can display native VTK render windows from python. Alternatively, you can integrate the RenderWindowInteractor in PyQt, PySide, Tk or Wx at runtime. Read more: import vtk.qt4; help(vtk.qt4) or import vtk.wx; help(vtk.wx) Python modules have been installed and Homebrew's site-packages is not in your Python sys.path, so you will not be able to import the modules this formula installed. If you plan to develop with these modules, please run: mkdir -p /Users/TheUser/Library/Python/2.7/lib/python/site-packages echo 'import site; site.addsitedir("/usr/local/lib/python2.7/site-packages")' &gt;&gt; /Users/TheUser/Library/Python/2.7/lib/python/site-packages/homebrew.pth ==&gt; Summary 🍺 /usr/local/Cellar/vtk/7.0.0_3: 3,203 files, 107.7M </code></pre> <p>So I ran the mkdir &amp; echo lines</p> <p>And when I tried <code>import vtk</code> in the Python console, it returns:</p> <pre class="lang-none prettyprint-override"><code> Fatal Python error: PyThreadState_Get: no current thread Abort trap: 6 </code></pre> <p>I retried to reinstall it later:</p> <pre class="lang-none prettyprint-override"><code>==&gt; Installing vtk from homebrew/science Error: vtk-7.0.0_3 already installed To install this version, first `brew unlink vtk` </code></pre> <p>So I did the unlink, and I reran <code>HOMEBREW_MAKE_JOBS=1 VERBOSE=1 brew install vtk --qt --python --pyqt</code> .</p> <p>The result:</p> <pre class="lang-none prettyprint-override"><code>==&gt; Patching VTK to use system Python 2 ==&gt; Caveats Even without the --with-qt option, you can display native VTK render windows from python. Alternatively, you can integrate the RenderWindowInteractor in PyQt, PySide, Tk or Wx at runtime. Read more: import vtk.qt4; help(vtk.qt4) or import vtk.wx; help(vtk.wx) VTK was linked against your system copy of Python. If you later decide to change Python installations, relink VTK with: brew postinstall vtk ==&gt; Summary 🍺 /usr/local/Cellar/vtk/7.0.0_5: 3,204 files, 107.7M </code></pre> <p>And when I <code>import vtk</code> on the python console: abortion!</p> <p>How can I fix that?</p>
0
2016-10-13T16:00:49Z
40,026,809
<p>I am currently updating to vtk/7.0.0_5 (used 7.0.0_3 before), the line I used to install it was :</p> <pre><code>brew install vtk --with-qt --with-qt5 --with-python </code></pre> <p>And I did not get any issue using it in python (2.7).</p> <p>Ok - So just finished to do the upgrade to 7.0.0_5 and I got the same message tan you. But no issue at all to launch python and launch :</p> <pre><code>&gt; $ python Python 2.7.12 (default, Oct 11 2016, 05:20:59) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.38)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import vtk &gt;&gt;&gt; import vtk.qt4 </code></pre> <p>Hope that help,</p> <p>Stephane</p>
0
2016-10-13T16:51:45Z
[ "python", "osx", "homebrew", "vtk", "failed-installation" ]
Can't use sympy parser in my class; TypeError : 'module' object is not callable
40,025,837
<p>I wrote some code for calculating the differential equation and it's solution using sympy, but I'm getting an error, my code : ( example )</p> <pre><code>from sympy.parsing import sympy_parser expr=1/2 r='3/2' r=sympy_parser(r) </code></pre> <p>I get </p> <pre><code>TypeError: 'module' object is not callable </code></pre> <p>What am I doing wrong here ?</p>
2
2016-10-13T16:01:58Z
40,025,910
<p><code>sympy_parser</code> is a <em>module</em>, and modules are not a <em>callable</em>. What you want is <a href="http://docs.sympy.org/dev/modules/parsing.html" rel="nofollow"><code>sympy_parser.parse_expr</code></a>:</p> <pre><code>&gt;&gt;&gt; from sympy.parsing import sympy_parser &gt;&gt;&gt; r ='3/2' &gt;&gt;&gt; r = sympy_parser.parse_expr(r) &gt;&gt;&gt; r 3/2 </code></pre>
2
2016-10-13T16:04:53Z
[ "python", "python-3.x", "sympy" ]
Problems when pandas reading Excel file that has blank top row and left column
40,026,020
<p>I tried to read an Excel file that looks like below, <a href="https://i.stack.imgur.com/vD3Di.png" rel="nofollow"><img src="https://i.stack.imgur.com/vD3Di.png" alt="enter image description here"></a></p> <p>I was using pandas like this</p> <pre><code>xls = pd.ExcelFile(file_path) assets = xls.parse(sheetname="Sheet1", header=1, index_col=1) </code></pre> <p>But I got error</p> <blockquote> <p>ValueError: Expected 4 fields in line 3, saw 5</p> </blockquote> <p>I also tried </p> <pre><code>assets = xls.parse(sheetname="Sheet1", header=1, index_col=1, parse_cols="B:E") </code></pre> <p>But I got misparsed result as follows</p> <p><a href="https://i.stack.imgur.com/rCP9E.png" rel="nofollow"><img src="https://i.stack.imgur.com/rCP9E.png" alt="enter image description here"></a></p> <p>Then tried </p> <pre><code>assets = xls.parse(sheetname="Sheet1", header=1, index_col=0, parse_cols="B:E") </code></pre> <p>Finally works, but why index_col=0 and parse_cols="B:E"? This makes me confused becasue based on pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html" rel="nofollow">documents</a>, <code>assets = xls.parse(sheetname="Sheet1", header=1, index_col=1)</code> should just be fine. Have I missed something?</p>
1
2016-10-13T16:10:50Z
40,030,423
<p>The <code>read_excel</code> <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html" rel="nofollow">documentation</a> is not clear on a point.</p> <ul> <li><code>skiprows=1</code> to skip the first empty row at the top of the file or <code>header=1</code> also works to use the second row has column index.</li> <li><code>parse_cols='B:E'</code> is a way to skip the first empty column at the left of the file</li> <li><code>index_col=0</code> is optional and permits to define the first parsed column (B in this example) as the <code>DataFrame</code> index. The mistake is here since <code>index_col</code> is relative to columns selected though the <code>parse_cols</code> parameter.</li> </ul> <p>With your example, you can use the following code</p> <pre><code>pd.read_excel('test.xls', sheetname='Sheet1', skiprows=1, parse_cols='B:E', index_col=0) # AA BB CC # 10/13/16 1 12 -1 # 10/14/16 3 12 -2 # 10/15/16 5 12 -3 # 10/16/16 3 12 -4 # 10/17/16 5 23 -5 </code></pre>
0
2016-10-13T20:30:51Z
[ "python", "python-3.x", "pandas" ]
Find filenames in folders and match up to an Excel table
40,026,117
<p>I need to extract file names (drawing numbers) from a given folder and subfolders. Then I need to cross-reference the list of found drawing numbers against an Excel file that contains a list of drawing numbers and corresponding drawing descriptions. The output needs to be an Excel table with two columns, for the drawing number and drawing description. There are about 500 drawings in 20 folders and subfolders that need to be traversed.</p>
0
2016-10-13T16:15:57Z
40,026,500
<p><code>walk</code> from the <code>os</code> module is probably going to be helpful, as is the <code>csv</code> module for making files excel can read. Without more details, I can only give you a rough skeleton. In the following, <code>root</code> is the top-level directory that contains all the directories you want to search:</p> <pre><code>import os import csv #The below is sample code for reading your existing csv files. #It will vary based on their exact specifications with open('myfile.csv', newline='') as f: reader = csv.reader(f) d = {line[0]: line[1] for line in reader} #Next is code for opening the output file, #then going through all the filenames in our directory #For each filename, we look it up in the dictionary from earlier # then write that pair to the output file with open('output.csv', 'w+', newline='') as out: writer = csv.writer(out) for dirpath, dirnames, filenames in os.walk('root'): for filename in filenames: writer.writerow([filename, d[filename]) </code></pre> <p>I suggest you look up <code>csv</code> and <code>os.walk</code> in the official Python documentation</p>
2
2016-10-13T16:34:28Z
[ "python", "excel", "windows" ]
Importing CherryPy fails on openshift
40,026,173
<p>I'm running a cherrypy based app on an openshift gear. Recently I've been getting a "503 service temporarily unavailable" error whenever I try to go to the site. Inspecting the logs, I see I'm getting an ImportError where I try to import CherryPy. This is strange - CherryPy is listed as a dependency in my requirements.txt and used to be imported just fine. I double checked to make sure I'm getting the right path to the openshift activate_this.py and it seems to be correct. I'm not quite sure where to look next; any help would be appreciated. Thanks!</p> <p>The failed import is at line 14 of app.py:</p> <pre><code>import os import files virtenv = os.path.join(os.environ['OPENSHIFT_PYTHON_DIR'], 'virtenv') virtualenv = os.path.join(virtenv, 'bin', 'activate_this.py') conf = os.path.join(files.get_root(), "conf", "server.conf") try: execfile(virtualenv, dict(__file__=virtualenv)) print virtualenv except IOError: pass import cherrypy import wsgi def mount(): def CORS(): cherrypy.response.headers["Access-Control-Allow-Origin"] = os.environ['OPENSHIFT_APP_DNS'] cherrypy.config.update({"tools.staticdir.root": files.get_root()}) cherrypy.tools.CORS = cherrypy.Tool('before_handler', CORS) cherrypy.tree.mount(wsgi.application(), "/", conf) def start(): cherrypy.engine.start() def end(): cherrypy.engine.exit() if __name__ == "__main__": mount() start() </code></pre> <p><strong>UPDATE</strong></p> <p>I eventually saw (when pushing to the openshift repo using git bash CLI) that the dependency installation from requirements.txt was failing with some exceptions I haven't bothered to look into yet. It then goes on to try to install dependencies in setup.py, and that works just fine. </p> <p>Regarding the port in use issue...I have no idea. I changed my startup from tree.mount and engine.start to quickstart, and everything worked when I pushed to openshift. Just for kicks (and because I need it to run my tests), I switched back to cherrypy.tree.mount, pushed it, and it worked just fine. </p> <p>Go figure.</p>
0
2016-10-13T16:18:17Z
40,030,040
<p>I use the app.py entry point for Openshift. Here are several examples on how I start my server using the pyramid framework on Openshift. I use waitress as the server but I have also used the cherrypy wsgi server. Just comment out the code you don't want.</p> <p><strong>app.py</strong></p> <pre><code>#Openshift entry point import os from pyramid.paster import get_app from pyramid.paster import get_appsettings if __name__ == '__main__': here = os.path.dirname(os.path.abspath(__file__)) if 'OPENSHIFT_APP_NAME' in os.environ: #are we on OPENSHIFT? ip = os.environ['OPENSHIFT_PYTHON_IP'] port = int(os.environ['OPENSHIFT_PYTHON_PORT']) config = os.path.join(here, 'production.ini') else: ip = '0.0.0.0' #localhost port = 6543 config = os.path.join(here, 'development.ini') app = get_app(config, 'main') #find 'main' method in __init__.py. That is our wsgi app settings = get_appsettings(config, 'main') #don't really need this but is an example on how to get settings from the '.ini' files # Waitress (remember to include the waitress server in "install_requires" in the setup.py) from waitress import serve print("Starting Waitress.") serve(app, host=ip, port=port, threads=50) # Cherrypy server (remember to include the cherrypy server in "install_requires" in the setup.py) # from cherrypy import wsgiserver # print("Starting Cherrypy Server on http://{0}:{1}".format(ip, port)) # server = wsgiserver.CherryPyWSGIServer((ip, port), app, server_name='Server') # server.start() #Simple Server # from wsgiref.simple_server import make_server # print("Starting Simple Server on http://{0}:{1}".format(ip, port)) # server = make_server(ip, port, app) # server.serve_forever() #Running 'production.ini' method manually. I find this method the least compatible with Openshift since you can't #easily start/stop/restart your app with the 'rhc' commands. Mabye somebody can suggest a better way :) # #Don't forget to set the Host IP in 'production.ini'. Use 8080 for the port for Openshift # You will need to use the 'pre_build' action hook(pkill python) so it stops the existing running instance of the server on OS # You also will have to set up another custom action hook so rhc app-restart, stop works. # See Openshifts Origin User's Guide ( I have not tried this yet) #Method #1 # print('Running pserve production.ini') # os.system("pserve production.ini &amp;") #Method #2 #import subprocess #subprocess.Popen(['pserve', 'production.ini &amp;']) </code></pre>
1
2016-10-13T20:09:07Z
[ "python", "python-2.7", "openshift", "cherrypy" ]
Is there a function in python to get the size of an arbitrary precision number?
40,026,200
<p>I'm working on a cryptographic scheme in python, so I use arbitrary precision numbers (<code>long</code>) all the time. I'm using python 2.7.</p> <p>My problem is that I need to get the most significant two bytes (16 bits) of a number and check if they are the padding I inserted. I've tried <code>sys.getsizeof()</code> but that gives the size of the entire object and guess I could also iterate through every few bits of the number until there are only two bytes left, but is there a more pythonian way of doing this?</p> <p>Thanks in advance.</p>
1
2016-10-13T16:20:02Z
40,026,256
<p>This should do it for you:</p> <pre><code>&gt;&gt;&gt; n = 1 &lt;&lt; 1000 &gt;&gt;&gt; n.bit_length() 1001 &gt;&gt;&gt; n &gt;&gt; (n.bit_length() - 16) 32768L </code></pre>
2
2016-10-13T16:23:01Z
[ "python", "arbitrary-precision" ]
Is there a function in python to get the size of an arbitrary precision number?
40,026,200
<p>I'm working on a cryptographic scheme in python, so I use arbitrary precision numbers (<code>long</code>) all the time. I'm using python 2.7.</p> <p>My problem is that I need to get the most significant two bytes (16 bits) of a number and check if they are the padding I inserted. I've tried <code>sys.getsizeof()</code> but that gives the size of the entire object and guess I could also iterate through every few bits of the number until there are only two bytes left, but is there a more pythonian way of doing this?</p> <p>Thanks in advance.</p>
1
2016-10-13T16:20:02Z
40,026,284
<p>Use <code>long.bit_length()</code>. E.g.:</p> <pre><code>% long.bit_length(1024L) 11 </code></pre> <p>Or:</p> <pre><code>% 1024L.bit_length() 11 </code></pre> <p>To get the first 2 bytes, assuming "first" means "least significant", use modulo 16:</p> <pre><code>x = 123456789 x % 2**16 52501 </code></pre>
1
2016-10-13T16:24:41Z
[ "python", "arbitrary-precision" ]
python3.5 not opening a .py file
40,026,247
<p>Hello im having trouble opening a .py file using processes call in python 3.5. ive have opened other files for example a text file using this method but with .py files it seems to just skip the command. Here is my code :</p> <p><code>import subprocess subprocess.call(['C:\\Users\\Edvin\\AppData\\Local\\Programs\\Python\\Python35-32\\pythonw.exe', 'C:\\Users\\Edvin\\Desktop\\test.py']) print ("done") </code></p> <p>There is no error it is simply doing >>> then >>>done when test.py isnt even open. Is this even possible for python to open another python file?</p> <p>the context of test.py is:</p> <pre><code>print("hello world") </code></pre> <p>reply=input("Say hello!")</p>
0
2016-10-13T16:22:24Z
40,026,504
<p>Try to use run instead of call, and you had a typo in your path.</p> <pre><code>subprocess.run(['C:\\Users\\Edvin\\AppData\\Local\\Programs\\Python\\Python35-32\\python.exe', 'C:\\Users\\Edvin\\Desktop\\test.py']) </code></pre>
1
2016-10-13T16:34:33Z
[ "python", "subprocess" ]
Sort list of strings with data in the middle of them
40,026,332
<p>So I have a list of strings which correlates to kibana indices, the strings look like this: </p> <pre><code>λ curl '10.10.43.210:9200/_cat/indices?v' health status index pri rep docs.count docs.deleted store.size pri.store.size yellow open filebeat-2016.10.08 5 1 899 0 913.8kb 913.8kb yellow open filebeat-2016.10.12 5 1 902 0 763.9kb 763.9kb yellow open filebeat-2016.10.13 5 1 816 0 588.9kb 588.9kb yellow open filebeat-2016.10.10 5 1 926 0 684.1kb 684.1kb yellow open filebeat-2016.10.11 5 1 876 0 615.2kb 615.2kb yellow open filebeat-2016.10.09 5 1 745 0 610.7kb 610.7kb </code></pre> <p>The dates are coming back unsorted. I want to sort these by the index (which is a date) filebeat-2016-10.xx ASC or DESC is fine. </p> <p>As it stands now I isolate the strings like this:</p> <pre><code> subp = subprocess.Popen(['curl','-XGET' ,'-H', '"Content-Type: application/json"', '10.10.43.210:9200/_cat/indices?v'], stdout=subproce$ curlstdout, curlstderr = subp.communicate() op = str(curlstdout) kibanaIndices = op.splitlines() for index,elem in enumerate(kibanaIndices): if "kibana" not in kibanaIndices[index]: print kibanaIndices[index]+"\n" kibanaIndexList.append(kibanaIndices[index]) </code></pre> <p>But can't sort them in a meaningful way.</p>
1
2016-10-13T16:26:57Z
40,026,532
<p>Is it what you need?</p> <pre><code>lines = """yellow open filebeat-2016.10.08 5 1 899 0 913.8kb 913.8kb yellow open filebeat-2016.10.12 5 1 902 0 763.9kb 763.9kb yellow open filebeat-2016.10.13 5 1 816 0 588.9kb 588.9kb yellow open filebeat-2016.10.10 5 1 926 0 684.1kb 684.1kb yellow open filebeat-2016.10.11 5 1 876 0 615.2kb 615.2kb yellow open filebeat-2016.10.09 5 1 745 0 610.7kb 610.7kb """.splitlines() def extract_date(line): return line.split()[2] lines.sort(key=extract_date) print("\n".join(lines)) </code></pre> <p>Here <code>extract_date</code> is a function that returns third column (like <code>filebeat-2016.10.12</code>). We use this function as <code>key</code> argument to <code>sort</code> to use this value as a sort key. You date format can be sorted just as strings. You can probably use more sophisticated <code>extract_line</code> function to extract only the date.</p>
1
2016-10-13T16:36:31Z
[ "python", "sorting" ]
Sort list of strings with data in the middle of them
40,026,332
<p>So I have a list of strings which correlates to kibana indices, the strings look like this: </p> <pre><code>λ curl '10.10.43.210:9200/_cat/indices?v' health status index pri rep docs.count docs.deleted store.size pri.store.size yellow open filebeat-2016.10.08 5 1 899 0 913.8kb 913.8kb yellow open filebeat-2016.10.12 5 1 902 0 763.9kb 763.9kb yellow open filebeat-2016.10.13 5 1 816 0 588.9kb 588.9kb yellow open filebeat-2016.10.10 5 1 926 0 684.1kb 684.1kb yellow open filebeat-2016.10.11 5 1 876 0 615.2kb 615.2kb yellow open filebeat-2016.10.09 5 1 745 0 610.7kb 610.7kb </code></pre> <p>The dates are coming back unsorted. I want to sort these by the index (which is a date) filebeat-2016-10.xx ASC or DESC is fine. </p> <p>As it stands now I isolate the strings like this:</p> <pre><code> subp = subprocess.Popen(['curl','-XGET' ,'-H', '"Content-Type: application/json"', '10.10.43.210:9200/_cat/indices?v'], stdout=subproce$ curlstdout, curlstderr = subp.communicate() op = str(curlstdout) kibanaIndices = op.splitlines() for index,elem in enumerate(kibanaIndices): if "kibana" not in kibanaIndices[index]: print kibanaIndices[index]+"\n" kibanaIndexList.append(kibanaIndices[index]) </code></pre> <p>But can't sort them in a meaningful way.</p>
1
2016-10-13T16:26:57Z
40,027,212
<p>I copied your sample data into a text file as UTF-8 since I don't have access to the server you referenced. Using list comprehensions and string methods you can clean the data then break it down into its component parts. Sorting is accomplished by passing a lambda function as an argument to the builtin sorted() method:</p> <pre><code># read text data into list one line at a time result_lines = open('kibana_data.txt').readlines() # remove trailing newline characters clean_lines = [line.replace("\n", "") for line in result_lines] # get first line of file info = clean_lines[0] # create list of field names header = [val.replace(" ", "") for val in clean_lines[1].split()] # create list of lists for data rows data = [[val.replace(" ", "") for val in line.split()] for line in clean_lines[2:]] # sort data rows by date (third row item at index 2) final = sorted(data, key=lambda row: row[2], reverse=False) </code></pre> <p>More info on list comprehensions here: <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow">https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions</a></p> <p>More info on sorting here: <a href="https://wiki.python.org/moin/HowTo/Sorting" rel="nofollow">https://wiki.python.org/moin/HowTo/Sorting</a></p>
0
2016-10-13T17:17:37Z
[ "python", "sorting" ]
Joining Dataframes on DatetimeIndex by Seconds and Minutes for NaNs
40,026,441
<p>I'm looking for a good way to align dataframes each having a timestamp that "includes" seconds without loosing data. Specifically, my problem looks as follows:</p> <p>Here <code>d1</code> is my "main" dataframe.</p> <pre><code>ind1 = pd.date_range("20120101", "20120102",freq='S')[1:20] data1 = np.random.randn(len(ind1)) df1 = pd.DataFrame(data1, index=ind1) </code></pre> <p>Eg. df1 could look like:</p> <pre><code> 0 2012-01-01 00:00:01 2.738425 2012-01-01 00:00:02 -0.323905 2012-01-01 00:00:03 1.861855 2012-01-01 00:00:04 0.480284 2012-01-01 00:00:05 0.340270 2012-01-01 00:00:06 -1.139052 2012-01-01 00:00:07 -0.203018 2012-01-01 00:00:08 -0.398599 2012-01-01 00:00:09 -0.568802 2012-01-01 00:00:10 -1.539783 2012-01-01 00:00:11 -1.778668 2012-01-01 00:00:12 -1.488097 2012-01-01 00:00:13 0.889712 2012-01-01 00:00:14 -0.620267 2012-01-01 00:00:15 0.075169 2012-01-01 00:00:16 -0.091302 2012-01-01 00:00:17 -1.035364 2012-01-01 00:00:18 -0.459013 2012-01-01 00:00:19 -2.177190 </code></pre> <p>In addition I have another dataframe, say df2:</p> <pre><code>ind21 = pd.date_range("20120101", "20120102",freq='S')[2:7] ind22 = pd.date_range("20120101", "20120102",freq='S')[12:19] data2 = np.random.randn(len(ind21+ind22)) df2 = pd.DataFrame(data2, index=ind21+ind22) </code></pre> <p>df2 looks like (note the non-periodic timestamps):</p> <pre><code> 0 2012-01-01 00:00:02 -1.877779 2012-01-01 00:00:03 1.772659 2012-01-01 00:00:04 0.037251 2012-01-01 00:00:05 -1.195782 2012-01-01 00:00:06 -0.145339 2012-01-01 00:00:12 -0.220673 2012-01-01 00:00:13 -0.581469 2012-01-01 00:00:14 -0.520756 2012-01-01 00:00:15 -0.562677 2012-01-01 00:00:16 0.109325 2012-01-01 00:00:17 -0.195091 2012-01-01 00:00:18 0.838294 </code></pre> <p>Now, I join both to df and get:</p> <pre><code>df = df1.join(df2, lsuffix='A') 0A 0 2012-01-01 00:00:01 2.738425 NaN 2012-01-01 00:00:02 -0.323905 -1.877779 2012-01-01 00:00:03 1.861855 1.772659 2012-01-01 00:00:04 0.480284 0.037251 2012-01-01 00:00:05 0.340270 -1.195782 2012-01-01 00:00:06 -1.139052 -0.145339 2012-01-01 00:00:07 -0.203018 NaN 2012-01-01 00:00:08 -0.398599 NaN 2012-01-01 00:00:09 -0.568802 NaN 2012-01-01 00:00:10 -1.539783 NaN 2012-01-01 00:00:11 -1.778668 NaN 2012-01-01 00:00:12 -1.488097 -0.220673 2012-01-01 00:00:13 0.889712 -0.581469 2012-01-01 00:00:14 -0.620267 -0.520756 2012-01-01 00:00:15 0.075169 -0.562677 2012-01-01 00:00:16 -0.091302 0.109325 2012-01-01 00:00:17 -1.035364 -0.195091 2012-01-01 00:00:18 -0.459013 0.838294 2012-01-01 00:00:19 -2.177190 NaN </code></pre> <p>This is fine, however, I would like to replace the NaN values in column 0 with the "minute level" value of df2. So only in cases where I don't have an exact match on the "seconds level", I would like to go back to the minute level. This could be a simple average over all values for that specific minute (here: 2012-01-01 00:00:00).</p> <p>Thx for any help!</p>
0
2016-10-13T16:32:13Z
40,026,898
<p>Use the DateTimeIndex attribute <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.minute.html" rel="nofollow"><code>.minute</code></a> to perform grouping and later fill the missing values with it's mean across each group(every minute):</p> <pre><code>df['0'] = df.groupby(df.index.minute)['0'].transform(lambda x: x.fillna(x.mean())) </code></pre>
0
2016-10-13T16:57:18Z
[ "python", "pandas", "datetimeindex", "datetime64" ]
Python SQLite removes/escapes part of regular expression pattern in user defined function
40,026,570
<p>I did a simple replace implementation for regular expressions in python sqlite3:</p> <pre><code>import sqlite3, re db = sqlite3.connect(':memory:') c = db.cursor() c.executescript(""" create table t2 (n REAL, v TEXT, t TEXT); insert into t2 VALUES (6, "F", "ef"); insert into t2 VALUES (1, "A", "aa"); insert into t2 VALUES (2, "B", "be"); insert into t2 VALUES (4, "D", "de"); insert into t2 VALUES (5, "E", "ee"); insert into t2 VALUES (3, "C", "ze"); """); db.commit() def preg_replace(string, pattern, replace): return re.sub(pattern, replace, string) db.create_function('replace',1,preg_replace) c = db.cursor() # This does not do anything c.execute("UPDATE t2 SET t=replace(t,?,?)",('e$','ee')) db.commit() c = db.cursor() c.execute("select * from t2") print c.fetchall() // This makes 'be' to 'bee' print preg_replace("be","e$","ee") </code></pre> <p>My problem is now that my UPDATE command does not replace 'e' at the end of the table entries.<br> If I use just 'e' as a pattern it works fine ('be' ends up as 'bee').<br> If I manually change 'be' in the table to 'be$', it gets modiefied to 'bee'.</p> <p>However, I can replace the 'e' at the end of the string if I use the preg_replace function directly.</p> <p>I do not understand why. is there some string escaping going on when the input for my user defined function goes to sqlite? Thanks a lot in advance.</p> <p>PS: Running Python 2.7.3</p>
0
2016-10-13T16:38:47Z
40,028,549
<p>You must tell <a href="https://docs.python.org/2/library/sqlite3.html#sqlite3.Connection.create_function" rel="nofollow">create_function()</a> how many parameters the function has.</p> <p>Your <code>preg_replace</code> will be used if the SQL calls <code>replace()</code> with one parameter.</p>
0
2016-10-13T18:38:51Z
[ "python", "sqlite", "sqlite3" ]
How to identify if __iter__ is called by dict or list?
40,026,579
<p>What I understand is <code>__iter__</code> method makes an object iterable. If it yields a pair, it produces a dictionary if called with <code>dict</code>. Now, if I want to create class that creates a list of values if called with <code>list</code> and creates a dict if called with <code>dict</code>, how to do that?</p> <p>Let say the class is this:</p> <pre><code>class Container(object): def __init__(self): self.pairs = [ ('key1', 'val1'), ('key2', 'val2'), ] def __getitem__(self, idx): return self.pairs[idx][1] # return value only def __iter__(self): for key, val in self.pairs: yield key, val </code></pre> <p>Now, if I use <code>list</code> or <code>dict</code>, I got:</p> <pre><code>data = Container() list(data) # [('key1', 'val1'), ('key2', 'val2')] dict(data) # {'key1': 'val1', 'key2': 'val2'} </code></pre> <p>What I want (with <code>list</code>) is:</p> <pre><code>list(data) # ['val1', 'val2'] </code></pre> <p>without keys.</p> <p>Is it possible? If yes, how?</p>
1
2016-10-13T16:39:29Z
40,026,656
<p>This isn't specifically what you want to do, but I'm not sure that what you want to do is that necessary. Let me know if it is-- though I'm not sure it's possible. In the meantime:</p> <p><code>list_data = [val for key,val in list(data)]</code></p> <p>Also what Blender said. That was really my first inclination, but I tried to stick more to what you were asking. Something like this:</p> <pre><code>def to_list(self): return [val for key,val in self.pairs] </code></pre>
0
2016-10-13T16:44:38Z
[ "python" ]
How to identify if __iter__ is called by dict or list?
40,026,579
<p>What I understand is <code>__iter__</code> method makes an object iterable. If it yields a pair, it produces a dictionary if called with <code>dict</code>. Now, if I want to create class that creates a list of values if called with <code>list</code> and creates a dict if called with <code>dict</code>, how to do that?</p> <p>Let say the class is this:</p> <pre><code>class Container(object): def __init__(self): self.pairs = [ ('key1', 'val1'), ('key2', 'val2'), ] def __getitem__(self, idx): return self.pairs[idx][1] # return value only def __iter__(self): for key, val in self.pairs: yield key, val </code></pre> <p>Now, if I use <code>list</code> or <code>dict</code>, I got:</p> <pre><code>data = Container() list(data) # [('key1', 'val1'), ('key2', 'val2')] dict(data) # {'key1': 'val1', 'key2': 'val2'} </code></pre> <p>What I want (with <code>list</code>) is:</p> <pre><code>list(data) # ['val1', 'val2'] </code></pre> <p>without keys.</p> <p>Is it possible? If yes, how?</p>
1
2016-10-13T16:39:29Z
40,026,697
<p>I think you have to do it manually with something like a list comprehension</p> <pre><code>[v for k, v in data] </code></pre>
1
2016-10-13T16:46:30Z
[ "python" ]
How to identify if __iter__ is called by dict or list?
40,026,579
<p>What I understand is <code>__iter__</code> method makes an object iterable. If it yields a pair, it produces a dictionary if called with <code>dict</code>. Now, if I want to create class that creates a list of values if called with <code>list</code> and creates a dict if called with <code>dict</code>, how to do that?</p> <p>Let say the class is this:</p> <pre><code>class Container(object): def __init__(self): self.pairs = [ ('key1', 'val1'), ('key2', 'val2'), ] def __getitem__(self, idx): return self.pairs[idx][1] # return value only def __iter__(self): for key, val in self.pairs: yield key, val </code></pre> <p>Now, if I use <code>list</code> or <code>dict</code>, I got:</p> <pre><code>data = Container() list(data) # [('key1', 'val1'), ('key2', 'val2')] dict(data) # {'key1': 'val1', 'key2': 'val2'} </code></pre> <p>What I want (with <code>list</code>) is:</p> <pre><code>list(data) # ['val1', 'val2'] </code></pre> <p>without keys.</p> <p>Is it possible? If yes, how?</p>
1
2016-10-13T16:39:29Z
40,027,115
<p>This is a terrible idea! But you can try reading the calling line to see if the explicit <code>list</code> constructor was calling using the <code>inspect</code> module. Note that this only works when the <code>list</code> constructor is called and will probably produce unexpected results when the regex matches something it wasn't intended to match.</p> <pre><code>import inspect, re class Container(object): def __init__(self): self.pairs = [ ('key1', 'val1'), ('key2', 'val2'), ] def __getitem__(self, idx): return self.pairs[idx][1] # return value only def __iter__(self): line = inspect.stack()[1][4][0] # print list(Container()) list_mode = re.match('^.*?list\(.*?\).*$', line) is not None for key, val in self.pairs: if list_mode: yield val else: yield key, val print list(Container()) # ['val1', 'val2'] </code></pre>
1
2016-10-13T17:11:57Z
[ "python" ]
Use scrapy with selenium for dynamic pages
40,026,586
<p>I want to crawl this pages for all the exibitors:</p> <p><a href="https://greenbuildexpo.com/Attendee/Expohall/Exhibitors" rel="nofollow">https://greenbuildexpo.com/Attendee/Expohall/Exhibitors</a></p> <p>But scrapy doesn't load the content, what I'm doing now it using selenium to load the page and search the links with scrapy:</p> <pre><code>url = 'https://greenbuildexpo.com/Attendee/Expohall/Exhibitors' driver_1 = webdriver.Firefox() driver_1.get(url) content = driver_1.page_source response = TextResponse(url='',body=content,encoding='utf-8') print len(set(response.xpath('//*[contains(@href,"Attendee/")]//@href').extract())) </code></pre> <p>The site doesn't seem to make any new request when "next" button is pressed so I was hoping to get all links at one, but I'm only getting 43 links with that code. They should be around 500.</p> <p>Now I'm trying to crawl the page by pressing the "next" button:</p> <pre><code>for i in range(10): xpath = '//*[@id="pagingNormalView"]/ul/li[15]' driver_1.find_element_by_xpath(xpath).click() </code></pre> <p>but I got an error:</p> <pre><code>File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 192, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: {"method":"xpath","selector":"//*[@id=\"pagingNormalView\"]/ul/li[15]"} Stacktrace: </code></pre>
1
2016-10-13T16:40:13Z
40,026,713
<p>You don't need <code>selenium</code> for that, there is an XHR request to get all exhibitors, simulate it, demo from the <a href="https://doc.scrapy.org/en/latest/topics/shell.html" rel="nofollow">Scrapy Shell</a>:</p> <pre><code>$ scrapy shell https://greenbuildexpo.com/Attendee/Expohall/Exhibitors In [1]: fetch("https://greenbuildexpo.com/Attendee/ExpoHall/GetAllExhibitors") 2016-10-13 12:45:46 [scrapy] DEBUG: Crawled (200) &lt;GET https://greenbuildexpo.com/Attendee/ExpoHall/GetAllExhibitors&gt; (referer: None) In [2]: import json In [3]: data = json.loads(response.body) In [4]: len(data["Data"]) Out[4]: 541 # printing booth number for demonstration purposes In [5]: for item in data["Data"]: ...: print(item["BoothNumber"]) ...: 2309 2507 ... 1243 2203 943 </code></pre>
3
2016-10-13T16:47:31Z
[ "python", "selenium", "xpath", "scrapy" ]
How to stop script if user inputs certain characters - PYTHON
40,026,651
<p>I'm a beginner in programming and I'm creating a roll the dice type of game. And I want to create a command in which if the user types in Exit, the whole script would print bye and stop. I tried something like:</p> <pre><code>commandLine = "Exit" if commandLine == "Exit". print ("Bye!") quit() </code></pre> <p>But it doesn`t work at all. The script would go on. This would be my script:</p> <pre><code>import random from random import randint import re print ("Welcome to Roll the Dice") roll = input("Do you want to Roll the Dice? \n Yes / No \n") if roll == "Yes".lower(): print("Nice , let`s do it!") elif roll == "No".lower(): print("Too bad! :( See you later!") quit() dice = input("Press 'x' to roll the dice!\n") if dice == "X".lower(): print(random.randint(1,9)) again = input("Sweet ! Would you like to try again?\n") while again == "Yes".lower(): dice = input("Press 'x' to roll the dice!\n") if dice == "X".lower(): print(random.randint(1, 9)) if again == "No".lower(): print("See you later!") quit() </code></pre>
0
2016-10-13T16:44:18Z
40,026,906
<p>try:</p> <pre><code>while again == "yes": dice = input("Press 'x' to roll the dice!\n") if dice == "x": print(random.randint(1, 9)) if dice == "no": print("See you later!") quit() </code></pre>
1
2016-10-13T16:57:44Z
[ "python" ]
How to stop script if user inputs certain characters - PYTHON
40,026,651
<p>I'm a beginner in programming and I'm creating a roll the dice type of game. And I want to create a command in which if the user types in Exit, the whole script would print bye and stop. I tried something like:</p> <pre><code>commandLine = "Exit" if commandLine == "Exit". print ("Bye!") quit() </code></pre> <p>But it doesn`t work at all. The script would go on. This would be my script:</p> <pre><code>import random from random import randint import re print ("Welcome to Roll the Dice") roll = input("Do you want to Roll the Dice? \n Yes / No \n") if roll == "Yes".lower(): print("Nice , let`s do it!") elif roll == "No".lower(): print("Too bad! :( See you later!") quit() dice = input("Press 'x' to roll the dice!\n") if dice == "X".lower(): print(random.randint(1,9)) again = input("Sweet ! Would you like to try again?\n") while again == "Yes".lower(): dice = input("Press 'x' to roll the dice!\n") if dice == "X".lower(): print(random.randint(1, 9)) if again == "No".lower(): print("See you later!") quit() </code></pre>
0
2016-10-13T16:44:18Z
40,026,983
<pre><code>again = input("Sweet ! Would you like to try again?\n") while again == "Yes".lower(): dice = input("Press 'x' to roll the dice!\n") if dice == "X".lower(): print(random.randint(1, 9)) again = input("Sweet ! Would you like to try again?\n") if again == "No".lower(): print("See you later!") quit() </code></pre> <p>This should fix it!</p>
0
2016-10-13T17:03:32Z
[ "python" ]
Arrow colour quiver plot - Python
40,026,718
<p>I am plotting an arrow graph and my code uses an external file as follows:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl from pylab import rcParams data=np.loadtxt(r'data.dat') x = data[:,0] y = data[:,1] u = data[:,2] v = data[:,3] plt.quiver(x, y, u, v, angles='xy', scale_units='xy', scale=1, pivot='mid',color='g') </code></pre> <p>The data file basically looks like :</p> <pre><code>0 0 0 1 0 1 1 0 1 0 1 0 1 1 0 1 </code></pre> <p>that generates a plot that looks like </p> <p><a href="https://i.stack.imgur.com/jkFgL.png" rel="nofollow"><img src="https://i.stack.imgur.com/jkFgL.png" alt="enter image description here"></a></p> <p>Is there a way to plot this with different colours for the different arrow directions?</p> <p>Ps.: I have got a lot more arrows in my data file in a not very logical sentence like the one I am using as example.</p>
1
2016-10-13T16:48:02Z
40,026,959
<p>This probably do the trick:</p> <pre><code>plt.quiver(x, y, u, v, np.arctan2(v, u), angles='xy', scale_units='xy', scale=1, pivot='mid',color='g') </code></pre> <p>Note that the fifth's argument of <code>plt.quiver</code> is a color. <a href="https://i.stack.imgur.com/Nc5mK.png" rel="nofollow"><img src="https://i.stack.imgur.com/Nc5mK.png" alt="colored arrows"></a></p> <hr> <p>UPD. If you want to control the colors, you have to use <a href="http://matplotlib.org/users/colormaps.html" rel="nofollow">colormaps</a>. Here are a couple of examples:</p> <p>Use colormap with <code>colors</code> parameter:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm from matplotlib.colors import Normalize %matplotlib inline ph = np.linspace(0, 2*np.pi, 13) x = np.cos(ph) y = np.sin(ph) u = np.cos(ph) v = np.sin(ph) colors = arctan2(u, v) norm = Normalize() norm.autoscale(colors) # we need to normalize our colors array to match it colormap domain # which is [0, 1] colormap = cm.inferno # pick your colormap here, refer to # http://matplotlib.org/examples/color/colormaps_reference.html # and # http://matplotlib.org/users/colormaps.html # for details plt.figure(figsize=(6, 6)) plt.xlim(-2, 2) plt.ylim(-2, 2) plt.quiver(x, y, u, v, color=colormap(norm(colors)), angles='xy', scale_units='xy', scale=1, pivot='mid') </code></pre> <p><a href="https://i.stack.imgur.com/EWeAj.png" rel="nofollow"><img src="https://i.stack.imgur.com/EWeAj.png" alt="different colormap"></a></p> <p>You can also stick with fifth argument like in my first example (which works in a bit different way comparing with <code>colors</code>) and change default colormap to control the colors.</p> <pre><code>plt.rcParams['image.cmap'] = 'Paired' plt.figure(figsize=(6, 6)) plt.xlim(-2, 2) plt.ylim(-2, 2) plt.quiver(x, y, u, v, np.arctan2(v, u), angles='xy', scale_units='xy', scale=1, pivot='mid') </code></pre> <p><a href="https://i.stack.imgur.com/9evy3.png" rel="nofollow"><img src="https://i.stack.imgur.com/9evy3.png" alt="Paired colormap"></a></p> <p>You can also create your own colormaps, see e.g. <a href="http://stackoverflow.com/questions/16834861/create-own-colormap-using-matplotlib-and-plot-color-scale">here</a>.</p>
3
2016-10-13T17:01:45Z
[ "python", "arrays", "matplotlib", "plot", "arrow" ]
3D surface plot from a .dat file
40,026,758
<p>Hi I am trying to do a 3D surface plot in python by plotting from a .dat file. I am having quite some trouble. I finally have a code that does not produce any error messages, however the plot displays nothing, even though the .dat file is not empty. My code is below. </p> <p>How can I plot my data from a .dat file via a 3Dsurface plot? My data is formatted in the .dat file as three columns. Thanks for the help!</p> <p>Update: The .dat file is not empty, I am able to plot the same .dat file with a 3D scatter plot fine, but it will not work in this 3D surface plot code. The .dat file looks something like this (just 3 columns of numbers):</p> <pre><code>1 2 6 3 8 7 4 9 3 5 2 5 from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm import matplotlib.pyplot as plt from matplotlib.mlab import griddata import numpy as np fig = plt.figure() ax = fig.gca(projection='3d') data = np.genfromtxt('file.dat') x = data[:,0] y = data[:,1] z = data[:,2] xi = np.linspace(min(x), max(x),0.1) yi = np.linspace(min(y), max(y),0.1) X, Y = np.meshgrid(xi, yi) Z = griddata(x, y, z, xi, yi, interp='linear') ax.set_xlabel('$x$', fontsize = 14) ax.set_ylabel('$y$', fontsize = 14) ax.set_zlabel('$z$', fontsize = 14) ax.set_title('result..', fontsize = 14) surf = ax.plot_surface(X, Y, Z, linewidth=1, antialiased=True) ax.set_zlim3d(0,1) plt.show() </code></pre>
0
2016-10-13T16:49:38Z
40,048,917
<p>My guess is that your problem comes down to a rather trivial mistake you're making with <code>np.linspace</code> that I didn't notice when I commented. The third argument of <code>np.linspace</code> is the number of points in the array, not the spacing between points (that would be <code>np.arange</code>).</p> <p>In case I'm wrong, I'll show a full working example here (modified from <a href="http://matplotlib.org/examples/pylab_examples/griddata_demo.html" rel="nofollow">http://matplotlib.org/examples/pylab_examples/griddata_demo.html</a>), and if your surface plot still doesn't show up when running this example, then it may be a more basic issue you're having with <code>matplotlib</code>.</p> <pre><code>from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm import matplotlib.pyplot as plt from matplotlib.mlab import griddata import numpy as np fig = plt.figure() ax = fig.gca(projection='3d') #data = np.genfromtxt('file.dat') npts = 1000 x = np.random.uniform(-2, 2, npts) y = np.random.uniform(-2, 2, npts) z = x*np.exp(-x**2 - y**2) xi = np.linspace(min(x), max(x), 100) # &lt;-- note change to 100 yi = np.linspace(min(y), max(y), 100) # &lt;-- note change to 100 X, Y = np.meshgrid(xi, yi) Z = griddata(x, y, z, xi, yi, interp='linear') surf = ax.plot_surface(X, Y, Z, rstride=5, cstride=5, cmap=cm.viridis, linewidth=1, antialiased=True) ax.set_zlim3d(np.min(Z), np.max(Z)) fig.colorbar(surf) </code></pre> <p><a href="https://i.stack.imgur.com/cWm5E.png" rel="nofollow"><img src="https://i.stack.imgur.com/cWm5E.png" alt="enter image description here"></a></p> <p>Note that your use of <code>ax.set_zlim3d(0,1)</code> could also be an issue. I wouldn't recommend setting limits on your axes before you see your data plotted.</p>
1
2016-10-14T17:32:05Z
[ "python", "matplotlib", "plot" ]
Load preset directory in Maya with python/MEL?
40,026,880
<p>I have a folder where I'm storing some maya presets (specifically nCloth presets) and I would like to make this directory available to all of the users on my current network. To do this, I would like to have this folder added to the MAYA_PRESET_PATH on startup. However, I am not able to create/modify the maya.env file (restricted permissions on network). So, is there a way to append a directory to maya's environment variables using python or MEL, so that I can call a script on startup to dynamically load all of my presets? </p> <p>I tried the following in my startup MEL script, but to no avail...</p> <pre><code>python("PRESET_DIR = os.environ.get('MAYA_CUSTOM_PRESET_DIR')"); //Path to my custom preset directory python("PRESET_DIR = os.environ.get('MAYA_PRESET_PATH') + ':' + PRESET_DIR"); python("os.putenv('MAYA_PRESET_PATH', PRESET_DIR)"); </code></pre>
0
2016-10-13T16:56:21Z
40,041,458
<p>in your maya.env: </p> <pre><code>CUSTOM_BASE_PATH = C:\MayaResource #your custom env MAYA_PRESET_PATH = %CUSTOM_BASE_PATH%\preset;%CUSTOM_BASE_PATH%\plugins; </code></pre>
0
2016-10-14T10:55:26Z
[ "python", "maya", "mel", "pymel" ]
Data Scraping a Locally Stored HTML File - using Python
40,026,885
<p>I have a big Excel file, and in each cell I have various HTML content containing comments made by a database user. The content in each cell is unique and varying in length. I need to get rid of all HTML syntax/tags so that I can upload this content to a database table. How can I scrape this data using Python (or Java if there are no answers for Python)? Could you provide a code example?</p>
0
2016-10-13T16:56:44Z
40,031,131
<p>In a terminal, <code>pip install bs4</code>. Then you can extract the text with python like so:</p> <pre><code>import bs4 for cell in [ '&lt;html&gt;The indicator lights on the control cabinet&amp;nbsp;are to be replaced with 24Vdc&amp;nbsp;LED\'s. 3 Red &amp;amp;&amp;nbsp;3 Green.&lt;/html&gt;', '&lt;html&gt;&lt;div&gt; &lt;span style=""FONT-SIZE: 18pt""&gt;Close the Monthly LAD and Lanyard Work orders to show they were executed. &lt;/span&gt;&lt;/div&gt;']: print(bs4.BeautifulSoup(cell).text.strip()) </code></pre> <p>Result:</p> <pre><code>The indicator lights on the control cabinet are to be replaced with 24Vdc LED's. 3 Red &amp; 3 Green. Close the Monthly LAD and Lanyard Work orders to show they were executed. </code></pre>
0
2016-10-13T21:16:08Z
[ "java", "python", "html", "web-scraping" ]
Python "list index out of range" other rule works
40,026,900
<p>I have tried to make a script to read out a csv file and determine some information.</p> <p>Now I receive an error: </p> <pre><code>Traceback (most recent call last): File "/home/pi/vullijst/vullijst.py", line 26, in &lt;module&gt; startdate = datetime.datetime.strptime (row[0],"%d-%m-%Y") IndexError: list index out of range </code></pre> <p>Part of Script:</p> <pre><code>import csv import datetime import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText #Variabelen smtpserver = '' smtplogin = '' smtppassword = '' sender = '' csvfile = '/home/pi/vullijst/vullijst.csv' #Inlezen CSV File f = open(csvfile) csv_f = csv.reader(f, delimiter=';') today = datetime.datetime.now() #Tijd bepalen en opstellen E-mail for row in csv_f: startdate = datetime.datetime.strptime (row[0],"%d-%m-%Y") enddate = datetime.datetime.strptime (row[1],"%d-%m-%Y") if today &gt;= startdate and today &lt;= enddate: receiver = row[3] </code></pre> <p>The csv file has the following structure:</p> <pre><code>1-10-2016;12-10-2016;Test 1;[email protected];06-123456789 12-10-2016;13-10-2016;Test 2;[email protected];06-123456789 13-10-2016;14-10-2016;Test 3;[email protected];06-123456789 14-10-2016;15-10-2016;Test 4;[email protected];06-123456790 15-10-2016;16-10-2016;Test 5;[email protected];06-123456791 16-10-2016;17-10-2016;Test 6;[email protected];06-123456792 17-10-2016;18-10-2016;Test 7;[email protected];06-123456793 </code></pre> <p>If I comment out this rule then I don't receive the error on the rule below. Does somebody know what is wrong?</p>
1
2016-10-13T16:57:23Z
40,064,126
<p>Your csv file appears to have an empty line at the end, after the last row with real data. So your script reads all the real lines and processes them, but it breaks when the last line is parsed into an empty list. The <code>row[0]</code> you're trying to parse into a date isn't valid in that situation.</p> <p>To avoid this issue, put a check at the top of your loop that skips the rest of the loop body if <code>row</code> is empty.</p> <pre><code>for row in csv_f: if not row: # skip empty rows continue startdate = datetime.datetime.strptime (row[0],"%d-%m-%Y") # ... </code></pre>
0
2016-10-15T20:56:08Z
[ "python" ]
Python Version (sys.version) Meaning?
40,026,902
<p>I've hit what should be a basic question... but my googles are failing me and I need a sanity check. </p> <p>If I run the following in my Python shell:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; sys.version </code></pre> <p>from two different Python environments, I get:</p> <pre><code>'2.7.8 (default, Nov 10 2014, 08:19:18) \n[GCC 4.9.2 20141101 (Red Hat 4.9.2-1)]' </code></pre> <p>and...</p> <pre><code>'2.7.8 (default, Apr 15 2015, 09:26:43) \n[GCC 4.9.2 20150212 (Red Hat 4.9.2-6)]' </code></pre> <p>Does that mean the two environments are actually running slightly different Python guts or is it enough that the '2.7.8' bit in that version string is the same so I can be confident these are 1:1 identical Python interpreters? </p> <p>If I am guaranteed they are the same, then what's the significance of the date and other parts of that version output string?</p>
1
2016-10-13T16:57:31Z
40,026,927
<p>All you need to compare is the first bit, the 2.7.8 string.</p> <p>The differences you see are due to the <em>compiler</em> used to build the binary, and when the binary was built. That shouldn't really make a difference here.</p> <p>The string is comprised of information you can find in machine-readable form elsewhere; specifically:</p> <ul> <li><p><a href="https://docs.python.org/2/library/platform.html#platform.python_version" rel="nofollow"><code>platform.python_version()</code></a></p> <blockquote> <p>Returns the Python version as string 'major.minor.patchlevel'.</p> </blockquote></li> <li><p><a href="https://docs.python.org/2/library/platform.html#platform.python_build" rel="nofollow"><code>platform.python_build()</code></a></p> <blockquote> <p>Returns a tuple <code>(buildno, builddate)</code> stating the Python build number and date as strings.</p> </blockquote></li> <li><p><a href="https://docs.python.org/2/library/platform.html#platform.python_compiler" rel="nofollow"><code>platform.python_compiler()</code></a></p> <blockquote> <p>Returns a string identifying the compiler used for compiling Python.</p> </blockquote></li> </ul> <p>For your sample strings, what differs is the date the binary was build (second value of the <code>platform.python_build()</code> tuple) and the exact revision of the GCC compiler used (from the <code>platform.python_compiler()</code> string). Only when there are specific problems with the compiler would this matter.</p> <p>You should normally only care about the Python version information, which is more readily available as the <a href="https://docs.python.org/2/library/sys.html#sys.version_info" rel="nofollow"><code>sys.version_info</code> tuple</a>.</p>
5
2016-10-13T16:58:58Z
[ "python" ]
Python - REGEX issue with RE using function re.compile + search
40,026,923
<p>I'm using regex library 're' in Python (2.7) to validate a flight number.</p> <p>I've had no issues with expected outputs using a really helpful online editor here: <a href="http://regexr.com/" rel="nofollow">http://regexr.com/</a></p> <p>My results on regexr.com are: <a href="http://imgur.com/nB0QDug" rel="nofollow">http://imgur.com/nB0QDug</a></p> <p>My code is:</p> <pre><code>import re test1 = 'ba116' ###Referencelink: http://academe.co.uk/2014/01/validating-flight-codes/ p = re.compile('/^([a-z][a-z]|[a-z][0-9]|[0-9][a-z])[a-z]?[0-9]{1,4}[a-z]?$/g') m = p.search(test1) # p.match() to find from start of string only if m: print 'It works!: ', m.group() # group(1...n) for capture groups else: print 'Did not work' </code></pre> <p>I'm unsure why I get the 'didn't work' output where regexr shows one match (as expected)</p> <p>I made a much simpler regex lookup, and it <em>seemed</em> that the results were correct, so it seems either my regex string is invalid, or I'm using re.complile (or perhaps the if loop) incorrectly?</p> <p>'ba116' is valid, and should match.</p>
0
2016-10-13T16:58:44Z
40,027,046
<p>Python's <code>re.compile</code> is treating your leading <code>/</code> and trailing <code>/g</code> as part of the regular expression, not as delimiters and modifiers. This produces a compiled RE that will never match anything, since you have <code>^</code> with stuff before it and <code>$</code> with stuff after it.</p> <p>The first argument to <code>re.compile</code> should be a string containing <em>only</em> the stuff you would put inside the slashes in a language that had <code>/.../</code> regex notation. The <code>g</code> modifier corresponds to calling the <code>findall</code> method on the compiled RE; in this case it appears to be unnecessary. (Some of the other modifiers, e.g. <code>i</code>, <code>s</code>, <code>m</code>, correspond to values passed to the <em>second</em> argument to <code>re.compile</code>.)</p> <p>So this is what your code should look like:</p> <pre><code>import re test1 = 'ba116' ###Referencelink: http://academe.co.uk/2014/01/validating-flight-codes/ p = re.compile(r'^([a-z][a-z]|[a-z][0-9]|[0-9][a-z])[a-z]?[0-9]{1,4}[a-z]?$') m = p.search(test1) # p.match() to find from start of string only if m: print 'It works!: ', m.group() # group(1...n) for capture groups else: print 'Did not work' </code></pre> <p>The <code>r</code> immediately before the open quote makes no difference for <em>this</em> regular expression, but if you needed to use backslashes in the RE it would save you from having to double all of them.</p>
1
2016-10-13T17:08:15Z
[ "python", "regex", "if-statement" ]
Python: Connecting list values with array values
40,026,930
<p>I have created a tornado plot taking inspiration from <a href="http://stackoverflow.com/questions/32132773/a-tornado-chart-and-p10-p90-in-python-matplotlib">here</a>. It has input variables labelled on the y-axis (a1,b1,c1...) and their respective correlation coefficients plotted next to them. See pic below:</p> <p><a href="https://i.stack.imgur.com/4NE3f.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/4NE3f.jpg" alt="enter image description here"></a></p> <p>I then sorted the correlation coefficients in a way that the highest absolute value without loosing its sign gets plotted first, then the next highest and so on. using <code>sorted(values,key=abs, reverse=True)</code>. See the result below</p> <p><a href="https://i.stack.imgur.com/xamYL.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/xamYL.jpg" alt="enter image description here"></a></p> <p>If you notice, in the second pic even though the bars were sorted in the absolute descending order, the y-axis label still stay the same.</p> <p>Question: How do I make the y-axis label(variable) connect to the correlation coefficient such that it always corresponds to its correlation coefficient.</p> <p>Below is my code:</p> <pre><code>import numpy as np from matplotlib import pyplot as plt #####Importing Data from csv file##### dataset1 = np.genfromtxt('dataSet1.csv', dtype = float, delimiter = ',', skip_header = 1, names = ['a', 'b', 'c', 'x0']) dataset2 = np.genfromtxt('dataSet2.csv', dtype = float, delimiter = ',', skip_header = 1, names = ['a', 'b', 'c', 'x0']) dataset3 = np.genfromtxt('dataSet3.csv', dtype = float, delimiter = ',', skip_header = 1, names = ['a', 'b', 'c', 'x0']) corr1 = np.corrcoef(dataset1['a'],dataset1['x0']) corr2 = np.corrcoef(dataset1['b'],dataset1['x0']) corr3 = np.corrcoef(dataset1['c'],dataset1['x0']) corr4 = np.corrcoef(dataset2['a'],dataset2['x0']) corr5 = np.corrcoef(dataset2['b'],dataset2['x0']) corr6 = np.corrcoef(dataset2['c'],dataset2['x0']) corr7 = np.corrcoef(dataset3['a'],dataset3['x0']) corr8 = np.corrcoef(dataset3['b'],dataset3['x0']) corr9 = np.corrcoef(dataset3['c'],dataset3['x0']) np.set_printoptions(precision=4) variables = ['a1','b1','c1','a2','b2','c2','a3','b3','c3'] base = 0 values = np.array([corr1[0,1],corr2[0,1],corr3[0,1], corr4[0,1],corr5[0,1],corr6[0,1], corr7[0,1],corr8[0,1],corr9[0,1]]) values = sorted(values,key=abs, reverse=True) # The y position for each variable ys = range(len(values))[::-1] # top to bottom # Plot the bars, one by one for y, value in zip(ys, values): high_width = base + value #print high_width # Each bar is a "broken" horizontal bar chart plt.broken_barh( [(base, high_width)], (y - 0.4, 0.8), facecolors=['red', 'red'], # Try different colors if you like edgecolors=['black', 'black'], linewidth=1) # Draw a vertical line down the middle plt.axvline(base, color='black') # Position the x-axis on the top/bottom, hide all the other spines (=axis lines) axes = plt.gca() # (gca = get current axes) axes.spines['left'].set_visible(False) axes.spines['right'].set_visible(False) axes.spines['top'].set_visible(False) axes.xaxis.set_ticks_position('bottom') # Make the y-axis display the variables plt.yticks(ys, variables) plt.ylim(-2, len(variables)) plt.show() </code></pre> <p>Many thanks in advance</p>
0
2016-10-13T16:59:21Z
40,028,171
<p>use build-in zip function - returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. But aware the returned list is truncated in length to the length of the shortest argument sequence.</p>
0
2016-10-13T18:16:24Z
[ "python", "python-2.7", "matplotlib" ]
scikit- DBSCAN giving error on clustering (x.y) co-ordinate points
40,027,042
<p>I am trying to computer ORB descriptors for an image and cluster them <em>spatially</em>. I was trying to use DBSCAN in scikit</p> <pre><code>detector = cv2.ORB(500) orb_kp = detector.detect(gray,None) # compute the descriptors with ORB kps, descs = detector.compute(gray, orb_kp) img2 = cv2.drawKeypoints(gray,kps,color=(0,255,0), flags=0) #extract the x,y points from the list (since kp contains various other attribs) pts = (p.pt for p in kps) db = DBSCAN(eps=0.3, min_samples=5).fit(pts) </code></pre> <p>but I get this error:</p> <p><code>float() argument must be a string or a number</code></p> <p>so I tried : <code>pts = (int(p.pt) for p in kps)</code> and <code>pts = ([int(p.pt.x),int(p.pt.y)] for p in kps)</code> and still get the same error.</p> <p>I tried printing the pts in python but get this message:</p> <p><code>print pts None &lt;generator object &lt;genexpr&gt; at 0x10fcab3c0&gt;</code></p> <p>I am not sure how I can "cast" the <code>float</code> type for points into an <code>int</code></p>
0
2016-10-13T17:07:56Z
40,028,389
<p>OK posting an answer for anyone who has the same issue:</p> <p><code>pts = (p.pt for p in kps)</code> is incorrect</p> <p>it should be: <code>pts = [p.pt for p in kps]</code></p> <p>Silly me!</p>
0
2016-10-13T18:29:15Z
[ "python", "scikit-learn" ]
Aborted connection error in flask
40,027,108
<p>If the client closes an established connection that it has made with the <em>flask</em> server, I get the following error in the terminal: </p> <pre><code>[Errno 10053] An established connection was aborted by the software in your host machine </code></pre> <p>It seems when <em>flask</em> tries to write in the closed stream, it faces errors and hence will complain.<br> It seemed like a warning or so as the application does not quit after printing the error, but the problem is that my server will stop serving other requests despite being alive in the system. </p> <p>I have read similar questions but they did not help. How can I prevent this issue? I use both Windows and Linux operating systems.</p>
2
2016-10-13T17:11:19Z
40,027,326
<p>The cause of this problem is, as we previously discussed, insufficient permissions to perform the network operation. The remedy to the problem was to run the process as an administrator and/or to modify the system policy to allow connections on the restricted port.</p>
2
2016-10-13T17:24:46Z
[ "python", "flask", "flask-restful" ]
URL parameters with GET request in django
40,027,119
<p>guys. I'm passing parameters via GET requests to my view. But it seems that django is not properly handling my URL.</p> <p>With parameters longer than one char, it works, but if I use a single char, I get Page not found (404) error.</p> <p>Example:</p> <p><strong>Works:</strong> <a href="http://localhost:8000/my_url/test" rel="nofollow">http://localhost:8000/my_url/test</a></p> <p><strong>Not found:</strong> <a href="http://localhost:8000/my_url/t" rel="nofollow">http://localhost:8000/my_url/t</a></p> <p>urls.py code fragment:</p> <pre><code>url(r'^my_url/(?P&lt;username&gt;\w.+)/$', views.my_url, name='my_url'), </code></pre> <p>Is there any django restriction to the length of parameters passed via GET? Thanks a lot in advance!</p>
0
2016-10-13T17:12:17Z
40,027,353
<p>Remove dot from regex string <code>r'^my_url/(?P&lt;username&gt;\w+)/$'</code></p>
2
2016-10-13T17:26:08Z
[ "python", "regex", "django" ]
python subprocess module hangs for spark-submit command when writing STDOUT
40,027,207
<p>I have a python script that is used to submit spark jobs using the spark-submit tool. I want to execute the command and write the output both to STDOUT and a logfile in real time. i'm using python 2.7 on a ubuntu server.</p> <p>This is what I have so far in my SubmitJob.py script</p> <pre><code>#!/usr/bin/python # Submit the command def submitJob(cmd, log_file): with open(log_file, 'w') as fh: process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while True: output = process.stdout.readline() if output == '' and process.poll() is not None: break if output: print output.strip() fh.write(output) rc = process.poll() return rc if __name__ == "__main__": cmdList = ["dse", "spark-submit", "--spark-master", "spark://127.0.0.1:7077", "--class", "com.spark.myapp", "./myapp.jar"] log_file = "/tmp/out.log" exist_status = submitJob(cmdList, log_file) print "job finished with status ",exist_status </code></pre> <p>The strange thing is, when I execute the same command direcly in the shell it works fine and produces output on screen as the proggram proceeds.</p> <p>So it looks like something is wrong in the way I'm using the subprocess.PIPE for stdout and writing the file.</p> <p>What's the current recommended way to use subprocess module for writing to stdout and log file in real time line by line? I see bunch of options on the internet but not sure which is correct or latest.</p> <p>thanks</p>
0
2016-10-13T17:17:09Z
40,046,887
<p>Figured out what the problem was. I was trying to redirect both stdout n stderr to pipe to display on screen. This seems to block the stdout when stderr is present. If I remove the stderr=stdout argument from Popen, it works fine. So for spark-submit it looks like you don't need to redirect stderr explicitly as it already does this implicitly </p>
0
2016-10-14T15:29:52Z
[ "python", "linux", "python-2.7", "apache-spark", "subprocess" ]
How to connect PyQt signal to external function
40,027,221
<p>How does one connect a pyqt button signal in one file, to a function in another python file? I've tried various things, but nothing seems to work. This is the first file:</p> <pre><code>from PyQt4 import QtGui from PyQt4.QtGui import QMainWindow from MainUIFile import Ui_Main from pythonfile import myOutsideFunction class MainWindow(QMainWindow,Ui_file): def __init__(self): QMainWindow.__init__(self) self.setupUi(self) self.btn.clicked.connect(myOutsideFunction()) </code></pre> <p>The second file that is called by the first:</p> <pre><code>def myOutsideFunction(self): # Do some stuff here </code></pre> <p>How would I go about doing this?</p>
0
2016-10-13T17:18:06Z
40,027,367
<p>You are currently making a call to <code>myOutsideFunction</code> and passing the result to the <code>connect</code> function, which expects a callable as an argument. </p> <p>Remove the parenthesis from <code>myOutsideFunction</code> in the connect call</p> <pre><code>self.btn.clicked.connect(myOutsideFunction) </code></pre>
2
2016-10-13T17:26:58Z
[ "python", "windows", "file", "pyqt" ]
How to connect PyQt signal to external function
40,027,221
<p>How does one connect a pyqt button signal in one file, to a function in another python file? I've tried various things, but nothing seems to work. This is the first file:</p> <pre><code>from PyQt4 import QtGui from PyQt4.QtGui import QMainWindow from MainUIFile import Ui_Main from pythonfile import myOutsideFunction class MainWindow(QMainWindow,Ui_file): def __init__(self): QMainWindow.__init__(self) self.setupUi(self) self.btn.clicked.connect(myOutsideFunction()) </code></pre> <p>The second file that is called by the first:</p> <pre><code>def myOutsideFunction(self): # Do some stuff here </code></pre> <p>How would I go about doing this?</p>
0
2016-10-13T17:18:06Z
40,031,710
<p>What is the importance of connecting to a function outside of your code? Could you not just do something like this:</p> <pre><code>def myOutsideFunction(a,b,c,d): #process variables/objects a,b,c,d as you wish return answer from PyQt4 import QtGui from PyQt4.QtGui import QMainWindow from MainUIFile import Ui_Main from pythonfile import myOutsideFunction class MainWindow(QMainWindow,Ui_file): def __init__(self): QMainWindow.__init__(self) self.setupUi(self) self.btn.clicked.connect(self.pressed_the_button()) #initialize your variables/objects for your outside function if need be def pressed_the_button(self): answer_from_outside_function = myOutsideFunction(self.a,self.b,self.c,self.d) # run whatever you need to here... </code></pre>
0
2016-10-13T21:59:01Z
[ "python", "windows", "file", "pyqt" ]
access pandas axes by axis number
40,027,233
<p>consider the <code>pd.Panel</code> <code>pn</code> and <code>pd.DataFrame</code> <code>df</code></p> <pre><code>import pandas as pd import numpy as np pn = pd.Panel(np.arange(27).reshape(3, 3, 3), list('XYZ'), list('abc'), list('ABC')) pn.to_frame().rename_axis('item', 1).unstack() </code></pre> <p><a href="https://i.stack.imgur.com/3Gpon.png" rel="nofollow"><img src="https://i.stack.imgur.com/3Gpon.png" alt="enter image description here"></a></p> <pre><code>df = pd.DataFrame(np.arange(9).reshape(3, 3), list('abc'), list('ABC')) df </code></pre> <p><a href="https://i.stack.imgur.com/gyjvS.png" rel="nofollow"><img src="https://i.stack.imgur.com/gyjvS.png" alt="enter image description here"></a></p> <hr> <p>I can access the <code>items</code> axis of <code>pn</code> with <code>pn.items</code> and the <code>columns</code> axis of <code>df</code> with <code>df.columns</code>.</p> <p><strong><em>Question</em></strong><br> But how do I get the <code>items</code> axis of <code>pn</code> with the number <code>0</code> and <code>minor_axis</code> axis with the number <code>2</code>? With as many methods that accept the parameter <code>axis=0</code>, I'm imagining there is a straight forward way to access axes via number.</p> <p><strong><em>What I've done</em></strong><br> Custom function</p> <pre><code>def get_axis(obj, axis=0): if isinstance(obj, pd.Panel): m = pd.Series(['items', 'major_axis', 'minor_axis']) else: m = pd.Series(['index', 'columns']) return obj.__getattribute__(m.loc[axis]) print(get_axis(pn, 2)) print(get_axis(pn, 1)) print(get_axis(pn, 0)) print(get_axis(df, 1)) print(get_axis(df, 0)) </code></pre> <hr> <pre><code>Index([u'A', u'B', u'C'], dtype='object') Index([u'a', u'b', u'c'], dtype='object') Index([u'X', u'Y', u'Z'], dtype='object') Index([u'A', u'B', u'C'], dtype='object') Index([u'a', u'b', u'c'], dtype='object') </code></pre>
2
2016-10-13T17:19:08Z
40,029,515
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Panel.axes.html" rel="nofollow"><code>.axes</code></a> to return a list of the index axis labels as well as the column axis labels and then you could access it via slice-notation.</p> <pre><code>pn.axes #[Index(['X', 'Y', 'Z'], dtype='object'), # Index(['a', 'b', 'c'], dtype='object'), # Index(['A', 'B', 'C'], dtype='object')] </code></pre> <p>Then, you could provide the slices to retrieve the objects:</p> <pre><code>pn.axes[0] #Index(['X', 'Y', 'Z'], dtype='object') df.axes[0] #Index(['a', 'b', 'c'], dtype='object') </code></pre>
2
2016-10-13T19:37:24Z
[ "python", "pandas" ]
Django Across All Apps
40,027,239
<p>I am creating a rather large django project which will require two things. 1) I need a few template files to be accessible across all apps. 2) I need a model to be accessible across all apps. How do I go about doing that? </p> <p>As far as the templates are concerned, it seems adding it to the TEMPLATES directive doesn't work.</p> <p>As far as the models are concerned, can I have a models.py in the project/project folder or something like that to be accessible by all apps?</p> <p>Django 1.10 and Python 3.5</p> <pre><code>TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { [...] </code></pre>
0
2016-10-13T17:19:24Z
40,028,159
<p>Was able to work it out with this work around.</p> <pre><code>BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR + '/templates'], 'APP_DIRS': True, 'OPTIONS': { [...] </code></pre>
0
2016-10-13T18:15:46Z
[ "python", "django" ]
Installed Python 3.5.2 (64bit) however can't open python
40,027,272
<p>I have installed Python 3.5.2 (64bit) however once I had installed it I couldn't find a link to open python and I couldn't find it on the program files. Is there a way to open it on the run command or how do I open it?</p> <p>I am using a 64bit AMD processsor and Windows 7 home basic 64 bit</p> <p>Kind Regards</p>
-2
2016-10-13T17:21:54Z
40,027,535
<p><strong>Windows</strong></p> <p>Default location on Windows <code>C:\Python</code> You can open cmd type <code>python</code> SHELL opens immediatly If python command not recognized you can add python location: <code>C:\Python</code> to <code>PATH</code> Environment variable Then reopen cmd type <code>python</code> Also you can find <code>IDLE</code> in start menu </p>
0
2016-10-13T17:36:50Z
[ "python" ]
Can a python unittest class add an assert statement for each test method in a parent class?
40,027,324
<p>I have a unit test class that is a sub-class of python's <code>unittest</code>:</p> <pre><code>import unittest class MyTestClass(unittest.TestCase): run_parameters = {param1: 'on'} def someTest(self): self.assertEquals(something, something_else) </code></pre> <p>Now I want to create a child class that modifies, say <code>run_parameters</code>, and adds an additional assert statement on top of what was already written:</p> <pre><code>class NewWayToRunThings_TestClass(MyTestClass): run_parameters = {param1: 'blue'} # Want someTest, and all other tests in MyTestClass to now run # with an additional assert statement </code></pre> <p>Is there someway to accomplish this so that each test runs with an additional assert statement to check that my parameter change worked properly across all my tests?</p>
0
2016-10-13T17:24:39Z
40,029,718
<p>Yes there is but it may not be a good idea because:</p> <ul> <li>assertions are hidden behind difficult to understand python magic</li> <li>assertions aren't explicit</li> </ul> <p>Could you update your methods to reflect the new contract, and expected param?</p> <p>Also if a single parameter change breaks a huge amount of tests, where it is easier to dynamically patch the test class then it is to update the tests, the test suite may not be focused enough. </p>
0
2016-10-13T19:49:59Z
[ "python", "unit-testing", "oop" ]
same code diferent output in different pcs with python 3.5
40,027,392
<p>I have this code:</p> <pre><code>import gc def hacerciclo(): l=[0] l[0]=l recolector=gc.collect() print("Garbage collector %d" % recolector) for i in range (10): hacerciclo() recolector=gc.collect() print("Garbage collector %d" % recolector) </code></pre> <p>This is an example code to the use of gc.collect(). The problem is that the same code shows different outputs in different computers.</p> <p>One computers show: Garbage collector 1 Garbage collector 10 others show: Garbage collector 0 Garbage collector 10</p> <p>Anyone knows why this happens? Thanks to everyone</p>
2
2016-10-13T17:28:47Z
40,027,843
<blockquote> <p>The current version of Python uses reference counting to keep track of allocated memory. Each object in Python has a reference count which indicates how many objects are pointing to it. When this reference count reaches zero the object is freed. This works well for most programs. However, there is one fundamental flaw with reference counting and it is due to something called reference cycles. The simplest example of a reference cycle is one object that refers to itself. For example:</p> </blockquote> <pre><code>&gt;&gt;&gt; l = [] &gt;&gt;&gt; l.append(l) &gt;&gt;&gt; del l </code></pre> <blockquote> <p>The reference count for the list created is now one. However, since it cannot not be reached from inside Python and cannot possibly be used again, it should be considered garbage. In the current version of Python, this list will never be freed.</p> <p>Creating reference cycles is usually not good programming practice and can almost always be avoided. However, sometimes it is difficult to avoid creating reference cycles and other times the programmer does not even realize it is happening. For long running programs such as servers this is especially troublesome. People do not want their servers to run out of memory because reference counting failed to free unreachable objects. For large programs it is difficult to find how reference cycles are being created.</p> </blockquote> <p>Source: <a href="http://arctrix.com/nas/python/gc/" rel="nofollow">http://arctrix.com/nas/python/gc/</a></p> <p>The link below has the sample example you are using and it also explains:</p> <p><a href="http://www.digi.com/wiki/developer/index.php/Python_Garbage_Collection" rel="nofollow">http://www.digi.com/wiki/developer/index.php/Python_Garbage_Collection</a></p>
2
2016-10-13T17:56:30Z
[ "python", "python-3.x" ]
Python Tornado BadYieldError for POST request with timeout
40,027,394
<p>I'm trying to write a post request for a Python Tornado server that sleeps for a second before sending a response back to a client. The server must handle many of these post requests per minute. The following code doesn't work because of <code>BadYieldError: yielded unknown object &lt;generator object get at 0x10d0b8870&gt;</code></p> <pre><code>@asynchronous def post(self): response = yield IOLoop.instance().add_timeout(time.time() + 1, self._process) self.write(response) self.finish() @gen.coroutine def _process(self, callback=None): callback("{}") </code></pre> <p>The server is to receive a post request, wait a second, and then return the result without blocking other requests. This is Python 2.7. How to resolve this? Thanks!</p>
-1
2016-10-13T17:28:52Z
40,027,711
<p>Either use callbacks or "yield", not both. So you could do:</p> <pre><code>@asynchronous def post(self): IOLoop.instance().add_timeout(time.time() + 1, self._process) def _process(self): self.write("{}") self.finish() </code></pre> <p>Or, better:</p> <pre><code>@gen.coroutine def post(self): yield gen.sleep(1) self.write("{}") # Tornado calls self.finish when coroutine exits. </code></pre>
1
2016-10-13T17:47:31Z
[ "python", "tornado", "yield" ]
How to get my network adapter IP with python?
40,027,402
<p>If I type "ipconfig" in cmd, its gives some IPs... I need the one who belongs to my network adapter\internal IP. So. for example: If I have 3 Ips:</p> <pre><code>10.100.102.2 192.168.231.1 192.168.233.1 </code></pre> <p>And I need the first one. How do I make python know that this is the one I need\The one belongs to my internal IP?</p>
0
2016-10-13T17:29:32Z
40,028,077
<p>The solution for extracting the first <strong>IPv4</strong> address of ethernet adapter (Python on Windows):<br> - used modules: <code>os</code>, <code>re</code></p> <pre><code>import os, re addresses = os.popen('IPCONFIG | FINDSTR /R "Ethernet adapter Local Area Connection .* Address.*[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*"') first_eth_address = re.search(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b', addresses.read()).group() print(first_eth_address) </code></pre>
0
2016-10-13T18:09:48Z
[ "python" ]
Pandas: Select data between Sunday 23:00-Friday 23:00 (1 year span)
40,027,447
<p>I have the timeseries of Euro-US Dollar Exchange Rate at minute granularity spanning the entire 2015 year, including non-trading days (ex.weekends) where the timeseries value get repeated for the entire non-trading period.</p> <p>I need to discard such periods by selecting only the data between Sunday 23:00 pm and Friday 23:00 pm.</p> <p>I haven't found a solution yet for Pandas (I know how to select between times inside a day and select between days). I could simply shift the time by 1h and then select only the business days but this is a sub-optimal solution.</p> <p>Any idea on how to achieve this?</p> <p>Example of data:</p> <pre><code>Local time, Open, High, Low, Close, Volume 02.01.2015 22:58:00.000, 1.20008, 1.20016, 1.20006, 1.20009, 119.84 02.01.2015 22:59:00.000, 1.20009, 1.20018, 1.20004, 1.20017, 40.61 02.01.2015 23:00:00.000, 1.20017, 1.20017, 1.20017, 1.20017, 0 02.01.2015 23:01:00.000, 1.20017, 1.20017, 1.20017, 1.20017, 0 ... 04.01.2015 22:58:00.000, 1.20017, 1.20017, 1.20017, 1.20017, 0 04.01.2015 22:59:00.000, 1.20017, 1.20017, 1.20017, 1.20017, 0 04.01.2015 23:00:00.000, 1.19495, 1.19506, 1.19358, 1.19410, 109.4 04.01.2015 23:01:00.000, 1.19408, 1.19414, 1.19052, 1.19123, 108.12 ... </code></pre>
1
2016-10-13T17:32:23Z
40,029,237
<p>consider the <code>pd.DataFrame</code> <code>df</code> and <code>pd.tseries.index.DatetimeIndex</code> <code>tidx</code></p> <pre><code>tidx = pd.date_range('2010-01-01', '2011-01-01', freq='H') df = pd.DataFrame(np.ones((tidx.shape[0], 2)), tidx, columns=list('AB')) </code></pre> <p>we can construct a series of values for which to filter</p> <pre><code>day_hour = (((tidx.weekday + 1) % 7) * 100) + tidx.hour </code></pre> <p>determine which values are prior to Friday 23:00</p> <pre><code>before_friday = day_hour &lt;= 523 </code></pre> <p>And after Sunday 23:00</p> <pre><code>after_sunday = day_hour &gt;= 23 </code></pre> <p>Filter our <code>df</code> based on above conditions</p> <pre><code>df[before_friday &amp; after_sunday] </code></pre>
1
2016-10-13T19:19:47Z
[ "python", "datetime", "pandas", "time-series", "datetimeindex" ]
Scraping Javascript using Selenium via Python
40,027,455
<p>I'm trying to scrape javascript data from a site. Currently I'm given myself the challenge of trying to scrape the number of Followers from <a href="http://freelegalconsultancy.blogspot.co.uk/" rel="nofollow">this website</a>. Here's my code so far: </p> <pre><code>import os from selenium import webdriver import time chromedriver = "/Users/INSERT USERNAME/Desktop/chromedriver" os.environ["webdriver.chrome.driver"] = chromedriver driver = webdriver.Chrome(chromedriver) driver.get("http://freelegalconsultancy.blogspot.co.uk/") time.sleep(5) title = driver.find_element_by_class_name print title </code></pre> <p>As you can see, I've got a chromedriver file located on my desktop. When I execute the code, I get the following result:</p> <pre><code>&lt;bound method WebDriver.find_element_by_class_name of &lt;selenium.webdriver.chrome.webdriver.WebDriver (session="dd9e5d3f429bc2810c30ebe7067e4e22")&gt;&gt; </code></pre> <p>I tried iterating into this with a for loop but it returned an error. Does anyone know how I can get the Javascript data and ultimately get the number of followers? </p> <p><strong>EDIT:</strong></p> <p>So as per request, I have changed my code to this:</p> <pre><code>import os from selenium import webdriver import time chromedriver = "/Users/INSERT USERNAME/Desktop/chromedriver" os.environ["webdriver.chrome.driver"] = chromedriver driver = webdriver.Chrome(chromedriver) driver.get("http://freelegalconsultancy.blogspot.co.uk/") time.sleep(5) title = driver.find_element_by_class_name("member-title") print title </code></pre> <p>But I now get this error:</p> <pre><code>Traceback (most recent call last): File "C:\Users\INSERT USERNAME\Desktop\blogger_v.1.py", line 11, in &lt;module&gt; title = driver.find_element_by_class_name("member-title") File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 413, in find_element_by_class_name return self.find_element(by=By.CLASS_NAME, value=name) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 752, in find_element 'value': value})['value'] File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 236, in execute self.error_handler.check_response(response) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 192, in check_response raise exception_class(message, screen, stacktrace) NoSuchElementException: Message: no such element: Unable to locate element: {"method":"class name","selector":"member-title"} (Session info: chrome=53.0.2785.143) (Driver info: chromedriver=2.24.417431 (9aea000394714d2fbb20850021f6204f2256b9cf),platform=Windows NT 6.1.7601 SP1 x86_64) </code></pre> <p>Any ideas on how I can get around it? </p> <p><strong>EDIT:</strong></p> <p>So I've changed my code to this:</p> <pre><code>import os from selenium import webdriver import time chromedriver = "/Users/INSERT USERNAME/Desktop/chromedriver" os.environ["webdriver.chrome.driver"] = chromedriver driver = webdriver.Chrome(chromedriver) driver.get("http://freelegalconsultancy.blogspot.co.uk/") time.sleep(5) title = driver.find_element_by_class_name("item-title") print title </code></pre> <p>And I get this result:</p> <pre><code>&lt;selenium.webdriver.remote.webelement.WebElement (session="5fe8fb966edd26fdf808da07f99d4109", element="0.9924860218635834-1")&gt; </code></pre> <p>How would I go about just printing all the javascript? Is this even possible?</p>
0
2016-10-13T17:32:50Z
40,027,551
<p><code>find_element_by_class_name</code> is a function but you're not calling it, you're just asking for a reference to the function. The output you get is the stringified version of that function reference. <hr> <strong>Update:</strong> Your error tells you what's wrong towards the bottom:</p> <pre><code>NoSuchElementException: Message: no such element: Unable to locate element: [...] </code></pre> <p>As the <a href="http://selenium-python.readthedocs.io/locating-elements.html" rel="nofollow">Selenium docs</a> say, <code>find_element_by_class_name</code> will throw an exception if the target doesn't exist. I checked <a href="http://freelegalconsultancy.blogspot.co.uk/" rel="nofollow">the page</a> myself and, indeed, there is no element with the class <code>member-title</code>. <hr> <strong>Update 2:</strong> This should get you a collection of script urls or bodies:</p> <pre><code>scripts = driver.find_elements_by_tag_name("script") results = [] for script in scripts: src = script.get_attribute("src") if src: results.append({"src":src}) else: results.append({"content":script.get_attribute("innerHTML")}) print results </code></pre> <p>If you need the content of the sourced script elements, you'll need to figure out how to assemble a url from the page url and script <code>src</code> content and download that url.</p>
0
2016-10-13T17:37:48Z
[ "javascript", "python", "selenium" ]
Scraping Javascript using Selenium via Python
40,027,455
<p>I'm trying to scrape javascript data from a site. Currently I'm given myself the challenge of trying to scrape the number of Followers from <a href="http://freelegalconsultancy.blogspot.co.uk/" rel="nofollow">this website</a>. Here's my code so far: </p> <pre><code>import os from selenium import webdriver import time chromedriver = "/Users/INSERT USERNAME/Desktop/chromedriver" os.environ["webdriver.chrome.driver"] = chromedriver driver = webdriver.Chrome(chromedriver) driver.get("http://freelegalconsultancy.blogspot.co.uk/") time.sleep(5) title = driver.find_element_by_class_name print title </code></pre> <p>As you can see, I've got a chromedriver file located on my desktop. When I execute the code, I get the following result:</p> <pre><code>&lt;bound method WebDriver.find_element_by_class_name of &lt;selenium.webdriver.chrome.webdriver.WebDriver (session="dd9e5d3f429bc2810c30ebe7067e4e22")&gt;&gt; </code></pre> <p>I tried iterating into this with a for loop but it returned an error. Does anyone know how I can get the Javascript data and ultimately get the number of followers? </p> <p><strong>EDIT:</strong></p> <p>So as per request, I have changed my code to this:</p> <pre><code>import os from selenium import webdriver import time chromedriver = "/Users/INSERT USERNAME/Desktop/chromedriver" os.environ["webdriver.chrome.driver"] = chromedriver driver = webdriver.Chrome(chromedriver) driver.get("http://freelegalconsultancy.blogspot.co.uk/") time.sleep(5) title = driver.find_element_by_class_name("member-title") print title </code></pre> <p>But I now get this error:</p> <pre><code>Traceback (most recent call last): File "C:\Users\INSERT USERNAME\Desktop\blogger_v.1.py", line 11, in &lt;module&gt; title = driver.find_element_by_class_name("member-title") File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 413, in find_element_by_class_name return self.find_element(by=By.CLASS_NAME, value=name) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 752, in find_element 'value': value})['value'] File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 236, in execute self.error_handler.check_response(response) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 192, in check_response raise exception_class(message, screen, stacktrace) NoSuchElementException: Message: no such element: Unable to locate element: {"method":"class name","selector":"member-title"} (Session info: chrome=53.0.2785.143) (Driver info: chromedriver=2.24.417431 (9aea000394714d2fbb20850021f6204f2256b9cf),platform=Windows NT 6.1.7601 SP1 x86_64) </code></pre> <p>Any ideas on how I can get around it? </p> <p><strong>EDIT:</strong></p> <p>So I've changed my code to this:</p> <pre><code>import os from selenium import webdriver import time chromedriver = "/Users/INSERT USERNAME/Desktop/chromedriver" os.environ["webdriver.chrome.driver"] = chromedriver driver = webdriver.Chrome(chromedriver) driver.get("http://freelegalconsultancy.blogspot.co.uk/") time.sleep(5) title = driver.find_element_by_class_name("item-title") print title </code></pre> <p>And I get this result:</p> <pre><code>&lt;selenium.webdriver.remote.webelement.WebElement (session="5fe8fb966edd26fdf808da07f99d4109", element="0.9924860218635834-1")&gt; </code></pre> <p>How would I go about just printing all the javascript? Is this even possible?</p>
0
2016-10-13T17:32:50Z
40,027,589
<p>You need to provide the class name you're looking for as a parameter.</p> <p><code>title = driver.find_element_by_class_name("TheNameOfTheClass")</code></p>
0
2016-10-13T17:40:07Z
[ "javascript", "python", "selenium" ]
How to install a python package named figures
40,027,486
<p>I am trying to run an <a href="http://toblerity.org/shapely/code/polygon.py" rel="nofollow">example code</a>, but an exception No module named figures is thrown. I google how to install the figures package, but there is no clue how to do it except the example code as shown above. If you know how to install it, please help me. </p> <p>I run python on Ubuntu 14.04 with Anaconda 4.0.0.</p>
-1
2016-10-13T17:34:02Z
40,027,570
<p>The code you linked is all from a package called <code>shapely</code>. None of it uses a module named <code>figures</code>. The reason the word figure is used on the page is because figure is another word for diagram</p>
0
2016-10-13T17:39:17Z
[ "python", "anaconda", "figures" ]
Pulling Cuisine Type from TripAdvisor Restaurants using Python
40,027,492
<p>I am currently trying to pull data from TripAdvisor Restaurant from different countries. The fields I am trying to pull is name, address, and cuisine type (chinese, steakhouse, etc.). I have successfully been able to pull name and address using my script; however, pulling cuisine type is proving pretty difficult for myself. If you take a look below, you'll find screenshots of what I am trying to pull from TripAdvisor, and my code. </p> <p><a href="https://i.stack.imgur.com/ajaFg.png" rel="nofollow">What I want to pull from TripAdvisor is circled in red.</a></p> <p><a href="https://i.stack.imgur.com/qsGks.png" rel="nofollow">When I print my code it keeps printing 'Asian' even thought the second one should be a 'Steakhouse'.</a></p> <pre><code>#import libraries import requests from bs4 import BeautifulSoup import csv #loop to move into the next pages. entries are in increments of 30 per page for i in range(0, 120, 30): #need this here for when you want more than 30 entries pulled while i &lt;= range: i = str(i) #url format offsets the restaurants in increments of 30 after the oa url1 = 'https://www.tripadvisor.com/Restaurants-g294217-oa' + i + '-Hong_Kong.html#EATERY_LIST_CONTENTS' r1 = requests.get(url1) data1 = r1.text soup1 = BeautifulSoup(data1, "html.parser") for link in soup1.findAll('a', {'property_title'}): #print 'https://www.tripadvisor.com/Restaurant_Review-g294217-' + link.get('href') restaurant_url = 'https://www.tripadvisor.com/Restaurant_Review-g294217-' + link.get('href') #print link.string account_name = link.string.strip() #cuisine type pull for link in soup1.findAll('a', {'cuisine'}): cuisinetype = link.string.strip() r_address = requests.get(restaurant_url) r_addresstext = r_address.text soup2 = BeautifulSoup(r_addresstext, "html.parser") for restaurant_url in soup2.findAll('span', {'street-address'})[0]: #print(restaurant_url.string) rest_address = restaurant_url.string rest_array = [account_name, rest_address, cuisinetype] print rest_array #with open('ListingsPull-HongKong.csv', 'a') as file: #writer = csv.writer(file) #writer.writerow([account_name, rest_address]) break </code></pre>
0
2016-10-13T17:34:28Z
40,031,849
<p>This approach is not especially elegant but might be acceptable to you. I notice that the information you want seems to be repeated under the 'Details' tab for 'Cuisine'. I've found it easier to access there this way.</p> <pre><code>&gt;&gt;&gt; import requests &gt;&gt;&gt; from bs4 import BeautifulSoup &gt;&gt;&gt; restaurant_url='https://www.tripadvisor.ca/Restaurant_Review-g294217-d2399904-Reviews-Tin_Lung_Heen-Hong_Kong.html' &gt;&gt;&gt; soup2 = BeautifulSoup(requests.get(restaurant_url).text, "html.parser") &gt;&gt;&gt; street_address=soup2.find('span',{'street-address'}) &gt;&gt;&gt; street_address &lt;span class="street-address" property="streetAddress"&gt;International Commerce Centre, 1 Austin Road West, Kowloon&lt;/span&gt; &gt;&gt;&gt; street_address.contents[0] 'International Commerce Centre, 1 Austin Road West, Kowloon' &gt;&gt;&gt; for item in soup2.findAll('div', attrs={'class', 'title'}): ... if 'Cuisine' in item.text: ... ... item.text.strip() ... break ... 'Cuisine' &gt;&gt;&gt; content=item.findNext('div', attrs={'class', 'content'}) &gt;&gt;&gt; content &lt;div class="content"&gt; Chinese, Asian &lt;/div&gt; &gt;&gt;&gt; content.text '\nChinese,\xa0Asian\n' &gt;&gt;&gt; content.text.strip().split('\xa0') ['Chinese,', 'Asian'] </code></pre>
0
2016-10-13T22:08:47Z
[ "python", "python-2.7", "web-scraping", "beautifulsoup" ]
Apply a function to pandas dataframe and get different sized ndarray output
40,027,612
<p>My goal is to get the indexes of the local max heights of a dataframe. These change between 3 and 5 per column.</p> <p>I have tried using the apply function, but get either the error <code>Shape of passed values is (736, 4), indices imply (736, 480)</code> or <code>could not broadcast input array from shape (0) into shape (1)</code>.</p> <p>My matrix is <code>480x736</code>. </p> <p>Here is what I've written for the apply function:</p> <pre><code>import numpy as np import peakutils df.apply(lambda x: peakutils.indexes(x, thres=0.02/max(x), min_dist=100)) </code></pre> <p>Here is what I am able to get to work:</p> <pre><code>indexes =[] import numpy as np import peakutils for column in df: indexes.append(peakutils.indexes(df[column], thres=0.02/max(df[column]), min_dist=100)) </code></pre> <p>Often the indexes are 4 in length, but occasionally I'll get 1 more or less:</p> <pre><code>Out[32]: [array([ 12, 114, 217, 328, 433]), array([ 12, 116, 217, 325, 433]), array([ 64, 166, 283, 389]), array([105, 217, 326, 433]), array([105, 237, 390])] </code></pre> <p>My guess is that the problem with the output comes from my not knowing the shape of the resultant dataframe. The shape is indeterminable from the outset.</p> <p><strong>How do I apply a function to a df where the output differs in size &amp; type?</strong></p>
1
2016-10-13T17:41:17Z
40,029,290
<p>pandas is trying to do "something" with the arrays. You can short circuit that "something" by wrapping your <code>lambda</code>'s return value in a <code>pd.Series</code></p> <p>Try this:</p> <pre><code>df.apply(lambda x: pd.Series(peakutils.indexes(x, thres=0.02/max(x), min_dist=100))) </code></pre>
2
2016-10-13T19:23:00Z
[ "python", "python-3.x", "pandas", "scipy" ]
subprocess.Popen process stdout returning empty?
40,027,670
<p>I have this python code</p> <pre><code>input() print('spam') </code></pre> <p>saved as <code>ex1.py</code></p> <p>in interactive shell</p> <pre><code>&gt;&gt;&gt;from subprocess import Popen ,PIPE &gt;&gt;&gt;a=Popen(['python.exe','ex1.py'],stdout=PIPE,stdin=PIPE) &gt;&gt;&gt; a.communicate() (b'', None) &gt;&gt;&gt; </code></pre> <p>why it is not printing the <code>spam</code></p>
0
2016-10-13T17:44:52Z
40,027,736
<p>What you're looking for is <code>subprocess.check_output</code></p>
0
2016-10-13T17:49:28Z
[ "python", "python-3.x", "subprocess" ]
subprocess.Popen process stdout returning empty?
40,027,670
<p>I have this python code</p> <pre><code>input() print('spam') </code></pre> <p>saved as <code>ex1.py</code></p> <p>in interactive shell</p> <pre><code>&gt;&gt;&gt;from subprocess import Popen ,PIPE &gt;&gt;&gt;a=Popen(['python.exe','ex1.py'],stdout=PIPE,stdin=PIPE) &gt;&gt;&gt; a.communicate() (b'', None) &gt;&gt;&gt; </code></pre> <p>why it is not printing the <code>spam</code></p>
0
2016-10-13T17:44:52Z
40,027,747
<p>Input expects a whole line, but your input is empty. So there is only an exception written to <code>stderr</code> and nothing to <code>stdout</code>. At least provide a newline as input:</p> <pre><code>&gt;&gt;&gt; a = Popen(['python3', 'ex1.py'], stdout=PIPE, stdin=PIPE) &gt;&gt;&gt; a.communicate(b'\n') (b'spam\n', None) &gt;&gt;&gt; </code></pre>
1
2016-10-13T17:50:02Z
[ "python", "python-3.x", "subprocess" ]
Can't install Selenium WebDriver with Python
40,027,675
<p>I am trying to install Selenium WebDriver with Python on my Mac. I used this command:</p> <pre><code>sudo easy_install selenium </code></pre> <p>After that, I tried the following simple test:</p> <p>python</p> <pre><code>from selenium import webdriver driver = webdriver.Firefox() </code></pre> <p>And I got the following error. What am I doing wrong?</p> <blockquote> <p>Traceback (most recent call last): File "", line 1, in File "/Library/Python/2.7/site-packages/selenium-3.0.0.b3-py2.7.egg/selenium/webdriver/firefox/webdriver.py", line 68, in <strong>init</strong> self.service.start() File "/Library/Python/2.7/site-packages/selenium-3.0.0.b3-py2.7.egg/selenium/webdriver/common/service.py", line 71, in start os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH. </p> </blockquote>
2
2016-10-13T17:45:13Z
40,027,920
<p>If you call a selenium driver without any arguments, the path to the webdriver executable must be in the system PATH environment variables.</p> <p>Alternatively, you can specify the path explicitly as such:</p> <pre><code>driver = webdriver.Firefox("path/to/the/FireFoxExecutable") </code></pre>
1
2016-10-13T18:00:34Z
[ "python", "selenium-webdriver" ]
AbstractUser Login View
40,027,694
<p>I've spent a couple of days on this, read the docs, read some Two Scoops info, and I'm missing something. I'm trying to make a view to log in an AbstractUser. The AbstractUser model is in <code>my_app</code> and the view is in an app called <code>mainsite</code>, that I use to store project-wide views.</p> <p>After the user logs in, they will have access to class-based views that they will use to add, edit, and delete database records. These users are not staff, so I am not giving them access to the admin.</p> <p>Every time I try to log in as a user, <code>authenticate(username, password)</code> (in views.py) returns none.</p> <p>What am I missing?</p> <p>Here's the setup--I have a custom Person model that extends the AbstractUser model:</p> <pre><code># my_app.models.py class Person(AbstractUser): date_left = models.DateField(blank=True, null=True) phone_number = models.IntegerField(blank=True, null=True) def _full_name(self): return self.get_full_name() full_name = property(_full_name) def __str__(self): return self.get_full_name() class Meta: verbose_name_plural = 'People' </code></pre> <p>I've added Person to settings.py:</p> <pre><code># settings.py ... AUTH_USER_MODEL = "my_app.Person" ... </code></pre> <p>I have the following URLconf:</p> <pre><code># project/urls.py from mainsite.views import login_view ... url(r'^login/$', login_view, name='login'), ... </code></pre> <p>This view logs in the user:</p> <pre><code># mainsite.views.py def login_view(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return render(request, 'logged_in.html') else: return render(request, 'login.html', {'message': 'Bad username or password'} ) else: return render(request, 'login.html') </code></pre> <p>And finally, here's the template with the login fields:</p> <pre><code>#templates/login.html &lt;form action="{% url 'login' %}" method="post"&gt; {% csrf_token %} &lt;div class="row column"&gt;&lt;h1&gt;Login&lt;/h1&gt;&lt;/div&gt; {% if message %} &lt;div class="row"&gt; &lt;div class="small-12 medium-6 columns"&gt; &lt;div class="alert callout"&gt; &lt;p&gt;{{ message }}&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; {% endif %} &lt;div class="row"&gt; &lt;div class="small-12 medium-6 columns"&gt; &lt;label&gt;Username &lt;input type="text" id="username" name="username"&gt; &lt;/label&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="small-12 medium-6 columns"&gt; &lt;label&gt;Password &lt;input type="password" id="password" name="password"&gt; &lt;/label&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="small-12 medium-6 columns"&gt; &lt;input type="submit" value="Log in" class="button"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; </code></pre>
0
2016-10-13T17:46:29Z
40,043,592
<p>I found an answer (with help from reddit) in the docs.</p> <p><a href="https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#custom-users-and-the-built-in-auth-forms" rel="nofollow">When you use AbstractUser, you need to create your own UserCreationForm and UserChangeForm.</a> If you use AbstractBaseUser, then you will need to create additional forms.</p> <p>I had not created these forms, and I created my users in the admin using forms automatically generated by Django. These forms did not set the password correctly. The automatically generated form probably used <code>user.password = 'some_password'</code>. The correct way to do it is <code>user.set_password('some_password') </code>.</p>
1
2016-10-14T12:49:02Z
[ "python", "django" ]