title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Python - Socket Communication, multiple messages
37,777,222
<p>Hey guys I think i need your help again :(</p> <p>I'm stuck on this socket communication, I've looked everywhere but I haven't found an answer yet.</p> <p>THE PROBLEM: I can only send 1 message from the client before it either gives me an error or ends the script. I need to be able to send multiple messages to the...
2
2016-06-12T17:39:56Z
37,777,383
<p>The problem is, that you only read the first message from each open connection before moving on to the next. The <code>accept()</code> methods waits for a new connection and gives you the information needed when a new one comes in. the <code>recv()</code> method on the other hand, receives data from a existing conne...
3
2016-06-12T17:55:33Z
[ "python", "sockets", "communication" ]
Why all the lines of my 2d array take the value I pass to only one of them?
37,777,271
<p>hello!</p> <p>I am trying to run the following code recursively, where "vetor" is the current state of several variables and I am storing the first 50 in "matriz", a 2d array with 50 lines and 10 columns. Everything is initialized as zero.</p> <p>What happens is that in the first iteration, the first line takes th...
0
2016-06-12T17:43:37Z
37,777,560
<p>When you have an assignment <code>a = b</code> (<code>matriz[cnt]=vetor</code> in your case) in c/c++ the copy/asignment constructor is called and the content of the object is essentially copied. No matter whether the type of <code>a</code> is a primitive type like <code>int</code>/<code>float</code> or <code>struct...
0
2016-06-12T18:13:36Z
[ "python", "arrays" ]
Validating a foreign key field in a serializer django rest framework
37,777,321
<p>I am using django rest framework and have a html form which sends data to the rest api. I am doing a serializer.is_valid check and save() on the request data. In the the front end form I have an ID field which is a foreign key in the serializer's model. And when serializer.is_valid is run, it throws an error that sa...
0
2016-06-12T17:49:25Z
37,777,530
<p>I get it now. The validate method doesn't get executed if the field is not included in the request data. After I have included the field in the request data, the validate method for that field is running.</p>
0
2016-06-12T18:10:35Z
[ "python", "django", "rest", "serialization", "django-rest-framework" ]
How to get rid of \n and \r in a string using python
37,777,324
<p>I have written a python(2.7) program to retreive data from a table in a database and copy it into a csv file. There are various data in non-printable format(unicode) which contain \n, \r. Because of \n, \r I am not able to retreive the data as it is in the table.</p> <p>I have tried the following</p> <pre><code>st...
0
2016-06-12T17:49:36Z
37,777,367
<p><code>str.replace()</code> returns a new string, so you have to assign it to the original string to change it:</p> <pre><code>s = s.replace('\n','').replace('\r','') </code></pre>
2
2016-06-12T17:54:03Z
[ "python" ]
How to get rid of \n and \r in a string using python
37,777,324
<p>I have written a python(2.7) program to retreive data from a table in a database and copy it into a csv file. There are various data in non-printable format(unicode) which contain \n, \r. Because of \n, \r I am not able to retreive the data as it is in the table.</p> <p>I have tried the following</p> <pre><code>st...
0
2016-06-12T17:49:36Z
37,777,705
<p>Unicode has external serialized representations such as UTF-8 and UTF-16 and language-dependent internal implementations such as WCHAR. Your database read appears to have given you a UTF-16 serialized version of the string and all you have to do is decode it. You certainly don't want to remove the <code>\r</code> an...
1
2016-06-12T18:29:10Z
[ "python" ]
Teradata Python module cursor result set is exhausted after one iteration
37,777,512
<p>I am experimenting Teradata python module tutorial <a href="https://developer.teradata.com/tools/reference/teradata-python-module" rel="nofollow">here</a> </p> <p>I am executing a query and I want to iterate over the result set several times. The problem is that if i iterate over the result set once, I can't do it ...
1
2016-06-12T18:09:14Z
37,777,540
<p>Generators can only be iterated over once, use <code>list</code> or <code>tuple</code> to convert them, and then you can iterate over it multiple times:</p> <pre><code>rows = tuple(db.func1()) for row in rows: # do something for row in rows: # would work # do something else </code></pre>
1
2016-06-12T18:12:29Z
[ "python", "cursor", "iteration", "teradata", "resultset" ]
Comparing multiple numpy arrays
37,777,529
<p>how should i compare more than 2 numpy arrays?</p> <pre><code>import numpy a = numpy.zeros((512,512,3),dtype=numpy.uint8) b = numpy.zeros((512,512,3),dtype=numpy.uint8) c = numpy.zeros((512,512,3),dtype=numpy.uint8) if (a==b==c).all(): pass </code></pre> <p>this give a valueError, and i am not interested in ...
3
2016-06-12T18:10:29Z
37,777,691
<p>For three arrays, you can check for equality among the corresponding elements between the first and second arrays and then second and third arrays to give us two boolean scalars and finally see if both of these scalars are <code>True</code> for final scalar output, like so -</p> <pre><code>np.logical_and( (a==b).a...
2
2016-06-12T18:27:36Z
[ "python", "arrays", "numpy" ]
Comparing multiple numpy arrays
37,777,529
<p>how should i compare more than 2 numpy arrays?</p> <pre><code>import numpy a = numpy.zeros((512,512,3),dtype=numpy.uint8) b = numpy.zeros((512,512,3),dtype=numpy.uint8) c = numpy.zeros((512,512,3),dtype=numpy.uint8) if (a==b==c).all(): pass </code></pre> <p>this give a valueError, and i am not interested in ...
3
2016-06-12T18:10:29Z
37,777,724
<p>For three arrays, you should really just compare them two at a time:</p> <pre><code>if np.array_equal(a, b) and np.array_equal(b, c): do_whatever() </code></pre> <p>For a variable number of arrays, let's suppose they're all combined into one big array <code>arrays</code>. Then you could do</p> <pre><code>if n...
2
2016-06-12T18:30:47Z
[ "python", "arrays", "numpy" ]
What is the point of adding short sleep to while true loop?
37,777,542
<p>Across the internet, I've saw several examples of handling a service, which awaits for messages from clients in an endless loop, including a short sleep. Example:</p> <pre><code>while True: check_messages_stack() sleep(0.1) </code></pre> <p>What's the point of the sleep there? Is it supposed to save resour...
0
2016-06-12T18:12:35Z
37,777,566
<p><code>sleep</code> doesn't use CPU resources, but constantly executing <code>check_messages_stack()</code> might (depending what you have there) so if you don't need to do it constantly it is a good practice to give CPU some time off.</p>
0
2016-06-12T18:14:18Z
[ "python", "loops" ]
What is the point of adding short sleep to while true loop?
37,777,542
<p>Across the internet, I've saw several examples of handling a service, which awaits for messages from clients in an endless loop, including a short sleep. Example:</p> <pre><code>while True: check_messages_stack() sleep(0.1) </code></pre> <p>What's the point of the sleep there? Is it supposed to save resour...
0
2016-06-12T18:12:35Z
37,777,569
<p>If the function doesn't wait for anything, it would consume 100% CPU, by adding that sleep, it gives the CPU some time to execute other processes</p>
0
2016-06-12T18:14:35Z
[ "python", "loops" ]
What is the point of adding short sleep to while true loop?
37,777,542
<p>Across the internet, I've saw several examples of handling a service, which awaits for messages from clients in an endless loop, including a short sleep. Example:</p> <pre><code>while True: check_messages_stack() sleep(0.1) </code></pre> <p>What's the point of the sleep there? Is it supposed to save resour...
0
2016-06-12T18:12:35Z
37,777,579
<p><code>sleep</code> like the others have said relaxes the CPU usage, but in addition if it's something like accessing network/web data the sleep is needed to not crash the host server and ban you.</p>
1
2016-06-12T18:15:28Z
[ "python", "loops" ]
What is the point of adding short sleep to while true loop?
37,777,542
<p>Across the internet, I've saw several examples of handling a service, which awaits for messages from clients in an endless loop, including a short sleep. Example:</p> <pre><code>while True: check_messages_stack() sleep(0.1) </code></pre> <p>What's the point of the sleep there? Is it supposed to save resour...
0
2016-06-12T18:12:35Z
37,778,199
<p>While your PC is running, your CPU needs to execute a lot of process (to make your PC run). As CPUs are extremly fast they can fake to do multiple tasks at the same time but they don't really do (nowadays we get multiple cores CPU and mutithreading but forget about it for this explaination).<br> They just execute s...
1
2016-06-12T19:22:44Z
[ "python", "loops" ]
Removing duplicated rows but keep the ones with a particular value in one column (pandas python)
37,777,662
<p>I would like to do the following: </p> <p>If two rows have exactly the same value in 3 columns ("ID","symbol", and "date") and have either "X" or "T" in one column ("message"), then remove both of these rows. However, if two rows have the same value in the same 3 columns but a value different than "X" or "T" in the...
1
2016-06-12T18:25:04Z
37,777,855
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html" rel="nofollow"><code>filter</code></a> - conditions are - not <co...
0
2016-06-12T18:45:48Z
[ "python", "pandas", "dataframe", "duplicates" ]
Removing duplicated rows but keep the ones with a particular value in one column (pandas python)
37,777,662
<p>I would like to do the following: </p> <p>If two rows have exactly the same value in 3 columns ("ID","symbol", and "date") and have either "X" or "T" in one column ("message"), then remove both of these rows. However, if two rows have the same value in the same 3 columns but a value different than "X" or "T" in the...
1
2016-06-12T18:25:04Z
37,777,864
<p>This might work for you:</p> <pre><code>vals = ['X', 'T'] pd.concat([df[~df.message.isin(vals)], df[df.message.isin(vals)].loc[~df.duplicated(subset=['ID', 'date', 'symbol'], keep=False), :]]) ID date message symbol 3 BB-2 06/25/2014 B 4 BB-2 06/25/2015 B 2 C-0 06/20/20...
0
2016-06-12T18:47:10Z
[ "python", "pandas", "dataframe", "duplicates" ]
this python code for pretty printing a tree blows up with a stack overflow
37,777,729
<p>I cannot figure out why this explodes and I'm still trying to learn python debugging.</p> <pre><code>class Node(): def __init__(self, parent = None, children = [], data = None): self.parent = parent self.children = children self.data = data if parent == None: self.roo...
-1
2016-06-12T18:31:05Z
37,777,822
<pre><code>def __init__(self, parent = None, children = [], data = None): </code></pre> <p>All Nodes will use the same mutable object <code>children</code>. This results in <code>children</code> acting like a global variable.</p> <p>Read more <a href="http://docs.python-guide.org/en/latest/writing/gotchas/" rel="nofo...
2
2016-06-12T18:42:57Z
[ "python" ]
Memory efficient dicts -- deriving an item's key from its value
37,777,735
<p>I have a use case where I things that contain both a key and data. I would like an efficient encoding of this data and the dict index of the data. So Thing is a class, and dictionary is a dict index of its instances:</p> <pre><code>d = {} class Thing: def __init__(k,v): self.key=k; self.data=v; d[v]=self </cod...
0
2016-06-12T18:31:43Z
37,777,944
<p>It is strange to store the key in the value since you must have the key in order to get the value.</p> <p>If you don't want to store it, you can get it with a special getter function:</p> <pre><code>def get_key_and_value(d, k): return (k, d[k]) obj = get_key_and_value(d, k) print "my key is %s and value is %s...
0
2016-06-12T18:53:55Z
[ "python", "dictionary", "hashmap" ]
Memory efficient dicts -- deriving an item's key from its value
37,777,735
<p>I have a use case where I things that contain both a key and data. I would like an efficient encoding of this data and the dict index of the data. So Thing is a class, and dictionary is a dict index of its instances:</p> <pre><code>d = {} class Thing: def __init__(k,v): self.key=k; self.data=v; d[v]=self </cod...
0
2016-06-12T18:31:43Z
37,778,003
<p>You haven't explained the use case well enough, so my guidance will not be very precise. I assume from your question you do NOT want to store the key in the value to conserve memory (as you demonstrated in your example -- and then rejected)? And further, that you will have some operation that will require access to...
0
2016-06-12T18:59:57Z
[ "python", "dictionary", "hashmap" ]
How to parse tuple into several properties?
37,777,755
<p>In my django app I do calculations on model side, for this i use only one function that returns a tuple. I want to parse this tuple into several properties </p> <p>But I cant since -</p> <blockquote> <p>TypeError: 'property' object is not iterable</p> </blockquote> <pre><code>def _get_total(self): from inve...
1
2016-06-12T18:33:55Z
37,778,865
<p>does the following code provide the necessary functionality?</p> <pre><code>class MyClass(ClassParent): _total_inventory = None _total_po = None ... ... def _get_total_(self): ... # everything before the return clause self._total_inventory = inventory_quantity self._total_po = po_quanti...
1
2016-06-12T20:39:45Z
[ "python", "django" ]
Python calling function from DLL (WinDLL)
37,777,858
<p><em>I trying a lot of methods, but any method work strange. Some return error, some return value, but not what I need to be returned ("0" rather than string).</em></p> <p>So, I try to use <a href="https://www.voidtools.com/" rel="nofollow">Everything</a> in python code. I make example tool, but when I start using A...
0
2016-06-12T18:46:07Z
37,778,001
<p>Rather than struggling with calling "Everything" I would suggest that you take a look at the python built-in library functions <code>os.walk</code>, <code>fnmatch.fnmatch</code> and <code>glob.glob</code> - they work very well to do what everything does with no external dependencies and a simple pythonic user callin...
0
2016-06-12T18:59:49Z
[ "python", "dll", "ctypes" ]
Django : return two string for self - Admin
37,777,923
<p>I have a Python model and I would like to return a combination of two fields : <code>category</code> + <code>name</code>.</p> <p>The only thing is that the category field is a relationship, and within the category table, it is a "name" field. Note that the <code>__str__</code> is the name.</p> <hr> <p>Example :</...
-1
2016-06-12T18:52:10Z
37,778,398
<p>You need to give the + operand 2 strings. So <code>str(self.category) + self.name</code> would work. Or perhaps <code>self.category.name + self.name</code> if the category has a <code>name</code> attribute.</p> <p>Be aware, that accessing the Category object might cause a lot of queries making your admin slow.</p>
0
2016-06-12T19:44:08Z
[ "python", "django", "django-models", "django-admin" ]
Pygame not checking keyevents after another happens
37,778,015
<p>I am moving a sprite on the x-axis. It is properly moving left and right. When I press both LEFT and RIGHT at the same time it stop moving properly. </p> <p>I am trying to make it when a user presses both keys and then lets go of one, for it to continue moving in the direction still pressed.</p> <p>Weirdly it work...
0
2016-06-12T19:01:01Z
37,778,230
<p>Try to use the following code in your movement:</p> <pre><code> if keyPressed[pygame.K_LEFT]: movement_x = -5 elif keyPressed[pygame.K_RIGHT]: movement_x = +5 elif event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: m...
0
2016-06-12T19:25:39Z
[ "python", "python-2.7", "pygame" ]
Pygame not checking keyevents after another happens
37,778,015
<p>I am moving a sprite on the x-axis. It is properly moving left and right. When I press both LEFT and RIGHT at the same time it stop moving properly. </p> <p>I am trying to make it when a user presses both keys and then lets go of one, for it to continue moving in the direction still pressed.</p> <p>Weirdly it work...
0
2016-06-12T19:01:01Z
37,778,745
<p>I think what you need is this:</p> <pre><code>if keyPressed[pygame.K_LEFT]: movement_x = -5 if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT and movement_x &lt; 0: movement_x = 0 if keyPressed[pygame.K_RIGHT]: movement_x = 5 if event.type == pygame.KEYUP: if event.key == pygame.K...
0
2016-06-12T20:24:59Z
[ "python", "python-2.7", "pygame" ]
Aiohttp, Asyncio: RuntimeError: Event loop is closed
37,778,019
<p>I have two scripts, scraper.py and db_control.py. In scraper.py I have something like this:</p> <pre><code>... def scrap(category, field, pages, search, use_proxy, proxy_file): ... loop = asyncio.get_event_loop() to_do = [ get_pages(url, params, conngen) for url in urls ] wait_coro = asyncio.wait(t...
0
2016-06-12T19:01:24Z
37,778,837
<p>Methods <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.BaseEventLoop.run_until_complete" rel="nofollow"><code>run_until_complete</code></a>, <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.BaseEventLoop.run_forever" rel="nofollow"><code>run_forever</code></a>, <a ...
3
2016-06-12T20:36:02Z
[ "python", "python-3.x", "python-asyncio", "aiohttp" ]
piping from shell into jupyter notebook cell
37,778,082
<p>Does anyone know how to stream the output of a shell command (a chain of csvkit tool invocations) into a jupyter notebook cell, but specifically into a Pandas DataFrame. From the cell's content it would look something like this:</p> <pre><code> output = !find /path -name "*.csv" | csvstack ... | csvgrep ... df =...
0
2016-06-12T19:07:08Z
37,778,567
<p>IIUC you can do it by letting pandas read from STDIN:</p> <p>Python script:</p> <pre><code>import sys import pandas as pd df = pd.read_csv(sys.stdin) print(df) </code></pre> <p>Shell command line:</p> <pre><code>!find /path -name "*.csv" | csvstack ... | csvgrep ... | python our_pyscript.py </code></pre> <p>ple...
0
2016-06-12T20:04:19Z
[ "python", "pandas", "jupyter-notebook", "csvkit" ]
piping from shell into jupyter notebook cell
37,778,082
<p>Does anyone know how to stream the output of a shell command (a chain of csvkit tool invocations) into a jupyter notebook cell, but specifically into a Pandas DataFrame. From the cell's content it would look something like this:</p> <pre><code> output = !find /path -name "*.csv" | csvstack ... | csvgrep ... df =...
0
2016-06-12T19:07:08Z
38,838,228
<p>Perhaps "named pipes" would be useful in your case. </p> <p>In shell:</p> <pre><code>mkfifo MYFIFO head myfile.txt &gt; MYFIFO </code></pre> <p>In notebook:</p> <pre><code>with open('MYFIFO', 'rt') as f: print(f.readline()) </code></pre> <p>A few good internet searches should give you the information you ne...
0
2016-08-08T20:46:29Z
[ "python", "pandas", "jupyter-notebook", "csvkit" ]
Debugging previous entries in partially filled list comprehension
37,778,118
<p>I am currently debugging a function (<code>produceEntry</code>) whose results are stored in a list comprehension:</p> <pre><code>entries = [produceEntry(i) for i in range(i)] </code></pre> <p>The error in the function manifests in one of the middle entries and I would like to inspect the previous entries but I can...
-1
2016-06-12T19:12:49Z
37,778,272
<p>As <em>jonrsharpe</em> already stated, a list comprehension should be treated as a single operation, so you will not be able to access partial results. </p> <p>In your case, you could for example catch your error and replace it with an error flag:</p> <pre><code>def produceEntry(i): try: return 1 / (5 ...
-1
2016-06-12T19:29:56Z
[ "python", "python-3.x", "debugging", "pdb" ]
Python 3.5.1 in Anaconda 3 from JetBrains PyCharm IDE - environment objects
37,778,144
<p>I am coming into Python from R, and installed Python 3.5 with Anaconda. Now, PyCharm console has a prompt identical to an iPython Notebook, i.e. instead of <code>&gt;&gt;&gt;</code>, it shows <code>[1]</code> at the command line.</p> <p>After writing a toy line of code (below) in a <code>.py</code> document, and ru...
0
2016-06-12T19:16:05Z
37,778,349
<p>You need to import it first. Let's say that your function <code>toss()</code> is in a file called <code>foo.py</code> then that means that you can do</p> <pre><code>from foo import toss toss() </code></pre> <p>in your Python Console to use your function. A Python source file is, by definition, a <a href="http://p...
1
2016-06-12T19:39:00Z
[ "python", "pycharm", "anaconda" ]
Implementing `__remove__` in linked list
37,778,176
<p>Creating a doubly-linked list class, I've run into a problem with removing a value from the list. I'm not sure how to go about fixing the <code>__remove__</code> method for this code to work correctly. Is there a loop that isn't being updated because of my sentinel node? I tried to make this similar to my <code>__de...
0
2016-06-12T19:20:07Z
37,778,605
<p>Your issue is that your <code>for</code> loop never runs, since <code>nidx</code> is zero and <code>range(0)</code> is empty. You don't need any indexes in this function. Just use a <code>while</code> loop that keeps you from wrapping around when you reach the end of the list:</p> <pre><code>def remove(self, value)...
0
2016-06-12T20:09:29Z
[ "python", "linked-list" ]
Why is this simple code wrong?
37,778,189
<pre><code>print("Hello there") name=input("What is your name?") print("Welcome to the some game, " + name + "!") print("I'm going to ask you some basic questions so that we could work together") age=input("Your age") if age &gt;= 14 and age &lt; 41: print("K") else: print("Sorry bruh") print("Thanks") </code><...
-4
2016-06-12T19:21:44Z
37,778,210
<p>Cast your <code>input</code> to <code>int</code>:</p> <pre><code>age = int(input("Your age")) </code></pre> <p>You could add a <code>try-except</code>. Your condition should equally be evaluated on <code>or</code> not <code>and</code></p>
3
2016-06-12T19:23:33Z
[ "python", "python-3.x" ]
Why is this simple code wrong?
37,778,189
<pre><code>print("Hello there") name=input("What is your name?") print("Welcome to the some game, " + name + "!") print("I'm going to ask you some basic questions so that we could work together") age=input("Your age") if age &gt;= 14 and age &lt; 41: print("K") else: print("Sorry bruh") print("Thanks") </code><...
-4
2016-06-12T19:21:44Z
37,778,339
<p>Either you use Python3 and you need to cast with <code>int(input("Your age"))</code> or you use Python2 and then you need to use <code>raw_input</code> to read the name: <code>name=raw_input("What is your name?")</code></p>
0
2016-06-12T19:38:07Z
[ "python", "python-3.x" ]
Why is this simple code wrong?
37,778,189
<pre><code>print("Hello there") name=input("What is your name?") print("Welcome to the some game, " + name + "!") print("I'm going to ask you some basic questions so that we could work together") age=input("Your age") if age &gt;= 14 and age &lt; 41: print("K") else: print("Sorry bruh") print("Thanks") </code><...
-4
2016-06-12T19:21:44Z
37,778,449
<p>Ok , so you can try this code in python2.7 and it will work as you desired:</p> <pre><code>print("Hello there") name=raw_input("What is your name?") print("Welcome to the some game, " + name + "!") print("I'm going to ask you some basic questions so that we could work together") age=input("Your age") if age &gt;= 1...
0
2016-06-12T19:49:03Z
[ "python", "python-3.x" ]
Site wide navbar search using class based views
37,778,273
<p>I have a search form in the navbar that is obviously available site wide, however, search only works on the home page because thats the view the search code is written. I figured class based views were the answer such that I could easily add the search functionality as a mixin or something of the kind.</p> <p>Bott...
0
2016-06-12T19:29:56Z
37,779,746
<p>Nice job creating your first site. On every view that you would like to have a functional search bar, you should include the <code>SearchMixin</code> that you've created.</p> <p>One important thing that will save you some trouble down the road is to make sure that the generic class-based views go on the right-hand ...
0
2016-06-12T22:36:02Z
[ "python", "django", "django-views" ]
Site wide navbar search using class based views
37,778,273
<p>I have a search form in the navbar that is obviously available site wide, however, search only works on the home page because thats the view the search code is written. I figured class based views were the answer such that I could easily add the search functionality as a mixin or something of the kind.</p> <p>Bott...
0
2016-06-12T19:29:56Z
37,782,487
<p>Instead of using <code>SearchMixin</code> and inheriting everywhere, I suggest creating a <code>SearchView</code>, assigning it some URL and returning search results from there.</p> <pre><code># urls.py urlpatterns = [ url(r'/search/', SearchView.as_view(), name='search'), ... ] # views.py class SearchView...
0
2016-06-13T05:40:28Z
[ "python", "django", "django-views" ]
Cannot install h5py
37,778,299
<p>I'm trying to install <a href="http://www.h5py.org/" rel="nofollow">h5py</a>, but when I do <code>pip install h5py</code> or use <code>python setup.py install</code> from the source code, fatal error:</p> <pre><code>hdf5.h: No such file or directory. </code></pre> <p>Other posts mention to do <code>pip install lib...
2
2016-06-12T19:33:22Z
37,778,347
<p>Your error is because you are missing the <code>hdf5.h</code> header, <em>pip</em> will not install the development headers, you need to install them using your package manager, on <em>Centos</em> it would be:</p> <pre><code>yum install hdf5-devel </code></pre> <p>If you look at the installation instrcutions:</p>...
2
2016-06-12T19:38:47Z
[ "python", "pip", "packages", "h5py" ]
Cannot install h5py
37,778,299
<p>I'm trying to install <a href="http://www.h5py.org/" rel="nofollow">h5py</a>, but when I do <code>pip install h5py</code> or use <code>python setup.py install</code> from the source code, fatal error:</p> <pre><code>hdf5.h: No such file or directory. </code></pre> <p>Other posts mention to do <code>pip install lib...
2
2016-06-12T19:33:22Z
37,778,630
<p>This link helped: <a href="https://github.com/Homebrew/legacy-homebrew/issues/23144" rel="nofollow">https://github.com/Homebrew/legacy-homebrew/issues/23144</a></p> <p>I installed LinuxHomeBrew and did: </p> <pre><code>brew tap homebrew/science brew install hdf5 pip install h5py </code></pre> <p>I was able to in...
1
2016-06-12T20:12:05Z
[ "python", "pip", "packages", "h5py" ]
using the TOP statement for updating data in sqlite with python
37,778,356
<p>I don't know if the answer has been given already, but I couldn't find it. I am trying to update data in an existing table in sqlite with python. The data has to come in rows were other data is already saved in. My code looks like this:</p> <pre><code>for lst in adresCor: cursor.execute('''INSERT TOP 11 INTO Hu...
-2
2016-06-12T19:39:22Z
37,778,765
<p>If you want to update, and assuming you have a primary key called id, and it is an auto-increment field you can do this:</p> <pre><code>for id, lst in enumerate(adresCor): sql = "update Huisartsen set lat = %f, long = %f where id = %d" % (lst[0], lst[1], id) cursor.execute(sql) </code></pre> <p>for data li...
0
2016-06-12T20:27:55Z
[ "python", "sqlite" ]
Python: How to iterate through each value in two lists, count the occurrences that value is < 22 in the 1st list OR < 27 in the 2nd list?
37,778,371
<p>I'm confused on how to iterate through each value in two lists and which loop to use and how for this. Please help!!</p> <p>I have two lists (<code>datalist_country</code> and <code>datalist_urban</code>). In my main function, I assigned each list to a text file. The values with the same index (e.g. 23) on each lis...
0
2016-06-12T19:41:24Z
37,778,445
<p>The <a href="https://docs.python.org/3.3/library/functions.html#zip" rel="nofollow">zip</a> function can help you with that. It take as many iterables (such as lists) as you want and creates an iterator that gives you tuples, where the n-th tuple contains the n-th element of each list and the order in the tuple is t...
0
2016-06-12T19:48:05Z
[ "python", "list", "loops", "count" ]
Python: How to iterate through each value in two lists, count the occurrences that value is < 22 in the 1st list OR < 27 in the 2nd list?
37,778,371
<p>I'm confused on how to iterate through each value in two lists and which loop to use and how for this. Please help!!</p> <p>I have two lists (<code>datalist_country</code> and <code>datalist_urban</code>). In my main function, I assigned each list to a text file. The values with the same index (e.g. 23) on each lis...
0
2016-06-12T19:41:24Z
37,778,516
<p>You can do this with <code>zip</code> and <code>sum</code>:</p> <pre><code>count = sum(1 for x, y in zip(datalist_country, datalist_urban) if float(x) &lt; 22 or float(y) &lt; 27) </code></pre>
-1
2016-06-12T19:57:35Z
[ "python", "list", "loops", "count" ]
Python: How to iterate through each value in two lists, count the occurrences that value is < 22 in the 1st list OR < 27 in the 2nd list?
37,778,371
<p>I'm confused on how to iterate through each value in two lists and which loop to use and how for this. Please help!!</p> <p>I have two lists (<code>datalist_country</code> and <code>datalist_urban</code>). In my main function, I assigned each list to a text file. The values with the same index (e.g. 23) on each lis...
0
2016-06-12T19:41:24Z
37,778,518
<p>Use the <code>zip</code> function to create successive pairs of your mileage, with a filter (<code>if</code> expression) that returns a one if the condition passes. <code>sum</code> takes its value from the <a href="https://docs.python.org/2/reference/expressions.html#generator-expressions" rel="nofollow">generator ...
0
2016-06-12T19:57:50Z
[ "python", "list", "loops", "count" ]
AssertionError when using variable instead of a literal
37,778,463
<p>I am using Selenium WebDriver with Python. I have a code like the following. Why do I get an AssertionError, when I use <code>assert &lt;some variable&gt; in driver.page_source</code>? Instead of the variable if I use a literal, such as a string, the test passes.</p> <pre><code>import unittest from selenium impo...
1
2016-06-12T19:50:54Z
37,778,531
<p>This is a <em>timing</em> problem (reproduced it as well). The assertion is made at the moment the search results are not loaded yet and, hence, <code>Ireland</code> is not yet there in the <code>page_source</code>. Add a wait via <a href="http://selenium-python.readthedocs.io/waits.html#explicit-waits" rel="nofollo...
2
2016-06-12T19:59:31Z
[ "python", "selenium", "webdriver" ]
Decoding an API list and breaking it up in Python 3?
37,778,565
<p>I'm hoping to get your help on decoding a response I'm getting from an API into Python 3, and break it down into variables. It's <em>almost</em> a list, see for yourself:</p> <p>API returns this: </p> <pre><code>['b', "[[1465617600000,591.41,651.95,587.96,647.45,1474960.0,240144.89982940466],[1465704000000,647.2,...
-2
2016-06-12T20:04:07Z
37,778,624
<p>Use <a href="https://docs.python.org/2/library/ast.html#ast.literal_eval" rel="nofollow"><code>ast.literal_eval</code></a>:</p> <pre><code>import ast api_return = apiReturn[1][:-1] # [:-1]: is there an extra quote trailing the second item? # '[[1465185600000,589.02,600.0,585.01,591.78,401760.0,67821.2330781393],[...
0
2016-06-12T20:11:23Z
[ "python", "string", "list", "python-3.x", "split" ]
Decoding an API list and breaking it up in Python 3?
37,778,565
<p>I'm hoping to get your help on decoding a response I'm getting from an API into Python 3, and break it down into variables. It's <em>almost</em> a list, see for yourself:</p> <p>API returns this: </p> <pre><code>['b', "[[1465617600000,591.41,651.95,587.96,647.45,1474960.0,240144.89982940466],[1465704000000,647.2,...
-2
2016-06-12T20:04:07Z
37,779,477
<p>There are many answers, some that can come from those more experienced than I but I'll try to give you the best I came up with. I'm sure this could be shorter.</p> <p><strong>This answer is given step by step and I hope it helps:</strong></p> <p>.</p> <p>.</p> <p>First assign your API response to a variable. Som...
-1
2016-06-12T22:02:03Z
[ "python", "string", "list", "python-3.x", "split" ]
How to get team text and score using Beautiful soup with python?
37,778,589
<p>Im trying to get all the team vs team information and the score which is hidden under a show button using this url <a href="http://www.gosugamers.net/counterstrike/teams/7397-natus-vincere/matches" rel="nofollow">http://www.gosugamers.net/counterstrike/teams/7397-natus-vincere/matches</a>. Im trying to get opp 1 vs ...
1
2016-06-12T20:06:53Z
37,778,676
<p>The game results are under the hidden span (well, there is no "hidden" for <code>BeautifulSoup</code>, it is not a browser). The home score is in the <code>span</code> with <code>hscore</code> class, the away - in the <code>span</code> with <code>ascore</code> class. The team names are under inner <code>span</code> ...
2
2016-06-12T20:16:01Z
[ "python", "python-3.x", "web-scraping", "beautifulsoup" ]
How to get team text and score using Beautiful soup with python?
37,778,589
<p>Im trying to get all the team vs team information and the score which is hidden under a show button using this url <a href="http://www.gosugamers.net/counterstrike/teams/7397-natus-vincere/matches" rel="nofollow">http://www.gosugamers.net/counterstrike/teams/7397-natus-vincere/matches</a>. Im trying to get opp 1 vs ...
1
2016-06-12T20:06:53Z
37,778,690
<p>View the source of the page and you will see that all the info that you need is in a table with the class <code>simple gamelist profilelist</code>.</p> <p>Read the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow"> Beautiful Soup Documentation </a> and especially the find method.</p> ...
-1
2016-06-12T20:17:09Z
[ "python", "python-3.x", "web-scraping", "beautifulsoup" ]
pickling python objects to google cloud storage
37,778,621
<p>I've been pickling the objects to filesystem and reading them back when needed to work with those objects. Currently I've this code for that purpose.</p> <pre><code>def pickle(self, directory, filename): if not os.path.exists(directory): os.makedirs(directory) with open(directory + '/' + filename, '...
1
2016-06-12T20:11:04Z
37,778,921
<p>You can use the <a href="https://cloud.google.com/appengine/docs/python/googlecloudstorageclient/read-write-to-cloud-storage" rel="nofollow">Cloud Storage client library</a>.</p> <p>Instead of <code>open()</code> use <code>cloudstorage.open()</code> (or <code>gcs.open()</code> if importing <code>cloudstorage</code>...
3
2016-06-12T20:45:27Z
[ "python", "google-app-engine", "google-cloud-storage", "pickle" ]
Image plotted from a FITS file with matplotlib oriented incorrectly
37,778,651
<p>I'm having a little issue with something regarding plotting a fits image using <code>matplotlib</code>'s <code>imshow</code>. It seems that my image is flipped both horizontally and vertically. I'm sure there is something simple I am overlooking, if anyone could point me in the right direction that would be great.</...
1
2016-06-12T20:13:52Z
37,779,127
<p>I have never used the astropy module, but I know that PyFITS opens the image data as a NumPy array (and from what I'm <a href="http://www.stsci.edu/institute/software_hardware/pyfits" rel="nofollow">reading</a>, astropy.io.fits has inherited the functionality of PyFITS anyway, so it should work the same way). If tha...
2
2016-06-12T21:12:55Z
[ "python", "image", "matplotlib", "astronomy", "fits" ]
Image plotted from a FITS file with matplotlib oriented incorrectly
37,778,651
<p>I'm having a little issue with something regarding plotting a fits image using <code>matplotlib</code>'s <code>imshow</code>. It seems that my image is flipped both horizontally and vertically. I'm sure there is something simple I am overlooking, if anyone could point me in the right direction that would be great.</...
1
2016-06-12T20:13:52Z
37,784,295
<p>For FITS files the convention is that the origin is at the lower left hand corner of the image, so you need to use <code>origin='lower'</code> (by default Matplotlib uses <code>origin='upper'</code>).</p>
3
2016-06-13T07:48:23Z
[ "python", "image", "matplotlib", "astronomy", "fits" ]
Python tweetbot follow code won't work
37,778,657
<p>I am building a tweetbot and I keep getting an error when running my code this only showed up after I tried to add code to follow anyone who follows me (I delete tweets from the text file before running again, the error is due to the part that follows people back): </p> <pre><code>import tweepy, time CONSUMER_KEY ...
0
2016-06-12T20:14:31Z
37,778,812
<p>Tweepy does not let you tweet if you have the same tweet...</p> <p>So you can do this - </p> <pre><code>for status in tweepy.Cursor(api.user_timeline).items(): api.destroy_status(status.id) </code></pre>
2
2016-06-12T20:33:12Z
[ "python" ]
python dictionary : unorderable types error
37,778,660
<p>I am adding a generic GDB pretty printer as described <a href="https://www.rethinkdb.com/blog/make-debugging-easier-with-custom-pretty-printers/" rel="nofollow">here</a> to my gdb, the following line adds the map of the types to use the printer:</p> <pre><code>pretty_printers_dict[re.compile ('.*Generic.*')] = Gene...
0
2016-06-12T20:14:45Z
37,779,019
<p>This problem only occurs in python 3:</p> <p>The <code>sorted</code> function needs to compare the two compiled regexes wich does only work in python 2 (I don't know why).</p> <p>But I do not think that the <code>sorted</code> call is necessary so just leave it out:</p> <pre><code>for function in pretty_printers_...
0
2016-06-12T20:56:52Z
[ "python", "gdb" ]
python dictionary : unorderable types error
37,778,660
<p>I am adding a generic GDB pretty printer as described <a href="https://www.rethinkdb.com/blog/make-debugging-easier-with-custom-pretty-printers/" rel="nofollow">here</a> to my gdb, the following line adds the map of the types to use the printer:</p> <pre><code>pretty_printers_dict[re.compile ('.*Generic.*')] = Gene...
0
2016-06-12T20:14:45Z
37,823,285
<p>I get away from it by combining the regular expressions:</p> <pre><code>pretty_printers_dict[re.compile ('MyNamespace1.*|MyNamespace2.*')] = GenericPrinter </code></pre>
0
2016-06-14T22:40:56Z
[ "python", "gdb" ]
function takes exactly 2 arguments (1 given) kivy timer
37,778,689
<p>I'm trying to have a user input a time, and when they start the timer, the time the user inserted will start to countdown from that inputted time.</p> <p>However I get the error updatetimer() takes exactly 2 arguments (1 given)</p> <p>What is the best way to return the value from an input so that it can be used th...
0
2016-06-12T20:16:59Z
37,779,463
<p>first of all, I would tidy up the code a bit and keep the method names a little more descriptive and inside the Class.</p> <pre><code>Builder.load_string(""" &lt;MenuScreen&gt;: GridLayout: cols: 1 TextInput: id: ti Button: id: btn_0 text: "press me to...
0
2016-06-12T21:59:37Z
[ "python", "timer", "kivy" ]
Find the maximum of a & b in a set s = {1, 2, ... n } lesser than a certain value k
37,778,700
<p>I was playing a bit with the Python language to solve a tutorial on HackerRank, available here: <a href="https://www.hackerrank.com/challenges/30-bitwise-and" rel="nofollow">https://www.hackerrank.com/challenges/30-bitwise-and</a></p> <p>The gist of the challenge is to find the maximum of <code>a &amp; b</code> whe...
2
2016-06-12T20:19:04Z
37,779,188
<p>Let <code>j = k - 1</code>, and let <code>unset_bit</code> be the lowest power of two such that <code>(j &amp; unset_bit) == 0</code>.</p> <p>If <code>(j | unset_bit) &lt;= n</code>, then we pick <code>a = j</code> and <code>b = j | unset_bit</code> for the optimal value of <code>(a &amp; b) == j</code>.</p> <p>If...
1
2016-06-12T21:20:01Z
[ "python", "algorithm", "bit-manipulation", "bitwise-operators", "boolean-logic" ]
Disregarding specific input losses when training network in Tensorflow
37,778,702
<p>I have a binary classification problem in which only the beginning 3 time instances of positive events are annotated in the data set, and I have apriori knowledge that they could last up to 15 time instances. To cope with this issue, I have decided to disregard loss values from the 15-3 = 12 time instances following...
0
2016-06-12T20:19:23Z
37,778,830
<p>Quickly after posting this question I came up with the obvious answer myself. I will include a placeholder for "error weights" in the network:</p> <pre><code>self._mask = tf.placeholder(tf.float32, [None]) </code></pre> <p>Then in the cost function I will perform a weighted loss on these.</p> <pre><code>loss = tf...
0
2016-06-12T20:35:36Z
[ "python", "numpy", "tensorflow", "training-data" ]
Python 3 way partitioning (Quicksort)
37,778,707
<p>I am trying to write a python code for the 3 way partition, however I get an indexing error. I tried to fix it but do not seem to succeed. In my code I pick the first entry to be the pivot and then scan from left and from right, swapping the values if necessary. If any entry is equal to pivot I either move it to the...
0
2016-06-12T20:20:05Z
37,779,020
<p>As noted in the comments on the question, the <code>swap()</code> function in your code doesn't do anything. In Python, names are just labels attached to objects. If you assign to a name, you just attach a label to an object. When you pass an object to a function, the object is passed, not the names assigned to i...
0
2016-06-12T20:57:05Z
[ "python", "quicksort", "partitioning" ]
Untangling the cause of an error in Theano
37,778,804
<p>I have a bug in my code, but finding the exact cause of it is difficult because of how theano works.</p> <p>Following the tips in the exception details, I set <code>theano.config.optimizer='None'</code> and <code>theano.config.exception_verbosity='high'</code>, but that doesn't tell me enough.</p> <p>In my case, f...
0
2016-06-12T20:32:13Z
37,778,931
<p>If you want to find the spots in your code that use <code>theano.tensor.dot</code> you can monkeypatch it with wrapper code that uses <code>traceback.print_stack</code>:</p> <pre><code>import traceback original_dot = theano.tensor.dot def debug_wrapper(*args,**kw): traceback.print_stack() return original_d...
1
2016-06-12T20:46:22Z
[ "python", "theano" ]
Untangling the cause of an error in Theano
37,778,804
<p>I have a bug in my code, but finding the exact cause of it is difficult because of how theano works.</p> <p>Following the tips in the exception details, I set <code>theano.config.optimizer='None'</code> and <code>theano.config.exception_verbosity='high'</code>, but that doesn't tell me enough.</p> <p>In my case, f...
0
2016-06-12T20:32:13Z
37,809,745
<p>You should try using theano <a href="http://deeplearning.net/software/theano/tutorial/debug_faq.html#using-test-values" rel="nofollow">test_values</a>. That way the exception will be raised exactly on the line where the error occurs and not after the compilation of the graph.</p> <p>You need to change the <code>the...
0
2016-06-14T10:43:23Z
[ "python", "theano" ]
Python: Encode ordered categories/factors to numeric w/ specific encoding conversion
37,778,810
<p>TLDR: What's the most concise way to encode ordered categories to numeric w/ a particular encoding conversion? (i.e. one that preserves the ordered nature of the categories).</p> <p>["Weak","Normal","Strong"] --> [0,1,2]</p> <p><hr> Assuming I have an <strong>ordered</strong> categorical variable like similar to t...
0
2016-06-12T20:33:09Z
37,778,832
<p>you can use <code>map()</code> in conjunction with a dictionary, containing your mapping:</p> <pre><code>In [5]: d = {'strong':3, 'normal':2, 'weak':1} In [7]: df['score_num'] = df.score.map(d) In [8]: df Out[8]: patient obs treatment score score_num 0 1 1 0 strong 3 1 ...
1
2016-06-12T20:35:47Z
[ "python", "pandas", "encoding", "types", "scikit-learn" ]
Variable set to random number, then printed, then input, correct input (variable) prints x
37,779,012
<p>Ok so here is what a trying to do. </p> <ol> <li>Am creating a random number.</li> <li>Am printing it.</li> <li>Am prompting the user to input the number that was printed.</li> <li>Then 'if' the number entered = the number printed (the variable) x will happen.</li> </ol> <p>Ok am confused hopefully your not.</p> ...
-2
2016-06-12T20:54:43Z
37,779,023
<p>The problem is that your input is a string, which you compare to an int. This should work: </p> <pre><code>if int(ask) == var : print('thank you') </code></pre> <p>A different approach would be to convert the variable to an int directly (as pointed out by Alex.S and cricket_007). This is better if you later us...
0
2016-06-12T20:57:51Z
[ "python" ]
Variable set to random number, then printed, then input, correct input (variable) prints x
37,779,012
<p>Ok so here is what a trying to do. </p> <ol> <li>Am creating a random number.</li> <li>Am printing it.</li> <li>Am prompting the user to input the number that was printed.</li> <li>Then 'if' the number entered = the number printed (the variable) x will happen.</li> </ol> <p>Ok am confused hopefully your not.</p> ...
-2
2016-06-12T20:54:43Z
37,779,030
<p>You have to convert your input variable to a number:</p> <p><code>ask = int(input('Please enter pin. '))</code></p>
0
2016-06-12T20:58:49Z
[ "python" ]
Variable set to random number, then printed, then input, correct input (variable) prints x
37,779,012
<p>Ok so here is what a trying to do. </p> <ol> <li>Am creating a random number.</li> <li>Am printing it.</li> <li>Am prompting the user to input the number that was printed.</li> <li>Then 'if' the number entered = the number printed (the variable) x will happen.</li> </ol> <p>Ok am confused hopefully your not.</p> ...
-2
2016-06-12T20:54:43Z
37,779,046
<p>Your code will work fine in Python 2.7. However, in Python 3 you will need to do the following: </p> <pre><code>if int(ask) == var: print('thank you') </code></pre>
0
2016-06-12T21:00:57Z
[ "python" ]
Variable set to random number, then printed, then input, correct input (variable) prints x
37,779,012
<p>Ok so here is what a trying to do. </p> <ol> <li>Am creating a random number.</li> <li>Am printing it.</li> <li>Am prompting the user to input the number that was printed.</li> <li>Then 'if' the number entered = the number printed (the variable) x will happen.</li> </ol> <p>Ok am confused hopefully your not.</p> ...
-2
2016-06-12T20:54:43Z
37,779,143
<p>The recommendations to convert your input to an int are fine, but only if you are going to be entering numbers into your input. Otherwise, the code will error out. </p> <p>The way to prevent that is switch the variable that is casted </p> <pre><code>if ask == str(var) : </code></pre>
0
2016-06-12T21:13:59Z
[ "python" ]
Running out of RAM when writing to a file line by line [Python]
37,779,050
<p>I have a data processing task on some large data. I run the script on EC2 using Python that looks something like the following:</p> <pre><code>with open(LARGE_FILE, 'r') as f: with open(OUTPUT_FILE, 'w') as out: for line in f: results = some_computation(line) out.write(json.dumps...
0
2016-06-12T21:01:17Z
37,801,171
<p>I was using SpaCy to do some preprocessing of text. Looks like using the tokenizer causes steady memory growth.</p> <p><a href="https://github.com/spacy-io/spaCy/issues/285" rel="nofollow">https://github.com/spacy-io/spaCy/issues/285</a></p>
0
2016-06-14T00:29:34Z
[ "python", "amazon-web-services", "file-io", "amazon-ec2", "spacy" ]
OSError: Version mismatch while installing h2o?
37,779,076
<p>I am new with H2o. Based in the <a href="https://github.com/h2oai/h2o-3/blob/master/h2o-docs/src/booklets/v2_2015/PDFs/online/Python_Vignette.pdf" rel="nofollow">documentation</a> I installed H2o for python </p> <pre><code>$ pip install h2o </code></pre> <p>Then:</p> <p>In:</p> <pre><code>import h2o h2o.init() <...
0
2016-06-12T21:05:58Z
37,780,288
<pre><code>In order to use H2O, need to update the h20 jar file to python version. </code></pre> <p>Delete H20 versions on disk and do a fresh install.. Then <code>pip install h20.</code> </p> <p>Or follow these instructions: </p> <p><a href="http://www.h2o.ai/download/h2o/python" rel="nofollow">http://www.h2o.ai/d...
0
2016-06-13T00:01:38Z
[ "python", "python-3.x", "machine-learning", "h2o" ]
OSError: Version mismatch while installing h2o?
37,779,076
<p>I am new with H2o. Based in the <a href="https://github.com/h2oai/h2o-3/blob/master/h2o-docs/src/booklets/v2_2015/PDFs/online/Python_Vignette.pdf" rel="nofollow">documentation</a> I installed H2o for python </p> <pre><code>$ pip install h2o </code></pre> <p>Then:</p> <p>In:</p> <pre><code>import h2o h2o.init() <...
0
2016-06-12T21:05:58Z
37,781,534
<p>First try again with the latest version of H2O:</p> <pre><code>pip3 uninstall h2o pip3 install http://h2o-release.s3.amazonaws.com/h2o/rel-turchin/9/Python/h2o-3.8.2.9-py2.py3-none-any.whl </code></pre> <p>If you run into the same issue, then do the following:</p> <p>It looks like you already have a development v...
2
2016-06-13T03:47:41Z
[ "python", "python-3.x", "machine-learning", "h2o" ]
Search for a number and access info related in a text file, in python?
37,779,085
<p>I am new in python. I have a large text file which has lots of numbers and looks like this. With 8 space gaps between the numbers.</p> <pre><code>100 200 300 400 500 .. 101 201 301 401 501 .. 102 202 302 402 502 ...
-1
2016-06-12T21:07:12Z
37,779,727
<p>You can open the text file and read it, and then store those numbers in a list, like this:</p> <pre><code>handle = open(name, 'r') text = handle.read() numbers = text.split() </code></pre> <p>To find a certain number, use a loop to run through the list and find the position of your desired number. After that, if ...
0
2016-06-12T22:33:32Z
[ "python", "python-2.7" ]
Writing a repr method
37,779,105
<p>Situation: I'm new to python and currently trying to learn the ropes, I've attempted creating a linked list class to assist in getting a better understanding of the language and its structures. I know that the <code>__repr__</code> function is basically supposed to return the same thing as <code>__str__</code> but ...
2
2016-06-12T21:09:25Z
37,779,152
<p>The <code>__repr__</code> function returns a string representation of a Python object that may be evaluated by the Python interpreter to instantiate another instance of the object. So if you had a list:</p> <pre><code>x = ['foo', 'bar'] </code></pre> <p>Its <code>__repr__</code> string would be:</p> <pre><code>x_...
1
2016-06-12T21:15:38Z
[ "python", "repr" ]
Looping over list of vectors to create histograms for each vector
37,779,161
<p>I am working on creating histograms for output data from a CFD simulation. </p> <p>Since output variables are a lot more than one, I want to loop over the list containing output variables and create separate figure for each histogram of output variable. </p> <p>Here is a sample code of my working thus far:</p> <p...
2
2016-06-12T21:16:51Z
37,779,673
<p>Give this code a try:</p> <pre><code>var = {'Power': data[:,][:,9], 'Per_Lk': data[:,][:,10], 'VFR_Fan': data[:,][:,11], 'VFR_MF': data[:,][:,13], 'TP': =data[:,][:,14], } numbins = 40 for i in var: plt.hist(var[i], numbins, color='g') plt.figure() plt.show() </code><...
2
2016-06-12T22:25:45Z
[ "python", "numpy", "matplotlib", "statistics", "histogram" ]
How can I get open() to skip bytes at the beginning of a binary file?
37,779,265
<p>I would like to open time series data written as a binary file using Python 3.5.</p> <p>Here is the script that I wrote so far: </p> <pre><code>filename = 'dummy.ats' file = open(filename, 'rb') </code></pre> <p>The binary file starts with a header of 1024 bytes that I would like to skip. How can I modify my scri...
-1
2016-06-12T21:30:47Z
37,779,365
<p>The function <code>seek()</code> allows you to move the reading cursor where you want in your file (this cursor automatically moves forward when you read something). </p> <p>It works like :</p> <pre><code>file.seek(how many positions you will move[,0 or 1 or 2]) </code></pre> <blockquote> <p>( [] &lt;- means op...
1
2016-06-12T21:43:56Z
[ "python" ]
python TypeError adding time using timedelta
37,779,269
<p>I'm trying to add time. eventually I will create a function passing different times and I want to change the time. For some reason I can't make timedelta to do it.</p> <p>this is my code:</p> <pre><code>time1 = datetime.time(9,0) timedelta = datetime.timedelta(minutes=15) time2 = time1 + timedelta </code></pre> <...
0
2016-06-12T21:31:19Z
37,779,356
<p><code>time</code> objects don't participate in arithmetic by design: there's no compelling answer to "what happens if the result overflows? Wrap around? Raise <code>OverflowError</code>?".</p> <p>You can implement your <em>own</em> answer by combining the <code>time</code> object with a <code>date</code> to crea...
0
2016-06-12T21:42:40Z
[ "python" ]
python TypeError adding time using timedelta
37,779,269
<p>I'm trying to add time. eventually I will create a function passing different times and I want to change the time. For some reason I can't make timedelta to do it.</p> <p>this is my code:</p> <pre><code>time1 = datetime.time(9,0) timedelta = datetime.timedelta(minutes=15) time2 = time1 + timedelta </code></pre> <...
0
2016-06-12T21:31:19Z
37,779,368
<p>You can only add a <code>timedelta</code> to a <code>datetime</code> (as pointed out by Ben). What you can do, is make a <code>datetime</code> object with your time and then add the <code>timedelta</code>. This can then be turned back to and <code>time</code> object. The code to do this would look like this: </p> <...
0
2016-06-12T21:44:28Z
[ "python" ]
Pandas: Create a new Data Frame using multiple GroupBy results
37,779,286
<p>My data is a Data Frame with retail items and their sales performance. Columns include: 2016 unit sales, 2015 unit sales, item description, etc. When I try to do a groupby for brand: </p> <pre><code>Data.groupby(by="Major Brand").sum() </code></pre> <p>I get the following error: <code>TypeError: unorderable types:...
0
2016-06-12T21:33:33Z
37,779,319
<p>you can do it this way:</p> <pre><code>Data.groupby(by="Major Brand")["2016 Units","2015 Units"].sum() </code></pre> <p>Demo:</p> <pre><code>In [29]: Data.groupby(by="Major Brand")["2016 Units","2015 Units"].sum() Out[29]: 2016 Units 2015 Units Major Brand 1 218 238 2 ...
2
2016-06-12T21:37:39Z
[ "python", "pandas", "dataframe" ]
Pandas: Create a new Data Frame using multiple GroupBy results
37,779,286
<p>My data is a Data Frame with retail items and their sales performance. Columns include: 2016 unit sales, 2015 unit sales, item description, etc. When I try to do a groupby for brand: </p> <pre><code>Data.groupby(by="Major Brand").sum() </code></pre> <p>I get the following error: <code>TypeError: unorderable types:...
0
2016-06-12T21:33:33Z
37,784,613
<blockquote> <p>I get the following error: TypeError: unorderable types: int() &lt; str()</p> </blockquote> <p>Could it be that your dtypes are not correct? Eg str. instead of int? You could try create your dataframe with something as follows:</p> <pre class="lang-py prettyprint-override"><code>In [18]: import nump...
1
2016-06-13T08:07:17Z
[ "python", "pandas", "dataframe" ]
Heart Rate measuring using Xiaomi MiBand 1S and BLE
37,779,288
<p>I am trying to get heart rate measurement notifications on my computer from Xiaomi MiBand 1S using Python and <a href="https://bitbucket.org/OscarAcena/pygattlib" rel="nofollow" title="pygattlib">pygattlib</a>.</p> <p>I can successfully initialize the device with user info (tapping the sensor to "pair"), using the ...
0
2016-06-12T21:33:48Z
39,274,242
<p>I managed to make a measurement, coping the packages sniffed from the official application, but when I tried to do the same a bit later it didn't work anymore, and now I have your same problem. Did you solved the problem about disconnection after the writing command in handle 0x004c?</p> <p>Here are the shell comma...
0
2016-09-01T14:26:26Z
[ "python", "bluetooth", "bluetooth-lowenergy", "gatt" ]
Will pop(0) copy all elements
37,779,335
<p>When removing an element from the front of a list in python by doing <code>list.pop(0)</code>. Will this create a new array or just move the pointer to the new first element. And if not what are the reasons for not doing so? </p>
-2
2016-06-12T21:40:16Z
37,779,374
<blockquote> <p>Will this create a new array or just move the pointer to the new first element.</p> </blockquote> <p>Neither. It shifts all remaining list elements to fill the gap. While it could be implemented by changing the pointer to the first element, doing so would introduce additional time and space overhead ...
4
2016-06-12T21:45:55Z
[ "python", "arrays", "performance" ]
Plotting fits image with matplotlib.imshow with WCS as x and y axes
37,779,372
<p>I was wondering if anyone knew how to plot a fits image with the python package matplotlib.imshow with the corresponding world coordinate system values or perhaps even Right Ascension or Declination as the x and y values rather than the physical pixel values, similar to the bottom plot of this page: <a href="http://...
-1
2016-06-12T21:45:05Z
37,784,418
<p>One solution might be to use the <a href="http://aplpy.readthedocs.io/en/stable/api/aplpy.FITSFigure.html#aplpy.FITSFigure" rel="nofollow"><code>subplot</code> parameter to <code>FITSFigure</code></a>, and obtain the bounds from your gridspec. </p> <p>Something along the following lines:</p> <pre><code>from matplo...
1
2016-06-13T07:55:33Z
[ "python", "image", "matplotlib", "astropy", "fits" ]
Simple script to send email with python
37,779,377
<p>So I was trying to send a basic email with python with the folllowing code but it gives me an error sugesting I sign in using a browser . I did it and it stil spit out the same error. The code:</p> <pre><code>import smtplib server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login("projtig6@gmail....
0
2016-06-12T21:46:10Z
38,546,336
<p>First, make sure you "allow less secure apps to authenticate to your gmail": <a href="https://support.google.com/accounts/answer/6010255?hl=en" rel="nofollow">https://support.google.com/accounts/answer/6010255?hl=en</a></p> <p>If that's not the issue, try using this wrapper I wrote around sending emails in python; ...
0
2016-07-23T20:55:09Z
[ "python", "email", "gmail", "smtplib" ]
convert list of strings to unique lowercase, preserving order (python 2.7)
37,779,453
<p>I'd like to convert a list of strings to lowercase and remove duplicates while preserving the order. A lot of the single-line Python magic I've found on StackOverflow converts a list of strings to lowercase, but it seems the order is lost.</p> <p>I've written the code below which actually works, and I'm happy to st...
0
2016-06-12T21:57:49Z
37,779,486
<p>Slightly modifying the answer from <a href="http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order">How do you remove duplicates from a list in Python whilst preserving order?</a></p> <pre><code>def f7(seq): seen = set() seen_add = seen.add s...
1
2016-06-12T22:03:11Z
[ "python", "string", "list", "python-2.7" ]
convert list of strings to unique lowercase, preserving order (python 2.7)
37,779,453
<p>I'd like to convert a list of strings to lowercase and remove duplicates while preserving the order. A lot of the single-line Python magic I've found on StackOverflow converts a list of strings to lowercase, but it seems the order is lost.</p> <p>I've written the code below which actually works, and I'm happy to st...
0
2016-06-12T21:57:49Z
37,779,539
<p>Just do something like:</p> <pre><code>initial_list = ['ONE','one','TWO','two'] uninique_list = [x.lower() for x in list(set(initial_list))] print unique_list </code></pre>
0
2016-06-12T22:11:12Z
[ "python", "string", "list", "python-2.7" ]
convert list of strings to unique lowercase, preserving order (python 2.7)
37,779,453
<p>I'd like to convert a list of strings to lowercase and remove duplicates while preserving the order. A lot of the single-line Python magic I've found on StackOverflow converts a list of strings to lowercase, but it seems the order is lost.</p> <p>I've written the code below which actually works, and I'm happy to st...
0
2016-06-12T21:57:49Z
37,779,685
<p>You can also do:</p> <pre><code>pip install orderedset </code></pre> <p>and then:</p> <pre><code>from orderedset import OrderedSet initial_list = ['ONE','one','TWO','two','THREE','three'] unique_list = [x.lower() for x in list(OrderedSet(initial_list))] print unique_list </code></pre>
1
2016-06-12T22:26:49Z
[ "python", "string", "list", "python-2.7" ]
convert list of strings to unique lowercase, preserving order (python 2.7)
37,779,453
<p>I'd like to convert a list of strings to lowercase and remove duplicates while preserving the order. A lot of the single-line Python magic I've found on StackOverflow converts a list of strings to lowercase, but it seems the order is lost.</p> <p>I've written the code below which actually works, and I'm happy to st...
0
2016-06-12T21:57:49Z
37,785,371
<pre><code>initial_list = ['ONE','one','TWO','two'] new_list = [] [new_list.append(s.lower()) for s in initial_list if s.lower() not in new_list] </code></pre>
0
2016-06-13T08:49:50Z
[ "python", "string", "list", "python-2.7" ]
How to observe CoAP resources with aiocoap library?
37,779,470
<p>I'm using <a href="http://aiocoap.readthedocs.io/en/latest/index.html" rel="nofollow">aiocoap</a> library to issue CoAP requests to an embedded device. The communications and the basic functionality seems to work fine, but the documentation doesn't say how to enable observations. The observe functionality <em>does</...
1
2016-06-12T22:00:25Z
37,786,621
<p>It helps to replace this line:</p> <pre><code> response = yield from protocol.request(request).response </code></pre> <p>with this:</p> <pre><code> protocol_request = protocol.request(request) protocol_request.observation.register_callback(observation_callback) response = yield from protocol_request...
0
2016-06-13T09:51:07Z
[ "python", "python-3.x", "python-asyncio" ]
Django: Got FieldDoesNotExist error when changing field type in models
37,779,517
<p>I made a change in my <code>models.py</code>. I change the field from <code>FileField()</code> to <code>ImageWithThumbsField()</code></p> <pre><code>from mongoengine import * from gradfounder.settings import DBNAME from embed_video.fields import EmbedVideoField from thumbs import ImageWithThumbsField #############...
0
2016-06-12T22:08:06Z
37,779,553
<p>Yes! I found the solution!</p> <p>The error was caused by Mongoengine validation who got confused by the changed field. The solution is to disable the validation by adding this code:</p> <pre><code>class Author(Document): # photo = FileField() photo = ImageWithThumbsField(upload_to="avatars") photoname...
0
2016-06-12T22:13:21Z
[ "python", "django", "django-models", "mongoengine", "django-file-upload" ]
Generate python methods from template requiring mere search/replace of string
37,779,525
<p>I'm working with ANTLR to parse some language these days. I chose to work with Python. The parser class which ANTLR generates, contains many methods with similar names:</p> <pre><code>class autogeneratedparser(xxx): def something_enter(self,ctx): pass def something_exit(self,ctx) pass </code><...
0
2016-06-12T22:08:42Z
37,781,344
<p>All you need to do is iterate over the initial class' attributes, select only the ones that match <code>SOMETHING_enter</code> and <code>SOMETHING_exit</code>, then create stub methods and put it all together with <code>type()</code> (<a href="https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python/...
0
2016-06-13T03:18:37Z
[ "python", "dynamic", "methods", "lambda" ]
Insert Rows based on Missing numbers in repeated Series using Excel or Python
37,779,541
<p>I have a csv file with the following format (actually, the repeat number is larger than 4):</p> <pre><code>Number, Time, Speed 1, 12, 5.8 2, 11, 6.2 3, 9, 7.0 4, 3, 11.9 1, 6, 9.5 3, 7.5, 8.2 4, 4.2, 8.2 2, 2.3, 8.1 4, 4.6, 9.2 </code></pre> <p>I want the output looks like this:</p> <pre><code>Number, Time, Speed...
0
2016-06-12T22:11:30Z
37,811,430
<p>This creates a new dataframe called data2 with the rows inserted. The fourth row in your sample has an extra variable so i have an extra column added also. </p> <pre><code>data = pd.read_csv("soqn.csv") data2 = data.copy() data2_index = 0 for index , row in data.iterrows(): #Set the current value of the number...
2
2016-06-14T12:01:21Z
[ "python", "excel", "vba", "csv", "pandas" ]
How to install python-fitbit module?
37,779,565
<p>I am following <a href="https://roboticape.wordpress.com/2014/01/13/first-steps-into-the-quantified-self-getting-to-know-the-fitbit-api/" rel="nofollow">this tutorial</a> and try to download my personal Fitbit data. After cloning the <a href="https://github.com/orcasgit/python-fitbit" rel="nofollow">git repo</a>, I ...
0
2016-06-12T22:14:38Z
37,779,617
<p>If you're just looking to use the library, you don't need to clone the git repo at all. You should be able to just use <code>pip install fitbit</code>.</p>
2
2016-06-12T22:20:41Z
[ "python", "api", "module", "install" ]
eval() Method Returning Undesired Complex Number in Python
37,779,616
<p>I am writing some simple mathematical functions in Python. I need to use the eval() method to evaluate a user inputted function. If the user inputs the function y=x**0.4, however, my code starts yielding complex numbers when x is negative. Just as a test, I wrote:</p> <pre><code>print(eval("(-9.451)**0.4")) </code>...
-1
2016-06-12T22:20:36Z
37,779,653
<p>No, 0.7588806326318368+2.335594429732145j is the correct answer.</p> <p>2.455789314 would be the result of 9.451**0.4, not -9.451.</p>
1
2016-06-12T22:24:33Z
[ "python", "math" ]
eval() Method Returning Undesired Complex Number in Python
37,779,616
<p>I am writing some simple mathematical functions in Python. I need to use the eval() method to evaluate a user inputted function. If the user inputs the function y=x**0.4, however, my code starts yielding complex numbers when x is negative. Just as a test, I wrote:</p> <pre><code>print(eval("(-9.451)**0.4")) </code>...
-1
2016-06-12T22:20:36Z
37,779,733
<blockquote> <p>In reality, (-9.451)**0.4 should evaluate to 2.455789314</p> </blockquote> <p>No, the square of the real fifth root of -9.451 is (roughly) 2.455789314. When you use negative numbers as the base of exponents, you lose nice properties like square(fifthroot(x)) = x^0.4. Also, when you use binary floatin...
3
2016-06-12T22:34:11Z
[ "python", "math" ]
eval() Method Returning Undesired Complex Number in Python
37,779,616
<p>I am writing some simple mathematical functions in Python. I need to use the eval() method to evaluate a user inputted function. If the user inputs the function y=x**0.4, however, my code starts yielding complex numbers when x is negative. Just as a test, I wrote:</p> <pre><code>print(eval("(-9.451)**0.4")) </code>...
-1
2016-06-12T22:20:36Z
37,779,747
<p>Sorry, but you realize that you are trying to compute the root of a negative number? You could just use the <code>abs</code> function here to solve this problem, I guess :)</p> <pre><code>&gt;&gt;&gt; eval("abs(-9.451)**0.4") 2.4557893140046687 </code></pre>
0
2016-06-12T22:36:31Z
[ "python", "math" ]
Functional programming method, or most Pythonic way, to loop over an array using two adjacent variables at a time
37,779,623
<p>Consider the problem: Given an array of integers, returning the number of times at which the array is decreasing. So [3,2,1] is decreasing twice (at 3 and 2); [1,2,3,4,5,4,3,2,1] is decreasing 4 times (at 5, 4, 3, 2), and [1] is decreasing none.</p> <p>It's extremely easy to solve this in a for loop in any language...
1
2016-06-12T22:21:17Z
37,779,699
<p>One nice way of doing this is using the <a href="https://docs.python.org/3.3/library/functions.html#zip">zip</a> method in combination with <a href="https://docs.python.org/3.3/library/functions.html#sum">sum</a>:</p> <pre><code>sum(a &gt; b for a, b in zip(array, array[1:])) </code></pre>
6
2016-06-12T22:29:40Z
[ "python", "arrays", "functional-programming", "language-agnostic" ]
Functional programming method, or most Pythonic way, to loop over an array using two adjacent variables at a time
37,779,623
<p>Consider the problem: Given an array of integers, returning the number of times at which the array is decreasing. So [3,2,1] is decreasing twice (at 3 and 2); [1,2,3,4,5,4,3,2,1] is decreasing 4 times (at 5, 4, 3, 2), and [1] is decreasing none.</p> <p>It's extremely easy to solve this in a for loop in any language...
1
2016-06-12T22:21:17Z
37,779,843
<p>I don't know if python arrays have a reduce function, but if they have, you could do something that in javascript would be done this way:</p> <pre><code>let result = 0; [1,2,3,4,5,4,3,2,1].reduce((prev,current) =&gt; { if (prev &gt; current){ result = result + 1;; } return current; }); console....
0
2016-06-12T22:50:51Z
[ "python", "arrays", "functional-programming", "language-agnostic" ]
Functional programming method, or most Pythonic way, to loop over an array using two adjacent variables at a time
37,779,623
<p>Consider the problem: Given an array of integers, returning the number of times at which the array is decreasing. So [3,2,1] is decreasing twice (at 3 and 2); [1,2,3,4,5,4,3,2,1] is decreasing 4 times (at 5, 4, 3, 2), and [1] is decreasing none.</p> <p>It's extremely easy to solve this in a for loop in any language...
1
2016-06-12T22:21:17Z
37,809,809
<p>Here it is as a recursive function.</p> <pre><code>def decreasing(xs): if len(xs) &lt; 2: return 0 (x0, x1, *xss) = xs if x0 &gt; x1: return 1 + decreasing([x1] + xss) return decreasing([x1] + xss) </code></pre> <p>I'm not sure creating multiple lists like this in python is healthy ...
0
2016-06-14T10:46:14Z
[ "python", "arrays", "functional-programming", "language-agnostic" ]
Anaconda Accelerate check_cuda()
37,779,627
<p>What is the correct anaconda accelerate function to check cuda?</p> <p>With numba-pro you could use:</p> <pre><code>&gt;&gt;&gt; from numbapro import check_cuda numbapro:1: ImportWarning: The numbapro package is deprecated in favour of the accelerate package. Please update your code to use equivalent functions fro...
0
2016-06-12T22:21:35Z
38,248,831
<p>I didn't see a direct analog, but the underlying routines still seem to be present, now in numba: First part is from <code>numba.cuda.cudadrv.libs.test()</code> which generates searches for CUDA libraries. The second is <code>numba.cuda.api.detect()</code> which searches for devices. (In accelerate proper, you might...
1
2016-07-07T14:59:09Z
[ "python", "python-3.x", "anaconda", "numba-pro", "accelerate" ]
Python: Given a link, how to save locally if the link is an image and do not save if it is not an image?
37,779,631
<p>I am currently using</p> <pre><code>import urllib urllib.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg") </code></pre> <p>Is there a way to see if the link contains a pic or not, if not then no need to download, if so, then download.</p> <p>Thanks!</p>
-1
2016-06-12T22:22:11Z
37,779,730
<p>You can do something like this:</p> <pre><code>import urllib url_obj = urllib.urlopen("https://upload.wikimedia.org/wikipedia/commons/1/1e/Large_Siamese_cat_tosses_a_mouse.jpg") main_type = url_obj.maintype if main_type == "image": // perform some operations else: // perform other operations </code></pre>...
-1
2016-06-12T22:33:59Z
[ "python", "web-scraping" ]
Python: Given a link, how to save locally if the link is an image and do not save if it is not an image?
37,779,631
<p>I am currently using</p> <pre><code>import urllib urllib.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg") </code></pre> <p>Is there a way to see if the link contains a pic or not, if not then no need to download, if so, then download.</p> <p>Thanks!</p>
-1
2016-06-12T22:22:11Z
37,779,953
<p>The extension does not mean a file is an actual image, if you want to check that the file is indeed an image you could use <a href="http://www.imagemagick.org/script/identify.php" rel="nofollow">imagemagik identify</a>:</p> <pre><code>from subprocess import check_output, CalledProcessError from tempfile import Nam...
1
2016-06-12T23:04:34Z
[ "python", "web-scraping" ]
Why is the following algorithm O(1) space?
37,779,668
<p>Input: A list of positive integers where one entry occurs exactly once, and all other entries occur exactly twice (for example [1,3,2,5,3,4,1,2,4])</p> <p>Output: The unique entry (5 in the above example)</p> <p>The following algorithm is supposed to be O(m) time and O(1) space where m is the size of the list.</p>...
2
2016-06-12T22:25:28Z
37,779,777
<p>Your analysis is certainly one correct answer, particularly in a language like Python which gracefully handles arbitrarily large numbers.</p> <p>It's important to be clear about what you're trying to measure when thinking about space and time complexity. A reasonable assumption might be that the size of an integer ...
3
2016-06-12T22:40:37Z
[ "python", "algorithm", "asymptotic-complexity", "space-complexity" ]
Why is the following algorithm O(1) space?
37,779,668
<p>Input: A list of positive integers where one entry occurs exactly once, and all other entries occur exactly twice (for example [1,3,2,5,3,4,1,2,4])</p> <p>Output: The unique entry (5 in the above example)</p> <p>The following algorithm is supposed to be O(m) time and O(1) space where m is the size of the list.</p>...
2
2016-06-12T22:25:28Z
37,779,782
<p>The (space/time) complexity analysis is usually applied to algorithms on a higher level. While you can drop down to specific language implementation level, it may not be useful in all cases.</p> <p>Your analysis is both right and possibly wrong. It's right for current cpython implementation where integers do not ha...
2
2016-06-12T22:41:37Z
[ "python", "algorithm", "asymptotic-complexity", "space-complexity" ]
Why is the following algorithm O(1) space?
37,779,668
<p>Input: A list of positive integers where one entry occurs exactly once, and all other entries occur exactly twice (for example [1,3,2,5,3,4,1,2,4])</p> <p>Output: The unique entry (5 in the above example)</p> <p>The following algorithm is supposed to be O(m) time and O(1) space where m is the size of the list.</p>...
2
2016-06-12T22:25:28Z
37,779,856
<p>The complexity of an algorithm is always dependent on the machine model (= platform) you use. E.g. we often say that multiplying and dividing IEEE floating point numbers is of run-time complexity O(1) - which is not always the case (e.g. on an 8086 processor without FPU). </p> <p>For the above algorithm, the space ...
1
2016-06-12T22:52:20Z
[ "python", "algorithm", "asymptotic-complexity", "space-complexity" ]
Finding average length per line in a file using Python
37,779,737
<p>I'm very beginner at Python. My question is as the title states, how would I write a function that would return the average line length in a file? (Not really sure how to incorporate files in functions) (Any help would help!)</p>
-1
2016-06-12T22:34:52Z
37,779,780
<p>Pretty straightforward, sum the length of the lines then divide by the number of lines.</p> <pre><code>with open("testfile.txt", "r") as f: lines = f.readlines() print(sum(len(line) for line in lines) / len(lines)) </code></pre>
-2
2016-06-12T22:41:01Z
[ "python" ]
Finding average length per line in a file using Python
37,779,737
<p>I'm very beginner at Python. My question is as the title states, how would I write a function that would return the average line length in a file? (Not really sure how to incorporate files in functions) (Any help would help!)</p>
-1
2016-06-12T22:34:52Z
37,779,841
<p>if you have test.txt like:</p> <pre><code>line one text line two text longer line three text even longer </code></pre> <p>and the script test.py:</p> <pre><code>from __future__ import division def average(lines): length = 0 for l in lines: length = length+len(l) return int(length/len(lines))...
0
2016-06-12T22:50:42Z
[ "python" ]
Python - Panda - Get last non empty value
37,779,762
<p>Consider I have one DataFrame like this:</p> <pre><code>ID, name, result_1, result_2 1 , John, 8.9, 1.1 2 , John, 3.3, 3 , John, , 9.9 4 , Mark, 8.8, 4.5 5 , Mark, 5.5, </code></pre> <p>What I need to retrieve is the 'result_1'...
0
2016-06-12T22:38:41Z
37,782,058
<p>Try This: </p> <pre><code>ID name, result_1 result_2 1 John, 8.9 1.1 2 John, 3.3 N/A 3 John, N/A 9.9 4 Mark, 8.8 4.5 5 Mark, 5.5 N/A df = df.groupby(['name,']).last() df[['result_1', 'result_2' ]] # result_1 re...
0
2016-06-13T04:56:06Z
[ "python", "pandas", "dataframe" ]