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
Removing zigzag line joining data in matplotlib
39,511,404
<p>I am plotting using the matplotlib.pyplot plot() method:</p> <pre><code>import matplotlib.pyplot as plt import matplotlib #matplotlib.style.use('ggplot') plt.plot(df_both_grouped['TSD_mean'], df_both_grouped['hgd_mean'], 'or', color = 'blue') plt.errorbar(df_both_grouped['TSD_mean'], df_both_grouped['hgd_mean'], y...
0
2016-09-15T12:46:02Z
39,511,534
<p>You are looking for the <em>fmt</em> argument of the <em>errorbar</em> method.</p> <p>Simply change your code to</p> <pre><code>import matplotlib.pyplot as plt import matplotlib #matplotlib.style.use('ggplot') plt.plot(df_both_grouped['TSD_mean'], df_both_grouped['hgd_mean'], 'or', color = 'blue') plt.errorbar(df...
0
2016-09-15T12:52:35Z
[ "python", "matplotlib", "plot" ]
What determines how "at most size bytes are read and returned" with Python read()?
39,511,613
<p>In the documentation for Python's input/output, it states under Reading and Writing Files:</p> <p><a href="https://docs.python.org/3.5/tutorial/inputoutput.html#methods-of-file-objects" rel="nofollow">https://docs.python.org/3.5/tutorial/inputoutput.html#methods-of-file-objects</a></p> <p>"When size is omitted or ...
-2
2016-09-15T12:56:41Z
39,511,682
<p><code>read</code> is not <code>readline</code> or <code>readlines</code>. It just reads bytes regardless of the file content (apart from the end of line translation since your file is open as text)</p> <ul> <li>If there's 1000 bytes to be read in the buffer, it returns 1000 bytes (or less if file has <code>\r\n</co...
1
2016-09-15T12:59:08Z
[ "python", "file", "input", "chunking" ]
Django field Error
39,511,646
<p>I am a Django beginner working on Django v1.9 and trying to learn and replicate DjangoGirl tutorial. I have stuck at "Dynamic data in templates" and "Django templates". </p> <pre><code>from django.shortcuts import render from .models import Post from django.utils import timezone # Create your views here. def po...
0
2016-09-15T12:58:00Z
39,511,679
<pre><code>from django.shortcuts import render from .models import Post from django.utils import timezone def post_list(request): posts = Post.objects.filter(publish_Data__lte=timezone.now()).order_by('publish_Data') return render(request, 'blog/post_list.html', {'posts':posts}) </code></pre>
1
2016-09-15T12:59:02Z
[ "python", "django" ]
Python simple ProcessPoolExecutor example wont work
39,511,695
<p>I'm trying out multithreading in Python 3, but I can't figure out why my example won't work. It should just print the numbers and as confirmation print the number again. But it runs into many errors.</p> <pre><code>from concurrent import futures def print_me(num): print('Zahl: ' + str(num)) return num de...
0
2016-09-15T12:59:40Z
39,576,162
<p>To get the code running i just need to add:</p> <pre><code>**if __name__ == "__main__":** test_multi() </code></pre>
0
2016-09-19T14:53:06Z
[ "python", "multithreading" ]
Generating a list of random lists
39,511,708
<p>I'm new to Python, so I might be doing basic errors, so apologies first.</p> <p>Here is the kind of result I'm trying to obtain : </p> <pre><code>foo = [ ["B","C","E","A","D"], ["E","B","A","C","D"], ["D","B","A","E","C"], ["C","D","E","B","A"] ] </code></pre> <p>So basically, a list of lists of r...
1
2016-09-15T13:00:20Z
39,511,956
<p><code>np.repeat</code> repeats the same array. Your approach would work if you changed it to:</p> <pre><code>[''.join(random.sample(letters, len(letters))) for _ in range(nblines)] Out: ['EBCAD', 'BCEAD', 'EBDCA', 'DBACE'] </code></pre> <p>This is a short way of writing this:</p> <pre><code>foo = [] for _ in rang...
1
2016-09-15T13:12:10Z
[ "python" ]
Generating a list of random lists
39,511,708
<p>I'm new to Python, so I might be doing basic errors, so apologies first.</p> <p>Here is the kind of result I'm trying to obtain : </p> <pre><code>foo = [ ["B","C","E","A","D"], ["E","B","A","C","D"], ["D","B","A","E","C"], ["C","D","E","B","A"] ] </code></pre> <p>So basically, a list of lists of r...
1
2016-09-15T13:00:20Z
39,512,413
<p>Here's a plain Python solution using a "traditional" style <code>for</code> loop.</p> <pre><code>from random import shuffle nblines = 4 letters = list("ABCDE") foo = [] for _ in range(nblines): shuffle(letters) foo.append(letters[:]) print(foo) </code></pre> <p><strong>typical output</strong></p> <pre><...
1
2016-09-15T13:31:57Z
[ "python" ]
Generating a list of random lists
39,511,708
<p>I'm new to Python, so I might be doing basic errors, so apologies first.</p> <p>Here is the kind of result I'm trying to obtain : </p> <pre><code>foo = [ ["B","C","E","A","D"], ["E","B","A","C","D"], ["D","B","A","E","C"], ["C","D","E","B","A"] ] </code></pre> <p>So basically, a list of lists of r...
1
2016-09-15T13:00:20Z
39,512,427
<p>The problem with your code is that the line</p> <pre><code>foo = np.repeat(''.join(random.sample(letters, len(letters))), nblines) </code></pre> <p>will first create a random permutation, and then repeat that same permutation nblines times. Numpy.repeat does not repeatedly invoke a function, it repeats elements ...
2
2016-09-15T13:32:28Z
[ "python" ]
Data structures homework in Python
39,511,713
<p>I'm supposed to write a function called manipulate_data which will act as follows:</p> <p>When given a list of integers, return a list, where the first element is the count of positives numbers and the second element is the sum of negative numbers. </p> <p>Here is my code</p> <pre><code>def manipulate_data(data):...
-6
2016-09-15T13:00:32Z
39,520,648
<p>Apparently, you have only to add the following at the end of your function:</p> <pre><code>else: return 'Only lists allowed' </code></pre> <p>I would say it works pretty well... ;)</p> <p><a href="http://i.stack.imgur.com/8W3t6.png" rel="nofollow"><img src="http://i.stack.imgur.com/8W3t6.png" alt="enter image...
-1
2016-09-15T21:28:14Z
[ "python" ]
Data structures homework in Python
39,511,713
<p>I'm supposed to write a function called manipulate_data which will act as follows:</p> <p>When given a list of integers, return a list, where the first element is the count of positives numbers and the second element is the sum of negative numbers. </p> <p>Here is my code</p> <pre><code>def manipulate_data(data):...
-6
2016-09-15T13:00:32Z
39,544,969
<p>This should work well, just needed to correct some things.</p> <pre><code>def manipulate_data(data): if isinstance(data, list): return [sum(1 for n in data if isinstance(n, int) and n &gt;= 0), sum(n for n in data if isinstance(n, int) and n &lt; 0)] else: return 'Only lists allowed' </code>...
0
2016-09-17T09:06:12Z
[ "python" ]
Data structures homework in Python
39,511,713
<p>I'm supposed to write a function called manipulate_data which will act as follows:</p> <p>When given a list of integers, return a list, where the first element is the count of positives numbers and the second element is the sum of negative numbers. </p> <p>Here is my code</p> <pre><code>def manipulate_data(data):...
-6
2016-09-15T13:00:32Z
40,057,215
<p>this should work now for home study</p> <pre><code>def manipulate_data(data): if isinstance(data, list): return [sum(1 for n in data if isinstance(n, int) and n &gt;= 0), sum(n for n in data if isinstance(n, int) and n &lt; 0)] else: return 'Only lists all...
0
2016-10-15T09:11:58Z
[ "python" ]
Import Module Benchmark
39,511,774
<p>I have been doing some performance testing and got rather curious at my latest findings.</p> <pre><code>&gt;&gt;&gt; timeit("import timeit") 0.8010718822479248 &gt;&gt;&gt; timeit("from timeit import timeit") 1.3421258926391602 </code></pre> <p>How can importing the <strong>whole module be faster</strong>, than im...
3
2016-09-15T13:03:16Z
39,511,879
<p><code>import timeit</code> will get the module directly while <code>from timeit import timeit</code> will take time browsing entire timeit module. Hence the results.</p>
2
2016-09-15T13:08:36Z
[ "python", "performance", "time" ]
Import Module Benchmark
39,511,774
<p>I have been doing some performance testing and got rather curious at my latest findings.</p> <pre><code>&gt;&gt;&gt; timeit("import timeit") 0.8010718822479248 &gt;&gt;&gt; timeit("from timeit import timeit") 1.3421258926391602 </code></pre> <p>How can importing the <strong>whole module be faster</strong>, than im...
3
2016-09-15T13:03:16Z
39,511,889
<p>Because when you want to import one/some part of a module, all the searching through the module's namespace, storing the object in stack and pop from it take time, while for importing the module at once python just does one step, binding the module to its name.</p> <p>For a better demonstration you can use <code>di...
2
2016-09-15T13:09:08Z
[ "python", "performance", "time" ]
Why wrap a single static method in a class?
39,511,826
<p>I'm reading some code where the author is using a coding style with which I am unfamiliar; they put absolutely every function definition into a class. For example (details removed so as to not identify the author and codebase):</p> <pre><code>class CSVChecker: @staticmethod def is_ok(file): #some st...
0
2016-09-15T13:05:38Z
39,513,383
<p>@deceze probably has the answer in his comment. Some of these function-objects are indeed stored in lists, and some elements of the lists may be instances of "proper" objects. Stripped down to the absolute basics:</p> <pre><code>class F1: def __init__(self, a): self.max=a def ok(self, x): return x &lt;...
1
2016-09-15T14:13:27Z
[ "python", "oop" ]
Pygame (A bit racey) Objects are there, but not visible
39,511,858
<p>I have a couple of objects defined/entered into a variable</p> <pre><code>car1 = pygame.image.load('C:\Users\itzrb_000\Downloads\download (3).png') car2 = pygame.image.load('C:\Users\itzrb_000\Downloads\download (2).png') car3 = pygame.image.load('C:\Users\itzrb_000\Downloads\images.png') rock = pygame.image.load('...
0
2016-09-15T13:07:24Z
39,513,920
<p>You're blitting the objects off screen. <code>gameDisplay.blit(y,(random.randrange(130, 625),-300))</code> will blit the image at x between 130 to 625 and y at -300 (which means 300 to the left of the screen).</p> <p>But is the function doing what you want it to do? Every loop you're blitting a random number of ran...
1
2016-09-15T14:38:19Z
[ "python", "pygame" ]
Why does providing an environment to my Python subprocess cause it to abort?
39,511,923
<p>I am attempting to run a subprocess through Python of an executable developed by my company; let's call it <code>prog.exe</code>. I can run this command just fine on from CMD; I can run it just fine through <code>subprocess</code>; but if I try to pass <code>env</code> to <code>subprocess</code>, I get an error:</p...
0
2016-09-15T13:10:55Z
39,514,071
<p>As described <a href="http://stackoverflow.com/a/19023293/1449189">in an older SO post</a>, the <code>os.environ</code> keys are stored/accessed in a case insensitive manner. <code>nt.environ</code> preserves the case of the environment variables as passed into the Python process.</p> <p>In this case, <code>prog.e...
1
2016-09-15T14:45:40Z
[ "python", "windows", "subprocess", "case-sensitive" ]
After reading a csv using header/skiprows argument values become NaN
39,511,976
<p>I'm an trying to open a csv file with the header spanning multiple rows. To avoid dealing with MultiIndex I am using the header argument to skip some lines, but all values become NaNs.</p> <p>An example which reproduces the error:</p> <pre><code>,, x,a,c y,b,d labels,l1,l2 2016-01-01,1,6 2016-01-02,2.0,7.0 2016-01...
0
2016-09-15T13:13:28Z
39,512,109
<p>how about this:</p> <pre><code>my_file = 'test.csv' df = pd.read_csv(my_file, sep=',', names=['labels', 'l1', 'l2'], skiprows=4, header=None) </code></pre> <p>Forget about the first 4 rows entirely and specify the headers yourself.</p>
1
2016-09-15T13:19:23Z
[ "python", "pandas" ]
After reading a csv using header/skiprows argument values become NaN
39,511,976
<p>I'm an trying to open a csv file with the header spanning multiple rows. To avoid dealing with MultiIndex I am using the header argument to skip some lines, but all values become NaNs.</p> <p>An example which reproduces the error:</p> <pre><code>,, x,a,c y,b,d labels,l1,l2 2016-01-01,1,6 2016-01-02,2.0,7.0 2016-01...
0
2016-09-15T13:13:28Z
39,513,207
<p>try this:</p> <pre><code>In [20]: pd.read_csv(filename, skiprows=3) Out[20]: labels l1 l2 0 2016-01-01 1.0 6.0 1 2016-01-02 2.0 7.0 2 2016-01-03 3.0 8.0 </code></pre>
1
2016-09-15T14:06:00Z
[ "python", "pandas" ]
How to recursively query in django efficiently?
39,511,993
<p>I have a model, which looks like:</p> <pre><code>class StaffMember(models.Model): id = models.OneToOneField(to=User, unique=True, primary_key=True, related_name='staff_member') supervisor = models.ForeignKey(to='self', null=True, blank=True, related_name='team_members') </code></pre> <p>My current hierarc...
2
2016-09-15T13:14:07Z
39,932,852
<p>I found a solution to the problem. The recursive solution takes the node, goes to it's first child and goes deep down till bottom of the hierarchy. Then comes back up again to the second child (if exists), and then again goes down till the bottom. In short, it explores all the nodes one by one and appends all the me...
0
2016-10-08T13:19:46Z
[ "python", "django", "recursion", "list-comprehension", "django-orm" ]
How to recursively query in django efficiently?
39,511,993
<p>I have a model, which looks like:</p> <pre><code>class StaffMember(models.Model): id = models.OneToOneField(to=User, unique=True, primary_key=True, related_name='staff_member') supervisor = models.ForeignKey(to='self', null=True, blank=True, related_name='team_members') </code></pre> <p>My current hierarc...
2
2016-09-15T13:14:07Z
39,933,958
<p>If you're using a database that supports recursive common table expressions (e.g. PostgreSQL), this is precisely the use-case.</p> <pre><code>team = StaffMember.objects.raw(''' WITH RECURSIVE team(id, supervisor) AS ( SELECT id, supervisor FROM staff_member WHERE id = 42 U...
0
2016-10-08T15:09:56Z
[ "python", "django", "recursion", "list-comprehension", "django-orm" ]
Convert whole dataframe from lower case to upper case with Pandas
39,512,002
<p>I have a dataframe like the one displayed below: </p> <pre><code># Create an example dataframe about a fictional army raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks'], 'company': ['1st', '1st', '2nd', '2nd'], 'deaths': ['kkk', 52, '25', 616], 'batt...
0
2016-09-15T13:14:27Z
39,512,116
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.astype.html" rel="nofollow">astype()</a> will cast each series to the <a href="http://pandas.pydata.org/pandas-docs/stable/basics.html#astype" rel="nofollow">dtype</a> object (string) and then call the <a href="http://pandas.pydata.org/p...
5
2016-09-15T13:19:39Z
[ "python", "pandas", "type-conversion", "uppercase", "lowercase" ]
Convert whole dataframe from lower case to upper case with Pandas
39,512,002
<p>I have a dataframe like the one displayed below: </p> <pre><code># Create an example dataframe about a fictional army raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks'], 'company': ['1st', '1st', '2nd', '2nd'], 'deaths': ['kkk', 52, '25', 616], 'batt...
0
2016-09-15T13:14:27Z
39,512,200
<p>Since <code>str</code> only works for series, you can apply it to each column individually then concatenate:</p> <pre><code>In [6]: pd.concat([df[col].astype(str).str.upper() for col in df.columns], axis=1) Out[6]: regiment company deaths battles size 0 NIGHTHAWKS 1ST KKK 5 L 1 NIGHTHAWKS ...
2
2016-09-15T13:23:52Z
[ "python", "pandas", "type-conversion", "uppercase", "lowercase" ]
Py.test mixin class can't access `self`
39,512,042
<p>I am trying to make a mixin for a shared set of tests. I want to be able to inherit from the mixin whenever I want those generic tests to run.</p> <p>Here is some of my mixin:</p> <pre><code>class CommonRuleWhenTestsMixin(TestCase): def test_returns_false_if_rule_inactive(self): self.rule.active = Fal...
0
2016-09-15T13:16:41Z
39,513,850
<p>Your mixin inerhits from <code>unittest.TestCase</code>, so its test gets picked up by pytest (and would probably get picked up by <code>unittest</code> as well).</p> <p>Instead, don't inherit your mixin from anything (or from <code>object</code> on Python 2), and make your <code>TestWhen</code> class inherit from ...
2
2016-09-15T14:35:20Z
[ "python", "py.test" ]
Writing Parallelly into two files python
39,512,186
<p>I am just trying to write parallelly in to two file with the help of threading.</p> <pre><code>def dmesg (i): cmd = 'dmesg' print cmd (status, cmd_out) = commands.getstatusoutput(cmd) fil = open('dmesg_logs', 'w') fil.write(cmd_out) fil.close() def dump (i): cmd = 'lsmod' print cm...
1
2016-09-15T13:23:20Z
39,675,378
<pre><code>cmd = ['dmesg'] with open ('dmesg_log.txt', 'w') as out1: retun1 = subprocess.Popen(cmd, shell = True, stdout=out1) </code></pre> <p>Found the solution. Above code works for me.</p>
0
2016-09-24T10:33:39Z
[ "python", "python-2.7" ]
Python Scrapy - Execute code after spider exits
39,512,249
<p>I am not able to find an answer for that question. How can I execute a python code after a scrapy spider exits:</p> <p>I did the following inside the function which parses the response (def parse_item(self, response):) : self.my_function() Than I defined my_function(), but the problem is that it is still inside th...
0
2016-09-15T13:26:03Z
39,516,118
<p>Use the function <a href="http://doc.scrapy.org/en/latest/topics/signals.html#spider-closed" rel="nofollow">closed</a> of the Scrapy class as follows:</p> <pre><code>class MySpider(scrapy.Spider): # some attributes spider_attr=[] def parse(self, response): # do your logic here # page_te...
1
2016-09-15T16:32:14Z
[ "python", "scrapy" ]
calculating Gini coefficient in Python/numpy
39,512,260
<p>i'm calculating <a href="https://en.wikipedia.org/wiki/Gini_coefficient" rel="nofollow">Gini coefficient</a> (similar to: <a href="http://stackoverflow.com/questions/31416664/python-gini-coefficient-calculation-using-numpy">Python - Gini coefficient calculation using Numpy</a>) but i get an odd result. for a uniform...
1
2016-09-15T13:26:21Z
39,513,799
<p>This is to be expected. A random sample from a uniform distribution does not result in uniform values (i.e. values that are all relatively close to each other). With a little calculus, it can be shown that the <em>expected</em> value (in the statistical sense) of the Gini coefficient of a sample from the uniform d...
1
2016-09-15T14:33:05Z
[ "python", "numpy", "statistics" ]
TensorFlow simple operations: tensors vs Python variables
39,512,276
<p>I'm unsure about the practical differences between the 4 variations below (they all evaluate to the same value). My understanding is that if I call <code>tf</code>, it <em>will</em> create an operation on the graph, and otherwise it <em>might</em>. If I don't create the <code>tf.constant()</code> at the beginning, I...
3
2016-09-15T13:27:02Z
39,513,161
<p>They are all the same. </p> <p>The python-'+' in a + b is captured by tensorflow and actually does generate the same op as tf.add(a, b) does.</p> <p>The tf.conctant allows you more specifics, such as defining the shape, type and name of the created tensor. But again tensorflow owns that "a" in your example a = 1 a...
1
2016-09-15T14:03:54Z
[ "python", "tensorflow" ]
TensorFlow simple operations: tensors vs Python variables
39,512,276
<p>I'm unsure about the practical differences between the 4 variations below (they all evaluate to the same value). My understanding is that if I call <code>tf</code>, it <em>will</em> create an operation on the graph, and otherwise it <em>might</em>. If I don't create the <code>tf.constant()</code> at the beginning, I...
3
2016-09-15T13:27:02Z
39,513,596
<p>The result is the same because every operator (<code>add</code> or <code>__add__</code> that's the overload of <code>+</code>) call <a href="https://www.tensorflow.org/versions/master/api_docs/python/framework.html#convert_to_tensor%60" rel="nofollow"><code>tf.convert_to_tensor</code></a> on its operands.</p> <p>Th...
1
2016-09-15T14:23:43Z
[ "python", "tensorflow" ]
TensorFlow simple operations: tensors vs Python variables
39,512,276
<p>I'm unsure about the practical differences between the 4 variations below (they all evaluate to the same value). My understanding is that if I call <code>tf</code>, it <em>will</em> create an operation on the graph, and otherwise it <em>might</em>. If I don't create the <code>tf.constant()</code> at the beginning, I...
3
2016-09-15T13:27:02Z
39,513,635
<p>The four examples you gave will all give the same result, and generate the same graph (if you ignore that some of the operation names in the graph are different). TensorFlow will convert many different Python objects into <code>tf.Tensor</code> objects when they are passed as arguments to TensorFlow operators, such ...
2
2016-09-15T14:25:13Z
[ "python", "tensorflow" ]
Python 3 | Sorted, Max, Min Dictionary trought a ZIP, Error
39,512,333
<p>I'm learning python 3 and I'm trying to use zip to transform a dictionary into a zip, this way I would be able to use functions like sorted, max and min on it.</p> <p>Stocks is the dictionary btw. So I tested it out like this, and it worked:</p> <pre><code>print(min(zip(Stocks.values(),Stocks.keys()))) print(max(z...
-1
2016-09-15T13:29:02Z
39,512,376
<p>In python3.X <code>zip</code> returns an iterator, and once you pass it to a function actually you've consumed it, therefor when you pass it to another function you're passing an empty iterator. </p> <pre><code>In [15]: a = zip(range(3), range(3)) In [16]: list(a) Out[16]: [(0, 0), (1, 1), (2, 2)] In [17]: list(a...
3
2016-09-15T13:30:50Z
[ "python", "python-3.x" ]
Python 3 | Sorted, Max, Min Dictionary trought a ZIP, Error
39,512,333
<p>I'm learning python 3 and I'm trying to use zip to transform a dictionary into a zip, this way I would be able to use functions like sorted, max and min on it.</p> <p>Stocks is the dictionary btw. So I tested it out like this, and it worked:</p> <pre><code>print(min(zip(Stocks.values(),Stocks.keys()))) print(max(z...
-1
2016-09-15T13:29:02Z
39,512,403
<p><code>zip</code> returns an iterator.</p> <p>When you are calling <code>max(stock_zip)</code> it iterates and consume the <code>stock_zip</code> iterator. By the time <code>min(stock_zip)</code> is called, <code>stock_zip</code> is totally consumed and is empty.</p> <p>Instead of saving a reference to the output o...
1
2016-09-15T13:31:30Z
[ "python", "python-3.x" ]
How to import time column from snowflake to jupyter notebook dataframe?
39,512,396
<p>I need to import data from snowflake to Jupyter. In the dataset I have a time column which is derived from timestamp values. </p> <p>Every time I try to import the data, Jupyter says the process failed and below is the error message.</p> <p>How should I get around this issue?</p> <pre><code>ERROR:snowflake.connec...
1
2016-09-15T13:31:22Z
39,553,249
<p>Can you check the Python Connector version? The error indicates TIME data type is not supported by Python Connector. TIME data type has been supported since v1.0.6. As of today, the latest version is 1.2.8: <a href="https://pypi.python.org/pypi/snowflake-connector-python/" rel="nofollow">https://pypi.python.org/pypi...
0
2016-09-18T01:29:56Z
[ "python", "jupyter", "snowflake-datawarehouse" ]
How to add queryset to ManyToMany relationship?
39,512,467
<p>I have following models:</p> <pre><code>class EnMovielist(models.Model): content_ID = models.CharField(max_length=30) release_date = models.CharField(max_length=30) running_time = models.CharField(max_length=10) actress = models.CharField(max_length=300) series = models.CharField(max_length=30) ...
0
2016-09-15T13:34:39Z
39,512,564
<p>You should call m2m <code>add</code> from instance and adding entity should be also model instance. Otherwise your expression doesn't make sense. </p> <pre><code>b = EnActress.objects.get(pk=some_pk) # get an instance, not queryset a = EnMovielist.objects.get(pk=some_pk) # also instance b.movielist.add(a) </code><...
0
2016-09-15T13:38:46Z
[ "python", "django", "django-queryset", "manytomanyfield" ]
How to add queryset to ManyToMany relationship?
39,512,467
<p>I have following models:</p> <pre><code>class EnMovielist(models.Model): content_ID = models.CharField(max_length=30) release_date = models.CharField(max_length=30) running_time = models.CharField(max_length=10) actress = models.CharField(max_length=300) series = models.CharField(max_length=30) ...
0
2016-09-15T13:34:39Z
39,512,677
<p>You should not be using <code>values_list</code> if you intend to <code>add</code> a new relation afterwards. From the <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#values-list" rel="nofollow">docs</a>:</p> <blockquote> <p><code>values()</code> and <code>values_list()</code> are both inten...
0
2016-09-15T13:43:46Z
[ "python", "django", "django-queryset", "manytomanyfield" ]
Django - Tango With Django upload picture
39,512,498
<p>I'm on chapter 9 in Tango With Django - creating user authentication. In the registration page I have the option of uploading a picture. In my admin file everything looks good after I register myself. I show up in the User Profiles, and it even shows the image I uploaded: <code>Picture: Currently: profile_image...
0
2016-09-15T13:35:43Z
39,516,325
<blockquote> <p>user profile object with primary key u'1/change/profile_images/earth.jpeg' does not exist.</p> </blockquote> <p>It looks like one of your URL patterns may be off; it probably just wants to capture that <code>1</code> to use as the PK for a lookup, but instead is capturing <code>1/change/profile_image...
1
2016-09-15T16:44:19Z
[ "python", "django" ]
csv python file not saving in individual line
39,512,506
<ol> <li><p>The code is working but the URLs saved are being saved in a single line rather than a different line.</p> <pre><code>from bs4 import BeautifulSoup import urllib2 import requests import csv import re page=requests.get("https://www.tutorialspoint.com/python/dictionary_values.htm") data=BeautifulSoup(page.c...
0
2016-09-15T13:35:58Z
39,516,448
<p>Instead of just <code>csv1.write</code>, use <code>csv.writer</code> modules</p> <pre><code>from bs4 import BeautifulSoup import urllib2 import requests import csv import re page=requests.get("https://www.tutorialspoint.com/python/dictionary_values.htm") data=BeautifulSoup(page.content) csv1=open("123.csv","wb+"...
0
2016-09-15T16:51:33Z
[ "python", "csv", "url", "beautifulsoup" ]
Regexp: some questions
39,512,633
<p><strong>Python 3</strong></p> <pre><code>text = "(CNN)Meaalofa Te'o -- Buemi. Canberra," def discard_punctuation(text): regex = '\W*^\s^\d*-' return re.sub(regex, "", text) def handle_text(text): text_without_punctuation = discard_punctuation(text) words_array = text_without_punctuation.split() ...
0
2016-09-15T13:41:43Z
39,513,184
<p>With your rather vague definition of a "word", you could come up with:</p> <pre><code>import re rx = re.compile(r'\s*(\S+)\s*') string = """(CNN)Meaalofa Te'o -- Buemi. Canberra,""" words = rx.findall(string) print(words) # ['(CNN)Meaalofa', "Te'o", '--', 'Buemi.', 'Canberra,'] </code></pre> <p>See <a href="http...
1
2016-09-15T14:05:04Z
[ "python", "regex", "python-3.x" ]
many2many fileds are both are same values?
39,512,749
<p>I have this code:</p> <p>In .py file:</p> <pre><code>class newsaleorderline(models.Model): _inherit='sale.order.line' supply_tax_id = fields.Many2many('account.tax',string='Supply Taxes',domain=['|', ('active', '=', False), ('active', '=', True)]) labour_tax_id = fields.Many2many('account.tax...
2
2016-09-15T13:46:53Z
39,515,895
<p>Odoo is generating relational tables in your database. You can give table names by yourself on field definition:</p> <pre class="lang-py prettyprint-override"><code>class MyModel(models.Model): _name = "my.model" my_m2m_field = fields.Many2Many( comodel_name="another.model", # required rela...
3
2016-09-15T16:18:24Z
[ "python", "postgresql", "openerp" ]
Enums with pointers in struct definitions
39,512,841
<p>I am working on creating access to a dynamic library in python using the ctypes module. While duplicating some of the tydef'd structures in my python implementation I came across a bit of code that has me stumped as to what is happening. Basically what I have is</p> <pre><code>enum foo { a, b, c, }; ...
1
2016-09-15T13:51:01Z
39,512,925
<p>Those aren't "enum calls", those are declaring two members in the structure, members that are pointers to functions.</p> <p>For example</p> <pre><code>enum foo (*lem)(); </code></pre> <p>declares a structure member variable <code>lem</code> that is a pointer to a function taking an indeterminate number of argumen...
3
2016-09-15T13:54:25Z
[ "python", "c", "pointers", "enums", "ctypes" ]
sorting by dictionary value in array python
39,512,942
<p>Okay so I've been working on processing some annotated text output. What I have so far is a dictionary with annotation as key and relations an array of elements:</p> <pre><code>'Adenotonsillectomy': ['0', '18', '1869', '1716'], 'OSAS': ['57', '61'], 'apnea': ['41', '46'], 'can': ['94', '97', '1796', '1746'], '...
1
2016-09-15T13:55:12Z
39,512,969
<p>The entries are sorted in alphabetical order. If you want to sort them on integer value, convert the value to int first:</p> <pre><code>sorted(dependency_dict.items(), key=lambda x: int(x[1][0])) </code></pre>
5
2016-09-15T13:56:34Z
[ "python", "arrays", "sorting", "dictionary" ]
How to return array list as a python object?
39,513,084
<p>I have a method which sends message to facebook in <a href="https://developers.facebook.com/docs/messenger-platform/send-api-reference/generic-template" rel="nofollow">Generic template</a> . My code:</p> <pre><code>def send_receipt(self, fbid, title, url, img_url, summary): return self._send(message={ "...
0
2016-09-15T14:01:06Z
39,514,471
<p>What I do is making a method which converts the result to a list elements</p> <pre><code>temp = [] for index, product in enumerate(products): element = {'title': title, 'subtitle': sumary, 'item_url': item_url} #not every product has image_url so to prevent KeyError, I have a i...
0
2016-09-15T15:05:45Z
[ "python", "arrays", "json", "list" ]
percentage completion of a long-running python task
39,513,085
<p>I have a python program that crunches a large dataset using Pandas. It currently takes about 15 minute to complete. I want to log (stdout &amp; send the metric to Datadog) about the progress of the task. Is there a way to get the %-complete of the task (or a function)? In the future, I might be dealing with larger d...
0
2016-09-15T14:01:07Z
39,513,221
<p>You can modify the following according to your needs.</p> <pre><code>from time import sleep for i in range(12): sleep(1) print("\r\t&gt; Progress\t:{:.2%}".format((i + 1)/12), end='') </code></pre> <p>What this basically does, is that it prevents <code>print()</code> from writing the default end character...
0
2016-09-15T14:06:29Z
[ "python" ]
percentage completion of a long-running python task
39,513,085
<p>I have a python program that crunches a large dataset using Pandas. It currently takes about 15 minute to complete. I want to log (stdout &amp; send the metric to Datadog) about the progress of the task. Is there a way to get the %-complete of the task (or a function)? In the future, I might be dealing with larger d...
0
2016-09-15T14:01:07Z
39,513,348
<p>the naive solution would be to just use the total amount of rows in your dataset and the index your are at, then calculate the progress:</p> <pre><code>size = len(dataset) for index, element in enumerate(dataset): print(index / size * 100) </code></pre> <p>This will only be somewhat reliable if every row takes...
0
2016-09-15T14:12:09Z
[ "python" ]
Python operator overloading with multiple operands
39,513,191
<p>I know I can do simple operator overloading in python by the following way.</p> <p>Let say overloading '+' operator.</p> <pre><code>class A(object): def __init__(self,value): self.value = value def __add__(self,other): return self.value + other.value a1 = A(10) a2 = A(20) print a1 + a2 </code></pre> ...
1
2016-09-15T14:05:25Z
39,513,296
<p>This is failing because <code>a1 + a2</code> return an <code>int</code> instance and its <code>__add__</code> is called which doesn't support addition with the custom class <code>A</code>; you could return a <code>A</code> instance in <code>__add__</code> to eliminate the Exception for this specific operation:</p> ...
2
2016-09-15T14:10:04Z
[ "python", "python-2.7", "python-3.x", "python-2.x" ]
Python operator overloading with multiple operands
39,513,191
<p>I know I can do simple operator overloading in python by the following way.</p> <p>Let say overloading '+' operator.</p> <pre><code>class A(object): def __init__(self,value): self.value = value def __add__(self,other): return self.value + other.value a1 = A(10) a2 = A(20) print a1 + a2 </code></pre> ...
1
2016-09-15T14:05:25Z
39,513,302
<p>The problem is that</p> <p><code>a1 + a2 + a3</code> gives <code>30 + a3</code></p> <p>30 is an int, and ints do not know how to sum to A</p> <p>You should return an instance of A in your <code>__add__</code> function</p>
0
2016-09-15T14:10:21Z
[ "python", "python-2.7", "python-3.x", "python-2.x" ]
Getting invalid syntax
39,513,232
<p>Im getting this error bellow when I run my python script.</p> <pre><code> File "supreme.py", line 24 print UTCtoEST(),':: Parsing page...' ^ SyntaxError: invalid syntax </code></pre> <p>Preview of the part of the script:</p> <pre><code>import sys, json, time, requests, urllib2 from dat...
-3
2016-09-15T14:06:43Z
39,513,766
<p>Seems like your issue here is not the code, but the version of Python you are running it with. Your code is written in Python 2.7, but you are running with Python 3.5.</p> <p>Option one, run with Python 2.7.</p> <p>Option two, change the code...</p> <pre><code># imports ^ qty='1' def UTCtoEST(): current=dat...
1
2016-09-15T14:31:45Z
[ "python", "python-3.x" ]
Appending a list into a list of lists in python
39,513,256
<p>I am trying to create and append a list and index in a list. Appending any list element is being automatically appended to all the lists available in this list First of all I have a list as following</p> <pre><code>sygma_list [[]] * 3 </code></pre> <p>and I have another lists having the form</p> <pre><code>mts_co...
0
2016-09-15T14:08:09Z
39,513,304
<p>The biggest catch in your code is this: When you do this:</p> <pre><code>sygma_list = [[]] * 3 </code></pre> <p>you create a size-3 array of references on the same list: not that you generally want and certainly not here</p> <p>Do this instead:</p> <pre><code>sygma_list = [list() for x in range(3)] </code></pre>...
3
2016-09-15T14:10:27Z
[ "python", "list", "append" ]
Appending a list into a list of lists in python
39,513,256
<p>I am trying to create and append a list and index in a list. Appending any list element is being automatically appended to all the lists available in this list First of all I have a list as following</p> <pre><code>sygma_list [[]] * 3 </code></pre> <p>and I have another lists having the form</p> <pre><code>mts_co...
0
2016-09-15T14:08:09Z
39,519,792
<p>If all the <code>mts_columns</code> lists contain the same sublists as in your post then you could use a list comprehension like so:</p> <pre><code>sygma_list = [ [i]*2 for i in mts_columns] </code></pre> <p>in this case <code>sygma_list</code> doesn't have to be initialized as in your post (or you could simply do...
0
2016-09-15T20:26:58Z
[ "python", "list", "append" ]
My if statement keeps returning 'None' for empty list
39,513,310
<p>I'm a beginner at coding in Python and I've been practising with exercises CodeWars.</p> <p>There's this exercise which basically wants you to recreate the display function of the "likes" on Facebook, i.e. how it shows the number likes you have on a post etc.</p> <p>Here is my code:</p> <pre><code>def likes(names...
2
2016-09-15T14:10:49Z
39,513,375
<p>If <code>names</code> is an empty list the <code>for</code> loop won't be executed at all, which will cause the function to return <code>None</code>. You should change the structure of your function (hint: you might not even need a loop, not an explicit one at least). There is no point in having a loop and then <cod...
7
2016-09-15T14:13:06Z
[ "python", "list", "function", "if-statement" ]
My if statement keeps returning 'None' for empty list
39,513,310
<p>I'm a beginner at coding in Python and I've been practising with exercises CodeWars.</p> <p>There's this exercise which basically wants you to recreate the display function of the "likes" on Facebook, i.e. how it shows the number likes you have on a post etc.</p> <p>Here is my code:</p> <pre><code>def likes(names...
2
2016-09-15T14:10:49Z
39,513,453
<p>The for loop that you have done occurs one time for each element of the list, but you do non have elements in the list, so the loop won't occour, and the return value will be "None"</p> <pre><code>def likes(names): #for name in names: #LOOK HERE: you definetly not need this loop if len(names) == 0: ...
4
2016-09-15T14:17:15Z
[ "python", "list", "function", "if-statement" ]
Python DataFrame Transform Rows to Column
39,513,332
<p>I have a csv that stores information about a particular object and Date. </p> <pre><code>Device Date Category Amount Pen 01/01/2014 A 12 Pen 01/01/2014 B 42 Pen 01/01/2014 C 10 Pen 01/01/2014 D 5 Pen 02/01/2014 A 7 Pen 02/01/2...
1
2016-09-15T14:11:39Z
39,513,425
<p>You can use <code>pivot_table</code> where columns that you want to keep are set as <code>index</code>, columns that go to the header are set as <code>columns</code> and columns that fill the cells in the output data frame are set as <code>values</code>:</p> <pre><code>df.pivot_table(index=['Device', 'Date'], colum...
5
2016-09-15T14:15:49Z
[ "python", "pandas", "dataframe" ]
Python DataFrame Transform Rows to Column
39,513,332
<p>I have a csv that stores information about a particular object and Date. </p> <pre><code>Device Date Category Amount Pen 01/01/2014 A 12 Pen 01/01/2014 B 42 Pen 01/01/2014 C 10 Pen 01/01/2014 D 5 Pen 02/01/2014 A 7 Pen 02/01/2...
1
2016-09-15T14:11:39Z
39,514,169
<p>using <code>groupby</code> and <code>unstack</code></p> <pre><code>df.groupby(['Device', 'Date', 'Category'])['Amount'].sum().unstack().reset_index() </code></pre> <p><a href="http://i.stack.imgur.com/ZOOY6.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZOOY6.png" alt="enter image description here"></a></p...
2
2016-09-15T14:50:41Z
[ "python", "pandas", "dataframe" ]
Given an arc with a known start(x, y), end(x, y) and angle, how can I calculate its bounding box?
39,513,353
<p>The title says it all. Given an arc with (for example):</p> <pre><code>Start Point: x = 53.34, y = 52.07 End Point: x = 13.97, y = 52.07 Angle: 180 degrees </code></pre> <p><a href="http://i.stack.imgur.com/xxQ0i.png" rel="nofollow"><img src="http://i.stack.imgur.com/xxQ0i.png" alt="enter image description here"><...
0
2016-09-15T14:12:24Z
39,513,824
<pre><code>h = Sqrt( (start.x - end.x)^2 + (start.y - end.y)^2) or h = Math.Hypot(start.x - end.x, start.y - end.y) R = Abs(h / (2*Sin(Angle/2))) if angle &lt;= Pi/2 top = end.y left = end.x bottom = start.y right = start.x else if angle &lt;= Pi top = start.y - R left = end.x bottom = st...
1
2016-09-15T14:34:07Z
[ "python", "math", "geometry", "bounding-box" ]
RedisClusterException when trying to write using Celery
39,513,405
<p><strong>My environment:</strong> I have three Ubuntu servers. One server is used as a load balancer using Nginx. The other two servers contain the exact same project (are identical apart from redis where one box is the master and other is the slave).</p> <p><strong>The Programs/Applications I'm using</strong> Pytho...
0
2016-09-15T14:14:30Z
39,548,072
<p>You are not running a redis cluster, so attempting to run redis-cluster only commands are going to fail. </p>
0
2016-09-17T14:43:50Z
[ "python", "django", "sockets", "redis", "redis-cluster" ]
Python: How to restart a FOR loop, which iterates over a csv
39,513,569
<p>I am using Python 3.5 and I wanna load data from a csv into several lists, but it only works exactly one time with a FOR-Loop. Then it loads 0 into it.</p> <p>Here is the code:</p> <pre><code>f1 = open("csvfile.csv", encoding="latin-1") csv_f1 = csv.reader(f1, delimiter=';') list_f1_vorname = [] for row_f1 in csv...
2
2016-09-15T14:22:19Z
39,513,620
<p>Try:</p> <pre><code>csv_f1 = list(csv.reader(f1, delimiter=';')) </code></pre> <p>It is not exactly restarting the reader, but rather caching the file contents in a list, which may be iterated many times.</p>
0
2016-09-15T14:24:47Z
[ "python", "loops", "csv", "for-loop", "restart" ]
Python: How to restart a FOR loop, which iterates over a csv
39,513,569
<p>I am using Python 3.5 and I wanna load data from a csv into several lists, but it only works exactly one time with a FOR-Loop. Then it loads 0 into it.</p> <p>Here is the code:</p> <pre><code>f1 = open("csvfile.csv", encoding="latin-1") csv_f1 = csv.reader(f1, delimiter=';') list_f1_vorname = [] for row_f1 in csv...
2
2016-09-15T14:22:19Z
39,513,657
<p><code>csv_f1</code> is not an <code>list</code>, it is an iterative.</p> <p>Either, you cache the <code>csv_f1</code> into a list by using <code>list()</code> or you just recreate the object.</p> <p>I would recommend to recreate the object in case your cvs data gets very big. This way, the data is not put into RAM...
3
2016-09-15T14:26:28Z
[ "python", "loops", "csv", "for-loop", "restart" ]
Python: How to restart a FOR loop, which iterates over a csv
39,513,569
<p>I am using Python 3.5 and I wanna load data from a csv into several lists, but it only works exactly one time with a FOR-Loop. Then it loads 0 into it.</p> <p>Here is the code:</p> <pre><code>f1 = open("csvfile.csv", encoding="latin-1") csv_f1 = csv.reader(f1, delimiter=';') list_f1_vorname = [] for row_f1 in csv...
2
2016-09-15T14:22:19Z
39,513,935
<p>The simple answer is to iterate over the csv once and store it into a list. something like</p> <pre><code>my_list = [] for row in csv_f1: my_list.append(row) </code></pre> <p>or what abukaj wrote with</p> <pre><code>csv_f1 = list(csv.reader(f1, delimiter=';')) </code></pre> <p>and then move on and iterate ov...
1
2016-09-15T14:38:58Z
[ "python", "loops", "csv", "for-loop", "restart" ]
Python: How to restart a FOR loop, which iterates over a csv
39,513,569
<p>I am using Python 3.5 and I wanna load data from a csv into several lists, but it only works exactly one time with a FOR-Loop. Then it loads 0 into it.</p> <p>Here is the code:</p> <pre><code>f1 = open("csvfile.csv", encoding="latin-1") csv_f1 = csv.reader(f1, delimiter=';') list_f1_vorname = [] for row_f1 in csv...
2
2016-09-15T14:22:19Z
39,515,167
<p>One thing nobody noticed so far is that you're trying to store names and last names in two separate lists. This is not going to be very convenient to use later on. Therefore despite other answers show correct possible solutions to read names and last names from csv into two separate lists, I'm going to propose you t...
0
2016-09-15T15:39:50Z
[ "python", "loops", "csv", "for-loop", "restart" ]
Django Count of Items in a Field
39,513,627
<p>models.py</p> <pre><code>class Event(models.Model): name = models.CharField(max_length=20, unique=True) distance = models.IntegerField() date = models.DateField() class Category(models.Model): name = models.CharField(max_length=20, unique=True) description = models.CharField(max_length=20, uniq...
3
2016-09-15T14:24:58Z
39,514,173
<p>Use <a href="https://docs.djangoproject.com/en/1.10/topics/db/aggregation/" rel="nofollow"><code>annotate</code></a>:</p> <pre><code>from django.db.models import Count Results.objects.filter(event=some_event).annotate(Count('category'), distinct=True) </code></pre>
0
2016-09-15T14:51:00Z
[ "python", "django", "django-models" ]
Django Count of Items in a Field
39,513,627
<p>models.py</p> <pre><code>class Event(models.Model): name = models.CharField(max_length=20, unique=True) distance = models.IntegerField() date = models.DateField() class Category(models.Model): name = models.CharField(max_length=20, unique=True) description = models.CharField(max_length=20, uniq...
3
2016-09-15T14:24:58Z
39,514,186
<p>You can use <code>annotate()</code> with <code>values()</code>. This approach is shown in the docs for <a href="https://docs.djangoproject.com/en/1.10/topics/db/aggregation/#values" rel="nofollow"><code>values()</code></a>. To get the count for each category name, you could do:</p> <pre><code>from django.db.models ...
4
2016-09-15T14:51:49Z
[ "python", "django", "django-models" ]
Django Count of Items in a Field
39,513,627
<p>models.py</p> <pre><code>class Event(models.Model): name = models.CharField(max_length=20, unique=True) distance = models.IntegerField() date = models.DateField() class Category(models.Model): name = models.CharField(max_length=20, unique=True) description = models.CharField(max_length=20, uniq...
3
2016-09-15T14:24:58Z
39,514,304
<p>There is <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow">collections.Counter</a> in python standard library:</p> <pre><code>results = Result.objects.filter(event=myevent).select_related('category') c = Counter(r.category for r in results) </code></pre> <p>Now c is a ...
0
2016-09-15T14:57:50Z
[ "python", "django", "django-models" ]
from pytrends.pyGTrends import pyGTrendsnot working
39,514,109
<p>I installed pytrends using this wheel file <a href="https://pypi.python.org/packages/b5/b9/1942e2b6cfa643212d5d856793ae9584d635be2f536e94983fb74496ab5b/pytrends-3.1.0-py2.py3-none-any.whl" rel="nofollow">pytrends.whl</a> and the below directories</p> <pre><code> Directory of C:\Python35\Lib\site-packages\pytrends ...
0
2016-09-15T14:47:51Z
39,621,481
<p>You should probably use <code>from pytrends.request import TrendReq</code>.</p> <p>See <a href="https://github.com/GeneralMills/pytrends/blob/master/examples/example.py" rel="nofollow">example.py</a>.</p>
2
2016-09-21T16:04:53Z
[ "python", "google-trends" ]
Counting how many times in a row the result of a sum is positive (or negative)
39,514,202
<p><strong>First Part</strong></p> <blockquote> <p>I have a dataframe with finance data (33023 rows, here the link to the data: <a href="https://mab.to/Ssy3TelRs" rel="nofollow">https://mab.to/Ssy3TelRs</a>); df.open is the price of the title and df.close is the closing price.</p> <p>I have been trying to s...
2
2016-09-15T14:52:39Z
39,514,416
<p>It sounds like what you want to do is: </p> <ul> <li>compute the difference of two series (open &amp; close), eg <code>diff = df.open - df.close</code></li> <li>apply a condition to the result to get a boolean series <code>diff &gt; 0</code></li> <li>pass the resulting boolean series to the DataFrame to get a subse...
2
2016-09-15T15:03:27Z
[ "python", "pandas", "dataframe" ]
Counting how many times in a row the result of a sum is positive (or negative)
39,514,202
<p><strong>First Part</strong></p> <blockquote> <p>I have a dataframe with finance data (33023 rows, here the link to the data: <a href="https://mab.to/Ssy3TelRs" rel="nofollow">https://mab.to/Ssy3TelRs</a>); df.open is the price of the title and df.close is the closing price.</p> <p>I have been trying to s...
2
2016-09-15T14:52:39Z
39,514,805
<p>If I understood you correctly, you want the number of days that have at least <code>n</code> positive days in a row before and itself included.</p> <p>Similarly to what @Thang suggested, you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolling.html" rel="nofollow">rolling<...
2
2016-09-15T15:21:36Z
[ "python", "pandas", "dataframe" ]
Counting how many times in a row the result of a sum is positive (or negative)
39,514,202
<p><strong>First Part</strong></p> <blockquote> <p>I have a dataframe with finance data (33023 rows, here the link to the data: <a href="https://mab.to/Ssy3TelRs" rel="nofollow">https://mab.to/Ssy3TelRs</a>); df.open is the price of the title and df.close is the closing price.</p> <p>I have been trying to s...
2
2016-09-15T14:52:39Z
39,515,000
<p>This should work:</p> <pre><code>import pandas as pd import numpy as np test = pd.DataFrame(np.random.randn(100,2), columns = ['open','close']) test['gain?'] = (test['open']-test['close'] &lt; 0) test['cumulative'] = 0 for i in test.index[1:]: if test['gain?'][i]: test['cumulative'][i] = test['cumulat...
0
2016-09-15T15:31:18Z
[ "python", "pandas", "dataframe" ]
Counting how many times in a row the result of a sum is positive (or negative)
39,514,202
<p><strong>First Part</strong></p> <blockquote> <p>I have a dataframe with finance data (33023 rows, here the link to the data: <a href="https://mab.to/Ssy3TelRs" rel="nofollow">https://mab.to/Ssy3TelRs</a>); df.open is the price of the title and df.close is the closing price.</p> <p>I have been trying to s...
2
2016-09-15T14:52:39Z
39,516,000
<p>If i understood your question correctly you can do it this way:</p> <pre><code>In [76]: df.groupby((df.close.diff() &lt; 0).cumsum()).cumcount() Out[76]: 0 0 1 1 2 2 3 0 4 1 5 2 6 0 7 0 dtype: int64 </code></pre> <blockquote> <p>The result that I'm looking for should tell me that the titl...
1
2016-09-15T16:25:09Z
[ "python", "pandas", "dataframe" ]
Execute python script via Arduino Uno in windows
39,514,309
<p>I am wondering is there any way to run python script via Arduino commands in Windows ?</p>
1
2016-09-15T14:58:09Z
39,515,223
<p>I believe that there won't be any Arduino library that support Python because python is interpreted and the Arduino doesn't have the memory for the entire of Python, if you're looking to program an Arduino using Python then maybe just try C the code you need to learn for programming the Arduino isn't too different t...
0
2016-09-15T15:42:55Z
[ "python", "arduino-uno" ]
Execute python script via Arduino Uno in windows
39,514,309
<p>I am wondering is there any way to run python script via Arduino commands in Windows ?</p>
1
2016-09-15T14:58:09Z
39,521,928
<p>I don't know if this answers your question, but you can download Vpython library to create some cool projects with it, or connect sensors and getting data back into python from arduino or viceversa</p> <p>So for example:</p> <pre><code>int trigPin=13; //Sensor Trig pin connected to Arduino pin 13 int echoPin=11; ...
0
2016-09-15T23:48:35Z
[ "python", "arduino-uno" ]
Nginx - serve flask python on https and another port without https
39,514,407
<p>What I'm trying to accomplish. Have a domain on https. Check. it's working ok using the following config. The flask app runs on port 1337 -> nginx takes it -> serves it though https. Everything is working nicely</p> <p>Now I want to run another app, on port 1338 let's say. But if I do this, the browser (chrome) aut...
0
2016-09-15T15:03:02Z
39,517,216
<p>The answer to your question depends on what exactly you want the user experience to be.</p> <p>As I understand your goal, you only have one domain (example.com). Your first app, (I'm going to call it <code>app1337</code>) is running on port 1337 and you can access in a browser at <a href="https://example.com/" rel=...
2
2016-09-15T17:41:01Z
[ "python", "nginx", "flask" ]
How do you output a list out without quotes around strings?
39,514,657
<p>I'm trying to set up a block to accept only inputs that are in a list but first it asks for the inputs in the input function but I can't seem to get rid of the quotes around the strings in the list. Here is some example code:</p> <pre><code>def Sinput(acceptable): while True: acceptable = [str(i) for i ...
0
2016-09-15T15:14:26Z
39,514,729
<p>Use <a href="https://docs.python.org/2/library/stdtypes.html#str.join" rel="nofollow"><code>.join(...)</code></a> which is the recommended way for joining an iterable of strings:</p> <pre><code>a = input('Enter'+ ' ,'.join(acceptable[:-1]) + ...) # ^^^^^^^^^ </code></pre> <p>P.S. I don't see why y...
2
2016-09-15T15:17:49Z
[ "python", "python-3.x" ]
How do you output a list out without quotes around strings?
39,514,657
<p>I'm trying to set up a block to accept only inputs that are in a list but first it asks for the inputs in the input function but I can't seem to get rid of the quotes around the strings in the list. Here is some example code:</p> <pre><code>def Sinput(acceptable): while True: acceptable = [str(i) for i ...
0
2016-09-15T15:14:26Z
39,515,206
<p>I think this would do good for you:</p> <pre><code> a = input('Enter {} or {}'.format(' ,'.join(acceptable[:-1]), acceptable[-1])) </code></pre>
2
2016-09-15T15:41:50Z
[ "python", "python-3.x" ]
How to retrieve subset in partitioning algorithm?
39,514,839
<p>I have an array and I would like to split it two parts such that their sum is equal for example <code>[10, 30, 20, 50]</code> can be split into <code>[10, 40] , [20, 30]</code>. Both have a sum of 50. This is essentially partitioning algorithm but I'd like the retrieve the subsets not just identify whether it's part...
4
2016-09-15T15:23:33Z
39,515,717
<p>Though it is still a hard problem, you could try the following. I assume that there are <code>n</code> elements and they are stored in the array named <code>arr</code> ( I assume 1-based indexing ). Let us make two teams <code>A</code> and <code>B</code>, such that I want to partition the elements of <code>arr</code...
3
2016-09-15T16:08:30Z
[ "python", "algorithm", "performance", "python-3.x", "partitioning" ]
How to retrieve subset in partitioning algorithm?
39,514,839
<p>I have an array and I would like to split it two parts such that their sum is equal for example <code>[10, 30, 20, 50]</code> can be split into <code>[10, 40] , [20, 30]</code>. Both have a sum of 50. This is essentially partitioning algorithm but I'd like the retrieve the subsets not just identify whether it's part...
4
2016-09-15T15:23:33Z
39,516,239
<p>This is my implementation of @sasha's algo on the feasibility.</p> <pre><code>def my_part(my_list): item = my_list.pop() balance = [] temp = [item, -item] while len(my_list) != 0: new_player = my_list.pop() for i, items in enumerate(temp): balance.append(items + new_playe...
0
2016-09-15T16:39:05Z
[ "python", "algorithm", "performance", "python-3.x", "partitioning" ]
ImportError: No module named durationfield.db.models.fields.duration (Python, Django 1.9)
39,514,880
<p>I'm trying to put a duration field in my models and I'm following the instructions <a href="https://django-durationfield.readthedocs.io/en/latest/" rel="nofollow">here</a>. First problems I run into is that I can't seem to import the module. Doesn't this come standard with Django?</p> <pre><code> from duration...
-1
2016-09-15T15:25:30Z
39,514,916
<p>You should be importing from django.db.models....</p>
0
2016-09-15T15:27:26Z
[ "python", "django", "import", "models", "duration" ]
ImportError: No module named durationfield.db.models.fields.duration (Python, Django 1.9)
39,514,880
<p>I'm trying to put a duration field in my models and I'm following the instructions <a href="https://django-durationfield.readthedocs.io/en/latest/" rel="nofollow">here</a>. First problems I run into is that I can't seem to import the module. Doesn't this come standard with Django?</p> <pre><code> from duration...
-1
2016-09-15T15:25:30Z
39,515,057
<p>It's here:</p> <pre><code>from django.db.models import DurationField </code></pre> <p>And yes, it comes with Django 1.8+ so you don't need to install it. </p>
1
2016-09-15T15:34:00Z
[ "python", "django", "import", "models", "duration" ]
Pandas - Expand DataFrame by fetching data using one column
39,515,043
<p>I start with a DataFrame configuration</p> <pre><code>import pandas as pd getData = lambda n: pd.util.testing.makeTimeDataFrame(n) origDF = pd.DataFrame([{'weight':70, 'name':'GOLD', 'n':3}, {'weight':30, 'name':'SILVER', 'n':4}]) n name weight 0 3 GOLD 70 1 4 SILVER 30 </code></pre> <p>N...
1
2016-09-15T15:33:27Z
39,516,715
<p>here is a solution, which loops ones through your <code>origDF</code>:</p> <pre><code>In [167]: res = getData(origDF.n.sum()) In [168]: res['name'] = 'N/A' In [169]: res['weight'] = 0 In [170]: res Out[170]: A B C D name weight 2000-01-03 1.097798 -1.537407 0.692180 ...
0
2016-09-15T17:08:21Z
[ "python", "pandas", "dataframe" ]
Set a current row in a dataframe based off of future values
39,515,086
<p>Given:</p> <pre class="lang-py prettyprint-override"><code> d = { 'datetime': ['2010-01-08 09:45:00', '2010-01-08 10:00:00', '2010-01-08 10:15:00', '2010-01-08 10:30:00', '2010-01-08 10:45:00', '2010-01-08 11:00:00', '2010-01-08 11:15:00', '2010-01-08 11:30:00', ...
0
2016-09-15T15:35:23Z
39,515,387
<p>You can use the ungainly expression</p> <pre><code>In [56]: import numpy as np In [57]: ((np.cumsum((df['Total-tops'] == -1)[:: -1])[:: -1] &gt; 0) &amp; (df['Total-tops'] &gt; 0)).astype(int) Out[57]: datetime 2010-01-08 09:45:00 0 2010-01-08 10:00:00 0 2010-01-08 10:15:00 0 2010-01-08 10:30:00 1 201...
0
2016-09-15T15:51:19Z
[ "python", "pandas" ]
Set a current row in a dataframe based off of future values
39,515,086
<p>Given:</p> <pre class="lang-py prettyprint-override"><code> d = { 'datetime': ['2010-01-08 09:45:00', '2010-01-08 10:00:00', '2010-01-08 10:15:00', '2010-01-08 10:30:00', '2010-01-08 10:45:00', '2010-01-08 11:00:00', '2010-01-08 11:15:00', '2010-01-08 11:30:00', ...
0
2016-09-15T15:35:23Z
39,518,063
<p>You could select all rows until the last index where -1 occurs and assign values to a new column, <em>breaks</em> where <em>Total-tops</em> values are greater than 1 using <code>loc</code>.</p> <p>Then, cast the bool types to integers followed by filling values which come after these indices with 0's as shown:</p> ...
0
2016-09-15T18:31:57Z
[ "python", "pandas" ]
urllib.error.HTTPError: HTTP Error 403: Forbidden Python
39,515,096
<p>My code: </p> <pre><code>import sqlite3, os, urllib.request from xml.dom import minidom if os.path.exists("data.db"): con = sqlite3.connect("data.db") cursor = con.cursor() sql = "SELECT * FROM data WHERE test= '123'" cursor.execute(sql) else: print("ERROR") for dsatz in cursor: #print(dsatz) lin...
-1
2016-09-15T15:36:05Z
39,515,701
<p>The web server is telling you that link is forbidden. There's (probably) nothing wrong with your code.</p> <p>Do some links always work and other links always fail, or does the pattern change over time?</p> <p>After getting a 403 Forbidden response, have you tried going back and re-requesting one of the earlier s...
0
2016-09-15T16:07:51Z
[ "python", "xml", "parsing" ]
Pandas, Concurrent.Futures and the GIL
39,515,123
<p>I'm writing code using Pandas 0.18/Python 3.5 on an intel i3 (four cores).</p> <p>I have read this: <a href="https://www.continuum.io/content/pandas-releasing-gil" rel="nofollow">https://www.continuum.io/content/pandas-releasing-gil</a></p> <p>I also have some work that is IO bound (parsing CSV files into datafram...
1
2016-09-15T15:37:28Z
39,515,335
<p>Best I can tell from reading the docs, pandas <a href="http://pandas-docs.github.io/pandas-docs-travis/whatsnew.html#releasing-the-gil" rel="nofollow">simply releases the GIL for certain operations</a>:</p> <blockquote> <p>We are releasing the global-interpreter-lock (GIL) on some cython operations. This will a...
1
2016-09-15T15:48:44Z
[ "python", "multithreading", "pandas", "python-multithreading" ]
Python, Pandas - How can I get something printed in a data range?
39,515,152
<p>I suppose to create a function that allows user pick a range and it will print out the number within the range. however, I keep getting empty DataFrame with my code. can anyone help me? </p> <p>` import pandas as pd</p> <pre><code>if __name__ == "__main__": file_name = "sales_rossetti.xlsx" # Formatting ...
0
2016-09-15T15:39:13Z
39,515,373
<p>You're overwriting the <code>your_sales</code> variable as you're reusing it, so you should use a different variable name for the min and max params. You then need to generate a proper boolean mask using <code>loc</code> and enclosing your boolean conditions using parentheses and <code>&amp;</code> to <code>and</cod...
0
2016-09-15T15:50:43Z
[ "python", "pandas", "dataframe" ]
Convert from decimal to Binary function
39,515,184
<p>I tried creating a function to convert to binary the long way but i keep getting a very basic error that i can't seem to figure out. Would appreciate an extra pair of eyes.</p> <pre><code>def convert_to_binary(n): if (-1.0 &lt; n &lt; 256.0): number_list = [] while (n != 0): rem = n...
0
2016-09-15T15:40:36Z
39,515,410
<pre><code>def convert_to_binary(n): if (-1.0 &lt; n &lt; 256.0): print '{0:b}'.format(n) else: print("Invalid input") </code></pre>
0
2016-09-15T15:52:08Z
[ "python" ]
Get file from Folder in Python
39,515,199
<p>The issue has been reported <a href="https://github.com/fchollet/keras/issues/2369" rel="nofollow">here</a> too.</p> <p>I have code like:</p> <pre><code>from keras.datasets.data_utils import get_file path = get_file('babi-tasks-v1-2.tar.gz', origin='http://www.thespermwhale.com/jaseweston/babi/tasks_1-20_v1-2.tar...
1
2016-09-15T15:41:27Z
39,515,306
<p>Your function <em>get_file</em> seems to take an <strong>url address as a argument</strong> and not an absolute path.</p> <p>Could you give us more details about this function ?</p>
1
2016-09-15T15:47:28Z
[ "python", "url", "error-handling", "anaconda" ]
Get file from Folder in Python
39,515,199
<p>The issue has been reported <a href="https://github.com/fchollet/keras/issues/2369" rel="nofollow">here</a> too.</p> <p>I have code like:</p> <pre><code>from keras.datasets.data_utils import get_file path = get_file('babi-tasks-v1-2.tar.gz', origin='http://www.thespermwhale.com/jaseweston/babi/tasks_1-20_v1-2.tar...
1
2016-09-15T15:41:27Z
39,515,504
<p>The error message suggests that your library requires a resource type at the beginning of the URL. Try specifying your path like this:</p> <pre class="lang-none prettyprint-override"><code>file:/home/xxxxxx/Downloads/tasks_1-20_v1-2.tar.gz </code></pre>
1
2016-09-15T15:55:58Z
[ "python", "url", "error-handling", "anaconda" ]
Python CSV: How to ignore writing similar rows given one row meets a condition?
39,515,291
<p>I'm currently keeping track of the large scale digitization of video tapes and need help pulling data from multiple CSVs. Most tapes have multiple copies, but we only digitize one tape from the set. I would like to create a new CSV containing only tapes of shows that have yet to be digitized. Here's a mockup of my o...
1
2016-09-15T15:46:54Z
39,535,979
<p>The simplest approach is to make two reads of the set of CSV files: one to build a list of all digitized tapes, the second to build a unique list of all tapes not on the digitized list:</p> <pre><code># build list of digitized tapes digitized = [] for name in names: with open("%s_.csv" % name, "rb") as source: ...
0
2016-09-16T16:13:54Z
[ "python", "csv" ]
Python CSV: How to ignore writing similar rows given one row meets a condition?
39,515,291
<p>I'm currently keeping track of the large scale digitization of video tapes and need help pulling data from multiple CSVs. Most tapes have multiple copies, but we only digitize one tape from the set. I would like to create a new CSV containing only tapes of shows that have yet to be digitized. Here's a mockup of my o...
1
2016-09-15T15:46:54Z
39,536,891
<p>I am not a hundred percent sure I've understood your needs. However, this might put you on a right track. I am using <a href="http://pandas.pydata.org/pandas-docs/stable/index.html" rel="nofollow"><code>pandas</code></a> module:</p> <pre><code>data = """ Date Digitized | Series | Episode Number | Title | Format -...
1
2016-09-16T17:13:59Z
[ "python", "csv" ]
Django Model reference assignment in loop
39,515,354
<p>Is the following code correct? The <code>e</code> should refer to a new object in the beginning of each for iteration, after try/except blocks are executed. I suspect some interference with an old object, because there is a bug which I cannot reproduce now.</p> <pre><code> from webapp.models import Profile .... ...
0
2016-09-15T15:49:44Z
39,515,825
<p>If you want all the try/catch blocks to run within the for loop you need make sure your identation is correct</p> <p>Try (check the indentation)</p> <pre><code>from webapp.models import Profile .... for e in Profile.objects.all(): if not e.profile_link in profile_data: e.delete() try: for ...
0
2016-09-15T16:13:53Z
[ "python", "django" ]
Can one form a view into diagonal of ndarray in numpy
39,515,391
<p>Simple slices form views into the parent array. The strides of the view is generically the multiple of the strides of the parent array. </p> <p>Given 2d parent array with strides <code>(s0, s1)</code>, the 1D array with strides <code>(s0+s1)</code> gives the view in the diagonal of the parent array. </p> <p>Is the...
1
2016-09-15T15:51:25Z
39,516,049
<p>With <code>as_strided</code> I can do what you want:</p> <pre><code>In [298]: X=np.eye(5) In [299]: X.strides Out[299]: (40, 8) In [300]: np.lib.stride_tricks.as_strided(X,shape=(5,),strides=(48,)) Out[300]: array([ 1., 1., 1., 1., 1.]) </code></pre> <p>though some would argue the <code>as_strided</code> is a ...
2
2016-09-15T16:28:10Z
[ "python", "numpy" ]
Can one form a view into diagonal of ndarray in numpy
39,515,391
<p>Simple slices form views into the parent array. The strides of the view is generically the multiple of the strides of the parent array. </p> <p>Given 2d parent array with strides <code>(s0, s1)</code>, the 1D array with strides <code>(s0+s1)</code> gives the view in the diagonal of the parent array. </p> <p>Is the...
1
2016-09-15T15:51:25Z
39,523,651
<p>If you are using numpy 1.9 or later, and a read-only view is sufficient, you can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.diagonal.html" rel="nofollow"><code>numpy.diagonal</code></a>. The docstring says that in some future version of numpy, <code>numpy.diagonal</code> will return a re...
2
2016-09-16T04:15:31Z
[ "python", "numpy" ]
Plotting two groupby() series in python
39,515,408
<p>I am new to python in general but I did do a lot of research to see if I can find a solution to this problem. Hope you guys can help.</p> <p>Say A is a dataframe with Cost and site fields. B is a similar dataframe with cost and site fields. I want to group by the Site field and plot A/B for each site as a bar graph...
0
2016-09-15T15:51:55Z
39,515,728
<p>You're nearly there!</p> <pre><code>import pylab as P t = P.bar(range(5),C,tick_label = C.index, align = 'center') </code></pre> <p>The first argument tells pylab there are 5 bars, the second gives the values from C, tick_label and alignment just name and align the bar labels.</p>
0
2016-09-15T16:09:07Z
[ "python", "dataframe" ]
How can admin post content visible by other users in django 1.8?
39,515,435
<p>First of all, I'm new to django, this is my first projet so I have minimum knowledge.</p> <p>I'm working with django 1.8 and I have made a basic website. My problem is the following: You know how when you visit a website and the content is updated by the admin ? (news, schedule or reminder of deadline if you're a ...
0
2016-09-15T15:53:25Z
39,519,937
<p>You can use the Django Admin to create/edit models through a web interface with zero programming.</p> <p>Of course, for this to work you'd have to keep your editable content in models instead of hardcoding them in your templates.</p> <p>Let's assume our site is a small blog and our posts are instances of the follo...
1
2016-09-15T20:35:37Z
[ "python", "django", "model-view-controller", "admin", "django-1.8" ]
What is the downside of using object.__new__ in __new__?
39,515,463
<p>Coding exception classes, I came across this error: </p> <p><code>TypeError: object.__new__(A) is not safe, use Exception.__new__()</code></p> <p>There's a similar question posted here: <a href="http://stackoverflow.com/questions/12952184/typeerror-object-new-int-is-not-safe-use-int-new">TypeError: object.__new__(...
3
2016-09-15T15:54:20Z
39,515,655
<p>Calling <code>object.__new__(A)</code> returns an instance of <code>A</code>, but does so without calling <code>Exception.__new__()</code> if it is defined.</p>
0
2016-09-15T16:04:59Z
[ "python" ]
What is the downside of using object.__new__ in __new__?
39,515,463
<p>Coding exception classes, I came across this error: </p> <p><code>TypeError: object.__new__(A) is not safe, use Exception.__new__()</code></p> <p>There's a similar question posted here: <a href="http://stackoverflow.com/questions/12952184/typeerror-object-new-int-is-not-safe-use-int-new">TypeError: object.__new__(...
3
2016-09-15T15:54:20Z
39,519,014
<p>There is no problem in calling <code>object.__new__</code>, but there is a problem in not calling <code>Exception.__new__</code>.</p> <p><code>Exception</code> class was designed in such way that it is crucial that its <code>__new__</code> must be called, so it complains if that is not done.</p> <p>There was a que...
1
2016-09-15T19:35:00Z
[ "python" ]
Autotesting application written on Qt with Python
39,515,498
<p>I want to test application written on Qt by Python. Workflow that I want: 1. Python script should run .exe 2. Python script should get/set info from/into active window.</p> <p>Is it possible to manipulate Qt window if I know "object name" (<a href="http://doc.qt.io/qt-5/qobject.html#objectName-prop" rel="nofollow">...
-1
2016-09-15T15:55:48Z
39,548,179
<p>You will need a method of communication between the Python test and the program.</p> <p>For example the program could read commands from STDIN or a socket when being started in a test mode and the test would write to that.</p> <p>Depending on the platform it might also be possible to expose objects via a remote pr...
0
2016-09-17T14:53:58Z
[ "python", "c++", "qt", "automated-tests" ]
scipy.integrate.quad precision on big numbers
39,515,582
<p>I try to compute such an integral (actually cdf of exponential distribution with its pdf) via <code>scipy.integrate.quad()</code>:</p> <pre><code>import numpy as np from scipy.integrate import quad def g(x): return .5 * np.exp(-.5 * x) print quad(g, a=0., b=np.inf) print quad(g, a=0., b=10**6) print quad(g, a...
0
2016-09-15T16:00:24Z
39,517,294
<p>I believe the issue is due to <code>np.exp(-x)</code> quickly becoming very small as <code>x</code> increases, which results in evaluating as zero due to limited numerical precision. For example, even for <code>x</code> as small as <code>x=10**2*</code>, <code>np.exp(-x)</code> evaluates to <code>3.72007597602e-44</...
1
2016-09-15T17:45:54Z
[ "python", "numpy", "scipy", "calculus" ]
scipy.integrate.quad precision on big numbers
39,515,582
<p>I try to compute such an integral (actually cdf of exponential distribution with its pdf) via <code>scipy.integrate.quad()</code>:</p> <pre><code>import numpy as np from scipy.integrate import quad def g(x): return .5 * np.exp(-.5 * x) print quad(g, a=0., b=np.inf) print quad(g, a=0., b=10**6) print quad(g, a...
0
2016-09-15T16:00:24Z
39,518,212
<p>Use the <code>points</code> argument to tell the algorithm where the support of your function roughly is:</p> <pre><code>import numpy as np from scipy.integrate import quad def g(x): return .5 * np.exp(-.5 * x) print quad(g, a=0., b=10**3, points=[1, 100]) print quad(g, a=0., b=10**6, points=[1, 100]) print q...
2
2016-09-15T18:41:53Z
[ "python", "numpy", "scipy", "calculus" ]
getting percentage of values meeting conditions within a Pandas group by
39,515,589
<p>I have a dataframe of of <code>People</code>, <code>Days</code>, and <code>Types</code>. The data doesn't really make sense, it's just an example.</p> <p>I'd like to do a group by first on <code>People</code> then <code>Type</code> and then find the percentage of Days that are less than or equal to 3.</p> <p>In or...
1
2016-09-15T16:00:52Z
39,516,256
<ul> <li><code>set_index</code> on <code>Person</code> and <code>Type</code></li> <li>boolean series of <code>Days</code> >= 3</li> <li><code>groupby</code> levels in index</li> <li><code>value_counts(normalize=True)</code></li> </ul> <hr> <pre><code>df.set_index(['Person', 'Type']).Days.ge(3).groupby(level=[0, 1]).v...
2
2016-09-15T16:39:53Z
[ "python", "python-2.7", "pandas" ]
Efficiently looping through lists in Python
39,515,671
<p>I need to make a python function which, given ordered list <code>a</code> and <code>b</code> returns <code>True</code> if there exists an item in a for which holds that there is an item in <code>b</code> that is <code>a+1</code>.</p> <p>This is of course easily done by using something like this:</p> <pre><code>for...
0
2016-09-15T16:06:27Z
39,516,275
<p>I can see two options that are more efficient.</p> <ol> <li>Go through each element in <code>a</code>, and perform a binary search for <code>element+1</code> in <code>b</code>.</li> </ol> <p>Time complexity: O(n*log(m)) where n = <code>|a|</code> and m = <code>|b|</code>.</p> <pre><code> for element in a: ...
0
2016-09-15T16:41:40Z
[ "python", "list", "loops", "iterator" ]
Efficiently looping through lists in Python
39,515,671
<p>I need to make a python function which, given ordered list <code>a</code> and <code>b</code> returns <code>True</code> if there exists an item in a for which holds that there is an item in <code>b</code> that is <code>a+1</code>.</p> <p>This is of course easily done by using something like this:</p> <pre><code>for...
0
2016-09-15T16:06:27Z
39,516,408
<p>Warning: not very well tested code. Assuming sorted lists as you wrote.</p> <p>The idea behind the hint with <code>iter</code> and <code>next</code> is that within a single loop you can advance in one or in the other list. If the first number is too small, you try the next first number. If the second one is too sma...
0
2016-09-15T16:49:02Z
[ "python", "list", "loops", "iterator" ]
Efficiently looping through lists in Python
39,515,671
<p>I need to make a python function which, given ordered list <code>a</code> and <code>b</code> returns <code>True</code> if there exists an item in a for which holds that there is an item in <code>b</code> that is <code>a+1</code>.</p> <p>This is of course easily done by using something like this:</p> <pre><code>for...
0
2016-09-15T16:06:27Z
39,520,027
<p>Thank you both for your answers! I ended up using a combined version of your solutions:</p> <pre><code>a = iter(l1) b = iter(l2) i = next(a) j = next(b) try: while (i): if i + 1 == j: return True elif i + 1 &gt; j: j = next(b) else: i = next(a) except ...
0
2016-09-15T20:41:48Z
[ "python", "list", "loops", "iterator" ]
How can I kill omxplayer player on a Raspberry Pi using Python
39,515,757
<p>I'm doing a DIY project using a Raspberry Pi 3 where I need to play 4 videos using omxplayer. </p> <p>Each video is played once you press a certain button on the protoboard:</p> <ul> <li>Press Button 1 - Play Video 1</li> <li>Press Button 2 - Play Video 2</li> <li>Press Button 3 - Play Video 3</li> <li>Press Butto...
0
2016-09-15T16:10:50Z
39,552,427
<p>A bit hacky i guess but have you tried to killall before running the omxplayer?</p> <pre><code>command = "killall omxplayer; omxplayer -p -o hdmi %s/%s.mp4" % (pathVideos,nameVideo) os.system(command) </code></pre>
1
2016-09-17T22:45:49Z
[ "python", "raspberry-pi", "omxplayer" ]