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 |
|---|---|---|---|---|---|---|---|---|---|
Add a new column to a csv file in python | 39,733,158 | <p>I am trying to add a column to a csv file that combines strings from two other columns. Whenever I try this I either get an output csv with only the new column or an output with all of the original data and not the new column. </p>
<p>This is what I have so far:</p>
<pre><code>with open(filename) as csvin:
rea... | 2 | 2016-09-27T19:49:28Z | 39,734,612 | <p>Below code snippet combines strings in column 10 and column 11 in each row and add that to the end of the each row</p>
<pre><code>import csv
input = 'test.csv'
output= 'output.csv'
with open(input, 'rb') as csvin:
readfile = csv.reader(csvin, delimiter=',')
with open(output, 'wb') as csvout:
writefi... | 0 | 2016-09-27T21:30:04Z | [
"python",
"python-2.7",
"csv"
] |
Beginner : python len() closes file? | 39,733,269 | <p>I am new to Python and going through the book of Zed. I stumbled upon the following exercise, scope of which is to copy one txt to another.</p>
<p>The original code from the book <em>works perfectly</em> and I copy below - so that I can show the difference:</p>
<pre><code>1 from sys import argv
2 from os.path impo... | 4 | 2016-09-27T19:57:47Z | 39,733,305 | <p>It's actually the act of calling <code>in_file.read()</code> twice that's causing your problem. You can fix it by assigning the result to a variable, as in the original:</p>
<pre><code>indata = in_file.read()
</code></pre>
<p>The reason is that when you call <code>in_file.read()</code>, you "exhaust" the file. T... | 2 | 2016-09-27T19:59:49Z | [
"python"
] |
Why do I have an infinite loop in my code? | 39,733,302 | <p>Below I have a piece of code which calculates credit card balance, but it doesn't work when <code>balance</code> has an extreme value (such as <code>balance=9999999999</code>below). It throws the code through an infinite loop. I have a couple of theories as to how to fix this flaw, but don't know how to move forward... | 1 | 2016-09-27T19:59:37Z | 39,733,390 | <p>This loop is not infinite, but will take a long time to resolve. For very large values of <code>balance</code>, <code>monthlyPayment</code> will have to get very large in order to drop it past zero. </p>
| 3 | 2016-09-27T20:05:04Z | [
"python",
"python-3.x",
"infinite-loop"
] |
Why do I have an infinite loop in my code? | 39,733,302 | <p>Below I have a piece of code which calculates credit card balance, but it doesn't work when <code>balance</code> has an extreme value (such as <code>balance=9999999999</code>below). It throws the code through an infinite loop. I have a couple of theories as to how to fix this flaw, but don't know how to move forward... | 1 | 2016-09-27T19:59:37Z | 39,733,646 | <p>The bisection method will execute much quicker if you're allowed to use it in your assignment. Will not help you though, if you're required to increment the monthly payment by .01.</p>
<pre><code>static_balance = balance
interest = (annualInterestRate/12)
epsilon = 0.01
lo = balance/12
hi = balance
while abs(bala... | 0 | 2016-09-27T20:22:15Z | [
"python",
"python-3.x",
"infinite-loop"
] |
Python regex numbers and underscores | 39,733,358 | <p>I'm trying to get a list of files from a directory whose file names follow this pattern:</p>
<pre><code>PREFIX_YYYY_MM_DD.dat
</code></pre>
<p>For example</p>
<pre><code>FOO_2016_03_23.dat
</code></pre>
<p>Can't seem to get the right regex. I've tried the following:</p>
<pre><code>pattern = re.compile(r'(\d{4}... | 1 | 2016-09-27T20:03:11Z | 39,733,412 | <p>Use <code>pattern.search()</code> instead of <code>pattern.match()</code>.</p>
<p><code>pattern.match()</code> always matches from the start of the string (which includes the PREFIX).
<code>pattern.search()</code> searches anywhere within the string.</p>
| 1 | 2016-09-27T20:06:38Z | [
"python",
"regex"
] |
Python regex numbers and underscores | 39,733,358 | <p>I'm trying to get a list of files from a directory whose file names follow this pattern:</p>
<pre><code>PREFIX_YYYY_MM_DD.dat
</code></pre>
<p>For example</p>
<pre><code>FOO_2016_03_23.dat
</code></pre>
<p>Can't seem to get the right regex. I've tried the following:</p>
<pre><code>pattern = re.compile(r'(\d{4}... | 1 | 2016-09-27T20:03:11Z | 39,733,418 | <p>Does this do what you want?</p>
<pre><code>>>> import re
>>> pattern = r'\A[a-z]+_\d{4}_\d{2}_\d{2}\.dat\Z'
>>> string = 'FOO_2016_03_23.dat'
>>> re.search(pattern, string, re.IGNORECASE)
<_sre.SRE_Match object; span=(0, 18), match='FOO_2016_03_23.dat'>
>>>
</code... | 1 | 2016-09-27T20:06:53Z | [
"python",
"regex"
] |
Python regex numbers and underscores | 39,733,358 | <p>I'm trying to get a list of files from a directory whose file names follow this pattern:</p>
<pre><code>PREFIX_YYYY_MM_DD.dat
</code></pre>
<p>For example</p>
<pre><code>FOO_2016_03_23.dat
</code></pre>
<p>Can't seem to get the right regex. I've tried the following:</p>
<pre><code>pattern = re.compile(r'(\d{4}... | 1 | 2016-09-27T20:03:11Z | 39,733,492 | <p>You have two issues with your expression:
<code>re.compile(r'(\d{4})_(\d{2})_(\d{2}).dat')</code></p>
<p>The first one, as a previous comment stated, is that the <code>.</code> right before <code>dat</code> should be escaped by putting a backslash (<code>\</code>) before. Otherwise, python will treat it as a specia... | 2 | 2016-09-27T20:12:07Z | [
"python",
"regex"
] |
Python regex numbers and underscores | 39,733,358 | <p>I'm trying to get a list of files from a directory whose file names follow this pattern:</p>
<pre><code>PREFIX_YYYY_MM_DD.dat
</code></pre>
<p>For example</p>
<pre><code>FOO_2016_03_23.dat
</code></pre>
<p>Can't seem to get the right regex. I've tried the following:</p>
<pre><code>pattern = re.compile(r'(\d{4}... | 1 | 2016-09-27T20:03:11Z | 39,733,509 | <p>The following should match for what you requested. </p>
<pre><code>[^_]+[_]\d{4}[_]\d{2}[_]\d{2}[\.]\w+
</code></pre>
<p>I recommend using <a href="https://regex101.com/" rel="nofollow">https://regex101.com/</a> (for python regular expressions) or <a href="http://regexr.com/" rel="nofollow">http://regexr.com/</a> ... | 1 | 2016-09-27T20:13:39Z | [
"python",
"regex"
] |
TemplateDoesNotExist at /accounts/register/ Error | 39,733,402 | <p>So I am new to Django and am currently trying to build registration into my app. I have already followed this <a href="http://code.techandstartup.com/django/registration/#app-download" rel="nofollow">guide</a>. However I am running into an issue in which the application is not able to find the template somehow.</p>
... | 0 | 2016-09-27T20:06:09Z | 39,733,901 | <p>Please check that you have defined TEMPLATES_DIRS properly</p>
<p>In Django 1.8 upwards:</p>
<pre><code>TEMPLATES = [
{
'DIRS': [
# insert your TEMPLATE_DIRS here (absolute path)
],
},
]
</code></pre>
| 0 | 2016-09-27T20:40:06Z | [
"python",
"django",
"templates",
"django-templates",
"django-registration"
] |
Python dictionary sumUp values | 39,733,443 | <p>The function below should return a new dictionary which has summed the values up. </p>
<pre><code>import functools
def sumUp(d):
for k in d:
d.update({k: functools.reduce(lambda x, y: x + y, d[k])})
print(d)
</code></pre>
<p>When i call the function as follows i get the following <code>TypeError</c... | 2 | 2016-09-27T20:09:10Z | 39,733,502 | <p>This works:</p>
<pre><code>def sumUp(d):
new_d = {k: sum(v) for k, v in d.items()}
print(new_d)
return new_d
</code></pre>
<p>Keep in mind you are updating the dictionary while iterating over it, which causes all sorts of strange behavior.</p>
<p>The behavior is quite random and depends on the salting... | 2 | 2016-09-27T20:13:01Z | [
"python",
"python-3.x",
"dictionary"
] |
I am learning Python, need some pushing in the right direction | 39,733,476 | <p>I am trying to learn Python through Coursera, and have some questions about an assignment.</p>
<blockquote>
<p>Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:</p>
<pre><code>X-DSPAM-Confidence: 0.8475
</code></pre>
<p>Count the... | 3 | 2016-09-27T20:10:29Z | 39,733,609 | <p>The reason not to use a variable named <code>sum</code> is because there is a function with the same name.</p>
<p>The assignment asks you to do the work of the <code>sum()</code> function explicitly. You are on the right track with the <code>if not</code> line but might be more successful if you reverse the logic ... | 1 | 2016-09-27T20:19:39Z | [
"python"
] |
I am learning Python, need some pushing in the right direction | 39,733,476 | <p>I am trying to learn Python through Coursera, and have some questions about an assignment.</p>
<blockquote>
<p>Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:</p>
<pre><code>X-DSPAM-Confidence: 0.8475
</code></pre>
<p>Count the... | 3 | 2016-09-27T20:10:29Z | 39,733,633 | <pre><code>with open(fname) as f:
s = 0
linecount = 0
for line in f:
l = line.split()
try:
num = float(l[1])
except ValueError:
continue
if l[0] == 'X-DSPAM-Confidence:':
s += num
linecount += 1
print(s/linecount)
</code></p... | 1 | 2016-09-27T20:21:27Z | [
"python"
] |
I am learning Python, need some pushing in the right direction | 39,733,476 | <p>I am trying to learn Python through Coursera, and have some questions about an assignment.</p>
<blockquote>
<p>Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:</p>
<pre><code>X-DSPAM-Confidence: 0.8475
</code></pre>
<p>Count the... | 3 | 2016-09-27T20:10:29Z | 39,733,688 | <p>@PatrickHaugh beat me to it but here's my answer. It's less complex than his in that it does not implement try/except. I assume you haven't learned try/except yet.</p>
<pre><code>fname = raw_input("Enter file name: ")
sum = 0
lines = 0
f = open(fname)
for line in f:
if line.startswith("X-DSPAM-Confidence:"):
... | 0 | 2016-09-27T20:25:04Z | [
"python"
] |
I am learning Python, need some pushing in the right direction | 39,733,476 | <p>I am trying to learn Python through Coursera, and have some questions about an assignment.</p>
<blockquote>
<p>Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:</p>
<pre><code>X-DSPAM-Confidence: 0.8475
</code></pre>
<p>Count the... | 3 | 2016-09-27T20:10:29Z | 39,733,730 | <p>Using <strong>Regular expression</strong>.</p>
<p><a href="https://pymotw.com/2/re/" rel="nofollow">More info regarding re module, check here !!!</a></p>
<p><strong>Code:</strong></p>
<pre><code>import re
fname = raw_input("Enter file name: ")
f = open(fname)
val_list = []
tot = 0
line_cnt = 0
for line in f:
a ... | 1 | 2016-09-27T20:28:23Z | [
"python"
] |
I am learning Python, need some pushing in the right direction | 39,733,476 | <p>I am trying to learn Python through Coursera, and have some questions about an assignment.</p>
<blockquote>
<p>Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:</p>
<pre><code>X-DSPAM-Confidence: 0.8475
</code></pre>
<p>Count the... | 3 | 2016-09-27T20:10:29Z | 39,733,950 | <p>Here is a code snippet that suffices your work. I am reading the float values from the line with "X-DSPAM-Confidence:" and adding them and in the end, I am taking the mean. Also, since you are a beginner, I suggest to keep in mind that when you are dealing with division and you are expecting a float, either numerato... | 1 | 2016-09-27T20:42:22Z | [
"python"
] |
tornado web application fails to decode compressed http body | 39,733,500 | <p>I am writing some simple prototype tornado web applications and found that tornado fails to decode the http request body with</p>
<pre><code>Error -3 while decompressing: incorrect header check
</code></pre>
<p>From one of the tornado web application, I am sending http request by compressing the body using zlib.</... | 0 | 2016-09-27T20:12:44Z | 39,760,582 | <p><code>gzip</code> and <code>zlib</code> are both based on the same underlying compression algorithm, but they are not the same thing. You must use <code>gzip</code> and not just <code>zlib</code> here:</p>
<pre><code>def post_gzip(self, body):
bytesio = BytesIO()
gzip_file = gzip.GzipFile(mode='w', fileobj=... | 0 | 2016-09-29T02:46:55Z | [
"python",
"http",
"tornado"
] |
how to keep pd.read_csv() from changing datatype | 39,733,518 | <p>I save a DataFrame using to_csv(), then retrieve it with csv_read() and it comes back with a different datatype.</p>
<pre><code>df1i=['00','01']
df1=pd.DataFrame( columns=['00','01'],index=df1i)
df1
df1.iloc[0,0]=([11, 22])
df1
print((df1.iloc[0,0]))
print(type(df1.iloc[0,0]))
print(df1.iloc[0,0][0])
print(type(df1... | 1 | 2016-09-27T20:14:08Z | 39,734,021 | <p>It is a bit weird to store lists as elements of a DataFrame, but if it is what you need to do then consider using a converter along with <code>ast.literal_eval</code> in order to get a list back. </p>
<pre><code>import pandas as pd
import ast
df1i = ['00', '01']
df1=pd.DataFrame( columns=['00','01'],index=df1i)
d... | 1 | 2016-09-27T20:47:13Z | [
"python"
] |
Python Selenium 'module' object is not callable in python selenium script | 39,733,650 | <p>Learning Selenium driven by Python and in my practice I keep getting the following error. I am stuck and could use some guidance </p>
<blockquote>
<p>Traceback (most recent call last): File "test_login.py", line 14, in
test_Login
loginpage = homePage(self.driver) TypeError: 'module' object is not callab... | 1 | 2016-09-27T20:22:25Z | 39,733,672 | <p>I think here:</p>
<pre><code>loginpage = homePage(self.driver)
</code></pre>
<p>you meant to instantiate the <code>LoginPage</code> class:</p>
<pre><code>loginpage = homePage.LoginPage(self.driver)
</code></pre>
| 1 | 2016-09-27T20:23:49Z | [
"python",
"selenium"
] |
Iterate through worksheets in workbook- Python Nested For loop | 39,733,669 | <p>I am trying to open an excel workbook and iterate through each of the worksheets in a loop. Here is first loop:</p>
<pre><code>wb = openpyxl.load_workbook('snakes.xlsx')
for i in wb.worksheets:
i= 0
wb.get_sheet_names()
i = i + 1
</code></pre>
<p>Once I can successful go through each one of these work... | 1 | 2016-09-27T20:23:41Z | 39,733,924 | <p>Your code snippets seem to show a fundamental misunderstanding of how the <code>for</code> loop works in Python.</p>
<p>To loop through each sheet, you were on the right track:</p>
<pre><code>wb = openpyxl.load_workbook('test.xlsx')
for sheet in wb.worksheets:
# do stuff with "sheet"
pass
</code></pre>
<p... | 1 | 2016-09-27T20:41:03Z | [
"python",
"for-loop",
"openpyxl"
] |
Python, Scrapy problems when parsing tables in Earning Reports | 39,733,693 | <p>I am trying to parse some data from the table (the balance sheet) under every earning report. Here I use AMD as an example, but not limited to AMD.</p>
<p>Here is <a href="http://www.marketwired.com/press-release/amd-reports-2016-second-quarter-results-nasdaq-amd-2144535.htm" rel="nofollow">the link</a></p>
<p>The... | 1 | 2016-09-27T20:25:35Z | 39,736,933 | <p>The html provided by the inspect tool in chrome is the result of the browser interpretation of the actual code that it is sent by the server to your browser.</p>
<p>The <code>tbody</code> tag is a prime example. If you view the page source of a website you'll see a structure like this</p>
<pre><code><table>
... | 0 | 2016-09-28T02:07:44Z | [
"python",
"python-2.7",
"scrapy",
"scrapy-spider"
] |
Python Query list for oldest date | 39,733,775 | <p>My query returns the following in a list:</p>
<pre><code>"Alex";"275467125";"2015-02-03 02:55:36-05";"1"
"Alex";"275467125";"2015-01-13 02:09:39-05";"1"
"Alex";"275467125";"2015-01-05 04:13:35-05";"1"
"Alex";"275467125";"2014-12-27 04:55:47-05";"1"
"Alex";"275467125";"2014-12-27 04:54:52-05";"1"
"Alex";"275467125";... | 1 | 2016-09-27T20:31:49Z | 39,733,851 | <p>Since you need last record for each <code>name</code> instead of doing it explicitly with the <code>dict</code> make your queryset to perform <code>GROUP BY</code> on name. In Django you can do that using <code>.annotate</code> as is mentioned here: <a href="http://stackoverflow.com/questions/19923877/django-orm-get... | 0 | 2016-09-27T20:36:01Z | [
"python",
"list",
"date",
"dictionary",
"time"
] |
Python Query list for oldest date | 39,733,775 | <p>My query returns the following in a list:</p>
<pre><code>"Alex";"275467125";"2015-02-03 02:55:36-05";"1"
"Alex";"275467125";"2015-01-13 02:09:39-05";"1"
"Alex";"275467125";"2015-01-05 04:13:35-05";"1"
"Alex";"275467125";"2014-12-27 04:55:47-05";"1"
"Alex";"275467125";"2014-12-27 04:54:52-05";"1"
"Alex";"275467125";... | 1 | 2016-09-27T20:31:49Z | 39,734,355 | <p>It was a bit frustrating to get your given "list" into an actual list format. If you can't deal with this task in the query itself, you could try:</p>
<pre><code>from itertools import groupby
from operator import itemgetter
lst = '''"Alex";"275467125";"2015-02-03 02:55:36-05";"1",
"Alex";"275467125";"2015-01-13 02... | 1 | 2016-09-27T21:09:47Z | [
"python",
"list",
"date",
"dictionary",
"time"
] |
Python Query list for oldest date | 39,733,775 | <p>My query returns the following in a list:</p>
<pre><code>"Alex";"275467125";"2015-02-03 02:55:36-05";"1"
"Alex";"275467125";"2015-01-13 02:09:39-05";"1"
"Alex";"275467125";"2015-01-05 04:13:35-05";"1"
"Alex";"275467125";"2014-12-27 04:55:47-05";"1"
"Alex";"275467125";"2014-12-27 04:54:52-05";"1"
"Alex";"275467125";... | 1 | 2016-09-27T20:31:49Z | 39,734,564 | <p>I was pretty close. The answer I found that works best was a tweak of my original code but using the sorted() function. </p>
<p>For the newest I'd do:</p>
<pre><code>newestlist = {d[0]:d[2] for d in sorted(records)}
</code></pre>
<p>For the oldest I'd do:</p>
<pre><code>oldestlist = {d[0]:d[2] for d in sorted(re... | 0 | 2016-09-27T21:26:22Z | [
"python",
"list",
"date",
"dictionary",
"time"
] |
Python Query list for oldest date | 39,733,775 | <p>My query returns the following in a list:</p>
<pre><code>"Alex";"275467125";"2015-02-03 02:55:36-05";"1"
"Alex";"275467125";"2015-01-13 02:09:39-05";"1"
"Alex";"275467125";"2015-01-05 04:13:35-05";"1"
"Alex";"275467125";"2014-12-27 04:55:47-05";"1"
"Alex";"275467125";"2014-12-27 04:54:52-05";"1"
"Alex";"275467125";... | 1 | 2016-09-27T20:31:49Z | 39,734,569 | <p>You don't need to sort any data, just use a <em>defaultdict</em> and check the current date vs any new date and update accordingly:</p>
<pre><code>s = """"Alex";"275467125";"2015-02-03 02:55:36-05";"1"
"Alex";"275467125";"2015-01-13 02:09:39-05";"1"
"Alex";"275467125";"2015-01-05 04:13:35-05";"1"
"Alex";"275467125"... | 1 | 2016-09-27T21:26:41Z | [
"python",
"list",
"date",
"dictionary",
"time"
] |
Python: count TP, FP, FN и TN | 39,733,934 | <p>I have dataframe with true class and class, that were predicted by some algorithm.</p>
<pre><code> true pred
0 1 0
1 1 1
2 1 1
3 0 0
4 1 1
</code></pre>
<p>I try to use</p>
<pre><code>def classification(y_actual, y_hat):
TP = 0
FP = 0
TN = 0
F... | 0 | 2016-09-27T20:41:41Z | 39,733,979 | <p>The error message happens because Python tries to convert an array to a boolean and fails.</p>
<p>That's because you're comparing <code>y_actual</code> with <code>y_hat[i]</code>.</p>
<p>It should be <code>y_actual[i] != y_hat[i]</code> (2 times in the code)</p>
<p>(I realize that it's just a typo, but the messag... | 1 | 2016-09-27T20:44:41Z | [
"python",
"machine-learning",
"scikit-learn"
] |
Python: count TP, FP, FN и TN | 39,733,934 | <p>I have dataframe with true class and class, that were predicted by some algorithm.</p>
<pre><code> true pred
0 1 0
1 1 1
2 1 1
3 0 0
4 1 1
</code></pre>
<p>I try to use</p>
<pre><code>def classification(y_actual, y_hat):
TP = 0
FP = 0
TN = 0
F... | 0 | 2016-09-27T20:41:41Z | 39,734,245 | <p>I use <code>confusion_matrix</code> from <code>sklearn.metrics</code> and it return me need matrix.</p>
| 1 | 2016-09-27T21:01:51Z | [
"python",
"machine-learning",
"scikit-learn"
] |
Counting Mulitple Values in a Python pandas Dataframe Column | 39,733,948 | <p>I'm trying to count unique values in a pandas dataframe column that contains multiple values separated by a string. I could do this using value_counts() if this were a series, but how would I do this in a dataframe? It seems like a dataframe should be easier. </p>
<p>Data:</p>
<pre><code> ID ... | 1 | 2016-09-27T20:42:20Z | 39,734,034 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow"><code>str.split</code></a> with <code>expand=True</code> to separate each string into different columns, then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html"... | 3 | 2016-09-27T20:48:00Z | [
"python",
"pandas"
] |
Python str.format() list of dictionaries | 39,734,016 | <p>I am trying to develop a format that prints a certain way when iterating through a list of dictionaries. </p>
<p>Error Raised: "tuple index out of range"</p>
<p>I have looked at several other questions that with a similar topic and know that you can't key in using a numerical value and format(). At least that's wh... | 1 | 2016-09-27T20:46:58Z | 39,734,231 | <p>The error you are getting occurs when you try to unpack a format string with too few arguments. Here is a basic example:</p>
<pre><code>>>> '{}{}'.format('test')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
</code></pre>
<p>This ... | 0 | 2016-09-27T21:01:04Z | [
"python",
"list",
"dictionary",
"format"
] |
Python str.format() list of dictionaries | 39,734,016 | <p>I am trying to develop a format that prints a certain way when iterating through a list of dictionaries. </p>
<p>Error Raised: "tuple index out of range"</p>
<p>I have looked at several other questions that with a similar topic and know that you can't key in using a numerical value and format(). At least that's wh... | 1 | 2016-09-27T20:46:58Z | 39,736,244 | <p>The problem seems simpler than you're trying to make it:</p>
<pre><code>formats = [None, '{}', '{} & {}']
def namelist(names):
length = len(names)
if length > 2:
name_format = '{}, ' * (length - 2) + formats[2] # handle any number of names
else:
name_format = formats[length]
... | 1 | 2016-09-28T00:25:53Z | [
"python",
"list",
"dictionary",
"format"
] |
How to get all API tokens from a JSON list | 39,734,033 | <p>So, basically I have a loop that retrieves all of the API tokens I need in order to run another get call.</p>
<p>Here is a segment of my code:</p>
<pre><code>tokens = [result['apiToken'] for result in data_2['result']['apiToken']]
for i in tokens:
url = "https://swag.com"
headers = {
'x-api-token': i
... | 0 | 2016-09-27T20:47:58Z | 39,734,284 | <p>As per your comment</p>
<blockquote>
<p>typeerror string indices must be integers</p>
</blockquote>
<p>try updating your list comprehension (assuming that <code>data_2</code> is a list of dicts and not a <code>JSON</code> string). It looks like you are iterating over the token characters.</p>
<pre><code>tokens ... | 2 | 2016-09-27T21:04:01Z | [
"python",
"json"
] |
How to view variables within a function when warning is thrown pdb in python? | 39,734,045 | <p>Im running into a problem where</p>
<pre><code>cds_to_protein = str(feature.extract(record).seq.translate(to_stop = True))
</code></pre>
<p>will throw a Biopython warning. So I need to see what record and feature is being passed to it that causes that warning.</p>
<p>Is there a way to use pdb or another debugger... | 1 | 2016-09-27T20:48:21Z | 39,734,180 | <p>Try adding a trace to your function:</p>
<pre><code>def validate_cds(record, feature):
import pdb; pdb.set_trace()
saved_record = record
saved_feature = feature
protein_in_file = str(feature.qualifiers.get('translation', 'no_translation')).strip('\'[]')
cds_to_protein = str(feature.extract(rec... | 1 | 2016-09-27T20:57:48Z | [
"python",
"python-2.7",
"biopython"
] |
How to view variables within a function when warning is thrown pdb in python? | 39,734,045 | <p>Im running into a problem where</p>
<pre><code>cds_to_protein = str(feature.extract(record).seq.translate(to_stop = True))
</code></pre>
<p>will throw a Biopython warning. So I need to see what record and feature is being passed to it that causes that warning.</p>
<p>Is there a way to use pdb or another debugger... | 1 | 2016-09-27T20:48:21Z | 39,734,676 | <p>thanks to @TomaszPlaskota for his suggestion to use a <code>try: except</code></p>
<p>Added the following to turn a warning into an exception</p>
<pre><code>import warnings
from Bio import BiopythonWarning
warnings.filterwarnings('error')
</code></pre>
<p>And a simple <code>try: except</code> correctly stops it<... | 0 | 2016-09-27T21:35:18Z | [
"python",
"python-2.7",
"biopython"
] |
How to view variables within a function when warning is thrown pdb in python? | 39,734,045 | <p>Im running into a problem where</p>
<pre><code>cds_to_protein = str(feature.extract(record).seq.translate(to_stop = True))
</code></pre>
<p>will throw a Biopython warning. So I need to see what record and feature is being passed to it that causes that warning.</p>
<p>Is there a way to use pdb or another debugger... | 1 | 2016-09-27T20:48:21Z | 39,734,762 | <p>Per the <a href="https://docs.python.org/2/library/pdb.html" rel="nofollow">docs</a>:</p>
<blockquote>
<p>The typical usage to break into the debugger from a running program is to insert</p>
</blockquote>
<p><code>import pdb; pdb.set_trace()</code></p>
<blockquote>
<p>at the location you want to break into th... | 0 | 2016-09-27T21:41:30Z | [
"python",
"python-2.7",
"biopython"
] |
Tokenise line containing string literals | 39,734,209 | <p>Using <code>str.split</code> on <code>"print 'Hello, world!' times 3"</code> returns the list <code>["print", "'Hello,", "world!'", "times", "3"]</code>. However, I want the result <code>["print", "'Hello, world!'", "times", "3"]</code>. How can I do that?</p>
| 2 | 2016-09-27T20:59:33Z | 39,734,294 | <p>If you're going to exclude the words in quote out of the <em>split</em>, you could use <a href="https://docs.python.org/2/library/shlex.html#shlex.split" rel="nofollow"><code>shlex.split</code></a>:</p>
<pre><code>import shlex
s = "print 'Hello, world!' times 3"
print(shlex.split(s))
# ['print', 'Hello, world!', '... | 3 | 2016-09-27T21:04:43Z | [
"python",
"string",
"parsing"
] |
Tokenise line containing string literals | 39,734,209 | <p>Using <code>str.split</code> on <code>"print 'Hello, world!' times 3"</code> returns the list <code>["print", "'Hello,", "world!'", "times", "3"]</code>. However, I want the result <code>["print", "'Hello, world!'", "times", "3"]</code>. How can I do that?</p>
| 2 | 2016-09-27T20:59:33Z | 39,734,318 | <p><a href="https://www.tutorialspoint.com/python/string_split.htm" rel="nofollow"><code>.split()</code></a> function splits the <code>str</code> based on the delimiter. The default delimiter is a <code>blank space</code>. It doesn't care about the <code>'</code> within your string. In case you want to treat words with... | 0 | 2016-09-27T21:06:22Z | [
"python",
"string",
"parsing"
] |
Tokenise line containing string literals | 39,734,209 | <p>Using <code>str.split</code> on <code>"print 'Hello, world!' times 3"</code> returns the list <code>["print", "'Hello,", "world!'", "times", "3"]</code>. However, I want the result <code>["print", "'Hello, world!'", "times", "3"]</code>. How can I do that?</p>
| 2 | 2016-09-27T20:59:33Z | 39,734,684 | <p>This regex will capture the quotes, if you want them.</p>
<pre><code>import re
s = "print 'hello, world!' 3 times"
re.findall(r'(\w+|\'.+\')',s)
</code></pre>
| 1 | 2016-09-27T21:35:37Z | [
"python",
"string",
"parsing"
] |
How do I get PyOpenGL to work with a wxPython context, based on this C++ Modern OpenGL tutorial? | 39,734,211 | <p>I've been following <a href="https://open.gl/drawing" rel="nofollow">this tutorial</a> for drawing a simple triangle using shaders and modern OpenGL features such as Vertex Array Objects andVertex Buffer Objects. The tutorial code is in C++, but I figured that as OpenGL is the same whichever bindings you use, it wou... | 1 | 2016-09-27T20:59:40Z | 39,803,714 | <p>If you are still having this problem, I think the issue is in this following line and the way PyOpenGL works. I found just making this following fix got your demo to work.</p>
<pre><code>glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 0, None)
</code></pre>
<p>Apparently 0 != None in the bindings!</p>
| 0 | 2016-10-01T06:32:05Z | [
"python",
"python-2.7",
"wxpython",
"opengl-3",
"pyopengl"
] |
Formatting negative fixed-length string | 39,734,252 | <p>In <code>python</code>, I'm trying to format a number to be a fixed-length string with leading zeros, which can be done like so:</p>
<pre><code>'{:0>10}'.format('10.0040')
'00010.0040'
</code></pre>
<p>I have a negative number and want to express the negative, I would get this:</p>
<pre><code>'{:0>10}'.form... | 2 | 2016-09-27T21:01:57Z | 39,734,358 | <p>I don't know how to do it with <code>str.format</code>. May I propose using <a href="https://docs.python.org/2/library/string.html#string.zfill" rel="nofollow"><code>str.zfill</code></a> instead?</p>
<pre><code>>>> '-10.0040'.zfill(10)
'-0010.0040'
>>> '10.0040'.zfill(10)
'00010.0040'
</code></pr... | 4 | 2016-09-27T21:09:52Z | [
"python"
] |
Formatting negative fixed-length string | 39,734,252 | <p>In <code>python</code>, I'm trying to format a number to be a fixed-length string with leading zeros, which can be done like so:</p>
<pre><code>'{:0>10}'.format('10.0040')
'00010.0040'
</code></pre>
<p>I have a negative number and want to express the negative, I would get this:</p>
<pre><code>'{:0>10}'.form... | 2 | 2016-09-27T21:01:57Z | 39,734,420 | <p>You're problem is that your "number" is being represented as a string, so python has no way of knowing whether it's positive or negative, because it doesn't know it's a number.</p>
<pre><code>>>> '{: 010.4f}'.format(10.0400)
' 0010.0400'
>>> '{: 010.4f}'.format(-10.0400)
'-0010.0400'
</code></pre>... | 5 | 2016-09-27T21:15:30Z | [
"python"
] |
Formatting negative fixed-length string | 39,734,252 | <p>In <code>python</code>, I'm trying to format a number to be a fixed-length string with leading zeros, which can be done like so:</p>
<pre><code>'{:0>10}'.format('10.0040')
'00010.0040'
</code></pre>
<p>I have a negative number and want to express the negative, I would get this:</p>
<pre><code>'{:0>10}'.form... | 2 | 2016-09-27T21:01:57Z | 39,734,468 | <p>If you can convert the string to a float, you can do this:</p>
<pre><code>>>> '{:0=10.4f}'.format(float('-10.0040'))
'-0010.0040'
>>> '{:0=10.4f}'.format(float('10.0040'))
'00010.0040'
</code></pre>
| 2 | 2016-09-27T21:18:29Z | [
"python"
] |
covariance between two columns in pandas groupby pandas | 39,734,304 | <p>I am trying to calculate the covariance between two columns by group. I am doing doing the following:</p>
<pre><code>A = pd.DataFrame({'group':['A','A','A','A','B','B','B'],
'value1':[1,2,3,4,5,6,7],
'value2':[8,5,4,3,7,8,8]})
B = A.groupby('group')
B['value1'].cov(B['value2'])... | 1 | 2016-09-27T21:05:20Z | 39,734,367 | <p>The following code gives you the grouped variance-covariance matrix. You can subset it as you wish to just get the covariances. </p>
<pre><code>import pandas as pd
A = pd.DataFrame({'group':['A','A','A','A','B','B','B'],
'value1':[1,2,3,4,5,6,7],
'value2':[8,5,4,3,7,8,8]})
print ... | 2 | 2016-09-27T21:11:03Z | [
"python",
"pandas"
] |
covariance between two columns in pandas groupby pandas | 39,734,304 | <p>I am trying to calculate the covariance between two columns by group. I am doing doing the following:</p>
<pre><code>A = pd.DataFrame({'group':['A','A','A','A','B','B','B'],
'value1':[1,2,3,4,5,6,7],
'value2':[8,5,4,3,7,8,8]})
B = A.groupby('group')
B['value1'].cov(B['value2'])... | 1 | 2016-09-27T21:05:20Z | 39,734,585 | <p>You are almost there, only that you do not clear understand the groupby object, see <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow">Pandas-GroupBy</a> for more details.</p>
<p>For your problem, if I understand correctly, you would like to calculate cov between two columns in same g... | 3 | 2016-09-27T21:27:58Z | [
"python",
"pandas"
] |
Changed Django model attribute and now getting error for it | 39,734,334 | <p>I had a model with a DateField that worked just fine. I wanted to change it from a DateField to a CharField. </p>
<p><strong>Before:</strong></p>
<pre><code>class NWEAScore(models.Model):
test_date = models.DateField(default=date.today, verbose_name='Test Date')
</code></pre>
<p><strong>After:</strong></p>
... | 1 | 2016-09-27T21:07:52Z | 39,734,393 | <p>Go to the <em>migrations</em> folder of your app and delete all files, except <code>__init__.py</code>. Then run the command:</p>
<pre><code>python manage.py makemigrations
</code></pre>
<p>to make new migrations with the updated fields</p>
| 1 | 2016-09-27T21:13:30Z | [
"python",
"django",
"django-models"
] |
Ordered Dictionary and Sorting | 39,734,360 | <p>I'm trying to solve a simple practice test question:</p>
<blockquote>
<p>Parse the CSV file to:</p>
<ul>
<li>Find only the rows where the user started before September 6th, 2010. </li>
<li>Next, order the values from the "words" column in ascending order (by start date) </li>
<li>Return the compiled "h... | 0 | 2016-09-27T21:10:11Z | 39,734,446 | <p>Here's the corrected version:</p>
<pre><code>import csv
from collections import OrderedDict
from datetime import datetime
with open('TSE_sample_data.csv', 'rb') as csvIn:
reader = csv.DictReader(csvIn)
words = []
dates = []
for row in reader:
#convert from UTC to more standard date format... | 0 | 2016-09-27T21:17:17Z | [
"python",
"sorting",
"for-loop",
"dictionary",
"ordereddictionary"
] |
Flask wtforms DecimalField not displaying in HTML | 39,734,361 | <p>My TextField forms are displaying fine in the html page, but not the DecimalFields. The DecimalFields don't display at all.</p>
<p>My forms.py:</p>
<pre><code>from flask.ext.wtf import Form
from wtforms import TextField, validators, IntegerField, DateField, BooleanField, DecimalField
class EnterPart(Form):
De... | -1 | 2016-09-27T21:10:16Z | 39,734,882 | <p>Macros.html didn't have an option for dealing with DecimalField. By adding a rendering option for DecimalField, it now displays correctly.</p>
<p>I changed a block in macros.html from:</p>
<pre><code><div class="form-group {% if field.errors %}has-error{% endif %} {{ kwargs.pop('class_', '') }}">
{% if (... | 0 | 2016-09-27T21:50:46Z | [
"python",
"flask",
"wtforms",
"flask-wtforms"
] |
Python: Combining two lists and removing duplicates in a functional programming way | 39,734,485 | <p>I'm trying to write a function that would combine two lists while removing duplicate items, but in a pure functional way.
For example:</p>
<pre><code>a = [1,2,2]
b = [1,3,3,4,5,0]
union(a,b) --> [1,2,3,4,5,0]
</code></pre>
<p>The imperative form of the code would be:</p>
<pre><code>def union(a,b):
c = []
... | 1 | 2016-09-27T21:19:48Z | 39,734,524 | <p>If you want to keep the order you can use <code>collections.OrderedDict</code>, otherwise just use <code>set</code>. These data structures use hash values of their items for preserving them, thus they don't keep the duplicates.</p>
<pre><code>In [11]: from collections import OrderedDict
In [12]: list(OrderedDict.f... | 1 | 2016-09-27T21:23:26Z | [
"python",
"functional-programming"
] |
Python: Combining two lists and removing duplicates in a functional programming way | 39,734,485 | <p>I'm trying to write a function that would combine two lists while removing duplicate items, but in a pure functional way.
For example:</p>
<pre><code>a = [1,2,2]
b = [1,3,3,4,5,0]
union(a,b) --> [1,2,3,4,5,0]
</code></pre>
<p>The imperative form of the code would be:</p>
<pre><code>def union(a,b):
c = []
... | 1 | 2016-09-27T21:19:48Z | 39,734,533 | <p>To combine the two lists:</p>
<pre><code>a = [1,2,2]
b = [1,3,3,4,5,0]
</code></pre>
<p>Using sets:</p>
<pre><code>union = set(a) | set(b)
# -> set([0, 1, 2, 3, 4, 5])
</code></pre>
<p>Using comprehension list:</p>
<pre><code>union = a + [x for x in b if x not in a]
# -> [1, 2, 2, 3, 3, 4, 5, 0]
</code></... | 0 | 2016-09-27T21:23:52Z | [
"python",
"functional-programming"
] |
Python: Combining two lists and removing duplicates in a functional programming way | 39,734,485 | <p>I'm trying to write a function that would combine two lists while removing duplicate items, but in a pure functional way.
For example:</p>
<pre><code>a = [1,2,2]
b = [1,3,3,4,5,0]
union(a,b) --> [1,2,3,4,5,0]
</code></pre>
<p>The imperative form of the code would be:</p>
<pre><code>def union(a,b):
c = []
... | 1 | 2016-09-27T21:19:48Z | 39,734,546 | <p>Have you tried using <code>sets</code>?</p>
<pre><code>>>> a = [1,2,2]
>>> b = [1,3,3,4,5,0]
>>> list(set(a).union(set(b)))
[0, 1, 2, 3, 4, 5]
</code></pre>
| 1 | 2016-09-27T21:25:04Z | [
"python",
"functional-programming"
] |
Python: Combining two lists and removing duplicates in a functional programming way | 39,734,485 | <p>I'm trying to write a function that would combine two lists while removing duplicate items, but in a pure functional way.
For example:</p>
<pre><code>a = [1,2,2]
b = [1,3,3,4,5,0]
union(a,b) --> [1,2,3,4,5,0]
</code></pre>
<p>The imperative form of the code would be:</p>
<pre><code>def union(a,b):
c = []
... | 1 | 2016-09-27T21:19:48Z | 39,734,553 | <p>How about </p>
<pre><code>>>> x = [1,2,3]
>>> y = [1,3,5,7,9]
>>> list(set(x).union(set(y)))
</code></pre>
| 0 | 2016-09-27T21:25:41Z | [
"python",
"functional-programming"
] |
Python: Combining two lists and removing duplicates in a functional programming way | 39,734,485 | <p>I'm trying to write a function that would combine two lists while removing duplicate items, but in a pure functional way.
For example:</p>
<pre><code>a = [1,2,2]
b = [1,3,3,4,5,0]
union(a,b) --> [1,2,3,4,5,0]
</code></pre>
<p>The imperative form of the code would be:</p>
<pre><code>def union(a,b):
c = []
... | 1 | 2016-09-27T21:19:48Z | 39,734,678 | <pre><code>list(set(a+b))
</code></pre>
<p>This combines two lists a and b and using set takes only unique vales and then we can make it back to list. </p>
| 0 | 2016-09-27T21:35:28Z | [
"python",
"functional-programming"
] |
Sum numbers by letter in list of tuples | 39,734,549 | <p>I have a list of tuples: </p>
<pre><code>[ ('A',100), ('B',50), ('A',50), ('B',20), ('C',10) ]
</code></pre>
<p>I am trying to sum up all numbers that have the same letter. I.e. I want to output </p>
<pre><code>[('A', 150), ('B', 70), ('C',10)]
</code></pre>
<p>I have tried using set to get the unique values bu... | 1 | 2016-09-27T21:25:12Z | 39,734,639 | <p>In order to achieve this, firstly create a dictionary to store your values. Then convert the <code>dict</code> object to <code>tuple list</code> using <code>.items()</code> Below is the sample code on how to achieve this:</p>
<pre><code>my_list = [ ('A',100), ('B',50), ('A',50), ('B',20), ('C',10) ]
my_dict = {}
fo... | 0 | 2016-09-27T21:32:08Z | [
"python",
"list",
"tuples"
] |
Sum numbers by letter in list of tuples | 39,734,549 | <p>I have a list of tuples: </p>
<pre><code>[ ('A',100), ('B',50), ('A',50), ('B',20), ('C',10) ]
</code></pre>
<p>I am trying to sum up all numbers that have the same letter. I.e. I want to output </p>
<pre><code>[('A', 150), ('B', 70), ('C',10)]
</code></pre>
<p>I have tried using set to get the unique values bu... | 1 | 2016-09-27T21:25:12Z | 39,734,640 | <p>How about this: (assuming <code>a</code> is the name of the tuple you have provided)</p>
<pre><code>letters_to_numbers = {}
for i in a:
if i[0] in letters_to_numbers:
letters_to_numbers[i[0]] += i[1]
else:
letters_to_numbers[i[0]] = i[1]
b = letters_to_numbers.items()
</code></pre>
<p>The e... | 0 | 2016-09-27T21:32:17Z | [
"python",
"list",
"tuples"
] |
Sum numbers by letter in list of tuples | 39,734,549 | <p>I have a list of tuples: </p>
<pre><code>[ ('A',100), ('B',50), ('A',50), ('B',20), ('C',10) ]
</code></pre>
<p>I am trying to sum up all numbers that have the same letter. I.e. I want to output </p>
<pre><code>[('A', 150), ('B', 70), ('C',10)]
</code></pre>
<p>I have tried using set to get the unique values bu... | 1 | 2016-09-27T21:25:12Z | 39,734,647 | <p>Here is a one(and a half?)-liner: group by letter (for which you need to sort before), then take the sum of the second entries of your tuples.</p>
<pre><code>from itertools import groupby
from operator import itemgetter
data = [('A', 100), ('B', 50), ('A', 50), ('B', 20), ('C', 10)]
res = [(k, sum(map(itemgetter(1... | 0 | 2016-09-27T21:32:49Z | [
"python",
"list",
"tuples"
] |
Sum numbers by letter in list of tuples | 39,734,549 | <p>I have a list of tuples: </p>
<pre><code>[ ('A',100), ('B',50), ('A',50), ('B',20), ('C',10) ]
</code></pre>
<p>I am trying to sum up all numbers that have the same letter. I.e. I want to output </p>
<pre><code>[('A', 150), ('B', 70), ('C',10)]
</code></pre>
<p>I have tried using set to get the unique values bu... | 1 | 2016-09-27T21:25:12Z | 39,734,656 | <p>What is generating the list of tuples? Is it you? If so, why not try a defaultdict(list) to append the values to the right letter at the time of making the list of tuples. Then you can simply sum them. See example below. </p>
<pre><code>>>> from collections import defaultdict
>>> val_store = defau... | 0 | 2016-09-27T21:33:42Z | [
"python",
"list",
"tuples"
] |
Sum numbers by letter in list of tuples | 39,734,549 | <p>I have a list of tuples: </p>
<pre><code>[ ('A',100), ('B',50), ('A',50), ('B',20), ('C',10) ]
</code></pre>
<p>I am trying to sum up all numbers that have the same letter. I.e. I want to output </p>
<pre><code>[('A', 150), ('B', 70), ('C',10)]
</code></pre>
<p>I have tried using set to get the unique values bu... | 1 | 2016-09-27T21:25:12Z | 39,734,663 | <p>Try this:</p>
<pre><code>a = [('A',100), ('B',50), ('A',50), ('B',20), ('C',10) ]
letters = set([s[0] for s in a])
new_a = []
for l in letters:
nums = [s[1] for s in a if s[0] == l]
new_a.append((l, sum(nums)))
print new_a
</code></pre>
<p>Results:</p>
<pre><code>[('A', 150), ('C', 10), ('B', 70)]
... | -1 | 2016-09-27T21:33:58Z | [
"python",
"list",
"tuples"
] |
Sum numbers by letter in list of tuples | 39,734,549 | <p>I have a list of tuples: </p>
<pre><code>[ ('A',100), ('B',50), ('A',50), ('B',20), ('C',10) ]
</code></pre>
<p>I am trying to sum up all numbers that have the same letter. I.e. I want to output </p>
<pre><code>[('A', 150), ('B', 70), ('C',10)]
</code></pre>
<p>I have tried using set to get the unique values bu... | 1 | 2016-09-27T21:25:12Z | 39,734,681 | <p>A simpler approach</p>
<pre><code>x = [('A',100),('B',50),('A',50),('B',20),('C',10)]
y = {}
for _tuple in x:
if _tuple[0] in y:
y[_tuple[0]] += _tuple[1]
else:
y[_tuple[0]] = _tuple[1]
print [(k,v) for k,v in y.iteritems()]
</code></pre>
| -1 | 2016-09-27T21:35:31Z | [
"python",
"list",
"tuples"
] |
Sum numbers by letter in list of tuples | 39,734,549 | <p>I have a list of tuples: </p>
<pre><code>[ ('A',100), ('B',50), ('A',50), ('B',20), ('C',10) ]
</code></pre>
<p>I am trying to sum up all numbers that have the same letter. I.e. I want to output </p>
<pre><code>[('A', 150), ('B', 70), ('C',10)]
</code></pre>
<p>I have tried using set to get the unique values bu... | 1 | 2016-09-27T21:25:12Z | 39,734,696 | <p>A one liner:</p>
<pre><code>>>> x = [ ('A',100), ('B',50), ('A',50), ('B',20), ('C',10) ]
>>> {
... k: reduce(lambda u, v: u + v, [y[1] for y in x if y[0] == k])
... for k in [y[0] for y in x]
... }.items()
[('A', 150), ('C', 10), ('B', 70)]
</code></pre>
| -1 | 2016-09-27T21:36:12Z | [
"python",
"list",
"tuples"
] |
Sum numbers by letter in list of tuples | 39,734,549 | <p>I have a list of tuples: </p>
<pre><code>[ ('A',100), ('B',50), ('A',50), ('B',20), ('C',10) ]
</code></pre>
<p>I am trying to sum up all numbers that have the same letter. I.e. I want to output </p>
<pre><code>[('A', 150), ('B', 70), ('C',10)]
</code></pre>
<p>I have tried using set to get the unique values bu... | 1 | 2016-09-27T21:25:12Z | 39,740,468 | <pre><code>>>> from collections import Counter
>>> c = Counter()
>>> for k, num in items:
c[k] += num
>>> c.items()
[('A', 150), ('C', 10), ('B', 70)]
</code></pre>
<p>Less efficient (but nicer looking) one liner version:</p>
<pre><code>>>> Counter(k for k, num i... | -1 | 2016-09-28T07:13:49Z | [
"python",
"list",
"tuples"
] |
parse html tables with lxml | 39,734,584 | <p>I have been trying to parse the table contents from <a href="https://nseindia.com/products/content/derivatives/equities/fo_underlying_home.htm" rel="nofollow">here</a>
i have tried a couple of alternatives, like </p>
<pre><code>xpath('//table//tr/td//text()')
xpath('//div[@id="replacetext"]/table/tbody//tr/td/a//t... | -1 | 2016-09-27T21:27:55Z | 39,734,743 | <p>In the HTML page, there is a namespace:</p>
<pre><code><html xmlns="http://www.w3.org/1999/xhtml">
</code></pre>
<p>So, you need to specify it:</p>
<pre><code>NSMAP = {'html' : "http://www.w3.org/1999/xhtml"}
path = '//html:div[@id="replacetext"]/html:table/html:tbody//html:tr/html:td/html:a//text()'
packa... | 0 | 2016-09-27T21:39:57Z | [
"python",
"parsing",
"lxml"
] |
parse html tables with lxml | 39,734,584 | <p>I have been trying to parse the table contents from <a href="https://nseindia.com/products/content/derivatives/equities/fo_underlying_home.htm" rel="nofollow">here</a>
i have tried a couple of alternatives, like </p>
<pre><code>xpath('//table//tr/td//text()')
xpath('//div[@id="replacetext"]/table/tbody//tr/td/a//t... | -1 | 2016-09-27T21:27:55Z | 39,735,268 | <p>I tried you code. The problem is not caused by <code>lxml</code>. It is caused by how you load the webpage.</p>
<p>I know that you use the <code>requests</code> to get the content of webpage, however, the content you get from <code>requests</code> may be different from the content you see in the browser.</p>
<p>I... | 0 | 2016-09-27T22:25:24Z | [
"python",
"parsing",
"lxml"
] |
Is there an equivalent to the C++ pre/postfix operators for use in Python list comprehensions? | 39,734,722 | <p>I writing a function which populates a list of lists of two elements, where the first element is an element from a different list and the second element is a value which increments.</p>
<pre><code>def list_of_pairs(seq, start):
""" Returns a list of pairs """
>>> list_of_pairs([3, 2, 1], 1)
[ [... | 0 | 2016-09-27T21:38:09Z | 39,734,752 | <p>You can achieve the same with <a href="https://docs.python.org/2/library/itertools.html#itertools.count" rel="nofollow"><code>itertools.count</code></a>, calling <code>next</code> on the <code>count</code> object for each element of the sequence:</p>
<pre><code>from itertools import count
c = count(start)
lst = [[... | 2 | 2016-09-27T21:40:39Z | [
"python",
"list"
] |
Is there an equivalent to the C++ pre/postfix operators for use in Python list comprehensions? | 39,734,722 | <p>I writing a function which populates a list of lists of two elements, where the first element is an element from a different list and the second element is a value which increments.</p>
<pre><code>def list_of_pairs(seq, start):
""" Returns a list of pairs """
>>> list_of_pairs([3, 2, 1], 1)
[ [... | 0 | 2016-09-27T21:38:09Z | 39,734,802 | <p>You may use <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow"><code>enumerate()</code></a> to achieve this. Enumerate return the index along with value while iterating over the list of values. And as per your requirement, you need list of <code>list</code> as <code>[val, index + cou... | 2 | 2016-09-27T21:44:45Z | [
"python",
"list"
] |
Is there an equivalent to the C++ pre/postfix operators for use in Python list comprehensions? | 39,734,722 | <p>I writing a function which populates a list of lists of two elements, where the first element is an element from a different list and the second element is a value which increments.</p>
<pre><code>def list_of_pairs(seq, start):
""" Returns a list of pairs """
>>> list_of_pairs([3, 2, 1], 1)
[ [... | 0 | 2016-09-27T21:38:09Z | 39,734,834 | <p><code>++</code> and <code>--</code> have been deliberately excluded from Python, because using them in expressions tends to lead to confusing code and off-by-one errors.</p>
<p>You should use <a href="https://docs.python.org/3/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a> instead:</p>
... | 1 | 2016-09-27T21:46:36Z | [
"python",
"list"
] |
Python - Switch translations dynamically in a PyQt4 application | 39,734,775 | <p>I want to add a feature in my program. The user should be able to switch/change the language at runtime - without restart. Imagine the UI displays in English and he wants to switch in German.</p>
<p>Well, I wrote a small example - can't be executed, because you have missing some translation-files and ui-files. But ... | 1 | 2016-09-27T21:42:15Z | 39,735,770 | <p>Use <a href="http://pyqt.sourceforge.net/Docs/PyQt4/designer.html#PyQt4.uic.loadUiType" rel="nofollow">loadUiType</a> to load the ui file, which will give you the base-class and the ui-class needed for creating a subclass. As with your previous approach, this will result in all the child widgets becoming attributes ... | 1 | 2016-09-27T23:21:32Z | [
"python",
"pyqt4",
"translation"
] |
Drawing a polygon in Python with a set of random colors | 39,734,780 | <p>I am working on a simple python program which prompts the user to enter the length of the side of a polygon and the program (using turtle) will draw the polygon with a random color that has been set using the random.randint</p>
<p>my code so far is:</p>
<pre><code>import turtle
polygonSideLength = int(input('Ente... | 0 | 2016-09-27T21:42:42Z | 39,735,132 | <p>I am agree with the fact that you are choosing a random color with</p>
<pre><code>randomColor = random.randint(0,5)
</code></pre>
<p>but when you want to set the random color to your polygon</p>
<p>you specify an integer (value of randomColor variable) instead of a string (value of fillcolor variable)</p>
<p>fi... | 0 | 2016-09-27T22:10:08Z | [
"python"
] |
Return value in generator function Python 2 | 39,734,786 | <p>I'm wondering how I can write a generator function that also has the option to return a value. In Python 2, you get the following error message if a generator function tries to return a value. <code>SyntaxError: 'return' with argument inside generator</code></p>
<p>Is it possible to write a function where I specify... | 0 | 2016-09-27T21:43:01Z | 39,735,017 | <p>Mandatory reading: <a href="http://stackoverflow.com/questions/1756096/understanding-generators-in-python">Understanding Generators in Python</a></p>
<p>Key information: </p>
<blockquote>
<p><code>yield</code> anywhere in a function makes it a generator.</p>
</blockquote>
<p>Function is marked as generator when... | 4 | 2016-09-27T22:01:12Z | [
"python"
] |
Join Python dataframe time series efficiently | 39,734,836 | <p>I have the following 2 dataframes with:</p>
<pre><code>day
date val
11740 2016-01-04 1.3970
11741 2016-01-05 1.3991
11742 2016-01-06 1.4084
11743 2016-01-07 1.4061
</code></pre>
<p>and</p>
<pre><code>df
Adj_Close Close Date High Low
182 12927.200195 129... | 2 | 2016-09-27T21:46:38Z | 39,735,030 | <pre><code>pd.concat([day.set_index('date'), df.set_index('Date')], axis=1)
>>>
val Adj_Close Close High \
2016-01-04 1.3970 12927.200195 12927.200195 12928.900391
2016-01-05 1.3991 12920.099609 12920.099609 12954.900391
2016-01-06 1.4084 12726.799805 12726.799... | 1 | 2016-09-27T22:02:09Z | [
"python",
"pandas",
"dataframe",
"time-series"
] |
Having output issues with python; loop totals and averages | 39,734,909 | <p>Having a few output issues with my nested loop, normally I use <code>break</code> to add some lines into my code or <code>print()</code></p>
<p>When I use <code>print()</code> within my code my output looks like I am typing totals on a new line all together that is not what I want</p>
<p>Following is a picture of ... | 1 | 2016-09-27T21:52:56Z | 39,735,038 | <blockquote>
<p><em>Following is a picture of my current output and where I need a blank line</em></p>
</blockquote>
<p>In order to get a blank line before <code>You have entered data for</code>, add <code>\n</code> at the start of the string. It represents new line. Hence your print statement should be as:</p>
<pr... | 0 | 2016-09-27T22:02:55Z | [
"python",
"loops",
"nested"
] |
Validating where the "@" symbol is in an email. Not validation of the email itself | 39,734,943 | <p>"it must contain an â@â symbol
which is NEITHER the first character nor the last character in the string."</p>
<p>So I have this assignment in my class and I can't for the life of me figure out how to make the boolean false for having it at the front or end of the email. This is what I have so far.</p>
<pre><c... | 0 | 2016-09-27T21:55:22Z | 39,735,142 | <p>With <code>s</code> as your string, you can do:</p>
<pre><code>not (s.endswith('@') or s.startswith('@')) and s.count('@')==1
</code></pre>
<p>Test:</p>
<pre><code>def valid(s):
return not (s.endswith('@') or s.startswith('@')) and s.count('@')==1
cases=('@abc','abc@','abc@def', 'abc@@def')
for case in case... | 2 | 2016-09-27T22:11:22Z | [
"python",
"python-3.x",
"character",
"email-validation"
] |
python, smart way of storing repeating entries | 39,734,944 | <p>I've log files containing all sort of junk as well as useful data.
I'm extracting some information by matching certain patterns and able to get in following format while reading the file line by line in python and applying some if statements </p>
<pre><code>job id: job#33ABC
Bin 1:30.86
Bin2: 30.86
job id: job#4... | 1 | 2016-09-27T21:55:25Z | 39,735,571 | <p>Putting the issue of IO aside, you could use a <a href="https://docs.python.org/3/library/collections.html#defaultdict-objects" rel="nofollow"><code>defaultdict</code></a> for easy logistics. Or a <code>defaultdict</code> of <code>defaultdict</code>s to be precise.</p>
<p>Your outer dict can have keys corresponding... | 2 | 2016-09-27T22:55:15Z | [
"python",
"file",
"dictionary",
"text"
] |
Plotting the Degree Distribution in Python iGraph | 39,734,974 | <p>I want to plot the histogram of a degree distribution, but using the iGraph's plot() on the degree_distribution gives just that...a plot, but with no title, no labels, no nothing, like this:
<a href="http://i.stack.imgur.com/zC6tl.png" rel="nofollow"><img src="http://i.stack.imgur.com/zC6tl.png" alt="enter image des... | 0 | 2016-09-27T21:57:21Z | 39,779,771 | <p>Igraph is not meant to be a fully functional plotting library - the plot that it can generate for degree distributions is meant only for quock "eyeballing". Use a dedicated plotting library like matplotlib. The <code>bins()</code> method of the degree distribution object may be used to extract the bin counts of the ... | 0 | 2016-09-29T20:49:59Z | [
"python",
"plot",
"igraph",
"cairo"
] |
Pandas crosstab, but with values from aggregation of third column | 39,735,068 | <p>Here is my problem:</p>
<pre><code>df = pd.DataFrame({'A': ['one', 'one', 'two', 'two', 'one'] ,
'B': ['Ar', 'Br', 'Cr', 'Ar','Ar'] ,
'C': [1, 0, 0, 1,0 ]})
</code></pre>
<p>I would like to generate something like output of <code>pd.crosstab</code> function, but values on the ... | 3 | 2016-09-27T22:05:10Z | 39,735,093 | <p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow">pivot_table()</a> method, which uses <code>aggfunc='mean'</code> per-default:</p>
<pre><code>In [46]: df.pivot_table(index='A', columns='B', values='C', fill_value=0)
Out[46]:
B Ar Br Cr
A
one 0... | 3 | 2016-09-27T22:07:06Z | [
"python",
"pandas",
"aggregate"
] |
Pandas crosstab, but with values from aggregation of third column | 39,735,068 | <p>Here is my problem:</p>
<pre><code>df = pd.DataFrame({'A': ['one', 'one', 'two', 'two', 'one'] ,
'B': ['Ar', 'Br', 'Cr', 'Ar','Ar'] ,
'C': [1, 0, 0, 1,0 ]})
</code></pre>
<p>I would like to generate something like output of <code>pd.crosstab</code> function, but values on the ... | 3 | 2016-09-27T22:05:10Z | 39,735,113 | <p>I like <code>groupby</code> and <code>unstack</code></p>
<pre><code>df.groupby(['A', 'B']).C.mean().unstack(fill_value=0)
</code></pre>
<p><a href="http://i.stack.imgur.com/ek6hU.png" rel="nofollow"><img src="http://i.stack.imgur.com/ek6hU.png" alt="enter image description here"></a></p>
| 2 | 2016-09-27T22:08:45Z | [
"python",
"pandas",
"aggregate"
] |
How to make an image move diagonally in pygame | 39,735,193 | <p>I've been taught how to move an image in pygame left, right, up and down. Our next task is to make the image move diagonally, but I don't understand how. This is my code so far: (sorry for the weird names)
Oh and also, I have two images in my code. I was wondering if there was a way that I could move both images wit... | 0 | 2016-09-27T22:17:53Z | 39,735,342 | <p>I think you should monitor key down and key up and then do the maths.</p>
<p>First set this :</p>
<pre><code>keys = {'right':False, 'up':False, 'left':False, 'down':False}
</code></pre>
<p>Then on event <code>KEYDOWN</code> set your <code>dict[key]</code> to <code>True</code> :</p>
<pre><code>if event.key == pyg... | 0 | 2016-09-27T22:32:26Z | [
"python",
"image",
"move"
] |
Can't get SVC Score function to work | 39,735,235 | <p>I am trying to run this machine learning platform and I get the following error: </p>
<pre><code>ValueError: X.shape[1] = 574 should be equal to 11, the number of features at training time
</code></pre>
<p>My Code:</p>
<pre><code>from pylab import *
from sklearn.svm import SVC
from sklearn.ensemble import RandomF... | 0 | 2016-09-27T22:22:08Z | 39,735,457 | <p>You are simply passing <strong>wrong object</strong> to score function, <a href="http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html#sklearn.ensemble.RandomForestClassifier.score" rel="nofollow">documentation</a> clearly states</p>
<blockquote>
<p>score(X, y, sample_weigh... | 0 | 2016-09-27T22:43:22Z | [
"python",
"numpy",
"machine-learning"
] |
Installing plyfile to Anaconda3 | 39,735,461 | <p>I run the following line from Spyder (Anaconda3):</p>
<pre><code> from plyfile import PlyData, PlyElement
</code></pre>
<p>and I get the following error message:</p>
<pre><code> Traceback (most recent call last):
File "<ipython-input-269-2c796028388e>", line 1, in <module>
from plyfile import PlyDat... | 0 | 2016-09-27T22:43:37Z | 39,735,681 | <p><code>pip install plyfile</code>, if something isn't in the default anaconda repository but still a pypi package you can pip install and conda will still track the package within your environment.</p>
| 0 | 2016-09-27T23:08:35Z | [
"python"
] |
OpenCV Installation failure due to QTKit | 39,735,485 | <p>I'm trying to install openCV for Python on my Mac but after going through a bunch of tutorials, none seem to work for me. These are the steps I took</p>
<ol>
<li>Installed <code>CMake</code></li>
<li>Downloaded the OpenCV library</li>
<li>Used <code>CMake</code> to generate the Unix Makefiles</li>
<li>Run <code>mak... | 1 | 2016-09-27T22:46:34Z | 39,735,943 | <p>I found a workaround by downloading the QTKit framework from <a href="https://github.com/phracker/MacOSX-SDKs/releases" rel="nofollow">this</a> repo then I simply merged my framework with the one included in the repo and continued with my installation process successfully.</p>
<p><strong>EDIT for Merging files</str... | 0 | 2016-09-27T23:43:41Z | [
"python",
"osx",
"opencv",
"opencv3.0"
] |
How to prompt user for two dates and output date difference in YY, M, DD? | 39,735,535 | <p>I have been searching for a clarified answer on this. I have read many threads and other websites about using datetime, but how can I build a simple program that prompts a user for two certain dates, and then calculate the difference between those dates? I am stuck on figuring out how to get the month and days.</p>
... | -1 | 2016-09-27T22:50:59Z | 39,736,907 | <p>You can use the <code>datetime</code> and <a href="http://dateutil.readthedocs.io/en/stable/index.html" rel="nofollow"><code>dateutil</code></a> modules. <code>datetime</code> is in the Python standard library, however, <code>dateutil</code> is 3rd party - it can be installed with pip.</p>
<pre><code>from datetime ... | 0 | 2016-09-28T02:04:13Z | [
"python",
"datetime",
"difference"
] |
Could not browse django site | 39,735,541 | <p>I'm trying to follow the the django <a href="https://docs.djangoproject.com/en/1.10/intro/tutorial01/" rel="nofollow">tutorial</a> but when when I get to the <code>python manage.py runserver</code> step, I can't browse <a href="http://127.0.0.1:8000/" rel="nofollow">http://127.0.0.1:8000/</a> in chrome or IE. But wh... | 0 | 2016-09-27T22:51:31Z | 39,735,592 | <p>Since you say you use wget in bash I'll assume you aren't using windows, so maybe it's another machine.</p>
<p>When you tell django to listen on <code>127.0.0.1</code> it will only accept local connections.</p>
<p>Now to open django to everyone you'll have to run it as such :</p>
<pre><code>python manage.py runse... | 2 | 2016-09-27T22:58:21Z | [
"python",
"django",
"virtualenv"
] |
Selenium iterating over paginator: optimization | 39,735,573 | <p>I have a website with a paginator in it. Each page shows 32 links and I get each of them and store them in separate files in a folder. I'm using the Firefox driver from Selenium in Python.</p>
<p>The procedure is basically:</p>
<pre><code>get the 32 elements
for element in elements:
open new file and save elem... | 0 | 2016-09-27T22:55:34Z | 39,736,441 | <p>A few suggestions...</p>
<ol>
<li><p>You have a lot of nested <code>.find_elements_*</code> at the start. You should be able to craft a single find that gets the elements you are looking for. From the site and your code, it looks like you are getting codes that look like, "MC1595226". If you grab one of these MC co... | 1 | 2016-09-28T00:57:22Z | [
"python",
"selenium",
"pagination"
] |
Adding lazy constraint in python-Gurobi interface | 39,735,659 | <p>I am trying to add some lazy constraints to the first stage of a stochastic programming problem. For example, the optimal solution shows me that locations 16 and 20 are chosen together which I don't want to so I want to add a lazy constraint as follows:</p>
<pre><code> First Stage
x1 + x2 + ... + x40 = 5
... | 1 | 2016-09-27T23:06:33Z | 39,757,166 | <p>In your code, the test </p>
<pre><code>if sol[16] + sol[20] == 2:
</code></pre>
<p>is comparing the sum of two floating point numbers with an integer using equality. Even if you declare decision variables to be integer, the solution values are floating point numbers. The floating point numbers don't ev... | 1 | 2016-09-28T20:34:27Z | [
"python",
"lazy-evaluation",
"gurobi"
] |
Binarize a float64 Pandas Dataframe in Python | 39,735,676 | <p>I've got a Panda DF with various columns (each indicating the frequency of a word in a corpus). Each row corresponds to a document and each is of type float64. </p>
<p>for example:</p>
<pre><code>word1 word2 word3
0.0 0.3 1.0
0.1 0.0 0.5
etc
</code></pre>
<p>I want to Binarize this and instead of the freq... | 3 | 2016-09-27T23:08:17Z | 39,735,754 | <p>Code:</p>
<pre><code>import numpy as np
import pandas as pd
""" create some test-data """
random_data = np.random.random([3, 3])
random_data[0,0] = 0.0
random_data[1,2] = 0.0
df = pd.DataFrame(random_data,
columns=['A', 'B', 'C'], index=['first', 'second', 'third'])
print(df)
""" binarize """
threshold = l... | 0 | 2016-09-27T23:19:33Z | [
"python",
"pandas",
"dataframe"
] |
Binarize a float64 Pandas Dataframe in Python | 39,735,676 | <p>I've got a Panda DF with various columns (each indicating the frequency of a word in a corpus). Each row corresponds to a document and each is of type float64. </p>
<p>for example:</p>
<pre><code>word1 word2 word3
0.0 0.3 1.0
0.1 0.0 0.5
etc
</code></pre>
<p>I want to Binarize this and instead of the freq... | 3 | 2016-09-27T23:08:17Z | 39,735,878 | <p>Casting to boolean will result in <code>True</code> for anything that is not zero — and <code>False</code> for any zero entry. If you then cast to integer, you get ones and zeroes.</p>
<pre><code>import io
import pandas as pd
data = io.StringIO('''\
word1 word2 word3
0.0 0.3 1.0
0.1 0.0 0.5
''')
df =... | 4 | 2016-09-27T23:36:02Z | [
"python",
"pandas",
"dataframe"
] |
Binarize a float64 Pandas Dataframe in Python | 39,735,676 | <p>I've got a Panda DF with various columns (each indicating the frequency of a word in a corpus). Each row corresponds to a document and each is of type float64. </p>
<p>for example:</p>
<pre><code>word1 word2 word3
0.0 0.3 1.0
0.1 0.0 0.5
etc
</code></pre>
<p>I want to Binarize this and instead of the freq... | 3 | 2016-09-27T23:08:17Z | 39,736,116 | <p>I would have answered as @Alberto Garcia-Raboso answered but here is an alternative that is very quick and leverages the same idea.</p>
<p>Use <code>np.where</code></p>
<pre><code>pd.DataFrame(np.where(df, 1, 0), df.index, df.columns)
</code></pre>
<p><a href="http://i.stack.imgur.com/YE8F7.png" rel="nofollow"><i... | 2 | 2016-09-28T00:09:23Z | [
"python",
"pandas",
"dataframe"
] |
Binarize a float64 Pandas Dataframe in Python | 39,735,676 | <p>I've got a Panda DF with various columns (each indicating the frequency of a word in a corpus). Each row corresponds to a document and each is of type float64. </p>
<p>for example:</p>
<pre><code>word1 word2 word3
0.0 0.3 1.0
0.1 0.0 0.5
etc
</code></pre>
<p>I want to Binarize this and instead of the freq... | 3 | 2016-09-27T23:08:17Z | 39,860,720 | <p>Found an alternative way using Pandas Indexing.</p>
<p>This can be simply done by </p>
<pre><code>df[df>0] = 1
</code></pre>
<p>simple as that!</p>
| 0 | 2016-10-04T19:55:36Z | [
"python",
"pandas",
"dataframe"
] |
"Tuple index out of range" Error? | 39,735,686 | <p>I'm not sure what I'm doing wrong here, does anyone know? I keep getting an error that says "Tuple index out of range." I'm following a tutorial for school and I seem to be doing everything right, however I keep getting this error. Any help would be appreciated! Thank you so much.</p>
<pre><code>animal = input("Ent... | 0 | 2016-09-27T23:09:35Z | 39,735,732 | <p>In animalFormat, replace:</p>
<pre><code>{1}
</code></pre>
<p>With:</p>
<pre><code>{smallAnimal}
</code></pre>
<p>This change must be made in two places.</p>
<p>Since you are supplying arguments to <code>format</code> with keywords, there is nothing for <code>1</code> to refer to.</p>
<h3>Simpler example</h3>
... | 0 | 2016-09-27T23:16:07Z | [
"python",
"tuples"
] |
"Tuple index out of range" Error? | 39,735,686 | <p>I'm not sure what I'm doing wrong here, does anyone know? I keep getting an error that says "Tuple index out of range." I'm following a tutorial for school and I seem to be doing everything right, however I keep getting this error. Any help would be appreciated! Thank you so much.</p>
<pre><code>animal = input("Ent... | 0 | 2016-09-27T23:09:35Z | 39,735,735 | <p>You are mixing up formatting string by keywords and ordered data.</p>
<p>MCVE:</p>
<pre><code>s = "{0}{k}".format(k='something')
</code></pre>
<p>Exception:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
</code></pre>
<p>S... | 0 | 2016-09-27T23:16:58Z | [
"python",
"tuples"
] |
"Tuple index out of range" Error? | 39,735,686 | <p>I'm not sure what I'm doing wrong here, does anyone know? I keep getting an error that says "Tuple index out of range." I'm following a tutorial for school and I seem to be doing everything right, however I keep getting this error. Any help would be appreciated! Thank you so much.</p>
<pre><code>animal = input("Ent... | 0 | 2016-09-27T23:09:35Z | 39,735,743 | <p>This error is because you have <strong>named substitution</strong> (such as <code>.. very large {animal} ..</code>) as well as <strong>positional substitution</strong> (such as <code>At that moment, the {1} knew ..</code>).</p>
<p>Consider passing something like:</p>
<pre><code>animalFormat.format("Replacement for... | 0 | 2016-09-27T23:17:26Z | [
"python",
"tuples"
] |
How can I filter exported tickets from database using Django? | 39,735,803 | <p>I am working on a Django based web project where we handle tickets based requests. I am working on an implementation where I need to export all closed tickets everyday.</p>
<p>My ticket table database looks like,</p>
<pre><code>-------------------------------------------------
| ID | ticket_number | ticket_data | ... | 0 | 2016-09-27T23:25:55Z | 39,735,884 | <p>you can do without <code>is_exported</code> field: </p>
<pre><code>exported_tickets = TicketsExported.objects.all()
unexported_tickets = Tickets.object.exclude(id__in=[et.id for et in exported_tickets])
</code></pre>
<p>but <code>is_exported</code> field can be useful somewhere else </p>
| 2 | 2016-09-27T23:36:54Z | [
"python",
"mysql",
"django"
] |
How can I filter exported tickets from database using Django? | 39,735,803 | <p>I am working on a Django based web project where we handle tickets based requests. I am working on an implementation where I need to export all closed tickets everyday.</p>
<p>My ticket table database looks like,</p>
<pre><code>-------------------------------------------------
| ID | ticket_number | ticket_data | ... | 0 | 2016-09-27T23:25:55Z | 39,735,953 | <p>Per my comment- you could probably save yourself a bunch of trouble and just add another BooleanField for <code>'is_exported'</code> instead of having a separate model assuming there aren't fields specific to TicketExported. </p>
<p>@doniyor's answer gets you the queryset you're looking for though. In response to y... | 1 | 2016-09-27T23:44:54Z | [
"python",
"mysql",
"django"
] |
Pycharm: Type hint list of items | 39,735,843 | <p>My question is different because I made a mistake using type hint.</p>
<p>I found a weird type hinging in pycharm:
<a href="http://i.stack.imgur.com/KFi0B.png" rel="nofollow"><img src="http://i.stack.imgur.com/KFi0B.png" alt="enter image description here"></a></p>
<p><code>Example</code> is my own class. But I gue... | 3 | 2016-09-27T23:31:25Z | 39,735,879 | <p>Accoring to <a href="https://www.python.org/dev/peps/pep-0484/">official PEP</a> to denote list of objects you should use <code>typing.List</code>, not <code>list</code> builtin.</p>
<pre><code>from typing import List
class Something:
pass
def f(seq: List[Something]): # no warning
for o in seq:
... | 6 | 2016-09-27T23:36:35Z | [
"python",
"pycharm"
] |
Pycharm: Type hint list of items | 39,735,843 | <p>My question is different because I made a mistake using type hint.</p>
<p>I found a weird type hinging in pycharm:
<a href="http://i.stack.imgur.com/KFi0B.png" rel="nofollow"><img src="http://i.stack.imgur.com/KFi0B.png" alt="enter image description here"></a></p>
<p><code>Example</code> is my own class. But I gue... | 3 | 2016-09-27T23:31:25Z | 39,736,086 | <p>Åukasz explained how to correct your code. I'll explain why the error message says what it does.</p>
<p><code>list</code> defines <code>__getitem__</code>, true, but that isn't what the error message is complaining about. The error message is saying that <code>type</code> itself, which is the <code>list</code> <em... | 1 | 2016-09-28T00:05:49Z | [
"python",
"pycharm"
] |
Cant get inner loops to add up properly | 39,735,921 | <p>My issue is with my user input totals for rainfall not adding up properly</p>
<p>my assumption is that it is not adding the 1st month in when asked on multiple years as </p>
<p><img src="http://i.stack.imgur.com/XKqhg.jpg" alt="problem explained"></p>
<pre><code>def main():
#define accumulators
monthRain... | 0 | 2016-09-27T23:41:04Z | 39,735,974 | <p>Take <code>total = 0</code> out of the for loop. Every time you enter the loop, it sets <code>total</code> to zero. Take it out and put it before the for loop. I think that will fix it.</p>
<p>Let me know...</p>
| 2 | 2016-09-27T23:48:45Z | [
"python",
"loops",
"nested"
] |
Cant get inner loops to add up properly | 39,735,921 | <p>My issue is with my user input totals for rainfall not adding up properly</p>
<p>my assumption is that it is not adding the 1st month in when asked on multiple years as </p>
<p><img src="http://i.stack.imgur.com/XKqhg.jpg" alt="problem explained"></p>
<pre><code>def main():
#define accumulators
monthRain... | 0 | 2016-09-27T23:41:04Z | 39,735,985 | <p>At the start of every year entry, you zero <code>total</code>, then print <code>total</code> at the end. The 64 you see is actually the 2nd year's rainfall, and the 1st year is being thrown out.</p>
| 1 | 2016-09-27T23:50:01Z | [
"python",
"loops",
"nested"
] |
Cant get inner loops to add up properly | 39,735,921 | <p>My issue is with my user input totals for rainfall not adding up properly</p>
<p>my assumption is that it is not adding the 1st month in when asked on multiple years as </p>
<p><img src="http://i.stack.imgur.com/XKqhg.jpg" alt="problem explained"></p>
<pre><code>def main():
#define accumulators
monthRain... | 0 | 2016-09-27T23:41:04Z | 39,735,988 | <p>I think you shouldn't be resetting the <code>total</code> for each year. That's why you were missing a year's worth of data. The total rainfall in the example you provided was <code>131</code> and the average is approximately <code>5.46</code>. I ran your example and got the following.</p>
<pre><code>Enter the numb... | 0 | 2016-09-27T23:50:20Z | [
"python",
"loops",
"nested"
] |
Cant get inner loops to add up properly | 39,735,921 | <p>My issue is with my user input totals for rainfall not adding up properly</p>
<p>my assumption is that it is not adding the 1st month in when asked on multiple years as </p>
<p><img src="http://i.stack.imgur.com/XKqhg.jpg" alt="problem explained"></p>
<pre><code>def main():
#define accumulators
monthRain... | 0 | 2016-09-27T23:41:04Z | 39,735,994 | <p>The 64 is actually the result of your second year.</p>
<p>Because you have <code>total = 0</code> inside your loop, it is <strong>rest</strong> after every year. Thus the values of the first year are overwritten by the values of the second year.</p>
<p>Take <code>total=0</code> outside of the loop. That should fix... | 0 | 2016-09-27T23:51:02Z | [
"python",
"loops",
"nested"
] |
Unable to ftp a file using python ftplib, but successful using curl | 39,735,937 | <p>I receive the following error when uploading a small text file to an ftp site when using python's ftplib:</p>
<pre><code> File "ftpuploader.py", line 13, in uploadFilePath
ftp.storbinary("STOR {}".format(filepath), file)
File "/usr/lib64/python2.7/ftplib.py", line 471, in storbinary
conn = self.trans... | 0 | 2016-09-27T23:42:39Z | 39,763,819 | <p>You are passing a path to a local path to the <code>STOR</code> command (the same path you use with the <code>open(filepath, 'rb')</code>).</p>
<p>While with the CURL, you do not specify any path to the remote file. So the file gets uploaded to the current FTP working directory.</p>
<p>As already suggested in the ... | 2 | 2016-09-29T07:17:50Z | [
"python",
"curl",
"ftp"
] |
Simple data transmission from multiple Arduinos (client) to Raspberry pi (server) wirelessly | 39,735,991 | <p>I'm building a project where I have multiple Arduinos, each having a temperature sensor and a [input wireless transmission method here]. </p>
<p>This data would be received by a controller, a Raspberry pi, which would act as the server: call to Arduino, collect the data, and store it. This data would be accessible ... | 0 | 2016-09-27T23:50:25Z | 39,738,705 | <p>Cheap, low power and tiny row data? </p>
<p>I suggest you to use nRF 2.4GHz transceiver module. It may look some old school way but will meet with your requirements. </p>
<p>It consumes 0.9 nA while deep-sleep mode and ~10mA for just transmission.</p>
<p>Also it is easy to program and due to its connectionless ar... | 0 | 2016-09-28T05:27:12Z | [
"python",
"bluetooth",
"arduino",
"wireless",
"transmission"
] |
Exception: Cannot find PyQt5 plugin directories when using Pyinstaller despite PyQt5 not even being used | 39,736,000 | <p>A month ago I solved my applcation freezing issues for Python 2.7 as you can see <a href="http://stackoverflow.com/questions/39135408/using-pyinstaller-on-parmap-causes-a-tkinter-matplotlib-import-error-why">here</a>. I have since adapted my code to python 3.5 (using Anaconda) and it appears to be working. couldn't... | 2 | 2016-09-27T23:51:55Z | 39,823,782 | <p>Uninstall Anaconda and everything works... I conclude that you simply cannot have Anaconda installed and use the standard Python 3.5 compiler at the same time if you're using Pyinstaller. Maybe <a href="http://stackoverflow.com/questions/39728108/running-pyinstaller-after-anaconda-install-results-in-importerror-no-m... | 0 | 2016-10-03T02:19:36Z | [
"python",
"python-2.7",
"python-3.x",
"pyinstaller"
] |
Python : Extract one string from 100 lines of text | 39,736,110 | <ol>
<li><p>I need to extract a particular string from 100 lines of log data. I
tried split and then tried to get the needed string but couldn't
succeed. Any suggestions/help appreciated. Thanks!</p>
<p>In the log below, I would like to extract the highlighted part, that
is
<strong>zqn.2005- 04.com.sanblaze:virtualun.... | -1 | 2016-09-28T00:08:30Z | 39,736,155 | <p>Looks like the string is in dictionary format (correct me if I'm wrong), so you could try converting it to one. Then you won't need regex.</p>
<pre><code>import ast
your_dict = ast.literal_eval(your_string)
</code></pre>
<p>Then what you want would be: </p>
<pre><code>your_dict['status']['initiator0_iqn']
</code>... | 1 | 2016-09-28T00:13:48Z | [
"python",
"regex",
"logging"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.