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
Sorting Lists containing numbers
37,438,447
<p>I have a series of lists like this that include scores.The first number following the name is student status. 1=Freshman 2=Sophomore 3=Jr.4=Sr</p> <pre><code>Ablao 3 74 96 72 88 71 80 83 77 90 88 95 71 76 94 80 74 98 77 Anderson 3 76 92 98 95 92 76 93 97 85 76 85 93 82 88 75 84 92 77 Aspinwall 1 86 74 78 97 86 94...
1
2016-05-25T13:18:15Z
37,438,788
<pre><code>Ablao 3 74 96 72 88 71 80 83 77 90 88 95 71 76 94 80 74 98 77 Anderson 3 76 92 98 95 92 76 93 97 85 76 85 93 82 88 75 84 92 77 Aspinwall 1 86 74 78 97 86 94 73 95 74 91 75 94 83 99 83 78 88 96 Bacon 4 72 95 81 80 89 88 100 87 87 81 79 77 75 83 87 96 72 95 </code></pre> <p>To read this from a file:</p> <...
0
2016-05-25T13:32:12Z
[ "python", "function", "sorting", "statistics" ]
Sorting Lists containing numbers
37,438,447
<p>I have a series of lists like this that include scores.The first number following the name is student status. 1=Freshman 2=Sophomore 3=Jr.4=Sr</p> <pre><code>Ablao 3 74 96 72 88 71 80 83 77 90 88 95 71 76 94 80 74 98 77 Anderson 3 76 92 98 95 92 76 93 97 85 76 85 93 82 88 75 84 92 77 Aspinwall 1 86 74 78 97 86 94...
1
2016-05-25T13:18:15Z
37,438,814
<p>First I would recommend creating a student class</p> <pre><code>class Student(object): def __init__(self, name, status, *grades): self.name = name self.status = status self.grades = grades @property def student_year(self): return ('Freshman','Sophomore','Junior','Senior')[s...
0
2016-05-25T13:33:02Z
[ "python", "function", "sorting", "statistics" ]
How can I count occurrences of values in a list of dicts?
37,438,550
<p>I have this list of dicts:</p> <pre><code>[{'Description': 'LARCENY'}, {'Description': 'LARCENY'}, {'Description': 'BURGLARY'}, {'Description': 'ROBBERY - STREET'}, {'Description': 'COMMON ASSAULT'}, {'Description': 'COMMON ASSAULT'}, {'Description': 'AUTO THEFT'}, {'Description': 'AUTO THEFT'}, {'Description': 'RO...
1
2016-05-25T13:22:31Z
37,438,709
<p>Given the result you've got so far...</p> <pre><code>&gt;&gt;&gt; result = {'LARCENY' : 3, 'BURGLARY' : 2, 'ROBBERY - STREET' : 3} &gt;&gt;&gt; result = [{k:v} for k,v in result.items()] &gt;&gt;&gt; result [{'BURGLARY': 2}, {'LARCENY': 3}, {'ROBBERY - STREET': 3}] </code></pre>
2
2016-05-25T13:28:47Z
[ "python", "list", "python-2.7", "dictionary" ]
How can I count occurrences of values in a list of dicts?
37,438,550
<p>I have this list of dicts:</p> <pre><code>[{'Description': 'LARCENY'}, {'Description': 'LARCENY'}, {'Description': 'BURGLARY'}, {'Description': 'ROBBERY - STREET'}, {'Description': 'COMMON ASSAULT'}, {'Description': 'COMMON ASSAULT'}, {'Description': 'AUTO THEFT'}, {'Description': 'AUTO THEFT'}, {'Description': 'RO...
1
2016-05-25T13:22:31Z
37,438,722
<p>While your data structure doesn't make sense as noted above, you can solve this easily using the Counter class from collections.</p> <pre><code>from collections import Counter crimes = [{'Description': 'LARCENY'}, {'Description': 'LARCENY'}, {'Description': 'BURGLARY'}, {'Description': 'ROBBERY - STREET'}, {'Descr...
0
2016-05-25T13:29:08Z
[ "python", "list", "python-2.7", "dictionary" ]
How can I count occurrences of values in a list of dicts?
37,438,550
<p>I have this list of dicts:</p> <pre><code>[{'Description': 'LARCENY'}, {'Description': 'LARCENY'}, {'Description': 'BURGLARY'}, {'Description': 'ROBBERY - STREET'}, {'Description': 'COMMON ASSAULT'}, {'Description': 'COMMON ASSAULT'}, {'Description': 'AUTO THEFT'}, {'Description': 'AUTO THEFT'}, {'Description': 'RO...
1
2016-05-25T13:22:31Z
37,438,771
<p>Looks like you want to maintain the order of occurrence of the crimes as well.</p> <p>So, use <a href="https://docs.python.org/3/library/collections.html#collections.OrderedDict" rel="nofollow"><code>collections.OrderedDict</code></a> instead of normal dict.</p> <pre><code>&gt;&gt;&gt; from collections import Orde...
3
2016-05-25T13:31:13Z
[ "python", "list", "python-2.7", "dictionary" ]
pandas condensing multiple columns for same value
37,438,564
<p>I'm trying to integrate multiple data sources and I'm finding it a bit tricky to concisely combine my columns. I have a dataframe that looks something like this:</p> <pre><code>df = pd.DataFrame([['Address Data','City data','State Data', 'Zip Data', np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan], [ ...
2
2016-05-25T13:23:22Z
37,438,712
<p>IIUC you can first select column names by <code>list</code> comprehension and then use <code>pd.lreshape</code>:</p> <pre><code>a = ([col for col in df.columns if col.startswith('Address')]) c = ([col for col in df.columns if col.startswith('City')]) s = ([col for col in df.columns if col.startswith('State')]) z = ...
1
2016-05-25T13:28:50Z
[ "python", "pandas" ]
pandas condensing multiple columns for same value
37,438,564
<p>I'm trying to integrate multiple data sources and I'm finding it a bit tricky to concisely combine my columns. I have a dataframe that looks something like this:</p> <pre><code>df = pd.DataFrame([['Address Data','City data','State Data', 'Zip Data', np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan], [ ...
2
2016-05-25T13:23:22Z
37,442,213
<p>I think solution is totally different, so I decide create new answer:</p> <pre><code>import pandas as pd import numpy as np #random dataframe np.random.seed(1) df1 = pd.DataFrame(np.random.randint(10, size=(3,9))) df1.columns = ['a1','b1','c1','a2','b2','c2','a3','b3','c3'] df1.loc[[1,2],['a1','b1','c1']] = np.na...
1
2016-05-25T15:54:36Z
[ "python", "pandas" ]
pandas condensing multiple columns for same value
37,438,564
<p>I'm trying to integrate multiple data sources and I'm finding it a bit tricky to concisely combine my columns. I have a dataframe that looks something like this:</p> <pre><code>df = pd.DataFrame([['Address Data','City data','State Data', 'Zip Data', np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan], [ ...
2
2016-05-25T13:23:22Z
37,442,787
<p>what about this?</p> <pre><code>uniq_cols = df.columns.str.replace(r'\d+$', '').unique() new = pd.DataFrame(columns=uniq_cols) for col in uniq_cols: new[col] = df.filter(like=col).apply(lambda x: x.dropna()[0], axis=1) </code></pre> <p>Output:</p> <pre><code>In [282]: new Out[282]: Address Cit...
0
2016-05-25T16:21:44Z
[ "python", "pandas" ]
Calculating velocity variables from transaction logs
37,438,567
<p>I have a table with several million transactions. The table contains a timestamp for the transaction, an amount, and several other properties (e.g., address). For each transaction I want to calculate the count and amount sum of transactions that have happened in a timeframe, e.g., 1 month, with the same, e.g., addre...
1
2016-05-25T13:23:31Z
37,461,024
<p>Either I fundamentally misunderstand what you're trying to do, or you do, because your code is <em>vastly</em> more complicated (not complex, <strong>complicated</strong>) than it needs to be if you're doing what you say you're doing.</p> <pre><code>import csv from collections import namedtuple, defaultdict, Counte...
0
2016-05-26T12:35:04Z
[ "python" ]
python - Return a value captured in a function and add it to a csv file
37,438,613
<p>I am currently working on a piece of code and I cant seem to get it working no matter what I try.</p> <p>What I am trying to do is return a value to a function which can then be accessed outside of the function by calling the function in a different section of the code. I want the value to then be passed into an ar...
0
2016-05-25T13:25:14Z
37,439,435
<p>The way the function is defined and arguments are passed,</p> <pre><code>cHandle = 24 data = temp </code></pre> <p>In the line</p> <pre><code>if cHandle == 24 and data[0] == '\x02': </code></pre> <p><code>data[0]</code> is wrong syntax, since <code>data</code> is a float (you mentioned <code>temp</code> to be a ...
0
2016-05-25T13:59:08Z
[ "python", "csv", "bluetooth-lowenergy" ]
Histogram height with Matplotlib and Python
37,438,646
<p>I'm trying to learn Matplotlib and graphing using python and I am trying to learn how to graph a histogram but I don't know how to get the height of the bars. Let's say I want 3 bars at 1,2,3 and height 10,20,30. How can I do this?</p> <pre><code>np.hist((1,2,3)) np.hist(((1,10),(2,20),(3,30))) </code></pre> <p>A...
0
2016-05-25T13:26:32Z
37,439,635
<p>I guess you are trying to use matplotlib.pyplot and you must have used the 'hist' function for your first test. </p> <p>I will just step back to make sure you get what a histogram is. When you plot a histogram of your vector, you plot the estimate of the density probability function. If you give your vector (1, 2, ...
3
2016-05-25T14:07:30Z
[ "python", "matplotlib" ]
Histogram height with Matplotlib and Python
37,438,646
<p>I'm trying to learn Matplotlib and graphing using python and I am trying to learn how to graph a histogram but I don't know how to get the height of the bars. Let's say I want 3 bars at 1,2,3 and height 10,20,30. How can I do this?</p> <pre><code>np.hist((1,2,3)) np.hist(((1,10),(2,20),(3,30))) </code></pre> <p>A...
0
2016-05-25T13:26:32Z
37,445,832
<p>I assume you mean the <code>numpy.histogram()</code> function, which is designed to do the work for you to take a distribution of real-valued numbers and produce frequency bins from that. You are giving the function a list containing three values, so the frequencies for those values are all 1--that is, there is a s...
0
2016-05-25T19:17:13Z
[ "python", "matplotlib" ]
Timing how long it takes for subprocess to complete
37,438,688
<p>I currently have a method that executes other python scripts by using subprocess calls, I was wondering if there was anyway I could time how long it takes for this to complete? The scripts are running in an interval, what I want to achieve from this is to check whether the scripts finish within that interval.</p> ...
3
2016-05-25T13:28:09Z
37,439,298
<p>Do you need the program to keep running while the scripts are executing? If not, you can block your program execution until the process finishes and report the time it took:</p> <pre><code>def execute_scripts(script_name): time_start = time.time() print "starting process" process = sp.call(['python2.7',...
0
2016-05-25T13:53:27Z
[ "python", "python-2.7", "subprocess" ]
Timing how long it takes for subprocess to complete
37,438,688
<p>I currently have a method that executes other python scripts by using subprocess calls, I was wondering if there was anyway I could time how long it takes for this to complete? The scripts are running in an interval, what I want to achieve from this is to check whether the scripts finish within that interval.</p> ...
3
2016-05-25T13:28:09Z
37,439,987
<p>Use <a href="https://docs.python.org/2/library/timeit.html" rel="nofollow">timeit</a> to time the execution of small bits of code. </p> <pre><code>#sleep2.py import time time.sleep(2) </code></pre> <p>You need to use <a href="https://docs.python.org/2/library/subprocess.html#module-subprocess" rel="nofollow">subpr...
1
2016-05-25T14:21:47Z
[ "python", "python-2.7", "subprocess" ]
Getting info from exception without sys.exc_info
37,438,716
<p>I am trying to get more information out of an exception object, <code>err</code>, beyond its error message. In my code I sometimes capture exceptions deep in some subfunction. Back at the top level I want to print info about where the exception occurred etc.</p> <p>I have seen similar questions where the answers in...
2
2016-05-25T13:28:53Z
37,444,553
<p>Use the <a href="https://docs.python.org/3/library/traceback.html" rel="nofollow"><code>traceback</code></a> module:</p> <pre><code>&gt;&gt;&gt; import traceback &gt;&gt;&gt; try: ... raise Exception() ... except Exception as e: ... print(traceback.extract_tb(e.__traceback__)) ... [('&lt;stdin&gt;', 2, '&lt;modu...
1
2016-05-25T18:01:50Z
[ "python", "exception" ]
Celery PeriodicTask per user
37,438,867
<p>I'm working on project which main future will be running periodically one type of async task for each user. Every user will be able to configure task (running daily, weekly etc. at specified time). Also task will use some data stored by user. Now I'm wondering which approach should be better: allow users to create o...
2
2016-05-25T13:34:56Z
37,637,827
<p>periodic tasks scheduler in celery is not designed to handle thousands of scheduled tasks, so from performance perspective, much better solution is to have one task that is running at the smallest interval (e.g. if you allow user to sechedule dayly, weekly, monthly - running task daily is enough)</p> <p>such approa...
1
2016-06-05T02:18:50Z
[ "python", "django", "celery" ]
Not able to install Python 2.7.9 on Windows Vista machine
37,438,895
<p>I am not able to install Python 2.7.9 on Windows Vista machine &amp; getting below error.</p> <p>There is a problem with Windows installer package. A program required for this install to complete could not be run. Contact your support personnel or package vendor.</p> <p>Can you please help me resolving this issue ...
0
2016-05-25T13:36:23Z
37,439,261
<p>You can open start menu (tap on e.g windows key) and type the name of the program you're looking for, so in this case 'python'. If you have that program already on your computer, it will show.</p>
0
2016-05-25T13:51:40Z
[ "python", "windows", "installation", "windows-vista" ]
How can I eliminate a book's connection made with Workbook.caller()
37,438,943
<p>I have a python script for open a workbook. I need use this script many times but I receive a message error like this:</p> <blockquote> <p>C:\Anaconda3\lib\site-packages\xlwings_xlwindows.py:159: UserWarning: This Work book is open in multiple instances.The connection was made with the one that was last active. w...
0
2016-05-25T13:38:25Z
37,442,313
<p>My guess is that you're just seeing a bug that sneaked in with Excel >= 2013 since that is when they started to open a new window for each workbook even if you're working with just a single instance of Excel. See <a href="https://github.com/ZoomerAnalytics/xlwings/issues/454" rel="nofollow">here</a>. This warning sh...
0
2016-05-25T15:59:44Z
[ "python", "excel", "python-3.x", "xlwings" ]
OpenERP Function python
37,438,999
<p>I want to do on the writing process. I have created e new field in the tree view '<strong>' Total Caisse'</strong>'. I want to show the same total existing <strong>' Montant'</strong> , but if journal id <strong>''Journal des achats "</strong> Total negative shows</p> <p>For example</p> <ul> <li>if Montant = 500...
0
2016-05-25T13:40:50Z
37,454,027
<p>Your query is still unclear for us.</p> <p>Regrading:<strong>if journal id ''Journal des achats " Total negative shows</strong></p> <p>Correct your query by replacing <code>SELECT journal_id,SUM(debit) *-1 '</code> with <code>SELECT journal_id,SUM(debit)'</code> Like:</p> <pre><code> cr.execute( 'SELECT journal_...
1
2016-05-26T07:18:01Z
[ "python", "openerp" ]
Tricky list processing in Django app
37,439,051
<p>In a Django app of mine, users upload photos and others upvote or downvote them.</p> <p>I have a list of 100 user ids that have the best aggregate photo score. For each id in this list, I want to find out the total count of photos the id has posted. I'm currently doing this in a for loop, that makes me do 100 DB ca...
1
2016-05-25T13:43:23Z
37,439,678
<p>You can do the count from your <code>User</code> model instead (the code is more intuitive) using <code>annotate</code> with <code>in_bulk</code> </p> <pre><code> from django.db.models import Count user_ids = [user.id for user in context["object_list"]]: users = User.objects.annotate(photo_count=Count('photo',...
1
2016-05-25T14:09:07Z
[ "python", "django", "django-models", "django-views" ]
Tricky list processing in Django app
37,439,051
<p>In a Django app of mine, users upload photos and others upvote or downvote them.</p> <p>I have a list of 100 user ids that have the best aggregate photo score. For each id in this list, I want to find out the total count of photos the id has posted. I'm currently doing this in a for loop, that makes me do 100 DB ca...
1
2016-05-25T13:43:23Z
37,440,050
<p>You can do this with <code>annotate</code> with <code>values_list()</code></p> <p>As you expect the output is list of tuples with user_id and their photos uploaded count</p> <pre><code>from django.db.models import Count user_ids = [user.id for user in context["object_list"]] user_photos = Photo.objects.filter(ow...
0
2016-05-25T14:24:21Z
[ "python", "django", "django-models", "django-views" ]
Timeout while Loop If No Input
37,439,156
<p>I have a piece of code that does exactly what I need, barring one thing, a timeout.</p> <p>Basically, this code will log an entry every 0,5s for 3 seconds and then print "Done" and then restart. The sound I am trying to log is constant for about 3,1s, so that's perfect. Every time the sound is present it will print...
0
2016-05-25T13:47:29Z
37,439,637
<p>You want a long sound to be one signal. You want no sound to be no signal, and a short sound to be no signal.</p> <pre><code>sound_present_for_samples = 0 logging_threshold = 6 # 6 half seconds while True: if GPIO.input(pin) == GPIO.LOW: sound_present_for_samples += 1 if sound_present_for_sampl...
0
2016-05-25T14:07:32Z
[ "python", "python-3.x" ]
Plotting a wrapped path in Basemap
37,439,186
<p>I am trying to plot a satellite ground track. I have a list of latitudes and longitudes in degrees. The longitude values are all from -180 to +180 deg. My first issue is with using the <code>latlon</code> keyword (by the way, I'm using this in Julia via the <code>PyCall.jl</code> package, so forgive the weird-lookin...
2
2016-05-25T13:48:31Z
37,592,433
<p>At the beginning I thought this could be related to an <a href="https://github.com/matplotlib/basemap/issues/54" rel="nofollow">old issue</a> of <code>Basemap</code>. However, I think your problem is not due to <code>Basemap</code>, which is actually handling correctly the longitude wrapping, as you could see if you...
5
2016-06-02T12:52:06Z
[ "python", "plot", "maps", "matplotlib-basemap" ]
SQLAlchemy: How to select max from several tables
37,439,219
<p>I am starting to use sqlalchemy in an ORM way rather than in an SQL way. I have been through the doc quickly but I don't find how to easily do the equivalent of SQL:</p> <pre><code>select max(Table1.Date) from Table1, Table2 where... </code></pre> <p>I can do:</p> <pre><code>session.query(Table1, Table2) ... orde...
1
2016-05-25T13:49:45Z
37,448,230
<p>Ideally one would know the other parts of the query. But without any additional information, below should do it</p> <pre><code>import sqlalchemy as sa q = ( session .query(sa.func.max(Table1.date)) .select_from(Table1, Table2) # or any other `.join(Table2)` would do .filter(...) .order_by(Tabl...
1
2016-05-25T21:50:52Z
[ "python", "sqlalchemy" ]
Implementing Pollard's Rho Algorithm for Discrete Logarithms
37,439,263
<p>I am trying to implement Pollard's rho algorithm for computing discrete logarithms based on the description in the book <a href="http://thales.doa.fmph.uniba.sk/macaj/skola/teoriapoli/primes.pdf" rel="nofollow"><em>Prime Numbers: A Computational Perspective</em></a> by Richard Crandall and Carl Pomerance, section 5....
1
2016-05-25T13:51:44Z
37,440,171
<h2>Problem 1</h2> <p>One thing that looks suspicious is this function:</p> <pre><code>def inverse(x, p): return pow(x, p-2, p) </code></pre> <p>This is computing a modular inverse of x modulo p using <a href="https://en.wikipedia.org/wiki/Modular_multiplicative_inverse#Using_Euler.27s_theorem" rel="nofollow">Euler'...
3
2016-05-25T14:29:05Z
[ "python", "algorithm", "cryptography" ]
Python: Using Regex to create an array of non-duplicate entries
37,439,303
<p>I am writing a function to find the names of processes occurring on a system. I take in an array like this:</p> <pre><code>['\\\\TEST-PC\\Process(python)\\Operations/sec', '\\\\TEST-PC\\Process(process#2)\\Operations/sec', '\\\\TEST-PC\\Process(process#1)\\Operations/sec', '\\\\TEST-PC\\Process(process)\\Operatio...
1
2016-05-25T13:53:35Z
37,439,669
<p>Reminder that <a href="https://docs.python.org/2/library/re.html#re.search" rel="nofollow"><code>re.search()</code></a> returns a MatchObject; in order to extract what you want, you would want to use something like <code>match.group(1)</code> which would return the first group of the match, in other words, the token...
1
2016-05-25T14:08:33Z
[ "python", "arrays", "regex" ]
Python: Using Regex to create an array of non-duplicate entries
37,439,303
<p>I am writing a function to find the names of processes occurring on a system. I take in an array like this:</p> <pre><code>['\\\\TEST-PC\\Process(python)\\Operations/sec', '\\\\TEST-PC\\Process(process#2)\\Operations/sec', '\\\\TEST-PC\\Process(process#1)\\Operations/sec', '\\\\TEST-PC\\Process(process)\\Operatio...
1
2016-05-25T13:53:35Z
37,439,767
<p>You could come up with:</p> <pre><code>import re processes = ['\\\\TEST-PC\\Process(python)\\Operations/sec', '\\\\TEST-PC\\Process(process#2)\\Operations/sec', '\\\\TEST-PC\\Process(process#1)\\Operations/sec', '\\\\TEST-PC\\Process(process)\\Operations/sec', '\\\\TEST-PC\\Process(python)\\Thread Count', '\\\...
1
2016-05-25T14:12:35Z
[ "python", "arrays", "regex" ]
Python: Using Regex to create an array of non-duplicate entries
37,439,303
<p>I am writing a function to find the names of processes occurring on a system. I take in an array like this:</p> <pre><code>['\\\\TEST-PC\\Process(python)\\Operations/sec', '\\\\TEST-PC\\Process(process#2)\\Operations/sec', '\\\\TEST-PC\\Process(process#1)\\Operations/sec', '\\\\TEST-PC\\Process(process)\\Operatio...
1
2016-05-25T13:53:35Z
37,440,225
<p>If order does not matter, you can do:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; tgt=['\\\\TEST-PC\\Process(python)\\Operations/sec', ... '\\\\TEST-PC\\Process(process#2)\\Operations/sec', ... '\\\\TEST-PC\\Process(process#1)\\Operations/sec', ... '\\\\TEST-PC\\Process(process)\\Operations/sec', ... '\\\...
0
2016-05-25T14:30:51Z
[ "python", "arrays", "regex" ]
Calling a function within a function [Python]
37,439,330
<p>The instructions that I've been given tells me create 2 functions: first one (helloWorld) just has to print a basic string but the second one (helloWorldNTimes) has to call the first one 'n' amount of times. This is what I have so far - I either don't understand the question completely or misinterpreting it.</p> <p...
0
2016-05-25T13:54:29Z
37,439,689
<p>You have to study loops in programming language. Especially for loop. </p> <p>You have to call function inside a loop. It can be either while or for loop. Then only it can be called n number of times.</p> <p>Example :</p> <pre><code>def helloWorld(): print ("Hello, World!") for x in range(7): helloWorld(...
0
2016-05-25T14:09:21Z
[ "python", "python-3.x" ]
Plone: python script index_html related to a non folder object
37,439,380
<p>I've created a folder in a plone site (4.3.x) and I know it's possible define a python script (default method) <strong>index_html</strong> that runs on its request:</p> <blockquote> <p>[plone site]/[folder] --> request --> run index_html default method</p> </blockquote> <p>The question now: Is there any resource...
2
2016-05-25T13:56:24Z
37,498,104
<p>You can put the Python Script as default view of the content.</p> <p>Go to <code>/folder/page/manage_propertiesForm</code> and set a <code>layout</code> string property with value <code>page_html</code>.</p> <p><strong>Please note</strong>: this is the old way of doing stuff on Plone. It won't work on Dexterity ba...
4
2016-05-28T10:51:52Z
[ "python", "plone", "zope", "plone-4.x" ]
pandas: unexpected join behavior results in NaN
37,439,542
<p>I have two dataframes that I'm trying to join in pandas (version 0.18.1).</p> <pre><code>test1 = pd.DataFrame({'id': range(1,6), 'place': ['Kent','Lenawee','Washtenaw','Berrien','Ottawa']}) id_1 place 0 1 Kent 1 2 Lenawee 2 3 Montreal 3 4 Berrien 4 5 Ottawa test2 = pd.DataFrame...
1
2016-05-25T14:03:20Z
37,439,780
<p><a href="http://pandas.pydata.org/pandas-docs/stable/merging.html#joining-key-columns-on-an-index" rel="nofollow"><code>join</code></a> joins primarily on indices, use <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html#database-style-dataframe-joining-merging" rel="nofollow"><code>merge</code></a> for...
3
2016-05-25T14:12:54Z
[ "python", "pandas" ]
pandas: unexpected join behavior results in NaN
37,439,542
<p>I have two dataframes that I'm trying to join in pandas (version 0.18.1).</p> <pre><code>test1 = pd.DataFrame({'id': range(1,6), 'place': ['Kent','Lenawee','Washtenaw','Berrien','Ottawa']}) id_1 place 0 1 Kent 1 2 Lenawee 2 3 Montreal 3 4 Berrien 4 5 Ottawa test2 = pd.DataFrame...
1
2016-05-25T14:03:20Z
37,439,815
<p>Here I quote the documentation of pandas : 'join takes an optional on argument which may be a column or multiple column names, which specifies that the passed DataFrame is to be aligned on that column in the DataFrame. "</p> <p>So in your case, you are matching the index of test2 on id_parent from test1.</p>
1
2016-05-25T14:14:23Z
[ "python", "pandas" ]
How to correct one unicode string like "\u8bf8\u845b\u4eae" in python?
37,439,567
<p>I don't know how they printed strings like "\u8bf8\u845b\u4eae" to the log files. But now i need to get the correct string from it, it is "诸葛亮" in chinese. I have tried many ways, but failed.</p> <pre><code>In [56]: print u"\u8bf8\u845b\u4eae" 诸葛亮 In [57]: print "\u8bf8\u845b\u4eae" \u8bf8\u845b\u4eae...
1
2016-05-25T14:04:19Z
37,439,693
<p>You have to use: <code>unicode-escape</code></p> <pre><code>print '\\u8bf8\\u845b\\u4eae'.encode('ascii').decode('unicode-escape') </code></pre> <p>also see: <a href="http://stackoverflow.com/questions/19371953/converting-unicode-string-to-chinese-characters">Converting Unicode string to Chinese characters</a></p>...
2
2016-05-25T14:09:29Z
[ "python", "python-2.7", "unicode" ]
Which bytes should i pass to Capstone to disassemble the executable code of a PE file
37,439,627
<p>Im trying to disassemble a PE executable with python using pefile and capstone to later obtain the CFG from that code. My idea is to take the portion of PE file that holds the executable code and pass all those bytes to capstone. What i don't know is exactly which portion should i pass to capstone so no more code th...
0
2016-05-25T14:07:00Z
37,495,768
<p>You don't need to pass a parameter to get_data.</p> <p>This should work fine</p> <pre><code>import pefile from capstone import * def disassemble(file_path): pe = pefile.PE(file_path) eop = pe.OPTIONAL_HEADER.AddressOfEntryPoint code_section = pe.get_section_by_rva(eop) code_dump = code_section.g...
0
2016-05-28T06:02:09Z
[ "python", "pe", "disassembly", "capstone" ]
Python chatbot - TypeError: list indices must be integers, not str
37,439,633
<p>I've created a simple chatbot using Python, but when I try to use it, it gives me an error: <code>TypeError: list indices must be integers, not str</code>.</p> <p>I'll get into the error later, but first I'll explain what the bot should do. The bot has a database, represented by a dictionary, in which all of the us...
0
2016-05-25T14:07:22Z
37,439,790
<p><code>self.database</code> is a list. List items are accessed by specifying their position within the list, for example <code>self.database[0]</code> for the first item and <code>self.database[4]</code> for the fifth item.</p> <p>You're trying to use <code>text</code> as a list position, which makes no sense.</p> ...
1
2016-05-25T14:13:10Z
[ "python", "dictionary", "chatbot" ]
Python chatbot - TypeError: list indices must be integers, not str
37,439,633
<p>I've created a simple chatbot using Python, but when I try to use it, it gives me an error: <code>TypeError: list indices must be integers, not str</code>.</p> <p>I'll get into the error later, but first I'll explain what the bot should do. The bot has a database, represented by a dictionary, in which all of the us...
0
2016-05-25T14:07:22Z
37,439,886
<p>You mention the database is a dictionary, yet you're creating a list</p> <pre><code>self.database = [] </code></pre> <p>A <code>dict</code> is created by curly braces</p> <pre><code>self.database = {} </code></pre>
0
2016-05-25T14:17:21Z
[ "python", "dictionary", "chatbot" ]
Importing from sibling directories (python 3)
37,439,691
<p>I can't figure out how to import modules from sibling directories in Python 3 using absolute imports.</p> <ol> <li>modify the <code>sys.path</code>.</li> <li>turn the directory into a pip installable package via <code>__init__.py</code> and <code>setup.py</code>.</li> </ol> <p>For option 1. I figured out how to im...
0
2016-05-25T14:09:28Z
37,441,290
<blockquote> <p>From what I've read, Python 3 does not support relative imports</p> </blockquote> <p>It does.</p> <p>To import <code>myproject/foo/__init__.py</code> from <code>myproject/bar/baz.py</code>, you can use this:</p> <pre><code>from .. import foo </code></pre> <p>Or if you want to import an object/modu...
0
2016-05-25T15:15:35Z
[ "python", "python-3.x", "packages", "python-import", "setup.py" ]
Python Multiprocessing: How do I keep it within the specified function?
37,439,704
<p>I've been a long-term observer of Stack Overflow but this time I just can't find a solution to my problem, so here I am asking you directly!</p> <p>Consider this code:</p> <pre><code>from multiprocessing import Pool def f(x): return x*x if __name__ == '__main__': p = Pool(5) print(p.map(f, [1, 2, 3])...
1
2016-05-25T14:09:50Z
37,440,354
<p>Since the <code>print</code> instruction is not indented, it is executed each time the python file is imported. Which is, every time a new process is created.</p> <p>On the opposite, all the code placed beneath <code>if __name__ == '__main__</code> will not be executed each time a process is created, but only from ...
1
2016-05-25T14:36:17Z
[ "python", "multithreading", "multiprocessing", "execution" ]
Convert only one item with dictionary comprehension
37,439,734
<p>Cheers,</p> <p>I'm currently working on a piece of code and and I'm trying to find the best, more pythonic and CPU low cost solution for my problem.</p> <p>I actually have a array of "index value" which I read through a file, an example is:</p> <pre><code>&gt;&gt;&gt; list = ['index_1 200', 'index_2 500',...
1
2016-05-25T14:10:59Z
37,439,860
<p>You can avoid splitting each string twice, and you can make use of a dictionary comprehension like this:</p> <pre><code>&gt;&gt;&gt; mylist = ['index_1 200', 'index_2 500', 'index_3 50'] &gt;&gt;&gt; mydict = {k:int(v) for (k,v) in (line.split() for line in mylist)} &gt;&gt;&gt; mydict {'index_2': 500, 'in...
8
2016-05-25T14:16:04Z
[ "python", "dictionary" ]
SONY Lifelog Api: SSL Handshake failure
37,439,759
<p>I get an SSL handshake failure while trying to reach <code>platform.lifelog.sonymobile.com:443</code> with either python (with <code>requests</code> library) or <code>openssl</code>.</p> <p>Here are the output I get from <strong>openssl</strong></p> <p><strong>ssl3</strong>:</p> <pre><code>$ &gt;openssl s_client ...
0
2016-05-25T14:12:17Z
38,881,583
<p>I'm using <code>google-oauth-java-client</code> from <a href="https://github.com/google/google-oauth-java-client" rel="nofollow">https://github.com/google/google-oauth-java-client</a> to get data regularly from lifelog API. No special care was needed for certificates. Previous to Android client, I tested all my logi...
0
2016-08-10T19:03:03Z
[ "python", "ssl", "sony", "sony-lifelog-api" ]
How to skip items in a loop
37,439,787
<p>I am trying to create a list with all the newspapers articles from 5 different sources. They are stored in <code>JSON</code> format. All articles are stored in different files that contain that contain the newspaper and the year (time spam 2005-2015). The problem is that one of the newspapers is available for only 2...
1
2016-05-25T14:13:04Z
37,440,246
<p>For the skipping part, you can:</p> <pre><code>for i in range(2005,2016): if i &gt; 2013: df0 = pandas.DataFrame([json.loads(l) for l in open('SDM_%d.json' % i)]) appended_data.append(df0) df1 = pandas.DataFrame([json.loads(l) for l in open('Scot_%d.json' % i)]) </code></pre> <p>To know whe...
1
2016-05-25T14:31:27Z
[ "python", "loops", "pandas", "append" ]
How to skip items in a loop
37,439,787
<p>I am trying to create a list with all the newspapers articles from 5 different sources. They are stored in <code>JSON</code> format. All articles are stored in different files that contain that contain the newspaper and the year (time spam 2005-2015). The problem is that one of the newspapers is available for only 2...
1
2016-05-25T14:13:04Z
37,440,361
<p>First of all you need to check the version of python to determine what type of error is thrown when the file name is not found as explained in <a href="http://stackoverflow.com/questions/15032108/pythons-open-throws-different-errors-for-file-not-found-how-to-handle-b">Python&#39;s &quot;open()&quot; throws different...
1
2016-05-25T14:36:31Z
[ "python", "loops", "pandas", "append" ]
How to print postgresql timestamp in python
37,439,796
<p>From my code in Python 3.5:</p> <pre><code>cur.execute("SELECT cdate FROM tru_" + uid + " WHERE signature='" + data[2:66] + "'") results = cur.fetchall() </code></pre> <p>"cdate" it's a TIMESTAMP WITH TIMEZONE on my PostgreSQL database, if I print "results" from my code in Python I get this:</p> <pre><code>[(date...
0
2016-05-25T14:13:34Z
37,441,402
<p>You are printing a list of tuples. Print just the timestamp:</p> <pre><code>print (results[0][0]) </code></pre>
0
2016-05-25T15:20:21Z
[ "python", "postgresql" ]
Implied git clone in operating instructions?
37,439,808
<p>I have found several installation instructions from Github that appear to have an implied step where I git clone the files. I usually do this but I wonder why it's not stated explicitly. Am I doing something wrong? Here's an example from <a href="https://github.com/jcjohnson/torch-rnn" rel="nofollow">https://github....
0
2016-05-25T14:14:13Z
37,440,292
<p>Actually the README.md just describes how to install the files you got. Where or how you got them, whether you downloaded a ZIP, or git cloned them or typed them in with an electric typewriter is unimportant. GitHub just happens to show the README.md files content on the repository start page, but that does not mean...
1
2016-05-25T14:33:44Z
[ "python", "git", "github" ]
create pandas dataframe from uneven data
37,439,841
<p>I am working with a data set that has yearly data as well as lifelong data in python 2.7. I have a dictionary that stores lifelong data, as well as an inner DataFrame of yearly data. So it looks something like</p> <pre><code>Bear1 {'color':'brown', 'grown_size':'7ft', 'stats': df1} } </code></pre> <p>where the dat...
0
2016-05-25T14:15:37Z
37,439,898
<p>Use <code>from_dict</code>:</p> <pre><code>In [20]: d={'color':'brown', 'grown_size':'7ft', 'stats': {2007:[1,5,7,2], 2008:[5,3,4,5], 2009:[5,2,6,7]} } pd.DataFrame.from_dict(d) Out[20]: color grown_size stats 2007 brown 7ft [1, 5, 7, 2] 2008 brown 7ft [5, 3, 4, 5] 2...
0
2016-05-25T14:17:43Z
[ "python", "python-2.7", "pandas", "dataframe" ]
create pandas dataframe from uneven data
37,439,841
<p>I am working with a data set that has yearly data as well as lifelong data in python 2.7. I have a dictionary that stores lifelong data, as well as an inner DataFrame of yearly data. So it looks something like</p> <pre><code>Bear1 {'color':'brown', 'grown_size':'7ft', 'stats': df1} } </code></pre> <p>where the dat...
0
2016-05-25T14:15:37Z
37,440,875
<p>EDIT</p> <p>Here is a simple way to have what you want for one bear.</p> <pre><code># recreating your data d = {'meals':[4,2,5], 'children':[5,4,2], 'territory':[8,6,7]} bear1 = {'color':'brown', 'grown_size':'7ft', 'stats': DataFrame(d)} def bear_to_df(bear_dict): df = bear_dict['stats'] ...
0
2016-05-25T14:57:51Z
[ "python", "python-2.7", "pandas", "dataframe" ]
Why is my code locking the database? SQLite and Python
37,439,943
<pre><code>import sqlite3 conn = sqlite3.connect('/Users/macbook/Desktop/lool.db') c = conn.cursor() invalid_input = True def startinglogin(self): loginmessage = input("To register to the Quizzer, type in 'Register'. To login, type in 'Login'.\n") while loginmessage != "Login" and loginmessage != "Register": ...
0
2016-05-25T14:20:00Z
37,440,144
<p>Would you happen to be using a visual tool for sqlite (e.g. sqlitebrowser) while running your code? If you have unwritten changes in the visual tool it might throw errors if you try to run your python code. The fix is to write the changes, then try the code again.</p> <p>EDIT: <a href="http://stackoverflow.com/ques...
0
2016-05-25T14:27:57Z
[ "python", "database", "sqlite", "sqlite3" ]
Python pip argparse upgrade
37,439,993
<p>I have been attempting to upgrade <code>argparse</code> on Ubuntu 16.04 to the latest version, but <code>pip</code> keeps saying that it is part of the standard library.</p> <p>How can this package be upgraded?</p> <pre><code>$ sudo pip install argparse --upgrade Collecting argparse Using cached argparse-1.4.0-p...
2
2016-05-25T14:22:03Z
37,440,207
<p>Argparse is maintained as a separate package here: <a href="https://pypi.python.org/pypi/argparse" rel="nofollow">https://pypi.python.org/pypi/argparse</a> Which is where pip is going to collect it.</p> <p>But</p> <blockquote> <p>As of Python >= 2.7 and >= 3.2, the argparse module is maintained within the Pyth...
4
2016-05-25T14:30:19Z
[ "python", "pip" ]
Pandas: Error tokenizing data--when using glob.glob
37,440,002
<p>I am using the following code to concatenate several files (candidate master files) I have downloaded from <a href="http://fec.gov/finance/disclosure/ftpdet.shtml#a2011_2012" rel="nofollow">here</a>; but they can also be found here:</p> <pre><code>https://github.com/108michael/ms_thesis/blob/master/cn06.txt https:...
0
2016-05-25T14:22:18Z
37,440,577
<p>The default delimiter for <code>pd.read_csv</code> is the comma <code>,</code>. Since all of your candidates have names listed in the format <code>Last, First</code>, pandas reads two columns: everything before the comma and everything after. In one of the files, there are additional commas, leading pandas to assume...
1
2016-05-25T14:45:20Z
[ "python", "pandas", "concatenation", "glob" ]
Pandas: Error tokenizing data--when using glob.glob
37,440,002
<p>I am using the following code to concatenate several files (candidate master files) I have downloaded from <a href="http://fec.gov/finance/disclosure/ftpdet.shtml#a2011_2012" rel="nofollow">here</a>; but they can also be found here:</p> <pre><code>https://github.com/108michael/ms_thesis/blob/master/cn06.txt https:...
0
2016-05-25T14:22:18Z
37,440,589
<pre><code>import numpy as np import pandas as pd import glob df = pd.concat((pd.read_csv(f, header=None, names=['feccandid','candname', \ 'party','date', 'state', 'chamber', 'district', 'incumb.challeng', \ 'cand_status', '1', '2','3','4', '5', '6' ],sep='|', \ usecols=['feccandid', 'party', 'date', 'st...
1
2016-05-25T14:45:51Z
[ "python", "pandas", "concatenation", "glob" ]
Regex to word match on python
37,440,158
<p>I'm trying to create a regex for extracting the software name and the version (if exist) from a Nmap output for example :</p> <pre><code>ftp (product: vsftpd version: 2.3.4 ostype: Unix) </code></pre> <p>I applied the regex : <code>/product: (.*) version: (.*)/</code> </p> <p>It gives the result : </p> <pre><cod...
1
2016-05-25T14:28:40Z
37,440,414
<p>Use this regex <a href="https://regex101.com/r/mN2lZ2/2" rel="nofollow">demo</a>:</p> <pre><code>product: ([\w ]+)(?:version: ([\w.]+)| \w+:) </code></pre>
2
2016-05-25T14:38:52Z
[ "python", "regex", "match", "word" ]
Regex to word match on python
37,440,158
<p>I'm trying to create a regex for extracting the software name and the version (if exist) from a Nmap output for example :</p> <pre><code>ftp (product: vsftpd version: 2.3.4 ostype: Unix) </code></pre> <p>I applied the regex : <code>/product: (.*) version: (.*)/</code> </p> <p>It gives the result : </p> <pre><cod...
1
2016-05-25T14:28:40Z
37,440,636
<p>Just ignore the whitespaces to solve your first issue and then use Alternation to not return version if there is none.</p> <pre><code>(?&lt;=product|version):\s(\S*) </code></pre>
0
2016-05-25T14:47:40Z
[ "python", "regex", "match", "word" ]
How do I retrieve a list of my corpora using watson-developer-cloud python sdk?
37,440,293
<p>I created a single corpora like so:</p> <pre><code>from watson_developer_cloud import ConceptInsightsV2 as ConceptInsights concept_insights = ConceptInsights( username='&lt;My Service User&gt;', password='&lt;My Service Pass&gt;') create_corpora = concept_insights.create_corpus('Test Corpora One!') </code><...
0
2016-05-25T14:33:46Z
37,858,509
<p>That functionality was missing from the Python SDK but has since been added (thanks to your question), so you can now do:</p> <p><code>print(concept_insights.list_corpora(account='&lt;My Account&gt;'))</code></p>
1
2016-06-16T11:56:50Z
[ "python", "ibm-watson-cognitive" ]
conditionally reading a block of lines from file in python
37,440,337
<p>I have an address book and would like to print all (possibly multiple) entries, for a given "last name" efficiently.</p> <p>The entries have the following structure:</p> <pre><code>Johnsen Paul First Street 313 94134 State1 1343154622525 myemail101@mail.com Parker Peter Scnd Street 44 9134...
0
2016-05-25T14:35:37Z
37,441,486
<p>You could always load the file into a dict where key is l_name and data is everything. I've written a small working portion for you. I would recommend creating a class Address_book that has functionality for loading data, searching, adding data, and writing data back out. It would be simple and straight forward but ...
0
2016-05-25T15:23:33Z
[ "python", "io", "conditional", "readline" ]
conditionally reading a block of lines from file in python
37,440,337
<p>I have an address book and would like to print all (possibly multiple) entries, for a given "last name" efficiently.</p> <p>The entries have the following structure:</p> <pre><code>Johnsen Paul First Street 313 94134 State1 1343154622525 myemail101@mail.com Parker Peter Scnd Street 44 9134...
0
2016-05-25T14:35:37Z
37,441,715
<p>If the your file is small enough to fit into memory, you can store the data in a dict where each last name corresponds to a list of one or more entry:</p> <pre><code>from collections import defaultdict with open('test.txt') as f: dct = defaultdict(list) for block in f.read().split('\n\n'): dct[bloc...
0
2016-05-25T15:33:13Z
[ "python", "io", "conditional", "readline" ]
conditionally reading a block of lines from file in python
37,440,337
<p>I have an address book and would like to print all (possibly multiple) entries, for a given "last name" efficiently.</p> <p>The entries have the following structure:</p> <pre><code>Johnsen Paul First Street 313 94134 State1 1343154622525 myemail101@mail.com Parker Peter Scnd Street 44 9134...
0
2016-05-25T14:35:37Z
37,447,003
<p>Thanks for your altenative suggestions. I really appreciate the idea of buiding an address book class and also the in-memory approach, though not quite what I need.</p> <p>My - not the most efficient, but simple - workaround looks like this:</p> <pre><code>choice = int(input("Enter your choice (1/2/3): ")) if choi...
0
2016-05-25T20:26:50Z
[ "python", "io", "conditional", "readline" ]
How to append items into new different lists while looping?
37,440,385
<p>I'm working with the Facebook Graph API and want to collect from a public facebook page all the posts and all the comments of these posts. </p> <p>I already wrote a code that retrieves all the comments of 1 post, but now I want all the comments in a list of all the posts. However, I don't want them in the same list...
0
2016-05-25T14:37:45Z
37,450,193
<p>Instead of:</p> <pre><code>commentsperpost+=[textpost(post=comment) for comment in comments3['data']] </code></pre> <p>you should have:</p> <pre><code>commentsperpost.append([textpost(post=comment) for comment in comments3['data']]) </code></pre>
0
2016-05-26T01:37:02Z
[ "python", "list", "loops", "facebook-graph-api", "dictionary" ]
Python: priority queue with time as priority
37,440,634
<p>I have a priority queue build using <code>heaps</code>. The queue contains messages, which should be send in the order regarding to the priority. However, as the priority value I have a time after which the message should be send, for example a set of messages which I have to put to the queue:</p> <pre><code>(10, m...
2
2016-05-25T14:47:36Z
37,441,132
<p>You could use epoch as a priority value and every time timer fires calculate when it should fire again based on current time. Here's a short example of that in practice:</p> <pre><code>import calendar import time import heapq from threading import Timer def epoch(): return calendar.timegm(time.gmtime()) start...
1
2016-05-25T15:09:16Z
[ "python", "python-2.7", "timer", "heap", "priority-queue" ]
Python - How to add local variables based on number of n provided
37,440,695
<p>I have a function that takes in a list and n number. I'd like to create something like this:</p> <pre><code>def create_list_sets(lst, n): if n == 1: for i in range(len(lst)-1): res = [lst[i], lst[i+1]] return res if n == 2: for i in range(len(lst)-1): res2...
0
2016-05-25T14:50:12Z
37,440,874
<p>Since you know n and have the full lst and the value of n you can use the append</p> <pre><code>def create_list_sets(lst, n): res = [] if n &lt;= len(lst): for i in range(n): res.append([lst[i]) return res </code></pre> <p>Note that this assumes that you want an empty list to return ...
0
2016-05-25T14:57:51Z
[ "python" ]
Python - How to add local variables based on number of n provided
37,440,695
<p>I have a function that takes in a list and n number. I'd like to create something like this:</p> <pre><code>def create_list_sets(lst, n): if n == 1: for i in range(len(lst)-1): res = [lst[i], lst[i+1]] return res if n == 2: for i in range(len(lst)-1): res2...
0
2016-05-25T14:50:12Z
37,441,083
<p>I would guess what you want to do is simply: </p> <pre><code>lst = lst[:min(len(lst), n)] </code></pre> <p>This will give you all the elements up to n-1 or the full list</p>
0
2016-05-25T15:06:46Z
[ "python" ]
Python - How to add local variables based on number of n provided
37,440,695
<p>I have a function that takes in a list and n number. I'd like to create something like this:</p> <pre><code>def create_list_sets(lst, n): if n == 1: for i in range(len(lst)-1): res = [lst[i], lst[i+1]] return res if n == 2: for i in range(len(lst)-1): res2...
0
2016-05-25T14:50:12Z
37,441,250
<p>Your code seems to be:</p> <pre><code>def create_list_sets(lst, n): # multiple cases for value X if n == X: for i in range(len(lst)-1): res = [lst[i], ..., lst[i+X]] return res </code></pre> <p>Your <code>for</code> loop executes only once, because you are <code>return</code...
0
2016-05-25T15:14:03Z
[ "python" ]
Matplotlib: Different colors for each date, labelled via colorbar
37,440,757
<p>I have a system in two variables, <code>v</code> and <code>u</code>, which change over time. I would like to plot them against each other, and have the time indicated by the color.</p> <p>Here is my data, where the index was generated using <code>pd.to_datetime()</code>:</p> <pre><code> v u d...
2
2016-05-25T14:52:44Z
37,441,263
<p>You create <code>indices</code> and then you do not use it.</p> <p>You have to use it for <code>my_colors</code>:</p> <pre><code>cmap = plt.get_cmap('viridis') indices = np.linspace(0, cmap.N, len(df)) my_colors = [cmap(int(i)) for i in indices] fig, ax = plt.subplots() for i, idx in enumerate(df.index): ax.p...
1
2016-05-25T15:14:35Z
[ "python", "pandas", "matplotlib" ]
How do I iterate through cells in a specific column using openpyxl 1.6
37,440,855
<p>I am currently using Python 2.7 and so far have been able to make it this far. I need to print the value of cells in column D till the maximum row the excel sheet has.</p> <pre><code>wb = openpyxl.load_workbook(filename) sheet = wb.get_sheet_by_name('Something') for row in range(2, sheet.get_highest_row()): bla=...
1
2016-05-25T14:57:21Z
37,441,070
<p>I suspect you are using an outdated version of <code>openpyxl</code>, update it:</p> <pre><code>pip install --upgrade openpyxl </code></pre> <p>And, you should not be calling <code>value</code>, it is a property:</p> <pre><code>status = sheet['D' + bla].value </code></pre>
0
2016-05-25T15:06:10Z
[ "python", "excel", "openpyxl" ]
How do I iterate through cells in a specific column using openpyxl 1.6
37,440,855
<p>I am currently using Python 2.7 and so far have been able to make it this far. I need to print the value of cells in column D till the maximum row the excel sheet has.</p> <pre><code>wb = openpyxl.load_workbook(filename) sheet = wb.get_sheet_by_name('Something') for row in range(2, sheet.get_highest_row()): bla=...
1
2016-05-25T14:57:21Z
37,441,580
<p>I think this is a very primitive and not very optimized way, but I got the answer nevertheless.</p> <pre><code>for cow in range(1, sheet.get_highest_row()): status = sheet.cell(row=cow, column=3).value </code></pre> <p>Please, If anyone can, help me improve it. Thank you very much in advance.</p> <p>See more ...
0
2016-05-25T15:27:43Z
[ "python", "excel", "openpyxl" ]
Non-linear fit in Python 2.7 doesn't give any good result
37,441,137
<p>Here is my problem: I have experimental data to fit with a model. To do this, i used curve_fit from scipy. The script goes without any error or warning, but doesn't give a satisfying result (it gives me a quasi line instead of two Lorentzian shaped graph).</p> <p>But the strangest part is that when I give a guessin...
0
2016-05-25T15:09:25Z
37,450,165
<p>it's very hard to tell what is going on with the mixture of constants and very long formulae. But a couple points to consider:</p> <ol> <li><p>If variables are not changing from their initial values, you should be careful about scaling. Your (<code>X**2+Z**2)*10**(6)</code> will be around ~1e16, which might make ...
0
2016-05-26T01:33:09Z
[ "python", "scipy", "curve-fitting" ]
Non-linear fit in Python 2.7 doesn't give any good result
37,441,137
<p>Here is my problem: I have experimental data to fit with a model. To do this, i used curve_fit from scipy. The script goes without any error or warning, but doesn't give a satisfying result (it gives me a quasi line instead of two Lorentzian shaped graph).</p> <p>But the strangest part is that when I give a guessin...
0
2016-05-25T15:09:25Z
37,469,672
<p>Well people, thank to you i finally found a solution!</p> <p>instead of using <code>curve_fit</code>, i tried to use directly <code>leastsq</code> following <a href="http://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html#least-square-fitting-leastsq" rel="nofollow">this tutorial</a> in order to see what w...
0
2016-05-26T19:42:02Z
[ "python", "scipy", "curve-fitting" ]
How to use tf.while_loop() in tensorflow
37,441,140
<p>This is a generic question. I found that in the tensorflow, after we build the graph, fetch data into the graph, the output from graph is a tensor. but in many cases, we need to do some computation based on this output (which is a <code>tensor</code>), which is not allowed in tensorflow. </p> <p>for example, I'm tr...
0
2016-05-25T15:09:35Z
37,444,810
<p>What is stopping you from adding more functionality to the body? You can build whatever complex computational graph you like in the body and take whatever inputs you like from the enclosing graph. Also, outside of the loop, you can then do whatever you want with whatever outputs you return. As you can see from the a...
1
2016-05-25T18:17:18Z
[ "python", "tensorflow" ]
I cant init Google Cloud SDK on Ubuntu
37,441,174
<p>I downloaded Google Cloud SDK for python on my Ubuntu. (<a href="https://cloud.google.com/sdk/docs/quickstart-linux#before-you-begin" rel="nofollow">https://cloud.google.com/sdk/docs/quickstart-linux#before-you-begin</a>)</p> <p>Then I followed the steps from the page but when I run</p> <pre><code>gcloud init </co...
2
2016-05-25T15:11:24Z
37,443,950
<p>The user <strong>gcbirzan</strong> responded my questions at an irc channel (which I recommend), it is <strong>#appengine</strong> on <strong>irc.freenode.net</strong></p> <p>I had to run this:</p> <pre><code>sudo chown ariel -R /home/ariel/.config/gcloud </code></pre> <p>I also leave the transcription of the cha...
3
2016-05-25T17:27:36Z
[ "python", "linux", "google-app-engine", "ubuntu", "permissions" ]
how do arrow coordinates work in matplotlib?
37,441,212
<p>i tried to draw an arrow from (0.1,0.5) to (0.5,0.5) in matplotlib based on this example (<a href="http://matplotlib.org/examples/pylab_examples/arrow_simple_demo.html" rel="nofollow">http://matplotlib.org/examples/pylab_examples/arrow_simple_demo.html</a>):</p> <pre><code>f = plt.figure() ax = plt.subplot(2, 1, 1)...
0
2016-05-25T15:12:32Z
37,441,465
<p>From the <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.arrow" rel="nofollow">documentation</a>:</p> <blockquote> <pre><code>matplotlib.pyplot.arrow(x, y, dx, dy, hold=None, **kwargs) </code></pre> <p>Add an arrow to the axes.</p> <p>Call signature:</p> <pre><code>arrow(x, y, dx, d...
3
2016-05-25T15:22:29Z
[ "python", "matplotlib" ]
can a pandas.Period represent an arbitrary time span?
37,441,284
<p><strong>Edit: the (puzzling) behavior below was for pandas 0.17.1. It appears fixed in 0.18.1.</strong></p> <p>Is there a way to represent an arbitrary time span with a <code>pandas.Period</code>?</p> <p>Specifically, I was trying to contrive a <code>pandas.Period()</code> to represent an arbitrary <em>n</em>-day...
1
2016-05-25T15:15:18Z
37,444,751
<p><code>pd.Period(1970, freq='2D')</code> has the expected <code>start_time</code> and <code>end_time</code> for me, also using Pandas 0.18.1. Maybe try restarting your interpreter, and run the first bit of code you posted again to verify that you're still getting the unexpected output?</p>
1
2016-05-25T18:13:54Z
[ "python", "pandas" ]
finding last business day of a month in python
37,441,323
<p>I'm trying to find last business day of of the month. I wrote the code below for that and it works fine but I was wondering if there is a cleaner way of doing it? </p> <pre><code>from datetime import date,timedelta import datetime import calendar today=datetime.date.today() last = today.replace(day=calendar.mont...
0
2016-05-25T15:16:50Z
37,442,360
<p>You can use <code>Pandas</code> to get business days. Refer <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/timeseries.html</a></p> <p>Also you can refer this <a href="https://pypi.python.org/pypi/business_calendar/" rel="nofollow">htt...
0
2016-05-25T16:01:39Z
[ "python", "datetime", "calendar" ]
finding last business day of a month in python
37,441,323
<p>I'm trying to find last business day of of the month. I wrote the code below for that and it works fine but I was wondering if there is a cleaner way of doing it? </p> <pre><code>from datetime import date,timedelta import datetime import calendar today=datetime.date.today() last = today.replace(day=calendar.mont...
0
2016-05-25T15:16:50Z
39,478,209
<p>I use the following:</p> <pre><code>from pandas.tseries.offsets import BMonthEnd from datetime import date d=date.today() offset = BMonthEnd() #Last day of current month offset.rollforward(d) #Last day of previous month offset.rollback(d) </code></pre>
0
2016-09-13T20:08:31Z
[ "python", "datetime", "calendar" ]
How to avoid PyObject_to_MemoryviewSlice, GOTREF / DECREF Python API calls?
37,441,423
<p>I have a problem with cythonizing my code, more specifically the following (and similar) sniplets:</p> <pre><code>cdef double [:,:] grad_d_him_d_jm grad_d_ihm_d_jm = grad_d_im_d_jm(...) </code></pre> <p>where grad_d_im_d_jm(...) would return a double [:,:] memoryview. This code would be translated by Cython into t...
0
2016-05-25T15:21:10Z
37,444,458
<p>These appear to be part of Cython reference counting API explained <a href="https://github.com/cython/cython/wiki/enhancements-refnanny" rel="nofollow">here</a>. </p> <p>My guess is that <code>grad_d_im_d_jm</code> returns a Python object (e.g. NumPy array) and thus Cython has to decrement the object reference coun...
1
2016-05-25T17:55:21Z
[ "python", "cython", "memoryview" ]
Importing headers and payload into Scrapy
37,441,447
<p>I've been working with firebug and I've got the following dictionaries to query an api.</p> <pre><code>payload = "{\"prefixText\":\"2261\",\"count\":\"10 \"}" headers = { 'origin': "site.com", 'x-requested-with': "XMLHttpRequest", 'user-agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like G...
0
2016-05-25T15:21:54Z
37,441,628
<p>Scrapy isn't very useful for just "making requests", that's the <code>requests</code> module for. Scrapy is a crawling framework, used for creating website spiders and on those spiders, the request rules are necessary.</p> <p>Anyway if you create a spider, and you need to send a <code>POST</code> request, you can d...
2
2016-05-25T15:29:37Z
[ "python", "scrapy" ]
Twisted: How to interrupt callback chain on deferred
37,441,491
<p>My problem: I have a deferred with callbacks and errbacks. I need to stop the process after a specific errback. In another words, if a specific function of errback is called, i need to get its returns and DO NOT process the following callbacks.</p> <pre><code>from twisted.internet import defer from twisted.python i...
2
2016-05-25T15:23:54Z
37,443,701
<p>That's a really interesting question. Twisted does not give any documented API for modifying callback chain after error occurs. If you really want to interrupt processing in errback you can always raise error instead of trapping it. </p> <p>However if you really want to remove all callbacks from Deferred in certain...
0
2016-05-25T17:13:17Z
[ "python", "twisted", "deferred" ]
Beautiful Soup - Loop Through Navigable String
37,441,526
<p>I'm trying to loop through a NavigableString and grab all the content within the 'a' tags. I did a </p> <pre><code>home= items.findAll('div', class_="dlineups-half") </code></pre> <p>and it gets me the NaviableString below. I can get the first piece of data via home.a.contents which gives me Joe Bendik, but whe...
0
2016-05-25T15:25:29Z
37,441,582
<p>Find all <code>a</code> elements inside and <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#get-text" rel="nofollow">get the text</a>:</p> <pre><code>home = items.find_all('div', class_="dlineups-half") for item in home: for a in item.find_all("a"): print(a.get_text()) </code></pre>
0
2016-05-25T15:27:54Z
[ "python", "beautifulsoup" ]
Error while installing cryptography using pip
37,441,668
<p>Installation fails in Ubuntu 14.04 while I tried to install <code>cryptography</code>. I have tried to check if their are any special requirements from ubuntu side apart from basic python installation, I have also installed the below requirments.</p> <pre><code>"libxml2-dev", "libxslt1-dev", "lib32z1-dev", "libffi-...
0
2016-05-25T15:30:54Z
37,441,669
<p>I found the answer, this error has occurred due because of the low resources on server.</p> <p>I needed more ram or a bigger swap file for the command to succeed.</p> <p>Similar Issue: <a href="http://stackoverflow.com/questions/24455238/lxml-installation-error-ubuntu-14-04-internal-compiler-error">lxml installati...
1
2016-05-25T15:30:54Z
[ "python" ]
BeautifulSoup Parsing
37,441,692
<p>I have been struggling to parse out this tree using BeautifulSoup to get just the text I am looking for. After prettifying the HTML I end up with a table I am interested in.</p> <pre><code> &lt;td&gt; &lt;a href="/inventoryCheck/16783169/?zip=93817"&gt; &lt;h3&gt; Product A &lt;/...
1
2016-05-25T15:32:14Z
37,441,889
<p>At the very least, you want to find all <code>td</code> elements having an <code>h3</code> element inside - these would be your products. Then, you can get the availability from the <code>a</code> element having <code>show_hide</code> class and <code>inventoryCheck</code> inside <code>href</code>. Working code:</p> ...
1
2016-05-25T15:40:26Z
[ "python", "beautifulsoup" ]
BeautifulSoup Parsing
37,441,692
<p>I have been struggling to parse out this tree using BeautifulSoup to get just the text I am looking for. After prettifying the HTML I end up with a table I am interested in.</p> <pre><code> &lt;td&gt; &lt;a href="/inventoryCheck/16783169/?zip=93817"&gt; &lt;h3&gt; Product A &lt;/...
1
2016-05-25T15:32:14Z
37,442,245
<p>What you're looking for are the <code>.parent</code> and <code>.nextSibling</code> attributes. They help you navigate the tree relative to your <code>h3</code> tags.The important thing to remember about BeautifulSoup (and any HTML/XML/etc.) is that it's tree based. The rough structure of your HTML is like this:</p> ...
1
2016-05-25T15:56:16Z
[ "python", "beautifulsoup" ]
BeautifulSoup Parsing
37,441,692
<p>I have been struggling to parse out this tree using BeautifulSoup to get just the text I am looking for. After prettifying the HTML I end up with a table I am interested in.</p> <pre><code> &lt;td&gt; &lt;a href="/inventoryCheck/16783169/?zip=93817"&gt; &lt;h3&gt; Product A &lt;/...
1
2016-05-25T15:32:14Z
37,444,162
<p>If you just want the product and availability you can use a css selector, pull the h3 tags inside the td tags then use <code>find_next</code> to get the anchor:</p> <pre><code>soup = BeautifulSoup(h,"html.parser") h3s = soup.select("td h3") print([(h3.text.strip(), h3.find_next("a").text.strip()) for h3 in h3s]) ...
1
2016-05-25T17:39:02Z
[ "python", "beautifulsoup" ]
Scapy sniffing on Windows
37,441,698
<p>I run this code as administrator:</p> <pre><code>from scapy.all import * def poison(packet): packet[TCP].flags='R' sendp(packet) sniff(prn=poison,filter='tcp',iface='any') </code></pre> <p>And I have error:AttributeError None Type object has no attribute encode<br> What should I do to make it work?</p>
2
2016-05-25T15:32:25Z
37,498,518
<p>I don't think setting <code>iface</code> to <code>"any"</code> is valid under Windows.</p> <p>You can check by removing the <code>iface</code> parameter from your code (or by using a valid interface name).</p>
0
2016-05-28T11:39:02Z
[ "python", "scapy" ]
Python: Unpacking binary file into a 2-d array and giving a length error
37,441,731
<p>I'm trying to read in data from a file in binary format and store it in a 2-d array. However, I'm getting an error that reads</p> <pre><code>error: unpack requires a bytes object of length 2 </code></pre> <p>Essentially what I have is something like</p> <pre><code>import os, struct from itertools import chain pa...
0
2016-05-25T15:33:55Z
37,444,475
<p>As it turns out, there was still iterations to be performed that when reading in 2 bytes (or more) at a time the data from the file was running out. The fix is to do something like the following</p> <pre><code>readBytes = value_wanting_to_be_read dataLength = int(value2/readBytes) </code></pre> <p>and then in the ...
0
2016-05-25T17:56:37Z
[ "python", "arrays", "file", "python-3.x", "unpack" ]
Getting unicode path of current running script
37,441,805
<p><a href="http://stackoverflow.com/questions/50499/how-do-i-get-the-path-and-name-of-the-file-that-is-currently-executing">This</a> question exists on this website but it is flawed as it returns a <code>&lt;type 'str'&gt;</code> (both when using <code>__file__</code> and when using the module <code>inspect</code>) an...
0
2016-05-25T15:37:01Z
37,442,119
<p>You need <code>.decode()</code>, not <code>.encode()</code>. To go from <code>unicode</code> to <code>str</code>, one <em>encodes</em>. To go the other direction, one <em>decodes</em>.</p> <p>Try:</p> <pre><code>import sys filename = __file__.decode(sys.getfilesystemencoding()) print type(filename), filename </cod...
2
2016-05-25T15:50:34Z
[ "python", "unicode" ]
Getting unicode path of current running script
37,441,805
<p><a href="http://stackoverflow.com/questions/50499/how-do-i-get-the-path-and-name-of-the-file-that-is-currently-executing">This</a> question exists on this website but it is flawed as it returns a <code>&lt;type 'str'&gt;</code> (both when using <code>__file__</code> and when using the module <code>inspect</code>) an...
0
2016-05-25T15:37:01Z
37,442,130
<p>I guess you want to use <code>decode</code> instead of <code>encode</code>:</p> <pre><code>&gt;&gt;&gt; type('string'.encode('utf-8')) &lt;type 'str'&gt; &gt;&gt;&gt; type('string'.decode('utf-8')) &lt;type 'unicode'&gt; </code></pre> <p>Genrally, <code>encode</code> returns a bytestring, <code>decode</code> a uni...
1
2016-05-25T15:50:51Z
[ "python", "unicode" ]
Python - XML Parsing - Accessing values of different descendants of the same element
37,441,928
<p>I am trying to parse an Xml file using Python. My file has a structure similar to the below:</p> <pre><code>&lt;dataset&gt; &lt;dataTable id = 123&gt; &lt;name&gt; Name1 &lt;/name&gt; &lt;attributeList&gt; &lt;attribute id = 1&gt; &lt;measurement&gt; &lt;text...
0
2016-05-25T15:42:23Z
37,444,915
<p>You can use a wildcard to get the child of the <em>measurement</em> tag and any child of that child:</p> <pre><code>import lxml.etree as et xml = et.parse("in.xml") print(xml.xpath("//attributeList//measurement/*/*/text()")) </code></pre> <p>Which gives you:</p> <pre><code>['User defined.', 'MM-YYYY ', 'degree...
0
2016-05-25T18:23:03Z
[ "python", "xml", "lxml" ]
How can I include try: and except: for exception handling?
37,441,958
<p>I attempted to include <code>try:</code> and <code>except:</code> in this program to catch text string exceptions, but unable to figure out how to implement. How can I include <code>try:</code> and <code>except:</code> for exception handling?</p> <pre><code>#!/usr/bin/python2.7 h = float(raw_input('Enter Hours: ')...
-4
2016-05-25T15:43:47Z
37,442,504
<p>You just need to use a try except pair</p> <pre><code>def num(s): try: return float(s) except : return None h = num(raw_input('Enter Hours: ')) </code></pre> <p>Now you need to ask for a valid response. for example.</p> <pre><code>h = None p = None while (h is None): h = num(raw_input(...
0
2016-05-25T16:08:59Z
[ "python", "python-2.7", "exception", "exception-handling", "try-catch" ]
How can I include try: and except: for exception handling?
37,441,958
<p>I attempted to include <code>try:</code> and <code>except:</code> in this program to catch text string exceptions, but unable to figure out how to implement. How can I include <code>try:</code> and <code>except:</code> for exception handling?</p> <pre><code>#!/usr/bin/python2.7 h = float(raw_input('Enter Hours: ')...
-4
2016-05-25T15:43:47Z
37,444,545
<pre><code>#!/usr/bin/python2.7 def calc_pay(h, r) : if h &lt;= 0 or r &lt;= 0 : return None elif h &gt; 40 : return (h * r + (h - 40) * r * 0.5) else : return (h * r) try : h = float(raw_input('Enter Hours: ')) r = float(raw_input('Enter Rate: ')) p = calc_pay(h, r) ...
1
2016-05-25T18:01:23Z
[ "python", "python-2.7", "exception", "exception-handling", "try-catch" ]
NotImplementedError() what does this mean, event profiler pyalgotrade
37,441,982
<p>I'm trying to run pyalgotrade's event profiler. I'm using custom data, it works when I run it with the default stratergy/predicate 'BuyOnGap' however when I try and run it with a simple custom strategy it throw the error:</p> <pre><code>Traceback (most recent call last): File "C:\Users\David\Desktop\Python\Course...
0
2016-05-25T15:44:41Z
37,442,549
<p>I think you just made a spelling mistake in eventOccurred method definition</p> <pre><code>def eventOccoured( self, instrument, aBarDS): </code></pre> <p>should be replaced by </p> <pre><code>def eventOccurred( self, instrument, aBarDS): </code></pre>
4
2016-05-25T16:10:54Z
[ "python", "trading", "algorithmic-trading", "pyalgotrade" ]
Matrix Expression from String
37,442,054
<p>Context: I'm doing a bunch of simulations that require me to implement different Hamiltonians. These Hamiltonians are just matrices, built out of Kronecker products of some common elements, with some prefactors that I have to calculate based on the system parameters. E.g, using ⊗ for the Kronecker product</p> <p>...
2
2016-05-25T15:47:47Z
37,453,142
<p>Let's look what's going on in simpler case:</p> <pre><code>exp = sympify('w1*X1'); right_exp = w1*X1 type(exp), type(right_exp) Out[47]: (sympy.core.mul.Mul, sympy.matrices.expressions.matmul.MatMul) </code></pre> <p>Looks like <code>simpify</code> doesn'y understand that <code>X1</code> is a matrix. So, if we me...
1
2016-05-26T06:28:24Z
[ "python", "matrix", "simulation", "sympy" ]
Can't access matplotlib title fontsize when not centered
37,442,071
<p>Not sure what's going on here. If I set <code>loc='left'</code> or <code>loc='right'</code> the <code>get_fontsize</code> method no longer points to the non-centered title.</p> <p>How do I access the fontsize of a left aligned title? </p> <pre><code>import matplotlib.pyplot as plt # Set up a blank plot fig, a...
0
2016-05-25T15:48:26Z
37,442,639
<p>From <a href="http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_title" rel="nofollow">docs</a>: </p> <blockquote> <p>Set one of the three available axes titles. The available titles are positioned above the axes in the center, flush with the left edge, and flush with the right edge.</p> </block...
1
2016-05-25T16:15:14Z
[ "python", "matplotlib", "plot" ]
Cannot import WebSocketApp form websocket in python
37,442,193
<p>After installing websocket from pip, I am able to run the python interpreter and from there import WebSocketApp. But when I put same line, <code>from websoket import WebSocketApp</code>, in a file and try to run it, I get the error <code>ImportError: cannot import name WebSocketApp</code>. </p> <p>What is happening...
1
2016-05-25T15:53:27Z
37,443,874
<p>Try to update this websocket to a latest version: <a href="https://pypi.python.org/pypi/websocket-client/0.37.0" rel="nofollow">https://pypi.python.org/pypi/websocket-client/0.37.0</a></p> <p>I think the version 0.2.1 has not implemented WebsocketApp.</p>
0
2016-05-25T17:23:39Z
[ "python", "websocket" ]
importing file in python through multiple directories
37,442,207
<p>I have a directory structure like this in python:</p> <pre><code>- __init__.py (1) - folder1 - __init__.py (2) - folder2 - __init__.py (3) - file.py </code></pre> <p>how can I expose file.py?</p> <p>currently in <code>__init__.py(2)</code> I have:</p> <pre><code>from folder2 import file <...
0
2016-05-25T15:54:01Z
37,442,299
<p>These are all the imports you could do (you are not required to perform all of them, just the ones you need):</p> <p>in <code>__init__.py</code> (1):</p> <pre><code>from .folder1.folder2 import file </code></pre> <p>in <code>__init__.py</code> (2):</p> <pre><code>from .folder2 import file </code></pre> <p>in <c...
1
2016-05-25T15:59:07Z
[ "python" ]
importing file in python through multiple directories
37,442,207
<p>I have a directory structure like this in python:</p> <pre><code>- __init__.py (1) - folder1 - __init__.py (2) - folder2 - __init__.py (3) - file.py </code></pre> <p>how can I expose file.py?</p> <p>currently in <code>__init__.py(2)</code> I have:</p> <pre><code>from folder2 import file <...
0
2016-05-25T15:54:01Z
37,442,409
<pre><code>myproject |-app.py |-__init__.py |-folder1 |-__init__.py |-folder2 |-__init__.py |-file.py </code></pre> <p>for example, we have app.py under folder project. In app.py, put the following lines on the top:</p> <pre><code>import sys sys.path.append("/path/to/myproject") #...
1
2016-05-25T16:03:52Z
[ "python" ]
Split '&lt; &gt;' line with python re
37,442,212
<p>I cannot figure out how to split this line with &amp;lt, &amp;gt symbols:</p> <pre><code>"&amp;lt;c#&amp;gt;&amp;lt;winforms&amp;gt;&amp;lt;type-conversion&amp;gt;&amp;lt;decimal&amp;gt;&amp;lt;opacity&amp;gt;" </code></pre> <p>I would like to get following list from the line above:</p> <pre><code>['c#', 'winform...
0
2016-05-25T15:54:33Z
37,442,363
<p><code>split()</code> or <code>re.split()</code> based solutions should probably be preferred in this case, but here is an alternative "don't use it in practice" approach involving using HTML parsers:</p> <pre><code>&gt;&gt;&gt; from bs4 import BeautifulSoup &gt;&gt;&gt; from HTMLParser import HTMLParser &gt;&gt;&gt...
1
2016-05-25T16:01:40Z
[ "python", "regex", "python-2.7" ]
Split '&lt; &gt;' line with python re
37,442,212
<p>I cannot figure out how to split this line with &amp;lt, &amp;gt symbols:</p> <pre><code>"&amp;lt;c#&amp;gt;&amp;lt;winforms&amp;gt;&amp;lt;type-conversion&amp;gt;&amp;lt;decimal&amp;gt;&amp;lt;opacity&amp;gt;" </code></pre> <p>I would like to get following list from the line above:</p> <pre><code>['c#', 'winform...
0
2016-05-25T15:54:33Z
37,442,374
<p>You can use:</p> <pre><code>[s for s in re.split("&amp;lt;|&amp;gt;", str) if s] </code></pre> <p>which returns: </p> <pre><code>'c#', 'winforms', 'type-conversion', 'decimal', 'opacity'] </code></pre>
0
2016-05-25T16:02:07Z
[ "python", "regex", "python-2.7" ]
Split '&lt; &gt;' line with python re
37,442,212
<p>I cannot figure out how to split this line with &amp;lt, &amp;gt symbols:</p> <pre><code>"&amp;lt;c#&amp;gt;&amp;lt;winforms&amp;gt;&amp;lt;type-conversion&amp;gt;&amp;lt;decimal&amp;gt;&amp;lt;opacity&amp;gt;" </code></pre> <p>I would like to get following list from the line above:</p> <pre><code>['c#', 'winform...
0
2016-05-25T15:54:33Z
37,442,423
<p>If we a few assumptions about the input string are true, we can probably avoid regular expressions all together. My assumptions is that the "columns" are xml escaped strings that follow this form: <code>&lt;col1&gt;&lt;col2&gt;...&lt;coln&gt;</code>. If that is the case, then we really don't need the <code>&lt;</...
2
2016-05-25T16:04:54Z
[ "python", "regex", "python-2.7" ]
Split '&lt; &gt;' line with python re
37,442,212
<p>I cannot figure out how to split this line with &amp;lt, &amp;gt symbols:</p> <pre><code>"&amp;lt;c#&amp;gt;&amp;lt;winforms&amp;gt;&amp;lt;type-conversion&amp;gt;&amp;lt;decimal&amp;gt;&amp;lt;opacity&amp;gt;" </code></pre> <p>I would like to get following list from the line above:</p> <pre><code>['c#', 'winform...
0
2016-05-25T15:54:33Z
37,443,148
<p>Why use split, it just uses a regex for start/end cut'n paste.<br> Cut out the middle man, it's quicker. </p> <p>Use a findall kind of function with a regex like this<br> (set the <em>dot-all</em> modifier if spanning lines) </p> <p><code>((?:(?!&amp;[gl]t;).)+)(?:&amp;[gl]t;)*</code></p> <p>Or, if you still ne...
1
2016-05-25T16:41:48Z
[ "python", "regex", "python-2.7" ]
Can I control a powershell "session" from Python
37,442,292
<p>I want to initalise a powershell subprocess and be able to send commands to it and then receive its output.</p> <p>Slightly different from the usual subprocess.Popen(['powershell', '...']) use case because ideally I would like my powershell session to persist whilst my script is running.</p> <p>This is because I m...
0
2016-05-25T15:58:35Z
37,442,450
<p>You can try by combining this 2 post:</p> <p>hope it helps:</p> <p><a href="http://stackoverflow.com/questions/9322796/keep-a-subprocess-alive-and-keep-giving-it-commands-python">Keep a subprocess alive and keep giving it commands? Python</a></p> <p><a href="http://stackoverflow.com/questions/14508809/run-powersh...
0
2016-05-25T16:06:29Z
[ "python", "powershell", "subprocess" ]
Download S3 Files with Boto
37,442,444
<p>I am trying to set up an app where users can download their files stored in an S3 Bucket. I am able to set up my bucket, and get the correct file, but it won't download, giving me the this error: <code>No such file or directory: 'media/user_1/imageName.jpg'</code> Any idea why? This seems like a relatively easy prob...
1
2016-05-25T16:05:55Z
37,443,504
<p>The problem is that you are downloading to a <strong>local directory that doesn't exist</strong> (<code>media/user1</code>). You need to either:</p> <ul> <li>Create the directory on the local machine first</li> <li>Just use the filename rather than a full path</li> <li>Use the full path, but replace slashes (<code>...
1
2016-05-25T17:03:00Z
[ "python", "amazon-s3", "boto" ]
Trying to understand recursion in Python
37,442,445
<p>I've been trying to understand the following code, it's a recursion example from my Python book:</p> <pre><code>def mysum(L): if not L: return 0 else: return L[0] + mysum(L[1:]) print(mysum([1, 2, 3, 4, 5])) </code></pre> <p><code>output: 15</code></p> <p>I have a very hard time to under...
1
2016-05-25T16:06:04Z
37,442,647
<p>Let's follow your first part of code, we call it with the list [1,2,3,4,5]</p> <p>The first call has L = [1,2,3,4,5] so gets into the second portion and does:</p> <pre><code>return 1 + mysum([2,3,4,5]) </code></pre> <p>mysum is called again, now with a smaller list, which does:</p> <pre><code>return 2 + mysum([3...
0
2016-05-25T16:15:22Z
[ "python", "python-2.7", "python-3.x" ]