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 |
|---|---|---|---|---|---|---|---|---|---|
Why is the maximum recursion depth in python 1000? | 40,115,683 | <p>I was curious about what the MRD (maximum recursion depth) is in python, so i wrote this:</p>
<pre><code>def call(n):
print (n)
return call(n+1)
call(1)
</code></pre>
<p>The end result was 979, wich is a peculiar number for me. I could not find anywhere why this number is the standard. As i am a self taug... | 1 | 2016-10-18T18:39:55Z | 40,115,931 | <p>Here is a better test:</p>
<pre><code>n = 0
def test_recursion_limit():
def call():
global n
n += 1
call()
try:
call()
except RuntimeError:
print(n)
test_recursion_limit()
</code></pre>
<p>If you put it in <code>spam.py</code> and execute that, it should return... | 4 | 2016-10-18T18:53:22Z | [
"python"
] |
Cassandra auto-complete does not work | 40,115,699 | <p>I have a problem with the auto-complete within Cassandra 3.9 client "cqlsh", I don't know why? I did an update my brew command on MacOS Sierra. I suppose this problem is for a python update, but how it's related?</p>
<p>I tried to execute the tests:</p>
<pre><code>$ cd apache-cassandra-3.9/pylib/cqlshlib/test
$ py... | 0 | 2016-10-18T18:40:46Z | 40,115,820 | <p>you don't have <code>__init__.py</code> in your package folder</p>
| 0 | 2016-10-18T18:46:17Z | [
"java",
"python",
"cassandra",
"cqlsh"
] |
Maintaining accurate f.name through rename operation in Python w/o dropping lock | 40,115,707 | <p>I have a file which I'm atomically replacing in Python, while trying to persistently retain a lock.</p>
<p>(Yes, I'm well aware that this will wreak havoc on any other programs waiting for a lock on the file unless they check for the directory entry pointing to a new inode after they actually receive their lock; th... | 0 | 2016-10-18T18:41:02Z | 40,116,142 | <p>If your code is under Linux, here's a way to get filename from a file descriptor:</p>
<pre><code>...
f = replace_file(f, "new string")
print os.readlink('/proc/self/fd/%d' % f.fileno())
</code></pre>
<p>Reference: <a href="http://stackoverflow.com/a/1189582/2644759">http://stackoverflow.com/a/1189582/2644759</a></... | 0 | 2016-10-18T19:06:54Z | [
"python"
] |
Maintaining accurate f.name through rename operation in Python w/o dropping lock | 40,115,707 | <p>I have a file which I'm atomically replacing in Python, while trying to persistently retain a lock.</p>
<p>(Yes, I'm well aware that this will wreak havoc on any other programs waiting for a lock on the file unless they check for the directory entry pointing to a new inode after they actually receive their lock; th... | 0 | 2016-10-18T18:41:02Z | 40,117,055 | <p>A simplicity-focused solution is to use an entirely separate lockfile with a different name (ie. <code><filename>.lck</code>).</p>
<ul>
<li>Using a separate lockfile means that the code performing the write-and-rename operation doesn't need to be involved in locking at all, as the rename operation doesn't int... | 0 | 2016-10-18T20:01:32Z | [
"python"
] |
MatPlotLib is very slow in python | 40,115,725 | <pre><code>import matplotlib
matplotlib.use('TkAgg')
def generate_graph(self,subject,target,filename):
x_data = range(0, len(self.smooth_hydro))
mslen = len([i[1] for i in self.master_seq.items()][0])
diff=(mslen-len(self.smooth_hydro))/2
x1_data = range(0,len(self.smooth_groups.items()[0][-1]))
x2_... | 0 | 2016-10-18T18:41:50Z | 40,116,097 | <p>I found this answer in another <a href="http://stackoverflow.com/a/11093027/5104387">post</a>. All credit to <a href="http://stackoverflow.com/users/643629/luke">Luke</a>.</p>
<blockquote>
<p>Matplotlib makes great publication-quality graphics, but is not very
well optimized for speed. There are a variety of py... | 1 | 2016-10-18T19:04:05Z | [
"python",
"matplotlib"
] |
Deleting cookies and changing user agent in Python 3+ without Mechanize | 40,115,727 | <p>How do I delete cookies from a web browser and change the user agent in Python 3+ without using mechanize? I'm not going to be accessing the web through Python, I would just like my browser (Firefox or Chrome) to delete cookies and change my user agent for example at every startup (I can do the startup bit, just not... | 0 | 2016-10-18T18:41:51Z | 40,135,540 | <p>set the <code>Expires</code> attribute to a date in the past (like Epoch):</p>
<pre><code>Set-Cookie: name=val; expires=Thu, 01 Jan 1970 00:00:00 GMT
</code></pre>
<p>Read more here:
<a href="http://stackoverflow.com/questions/5285940/correct-way-to-delete-cookies-server-side">Correct way to delete cookies server-... | 0 | 2016-10-19T15:19:21Z | [
"python",
"python-3.x",
"cookies",
"user-agent"
] |
If a character in string is found before another character | 40,115,732 | <p>I'm trying to figure out a way to see if a character in a string before another one to get and output. Say:</p>
<pre><code>v="Hello There"
x=v[0]
if "Hello" in x:
print("V consists of '"'Hello'"'")
if "There" in x:
print("Hello comes before There)
if "There" in x:
print("V consists of... | 0 | 2016-10-18T18:42:00Z | 40,115,804 | <p>For string 's', <code>s.find(substring)</code> returns the lowest index of <code>s</code> that begins <code>substring</code></p>
<pre><code>if s.find('There') < s.find('Hello'):
print('There comes before Hello')
</code></pre>
| 3 | 2016-10-18T18:45:24Z | [
"python",
"string",
"variables",
"if-statement"
] |
If a character in string is found before another character | 40,115,732 | <p>I'm trying to figure out a way to see if a character in a string before another one to get and output. Say:</p>
<pre><code>v="Hello There"
x=v[0]
if "Hello" in x:
print("V consists of '"'Hello'"'")
if "There" in x:
print("Hello comes before There)
if "There" in x:
print("V consists of... | 0 | 2016-10-18T18:42:00Z | 40,115,908 | <pre><code>v="Hello There".split() #splitting the sentence into a list of words ['Hello', 'There'], notice the order stays the same which is important
#got rid of your x = v[0] since it was pointless
if "Hello" in v[0]: #v[0] == 'Hello... | 0 | 2016-10-18T18:51:38Z | [
"python",
"string",
"variables",
"if-statement"
] |
If a character in string is found before another character | 40,115,732 | <p>I'm trying to figure out a way to see if a character in a string before another one to get and output. Say:</p>
<pre><code>v="Hello There"
x=v[0]
if "Hello" in x:
print("V consists of '"'Hello'"'")
if "There" in x:
print("Hello comes before There)
if "There" in x:
print("V consists of... | 0 | 2016-10-18T18:42:00Z | 40,116,325 | <p>Assuming your needs are as simple as you have implied in the question details, then this should do -</p>
<pre><code>v = "Hello There"
# Change s1 and s2 as you please depending on your actual need.
s1 = "Hello"
s2 = "There"
if s1 in v and s2 in v:
# Refer - https://docs.python.org/2/library/string.html#string... | 0 | 2016-10-18T19:19:05Z | [
"python",
"string",
"variables",
"if-statement"
] |
Python: Setting multiple continuous timeouts | 40,115,841 | <p>I want to have some kind of server that receives events (i.e using sockets), and each event has a different ID (i.e dst port number). </p>
<p>Is there a way that from the moment I see the first packet of an specific ID, I start some kind of timeout (i.e, 1ms), and if in that time nothing else with the same ID is re... | 1 | 2016-10-18T18:47:48Z | 40,116,586 | <p>See the <a href="https://docs.python.org/3/library/sched.html" rel="nofollow"><code>sched</code></a> built-in module, which has a scheduler.</p>
<p>You can construct a new scheduler instance, then use <code>scheduler.enter</code> to schedule a function to be called after a delay; and if you receive a message within... | 1 | 2016-10-18T19:33:15Z | [
"python",
"sockets",
"timeout",
"signals"
] |
Python: Setting multiple continuous timeouts | 40,115,841 | <p>I want to have some kind of server that receives events (i.e using sockets), and each event has a different ID (i.e dst port number). </p>
<p>Is there a way that from the moment I see the first packet of an specific ID, I start some kind of timeout (i.e, 1ms), and if in that time nothing else with the same ID is re... | 1 | 2016-10-18T18:47:48Z | 40,117,677 | <p>Sounds like a job for <code>select</code>. As you are using sockets, you have a socket descriptor for a client (presumably one for each client but as long as you have one, it works). So you either want to wait until a packet arrives on one of your sockets or until a timeout occurs. This is exactly what <code>select<... | 2 | 2016-10-18T20:40:03Z | [
"python",
"sockets",
"timeout",
"signals"
] |
Pyspark update two columns using one when statement? | 40,115,869 | <p>So I am using <code>df.Withcolumn()</code> in PySpark to create a column and using <code>F.when()</code> to specify the criteria as to when the column should be updated.</p>
<pre><code>df = df.withColumn('ab', F.when(df['text']=="0", 1).otherwise(0))
</code></pre>
<p>Basically I am updating the column to be '1' if... | 0 | 2016-10-18T18:49:20Z | 40,116,311 | <p>It is not possible. You can only created struct:</p>
<pre><code>>>> from pyspark.sql.functions import *
>>> df.withColumn('ab', F.when(df['text']=="0" , struct(1, "foo")).otherwise(struct(0, "bar")))
</code></pre>
| 0 | 2016-10-18T19:18:08Z | [
"python",
"pyspark"
] |
changing variable between flask server and a multiprocessing | 40,115,875 | <p>I have a flask server running and multiprocessing running a loop working. I need to be able to change a variable in the flask server and have it to be used in an <code>if</code> statement in the loop. Here is my code, I removed a lot of things that I thought was not important to show.</p>
<p>The variable that needs... | -1 | 2016-10-18T18:49:45Z | 40,117,893 | <p>Multiprocessing efectivelly runs the target function in another process - which also means that is an entirely new Python program - this otherprogram won't share any variables with the parent program. That is why your use of a global variable to communicate with your secondary loop won't work in this way: the <code>... | 0 | 2016-10-18T20:53:48Z | [
"python",
"flask",
"python-multiprocessing"
] |
Append each line in file | 40,116,025 | <p>I want to append each line in file in <code>python</code> For example:</p>
<p><strong>File.txt</strong></p>
<pre><code>Is it funny?
Is it dog?
</code></pre>
<p><strong>Expected Result</strong></p>
<pre><code>Is it funny? Yes
Is it dog? No
</code></pre>
<p>Assume that YES, No is given. I am doing in this way:</p... | 2 | 2016-10-18T19:00:14Z | 40,116,309 | <p>Here is a solution that copies existing file content to a temp file. Modifies it as per needs. Then writes back to original file.
Inspiration from <a href="http://stackoverflow.com/questions/17646680/writing-back-into-the-same-file-after-reading-from-the-file">here</a></p>
<pre><code>import tempfile
filename =... | 1 | 2016-10-18T19:17:58Z | [
"python",
"python-3.x"
] |
Append each line in file | 40,116,025 | <p>I want to append each line in file in <code>python</code> For example:</p>
<p><strong>File.txt</strong></p>
<pre><code>Is it funny?
Is it dog?
</code></pre>
<p><strong>Expected Result</strong></p>
<pre><code>Is it funny? Yes
Is it dog? No
</code></pre>
<p>Assume that YES, No is given. I am doing in this way:</p... | 2 | 2016-10-18T19:00:14Z | 40,116,338 | <p>You can write to a <em>tempfile</em> then replace the original:</p>
<pre><code>from tempfile import NamedTemporaryFile
from shutil import move
data = ["Yes", "No"]
with open("in.txt") as f, NamedTemporaryFile("w",dir=".", delete=False) as temp:
# pair up lines and each string
for arg, line in zip(data, f):
... | 3 | 2016-10-18T19:19:52Z | [
"python",
"python-3.x"
] |
python pandas - how can I map values in 1 dataframe to indices in another without looping? | 40,116,065 | <p>I have 2 dataframes - "df_rollmax" is a derivative of "df_data" with the same shape. I am attempting to map the values of df_rollmax back to df_data and create a third df (df_maxdates) which contains the dates at which each value in df_rollmax originally showed up in df_data.</p>
<pre><code>list1 = [[21,101],[22,11... | 1 | 2016-10-18T19:02:27Z | 40,117,126 | <p>You can use <a href="http://stackoverflow.com/a/40101614/5741205">this BrenBarn's solution</a>:</p>
<pre><code>W = 5 # window size
df = pd.DataFrame(columns=df_data.columns, index=df_data.index[W-1:])
for col in df.columns.tolist():
df[col] = df_data.index[df_data[col].rolling(W)
... | 1 | 2016-10-18T20:05:20Z | [
"python",
"pandas",
"dataframe",
"duplicates",
"mapping"
] |
Sum values in dictionary | 40,116,099 | <p>I'm working with an Excel file and openpyxl.</p>
<p>Below is sample data:</p>
<pre><code>Name Value
Amy1 4
Bob1 5
Bob1 5
Bob2 8
Chris1 7
Chris2 3
Chris3 6
Chris3 6
Chris3 6
</code></pre>
<p>Using the for loop below, I grab the value associated with each unique name.</p>
<pre><code>for rowNum ... | 0 | 2016-10-18T19:04:12Z | 40,116,699 | <p>You can use the <code>get()</code> method to set a default value for a key and then add to it that way.</p>
<p>Since all of your keys are in the format name#, you can get the end result you want like this:</p>
<pre><code>mergedResult = dict()
for name in startingDict:
mergedResult[name[:-1]] = mergedResult.ge... | 0 | 2016-10-18T19:39:38Z | [
"python",
"list",
"dictionary",
"sum"
] |
Sum values in dictionary | 40,116,099 | <p>I'm working with an Excel file and openpyxl.</p>
<p>Below is sample data:</p>
<pre><code>Name Value
Amy1 4
Bob1 5
Bob1 5
Bob2 8
Chris1 7
Chris2 3
Chris3 6
Chris3 6
Chris3 6
</code></pre>
<p>Using the for loop below, I grab the value associated with each unique name.</p>
<pre><code>for rowNum ... | 0 | 2016-10-18T19:04:12Z | 40,116,710 | <p>If <code>name = sheet.cell(row = rowNum, column = 13).value</code></p>
<p>And <code>value = sheet.cell(row = rowNum, column = 26).value</code></p>
<p>Edited according to your comments:</p>
<pre><code>from collections import defaultdict
people = defaultdict(int)
category = defaultdict(int)
for rowNum in range(2... | 0 | 2016-10-18T19:40:15Z | [
"python",
"list",
"dictionary",
"sum"
] |
Get row with maximum value from groupby with several columns in PySpark | 40,116,117 | <p>I have a dataframe similar to </p>
<pre><code>from pyspark.sql.functions import avg, first
rdd = sc.parallelize(
[
(0, "A", 223,"201603", "PORT"),
(0, "A", 22,"201602", "PORT"),
(0, "A", 22,"201603", "PORT"),
(0, "C", 22,"201605", "PORT"),
(0, "D", 422,"201601", "DOCK"),
(0, "D", 422,"201602", "DOCK"),
(0, "... | 0 | 2016-10-18T19:05:16Z | 40,117,220 | <p>Based on your expected output, it seems you are only grouping by <code>id</code> and <code>ship</code> - since you already have distinct values in <code>grouped</code> - and consequently drop duplicate elements based on the columns <code>id</code>, <code>ship</code> and <code>count</code>, sorted by <code>type</code... | 1 | 2016-10-18T20:10:17Z | [
"python",
"apache-spark",
"pyspark"
] |
List index out of range(line 5) | 40,116,124 | <p>Code:</p>
<pre><code>selObj = mc.ls(sl=True)
sizeSel = len(selObj)
for a in range(sizeSel):
if a < sizeSel:
mc.parent( selObj[a +1], selObj[a])
</code></pre>
| -4 | 2016-10-18T19:05:34Z | 40,116,204 | <p>I don't know enough about your code to test, but its clear that since <code>a</code> counts to the end of your list, <code>a+1</code> overflows. Just reduce the index counter by one. And no need to check it twice.</p>
<pre><code>selObj = mc.ls(sl=True)
sizeSel = len(selObj)
for a in range(sizeSel-1):
mc.parent(... | 0 | 2016-10-18T19:11:12Z | [
"python"
] |
python: could not convert string to float | 40,116,150 | <p>im submitting this code..</p>
<pre><code>a = float(input())
b = float(input())
c = float(input())
if abs(b - c) < a < (b + c) and abs(a - c) < b < (a + c) and abs(a - b) < c < (a + b):
print("Perimetro = " + str(a + b + c))
else:
print("Area = " + str(((a + b) * c) / 2))
</code></pre>
<p... | -2 | 2016-10-18T19:07:27Z | 40,116,182 | <p>The issue is that you are entering all the three values at once. Add one value and then press enter. For example:</p>
<pre><code>>>> a = float(input())
6.0
>>> b = float(input())
4.0
>>> c = float(input())
2.0
>>> a, b, c
(6.0, 4.0, 2.0)
</code></pre>
<p>OR, get the single strin... | 0 | 2016-10-18T19:09:44Z | [
"python",
"string",
"input",
"floating-point"
] |
xgboost sklearn wrapper value 0for Parameter num_class should be greater equal to 1 | 40,116,215 | <p>I am trying to use the <code>XGBClassifier</code> wrapper provided by <code>sklearn</code> for a multiclass problem. My classes are [0, 1, 2], the objective that I use is <code>multi:softmax</code>. When I am trying to fit the classifier I get </p>
<blockquote>
<p>xgboost.core.XGBoostError: value 0for Parameter n... | 0 | 2016-10-18T19:11:39Z | 40,123,113 | <p>You shouldn't have to set this manually, probably what's happening is that the dataset you're training only contains one label, e.g. maybe all 0's.</p>
| 0 | 2016-10-19T05:45:01Z | [
"python",
"scikit-learn",
"xgboost"
] |
Sum of several columns from a pandas dataframe | 40,116,219 | <p>So say I have the following table:</p>
<pre><code>In [2]: df = pd.DataFrame({'a': [1,2,3], 'b':[2,4,6], 'c':[1,1,1]})
In [3]: df
Out[3]:
a b c
0 1 2 1
1 2 4 1
2 3 6 1
</code></pre>
<p>I can sum a and b that way:</p>
<pre><code>In [4]: sum(df['a']) + sum(df['b'])
Out[4]: 18
</code></pre>
<p>Howeve... | 3 | 2016-10-18T19:11:50Z | 40,116,249 | <p>I think you can use double <code>sum</code> - first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sum.html" rel="nofollow"><code>DataFrame.sum</code></a> create <code>Series</code> of sums and second <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sum.ht... | 4 | 2016-10-18T19:13:55Z | [
"python",
"pandas",
"dataframe"
] |
Django "module 'portal.views' has no attribute 'MyAccount'" | 40,116,421 | <p>I just made another class based view in Django and it apparently isn't being imported in urls.py, which is confusing. I even simplified it by making the view just a def.</p>
<p>views.py:</p>
<pre><code>from django.shortcuts import render
from django.views import generic
from django.contrib.auth.decorators import l... | 0 | 2016-10-18T19:23:38Z | 40,118,461 | <p>MyProfile != MyAccount. Thanks Daniel, I don't know why I didn't see that.</p>
<p>-gns</p>
| 0 | 2016-10-18T21:33:31Z | [
"python",
"django"
] |
Having trouble rewriting code to list comprehension for image rotation in python | 40,116,437 | <p>So after not finding my problem here on stackoverflow, which is how to rewrite a for-loop to a list comprehension, where values are inserted I have to ask now if it possible to rewrite this code:</p>
<pre><code>rotate = np.zeros((w,h,c), np.uint8) # create an empty image filled with zeros turned 90°
for y in xran... | 0 | 2016-10-18T19:24:27Z | 40,116,496 | <pre><code>rotate = np.array([[img[y][x] for y in xrange(h)] for x in xrange(w)])
</code></pre>
| 3 | 2016-10-18T19:27:55Z | [
"python",
"opencv",
"numpy",
"list-comprehension"
] |
Django -- Form Field on change | 40,116,461 | <p>I'm using Django forms to display data.</p>
<p>There is a HTML select field - which has 2 options a) teachers and b) Students.</p>
<p>Django forms:- </p>
<pre><code>self.fields['account_type'].choices = [('student','Student'),('teacher', 'Teacher')]
self.helper.layout = Layout(
HTML('''<h5... | 2 | 2016-10-18T19:25:44Z | 40,116,778 | <p>It looks like you are using Django Crispy forms and not plain Django forms.</p>
<p>If you want to set the <code>onchange</code> attribute, you should be able to just pass that as a keyword argument, as <a href="https://django-crispy-forms.readthedocs.io/en/latest/layouts.html#layout-objects-attributes" rel="nofollo... | 0 | 2016-10-18T19:44:13Z | [
"python",
"django"
] |
Python subprocess hangs | 40,116,548 | <p>I'm executing the following subprocess...</p>
<p><code>p.call(["./hex2raw", "<", "exploit4.txt", "|", "./rtarget"])</code></p>
<p>...and it hangs.</p>
<p>But if I execute <code>kmwe236@kmwe236:~/CS485/prog3/target26$ ./hex2raw < exploit4.txt | ./rtarget</code> then it executes fine. Is there something wrong... | 0 | 2016-10-18T19:31:14Z | 40,116,619 | <p>Since you're using redirection and piping, you have to enable <code>shell=True</code></p>
<pre><code>sp.call(["./hex2raw", "<", "exploit4.txt", "|", "./rtarget"],shell=True)
</code></pre>
<p>but it would be much cleaner to use <code>Popen</code> on both executables and feeding the contents of <code>exploit4.txt... | 2 | 2016-10-18T19:34:55Z | [
"python",
"subprocess"
] |
PYSPARK : How to work with dataframes? | 40,116,603 | <p>I have the following dataframes</p>
<pre><code>from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.sql.functions import *
sc = SparkContext()
sql = SQLContext(sc)
df1 = sql.createDataFrame([("Mark", 68), ("John", 59), ("Mary", 49)], ['Name', \
'Weight'])
df2 = sql.createDataFrame([("... | -1 | 2016-10-18T19:33:57Z | 40,117,117 | <p>Try:</p>
<pre><code>>>> df1.where(df1['Weight'].between(68, 59)).union(df2.where(df2['Weight'].between(49, 68)))
</code></pre>
| 0 | 2016-10-18T20:04:40Z | [
"python",
"apache-spark",
"pyspark"
] |
Python Selenium Xpath from firebug not found | 40,116,629 | <p>I am trying to login to the ESPN website using selenium. Here is my code thus far</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Fi... | 0 | 2016-10-18T19:35:26Z | 40,116,943 | <p>This works for me, switching to the iframe first. Note that you will need to switch back out of the iframe after entering the credentials.</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support... | 1 | 2016-10-18T19:54:15Z | [
"python",
"selenium",
"xpath"
] |
Python Selenium Xpath from firebug not found | 40,116,629 | <p>I am trying to login to the ESPN website using selenium. Here is my code thus far</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Fi... | 0 | 2016-10-18T19:35:26Z | 40,116,944 | <p>Try to use</p>
<pre><code>driver.switch_to_frame('disneyid-iframe')
# handle authorization pop-up
driver.switch_to_default_content() # if required
</code></pre>
| 1 | 2016-10-18T19:54:21Z | [
"python",
"selenium",
"xpath"
] |
How to use a variable to find another variable in a list - python | 40,116,648 | <p>(Python 3.x)</p>
<pre><code>z=[]
x=0
while 1==1:
x=x+1
y=1
z.append(x)
while y==1:
a = 0
b = 0
if z(a)==x:
print(x)
y = 2
elif x%z(a)!= 0:
a = a+1
elif b == 2:
y = 2
else:
b = b+1
</code></pre... | -2 | 2016-10-18T19:36:39Z | 40,116,670 | <p><code>z</code> is a list. You can approach values inside it by indexes using the <code>z[a]</code> operator (and not <code>z(a)</code> which assumes a function call with <code>a</code> as parameter).</p>
<hr>
<p>I've took the liberty of using <code>boolean variables</code>, <code>+=</code> operators and unpacking ... | 0 | 2016-10-18T19:37:58Z | [
"python",
"python-3.x"
] |
Python: Elegant way to store items for checking item existence in a container | 40,116,653 | <p>In the situation I encounter, I would like to define "elegant" being having <strong>1) constant O(1) time complexity</strong> for checking if an item exists and <strong>2) store only items</strong>, nothing more.</p>
<p>For example, if I use a list</p>
<pre><code>num_list = []
for num in range(10): # Dummy operati... | 0 | 2016-10-18T19:37:02Z | 40,116,882 | <p>The solution here is to use a <code>set</code>, which doesnËt requires you to save a dummy variable for each value.</p>
| 1 | 2016-10-18T19:50:55Z | [
"python"
] |
Python: Elegant way to store items for checking item existence in a container | 40,116,653 | <p>In the situation I encounter, I would like to define "elegant" being having <strong>1) constant O(1) time complexity</strong> for checking if an item exists and <strong>2) store only items</strong>, nothing more.</p>
<p>For example, if I use a list</p>
<pre><code>num_list = []
for num in range(10): # Dummy operati... | 0 | 2016-10-18T19:37:02Z | 40,116,958 | <p>Normally you can't optimise both space and time together. One thing you can do is have more details about the range of data(here min to max value of num) and size of data(here it is number of times loop runs ie., 10). Then you will have two options :</p>
<ol>
<li>If range is limited then go for dictionary method(or... | 0 | 2016-10-18T19:55:20Z | [
"python"
] |
Exclude Item from Web-Scraped Loop | 40,116,665 | <p>Suppose I have the following <code>html</code>:</p>
<pre><code><h4>
<a href="http://www.google.com">Google</a>
</h4>
<h4>Random Text</h4>
</code></pre>
<p>I am able to identify all <code>h4</code> headings via a loop such as:</p>
<pre><code>for url in soup.findAll("h4")
... | 1 | 2016-10-18T19:37:42Z | 40,116,743 | <p>Sure, you can go with a straightforward approach, simply filtering the headings:</p>
<pre><code>for url in soup.find_all("h4")
if not url.a: # "url.a" is a shortcut to "url.find('a')"
continue
print(url.get_text())
</code></pre>
<p>Or, a better way would be to filter them with a <a href="https://w... | 3 | 2016-10-18T19:41:57Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
Exclude Item from Web-Scraped Loop | 40,116,665 | <p>Suppose I have the following <code>html</code>:</p>
<pre><code><h4>
<a href="http://www.google.com">Google</a>
</h4>
<h4>Random Text</h4>
</code></pre>
<p>I am able to identify all <code>h4</code> headings via a loop such as:</p>
<pre><code>for url in soup.findAll("h4")
... | 1 | 2016-10-18T19:37:42Z | 40,116,796 | <p>Use list comprehension as the most pythonic approach:</p>
<pre><code>[i.get_text() for i in soup.findAll("h4") if #Insert criteria here#]
</code></pre>
| 0 | 2016-10-18T19:45:29Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
Minimize memory overhead in sparse matrix inverse | 40,116,690 | <p>As pretense, I am continuing development in Python 2.7 from a prior question: <a href="http://stackoverflow.com/questions/40050947/determining-a-sparse-matrix-quotient">Determining a sparse matrix quotient</a> </p>
<h2>My existing code:</h2>
<pre><code>import scipy.sparse as sp
k = sp.csr_matrix(([], ([],[])),sha... | 0 | 2016-10-18T19:39:06Z | 40,119,148 | <p>No need to 'preallocate' <code>k</code>; this isn't a compiled language. Not that this is costing anything.</p>
<pre><code>k = sp.csr_matrix(([], ([],[])),shape=[R,R])
</code></pre>
<p>I need to double check this, but I think the <code>dot/inv</code> can be replaced by one call to <code>spsolve</code>. Remember ... | 1 | 2016-10-18T22:30:22Z | [
"python",
"scipy",
"sparse-matrix"
] |
making a chat client and wont work | 40,116,815 | <p>what's wrong here I'm stuck :(
I'm using <strong>3.4.4</strong> if that helps
I've tried everything! I've even searched on this! It keeps saying:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\matthew\Desktop\chatclient.py", line 36, in <module>
s.sendto(alias.encode() + ": " + message... | 0 | 2016-10-18T19:46:08Z | 40,116,949 | <p>The message is right! Once you encode <code>alias</code> and <code>message</code>, they are <code>bytes</code> not strings. But <code>": "</code> is a string, hence the error. In python 3.x, strings are unicode and need to be encoded to bytes to be saved to disk or sent on the wire.</p>
<p>An additional but subtle ... | 0 | 2016-10-18T19:54:37Z | [
"python",
"sockets"
] |
How to search the entire HDD for all pdf files? | 40,116,923 | <p>As the title suggests, I would like to get python 3.5 to search my root ('C:\')
for pdf files and then move those files to a specific folder.
This task can easily split into 2:
1. Search my root for files with the pdf extension.
2. Move those to a specific folder.</p>
<p>Now. I know how to search for a specific fi... | 0 | 2016-10-18T19:53:24Z | 40,122,637 | <p>Your find_all function is very close to the final result.
When you loop through the files, you can check their extension with os.path.splitext, and if they are .pdf files you can move them with shutil.move</p>
<p>Here's an example that walks the tree of a source directory, checks the extension of every file and, in... | 0 | 2016-10-19T05:11:34Z | [
"python",
"windows",
"python-3.x"
] |
How to search the entire HDD for all pdf files? | 40,116,923 | <p>As the title suggests, I would like to get python 3.5 to search my root ('C:\')
for pdf files and then move those files to a specific folder.
This task can easily split into 2:
1. Search my root for files with the pdf extension.
2. Move those to a specific folder.</p>
<p>Now. I know how to search for a specific fi... | 0 | 2016-10-18T19:53:24Z | 40,131,752 | <p>You can use <a href="https://docs.python.org/3/library/glob.html" rel="nofollow"><code>glob</code></a> from python 3.5 onwards. It supports a recursive search.</p>
<blockquote>
<p>If recursive is true, the pattern â**â will match any files and zero or more directories and subdirectories. If the pattern is fol... | 0 | 2016-10-19T12:44:02Z | [
"python",
"windows",
"python-3.x"
] |
How can I extract the information I want using this RegEx or better? | 40,116,937 | <p>So here's the Regular Expression I have so far.</p>
<p><code>r"(?s)(?<=([A-G][1-3])).*?(?=[A-G][1-3]|$)"</code></p>
<p>It looks behind for a letter followed by a number between A-G and 1-3 as well as doing the same when looking ahead. I've tested it using <a href="https://regex101.com/" rel="nofollow">Regex101<... | 2 | 2016-10-18T19:53:56Z | 40,117,108 | <p>I suggest</p>
<pre><code>(?s)([A-G][1-3])((?:(?![A-G][1-3]).)*)
</code></pre>
<p>See the <a href="https://regex101.com/r/xlC4tZ/2" rel="nofollow">regex demo</a></p>
<p>The <code>(?s)</code> will enable <code>.</code> to match linebreaks, <code>([A-G][1-3])</code> will capture the uppercase letter+digit into Grou... | 1 | 2016-10-18T20:04:11Z | [
"python",
"regex"
] |
Colorbar/plotting issue? "posx and posy should be finite values" | 40,116,968 | <p><strong>The problem</strong></p>
<p>So I have a lat-lon array with <code>6</code> layers (<code>array.size = (192,288,6)</code>) containing a bunch of data ranging in values from nearly <code>0</code> to about <code>0.65</code>. When I plot data from every one of the <code>6</code> layers (<code>[:,:,0]</code>, <co... | 1 | 2016-10-18T19:55:51Z | 40,141,093 | <p>So I found out that specifying <code>vmax</code> & <code>vmin</code> solves the problem. I have no idea why, but once I did, my plot turned out correctly with the colorbar.</p>
<pre><code>trend = m.pcolormesh(x,y,array[:,:,5],cmap='jet',norm=norm,shading='gouraud',vmin=0.,vmax=0.6)
</code></pre>
<p><a href="ht... | 0 | 2016-10-19T20:38:02Z | [
"python",
"arrays",
"matplotlib",
"jupyter-notebook",
"colorbar"
] |
Average and RMSE of n x k array | 40,117,208 | <p>I have this target array:</p>
<pre><code>[ 0.88 0.51 0.55 0.59 0.7 ]
</code></pre>
<p>and this sample array:</p>
<pre><code>[[ 0.4 0.02 0.52 0.44 0.48]
[ 0.53 0.73 0.13 0.15 0.78]
[ 0.67 0.27 0.26 0.31 0.17]
[ 0.37 0.51 0.98 0.2 0.57]]
</code></pre>
<p>and I would like to produce another... | 0 | 2016-10-18T20:09:30Z | 40,118,969 | <p>You can avoid the nested for loops by using the axis argument available to many <code>numpy</code> methods. </p>
<pre><code>fns = np.empty((4,sample.shape[1]))
stdv = np.std(sample,axis=0)
fns[0,:] = np.mean(sample,axis=0)
fns[1,:] = fns[0,:] - stdv
fns[2,:] = fns[0,:] + stdv
fns[3,:] = np.sqrt(np.mean((sample - ta... | 1 | 2016-10-18T22:13:20Z | [
"python",
"statistics"
] |
Pack hex string using struct module? | 40,117,221 | <p>I want to pack a hex string with python pack.
Here is my code:</p>
<pre><code>import struct
query='430401005001'
q= ('%x' % int(query, 16)).decode('hex').decode('utf-8')
qpacked=struct.pack('6s',str(q))
</code></pre>
<p>Query is a hex string.
The code does not work if I change the string to '53040600d0010100' and... | 0 | 2016-10-18T20:10:17Z | 40,117,293 | <p>The string gets truncated because you're telling it you want to pack it up to length 6 (<code>6s</code>). You'll have to either raise that number, or work around your string getting truncated.</p>
<p>Also, stop juggling with the encoding of your string, just <code>query.decode('hex')</code> should suffice.</p>
| 0 | 2016-10-18T20:15:39Z | [
"python",
"string",
"hex"
] |
How to programm a stencil with Dask | 40,117,237 | <p>In many occasions, scientists simulates a system's dynamics using a Stencil, this is convolving a mathematical operator over a grid. Commonly, this operation consumes a lot of computational resources. <a href="https://en.wikipedia.org/wiki/Stencil_code" rel="nofollow">Here</a> is a good explanation of the idea. </p>... | 2 | 2016-10-18T20:10:53Z | 40,117,491 | <p>Nice question. You're correct that <a href="http://dask.pydata.org/en/latest/array.html" rel="nofollow">dask.array</a> <em>do</em> provide parallel computing but <em>don't</em> doesn't support item assignment. We can solve stencil computations by making a function to operate on a block of numpy data at a time and ... | 1 | 2016-10-18T20:28:02Z | [
"python",
"dask"
] |
How to programm a stencil with Dask | 40,117,237 | <p>In many occasions, scientists simulates a system's dynamics using a Stencil, this is convolving a mathematical operator over a grid. Commonly, this operation consumes a lot of computational resources. <a href="https://en.wikipedia.org/wiki/Stencil_code" rel="nofollow">Here</a> is a good explanation of the idea. </p>... | 2 | 2016-10-18T20:10:53Z | 40,118,151 | <p>Dask internally divides arrays into smaller numpy arays, when you create an array with dask.array, you must provide some information about how to divide it into <em>chunks</em>, like this:</p>
<pre><code>grid = dask.array.zeros((100,100), chunks=(50,50))
</code></pre>
<p>That requests an array of 100 x 100 divided... | 1 | 2016-10-18T21:12:36Z | [
"python",
"dask"
] |
NLTK separately extract leaves and non-leaf nodes | 40,117,239 | <p>I'm working with the <a href="http://nlp.stanford.edu/sentiment/" rel="nofollow">Standford Sentiment Treebank</a> dataset and I'm attempting to extract the leaves and the nodes. The data is given follows </p>
<pre><code>(3 (2 (2 The) (2 Rock)) (4 (3 (2 is) (4 (2 destined) (2 (2 (2 (2 (2 to) (2 (2 be) (2 (2 the) (2 ... | -1 | 2016-10-18T20:10:59Z | 40,118,405 | <p>Don't waste your time with regexps, this is what tree classes are for. Use the nltk's <code>Tree</code> class like this:</p>
<pre><code>mytree = "(3 (2 (2 The) (2 Rock)) (4 (3 (2 is) (4 (2 destined) (2 (2 (2 (2 (2 to) (2 (2 be) (2 (2 the) (2 (2 21st) (2 (2 (2 Century) (2 's)) (2 (3 new) (2 (2 ``) (2 Conan)))))))) ... | 2 | 2016-10-18T21:29:44Z | [
"python",
"tree",
"nlp",
"nltk",
"nodes"
] |
Routing error with python flask search app | 40,117,312 | <p>I am trying to get a simple search function going with my flask app. I have the following code that kicks off the search</p>
<pre><code><form action="/search" method=post>
<input type=text name=search value="{{ request.form.search }}"></br>
<div class="actions"><input type=submit value=... | 1 | 2016-10-18T20:16:40Z | 40,117,376 | <p>As the error states, your form is posting to /search but your handler is set up for /search/. Make them the same.</p>
| 0 | 2016-10-18T20:20:28Z | [
"python",
"flask"
] |
Routing error with python flask search app | 40,117,312 | <p>I am trying to get a simple search function going with my flask app. I have the following code that kicks off the search</p>
<pre><code><form action="/search" method=post>
<input type=text name=search value="{{ request.form.search }}"></br>
<div class="actions"><input type=submit value=... | 1 | 2016-10-18T20:16:40Z | 40,117,422 | <p>Use <code>url_for('index')</code> to generate the correct url for the action.</p>
<pre><code><form action="{{ url_for('index') }}">
</code></pre>
<hr>
<p>Currently, you're submitting to the url without the trailing <code>/</code>. Flask redirects this to the route with the trailing <code>/</code>, but POST ... | 2 | 2016-10-18T20:23:27Z | [
"python",
"flask"
] |
return len of list without changing the method that returns index of list | 40,117,456 | <p>How can write a function outside of this class that will return the len of the list without modifying the class at all. </p>
<pre><code>class SingleMethodList(object):
def __init__(self, l):
self._list = l
def get(self, index):
try:
return self._list[index]
except IndexE... | -3 | 2016-10-18T20:25:47Z | 40,117,603 | <p>You can simply use a function like this in order to iterate through the list until you reach the end of it:</p>
<pre><code>def get_single_method_list_length(list_to_check):
check_index = 0
while list_to_check.get(check_index) is not None:
check_index += 1
return check_index # This will be the le... | 3 | 2016-10-18T20:35:30Z | [
"python"
] |
String Containment in Pandas | 40,117,685 | <p>I am trying to produce all the rows where company1 in df is contained in company2. I am doing it as follows:</p>
<pre><code>df1=df[['company1','company2']][(df.apply(lambda x: x['company1'] in x['company2'], axis=1) == True)]
</code></pre>
<p>When I run the above line of code, it also shows "South" matched with "S... | 3 | 2016-10-18T20:40:46Z | 40,117,903 | <p>I think you need:</p>
<pre><code>df = pd.DataFrame({'company1': {0: 'South', 1: 'South', 2:'South'},
'company2': {0: 'Southern', 1: 'Route South', 2: 'South Route'}})
print (df)
company1 company2
0 South Southern
1 South Route South
2 South South Route
df1=df[df['company2'... | 1 | 2016-10-18T20:54:15Z | [
"python",
"string",
"pandas"
] |
TypeError: not enough arguments for format string - Python SQL connection while using %Y-%m | 40,117,760 | <pre><code>with engine.connect() as con:
rs = con.execute("""
SELECT datediff(STR_TO_DATE(CONCAT(year,'-',month,'-',day), '%Y-%m-%d') , current_date())
from TABLE
WHERE datediff(STR_TO_DATE(CONCAT(year,'-',month,'-',day), '%Y-%m-%d') , curr... | 0 | 2016-10-18T20:45:43Z | 40,117,918 | <p>It sees your <code>%</code> signs and thinks you want to format the string. I believe you should be able to replace them with <code>%%</code> to indicate that you want the character, not a format substitution.</p>
| 0 | 2016-10-18T20:55:23Z | [
"python",
"mysql",
"compiler-errors",
"python-3.5"
] |
TypeError: not enough arguments for format string - Python SQL connection while using %Y-%m | 40,117,760 | <pre><code>with engine.connect() as con:
rs = con.execute("""
SELECT datediff(STR_TO_DATE(CONCAT(year,'-',month,'-',day), '%Y-%m-%d') , current_date())
from TABLE
WHERE datediff(STR_TO_DATE(CONCAT(year,'-',month,'-',day), '%Y-%m-%d') , curr... | 0 | 2016-10-18T20:45:43Z | 40,117,924 | <p>You need to escape the <code>%</code>:</p>
<pre><code>with engine.connect() as con:
rs = con.execute("""
SELECT datediff(STR_TO_DATE(CONCAT(year,'-',month,'-',day), '%%Y-%%m-%%d') , current_date())
from TABLE
WHERE datediff(STR_TO_DATE(... | 0 | 2016-10-18T20:56:01Z | [
"python",
"mysql",
"compiler-errors",
"python-3.5"
] |
How Can I Detect Gaps and Consecutive Periods In A Time Series In Pandas | 40,118,037 | <p>I have a pandas Dataframe that is indexed by Date. I would like to select all consecutive gaps by period and all consecutive days by Period. How can I do this?</p>
<p><strong>Example of Dataframe with No Columns but a Date Index:</strong></p>
<pre><code>In [29]: import pandas as pd
In [30]: dates = pd.to_date... | 0 | 2016-10-18T21:04:14Z | 40,129,387 | <p>here's something to get started:</p>
<pre><code>df = pd.DataFrame(np.ones(5),columns = ['ones'])
df.index = pd.DatetimeIndex(['2016-09-19 10:23:03', '2016-08-03 10:53:39', '2016-09-05 11:11:30', '2016-09-05 11:10:46', '2016-09-06 10:53:39'])
daily_rng = pd.date_range('2016-08-03 00:00:00', periods=48, freq='D')
dai... | 0 | 2016-10-19T10:54:31Z | [
"python",
"pandas"
] |
changed settings in python IDLE | 40,118,041 | <p>I tried to change the window size in IDLE but now IDLE won't launch. I have tried deleting it, removing it from trash and reinstalling both 3.5 and 2.7 again but still have the same problem. Command/option/escape indicates it hasn't launched and is not in the background.</p>
<p>The screen size when this started was... | 0 | 2016-10-18T21:04:25Z | 40,118,249 | <p>Assuming this is Windows, there is a hidden folder in your user folder</p>
<pre><code>C:\Users\username\.idlerc\config-main.cfg
</code></pre>
<p>In this file, you can edit the size of the IDLE window, under the <code>[EditorWindow]</code> header. See <a href="https://svn.python.org/projects/python/trunk/Mac/IDLE/c... | 0 | 2016-10-18T21:19:25Z | [
"python"
] |
How to convert JSON data into a tree image? | 40,118,113 | <p>I'm using <a href="http://treelib.readthedocs.io/en/latest/examples.html" rel="nofollow">treelib</a> to generate trees, now I need easy-to-read version of trees, so I want to convert them into images. For example:
<a href="https://i.stack.imgur.com/sr9eC.png" rel="nofollow"><img src="https://i.stack.imgur.com/sr9eC.... | 1 | 2016-10-18T21:10:11Z | 40,130,160 | <p>For a tree like this there's no need to use a library: you can generate the Graphviz DOT language statements directly. The only tricky part is extracting the tree edges from the JSON data. To do that, we first convert the JSON string back into a Python <code>dict</code>, and then parse that <code>dict</code> recursi... | 1 | 2016-10-19T11:28:07Z | [
"python",
"json",
"tree"
] |
Library `requests` getting different results unpredictably | 40,118,133 | <p>Why does this code:</p>
<pre><code>import requests
response = requests.post('http://evds.tcmb.gov.tr/cgi-bin/famecgi', data={
'cgi': '$ozetweb',
'ARAVERIGRUP': 'bie_yymkpyuk.db',
'DIL': 'UK',
'ONDALIK': '5',
'wfmultiple_selection': 'ZAMANSERILERI',
'f_begdt': '07-01-2005',
'f_enddt': '... | 3 | 2016-10-18T21:11:48Z | 40,119,137 | <p>It does seem to come down to different between dicts in python2 vs python3 in relation to <a href="https://docs.python.org/3/whatsnew/3.3.html#porting-python-code" rel="nofollow">Hash randomization is enabled by default</a> since python3.3 and the server needing at least the <em>cgi</em> field to come first, the fo... | 1 | 2016-10-18T22:29:46Z | [
"python",
"python-requests"
] |
How to find all pairs of neighboring values in matrix? | 40,118,137 | <p>For an image represented as a matrix, what is an efficient way to find all unique pairs of elements that touch within a 3x3 square?</p>
<pre><code>Let A=
1 1 2 2 3 3 3
1 1 1 1 2 4 4
1 1 2 2 5 5 5
</code></pre>
<p>Then we would return</p>
<pre><code>(1,2),(1,3),(1,5),(2,3),(2,4),(2,5),(3,4),(4,5)
</cod... | -2 | 2016-10-18T21:11:58Z | 40,118,374 | <p>You may use <a href="https://docs.python.org/2/library/itertools.html#itertools.combinations" rel="nofollow"><code>itertools.combinations()</code></a> to achieve this. Below is the sample code:</p>
<pre><code>a = [[1, 1, 2, 2, 3, 3, 3,],
[1, 1, 1, 1, 2, 4, 4,],
[1, 1, 2, 2, 5, 5, 5,],
]
# Extract bou... | 0 | 2016-10-18T21:27:18Z | [
"python",
"image-processing",
"matrix"
] |
How to find all pairs of neighboring values in matrix? | 40,118,137 | <p>For an image represented as a matrix, what is an efficient way to find all unique pairs of elements that touch within a 3x3 square?</p>
<pre><code>Let A=
1 1 2 2 3 3 3
1 1 1 1 2 4 4
1 1 2 2 5 5 5
</code></pre>
<p>Then we would return</p>
<pre><code>(1,2),(1,3),(1,5),(2,3),(2,4),(2,5),(3,4),(4,5)
</cod... | -2 | 2016-10-18T21:11:58Z | 40,119,187 | <p>Here is some partially-hardcoded easy-to-understand-approach.</p>
<ul>
<li><strong>Edit:</strong> faster version due to preprocessing</li>
<li><strong>Edit 2:</strong> one more final speedup (symmetry-reduction in preprocessing)</li>
<li><strong>Edit 3:</strong> okay; added one more symmetry-reduction step in prepr... | 0 | 2016-10-18T22:34:05Z | [
"python",
"image-processing",
"matrix"
] |
How do I convert number to binary just by using the math functions in python? | 40,118,197 | <p>My assignment is to make a code to change a number between 0 and 255 to binary. All we have learned is the print, input, and the math functions? how would I code it so that when I have it ask for a number I can type the number in and it will go through the process of converting it? sorry if my explanation is weird. ... | -7 | 2016-10-18T21:15:50Z | 40,119,531 | <p>Given the number of down votes, Iâll probably be pilloried for helping youâespecially when you havenât posted any code (pro tip: the people who answer questions on stack have actual lives where they do things with people they care about). But enough of my hectoring, start with what you have and go from there... | 0 | 2016-10-18T23:14:22Z | [
"python",
"binary"
] |
get, access and modify element values for an numpy array | 40,118,240 | <p>I once saw the following code segment</p>
<pre><code>import numpy as np
nx=3
ny=3
label = np.ones((nx, ny))
mask=np.zeros((nx,ny),dtype=np.bool)
label[mask]=0
</code></pre>
<p>The <code>mask</code> generated is a bool array</p>
<pre><code>[[False False False]
[False False False]
[False False False]]
</code></pr... | 0 | 2016-10-18T21:18:40Z | 40,120,099 | <p>Here is a code snippet with some comments that might help you make sense of this. I would suggest you look into the link that @Divakar provided and look into <a href="https://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html#boolean-or-mask-index-arrays" rel="nofollow">boolean-indexing</a>. </p>
<pre><code... | 0 | 2016-10-19T00:22:04Z | [
"python",
"numpy",
"scipy"
] |
Unable to create a second dataframe python pandas | 40,118,259 | <p>My second data frame is not loading values when i create it. Any help with why it is not working? When i make my cursor a list, it has a bunch of values in it, but for whatever reason when i try to do a normal data frame load with pandas a second time, it does not work.</p>
<p>My code:</p>
<pre><code> conn = py... | 2 | 2016-10-18T21:19:54Z | 40,118,556 | <p>Why not just use pd.read_sql_query("your_query", conn) this will return the result of the query as a dataframe and requires less code. Also you set cursor to cursor.execute(strsql) at the top and then you are trying to call execute on cursor again in your for loop but you can no longer call execute on cursor you wil... | 3 | 2016-10-18T21:39:35Z | [
"python",
"pandas",
"pyodbc"
] |
sqlalchemy can't read null dates from sqlite3 (0000-00-00): ValueError: year is out of range | 40,118,266 | <p>When I try to query a database containing dates such as <code>0000-00-00 00:00:00</code> with <code>sqlachemy</code>, I get <code>ValueError: year is out of range</code>.</p>
<p>Here's the db dump:</p>
<p><a href="https://i.stack.imgur.com/k6wiR.png" rel="nofollow"><img src="https://i.stack.imgur.com/k6wiR.png" al... | 0 | 2016-10-18T21:20:28Z | 40,118,382 | <p>Got the answer via <code>inklesspen</code> on IRC: <a href="https://docs.python.org/2/library/datetime.html#datetime.MINYEAR" rel="nofollow">Python datetime representation has <strong>minimum year</strong> and it's <strong>1</strong></a></p>
| 0 | 2016-10-18T21:27:50Z | [
"python",
"sqlalchemy"
] |
How to set multiple function keywords at once, in Python 2? | 40,118,384 | <p>all.</p>
<p>I was wondering if it was possible to set multiple keywords at once (via list?) in a function call.</p>
<p>For example, if you do:</p>
<pre><code>foo, bar = 1, 2
print(foo, bar)
</code></pre>
<p>The output is <code>(1,2)</code>.</p>
<p>For the function</p>
<pre><code>def printer(foo, bar)
print... | 0 | 2016-10-18T21:27:55Z | 40,118,440 | <p>To pass args as a list</p>
<pre><code>arg_list = ["foo", "bar"]
my_func(*arg_list)
</code></pre>
<p>To pass kwargs, use a dictionary</p>
<pre><code>kwarg_dict = {"keyword": "value"}
my_func(**kwarg_dict)
</code></pre>
| 3 | 2016-10-18T21:32:05Z | [
"python",
"arguments",
"parameter-passing",
"kwargs",
"function-call"
] |
Replace/remap server response body while preserving most of original header fields served to browser | 40,118,464 | <p>How can I replace particular file body returned to browser by remote server but leave the original respond header mostly unchanged/intact/unaffected/unaltered/untouched? (I don't know which English word is best in this context so please: fix my question!)
This probably may be done using penetration testing proxy (Bu... | 0 | 2016-10-18T21:33:32Z | 40,125,565 | <p>Yes, you can do this with OWASP ZAP.</p>
<p>ZAP supports lots of scripting languages including python (actually jython;).
You can change anything to do with requests and responses using proxy scripts. You have full access to all of the information about the requests and responses, all of the ZAP functionality and y... | 0 | 2016-10-19T08:05:57Z | [
"python",
"fiddler",
"owasp",
"charles",
"penetration-testing"
] |
Cannot connect to SQL server from python using Active Directory Authentication | 40,118,470 | <p>I am using pymssql library to connect python to Sql Server. I can connect using windows/sql server authentication. I want to connect using Active Directory Authentication. </p>
<p>Tried the below connection string. But it fails with error : </p>
<pre><code>unexpected keyword authentication
conn = pymssql.connect... | 1 | 2016-10-18T21:33:59Z | 40,120,437 | <p><a href="http://pymssql.org/en/latest/ref/pymssql.html#functions" rel="nofollow">Note that pymssql.connect does not have an 'authentication' parameter</a>. You are passing it that as a named arg, which is invalid, and the reason you see your error.</p>
<p>See <a href="http://pymssql.org/en/latest/pymssql_examples.h... | 0 | 2016-10-19T01:03:31Z | [
"python",
"sql-server"
] |
How to create a backward moving input class in Python | 40,118,471 | <p>How to create a backward moving input class in Python? I have a class called input which reads a file forward returning one character at a time now I would like to change it to read backwards.</p>
<pre><code># Buffered input file. Returns one character at a time.
class Input:
def __init__( self, file ):... | -2 | 2016-10-18T21:34:03Z | 40,118,787 | <p>I think the only way this can work with text files in Python 3 is to read the whole text of the file in at once, and then yield characters from the end of the string you've loaded. You can't read the file in chunks starting from the end because there's no way to safely seek to an arbitrary position in the text. If y... | 0 | 2016-10-18T21:58:13Z | [
"python",
"python-3.x"
] |
Controlling nonstandard classes with pywinauto | 40,118,492 | <p>I am using pywinauto in order to ease my work with certain program. I would like to select in this <a href="https://i.stack.imgur.com/OHbHV.png" rel="nofollow">combobox</a> item "vs. Reference". I used <code>app['Setup Potentiodynamic Experiment'].PrintControlIdentifiers()</code> to get name and class of the combobo... | 1 | 2016-10-18T21:35:43Z | 40,119,074 | <p><code>ComboBoxWrapper</code> can be created explicitly:</p>
<pre><code>from pywinauto.controls.win32_controls import ComboBoxWrapper
hwnd_wr = app['Setup Potentiodynamic Experiment']["TComboDJ5"].WrapperObject()
combo = ComboBoxWrapper(hwnd_wr)
combo.Select("vs. Reference")
</code></pre>
<p>Of course it would work... | 0 | 2016-10-18T22:24:32Z | [
"python",
"combobox",
"pywinauto"
] |
output truncated when writing to a file in python | 40,118,500 | <p>i have unusual problem, i'm using Anaconda and my python code runs really good the output on the screen is perfect, however, after each print i put file.write to write my result in my file as well but not all output is written there every time it truncates the output in different positions which doesn't make sense. ... | -4 | 2016-10-18T21:36:08Z | 40,118,705 | <p>i just added the parenthesses to the file.close it fixed the problem ... thanks and sorry for the </p>
| 0 | 2016-10-18T21:51:12Z | [
"python",
"python-2.7"
] |
Plotting secondary Y-axis using Panda? | 40,118,548 | <p>My current code takes a list from a csv file and lists the header for the user to pick from so it can plot.</p>
<pre><code>import pandas as pd
df = pd.DataFrame.from_csv('log40a.csv',index_col=False)
from collections import OrderedDict
headings = OrderedDict(enumerate(df,1))
for num, heading in headings.items():
... | 0 | 2016-10-18T21:39:10Z | 40,124,887 | <p>You need to create an array with the column names that you want plotted on the y axis. </p>
<p>An example if you delimite the y columns with a ','</p>
<pre><code>df.plot(x= headings[xaxis], y=headings[yaxis.split(",")], figsize=(15, 10))
</code></pre>
<p>To run it you will need to change your input method, so tha... | 0 | 2016-10-19T07:29:50Z | [
"python",
"pandas"
] |
Pandas merging 2 DataFrames into one graph | 40,118,638 | <p>I am trying to plot two pandas dataframes. One dataframe needs to be displayed as a line graph and another as a scatter plot on the same graph.</p>
<p>This plots the first dataframe:</p>
<pre><code>line = pd.read_csv('nugt_daily.csv',parse_dates=['Date'])
line = line.sort_values(by='Date')
line.set_index('Date',in... | 0 | 2016-10-18T21:46:11Z | 40,118,802 | <p>Use <code>return_type='axes'</code> to get <code>df1.scatterplot</code> to return a matplotlib Axes object. Then pass that axes to the second call to linegraph using <code>ax=ax</code>. This will cause both plots to be drawn on the same axes.</p>
<p>Try:</p>
<pre><code>ax = df1.plot()
df2.plot(ax=ax)
</code></pre>... | 0 | 2016-10-18T21:59:46Z | [
"python",
"pandas",
"numpy",
"matplotlib"
] |
django contact page send_email | 40,118,704 | <p>I am trying to create a contact page which will take 17 inputs from a visitor and then email that information to me. I found many basic tutorials but none specific to what I am trying to achieve. So far this is what I have:</p>
<p>I created a new Django project "contactform" then a new app "send_email"</p>
<p>This... | 0 | 2016-10-18T21:51:02Z | 40,119,216 | <p>Here you go:</p>
<hr>
<p><strong>email.template.html</strong></p>
<pre><code>Hello, someone filled out a contact form with the following information:
First name: {{ first_name }}
Last name : {{ last_name }}
. . . and so on
</code></pre>
<p>-- or if youâre lazy like me --</p>
<pre><code>Hello, someone filled ... | 0 | 2016-10-18T22:36:20Z | [
"python",
"django",
"django-forms",
"contact-form"
] |
adding vector valued attribute to an edge in networkx | 40,118,713 | <p>I want to add a list, say [1,2,3] to every edge in a directed networkX graph. Any ideas? I found something like this can be done for nodes (using np.array) but it did not work on edges.</p>
| 0 | 2016-10-18T21:51:36Z | 40,119,056 | <p>You can add the attributes when you put the edges into the network.</p>
<pre><code>import networkx as nx
G=nx.Graph()
G.add_edge(1,2, values = [1,2,3])
G.add_edge(2,3, values = ['a', 'b', 'c'])
G.edge[1][2]['values']
> [1, 2, 3]
G.edges(data = True)
> [(1, 2, {'values': [1, 2, 3]}), (2, 3, {'values': ['a', 'b... | 2 | 2016-10-18T22:22:59Z | [
"python",
"graph",
"networkx"
] |
How to use REGEX with multiline | 40,118,721 | <p>The following expression works well extracting the portion of <code>data</code> string that starts with the word <code>Block</code> followed by open bracket <code>{</code> and ending with the closing bracket '}':</p>
<pre><code>data ="""
Somewhere over the rainbow
Way up high
Block {
line 1
line 2
line 3
}
And ... | 0 | 2016-10-18T21:52:19Z | 40,118,754 | <p>Wouldn't this work?</p>
<p><code>regex = re.compile("""(Block\ {\n\ [^\}]*\n}\n)""", re.MULTILINE)</code></p>
<p>In the version you've posted, it is exiting the match whenever it comes across a second opening brace, even though you want it to exit upon the first closing brace. If you want nested opening / closing... | 2 | 2016-10-18T21:54:57Z | [
"python",
"regex"
] |
How to use REGEX with multiline | 40,118,721 | <p>The following expression works well extracting the portion of <code>data</code> string that starts with the word <code>Block</code> followed by open bracket <code>{</code> and ending with the closing bracket '}':</p>
<pre><code>data ="""
Somewhere over the rainbow
Way up high
Block {
line 1
line 2
line 3
}
And ... | 0 | 2016-10-18T21:52:19Z | 40,118,885 | <p>I would suggest you to use:</p>
<pre><code>(Block ?{\n ?[^$]+?\n}\n)
</code></pre>
<p>Since python matches <em>greedy</em>, we use <em>?</em> to be non-greedy.</p>
<p>Worked well for me.
In addition I would recommend you the use of <a href="https://regex101.com/" rel="nofollow">https://regex101.com/</a></p>
<p>... | 0 | 2016-10-18T22:05:48Z | [
"python",
"regex"
] |
How to randomly select an image using findall and clickall? Sikuli | 40,118,859 | <p>The problem that I'm having is that when using "if image exists, then click image" the script wants to select the top image every time even if there are 8 others. How do I have it randomly select any of the images each time with equal chance?</p>
<p>Example
DOG it will pick this one each time.
DOG I want it to pick... | -1 | 2016-10-18T22:04:03Z | 40,119,110 | <p>import random
click(random.choice(list(findAll(("dog-1"))))</p>
| 0 | 2016-10-18T22:27:18Z | [
"python",
"jython",
"sikuli"
] |
Python How to Check if time is midnight and not display time if true | 40,118,869 | <p>I'm modifying our pacific time zone filter to include a time option. I don't want the time component to be shown if midnight. The only import thus far we are using is dateutil.parser. Any pointers on best solution would be appreciated! Thanks.</p>
<pre><code>def to_pacific_date_str(timestamp, format='%Y-%m-%d', tim... | 2 | 2016-10-18T22:04:37Z | 40,118,929 | <p>To check if the time is midnight:</p>
<pre><code>from datetime import datetime
def checkIfMidnight():
now = datetime.now()
seconds_since_midnight = (now - now.replace(hour=0, minute=0, second=0, microsecond=0)).total_seconds()
return seconds_since_midnight == 0
</code></pre>
| 0 | 2016-10-18T22:09:59Z | [
"python",
"datetime",
"timezone",
"pytz"
] |
Python How to Check if time is midnight and not display time if true | 40,118,869 | <p>I'm modifying our pacific time zone filter to include a time option. I don't want the time component to be shown if midnight. The only import thus far we are using is dateutil.parser. Any pointers on best solution would be appreciated! Thanks.</p>
<pre><code>def to_pacific_date_str(timestamp, format='%Y-%m-%d', tim... | 2 | 2016-10-18T22:04:37Z | 40,119,335 | <p>I believe the best thing to do would be to just take the <code>time()</code> from the <code>datetime</code> before passing it, then compare that to <code>datetime.time(0, 0)</code>.</p>
<pre><code>import pytz
import datetime
def to_pacific_date_str(timestamp, date_fmt='%Y-%m-%d', time=False):
pacific_timestamp... | 2 | 2016-10-18T22:48:43Z | [
"python",
"datetime",
"timezone",
"pytz"
] |
Python: cannot imoport keras, ImportError: No module named tensorflow | 40,118,874 | <p>I just update keras package to 1.1.0 version. But it canot be properly imported.
Error message:</p>
<pre><code>import tensorflow as tf
ImportError: No module named tensorflow
</code></pre>
<p>It seems that the new version requires TensorFlow. I use anaconda in windows 10. </p>
<p>How to solve the problem?</p>
| 0 | 2016-10-18T22:05:01Z | 40,118,982 | <p>It has been fixed by changing backend setup to 'theano'</p>
| 0 | 2016-10-18T22:15:08Z | [
"python",
"keras"
] |
How to run 'module load < > ' command from within python script | 40,118,919 | <p>I tried using <code>os.system()</code>, <code>subprocess.call()</code> and <code>subprocess.Popen()</code> {<em>with and without the option <code>shell=True</code></em>} to execute <code>module load ___</code> from within my python script. Even though the script runs successfully and it mentions that my module has b... | -1 | 2016-10-18T22:09:00Z | 40,119,175 | <p>I believe the problem is that both os.system and subprocess are running the command in a... well, subprocess. So the module is load successfully in the subprocess context and it exists immediately. No effect in python's process context though.</p>
<p>I'm not near a computer now to try it out, this should work:</p>
... | 0 | 2016-10-18T22:32:58Z | [
"python",
"shell"
] |
How argument with return statement calling function? | 40,118,976 | <p>I am trying to understand a program how this return is calling function and how we are passing argument in function with return ?</p>
<p>program is :</p>
<pre><code>def hello(x,b):
z=x+b
print(z)
return "hi"
def hi(n):
return hello(4,4)
for i in range(3):
print(hi(3))
</code></pre>
<p>i am c... | -1 | 2016-10-18T22:14:03Z | 40,119,082 | <pre><code>def hello(x,b):
z=x+b
print(z)
return hello(4, 4)
</code></pre>
<p>does not work because of infinite recursion. Essentially this function is making an infinite loop.</p>
<p>To see how this works, look at how you would write it out in code:</p>
<pre><code>x = 4
b = 4
z = x+b
print(z)
#And the... | 0 | 2016-10-18T22:25:06Z | [
"python",
"python-2.7",
"function",
"python-3.x",
"return"
] |
Invalid view definition - Odoo v9 community | 40,118,981 | <p>I manage to find a way to have the product price on <code>stock.picking</code>, but now I have a view error.</p>
<p>This is my model:</p>
<pre><code>from openerp import models, fields, api
import openerp.addons.decimal_precision as dp
class StockPicking(models.Model):
_inherit = 'stock.picking'
product... | 1 | 2016-10-18T22:14:38Z | 40,122,543 | <p>You are adding <em>price_unity</em> field in view inside <em>pack_operation_product_ids</em> field.</p>
<p><em>pack_operation_product_ids</em> is a One2many relation type with <em>stock_pack_operation</em> object.</p>
<p>So we need to add/register <em>price_unity</em> field in <em>stock_pack_operation</em> object.... | 2 | 2016-10-19T05:04:09Z | [
"python",
"openerp",
"odoo-9",
"qweb"
] |
Creating a chart in python 3.5 using XlsxWriter where series values are based on a loop | 40,119,012 | <p>I'm using Python 3.5 on Windows 10. Hopefully I can articulate what I'm trying to accomplish while permitting as little confusion as possible... </p>
<p>I've written a Python script that performs several tasks, some of which include creating an Excel workbook via XlsxWriter based on data generated from code in the ... | 1 | 2016-10-18T22:18:01Z | 40,127,334 | <p>In almost all parts of the XlsxWriter API, anywhere there is a Cell reference like <code>A1</code> or a range like <code>=Sheet1!$A$1</code> you can use a tuple or a list of values. For charts you can use a list of values like this:</p>
<pre><code># String interface. This is good for static ranges.
chart.add_series... | 0 | 2016-10-19T09:26:00Z | [
"python",
"excel",
"graph",
"charts",
"xlsxwriter"
] |
Python: Pandas, dealing with spaced column names | 40,119,050 | <p>If I have multiple text files that I need to parse that look like so, but can vary in terms of column names, and the length of the hashtags above: <img src="https://s4.postimg.org/8p69ptj9p/feafdfdfdfdf.png" alt="txt.file"></p>
<p>How would I go about turning this into a pandas dataframe? I've tried using <code... | 3 | 2016-10-18T22:22:16Z | 40,121,644 | <p>Consider reading in raw file, cleaning it line by line while writing to a new file using <code>csv</code> module. Regex is used to identify column headers using the <em>i</em> as match criteria. Below assumes more than one space separates columns:</p>
<pre><code>import os
import csv, re
import pandas as pd
rawfile... | 2 | 2016-10-19T03:30:51Z | [
"python",
"python-3.x",
"pandas",
"text"
] |
Python: Pandas, dealing with spaced column names | 40,119,050 | <p>If I have multiple text files that I need to parse that look like so, but can vary in terms of column names, and the length of the hashtags above: <img src="https://s4.postimg.org/8p69ptj9p/feafdfdfdfdf.png" alt="txt.file"></p>
<p>How would I go about turning this into a pandas dataframe? I've tried using <code... | 3 | 2016-10-18T22:22:16Z | 40,137,973 | <p>This is the way I'm mentioning in the comment: it uses a file object to skip the custom dirty data you need to skip at the beginning. You land the file offset at the appropriate location in the file where <code>read_fwf</code> simply does the job:</p>
<pre><code>with open(rawfile, 'r') as data_file:
while(data_... | 1 | 2016-10-19T17:31:53Z | [
"python",
"python-3.x",
"pandas",
"text"
] |
Python: how to stall execution of function until two threads complete | 40,119,179 | <p>I'm new enough to python programming and starting to dabble with concurrency for the first time, so please forgive any terms.</p>
<p>My programme starts two threads with each call a function "lightshow()" but rather than the programme stalling it's execution until both threads have completed it moves on to the next... | 0 | 2016-10-18T22:33:20Z | 40,119,203 | <pre><code>#send handshake to Relay board to reset it
t2.join() #block until thread exits
setup()
</code></pre>
<p>but since its just a hardcoded timeout why not just</p>
<pre><code>time.sleep(61)
</code></pre>
| 1 | 2016-10-18T22:35:19Z | [
"python",
"multithreading",
"python-multithreading"
] |
Python - Quadratic Equation PLS respond | 40,119,192 | <p>We have to make a program that solves a quadratic equation, I did that part but we also have to include a section where the user inputs what they think the correct answer is and if they are right the program should output something like "You are correct". If they are wrong however, it should output something like "Y... | 0 | 2016-10-18T22:34:24Z | 40,119,861 | <p>I understood that you are having an issue dealing with comparison part. So you can add a realy basic validation, something look like that:
<code>d = float(raw_input("what is your answer: "))
if d*d=root_1*root_1 | d*d=repeated_solution*repeated_solution:
print('correct')
else:
print('false')</code>
Math... | 0 | 2016-10-18T23:50:08Z | [
"python",
"python-2.7",
"python-3.x"
] |
Python - Quadratic Equation PLS respond | 40,119,192 | <p>We have to make a program that solves a quadratic equation, I did that part but we also have to include a section where the user inputs what they think the correct answer is and if they are right the program should output something like "You are correct". If they are wrong however, it should output something like "Y... | 0 | 2016-10-18T22:34:24Z | 40,120,037 | <pre><code>print "This program can be used to solve quadratic equations"
print "Below, please input values for a, b, and c"
print "\n----------------------------\n"
import math
for i in range(39479):
a = float(raw_input("Enter a value for a: "))
b = float(raw_input("Enter a value for b: "))
c = float... | 0 | 2016-10-19T00:12:39Z | [
"python",
"python-2.7",
"python-3.x"
] |
Python: edit child methods for objects contained in child object | 40,119,219 | <p>I apologize for the title...couldn't think of anything else. I have 2 classes as follows:</p>
<pre><code>class Widget:
def __init__(self):
...
def remove(self):
widgets_to_remove.add(self)
def update(self, events, mouse_pos):
pass
def draw(self, screen):
pass
cla... | 0 | 2016-10-18T22:36:28Z | 40,119,993 | <p>It sounds like this is your situation:</p>
<p>You have a class <code>Widget_bundle</code> that has a property <code>Widget_bundle.widget_group</code>. That property is a list of classes <code>Widget</code>.</p>
<p>You want to make a call, for example, <code>Widget_bundle.remove()</code> and translate that to a cal... | 0 | 2016-10-19T00:04:43Z | [
"python",
"inheritance",
"methods"
] |
Python regex issue. Validation works but in two parts, I to extract each valid 'part' separately | 40,119,370 | <p>My code is:</p>
<pre><code>test1 = flight
###Referencelink: http://academe.co.uk/2014/01/validating-flight-codes/
#Do not mess up trailing strings
p = re.compile(r'^([a-z][a-z]|[a-z][0-9]|[0-9][a-z])[a-z]?[0-9]{1,4}[a-z]?$')
m = p.search(test1) # p.match() to find from start of string only
if m:
print '[200],[goo... | 0 | 2016-10-18T22:52:57Z | 40,119,739 | <p>Try this maybe.</p>
<pre><code>p = re.compile(r'^([a-z][a-z]|[a-z][0-9]|[0-9][a-z])([a-z]?[0-9]{1,4}[a-z]?)$')
m = p.findall(test1)
</code></pre>
| 0 | 2016-10-18T23:34:26Z | [
"python",
"regex",
"api",
"extract"
] |
Why additional memory allocation makes multithread Python application work few times faster? | 40,119,420 | <p>I'm writing python module which one of the functions is to check multiple IP addresses if they're active and write this information to database. As those are I/O bound operations I decided to work on multiple threads:</p>
<ul>
<li>20 threads for pinging host and checking if it's active (function <code>check_if_acti... | 0 | 2016-10-18T22:59:22Z | 40,119,583 | <p>In order to give you an exact explanation it would help to know what version of Python you're using. For instance if you're using PyPy then what you've observed is the JIT kicking in after you call your loop 5 times and it just returns a pre-calculated answer. If you're using a standard version of Python then this s... | -1 | 2016-10-18T23:19:42Z | [
"python",
"multithreading"
] |
Find cells with data and use as index in dataframe | 40,119,486 | <p>I'm reading an excel file, but for this question purposes I will provide an example of what my dataframe looks like.
I have a <code>dataframe</code> like so:</p>
<pre><code>df = pd.DataFrame([
['Texas 1', '111', '222', '333'],
['Texas 1', '444', '555', '666'],
['Texas 2', '777','888','999']
... | 3 | 2016-10-18T23:08:51Z | 40,122,055 | <p>first of all, you say "where is not NaN" but you <code>replace</code> with <code>''</code>.<br>
I'll replace <code>''</code> with <code>np.nan</code> then <code>dropna</code></p>
<pre><code>df.iloc[0].replace('', np.nan).dropna().index
Int64Index([0, 1, 3], dtype='int64')
</code></pre>
<hr>
<pre><code>df[df.iloc... | 2 | 2016-10-19T04:18:56Z | [
"python",
"pandas"
] |
php - What is quicker for search and replace in a csv file? In a string or in an array? | 40,119,499 | <p>I am dealing with csv files that usually have between 2 million to 5 million rows. I have (for example) 3000 specific values that need to be replaced by 3000 different values. I have two arrays of 3000 items called $search and $replace. Note: The search and replace phrases are complete values (e.g. ...,search,...... | 1 | 2016-10-18T23:10:27Z | 40,136,692 | <p>If your csv file is that big (> 1 million rows), it might not be the best idea to load it all at once unless memory usage is of no concern to you.</p>
<p>Therefor, I'd recommend running the replace line by line. Here's a very basic example:</p>
<pre><code>$input = fopen($inputFile, 'r');
$output = fopen($outputFil... | 0 | 2016-10-19T16:15:05Z | [
"php",
"python",
"mysql",
"arrays",
"csv"
] |
Swap list / string around a character python | 40,119,616 | <p>I want to swap two parts of a list or string around a specified index, example:</p>
<pre><code>([1, 2, 3, 4, 5], 2)
</code></pre>
<p>should return</p>
<pre><code>[4, 5, 3, 1, 2]
</code></pre>
<p>I'm only supposed to have one line of code, it works for strings but I get</p>
<p>can only concatenate list (not "int... | 3 | 2016-10-18T23:23:00Z | 40,119,652 | <p>It's because you took two slices and one indexing operation and tried to concatenate. slices return sub-lists, indexing returns a single element.</p>
<p>Make the middle component a slice too, e.g. <code>listOrString[index:index+1]</code>, (even though it's only a one element slice) so it keeps the type of whatever ... | 5 | 2016-10-18T23:26:06Z | [
"python"
] |
Detect Unicode empty value in a dictionary | 40,119,634 | <p>I have something like this in a list.</p>
<pre><code>my_arr = [{'Brand_Name': u''}, {'Brand_Name':u''}, {'Brand_Name':u'randomstr1'}]
</code></pre>
<p>I want to be able to get all the values that are empty for brand name. In thise case I'd get two empty values. I tried this</p>
<pre><code>for dictionary in my_... | 1 | 2016-10-18T23:24:30Z | 40,119,654 | <p>You can just check for falsey values with <code>if not ...</code> (this will also include <code>None</code>, <code>[]</code>, <code>()</code>, etc)</p>
<pre><code>>>> brands = [
{'Brand_Name': u''},
{'Brand_Name':u''},
{'Brand_Name':u'randomstr1'},
]
>>> for brand in br... | 1 | 2016-10-18T23:26:25Z | [
"python",
"unicode",
"syntax"
] |
How to loop through a list and then swap digits for other instances of the loop to see? | 40,119,661 | <p>I have an XML Document with a structure like this:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
<url>
<loc>https://www.website.com/</loc>
<ch... | 0 | 2016-10-18T23:27:12Z | 40,120,515 | <p>This version remembers the newest addition date (and time):</p>
<pre><code>import jdcal
def julian(y, m, d, h, mi, s):
return sum(jdcal.gcal2jd(y, m, d)) + (h-12.0)/24 + mi/1440.0 + s/86400.0
tree = get_xml_data(line)
to_log(tree)
julNewest = 0.0 ... | 0 | 2016-10-19T01:14:21Z | [
"python",
"xml",
"list",
"loops",
"compare"
] |
Django model formset factory and forms | 40,119,792 | <p>I'm trying to user Django model formset factory to render a template where a user can add images and change the images they have uploaded(very similar to what can be done in the admin). I currently can render the template and its correct fields to the template. What I cannot do is have the user preselected(want curr... | 0 | 2016-10-18T23:41:03Z | 40,125,395 | <p>let me explain the way you can do it.</p>
<h1>MODELS</h1>
<pre><code>from django.utils.text import slugify
from django.db import models
from custom_user.models import AbstractEmailUser
# User model
class UserModel(AbstractEmailUser):
full_name = models.CharField(max_length=255)
def __str__(self):
... | 0 | 2016-10-19T07:56:57Z | [
"python",
"django",
"django-forms"
] |
Python 3.x : using a list, if a letter isn't in that list, add it. otherwise, increment the value by 1 | 40,119,855 | <p>so this is what I'm doing: I'm pulling up a file and having the program read it. Every time it encounters a letter, it'll add the letter to list1 and add '1' to list2. Every time it encounters a letter in list1, it'll increment list2 by 1. </p>
<pre><code>txt = open("Nameoffile.txt")
wordcount = 0
Charcount = 0
let... | -1 | 2016-10-18T23:49:43Z | 40,119,936 | <p>Lists work with integer indexes, you can use a dictionary instead:</p>
<pre><code>lettercount = {} #list 2
</code></pre>
<p>Dictionaries have the capacity to store key, values objects, so you can use not numeric keys to acees values. Their use is similar to the lists so you can still use:</p>
<pre><code>lettercou... | 0 | 2016-10-18T23:58:37Z | [
"python",
"list",
"python-3.x",
"append",
"increment"
] |
Python 3.x : using a list, if a letter isn't in that list, add it. otherwise, increment the value by 1 | 40,119,855 | <p>so this is what I'm doing: I'm pulling up a file and having the program read it. Every time it encounters a letter, it'll add the letter to list1 and add '1' to list2. Every time it encounters a letter in list1, it'll increment list2 by 1. </p>
<pre><code>txt = open("Nameoffile.txt")
wordcount = 0
Charcount = 0
let... | -1 | 2016-10-18T23:49:43Z | 40,119,953 | <p>lettercount should be type dict, not list.
Type dict maps a unique key to a value, while list just contains values.
The value within brackets for a list should be an integer referring to a position in the list, while a dictionary will reference the key in brackets. </p>
| -1 | 2016-10-19T00:00:05Z | [
"python",
"list",
"python-3.x",
"append",
"increment"
] |
Python 3.x : using a list, if a letter isn't in that list, add it. otherwise, increment the value by 1 | 40,119,855 | <p>so this is what I'm doing: I'm pulling up a file and having the program read it. Every time it encounters a letter, it'll add the letter to list1 and add '1' to list2. Every time it encounters a letter in list1, it'll increment list2 by 1. </p>
<pre><code>txt = open("Nameoffile.txt")
wordcount = 0
Charcount = 0
let... | -1 | 2016-10-18T23:49:43Z | 40,120,416 | <p>That line of your function essentially tries to do something like this:</p>
<pre><code>lettercount['a'] += 1
</code></pre>
<p>which doesn't really make any sense. Lists are ordered collections and are only accessible via numerical index, which is why you get an error telling you that an integer is required (not a ... | 0 | 2016-10-19T01:01:19Z | [
"python",
"list",
"python-3.x",
"append",
"increment"
] |
Pythonic way to create list of address letter/numbers from an input address range like 1-12A | 40,119,867 | <p>Simple case: For a given string input like '1-12A', I'd like to output a list like</p>
<pre><code>['1A', '2A', '3A', ... , '12A']
</code></pre>
<p>That's easy enough, I could use something like the following code:</p>
<pre><code>import re
input = '1-12A'
begin = input.split('-')[0] #the first ... | 1 | 2016-10-18T23:50:58Z | 40,120,439 | <p>I'm not sure if there's a more <em>pythonic</em> way of doing it, but using some regexes and python's <a href="https://docs.python.org/2/library/stdtypes.html#str.format" rel="nofollow"><code>format</code></a> syntax, we can fairly easily deal with your inputs. Here is a solution :</p>
<pre><code>import re
def add... | 2 | 2016-10-19T01:03:38Z | [
"python",
"list",
"functional-programming",
"list-comprehension",
"leading-zero"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.