title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Python - Project Euler #80, understanding the error | 37,707,042 | <p>Project Euler problem #80 seems straightforward:</p>
<p><a href="https://projecteuler.net/problem=80" rel="nofollow">https://projecteuler.net/problem=80</a></p>
<p>Using the decimal module to calculate the square root to a given precision:</p>
<pre><code>from decimal import Decimal, localcontext
def prob80():
... | 0 | 2016-06-08T15:38:07Z | 37,708,208 | <p>You made two mistakes which cancelled each other out for the example case.</p>
<ol>
<li>You did not count in 1st digit <code>1</code></li>
<li>You set precision too low by one digit. Last digit almost always contain some rounding error. 100th and 101st digits of <code>sqrt(2)</code> are <code>27</code>, so when you... | 2 | 2016-06-08T16:37:27Z | [
"python",
"decimal",
"rounding",
"precision",
"square"
] |
Segmentation Fault: 11 on OSX python | 37,707,045 | <p>I'm getting an intermittant segfault in python, which really shouldn't happen. It's a heisenbug, so I haven't figured out exactly what's causing it.</p>
<p>I've done the search and found that there was a known problem with an older version of python, but I'm using 2.7.10 (in a virtualenv, in case that matters)</p>
... | -1 | 2016-06-08T15:38:14Z | 37,845,973 | <p>It looks like: <a href="http://stackoverflow.com/questions/9412156/how-to-generate-core-dumps-in-mac-os-x">How to generate core dumps in Mac OS X?</a></p>
<p>might be the best way to get stack trace...it appears in ~/Library/Logs/DiagnosticReports I'm not sure if it's USEFUL, and it's not a core per se, to be put i... | 0 | 2016-06-15T21:20:18Z | [
"python",
"osx",
"numpy",
"pandas",
"scipy"
] |
How to read a CSV file line by line and store it to new CSV file on new row every time? | 37,707,148 | <p>I am new to Python. I am trying to read a CSV file and after removing stopwords from the file I have to store it into new CSV file. My code is removing stop words but it copying the first row to the each row of the file in single row. (e.g, if there are three rows in a file, then it will copy the first row three tim... | 0 | 2016-06-08T15:43:11Z | 37,707,565 | <p>You're only reading the first line of your file: <code>line=myfile.readline()</code>. You want to iterate over each line in your file. One way to do this is</p>
<pre><code>with open(fileName,'r') as myfile:
for line in myfile:
# the rest of your code here, i.e.:
stop_words=set(stopwords.words("e... | 2 | 2016-06-08T16:04:20Z | [
"python",
"csv",
"nltk"
] |
Merge data on in a SQLite database through Python | 37,707,185 | <p>I have managed to import multiple csv files (contained in one folder) into an SQLite database - thanks to the very useful feedback I received on my previous
<a href="http://stackoverflow.com/questions/37216486/using-python-to-build-an-sqlite-database-from-multiple-csv-files">question on this forum</a>.</p>
<p><a hr... | 0 | 2016-06-08T15:45:05Z | 37,707,321 | <p>You just have to create the new table and use two <code>INSERT INTO <newtable> SEÃECT <collunmns_wanted> FROM <old_table_1></code> to the sqlite engine.</p>
<p>Full documentation to the INSERT is here:
<a href="https://www.sqlite.org/lang_insert.html" rel="nofollow">https://www.sqlite.org/lang_i... | 0 | 2016-06-08T15:52:13Z | [
"python",
"sqlite",
"csv",
"merge",
"upsert"
] |
Python PEP479 Change StopIteration handling inside generators | 37,707,187 | <p>Could someone help me understand what PEP479 is about ? I was reading the doc and couldn't get my head around it.</p>
<p>The abstract says:</p>
<blockquote>
<p>This PEP proposes a change to generators: when StopIteration is raised inside a generator, it is replaced it with RuntimeError. (More precisely, this hap... | 2 | 2016-06-08T15:45:16Z | 37,707,387 | <p>Your first loop should still work -- <code>StopIteration</code> will still be raised when a generator is exhausted.</p>
<p>The difference is that there <em>was</em> ambiguity when a <code>StopIteration</code> was raised in a generator. Did it get raised (implicitly) because the generator ran out of things to yield... | 3 | 2016-06-08T15:56:20Z | [
"python",
"runtime-error",
"stopiteration"
] |
Pyspark: multiple conditions in when clause | 37,707,305 | <p>I would like to modify the cell values of a dataframe column (Age) where currently it is blank and I would only do it if another column (Survived) has the value 0 for the corresponding row where it is blank for Age. If it is 1 in the Survived column but blank in Age column then I will keep it as null. </p>
<p>I tr... | 0 | 2016-06-08T15:51:36Z | 37,712,867 | <p>You get <code>SyntaxError</code> error exception because Python has no <code>&&</code> operator. It has <code>and</code> and <code>&</code> where the latter one is the correct choice to create boolean expressions on <code>Column</code> (<code>|</code> for a logical disjunction and <code>~</code> for lo... | 5 | 2016-06-08T21:02:25Z | [
"python",
"apache-spark",
"pyspark",
"spark-dataframe"
] |
Python- Most efficient way to return batches of numbers | 37,707,342 | <p><strong>Background</strong></p>
<p>I am working on some REST JSON calls via python to get a list of users. Unfortunately, the server can only return a maximum number of 50 users at a time.
e.g.</p>
<p>call "[0:49]" returns the first 50 users</p>
<p>call "[51:99]" returns the next batch of 50 users</p>
<p>The ser... | -1 | 2016-06-08T15:53:23Z | 37,707,587 | <p>You can simply use python's <code>range(start, stop, step)</code>. You can set <code>step</code> to be 50. ie,</p>
<pre><code>>>> for i in range(0, max_no+1, 50):
... print i, i+49
...
0 49
50 99
100 149
150 199
200 249
250 299
300 349
350 399
</code></pre>
<p>Then possibly have an extra <code>if</cod... | 1 | 2016-06-08T16:05:19Z | [
"python",
"dictionary",
"numbers",
"logic"
] |
Python- Most efficient way to return batches of numbers | 37,707,342 | <p><strong>Background</strong></p>
<p>I am working on some REST JSON calls via python to get a list of users. Unfortunately, the server can only return a maximum number of 50 users at a time.
e.g.</p>
<p>call "[0:49]" returns the first 50 users</p>
<p>call "[51:99]" returns the next batch of 50 users</p>
<p>The ser... | -1 | 2016-06-08T15:53:23Z | 37,708,152 | <p>Try this:: Your results are incorrect... in your question</p>
<pre><code> def get_all_possible_items(users):
return dict([[x, min(x+49,users) ] for x in range(0,users,50)])
# or
#def get_all_possible_items(users):
# print dict([[x, min(x+49,users) ] for x in range(0,users,50)])
ge... | 0 | 2016-06-08T16:33:50Z | [
"python",
"dictionary",
"numbers",
"logic"
] |
Using for and if to alter specific data using Python | 37,707,359 | <p>I have a data set that has 3 columns - longitude, latitude and data - and 64800 rows.</p>
<pre><code>Lon Lat Data
-180.0 -90.0 0.0
-180.0 -89.0 1500.0
-180.0 -88.0 18.5
</code></pre>
<p>etc...</p>
<p>I want to edit the data column in certain geographical areas, e.g. ... | 0 | 2016-06-08T15:54:29Z | 37,708,428 | <p>try this:</p>
<pre><code>f = np.array([[-180., -90., 0.], [-180., -89., 1500.], [-180., -88., 18.5]])
lon_rng = (-181 < f[:, 0]) & (f[:, 0] < -179)
lat_rng = (-90 < f[:, 1]) & (f[:, 1] < -88)
f[lat_rng & lon_rng, 2] = f[lat_rng & lon_rng, 2] * 1.2
f
array([[ -180. , -90. , 0. ... | 0 | 2016-06-08T16:49:18Z | [
"python",
"numpy"
] |
Django Inline formsets only saving three objects | 37,707,362 | <p>I have a question object that has a foreign key field to a discussion object. I am trying to render a form using a discussion ModelForm, and a question Inline formset. When it renders an empty form to the page, everything works fine, and all the fields are where they need to be. The error is that I have JQuery that ... | 0 | 2016-06-08T15:54:45Z | 37,707,832 | <p>You need to update the hidden field from the management form which specifies the total number of forms. It needs to be updated each time you add a form. You can target this using the id:</p>
<pre><code>id_form-TOTAL_FORMS
</code></pre>
<p>Currently, your <code>count</code> variable is assigned on page load (which ... | 2 | 2016-06-08T16:18:23Z | [
"python",
"django",
"forms",
"inline-formset"
] |
Python, Seaborn - How to add significance bars and asterisks to boxplots | 37,707,406 | <p>I'm looking for suggestions on how to add significance bars between boxes on a box plot and also have asterisks representing significance. I am using seaborn to create plots and I couldn't find any common methods for accomplishing this. Nothing stuck out to me in the documentation but I am a novice and new to matplo... | 1 | 2016-06-08T15:56:51Z | 38,058,164 | <p>@UlrichStern suggested an answer to a previous question that does exactly what I need. </p>
<p><a href="http://stackoverflow.com/questions/36578458/how-does-one-insert-statistical-annotations-stars-or-p-values-into-matplotlib/37518947#37518947">How does one insert statistical annotations (stars or p-values) into ma... | 0 | 2016-06-27T15:45:01Z | [
"python",
"seaborn"
] |
Excluding directories from tarfile module | 37,707,408 | <p>I am trying to tar the contents of a directory using the tarfile module.</p>
<p>Say this directory, called 'A', has several subdirectories, 'a' and 'a1' etc...
Is there a way to exclude these directories from the tarfile object when trying to add?
For example, I have a list of files to exclude, which I put in the l... | 0 | 2016-06-08T15:56:52Z | 37,707,542 | <p>Building on the example from the other answer you've posted, can you not do:</p>
<pre><code>def exclude_function(filename):
return os.path.isdir(filename):
mytarfile.add(..., exclude=exclude_function)
</code></pre>
<p>Or to simplify, perhaps:</p>
<pre><code>mytarfile.add(..., exclude=os.path.isdir)
</code></... | 0 | 2016-06-08T16:03:09Z | [
"python",
"tarfile"
] |
Plotting the boundaries of cluster zone in Python with scikit package | 37,707,432 | <p>Here is my simple example of dealing with data clustering in 3 attribute(x,y,value). each sample represent its location(x,y) and its belonging variable. </p>
<p>My code was post here:</p>
<pre><code>x = np.arange(100,200,1)
y = np.arange(100,200,1)
value = np.random.random(100*100)
xx,yy = np.meshgrid(x,y)
xx = x... | 0 | 2016-06-08T15:58:00Z | 37,713,365 | <p>The cluster zones are actually just a Voronoi diagram of the cluster centers. Scipy has some tools for computing Voronoi cells given a set of points. <a href="http://docs.scipy.org/doc/scipy-0.17.0/reference/generated/scipy.spatial.Voronoi.html" rel="nofollow">This page</a> has some examples on how you can do this.<... | 1 | 2016-06-08T21:37:49Z | [
"python",
"matplotlib",
"scikit-learn",
"cluster-analysis",
"k-means"
] |
Why does the find function return -1 in python when searching a string and failing to find a match? | 37,707,616 | <p>I would expect a return of 0. Is -1 simply the equivalent of false? For a moment I thought it was because 0 is a position (index?) in the string, but so is -1. While I know it is enough to simply memorize that this is how the find operation works, I was wondering if there was a deeper explanation or if this is somet... | 0 | 2016-06-08T16:07:13Z | 37,708,306 | <p>The objective of the find method is to return the index value, which (for all practical purposes) programmers <strong>want</strong> as positive. In this case, any negative value means that the function could not find the particular element.</p>
<p>The reason why <em>True</em> or <em>False</em> is <strong>NOT</stron... | 0 | 2016-06-08T16:42:11Z | [
"python",
"find"
] |
Why does the find function return -1 in python when searching a string and failing to find a match? | 37,707,616 | <p>I would expect a return of 0. Is -1 simply the equivalent of false? For a moment I thought it was because 0 is a position (index?) in the string, but so is -1. While I know it is enough to simply memorize that this is how the find operation works, I was wondering if there was a deeper explanation or if this is somet... | 0 | 2016-06-08T16:07:13Z | 37,708,679 | <p>@jonrsharpe I believe your comment answered my question best. While -1 is an index, the find function always returns a non-negative index when successful and -1 otherwise.</p>
| 0 | 2016-06-08T17:02:16Z | [
"python",
"find"
] |
Exporting Scrapy requests in Curl format | 37,707,660 | <p><a href="http://i.stack.imgur.com/pRGp7.png" rel="nofollow"><img src="http://i.stack.imgur.com/pRGp7.png" alt="enter image description here"></a></p>
<p>I use Postman for API testing , which has the ability to import curl commands. </p>
<p><a href="https://www.getpostman.com/docs/importing_curl" rel="nofollow">htt... | 1 | 2016-06-08T16:09:23Z | 37,707,707 | <p>Not exactly answering the question, but I hope may help as well. </p>
<p>I remember going to browser developer tools, using the "Copy as cURL" functionality, then pasting it to the textbox <a href="http://curl.trillworks.com/" rel="nofollow">here</a> and getting a Python+Requests code, which should be easier to tra... | 2 | 2016-06-08T16:12:04Z | [
"python",
"curl",
"scrapy"
] |
Exporting Scrapy requests in Curl format | 37,707,660 | <p><a href="http://i.stack.imgur.com/pRGp7.png" rel="nofollow"><img src="http://i.stack.imgur.com/pRGp7.png" alt="enter image description here"></a></p>
<p>I use Postman for API testing , which has the ability to import curl commands. </p>
<p><a href="https://www.getpostman.com/docs/importing_curl" rel="nofollow">htt... | 1 | 2016-06-08T16:09:23Z | 37,708,057 | <p>You could use <a href="https://github.com/csalazar/minreq" rel="nofollow"><code>minreq</code></a> to ouptut a Scrapy Request from curl. It even only outputs the necessary data to send to repeat the same request successfully.</p>
| 2 | 2016-06-08T16:29:35Z | [
"python",
"curl",
"scrapy"
] |
Can not find/click this button with Selenium/Firefox | 37,707,703 | <p>I am trying to press this "New Search" button. It appears on the top of the screen after entering a search on <a href="http://www.lexisnexis.com/hottopics/lnacademic/" rel="nofollow">http://www.lexisnexis.com/hottopics/lnacademic/</a></p>
<p>I have looked at the Xpath and Unique Selector.</p>
<p>What I have tried:... | 1 | 2016-06-08T16:11:57Z | 37,707,795 | <p>This is because the element is <em>inside an <code>iframe</code>.</em> You have to be in the context to search elements inside. Use <code>.switch_to.frame()</code>:</p>
<pre><code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.w... | 0 | 2016-06-08T16:16:33Z | [
"python",
"selenium",
"firefox",
"xpath"
] |
Can not find/click this button with Selenium/Firefox | 37,707,703 | <p>I am trying to press this "New Search" button. It appears on the top of the screen after entering a search on <a href="http://www.lexisnexis.com/hottopics/lnacademic/" rel="nofollow">http://www.lexisnexis.com/hottopics/lnacademic/</a></p>
<p>I have looked at the Xpath and Unique Selector.</p>
<p>What I have tried:... | 1 | 2016-06-08T16:11:57Z | 37,707,948 | <p>To build on alecxes answer,</p>
<p>once you're inside the iframe, you can find the clickable using it's xpath:</p>
<pre><code>new_search_xpath = '/html/body/div[2]/table/tbody/tr[2]/td[2]/div[1]/table/tbody/tr/td/span/a[3]'
new_search = driver.find_element(By.XPATH, new_search_xpath)
new_search.click()
</code></pr... | 1 | 2016-06-08T16:24:01Z | [
"python",
"selenium",
"firefox",
"xpath"
] |
Can not find/click this button with Selenium/Firefox | 37,707,703 | <p>I am trying to press this "New Search" button. It appears on the top of the screen after entering a search on <a href="http://www.lexisnexis.com/hottopics/lnacademic/" rel="nofollow">http://www.lexisnexis.com/hottopics/lnacademic/</a></p>
<p>I have looked at the Xpath and Unique Selector.</p>
<p>What I have tried:... | 1 | 2016-06-08T16:11:57Z | 37,718,722 | <p>Or you can use <code>.submit()</code> method<br>
Adding to @alecxe answers - In a note :--</p>
<pre><code>driver = webdriver.Chrome()
driver.get('http://www.lexisnexis.com/hottopics/lnacademic/')
actions = ActionChains(driver)
wait = WebDriverWait(driver, 10)
frame = wait.until(EC.presence_of_element_located((By.... | 0 | 2016-06-09T06:50:29Z | [
"python",
"selenium",
"firefox",
"xpath"
] |
Matching 2 different dataframes to return value and then compare | 37,707,769 | <p>I need to match these 2 dataframes of different size, get the matched field, and then compare if it is bigger or smaller.</p>
<pre><code>df = pd.DataFrame({'first_name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
'id': ['a1', 'a2', 'a3', 'a4', 'a5'],
'id2': ['', '', '', 'b1', 'b2'],
'cost':[... | 1 | 2016-06-08T16:15:28Z | 37,708,113 | <p>I think you can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow"><code>replace</code></a> values in columns <code>id</code> and <code>id2</code> by <code>df2</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_ind... | 2 | 2016-06-08T16:32:09Z | [
"python",
"pandas",
"dataframe"
] |
How to join time/int intervals by delta? | 37,707,852 | <p>I have a simple list of intervals:</p>
<pre><code>[
{ "begin" : 10, "end" : 20 },
{ "begin" : 1, "end" : 2 },
{ "begin" : 5, "end" : 7 },
{ "begin" : 100, "end" : 200 }
]
</code></pre>
<p>How to join intervals by condition </p>
<pre><code>if abs(current["end"] - next["begin"] < 40) ?
</code></pre>
<... | 1 | 2016-06-08T16:19:25Z | 37,707,947 | <p>How about this,</p>
<pre><code>list_dicts = [ {"begin" : 10, "end" : 20 },
{"begin" : 1, "end" : 2 },
{"begin" : 5, "end" : 7 },
{"begin" : 100, "end" : 200 }]
# sorted by d['begin']
ld = sorted(list_dicts, key=lambda d:d['begin'])
# merge
results = [ld[0]]
for idx... | 1 | 2016-06-08T16:23:54Z | [
"python",
"list"
] |
inserting numpy data into a bigger array of zeros | 37,707,992 | <p>I would like to put data of a numpy array of any size from the start of another bigger array of zeros.</p>
<p>Looking at numpy documentation I found the function np.put but it gives me a problem like this:</p>
<p>Supossing</p>
<pre><code>import numpy as np
b = np.zeros(5)
a = np.range(1,4)
np.put(b,a,a)
</code></... | 1 | 2016-06-08T16:25:47Z | 37,708,276 | <p>You're using <code>np.put</code> incorrectly.</p>
<pre><code>np.put(b, a, a)
# ^ ^ ^
# | | |
# Target | |
# Indices |
# Values
</code></pre>
<p>You told <code>np.put</code> to place the values of <code>a</code> at positions defined by <code>a</code>.</p>
<p>Instead:</p>
<pre><code>np.put... | 1 | 2016-06-08T16:40:30Z | [
"python",
"arrays",
"numpy"
] |
Deploy Python Script without using pip | 37,708,002 | <p>A Python 2.7 script needs to be deployed on several systems that does not have a internet connection for <code>pip install</code>. This script depends on several libraries installed using <code>pip install</code>.</p>
<p>How can these packages that are normally installed using <code>pip</code> be packaged along wit... | 0 | 2016-06-08T16:26:12Z | 37,708,097 | <p>You should download the package using a machine with internet with --download option </p>
<pre><code>pip install --download <path>
</code></pre>
<p>copy the contents of the directory to target machine then use </p>
<pre><code>pip install --no-index --find-links=<path>
</code></pre>
| 0 | 2016-06-08T16:31:27Z | [
"python",
"python-2.7",
"pip"
] |
Deploy Python Script without using pip | 37,708,002 | <p>A Python 2.7 script needs to be deployed on several systems that does not have a internet connection for <code>pip install</code>. This script depends on several libraries installed using <code>pip install</code>.</p>
<p>How can these packages that are normally installed using <code>pip</code> be packaged along wit... | 0 | 2016-06-08T16:26:12Z | 37,708,130 | <p>You can download tar package from PIP and extract it locally.
You can copy the package directory from the tar and place at the root location of your application.</p>
<p>The other approach is to copy the package directory to <code>/usr/lib/python2.7/site-packages/</code> or <code>/usr/local/lib/python2.7/site-packa... | 0 | 2016-06-08T16:33:02Z | [
"python",
"python-2.7",
"pip"
] |
Deploy Python Script without using pip | 37,708,002 | <p>A Python 2.7 script needs to be deployed on several systems that does not have a internet connection for <code>pip install</code>. This script depends on several libraries installed using <code>pip install</code>.</p>
<p>How can these packages that are normally installed using <code>pip</code> be packaged along wit... | 0 | 2016-06-08T16:26:12Z | 37,708,223 | <p>I guess you download the <code>packagename.whl</code> <strong>(for linux, use it's <code>.tar</code>)</strong> file of the required package on a machine and copy that file to install it over several machines using <code>pip -install packagename.whl</code> <strong>(<code>.tar</code> for Linux)</strong> on terminal.</... | 0 | 2016-06-08T16:38:06Z | [
"python",
"python-2.7",
"pip"
] |
Regex need to have two conditional end conditions | 37,708,036 | <p>I need to have a regex that deals with different end conditions, my idea was something like this, but it does not work</p>
<pre><code>re.findall(r'(?<=tests\[")(.*)((?="\])|(?=:)', input_string])
</code></pre>
<p>inputs are in this format:</p>
<pre><code>tests["Status code: " +responseCode.code] = responseCode... | -1 | 2016-06-08T16:28:27Z | 37,712,911 | <h1>Description</h1>
<pre class="lang-regex prettyprint-override"><code>^tests\["(.*?)(?::\s*"\s*[^\]]|"\])
</code></pre>
<p><img src="https://www.debuggex.com/i/7JlaluKv14hy30wa.png" alt="Regular expression visualization"></p>
<p>This regular expression will do the following:</p>
<ul>
<li>require the string to sta... | 1 | 2016-06-08T21:04:50Z | [
"python",
"regex"
] |
Possible to replace paragraph numbers in .doc file with "actual" text? | 37,708,079 | <p>In Microsoft Word, paragraph numbers are marked up slightly differently to the actual text of a document. To illustrate -</p>
<p><a href="http://i.stack.imgur.com/L8wfr.png" rel="nofollow"><img src="http://i.stack.imgur.com/L8wfr.png" alt="enter image description here"></a></p>
<p>I assume this is because they are... | 0 | 2016-06-08T16:30:31Z | 37,732,837 | <p>Depending on where that underline is coming from, converting the numbers to text may not have the result you're looking for. You need to make sure that all the formatting is part of the Heading style and not applied directly. The <code>ConvertNumbertToText</code> method, performed on any specified Range, will conver... | 1 | 2016-06-09T17:43:32Z | [
"python",
".net",
"ms-word",
"ms-office"
] |
Changing the linewidth and the color simultaneously in matplotlib | 37,708,166 | <p><a href="http://i.stack.imgur.com/DHvrA.png" rel="nofollow"><img src="http://i.stack.imgur.com/DHvrA.png" alt="enter image description here"></a></p>
<p>The figure above is a great artwork showing the wind speed, wind direction and temperature simultaneously. detailedly: </p>
<ul>
<li>The X axes represent the date... | 2 | 2016-06-08T16:34:36Z | 37,712,573 | <p>Using as inspiration <a href="http://stackoverflow.com/questions/22081361/pyplot-vertical-gradient-fill-under-curve">another question</a>.</p>
<p>One option would be to use <code>fill_between</code>. But perhaps not in the way it was intended. Instead of using it to create your line, use it to mask everything that ... | 2 | 2016-06-08T20:44:21Z | [
"python",
"matplotlib",
"visualization"
] |
Pandas Dataframe - Isolating values | 37,708,201 | <p>I have a dataframe (see below) and I want to run through it to isolate values above a certain number (60) and have it return the month, how do I do this:</p>
<pre><code> Month Increase
0 Jan 34
1 Feb 4
2 Mar 33
3 Apr 12
4 May 66
</code></pre>
| 1 | 2016-06-08T16:36:54Z | 37,708,265 | <p>IIUC you can use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p>
<pre><code>mask = df.Increase > 60
print (mask)
0 False
1 False
2 False
3 False
4 True
Name: Increase, dtype: bool
print (df[mask])
Month... | 1 | 2016-06-08T16:40:05Z | [
"python",
"pandas",
"filter",
"dataframe"
] |
Pandas Dataframe - Isolating values | 37,708,201 | <p>I have a dataframe (see below) and I want to run through it to isolate values above a certain number (60) and have it return the month, how do I do this:</p>
<pre><code> Month Increase
0 Jan 34
1 Feb 4
2 Mar 33
3 Apr 12
4 May 66
</code></pre>
| 1 | 2016-06-08T16:36:54Z | 37,708,489 | <p>Try this with filtering: </p>
<pre><code>df[df['Increase']>60 ]
# Month Increase
#4 May 66
df[df['Increase']>60 ]['Month']
#4 May
#Name: Month, dtype: object
</code></pre>
| 0 | 2016-06-08T16:51:46Z | [
"python",
"pandas",
"filter",
"dataframe"
] |
editing plot - python | 37,708,232 | <p>Hi I have a code that plots 2D data from a .dat file (I'll call it filename.dat which is just a .dat file with 2 columns of numbers). It works fine, I just have some questions as to how to improve it. </p>
<p>How can I edit my code to make the axes label larger and add a title? This code is not so easy to edit ... | 1 | 2016-06-08T16:38:35Z | 37,708,369 | <p>I assume you want to add them to the plot.</p>
<p>You can add a title with:</p>
<pre><code>plt.title("MyTitle")
</code></pre>
<p>and you add text to the graph with</p>
<pre><code># the following coordinates need to be determined with experimentation
# put them at a location and move them around if they are in
# ... | 1 | 2016-06-08T16:45:47Z | [
"python",
"plot"
] |
python flask sqlalchemy, i can'trun my db_create.py | 37,708,269 | <p>Ame getting this error of TypeError: <strong>init</strong>() takes exactly 1 argument (5 given)...where have i gone wrong?? any help i will appreciate ,thanks</p>
<p>thats my db_create.py file</p>
<pre><code>from app import db
from models import post
db.create_all()
db.session.add(post("Good", "i\m good","yes","... | 0 | 2016-06-08T16:40:10Z | 37,708,312 | <p>You don't need the <code>__init__</code> method in your post model. Just use the <code>__init__</code> method inherited from <code>db.Model</code> and you should be fine.</p>
<p>But then I believe you'd need to modify your <code>db_create.py</code> a bit:</p>
<p>For example:</p>
<pre><code>db.session.add(post(use... | 0 | 2016-06-08T16:42:30Z | [
"python"
] |
Running an infinite Python script while connected to database | 37,708,284 | <p>I'm working on a project to learn Python, SQL, Javascript, running servers -- basically getting a grip of full-stack. Right now my basic goal is this:</p>
<p>I want to run a Python script infinitely, which is constantly making API calls to different services, which have different rate limits (e.g. 200/hr, 1000/hr, ... | 0 | 2016-06-08T16:40:57Z | 37,708,611 | <p>I actually do exactly what you do for one of my personal applications and I can explain how I do it. </p>
<p>I use Celery instead of cron because it allows for finer adjustments in scheduling and it is Python and not bash, so it's easier to use. I have different tasks (basically a group of API calls and DB updates)... | 1 | 2016-06-08T16:58:32Z | [
"python",
"sql",
"postgresql",
"architecture",
"daemon"
] |
Python regexp everything between parenthesis on multiple lines | 37,708,327 | <p>My regexp is:</p>
<pre><code>TMP_REGEXP = r'_\(\s*(.*)\s*\)\s*$'
TMP_PATTERN = re.compile(TMP_REGEXP, re.MULTILINE)
</code></pre>
<p>File input_data.txt:</p>
<pre><code>print _(
'Test #A'
)
print _(
'''Test #B'''
'''Test #C'''
)
</code></pre>
<p>I am running this like that:</p>
<p... | 0 | 2016-06-08T16:43:17Z | 37,708,529 | <p>This worked for me:</p>
<pre><code>m = re.findall(r'(?s)_\((.*?)\)', content)
</code></pre>
<p><code>(?s)</code> looks for anything (including newlines).</p>
<p><code>_\(</code> matches your desired start.</p>
<p><code>(.*?)</code> looks for something.</p>
<p><code>\)</code> matches your end.</p>
<p>You might ... | 2 | 2016-06-08T16:53:59Z | [
"python",
"regex"
] |
Django (alternative to "runserver") | 37,708,334 | <p>I'm trying to figure out how to deploy a django website without having to use a "run server" method on the command prompt. About 30 people in the company will utilize it internally, but documentation states that runserver is only for development purposes and not for production.</p>
<p>I've looked at MAMP, Apache, F... | 0 | 2016-06-08T16:43:46Z | 37,708,757 | <p><strong>WARNING:</strong> I know OP doesn't want to use <code>runserver</code>, I'm knowingly suggesting that he probably should because scaling is not an issue yet and there's no reason to introduce other dependencies for other reasons.</p>
<p><strong>ANSWER</strong>
Not using runserver is a choice that depends on... | 1 | 2016-06-08T17:06:37Z | [
"python",
"django",
"deployment",
"webserver",
"localhost"
] |
Cast Column as Text or Prefix with Apostrophe When Writing a CSV File in Python 2.7 | 37,708,376 | <p>I have a script that that dumps data from a database into a CSV file via the Python CSV writer (more accurately, unicodecsv)</p>
<p>My problem is I have one column that I need to cast as text or prefix as an apostrophe because it's a 16 digit number and formats as scientific when viewed in Excel. THe code works pe... | 0 | 2016-06-08T16:46:09Z | 37,709,145 | <p>Iterate over the rows and replace the value with a string:</p>
<p>First example: define a function that makes a change then use <code>map</code> to implement the change:</p>
<pre><code>import functools
def change(row, col):
'''changes the column of a pyodbc row
returns modified pyodbc row
'''
retu... | 1 | 2016-06-08T17:29:26Z | [
"python",
"python-2.7",
"csv"
] |
Await sub task finished on outer task finished event (async version of add_done_callback) | 37,708,459 | <p>Let's say we have some task (sub task) that should be finished when outer task done. We have no control of outer task: we don't know when it would be finished (it can happen before sub task done), we can't wait for sub task inside.</p>
<p>In this snippet we will get warning because outer task finished before sub ta... | 0 | 2016-06-08T16:50:18Z | 37,712,893 | <p>AFAIK there is no way to solve this without internals. Personally I would <code>asyncio.gather</code> outer and sub tasks in one future and then rewrite callbacks. </p>
<p>Unfortunately Future's list of callbacks is not exposed with public interface (I'm using <code>_callbacks</code>):</p>
<pre><code>import asynci... | 1 | 2016-06-08T21:03:55Z | [
"python",
"python-3.x",
"python-asyncio"
] |
Iterate a simple calculation in Pandas across multiple files | 37,708,570 | <p>The code below generates a sum from the "Value" column in an ndarray called 'File1.csv'. </p>
<p>How do I apply this code to every file in a directory and place the sums in a new file called Sum.csv?</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.read_csv("~/File1.csv")
df["Value"].sum()
</code></... | 1 | 2016-06-08T16:56:10Z | 37,709,123 | <p>There's probably a nice way to do this with a pandas <code>Panel</code>, but this is a basic python implementation.</p>
<pre class="lang-py prettyprint-override"><code>import os
import pandas as pd
# Get the home directory (not recommended, work somewhere else)
directory = os.environ["HOME"]
# Read all files in d... | 2 | 2016-06-08T17:28:09Z | [
"python",
"pandas"
] |
Getting an error when entering valid data | 37,708,699 | <p>The program I am writing takes a GTIN-8 code from the user, searches for it in a CSV file and asks for the quantity etc. When I write a valid GTIN code, it still acts as if I have entered a wrong GTIN and asks me to re-enter the code. It basically does the opposite of what I want it to do.</p>
<p>My CSV file is as ... | 0 | 2016-06-08T17:03:33Z | 37,709,193 | <p>It's erroring because you're checking the entered code on each line of the csv and showing the prompt if <em>any</em> of the lines don't match the entered code.</p>
<pre><code>for row in csv.reader(file2):
if str(gtinNum) in row:
...
break
elif str(gtinNum) not in row:
print("The cod... | 0 | 2016-06-08T17:32:54Z | [
"python",
"validation",
"csv"
] |
Getting an error when entering valid data | 37,708,699 | <p>The program I am writing takes a GTIN-8 code from the user, searches for it in a CSV file and asks for the quantity etc. When I write a valid GTIN code, it still acts as if I have entered a wrong GTIN and asks me to re-enter the code. It basically does the opposite of what I want it to do.</p>
<p>My CSV file is as ... | 0 | 2016-06-08T17:03:33Z | 37,709,205 | <p>Use <code>raw_input</code> instead of <code>input</code> so that you are getting a string back instead of an integer.</p>
<pre><code>gtinNum = raw_input("Please enter the GTIN-8 Code of the product you would like to order:")
</code></pre>
<p>With <code>input</code>, when you provide an <code>int</code> as input, y... | 0 | 2016-06-08T17:33:31Z | [
"python",
"validation",
"csv"
] |
Getting an error when entering valid data | 37,708,699 | <p>The program I am writing takes a GTIN-8 code from the user, searches for it in a CSV file and asks for the quantity etc. When I write a valid GTIN code, it still acts as if I have entered a wrong GTIN and asks me to re-enter the code. It basically does the opposite of what I want it to do.</p>
<p>My CSV file is as ... | 0 | 2016-06-08T17:03:33Z | 37,710,815 | <p>Your real problem here is that you don't have the responsibilites of your program clearly separated - either in your mind or in the program.</p>
<p>To clearly define the different principles that you have:</p>
<ol>
<li>Get a valid GTIN # from the user</li>
<li>Search the CSV file for the provided GTIN #</li>
<li>I... | 0 | 2016-06-08T19:02:54Z | [
"python",
"validation",
"csv"
] |
Get the method on a class or its parents | 37,708,910 | <p>I need to get the method of a class or, if the class doesn't have a method, the method on its closest parent.
Another way of saying that is to find the method that would be called by calling a method on an instance of that class.</p>
<p>What's the best way of doing this?</p>
<p>(I'm going to respond to this quest... | 0 | 2016-06-08T17:15:04Z | 37,710,138 | <p>Attribute lookups on a class will already search base classes, with no extra code needed. Just do:</p>
<pre><code>@classmethod
def _init_args(cls):
return getargspec(cls.__init__).args[1:]
</code></pre>
<p>If you're using this only on new-style classes (which are the only kind of classes in Python 3), you'll a... | 1 | 2016-06-08T18:25:01Z | [
"python"
] |
Edit: Python - Going from 1 Player to Two Player Game Using Functions | 37,708,957 | <p>I posted something similar earlier, but I did a horrible job of asking the right question.
I'm trying to code a two player connect four game, but can only manage a 1 player game, with the user playing against the computer. Can anyone help me with trying to write a 2 player approach to the game? I'm still quite a be... | -2 | 2016-06-08T17:18:26Z | 37,709,206 | <p>I found a simpler way: I made a new function, <code>playerMoveO</code>, and renamed your old one <code>playerMoveX</code>. I made playerMoveO look like this:</p>
<pre><code>def playerMoveO(board):
validMove = False
while not validMove:
col = input("You are the O player. What column would you like t... | 0 | 2016-06-08T17:33:37Z | [
"python",
"function"
] |
Is there a way to use methods dynamically within a for loop in python? | 37,708,989 | <p>Is there a way to use methods within a loop in Python? Something like the following:</p>
<pre><code>obj=SomePythonObject()
list_of_methods=dir(obj)
for i in list_of_methods:
try:
print obj.i()
except:
print i,'failed'
</code></pre>
| 1 | 2016-06-08T17:20:04Z | 37,709,033 | <p>Yes that's possible, use <a href="https://docs.python.org/2/library/functions.html#callable" rel="nofollow">callable</a> and <a href="https://docs.python.org/2/library/functions.html#getattr" rel="nofollow">getattr</a>:</p>
<pre><code>obj=SomePythonObject()
list_of_methods=dir(obj)
for i in list_of_methods:
try... | 2 | 2016-06-08T17:22:37Z | [
"python"
] |
Parsing attribute name text from xml using xml.etree.elementTree | 37,709,063 | <p>I'm not sure how i could get the values from <code><array name="logEntries" type="value" depth="1"></code> with the following code.</p>
<p>What i currently have so far, which works if have only <strong>one</strong> array tag on the xml, but not on multiple.</p>
<pre><code>#Currently xml_input var is return... | 0 | 2016-06-08T17:24:36Z | 37,709,097 | <p>Try this:</p>
<pre><code>for child in root.findall('.//array[@name="logEntries"]/value'):
print(child.text)
</code></pre>
| 2 | 2016-06-08T17:26:37Z | [
"python",
"python-2.7",
"elementtree"
] |
My python script is getting stuck on fetching distinct count of a column from hive | 37,709,090 | <pre><code>cur.execute("SELECT COUNT(DISTINCT USER_ID) FROM tname")
a= cur.fetchone()[0]
</code></pre>
<p>And my table has more than 2,500,000,000 records.</p>
| 1 | 2016-06-08T17:26:02Z | 37,709,672 | <p>There is no syntax error in your query. Did you try use fetchall?</p>
<pre><code>a= cur.fetchall()
</code></pre>
| 0 | 2016-06-08T17:59:06Z | [
"python",
"count",
"hive",
"distinct"
] |
My python script is getting stuck on fetching distinct count of a column from hive | 37,709,090 | <pre><code>cur.execute("SELECT COUNT(DISTINCT USER_ID) FROM tname")
a= cur.fetchone()[0]
</code></pre>
<p>And my table has more than 2,500,000,000 records.</p>
| 1 | 2016-06-08T17:26:02Z | 37,728,867 | <p>Because USER_ID is not an indexed field, the database must access every row in order to determine all the unique values in that field. This can take a really long time with that many rows. (As you noted running the query in hive takes an hour to execute).</p>
<p>So, if by "hang" you mean you are getting something l... | 0 | 2016-06-09T14:32:06Z | [
"python",
"count",
"hive",
"distinct"
] |
Python/Django - String not accepted ('Expected a string or bytes-like object) | 37,709,126 | <p>At the end of a form wizard, I have a custom save for an object:</p>
<pre><code>def done(self, form_list, **kwargs):
(...)
start = datetime.strptime(self.request.session['event_start'], '%Y-%m-%d %H:%M:%S')
duration = datetime.strptime(self.request.session['duration'], '%H:%M:%S').time()
EventIns... | 2 | 2016-06-08T17:28:18Z | 37,709,231 | <p>It's highlighted on the last line, but it's obvious that by tracing the stack it ends up in django's <code>dateparse.py</code> file, which indicates that it's related to <code>datetime</code> issues not correctly parsed. Traceback would only highlight a complete statement but since your <code>create</code> function ... | 3 | 2016-06-08T17:34:42Z | [
"python",
"django"
] |
Navigating html table lxml | 37,709,153 | <p>I have some html which looks like:</p>
<pre><code><html>
<body>
<table cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td align="left" colspan="4">
<!-- BEGIN NEXT PREV LINKS -->
<table cellspacing="2" cellpadding="0" border="0">... | 0 | 2016-06-08T17:30:11Z | 37,711,715 | <p>You will have to traverse the html document and get a more refined XPath. Additionally, you face the challenge of related data in different elements requiring two XPath expressions. This will require some manipulation to get the final related results together:</p>
<pre><code>import lxml.etree as et
with open("empl... | 1 | 2016-06-08T19:53:21Z | [
"python",
"lxml"
] |
Navigating html table lxml | 37,709,153 | <p>I have some html which looks like:</p>
<pre><code><html>
<body>
<table cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td align="left" colspan="4">
<!-- BEGIN NEXT PREV LINKS -->
<table cellspacing="2" cellpadding="0" border="0">... | 0 | 2016-06-08T17:30:11Z | 37,712,250 | <p>Not sure what the <code>...</code> should be in your expected output but to get the data in the first three sublists, you can narrow down the search looking for trs that have a nowrap attribute and only one attribute altogether:</p>
<pre><code>from lxml import html
root = html.fromstring(h)
rows = root.xpath("//tr... | 1 | 2016-06-08T20:25:51Z | [
"python",
"lxml"
] |
Python: importing from somewhere else? | 37,709,164 | <pre><code>bash-4.1$ airflow initdb
Traceback (most recent call last):
File "/u/bin/airflow", line 4, in <module>
from airflow import configuration
File "/u/lib/python2.7/site-packages/airflow/__init__.py", line 31, in <module>
from airflow.models import DAG
File "/u/lib/python2.7/site-package... | 2 | 2016-06-08T17:31:01Z | 38,065,842 | <p>You need to install <a href="https://pypi.python.org/pypi/six" rel="nofollow">Six</a> python package.</p>
<p>Just make a <code>pip install six</code></p>
| 1 | 2016-06-28T01:48:54Z | [
"python",
"airflow"
] |
Python - writing dbf to txt, text file incomplete | 37,709,214 | <p>I am writing a script in Python to automate a GIS process. The general process is as follows:</p>
<ul>
<li>set up initial parameters</li>
<li>establish a database connection</li>
<li>run an ArcGIS model</li>
<li>convert the resulting table into <code>.dbf</code></li>
<li>convert the <code>.dbf</code> to a <code>.tx... | 0 | 2016-06-08T17:34:05Z | 37,711,124 | <p>Change <code>del (ERU_file)</code> to <code>report.close()</code>. <code>del (ERU_file)</code> just deletes the string identifying the location of the file, it doesn't actually close the open file handle and flush the data to disk.</p>
<p>Or better yet, use a <a href="http://www.pythonforbeginners.com/files/with-st... | 1 | 2016-06-08T19:21:08Z | [
"python",
"arcgis"
] |
Python equivalent for do.call(rbind, lapply()) from R | 37,709,265 | <p>One of my main tools in my workflows is the <code>do.call(rbind, lapply())</code> as exampled here in R:</p>
<pre><code>df1 <- data.frame(x1 = rnorm(10), x2 = rnorm(10), x3 = rnorm(10))
df2 <- data.frame(x1 = rnorm(10, 5), x2 = rnorm(10), x3 = rnorm(10))
getp <- function(var) {
return(t.test(df1[, var],... | 3 | 2016-06-08T17:36:58Z | 37,709,515 | <p>Instead of passing variables one by one, you can pass all three:</p>
<pre><code>ttest_ind(df1[vars], df2[vars])[1]
Out[85]: array([ 4.97835813e-11, 8.30544748e-08, 9.24917262e-07])
</code></pre>
<p>The returning object is a one-dimensional array. If you want a dataframe instead</p>
<pre><code>pd.DataFrame(tt... | 6 | 2016-06-08T17:50:03Z | [
"python",
"pandas",
"lapply"
] |
Comparing data flow graphs quickly in Python | 37,709,402 | <h2>Background</h2>
<p>I want to prove that two data processing functions are functionally equivalent. To do this I built an abstract syntax tree for each function and then ran a simulation of the control flow to construct a data flow graph of the final output.</p>
<p>The data flow graph is represented by 3-tuples o... | 1 | 2016-06-08T17:44:30Z | 37,710,263 | <p>I can't speak to whether it's idiomatic Python, but you could borrow an idea from Lisp called <a href="https://en.wikipedia.org/wiki/Hash_consing" rel="nofollow">hash consing</a>. In a sentence, the idea is to use a hash table to increase subobject sharing to the max, allowing tuples to be compared by identity inste... | 2 | 2016-06-08T18:32:02Z | [
"python",
"algorithm"
] |
File Not Found Error Python 3.5 | 37,709,492 | <p>The code below gives me <code>FileNotFoundError</code>. I'm running Python 3.5.1 in Jupyter Notebook (installed with Anaconda package). The file <code>test.txt</code> exists in the described folder with a simple text string in it. </p>
<pre><code> myfile = open(r'C:\Users\324706\test.txt', 'r')
</code></pre>
<p><... | -1 | 2016-06-08T17:48:53Z | 37,709,586 | <p>It looks pretty self explanatory. You don't have the correct destination for the file you're trying to open. Double check where it is and try again.</p>
| 0 | 2016-06-08T17:53:47Z | [
"python"
] |
File Not Found Error Python 3.5 | 37,709,492 | <p>The code below gives me <code>FileNotFoundError</code>. I'm running Python 3.5.1 in Jupyter Notebook (installed with Anaconda package). The file <code>test.txt</code> exists in the described folder with a simple text string in it. </p>
<pre><code> myfile = open(r'C:\Users\324706\test.txt', 'r')
</code></pre>
<p><... | -1 | 2016-06-08T17:48:53Z | 37,709,796 | <p>Thank you Peter Brittain, and others. I did that and the file is shown as test.txt.txt. </p>
| 0 | 2016-06-08T18:05:33Z | [
"python"
] |
How do I convert an Integer to ctypes.c_byte in python | 37,709,499 | <p>I am trying to use Read and Write ProcessMemory form <code>kernel32.dll</code> in Python 3.5.</p>
<p>I got <code>ReadProcessMemory</code> working like this:</p>
<pre><code>def ReadMemInt(adress):
buffer = (ctypes.c_byte * 8)()
bytesRead = ctypes.c_ulonglong(0)
if ctypes.windll.kernel32.ReadProcessMemor... | 0 | 2016-06-08T17:49:29Z | 37,715,783 | <p>Got it working:</p>
<pre><code> def WriteMem(self, adress, Val, type):
buffer = (ctypes.c_byte * self.GetSize(type))(*struct.pack(type, Val))
bytesRead = ctypes.c_ulonglong(0)
if ctypes.windll.kernel32.WriteProcessMemory(self.processHandle, adress, buffer, len(buffer), ctypes.byref(bytesR... | 0 | 2016-06-09T02:12:30Z | [
"python",
"kernel"
] |
new environment conda install pandas | 37,709,572 | <p>If I create a new environment in conda and add packages, shouldn't the python interpreter still find packages in the base installation if I don't add them to the new environment? For example:</p>
<pre><code>conda create -n work pysal
</code></pre>
<p>then activate and I can't import pandas which is in the base? e... | 0 | 2016-06-08T17:52:53Z | 37,710,330 | <pre><code>conda create -n <name> <packages>
</code></pre>
<p>creates a new environment containing only those packages that are explicitly given to the create command.
Using the install command you can install pandas in your new environment. If the package in your base environment or any other environment ... | 2 | 2016-06-08T18:36:02Z | [
"python",
"conda"
] |
Mock Tornado class in Python | 37,709,628 | <p>I would like to cover <code>on_text</code> method with unit test. I feel like checking <code>on_text</code> with non-unicode message to see that <code>send_message</code> was called.</p>
<pre><code>class MyTornadoClass(object):
@gen.coroutine
def on_text(self, message):
"""
User message cont... | 0 | 2016-06-08T17:55:57Z | 37,786,769 | <p>When you use <code>patch.object()</code> as a context manager, the patching applies to the indented block after the <code>with</code> statement. If you move the call to <code>.on_text()</code> <em>inside</em> the block, you'll see a different <code>AssertionError</code>:</p>
<pre><code>with mock.patch.object(bot_te... | 1 | 2016-06-13T09:58:41Z | [
"python",
"unit-testing",
"mocking"
] |
Can I use something other than 'self' in this PyQt Function? | 37,709,648 | <p>I am new to Python and PyQt. This function is not within a class, and is called by another function that is not self referencing. (I'm not sure if that's what you call it. What I mean is, none of the functions are of the type <code>function_name(self)</code>) </p>
<pre><code>def openFileDialog():
filename = QtG... | 0 | 2016-06-08T17:57:52Z | 37,709,917 | <p>The <code>parent</code> argument is just so the <code>QFileDialog</code> is correctly parented to a widget. There are many reasons why you would want dialogs and windows to be correctly parented to each other. </p>
<ul>
<li>They inherit the styling and color palette of the parent.</li>
<li>They will be created wit... | 2 | 2016-06-08T18:12:45Z | [
"python",
"pyqt",
"pyqt4"
] |
MySQLdb can't initialize character set utf-8 error | 37,709,659 | <p>I am trying to insert some Arabic word into the <code>arabic_word</code> column of my <code>hanswehr2</code> database Maria DB using the MySQLdb driver.</p>
<p>I was getting a <code>latin-1 encode error</code>. But after reading around, I found out that the MySQLdb driver was defaulted to <code>latin-1</code> and I... | 1 | 2016-06-08T17:58:26Z | 37,710,109 | <p>There is a thing called <strong>collations</strong> that helps encode/decode characters for specific languages.
<a href="http://programmers.stackexchange.com/questions/95048/what-is-the-difference-between-collation-and-character-set">http://programmers.stackexchange.com/questions/95048/what-is-the-difference-between... | -1 | 2016-06-08T18:23:17Z | [
"python",
"mysql",
"utf-8",
"character-encoding",
"latin1"
] |
MySQLdb can't initialize character set utf-8 error | 37,709,659 | <p>I am trying to insert some Arabic word into the <code>arabic_word</code> column of my <code>hanswehr2</code> database Maria DB using the MySQLdb driver.</p>
<p>I was getting a <code>latin-1 encode error</code>. But after reading around, I found out that the MySQLdb driver was defaulted to <code>latin-1</code> and I... | 1 | 2016-06-08T17:58:26Z | 37,743,769 | <p>The charset alias for UTF-8 in MySQL is <strong><code>utf8</code></strong> (no hyphen). </p>
<p>See <a href="https://dev.mysql.com/doc/refman/5.5/en/charset-charsets.html" rel="nofollow">https://dev.mysql.com/doc/refman/5.5/en/charset-charsets.html</a> for available charsets.</p>
<p>Note, if you need to use non-BM... | 3 | 2016-06-10T08:43:25Z | [
"python",
"mysql",
"utf-8",
"character-encoding",
"latin1"
] |
How do I delete data in a variable without deleting the variable? | 37,709,676 | <p>I'm trying to make a program which you can add stuff to your shopping list.</p>
<pre><code>shopping_list = ["Eggs", "Milk", "Bread"]
</code></pre>
<p>Now i know how to add and remove items, but how do i delete the string or number in a variable without losing the variable?</p>
<pre><code>price = "£12"
</code></p... | 1 | 2016-06-08T17:59:21Z | 37,709,701 | <p>Just do </p>
<pre><code>price = None
</code></pre>
<p>Anything referenced by that variable will get garbage-collected.</p>
| 4 | 2016-06-08T18:00:34Z | [
"python"
] |
Finding simplest solution to list equality python | 37,709,733 | <p>I am looking for a module or a function to write that does the following in Python:</p>
<p>Say I have two matrices:</p>
<pre><code>left = ['2B', '1A', '2A+1B']
right = ['8C', '3C', '2D']
</code></pre>
<p>I want to find the smallest whole numbers for A, B, C, and D (all must be greater than 0) such that </p>
<pre... | 3 | 2016-06-08T18:01:54Z | 37,710,099 | <p>In general, you are trying to solve a system of equations over the integers, which is no simple task (<a href="https://people.hofstra.edu/raymond_n_greenwell/matrixarticle.pdf" rel="nofollow">check out this paper</a>).</p>
<p>However there are some tools that can help, assuming you put in the work to transform your... | 3 | 2016-06-08T18:22:57Z | [
"python",
"solver"
] |
Password program not working in Python | 37,709,795 | <p>I have made a password prog to input the first line of the file as the password and then upon accessing the file the prog should ask the password and only if the password is right should the contents of the file be printed. But I just canât get it to work. Pls help.</p>
<pre><code>p=open("abc.txt", 'w+')
p.write(... | 1 | 2016-06-08T18:05:30Z | 37,709,937 | <p><code>readline()</code> returns the line, including the trailing new line. You have to strip it off: </p>
<pre><code>if p.readline().rstrip() == y:
</code></pre>
| 2 | 2016-06-08T18:13:57Z | [
"python"
] |
Python/PostgreSQL insert row having no effect | 37,709,951 | <p>I am using the pg8000 module to connect a python script to a postgreSQL database and I want to insert some new rows. When I run the script I get no errors and it appears to run fine, but when I check the table afterwards, nothing was actually added to it. </p>
<p>What is confusing me is that if I print out the qu... | 0 | 2016-06-08T18:14:31Z | 37,710,128 | <p>Since autocommit is off by default, unless you explicitly call conn.commit(), any actions done in the transaction will be undone. However, ID numbers are not rolled back and hence you are seeing that behavior.</p>
<p>You have two options:
1) explicitly commit after performing execute statements:</p>
<pre><code>con... | 4 | 2016-06-08T18:24:29Z | [
"python",
"postgresql"
] |
Python: Using Pandas, how do I choose the columns in my output? | 37,709,960 | <p>I am running my whole Active directory against user accounts trying to find what doesn't belong.
Using my code my output gives me the words that only occur once in the Username column. Even though I am analyzing one column of data, I want to keep all of the columns that are with the data. </p>
<pre><code>from ... | -2 | 2016-06-08T18:15:22Z | 37,710,560 | <p>Based on your description, I guess you want to use the counts of unique elements as index to select rows in your dataframe. Maybe you can try this:</p>
<pre><code>df2 = pd.DataFrame()
counts = f['User Name'].value_counts()
counts = counts[counts == 1].index
for index in counts:
df2 = df2.append(f[f['User Na... | 1 | 2016-06-08T18:47:59Z | [
"python",
"python-3.x",
"pandas",
"ipython",
"jupyter-notebook"
] |
Dask Bag.to_textfiles works with single partition but not multiple | 37,709,962 | <p>Very briefly.. is this a bug or am I missing something?
<code>tmp_j</code> is a bag with a single item and 6 partitions. However, I get
similar responses with larger bags. </p>
<p>This particular bag was constructed with: </p>
<pre><code>>>> tmp_j = jnode_b.filter(lambda r: (r['node']['attrib']['uid'] ==... | 1 | 2016-06-08T18:15:33Z | 37,713,937 | <p>This was a genuine bug and has now been resolved in master</p>
<pre><code>In [1]: import dask.bag as db
In [2]: db.range(5, npartitions=5).filter(lambda x: x == 1).map(str).to_textfiles('*.txt')
In [3]: ls *.txt
0.txt 1.txt 2.txt 3.txt 4.txt C:\nppdf32Log\debuglog.txt foo.txt
</code></pre>
| 1 | 2016-06-08T22:23:36Z | [
"python",
"dask"
] |
Speed up pandas lookup | 37,709,975 | <p>I have 2 pandas series: data and events.</p>
<ul>
<li>data is an ordered series of datapoints</li>
<li>events contains indices of points of interest in data</li>
</ul>
<p>I would like to extract a window of fixed size around each point of interest.</p>
<p>I came up with:</p>
<pre><code>res = []
for k in events:
... | 2 | 2016-06-08T18:16:12Z | 37,710,967 | <p>I believe filtering on a time index should be very efficient, with Pandas.</p>
<p>Something like</p>
<pre><code>df.set_index('my_time_variable',inplace=True)
df[time - ticks_before:time + ticks_after]
</code></pre>
<p>should speed up the lookup a lot. and then you can still loop over all your dates.
Be sure to us... | 0 | 2016-06-08T19:11:37Z | [
"python",
"pandas"
] |
Speed up pandas lookup | 37,709,975 | <p>I have 2 pandas series: data and events.</p>
<ul>
<li>data is an ordered series of datapoints</li>
<li>events contains indices of points of interest in data</li>
</ul>
<p>I would like to extract a window of fixed size around each point of interest.</p>
<p>I came up with:</p>
<pre><code>res = []
for k in events:
... | 2 | 2016-06-08T18:16:12Z | 37,712,601 | <p>Simplified a bit, Question: Why is there a series of number for xxx.mean(). Mean should be one number! This is likely adding processing time. </p>
<pre><code> def fast_loop(data, events, ticks_before, ticks_after):
win_len = ticks_before + ticks_after + 1
res = np.zeros( (len(events), win_len) )... | 0 | 2016-06-08T20:46:12Z | [
"python",
"pandas"
] |
Speed up pandas lookup | 37,709,975 | <p>I have 2 pandas series: data and events.</p>
<ul>
<li>data is an ordered series of datapoints</li>
<li>events contains indices of points of interest in data</li>
</ul>
<p>I would like to extract a window of fixed size around each point of interest.</p>
<p>I came up with:</p>
<pre><code>res = []
for k in events:
... | 2 | 2016-06-08T18:16:12Z | 37,713,300 | <p>here is a numpy solution which seems to be 10 times faster, compared to <code>fast_loop</code>:</p>
<pre><code># numpy solution
def np1(data, events, ticks_before, ticks_after):
return pd.Series(
np.concatenate(
[data.values[x - ticks_before: x + ticks_after+1] for x in event... | 2 | 2016-06-08T21:32:11Z | [
"python",
"pandas"
] |
Speed up pandas lookup | 37,709,975 | <p>I have 2 pandas series: data and events.</p>
<ul>
<li>data is an ordered series of datapoints</li>
<li>events contains indices of points of interest in data</li>
</ul>
<p>I would like to extract a window of fixed size around each point of interest.</p>
<p>I came up with:</p>
<pre><code>res = []
for k in events:
... | 2 | 2016-06-08T18:16:12Z | 37,713,356 | <p>I give up! I've tried a bunch of things. Below are just a few:</p>
<pre><code>def pir1(data, events, ticks_before, ticks_after):
rng = np.add.outer(events, [-1 * ticks_before, ticks_after + 1])
res = np.zeros(ticks_before + ticks_after + 1)
for r in rng:
res += data[r[0]:r[1]]
res /= len(r... | 1 | 2016-06-08T21:37:08Z | [
"python",
"pandas"
] |
Not reaching part of code | 37,710,012 | <p>My piece of code below is not reaching the intended point.</p>
<pre><code>print("Welcome to the Stockroom\n")
print("The following products need new stock:\n")
f = open("lowstock","r")
print(f.read())
choice = input("\nTo update the stock levels of the above products, type 1. To cancel, enter anything else.")
i... | 0 | 2016-06-08T18:18:59Z | 37,710,735 | <p>In Python 3, the <code>input</code> function always returns a string. So if the user enters <code>1</code>, <code>choice</code> will be <code>"1"</code>, not the integer <code>1</code> which you're testing for.</p>
<p>You seem to have edited the question to change things in the wrong direction, for reasons that are... | 1 | 2016-06-08T18:57:49Z | [
"python"
] |
How do I reach cookie information in python requests? | 37,710,226 | <p>I am trying to write a small script that will allow me to see information related to the cookies set by my website.</p>
<p>I want to know if it has <code>secure</code> or <code>httpOnly</code> flags set on them. But so far I wasn't able to do it, I only figured out how to get cookie names and values. Here is my cur... | 1 | 2016-06-08T18:30:06Z | 37,711,289 | <p>You can extract the information from each cookie individually:</p>
<pre><code>import requests
r = requests.post('http://www.about.com')
for cookie in r.cookies:
print(cookie.__dict__)
print(cookie.secure)
</code></pre>
<p>This is because <code>r.cookies</code> is an instance of <code>RequestsCookieJar</c... | 3 | 2016-06-08T19:30:10Z | [
"python",
"cookies",
"python-requests"
] |
Python - Streamlining sudoku solver code | 37,710,233 | <p>I am writing a script to efficiently solve a sudoku puzzle, but there's one part of my code that I think is extremely ugly and want to streamline.</p>
<pre><code>def square(cell):
rows='ABCDEFGHI'
cols='123456789'
cell_row = cell[0][0]
cell_col = cell[0][1]
if cell_row in rows[0:3]:
x... | 2 | 2016-06-08T18:30:23Z | 37,710,589 | <p>I was able to make a greatly simplified version of your formula. I started by assigning both the row and column a 0-based index. Then I used integer division to only get the information about what 3-block the square is in. Since moving down a 3-block of rows increases the index by 3 while moving to the right only... | 1 | 2016-06-08T18:49:30Z | [
"python",
"performance",
"grid",
"coordinates",
"sudoku"
] |
Python - Streamlining sudoku solver code | 37,710,233 | <p>I am writing a script to efficiently solve a sudoku puzzle, but there's one part of my code that I think is extremely ugly and want to streamline.</p>
<pre><code>def square(cell):
rows='ABCDEFGHI'
cols='123456789'
cell_row = cell[0][0]
cell_col = cell[0][1]
if cell_row in rows[0:3]:
x... | 2 | 2016-06-08T18:30:23Z | 37,710,600 | <p><strong>Edit</strong>: Fixed offset by 1 - even though I would rather start at 0 as you'll probably want to use the returned value as an index for another (sub-)array.</p>
<p>And as I cannot comment on other answers yet just my 2 cents here:
cdlane's answer is slightly slower than the one presented here. If you ge... | 0 | 2016-06-08T18:50:05Z | [
"python",
"performance",
"grid",
"coordinates",
"sudoku"
] |
Python - Streamlining sudoku solver code | 37,710,233 | <p>I am writing a script to efficiently solve a sudoku puzzle, but there's one part of my code that I think is extremely ugly and want to streamline.</p>
<pre><code>def square(cell):
rows='ABCDEFGHI'
cols='123456789'
cell_row = cell[0][0]
cell_col = cell[0][1]
if cell_row in rows[0:3]:
x... | 2 | 2016-06-08T18:30:23Z | 37,710,891 | <p>Personally, I don't think magic numbers like '65' and '97' make the solution more <em>presentable</em>! How about:</p>
<pre><code>def square(cell):
rows = 'ABCDEFGHI'
cell_row = rows.index(cell[0][0])
cell_col = int(cell[0][1]) - 1
return 3 * (cell_row // 3) + cell_col // 3 + 1
</code></pre>
| 1 | 2016-06-08T19:07:04Z | [
"python",
"performance",
"grid",
"coordinates",
"sudoku"
] |
Gspread to access google spreadsheet: HttpAccessTokenRefreshError, invalid JWT | 37,710,245 | <p>I'm struggling to get access to a google spreadsheet with python 2.7 using gspread.</p>
<p>Here's what I have so far:</p>
<pre><code>import gspread
from oauth2client.service_account import ServiceAccountCredentials
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_j... | 3 | 2016-06-08T18:31:07Z | 37,756,572 | <p>Looks like it was an issue with the version of oauth2client that I was using. To get things to work, I downgraded to oauth2client version 1.5.1. Then I used the following to gain access to the spreadsheet:</p>
<pre><code>import json
import gspread
from oauth2client.client import SignedJwtAssertionCredentials
json_... | 1 | 2016-06-10T20:19:26Z | [
"python",
"google-spreadsheet",
"gspread",
"oauth2client"
] |
urlopen works in Python 2.7 but fails in Python 3.4 | 37,710,264 | <p>I have both Python 2.7.10 and Python 3.4.4 running on my computer. The following code works in Python 2.7.10:</p>
<pre><code>import urllib2
print urllib2.urlopen('http://google.com').read()
</code></pre>
<p>However, if I move on to Python 3.4.4 and run</p>
<pre><code>import urllib.request
print(urllib.request.url... | 2 | 2016-06-08T18:32:12Z | 37,712,667 | <p>After working at the solution, the Python 2.7 code began throwing the same error. Out of frustration I began applying the microscoft fix. I started by logging off and logging back in again. Everything works as intended now...</p>
| 0 | 2016-06-08T20:50:34Z | [
"python",
"windows",
"urlopen"
] |
Removing strings in between two strings django templates | 37,710,317 | <p>I have objects that reference other names of objects to save database transactions </p>
<p>so when I render the html page It prints a string like so <code>(u'aRandomModel253', 0)</code> <----that is the exact string it prints now I need to get 'aRandomModel253' out of that string so I can organize my webpage lik... | 0 | 2016-06-08T18:35:33Z | 37,710,993 | <p>You could use string splicing. If the thing you want is always in single quotes you could use <code>str.find()</code></p>
<p>Ex:</p>
<pre><code>String = "(u'aRandomModel253', 0)"
ModifiedString = [String.find("'"):String[String.find("'"):].find("'")]
</code></pre>
<p>This splices the string from the first occur... | 0 | 2016-06-08T19:13:00Z | [
"python",
"django"
] |
Removing strings in between two strings django templates | 37,710,317 | <p>I have objects that reference other names of objects to save database transactions </p>
<p>so when I render the html page It prints a string like so <code>(u'aRandomModel253', 0)</code> <----that is the exact string it prints now I need to get 'aRandomModel253' out of that string so I can organize my webpage lik... | 0 | 2016-06-08T18:35:33Z | 37,711,406 | <p>Used a custom tag filter <a href="https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/" rel="nofollow">https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/</a></p>
<pre><code>from django import template
register = template.Library()
@register.filter
def number_and(value):
return find_... | 0 | 2016-06-08T19:35:01Z | [
"python",
"django"
] |
Removing strings in between two strings django templates | 37,710,317 | <p>I have objects that reference other names of objects to save database transactions </p>
<p>so when I render the html page It prints a string like so <code>(u'aRandomModel253', 0)</code> <----that is the exact string it prints now I need to get 'aRandomModel253' out of that string so I can organize my webpage lik... | 0 | 2016-06-08T18:35:33Z | 37,711,799 | <p>It <em>looks</em> like your object is a tuple. If not, then it likely has some other <code>.name</code> property or something (and if not, you should be able to add it):</p>
<pre><code><div>{{ model.0 }}</div>
</code></pre>
| 0 | 2016-06-08T19:58:15Z | [
"python",
"django"
] |
universal inner product of pandas.Series AND columns in a pandas.DataFrame | 37,710,387 | <p>I'm trying to build a function that computes the conditional Shannon entropy in a dataframe. I give it the following parameters:</p>
<pre><code>import random
rows = 1000
columns = 3
data=pd.DataFrame([[random.randrange(0, 4, 1) for x in range(columns)] for y in range(rows)], columns=['a', 'b', 'c'])
target = ['a',... | 0 | 2016-06-08T18:39:44Z | 37,746,014 | <p>Ok, I figured it out. Following @BrenBarn's advice I tracked the use of DataFrames and Series. </p>
<p>The problem I was having with the case <code>type(entropy)==Series</code>, (when there is just one column, <code>target=['a']</code>), is due to unexpected behavior of the <code>apply</code> function in line <code... | 0 | 2016-06-10T10:33:06Z | [
"python",
"pandas"
] |
Python datetime weekday strftime() vs weekday() | 37,710,397 | <p>Have a pandas dataframe df, in order to get weekday from the date column, I did:</p>
<pre><code>df_raw['DayOfWeek'] = df_raw[str_date_colname].dt.strftime('%w')
</code></pre>
<p>It returns weekday as a decimal number, where 0 is Sunday and 6 is Saturday. However, I want to get 0 is Monday and 6 is Sunday. So I did... | 2 | 2016-06-08T18:40:11Z | 37,710,616 | <p>If <code>df</code> is a Pandas DataFrame, then <code>df['date']</code> is a Series. If <code>df['date']</code> contains datetimes (in particular, if the dtype is <code>datetime64[ns]</code>s) then the Series will have a <a href="http://pandas.pydata.org/pandas-docs/stable/basics.html#dt-accessor" rel="nofollow"><cod... | 2 | 2016-06-08T18:50:59Z | [
"python",
"datetime",
"dataframe",
"strftime",
"weekday"
] |
Accessing OrientDB from Python | 37,710,542 | <p>I want to convert a >1mn record MySQL database into a graph database, because it is heavily linked network-type data. The free version of Neo4J had some restrictions I thought I might bump up against, so I've installed OrientDB (Community 2.2.0) (on Ubuntu Server 16.04) and got it working. Now I need to access it fr... | 5 | 2016-06-08T18:47:16Z | 37,991,865 | <p>I firstly got the error, but after upgrading Pyorient to last version 1.5.4 I get no errors.</p>
<pre><code>$ python test.py
('SessionID=', 6)
('Database', 'GratefulDeadConcerts', 'exists')
</code></pre>
<hr>
<pre><code>$ python --version
Python 2.7.11
</code></pre>
| 2 | 2016-06-23T12:38:52Z | [
"python",
"orientdb",
"pyorient"
] |
pyqt is installed but it won't import (Mac) | 37,710,574 | <p>I installed PyQt4 and I have xcode, Qt, Sip, and Python 2.7. When I check in terminal, it says that PyQt is installed and when I view the path there is no PyQt in the path. I have put it in the path before but it goes away when I close the shell. When I try and import it it says no module named PyQt4. Help </p>
<pr... | 0 | 2016-06-08T18:48:54Z | 37,710,712 | <p>Assuming that adding PyQt4 to PATH solved your problem before, do it again except now do it in the ~/.bashrc file. So, as follows:</p>
<ol>
<li>Add PyQt4 to PATH in ~/.bashrc as you have previously done.</li>
<li><code>source ~/.bashrc</code> from command line. </li>
<li>Reattempt import</li>
</ol>
| 0 | 2016-06-08T18:56:24Z | [
"python",
"import",
"pyqt4"
] |
'pip' is not recognized as an internal or external command, operable program or batch file | 37,710,662 | <p>I'm trying to install Tweepy using pip, but I keep getting this as the response:
<a href="http://i.stack.imgur.com/fSGUd.png" rel="nofollow"><img src="http://i.stack.imgur.com/fSGUd.png" alt="enter image description here"></a></p>
<p>I've seen similar problems and people always suggest adding C:\Python34\Scripts to... | 1 | 2016-06-08T18:53:42Z | 37,710,728 | <p>It seems like you are using windows so you need to download the <code>get-pip.py</code> and run like this.</p>
<p><code>Path_to_your_Python.exe\python.exe Path_to_get-pip.py\get-pip.py tweepy</code></p>
<p>Here is the link for download <a href="https://pip.pypa.io/en/stable/installing/" rel="nofollow">get-pip.py</... | 0 | 2016-06-08T18:57:09Z | [
"python",
"python-3.x",
"cmd",
"path",
"pip"
] |
'pip' is not recognized as an internal or external command, operable program or batch file | 37,710,662 | <p>I'm trying to install Tweepy using pip, but I keep getting this as the response:
<a href="http://i.stack.imgur.com/fSGUd.png" rel="nofollow"><img src="http://i.stack.imgur.com/fSGUd.png" alt="enter image description here"></a></p>
<p>I've seen similar problems and people always suggest adding C:\Python34\Scripts to... | 1 | 2016-06-08T18:53:42Z | 37,710,791 | <p>I would recommend using this guide for adding a new folder to your system path, normally works for me. It goes through a GUI instead of adding through the command line.</p>
<p><a href="http://windowsitpro.com/systems-management/how-can-i-add-new-folder-my-system-path" rel="nofollow">http://windowsitpro.com/systems-... | 1 | 2016-06-08T19:00:47Z | [
"python",
"python-3.x",
"cmd",
"path",
"pip"
] |
Python jedi code completion: how to get the doc string | 37,710,709 | <p>I have this snippet of Python code. In the Case A, I don't get the doc string, but in the Case B, I get it.</p>
<p>Please advise me to get it to work in the Case A. Thanks.</p>
<pre><code>from jedi import Script, Interpreter
import math
# Case A
completions = Interpreter(source="math.sin(0)", line=1, column=7, na... | 0 | 2016-06-08T18:56:08Z | 38,419,433 | <p>This has been fixed a few weeks ago! Just checkout the current dev branch.</p>
<p>It will probably be released to PyPi in one or two months.</p>
| 1 | 2016-07-17T08:45:12Z | [
"python",
"jedi-vim"
] |
Is it possible to modify a class with a decorator | 37,710,747 | <p>I am writing a class in python for some settings wich looks like this:</p>
<pre><code>class _CanvasSettings:
def __init__(self, **kwargs):
super().__init__()
self._size_x = _int(kwargs, 'size_x', 320)
self._size_y = _int(kwargs, 'size_y', 240)
self._lock_ratio = _bool(kwargs'lock... | 1 | 2016-06-08T18:58:11Z | 37,711,217 | <p>Decorator for the class.</p>
<pre><code>def add_get_set(cls):
for prop in cls.PROPERTIES:
# Note cannot be "lambda self: getattr(self, prop)" because of scope prop changes to be the last item in PROPERTIES
setattr(cls, "get"+prop, lambda self, attr=prop: getattr(self, attr))
return cls
@ad... | 1 | 2016-06-08T19:25:37Z | [
"python",
"class",
"python-3.x",
"decorator"
] |
Is it possible to modify a class with a decorator | 37,710,747 | <p>I am writing a class in python for some settings wich looks like this:</p>
<pre><code>class _CanvasSettings:
def __init__(self, **kwargs):
super().__init__()
self._size_x = _int(kwargs, 'size_x', 320)
self._size_y = _int(kwargs, 'size_y', 240)
self._lock_ratio = _bool(kwargs'lock... | 1 | 2016-06-08T18:58:11Z | 37,711,654 | <p>It's certainly possible to do what you want, using <code>setattr</code> to bind the functions and property as attributes of the class object:</p>
<pre><code>def add_getter_setter_property(cls, attrib_name):
escaped_name = "_" + attrib_name
setattr(cls, "get_{}_var".format(attrib_name),
lambda se... | 1 | 2016-06-08T19:49:50Z | [
"python",
"class",
"python-3.x",
"decorator"
] |
Is it possible to modify a class with a decorator | 37,710,747 | <p>I am writing a class in python for some settings wich looks like this:</p>
<pre><code>class _CanvasSettings:
def __init__(self, **kwargs):
super().__init__()
self._size_x = _int(kwargs, 'size_x', 320)
self._size_y = _int(kwargs, 'size_y', 240)
self._lock_ratio = _bool(kwargs'lock... | 1 | 2016-06-08T18:58:11Z | 37,712,980 | <p>As an alternative to automating making properties you could overload <code>__getattr__</code> and <code>__setattr__</code> to detect when a private field is available with an appropriate getter or setter method:</p>
<pre><code>class Field: # so I could test it.
def __init__(self,args,name,default):
self... | 1 | 2016-06-08T21:09:26Z | [
"python",
"class",
"python-3.x",
"decorator"
] |
How can I put a string to an array | 37,710,804 | <p>I want to put a string to an array location but I get an error:</p>
<blockquote>
<p>ValueError: could not convert string to float</p>
</blockquote>
<p>My code is the following:</p>
<pre><code>k = np.ceil(99/8)
rs = np.zeros((int(k), 10))
for i in range(0, int(k)):
rs[i, 0] = "FREQ"
for j in range(1,9)... | 1 | 2016-06-08T19:02:15Z | 37,710,929 | <p>You have an array of floats. You want to put a string value to an element of that array. It is not possible.</p>
| 2 | 2016-06-08T19:09:12Z | [
"python",
"arrays",
"numpy"
] |
How can I put a string to an array | 37,710,804 | <p>I want to put a string to an array location but I get an error:</p>
<blockquote>
<p>ValueError: could not convert string to float</p>
</blockquote>
<p>My code is the following:</p>
<pre><code>k = np.ceil(99/8)
rs = np.zeros((int(k), 10))
for i in range(0, int(k)):
rs[i, 0] = "FREQ"
for j in range(1,9)... | 1 | 2016-06-08T19:02:15Z | 37,711,253 | <p>Your array is implicitly a float array, but you can change the data type to <code>object</code> to be able to include both floats and strings:</p>
<pre><code>rs = np.zeros((int(k), 10), dtype='object')
</code></pre>
<p><strong>But</strong> this is going to rob you of potential optimizations and may cause unexpecte... | 2 | 2016-06-08T19:28:02Z | [
"python",
"arrays",
"numpy"
] |
ImportError: No module named 'resource' | 37,710,848 | <p>I am using python 3.5 and I am doing Algorithms specialization courses on Coursera. Professor teaching this course posted a program which can help us to know the time and memory associated with running a program. It has <code>import resource</code> command at the top. I tried to run this program along with the progr... | 1 | 2016-06-08T19:04:54Z | 37,713,583 | <p><code>resource</code> is a Unix specific package as seen in <a href="https://docs.python.org/2/library/resource.html" rel="nofollow">https://docs.python.org/2/library/resource.html</a> which is why it worked for you in Ubuntu, but raised an error when trying to use it in Windows.</p>
| 1 | 2016-06-08T21:52:01Z | [
"python",
"python-3.x",
"resources"
] |
Unicode handling in python 2 | 37,710,937 | <pre><code>>>> cmd="echo ö"
>>> type(s1)
<str>
>>> print s1
echo ö
>>> chan.exec_command(cmd)
</code></pre>
<p>I am getting a string with some unicode characters from an external application. How should I handle this string in my python code properly? I am getting exception ... | -1 | 2016-06-08T19:10:00Z | 37,712,264 | <p>Use <code>.decode('utf8')</code> to turn it into a unicode type:</p>
<pre><code>>>> cmd="echo ö"
>>> type(cmd)
<type 'str'>
>>> cmd_unicode=cmd.decode('utf8')
>>> type(cmd_unicode)
<type 'unicode'>
</code></pre>
<p>PS: Unicode handling differs between Python 2 and 3... | 0 | 2016-06-08T20:26:36Z | [
"python",
"python-2.7",
"unicode",
"paramiko",
"python-unicode"
] |
Unicode handling in python 2 | 37,710,937 | <pre><code>>>> cmd="echo ö"
>>> type(s1)
<str>
>>> print s1
echo ö
>>> chan.exec_command(cmd)
</code></pre>
<p>I am getting a string with some unicode characters from an external application. How should I handle this string in my python code properly? I am getting exception ... | -1 | 2016-06-08T19:10:00Z | 37,777,101 | <p><code>UnicodeEncodeError</code> while calling <code>.decode()</code> on Python 2 indicates that the input is Unicode and therefore Python tries to <em>encode</em> it first using <code>sys.getdefaultencoding()</code> that should be ASCII on Python 2 before passing it to <code>.decode()</code> method.</p>
<p>Drop <co... | 1 | 2016-06-12T17:28:07Z | [
"python",
"python-2.7",
"unicode",
"paramiko",
"python-unicode"
] |
Python "define__round__method" error | 37,710,950 | <p>Although I've done a little python at school for the past three years, I'm pretty new and inexperienced with it, but would love to learn more. We've been set an assessment to make a mobile phone bill calculator. For one section, we must ask the user how many minutes they have used in a month, and times it by 0.10 to... | 0 | 2016-06-08T19:10:48Z | 37,711,137 | <p>I think you have a typo. You write <code>mins</code>. It should be <code>minsprice</code> in last line.</p>
<pre><code> mins = input("How many minutes have you used this month? ")
minsprice = float(mins)*0.10
print ("You have used",round(minsprice,2),"GBP worth of minutes this month.")
</code></pre>
| 1 | 2016-06-08T19:21:53Z | [
"python"
] |
C# WebClient Strange Characters | 37,710,998 | <p>I am trying to download this webpage using C# WebClient..
Now it works perfectly with python urllib2 but with c# web client it gives these strange characters in the output file.. </p>
<p>I have tried using Encoding with webclient class as well but it doesn't work at all..</p>
<pre><code>public static string GetWe... | -3 | 2016-06-08T19:13:19Z | 38,093,984 | <p>You're looking at a compressed byte stream. You can tell by inspecting the headers of the http response, for example with <a href="https://curl.haxx.se/" rel="nofollow">curl</a>:</p>
<p><code>curl -X HEAD -i http://bet.hkjc.com/</code></p>
<p>but the Developer Console of your browser will reveal the same:</p>
<bl... | 0 | 2016-06-29T08:16:21Z | [
"c#",
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.