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 |
|---|---|---|---|---|---|---|---|---|---|
convert string to other type in python | 39,417,539 | <p>Hi everyone I have a simple problem but I don't find the solution, I have a function that returns something like that</p>
<pre><code>[[4, 'adr', 0, 0, 1, '2016-04-05T13:00:01'], [115, 'adr', 0, 0, 1, '2016-04-05T14:00:01'], [226, 'adr', 0, 0, 1, '2016-04-05T15:00:01'], [337, 'adr', 0, 0, 1, '2016-04-05T16:00:01']]
... | 0 | 2016-09-09T18:17:38Z | 39,417,609 | <p>You might consider to use <a href="https://docs.python.org/2/library/ast.html#ast.literal_eval" rel="nofollow">literal_eval from ast</a> module.</p>
<pre><code>In [8]: from ast import literal_eval
In [9]: a = "[[4, 'adr', 0, 0, 1, '2016-04-05T13:00:01'], [115, 'adr', 0, 0, 1, '2016-04-05T14:00:01'], [226, 'adr', 0... | 2 | 2016-09-09T18:22:26Z | [
"python",
"python-2.7"
] |
convert string to other type in python | 39,417,539 | <p>Hi everyone I have a simple problem but I don't find the solution, I have a function that returns something like that</p>
<pre><code>[[4, 'adr', 0, 0, 1, '2016-04-05T13:00:01'], [115, 'adr', 0, 0, 1, '2016-04-05T14:00:01'], [226, 'adr', 0, 0, 1, '2016-04-05T15:00:01'], [337, 'adr', 0, 0, 1, '2016-04-05T16:00:01']]
... | 0 | 2016-09-09T18:17:38Z | 39,417,648 | <p>You could use <a href="https://docs.python.org/3/library/ast.html#ast.literal%5Feval" rel="nofollow">ast.literal_eval</a>:</p>
<pre><code>import ast
myteststr = "[[4, 'adr', 0, 0, 1, '2016-04-05T13:00:01'], [115, 'adr', 0, 0, 1, '2016-04-05T14:00:01'], [226, 'adr', 0, 0, 1, '2016-04-05T15:00:01'], [337, 'adr', 0, 0... | 1 | 2016-09-09T18:24:51Z | [
"python",
"python-2.7"
] |
convert string to other type in python | 39,417,539 | <p>Hi everyone I have a simple problem but I don't find the solution, I have a function that returns something like that</p>
<pre><code>[[4, 'adr', 0, 0, 1, '2016-04-05T13:00:01'], [115, 'adr', 0, 0, 1, '2016-04-05T14:00:01'], [226, 'adr', 0, 0, 1, '2016-04-05T15:00:01'], [337, 'adr', 0, 0, 1, '2016-04-05T16:00:01']]
... | 0 | 2016-09-09T18:17:38Z | 39,475,738 | <p>Hi everyone I finally resolve the problem like this</p>
<pre><code>data = {}
data = {'names': []}
for item in project_name:
data['names'].append(item)
data.update({item: {}})
jobs_running = []
jobs_pending = []
for row in all_rows:
if (str(item) == row[1]):
parsed_t = dp.parse(str(row[5]))
... | 0 | 2016-09-13T17:23:45Z | [
"python",
"python-2.7"
] |
Python Flask WTForms-Components PhoneNumberField Import error | 39,417,571 | <p>I am trying to use the PhoneNumberField from WTForms-Components offcial docs are here <a href="https://wtforms-components.readthedocs.io/en/latest/#phonenumberfield" rel="nofollow">https://wtforms-components.readthedocs.io/en/latest/#phonenumberfield</a></p>
<p>this is what i am trying `</p>
<pre><code>from wtform... | -1 | 2016-09-09T18:19:58Z | 39,676,032 | <p>It looks as if <code>PhoneNumberField</code> was moved in WTForms-Components 0.10.0 to WTForms-Alchemy 0.15.0. Both packages have the same author. <a href="https://github.com/kvesteri/wtforms-components/issues/39#issuecomment-176649583" rel="nofollow">Here</a> is a GitHub issue that does a better job of explaining w... | 0 | 2016-09-24T11:52:51Z | [
"python",
"flask",
"wtforms",
"flask-wtforms"
] |
Reason and solution of "*** Error in `python': free(): corrupted unsorted chunks: 0x0000000000ff2460 ***" in Python | 39,417,641 | <p>i create a service on Python, who connects to sql Azure using pymssql and only makes a select querys, and after 1 day (or a bit more), the connection begins to fail in querys and finally the service ends with the error <strong>* Error in `python': free(): corrupted unsorted chunks: 0x0000000000ff2460 *</strong>, i d... | 0 | 2016-09-09T18:24:28Z | 39,465,603 | <p>@APRocha, It seems to be not a bug of pymssql, it's an error from glibc when python free some malloc memory. </p>
<p>Did you close the connection after done the sql opertion per request? If not, I suggest you do, or using SQLAlchemy with pymssql to manage the connections in a pool.</p>
<p>Otherwise, I think you ca... | 1 | 2016-09-13T08:37:33Z | [
"python",
"sql",
"azure"
] |
Complex pivot and resample | 39,417,686 | <p>I'm not sure where to start with this so apologies for my lack of an attempt.</p>
<p>This is the initial shape of my data:</p>
<pre><code>df = pd.DataFrame({
'Year-Mth': ['1900-01'
,'1901-02'
,'1903-02'
,'1903-03'
,'1903-04'
,... | 4 | 2016-09-09T18:27:09Z | 39,417,957 | <p>Here's my attempt:</p>
<pre><code>df['Year'] = pd.cut(df['Year-Mth'].str[:4].astype(int),
bins=np.arange(1900, 1920, 5), right=False)
df.pivot_table(index=['SubCategory', 'Year'], columns='Category',
values='counter', aggfunc='sum').dropna(how='all').fillna(0)
Out:
Category ... | 5 | 2016-09-09T18:45:31Z | [
"python",
"pandas"
] |
Complex pivot and resample | 39,417,686 | <p>I'm not sure where to start with this so apologies for my lack of an attempt.</p>
<p>This is the initial shape of my data:</p>
<pre><code>df = pd.DataFrame({
'Year-Mth': ['1900-01'
,'1901-02'
,'1903-02'
,'1903-03'
,'1903-04'
,... | 4 | 2016-09-09T18:27:09Z | 39,418,053 | <pre><code>cols = [df.SubCategory, pd.to_datetime(df['Year-Mth']), df.Category]
df1 = df.set_index(cols).counter
df1.unstack('Year-Mth').T.resample('60M', how='sum').stack(0).swaplevel(0, 1).sort_index().fillna('')
</code></pre>
<p><a href="http://i.stack.imgur.com/7trRO.png" rel="nofollow"><img src="http://i.stack.i... | 3 | 2016-09-09T18:52:40Z | [
"python",
"pandas"
] |
Print SparkSession Config Options | 39,417,743 | <p>When I start pyspark, a SparkSession is automatically generated and available as 'spark'. I would like to print/view the details of the spark session but am having a lot of difficulty accessing these parameters. </p>
<p>Pyspark auto creates a SparkSession. This can be created manually using the following code:</p>
... | 0 | 2016-09-09T18:30:51Z | 39,418,914 | <p>Application name can be accessed using <code>SparkContext</code>:</p>
<pre><code>spark.sparkContext.appName
</code></pre>
<p>Configuration is accessible using <code>RuntimeConfig</code>:</p>
<pre><code>from py4j.protocol import Py4JError
try:
spark.conf.get("some.conf")
except Py4JError as e:
pass
</code>... | 0 | 2016-09-09T19:57:56Z | [
"python",
"apache-spark",
"pyspark"
] |
pyqtSignal() connects bool object instead of str | 39,417,857 | <p>Let's say I have this snippet of code:</p>
<pre><code>from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QDialog
from PyQt5.QtCore import pyqtSignal
from ui_helloworld import Ui_MainWindow
from ui_hellodialog import Ui_Hi
from sys import argv
from sys import... | 0 | 2016-09-09T18:39:30Z | 39,418,398 | <p>I did not need to connect to <code>self.h.update_label</code> directly. I had to connect to the method inside MainWindow called <code>update_label_hello</code> to <code>doIt</code>, and then connect the <code>pyqtSignal</code> to the slot in <code>HelloDialog</code></p>
<p>So, the final result is this:</p>
<p>init... | 0 | 2016-09-09T19:20:33Z | [
"python",
"qt",
"pyqt5"
] |
Issues with Shape inheritance for base classes triangles and squares | 39,417,867 | <p>I keep getting an error. I want the program to display the area of my triangle class. Here is my code:</p>
<pre><code>#Parent class is Shape class
#Child class is Triangle and Square class
class Shape:
def __init__(self,base,height):
self.base=base
self.height=height
def triangle_area(self):
... | 0 | 2016-09-09T18:40:35Z | 39,417,927 | <p>You need to pass base and height in the constructor call like this:</p>
<pre><code>base=9
height=12
triangle_one=Triangle(base, height)
</code></pre>
| 1 | 2016-09-09T18:44:11Z | [
"python",
"inheritance"
] |
Human readable output in bits | 39,417,944 | <p>I have looked at the modules <em>humanize</em> and <em>humanfriendly</em>, and neither can convert a large bit value to human readable bit output (e.g. Mbits, Gbits, Tbits, ..etc). Has anyone come across such a module? Example:</p>
<pre><code>mbits = 1000000
gbits = 1000000000
</code></pre>
<p>Then </p>
<pre... | -3 | 2016-09-09T18:45:04Z | 39,418,077 | <p>You can try <code>hurry.filesize</code></p>
<pre><code>>>> from hurry.filesize import size
>>> size(11000)
'10K'
</code></pre>
<p>There is another library <code>bitmath</code></p>
<pre><code>>>> from bitmath import *
>>> small_number = MiB(10000)
>>> print small_number... | 0 | 2016-09-09T18:54:30Z | [
"python"
] |
Python Selenium is redirecting the URL to Sign up page | 39,417,959 | <p>I have the following code:</p>
<pre><code>> from selenium import webdriver
> browser = webdriver.Chrome(executable_path =
r"C:\Users\ABC\AppData\Local\Programs\Python\Python35-32\Lib\site-packages\selenium\webdriver\common\chromedriver.exe")
> browser.get('http://www.linkedin.com/pub/dir/?first=jatin&... | 0 | 2016-09-09T18:45:35Z | 39,418,131 | <p>Linkedin does not search page without login. First login on linkedin then you can scrape data. </p>
<pre><code>browser.get('https://www.linkedin.com/')
elem = browser.find_element_by_name('session_key')
elem.clear()
elem.send_keys(email_id) # enter your email id or phone number
elem = browser.find_element_by_name(... | 0 | 2016-09-09T18:57:29Z | [
"python",
"session",
"selenium"
] |
Python Selenium is redirecting the URL to Sign up page | 39,417,959 | <p>I have the following code:</p>
<pre><code>> from selenium import webdriver
> browser = webdriver.Chrome(executable_path =
r"C:\Users\ABC\AppData\Local\Programs\Python\Python35-32\Lib\site-packages\selenium\webdriver\common\chromedriver.exe")
> browser.get('http://www.linkedin.com/pub/dir/?first=jatin&... | 0 | 2016-09-09T18:45:35Z | 39,418,145 | <p>Linkedin redirect you to the signup page if you are crawling too fast.</p>
<p>I recommend you to wait a random amount of time between each http request.</p>
<p>Deleting your cookies wouldn't hurt either.</p>
| 0 | 2016-09-09T18:59:10Z | [
"python",
"session",
"selenium"
] |
How to shift list indexes by a certain value in Python | 39,418,008 | <p>I need to create a python function that right shifts values in a list by a given value. </p>
<p>For example if the list is [1,2,3,4] and the shift is 2 it will become [2,3,4,1]. the shift value must be a non negative integer. I can only use the len and range functions. </p>
<p>This is what I have so far</p>
<pre>... | -2 | 2016-09-09T18:48:55Z | 39,418,037 | <p>You could consider a <a href="https://docs.python.org/3/library/collections.html#collections.deque" rel="nofollow"><code>deque</code></a> instead:</p>
<pre><code>>>> from collections import deque
>>> d = deque([1,2,3,4])
>>> d.rotate(-1)
>>> d
deque([2, 3, 4, 1])
</code></pre>
| 0 | 2016-09-09T18:51:25Z | [
"python",
"indexing"
] |
How to shift list indexes by a certain value in Python | 39,418,008 | <p>I need to create a python function that right shifts values in a list by a given value. </p>
<p>For example if the list is [1,2,3,4] and the shift is 2 it will become [2,3,4,1]. the shift value must be a non negative integer. I can only use the len and range functions. </p>
<p>This is what I have so far</p>
<pre>... | -2 | 2016-09-09T18:48:55Z | 39,418,067 | <p>Usually you can do this with slicing</p>
<pre><code>arr = arr[shift:] + arr[:shift]
</code></pre>
<p>Your shifted list is only <code>shift = 1</code>, not 2. You can't get your output by shifting 2 positions.</p>
| 2 | 2016-09-09T18:53:40Z | [
"python",
"indexing"
] |
How to shift list indexes by a certain value in Python | 39,418,008 | <p>I need to create a python function that right shifts values in a list by a given value. </p>
<p>For example if the list is [1,2,3,4] and the shift is 2 it will become [2,3,4,1]. the shift value must be a non negative integer. I can only use the len and range functions. </p>
<p>This is what I have so far</p>
<pre>... | -2 | 2016-09-09T18:48:55Z | 39,430,009 | <p>I make some modifications in your code (If you have to use <code>len</code> and <code>range</code> functions) :</p>
<pre><code>def shift(array, shift_amount):
if shift_amount < 0:
return
ans = []
for i in range(len(array)):
ans.append(array[(i + shift_amount) % len(array)])
print... | 0 | 2016-09-10T19:50:52Z | [
"python",
"indexing"
] |
Unexpected number when reading PLC using pymodbus | 39,418,049 | <p><a href="http://i.stack.imgur.com/rYMVB.png" rel="nofollow"><img src="http://i.stack.imgur.com/rYMVB.png" alt="enter image description here"></a>I am using pymodbus to read a register on a Wago 750-881 PLC. I am also reading the same register on the Modbus Poll utility, as well as, an HMI. The Modbus Poll and HMI ar... | 0 | 2016-09-09T18:52:13Z | 39,419,045 | <p>You may be reading the wrong register, or from the wrong unit ID, or some combination of both.</p>
<p>If you use Wireshark to capture what the 3rd party software and your own software is doing you should be able to spot the difference pretty quickly.</p>
| 0 | 2016-09-09T20:09:24Z | [
"python",
"python-2.7",
"modbus",
"modbus-tcp"
] |
How does Elastic Beanstalk work behind the scenes for Django? | 39,418,059 | <p>For running django applications locally I can do </p>
<pre><code>django-admin startproject djangotest
python djangotest/manage.py runserver
</code></pre>
<p>and the sample webpage shows up at <a href="http://127.0.0.1:8000/" rel="nofollow">http://127.0.0.1:8000/</a></p>
<p>However, when I deploy this to EB with <... | 0 | 2016-09-09T18:53:07Z | 39,419,282 | <p>It doesn't just magically work. You have to configure Django for Elastic Beanstalk, as described in <a href="http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html#python-django-configure-for-eb" rel="nofollow">the EB documentation</a>: you provide a configuration file which points to... | 1 | 2016-09-09T20:30:29Z | [
"python",
"django",
"amazon-web-services",
"amazon-ec2",
"elastic-beanstalk"
] |
how to get field value in django admin form save_model | 39,418,062 | <p>I have the following model:</p>
<pre><code>class Guest(models.Model):
first_name = models.CharField(max_length=128)
last_name = models.CharField(max_length=128)
category = models.ForeignKey(Category)
player_achievement = models.ForeignKey(PlayerAchievement, related_name="guest_achievements")
pla... | 0 | 2016-09-09T18:53:25Z | 39,420,418 | <p>It depends on how you declared your form. If you inherited the <a href="https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/" rel="nofollow">ModelForm</a>, then you should in most cases use <a href="https://docs.djangoproject.com/en/1.10/ref/forms/fields/#django.forms.ModelChoiceField" rel="nofollow">Mode... | 1 | 2016-09-09T22:13:32Z | [
"python",
"django",
"django-models",
"django-forms",
"django-admin"
] |
DataError: (1406, "Data too long for column 'name' at row 1") | 39,418,063 | <p>I've read nearly all other posts with the same error and can't seem to find a proper solution. </p>
<p>In my models.py file I have this:</p>
<pre><code>class LetsSayCups(models.Model):
name = models.CharField(max_length=65535)
def __str__(self):
return str(self.name)
</code></pre>
<p>I get this e... | 0 | 2016-09-09T18:53:37Z | 39,420,389 | <p>You need to use a <code>TextField</code>. The <code>max_length</code> of a <code>CharField</code> should be set to 255 or less to avoid issues with DBs that store it as <code>VARCHAR</code>.</p>
<p><a href="https://docs.djangoproject.com/en/1.10/ref/databases/#character-fields" rel="nofollow">https://docs.djangopro... | 0 | 2016-09-09T22:11:23Z | [
"python",
"mysql",
"django",
"pycharm"
] |
DataError: (1406, "Data too long for column 'name' at row 1") | 39,418,063 | <p>I've read nearly all other posts with the same error and can't seem to find a proper solution. </p>
<p>In my models.py file I have this:</p>
<pre><code>class LetsSayCups(models.Model):
name = models.CharField(max_length=65535)
def __str__(self):
return str(self.name)
</code></pre>
<p>I get this e... | 0 | 2016-09-09T18:53:37Z | 39,451,226 | <p>I found out that my.cfn.bak is only a backup file. I'm not sure how it worked for the first issue, but when I renamed the file to my.cfn my problem was resolved. </p>
| 0 | 2016-09-12T13:15:03Z | [
"python",
"mysql",
"django",
"pycharm"
] |
Plotting a simple 2D vector | 39,418,165 | <p>New to Python and just trying to accomplish what I think must be the simplest of tasks: plotting a basic 2D vector. However my online search has gotten me nowhere so I turn to stackoverflow with my very first question.</p>
<p>I Just want to plot a single 2D vector, let's call it my_vector. my_vector goes from (0,0)... | 0 | 2016-09-09T19:00:24Z | 39,418,224 | <p>You can also unpack your 2D vector</p>
<pre><code>pl.plot(*my_vector)
</code></pre>
<p>Which is effectively just doing</p>
<pre><code>pl.plot(x_cords, y_cords)
</code></pre>
| 0 | 2016-09-09T19:05:22Z | [
"python",
"matplotlib",
"vector"
] |
Django store shell history | 39,418,167 | <p>I lost all my history when I login to shell. Inorder to view the history, I installed ipython and tried to use it.</p>
<p>Now, I get a error when I try this command - </p>
<pre><code>ipython manage.py shell_plus --print-sql
[TerminalIPythonApp] CRITICAL | Bad config encountered during
initialization:
[TerminalI... | 0 | 2016-09-09T19:00:28Z | 39,418,904 | <p>You shouldn't use <code>ipython</code> to start the shell. Just use <code>python manage.py...</code> as normal; Django will use IPython as the shell if it's installed.</p>
| 0 | 2016-09-09T19:57:17Z | [
"python",
"django",
"shell"
] |
Reading repeated information from the file in different order in Python | 39,418,191 | <p>I tried to search for similar questions, but I couldn't find. Please mark as a duplicate if there is similar questions available.</p>
<p>I'm trying to figure out a way to read and gather multiple information from single file. Here in the file Block-A,B & C are repeated in random order and Block-C has more than ... | 0 | 2016-09-09T19:02:17Z | 39,418,305 | <p>Use a dictionary for the datas from each block. When you read the line that starts a block, set a variable to that name, and use it as the key into the dictionary.</p>
<pre><code>out = {}
with open('test.txt', 'r') as f:
for line in f:
if line.endswidth(':'):
blockname = line[:-1]
... | 1 | 2016-09-09T19:12:07Z | [
"python",
"readfile"
] |
Reading repeated information from the file in different order in Python | 39,418,191 | <p>I tried to search for similar questions, but I couldn't find. Please mark as a duplicate if there is similar questions available.</p>
<p>I'm trying to figure out a way to read and gather multiple information from single file. Here in the file Block-A,B & C are repeated in random order and Block-C has more than ... | 0 | 2016-09-09T19:02:17Z | 39,418,547 | <p>If you don't want the Block-X to print, unhash the elif statment</p>
<pre><code>import os
data = r'/home/x/Desktop/test'
txt = open(data, 'r')
for line in txt.readlines():
line = line[:-1]
if line in ('END'):
pass
#elif line.startswith('Block'):
# pass
else:
print line
>&... | 0 | 2016-09-09T19:30:22Z | [
"python",
"readfile"
] |
ImportError: Import by filename is not supported. (WSGI) | 39,418,376 | <p>I don't now why I seem to be getting the following errors from the Apache24 error log: </p>
<pre><code> mod_wsgi (pid=9036): Exception occurred processing WSGI script 'C:/Apache24/htdocs/tools/ixg_dashboard/ixg_dashboard.wsgi'.
Traceback (most recent call last):
File "C:/Apache24/htdocs/tools/ixg_dashboa... | 0 | 2016-09-09T19:18:35Z | 39,419,868 | <p><code>PackageLoader</code> is defined as:</p>
<blockquote>
<p>class jinja2.PackageLoader(package_name, package_path='templates', encoding='utf-8')</p>
</blockquote>
<p>So the first argument should be a package name, not a path.</p>
<p>Check the Jinja2 documentation to better understand what you are supposed to ... | 0 | 2016-09-09T21:20:50Z | [
"python",
"jinja2",
"mod-wsgi"
] |
Histogram with equal number of points in each bin | 39,418,380 | <p>I have a sorted vector <code>points</code> with 100 points. I now want to create two histograms: the first histogram should have 10 bins having equal width. The second should also have 10 histograms, but not necessarily of equal width. In the second, I just want the histogram to have the same number of points in eac... | 3 | 2016-09-09T19:18:56Z | 39,418,480 | <p>provide bins to histogram:</p>
<p><code>bins=points[0::len(points)/10]</code></p>
<p>and then</p>
<p><code>n, bins, patches = plt.hist(points, bins=bins)</code></p>
<p>(provided points is sorted)</p>
| 0 | 2016-09-09T19:26:12Z | [
"python",
"matplotlib",
"histogram"
] |
Histogram with equal number of points in each bin | 39,418,380 | <p>I have a sorted vector <code>points</code> with 100 points. I now want to create two histograms: the first histogram should have 10 bins having equal width. The second should also have 10 histograms, but not necessarily of equal width. In the second, I just want the histogram to have the same number of points in eac... | 3 | 2016-09-09T19:18:56Z | 39,419,049 | <p>This question is <a href="http://stackoverflow.com/questions/37649342/matplotlib-how-to-make-a-histogram-with-bins-of-equal-area/37667480">similar to one</a> that I wrote an answer to a while back, but sufficiently different to warrant it's own question. The solution, it turns out, uses basically the same code from ... | 2 | 2016-09-09T20:10:13Z | [
"python",
"matplotlib",
"histogram"
] |
Histogram with equal number of points in each bin | 39,418,380 | <p>I have a sorted vector <code>points</code> with 100 points. I now want to create two histograms: the first histogram should have 10 bins having equal width. The second should also have 10 histograms, but not necessarily of equal width. In the second, I just want the histogram to have the same number of points in eac... | 3 | 2016-09-09T19:18:56Z | 39,437,454 | <p>Here I wrote an example on how you could get the result. My approach uses the data points to get the bins that will be passed to <code>np.histogram</code> to construct the histogram. Hence the need to sort the data using <code>np.argsort(x)</code>. The number of points per bin can be controlled with <code>npoints</c... | 0 | 2016-09-11T15:05:57Z | [
"python",
"matplotlib",
"histogram"
] |
Proper way to split Python list into list of lists on matching list item delimeter | 39,418,384 | <pre><code>list = ['a', 'b', 'c', '', 'd', 'e', 'f', '', 'g','h','i']
def chunk(list, delim):
ct = list.count(delim)
chunks = [[]] * (ct+1)
for iter in range(ct):
idx = list.index(delim)
chunks[iter] = list[:idx]
list = list[idx+1:]
chunks[ct] = list
return chunks
print chu... | 1 | 2016-09-09T19:19:19Z | 39,418,430 | <p>Here is one way to do it <a href="https://docs.python.org/dev/library/itertools.html#itertools.groupby" rel="nofollow">using <code>itertools.groupby</code></a></p>
<pre><code>[list(v) for k, v in groupby(l, key=lambda x: x!= '') if k]
</code></pre>
<p>Demo:</p>
<pre><code>>>> from itertools import groupb... | 3 | 2016-09-09T19:23:11Z | [
"python"
] |
Proper way to split Python list into list of lists on matching list item delimeter | 39,418,384 | <pre><code>list = ['a', 'b', 'c', '', 'd', 'e', 'f', '', 'g','h','i']
def chunk(list, delim):
ct = list.count(delim)
chunks = [[]] * (ct+1)
for iter in range(ct):
idx = list.index(delim)
chunks[iter] = list[:idx]
list = list[idx+1:]
chunks[ct] = list
return chunks
print chu... | 1 | 2016-09-09T19:19:19Z | 39,418,454 | <p>Focusing on the iterability of lists in Python:</p>
<pre class="lang-py prettyprint-override"><code>list = ['a', 'b', 'c', '', 'd', 'e', 'f', '', 'g','h','i']
def chunk(list, delim):
aggregate_list = []
current_list = []
for item in list:
if item == delim:
aggregate_list.append(current_... | 1 | 2016-09-09T19:24:40Z | [
"python"
] |
Proper way to split Python list into list of lists on matching list item delimeter | 39,418,384 | <pre><code>list = ['a', 'b', 'c', '', 'd', 'e', 'f', '', 'g','h','i']
def chunk(list, delim):
ct = list.count(delim)
chunks = [[]] * (ct+1)
for iter in range(ct):
idx = list.index(delim)
chunks[iter] = list[:idx]
list = list[idx+1:]
chunks[ct] = list
return chunks
print chu... | 1 | 2016-09-09T19:19:19Z | 39,418,561 | <p>A neat one-liner:</p>
<pre><code>L = ['a', 'b', 'c', '', 'd', 'e', 'f', '', 'g','h','i']
new_l = [x.split("_") for x in "_".join(L).split("__")]
</code></pre>
| 1 | 2016-09-09T19:31:31Z | [
"python"
] |
Proper way to split Python list into list of lists on matching list item delimeter | 39,418,384 | <pre><code>list = ['a', 'b', 'c', '', 'd', 'e', 'f', '', 'g','h','i']
def chunk(list, delim):
ct = list.count(delim)
chunks = [[]] * (ct+1)
for iter in range(ct):
idx = list.index(delim)
chunks[iter] = list[:idx]
list = list[idx+1:]
chunks[ct] = list
return chunks
print chu... | 1 | 2016-09-09T19:19:19Z | 39,418,640 | <pre><code>lists = ['a','b','c','','d','e','f','','g','h','i']
new_list = [[]]
delim = ''
for i in range(len(lists)):
if lists[i] == delim:
new_list.append([])
else:
new_list[-1].append(lists[i])
new_list
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
</code></pre>
| -1 | 2016-09-09T19:36:55Z | [
"python"
] |
Python: Auto response to the console output | 39,418,424 | <p>I am running an os command in python script and the command ask do you want to continue after running for sometime and it does that many times while it runs. I want to see if there is a way in python where it answers yes every time it sees its waiting for user confirmation.</p>
<p>Dint find much help.</p>
<p>If so... | 1 | 2016-09-09T19:22:46Z | 39,419,539 | <p>Finally I figured it out.</p>
<pre><code>#!/usr/bin/python
import subprocess
import os
f = open('test', 'r')
for i in f.readlines():
cmd = '/usr/sbin/nsrmm -d -S ' + i
cmd1 = cmd.split( )
print cmd1
p = subprocess.Popen(cmd1, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
... | 0 | 2016-09-09T20:52:43Z | [
"python"
] |
Counting matching substrings in a string | 39,418,432 | <pre><code>s = "abobabobabob"
total = 0
for i in range(len(s)):
if s[i-1 : i+2] == 'bob':
total += 1
print ('times bob occurs is:' + str(total))
</code></pre>
<p>Is there a simpler way to change the <code>if</code> statement? Also, could someone tell me what <code>i-1 : i+2</code> does?</p>
<p>I wrote t... | 0 | 2016-09-09T19:23:16Z | 39,418,619 | <p>The following code searches for the beginning index of each <code>'bob'</code> substring, and adds that value to an array. The <code>total</code> variable just returns the count of the values in that array. </p>
<p><strong>As a one-liner:</strong></p>
<pre><code>total = 0
s = "abobabobabob"
total = len([i for i i... | 1 | 2016-09-09T19:35:18Z | [
"python"
] |
Counting matching substrings in a string | 39,418,432 | <pre><code>s = "abobabobabob"
total = 0
for i in range(len(s)):
if s[i-1 : i+2] == 'bob':
total += 1
print ('times bob occurs is:' + str(total))
</code></pre>
<p>Is there a simpler way to change the <code>if</code> statement? Also, could someone tell me what <code>i-1 : i+2</code> does?</p>
<p>I wrote t... | 0 | 2016-09-09T19:23:16Z | 39,418,705 | <p>if s[i-1 : i+2] == 'bob' is checking whether the current index -1 to current index + 2 is 'bob'. It will cause issue, since i begin at 0 and i-1 is the last element of list<br></p>
<p>try:</p>
<pre><code>s = "abobabobabob"
total = 0
for i in range(1,len(s)):
if s[i-1 : i+2] == 'bob':
total += 1
</code... | 1 | 2016-09-09T19:41:44Z | [
"python"
] |
Counting matching substrings in a string | 39,418,432 | <pre><code>s = "abobabobabob"
total = 0
for i in range(len(s)):
if s[i-1 : i+2] == 'bob':
total += 1
print ('times bob occurs is:' + str(total))
</code></pre>
<p>Is there a simpler way to change the <code>if</code> statement? Also, could someone tell me what <code>i-1 : i+2</code> does?</p>
<p>I wrote t... | 0 | 2016-09-09T19:23:16Z | 39,418,763 | <p>Your if-statement is looking at a subset of s. To sort of answer your other question, here's a simpler approach that changes more than the if-statement:</p>
<p>This is python's regular expression library</p>
<pre><code>import re
</code></pre>
<p>The embedded statement searches for all, non-overlapping instances o... | 2 | 2016-09-09T19:46:04Z | [
"python"
] |
Counting matching substrings in a string | 39,418,432 | <pre><code>s = "abobabobabob"
total = 0
for i in range(len(s)):
if s[i-1 : i+2] == 'bob':
total += 1
print ('times bob occurs is:' + str(total))
</code></pre>
<p>Is there a simpler way to change the <code>if</code> statement? Also, could someone tell me what <code>i-1 : i+2</code> does?</p>
<p>I wrote t... | 0 | 2016-09-09T19:23:16Z | 39,418,927 | <p>Using <code>enumerate()</code></p>
<pre><code>s = "abobabobabob"
n = len([i for i, w in enumerate(s) if s[i:i+3] == "bob"])
print ('times bob occurs is:', n)
</code></pre>
<p>This checks for every character in string <code>s</code>(by index <code>i</code>) if the character + two characters on the right equals "bo... | 1 | 2016-09-09T19:58:24Z | [
"python"
] |
Can't open csv file via command prompt on windows | 39,418,504 | <p>I'm having trouble with the first argument in the pd.read_table function used for Python via Pandas. If I hardcode in the file path of the csv file I want to open and use as a data frame, it works. However, when I receive the file path via a command argument, which saves it into a variable, it won't receive the vari... | -1 | 2016-09-09T19:27:49Z | 39,418,661 | <p>I tried the same and it worked for me(I am using Ubuntu, but that should not matter). I did the following please crosscheck and see</p>
<p>test.py</p>
<pre><code>import sys
import pandas as pd
pd.read_table(sys.argv[1])
</code></pre>
<p>Then called the function like :</p>
<pre><code>test.py /home/user/test.csv
... | 3 | 2016-09-09T19:38:21Z | [
"python",
"windows",
"pandas",
"command-line"
] |
Getting attribute value using ansible filters | 39,418,600 | <p>I am new to ansible. I am trying to get my attribute value from JSON data. Here is my JSON data:</p>
<pre><code>{
"user1": "{\n \"data\":[\n {\n \"secure\": [\n {\n \"key\": \"-----BEGIN KEY-----\nMIIEowIBAAKCAQEAgOh+Afb0oQEnvHifHuzBwhCP3\n-----END KEY-----\"\n }\n ],\n ... | 1 | 2016-09-09T19:34:24Z | 39,423,604 | <p>Would you please check if the key in <code>filepath/myfile.json</code> spans multiple lines? We need to escape line breaks in JSON. Use <code>\n</code> to replace line breaks.</p>
<p>The <code>user1</code> is supported to be a map parsed from JSON. However, the JSON in <code>filepath/myfile.json</code> might be inv... | 0 | 2016-09-10T07:14:33Z | [
"python",
"json",
"ansible",
"ansible-playbook",
"ansible-2.x"
] |
Extracting text from multiple powerpoint files using python | 39,418,620 | <p>I am trying to find a way to look in a folder and search the contents of all of the powerpoint documents within that folder for specific strings, preferably using Python. When those strings are found, I want to report out the text after that string as well as what document it was found in. I would like to compile th... | -1 | 2016-09-09T19:35:27Z | 39,430,554 | <p><code>python-pptx</code> can be used to do what you propose. Just at a high level, you would do something like this (not working code, just and idea of overall approach):</p>
<pre><code>from pptx import Presentation
for pptx_filename in directory:
prs = Presentation(pptx_filename)
for slide in prs.slides:
... | 0 | 2016-09-10T21:04:27Z | [
"python",
"python-2.7",
"powerpoint"
] |
Using HTML to implement Python User Interface | 39,418,639 | <p>I've just started learning a bit of Python and I'm currently trying to implement a Python UI through HTML. Is there anything in vanilla Python that would allow for this, similar to how you can create UI's with Java and XML with JFX or will I have to use a framework such as Django? </p>
<p>I'm reluctant to use Djang... | 0 | 2016-09-09T19:36:54Z | 39,419,544 | <p>In vanilla python <a href="https://docs.python.org/3/library/wsgiref.html" rel="nofollow">wsgiref</a> is very helpful for building the server-side of web-applications (possibly with <a href="https://docs.python.org/3/library/stdtypes.html#str.format" rel="nofollow">str.format</a> or <a href="https://docs.python.org/... | 0 | 2016-09-09T20:53:26Z | [
"python",
"html",
"user-interface"
] |
Regex to find continuous characters in the word and remove the word | 39,418,648 | <p>I want to find whether a particular character is occurring continuously in the a word of the string or find if the word contains only numbers and remove those as well. For example,</p>
<pre><code>df
All aaaaaab the best 8965
US issssss is 123 good
qqqq qwerty 1 poiks
lkjh ggggqwe 1234 aqwe iphone5224s
</code></pre... | 1 | 2016-09-09T19:37:38Z | 39,418,787 | <p>I would suggest</p>
<pre><code>\s*\b(?=[a-zA-Z\d]*([a-zA-Z\d])\1{3}|\d+\b)[a-zA-Z\d]+
</code></pre>
<p>See the <a href="https://regex101.com/r/qA0aS0/1" rel="nofollow">regex demo</a></p>
<p>Only alphanumeric words are matched with this pattern:</p>
<ul>
<li><code>\s*</code> - zero or more whitespaces</li>
<li><c... | 0 | 2016-09-09T19:48:15Z | [
"python",
"regex",
"python-2.7",
"python-3.x"
] |
Regex to find continuous characters in the word and remove the word | 39,418,648 | <p>I want to find whether a particular character is occurring continuously in the a word of the string or find if the word contains only numbers and remove those as well. For example,</p>
<pre><code>df
All aaaaaab the best 8965
US issssss is 123 good
qqqq qwerty 1 poiks
lkjh ggggqwe 1234 aqwe iphone5224s
</code></pre... | 1 | 2016-09-09T19:37:38Z | 39,418,828 | <p>Numbers are easy:</p>
<pre><code>re.sub(r'\d+', '', s)
</code></pre>
<p>If you want to remove words where the same letter appears twice, you can use capturing groups (see <a href="https://docs.python.org/3/library/re.html" rel="nofollow">https://docs.python.org/3/library/re.html</a>):</p>
<pre><code>re.sub(r'\w*(... | 0 | 2016-09-09T19:51:17Z | [
"python",
"regex",
"python-2.7",
"python-3.x"
] |
Bulk insert into Vertica using Python using Uber's vertica-python package | 39,418,808 | <p><strong>Question 1 of 2</strong></p>
<p>I'm trying to import data from CSV file to Vertica using Python, using Uber's vertica-python package. The problem is that whitespace-only data elements are being loaded into Vertica as NULLs; I want only empty data elements to be loaded in as NULLs, and non-empty whitespace d... | 1 | 2016-09-09T19:49:15Z | 39,418,934 | <p>The copy statement you have should perform the way you want with regards to the spaces. I tested it using a very similar <code>COPY</code>. </p>
<p>Edit: I missed what you were really asking with the copy, I'll leave this part in because it might still be useful for some people: </p>
<p>To fix the whitespace, you... | 1 | 2016-09-09T19:59:05Z | [
"python",
"vertica"
] |
How to make a reddit bot invoke a username using PRAW | 39,418,819 | <p>I have been playing with PRAW to build reddit bots. While it is easy to build a bot that auto responds generic messages to triggered keywords, I want to build something that is a bit more interactive.</p>
<p>I am trying to build a reddit bot that invokes the username of the redditor it is replying to. Eg redditor /... | -1 | 2016-09-09T19:50:10Z | 39,419,165 | <p>If you <a href="http://praw.readthedocs.io/en/stable/pages/comment_parsing.html?highlight=author#deleted-comments" rel="nofollow">read the docs</a> you'll see that the comment has an <code>author</code> attribute (unless it was deleted), so you should be able to do:</p>
<pre><code>response_text = 'Good morning to y... | 0 | 2016-09-09T20:20:50Z | [
"python",
"bots",
"reddit",
"praw"
] |
Querying SQLAlchemy User model by password never matches user | 39,418,832 | <p>I want users in my Flask app to be able to change their email by providing a new email and their current password. However, when I try to look up the user by the password they entered with <code>User.query.filter_by(password=form.password.data)</code>, it never finds the user. How can I query the user so I can cha... | 1 | 2016-09-09T19:51:45Z | 39,419,149 | <p>The <em>whole point</em> of storing the hashed password is so that you <em>never</em> store the raw password. Query for the user that you're editing, then verify the password.</p>
<pre><code>@app.route('/<int:id>/change-email', methods=['GET', 'POST'])
def change_email(id):
user = User.query.get_or_404(i... | 4 | 2016-09-09T20:19:53Z | [
"python",
"flask",
"sqlalchemy"
] |
Python 3 import hooks | 39,418,845 | <p>I'm trying to implement an "import hook" in Python 3. The hook is supposed to add an attribute to every class that is imported. (Not really <em>every</em> class, but for the sake of simplifying the question, let's assume so.)</p>
<p>I have a loader defined as follows:</p>
<pre><code>import sys
class ConfigurableI... | 2 | 2016-09-09T19:52:34Z | 39,421,393 | <p>Imho, if you only need to alter the module, that is, play with it after it has been found and loaded, there's no need to actually create a full hook that finds, loads and returns the module; just patch <code>__import__</code>.</p>
<p>This can easily be done in a few lines:</p>
<pre><code>import builtins
from insp... | 1 | 2016-09-10T00:35:32Z | [
"python",
"python-3.x"
] |
Failed execute_child with while running google backend for speech_recognition | 39,418,846 | <p>I have a problem on the execution of the example of Speech Recognition in Python. Atter I have executed the next command line:<strong>python -m speech_recognition</strong>, I got the next result:</p>
<hr>
<pre><code>A moment of silence, please...
ALSA lib pcm.c:2239:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.re... | 0 | 2016-09-09T19:52:45Z | 39,420,370 | <p>You need to install flac:</p>
<blockquote>
<p>FLAC encoder (required only if the system is not x86-based
Windows/Linux/OS X)</p>
</blockquote>
<p>See the documentation <a href="https://github.com/Uberi/speech_recognition#flac-for-some-systems" rel="nofollow">https://github.com/Uberi/speech_recognition#flac-for... | 0 | 2016-09-09T22:09:16Z | [
"python",
"speech-recognition"
] |
Django - how do I clone object without applying clone changes to source object | 39,418,865 | <p>Best described by example:</p>
<p>View:</p>
<pre><code>def my_view(request):
obj_old = Inventories.objects.get(id = source_id)
obj_new = obj_old
obj_old.some_field = 0
obj_old.save()
obj_new.some_field = 1
obj_new.id = None
obj_new.save()
</code></pre>
<p>The problem is that the chan... | 0 | 2016-09-09T19:53:44Z | 39,418,930 | <p>You should make a <em>copy</em> of your object, and not make them equal. </p>
<p>To make a copy you can use the copy module</p>
<pre><code>import copy
obj_new = copy.deepcopy(obj_old)
</code></pre>
| 2 | 2016-09-09T19:58:29Z | [
"python",
"django"
] |
How to recode and count efficiently | 39,418,883 | <p>I have a large csv with three strings per row in this form:</p>
<pre><code>a,c,d
c,a,e
f,g,f
a,c,b
c,a,d
b,f,s
c,a,c
</code></pre>
<p>I read in the first two columns recode the strings to integers and then remove duplicates counting how many copies of each row there were as follows:</p>
<pre><code>import pandas ... | 0 | 2016-09-09T19:55:20Z | 39,418,952 | <p><strong><em>New Answer</em></strong></p>
<pre><code>unq = np.unique(df)
mapping = pd.Series(np.arange(unq.size), unq)
df.stack().map(mapping).unstack() \
.groupby(df.columns.tolist()).size().reset_index(name='count')
</code></pre>
<p><a href="http://i.stack.imgur.com/VSSrX.png" rel="nofollow"><img src="http://i... | 2 | 2016-09-09T20:00:30Z | [
"python",
"pandas"
] |
How to recode and count efficiently | 39,418,883 | <p>I have a large csv with three strings per row in this form:</p>
<pre><code>a,c,d
c,a,e
f,g,f
a,c,b
c,a,d
b,f,s
c,a,c
</code></pre>
<p>I read in the first two columns recode the strings to integers and then remove duplicates counting how many copies of each row there were as follows:</p>
<pre><code>import pandas ... | 0 | 2016-09-09T19:55:20Z | 39,419,342 | <p>I like to use <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html" rel="nofollow"><code>sklearn.preprocessing.LabelEncoder</code></a> to do the letter to digit conversion:</p>
<pre><code>from sklearn.preprocessing import LabelEncoder
# Perform the groupby (before conve... | 3 | 2016-09-09T20:36:30Z | [
"python",
"pandas"
] |
Modify output from series.rolling to 2 decimal points | 39,418,892 | <p>Using the following data:</p>
<pre><code> Open High Low Last Volume
Timestamp
2016-06-10 16:10:00 2088.00 2088.0 2087.75 2087.75 1418
2016-06-10 16:11:00 2088.00 2088.0 2087.75 2088.00 450
2016-06-10 16:12:00 2088.00 2088.0 2087.25 2087.25 2898
</code></pre>
<p... | 1 | 2016-09-09T19:56:23Z | 39,418,996 | <p>you can use pandas' <code>round</code> function</p>
<p><code>data["sma_9_volume"]=data["sma_9_volume"].round(decimals=2)</code></p>
<p>or directly:</p>
<p><code>data["sma_9_volume"] = data.Volume.rolling(window=9,center=False).mean().round(decimals=2)</code></p>
<p><a href="http://pandas.pydata.org/pandas-docs/s... | 2 | 2016-09-09T20:04:18Z | [
"python",
"pandas"
] |
Downloading a list files with python requests on a cert authenticated resource | 39,419,035 | <p>I've been on here all day long looking for a usable answer to this question, but haven't found something that works for my use case.</p>
<p>I am trying to download a bunch of files from a server that checks a client cert for authentication. I also have a list array of specific files I want to download in an automa... | 0 | 2016-09-09T20:08:31Z | 39,419,083 | <p>Ok, here is what I did to fix it:</p>
<p>instead of</p>
<pre><code>r.raw.decode_content = True
shutil.copyfileobj(r.raw, f)
</code></pre>
<p>I chunked it using:</p>
<pre><code>with open(i, "wb") as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
</code></pre>
<p... | 0 | 2016-09-09T20:14:20Z | [
"python",
"ssl",
"python-multithreading",
"downloading"
] |
scipy.misc save image with transparency | 39,419,055 | <p>I am trying to load a image, turn some of the pixels into transparent by setting the alpha param in scipy.misc module, e.g.:</p>
<pre><code>import scipy.misc as sm
im = sm.imread("tmp.png", mode = "RGBA")
im[0, 0, :] = [0,0,0,0]
</code></pre>
<p>When I try to save it:</p>
<pre><code>sm.imsave("out.png", im)
</cod... | 0 | 2016-09-09T20:10:46Z | 39,519,205 | <p>It turns out this works. I just wasn't aware the jpg format does not support transparency, if you save the image in png then things work.</p>
| 0 | 2016-09-15T19:46:49Z | [
"python",
"image-processing",
"scipy"
] |
KeyError: '_OrderedDict__root? | 39,419,098 | <p>Hi I have following code snippet which gives KeyError. I have checked other links specifying <code>make __init__ call to Ordered Dict</code> which I have done. But still no luck.</p>
<pre><code>from collections import OrderedDict
class BaseExcelNode(OrderedDict):
def __init__(self):
super(BaseExcelNode... | 3 | 2016-09-09T20:15:15Z | 39,419,358 | <p><code>OrderedDict</code> is implemented under the assumption that attribute access works by the default mechanisms, and in particular, that attribute access is not equivalent to indexing.</p>
<p>When you subclass it and change how attribute access works, you break one of the deepest assumptions of the <code>Ordered... | 2 | 2016-09-09T20:37:25Z | [
"python",
"ordereddictionary"
] |
KeyError: '_OrderedDict__root? | 39,419,098 | <p>Hi I have following code snippet which gives KeyError. I have checked other links specifying <code>make __init__ call to Ordered Dict</code> which I have done. But still no luck.</p>
<pre><code>from collections import OrderedDict
class BaseExcelNode(OrderedDict):
def __init__(self):
super(BaseExcelNode... | 3 | 2016-09-09T20:15:15Z | 39,419,527 | <p>Using monkey patching method:</p>
<pre><code>from collections import OrderedDict
class BaseExcelNode(OrderedDict):
def __init__(self):
super(BaseExcelNode, self).__init__()
self.start_row = -1
self.end_row = -1
self.col_no = -1
def __getattr__(self, name):
if not na... | 1 | 2016-09-09T20:51:39Z | [
"python",
"ordereddictionary"
] |
How to remove clutter from PyInstaller one-folder build? | 39,419,108 | <p>Alright, so I managed to use PyInstaller to build a homework assignment I made with Pygame. Cool. The executable works fine and everything.</p>
<p>Problem is, alongside the executable, there is so much clutter. So many files, like pyds and dlls accompany the exe in the same directory, making it look so ugly.</p>
<... | 0 | 2016-09-09T20:15:58Z | 39,569,588 | <p>Apparently this is an <a href="https://github.com/pyinstaller/pyinstaller/issues/1048" rel="nofollow">open request for <code>pyinstaller</code></a>, but hasn't happened in the past two years.</p>
<p>My workaround for this one was to create a shortcut one folder higher than the <code>.exe</code> folder with all the ... | 0 | 2016-09-19T09:22:44Z | [
"python",
"build",
"pygame",
"pyinstaller"
] |
assigning variables in a list based on its value in relation to the other values in the list | 39,419,114 | <p>This function takes, as an argument, a positive integer n and generates 3 random numbers between 200 and 625, the smallest random number will be called minValue, the middle random number will be called myTaret, and the largest random number will be called maxValue.</p>
<pre><code>def usingFunctionsGreater(n):
#crea... | 1 | 2016-09-09T20:16:32Z | 39,419,192 | <p>How about the following:</p>
<pre><code>>>> min, target, max = sorted([random.randrange(100, 625, 1) for i in range(3)])
>>> min, target, max
(155, 181, 239)
>>>
</code></pre>
| 4 | 2016-09-09T20:22:46Z | [
"python",
"list",
"random",
"variable-assignment"
] |
I am getting the output for the program but not in the required way? | 39,419,190 | <p>Write a Python function that accepts a string as an input.
The function must return the sum of the digits 0-9 that appear in the string, ignoring all other characters.Return 0 if there are no digits in the string.</p>
<p>my code:</p>
<pre><code>user_string = raw_input("enter the string: ")
new_user_string = list(u... | -1 | 2016-09-09T20:22:43Z | 39,419,246 | <p>This look suspiciously like homework...</p>
<pre><code>getsum = lambda word: sum(int(n) for n in word if n.isdigit())
getsum('aa11b33')
Out[3]: 8
getsum('aa')
Out[4]: 0
</code></pre>
<p>An explanation of how this works piece-by-piece:</p>
<ol>
<li>The function <code>n.isdigit()</code> returns <code>True</code> ... | 4 | 2016-09-09T20:27:17Z | [
"python",
"python-2.7",
"python-3.x",
"ipython"
] |
I am getting the output for the program but not in the required way? | 39,419,190 | <p>Write a Python function that accepts a string as an input.
The function must return the sum of the digits 0-9 that appear in the string, ignoring all other characters.Return 0 if there are no digits in the string.</p>
<p>my code:</p>
<pre><code>user_string = raw_input("enter the string: ")
new_user_string = list(u... | -1 | 2016-09-09T20:22:43Z | 39,419,264 | <p>Python cares about indentations:</p>
<pre><code>user_string = raw_input("enter the string: ")
new_user_string = list(user_string)
addition_list = []
for s in new_user_string:
if ( not s.isdigit()):
combine_string = "".join(new_user_string)
#print ( combine_string)
else:
if ( s.isdigi... | 0 | 2016-09-09T20:28:45Z | [
"python",
"python-2.7",
"python-3.x",
"ipython"
] |
I am getting the output for the program but not in the required way? | 39,419,190 | <p>Write a Python function that accepts a string as an input.
The function must return the sum of the digits 0-9 that appear in the string, ignoring all other characters.Return 0 if there are no digits in the string.</p>
<p>my code:</p>
<pre><code>user_string = raw_input("enter the string: ")
new_user_string = list(u... | -1 | 2016-09-09T20:22:43Z | 39,419,294 | <p>It should be </p>
<pre><code>user_string = raw_input("enter the string: ")
new_user_string = list(user_string)
addition_list = []
for s in new_user_string:
if ( not s.isdigit()):
combine_string = "".join(new_user_string)
else:
if ( s.isdigit()):
addition_list.append(s)
... | 1 | 2016-09-09T20:31:41Z | [
"python",
"python-2.7",
"python-3.x",
"ipython"
] |
launch selenium with python on osx | 39,419,293 | <p>I have the following script</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options
opts = Options()
opts.binary_location = "/Applications/Chrome.app/Contents/MacOS/Google\ Chrome"
browser = webdriver.Chrome(chrome_options=opts)
browser.get('0.0.0.0:3500')
assert 'Djang... | 1 | 2016-09-09T20:31:38Z | 39,419,740 | <p>Try adding the path to your <code>chromedriver</code> binary when you instantiate <code>webdriver.Chrome()</code></p>
<pre><code>browser = webdriver.Chrome('path/to/my/chomedriver', chrome_options=opts)
</code></pre>
<p>The <a href="https://sites.google.com/a/chromium.org/chromedriver/getting-started" rel="nofollo... | 1 | 2016-09-09T21:10:07Z | [
"python",
"osx",
"selenium"
] |
shortest distance from plane to origin using a plane equation | 39,419,343 | <p>suppose i have a plane equation ax+by+cz=d, how can I go about finding the shortest distance from the plane to the origin?</p>
<p>I am going in reverse of this post. In this post, they start out with a point P0 and the normal. In my case, I only have the plane equation
<a href="http://stackoverflow.com/questions/85... | 0 | 2016-09-09T20:36:37Z | 39,473,784 | <p>The normal of your plane is <code>[a,b,c]</code>. Multiply it by <code>d</code> and get the length of the result. This should give you what you need.</p>
| 1 | 2016-09-13T15:27:46Z | [
"python",
"3d",
"plane"
] |
Writing values to excel csv in python | 39,419,363 | <p>I have the below code where I'm trying to write values to an excel file, but my output adds one letter in every single column, instead of the whole word, like so
<a href="http://i.stack.imgur.com/nQsvd.png" rel="nofollow"><img src="http://i.stack.imgur.com/nQsvd.png" alt="enter image description here"></a></p>
<p>... | 0 | 2016-09-09T20:37:40Z | 39,419,489 | <p>You're extracting the text of a single column via:</p>
<blockquote>
<p>for header in headers</p>
</blockquote>
<p>For each single column, you're writing it out like a row of columns via:</p>
<blockquote>
<p>writer.writerows(header_text)</p>
</blockquote>
<p>The <a href="https://docs.python.org/2/library/csv.... | 2 | 2016-09-09T20:48:27Z | [
"python",
"excel",
"csv"
] |
understanding recursive function python | 39,419,369 | <p>I am trying to understand what happens when this recursive function is called. The code is supposed to be a trace </p>
<pre><code>def mysum(lower, upper, margin):
blanks = ' ' * margin
print blanks, lower, upper
if lower > upper:
print blanks, 0
return 0
else:
result = low... | 0 | 2016-09-09T20:38:11Z | 39,419,450 | <p>In brief, you always make a recursive call before you reach a <code>return</code> statement, until you reach the base case. Then, you always reach a <code>return</code> statement before you reach another recursive call (trivially so, since there is only one recursive call).</p>
| 0 | 2016-09-09T20:45:39Z | [
"python",
"recursion"
] |
understanding recursive function python | 39,419,369 | <p>I am trying to understand what happens when this recursive function is called. The code is supposed to be a trace </p>
<pre><code>def mysum(lower, upper, margin):
blanks = ' ' * margin
print blanks, lower, upper
if lower > upper:
print blanks, 0
return 0
else:
result = low... | 0 | 2016-09-09T20:38:11Z | 39,419,491 | <p>When one call of the function returns 0 ("bottoms out"), there might be many other calls to the function on the stack, waiting to proceed. When the recursion bottoms out, control returns to the last-but-one function on the stack. It finishes its work and returns, and control returns to the next earlier function on t... | 0 | 2016-09-09T20:48:34Z | [
"python",
"recursion"
] |
understanding recursive function python | 39,419,369 | <p>I am trying to understand what happens when this recursive function is called. The code is supposed to be a trace </p>
<pre><code>def mysum(lower, upper, margin):
blanks = ' ' * margin
print blanks, lower, upper
if lower > upper:
print blanks, 0
return 0
else:
result = low... | 0 | 2016-09-09T20:38:11Z | 39,419,506 | <p>I think a useful observation here is that the first five lines are printed before any of the nested calls returns. This all happens in the first part of the function body:</p>
<p><code>print</code> - check condition - go to <code>else</code> - and go to beginning again, one level deeper.</p>
<p>When <code>0</code>... | 0 | 2016-09-09T20:50:03Z | [
"python",
"recursion"
] |
understanding recursive function python | 39,419,369 | <p>I am trying to understand what happens when this recursive function is called. The code is supposed to be a trace </p>
<pre><code>def mysum(lower, upper, margin):
blanks = ' ' * margin
print blanks, lower, upper
if lower > upper:
print blanks, 0
return 0
else:
result = low... | 0 | 2016-09-09T20:38:11Z | 39,419,995 | <p>Here is the code with comments helping you to begin to understand how the recursive function works.</p>
<pre><code>def mysum(lower, upper, margin):
blanks = ' ' * margin # First time : margin = 0
# 2nd time : margin = 4
print blanks, lower, upper # first time : lower = 1,... | 0 | 2016-09-09T21:30:46Z | [
"python",
"recursion"
] |
Python - How to remotely execute processes in parallel and retrieve their output | 39,419,398 | <p>I'm trying to remotely execute a command on an unknown number of hosts (could be anywhere from one host to hundreds) in a Python script. The simple way of doing this is the following, but obviously it can get ridiculously time-consuming with many hosts:</p>
<pre><code>listOfOutputs = []
for host in listOfHosts:
o... | 0 | 2016-09-09T20:40:12Z | 39,419,584 | <p>You have to run your <code>Popen.subprocess</code> calls each in a separate thread so you can launch as many as you want without blocking your main program.</p>
<p>I made a small example creating as many threads as there will be hosts. No big deal since threads will mostly wait for host reply (else, thread pools wo... | 0 | 2016-09-09T20:57:06Z | [
"python",
"ssh",
"subprocess",
"popen"
] |
How to get last 3 digits after comma? | 39,419,408 | <p>For a number that is 32,146 ...how do I find only 146? Is this able to be done?</p>
<pre><code>findnum = '32,146'
return findnum
</code></pre>
| -2 | 2016-09-09T20:41:11Z | 39,419,421 | <p>Work with <code>split</code></p>
<pre><code>>>> findnum = '32,146'
>>> findnum.split(',')
['32', '146']
</code></pre>
| 4 | 2016-09-09T20:42:53Z | [
"python",
"regex"
] |
How to get last 3 digits after comma? | 39,419,408 | <p>For a number that is 32,146 ...how do I find only 146? Is this able to be done?</p>
<pre><code>findnum = '32,146'
return findnum
</code></pre>
| -2 | 2016-09-09T20:41:11Z | 39,419,438 | <p>If you want the number you can do:</p>
<pre><code># get number by ignoring commas
number = int(findnum.replace(',',''))
# get last three digits
last_three = number % 1000
</code></pre>
<p>This will result in <code>146</code> (int) and not <code>'146'</code> (string)</p>
<p>Example:</p>
<pre><code>>>> f... | 1 | 2016-09-09T20:44:21Z | [
"python",
"regex"
] |
How to get last 3 digits after comma? | 39,419,408 | <p>For a number that is 32,146 ...how do I find only 146? Is this able to be done?</p>
<pre><code>findnum = '32,146'
return findnum
</code></pre>
| -2 | 2016-09-09T20:41:11Z | 39,419,440 | <p>Since its a string and not a number:</p>
<p>Can use slicing after the ',' to the end:</p>
<pre><code>s[s.index(',')+1:]
</code></pre>
| -1 | 2016-09-09T20:44:36Z | [
"python",
"regex"
] |
Adjacency List Implementation in Python | 39,419,461 | <p>I'm a newbie to Python (and computer science in general), so bear with me.</p>
<p>I'm having trouble implementing an adjacency list in Python. I have learned how to implement it through a dictionary (I learned how through here lol), but I need to know how to do it using only basic lists (list of lists)</p>
<p>This... | 0 | 2016-09-09T20:46:31Z | 39,419,548 | <p>You'll still be thinking in terms of a set of vertices, each with a set of adjacent vertices, but you will be implementing the sets as lists rather than with a more sophisticated <code>set</code> data structure. You will need a fast way to index into the top-level set, and the only way to do that is with integer ind... | 0 | 2016-09-09T20:53:44Z | [
"python",
"adjacency-list"
] |
Running python lines from Atom on Windows | 39,419,463 | <p>I am trying to set up Atom to be my python IDE. I have seen many Mac users be able to pipe a line into a python shell using <code>ctrl + enter</code> command, but I have been unsuccessful in figuring out how to set this up.</p>
<p>I have seen packages like script that execute the entire program but am looking for s... | 0 | 2016-09-09T20:46:42Z | 39,464,538 | <p>Not sure if I get your question right, but there are two packages which might do (part of?) the job you're looking for:</p>
<ul>
<li><a href="https://atom.io/packages/terminal-panel" rel="nofollow">terminal-panel</a></li>
<li><a href="https://atom.io/packages/atom-terminal-panel" rel="nofollow">atom-terminal-panel<... | 0 | 2016-09-13T07:35:01Z | [
"python",
"windows",
"atom-editor"
] |
Python tool to decode a 2d datamatrix barcode using python | 39,419,510 | <p>I have a project which requires me to decode a 2D data matrix barcode from an image using python. </p>
<p>Example (which I believe is a 2d Data Matrix, but hey I could be wrong):</p>
<p><a href="https://imgur.com/a/Xbr1I" rel="nofollow">https://imgur.com/a/Xbr1I</a></p>
<p>I'm having trouble finding tools to do ... | 0 | 2016-09-09T20:50:09Z | 40,102,925 | <p>I think you can use ZXing to decode datamatrix.<br>
Please ref to site: <a href="https://github.com/oostendo/python-zxing" rel="nofollow">https://github.com/oostendo/python-zxing</a> to get more detail. it can support datamatrix as well in my test.</p>
<p>since ZBar is not support DataMatrix in python yet. ZXing is... | 0 | 2016-10-18T08:11:25Z | [
"python",
"opencv",
"barcode-scanner",
"zbar"
] |
Python: Calculating difference of values in a nested list by using a While Loop | 39,419,635 | <p>I have a list that is composed of nested lists, each nested list contains two values - a float value (file creation date), and a string (a name of the file). </p>
<p>For example: </p>
<pre><code>n_List = [[201609070736L, 'GOPR5478.MP4'], [201609070753L, 'GP015478.MP4'],[201609070811L, 'GP025478.MP4']]
</code></pre... | 0 | 2016-09-09T21:00:31Z | 39,419,721 | <p>n_list(len(n_list)) will always return an index out of range error</p>
<pre><code>while count < len(n_List):
</code></pre>
<p>should be enough because you are starting count at 0, not 1.</p>
| 0 | 2016-09-09T21:08:55Z | [
"python",
"list",
"while-loop",
"nested"
] |
Python: Calculating difference of values in a nested list by using a While Loop | 39,419,635 | <p>I have a list that is composed of nested lists, each nested list contains two values - a float value (file creation date), and a string (a name of the file). </p>
<p>For example: </p>
<pre><code>n_List = [[201609070736L, 'GOPR5478.MP4'], [201609070753L, 'GP015478.MP4'],[201609070811L, 'GP025478.MP4']]
</code></pre... | 0 | 2016-09-09T21:00:31Z | 39,419,895 | <p>I think using zip could be easier to get difference. </p>
<pre><code>res1,res2 = [],[]
for i,j in zip(n_List,n_List[1:]):
target = res1 if j[0]-i[0] < 100 else res2
target.append(i[1])
</code></pre>
| 0 | 2016-09-09T21:22:49Z | [
"python",
"list",
"while-loop",
"nested"
] |
Python: Calculating difference of values in a nested list by using a While Loop | 39,419,635 | <p>I have a list that is composed of nested lists, each nested list contains two values - a float value (file creation date), and a string (a name of the file). </p>
<p>For example: </p>
<pre><code>n_List = [[201609070736L, 'GOPR5478.MP4'], [201609070753L, 'GP015478.MP4'],[201609070811L, 'GP025478.MP4']]
</code></pre... | 0 | 2016-09-09T21:00:31Z | 39,514,499 | <p>FYI, here is the solution I used, thanks to @galaxyman for the help.</p>
<p>I handled the issue of the last value in the nested list, by simply
adding that value after the loop completes. Don't know if that's the most
elegant way to do it, but it works. </p>
<p>(note: i'm only posting the function related to the z... | 0 | 2016-09-15T15:06:39Z | [
"python",
"list",
"while-loop",
"nested"
] |
How to return the first highest value that is placed in a dictionary | 39,419,653 | <pre><code>dic = {}
count = 0
i = 0
str_in = str_in.replace(' ','')
while i < len(str_in):
count = str_in.count(str_in[i])
dic[str_in[i]] = count
i += 1
for key in dic:
if key == max(dic, key=dic.get):
return key
break
</code></pre>
<p>The dictionary that is made in this program is</... | 1 | 2016-09-09T21:01:54Z | 39,419,786 | <p>You can use an <code>OrderedDict</code></p>
<p>Just a simple change would resolve your problem </p>
<pre><code>ord_dic = OrderedDict(sorted(dic.items(), key=lambda t: str_in.index(t[0])))
</code></pre>
<p>So you could use something like </p>
<pre><code>dic = {}
count = 0
i = 0
str_in = str_in.replace(' ','')
whi... | 0 | 2016-09-09T21:13:44Z | [
"python",
"string",
"dictionary"
] |
How to return the first highest value that is placed in a dictionary | 39,419,653 | <pre><code>dic = {}
count = 0
i = 0
str_in = str_in.replace(' ','')
while i < len(str_in):
count = str_in.count(str_in[i])
dic[str_in[i]] = count
i += 1
for key in dic:
if key == max(dic, key=dic.get):
return key
break
</code></pre>
<p>The dictionary that is made in this program is</... | 1 | 2016-09-09T21:01:54Z | 39,419,795 | <p>If you don't want to manually count, you could use Python's <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow"><code>Counter</code></a> to count letter occurrences, find the max, then return the first letter in your string that matches that count:</p>
<pre><code>from col... | 1 | 2016-09-09T21:14:45Z | [
"python",
"string",
"dictionary"
] |
How to return the first highest value that is placed in a dictionary | 39,419,653 | <pre><code>dic = {}
count = 0
i = 0
str_in = str_in.replace(' ','')
while i < len(str_in):
count = str_in.count(str_in[i])
dic[str_in[i]] = count
i += 1
for key in dic:
if key == max(dic, key=dic.get):
return key
break
</code></pre>
<p>The dictionary that is made in this program is</... | 1 | 2016-09-09T21:01:54Z | 39,425,017 | <p>Another approach, by using <code>OrderedDict</code> as a mixin class it allows an ordered <code>Counter</code> class to be easily composed. You can then use the first entry of the list returned from the <code>most_common</code> method.</p>
<p>e.g.</p>
<pre><code>from collections import Counter, OrderedDict
class ... | 2 | 2016-09-10T10:13:28Z | [
"python",
"string",
"dictionary"
] |
Python pyspark error | 39,419,712 | <p>I am using Pyspark to create a dataframe but come up against an error from the get go.</p>
<p>I am using the following code to create the dataframe using data from the examples folder:</p>
<pre><code>df = spark.read.load(`c:/spark/examples/src/main/resources/users.parquet`)
</code></pre>
<p>This generates the fol... | 0 | 2016-09-09T21:07:42Z | 39,421,403 | <p>This was an issue with the Spark installation.I installed locally. I created rddâs & everything went fine until I wanted to create a Spark DataFrame from the rdds ... big errors.</p>
<p>The issue was with the pre-built Spark version: spark-2.0.0-bin-hadoop2.7</p>
<p>I Removed spark-2.0.0-bin-hadoop2.7 and do... | 0 | 2016-09-10T00:37:28Z | [
"python",
"pyspark"
] |
Python: C++ extension returning multiple values | 39,419,727 | <p>I am writing a C++ extension for python script and want to return multiple values like what we can do in python function.</p>
<p>Simple Example in python:</p>
<pre><code>def test():
return 0,0
</code></pre>
<p><strong>tuple</strong> seems to be the closest answer</p>
<pre><code>#include <tuple>
std::t... | 1 | 2016-09-09T21:09:17Z | 39,421,899 | <p>It seems you're using boost-python. Then should use boost::python::tuple, not std::tuple. See the examples on <a href="http://www.boost.org/doc/libs/1_61_0/libs/python/doc/html/reference/object_wrappers/boost_python_tuple_hpp.html#object_wrappers.boost_python_tuple_hpp.introduction" rel="nofollow">this page</a>.</p>... | 1 | 2016-09-10T02:21:35Z | [
"python",
"c++",
"python-c-api",
"python-c-extension"
] |
python - to read json file | 39,419,753 | <p>I'm new to JSON and Python, any help on this would be greatly appreciated.
Below is my JSON file format:</p>
<pre><code>{
"header": {
"platform":"atm"
"version":"2.0"
}
"details":[
{
"abc":"3"
"def":"4"
},
{
"abc":"5"
"def"... | -3 | 2016-09-09T21:10:44Z | 39,419,847 | <p>Open the file, and get a filehandle:</p>
<p><a href="https://docs.python.org/2/library/functions.html#open" rel="nofollow">https://docs.python.org/2/library/functions.html#open</a></p>
<p>Then, pass the file handle into json.load():</p>
<p><a href="https://docs.python.org/2/library/json.html#json.load" rel="nofol... | 0 | 2016-09-09T21:19:05Z | [
"python",
"json",
"spark-dataframe"
] |
python - to read json file | 39,419,753 | <p>I'm new to JSON and Python, any help on this would be greatly appreciated.
Below is my JSON file format:</p>
<pre><code>{
"header": {
"platform":"atm"
"version":"2.0"
}
"details":[
{
"abc":"3"
"def":"4"
},
{
"abc":"5"
"def"... | -3 | 2016-09-09T21:10:44Z | 39,419,927 | <p>I'm trying to understand your question as best as I can, but it looks like it was formatted poorly.</p>
<p>First off your json blob is not valid json, it is missing quite a few commas. This is probably what you are looking for:</p>
<pre><code>{
"header": {
"platform": "atm",
"version": "2.0"
... | 1 | 2016-09-09T21:25:57Z | [
"python",
"json",
"spark-dataframe"
] |
Set foreign key to nullable=false? | 39,419,762 | <p>Do you set your foreign keys as nullable=false if always expect a foreign key on that column in the database? </p>
<p>I'm using sqlalchemy and have set my models with required foreign keys. This sometimes causes me to run session.commit() more often, since I need the parent model to have an id and be fully created ... | 0 | 2016-09-09T21:11:36Z | 39,419,880 | <p>You don't need to do <code>session.commit()</code> to get an ID; <code>session.flush()</code> will do.</p>
<p>Even better, you don't need to get an ID at all if you set the relationship because SQLalchemy will figure out the order to do the <code>INSERT</code>s in. You can simply do:</p>
<pre><code>loc = Location(... | 2 | 2016-09-09T21:21:45Z | [
"python",
"sqlalchemy"
] |
Set foreign key to nullable=false? | 39,419,762 | <p>Do you set your foreign keys as nullable=false if always expect a foreign key on that column in the database? </p>
<p>I'm using sqlalchemy and have set my models with required foreign keys. This sometimes causes me to run session.commit() more often, since I need the parent model to have an id and be fully created ... | 0 | 2016-09-09T21:11:36Z | 39,420,590 | <p>I would suggest that you'd better not set nullable=False. Make foreign key nullable is very reasonable in many situations. In your scenario, for example, if I want to insert a hotel whose location is currently underdetermined, you can not accomplish this with the foreign key not null. So the best practice when using... | 0 | 2016-09-09T22:36:31Z | [
"python",
"sqlalchemy"
] |
Broadcasting in Python with permutations | 39,419,823 | <p>I understand that <code>transpose</code> on an <code>ndarray</code> is intended to be the equivalent of matlab's <code>permute</code> function however I have a specific usecase that doesn't work simply. In matlab I have the following:</p>
<pre><code>C = @bsxfun(@times, permute(A,[4,2,5,1,3]), permute(B, [1,6,2,7,3,... | 4 | 2016-09-09T21:16:32Z | 39,420,827 | <p>The huge difference between MATLAB and numpy is that the former uses column-major format for its arrays, while the latter row-major. The corollary is that implicit singleton dimensions are handled differently.</p>
<p>Specifically, MATLAB explicitly ignores trailing singleton dimensions: <code>rand(3,3,1,1,1,1,1)</c... | 6 | 2016-09-09T23:03:11Z | [
"python",
"matlab",
"vectorization",
"broadcasting",
"permute"
] |
Broadcasting in Python with permutations | 39,419,823 | <p>I understand that <code>transpose</code> on an <code>ndarray</code> is intended to be the equivalent of matlab's <code>permute</code> function however I have a specific usecase that doesn't work simply. In matlab I have the following:</p>
<pre><code>C = @bsxfun(@times, permute(A,[4,2,5,1,3]), permute(B, [1,6,2,7,3,... | 4 | 2016-09-09T21:16:32Z | 39,423,815 | <p>Looking at your MATLAB code, you have -</p>
<pre><code>C = bsxfun(@times, permute(A,[4,2,5,1,3]), permute(B, [1,6,2,7,3,4,5])
</code></pre>
<p>So, in essence -</p>
<pre><code>B : 1 , 6 , 2 , 7 , 3 , 4 , 5
A : 4 , 2 , 5 , 1 , 3
</code></pre>
<p>Now, in MATLAB we had to borrow singleton dimensions from higher one... | 2 | 2016-09-10T07:40:14Z | [
"python",
"matlab",
"vectorization",
"broadcasting",
"permute"
] |
Syntax error in print statement | 39,419,846 | <p>This is the end of my script. I'm getting the error : </p>
<pre><code>print "[%s]\t %s " % (item.sharing['access'], item.title)
^
SyntaxError: invalid syntax
</code></pre>
<p>Code:</p>
<pre><code>#List titles and sharing status for items in users'home folder
for item in currentUser.items:
... | -4 | 2016-09-09T21:18:54Z | 39,419,889 | <p>Either you're using Python 3, in which <code>print</code> is a function and thus requires surrounding parentheses (i.e. you have to say <code>print(x)</code> instead of <code>print x</code>), or you have an earlier line of code that wasn't terminated properly.</p>
| 0 | 2016-09-09T21:22:28Z | [
"python"
] |
Obtain documentation for a module implementing the NSGA-II algorithm | 39,419,848 | <p>I am attempting to use the implementation of the NSGA-II algorithm in this module <a href="https://github.com/wreszelewski/nsga2" rel="nofollow">https://github.com/wreszelewski/nsga2</a></p>
<p><strong>Question</strong></p>
<p>Where can I find documentation for this module?</p>
| 0 | 2016-09-09T21:19:20Z | 39,421,438 | <p>The documentation seems to be limited to the examples provided by the author. <a href="https://github.com/wreszelewski/nsga2/tree/master/examples" rel="nofollow">https://github.com/wreszelewski/nsga2/tree/master/examples</a> </p>
<p><strong>Collecting metrics during evolution, then plotting hvr metric per generatio... | 0 | 2016-09-10T00:45:08Z | [
"python",
"module"
] |
Compare a datetime with a datetime range | 39,419,869 | <p>I am fairly new to coding with Python and have so far managed to google my way out of most issues thanks to the great resources available on this site.</p>
<p>I am writing a program which takes multiple .csv files, strips out the data from each of the initial files into different types of log files and writes these... | 1 | 2016-09-09T21:20:53Z | 39,420,022 | <p>You can't compare a <code>datetime</code> representing a specific point in time to a <code>date</code>, which represents a whole day. What time of day should the date represent?</p>
<p><code>ssptime</code> is already a <code>datetime</code> (because that's what <code>strptime</code> returns) - why are you calling <... | 2 | 2016-09-09T21:33:04Z | [
"python",
"csv",
"datetime"
] |
Given a DAG, remove nodes exclusively present in paths shorter than length 3 | 39,419,947 | <p>I'm working with directed acyclic graphs in networkx. I have graphs that look like the figure below.
<a href="http://i.stack.imgur.com/OcdZN.png" rel="nofollow"><img src="http://i.stack.imgur.com/OcdZN.png" alt="enter image description here"></a></p>
<p>What I essentially want to do is remove all the nodes from thi... | 0 | 2016-09-09T21:27:48Z | 39,421,934 | <ol>
<li>generate the height map (a dictionary from node to height)</li>
<li>generate the inverse graph if needed (all edges are reversed)</li>
<li>generate the depth map (which is just the height map of the inverse graph)</li>
<li>nodes = [ n for n in nodes if hmap[n] + dmap[n] >= 3 ]</li>
</ol>
<p>That's O(nodes+edg... | 0 | 2016-09-10T02:27:38Z | [
"python",
"graph",
"graph-algorithm",
"networkx",
"graph-traversal"
] |
How do I concat corresponding values of two Pandas series? | 39,419,965 | <p>I have a PD DF with three columns: lon, lat, and count:</p>
<pre><code>lon lat count
123 456 3
789 012 4
345 678 5
</code></pre>
<p>And I'd like to concat lon and lat to make a fourth column so that the df looks like:</p>
<pre><code>lon lat count text
123 456 3 '123, 456'
789 ... | 1 | 2016-09-09T21:28:48Z | 39,420,004 | <pre><code>df[['lon', 'lat']].astype(str).apply(lambda r: ', '.join(r), axis=1)
</code></pre>
<p>Turn your integers into strings so that you can use them in <code>join</code>, then apply the join function for each row (i.e. across each row cell thus <code>axis=1</code>)</p>
<p>Another way:</p>
<pre><code>df.astype(s... | 2 | 2016-09-09T21:31:20Z | [
"python",
"pandas",
"pyspark",
"concat"
] |
How to copy and convert parquet files to csv | 39,419,975 | <p>I have access to a hdfs file system and can see parquet files with</p>
<pre><code>hadoop fs -ls /user/foo
</code></pre>
<p>How can I copy those parquet files to my local system and convert them to csv so I can use them? The files should be simple text files with a number of fields per row.</p>
| 0 | 2016-09-09T21:29:27Z | 39,428,561 | <p>If there is a table defined over those parquet files in Hive (or if you define such a table yourself), you can run a Hive query on that and save the results into a CSV file. Try something along the lines of:</p>
<pre>
insert overwrite local directory <i>dirname</i>
row format delimited fields terminated by ','
... | 0 | 2016-09-10T17:09:10Z | [
"python",
"hadoop",
"apache-spark",
"pyspark",
"parquet"
] |
How to copy and convert parquet files to csv | 39,419,975 | <p>I have access to a hdfs file system and can see parquet files with</p>
<pre><code>hadoop fs -ls /user/foo
</code></pre>
<p>How can I copy those parquet files to my local system and convert them to csv so I can use them? The files should be simple text files with a number of fields per row.</p>
| 0 | 2016-09-09T21:29:27Z | 39,433,883 | <p>Try</p>
<pre><code>df = spark.read.parquet("infile.parquet")
df.write.csv("outfile.csv")
</code></pre>
<p>Relevant API documentation:</p>
<ul>
<li><a href="http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrameReader.parquet" rel="nofollow">pyspark.sql.DataFrameReader.parquet</a></l... | 1 | 2016-09-11T07:36:56Z | [
"python",
"hadoop",
"apache-spark",
"pyspark",
"parquet"
] |
Error: object of type 'int' has no len() | 39,420,047 | <p>I have a function that is supposed to take an array and sort it from the smallest string size to the largest and then print it by using injection sort.</p>
<p>On the line: <code>while (j >=0) and (len(b[j]) > key):</code></p>
<p>I get this error: </p>
<blockquote>
<p>object of type 'int' has no len()</p>
... | 1 | 2016-09-09T21:35:53Z | 39,420,096 | <p>You can use <code>atleast_1d()</code> or <code>tolist()</code> to make sure that objects will have <code>len()</code> when dealing with a potential mixture of scalars and arrays/lists.</p>
| 1 | 2016-09-09T21:40:59Z | [
"python",
"arrays",
"sorting"
] |
Error: object of type 'int' has no len() | 39,420,047 | <p>I have a function that is supposed to take an array and sort it from the smallest string size to the largest and then print it by using injection sort.</p>
<p>On the line: <code>while (j >=0) and (len(b[j]) > key):</code></p>
<p>I get this error: </p>
<blockquote>
<p>object of type 'int' has no len()</p>
... | 1 | 2016-09-09T21:35:53Z | 39,420,260 | <p>I am not sure how you generated the error to begin with, since the input of <code>["alice", "bob", "sally"]</code> didn't crash, but it does generate numbers. </p>
<p>That's probably because you assign <code>b_list[j+1] = keyValue</code>, where <code>keyValue = len(b_list[i])</code>, which will be an int, and so, i... | 2 | 2016-09-09T21:57:24Z | [
"python",
"arrays",
"sorting"
] |
Error: object of type 'int' has no len() | 39,420,047 | <p>I have a function that is supposed to take an array and sort it from the smallest string size to the largest and then print it by using injection sort.</p>
<p>On the line: <code>while (j >=0) and (len(b[j]) > key):</code></p>
<p>I get this error: </p>
<blockquote>
<p>object of type 'int' has no len()</p>
... | 1 | 2016-09-09T21:35:53Z | 39,420,311 | <p>It sounds like you have a mixed list of integers and strings and want to sort by length of the strings. If that is the case, convert the entire list to like types -- strings -- before sorting. </p>
<p>Given:</p>
<pre><code>>>> li=[1,999,'a','bbbb',0,-3]
</code></pre>
<p>You can do:</p>
<pre><code>>&g... | 1 | 2016-09-09T22:01:56Z | [
"python",
"arrays",
"sorting"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.