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
Navigating pagination with selenium
39,534,584
<p>I am getting stuck on a weird case of pagination. I am scraping search results from <a href="https://cotthosting.com/NYRocklandExternal/LandRecords/protected/SrchQuickName.aspx" rel="nofollow">https://cotthosting.com/NYRocklandExternal/LandRecords/protected/SrchQuickName.aspx</a></p> <p>I have search results that ...
1
2016-09-16T14:59:24Z
39,536,073
<p>Click on the "last page" for get his numbers, and then click in each child.</p>
0
2016-09-16T16:20:05Z
[ "python", "loops", "selenium", "selenium-webdriver", "pagination" ]
TypeError: first argument must be an iterable of pandas objects, you passed an object of type "DataFrame"
39,534,676
<p>I have a big dataframe and I try to split that and after <code>concat</code> that. I use</p> <pre><code>df2 = pd.read_csv('et_users.csv', header=None, names=names2, chunksize=100000) for chunk in df2: chunk['ID'] = chunk.ID.map(rep.set_index('member_id')['panel_mm_id']) df2 = pd.concat(chunk, ignore_index=True...
1
2016-09-16T15:03:14Z
39,534,745
<p>IIUC you want the following:</p> <pre><code>df2 = pd.read_csv('et_users.csv', header=None, names=names2, chunksize=100000) chunks=[] for chunk in df2: chunk['ID'] = chunk.ID.map(rep.set_index('member_id')['panel_mm_id']) chunks.append(chunk) df2 = pd.concat(chunks, ignore_index=True) </code></pre> <p>You ...
1
2016-09-16T15:06:38Z
[ "python", "pandas" ]
Python requests SSL error [SSL: UNKNOWN_PROTOCOL] while getting https://www.nfm.com
39,534,804
<p>Using Python 3.4 and requests 2.11.1 package to get '<a href="https://www.nfm.com" rel="nofollow">https://www.nfm.com</a>' website, requests throws an SSLError [SSL: UNKNOWN_PROTOCOL]. I'm able to get a valid response from other https sites such as pythonanywhere.com and amazon.com. The error is only encountered try...
1
2016-09-16T15:09:40Z
39,535,211
<p>According to <a href="https://www.ssllabs.com/ssltest/analyze.html?d=www.nfm.com" rel="nofollow">SSLLabs</a> the server supports only TLS 1.1 and higher. My guess is that you have an older OpenSSL version which is not able to speak this version. Support for TLS 1.1 and TLS 1.2 was added with OpenSSL 1.0.1 years ago ...
1
2016-09-16T15:31:27Z
[ "python", "ssl", "https", "python-requests" ]
Is there a Python equivalent to the C# ?. and ?? operators?
39,534,935
<p>For instance, in C# (starting with v6) I can say:</p> <pre><code>mass = (vehicle?.Mass / 10) ?? 150; </code></pre> <p>to set mass to a tenth of the vehicle's mass if there is a vehicle, but 150 if the vehicle is null (or has a null mass, if the Mass property is of a nullable type).</p> <p>Is there an equivalent c...
6
2016-09-16T15:16:18Z
39,535,290
<p>No, Python does not (yet) have NULL-coalescing operators. </p> <p>There is a <em>proposal</em> (<a href="https://www.python.org/dev/peps/pep-0505/">PEP 505 – <em>None-aware operators</em></a>) to add such operators, but no consensus exists wether or not these should be added to the language at all and if so, what...
9
2016-09-16T15:35:23Z
[ "python", "ironpython" ]
python pandas Ignore Nan in integer comparisons
39,534,941
<p>I am trying to create dummy variables based on integer comparisons in series where Nan is common. A > comparison raises errors if there are any Nan values, but I want the comparison to return a Nan. I understand that I could use fillna() to replace Nan with a value that I know will be false, but I would hope there...
0
2016-09-16T15:16:37Z
39,535,163
<p>Here's a way:</p> <pre><code>s1 = pd.Series([1, 3, 4, 2, np.nan, 5, np.nan, 7]) s2 = pd.Series([2, 1, 5, 5, np.nan, np.nan, 2, np.nan]) (s1 &lt; s2).mask(s1.isnull() | s2.isnull(), np.nan) Out: 0 1.0 1 0.0 2 1.0 3 1.0 4 NaN 5 NaN 6 NaN 7 NaN dtype: float64 </code></pre> <p>This masks the ...
3
2016-09-16T15:28:40Z
[ "python", "pandas" ]
Phrasequery to make researches
39,535,046
<p>Is there anyway to use phrasequery with python? until now i was using parser, but i would like to know how to use phrasequery.</p> <pre><code>parser = QueryParser(Version.LUCENE_CURRENT, "contents", analyzer) parser.setDefaultOperator(QueryParser.Operator.AND) query = parser.parse(command) ...
0
2016-09-16T15:22:31Z
39,535,425
<p>Firstly, you should understand that when you cut out the QueryParser, you lose the analyzer. <code>PhraseQuery</code> won't analyze for you, like the QueryParser does, so it's on you to tokenize and normalize your phrase to match the index-time analysis. You may be better off sticking with the parser.</p> <p>That...
0
2016-09-16T15:43:08Z
[ "python", "lucene" ]
Python Iteration in list
39,535,049
<p>Is there a way to test whether an item in a list has repetitions of 5 digits and above, and the repetitions being adjacent to each other?</p> <pre><code>#!/usr/bin/env python import itertools from collections import Counter mylist = ['000002345','1112345','11122222345','1212121212'] #some function code here #exp...
0
2016-09-16T15:22:42Z
39,535,161
<blockquote> <p>The condition is that i only want the items with a repetition of 5 digits and above</p> </blockquote> <p>Use a <a href="https://docs.python.org/3/library/re.html" rel="nofollow">regular expression</a>:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; mylist = ['000002345', '1112345', '1112222234...
2
2016-09-16T15:28:33Z
[ "python" ]
Python Iteration in list
39,535,049
<p>Is there a way to test whether an item in a list has repetitions of 5 digits and above, and the repetitions being adjacent to each other?</p> <pre><code>#!/usr/bin/env python import itertools from collections import Counter mylist = ['000002345','1112345','11122222345','1212121212'] #some function code here #exp...
0
2016-09-16T15:22:42Z
39,535,374
<p>You could use <code>itertools.groupby</code></p> <pre><code>&gt;&gt;&gt; from itertools import groupby &gt;&gt;&gt; [item for item in mylist if any(len(list(y))&gt;=5 for x,y in groupby(item))] ['000002345', '11122222345'] </code></pre>
1
2016-09-16T15:40:10Z
[ "python" ]
Confusion with comparison error
39,535,140
<p>When i run the following </p> <pre class="lang-python prettyprint-override"><code>def max(L): m = L[0][0] for item in L: if item[0] &gt; m: m = item return m L = [[20, 10], [10, 20], [30, 20],[12,16]] print(max(L)) </code></pre> <p>i get the error <code>TypeError: unorderable typ...
-4
2016-09-16T15:27:25Z
39,535,264
<p>In the first iteration of your <em>for</em> loop, doing <code>m = item</code> makes <code>m</code> reference a <code>list</code> which afterwards cannot be compared with an <code>int</code> (viz. <code>item[0] &gt; m</code>) in the next iteration. </p> <p>You should instead assign <code>m</code> to one of the eleme...
2
2016-09-16T15:34:21Z
[ "python", "list", "int", "comparison" ]
Confusion with comparison error
39,535,140
<p>When i run the following </p> <pre class="lang-python prettyprint-override"><code>def max(L): m = L[0][0] for item in L: if item[0] &gt; m: m = item return m L = [[20, 10], [10, 20], [30, 20],[12,16]] print(max(L)) </code></pre> <p>i get the error <code>TypeError: unorderable typ...
-4
2016-09-16T15:27:25Z
39,535,464
<p>As Moses Koledoye says, you are getting that <code>TypeError: unorderable types: int() &gt; list()</code> error because the first assignment in the loop assigns the whole <code>item</code> to <code>m</code>, so the next time you attempt to compare you're comparing the list <code>m</code> with the integer <code>item[...
0
2016-09-16T15:45:31Z
[ "python", "list", "int", "comparison" ]
Stuck with nested for loop issue
39,535,377
<p>A website changes content dynamically, through the use of two date filters (year / week), without the need of a get request (it is handled asynchronously on the client side). Each filter option produces a different page_source with td elements I would like to extract.</p> <p>Currently, I am using a nested list for-...
0
2016-09-16T15:40:29Z
39,535,671
<p>Create a new list object per filter combination, so inside the <code>for w in weeks:</code> loop. Append your cell text to <em>that</em> list, and append the per-filter list this produces to <code>store</code>:</p> <pre><code>def getData(): store = [] year = ['2015','2014'] for y in year: # ......
1
2016-09-16T15:56:59Z
[ "python", "for-loop" ]
PyKCS11 unhashable list
39,535,387
<p>A python script of mine is designed to get detailed information of slots/tokens in a particular .so library. The output looks like this:</p> <pre><code>Library manufacturerID: Safenet, Inc. Available Slots: 4 Slot no: 0 slotDescription: ProtectServer K5E:00045 manufacturerID: SafeNet Inc. TokenIn...
0
2016-09-16T15:40:53Z
40,052,063
<p>(This answer was put together in the context of your other questions)</p> <p>To read attributes of a PKCS#11 object <code>o</code> you can use the following code:</p> <pre><code># List which attributes you want to read attributeIds = [ CKA_ENCRYPT, CKA_CLASS, CKA_DECRYPT, CKA_SIGN, CKA_VERIFY, ...
0
2016-10-14T21:11:41Z
[ "python", "list", "dictionary", "typeerror", "pkcs#11" ]
AttributeError: 'DataFrame' object has no attribute 'map'
39,535,447
<p>I wanted to convert the spark data frame to add using the code below:</p> <pre><code>from pyspark.mllib.clustering import KMeans spark_df = sqlContext.createDataFrame(pandas_df) rdd = spark_df.map(lambda data: Vectors.dense([float(c) for c in data])) model = KMeans.train(rdd, 2, maxIterations=10, runs=30, initializ...
2
2016-09-16T15:44:46Z
39,536,218
<p>You can't <code>map</code> a dataframe, but you can convert the dataframe to an RDD and map that by doing <code>spark_df.rdd.map()</code>. Prior to Spark 2.0, <code>spark_df.map</code> would alias to <code>spark_df.rdd.map()</code>. With Spark 2.0, you must explicitly call <code>.rdd</code> first. </p>
3
2016-09-16T16:28:47Z
[ "python", "apache-spark", "pyspark", "spark-dataframe", "apache-spark-mllib" ]
appending to python lists
39,535,481
<p>I have a web scrapper that returns me values like the example below. </p> <pre><code># Other code above here. test = [] results = driver.find_elements_by_css_selector("li.result_content") for result in results: # Other code about result.find_element_by_blah_blah product_feature = result.find_element_by_cla...
0
2016-09-16T15:46:16Z
39,535,621
<p>Rather than <code>print</code>, append your results to lists; one new list per iteration of the outer loop:</p> <pre><code>test = [] results = driver.find_elements_by_css_selector("li.result_content") for result in results: # Other code about result.find_element_by_blah_blah product_feature = result.find_e...
2
2016-09-16T15:54:34Z
[ "python", "list" ]
appending to python lists
39,535,481
<p>I have a web scrapper that returns me values like the example below. </p> <pre><code># Other code above here. test = [] results = driver.find_elements_by_css_selector("li.result_content") for result in results: # Other code about result.find_element_by_blah_blah product_feature = result.find_element_by_cla...
0
2016-09-16T15:46:16Z
39,535,716
<p>OK, not exactly sure what you want, but the code below will give the output you want:</p> <pre><code>test = [] results = driver.find_elements_by_css_selector("li.result_content") for result in results: # Other code about result.find_element_by_blah_blah product_feature = result.find_element_by_class_name("...
0
2016-09-16T15:59:03Z
[ "python", "list" ]
QT Creator converted ui to py working in windows terminal but not working with spyder IDE
39,535,486
<p>I am following a tutorial on making a basic GUI with QT creator and python. I have successfully created a window with a button that closes the window when pressed. It works fine in QT Creator and I converted the ui file to py and it runs and creates the window as expected when I open a command prompt window and call...
0
2016-09-16T15:46:24Z
39,537,547
<p>It's hard to say without the actual traceback. I'm guessing it's one of two things, both related to the fact that Spyder is also built on Qt.</p> <ol> <li><p>You're trying to run your app within the Spyder environment. Your app tries to create a <code>QApplication</code>, but because Spyder already runs on <code>...
0
2016-09-16T17:58:56Z
[ "python", "user-interface", "pyqt", "pyqt4", "spyder" ]
Acessing rows and columns in dictionary
39,535,522
<p>I have a dictionary that has its keys as tuples and values assigned to these keys.</p> <p>I want to perform a set of actions based on the keys positions.</p> <p>Here is my code that I have written so far.</p> <p>Dictionary:</p> <pre><code>p={(0, 1): 2, (1, 2): 6, (0, 0): 1, (2, 0): 7, (1, 0): 4, (2, 2): 9, (1, 1...
0
2016-09-16T15:49:05Z
39,535,662
<p>If you flip <code>x</code> and <code>y</code> in your code for <code>r</code>, it seems to output the way you desire. For example,</p> <pre><code>r=[[p[(x,y)] for y in range(3)] for x in range(3)] </code></pre> <p>results in </p> <blockquote> <p>[[1, 2, 3], [4, 5, 6], [7, 8, 9]]</p> </blockquote>
1
2016-09-16T15:56:39Z
[ "python", "dictionary" ]
Acessing rows and columns in dictionary
39,535,522
<p>I have a dictionary that has its keys as tuples and values assigned to these keys.</p> <p>I want to perform a set of actions based on the keys positions.</p> <p>Here is my code that I have written so far.</p> <p>Dictionary:</p> <pre><code>p={(0, 1): 2, (1, 2): 6, (0, 0): 1, (2, 0): 7, (1, 0): 4, (2, 2): 9, (1, 1...
0
2016-09-16T15:49:05Z
39,535,750
<p>I had tried to do several things in the code. I had written it but did not realize that and went on trying different combinations with code.</p> <p>Here is the answer:</p> <pre><code>z=[[p[(i,j)] for j in range(3)] for i in range(3)] </code></pre> <p>Thanks!</p>
1
2016-09-16T16:00:52Z
[ "python", "dictionary" ]
Expecting property name enclosed in double quotes - converting a string to a json object using Python
39,535,527
<p>I am trying to convert a string to JSON using python using the following code:</p> <pre><code>myStr = '[{u"total": "54", u"value": "54", u"label": u"16 Sep"}, {u"total": "58", u"value": "4", u"label": u"16 Sep"}, {u"total": "65", u"value": "7", u"label": u"16 Sep"}, {u"total": "65", u"value": "0", u"label": u"16 Se...
0
2016-09-16T15:49:23Z
39,535,598
<p>Remove the unicode qualifier from the string. <code>json.loads</code> assumes the property names are already in unicode.</p>
2
2016-09-16T15:53:24Z
[ "python", "json" ]
Expecting property name enclosed in double quotes - converting a string to a json object using Python
39,535,527
<p>I am trying to convert a string to JSON using python using the following code:</p> <pre><code>myStr = '[{u"total": "54", u"value": "54", u"label": u"16 Sep"}, {u"total": "58", u"value": "4", u"label": u"16 Sep"}, {u"total": "65", u"value": "7", u"label": u"16 Sep"}, {u"total": "65", u"value": "0", u"label": u"16 Se...
0
2016-09-16T15:49:23Z
39,535,692
<p>Putting together the puzzle pieces from this question and <a href="http://stackoverflow.com/questions/39534841/getting-syntaxerror-json-parse-error-expected-when-trying-to-convert-a-str">Getting SyntaxError: JSON Parse error: Expected &#39;}&#39; when trying to convert a string into JSON using javascript</a>, you wa...
0
2016-09-16T15:57:45Z
[ "python", "json" ]
Expecting property name enclosed in double quotes - converting a string to a json object using Python
39,535,527
<p>I am trying to convert a string to JSON using python using the following code:</p> <pre><code>myStr = '[{u"total": "54", u"value": "54", u"label": u"16 Sep"}, {u"total": "58", u"value": "4", u"label": u"16 Sep"}, {u"total": "65", u"value": "7", u"label": u"16 Sep"}, {u"total": "65", u"value": "0", u"label": u"16 Se...
0
2016-09-16T15:49:23Z
39,535,754
<pre><code>import json myStr = '[{"total": 54, "value": 54, "label": "u16 Sep"}, {"total": 58, "value": 4, "label": "u16 Sep"}, {"total": 65, "value": 7, "label":" u16 Sep"}, {"total": 65, "value": 0,"label": "u16 Sep"}]' obj = json.loads(myStr) print(repr(obj)) </code></pre> <p>You try load incorrect JSON, you can ch...
0
2016-09-16T16:01:01Z
[ "python", "json" ]
python: DataFrame.append does not append element
39,535,597
<p>I am working one week with python and I need some help. I want that if certain condition is fulfilled, it adds a value to a database. My program doesn't give an error but it doesn't append an element to my database </p> <pre><code>import pandas as pd noTEU = pd.DataFrame() # empty database index_TEU = 0 for vessel ...
1
2016-09-16T15:53:21Z
39,535,717
<p>You should reassign the dataframe such as:</p> <pre><code>import pandas as pd noTEU = pd.DataFrame() # empty database index_TEU = 0 for vessel in list: if condition is fullfilled: imo_vessel = pd.DataFrame({'imo': vessel}, index=[index_TEU]) noTEU = noTEU.append(imo_vessel) # I want here to a...
0
2016-09-16T15:59:04Z
[ "python", "pandas" ]
Comparing two lists of dictionaries in Python
39,535,712
<p>I would like to make a function that compares two lists of dictionaries in python by looking at their keys. When list A contains a dictionary that has an entry with the same key as an entry in the dictionary in list B, the function should return True.</p> <p>Here's an example of list A and B:</p> <pre><code>listA ...
0
2016-09-16T15:58:50Z
39,535,889
<p>first you have to take the keys out of the list of dictionaries, then compare.</p> <pre><code>keysA = [k for x in listA for k in x.keys()] keysB = [k for x in listB for k in x.keys()] any(k in keysB for k in keysA) </code></pre>
2
2016-09-16T16:08:06Z
[ "python", "list", "dictionary" ]
Comparing two lists of dictionaries in Python
39,535,712
<p>I would like to make a function that compares two lists of dictionaries in python by looking at their keys. When list A contains a dictionary that has an entry with the same key as an entry in the dictionary in list B, the function should return True.</p> <p>Here's an example of list A and B:</p> <pre><code>listA ...
0
2016-09-16T15:58:50Z
39,536,071
<p>Is this what you are looking for?</p> <pre><code>def cmp_dict(a, b): return any(frozenset(c) &amp; frozenset(d) for c, d in zip(a, b)) </code></pre> <p>Here is a demonstration of its usage:</p> <pre><code>&gt;&gt;&gt; listA = [{'key1':'value1'}, {'key2':'value2'}] &gt;&gt;&gt; listB = [{'key1':'value3'}, {'ke...
0
2016-09-16T16:20:03Z
[ "python", "list", "dictionary" ]
Setup pjsip for Python
39,535,729
<p>I'm trying to install pjsip's Python binding but am running into a build error that I feel is environmental but am just not able to figure out what's wrong.</p> <p>I'm able to build pjsip without issue but run into a problem when trying to build the python bindings -- I'm getting an error from ld about a bad value ...
0
2016-09-16T15:59:53Z
39,573,027
<p>I was able to find an answer in an old mailing list entry (<a href="http://lists.pjsip.org/pipermail/pjsip_lists.pjsip.org/2008-August/004456.html" rel="nofollow">http://lists.pjsip.org/pipermail/pjsip_lists.pjsip.org/2008-August/004456.html</a>).</p> <p>Set CFLAGS=-fPIC and rebuild the PJSIP library (make clean &a...
0
2016-09-19T12:19:26Z
[ "python", "pjsip" ]
apply vector of functions to vector of arguments
39,535,756
<p>I'd like to take in a list of functions, <code>funclist</code>, and return a new function which takes in a list of arguments, <code>arglist</code>, and applies the <code>i</code>th function in <code>funclist</code> to the <code>i</code>th element of <code>arglist</code>, returning the results in a list:</p> <pre><c...
0
2016-09-16T16:01:04Z
39,536,845
<p>In <code>numpy</code> terms true vectorization means performing the iterative stuff in compiled code. Usually that requires using <code>numpy</code> functions that work with whole arrays, doing thing like addition and indexing.</p> <p><code>np.vectorize</code> is a way of iterate of several arrays, and using their...
1
2016-09-16T17:11:16Z
[ "python", "numpy", "vectorization" ]
Python version compatibility with Windows Server 2003
39,535,762
<p>Which versions of python are compatible with Windows Server 2003? I'm using 32-bit (x86)</p> <p>Can versions 3.x be installed?</p> <p>Why I'm asking is because I've installed Python 3.5.2 on Windows Server 2003 and when I try to run it, it gives me an error "python.exe is not a valid Win32 application" </p>
0
2016-09-16T16:01:25Z
39,536,032
<p>The <a href="https://www.python.org/" rel="nofollow">official Site</a> (when pointing the mouse on Downloads) states that you cannot use Python 3.5+ on Windows XP and earlier (implying that earlier versions are usable) - Windows Server 2003 has many parts in common with XP so <em>propably</em> 3.5+ will not work the...
0
2016-09-16T16:17:27Z
[ "python", "version", "windows-server-2003" ]
Calculate cumulative p_value hourly in pandas
39,535,777
<p>I am wondering if there is a way to calculate the cumulative p_value for each hour of data in a dataframe. For example if you have 24 hours of data there would be 24 measurements of p_value, but they would be cumulative for all hours before the current hour.</p> <p>I have been able to get the p_value for each hour ...
0
2016-09-16T16:02:21Z
39,537,492
<p>So i came up with a workaround on my own for this one.</p> <p>What I came up with was modifying <code>calc_p()</code> such that it utilized global variables and thus could use updated values each time it was called by the aggfunc. Below is the edited code:</p> <pre><code>def calc_p(group): global df_old_len, d...
0
2016-09-16T17:54:48Z
[ "python", "pandas", "grouping", "p-value" ]
closing MYSQL JDBC connection in Spark
39,535,814
<p>I am loading data from MYSQL server to Spark through JDBC, but I need to close that connection after loading the data. What is the exact syntax for closing connection?</p> <pre><code>df_mysql = sqlContext.read.format("jdbc").options( url="jdbc:mysql://***/****”, driver="com.mysql.jdbc.Driver", dbtable="((SE...
0
2016-09-16T16:04:16Z
39,536,107
<p>There is really nothing to be closed here. <code>DateFrame</code> object is not a JDBC connection and <code>load</code> doesn't really <code>load</code> data. It simply fetches metadata required to build <code>DataFrame</code>.</p> <p>Actual data processing takes place only when you execute a job which contains tas...
2
2016-09-16T16:22:18Z
[ "python", "mysql", "jdbc", "apache-spark", "pyspark" ]
Installing Scala kernel (or Spark/Toree) for Jupyter (Anaconda)
39,535,858
<p>I'm running RHEL 6.7, and have Anaconda set up. (anaconda 4.10). Jupyter is working OOTB, and it by default has the Python kernel. Everything is dandy so I can select "python notebook" in Jupyter.</p> <p>I'm now looking to get Scala set up with Jupyter as well. (which it seems like Spark kernel - now Toree will wor...
2
2016-09-16T16:06:09Z
39,554,112
<p>First, make sure you set the SPARK_HOME variable in your shell environment to point to where spark is located, for example:</p> <pre><code>export SPARK_HOME=$HOME/Downloads/spark-2.0.0-bin-hadoop2.7 </code></pre> <p>next install toree with</p> <pre><code>sudo jupyter toree install --spark_home=$SPARK_HOME </code>...
0
2016-09-18T04:29:24Z
[ "python", "scala", "jupyter", "jupyter-notebook", "apache-toree" ]
Installing Scala kernel (or Spark/Toree) for Jupyter (Anaconda)
39,535,858
<p>I'm running RHEL 6.7, and have Anaconda set up. (anaconda 4.10). Jupyter is working OOTB, and it by default has the Python kernel. Everything is dandy so I can select "python notebook" in Jupyter.</p> <p>I'm now looking to get Scala set up with Jupyter as well. (which it seems like Spark kernel - now Toree will wor...
2
2016-09-16T16:06:09Z
39,628,777
<p>If you are trying to get spark 2.0 with 2.11 you may get strange msgs. You need to update to latest toree 0.2.0 For Ubuntu 16.04 64bit. I have package &amp; tgz file in <a href="https://anaconda.org/hyoon/toree" rel="nofollow">https://anaconda.org/hyoon/toree</a></p> <p>That's for python 2.7 &amp; you will need co...
0
2016-09-22T01:15:05Z
[ "python", "scala", "jupyter", "jupyter-notebook", "apache-toree" ]
Python break from if statement to else
39,535,877
<p>(I'm a Python newbie, so apologies for this basic question I for some reason couldn't find an answer to.)</p> <p>I have a nested if statement with the if statement of an if/else block. In the <em>nested</em> if statement, if it it meets the criteria, I'd like the code to break to the else statement. When I put a br...
0
2016-09-16T16:07:25Z
39,536,021
<p><code>break</code> is used when you want to break out of loops not if statments. You can have another if statement that executes this logic for you like this:</p> <pre><code>if (s[i] &lt;= s[i+1]): alpha_count += 1 elif (i+1 == (len(s)-1)) or (add boolean expression for else part in here too something like s[i]...
1
2016-09-16T16:16:19Z
[ "python", "if-statement", "break" ]
Find a more efficient way to code an If statement in python
39,535,878
<p>it's the second time I'm confronted to this kind of code : </p> <pre><code> if "associé" in gender or "gérant" in gender or "président" in gender or "directeur" in gender: gen = "male" elif "associée" in gender or "gérante" in gender or "présidente" in gender or "directrice" in gender: gen = "femal...
1
2016-09-16T16:07:25Z
39,535,982
<p>If you cannot have multiple of these stings in one <code>gender</code> string, maybe something like this?</p> <pre><code>gen = "error" for g in ["associé", "gérant", "président", "directeur"]: if g in gender: gen = "male" break for g in ["associée" "gérante", "présidente", "directrice"]: ...
0
2016-09-16T16:14:05Z
[ "python", "if-statement" ]
Find a more efficient way to code an If statement in python
39,535,878
<p>it's the second time I'm confronted to this kind of code : </p> <pre><code> if "associé" in gender or "gérant" in gender or "président" in gender or "directeur" in gender: gen = "male" elif "associée" in gender or "gérante" in gender or "présidente" in gender or "directrice" in gender: gen = "femal...
1
2016-09-16T16:07:25Z
39,535,985
<p>I personally like doing this with <a href="https://docs.python.org/2/library/sets.html#set-objects" rel="nofollow"><code>sets</code></a>. For example:</p> <pre><code>opts = ["associé", "gérant", "président", "directeur"] if set(opts) &amp; set(gender): ... </code></pre> <p><code>&amp;</code> is used for the s...
3
2016-09-16T16:14:13Z
[ "python", "if-statement" ]
Find a more efficient way to code an If statement in python
39,535,878
<p>it's the second time I'm confronted to this kind of code : </p> <pre><code> if "associé" in gender or "gérant" in gender or "président" in gender or "directeur" in gender: gen = "male" elif "associée" in gender or "gérante" in gender or "présidente" in gender or "directrice" in gender: gen = "femal...
1
2016-09-16T16:07:25Z
39,536,009
<p>Using lists and <code>any</code>:</p> <pre><code>males = ["associé", "gérant", "président", "directeur"] females = ["associée", "gérante", "présidente", "directrice"] if any(m in gender for m in males): gen = "male" elif any(m in gender for m in females): gen = "female" else: gen = "Error" </code...
4
2016-09-16T16:15:42Z
[ "python", "if-statement" ]
Printing Column Names and Values in Dataframe
39,535,939
<p>The end goal of this question is to plot X and Y for a graph using a dataframe. </p> <p>I have a dataframe like so:</p> <pre><code> Open High Low Close Volume stock symbol Date 2000-10-19 1.37 1.42 1.24 1.35 3...
0
2016-09-16T16:11:03Z
39,536,154
<p>You can <code>reset_index</code> on the data-frame and then print the subset dataframe consisting of the two columns</p> <pre><code>&gt;&gt;&gt; df a b Date 2000-10-19 1 3 2000-10-20 2 4 2000-10-21 3 5 2000-10-22 4 6 2000-10-23 5 7 &gt;&gt;&gt; print(df.reset_index()[['Date', 'a']...
3
2016-09-16T16:24:57Z
[ "python", "python-3.x", "pandas", "dataframe" ]
Migration clashes with forms.py
39,535,983
<p>The command <code>python manage.py makemigrations</code> fails most of time due to the <code>forms.py</code>, in which new models or new fields are referenced at class definition level.</p> <p>So I have to comment each such definitions for the migration to operate. It's a painfull task.</p> <p>I don't understand w...
0
2016-09-16T16:14:09Z
39,547,578
<p>Thanks to @alasdair I understood my problem and found a workaround: I replace the original code in the <code>views.py</code> file</p> <pre><code>from MyApp import forms </code></pre> <p>with</p> <pre><code>import sys if 'makemigrations' not in sys.argv and 'migrate' not in sys.argv: from MyApp import forms </...
0
2016-09-17T13:50:32Z
[ "python", "django", "django-forms", "django-migrations" ]
How to convert a datetime.time type to float in python?
39,536,000
<p>I am performing a data analysis with python. I need to convert a data type from datatime.time to float, something like what makes Excel when we change the cell format from "time" to "number".</p> <p><a href="http://i.stack.imgur.com/fwvHt.png" rel="nofollow"><img src="http://i.stack.imgur.com/fwvHt.png" alt="enter ...
0
2016-09-16T16:14:59Z
39,536,110
<p>The decimal number used by Excel is simply the fraction of a day that a time represents, with midnight being 0.0. You simply take the hours, minutes, and seconds in the time and divide by the fraction of a day they represent:</p> <pre><code>def excel_time(time): return time.hour / 24.0 + time.minute / (24.0*60...
2
2016-09-16T16:22:35Z
[ "python", "python-3.x", "time" ]
In python what is the correct nomenclature for accessing a class attribute using dot notation?
39,536,013
<p>This is semantics question, I'm writing a tutorial for a module that I hacked together for my lab and I would like to know if there is a correct term for accessing a class attribute by using dot notation. For example:</p> <pre><code>class funzo: def __init__(self,string): self.attribute = string fun = f...
2
2016-09-16T16:16:02Z
39,536,348
<p>Attribute Access, this is from the language reference section on <a href="https://docs.python.org/3/reference/datamodel.html#customizing-attribute-access" rel="nofollow">customizing it</a>:</p> <blockquote> <p>The following methods can be defined to customize the meaning of <em>attribute access</em> (use of, assi...
6
2016-09-16T16:36:08Z
[ "python", "python-3.x", "oop" ]
Python code working differently after a print statement
39,536,076
<p>I'm trying to use regex to search the keys in a dict and return the matches. The following code is simplified from the real code but shows the problem.</p> <pre><code>#!/bin/python # Import standard Python modules import os, sys, string, pdb, re key="" pat="" steps = {"pcb":"xxx","aoi":"xxx","pcb-pec":"xxx","pc...
-1
2016-09-16T16:20:17Z
39,536,118
<p>The signature of <code>re.search</code> (given as <a href="https://docs.python.org/2/library/re.html#re.search" rel="nofollow"><code>re.search(pattern, string, flags=0)</code></a>) takes the pattern first, then the string. </p> <p>You should swap the order of the parameters:</p> <pre><code>re.search(pat, key) # ...
2
2016-09-16T16:22:55Z
[ "python", "regex", "python-2.7" ]
Python code working differently after a print statement
39,536,076
<p>I'm trying to use regex to search the keys in a dict and return the matches. The following code is simplified from the real code but shows the problem.</p> <pre><code>#!/bin/python # Import standard Python modules import os, sys, string, pdb, re key="" pat="" steps = {"pcb":"xxx","aoi":"xxx","pcb-pec":"xxx","pc...
-1
2016-09-16T16:20:17Z
39,536,119
<p>You change the order of parameters in your last case. You have them out of order the first couple of times, and in the correct order the last time</p> <pre><code>re.search(pat,key) </code></pre> <p>is the correct order.</p> <p>In the loop, you're getting a match the one time the pattern and the string happen to b...
2
2016-09-16T16:23:01Z
[ "python", "regex", "python-2.7" ]
dictionary value operations shortcut
39,536,191
<p>I am wondering why arithmetic operations on dictionary values cannot be shortened with <code>=+</code> or <code>=-</code> as normal python variables can:</p> <pre><code>for item in myDict: myDict[item] =+ 1 </code></pre> <p>doesn't seem to work, but instead I'm told to use:</p> <pre><code>for item in myDict: ...
-1
2016-09-16T14:44:42Z
39,536,245
<p>The order of the operators is <code>+=</code> and <code>-=</code>, not the other way around:</p> <pre><code>In [31]: my_dict = {'key1': 1, 'key2': 2} In [32]: for item in my_dict: ....: my_dict[item] += 1 ....: In [33]: my_dict Out[33]: {'key1': 2, 'key2': 3} # values have been incremented by one </cod...
2
2016-09-16T16:30:23Z
[ "python", "shortcuts", "dictionary" ]
CSV joining based on keys
39,536,224
<p>This may be a simple/repeat question, but I could find/figure out yet how to do it. </p> <p>I have two csv files:</p> <p><strong>info.csv:</strong></p> <pre><code>"Last Name", First Name, ID, phone, adress, age X [Total age: 100] |009076 abc, xyz, 1234, 982-128-0000, pqt, bcd, uvw, 3124, 813-222-1111, tre, po...
1
2016-09-16T16:29:08Z
39,536,954
<p>Try this...</p> <pre><code>import csv info = list(csv.reader(open("info.csv", 'rb'))) age = list(csv.reader(open("age.csv", 'rb'))) def copyCSV(age, info, outFileName = 'out.csv'): # put age into dict, indexed by ID # assumes no duplicate entries # 1 - build a dict ageDict to represent data ageDi...
1
2016-09-16T17:17:27Z
[ "python", "csv", "inner-join", "csvkit" ]
CSV joining based on keys
39,536,224
<p>This may be a simple/repeat question, but I could find/figure out yet how to do it. </p> <p>I have two csv files:</p> <p><strong>info.csv:</strong></p> <pre><code>"Last Name", First Name, ID, phone, adress, age X [Total age: 100] |009076 abc, xyz, 1234, 982-128-0000, pqt, bcd, uvw, 3124, 813-222-1111, tre, po...
1
2016-09-16T16:29:08Z
39,537,149
<p>You can use <code>Pandas</code> and update the <code>info dataframe</code> using the <code>age</code> data. You do it by setting the index of both data frames to <code>ID</code> and <code>student_id</code> respectively, then update the age column in the <code>info dataframe</code>. After that you reset the index so...
3
2016-09-16T17:29:31Z
[ "python", "csv", "inner-join", "csvkit" ]
Issue with null character received by qpython/pandas from kdb
39,536,229
<p>This question is pretty much directed at @Maciej Lach but if anyone else has experienced this issue please let me know.</p> <p>The issue is simple - qpyhton crashes (when pandas is set to true) whenever kdb sends it a single row table where one of the columns has a blank char. </p> <p>I'm using: python version 2.7...
1
2016-09-16T16:29:16Z
39,608,894
<p>This is a bug in the <code>qPython</code> library in version &lt; 1.2.1.</p> <p>I've contributed a <a href="https://github.com/exxeleron/qPython/pull/41" rel="nofollow">pull request</a> with the fix to the maintainer.</p>
2
2016-09-21T06:24:08Z
[ "python", "pandas", "kdb", "q-lang", "exxeleron-q" ]
Django models in Many2Many relationship: filter by a group of member
39,536,262
<p>I have these models:</p> <pre><code>class Skill(models.Model): name = models.CharField(max_length=20) class Engineer(models.Model): name = models.CharField(max_length=20) skill = models.ManyToManyField(Skill) city = models.ForeignKey(City) class City(models.Model): city = models.CharField(ma...
1
2016-09-16T16:31:13Z
39,536,485
<p>You should read <em><a href="https://docs.djangoproject.com/en/1.10/topics/db/queries/#lookups-that-span-relationships" rel="nofollow">queries that span relationships</a></em> part of the docs. Basically querying is done in the same kinda syntax you do <em>ForeignKey</em> lookups. (In case you don't use <a href="htt...
1
2016-09-16T16:46:29Z
[ "python", "django", "django-models" ]
Variable dimensionality of a meshgrid with numpy
39,536,288
<p>I try to create a meshgrid with n dimensions. Is there a nicer way to call meshgrid with n column vectors than with the if clause I am using?</p> <p>Edit: The goal is to use it for user-defined n (2-100) without writing 100 if clauses.</p> <p>The second line in the if clauses reduces the grid so column(n) &lt; col...
0
2016-09-16T16:32:31Z
39,536,518
<p>I haven't fully absorbed your approach and goals, but here's a partial simplification</p> <pre><code>In [399]: r=np.arange(3) # simpler range for example In [400]: grid=np.meshgrid(*[r]*2) # use `[r]*3` for 3d case In [401]: grid=np.array(grid).T.reshape(-1,2) In [402]: np.array([g for g in grid if g[0]...
1
2016-09-16T16:48:49Z
[ "python", "numpy" ]
How to read Twitter's Streaming API and reply an user based on a certain keyword?
39,536,364
<p>I am implementing a Twitter bot for fun purposes using <code>Tweepy</code>.</p> <p>What I am trying to code is a bot that tracks a certain keyword and based in it the bot replies the user that tweeted with the given string.</p> <p>I considered storing the Twitter's Stream on a <code>.json</code> file and looping t...
0
2016-09-16T16:37:17Z
39,537,331
<p>Tweepy <code>StreamListener</code> class allows you to override it's <code>on_data</code> method. That's where you should be doing your logic.</p> <p>As per the code</p> <pre><code>class StreamListener(object): ... def on_data(self, raw_data): """Called when raw data is received from connection....
1
2016-09-16T17:42:53Z
[ "python", "api", "twitter", "stream", "tweepy" ]
Match unicode emoji in python regex
39,536,390
<p>I need to extract the text between a number and an emoticon in a text</p> <p>example text:</p> <pre><code>blah xzuyguhbc ibcbb bqw 2 extract1 ☺️ jbjhcb 6 extract2 🙅 bjvcvvv </code></pre> <p>output:</p> <pre><code>extract1 extract2 </code></pre> <p>The regex code that I wrote extracts the text between ...
3
2016-09-16T16:38:59Z
39,536,900
<p>So this may or not work depending on your needs. If you know the emoji's ahead of time though this will probably work, you just need a list of the types of emoticons to expect.</p> <p>Anyway without more information, this is what I'd do.</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- import re my_r...
0
2016-09-16T17:14:28Z
[ "python", "regex", "unicode", "emoji" ]
Match unicode emoji in python regex
39,536,390
<p>I need to extract the text between a number and an emoticon in a text</p> <p>example text:</p> <pre><code>blah xzuyguhbc ibcbb bqw 2 extract1 ☺️ jbjhcb 6 extract2 🙅 bjvcvvv </code></pre> <p>output:</p> <pre><code>extract1 extract2 </code></pre> <p>The regex code that I wrote extracts the text between ...
3
2016-09-16T16:38:59Z
39,537,131
<p>Here's my stab at the solution. Not sure if it will work in all circumstances. The trick is to convert all unicode emojis into normal text. This could be done by following <a href="http://stackoverflow.com/questions/25707222/print-python-emoji-as-unicode-string">this post</a> Then you can match the emoji just as any...
0
2016-09-16T17:28:23Z
[ "python", "regex", "unicode", "emoji" ]
Match unicode emoji in python regex
39,536,390
<p>I need to extract the text between a number and an emoticon in a text</p> <p>example text:</p> <pre><code>blah xzuyguhbc ibcbb bqw 2 extract1 ☺️ jbjhcb 6 extract2 🙅 bjvcvvv </code></pre> <p>output:</p> <pre><code>extract1 extract2 </code></pre> <p>The regex code that I wrote extracts the text between ...
3
2016-09-16T16:38:59Z
39,537,145
<p>Since there are a lot of emoji <a href="http://apps.timwhitlock.info/emoji/tables/unicode" rel="nofollow">with different unicode values</a>, you have to explicitly specify them in your regex, or if they are with a spesific range you can use a character class. In this case your second simbol is not a standard emoji, ...
1
2016-09-16T17:29:16Z
[ "python", "regex", "unicode", "emoji" ]
String split into dictionary containing lists in python
39,536,469
<p>I have to split a string that looks like;</p> <pre><code>'{ a:[(b,c), (d,e)] , b: [(a,c), (c,d)]}' </code></pre> <p>and convert it to a dict whose values are a list containing tuples like;</p> <pre><code>{'a':[('b','c'), ('d','e')] , 'b': [('a','c'), ('c','d')]} </code></pre> <p>In my case; The above string was ...
0
2016-09-16T16:44:59Z
39,536,583
<p>It is important to know where this string is coming from, but, assuming this is what you have and you cannot change that, you can pre-process the string putting alphanumerics into quotes and using <a href="https://docs.python.org/2/library/ast.html#ast.literal_eval" rel="nofollow"><code>ast.literal_eval()</code></a>...
3
2016-09-16T16:52:45Z
[ "python", "split" ]
PyQT Buttons has Incorrect Size in QGridLayout
39,536,497
<p>I just started a simple PyQt app on Windows 7 and Python 2.7. There are 2 buttons and a table. The Apple button should be 5x taller that the Orange button, and the table should be the same height as the Apple button.</p> <p>However both buttons are drawn the same height despite using <code>grid.addWidget(appleBtn, ...
1
2016-09-16T16:47:09Z
39,537,083
<p>The <code>addWidget</code> method doesn't work in the way you assume it does. The second and third arguments specify the row/column, whilst the third and fourth specify how many rows/columns to span.</p> <p>The correct way to specify proportional heights is with <code>setRowStretch</code>:</p> <pre><code>grid.addW...
1
2016-09-16T17:25:44Z
[ "python", "python-2.7", "qt", "pyqt" ]
Select certain row values and make them columns in pandas
39,536,529
<p>I have a dataset that looks like the below:</p> <pre><code>+-------------------------+-------------+------+--------+-------------+--------+--+ | | impressions | name | shares | video_views | diff | | +-------------------------+-------------+------+--------+-------------+--------+--+ | _ts...
2
2016-09-16T16:49:27Z
39,537,258
<p>You could take subsets of your <code>DF</code> to include rows for 15mins and 30mins and concatenate them by backfilling <code>NaN</code> values of first row(15mins) with that of it's next row(30mins) and dropping off the next row(30mins) as shown:</p> <pre><code>prefix_15="15mins" prefix_30="30mins" fifteen_mins ...
2
2016-09-16T17:37:26Z
[ "python", "pandas" ]
Select certain row values and make them columns in pandas
39,536,529
<p>I have a dataset that looks like the below:</p> <pre><code>+-------------------------+-------------+------+--------+-------------+--------+--+ | | impressions | name | shares | video_views | diff | | +-------------------------+-------------+------+--------+-------------+--------+--+ | _ts...
2
2016-09-16T16:49:27Z
39,537,341
<p>stacking to pivot and collapsing your columns</p> <pre><code>df1 = df.set_index('diff', append=True).stack().unstack(0).T df1.columns = df1.columns.map('_'.join) </code></pre> <hr> <p>To see just the first row</p> <pre><code>df1.iloc[[0]].dropna(1) </code></pre> <p><a href="http://i.stack.imgur.com/kpRmc.png" r...
0
2016-09-16T17:43:27Z
[ "python", "pandas" ]
Substitute Function call with sympy
39,536,540
<p>I want to receive input from a user, parse it, then perform some substitutions on the resulting expression. I know that I can use <code>sympy.parsing.sympy_parser.parse_expr</code> to parse arbitrary input from the user. However, I am having trouble substituting in function definitions. Is it possible to make sub...
1
2016-09-16T16:50:01Z
39,538,381
<p>After some experimentation, while I did not find a built-in solution, it was not difficult to build one that satisfies simple cases. I am not a sympy expert, and so there may be edge cases that I haven't considered.</p> <pre><code>import sympy from sympy.core.function import AppliedUndef def func_sub_single(expr,...
0
2016-09-16T18:54:08Z
[ "python", "sympy" ]
Substitute Function call with sympy
39,536,540
<p>I want to receive input from a user, parse it, then perform some substitutions on the resulting expression. I know that I can use <code>sympy.parsing.sympy_parser.parse_expr</code> to parse arbitrary input from the user. However, I am having trouble substituting in function definitions. Is it possible to make sub...
1
2016-09-16T16:50:01Z
39,647,654
<p>You can use the <code>replace</code> method. For instance</p> <pre><code>gaus = Function("gaus") # gaus is parsed as a Function expr.replace(gaus, Lambda((height, mean, sigma), height*sympy.exp(-((x-mean)/sigma)**2 / 2))) </code></pre> <p><code>replace</code> also has other options, such as pattern matching. </p>
0
2016-09-22T19:44:47Z
[ "python", "sympy" ]
Command to run a bat script against all filename in a folder and segmented databases and merging output
39,536,601
<p>I have a random number (and with random name) of .txt files within a folder named 'seq' as:</p> <pre><code>NP_4500.1.txt NP_4568.1.txt NP_45981.3.txt XM_we679.txt 36498746.txt </code></pre> <p>in another folder named 'db', I made a database fragmented in 20 segments (due to my computational limitations) which are ...
3
2016-09-16T16:53:51Z
39,548,916
<pre class="lang-dos prettyprint-override"><code>@ECHO OFF SETLOCAL ENABLEDELAYEDEXPANSION SET "sourcedir=U:\sourcedir" FOR /f "delims=" %%a IN ( 'dir /b /a-d "%sourcedir%\*.txt" ' ) DO ( SET "join=" FOR /L %%d IN (101,1,120) DO ( SET /a segment=%%d SET "segment=!segment:~-2!" ECHO(script.exe %sourcedir%\%%a ...
0
2016-09-17T16:08:16Z
[ "python", "perl", "batch-file", "cmd" ]
Math Domain Error Quadratic Formula
39,536,727
<p>Figured out the errors except for this last one, Im now getting this error message, and can't figure out why, I'm using the exact formulas for x1 and x2 that my teacher gave us to use and i'm not able to figure the error out.</p> <pre><code> # Quadratic Formula # Import the math library to use sqrt() function t...
0
2016-09-16T17:03:16Z
39,536,927
<p>You have <code>try</code> statements with no corresponding <code>except</code> statement. You should generally avoid <code>while True:</code>. The indentation in your code has many issues</p> <p>To get one value from the user with error handling, you could do something like the code below. You would then repeat ...
0
2016-09-16T17:16:03Z
[ "python", "quadratic" ]
Limits testing auth.sendCode in the telegram.org API
39,536,739
<p>Does the telegram server have a limit on the number of times a client can call auth.sendCode to receive a new <code>phone code</code>?</p> <p>While testing I have to make this call many times until I get my code fully debugged, but it seems to be limited to maybe three invokations per day (or less in some cases). A...
1
2016-09-16T17:03:59Z
39,537,796
<p>You can try this out with telegram on your phone to see how many times you can do a request for phone_codes from the same number before it stops responding.</p> <p>Also, during testing ensure that you are using the range of test IP addresses not the live IP addresses.</p> <p>During my testing I received way over 3...
1
2016-09-16T18:19:06Z
[ "python", "api", "telegram" ]
How to determine which Python class provides attributes when inheriting
39,536,792
<p>What's the easiest way to determine which Python class defines an attribute when inheriting? For example, say I have:</p> <pre><code>class A(object): defined_in_A = 123 class B(A): pass a = A() b = B() </code></pre> <p>and I wanted this code to pass:</p> <pre><code>assert hasattr(a, 'defined_in_A') ass...
3
2016-09-16T17:08:19Z
39,536,988
<p>(Almost) Every python object is defined with it's own instance variables (instance variables of a class object we usually call class variables) to get this as a dictionary you can use the <a href="https://docs.python.org/3/library/functions.html?highlight=built#vars" rel="nofollow"><code>vars</code></a> function and...
2
2016-09-16T17:19:47Z
[ "python", "inheritance" ]
Python - How to pass quantity in Pinax Stripe subscription?
39,536,798
<p>I am using the pinax stripe package in my Django project where a user can enroll multiple people for subscriptions. </p> <p>I know that stripe has a quantity parameter which can be passed for subscriptions but could not find it in pinax package. </p> <p>Can someone guide me on how can I pass the quantity parameter...
0
2016-09-16T17:08:52Z
39,538,462
<p><a href="https://github.com/pinax/pinax-stripe/blob/master/pinax/stripe/tests/test_actions.py#L479-L486" rel="nofollow">Like this</a>:</p> <pre><code>Subscription.objects.create( customer=self.customer, plan=plan, quantity=1 ) </code></pre>
0
2016-09-16T18:59:15Z
[ "python", "django", "stripe-payments", "pinax" ]
join two array in Python
39,536,809
<p>I am new to Python. I use np.lib.recfunctions.join_by to join two array, but the results is wrong. Here is the example and results:</p> <pre><code>a = np.array([('a',1),('b',2),('b',2),('c',3)],dtype=[('key','&lt;U1'),('x','&lt;i4')]) b = np.array([('a',-1),('b',-2)],dtype=[('key','&lt;U1'),('y','&lt;i4')]) np.lib...
1
2016-09-16T17:09:32Z
39,541,317
<p>Had some time to examine a bit more in the options. I think part of the information is being hidden using '.data' to get your return. Consider the following </p> <pre><code>from numpy.lib import recfunctions as rfn a # array a and dtype array([('a', 1), ('b', 2), ('b', 2), ('c', 3)], dtype=[('key', '&lt...
0
2016-09-16T23:19:39Z
[ "python", "arrays", "numpy" ]
Python - Where is the pip executable after install?
39,536,831
<p>Since I am on a server and do not have admin privilege, I need to install my own version of python and pip locally. After installed python, I used the code <code>python get-pip.py --user</code> which is on the <a href="https://pip.pypa.io/en/stable/installing/#id10" rel="nofollow">official site</a>. I get the follow...
1
2016-09-16T17:10:49Z
39,536,914
<p>On Unix, <code>pip install --user</code> ... drops scripts into <code>~/.local/bin</code></p> <p>pip sould be somewhere around <code>~/.local</code></p>
2
2016-09-16T17:15:28Z
[ "python", "install", "pip" ]
Create an automated script that login in into netflix
39,536,901
<p>I'd like to make an automated script in python using selenium that log in here: <a href="https://www.netflix.com/Login" rel="nofollow">https://www.netflix.com/Login</a>. I've tried with this code:</p> <pre><code>from selenium import webdriver driver = webdriver.Firefox() driver.get("https://www.netflix.com/Login")...
-1
2016-09-16T17:14:28Z
39,536,926
<p>Yeah, the <code>ui-text-input[name = 'email']</code> selector is not going to match anything on this page since there is no <code>&lt;ui-text-input&gt;</code> element on the page, but there is an <code>input</code> with <code>ui-text-input</code> class. Fix your selector:</p> <pre><code>form.login-form input[name=e...
0
2016-09-16T17:16:02Z
[ "python", "python-3.x", "selenium" ]
Create an automated script that login in into netflix
39,536,901
<p>I'd like to make an automated script in python using selenium that log in here: <a href="https://www.netflix.com/Login" rel="nofollow">https://www.netflix.com/Login</a>. I've tried with this code:</p> <pre><code>from selenium import webdriver driver = webdriver.Firefox() driver.get("https://www.netflix.com/Login")...
-1
2016-09-16T17:14:28Z
39,538,694
<p>I think below is syntax for CSS selector in selenium</p> <pre><code>driver.findElement(By.cssSelector("ui-text-input[name = 'email']")) </code></pre>
0
2016-09-16T19:15:50Z
[ "python", "python-3.x", "selenium" ]
Create an automated script that login in into netflix
39,536,901
<p>I'd like to make an automated script in python using selenium that log in here: <a href="https://www.netflix.com/Login" rel="nofollow">https://www.netflix.com/Login</a>. I've tried with this code:</p> <pre><code>from selenium import webdriver driver = webdriver.Firefox() driver.get("https://www.netflix.com/Login")...
-1
2016-09-16T17:14:28Z
39,539,387
<p>Solved.</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("https://www.netflix.com/it/") login = driver.find_element_by_css_selector(".authLinks.signupBasicHeader") login.click() element = driver.find_element_by_name("email") eleme...
-1
2016-09-16T20:10:31Z
[ "python", "python-3.x", "selenium" ]
Risks of keeping file open forever
39,536,902
<p>I am writing an application that requires reading the next line from a 1GB file exact every 5 minutes; when the end is reached it should start from the top</p> <p>I had 2 solutions in mind but I'm unsure which one is the best</p> <p><strong>Solution 1</strong></p> <pre><code>class I: def __init__(self): ...
1
2016-09-16T17:14:30Z
39,537,037
<p>Use Solution 1, but don't read line-by-line every time you open the file. Save the last offset read, and <code>seek</code> there directly. Also, you only want to call <code>file.readline()</code> a second time if the first call returned the empty string.</p> <pre><code>class I: def __init__(self): self....
2
2016-09-16T17:22:44Z
[ "python", "memory", "io" ]
Risks of keeping file open forever
39,536,902
<p>I am writing an application that requires reading the next line from a 1GB file exact every 5 minutes; when the end is reached it should start from the top</p> <p>I had 2 solutions in mind but I'm unsure which one is the best</p> <p><strong>Solution 1</strong></p> <pre><code>class I: def __init__(self): ...
1
2016-09-16T17:14:30Z
39,537,041
<p>Generally, the biggest risk of <em>lazily</em> reading from a file is another process writing to the file while you're reading from it.</p> <p>Do the contents of the file change? Is the file massive? If not, just read the whole file at startup.</p> <p>Does the file change a lot? Are lots of other processes writi...
2
2016-09-16T17:22:53Z
[ "python", "memory", "io" ]
Filtering a pandas dataframe based on a match to partial strings
39,536,940
<p>I have a pandas dataframe that contains strings of varying length and characters.</p> <p>For example:</p> <pre><code>print df['name'][0] print df['name'][1] print df['name'][2] print df['name'][3] </code></pre> <p>would return something like this:</p> <pre><code>UserId : Z5QF1X33A loginId : test.user UserId : 00...
1
2016-09-16T17:16:52Z
39,537,090
<p>try this:</p> <pre><code>In [31]: df.name.str.extract(r'\b(?:UserId|loginId)\s*:\s*\b([^\s]+)\b', expand=True) Out[31]: 0 0 Z5QF1X33A 1 test.user 2 0000012348 3 Z5QF1X33A </code></pre>
0
2016-09-16T17:26:05Z
[ "python", "regex", "string", "pandas", "split" ]
gevent monkey patching order
39,537,004
<p>At work we're using gevent to create some asynchronous servers, and there's some debate about when to perform monkey patching in relation to other modules. The gevent documentation shows things like this:</p> <pre><code>from gevent import monkey monkey.patch_socket() import socket </code></pre> <p>Where the monkey...
1
2016-09-16T17:20:43Z
39,537,693
<p>Well, according to the source code (see bellow) <code>patch_socket</code> calls <code>patch_module</code> which imports the <code>socket</code> module for you.</p> <pre><code>def patch_module(name, items=None): gevent_module = getattr(__import__('gevent.' + name), name) module_name = getattr(gevent_module, ...
0
2016-09-16T18:09:47Z
[ "python", "gevent", "monkeypatching" ]
gevent monkey patching order
39,537,004
<p>At work we're using gevent to create some asynchronous servers, and there's some debate about when to perform monkey patching in relation to other modules. The gevent documentation shows things like this:</p> <pre><code>from gevent import monkey monkey.patch_socket() import socket </code></pre> <p>Where the monkey...
1
2016-09-16T17:20:43Z
39,552,387
<p>As the current maintainer of gevent, I will point to <a href="http://www.gevent.org/intro.html#beyond-sockets" rel="nofollow">the documentation</a> which specifically says (<a href="http://www.gevent.org/gevent.monkey.html#patching" rel="nofollow">multiple times</a>) that the recommended way to monkey-patch is to do...
1
2016-09-17T22:40:29Z
[ "python", "gevent", "monkeypatching" ]
Generate random strings of fixed length from given characters with equal occurance
39,537,009
<p>I want to generate random strings from a list of characters C (e.g. C = ['A', 'B', 'C', 'D']). This random string shall have length N (e.g. N = 32). Every character should occur equally often - in that example 8 times.</p> <p>How can I implement that each character occurs equally often in here:</p> <pre><code>''.j...
0
2016-09-16T17:21:03Z
39,537,068
<p>I don't think you can guarantee that each item is picked with the same frequency if you use <code>random.choice</code>. Each choice is equally likely which isn't the same thing.</p> <p>The best way to do this would be to maintain a list of characters and shuffle it...</p> <pre><code>characters = C * 8 random.shuf...
1
2016-09-16T17:25:08Z
[ "python", "random", "fixed" ]
Setting up React in a large python project without Node
39,537,015
<p>I am trying to implement the front-end of a very large Python project with React. It seems that most of the tutorials ask that we use Node to access the packages, is there any way to get around without them? </p> <p>Initially I thought I could use it similarly to bootstrap or jquery where I just download the files ...
0
2016-09-16T17:21:13Z
39,537,661
<p>You can certainly use React with your own flavor of Python framework (Tornado, Flask, Django, etc.). In the final deploy, you don't have to have any Node dependencies. I've run Tornado with React and just used NPM and webpack locally to manage package dependencies and trans-compile.</p>
1
2016-09-16T18:07:37Z
[ "python", "reactjs", "react-router" ]
Request for help numpy array syntax
39,537,032
<p>I am using a template-script to learn data analysis in using numpy and I don't understand this syntax. There exist two arrays <code>dist_data</code> and <code>dataArray</code>, <code>l</code> is a loop-dummy-variable (as in <code>for l in range(0,k):</code>)and I don't understand the content, specifically the purpos...
-1
2016-09-16T17:22:32Z
39,537,467
<pre><code>dist_data[dist_data[:,-1].argsort()][l, self.dataArray.shape[1]-1] </code></pre> <p><code>dist_data[:,-1]</code> last column of 2d <code>dist_data</code>. Sort on that and get the indices</p> <p>So <code>dist_data[dist_data[:,-1].argsort()]</code> is <code>dist_data</code> sorted on the last column.</p> ...
1
2016-09-16T17:52:56Z
[ "python", "arrays", "numpy" ]
Sales commission program using while loop. Value not updating
39,537,144
<p>My while loop isn't updating my new sales commission program eveerytime I run the program. Here is my program:</p> <pre><code> #this program calculates sales commissions and sums the total of all sales commissions the user has entered print("Welcom to the program sales commission loop") keep_going='y' while keep...
0
2016-09-16T17:29:11Z
39,537,174
<p>Every time you loop you are setting total to zero. Move your initialization of total to outside of the loop as I show below.</p> <pre><code>#this program calculates sales commissions and sums the total of all sales commissions the user has entered print("Welcom to the program sales commission loop") keep_going='y...
2
2016-09-16T17:31:53Z
[ "python", "while-loop", "updating" ]
Sales commission program using while loop. Value not updating
39,537,144
<p>My while loop isn't updating my new sales commission program eveerytime I run the program. Here is my program:</p> <pre><code> #this program calculates sales commissions and sums the total of all sales commissions the user has entered print("Welcom to the program sales commission loop") keep_going='y' while keep...
0
2016-09-16T17:29:11Z
39,537,373
<p>The problem is that you are reinitializing 'total' every time you repeat the loop. You don't need to initialize the variable, but in case you want to, you must do it outside the while loop. The corrected code would be: </p> <pre><code>#this program calculates sales commissions and sums the total of all sales commis...
0
2016-09-16T17:46:04Z
[ "python", "while-loop", "updating" ]
python maintain two different random instance.
39,537,148
<p>I am trying to do some anaylsis and for 'reasons' I want objects in my programm to each have their own seeds but no global seeds. Can I accomplish something like this ? </p> <pre><code>a = random.seed(seed1) b = random.seed(seed2) for a in range(5) : print a.random() b.random() </code></pre> <p>The expect ou...
-2
2016-09-16T17:29:27Z
39,537,246
<p>I hope you are just looking for random numbers as mentioned in above output:</p> <p>Here is some code. Please check, if can be helpful for you:</p> <pre><code>&gt;&gt;&gt; for i in range(5): print(random.randint(1,100), random.randint(1,100)) </code></pre> <p>Output will be as:</p> <p>14 93</p> <p>51 62...
-1
2016-09-16T17:36:37Z
[ "python" ]
python maintain two different random instance.
39,537,148
<p>I am trying to do some anaylsis and for 'reasons' I want objects in my programm to each have their own seeds but no global seeds. Can I accomplish something like this ? </p> <pre><code>a = random.seed(seed1) b = random.seed(seed2) for a in range(5) : print a.random() b.random() </code></pre> <p>The expect ou...
-2
2016-09-16T17:29:27Z
39,537,309
<p>You need to use a <code>random.Random</code> class object.</p> <pre><code>from random import Random a = Random() b = Random() a.seed(0) b.seed(0) for _ in range(5): print(a.randrange(10), b.randrange(10)) # Output: # 6 6 # 6 6 # 0 0 # 4 4 # 8 8 </code></pre> <p>The <a href="https://docs.python.org/2/librar...
2
2016-09-16T17:41:01Z
[ "python" ]
python maintain two different random instance.
39,537,148
<p>I am trying to do some anaylsis and for 'reasons' I want objects in my programm to each have their own seeds but no global seeds. Can I accomplish something like this ? </p> <pre><code>a = random.seed(seed1) b = random.seed(seed2) for a in range(5) : print a.random() b.random() </code></pre> <p>The expect ou...
-2
2016-09-16T17:29:27Z
39,537,375
<p>Then, this may help you:</p> <pre><code>&gt;&gt;&gt; for _ in range(5): rn=random.randint(1,100) print(rn, rn) </code></pre> <p>Output is:<br> 38 38 </p> <p>98 98 </p> <p>8 8 </p> <p>29 29 </p> <p>67 67</p>
0
2016-09-16T17:46:09Z
[ "python" ]
Read Strings in Python
39,537,311
<p>I have some values in a string </p> <pre><code>[AD6:0.02] [AD7:0.03] [AD8:0.19][AD3:6][AD0:22][AD1:22][AD4:48.00][AD5:0.01] [AD6:0.03] </code></pre> <p>I just want to read the values of each 'AD' like 0.02 in AD6 for example. The string changes each time, so I cannot use 'substring'.</p> <p>Here is my code</p> <...
-1
2016-09-16T17:41:02Z
39,537,350
<p>Use <code>re.findall()</code> with a proper regex:</p> <pre><code>In [80]: s = "[AD6:0.02] [AD7:0.03] [AD8:0.19][AD3:6][AD0:22][AD1:22][AD4:48.00][AD5:0.01] [AD6:0.03]" In [81]: regex = re.compile(r'AD\d:([\d.]+)') In [82]: regex.findall(s) Out[82]: ['0.02', '0.03', '0.19', '6', '22', '22', '48.00', '0.01', '0.03...
3
2016-09-16T17:43:58Z
[ "python", "string" ]
Redirect to back to referrer page
39,537,329
<p>I am building an account settings page. I was thinking of having a few routes that only accept post request then edit the records and then go back the account settings page.</p> <p>The problem is that there is two account settings pages. One for users and one for an admin account.</p> <p>The admin account_setting...
-2
2016-09-16T17:42:45Z
39,537,400
<p>People usually solve this problem with session cookies (which you should have access to given that the user will be logged into an admin panel).</p> <p>This is of course safter than using <code>HTTP_REFERER</code> (header sent by the client), as you control the contents of the session cookie entirely.</p> <p>You c...
1
2016-09-16T17:47:31Z
[ "python", "flask" ]
Redirect to back to referrer page
39,537,329
<p>I am building an account settings page. I was thinking of having a few routes that only accept post request then edit the records and then go back the account settings page.</p> <p>The problem is that there is two account settings pages. One for users and one for an admin account.</p> <p>The admin account_setting...
-2
2016-09-16T17:42:45Z
39,552,793
<p>request.referrer will return back to the previous page. <a href="http://flask.pocoo.org/docs/0.11/reqcontext/" rel="nofollow">http://flask.pocoo.org/docs/0.11/reqcontext/</a></p>
-1
2016-09-17T23:48:36Z
[ "python", "flask" ]
Kivy position of a GridLayout's children always returns (0,0)
39,537,411
<p>When I add some element to my GridLayout, if want to get the element postion, Kivy always returns (0,0), but it not true, because the elements are correctly positioned on my windows.</p> <pre><code>class ImageButton(ButtonBehavior, Label): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) ...
0
2016-09-16T17:48:19Z
39,544,071
<p>The pos is equal to [0,0] at the first frame of the kivy GUI loop, when you print it. It changes a bit later. You have two ways of solving this problem:</p> <ol> <li>Wait till the second frame, when pos is updated as expected. </li> <li>Bind the pos instead of just assigning it once at the beginning.</li> </ol> <p...
0
2016-09-17T07:25:05Z
[ "python", "python-3.x", "kivy", "kivy-language" ]
Module cross reference design issue
39,537,416
<p>I have a python file called <code>testlib.py</code>, its intention is defined some utility class and global function used by other modules. The <code>uselib.py</code> is designed as a client which is using class/global functions from <code>testlib.py</code>.</p> <p>Dues to some design issues, <code>testlib.py</code...
0
2016-09-16T17:48:29Z
39,537,577
<p>I came up with a sneaky hack: only <code>import testlib</code> when you are already calling the <code>__main__</code> function in <code>uselib.py</code>. Using the check <code>if __name__ == "__main__"</code> in <code>uselib.py</code> is important in this case. That way, you avoid the circular importing. The <code>t...
1
2016-09-16T18:01:01Z
[ "python", "python-2.7" ]
Counting overlapping values of two 2D binary numpy arrays for a specific value
39,537,439
<p>I start with two images of the same size. I convert them to binary black/white numpy arrays (0 = black 1 = white). I'd like to find how many of the black pixels overlap (0 value at same position in both arrays).</p> <p>I know how to do this with for loops, but I'm trying to learn how to use numpy properly, and I im...
2
2016-09-16T17:50:42Z
39,537,633
<p>You can use a simple comparison with a logical and:</p> <pre><code>&gt;&gt;&gt; A array([[1, 1, 0], [1, 0, 0], [0, 1, 1]]) &gt;&gt;&gt; B array([[1, 0, 0], [1, 1, 0], [0, 1, 1]]) &gt;&gt;&gt; np.logical_and(A == 0, B == 0) array([[False, False, True], [False, False, True], ...
3
2016-09-16T18:05:42Z
[ "python", "arrays", "numpy", "multidimensional-array" ]
Counting overlapping values of two 2D binary numpy arrays for a specific value
39,537,439
<p>I start with two images of the same size. I convert them to binary black/white numpy arrays (0 = black 1 = white). I'd like to find how many of the black pixels overlap (0 value at same position in both arrays).</p> <p>I know how to do this with for loops, but I'm trying to learn how to use numpy properly, and I im...
2
2016-09-16T17:50:42Z
39,576,605
<p>For the record, your original try just lacked the right operator and some parentesis:</p> <pre><code>np.where( (arrayA==0) &amp; (arrayB==0)) </code></pre>
2
2016-09-19T15:14:49Z
[ "python", "arrays", "numpy", "multidimensional-array" ]
How to calculate a partial Area Under the Curve (AUC)
39,537,443
<p>In scikit learn you can compute the area under the curve for a binary classifier with</p> <pre><code>roc_auc_score( Y, clf.predict_proba(X)[:,1] ) </code></pre> <p>I am only interested in the part of the curve where the false positive rate is less than 0.1.</p> <blockquote> <p>Given such a threshold false posit...
4
2016-09-16T17:51:09Z
39,538,650
<p>That depends on whether the FPR is the <strong>x</strong>-axis or <strong>y</strong>-axis (independent or dependent variable).</p> <p>If it's <strong>x</strong>, the calculation is trivial: calculate only over the range [0.0, 0.1].</p> <p>If it's <strong>y</strong>, then you first need to solve the curve for <stro...
1
2016-09-16T19:12:32Z
[ "python", "machine-learning", "statistics", "scikit-learn" ]
How to calculate a partial Area Under the Curve (AUC)
39,537,443
<p>In scikit learn you can compute the area under the curve for a binary classifier with</p> <pre><code>roc_auc_score( Y, clf.predict_proba(X)[:,1] ) </code></pre> <p>I am only interested in the part of the curve where the false positive rate is less than 0.1.</p> <blockquote> <p>Given such a threshold false posit...
4
2016-09-16T17:51:09Z
39,678,975
<p>Calculate your fpr and tpr values only over the range [0.0, 0.1].</p> <p>Then, you can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.trapz.html" rel="nofollow">numpy.trapz</a> to evaluate the partial AUC (pAUC) like so:</p> <pre><code>pAUC = numpy.trapz(tpr_array, fpr_array) </code></pre> ...
1
2016-09-24T17:16:35Z
[ "python", "machine-learning", "statistics", "scikit-learn" ]
How to calculate a partial Area Under the Curve (AUC)
39,537,443
<p>In scikit learn you can compute the area under the curve for a binary classifier with</p> <pre><code>roc_auc_score( Y, clf.predict_proba(X)[:,1] ) </code></pre> <p>I am only interested in the part of the curve where the false positive rate is less than 0.1.</p> <blockquote> <p>Given such a threshold false posit...
4
2016-09-16T17:51:09Z
39,687,168
<p>Say we start with</p> <pre><code>import numpy as np from sklearn import metrics </code></pre> <p>Now we set the true <code>y</code> and predicted <code>scores</code>:</p> <pre><code>y = np.array([0, 0, 1, 1]) scores = np.array([0.1, 0.4, 0.35, 0.8]) </code></pre> <p>(Note that <code>y</code> has shifted down b...
2
2016-09-25T13:06:56Z
[ "python", "machine-learning", "statistics", "scikit-learn" ]
pyspark: append/merge PythonRDD to a pyspark dataframe
39,537,505
<p>I am using the following code to create a clustering model, then classify each record to certain cluster:</p> <pre><code>from pyspark.mllib.clustering import KMeans from pyspark.mllib.linalg import Vectors spark_df = sqlContext.createDataFrame(pandas_df) rdd = spark_df.rdd.map(lambda data: Vectors.dense([float(c) ...
0
2016-09-16T17:55:48Z
39,548,417
<p><code>pyspark.mllib.clustering.KMeansModel</code> is one of rare models that can be used directly inside PySpark transformation so you can simply <code>map</code> with <code>predict</code>:</p> <pre><code>rdd.map(lambda point: (model.predict(point), point)) </code></pre> <p>In general case when it is not possible ...
1
2016-09-17T15:16:19Z
[ "python", "apache-spark", "pyspark", "spark-dataframe", "apache-spark-mllib" ]
python: nested classes: access outer class class member
39,537,508
<p>This does not work:</p> <pre><code>class A: a1 = 4 class B: b1 = A.a1 # Fails b2 = 6 class C: c1 = A.B.b2 # Fails </code></pre> <p>Any non cryptic way to solve it? I know I could take B and C out from A but I would like to keep them embedded. I also think it would be easier with no class mem...
3
2016-09-16T17:56:13Z
39,537,602
<p>This fails for two different reasons. One is that <code>A</code> is not ready when you try to access <code>A.a1</code> in <code>B</code> giving you <code>NameError</code>.</p> <p>If you solve this using a subclass. The following will work:</p> <pre><code>class A: a1 = 4 class _A(A): class B: b1 = A.a1 #...
1
2016-09-16T18:02:46Z
[ "python", "nested", "inner-classes" ]
python: nested classes: access outer class class member
39,537,508
<p>This does not work:</p> <pre><code>class A: a1 = 4 class B: b1 = A.a1 # Fails b2 = 6 class C: c1 = A.B.b2 # Fails </code></pre> <p>Any non cryptic way to solve it? I know I could take B and C out from A but I would like to keep them embedded. I also think it would be easier with no class mem...
3
2016-09-16T17:56:13Z
39,537,673
<p>You might defer the definition of <code>B</code> until <code>A</code> is fully defined, and defer <code>C</code> until both <code>A</code> and <code>A.B</code> are defined.</p> <pre><code>class A: a1 = 4 class B: b1 = A.a1 b2 = 6 A.B = B del B class C: c1 = A.B.b2 A.C = C del C assert A.B.b1 == 4 assert ...
1
2016-09-16T18:08:19Z
[ "python", "nested", "inner-classes" ]
python: nested classes: access outer class class member
39,537,508
<p>This does not work:</p> <pre><code>class A: a1 = 4 class B: b1 = A.a1 # Fails b2 = 6 class C: c1 = A.B.b2 # Fails </code></pre> <p>Any non cryptic way to solve it? I know I could take B and C out from A but I would like to keep them embedded. I also think it would be easier with no class mem...
3
2016-09-16T17:56:13Z
39,537,909
<p>One trick is to put the common parameters into a parameter class and inherit from that:</p> <pre><code>class Params: p = 4 class A(Params): # A has p class B(Params): # B has p pass class C(Params): # C has p pass </code></pre> <p>Or, if you need the params with dif...
0
2016-09-16T18:24:51Z
[ "python", "nested", "inner-classes" ]
Why doesn't my selenium webdriver authentication work (Django 1.9)
39,537,615
<p>I am going through a process of registering and logging in for a list of users.</p> <p>I am using the same username and password to make things simple. </p> <pre><code>from selenium import webdriver from selenium.webdriver.common.keys import Keys import re for address in geolocations: # register browser...
0
2016-09-16T18:03:36Z
39,537,694
<p>In the login section of your test, it looks like you have forgotten to call <code>username.send_keys()</code>.</p>
2
2016-09-16T18:09:53Z
[ "python", "django", "selenium", "authentication", "login" ]
How to get a Logger that Prints to Console and to File in fewest lines
39,537,683
<p>This is how I obtain a logger that prints to both console and a file:</p> <pre><code>import logging logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s') handler.setFormatter(formatte...
0
2016-09-16T18:09:11Z
39,539,294
<p>I'm curious: why do you want that?</p> <p>You can use an external configuration in an INI file and load it with <code>logging.config.fileConfig</code>.</p> <p>Or</p> <p>Create your own handle which combine file and console handlers.</p> <p>Or</p> <p>Create a file-like object which writes it a file and in the co...
0
2016-09-16T20:01:46Z
[ "python", "logging" ]
How to get a Logger that Prints to Console and to File in fewest lines
39,537,683
<p>This is how I obtain a logger that prints to both console and a file:</p> <pre><code>import logging logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s') handler.setFormatter(formatte...
0
2016-09-16T18:09:11Z
39,581,852
<p>My opinion: when you are prototyping, you want a log file for each module.</p> <h2>A contextual handler</h2> <p>To do that, you can process as follow:</p> <ul> <li>Create a <code>LogNameFileHandler</code>: this is a subclass of <code>logging.StreamHandler</code> which behave like <code>logging.FileHandler</code>,...
1
2016-09-19T20:48:03Z
[ "python", "logging" ]
Comparing dictionaries in Python lists
39,537,687
<p>I have two lists which contain dictionaries. Each dictionary has only one entry. I would like to check if a key in dictionary A (in list X) also exists in a dictionary in list Y. If this is the case, the key and the values belonging to it should be printed.</p> <p>Example:</p> <pre><code>listA = [{key1: value1}, {...
-3
2016-09-16T18:09:20Z
39,540,051
<p>A very simple way to do it would be:</p> <pre><code>#!/usr/bin/env python l1 = [{'1':"one"} , {'2':"two"}] l2 = [{'3':"three"} , {'1':"one_too"}] def cmp(l1,l2): for i in l1: for j in l2: for (key1,value1),(key2,value2) in zip(i.iteritems(),j.iteritems()): if key1==key...
0
2016-09-16T21:04:46Z
[ "python", "list", "dictionary" ]
How to assign unique identifier to DataFrame row
39,537,689
<p>I have a <code>.csv</code> file that is created from an <code>nd.array</code> after the input data is processed by <code>sklearn.cluster.DBSCAN()</code>.I would like to be able to "tie" every point in the cluster to an unique identifier given by a column in my input file. </p> <p>This is how I'm reading my <code>in...
3
2016-09-16T18:09:29Z
39,539,808
<h2>UPDATE:</h2> <p><strong>Code:</strong></p> <pre><code>import numpy as np import pandas as pd from sklearn.cluster import DBSCAN from sklearn import metrics from sklearn.datasets.samples_generator import make_blobs from sklearn.preprocessing import StandardScaler fn = r'D:\temp\.data\2004_Charley_data.csv' df = p...
1
2016-09-16T20:43:07Z
[ "python", "pandas", "dataframe" ]
Errno 24: Too many open files. But I am not opening files?
39,537,731
<p>I am using treq (<a href="https://github.com/twisted/treq" rel="nofollow">https://github.com/twisted/treq</a>) to query some other api from my web service. Today when I was doing stress testing of my own services, It shows an error</p> <p><code>twisted.internet.error.DNSLookupError: DNS lookup failed: address 'api....
0
2016-09-16T18:13:04Z
39,537,952
<p>"Files" include network sockets, which are a type of file on Unix-based systems. The maximum number of open files is configurable with <code>ulimit -n</code></p> <pre><code># Check current limit $ ulimit -n 256 # Raise limit to 2048 $ ulimit -n 2048 </code></pre> <p>It is not surprising to run out of file handle...
1
2016-09-16T18:27:22Z
[ "python", "asynchronous", "twisted" ]