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 |
---|---|---|---|---|---|---|---|---|---|
Time Inaccuracy or Inefficient Code? | 39,842,201 | <p>I'm currently working on a program that will display the amount of time that has passed since a specific point. A stopwatch, if you will.</p>
<p>I've finally gotten my code working, but as it turns out, it's not very accurate. It falls behind very quickly, being 1 or even 2 seconds off within just the first 10 seconds of running, I'm not completely sure why this is.</p>
<pre><code># Draw
def draw():
stdscr.erase()
stdscr.border()
# Debugging
if debug:
stdscr.addstr(5 , 3, "running : %s " % running )
stdscr.addstr(6 , 3, "new : %s " % new )
stdscr.addstr(7 , 3, "pureNew : %s " % pureNew )
stdscr.addstr(8 , 3, "paused : %s " % paused )
stdscr.addstr(9 , 3, "complete : %s " % complete )
stdscr.addstr(10, 3, "debug : %s " % debug )
if running:
stdscr.addstr(1, 1, ">", curses.color_pair(8))
stdscr.addstr(1, 3, t.strftime( "%H:%M.%S", t.gmtime( timeElapsedTotal ) ) )
elif not running:
if new and pureNew:
stdscr.addstr(1, 1, ">", curses.color_pair(5))
stdscr.addstr(1, 3, t.strftime( "%H:%M.%S", timeNone ) )
elif paused:
stdscr.addstr(1, 3, t.strftime( "%H:%M.%S", t.gmtime( timeElapsedTotal ) ), curses.color_pair(1) )
stdscr.addstr(1, 1, ">", curses.color_pair(3))
else:
stdscr.addstr(1, 1, ">", curses.color_pair(5))
stdscr.addstr(1, 3, t.strftime( "%H:%M.%S", timeNone ) )
stdscr.redrawwin()
stdscr.refresh()
return
# Calculations
def calc():
global timeElapsedTotal
if running:
timeElapsedTotal = t.clock() - timeStart
return
# Main Loop
while True:
# Get input from the user
kInput = stdscr.getch()
# If q is pressed we close the program
if kInput == ord('q'):
endProg()
# If d is pressed we toggle 'debug' mode
elif kInput == ord('d'):
debug = not debug
# If s is pressed we stop the current run
elif kInput == ord('s'):
running = False
new = True
# If spacebar is pressed and we are ready for a new run,
# we start a new run
elif kInput == ord(' ') and new:
running = not running
new = not new
pureNew = False
timeStart = t.clock()
# If p is pressed and we are in the middle of a run,
# we pause the run
elif kInput == ord('p') and not new:
running = not running
paused = not paused
timeStart = t.clock() - timeStart
calc()
draw()
</code></pre>
<p>The above code is, as far as I am aware, working as intended. I'm not sure if the lag is coming from <code>time.clock()</code> or if it's simply my inefficient code. Is this the kind of work that I would need to use threads for?</p>
<p>I did a bit of googling and saw others talking about other functions in the time module but none of those worked any better for me.</p>
<p>Let me know if this isn't enough information or I made a simple mistake.</p>
| 1 | 2016-10-03T23:54:04Z | 39,842,416 | <p>Well as it turns out the solution was as simple as changing from <code>time.clock()</code> to <code>time.time()</code> as suggested by <em>tdelaney</em>. </p>
<p>Looks like I need to more thoroughly read up on modules as I use them. Thanks for the wisdom.</p>
| 2 | 2016-10-04T00:24:01Z | [
"python",
"datetime",
"time",
"stopwatch"
]
|
Bundling application and dependencies with pynsist | 39,842,237 | <p>I'm a python newbie so please bear with me.</p>
<p>I'm trying to bundle a PyQt4 application with pynsist. I want to import module A which depends on module B, C, and D, but specifying module A in the installer.cfg file does not bundle B, C, and D. Do I need to specify <strong>ALL</strong> the modules my application depends on in the installer.cfg file, and if so is there a good method of finding out what they are?</p>
| 0 | 2016-10-03T23:59:42Z | 40,087,914 | <p>You need to specify all of the modules or packages to be bundled.</p>
<p>If these are modules you are writing yourself, you can put them all in one package, so you import them as <code>import mypkg.A</code> or <code>import mypkg.B</code>. Then you can ask it to bundle <code>mypkg</code> as a whole.</p>
<p>You can see what modules your program has loaded by putting this code at the end:</p>
<pre><code>import sys
print(sorted(sys.modules))
</code></pre>
<p>That will show you every module that it's loaded, including standard library modules (which are always bundled).</p>
| 0 | 2016-10-17T13:37:11Z | [
"python",
"python-packaging",
"pynsist"
]
|
Go exec external python script and get the returned output | 39,842,242 | <p>In my Go file i use exec to run the external script:</p>
<pre><code>cmd := exec.Command("test.py")
out, err := cmd.CombinedOutput()
if err != nil {
fmt.Println(err)
}
fmt.Println(string(out))
</code></pre>
<p>The python script it's executed fine, but the go <code>fmt.Println(string(out))</code> prints nothing. </p>
<p>The question it's how i should return the value from the Python script to be read back again from Go?</p>
<p>Python pseudo code:</p>
<p><code>def main():
...
...
return value</code></p>
| -2 | 2016-10-04T00:00:10Z | 39,842,421 | <p>I think i found the bug, you need to put the full path to "test.py"</p>
<p><strong>Test</strong></p>
<p>I have two files in a directory:
test.py
test.go</p>
<p>The <code>test.py</code> is:</p>
<pre><code>#!/usr/bin/env python3
print("Hello from python")
</code></pre>
<p>and <code>test.go</code> is:</p>
<pre><code>package main
import (
"fmt"
"os/exec"
)
func main() {
//cmd := exec.Command("test.py")
// I got an error because test.py was not in my PATH, which makes sense
// When i added './' the program worked because go knew where to find test.py
cmd := exec.Command("./test.py")
out, err := cmd.CombinedOutput()
if err != nil {
fmt.Println(err)
}
fmt.Println(string(out))
}
</code></pre>
<p>And I get the following output:</p>
<pre><code>$ go run ./test.go
Hello from python
</code></pre>
| 0 | 2016-10-04T00:24:37Z | [
"python",
"go"
]
|
Traversing subfolder files? | 39,842,253 | <p>I have wrote a script to erase a given word from docx files and am at my last hurdle of it checking subfolder items as well. Can someone help me in figuring out where I am failing in my execution. It works with all the files within the same directory but it won't also check subfolder items right now. Thanks for your help.</p>
<pre><code>#!/usr/bin/env python3
# Search and Replace all docx
import os, docx
from docx import Document
findText = input("Type text to replace: ")
#replaceText = input('What text would you like to replace it with: ')
for dirs, folders, files in os.walk('.'):
for subDirs in dirs:
print('The Sub is ' + subDirs)
for fileNames in files:
print(subDirs + fileNames)
if fileNames.endswith('.docx'):
newDirName = os.path.abspath(subDirs)
fileLocation = subDirs + '\\' + fileNames
document = docx.Document(fileLocation)
print('Document is:' + fileLocation)
tables = document.tables
for table in tables:
for row in table.rows:
for cell in row.cells:
for paragraph in cell.paragraphs:
if findText in paragraph.text:
inline = paragraph.runs
for i in range(len(inline)):
if findText in inline[i].text:
text = inline[i].text.replace(findText, '')
inline[i].text = text
for paragraph in document.paragraphs:
if findText in paragraph.text:
inline = paragraph.runs
for i in range(len(inline)):
if findText in inline[i].text:
text = inline[i].text.replace(findText, '')
inline[i].text = text
document.save(fileLocation)
</code></pre>
| 3 | 2016-10-04T00:00:54Z | 39,842,733 | <p><a href="https://docs.python.org/3/library/os.html#os.walk" rel="nofollow">os.walk</a> iterates through subdirectories yielding a 3-tuple <code>(dirpath, dirnames, filenames)</code> for each subdirectory visited. When you do:</p>
<pre><code>for dirs, folders, files in os.walk('.'):
for subDirs in dirs:
</code></pre>
<p>things go badly wrong. <code>dirs</code> is the name of the subdirectory in each iteration which means that <code>for subDirs in dirs:</code> is really enumerating the characters in the directory name. It so happens that the first directory you iterate is <code>"."</code> and just by luck its a single character directory name so your for loop appears to work.</p>
<p>As soon as you walk into another subdirectory (lets call it 'foo'), your code will try to find subdirectories called <code>foo\f</code>, <code>foo\o</code> and <code>foo\o</code> a second time. That doesn't work.</p>
<p>But you shouldn't be re-enumerating the subdirectories yourself. <code>os.walk</code> already does that. Boiling your code down to the enumeration part, this will find all of the <code>.docx</code> in the subtree.</p>
<pre><code>#!/usr/bin/env python3
import os
for dirpath, dirnames, filenames in os.walk('.'):
docx_files = [fn for fn in filenames if fn.endswith('.docx')]
for docx_file in docx_files:
filename = os.path.join(dirpath, docx_file)
print(filename)
</code></pre>
| 3 | 2016-10-04T01:06:02Z | [
"python",
"python-3.x"
]
|
Python Pillow: Add transparent gradient to an image | 39,842,286 | <p>I need to add transparent gradient to an image like on the image below , I tried this:</p>
<pre><code>def test(path):
im = Image.open(path)
if im.mode != 'RGBA':
im = im.convert('RGBA')
width, height = im.size
gradient = Image.new('L', (width, 1), color=0xFF)
for x in range(width):
gradient.putpixel((0 + x, 0), x)
alpha = gradient.resize(im.size)
im.putalpha(alpha)
im.save('out.png', 'PNG')
</code></pre>
<p>But with this I added only white gradient. How can I change color of gradient and control size of gradient.</p>
<p>I need like the following but without text.</p>
<p><a href="http://i.stack.imgur.com/4TECp.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/4TECp.jpg" alt="this"></a></p>
| 1 | 2016-10-04T00:06:48Z | 39,857,434 | <p>Your code actually does what it says it does. However, if your image background is not black but white, then the image will appear lighter. The following code merges the original image with a black image, such that you have the dark gradient effect irrespective of background.</p>
<pre><code>def test(path):
im = Image.open(path)
if im.mode != 'RGBA':
im = im.convert('RGBA')
width, height = im.size
gradient = Image.new('L', (width, 1), color=0xFF)
for x in range(width):
gradient.putpixel((x, 0), 255-x)
alpha = gradient.resize(im.size)
black_im = Image.new('RGBA', (width, height), color=0) # i.e. black
black_im.putalpha(alpha)
gradient_im = Image.alpha_composite(im, black_im)
gradient_im.save('out.png', 'PNG')
</code></pre>
<h1>EDIT</h1>
<p>There are different ways to scale the gradient. Below is one suggestion.</p>
<pre><code>def test(path, gradient_magnitude=1.):
im = Image.open(path)
if im.mode != 'RGBA':
im = im.convert('RGBA')
width, height = im.size
gradient = Image.new('L', (width, 1), color=0xFF)
for x in range(width):
# gradient.putpixel((x, 0), 255-x)
gradient.putpixel((x, 0), int(255 * (1 - gradient_magnitude * float(x)/width)))
alpha = gradient.resize(im.size)
black_im = Image.new('RGBA', (width, height), color=0) # i.e. black
black_im.putalpha(alpha)
gradient_im = Image.alpha_composite(im, black_im)
gradient_im.save('out.png', 'PNG')
</code></pre>
| 1 | 2016-10-04T16:28:23Z | [
"python",
"python-imaging-library",
"pillow"
]
|
Dataframe groupby.apply with multiple arguments pandas python | 39,842,329 | <p>I have a dataframe like the one below and i'm trying to calculate the distance between two points in multiple gps trips using a haversine formula that has 4 inputs. So basically grouping on trip_id and applying the haversine formula. </p>
<p>I had thought something like <code>df['distance'] = df.groupby('trip_id').apply(haversine, df.lng, df.lat, df.lnglag_, df.latlag_)</code> would work but I get <code>TypeError: haversine() takes 4 positional arguments but 5 were given</code>. Any ideas on what is going on here?</p>
<pre><code> latlag_ lnglag_ trip_id lat lng
0 -7.11873 113.72512 NaN NaN NaN
1 -7.11873 113.72500 17799.0 -7.11873 113.72512
2 -7.11870 113.72476 17799.0 -7.11873 113.72500
3 -7.11870 113.72457 17799.0 -7.11870 113.72476
4 -7.11874 113.72444 17799.0 -7.11870 113.72457
</code></pre>
<p>Where the haversine formula is something I got from the web.</p>
<pre><code>def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(math.radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
c = 2 * math.asin(math.sqrt(a))
km = 6367 * c
m = km/1000
return m
</code></pre>
| 0 | 2016-10-04T00:11:55Z | 39,842,388 | <p>I would use numpy vectorize method such has</p>
<pre><code>import numpy as np
np.vectorize(haversine)(df.lng, df.lat, df.lnglag_, df.latlag_)
</code></pre>
| 0 | 2016-10-04T00:20:29Z | [
"python",
"pandas"
]
|
Python: function to alter a global variable that is also parameter | 39,842,332 | <pre><code>def fxn(L):
"""
"""
global L = 2
L = 1
fxn(L)
print(L)
</code></pre>
<p>I have a function like the one above. Assume I need the function to alter the global variable from within the function so that when I print L after calling fxn(L). I end up with the 2 rather than 1. </p>
<p>Is there any way to do this? I cant use global L in the function because L is also a parameter.</p>
| 0 | 2016-10-04T00:12:05Z | 39,842,415 | <p>You should not use the same variable as global variable and the functional argument to the function using that global variable. </p>
<p>But since you have asked, you can do it using the <a href="https://docs.python.org/2/library/functions.html#globals" rel="nofollow"><code>globals()</code></a> and <a href="https://docs.python.org/2/library/functions.html#locals" rel="nofollow"><code>locals()</code></a>. Below is the sample code:</p>
<pre><code>>>> x = 5
>>> def var_test(x):
... print('GLOBAL x: ', globals()['x'])
... print('LOCAL x: ', locals()['x'])
... globals()['x'] = 111
... print('GLOBAL x: ', globals()['x'])
... print('LOCAL x: ', locals()['x'])
...
>>> var_test(20)
GLOBAL x: 5
LOCAL x: 20
GLOBAL x: 111
LOCAL x: 20
</code></pre>
| 0 | 2016-10-04T00:24:00Z | [
"python",
"function",
"global"
]
|
Python: function to alter a global variable that is also parameter | 39,842,332 | <pre><code>def fxn(L):
"""
"""
global L = 2
L = 1
fxn(L)
print(L)
</code></pre>
<p>I have a function like the one above. Assume I need the function to alter the global variable from within the function so that when I print L after calling fxn(L). I end up with the 2 rather than 1. </p>
<p>Is there any way to do this? I cant use global L in the function because L is also a parameter.</p>
| 0 | 2016-10-04T00:12:05Z | 39,842,503 | <p>This is a bad idea, but there are ways, for example:</p>
<pre><code>a = 5
def f(a):
def change_a(value):
global a
a = value
change_a(7)
f(0)
print(a) # prints 7
</code></pre>
<p>In reality, there is seldom any need for writing to global variables. And then there is little chance that the global has the same name as a variable which just cannot change the name.</p>
<p>If you are in such a situation, ask yourself <em>"am i using <code>global</code> too often?"</em></p>
| 0 | 2016-10-04T00:34:27Z | [
"python",
"function",
"global"
]
|
Django - Simple search form | 39,842,386 | <p>Using Django 1.9 with Python 3.5, I would like to make a simple search form:</p>
<p><strong>views.py</strong> </p>
<pre><code>from django.views import generic
from django.shortcuts import render
from .models import Movie, Genre
class IndexView(generic.ListView):
template_name = 'movies/index.html'
page_template = 'movies/all_movies.html'
context_object_name = 'all_movies'
model = Movie
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context.update({
'all_genres': Genre.objects.all(),
'page_title': 'Latest'
})
return context
def get_queryset(self):
query = request.GET.get('q')
if query:
return Movie.objects.filter(title__icontains=query)
else:
return Movie.objects.all()
</code></pre>
<p><strong>form</strong></p>
<pre><code><form method="GET" action="" id="searchform">
<input class="searchfield" id="searchbox" name="q" type="text" value="{{ request.GET.q }}" placeholder="Search..."/>
</form>
</code></pre>
<p>For some reason I keep getting the error: </p>
<blockquote>
<p>name 'request' is not defined</p>
</blockquote>
<p>I'm not quite sure what I'm doing wrong, any help would be appreciated.</p>
| 2 | 2016-10-04T00:20:20Z | 39,842,412 | <p>That error does not come from your template as you seem to think. It comes from your view </p>
<pre><code>def get_queryset(self):
query = request.GET.get('q')
</code></pre>
<p>It should be</p>
<pre><code> query = self.request.GET.get('q')
</code></pre>
| 1 | 2016-10-04T00:23:36Z | [
"python",
"django"
]
|
How does one use the VSCode debugger to debug a Gunicorn worker process? | 39,842,422 | <p>I have a GUnicorn/Falcon web service written in Python 3.4 on Ubuntu 14.04. I'd like to use the VSCode debugger to debug this service. I currently start the process with the command </p>
<pre><code>/usr/local/bin/gunicorn --config /webapps/connects/routerservice_config.py routerservice:api
</code></pre>
<p>which starts routerservice.py using the config file routerservice_config.py. I have workers set to 1 in the config to keep it simple.</p>
<p>I've installed the Python extension to VSCode so I have the Python debugging tools. So how do I attach to the GUnicorn worker process or have VSCode run the startup command and auto attach.</p>
<p>Thanks,
Greg</p>
| 0 | 2016-10-04T00:25:00Z | 39,848,241 | <p>I'm the author of the extension.
You could try the following:
<a href="https://github.com/DonJayamanne/pythonVSCode/wiki/Debugging:-Remote-Debuging" rel="nofollow">https://github.com/DonJayamanne/pythonVSCode/wiki/Debugging:-Remote-Debuging</a></p>
<ul>
<li>Add the following code into your routerservice_config.py (or similar python startup file)
<code>
import ptvsd
ptvsd.enable_attach("my_secret", address = ('0.0.0.0', 3000))
</code></li>
<li>Start the above application</li>
<li>Go into VS Code and then attach the debugger</li>
</ul>
<p>FYI:<br>
- This requires you to include the ptvsd package and configure it in your application.<br>
- The plan is to add the feature to attach the debugger to any python process in the future (hopefully near future). </p>
| 1 | 2016-10-04T09:03:04Z | [
"python",
"debugging",
"vscode",
"gunicorn"
]
|
How to write a python function that ShellCommand, in the Lancent library, can execute? | 39,842,481 | <p><a href="https://github.com/ioam/lancet" rel="nofollow">Lancet</a> is a Python library to explore parameter spaces. It can launch jobs, organize the output, and dissect the results.</p>
<p>I'm having trouble getting the Quickstart example, in the documentation <a href="http://ioam.github.io/lancet/" rel="nofollow">here</a>, to run. This is the code:</p>
<pre><code>import lancet
example_name = 'prime_quintuplet'
integers = lancet.Range('integer', 100, 115, steps=16, fp_precision=0)
factor_cmd = lancet.ShellCommand(executable='python factor.py', posargs=['integer'])
lancet.Launcher(example_name, integers, factor_cmd, output_directory='output')()
def load_factors(filename):
"Return output of 'factor' command as dictionary of factors."
with open(filename, 'r') as f:
factor_list = f.read().replace(':', '').split()
return dict(enumerate(int(el) for el in factor_list))
output_files = lancet.FilePattern('filename', './output/*-prime*/streams/*.o*')
output_factors = lancet.FileInfo(output_files, 'filename',
lancet.CustomFile(metadata_fn=load_factors))
primes = sorted(factors[0] for factors in output_factors.specs
if factors[0]==factors[1]) # i.e. if the input integer is the 1st factor
primes # A prime quintuplet, the closest admissable constellation of 5 primes.
</code></pre>
<p>I believe the problem is that I don't understand how the ShellCommand function works.</p>
<p>I tried writing a file named 'factor.py' and placing it in the same dirrectory as the Quickstart example.</p>
<pre><code>import argparse
def factor():
''' Returns an arbitrary list for testing. Not really a factor command'''
parser = argparse.ArgumentParser()
parser.add_argument("num1",help="Number to factor",type=int)
args = parser.parse_args()
return [args.num1, 2*args.num1, 1, 3]
</code></pre>
<p>I get the error:</p>
<pre><code>FileNotFoundError: [Errno 2] No such file or directory: 'python factor.py'
</code></pre>
<p>Thrown on the line:</p>
<pre><code>lancet.Launcher(example_name, integers, factor_cmd, output_directory='output')()
</code></pre>
<p>I'm using Python 3.4.5 in a Jupyter notebook</p>
<p>Thanks in advance for any help!</p>
| -1 | 2016-10-04T00:31:35Z | 39,877,536 | <p>I copied the example code and did not remember to change the executable name to an absolute path for factor.py.</p>
<p>On my computer it should be:</p>
<pre><code>factor_cmd = lancet.ShellCommand(executable='/Users/klm/Devel/factor.py', posargs=['integer'])
</code></pre>
| 0 | 2016-10-05T15:01:57Z | [
"python"
]
|
get index value from merged pandas time series? | 39,842,623 | <p>I have various time series pandas data frames which look like:</p>
<p>data['F_NQ'] = </p>
<p><code>OPEN HIGH LOW CLOSE VOL OI P R RINFO
DATE<br>
1996-04-10 12450 12494 12200 12275 2282 627 0 0 0
1996-04-11 12200 12360 12000 12195 1627 920 0 0 0</code></p>
<p>I merged these into one dataframe so that I could select by date using concat
<code>mergeData = pd.concat(data, axis=1, keys=data.keys())</code></p>
<p>Now I can get a slice for a chunk of time:
<code>timeSlice = mergeData.loc[startDate:endDate]</code></p>
<p>my problem is that I am looping over that timeSlice object and selecting a particular day based on the index number...</p>
<p><code>selectedDay = timeSlice.iloc[n]</code></p>
<p>I need to know the DATE for the selected row. How do I access that location value? If I provide the location value with: <code>selectedDay = timeSlice.loc[date]</code> the correct information is returned. At the time I'm making the call however I don't know the date. How do I get at that information?</p>
| 0 | 2016-10-04T00:49:51Z | 39,842,678 | <p>This helped me find the solution... <a href="http://stackoverflow.com/questions/18327624/find-elements-index-in-pandas-series">post</a></p>
<p>I basically need to call: <code>timeSlice.index[-1]</code> to get the last date from whichever time block I've selected.</p>
| 0 | 2016-10-04T00:57:31Z | [
"python",
"pandas",
"time-series"
]
|
get index value from merged pandas time series? | 39,842,623 | <p>I have various time series pandas data frames which look like:</p>
<p>data['F_NQ'] = </p>
<p><code>OPEN HIGH LOW CLOSE VOL OI P R RINFO
DATE<br>
1996-04-10 12450 12494 12200 12275 2282 627 0 0 0
1996-04-11 12200 12360 12000 12195 1627 920 0 0 0</code></p>
<p>I merged these into one dataframe so that I could select by date using concat
<code>mergeData = pd.concat(data, axis=1, keys=data.keys())</code></p>
<p>Now I can get a slice for a chunk of time:
<code>timeSlice = mergeData.loc[startDate:endDate]</code></p>
<p>my problem is that I am looping over that timeSlice object and selecting a particular day based on the index number...</p>
<p><code>selectedDay = timeSlice.iloc[n]</code></p>
<p>I need to know the DATE for the selected row. How do I access that location value? If I provide the location value with: <code>selectedDay = timeSlice.loc[date]</code> the correct information is returned. At the time I'm making the call however I don't know the date. How do I get at that information?</p>
| 0 | 2016-10-04T00:49:51Z | 39,842,686 | <p>since <code>.iloc[n]</code> return a pandas series with the index has the name, you could get the name of that series doing this :</p>
<pre><code>date = timeSlice.iloc[n].name
</code></pre>
| 0 | 2016-10-04T00:58:43Z | [
"python",
"pandas",
"time-series"
]
|
boolean expression doesn't match | 39,842,634 | <p>I having a simple issue which I don't seem to understand why,<code>force_edl</code> variable value is 'False" (its an option to my python script and user enters True or False)but the conditions <code>if force_edl == False:</code> and <code>if not force_edl</code> doesnt seem to match,how do I debug this problem?below code always goes to else part...is there way to strip bool values?</p>
<pre><code> print "force_edl " + force_edl //prints false
if force_edl == False:
#if not force_edl
print "False"
else:
print "True"
</code></pre>
| 0 | 2016-10-04T00:51:18Z | 39,842,734 | <p><strong>You cannot concatenate 'str' and 'bool'.</strong> So if this</p>
<pre><code>print "force_edl " + force_edl
</code></pre>
<p>is not giving you an error <em>then your force_edl is definitely not a bool.</em> </p>
<p>That's why <strong>your if prints True</strong>. </p>
<pre><code>force_edl = False
if force_edl == False:
print "FALSE"
else:
print "TRUE"
</code></pre>
<p>Above corrected snippet will definitely print False. </p>
<p>Do let me know if this clears your doubt. </p>
| 0 | 2016-10-04T01:06:08Z | [
"python"
]
|
boolean expression doesn't match | 39,842,634 | <p>I having a simple issue which I don't seem to understand why,<code>force_edl</code> variable value is 'False" (its an option to my python script and user enters True or False)but the conditions <code>if force_edl == False:</code> and <code>if not force_edl</code> doesnt seem to match,how do I debug this problem?below code always goes to else part...is there way to strip bool values?</p>
<pre><code> print "force_edl " + force_edl //prints false
if force_edl == False:
#if not force_edl
print "False"
else:
print "True"
</code></pre>
| 0 | 2016-10-04T00:51:18Z | 39,842,809 | <p>Try setting it to a string, int or boolean when needed. Right now your trying to use a boolean as a string which wont work.</p>
<pre><code>enter code here
force_edl = int(False)
print "force_edl " + str(force_edl)
if force_edl == False:
print "False"
else:
print "True"
</code></pre>
| 0 | 2016-10-04T01:17:48Z | [
"python"
]
|
python How to call ob1.fun1.fun2 and handle ob1.fun1 as none? | 39,842,674 | <p>I tried to use the following code, but looks like ugly</p>
<pre><code>tmp = ob1.fun1
result = None
if tmp is not None:
global result
result = tmp.fun2
</code></pre>
<p>Is there a better way to do this?</p>
| 0 | 2016-10-04T00:56:57Z | 39,842,697 | <p>Use the <a href="http://stackoverflow.com/questions/11360858/what-is-the-eafp-principle-in-python">EAFP</a> (Easier to ask for forgiveness than permission) approach. Wrap it in a try/except and handle your exception accordingly: </p>
<pre><code>result = None
try:
result = ob1.fun1.fun2
except AttributeError:
# do your exception handling here
</code></pre>
<p>You could also use <a href="https://docs.python.org/3/library/functions.html#hasattr" rel="nofollow">hasattr</a> to check if <code>fun1</code> is in <code>ob1</code></p>
<pre><code>result = None
if hasattr(ob1, 'fun1'):
res = ob1.fun1.fun2
else:
print('no fun1 found in ob1')
# or raise an Exception
</code></pre>
| 0 | 2016-10-04T00:59:47Z | [
"python"
]
|
python How to call ob1.fun1.fun2 and handle ob1.fun1 as none? | 39,842,674 | <p>I tried to use the following code, but looks like ugly</p>
<pre><code>tmp = ob1.fun1
result = None
if tmp is not None:
global result
result = tmp.fun2
</code></pre>
<p>Is there a better way to do this?</p>
| 0 | 2016-10-04T00:56:57Z | 39,842,782 | <p>If you just want <code>result</code> to be <code>None</code> if <code>ob1.fun1</code> is <code>None</code> or if <code>fun2</code> doesn't exist as an attribute, you could use <a href="https://docs.python.org/3/library/functions.html#getattr" rel="nofollow"><code>getattr</code></a> and use <code>None</code> as a default. Note that <code>getattr(None, 'attr', something)</code> will return <code>something</code>.</p>
<pre><code>result = getattr(ob1.fun1, 'fun2', None)
</code></pre>
| 1 | 2016-10-04T01:13:00Z | [
"python"
]
|
python How to call ob1.fun1.fun2 and handle ob1.fun1 as none? | 39,842,674 | <p>I tried to use the following code, but looks like ugly</p>
<pre><code>tmp = ob1.fun1
result = None
if tmp is not None:
global result
result = tmp.fun2
</code></pre>
<p>Is there a better way to do this?</p>
| 0 | 2016-10-04T00:56:57Z | 39,849,366 | <p>How about:</p>
<pre><code>if t.fun1 is not None:
result = t.fun1.fun2
else:
result = None
</code></pre>
| 0 | 2016-10-04T09:58:34Z | [
"python"
]
|
How to have a Custom User model for my app while keeping the admins working as default in Django? | 39,842,758 | <p>Here is what I am trying to accomplish: <br/></p>
<p> - Have admins login to the admin page using the default way (username and password).</p>
<p> - Have users register/login to my web app using a custom User Model which uses email instead of password. They can also have other data associated that I don't need for my admins.</p>
<p> - Separate the admin accounts and user accounts into different tables. </p>
<p></p>
<p>I checked how to create a Custom User class by extending AbstracBaseUser, but the result I got is that my admins also became the new user type. So can I have the Custom User model be used for my app users while keeping the default admin system untouched? Or what is a good alternative to my design?</p>
| 3 | 2016-10-04T01:09:12Z | 39,843,275 | <p>After couple more hours of digging, I think it is best to keep a single User model and use permissions and roles for regulations. </p>
<p>There are ways that can make multiple different user model authentications work, such as describe in here: <a href="http://stackoverflow.com/questions/3206856/how-to-have-2-different-admin-sites-in-a-django-project][1]">How to have 2 different admin sites in a Django project?</a> But I decided it wasn't worth it for my purposes.</p>
| 0 | 2016-10-04T02:30:01Z | [
"python",
"django"
]
|
How to have a Custom User model for my app while keeping the admins working as default in Django? | 39,842,758 | <p>Here is what I am trying to accomplish: <br/></p>
<p> - Have admins login to the admin page using the default way (username and password).</p>
<p> - Have users register/login to my web app using a custom User Model which uses email instead of password. They can also have other data associated that I don't need for my admins.</p>
<p> - Separate the admin accounts and user accounts into different tables. </p>
<p></p>
<p>I checked how to create a Custom User class by extending AbstracBaseUser, but the result I got is that my admins also became the new user type. So can I have the Custom User model be used for my app users while keeping the default admin system untouched? Or what is a good alternative to my design?</p>
| 3 | 2016-10-04T01:09:12Z | 39,843,324 | <p>The recommended Django practice is to create a OneToOne field pointing to the User, rather than extending the User object - this way you build on top of Django's User by decorating only the needed new model properties (for example):</p>
<pre><code>class Profile(models.Model):
user = models.OneToOneField(User,parent_link=True,blank=True,null=True)
profile_image_path = models.CharField(max_length=250,blank=True, null=True)
phone = models.CharField(max_length=250,blank=True, null=True)
address = models.ForeignKey(Address,blank=True,null=True)
is_admin = models.NullBooleanField(default=False,blank=True,null=True)
class Meta:
verbose_name = 'Profile'
verbose_name_plural = 'Profiles'
</code></pre>
| 2 | 2016-10-04T02:36:34Z | [
"python",
"django"
]
|
How can I print a webpage line by line in Python 3.x | 39,842,762 | <p>All I want to do is print the HTML text of a simple website. When I try printing, I get the text below in raw format with newline characters (<code>\n</code>) instead of actual new lines.</p>
<p><strong>This is my code:</strong></p>
<pre><code>import urllib.request
page = urllib.request.urlopen('http://www.york.ac.uk/teaching/cws/wws/webpage1.html', data = None)
pageText = page.read()
pageLines = page.readlines()
print(pageLines)
print(pageText)
</code></pre>
<p>I've tried all kinds of other stuff and discovered some stuff. When I try to index the <code>pageText</code> variable, even after converting it to a string, it does not find any <code>\n</code> character. If I try copying the raw text myself with the new lines represented as <code>\n</code> and I <code>print()</code> that, it converts the <code>\n</code> characters into actual new lines which is what I want. The problem is that I can't get that result without copying it myself.</p>
<p>To show you what I mean, here are some HTML snippets:</p>
<p><strong>Raw text:</strong></p>
<pre><code>b'<HMTL>\n<HEAD>\n<TITLE>webpage1</TITLE>\n</HEAD>\n<BODY BGCOLOR="FFFFFf" LINK="006666" ALINK="8B4513" VLINK="006666">\n
</code></pre>
<p><strong>What I want:</strong></p>
<pre><code>b'<HMTL>
<HEAD>
<TITLE>webpage1</TITLE>
</HEAD>
<BODY BGCOLOR='FFFFFf' LINK='006666' ALINK='8B4513' VLINK='006666'>
</code></pre>
<p>I also used:</p>
<pre><code>page = str(page)
lines = page.split('\n')
</code></pre>
<p>and it suprisingly did nothing.
It just printed it as one line.</p>
<p>Please, help me. I am surprised that I found nothing that worked for me. Even on forums, nothing worked.</p>
| -1 | 2016-10-04T01:09:37Z | 39,842,794 | <p>One way to do it is by using pythons requests module. You can obtain it by doing pip install requests (you may have to use sudo if you're not using a virtualenv). </p>
<pre><code>import requests
res = requests.get('http://www.york.ac.uk/teaching/cws/wws/webpage1.html')
if res.status_code == 200: # check that the request went through
# print the entire html, should maintain internal newlines so that when it print to screen it isn't on a single line
print(res.content)
#if you want to split the html into lines, use the split command like below
#lines = res.content.split('\n')
#print(lines)
</code></pre>
| 0 | 2016-10-04T01:14:24Z | [
"python",
"python-3.x",
"web"
]
|
How can I print a webpage line by line in Python 3.x | 39,842,762 | <p>All I want to do is print the HTML text of a simple website. When I try printing, I get the text below in raw format with newline characters (<code>\n</code>) instead of actual new lines.</p>
<p><strong>This is my code:</strong></p>
<pre><code>import urllib.request
page = urllib.request.urlopen('http://www.york.ac.uk/teaching/cws/wws/webpage1.html', data = None)
pageText = page.read()
pageLines = page.readlines()
print(pageLines)
print(pageText)
</code></pre>
<p>I've tried all kinds of other stuff and discovered some stuff. When I try to index the <code>pageText</code> variable, even after converting it to a string, it does not find any <code>\n</code> character. If I try copying the raw text myself with the new lines represented as <code>\n</code> and I <code>print()</code> that, it converts the <code>\n</code> characters into actual new lines which is what I want. The problem is that I can't get that result without copying it myself.</p>
<p>To show you what I mean, here are some HTML snippets:</p>
<p><strong>Raw text:</strong></p>
<pre><code>b'<HMTL>\n<HEAD>\n<TITLE>webpage1</TITLE>\n</HEAD>\n<BODY BGCOLOR="FFFFFf" LINK="006666" ALINK="8B4513" VLINK="006666">\n
</code></pre>
<p><strong>What I want:</strong></p>
<pre><code>b'<HMTL>
<HEAD>
<TITLE>webpage1</TITLE>
</HEAD>
<BODY BGCOLOR='FFFFFf' LINK='006666' ALINK='8B4513' VLINK='006666'>
</code></pre>
<p>I also used:</p>
<pre><code>page = str(page)
lines = page.split('\n')
</code></pre>
<p>and it suprisingly did nothing.
It just printed it as one line.</p>
<p>Please, help me. I am surprised that I found nothing that worked for me. Even on forums, nothing worked.</p>
| -1 | 2016-10-04T01:09:37Z | 39,863,583 | <p>Your byte string appears to have hard-coded <code>\n</code> in it. </p>
<p>For example, can't split on the value initially. </p>
<pre><code>In [1]: s = b'<HMTL>\n<HEAD>\n'
In [2]: s.split('\n')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-e85dffa8b351> in <module>()
----> 1 s.split('\n')
TypeError: a bytes-like object is required, not 'str'
</code></pre>
<p>So, you <code>str()</code> it, but that doesn't seem to work either. </p>
<pre><code>In [3]: str(s).split('\n')
Out[3]: ["b'<HMTL>\\n<HEAD>\\n'"]
</code></pre>
<p>But, if you <em>escape</em> the new lines it does somewhat work. </p>
<pre><code>In [4]: str(s).split('\\n')
Out[4]: ["b'<HMTL>", '<HEAD>', "'"]
</code></pre>
<p>You <em>could</em> use a raw string to split on </p>
<pre><code>In [5]: for line in str(s).split(r'\n'):
...: print(line)
...:
b'<HMTL>
<HEAD>
'
</code></pre>
<p>Or, if you don't want the leading <code>b</code>, you can <code>decode</code> the byte string into a string object you can then split on. </p>
<pre><code>In [9]: for line in s.decode("UTF-8").split('\n'):
...: print(line)
...:
<HMTL>
<HEAD>
</code></pre>
| 0 | 2016-10-05T00:13:11Z | [
"python",
"python-3.x",
"web"
]
|
How can I print a webpage line by line in Python 3.x | 39,842,762 | <p>All I want to do is print the HTML text of a simple website. When I try printing, I get the text below in raw format with newline characters (<code>\n</code>) instead of actual new lines.</p>
<p><strong>This is my code:</strong></p>
<pre><code>import urllib.request
page = urllib.request.urlopen('http://www.york.ac.uk/teaching/cws/wws/webpage1.html', data = None)
pageText = page.read()
pageLines = page.readlines()
print(pageLines)
print(pageText)
</code></pre>
<p>I've tried all kinds of other stuff and discovered some stuff. When I try to index the <code>pageText</code> variable, even after converting it to a string, it does not find any <code>\n</code> character. If I try copying the raw text myself with the new lines represented as <code>\n</code> and I <code>print()</code> that, it converts the <code>\n</code> characters into actual new lines which is what I want. The problem is that I can't get that result without copying it myself.</p>
<p>To show you what I mean, here are some HTML snippets:</p>
<p><strong>Raw text:</strong></p>
<pre><code>b'<HMTL>\n<HEAD>\n<TITLE>webpage1</TITLE>\n</HEAD>\n<BODY BGCOLOR="FFFFFf" LINK="006666" ALINK="8B4513" VLINK="006666">\n
</code></pre>
<p><strong>What I want:</strong></p>
<pre><code>b'<HMTL>
<HEAD>
<TITLE>webpage1</TITLE>
</HEAD>
<BODY BGCOLOR='FFFFFf' LINK='006666' ALINK='8B4513' VLINK='006666'>
</code></pre>
<p>I also used:</p>
<pre><code>page = str(page)
lines = page.split('\n')
</code></pre>
<p>and it suprisingly did nothing.
It just printed it as one line.</p>
<p>Please, help me. I am surprised that I found nothing that worked for me. Even on forums, nothing worked.</p>
| -1 | 2016-10-04T01:09:37Z | 39,868,126 | <p>Whet you have is not text but bytes. If you want text just decode it.</p>
<pre><code>b = b'<HMTL>\n<HEAD>\n<TITLE>webpage1</TITLE>\n</HEAD>\n<BODY BGCOLOR="FFFFFf" LINK="006666" ALINK="8B4513" VLINK="006666">\n'
s = b.decode() # might need to specify an encoding
print(s)
</code></pre>
<p>Output:</p>
<pre><code><HMTL>
<HEAD>
<TITLE>webpage1</TITLE>
</HEAD>
<BODY BGCOLOR="FFFFFf" LINK="006666" ALINK="8B4513" VLINK="006666">
</code></pre>
| 0 | 2016-10-05T07:42:56Z | [
"python",
"python-3.x",
"web"
]
|
More efficient way to create JSON from Python | 39,842,766 | <p>I'd like to write an API that reads from a CSV on disk (with x, y coordinates) and outputs them in JSON format to be rendered by a web front end. The issue is that there are lots of data points (order of 30k) and so going from numpy arrays of x and y into JSON is really slow.</p>
<p>This is my current function to get the data in JSON format. Is there any way to speed this up? It seems very redundant to have such a large data structure for each 2d point.</p>
<pre><code>def to_json(xdata, ydata):
data = []
for x, y in zip(xdata, ydata):
data.append({"x": x, "y": y})
return data
</code></pre>
| 1 | 2016-10-04T01:10:00Z | 39,842,777 | <p>You could use list comprehension like:</p>
<pre><code>def to_json(xdata, ydata):
return [{"x": x, "y": y} for x, y in zip(xdata, ydata)]
</code></pre>
<p>Eliminates use of unnessacary variable, and is cleaner.</p>
<p>You can also use generators like:</p>
<pre><code>def to_json(xdata, ydata):
return ({"x": x, "y": y} for x, y in zip(xdata, ydata))
</code></pre>
<p>They're created super fast and are light on the system, use little to no memory.
This last's until you do something like convert it to a list.</p>
<p>Since the objects are just x-y co-ordinates i'd use a generator object with x-y tuples - which are also created faster - like so:</p>
<pre><code>def to_json(xdata, ydata):
return ((x,y) for x, y in zip(xdata, ydata))
</code></pre>
<p>Edit: You could replace the tuples with lists <code>[]</code>, theyre valid JSON arrays.</p>
| 1 | 2016-10-04T01:12:30Z | [
"python",
"json",
"rest"
]
|
More efficient way to create JSON from Python | 39,842,766 | <p>I'd like to write an API that reads from a CSV on disk (with x, y coordinates) and outputs them in JSON format to be rendered by a web front end. The issue is that there are lots of data points (order of 30k) and so going from numpy arrays of x and y into JSON is really slow.</p>
<p>This is my current function to get the data in JSON format. Is there any way to speed this up? It seems very redundant to have such a large data structure for each 2d point.</p>
<pre><code>def to_json(xdata, ydata):
data = []
for x, y in zip(xdata, ydata):
data.append({"x": x, "y": y})
return data
</code></pre>
| 1 | 2016-10-04T01:10:00Z | 39,842,841 | <p>Your method seems reasonable enough. Here are a few changes I might make to it. The itertools module has lots of handy tools that can make your life easier. I used izip, which you can read up on <a href="https://docs.python.org/2/library/itertools.html#itertools.izip" rel="nofollow">here</a> </p>
<pre><code>import json
from itertools import izip
def to_json(xdata, ydata):
data = []
for x, y in izip(xdata, ydata): # using izip is more memory efficient
data.append({"x": x, "y": y})
return json.dumps(data) # convert that list into json
</code></pre>
| 0 | 2016-10-04T01:23:17Z | [
"python",
"json",
"rest"
]
|
Proper way to populate model with one-to-one relationship with User model - Django | 39,842,818 | <p>I am using Djangos basic User model. There are some fields that I wanted to add to the User model for my own needs. I created a new model named <code>Profile</code> and made it have a one-to-one relationship with the User model. I can now create a user and then populate the <code>Profile</code> model that is associated with that user. However, the current implementation of populating the <code>Profile</code> model seems sloppy. For a couple reasons.</p>
<ol>
<li>I first create a user and then populate the <code>Profile</code> table. If the user didn't supply certain data then the <code>Profile</code> model wont be updated. How can I make sure the user wont be created before the <code>Profile</code>?</li>
<li><p>I want to know if there is a way to make a constructor for the <code>Profile</code> model. The current way I am populating the <code>Profile</code> model is very sloppy, here is my implementation:</p>
<pre><code>class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
def create(self, validated_data):
user = User.objects.create_user(
username=validated_data['email'],
email=validated_data['email'],
)
user.set_password(validated_data['password'])
user.profile.account_email = validated_data['email']
user.profile.middle_name = validated_data['middle_name']
user.profile.initial_name = validated_data['initial_name']
user.profile.bio = validated_data['bio']
user.profile.additional = validated_data['additional']
user.save()
return user
class Meta:
model = User
</code></pre></li>
</ol>
<p>Also any suggestions on the best way to approach having an extra model to keep track of extra user information would be appreciated. </p>
| 0 | 2016-10-04T01:19:01Z | 39,843,180 | <p>You could make it a bit more concise</p>
<pre><code>def create(self, validated_data):
user = User.objects.create_user(
username=validated_data['email'],
email=validated_data['email'],
)
user.set_password(validated_data.pop('password'))
profile = UserProfile(user=user, **validated_data)
profile.save()
user.save()
return user
</code></pre>
| 0 | 2016-10-04T02:15:32Z | [
"python",
"django"
]
|
How do I call a list or object defined in another instance into another instance? | 39,842,830 | <pre><code>class Sieve:
def __init__(self, digit):
self.digit = []
numbers = [True]*digit
if digit <= -1:
raise RuntimeError("Cannot use negative values.")
numbers[0] = False
numbers[1] = False
def findPrimes(self):
for i in range(len(self.digit)):
if numbers[i]:
j = (i+i)
while (j < len(numbers)):
numbers[j] = False
j += i
print(numbers)
</code></pre>
<p>This is my first post on stackoverflow and after trying for a long time figuring out what to do and searching the internet, I'm afraid I have to ask here.
My program is supposed to find all prime numbers given any number in the initial class. I was trying to check my findPrimes(), but I was having a difficult time trying to get the values to print. I keep getting the error "numbers is not defined". Am I supposed to define it outside of findPrimes? Or is there a specific way I can call numbers from <strong>init</strong> to findPrimes? Thank you!</p>
| 0 | 2016-10-04T01:21:09Z | 39,842,856 | <p>According to your post, your functions are unindented, so they're defined outside of your class.</p>
<p>Remember python relies heavily on indenting due to the lack of things like braces.</p>
<p>Also, your variable are local to your functions, and aren't properties of your class. You need to add them to your class by prepending them with <code>self.</code> (like you did with <code>self.digit</code>).</p>
<p>so <code>self.numbers = ...</code> instead of <code>numbers = ...</code></p>
| 0 | 2016-10-04T01:24:38Z | [
"python",
"sieve"
]
|
Way to accomplish task using list comphrehension | 39,842,831 | <p>Is there a way to accomplish the following using a <code>list comprehension</code>? Or is there a more Pythonic way of accomplishing this? </p>
<pre><code>count = 0
x = 'uewoiquewqoiuinkcnsjk'
for letter in x:
if letter in ['a', 'e', 'i', 'o', 'u']:
count += 1
</code></pre>
<p>Just trying to learn the best programming practices?</p>
| 1 | 2016-10-04T01:21:13Z | 39,842,845 | <p>Use the combination of list_comprehension and len function.</p>
<pre><code>>>> x = 'uewoiquewqoiuinkcnsjk'
>>> len([i for i in x if i in 'aeiou'])
10
>>>
</code></pre>
| 4 | 2016-10-04T01:23:52Z | [
"python",
"list-comprehension"
]
|
Way to accomplish task using list comphrehension | 39,842,831 | <p>Is there a way to accomplish the following using a <code>list comprehension</code>? Or is there a more Pythonic way of accomplishing this? </p>
<pre><code>count = 0
x = 'uewoiquewqoiuinkcnsjk'
for letter in x:
if letter in ['a', 'e', 'i', 'o', 'u']:
count += 1
</code></pre>
<p>Just trying to learn the best programming practices?</p>
| 1 | 2016-10-04T01:21:13Z | 39,842,875 | <p>Since <code>in</code> generates a <code>True</code> or <code>False</code> and <code>True</code> and <code>False</code> <a href="http://legacy.python.org/dev/peps/pep-0285/" rel="nofollow">can reliably be used</a> as <code>1</code> and <code>0</code> you can use <code>sum</code> with a generator:</p>
<pre><code>sum(c in 'aeiou' for c in x)
</code></pre>
<p>Or filter + len:</p>
<pre><code>len(filter(lambda c: c in 'aeiou', x))
</code></pre>
<p>A great way to do the <em>opposite</em> is to use str.translate to delete characters in the string:</p>
<pre><code>>>> x.translate(None, 'aeiou')
wqwqnkcnsjk
</code></pre>
<p>So then you can do:</p>
<pre><code>len(x)-len(x.translate(None, 'aeiou'))
</code></pre>
<p>In all cases, the answer is <code>10</code></p>
| 4 | 2016-10-04T01:27:30Z | [
"python",
"list-comprehension"
]
|
Python Leibniz summation | 39,842,873 | <p><a href="http://i.stack.imgur.com/baHSG.png" rel="nofollow">Leibniz summation</a></p>
<p>I'm trying to get leibniz summation with python, but, with my code, I'm getting slightly different value. I can't find why it's not giving me the right answer.</p>
<pre><code>import math
def estimate_pi( iterations ):
pi = 0.0
for n in range(0,iterations+1):
pi = pi + (math.pow(-1,n)/((2*n)+1))
return pi
print("How many iterations?")
print(estimate_pi(int(input())))
</code></pre>
| 1 | 2016-10-04T01:27:00Z | 39,842,962 | <p>The summation does not estimate <code>pi</code>, it estimates <code>pi/4</code>. So change the code to something like:</p>
<pre><code>def estimate_pi( iterations ):
sum = 0.0
for n in range(iterations):
sum += (math.pow(-1,n)/((2*n)+1))
# sum now estimates pi/4, so return sum * 4 ~ (pi/4) * 4 ~ pi
return (sum * 4)
print estimate_pi(100000)
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>3.14158265359
</code></pre>
| 1 | 2016-10-04T01:40:35Z | [
"python"
]
|
Extracting pdf attachment from IMAP account -- python 3.5.2 | 39,842,902 | <p>Ok, so I'm trying to save pdf attachments sent to a specific account to a specific network folder but I'm stuck at the attachment part. I've got the following code to pull in the unseen messages, but I'm not sure how to get the "parts" to stay intact. I think I can maybe figure this out if I can figure out how to keep the email message complete. I never make it past "Made it to walk" output. All testing emails in this account include pdf attachments. Thanks in advance. </p>
<pre><code>import imaplib
import email
import regex
import re
user = 'some_user'
password = 'gimmeAllyerMoney'
server = imaplib.IMAP4_SSL('mail.itsstillmonday.com', '993')
server.login(user, password)
server.select('inbox')
msg_ids=[]
resp, messages = server.search(None, 'UNSEEN')
for message in messages[0].split():
typ, data = server.fetch(message, '(RFC822)')
msg= email.message_from_string(str(data[0][1]))
#looking for 'Content-Type: application/pdf
for part in msg.walk():
print("Made it to walk")
if part.is_multipart():
print("made it to multipart")
if part.get_content_maintype() == 'application/pdf':
print("made it to content")
</code></pre>
| 0 | 2016-10-04T01:30:59Z | 39,843,526 | <p>You can use part.get_content_type() to get the full content type and part.get_payload() to get the payload as follows:
</p>
<pre><code>for part in msg.walk():
if part.get_content_type() == 'application/pdf':
# When decode=True, get_payload will return None if part.is_multipart()
# and the decoded content otherwise.
payload = part.get_payload(decode=True)
# Default filename can be passed as an argument to get_filename()
filename = part.get_filename()
# Save the file.
if payload and filename:
with open(filename, 'wb') as f:
f.write(payload)
</code></pre>
<p>Note that as tripleee pointed out, for a part with content type "application/pdf" you have:</p>
<pre><code>>>> part.get_content_type()
"application/pdf"
>>> part.get_content_maintype()
"application"
>>> part.get_content_subtype()
"pdf"
</code></pre>
| 0 | 2016-10-04T03:04:52Z | [
"python",
"email",
"imap"
]
|
Creating 2 strings out of 1 recursively | 39,842,918 | <p>I'm trying to write a program that takes a string(stringg) apart and creates 1 string with all uppercase letters in stringg and 1 string with all lowercase letters in stringg. </p>
<p>result should be something like this:</p>
<pre><code>split_rec('HsaIm') = ('HI', 'sam')
</code></pre>
<p>This is how I have tried to write it recursively.</p>
<pre><code>def split_rec(stringg):
if not stringg:
return ('')
elif stringg[0].isupper() == True and stringg[0].isalpha() == True:
return stringg[0] + split_rec(stringg[1:]), split_rec(stringg[1:])
elif stringg[0].isupper() == False and stringg[0].isalpha() == True:
return split_rec(stringg[1:]), stringg[0] + split_rec(stringg[1:])
</code></pre>
<p>But when I try it I get the error code "Can't convert 'tuple' object to str implicitly". Any kind of help is appreciated.</p>
| 0 | 2016-10-04T01:33:38Z | 39,843,006 | <p>There is issue with you recursion logic and it can easily be done without recursion like:</p>
<pre><code>def split_rec(stringg):
alphas = [x for x in stringg if x.isalpha()]
lower = [x for x in alphas if not x.isupper() ]
upper = [x for x in alphas if x.isupper() ]
return (''.join(upper), ''.join(lower))
</code></pre>
| 0 | 2016-10-04T01:46:52Z | [
"python",
"string",
"tuples"
]
|
Creating 2 strings out of 1 recursively | 39,842,918 | <p>I'm trying to write a program that takes a string(stringg) apart and creates 1 string with all uppercase letters in stringg and 1 string with all lowercase letters in stringg. </p>
<p>result should be something like this:</p>
<pre><code>split_rec('HsaIm') = ('HI', 'sam')
</code></pre>
<p>This is how I have tried to write it recursively.</p>
<pre><code>def split_rec(stringg):
if not stringg:
return ('')
elif stringg[0].isupper() == True and stringg[0].isalpha() == True:
return stringg[0] + split_rec(stringg[1:]), split_rec(stringg[1:])
elif stringg[0].isupper() == False and stringg[0].isalpha() == True:
return split_rec(stringg[1:]), stringg[0] + split_rec(stringg[1:])
</code></pre>
<p>But when I try it I get the error code "Can't convert 'tuple' object to str implicitly". Any kind of help is appreciated.</p>
| 0 | 2016-10-04T01:33:38Z | 39,843,013 | <p>First avoid test like so:</p>
<pre><code>if condition == True:
</code></pre>
<p>and write simply</p>
<pre><code>if condition:
</code></pre>
<p>Then you need to return a tuple and access the result as a tuple in all cases:</p>
<pre><code>def split_rec(stringg):
if not stringg:
return ('','')
else:
first = stringg[0]
assert first.isalpha(), "The string contains invalid characters."
upper, lower = split_rec(stringg[1:])
if first.isupper():
return first + upper, lower
else:
return upper, first + lower
</code></pre>
| 1 | 2016-10-04T01:48:32Z | [
"python",
"string",
"tuples"
]
|
Creating 2 strings out of 1 recursively | 39,842,918 | <p>I'm trying to write a program that takes a string(stringg) apart and creates 1 string with all uppercase letters in stringg and 1 string with all lowercase letters in stringg. </p>
<p>result should be something like this:</p>
<pre><code>split_rec('HsaIm') = ('HI', 'sam')
</code></pre>
<p>This is how I have tried to write it recursively.</p>
<pre><code>def split_rec(stringg):
if not stringg:
return ('')
elif stringg[0].isupper() == True and stringg[0].isalpha() == True:
return stringg[0] + split_rec(stringg[1:]), split_rec(stringg[1:])
elif stringg[0].isupper() == False and stringg[0].isalpha() == True:
return split_rec(stringg[1:]), stringg[0] + split_rec(stringg[1:])
</code></pre>
<p>But when I try it I get the error code "Can't convert 'tuple' object to str implicitly". Any kind of help is appreciated.</p>
| 0 | 2016-10-04T01:33:38Z | 39,843,148 | <pre><code>split_rec = lambda x: tuple(map(''.join, zip(*[(a,'') if a.isupper() else ('',a) for a in x if a.isalpha()])))
>>> split_rec('HsaIm')
('HI', 'sam')
</code></pre>
<p>This takes your string and sorts each letter as upper or lower case by putting it on the right or left side of a tuple. Then it unzips the tuples (using <code>zip(*[...])</code>), applies a <code>join</code> function to each to make them back into strings and then makes the whole thing a tuple again.</p>
<p>Just in case you needed a one-line solution </p>
| 1 | 2016-10-04T02:09:19Z | [
"python",
"string",
"tuples"
]
|
Python / pandas - SettingWithCopyWarning using DatetimeIndex().day | 39,842,955 | <p>I have code given the SettingWithCopy Warning and I can't figure out to recode it properly. </p>
<pre><code>dataframe['day'] = pandas.DatetimeIndex(dataframe['date_time']).day
</code></pre>
<p>I am trying to make columns in the original dataframe holidng the day, year, etc.</p>
| -1 | 2016-10-04T01:40:01Z | 39,842,994 | <p>you can do this simply by calling day:</p>
<pre><code>df['day'] = df['date_time'].day
</code></pre>
<p>but I doubt this where the warning is coming from.</p>
| 0 | 2016-10-04T01:45:07Z | [
"python",
"pandas"
]
|
Python / pandas - SettingWithCopyWarning using DatetimeIndex().day | 39,842,955 | <p>I have code given the SettingWithCopy Warning and I can't figure out to recode it properly. </p>
<pre><code>dataframe['day'] = pandas.DatetimeIndex(dataframe['date_time']).day
</code></pre>
<p>I am trying to make columns in the original dataframe holidng the day, year, etc.</p>
| -1 | 2016-10-04T01:40:01Z | 39,847,895 | <p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.day.html" rel="nofollow"><code>Series.dt.day</code></a>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.year.html" rel="nofollow"><code>Series.dt.year</code></a>:</p>
<pre><code>df['day'] = df['date_time'].dt.day
df['year'] = df['date_time'].dt.year
</code></pre>
| 0 | 2016-10-04T08:46:17Z | [
"python",
"pandas"
]
|
How can I convert a vector in string form to tuple form with each vector component being a tuple element? | 39,842,959 | <p>I'm writing a Python script to parse an XML file. When I get to the following part of the XML file,</p>
<pre><code> <H.1>
(1.00000000000000, 0.000000000000000E+000)
</H.1>
</code></pre>
<p>the script uses the following to parse the text</p>
<pre><code> H1 = H.find('H.1')
tokens = H1.text.split()
</code></pre>
<p>This produces a list named tokens with the single string element '(1.00000000000000,0.000000000000000E+000)'. How can I make it so that what is produced is a tuple with first element 1.00000000000000 and second element 0.000000000000000E+000? Or, at least, how can I convert the vector from string form to two-element tuple form?</p>
| 0 | 2016-10-04T01:40:31Z | 39,842,998 | <p>You can use <a href="https://docs.python.org/3/library/ast.html#ast.literal_eval" rel="nofollow">literal_eval</a> from <a href="https://docs.python.org/3/library/ast.html" rel="nofollow">ast</a>:</p>
<pre><code>>>> s = '(1.00000000000000,0.000000000000000E+000)'
>>> from ast import literal_eval
>>> t = literal_eval(s)
>>> t
(1.0, 0.0)
>>> type(t[0])
<type 'float'>
>>> print(type(t))
<type 'tuple'>
</code></pre>
| 1 | 2016-10-04T01:45:41Z | [
"python",
"xml",
"list",
"vector"
]
|
Creating a triangle of characters from a users input | 39,843,022 | <p>For an assignment I'm suppose to make a triangle using the users input if the characters are equal to an even number. The triangle is suppose to print up to 5 lines in height and the left of it should be the left half of the string and the right side of the triangle should be the right side of the string. </p>
<p><a href="http://i.stack.imgur.com/zM10K.png" rel="nofollow">Example of what the triangle is suppose to look like</a></p>
<p>The problem is I can't figure out how to divide my triangle in half without hard coding it or how to properly display the white space without a loop (were not allowed to in the assignment). Right now if I were to put in "ab" it would return:</p>
<pre><code> aabb
aabbaabb
aabbaabbaabb
aabbaabbaabbaabb
aabbaabbaabbaabbaabb
</code></pre>
<p>Instead of:</p>
<pre><code> aabb
aaaabbbb
aaaaaabbbbbb
aaaaaaaabbbbbbbb
aaaaaaaaaabbbbbbbbbb
</code></pre>
<p>Here's my code: </p>
<pre><code>#GET Users String
userString = input("Please enter a string with a value of 7 or less characters: ")
#CALCULATE IF userString is less than or equal to 7 and is even
if len(userString) <= 7 and len(userString) % 2 == 0:
print (" " * 5 + userString)
print(" " * 4 + userString * 2)
print(" " * 3 + userString * 3)
print(" " * 2 + userString * 4)
print(" " + userString * 5)
#CALCULATE IF userString is less than 7 but and off
elif len(userString) <=7 and len(userString) % 2 == 1:
print("You are odd")
#CALCULATE IF userString is over 7 characters
else:
print ('The string is too long. \nGood-bye!')
</code></pre>
| 0 | 2016-10-04T01:49:28Z | 39,843,234 | <p>Here's how you can do this:</p>
<pre><code>def print_next(st, index):
if index < 6: # have not reached 5 - print offset and string
offset = 6-index
print ' '*offset+st
index=index+1 # increase counter
print_next((st[0:2]+st[-2:len(st)])*index,index) # recursively go next
print_next('aabb',1) # initial call with index set to 1
</code></pre>
| 2 | 2016-10-04T02:24:56Z | [
"python"
]
|
Creating a triangle of characters from a users input | 39,843,022 | <p>For an assignment I'm suppose to make a triangle using the users input if the characters are equal to an even number. The triangle is suppose to print up to 5 lines in height and the left of it should be the left half of the string and the right side of the triangle should be the right side of the string. </p>
<p><a href="http://i.stack.imgur.com/zM10K.png" rel="nofollow">Example of what the triangle is suppose to look like</a></p>
<p>The problem is I can't figure out how to divide my triangle in half without hard coding it or how to properly display the white space without a loop (were not allowed to in the assignment). Right now if I were to put in "ab" it would return:</p>
<pre><code> aabb
aabbaabb
aabbaabbaabb
aabbaabbaabbaabb
aabbaabbaabbaabbaabb
</code></pre>
<p>Instead of:</p>
<pre><code> aabb
aaaabbbb
aaaaaabbbbbb
aaaaaaaabbbbbbbb
aaaaaaaaaabbbbbbbbbb
</code></pre>
<p>Here's my code: </p>
<pre><code>#GET Users String
userString = input("Please enter a string with a value of 7 or less characters: ")
#CALCULATE IF userString is less than or equal to 7 and is even
if len(userString) <= 7 and len(userString) % 2 == 0:
print (" " * 5 + userString)
print(" " * 4 + userString * 2)
print(" " * 3 + userString * 3)
print(" " * 2 + userString * 4)
print(" " + userString * 5)
#CALCULATE IF userString is less than 7 but and off
elif len(userString) <=7 and len(userString) % 2 == 1:
print("You are odd")
#CALCULATE IF userString is over 7 characters
else:
print ('The string is too long. \nGood-bye!')
</code></pre>
| 0 | 2016-10-04T01:49:28Z | 39,843,359 | <p>I think you can use a stack to save each line so you can easily get a triangle-like output. Also because you can't use loop so my suggestion would be recursive.</p>
<pre><code>public_stack = []
def my_func(original_str, line_count, space_num):
if(line_count == 0):
return
times = line_count * 2
half_length = len(original_str) / 2
left_str = original_str[:half_length] * times
right_str = original_str[half_length:] * times
space_str = ' ' * space_num
complete_str = space_str + left_str + right_str
global public_stack
public_stack.append(complete_str)
space_num += len(original_str)
line_count -= 1
return my_func(original_str,line_count,space_num)
if __name__ == '__main__':
original_str = 'ab'
line_count = 5
space_num = 0
my_func(original_str,line_count,space_num)
global public_stack
for i in range(len(public_stack)):
line = public_stack.pop()
print line
</code></pre>
| 0 | 2016-10-04T02:41:33Z | [
"python"
]
|
Having an issue with Python's unittest | 39,843,124 | <p>I am learning Python and trying to test a Polynomial class I wrote using unittest. It seems like I am getting different results from directly running a test in Python and running a test using unittest and I don't understand what's going on.</p>
<pre><code>import unittest
from w4_polynomial import Polynomial
class TestPolynomialClass(unittest.TestCase):
def setUp(self):
self.A = Polynomial()
self.A[1] = 1
self.A[2] = 2
self.B = Polynomial()
self.B[1234] = 5678
def test_assertNotEq(self):
self.C = Polynomial()
self.C[1234] = 5678
self.C[1] = 1
self.C[2] = 3
self.assertNotEqual(self.A+self.B, self.C)
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>Unittest fails... but I don't understand why. The two polynomials aren't the same. Here are the results from the same test done in a python script using print to compare. The polynomial is different, but same results:</p>
<pre><code>A+B = 442x^123 + 12x^6 + 12x^4 + 5x^1 + 0x^0 + -99x^-12
C = 442x^123 + 12x^6 + 12x^4 + 5x^1 + 0x^0 + 99x^-12
A+B==C is False
</code></pre>
<p>Any help explaining what's going on would be greatly appreciated. </p>
<p>Sorry forgot the error from unittest,</p>
<pre><code> FAIL: test_assertEq (__main__.TestPolynomialClass)
----------------------------------------------------------------------
Traenter code hereceback (most recent call last):
File "add.py", line 18, in test_assertEq
self.assertNotEqual(self.A+self.B, self.C)
AssertionError: <w4_polynomial.Polynomial object at 0x7f2d419ec390> == <w4_polynomial.Polynomial object at 0x7f2d419ec358>
</code></pre>
<p>And now the Polynomial Class:</p>
<pre><code>class Polynomial():
def __init__(self, value=[0]):
self.v = []
self.n = []
temp = list(reversed(value[:]))
if value == [0]:
self[0] = 0
else:
for x in range(0, len(temp)):
self[x] = temp[x]
#self.__compress()
...
def __eq__(self, value):
temp1 = self.v[:]
temp2 = self.n[:]
temp3 = value.v[:]
temp4 = value.n[:]
temp1.sort()
temp2.sort()
temp3.sort()
temp4.sort()
return (temp1 == temp3 and temp2 == temp4)
def __ne__(self, value):
temp1 = self.v[:]
temp2 = self.n[:]
temp3 = value.v[:]
temp4 = value.n[:]
temp1.sort()
temp2.sort()
temp3.sort()
temp4.sort()
return (temp1 != temp3 and temp2 != temp4)
...
def main():
pass
if __name__=="__main__":
main()
</code></pre>
| 1 | 2016-10-04T02:04:33Z | 39,846,639 | <p>I think the issue is with the implementation with <code>def __ne__</code> function in Polynomial class.
assertNotEqual when called, expects a True value when the values passed are not equal. But in this class, you are directly sending the output of temp1 != temp3 and temp2 != temp4.</p>
<p>So, the function should be like this </p>
<blockquote>
<pre><code>def __ne__(self, value):
temp1 = self.v[:]
temp2 = self.n[:]
temp3 = value.v[:]
temp4 = value.n[:]
temp1.sort()
temp2.sort()
temp3.sort()
temp4.sort()
result = True if not (temp1 != temp3 and temp2 != temp4) else False
return result
</code></pre>
</blockquote>
| 0 | 2016-10-04T07:33:14Z | [
"python",
"unit-testing",
"python-3.x",
"python-unittest"
]
|
Google Cloud Endpoints: Endpoint Request Parameters (Resource Containers) Empty when Deployed | 39,843,178 | <p>I have an app for Google App Engine. The backend uses Python and the front-end uses JavaScript. The app works as expected locally and the API Explorer works as expected when deployed.</p>
<p>However, the API does not work with the front-end as expected when deployed. The issue is that the cloud endpoint methods that take arguments ("Resource Containers") from requests receive "empty" requests -- the arguments given to the requests from the JavaScript front-end disappear.</p>
<p>Here is an example.</p>
<p>JavaScript API call:</p>
<pre><code>var id_resource = {'resource': {'user_google_id': "-1"}};
gapi.client.word_match.get_user_from_google_id(id_resource).execute(function(resp) {
console.log(resp); // THE API CALL 'LOSES' THE 'user_google_id' WHEN DEPLOYED: THIS LOGS AN ERROR ("Object {code: 404, data: Array[1], message: "No user with the id "None" exists.", error: Object}") WHEN DEPLOYED, BUT LOGS THE CORRECT USER INFO LOCALLY
if (!resp.code) {
self.user(new User(resp));
}
});
</code></pre>
<p>Cloud endpoint:</p>
<pre><code>REQUEST_BY_GOOGLE_ID = endpoints.ResourceContainer(user_google_id=messages.StringField(1),)
@endpoints.api(name='word_match', version='v1', allowed_client_ids=['the id'],
auth_level=endpoints.AUTH_LEVEL.OPTIONAL_CONTINUE)
class WordMatchApi(remote.Service):
"""Game API
"""
@endpoints.method(request_message=REQUEST_BY_GOOGLE_ID,
response_message=UserForm,
path='getuser',
name='get_user_from_google_id',
http_method='POST')
def get_user_from_google_id(self, request):
"""Get a user by the user's google account ID
"""
logging.info(request) // THIS IS THE ISSUE: LOGS "<CombinedContainer> user_google_id: u'-1'>" locally, but just "<CombinedContainer>" when deployed.
logging.info(request.user_google_id)
user = User.query(User.google_id == request.user_google_id).get()
if not user:
message = 'No user with the id "%s" exists.' % request.user_google_id
raise endpoints.NotFoundException(message)
return user.to_form()
</code></pre>
<p>Where did the user_google_id go in the request when deployed? Why does Python think there is nothing there?</p>
| 0 | 2016-10-04T02:15:08Z | 39,844,060 | <p>I got it working. The main fix was based on <a href="https://cloud.google.com/appengine/docs/python/endpoints/create_api" rel="nofollow">this documentation</a>. I "defined a message class that has all the arguments that will be passed in the request body", then defined the resource container used in the request message to include that class.</p>
| 0 | 2016-10-04T04:13:32Z | [
"javascript",
"python",
"google-app-engine",
"google-cloud-endpoints"
]
|
Command line arguments not being passed in sbatch | 39,843,230 | <p>I am trying to submit a job using the SLURM job scheduler and am finding that when I use the <code>--export=VAR=VALUE</code> syntax then some of my variables are not being passed (often the variable in the first instance of <code>export</code>). My understanding is that I need to specify <code>--export=...</code> for each variable, e.g.</p>
<pre><code>sbatch --export=build=true --export=param=p100_256 run.py
</code></pre>
<p>My script "run.py" looks like this:</p>
<pre><code>#! /usr/bin/env python
import os,fnmatch
print(os.environ["SLURM_JOB_NAME"])
print(os.environ["SLURM_JOB_ID"])
print(fnmatch.filter(os.environ.keys(),"b*"))
print(fnmatch.filter(os.environ.keys(),"p*"))
</code></pre>
<p>I'd prefer to submit a python script as all of my existing scripts (used previously with PBS) are already in python and I don't want to have to rewrite them in shell scripts. My problem is best demonstrated through a short example. </p>
<p>Firstly,</p>
<pre><code>> sbatch --export=build=true --export=param=p100_256 run.py
> Submitted batch job 2249581
</code></pre>
<p>produces a log file with the following:</p>
<pre><code>run.py
2249581
[]
['param']
</code></pre>
<p>If I reverse the order of the <code>export</code> flags for 'build' and 'param',</p>
<pre><code>> sbatch --export=param=true --export=build=p100_256 run.py
> Submitted batch job 2249613
</code></pre>
<p>then the log file now looks like,</p>
<pre><code>run.py
2249613
['build']
[]
</code></pre>
<p>which would suggest that only the final instance of the <code>export</code> flag is being passed. If I add in a third instance of <code>export</code>,</p>
<pre><code> > sbatch --export=param=1 --export=build=p100_256 --export=build_again=hello run.py
> Submitted batch job 2249674
</code></pre>
<p>then the log file returns,</p>
<pre><code>run.py
2249674
['build_again']
[]
</code></pre>
<p>So does anybody know why only the final instance of <code>export</code> is being passed? Have I got the syntax incorrect? Do I need to specify an additional flag?</p>
<p>Thanks!</p>
| 0 | 2016-10-04T02:24:27Z | 39,843,397 | <p>Yes, looks like I had the syntax incorrect. I missed in the documentation that additional variables should be comma separated and specified with a single <code>export</code> flag, e.g.</p>
<pre><code>> sbatch --export=build=true,param=p100_256 run.py
</code></pre>
<p>So previous instances of <code>export</code> must be being replaced each time <code>export</code> is specified.</p>
| 0 | 2016-10-04T02:47:38Z | [
"python",
"command-line-arguments",
"slurm"
]
|
Pandas remove rows which any string | 39,843,279 | <p>A very basic qs guys - thans vm for taking a look. I want to remove rows in <code>Col1</code> which contain any string - care about only numeric values in <code>Col1</code>.</p>
<p>Input:</p>
<pre><code> Col1 Col2 Col3
0 123 48.0 ABC
1 45 85.0 DEF
2 A.789 66.0 PQR
3 RN.35 9.0 PQR
4 LMO 12.0 ABC
</code></pre>
<p>Output:</p>
<pre><code> Col1 Col2 Col3
0 123.0 48.0 ABC
1 45.0 85.0 DEF
</code></pre>
<p>I tried </p>
<pre><code>test = input_[input_['Col1'].str.contains(r'ABCDEGGHIJKLMNOPQRSTUVWXYZ.')]
</code></pre>
<p>But see this error</p>
<blockquote>
<p>ValueError: cannot index with vector containing NA / NaN values</p>
</blockquote>
<p>Could you:</p>
<ul>
<li>Give a short explanation as to why that's not working?</li>
<li>What would be the alternate solution pls?</li>
</ul>
| 1 | 2016-10-04T02:30:27Z | 39,843,374 | <p>do like this:</p>
<pre><code>import re
regex = re.compile("[a-zA-Z]+")
df.ix[df.col1.map(lambda x: regex.search(x) is None)]
</code></pre>
| 4 | 2016-10-04T02:43:47Z | [
"python",
"string",
"pandas",
"indexing",
"numeric"
]
|
Pandas remove rows which any string | 39,843,279 | <p>A very basic qs guys - thans vm for taking a look. I want to remove rows in <code>Col1</code> which contain any string - care about only numeric values in <code>Col1</code>.</p>
<p>Input:</p>
<pre><code> Col1 Col2 Col3
0 123 48.0 ABC
1 45 85.0 DEF
2 A.789 66.0 PQR
3 RN.35 9.0 PQR
4 LMO 12.0 ABC
</code></pre>
<p>Output:</p>
<pre><code> Col1 Col2 Col3
0 123.0 48.0 ABC
1 45.0 85.0 DEF
</code></pre>
<p>I tried </p>
<pre><code>test = input_[input_['Col1'].str.contains(r'ABCDEGGHIJKLMNOPQRSTUVWXYZ.')]
</code></pre>
<p>But see this error</p>
<blockquote>
<p>ValueError: cannot index with vector containing NA / NaN values</p>
</blockquote>
<p>Could you:</p>
<ul>
<li>Give a short explanation as to why that's not working?</li>
<li>What would be the alternate solution pls?</li>
</ul>
| 1 | 2016-10-04T02:30:27Z | 39,844,743 | <p>Another faster solution with <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> and condition with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html" rel="nofollow"><code>to_numeric</code></a> where parameter <code>errors='coerce'</code> means if data are not numeric are converted to <code>NaN</code> - so you need find all not <code>NaN</code> data by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.notnull.html" rel="nofollow"><code>notnull</code></a>:</p>
<pre><code>print (pd.to_numeric(df.Col1, errors='coerce'))
0 123.0
1 45.0
2 NaN
3 NaN
4 NaN
Name: Col1, dtype: float64
print (pd.to_numeric(df.Col1, errors='coerce').notnull())
0 True
1 True
2 False
3 False
4 False
Name: Col1, dtype: bool
df = df[pd.to_numeric(df.Col1, errors='coerce').notnull()]
print (df)
Col1 Col2 Col3
0 123 48.0 ABC
1 45 85.0 DEF
</code></pre>
<p><strong>Timings</strong>:</p>
<pre><code>#[100000 rows x 3 columns]
df = pd.concat([df]*10000).reset_index(drop=True)
In [16]: %timeit (df.ix[df.Col1.map(lambda x: re.compile("[a-zA-Z]+").search(x) is None)])
10 loops, best of 3: 57.7 ms per loop
In [17]: %timeit (df[pd.to_numeric(df.Col1, errors='coerce').notnull()])
10 loops, best of 3: 22 ms per loop
In [18]: %timeit (df[~df['Col1'].astype(str).str.contains(r'[ABCDEGGHIJKLMNOPQRSTUVWXYZ.]', na=False)])
10 loops, best of 3: 38.8 ms per loop
</code></pre>
<hr>
<p>Your solution:</p>
<p>I think you need cast to <code>str</code> by <code>astype</code> and then add <code>[]</code> <a href="https://docs.python.org/2/library/re.html" rel="nofollow">used to indicate a set of characters</a> and last add parameter <code>na=False</code> because it seems some <code>NaN</code> value are in <code>col1</code> and then are converted to <code>False</code>:</p>
<pre><code>print (df['Col1'].astype(str).str.contains(r'[ABCDEGGHIJKLMNOPQRSTUVWXYZ.]', na=False))
0 False
1 False
2 True
3 True
4 True
Name: Col1, dtype: bool
</code></pre>
<p>Then need invert boolean mask by <code>~</code> and use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p>
<pre><code>print (df[~df['Col1'].astype(str).str.contains(r'[ABCDEGGHIJKLMNOPQRSTUVWXYZ.]', na=False)])
Col1 Col2 Col3
0 123 48.0 ABC
1 45 85.0 DEF
</code></pre>
| 1 | 2016-10-04T05:26:53Z | [
"python",
"string",
"pandas",
"indexing",
"numeric"
]
|
python/django: deployment to heroku fails | 39,843,305 | <p>I am trying to deploy an app to heroku.
It's a python/django app, and it runs fine on my local machine.</p>
<p>When deploying, heroku downloads the packages defined in requirements.txt, but then stops complaining about <code>qpython</code> not being able to be built, because it can't find <code>numpy</code>. But from the log output it's visible that <code>numpy</code> is being downloaded, and installed BEFORE qpython.</p>
<p>The only thing I could think of is that the logs actually say
"Collecting" and "Downloading", but not explicitly "Installing"...Could it be that the way heroku handles this causes qpython to be built before numpy is being installed? It's a weird assumption but the only one I could think of. In any case, I don't and would not know what to do.</p>
<p>I defined python to be python 2.7.12 in runtime.txt.</p>
<pre><code>$ git push heroku-dev django6_12:master
Counting objects: 21, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (20/20), done.
Writing objects: 100% (21/21), 1.99 KiB | 0 bytes/s, done.
Total 21 (delta 16), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
/*...more output omitted for brevity */
remote: -----> Python app detected
remote: -----> Installing python-2.7.12
remote: -----> Noticed cffi. Bootstrapping libffi.
remote: $ pip install -r requirements.txt
/*...more output omitted for brevity */
remote: Collecting nodeenv==0.7.2 (from -r requirements.txt (line 36))
remote: Downloading nodeenv-0.7.2.tar.gz
remote: Collecting numpy==1.8.1 (from -r requirements.txt (line 37))
remote: Downloading numpy-1.8.1-cp27-cp27m-manylinux1_x86_64.whl (14.6MB)
remote: Collecting pandas==0.14.0 (from -r requirements.txt (line 38))
remote: Downloading pandas-0.14.0.zip (7.3MB)
/*...more output omitted for brevity
**Note how numpy is being installed** */
remote: Collecting qpython==1.0.0 (from -r requirements.txt (line 112))
remote: Downloading qPython-1.0.0.zip (75kB)
remote: Complete output from command python setup.py egg_info:
remote: Traceback (most recent call last):
remote: File "<string>", line 1, in <module>
remote: File "/tmp/pip-build-NoEaTG/qpython/setup.py", line 19, in <module>
remote: import numpy
remote: ImportError: No module named numpy
remote:
remote: ----------------------------------------
remote: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-NoEaTG/qpython/
remote: ! Push rejected, failed to compile Python app.
$ git push heroku-dev django6_12:master
Counting objects: 21, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (20/20), done.
Writing objects: 100% (21/21), 1.99 KiB | 0 bytes/s, done.
Total 21 (delta 16), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
/*...more output omitted for brevity */
remote: -----> Python app detected
remote: -----> Installing python-2.7.12
remote: -----> Noticed cffi. Bootstrapping libffi.
remote: $ pip install -r requirements.txt
/*...more output omitted for brevity */
remote: Collecting nodeenv==0.7.2 (from -r requirements.txt (line 36))
remote: Downloading nodeenv-0.7.2.tar.gz
remote: Collecting numpy==1.8.1 (from -r requirements.txt (line 37))
remote: Downloading numpy-1.8.1-cp27-cp27m-manylinux1_x86_64.whl (14.6MB)
remote: Collecting pandas==0.14.0 (from -r requirements.txt (line 38))
remote: Downloading pandas-0.14.0.zip (7.3MB)
/*...more output omitted for brevity
**Note how numpy is being installed** */
remote: Collecting qpython==1.0.0 (from -r requirements.txt (line 112))
remote: Downloading qPython-1.0.0.zip (75kB)
remote: Complete output from command python setup.py egg_info:
remote: Traceback (most recent call last):
remote: File "<string>", line 1, in <module>
remote: File "/tmp/pip-build-NoEaTG/qpython/setup.py", line 19, in <module>
remote: import numpy
remote: ImportError: No module named numpy
remote:
remote: ----------------------------------------
remote: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-NoEaTG/qpython/
remote: ! Push rejected, failed to compile Python app.
</code></pre>
| 0 | 2016-10-04T02:34:15Z | 39,844,081 | <p>Like it says, you need to have numpy installed (it doesn't install on heroku with pip).</p>
<p>You have to use a buildpack to install numpy on your heroku app:</p>
<p><a href="https://github.com/thenovices/heroku-buildpack-scipy" rel="nofollow">https://github.com/thenovices/heroku-buildpack-scipy</a></p>
| 0 | 2016-10-04T04:16:44Z | [
"python",
"django",
"numpy",
"heroku",
"qpython"
]
|
Updating Each Row with Minutes Since First Row | 39,843,394 | <p>I have a file with a million tweets. The first tweet occurred <code>2013-04-15 20:17:18 UTC</code>. I want to update each tweet row afterward with the minutes since <code>minsSince</code> that first tweet. </p>
<p>I have found help with datetime <a href="http://stackoverflow.com/questions/2788871/python-date-difference-in-minutes">here</a>, and converting time <a href="http://stackoverflow.com/questions/7703865/going-from-twitter-date-to-python-datetime-date">here</a>, but when I put the two together I don't get the right times. It could be something with the UTC string at the end of each <code>published_at</code> value.</p>
<p>The error it throws is:</p>
<pre><code>tweets['minsSince'] = tweets.apply(timesince,axis=1)
...
TypeError: ('string indices must be integers, not str', u'occurred at index 0')
</code></pre>
<p>Thanks for any help.</p>
<pre><code>#Import stuff
from datetime import datetime
import time
import pandas as pd
from pandas import DataFrame
#Read the csv file
tweets = pd.read_csv('BostonTWEETS.csv')
tweets.head()
#The first tweet's published_at time
starttime = datetime (2013, 04, 15, 20, 17, 18)
#Run through the document and calculate the minutes since the first tweet
def timesince(row):
minsSince = int()
tweetTime = row['published_at']
ts = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(tweetTime['published_at'], '%Y-%m-%d %H:%M:%S %UTC'))
timediff = (tweetTime - starttime)
minsSince.append("timediff")
return ",".join(minsSince)
tweets['minsSince'] = tweets.apply(timesince,axis=1)
df = DataFrame(tweets)
print(df)
</code></pre>
<p>Sample csv <a href="https://drive.google.com/open?id=0B1HTWM4qq42VejJfcVhBYTRLUG8" rel="nofollow">file</a> of first 5 rows. </p>
| 1 | 2016-10-04T02:47:12Z | 39,843,629 | <pre><code>#Import stuff
from datetime import datetime
import time
import pandas as pd
from pandas import DataFrame
#Read the csv file
tweets = pd.read_csv('sample.csv')
tweets.head()
#The first tweet's published_at time
starttime = tweets.published_at.values[0]
starttime = datetime.strptime(starttime, '%Y-%m-%d %H:%M:%S UTC')
#Run through the document and calculate the minutes since the first tweet
def timesince(row):
ts = datetime.strptime(row, '%Y-%m-%d %H:%M:%S UTC')
timediff = (ts- starttime)
timediff = divmod(timediff.days * 86400 + timediff.seconds, 60)
return timediff[0]
tweets['minSince'] = 0
tweets.minSince = tweets.published_at.map(timesince)
df = DataFrame(tweets)
print(df)
</code></pre>
<p>I hope this is what you are looking for. </p>
| 0 | 2016-10-04T03:20:31Z | [
"python",
"datetime",
"twitter",
"time"
]
|
How to make an integer larger than any other integer? | 39,843,488 | <p>Note: while the accepted answer achieves the result I wanted, and @ecatmur answer provides a more comprehensive option, I feel it's very important to emphasize that my use case is a bad idea in the first place. This is explained very well in <a href="http://stackoverflow.com/a/39856605/336527">@Jason Orendorff answer below</a>.</p>
<p>Note: this question is not a duplicate of <a href="http://stackoverflow.com/questions/13795758/what-is-sys-maxint-in-python-3">the question about <code>sys.maxint</code></a>. It has nothing to do with <code>sys.maxint</code>; even in python 2 where <code>sys.maxint</code> is available, it does NOT represent largest integer (see the accepted answer).</p>
<p>I need to create an integer that's larger than any other integer, meaning an <code>int</code> object which returns <code>True</code> when compared to any other <code>int</code> object using <code>></code>. Use case: library function expects an integer, and the only easy way to force a certain behavior is to pass a very large integer.</p>
<p>In python 2, I can use <code>sys.maxint</code> (edit: I was wrong). In python 3, <code>math.inf</code> is the closest equivalent, but I can't convert it to <code>int</code>.</p>
| 41 | 2016-10-04T03:00:56Z | 39,843,523 | <p>Since python integers are unbounded, you have to do this with a custom class:</p>
<pre><code>import functools
@functools.total_ordering
class NeverSmaller(object):
def __le__(self, other):
return False
class ReallyMaxInt(NeverSmaller, int):
def __repr__(self):
return 'ReallyMaxInt()'
</code></pre>
<p>Here I've used a mix-in class <code>NeverSmaller</code> rather than direct decoration of <code>ReallyMaxInt</code>, because on Python 3 the action of <code>functools.total_ordering</code> would have been prevented by existing ordering methods inherited from <code>int</code>. </p>
<p>Usage demo:</p>
<pre><code>>>> N = ReallyMaxInt()
>>> N > sys.maxsize
True
>>> isinstance(N, int)
True
>>> sorted([1, N, 0, 9999, sys.maxsize])
[0, 1, 9999, 9223372036854775807, ReallyMaxInt()]
</code></pre>
<p>Note that in python2, <code>sys.maxint + 1</code> is bigger than <code>sys.maxint</code>, so you can't rely on that. </p>
<p><em>Disclaimer</em>: This is an integer in the <a href="https://en.wikipedia.org/wiki/Object-oriented_programming#Inheritance_and_behavioral_subtyping" rel="nofollow">OO</a> sense, it is not an integer in the mathematical sense. Consequently, arithmetic operations inherited from the parent class <code>int</code> may not behave sensibly. If this causes any issues for your intended use case, then they can be disabled by implementing <code>__add__</code> and friends to just error out.</p>
| 61 | 2016-10-04T03:04:16Z | [
"python",
"python-3.x"
]
|
How to make an integer larger than any other integer? | 39,843,488 | <p>Note: while the accepted answer achieves the result I wanted, and @ecatmur answer provides a more comprehensive option, I feel it's very important to emphasize that my use case is a bad idea in the first place. This is explained very well in <a href="http://stackoverflow.com/a/39856605/336527">@Jason Orendorff answer below</a>.</p>
<p>Note: this question is not a duplicate of <a href="http://stackoverflow.com/questions/13795758/what-is-sys-maxint-in-python-3">the question about <code>sys.maxint</code></a>. It has nothing to do with <code>sys.maxint</code>; even in python 2 where <code>sys.maxint</code> is available, it does NOT represent largest integer (see the accepted answer).</p>
<p>I need to create an integer that's larger than any other integer, meaning an <code>int</code> object which returns <code>True</code> when compared to any other <code>int</code> object using <code>></code>. Use case: library function expects an integer, and the only easy way to force a certain behavior is to pass a very large integer.</p>
<p>In python 2, I can use <code>sys.maxint</code> (edit: I was wrong). In python 3, <code>math.inf</code> is the closest equivalent, but I can't convert it to <code>int</code>.</p>
| 41 | 2016-10-04T03:00:56Z | 39,853,886 | <p>It seems to me that this would be fundamentally impossible. Let's say you write a function that returns this RBI ("really big int"). If the computer is capable of storing it, then someone else could write a function that returns the same value. Is your RBI greater than itself?</p>
<p>Perhaps you can achieve the desired result with something like @wim's answer: Create an object that overrides the comparison operators to make "<" always return false and ">" always return true. (I haven't written a lot of Python. In most object-oriented languages, this would only work if the comparison puts your value first, IF RBI>x. If someone writes the comparison the other way, IF x>RBI, it will fail because the compiler doesn't know how to compare integers to a user-defined class.)</p>
| 1 | 2016-10-04T13:40:28Z | [
"python",
"python-3.x"
]
|
How to make an integer larger than any other integer? | 39,843,488 | <p>Note: while the accepted answer achieves the result I wanted, and @ecatmur answer provides a more comprehensive option, I feel it's very important to emphasize that my use case is a bad idea in the first place. This is explained very well in <a href="http://stackoverflow.com/a/39856605/336527">@Jason Orendorff answer below</a>.</p>
<p>Note: this question is not a duplicate of <a href="http://stackoverflow.com/questions/13795758/what-is-sys-maxint-in-python-3">the question about <code>sys.maxint</code></a>. It has nothing to do with <code>sys.maxint</code>; even in python 2 where <code>sys.maxint</code> is available, it does NOT represent largest integer (see the accepted answer).</p>
<p>I need to create an integer that's larger than any other integer, meaning an <code>int</code> object which returns <code>True</code> when compared to any other <code>int</code> object using <code>></code>. Use case: library function expects an integer, and the only easy way to force a certain behavior is to pass a very large integer.</p>
<p>In python 2, I can use <code>sys.maxint</code> (edit: I was wrong). In python 3, <code>math.inf</code> is the closest equivalent, but I can't convert it to <code>int</code>.</p>
| 41 | 2016-10-04T03:00:56Z | 39,855,605 | <p>Konsta Vesterinen's <a href="https://github.com/kvesteri/infinity"><code>infinity.Infinity</code></a> would work (<a href="https://pypi.python.org/pypi/infinity/">pypi</a>), except that it doesn't inherit from <code>int</code>, but you can subclass it:</p>
<pre><code>from infinity import Infinity
class IntInfinity(Infinity, int):
pass
assert isinstance(IntInfinity(), int)
assert IntInfinity() > 1e100
</code></pre>
<p>Another package that implements "infinity" values is <a href="https://pypi.python.org/pypi/Extremes">Extremes</a>, which was salvaged from the rejected <a href="https://www.python.org/dev/peps/pep-0326/">PEP 326</a>; again, you'd need to subclass from <code>extremes.Max</code> and <code>int</code>.</p>
| 23 | 2016-10-04T14:57:45Z | [
"python",
"python-3.x"
]
|
How to make an integer larger than any other integer? | 39,843,488 | <p>Note: while the accepted answer achieves the result I wanted, and @ecatmur answer provides a more comprehensive option, I feel it's very important to emphasize that my use case is a bad idea in the first place. This is explained very well in <a href="http://stackoverflow.com/a/39856605/336527">@Jason Orendorff answer below</a>.</p>
<p>Note: this question is not a duplicate of <a href="http://stackoverflow.com/questions/13795758/what-is-sys-maxint-in-python-3">the question about <code>sys.maxint</code></a>. It has nothing to do with <code>sys.maxint</code>; even in python 2 where <code>sys.maxint</code> is available, it does NOT represent largest integer (see the accepted answer).</p>
<p>I need to create an integer that's larger than any other integer, meaning an <code>int</code> object which returns <code>True</code> when compared to any other <code>int</code> object using <code>></code>. Use case: library function expects an integer, and the only easy way to force a certain behavior is to pass a very large integer.</p>
<p>In python 2, I can use <code>sys.maxint</code> (edit: I was wrong). In python 3, <code>math.inf</code> is the closest equivalent, but I can't convert it to <code>int</code>.</p>
| 41 | 2016-10-04T03:00:56Z | 39,856,605 | <blockquote>
<p>Use case: library function expects an integer, and the only easy way to force a certain behavior is to pass a very large integer.</p>
</blockquote>
<p>This sounds like a flaw in the library that should be fixed in its interface. Then all its users would benefit. What library is it?</p>
<p>Creating a magical int subclass with overridden comparison operators might work for you. It's brittle, though; you never know what the library is going to do with that object. Suppose it converts it to a string. What should happen? And data is naturally used in different ways as a library evolves; you may update the library one day to find that your trick doesn't work anymore.</p>
| 15 | 2016-10-04T15:45:43Z | [
"python",
"python-3.x"
]
|
How to make an integer larger than any other integer? | 39,843,488 | <p>Note: while the accepted answer achieves the result I wanted, and @ecatmur answer provides a more comprehensive option, I feel it's very important to emphasize that my use case is a bad idea in the first place. This is explained very well in <a href="http://stackoverflow.com/a/39856605/336527">@Jason Orendorff answer below</a>.</p>
<p>Note: this question is not a duplicate of <a href="http://stackoverflow.com/questions/13795758/what-is-sys-maxint-in-python-3">the question about <code>sys.maxint</code></a>. It has nothing to do with <code>sys.maxint</code>; even in python 2 where <code>sys.maxint</code> is available, it does NOT represent largest integer (see the accepted answer).</p>
<p>I need to create an integer that's larger than any other integer, meaning an <code>int</code> object which returns <code>True</code> when compared to any other <code>int</code> object using <code>></code>. Use case: library function expects an integer, and the only easy way to force a certain behavior is to pass a very large integer.</p>
<p>In python 2, I can use <code>sys.maxint</code> (edit: I was wrong). In python 3, <code>math.inf</code> is the closest equivalent, but I can't convert it to <code>int</code>.</p>
| 41 | 2016-10-04T03:00:56Z | 39,857,811 | <p>Another way to do this (very much inspired by wim's answer) might be an object that isn't infinite, but increases on the fly as needed. </p>
<p>Here's what I have in mind: </p>
<pre><code>from functools import wraps
class AlwaysBiggerDesc():
'''A data descriptor that always returns a value bigger than instance._compare'''
def __get__(self, instance, owner):
try:
return instance._compare + 1
except AttributeError:
return instance._val
def __set__(self, instance, value):
try:
del instance._compare
except AttributeError:
pass
instance._val = value
class BiggerThanYou(int):
'''A class that behaves like an integer but that increases as needed so as to be
bigger than "other" values. Defaults to 1 so that instances are considered
to be "truthy" for boolean comparisons.'''
val = AlwaysBiggerDesc()
def __getattribute__(self, name):
f = super().__getattribute__(name)
try:
intf = getattr(int,name)
except AttributeError:
intf = None
if f is intf:
@wraps(f)
def wrapper(*args):
try:
self._compare = args[1]
except IndexError:
self._compare = 0 # Note: 1 will be returned by val descriptor
new_bigger = BiggerThanYou()
try:
new_bigger.val = f(self.val, *args[1:])
except IndexError:
new_bigger.val = f(self.val)
return new_bigger
return wrapper
else:
return f
def __repr__(self):
return 'BiggerThanYou()'
def __str__(self):
return '1000...'
</code></pre>
<p>Something like this might avoid a lot of weird behavior that one might not expect. Note that with this kind of approach, if two <code>BiggerThanYou</code> instances are involved in an operation, the LHS would be considered bigger than the RHS. </p>
<p>EDIT: currently this is not working- I'll fix it later. it seems I am being bitten by the <a href="http://stackoverflow.com/a/13063764/2437514">special method lookup functionality</a>. </p>
| -4 | 2016-10-04T16:52:24Z | [
"python",
"python-3.x"
]
|
How to make an integer larger than any other integer? | 39,843,488 | <p>Note: while the accepted answer achieves the result I wanted, and @ecatmur answer provides a more comprehensive option, I feel it's very important to emphasize that my use case is a bad idea in the first place. This is explained very well in <a href="http://stackoverflow.com/a/39856605/336527">@Jason Orendorff answer below</a>.</p>
<p>Note: this question is not a duplicate of <a href="http://stackoverflow.com/questions/13795758/what-is-sys-maxint-in-python-3">the question about <code>sys.maxint</code></a>. It has nothing to do with <code>sys.maxint</code>; even in python 2 where <code>sys.maxint</code> is available, it does NOT represent largest integer (see the accepted answer).</p>
<p>I need to create an integer that's larger than any other integer, meaning an <code>int</code> object which returns <code>True</code> when compared to any other <code>int</code> object using <code>></code>. Use case: library function expects an integer, and the only easy way to force a certain behavior is to pass a very large integer.</p>
<p>In python 2, I can use <code>sys.maxint</code> (edit: I was wrong). In python 3, <code>math.inf</code> is the closest equivalent, but I can't convert it to <code>int</code>.</p>
| 41 | 2016-10-04T03:00:56Z | 39,921,621 | <blockquote>
<p><strong>In Python 3.5, you can do:</strong></p>
<p><code>import math
test = math.inf</code></p>
<p>And then:</p>
<p><code>test > 1
test > 10000
test > x</code></p>
<p>Will always be true. Unless of course, as pointed out, x is also infinity or "nan" ("not a number").</p>
</blockquote>
<p><a href="https://stackoverflow.com/questions/7781260/how-can-i-represent-an-infinite-number-in-python">How can I represent an infinite number in Python?</a></p>
<p>Answered by @WilHall</p>
| 1 | 2016-10-07T16:08:53Z | [
"python",
"python-3.x"
]
|
How to make an integer larger than any other integer? | 39,843,488 | <p>Note: while the accepted answer achieves the result I wanted, and @ecatmur answer provides a more comprehensive option, I feel it's very important to emphasize that my use case is a bad idea in the first place. This is explained very well in <a href="http://stackoverflow.com/a/39856605/336527">@Jason Orendorff answer below</a>.</p>
<p>Note: this question is not a duplicate of <a href="http://stackoverflow.com/questions/13795758/what-is-sys-maxint-in-python-3">the question about <code>sys.maxint</code></a>. It has nothing to do with <code>sys.maxint</code>; even in python 2 where <code>sys.maxint</code> is available, it does NOT represent largest integer (see the accepted answer).</p>
<p>I need to create an integer that's larger than any other integer, meaning an <code>int</code> object which returns <code>True</code> when compared to any other <code>int</code> object using <code>></code>. Use case: library function expects an integer, and the only easy way to force a certain behavior is to pass a very large integer.</p>
<p>In python 2, I can use <code>sys.maxint</code> (edit: I was wrong). In python 3, <code>math.inf</code> is the closest equivalent, but I can't convert it to <code>int</code>.</p>
| 41 | 2016-10-04T03:00:56Z | 39,924,210 | <p>You should not be inheriting from <code>int</code> unless you want both its <em>interface</em> and its <em>implementation</em>. (Its implementation is an automatically-widening set of bits representing a finite number. You clearly dont' want that.) Since you only want the <em>interface</em>, then inherit from the ABC <code>Integral</code>. Thanks to @ecatmur's answer, we can use <code>infinity</code> to deal with the nitty-gritty of infinity (including negation). Here is how we could combine <code>infinity</code> with the ABC <code>Integral</code>:</p>
<pre><code>import pytest
from infinity import Infinity
from numbers import Integral
class IntegerInfinity(Infinity, Integral):
def __and__(self, other):
raise NotImplementedError
def __ceil__(self):
raise NotImplementedError
def __floor__(self):
raise NotImplementedError
def __int__(self):
raise NotImplementedError
def __invert__(self, other):
raise NotImplementedError
def __lshift__(self, other):
raise NotImplementedError
def __mod__(self, other):
raise NotImplementedError
def __or__(self, other):
raise NotImplementedError
def __rand__(self, other):
raise NotImplementedError
def __rlshift__(self, other):
raise NotImplementedError
def __rmod__(self, other):
raise NotImplementedError
def __ror__(self, other):
raise NotImplementedError
def __round__(self):
raise NotImplementedError
def __rrshift__(self, other):
raise NotImplementedError
def __rshift__(self, other):
raise NotImplementedError
def __rxor__(self, other):
raise NotImplementedError
def __trunc__(self):
raise NotImplementedError
def __xor__(self, other):
raise NotImplementedError
def test():
x = IntegerInfinity()
assert x > 2
assert not x < 3
assert x >= 5
assert not x <= -10
assert x == x
assert not x > x
assert not x < x
assert x >= x
assert x <= x
assert -x == -x
assert -x <= -x
assert -x <= x
assert -x < x
assert -x < -1000
assert not -x < -x
with pytest.raises(Exception):
int(x)
with pytest.raises(Exception):
x | x
with pytest.raises(Exception):
ceil(x)
</code></pre>
<p>This can be run with <code>pytest</code> to verify the required invariants.</p>
| 0 | 2016-10-07T19:04:35Z | [
"python",
"python-3.x"
]
|
I'm wondering how to assign a a few different files to different corresponding numbers in python | 39,843,491 | <p>I'm wondering how a assign the file to just one of the numbers in the list, and if they make another file it will assign it to the next corresponding number.</p>
<pre><code>number = [1, 2, 3, 4, 5]
while True:
with open(number, "w") as w:
number.write(input(""))
user_answer = input("1 to start another file, 2 to save and exit. -")
if user_answer == ("1"):
True
elif user_answer == ("2"):
break
</code></pre>
| 0 | 2016-10-04T03:01:11Z | 39,845,085 | <pre><code># An integer denoting the name of the file to be generated.
# The name of the first file generated would be "1" (excluding the extension format)
i = 0
while True:
# Create the path of the file to be generated
file_path = str(i) + ".txt"
with open(file_path, "w") as my_file_handle:
print("Writing in file - '" + file_path + "'")
my_file_handle.write(input(""))
user_answer = input("1 to start another file, 2 to save and exit. - ")
if user_answer == ("1"):
# Increment the filename.
i += 1
elif user_answer == ("2"):
break
</code></pre>
| 0 | 2016-10-04T05:56:25Z | [
"python",
"python-3.x"
]
|
I'm wondering how to assign a a few different files to different corresponding numbers in python | 39,843,491 | <p>I'm wondering how a assign the file to just one of the numbers in the list, and if they make another file it will assign it to the next corresponding number.</p>
<pre><code>number = [1, 2, 3, 4, 5]
while True:
with open(number, "w") as w:
number.write(input(""))
user_answer = input("1 to start another file, 2 to save and exit. -")
if user_answer == ("1"):
True
elif user_answer == ("2"):
break
</code></pre>
| 0 | 2016-10-04T03:01:11Z | 39,845,465 | <p>Let's take your program line by line.</p>
<pre><code>number = [1, 2, 3, 4, 5]
</code></pre>
<p>The only problem here is that <code>number</code> is not quite the right name for your variable.</p>
<p><code>[1, 2, 3, 4, 5]</code> isn't a single number, but a list of five numbers. Choosing good names for variables is an important (and sometimes tricky) skill for a programmer, because if your names are confusing, well, you'll get confused. Let's call it <code>number_list</code> instead.</p>
<pre><code>number_list = [1, 2, 3, 4, 5]
</code></pre>
<p>Ok, what's next?</p>
<pre><code>while True:
</code></pre>
<p>This is the standard way to repeat forever (or until told to stop) in Python. I think what you really want to do is go through each of the numbers in <code>number_list</code> in turn, though, and for that, we use a <code>for</code> loop:</p>
<pre><code>for number in number_list:
</code></pre>
<p>On the next line you're trying to open the file for writing:</p>
<pre><code> with open(number, "w") as w:
</code></pre>
<p>There's a problem here though, because <code>number</code> is an <a href="https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex" rel="nofollow">integer</a>, and filenames have to be <a href="https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str" rel="nofollow">strings</a>. We can fix that by converting <code>number</code> to a string using <code>str()</code>.</p>
<p>Also, <code>w</code> is a slightly confusing name for your file variable, because it's similar to the <code>"w"</code> you used to say that you're writing to the file â traditionally files are called <code>f</code> when we open them like this.</p>
<p>Let's make both those changes:</p>
<pre><code> with open(str(number), "w") as f:
</code></pre>
<p>Next line:</p>
<pre><code> number.write(input(""))
</code></pre>
<p>The problem here is that you're trying to write to your integer <code>number</code>, when you really want to write to the file you just opened, <code>f</code>. That's an easy fix though:</p>
<pre><code> f.write(input(""))
</code></pre>
<p>Your next two lines are perfect:</p>
<pre><code> user_answer = input("1 to start another file, 2 to save and exit. -")
if user_answer == ("1"):
</code></pre>
<p>... but the one after isn't quite right:</p>
<pre><code> True
</code></pre>
<p>The way we actually tell Python to go back to the top of the loop with the next value is like this:</p>
<pre><code> continue
</code></pre>
<p>Your last two lines are also perfect:</p>
<pre><code> elif user_answer == ("2"):
break
</code></pre>
<p>Putting the changes together, we get:</p>
<pre><code>number_list = [1, 2, 3, 4, 5]
for number in number_list:
with open(str(number), "w") as f:
f.write(input(""))
user_answer = input("1 to start another file, 2 to save and exit. -")
if user_answer == ("1"):
continue
elif user_answer == ("2"):
break
</code></pre>
<p>Quick question though: what happens if the user doesn't enter either '1' or '2'? Something to think about ...</p>
| 1 | 2016-10-04T06:25:18Z | [
"python",
"python-3.x"
]
|
Python - Append items to a list while making https requests inside a loop | 39,843,560 | <p>I am making requests to <code>SPotify API</code> inside a <code>for loop</code>, like so:</p>
<pre><code>track_ids = []
#get track_ids
for track in random.sample(pitchfork_tracks, 10):
results = sp.search(q=track, type='track') #here I call Spotify endpoint
items = results['tracks']['items']
for t in items:
track_ids.append(t['uri'])
return track_ids
</code></pre>
<p>I can <code>print</code> every <code>t</code> alright, but if I try to <code>return</code> <code>track_ids</code>, console returns me nothing.</p>
<p>Log tells me:</p>
<pre><code>2016-10-03 23:55:49 [requests.packages.urllib3.connectionpool] INFO: Starting new HTTPS connection (1): accounts.spotify.com
2016-10-03 23:55:50 [requests.packages.urllib3.connectionpool] DEBUG: "POST /api/token HTTP/1.1" 200 None
2016-10-03 23:55:50 [requests.packages.urllib3.connectionpool] INFO: Starting new HTTPS connection (1): api.spotify.com
2016-10-03 23:55:50 [requests.packages.urllib3.connectionpool] DEBUG: "GET /v1/search?q=Rushes&limit=10&type=track&offset=0 HTTP/1.1" 200 None
2016-10-03 23:55:50 [requests.packages.urllib3.connectionpool] INFO: Starting new HTTPS connection (1): api.spotify.com
2016-10-03 23:55:51 [requests.packages.urllib3.connectionpool] DEBUG: "GET /v1/search?q=Opposite+House&limit=10&type=track&offset=0 HTTP/1.1" 200 None
2016-10-03 23:55:51 [requests.packages.urllib3.connectionpool] INFO: Starting new HTTPS connection (1): api.spotify.com
</code></pre>
<p>it looks like starting and ending connections over and over has something to do with it...or am I missing something obvious here?</p>
<p>how can I solve this and manage to build my <code>track_ids</code> <code>list</code>?</p>
| 0 | 2016-10-04T03:09:04Z | 39,843,669 | <p><code>track_ids</code> scope is inside your function. To print list you can do like this </p>
<pre><code>track_ids = yourfunction()
print track_ids
</code></pre>
<p>OR </p>
<p>you can make <code>track_ids</code> list global and declare it outside of your function. </p>
| 2 | 2016-10-04T03:25:35Z | [
"python",
"for-loop",
"python-requests",
"spotipy"
]
|
Schema - Ability to change email address (primary user id) in Django | 39,843,618 | <p>Currently my user table looks like this - (all fields are not null)</p>
<pre><code>display_name = CharField # string
email_address = EmailField (primary key) # string
password = CharField # string
</code></pre>
<p>However, I have decided to add additional functionality and to allow users to change their email addresses.</p>
<p>The flow goes like this </p>
<p><a href="http://i.stack.imgur.com/rH1dn.png" rel="nofollow"><img src="http://i.stack.imgur.com/rH1dn.png" alt="enter image description here"></a></p>
<p>Does anyone have any ideas on how to do this?</p>
<p>Currently I am thinking of something like</p>
<pre><code>display_name = CharField # string
email_address = EmailField (primary key) # string
password = CharField # string
pending_email = EmailField (unique) # string
</code></pre>
<p>And simply hold the new email address in <code>pending_email</code> before replacing the old email address in <code>email_address</code></p>
<p>But obviously this is far from perfect (e.g. <code>pending_email</code> unique constraint does not cover <code>email_address</code>)</p>
<p>Ive thought about just leaving it like this and performing more selects against the database with AJAX queries to check if the desired new email address already lives in <code>email_address</code> before allowing it to be entered into <code>pending_email</code> but this seems still vulnerable to race conditions and poor user experiences on top of being not very database friendly.</p>
| 1 | 2016-10-04T03:18:44Z | 39,844,369 | <p>The standard practice in this sort of situation is to create a separate table for email addresses. That allows users to have more than one email address at a given time and one of them can be marked as default. </p>
<p>This is what <a href="https://github.com/pennersr/django-allauth/blob/master/allauth/account/models.py#L23" rel="nofollow">django-allauth</a>'s EmailAddress model looks like. In fact, unless you have a very compelling reason to write your own authentication system, I highly recommend that your swith to django allauth or any of the widely used django authentication/registration system.</p>
<pre><code>class EmailAddress(models.Model):
user = models.ForeignKey(allauth_app_settings.USER_MODEL,
verbose_name=_('user'))
email = models.EmailField(unique=app_settings.UNIQUE_EMAIL,
max_length=app_settings.EMAIL_MAX_LENGTH,
verbose_name=_('e-mail address'))
verified = models.BooleanField(verbose_name=_('verified'), default=False)
primary = models.BooleanField(verbose_name=_('primary'), default=False)
objects = EmailAddressManager()
</code></pre>
| 1 | 2016-10-04T04:50:38Z | [
"python",
"django",
"database",
"user",
"schema"
]
|
postgresql insert timestamp error with python | 39,843,631 | <p>I use psycopg2 for postgresql. Here is my snippet:</p>
<pre><code>a = "INSERT INTO tweets (Time) VALUES (%s);" % (datetime.now(),)
cursor.execute(a)
</code></pre>
<p>this won't work and gives me an error:</p>
<pre><code>ProgrammingError: syntax error at or near "20"
LINE 1: INSERT INTO tweets (Time) VALUES (2016-10-03 20:14:49.065092...
</code></pre>
<p>However, if I run this way:</p>
<pre><code>cursor.execute("INSERT INTO tweets (Time) VALUES (%s);", (datetime.now(),))
</code></pre>
<p>it works. I want to know what is the difference between these two expressions, and what is wrong with the first one. Can I do this function use the first structure?</p>
| 1 | 2016-10-04T03:20:53Z | 39,847,509 | <p>If you check the first query, it states <code>INSERT INTO tweets (Time) VALUES (2016-10-03 20:14:49.065092...</code>, that means, it tries to use unquoted value as a time and this won't work.</p>
<p>If you really want to use your first approach, you have to quote the value:</p>
<pre><code>a = "INSERT INTO tweets (Time) VALUES ('%s');" % (datetime.now(),)
cursor.execute(a)
</code></pre>
<p>I'd suggest you to use the second approach, where client library handles all quotes and usually prevents a lot of possible problems like SQL injection.</p>
| 2 | 2016-10-04T08:25:05Z | [
"python",
"postgresql",
"timestamp",
"psycopg2"
]
|
how to have multiple arguments in a input fuction in python | 39,843,660 | <p><strong>This function throws an error at the input function claiming that the arguments are invalid.. any resolutions?</strong></p>
<pre><code>def assignSquareValues():
square=[[0,0,0],
[0,0,0],
[0,0,0]]
count=0
try:
for r in range(3):
for c in range(3):
count+=1
print(count)
square[r][c]= int(input(("Enter a number(1-9) for square #",(count)+":",sep=''))) #this line throws an error stating that "TypeError: input expected at most 1 arguments, got 2"
except Exception as err:
print(err)
assignSquareValues()
checkMagicSquare(square)
</code></pre>
| 0 | 2016-10-04T03:24:30Z | 39,843,834 | <p><code>input()</code> expects one argument - displayed text - so you have to concatenate all arguments in to one text</p>
<p>ie.</p>
<pre><code>input("Enter a number(1-9) for square #" + str(count) + ":")
</code></pre>
<p>or</p>
<pre><code>input("Enter a number(1-9) for square #{}:".format(count))
</code></pre>
| 1 | 2016-10-04T03:46:43Z | [
"python"
]
|
Selection Sort Algorithm Python | 39,843,663 | <p>Working on implementing this algorithm using Python. I thought my logic was okay but apparently not as Python is complaining. The while loop is causing issues. If I remove that it works as expected but obviously doesn't sort the whole list. My thought process -> Use Linear Search to find the smallest number -> Append that new number to a list -> Remove that number from the current list -> Loop through that same list (but with smallest number removed) again -> Repeat process until we've gone through the entire list "x" number of times. "x" being equal to the length of the list. The problem I think I'm running into is that the list never gets updated every time I run through the for loop? I keep getting the error <code>Line 21: ValueError: list.index(x): x not in list</code>.
Even though "x" is in the list. Any idea as to what I'm doing wrong?</p>
<pre><code>"""
Selection sort algorithm.
"""
import random
ls = []
max_number = 10
while len(ls) < max_number:
ls.append(random.randint(1,101))
print ls
def selection_sort(items_to_sort):
smallest_number = items_to_sort[0]
current_number = 0
sorted_items = []
item_len = len(items_to_sort)
while item_len > 0:
for item in items_to_sort[:]:
if item < smallest_number:
smallest_number = item
items_to_sort.pop(items_to_sort.index(smallest_number))
sorted_items.append(smallest_number)
item_len -= 1
return sorted_items
print selection_sort(ls)
</code></pre>
| 0 | 2016-10-04T03:24:46Z | 39,843,739 | <p>It looks like <strong>you're not re-initializing</strong> the <code>smallest_number</code> variable, so after the first execution of your <code>while</code> loop - you look for a value smaller than the previous value which you just <code>pop</code>ed from the list.</p>
<p>When you don't find a value smaller than the previously smallest value which is no longer in the list, you try to <code>pop</code> the same <code>smallest_number</code> as in the previous iteration of the <code>while</code> loop. However, that value is no longer in the <code>items_to_sort</code> list which is why you get the <code>ValueError</code></p>
<p>Try moving the line <code>smallest_number = items_to_sort[0]</code> to be the first line executed in every iteration of your <code>while</code> loop.</p>
| 2 | 2016-10-04T03:34:35Z | [
"python",
"algorithm",
"list",
"sorting"
]
|
Selection Sort Algorithm Python | 39,843,663 | <p>Working on implementing this algorithm using Python. I thought my logic was okay but apparently not as Python is complaining. The while loop is causing issues. If I remove that it works as expected but obviously doesn't sort the whole list. My thought process -> Use Linear Search to find the smallest number -> Append that new number to a list -> Remove that number from the current list -> Loop through that same list (but with smallest number removed) again -> Repeat process until we've gone through the entire list "x" number of times. "x" being equal to the length of the list. The problem I think I'm running into is that the list never gets updated every time I run through the for loop? I keep getting the error <code>Line 21: ValueError: list.index(x): x not in list</code>.
Even though "x" is in the list. Any idea as to what I'm doing wrong?</p>
<pre><code>"""
Selection sort algorithm.
"""
import random
ls = []
max_number = 10
while len(ls) < max_number:
ls.append(random.randint(1,101))
print ls
def selection_sort(items_to_sort):
smallest_number = items_to_sort[0]
current_number = 0
sorted_items = []
item_len = len(items_to_sort)
while item_len > 0:
for item in items_to_sort[:]:
if item < smallest_number:
smallest_number = item
items_to_sort.pop(items_to_sort.index(smallest_number))
sorted_items.append(smallest_number)
item_len -= 1
return sorted_items
print selection_sort(ls)
</code></pre>
| 0 | 2016-10-04T03:24:46Z | 39,843,785 | <p>After every while loop, you should assign <code>items_to_sort[0]</code> to <code>smallest_number</code></p>
<pre><code>current_number = 0
sorted_items = []
item_len = len(items_to_sort)
while item_len > 0:
smallest_number = items_to_sort[0]
for item in items_to_sort[:]:
if item < smallest_number:
smallest_number = item
index=items_to_sort.index(smallest_number)
items_to_sort.pop(index)
print(items_to_sort)
sorted_items.append(smallest_number)
item_len -= 1
return sorted_items
</code></pre>
| 1 | 2016-10-04T03:41:26Z | [
"python",
"algorithm",
"list",
"sorting"
]
|
Python class instance variables disappear | 39,843,697 | <p>I define the response class like this:</p>
<pre><code>class Response(object):
def __index__(self):
self.country = ""
self.time_human = ""
self.time_utc = ""
self.text = ""
self.time_object = None
self.clean_word_list = []
def parse_line(self, line):
if 'text:' in line[:10]:
self.text = line[7:].strip()
elif 'country: ' in line[:9]:
self.country = line[8:].strip()
elif 'time_human: ' in line[:15]:
self.time_human = line[12:].strip()
elif 'time_utc: ' in line[:15]:
self.time_utc = int(line[10:].strip())
self.time_object = datetime.fromtimestamp(self.time_utc)
</code></pre>
<p>I then have a method that reads lines from a text file and assigns the proper value to the response:</p>
<pre><code>class file_importer(object):
def __init__(self, file_name):
self.file_name = file_name
def get_responses_from_file(self):
directory = DIRECTORY_TO_FILE
formatted_filename = directory + self.file_name
file = open(formatted_filename, 'r')
response = Response()
response_list = []
for line in file:
if line[0] == '*':
response_list.append(response)
response = Response()
else:
response.parse_line(line)
return response_list
</code></pre>
<p>But the response_list that the get_responses_from_file() returns is a list of responses that do not have a response.clean_word_list attribute. What happened?</p>
| -1 | 2016-10-04T03:29:48Z | 39,843,769 | <p>It has to be <code>__init__</code> instead of <code>__index__</code> in your <code>Response</code> class</p>
| 0 | 2016-10-04T03:37:36Z | [
"python",
"class"
]
|
why my links not writing in my file | 39,843,798 | <pre><code>import urllib
from bs4 import BeautifulSoup
import requests
import readability
import time
import http.client
seed_url = "https://en.wikipedia.org/wiki/Sustainable_energy"
root_url = "https://en.wikipedia.org"
max_limit=5
#file = open("file_crawled.txt", "w")
def get_urls(seed_url):
r = requests.get(seed_url)
soup = BeautifulSoup(r.content,"html.parser")
links = soup.findAll('a', href=True)
valid_links=[]
for links in links:
if 'wiki' in links['href'] and '.' not in links['href'] and ':' not in links['href'] and '#' not in links['href']:
valid_links.append(root_url + links['href'])
return valid_links
visited=[]
def crawl_dfs(seed_url, max_depth):
depth=1
file1 = open("file_crawled.txt", "w+")
visited.append(root_url)
if depth<=max_depth:
children=get_urls(seed_url)
for child in children:
if child not in visited:
file1.write(child)
time.sleep(1)
visited.append(child)
crawl_dfs(child,max_depth-1)
file1.close()
crawl_dfs(seed_url,max_limit)
</code></pre>
<p>dfs crawling use python 3.6
help me with the code, please correct where i am wrong, my crawled links are not writing to my file named file1. i dont know why i have tried everything at my end</p>
| 2 | 2016-10-04T03:42:31Z | 39,845,004 | <p>You have to open and close file only once - open before first <code>crawl_dfs()</code> and close after first <code>crawl_dfs()</code></p>
<p>Tested:</p>
<pre><code>import urllib
from bs4 import BeautifulSoup
import requests
#import readability
import time
import http.client
# --- functions ---
def get_urls(seed_url):
r = requests.get(seed_url)
soup = BeautifulSoup(r.content,"html.parser")
links = soup.findAll('a', href=True)
valid_links = []
for links in links:
if 'wiki' in links['href'] and '.' not in links['href'] and ':' not in links['href'] and '#' not in links['href']:
valid_links.append(root_url + links['href'])
return valid_links
def crawl_dfs(seed_url, max_depth, file_out):
if max_depth >= 1:
children = get_urls(seed_url)
for child in children:
if child not in visited:
file_out.write(child + "\n")
#time.sleep(1)
visited.append(child)
crawl_dfs(child, max_depth-1, file_out)
# --- main ---
seed_url = "https://en.wikipedia.org/wiki/Sustainable_energy"
root_url = "https://en.wikipedia.org"
max_limit = 1
visited=[root_url]
file1 = open("file_crawled.txt", "w+")
crawl_dfs(seed_url, max_limit, file1)
file1.close()
</code></pre>
| 1 | 2016-10-04T05:50:28Z | [
"python",
"python-3.x",
"web",
"web-crawler",
"depth-first-search"
]
|
Django - Splitting admin.py | 39,843,825 | <p>I tried to split admin.py with the following steps but failed.<br>
- Remove admin.py<br>
- Create folder named "admin"<br>
- Create files in folder "admin". modela.py, modelb.py<br>
- Create "_ <em>init</em> _.py" and leave it empty<br>
- In the "modela.py" file</p>
<pre><code>from django.contrib import admin
from myapp.models import *
@admin.register(ModelA)
class ModelAAdmin(admin.ModelAdmin):
class Meta:
model = ModelA
</code></pre>
<p>But the model is not showing in my admin site. What's wrong with the steps above or I missed anything?</p>
| 0 | 2016-10-04T03:45:24Z | 39,845,519 | <p>Firstly, the file is called <code>__init__.py</code>, with two underscores each side. Secondly, leaving it empty won't do anything at all; you would need to import your admin classes into that file.</p>
| 1 | 2016-10-04T06:28:54Z | [
"python",
"django"
]
|
JupyterHub openssl self signed cert "Error: error:0906D06C:PEM routines:PEM_read_bio:no start line" | 39,843,909 | <p>Trying to configure at JupyterHub on a AWS instance using a self signed OPENSSL key/cert pair. I have tried several openssl configurations, and continued to have this same error.</p>
<pre><code>jupyterhub
[I 2016-10-04 03:38:24.090 JupyterHub app:622] Loading cookie_secret from /home/ubuntu/jupyterhub_cookie_secret
[W 2016-10-04 03:38:24.123 JupyterHub app:304]
Generating CONFIGPROXY_AUTH_TOKEN. Restarting the Hub will require restarting the proxy.
Set CONFIGPROXY_AUTH_TOKEN env or JupyterHub.proxy_auth_token config to avoid this message.
[W 2016-10-04 03:38:24.127 JupyterHub app:757] No admin users, admin interface will be unavailable.
[W 2016-10-04 03:38:24.127 JupyterHub app:758] Add any administrative users to `c.Authenticator.admin_users` in config.
[I 2016-10-04 03:38:24.127 JupyterHub app:785] Not using whitelist. Any authenticated user will be allowed.
[I 2016-10-04 03:38:24.139 JupyterHub app:1231] Hub API listening on http://127.0.0.1:8081/hub/
[I 2016-10-04 03:38:24.143 JupyterHub app:968] Starting proxy @ http://*:8000/
crypto.js:128
c.context.setKey(options.key);
^
Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
at Object.exports.createCredentials (crypto.js:128:17)
at Server (tls.js:1176:28)
at new Server (https.js:35:14)
at Object.exports.createServer (https.js:54:10)
at new ConfigurableProxy (/usr/lib/node_modules/configurable-http- proxy/lib/configproxy.js:174:35)
at Object.<anonymous> (/usr/lib/node_modules/configurable-http-proxy/bin/configurable-http-proxy:189:13)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
[C 2016-10-04 03:38:25.158 JupyterHub app:1237] Failed to start proxy
Traceback (most recent call last):
File "/home/ubuntu/anaconda3/lib/python3.5/site-packages/jupyterhub/app.py", line 1235, in start
yield self.start_proxy()
File "/home/ubuntu/anaconda3/lib/python3.5/site-packages/jupyterhub/app.py", line 989, in start_proxy
_check()
File "/home/ubuntu/anaconda3/lib/python3.5/site-packages/jupyterhub/app.py", line 985, in _check
raise e
RuntimeError: Proxy failed to start with exit code 8
</code></pre>
<p>Generated the current pair using this command</p>
<pre><code>openssl req -new -x509 -days 365 -utf8 -out mycert.pem -keyout mykey.pem
</code></pre>
<p>Verified that it is in fact PEM format</p>
<pre><code>openssl x509 -in mycert.pem -text -noout
Certificate:
Data:
Version: 3 (0x2)
Serial Number:
ec:16:a1:7d:64:6b:90:42
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=SG, ST=SG, L=Singapore, O=GoldenCompass
Validity
Not Before: Oct 4 02:58:55 2016 GMT
Not After : Oct 4 02:58:55 2017 GMT
Subject: C=SG, ST=SG, L=Singapore, O=GoldenCompass
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (2048 bit)
<snippet>
</code></pre>
<p>jupyterhub_config.py</p>
<pre><code><snippet>
## Path to SSL certificate file for the public facing interface of the proxy
#
# Use with ssl_key
c.JupyterHub.ssl_cert = '/home/ubuntu/mykey.pem'
## Path to SSL key file for the public facing interface of the proxy
#
# Use with ssl_cert
c.JupyterHub.ssl_key = '/home/ubuntu/mycert.pem'
<snippet>
</code></pre>
| 0 | 2016-10-04T03:55:12Z | 39,852,086 | <p>Your config has your certificate and key reversed:</p>
<p>You have this:</p>
<pre><code>c.JupyterHub.ssl_cert = '/home/ubuntu/mykey.pem'
c.JupyterHub.ssl_key = '/home/ubuntu/mycert.pem'
</code></pre>
<p>but you should have this:</p>
<pre><code>c.JupyterHub.ssl_cert = '/home/ubuntu/mycert.pem'
c.JupyterHub.ssl_key = '/home/ubuntu/mykey.pem'
</code></pre>
| 0 | 2016-10-04T12:16:21Z | [
"python",
"ssl",
"jupyter",
"jupyter-notebook",
"jupyterhub"
]
|
Running a Function That Updates Array While Matplotlib Plots it | 39,843,925 | <p>I have a Python program (<em>main.py</em>) that has a constant stream of data that is handled by a class RTStreamer which basically gets the data -- via a live stream -- and appends it to a numpy array. However I would like to actually visualize the data as it is coming in which is where tkinter and matplotlib come in. In another python file (<em>gui.py</em>) I have a live plot using matplotlib animations and a button to trigger my first file (<em>main.py</em>) to start streaming the data. However when I click the button to start streaming the data I can see on my console that it is getting the data and appending it to the array (because I am printing the array), however the chart does not update at all. </p>
<p>Here is a simplified version of what my <em>main.py</em> looks like:</p>
<pre><code>closeBidArray = np.array([])
class RTStreamer(stream.Streamer):
def __init__(self, *args, **kwargs):
super(RTStreamer, self).__init__(*args, **kwargs)
print(datetime.now(), "initialized")
def on_success(self, data):
# get data and append it to closeBidArray
def on_error(self, data):
# disconnect
def run():
stream = RTStreamer()
stream.rates()
</code></pre>
<p>An here is what my <em>gui.py</em> looks like:</p>
<pre><code>import main # in order to get closeBidArray
figure = Figure(figsize=(5,5), dpi=100)
subplot1 = figure.add_subplot(111)
class App(tk.Tk):
# Mostly to do with formatting the window and frames in it
def animate():
subplot1.clear
subplot1.plot(main.closeBidArray)
class MainPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
# THIS IS THE BUTTON THAT TRIGGERS TO FUNCTION THAT STREAMS THE DATA:
button1 = tk.Button(text="Hi", command=main.run)
button1.pack()
canvas = FigureCanvasTkAgg(figure, self)
canvas.show()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
app = App()
ani = animation.FuncAnimation(figure, animate, interval=1000)
app.mainloop()
</code></pre>
<p>I've noticed if I hit <kbd>CTRL</kbd>+<kbd>C</kbd> to break the program, it strops streaming data and plots the array, and if I hit <kbd>CTRL</kbd>+<kbd>C</kbd> again it closes the matplotlib window altogether. However I would like to stream and append to the array while also plotting it, any ideas on how I can accomplish this? Thanks. </p>
| 0 | 2016-10-04T03:57:17Z | 39,856,802 | <p>To make your code work, you need to draw the artist on each frame, not just show the canvas. However, that will be effing slow. What you really want to do, is to only update the data, and keep as much of the canvas constant. For that you use blit. Minimum working example below.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
def animate(movie):
"""
Animate frames in array using blit.
Arguments:
----------
movie: (time, height, width) ndarray
"""
plt.ion()
fig, ax = plt.subplots(1,1)
# initialize blit for movie axis
img = ax.imshow(np.zeros((movie.shape[1],movie.shape[2])),
interpolation = 'nearest', origin = 'lower', vmin = 0, vmax = 1, cmap = 'gray')
# cache the background
bkg = fig.canvas.copy_from_bbox(ax.bbox)
# loop over frames
raw_input('Press any key to start the animation...')
for t in range(movie.shape[0]):
# draw movie
img.set_data(movie[t])
fig.canvas.restore_region(bkg)
ax.draw_artist(img)
fig.canvas.blit(ax.bbox)
return
if __name__ == "__main__":
movie = np.random.rand(1000, 10, 10)
animate(movie)
pass
</code></pre>
| 0 | 2016-10-04T15:54:16Z | [
"python",
"python-3.x",
"matplotlib",
"tkinter"
]
|
python dynamic object query | 39,844,041 | <p>I have a python object structured like:</p>
<pre><code>tree = {
"a": {
"aa": {
"aaa": {},
"aab": {},
"aac": {}
},
"ab": {
"aba": {},
"abb": {}
}
},
"b": {
"ba": {}
},
"c": {}
}
</code></pre>
<p>And a set of lists of strings like:</p>
<pre><code>arr_1 = ["a", "ab"]
arr_2 = ["b", "ab"]
arr_3 = ["a", "ab", "aba"]
</code></pre>
<p>Each list defines a path of keys in the tree and I want to determine whether the list describes a valid path through the tree or not.</p>
<p>Currently I can achieve a case by case answer like so:</p>
<pre><code>tree[arr_1[0]][arr_1[1]] # Returns correct object
tree[arr_2[0]][arr_2[1]] # Returns error
tree[arr_3[0]][arr_3[1]][arr_3[2]] # Returns correct object
</code></pre>
<p>Though this does not satisfy my requirements. I'd much prefer one function which will search the tree for the keys in any given list.</p>
<p>The following function is almost what I want but it does not handle lists of different lengths.</p>
<pre><code>def is_valid(tree, arr):
obj = tree[arr[0]][arr[1]]
if len(obj) > 0:
return(obj)
else:
return("No obj")
</code></pre>
<p>Currently this function outputs</p>
<pre><code>is_valid(tree, arr_1) # Returns the correct result
is_valid(tree, arr_2) # Returns an error
is_valid(tree, arr_3) # Returns the same result as arr_1, which is incorrect
</code></pre>
<p>Can anyone help me expand this function to react dynamicically to the length of the <code>arr</code> argument?</p>
<p>Thanks!</p>
| 1 | 2016-10-04T04:11:37Z | 39,844,125 | <p>I think the easiest way to do this is to utilize recursion. Every sub-tree is a tree and every sub-path is a path, so we can look at whether or not the first element in the path is valid then continue on from there.</p>
<pre><code>def is_valid(tree, path):
# base case. Any path would be valid for any tree
if len(path) == 0:
return True
# the path must be invalid, no matter what comes before or after
if not path[0] in tree:
return False
# look at the rest
return is_valid(tree[path[0]], path[1:])
</code></pre>
<p>If you want the sub-tree a path describes you could instead do this:</p>
<pre><code>def is_valid(tree, path):
if len(path) == 0:
return tree # the only difference
if not path[0] in tree:
return False
return is_valid(tree[path[0]], path[1:])
</code></pre>
| 3 | 2016-10-04T04:22:32Z | [
"python",
"arrays",
"object",
"dictionary"
]
|
Union of node and function on node in XPath | 39,844,061 | <p>I am using Scrapy to crawl some webpages. I want to write an XPath query that will, within a parent <code><div></code>, append a couple of characters of text to any child <code><a></code> nodes, while extracting the text of the div's <code>self</code> node normally. Essentially it is like a normal <code>descendant-or-self</code> or <code>//</code> query, just written with <code>|</code> and calling the <code>concat</code> function on the descendants (which, if they exist, will be <code><a></code> tags).</p>
<p>These all return a value:</p>
<ol>
<li><code>my_div.xpath('div[@class="my_class"]/text()).extract()</code></li>
<li><code>my_div.xpath('concat(\'@\', div[@class="my_class"]/a/text())').extract()</code></li>
<li><code>my_div.xpath('div[@class="my_class"]/text() | div[@class="my_class"]/a/text()').extract()</code></li>
</ol>
<p>However attempting to combine (1) and (2) above in the format of (3):</p>
<p><code>my_div.xpath('div[@class="my_class"]/text() |
concat(\'@\', div[@class="my_class"]/a/text())').extract()</code></p>
<p>results in the following error:</p>
<p><code>ValueError: XPath error: Invalid type in div[@class="my_class"]/text() | concat('@', div[@class="my_class"]/a/text())
</code></p>
<p>How do I get XPath to recognize the union of a node with a function called on a node?</p>
| 0 | 2016-10-04T04:14:16Z | 39,848,222 | <p>I think it doesn't work because concat is doesn't actually return a path, and <code>|</code> is used to select multiple <em>paths</em></p>
<blockquote>
<p>By using the | operator in an XPath expression you can select several paths. </p>
</blockquote>
<p>as per <a href="http://www.w3schools.com/xsl/xpath_syntax.asp" rel="nofollow">http://www.w3schools.com/xsl/xpath_syntax.asp</a></p>
<p>Why not just split it into two? Generally you use <a href="https://doc.scrapy.org/en/latest/topics/loaders.html" rel="nofollow">ItemLoaders</a> with your spider. So you can simply add as many paths and/or values as you like.</p>
<pre><code>mil = MyItemLoader(response=response)
mil.add_xpath('name', 'xpath1')
mil.add_xpath('name', 'xpath2')
mil.load_item()
# {'name': ['values_of_xpath1','values_of_xpath2']
</code></pre>
<p>If you want to preserve tree order you can try:</p>
<pre><code>nodes = my_div.xpath('div[@class="my_class"]')
text = []
for node in nodes:
text.append(node.xpath("text()").extract_first())
text.append(node.xpath("a/text()").extract_first())
text = '@'.join(text)
</code></pre>
<p>You can probably simplify it with list comprehension but you get the idea: extract the nodes and iterate through nodes for both values.</p>
| 0 | 2016-10-04T09:01:39Z | [
"python",
"xpath",
"scrapy"
]
|
Union of node and function on node in XPath | 39,844,061 | <p>I am using Scrapy to crawl some webpages. I want to write an XPath query that will, within a parent <code><div></code>, append a couple of characters of text to any child <code><a></code> nodes, while extracting the text of the div's <code>self</code> node normally. Essentially it is like a normal <code>descendant-or-self</code> or <code>//</code> query, just written with <code>|</code> and calling the <code>concat</code> function on the descendants (which, if they exist, will be <code><a></code> tags).</p>
<p>These all return a value:</p>
<ol>
<li><code>my_div.xpath('div[@class="my_class"]/text()).extract()</code></li>
<li><code>my_div.xpath('concat(\'@\', div[@class="my_class"]/a/text())').extract()</code></li>
<li><code>my_div.xpath('div[@class="my_class"]/text() | div[@class="my_class"]/a/text()').extract()</code></li>
</ol>
<p>However attempting to combine (1) and (2) above in the format of (3):</p>
<p><code>my_div.xpath('div[@class="my_class"]/text() |
concat(\'@\', div[@class="my_class"]/a/text())').extract()</code></p>
<p>results in the following error:</p>
<p><code>ValueError: XPath error: Invalid type in div[@class="my_class"]/text() | concat('@', div[@class="my_class"]/a/text())
</code></p>
<p>How do I get XPath to recognize the union of a node with a function called on a node?</p>
| 0 | 2016-10-04T04:14:16Z | 39,856,552 | <p>In XPath 1.0, a <a href="https://www.w3.org/TR/xpath/#location-paths" rel="nofollow"><em>location path</em></a> returns a <a href="https://www.w3.org/TR/xpath/#node-sets" rel="nofollow"><em>node-set</em></a>. The <a href="https://www.w3.org/TR/xpath/#function-concat" rel="nofollow"><code>concat</code></a> function returns a <a href="https://www.w3.org/TR/xpath/#strings" rel="nofollow"><em>string</em></a>. The <a href="https://www.w3.org/TR/xpath/#node-sets" rel="nofollow"><em>union operator</em> <code>|</code></a> computes the union of its operands, which must be <em>node-sets</em>.</p>
| 0 | 2016-10-04T15:42:58Z | [
"python",
"xpath",
"scrapy"
]
|
Union of node and function on node in XPath | 39,844,061 | <p>I am using Scrapy to crawl some webpages. I want to write an XPath query that will, within a parent <code><div></code>, append a couple of characters of text to any child <code><a></code> nodes, while extracting the text of the div's <code>self</code> node normally. Essentially it is like a normal <code>descendant-or-self</code> or <code>//</code> query, just written with <code>|</code> and calling the <code>concat</code> function on the descendants (which, if they exist, will be <code><a></code> tags).</p>
<p>These all return a value:</p>
<ol>
<li><code>my_div.xpath('div[@class="my_class"]/text()).extract()</code></li>
<li><code>my_div.xpath('concat(\'@\', div[@class="my_class"]/a/text())').extract()</code></li>
<li><code>my_div.xpath('div[@class="my_class"]/text() | div[@class="my_class"]/a/text()').extract()</code></li>
</ol>
<p>However attempting to combine (1) and (2) above in the format of (3):</p>
<p><code>my_div.xpath('div[@class="my_class"]/text() |
concat(\'@\', div[@class="my_class"]/a/text())').extract()</code></p>
<p>results in the following error:</p>
<p><code>ValueError: XPath error: Invalid type in div[@class="my_class"]/text() | concat('@', div[@class="my_class"]/a/text())
</code></p>
<p>How do I get XPath to recognize the union of a node with a function called on a node?</p>
| 0 | 2016-10-04T04:14:16Z | 39,860,611 | <p>Update: this is what I did:</p>
<pre class="lang-py prettyprint-override"><code>item['div_text'] = []
div_nodes = definition.xpath('div[@class="my_class"]/a | div[@class="my_class"]/text()')
for n in div_nodes:
if n.xpath('self::a'):
item['div_text'].append("@%s" % n.xpath('text()').extract_first())
else:
item['div_text'].append(n.extract())
</code></pre>
| 0 | 2016-10-04T19:48:32Z | [
"python",
"xpath",
"scrapy"
]
|
How can I write a C function that takes either an int or a float? | 39,844,100 | <p>I want to create a function in C that extends Python that can take inputs of either float or int type. So basically, I want <code>f(5)</code> and <code>f(5.5)</code> to be acceptable inputs.</p>
<p>I don't think I can use <code>if (!PyArg_ParseTuple(args, "i", $value))</code> because it only takes only int or only float.</p>
<p>How can I make my function allow inputs that are either ints or floats?</p>
<p>I'm wondering if I should just take the input and put it into a PyObject and somehow take the type of the PyObject - is that the right approach?</p>
| 9 | 2016-10-04T04:19:43Z | 39,844,489 | <p>You can check type of input value like this:</p>
<pre><code> PyObject* check_type(PyObject*self, PyObject*args) {
PyObject*any;
if (!PyArg_ParseTuple(args, "O", &any)) {
PyErr_SetString(PyExc_TypeError, "Nope.");
return NULL;
}
if (PyFloat_Check(any)) {
printf("indeed float");
}
else {
printf("\nint\n");
}
Py_INCREF(Py_None);
return Py_None;
}
</code></pre>
<p>You can extract float value from object using: </p>
<pre><code>double result=PyFloat_AsDouble(any);
</code></pre>
<p>But in this particular situation probably no need to do this, no matter what you parsing int or float you can grab it as a float and check on roundness: </p>
<pre><code> float target;
if (!PyArg_ParseTuple(args, "f", &target)) {
PyErr_SetString(PyExc_TypeError, "Nope.");
return NULL;
}
if (target - (int)target) {
printf("\n input is float \n");
}
else {
printf("\n input is int \n");
}
</code></pre>
| 1 | 2016-10-04T05:03:01Z | [
"python",
"c",
"python-extensions"
]
|
How can I write a C function that takes either an int or a float? | 39,844,100 | <p>I want to create a function in C that extends Python that can take inputs of either float or int type. So basically, I want <code>f(5)</code> and <code>f(5.5)</code> to be acceptable inputs.</p>
<p>I don't think I can use <code>if (!PyArg_ParseTuple(args, "i", $value))</code> because it only takes only int or only float.</p>
<p>How can I make my function allow inputs that are either ints or floats?</p>
<p>I'm wondering if I should just take the input and put it into a PyObject and somehow take the type of the PyObject - is that the right approach?</p>
| 9 | 2016-10-04T04:19:43Z | 39,845,432 | <p>If you declare a C function to accept floats, the compiler won't complain if you hand it an int. For instance, this program produces the answer 2.000000:</p>
<pre><code>#include <stdio.h>
float f(float x) {
return x+1;
}
int main() {
int i=1;
printf ("%f", f(i));
}
</code></pre>
<p>A python module version, iorf.c:</p>
<pre><code>#include <Python.h>
static PyObject *IorFError;
float f(float x) {
return x+1;
}
static PyObject *
fwrap(PyObject *self, PyObject *args) {
float in=0.0;
if (!PyArg_ParseTuple(args, "f", &in))
return NULL;
return Py_BuildValue("f", f(in));
}
static PyMethodDef IorFMethods[] = {
{"fup", fwrap, METH_VARARGS,
"Arg + 1"},
{NULL, NULL, 0, NULL} /* Sentinel */
};
PyMODINIT_FUNC
initiorf(void)
{
PyObject *m;
m = Py_InitModule("iorf", IorFMethods);
if (m == NULL)
return;
IorFError = PyErr_NewException("iorf.error", NULL, NULL);
Py_INCREF(IorFError);
PyModule_AddObject(m, "error", IorFError);
}
</code></pre>
<p>The setup.py:</p>
<pre><code>from distutils.core import setup, Extension
module1 = Extension('iorf',
sources = ['iorf.c'])
setup (name = 'iorf',
version = '0.1',
description = 'This is a test package',
ext_modules = [module1])
</code></pre>
<p>An example:</p>
<pre><code>03:21 $ python
Python 2.7.10 (default, Jul 30 2016, 18:31:42)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import iorf
>>> print iorf.fup(2)
3.0
>>> print iorf.fup(2.5)
3.5
</code></pre>
| 5 | 2016-10-04T06:23:21Z | [
"python",
"c",
"python-extensions"
]
|
How can I write a C function that takes either an int or a float? | 39,844,100 | <p>I want to create a function in C that extends Python that can take inputs of either float or int type. So basically, I want <code>f(5)</code> and <code>f(5.5)</code> to be acceptable inputs.</p>
<p>I don't think I can use <code>if (!PyArg_ParseTuple(args, "i", $value))</code> because it only takes only int or only float.</p>
<p>How can I make my function allow inputs that are either ints or floats?</p>
<p>I'm wondering if I should just take the input and put it into a PyObject and somehow take the type of the PyObject - is that the right approach?</p>
| 9 | 2016-10-04T04:19:43Z | 39,846,368 | <p>Floats are (usually) passed in via registers while ints are (usually) passed in via the stack. This means that you literally cannot, inside the function, check whether the argument is a float or an int.</p>
<p>The only workaround is to use variadic arguments, with the first argument specifying the type as either int or double (not float).</p>
<pre><code>func_int_or_double (uint8_t type, ...) {
va_list ap;
va_start (ap, type);
int intarg;
double doublearg;
if (type==1) {
intarg = va_arg (ap, int);
}
if (type==2) {
doublearg = va_arg (ap, double);
}
va_end (ap);
// Your code goes here
}
</code></pre>
<p>Although, I'm not really sure if python can handle calling variadic functions, so YMMV. As a last ditch-effort you can always sprintf the value into a buffer and let your function sscanf float/int from the buffer.</p>
| 1 | 2016-10-04T07:18:03Z | [
"python",
"c",
"python-extensions"
]
|
PermissionError: [Errno 13] Permission denied @ PYTHON | 39,844,123 | <p>i am trying to copy a file from one folder to another, but i am getting "PermissionError: [Errno 13] Permission denied". I am working within my home directory and i am the administrator of the PC. Went through many other previous posts .. tried all the options that are to my knowledge (newbie to programming) ... need some help.</p>
<pre><code>import os
import shutil
src = "C:\\Users\\chzia\\Scripts\\test" # the file lab.txt is in this folder that needs to be copied to testcp folder.
dst = "C:\\Users\\chzia\\Scripts\\testcp"
for file in os.listdir(src):
src_file = os.path.join(src, file)
dst_file = os.path.join(dst, file)
#shutil.copymode(src, dst) # i have tried these options too same error
#shutil.copyfile(src, dst) # i have tried these options too same error
shutil.copy(src, dst)
</code></pre>
<p>My target is to create an .exe that copies a file from the network location to a specific folder on a pc where the .exe is run.
Thanks in advance for all the support and help. </p>
| -1 | 2016-10-04T04:22:24Z | 39,844,477 | <p>Perhaps try to use shutil.copyfile instead:</p>
<pre><code>shutil.copyfile(src, dst)
</code></pre>
<p>Similar old topic on <a href="http://stackoverflow.com/questions/11835833/why-would-shutil-copy-raise-a-permission-exception-when-cp-doesnt">Why would shutil.copy() raise a permission exception when cp doesn't?</a></p>
| 1 | 2016-10-04T05:02:12Z | [
"python",
"shutil"
]
|
Find common values in dictionary that has keys with multiple values | 39,844,141 | <p>I am new to python and I have a problem. I am trying to find keys with a value; however, the keys have multiple values.</p>
<pre><code>d = {
'a': ['john', 'doe', 'jane'],
'b': ['james', 'danny', 'john'],
'C':['john', 'scott', 'jane'],
}
</code></pre>
<p>I want to find the value <code>john</code> in d and get the keys a, b and c or find <code>jane</code> and get keys a and c.</p>
| 0 | 2016-10-04T04:24:26Z | 39,844,174 | <p>This can easily be done using a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>. It iterates over every key/value pair from the dict's items list, which contains all key/value pairs (<code>for key,val in d.items()</code>) and selects only the pairs where the target string is contained in the value list (<code>if 'john' in val</code>), building a list out of the resulting keys (<code>[ key ... ]</code>).</p>
<pre><code>>>> [ key for key,val in d.items() if 'john' in val ]
['b', 'a', 'C']
>>> [ key for key,val in d.items() if 'jane' in val ]
['a', 'C']
</code></pre>
| 1 | 2016-10-04T04:29:05Z | [
"python",
"python-2.7",
"dictionary"
]
|
Find common values in dictionary that has keys with multiple values | 39,844,141 | <p>I am new to python and I have a problem. I am trying to find keys with a value; however, the keys have multiple values.</p>
<pre><code>d = {
'a': ['john', 'doe', 'jane'],
'b': ['james', 'danny', 'john'],
'C':['john', 'scott', 'jane'],
}
</code></pre>
<p>I want to find the value <code>john</code> in d and get the keys a, b and c or find <code>jane</code> and get keys a and c.</p>
| 0 | 2016-10-04T04:24:26Z | 39,844,227 | <p>So you have to go through the dictionary items and if the find keyword is in the item list then the corresponding key has to be stored in a list and this list has to be displayed.</p>
<pre><code>d = {'a':['john', 'doe', 'jane'], 'b': ['james', 'danny', 'john'], 'C':['john', 'scott', 'jane'],}
find ='jane'
</code></pre>
<p>So this is how the logic is written in python</p>
<pre><code>print ([m for m in d.keys() if find in d[m]])
</code></pre>
<p>And it will give the following output</p>
<pre><code>['a', 'C']
</code></pre>
| 1 | 2016-10-04T04:35:23Z | [
"python",
"python-2.7",
"dictionary"
]
|
In Django, how do I order_by() when reaching across tables? | 39,844,200 | <p>I'm trying to filter my Friendships objects and then order_by user.first_name, but it's not working. Can anyone tell me what I'm doing wrong?</p>
<p>Here's my models:</p>
<pre><code>class Friendships(models.Model):
user = models.ForeignKey('Users', models.DO_NOTHING, related_name="usersfriend")
friend = models.ForeignKey('Users', models.DO_NOTHING, related_name ="friendsfriend")
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'friendships'
class Users(models.Model):
first_name = models.CharField(max_length=45, blank=True, null=True)
last_name = models.CharField(max_length=45, blank=True, null=True)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'users'
</code></pre>
<p>My query is as follows, which returns my needed Friendships, but the order is not correct. I've tried a number of different combinations and examples but just am not sure what I'm not correctly understanding:</p>
<p>My query in my controller:</p>
<pre><code>ordered_friends = Friendships.objects.filter(user__id=1).order_by('user__first_name')
for ordered_friend in ordered_friends:
print ordered_friend.friend.first_name, ordered_friend.friend.last_name
</code></pre>
<p>Note, I've tried a number of combinations in place of <code>user__first_name</code> and I know this is where I'm failing.</p>
| 1 | 2016-10-04T04:32:13Z | 39,844,333 | <p>It's not your order by that's wrong but what you do with the results. Let us digest the following, particularly line 3</p>
<pre><code>ordered_friends = Friendships.objects.filter(user__id=1).order_by('user__first_name')
for ordered_friend in ordered_friends:
print ordered_friend.friend.first_name, ordered_friend.friend.last_name
</code></pre>
<p>In <code>ordered_friend</code> you have an instance of <code>FriendShip</code> each ordered_friend is returned to you in that <code>ordered_friend</code>'s username. But having obtained an <code>ordered_friend</code>, you then do <code>ordered_friend.friend</code> but this is not the column that you orderd by so it's not surprising that the items don't get printed in alphabetical order. You porbably meant to do</p>
<pre><code>print ordered_friend.user.first_name, ordered_friend.user.last_name
</code></pre>
<p>or did you perhaps intend to sort by friend in the first place?</p>
<pre><code>Friendships.objects.filter(user__id=1).order_by('friend__first_name')
</code></pre>
| 2 | 2016-10-04T04:45:49Z | [
"python",
"django",
"orm"
]
|
Python AST to dictionary structure | 39,844,212 | <p>I am using the Python <code>ast</code> module to parse expressions like <code>X >= 13 and Y == W</code>. What I need is to transform this expression in a pre-order dictionary found below:</p>
<pre><code>{
"function": "and",
"args": [
{
"function": ">=",
"args": [
{
"variable": "X"
},
{
"value": 13
}
]
},
{
"function": "==",
"args": [
{
"variable": "Y"
},
{
"variable": "W"
}
]
}
]
}
</code></pre>
<p>Python AST gives me the benefit of validating syntax and differencing variables from values. The following code does a basic parsing but notice the output is not pre-order and I'm not entirely sure how to procede:</p>
<pre><code>import ast
class ExclusionParser(ast.NodeVisitor):
tree = ''
def append(self, expr):
self.tree += expr
def visit_And(self, node):
self.append("and ")
def visit_Lt(self, node):
self.append("< ")
def visit_Gt(self, node):
self.append("> ")
def visit_Eq(self, node):
self.append("== ")
def visit_Num(self, node):
self.append("value: %s " % node.n)
def visit_Name(self, node):
self.append("variable: %s " % node.id)
def generic_visit(self, node):
"""Called if no explicit visitor function exists for a node."""
self.append("(")
for field, value in ast.iter_fields(node):
if isinstance(value, list):
for item in value:
if isinstance(item, ast.AST):
self.visit(item)
elif isinstance(value, ast.AST):
self.visit(value)
self.append(")")
if __name__ == '__main__':
v = ExclusionParser()
p = ast.parse("X > 13 and Y == W")
v.visit(p)
print(v.tree)
</code></pre>
<p><strong>output</strong></p>
<pre><code>(((and (variable: X > value: 13 )(variable: Y == variable: W ))))
</code></pre>
| 1 | 2016-10-04T04:33:42Z | 39,848,149 | <p>Consider these small changes - I've added <code>'</code>s and commas:</p>
<pre><code>import ast
class ExclusionParser(ast.NodeVisitor):
tree = ''
def append(self, expr):
self.tree += expr
def visit_And(self, node):
self.append("'func:and', ")
def visit_Lt(self, node):
self.append("'func:lt', ")
def visit_Gt(self, node):
self.append("'func:gt', ")
def visit_Eq(self, node):
self.append("'func:eq', ")
def visit_Num(self, node):
self.append("'value:%s', " % node.n)
def visit_Name(self, node):
self.append("'variable:%s', " % node.id)
def generic_visit(self, node):
"""Called if no explicit visitor function exists for a node."""
self.append("[")
for field, value in ast.iter_fields(node):
if isinstance(value, list):
for item in value:
if isinstance(item, ast.AST):
self.visit(item)
elif isinstance(value, ast.AST):
self.visit(value)
self.append("], ")
if __name__ == '__main__':
v = ExclusionParser()
p = ast.parse("X > 13 and Y == W")
v.visit(p)
tree = ast.literal_eval(v.tree[:-2])
print(tree)
</code></pre>
<p>At this point <code>tree</code> is a valid list:</p>
<pre><code>[[['func:and', ['variable:X', 'func:gt', 'value:13'], ['variable:Y', 'func:eq', 'variable:W']]]]
</code></pre>
<p>If you've written <code>generic_visit</code> you shouldn't face any difficulties in writing another recursive function that will convert this list of lists into a dictionary. The solution is a bit hacky. (And by "a bit" I mean it's really hacky.) The proper solution would be to modify <code>generic_visit</code>, I suppose.</p>
<p>And on a separate note: dictionaries don't preserve the order of theirs elements. Use <code>OrderedDict</code> to ensure <code>function</code> key goes first.</p>
| 1 | 2016-10-04T08:58:18Z | [
"python",
"json",
"abstract-syntax-tree"
]
|
Keras convolution filter size issue | 39,844,273 | <p>I'm <em>very</em> new to Keras, and in my early experiments I've been encountering an error when I create convolutional layers. When I run this code (found <a href="https://keras.io/getting-started/functional-api-guide/#more-examples" rel="nofollow" title="here">here</a>; "Shared vision model" section)</p>
<pre><code>from keras.models import *
from keras.layers import *
from keras.layers.convolutional import *
from keras.layers.pooling import *
digit_input = Input(shape=(1, 27, 27))
x = Convolution2D(64, 3, 3)(digit_input)
x = MaxPooling2D((2, 2))(x)
mdl = Model(digit_input, x)
</code></pre>
<p>I get the following error (traceback points to the Convolution2D line):</p>
<pre><code>ValueError: Filter must not be larger than the input: Filter: (3, 3) Input: (1, 27)
</code></pre>
<p>I'd assume I was misusing the interface--especially since no one else seems to have this particular problem--but I pulled the code directly from the Keras docs. The problem persists when I use the <code>model.add()</code> syntax. Interestingly though, when I shrink the filter size to 1x1 or increase the number of input channels to 3, the error goes away. I have tried manually setting <code>dim_ordering='tf'</code> for the convolution and my keras.json file reads:</p>
<pre><code>{
"image_dim_ordering": "tf",
"epsilon": 1e-07,
"floatx": "float32",
"backend": "tensorflow"
}
</code></pre>
<p>Keras looks like a great tool, but I'm completely unable to use it so far. </p>
<p>P.S. I am using Keras 1.1.0 and Tensorflow 0.10. </p>
| 0 | 2016-10-04T04:39:51Z | 39,847,099 | <p>'image_dim_ordering' : 'tf' is setting the input's third dimension as the channel input to the 2D Convolution: ie you've currently put a 1x27 input with 27 channels in to be convolved with a 3x3 kernel and no padding.</p>
<p>You should be able to switch 'image_dim_ordering' to 'th' and have this code immediately work. I think 'th' used to be the default and you've unfortunately hit an obsolete tutorial. Here's the Keras documentation from <a href="https://keras.io/layers/convolutional/" rel="nofollow">Convolution2D</a> - it's there but not particularly prominent:</p>
<blockquote>
<p>dim_ordering: 'th' or 'tf'. In 'th' mode, the channels dimension (the depth) is at index 1, in 'tf' mode is it at index 3. It defaults to the image_dim_ordering value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be "tf".</p>
</blockquote>
<p>Hope that helps!</p>
| 0 | 2016-10-04T07:58:49Z | [
"python",
"neural-network",
"tensorflow",
"convolution",
"keras"
]
|
Checking if string contains valid Python code | 39,844,350 | <p>I am writing some sort of simple web-interpreter for vk.com . I look for messages, check if they are valid Python code, and then I want to execute that code, and return any <code>stdout</code> to code sender. I have implemented anything but code checker.</p>
<pre><code>import ast
def is_valid(code):
try:
ast.parse(code)
except SyntaxError:
print('Input isnt code.')
return False
print('Code is ok.')
return True
</code></pre>
<p><code>is_valid()</code> always return <code>True</code> regardless of what comes in. Im really confused... </p>
| 0 | 2016-10-04T04:48:40Z | 39,844,402 | <p>Keep in mind, the difference between a runtime error and a parser error is significant in your case and example. The statement:</p>
<pre><code>test
</code></pre>
<p>is <em>valid</em> code. Even though this statement will throw a <code>NameError</code> when the Python VM executes the code, the parser will not know that it actually wasn't assigned a value before the statement is parsed, so that's why it's a runtime error, and not a syntax error.</p>
| 1 | 2016-10-04T04:54:34Z | [
"python"
]
|
Find the subset of a set of integers that has the maximum product | 39,844,473 | <p>Let A be a non-empty set of integers. Write a function <strong>find</strong> that outputs a non-empty subset of A that has the maximum product. For example, <strong>find([-1, -2, -3, 0, 2]) = 12 = (-2)*(-3)*2</strong></p>
<p>Here's what I think: divide the list into a list of positive integers and a list of negative integers:</p>
<ol>
<li>If we have an even number of negative integers, multiply everything in both list and we have the answer. </li>
<li>If we have an odd number of negative integers, find the largest and remove it from the list. Then multiply everything in both lists. </li>
<li>If the list has only one element, return this element.</li>
</ol>
<p>Here's my code in Python:</p>
<pre><code>def find(xs):
neg_int = []
pos_int = []
if len(xs) == 1:
return str(xs[0])
for i in xs:
if i < 0:
neg_int.append(i)
elif i > 0:
pos_int.append(i)
if len(neg_int) == 1 and len(pos_int) == 0 and 0 in xs:
return str(0)
if len(neg_int) == len(pos_int) == 0:
return str(0)
max = 1
if len(pos_int) > 0:
for x in pos_int:
max=x*max
if len(neg_int) % 2 == 1:
max_neg = neg_int[0]
for j in neg_int:
if j > max_neg:
max_neg = j
neg_int.remove(max_neg)
for k in neg_int:
max = k*max
return str(max)
</code></pre>
<p>Am I missing anything? P.S. This is a problem from Google's foobar challenge, I am apparently missing one case but I don't know which.</p>
<p>Now here's actual problem:
<a href="http://i.stack.imgur.com/zAw0f.png"><img src="http://i.stack.imgur.com/zAw0f.png" alt="enter image description here"></a></p>
| 8 | 2016-10-04T05:01:53Z | 39,844,702 | <p>You can simplify this problem with <code>reduce</code> (in <code>functools</code> in Py3)</p>
<pre><code>import functools as ft
from operator import mul
def find(ns):
if len(ns) == 1 or len(ns) == 2 and 0 in ns:
return str(max(ns))
pos = filter(lambda x: x > 0, ns)
negs = sorted(filter(lambda x: x < 0, ns))
return str(ft.reduce(mul, negs[:-1 if len(negs)%2 else None], 1) * ft.reduce(mul, pos, 1))
>>> find([-1, -2, -3, 0, 2])
'12'
>>> find([-3, 0])
'0'
>>> find([-1])
'-1'
>>> find([])
'1'
</code></pre>
| 1 | 2016-10-04T05:22:16Z | [
"python",
"algorithm"
]
|
Find the subset of a set of integers that has the maximum product | 39,844,473 | <p>Let A be a non-empty set of integers. Write a function <strong>find</strong> that outputs a non-empty subset of A that has the maximum product. For example, <strong>find([-1, -2, -3, 0, 2]) = 12 = (-2)*(-3)*2</strong></p>
<p>Here's what I think: divide the list into a list of positive integers and a list of negative integers:</p>
<ol>
<li>If we have an even number of negative integers, multiply everything in both list and we have the answer. </li>
<li>If we have an odd number of negative integers, find the largest and remove it from the list. Then multiply everything in both lists. </li>
<li>If the list has only one element, return this element.</li>
</ol>
<p>Here's my code in Python:</p>
<pre><code>def find(xs):
neg_int = []
pos_int = []
if len(xs) == 1:
return str(xs[0])
for i in xs:
if i < 0:
neg_int.append(i)
elif i > 0:
pos_int.append(i)
if len(neg_int) == 1 and len(pos_int) == 0 and 0 in xs:
return str(0)
if len(neg_int) == len(pos_int) == 0:
return str(0)
max = 1
if len(pos_int) > 0:
for x in pos_int:
max=x*max
if len(neg_int) % 2 == 1:
max_neg = neg_int[0]
for j in neg_int:
if j > max_neg:
max_neg = j
neg_int.remove(max_neg)
for k in neg_int:
max = k*max
return str(max)
</code></pre>
<p>Am I missing anything? P.S. This is a problem from Google's foobar challenge, I am apparently missing one case but I don't know which.</p>
<p>Now here's actual problem:
<a href="http://i.stack.imgur.com/zAw0f.png"><img src="http://i.stack.imgur.com/zAw0f.png" alt="enter image description here"></a></p>
| 8 | 2016-10-04T05:01:53Z | 39,844,742 | <p>Here is another solution that doesn't require libraries :</p>
<pre><code>def find(l):
if len(l) <= 2 and 0 in l: # This is the missing case, try [-3,0], it should return 0
return max(l)
l = [e for e in l if e != 0] # remove 0s
r = 1
for e in l: # multiply all
r *= e
if r < 0: # if the result is negative, remove biggest negative number and retry
l.remove(max([e for e in l if e < 0]))
r = find(l)
return r
print(find([-1, -2, -3, 0, 2])) # 12
print(find([-3, 0])) # 0
</code></pre>
<p><strong>EDIT :</strong></p>
<p>I think I've found the missing case which is when there are only two elements in the list, and the highest is 0.</p>
| 0 | 2016-10-04T05:26:38Z | [
"python",
"algorithm"
]
|
Find the subset of a set of integers that has the maximum product | 39,844,473 | <p>Let A be a non-empty set of integers. Write a function <strong>find</strong> that outputs a non-empty subset of A that has the maximum product. For example, <strong>find([-1, -2, -3, 0, 2]) = 12 = (-2)*(-3)*2</strong></p>
<p>Here's what I think: divide the list into a list of positive integers and a list of negative integers:</p>
<ol>
<li>If we have an even number of negative integers, multiply everything in both list and we have the answer. </li>
<li>If we have an odd number of negative integers, find the largest and remove it from the list. Then multiply everything in both lists. </li>
<li>If the list has only one element, return this element.</li>
</ol>
<p>Here's my code in Python:</p>
<pre><code>def find(xs):
neg_int = []
pos_int = []
if len(xs) == 1:
return str(xs[0])
for i in xs:
if i < 0:
neg_int.append(i)
elif i > 0:
pos_int.append(i)
if len(neg_int) == 1 and len(pos_int) == 0 and 0 in xs:
return str(0)
if len(neg_int) == len(pos_int) == 0:
return str(0)
max = 1
if len(pos_int) > 0:
for x in pos_int:
max=x*max
if len(neg_int) % 2 == 1:
max_neg = neg_int[0]
for j in neg_int:
if j > max_neg:
max_neg = j
neg_int.remove(max_neg)
for k in neg_int:
max = k*max
return str(max)
</code></pre>
<p>Am I missing anything? P.S. This is a problem from Google's foobar challenge, I am apparently missing one case but I don't know which.</p>
<p>Now here's actual problem:
<a href="http://i.stack.imgur.com/zAw0f.png"><img src="http://i.stack.imgur.com/zAw0f.png" alt="enter image description here"></a></p>
| 8 | 2016-10-04T05:01:53Z | 39,846,442 | <pre><code>from functools import reduce
from operator import mul
def find(array):
negative = []
positive = []
zero = None
removed = None
def string_product(iterable):
return str(reduce(mul, iterable, 1))
for number in array:
if number < 0:
negative.append(number)
elif number > 0:
positive.append(number)
else:
zero = str(number)
if negative:
if len(negative) % 2 == 0:
return string_product(negative + positive)
removed = max(negative)
negative.remove(removed)
if negative:
return string_product(negative + positive)
if positive:
return string_product(positive)
return zero or str(removed)
</code></pre>
| 1 | 2016-10-04T07:22:22Z | [
"python",
"algorithm"
]
|
Find the subset of a set of integers that has the maximum product | 39,844,473 | <p>Let A be a non-empty set of integers. Write a function <strong>find</strong> that outputs a non-empty subset of A that has the maximum product. For example, <strong>find([-1, -2, -3, 0, 2]) = 12 = (-2)*(-3)*2</strong></p>
<p>Here's what I think: divide the list into a list of positive integers and a list of negative integers:</p>
<ol>
<li>If we have an even number of negative integers, multiply everything in both list and we have the answer. </li>
<li>If we have an odd number of negative integers, find the largest and remove it from the list. Then multiply everything in both lists. </li>
<li>If the list has only one element, return this element.</li>
</ol>
<p>Here's my code in Python:</p>
<pre><code>def find(xs):
neg_int = []
pos_int = []
if len(xs) == 1:
return str(xs[0])
for i in xs:
if i < 0:
neg_int.append(i)
elif i > 0:
pos_int.append(i)
if len(neg_int) == 1 and len(pos_int) == 0 and 0 in xs:
return str(0)
if len(neg_int) == len(pos_int) == 0:
return str(0)
max = 1
if len(pos_int) > 0:
for x in pos_int:
max=x*max
if len(neg_int) % 2 == 1:
max_neg = neg_int[0]
for j in neg_int:
if j > max_neg:
max_neg = j
neg_int.remove(max_neg)
for k in neg_int:
max = k*max
return str(max)
</code></pre>
<p>Am I missing anything? P.S. This is a problem from Google's foobar challenge, I am apparently missing one case but I don't know which.</p>
<p>Now here's actual problem:
<a href="http://i.stack.imgur.com/zAw0f.png"><img src="http://i.stack.imgur.com/zAw0f.png" alt="enter image description here"></a></p>
| 8 | 2016-10-04T05:01:53Z | 39,876,069 | <p>Here's a solution in one loop:</p>
<pre><code>def max_product(A):
"""Calculate maximal product of elements of A"""
product = 1
greatest_negative = float("-inf") # greatest negative multiplicand so far
for x in A:
product = max(product, product*x, key=abs)
if x <= -1:
greatest_negative = max(x, greatest_negative)
return max(product, product // greatest_negative)
assert max_product([2,3]) == 6
assert max_product([-2,-3]) == 6
assert max_product([-1, -2, -3, 0, 2]) == 12
assert max_product([]) == 1
assert max_product([-5]) == 1
</code></pre>
<p>Extra credit: what if the integer constraint were relaxed? What extra information do you need to collect during the loop?</p>
| 1 | 2016-10-05T14:00:41Z | [
"python",
"algorithm"
]
|
"'CXXABI_1.3.8' not found" in tensorflow-gpu - install from source | 39,844,772 | <p>I have re-installed Anaconda2.
And I got the following error when 'python -c 'import tensorflow''</p>
<blockquote>
<p>ImportError: /home/jj/anaconda2/bin/../lib/libstdc++.so.6: version `CXXABI_1.3.8' not found (required by /home/jj/anaconda2/lib/python2.7/site-packages/tensorflow/python/_pywrap_tensorflow.so)</p>
</blockquote>
<h3>environment</h3>
<ul>
<li>CUDA8.0</li>
<li>cuDNN 5.1</li>
<li>gcc 5.4.1</li>
<li>tensorflow r0.10 </li>
<li>Anaconda2 : 4.2</li>
</ul>
<h3>the following is in bashrc file</h3>
<ul>
<li>export PATH="/home/jj/anaconda2/bin:$PATH"</li>
<li>export CUDA_HOME=/usr/local/cuda-8.0</li>
<li>export PATH=/usr/local/cuda-8.0/bin${PATH:+:${PATH}}</li>
<li>export LD_LIBRARY_PATH=/usr/local/cuda-8.0/lib64${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}</li>
</ul>
| 1 | 2016-10-04T05:30:04Z | 39,856,855 | <p>I solved this problem by copying the <code>libstdc++.so.6</code> file which contains version <code>CXXABI_1.3.8</code>. </p>
<p>Try run the following search command first:</p>
<p><code>$ strings /usr/lib/x86_64-linux-gnu/libstdc++.so.6 | grep CXXABI_1.3.8</code></p>
<p>If it returns <code>CXXABI_1.3.8</code>. Then you can do the copying.</p>
<p><code>$ cp /usr/lib/x86_64-linux-gnu/libstdc++.so.6 /home/jj/anaconda2/bin/../lib/libstdc++.so.6</code></p>
| 1 | 2016-10-04T15:56:55Z | [
"python",
"tensorflow",
"cudnn"
]
|
using variable name within list as string for file save python | 39,844,823 | <p>I have a python list which contains 4 elements, each of which is a time-series dataset.
e.g., </p>
<pre><code>full_set = [Apple_px, Banana_px, Celery_px]
</code></pre>
<p>I am charting them via matplotlib and I want to save the charts individually using the variable names. </p>
<pre><code>for n in full_set:
*perform analysis
plt.savefig("Chart_{}.png".format(n))
</code></pre>
<p>The ideal output would have Chart_Apple_px, Chart_Banana_px, Chart_Celery_px as the chart names.</p>
| 0 | 2016-10-04T05:34:38Z | 39,844,999 | <p>In Python names and values are two very different things, stored and dealt with in different ways - and more practically one value can have multiple names assigned to it.</p>
<p>So, instead of trying to get the name of some data value, use a tuple where you assign a title to the dataset in your list of datasets, something like this:</p>
<pre><code>full_set = [('Chart_Apple_px', Apple_px), ('Chart_Banana_px', Banana_px)]
for chart_name, dataset in full_set:
# do your calculations on the dataset
plt.savefig("{}.png".format(chart_name))
</code></pre>
| 0 | 2016-10-04T05:50:09Z | [
"python",
"matplotlib"
]
|
How to add prefix to files' names, replace a character, and move to new directory? | 39,844,829 | <p>For example, the files will look like <code>FG-4.jpg</code> <code>FG-5.jpg</code>, etc. and need to be copied to a new directory and named <code>test_FG_4.jpg</code> <code>test_FG_5.jpg</code>, etc. </p>
<p>Here is the updated code:</p>
<pre><code>import shutil
import glob
import os
InFolder = r"C:\test_in"
OutFolder = r"C:\test_out"
for f in glob.glob('*'):
shutil.move(InFolder/*, OutFolder, copy_function=copy2)
os.listdir(OutFolder)
new_filename = f.replace("-","_")
new_filename = "test_" + new_filename
os.rename(f,new_filename)
</code></pre>
<p>I'm getting the error </p>
<pre><code>File "c:\copyRename2.py", line 8, in ?
shutil.move(InFolder/*, OutFolder, copy_function=copy2)
invalid syntax: copyRename2.py, line 8, pos 26 in file c:\copyRename2.py, line 8
shutil.move(InFolder/*, OutFolder, copy_function=copy2)
</code></pre>
<p>First attempt: </p>
<pre><code>import shutil
import glob
import os
InFolder = r"C:\test_in"
OutFolder = r"C:\test_out"
for f in glob.glob('*'):
shutil.copyfile(f, OutFolder)
new_filename = f.replace("-","_")
new_filename = "test_" + new_filename
os.rename(f,new_filename)
</code></pre>
| 0 | 2016-10-04T05:35:29Z | 39,845,097 | <p>I am not sure about what you want. So this program checks for any file with extension .jpg and then copies them into a new folder("NewDir") by adding "Test_" to the file name. If the folder doesn't exist, the program creates the folder. Maybe you can make the changes you need based on this program.</p>
<pre><code>import shutil
import os
newdir="NewDir"
for m in (os.listdir()):
if m[-4:]==(".txt"):
if os.path.isdir(newdir):
shutil.copy(m,newdir+"/"+"Test_"+m)
else:
os.mkdir(newdir)
shutil.copy(m,newdir+"/"+"Test_"+m)
</code></pre>
| 0 | 2016-10-04T05:57:44Z | [
"python",
"replace",
"rename"
]
|
Pandas slow on data frame replace | 39,844,967 | <p>I have an Excel file (.xlsx) with about 800 rows and 128 columns with pretty dense data in the grid. There are about 9500 cells that I am trying to replace the cell values of using Pandas data frame:</p>
<pre><code>xlsx = pandas.ExcelFile(filename)
frame = xlsx.parse(xlsx.sheet_names[0])
media_frame = frame[media_headers] # just get the cols that need replacing
from_filenames = get_from_filenames() # returns ~9500 filenames to replace in DF
to_filenames = get_to_filenames()
media_frame = media_frame.replace(from_filenames, to_filenames)
frame.update(media_frame)
frame.to_excel(filename)
</code></pre>
<p>The <code>replace()</code> takes 60 seconds. Any way to speed this up? This is not huge data or task, I was expecting pandas to move much faster. FYI I tried doing the same processing with same file in CSV, but the time savings was minimal (about 50 seconds on the <code>replace()</code>)</p>
| 4 | 2016-10-04T05:48:04Z | 39,846,474 | <p><strong><em>strategy</em></strong><br>
create <code>pd.Series</code> representing a <code>map</code> from filenames to filenames.<br>
<code>stack</code> our dataframe, <code>map</code>, then <code>unstack</code></p>
<p><strong><em>setup</em></strong> </p>
<pre><code>import pandas as pd
import numpy as np
from string import letters
media_frame = pd.DataFrame(
pd.DataFrame(
np.random.choice(list(letters), 9500 * 800 * 3) \
.reshape(3, -1)).sum().values.reshape(9500, -1))
u = np.unique(media_frame.values)
from_filenames = pd.Series(u)
to_filenames = from_filenames.str[1:] + from_filenames.str[0]
m = pd.Series(to_filenames.values, from_filenames.values)
</code></pre>
<p><strong><em>solution</em></strong> </p>
<pre><code>media_frame.stack().map(m).unstack()
</code></pre>
<hr>
<h1>timing</h1>
<p><strong><em>5 x 5 dataframe</em></strong></p>
<p><a href="http://i.stack.imgur.com/jZbck.png" rel="nofollow"><img src="http://i.stack.imgur.com/jZbck.png" alt="enter image description here"></a></p>
<p><strong><em>100 x 100</em></strong></p>
<p><a href="http://i.stack.imgur.com/199TE.png" rel="nofollow"><img src="http://i.stack.imgur.com/199TE.png" alt="enter image description here"></a></p>
<p><strong><em>9500 x 800</em></strong></p>
<p><a href="http://i.stack.imgur.com/117t8.png" rel="nofollow"><img src="http://i.stack.imgur.com/117t8.png" alt="enter image description here"></a></p>
<p><strong><em>9500 x 800</em></strong><br>
<code>map</code> using <code>series</code> vs <code>dict</code><br>
<code>d = dict(zip(from_filenames, to_filenames))</code></p>
<p><a href="http://i.stack.imgur.com/Sw2V3.png" rel="nofollow"><img src="http://i.stack.imgur.com/Sw2V3.png" alt="enter image description here"></a></p>
| 4 | 2016-10-04T07:24:28Z | [
"python",
"excel",
"pandas",
"dataframe"
]
|
Pandas slow on data frame replace | 39,844,967 | <p>I have an Excel file (.xlsx) with about 800 rows and 128 columns with pretty dense data in the grid. There are about 9500 cells that I am trying to replace the cell values of using Pandas data frame:</p>
<pre><code>xlsx = pandas.ExcelFile(filename)
frame = xlsx.parse(xlsx.sheet_names[0])
media_frame = frame[media_headers] # just get the cols that need replacing
from_filenames = get_from_filenames() # returns ~9500 filenames to replace in DF
to_filenames = get_to_filenames()
media_frame = media_frame.replace(from_filenames, to_filenames)
frame.update(media_frame)
frame.to_excel(filename)
</code></pre>
<p>The <code>replace()</code> takes 60 seconds. Any way to speed this up? This is not huge data or task, I was expecting pandas to move much faster. FYI I tried doing the same processing with same file in CSV, but the time savings was minimal (about 50 seconds on the <code>replace()</code>)</p>
| 4 | 2016-10-04T05:48:04Z | 39,847,753 | <p>I got the 60 second task to complete in 10 seconds by removing <code>replace()</code> altogether and using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_value.html" rel="nofollow">set_value()</a> one element at a time.</p>
| 1 | 2016-10-04T08:38:29Z | [
"python",
"excel",
"pandas",
"dataframe"
]
|
Sorting a string to make a new one | 39,845,025 | <p>Here I had to remove the most frequent alphabet of a string(if frequency of two alphabets is same, then in alphabetical order) and put it into new string.</p>
<p>Input:</p>
<pre><code>abbcccdddd
</code></pre>
<p>Output:</p>
<pre><code>dcdbcdabcd
</code></pre>
<p>The code I wrote is:</p>
<pre><code>s = list(sorted(<the input string>))
a = []
for c in range(len(s)):
freq =[0 for _ in range(26)]
for x in s:
freq[ord(x)-ord('a')] += 1
m = max(freq)
allindices = [p for p,q in enumerate(freq) if q == m]
r = chr(97+allindices[0])
a.append(r)
s.remove(r)
print''.join(a)
</code></pre>
<p>But it passed the allowed runtime limit maybe due to too many loops.(There's another for loop which seperates the strings from user input)</p>
<p>I was hoping if someone could suggest a more optimised version of it using less memory space. </p>
| 2 | 2016-10-04T05:52:19Z | 39,871,672 | <p>What about this?
I am making use of in-built python functions to eliminate loops and improve efficiency.</p>
<pre><code>test_str = 'abbcccdddd'
remaining_letters = [1] # dummy initialisation
# sort alphabetically
unique_letters = sorted(set(test_str))
frequencies = [test_str.count(letter) for letter in unique_letters]
out = []
while(remaining_letters):
# in case of ties, index takes the first occurence, so the alphabetical order is preserved
max_idx = frequencies.index(max(frequencies))
out.append(unique_letters[max_idx])
#directly update frequencies instead of calculating them again
frequencies[max_idx] -= 1
remaining_letters = [idx for idx, freq in enumerate(frequencies) if freq>0]
print''.join(out) #dcdbcdabcd
</code></pre>
| 0 | 2016-10-05T10:36:26Z | [
"python",
"string",
"python-2.7",
"sorting",
"nested-loops"
]
|
Sorting a string to make a new one | 39,845,025 | <p>Here I had to remove the most frequent alphabet of a string(if frequency of two alphabets is same, then in alphabetical order) and put it into new string.</p>
<p>Input:</p>
<pre><code>abbcccdddd
</code></pre>
<p>Output:</p>
<pre><code>dcdbcdabcd
</code></pre>
<p>The code I wrote is:</p>
<pre><code>s = list(sorted(<the input string>))
a = []
for c in range(len(s)):
freq =[0 for _ in range(26)]
for x in s:
freq[ord(x)-ord('a')] += 1
m = max(freq)
allindices = [p for p,q in enumerate(freq) if q == m]
r = chr(97+allindices[0])
a.append(r)
s.remove(r)
print''.join(a)
</code></pre>
<p>But it passed the allowed runtime limit maybe due to too many loops.(There's another for loop which seperates the strings from user input)</p>
<p>I was hoping if someone could suggest a more optimised version of it using less memory space. </p>
| 2 | 2016-10-04T05:52:19Z | 39,873,115 | <p>Since the alphabet will always be a constant 26 characters,
this will work in O(N) and only takes a constant amount of space of 26</p>
<pre><code>from collections import Counter
from string import ascii_lowercase
def sorted_alphabet(text):
freq = Counter(text)
alphabet = filter(freq.get, ascii_lowercase) # alphabet filtered with freq >= 1
top_freq = max(freq.values()) if text else 0 # handle empty text eg. ''
for top_freq in range(top_freq, 0, -1): # from top_freq to 1
for letter in alphabet:
if freq[letter] >= top_freq:
yield letter
print ''.join(sorted_alphabet('abbcccdddd'))
print ''.join(sorted_alphabet('dbdd'))
print ''.join(sorted_alphabet(''))
print ''.join(sorted_alphabet('xxxxaaax'))
</code></pre>
<hr>
<pre><code>dcdbcdabcd
ddbd
xxaxaxax
</code></pre>
| 1 | 2016-10-05T11:46:12Z | [
"python",
"string",
"python-2.7",
"sorting",
"nested-loops"
]
|
Sorting a string to make a new one | 39,845,025 | <p>Here I had to remove the most frequent alphabet of a string(if frequency of two alphabets is same, then in alphabetical order) and put it into new string.</p>
<p>Input:</p>
<pre><code>abbcccdddd
</code></pre>
<p>Output:</p>
<pre><code>dcdbcdabcd
</code></pre>
<p>The code I wrote is:</p>
<pre><code>s = list(sorted(<the input string>))
a = []
for c in range(len(s)):
freq =[0 for _ in range(26)]
for x in s:
freq[ord(x)-ord('a')] += 1
m = max(freq)
allindices = [p for p,q in enumerate(freq) if q == m]
r = chr(97+allindices[0])
a.append(r)
s.remove(r)
print''.join(a)
</code></pre>
<p>But it passed the allowed runtime limit maybe due to too many loops.(There's another for loop which seperates the strings from user input)</p>
<p>I was hoping if someone could suggest a more optimised version of it using less memory space. </p>
| 2 | 2016-10-04T05:52:19Z | 39,873,264 | <p>Your solution involves 26 linear scans of the string and a bunch of unnecessary
conversions to count the frequencies. You can save some work by replacing all those linear scans with a linear count step, another linear repetition generation, then a sort to order your letters and a final linear pass to strip counts: </p>
<pre><code>from collections import Counter # For unsorted input
from itertools import groupby # For already sorted input
from operator import itemgetter
def makenewstring(inp):
# When inp not guaranteed to be sorted:
counts = Counter(inp).iteritems()
# Alternative if inp is guaranteed to be sorted:
counts = ((let, len(list(g))) for let, g in groupby(inp))
# Create appropriate number of repetitions of each letter tagged with a count
# and sort to put each repetition of a letter in correct order
# Use negative n's so much more common letters appear repeatedly at start, not end
repeats = sorted((n, let) for let, cnt in counts for n in range(0, -cnt, -1))
# Remove counts and join letters
return ''.join(map(itemgetter(1), repeats))
</code></pre>
<hr>
<p><strong>Updated:</strong> It occurred to me that my original solution could be made much more concise, a one-liner actually (excluding required imports), that minimizes temporaries, in favor of a single sort-by-key operation that uses a trick to sort each letter by the count of that letter seen so far:</p>
<pre><code>from collections import defaultdict
from itertools import count
def makenewstring(inp):
return ''.join(sorted(inp, key=lambda c, d=defaultdict(count): (-next(d[c]), c)))
</code></pre>
<p>This is actually the same basic logic as the original answer, it just accomplishes it by having <code>sorted</code> perform the decoration and undecoration of the values implicitly instead of doing it ourselves explicitly (implicit decorate/undecorate is the whole point of <code>sorted</code>'s <code>key</code> argument; it's doing the <a href="https://en.wikipedia.org/wiki/Schwartzian_transform" rel="nofollow">Schwartzian transform</a> for you).</p>
<p>Performance-wise, both approaches are similar; they both (in practice) scale linearly for smaller inputs (the one-liner up to inputs around 150 characters long, the longer code, using <code>Counter</code>, up to inputs in the <code>len</code> 2000 range), and while the growth is super-linear above that point, it's always below the theoretical <code>O(n log_2 n)</code> (likely due to the data being not entirely random thanks to the counts and limited alphabet, ensuring Python's TimSort has some existing ordering to take advantage of). The one-liner is somewhat faster for smaller strings (<code>len</code> 100 or less), the longer code is somewhat faster for larger strings (I'm guessing it has something to do with the longer code creating some ordering by grouping runs of counts for each letter). Really though, it hardly matters unless the input strings are expected to be huge.</p>
| 1 | 2016-10-05T11:54:47Z | [
"python",
"string",
"python-2.7",
"sorting",
"nested-loops"
]
|
Pandas groupby - grouping users and counting the type of subscription | 39,845,028 | <p>I'm attempting to use pandas to group members, to count the number of subscription types that a member has purchased and get a total spent per member. Once loaded the data resembles:</p>
<pre><code>df =
Member Nbr Member Name-First Member Name-Last Date-Joined Member Type Amount Addr-Formatted Date-Birth Gender Status
1 Aboud Tordon 2010-03-31 00:00:00 1 Year Membership 331.00 ADDRESS_1 1972-08-01 00:00:00 Male Active
1 Aboud Tordon 2011-04-16 00:00:00 1 Year Membership 334.70 ADDRESS_1 1972-08-01 00:00:00 Male Active
1 Aboud Tordon 2012-08-06 00:00:00 1 Year Membership 344.34 ADDRESS_1 1972-08-01 00:00:00 Male Active
1 Aboud Tordon 2013-08-21 00:00:00 1 Year Membership 362.53 ADDRESS_1 1972-08-01 00:00:00 Male Active
1 Aboud Tordon 2015-08-31 00:00:00 1 Year Membership 289.47 ADDRESS_1 1972-08-01 00:00:00 Male Active
2 Jean Manuel 2012-12-10 00:00:00 4 Month Membership 148.79 ADDRESS_2 1984-08-01 00:00:00 Male In-Active
2 Jean Manuel 2013-03-13 00:00:00 1 Year Membership 348.46 ADDRESS_2 1984-08-01 00:00:00 Male In-Active
2 Jean Manuel 2014-03-15 00:00:00 1 Year Membership 316.86 ADDRESS_2 1984-08-01 00:00:00 Male In-Active
3 Val Adams 2010-02-09 00:00:00 1 Year Membership 333.25 ADDRESS_3 1934-10-26 00:00:00 Female Active
3 Val Adams 2011-03-09 00:00:00 1 Year Membership 333.88 ADDRESS_3 1934-10-26 00:00:00 Female Active
3 Val Adams 2012-04-03 00:00:00 1 Year Membership 318.34 ADDRESS_3 1934-10-26 00:00:00 Female Active
3 Val Adams 2013-04-15 00:00:00 1 Year Membership 350.73 ADDRESS_3 1934-10-26 00:00:00 Female Active
3 Val Adams 2014-04-19 00:00:00 1 Year Membership 291.63 ADDRESS_3 1934-10-26 00:00:00 Female Active
3 Val Adams 2015-04-19 00:00:00 1 Year Membership 247.35 ADDRESS_3 1934-10-26 00:00:00 Female Active
5 Michele Younes 2010-02-14 00:00:00 1 Year Membership 333.25 ADDRESS_4 1933-06-23 00:00:00 Female In-Active
5 Michele Younes 2011-05-23 00:00:00 1 Year Membership 317.77 ADDRESS_4 1933-06-23 00:00:00 Female In-Active
5 Michele Younes 2012-05-28 00:00:00 1 Year Membership 328.16 ADDRESS_4 1933-06-23 00:00:00 Female In-Active
5 Michele Younes 2013-05-31 00:00:00 1 Year Membership 360.02 ADDRESS_4 1933-06-23 00:00:00 Female In-Active
7 Adam Herzburg 2010-07-11 00:00:00 1 Year Membership 335 48 ADDRESS_5 1987-08-30 00:00:00 Male In-Active
...
</code></pre>
<p>Since the most popular <code>Member Type</code> are <code>1 Month</code>, <code>3 Month</code>, <code>4 Month</code>, <code>6 Month</code>, and <code>1 Year</code> I would like to make a column counting the number of those <code>Member Type</code> that a given member has purchased. </p>
<p>There are also <code>2 Month</code>, <code>5 Month</code>, <code>7 Month</code>, <code>8 Month</code>, and <code>Pool-Only</code> <code>Member Type</code> that appear very infrequently and if a member has that type of contract I would like to count it as a 'Misc'.</p>
<p>I'm also trying to get a 'Total' column that sums up the total amount spent by a given member. </p>
<p>Essentially I would like to transform my previous dataframe to resemble:</p>
<pre><code>df1=
Member Nbr Member Name-First Member Name-Last 1_Month 3_Month 4_Month 6_Month 1_Year Misc Total Addr-Formatted Date-Birth Gender Status
1 Aboud Tordon 0 0 0 0 5 0 1662.04 ADDRESS_1 1972-08-01 00:00:00 Male Active
2 Jean Manuel 0 0 1 0 2 0 813.86 ADDRESS_2 1984-08-01 00:00:00 Male In-Active
3 Val Adams 0 0 0 0 6 0 1875.18 ADDRESS_3 1934-10-26 00:00:00 Female Active
5 Michele Younes 0 0 0 0 4 0 1339.20 ADDRESS_4 1933-06-23 00:00:00 Female In-Active
7 Adam Herzburg 0 0 0 0 1 0 335.48 ADDRESS_5 1933-06-23 00:00:00 Male In-Active
</code></pre>
<p>...</p>
<p>The problem that I'm encountering is that whenever I use <code>groupby</code> I am only able to either sum up the amount, or separately get a count for one specific type of contract, but I'm unable to get it to resemble <code>df1</code>.</p>
| 1 | 2016-10-04T05:52:34Z | 39,845,310 | <p>You can first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow"><code>map</code></a> values of column <code>Member Type</code> by dict <code>d</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html" rel="nofollow"><code>fillna</code></a> by value <code>Misc</code>:</p>
<pre><code>d = {'1 Year Membership':'1_Year','1 Month Membership':'1_Month', '3 Month Membership':'3_Month', '4 Month Membership':'4_Month', '6 Month Membership':'6_Month'}
df['Type'] = df['Member Type'].map(d).fillna('Misc')
#print (df)
</code></pre>
<p>Then <code>groupby</code> and aggregate <code>sum</code>:</p>
<pre><code>df0 = df.groupby(['Member Nbr','Member Name-First','Member Name-Last','Addr-Formatted','Date-Birth','Gender','Status'])['Amount'].sum()
#print (df0)
</code></pre>
<p>Add column <code>Type</code> to list of grouping columns and aggreagate <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html" rel="nofollow"><code>size</code></a>, then reshape by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.unstack.html" rel="nofollow"><code>unstack</code></a>:</p>
<pre><code>df1 = df.groupby(['Member Nbr','Member Name-First','Member Name-Last','Addr-Formatted','Date-Birth','Gender','Status', 'Type']).size().unstack(fill_value=0)
#print (df1)
</code></pre>
<p>Last <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> both <code>DataFrames</code>:</p>
<pre><code>print (pd.concat([df0, df1], axis=1).reset_index())
Member Nbr Member Name-First Member Name-Last Addr-Formatted \
0 1 Aboud Tordon ADDRESS_1
1 2 Jean Manuel ADDRESS_2
2 3 Val Adams ADDRESS_3
3 5 Michele Younes ADDRESS_4
4 7 Adam Herzburg ADDRESS_5
Date-Birth Gender Status Amount 1_Year 4_Month
0 1972-08-01 00:00:00 Male Active 1662.04 5 0
1 1984-08-01 00:00:00 Male In-Active 814.11 2 1
2 1934-10-26 00:00:00 Female Active 1875.18 6 0
3 1933-06-23 00:00:00 Female In-Active 1339.20 4 0
4 1987-08-30 00:00:00 Male In-Active 335.48 1 0
</code></pre>
<p>EDIT:</p>
<p>If some values are missing in column <code>Member Type</code>, is necessary add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a>:</p>
<pre><code>df1 = df.groupby(['Member Nbr','Member Name-First','Member Name-Last','Addr-Formatted','Date-Birth','Gender','Status', 'Type']).size().unstack(fill_value=0).reindex(columns=d.values(), fill_value=0)
#print (df1)
print (pd.concat([df0, df1], axis=1).reset_index())
Member Nbr Member Name-First Member Name-Last Addr-Formatted \
0 1 Aboud Tordon ADDRESS_1
1 2 Jean Manuel ADDRESS_2
2 3 Val Adams ADDRESS_3
3 5 Michele Younes ADDRESS_4
4 7 Adam Herzburg ADDRESS_5
Date-Birth Gender Status Amount 6_Month 3_Month 4_Month \
0 1972-08-01 00:00:00 Male Active 1662.04 0 0 0
1 1984-08-01 00:00:00 Male In-Active 814.11 0 0 1
2 1934-10-26 00:00:00 Female Active 1875.18 0 0 0
3 1933-06-23 00:00:00 Female In-Active 1339.20 0 0 0
4 1987-08-30 00:00:00 Male In-Active 335.48 0 0 0
1_Year 1_Month
0 5 0
1 2 0
2 6 0
3 4 0
4 1 0
</code></pre>
<hr>
<p>Instead second <code>groupby</code> (what is the fastest) is possible use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a>:</p>
<pre><code>df2 = df.pivot_table(index=['Member Nbr','Member Name-First','Member Name-Last','Addr-Formatted','Date-Birth','Gender','Status'], columns='Type', values='Amount', aggfunc=len, fill_value=0).reindex(columns=d.values(), fill_value=0)
print (pd.concat([df0, df2], axis=1).reset_index())
Member Nbr Member Name-First Member Name-Last Addr-Formatted \
0 1 Aboud Tordon ADDRESS_1
1 2 Jean Manuel ADDRESS_2
2 3 Val Adams ADDRESS_3
3 5 Michele Younes ADDRESS_4
4 7 Adam Herzburg ADDRESS_5
Date-Birth Gender Status Amount 6_Month 3_Month 4_Month \
0 1972-08-01 00:00:00 Male Active 1662.04 0 0 0
1 1984-08-01 00:00:00 Male In-Active 814.11 0 0 1
2 1934-10-26 00:00:00 Female Active 1875.18 0 0 0
3 1933-06-23 00:00:00 Female In-Active 1339.20 0 0 0
4 1987-08-30 00:00:00 Male In-Active 335.48 0 0 0
1_Year 1_Month
0 5 0
1 2 0
2 6 0
3 4 0
4 1 0
</code></pre>
| 2 | 2016-10-04T06:14:12Z | [
"python",
"pandas",
"group-by",
"pivot-table",
"reshape"
]
|
How to make regex that matches a number with commas for every three digits? | 39,845,034 | <p>I am a beginner in Python and in regular expressions and now I try to deal with one exercise, that sound like that:</p>
<blockquote>
<p>How would you write a regex that matches a number with commas for
every three digits? It must match the following:</p>
<p>'42'</p>
<p>'1,234'</p>
<p>'6,368,745'</p>
<p>but not the following:</p>
<p>'12,34,567' (which has only two digits between the commas)</p>
<p>'1234' (which lacks commas)</p>
</blockquote>
<p>I thought it would be easy, but I've already spent several hours and still don't have write answer. And even the answer, that was in book with this exercise, doesn't work at all (the pattern in the book is <code>^\d{1,3}(,\d{3})*$</code>)</p>
<p>Thank you in advance!</p>
| -2 | 2016-10-04T05:53:22Z | 39,845,105 | <p>You can go with this (which is a slightly improved version of what the book specifies):</p>
<pre><code>^\d{1,3}(?:,\d{3})*$
</code></pre>
<p><a href="https://regex101.com/r/amGFa4/2" rel="nofollow">Demo on Regex101</a></p>
| 0 | 2016-10-04T05:58:23Z | [
"python",
"regex"
]
|
How to make regex that matches a number with commas for every three digits? | 39,845,034 | <p>I am a beginner in Python and in regular expressions and now I try to deal with one exercise, that sound like that:</p>
<blockquote>
<p>How would you write a regex that matches a number with commas for
every three digits? It must match the following:</p>
<p>'42'</p>
<p>'1,234'</p>
<p>'6,368,745'</p>
<p>but not the following:</p>
<p>'12,34,567' (which has only two digits between the commas)</p>
<p>'1234' (which lacks commas)</p>
</blockquote>
<p>I thought it would be easy, but I've already spent several hours and still don't have write answer. And even the answer, that was in book with this exercise, doesn't work at all (the pattern in the book is <code>^\d{1,3}(,\d{3})*$</code>)</p>
<p>Thank you in advance!</p>
| -2 | 2016-10-04T05:53:22Z | 39,845,263 | <p>The answer in your book seems correct for me. It works on the test cases you have given also. </p>
<pre><code>(^\d{1,3}(,\d{3})*$)
</code></pre>
<p>The <code>'^'</code> symbol tells to search for integers at the start of the line. <code>d{1,3}</code> tells that there should be at least one integer but not more than 3 so ;</p>
<pre><code>1234,123
</code></pre>
<p>will not work.</p>
<pre><code>(,\d{3})*$
</code></pre>
<p>This expression tells that there should be one comma followed by three integers at the end of the line as many as there are.</p>
<p>Maybe the answer you are looking for is this:</p>
<pre><code>(^\d+(,\d{3})*$)
</code></pre>
<p>Which matches a number with commas for every three digits without limiting the number being larger than 3 digits long before the comma.</p>
| 1 | 2016-10-04T06:10:01Z | [
"python",
"regex"
]
|
What is the . symbol in matlab, how to change it to python | 39,845,102 | <pre><code>Xnorm = (X-repmat(mu,m,1))./repmat(sigma,m,1);
</code></pre>
<p>what does the . here do? And if I want to change it to the python, what should I do? </p>
| 0 | 2016-10-04T05:58:08Z | 39,845,186 | <p>IN MATLAB it's called <a href="https://www.mathworks.com/help/fixedpoint/ref/rdivide.html" rel="nofollow"><code>rdivide</code> - right array element-wise division</a>.</p>
<pre><code>>> [1,2;3,4]./[5,6;7,8]
ans =
0.2000 0.3333
0.4286 0.5000
</code></pre>
<p>Python equivalent is <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.divide.html#numpy-divide" rel="nofollow"><code>numpy.divide</code></a>.</p>
<pre><code>>>> from __future__ import division
>>> np.array([[1,2],[3,4]]) / np.array([[5,6],[7,8]])
array([[ 0.2 , 0.33333333],
[ 0.42857143, 0.5 ]])
</code></pre>
| 0 | 2016-10-04T06:04:09Z | [
"python",
"matlab"
]
|
What is the . symbol in matlab, how to change it to python | 39,845,102 | <pre><code>Xnorm = (X-repmat(mu,m,1))./repmat(sigma,m,1);
</code></pre>
<p>what does the . here do? And if I want to change it to the python, what should I do? </p>
| 0 | 2016-10-04T05:58:08Z | 39,845,223 | <p>It means element wise division
Matlab Example</p>
<p><a href="http://in.mathworks.com/help/fixedpoint/ref/rdivide.html;jsessionid=e4b080e387b57aaf3b1e526a26d9" rel="nofollow">http://in.mathworks.com/help/fixedpoint/ref/rdivide.html;jsessionid=e4b080e387b57aaf3b1e526a26d9</a></p>
<p>Divide elementwise Python Equivalent</p>
<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.divide.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.divide.html</a></p>
| 0 | 2016-10-04T06:06:30Z | [
"python",
"matlab"
]
|
What is the . symbol in matlab, how to change it to python | 39,845,102 | <pre><code>Xnorm = (X-repmat(mu,m,1))./repmat(sigma,m,1);
</code></pre>
<p>what does the . here do? And if I want to change it to the python, what should I do? </p>
| 0 | 2016-10-04T05:58:08Z | 39,845,591 | <p>In MATLAB you would explicitly replicate elements with that <code>repmat</code> and then do elementwise division with <code>./</code> as also stated in the comments. You could have also used <a href="https://www.mathworks.com/help/matlab/ref/bsxfun.html" rel="nofollow"><code>bsxfun</code></a> for under-the-hood replication aka <code>broadcasting</code> prior to <code>2016B</code> and division in one go, like so -</p>
<pre><code>bsxfun(@rdivide,bsxfun(@minus,X,mu),sigma)
</code></pre>
<p>In this post I am assuming that you are working with NumPy arrays in Python. In NumPy, the <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> is done implicitly. MATLAB would have the same starting from <code>2016b</code>. So, we can simply skip the <code>repmat</code> part. Thus, if the input arrays are floating pt ones, you can simply do -</p>
<pre><code>(X-mu)/sigma
</code></pre>
<p>If working with int arrays, I could suggest two ways to achieve the desired output.</p>
<p>One way would be with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.true_divide.html" rel="nofollow"><code>np.true_divide</code></a> -</p>
<pre><code>np.true_divide((X-mu),sigma)
</code></pre>
<p>Another way would be to convert one of the arrays to floating pt, so that the desired output would be upcasted, like so -</p>
<pre><code>(X-mu)/(sigma).astype(float)
</code></pre>
<p><strong>Sample runs</strong></p>
<p>1) MATLAB :</p>
<pre><code>X =
1 5 9 13 17
2 6 10 14 18
3 7 11 15 19
4 8 12 16 20
mu =
101 102 103 104 105
sigma =
201 202 203 204 205
m =
4
out =
-0.49751 -0.4802 -0.46305 -0.44608 -0.42927
-0.49254 -0.47525 -0.45813 -0.44118 -0.42439
-0.48756 -0.4703 -0.4532 -0.43627 -0.41951
-0.48259 -0.46535 -0.44828 -0.43137 -0.41463
</code></pre>
<p>2) NumPy :</p>
<pre><code>In [37]: X
Out[37]:
array([[ 1, 5, 9, 13, 17],
[ 2, 6, 10, 14, 18],
[ 3, 7, 11, 15, 19],
[ 4, 8, 12, 16, 20]])
In [38]: mu
Out[38]: array([101, 102, 103, 104, 105])
In [39]: sigma
Out[39]: array([201, 202, 203, 204, 205])
In [40]: np.true_divide(X-mu,sigma)
Out[40]:
array([[-0.49751244, -0.48019802, -0.46305419, -0.44607843, -0.42926829],
[-0.49253731, -0.47524752, -0.45812808, -0.44117647, -0.42439024],
[-0.48756219, -0.47029703, -0.45320197, -0.43627451, -0.4195122 ],
[-0.48258706, -0.46534653, -0.44827586, -0.43137255, -0.41463415]])
</code></pre>
| 1 | 2016-10-04T06:33:44Z | [
"python",
"matlab"
]
|
What is the . symbol in matlab, how to change it to python | 39,845,102 | <pre><code>Xnorm = (X-repmat(mu,m,1))./repmat(sigma,m,1);
</code></pre>
<p>what does the . here do? And if I want to change it to the python, what should I do? </p>
| 0 | 2016-10-04T05:58:08Z | 39,852,823 | <p>Element division instead of the default matrix division.</p>
| 0 | 2016-10-04T12:50:39Z | [
"python",
"matlab"
]
|
Receiving AssertionError using Flask sqlalchemy and restful | 39,845,187 | <p>I have been stumped and can't seem to figure out why I am receiving an AssertionError. I am currently working on a rest api using the flask_restful lib. I am querying by:</p>
<pre><code>@staticmethod
def find_by_id(id, user_id):
f = File.query.filter_by(id=id).first() #Error is happening here
if f is not None:
if f.check_permission(user_id)>=4:
return f
print f.check_permission(user_id)
FileErrors.InsufficientFilePermission()
FileErrors.FileDoesNotExist()
</code></pre>
<p>The error message looks like this:</p>
<pre><code>Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 2000, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1991, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py", line 271, in error_router
return original_handler(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1567, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py", line 268, in error_router
return self.handle_error(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py", line 271, in error_router
return original_handler(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1531, in handle_user_exception
assert exc_value is e
AssertionError
</code></pre>
<p>This is how my File model looks like:</p>
<pre><code>class File(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer)
parts = db.Column(db.Integer)
size = db.Column(db.Integer)
name = db.Column(db.String(100))
def __init__ (self, file_info):
self.user_id = file_info['user_id']
self.parts = file_info['parts']
self.size = file_info['size']
self.name = file_info['name']
@staticmethod
def create(file_info):
return add_to_db(File(file_info))
@staticmethod
def delete(file_id, user_id):
pass
def check_permission(self,user_id):
permission = 0
print 'self.user_id {}'.format(self.user_id)
print 'user_id {}'.format(user_id)
if self.user_id == user_id:
return 7
fs = FileShare.find_by_file_and_user_id(self.id, user_id)
if fs is not None:
permission = fs.permission
return permission
@staticmethod
def find_by_id(id, user_id):
f = File.query.filter_by(id=id).first() #Error is happening here
if f is not None:
if f.check_permission(user_id)>=4:
return f
print f.check_permission(user_id)
FileErrors.InsufficientFilePermission()
FileErrors.FileDoesNotExist()
</code></pre>
<p>Any help would be appreciated. Thanks in advance.</p>
| 0 | 2016-10-04T06:04:11Z | 39,848,104 | <p>Are you sure you want to have an assignment operator instead of comparison in your filter. Try replacing = with == and see if it solves your problem. </p>
<pre><code>f = File.query.filter_by(id == id).first()
</code></pre>
<p>Hannu</p>
| 0 | 2016-10-04T08:56:25Z | [
"python",
"flask",
"sqlalchemy",
"flask-sqlalchemy",
"flask-restful"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.