text stringlengths 256 65.5k |
|---|
I generate RSS feed with latest 10 records from GAE NDB datastore. Records in database are updated weekly. How can I avoid queries to datastore each time user requests RSS feed display? I.e. how to cache that?
You can use memcache to avoid hitting the datastore every time. As you probably know queries are not cached in... |
I was trying to port forward my minecraft server, using port 25566, and for some reason it wasn't working. So, I opened minecraft to enter localhost, and after clicking login, the window closed and placed an error log report on my desktop. The same thing happens with all subsequent tries. Here is the error report:
#
# ... |
I have two web application: parent_app and sub_app
say that, http://www.some.com/parent.png will be handled by parent_app.
if it is refererd in another website, parent_app get a HTTP_REFERER, say that is http://www.other.com/path?query=value,
I want a sub_app take this HTTP_REFERER's path and query_string as his own pa... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QMainWindow):
def __init__(self):
super(Example, self).__init__();
self.initUI()
def initUI(self):
field = QtGui.QLineEdit("", self)
field.resize(field.sizeHint())
fie... |
A few months ago, I wrote a diff to simplify the calculation of ICMP extension header checksums in the OpenBSD kernel. It so happened that the code is only used by the OpenBSD MPLS subsystem. I didn’t have access to an OpenBSD-based MPLS network at the time, nor was I familiar with MPLS in general; so in the spirit of ... |
I am new at python, currently I am working on a GPS tracker with that interacts with Google maps using an Arduino Uno. I am getting this error and it is not letting me run the .py script for my tcpServer this is the whole script.
#!/usr/bin/env python
import socket
import MySQLdb
TCP_IP = 'my machine IP'
TCP_PORT = 320... |
I want to load an image but I get an error-message.
My code:
from PIL import Image
im = Image.open("D:\Python26\PYTHON-PROGRAMME\bild.jpg")
im.show()
I get this error:
Traceback (most recent call last):
File "D:\Python26\PYTHON-PROGRAMME\00000000000000000", line 2, in <module>
im = Image.open("D:\Python26\PYTHON... |
JavaScript
iamjustoneman — 2011-12-20T18:02:28-05:00 — #1
Hi all,
I have work thumbnails on one side (meals), ingredients on the other side, what I would like to do is:
1) If I hover over a meal, the ingredients used for that dish are highlighted on the left
2) If I hover over an ingredient, the dishes that used this i... |
Anarcheon
Perte d'éléments suite à utilisation de compiz
Bonjour à tous,
Utilisateur relativement récent d'Ubuntu (<1 an), j'ai voulu faire mumuse avec compiz. J'essaie d'installer le cube et quelques autres "décorations", mais finis par me rendre compte que c'était aussi bien avant, et que j'irai bidouiller un peu plu... |
I am implementing the stock Django comments to an existing site.
I'd like comments to appear in multiple apps and models and have all the comments behave the same - i.e. an email sent, plus other bits (listening to 'flag' signals and dealing with accordingly)
Where's the best place to put my custom moderator code?
I un... |
How do you convert between a DateTime and a Time object in Ruby?
You'll need two slightly different conversions.
To convert from
require 'date'
class Time
def to_datetime
# Convert seconds + microseconds into a fractional number of seconds
seconds = sec + Rational(usec, 10**6)
# Convert a UTC offset measu... |
I'm making a request using urllib2 and the HTTPBasicAuthHandler like so:
import urllib2
theurl = 'http://someurl.com'
username = 'username'
password = 'password'
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, theurl, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)... |
bishop
Re : Qarte arte.tv browser (ex Qarte+7)
VinsS !
J'ai réinstallé Qarte.
Avant de lancer Qarte j'ai refait un test avec rtmpdump... pas de problème.
J'ai supprimé le dossier caché .qarte puis testé Qarte:
bishop@JC:~/Bureau$ qarte -d
lang: /usr/share/locale/fr/LC_MESSAGES/qarte.mo
11:44:14: WARNING - utils Config ... |
I need to perform case-insensitive queries on username by defaultwhen using the Django Auth framework.
I tried fixing the issue by writing a custom subclass of Querysetand overriding the _filter_or_exclude method and then using thatsubclass in a custom manager for the User model-
from django.db.models import Manager
fr... |
Module decimal
This is a Py2.3 implementation of decimal floating point arithmetic based on
the General Decimal Arithmetic Specification:
www2.hursley.ibm.com/decimal/decarith.html
and IEEE standard 854-1987:
www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
Decimal floating point has finit... |
I'm new to programming, and also to this site, so my apologies in advance for anything silly or "newbish" I may say or ask.
I'm currently trying to write a script in python that will take a list of items and write them into a csv file, among other things. Each item in the list is really a list of two strings, if that m... |
I hope you got pylons working; for anyone else that may later read question I'll present some pointers in the right direction.
First of all, you are only creating a engine and a metadata object. While you can use the engine to create connections directly you would almost always use a Session to manage querying and upda... |
To make the analysis of this algorithm more interesting I will the following input:
9
2
3
4
4
4
2
1
3
4
Firstly, notice if a kid sits next to a kid who is getting x candies and that kid has a lower rating then the first kid should get at least x+1 candies. Making the difference more than 1 will just waste candies. The ... |
I'm trying to do a relatively simple animation that requires rotating an ellipse on a rotating background. I've had to resort to a bit of trickery to get pygame.transform.rotate to play nice with the surfaces I'm trying to rotate. Namely, I've made this function that recenters the new rect obtained from pygame's rotati... |
Please consider using this website to upload your scripts:
It's a bit more organized and allows for easier browsing/uploading/viewing/downloading. If you have any comments/suggestions on that site, please use the feedback link. Eventually the scriptshare website's functionality will be incorporated into pnotepad.org, b... |
gtk.gdk.Cursor — standard and pixmap cursors
class gtk.gdk.Cursor(gobject.GBoxed):
gtk.gdk.Cursor(cursor_type)
gtk.gdk.Cursor(display, cursor_type)
gtk.gdk.Cursor(display, pixbuf, x, y)
gtk.gdk.Cursor(source, mask, fg, bg, x, y)
def get_display()
A gtk.gdk.Cursorrepresents a bitmap image used for t... |
When you have a well-written library, which is sometimes case in python, you ought just import it and use it as it. Well-written library tends to take life and language of its own, resulting in pleasant-to-read -code, where you rarely reference the library. When a library is well-written, you ought not need renaming or... |
doudoulolita
Faire une animation sur la création de jeux vidéo libres
Dans le topic Création de jeu vidéo libre - Appel à candidatures, j'ai découvert le créateur de jeu de Ultimate Smash Friends, Tshirtman.
Voici ce que je lui ai écrit:
Je cherche un jeu que notre Espace Public Numérique pourrait proposer aux jeunes s... |
I am making an Ajax request into views as follows:
def all_json_models(request):
data = {}
try:
isp = request.GET['status']
present_isp = Priority.objects.filter(ispname = isp)
isp_count = MultiWAN.objects.all()
# data['latest_no_rules'] = latest_no_rules
#data['present_isp'] = present_i... |
I am in the process of writing a proof of concept RESTful server using web.py
Here is the script:
#!/usr/bin/env python
import web
import json
def notfound():
#return web.notfound("Sorry, the page you were looking for was not found.")
return json.dumps({'ok':0, 'errcode': 404})
def internalerror():
#return ... |
The program seems to work, however the linear regression line created does not seem to really be the line of best fit.
I think the problem is the implementation of the equation. I'm not sure if i'm interpreting it right, also I am unsure if I am doing what should be done in regards to the last paragraph of the exercise... |
#!/usr/bin/python -tt
# A dictionary Of Each New SSID
WirelessNetwork = {}
WirelessNetwork['name'] = 'baz'
WirelessNetwork['type'] = 'bar'
WirelessNetwork['pass'] = 'foo'
# A list of all SSIDs
networkAddList = (WirelessNetwork)
def addWireless(passedDict={}):
print 'Adding SSID: %s' % passedDict['name']
print 'Of t... |
Python is a dynamic and strongly typed programming language that is used for a wide range of applications. It is a general-purpose, high-level programming language that is designed to emphasize usability.
Python programmers can express concepts in fewer lines of code than would be possible in languages such as c, and t... |
Saw this post about a kernel bug in 64 bit Windows that is a DoS, it can also create an unkillable process: Blog post: http://waleedassar.blogspot.com/2013/02/kernel-bug-1-processiopriority.html
Figured I’d take a swing at making a module that I could put Meterpreter into an unkillable state. Good times at CCDC could b... |
I am not a kind of expert in python twisted, please help me out for my problem , the getChild is not calling when I am trying the path localhost:8888/dynamicchild.even put isLeaf as False in my resource .
as per my understanding when I tried localhost:8888 it should return blue page of course it is happening but when e... |
Trees Indices Toggle frames
pyglet is a cross-platform games and multimedia package.
Detailed documentation is available at http://www.pyglet.org
pyglet.app
Application-wide functionality.
pyglet.clock
Precise framerate calculation, scheduling and framerate limiting.
pyglet.event
Event dispatch framework.
pyglet.font
L... |
I'm working with argparse and am trying to mix sub-commands and positional arguments, and the following issue came up.
This code runs fine:
import argparse
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
parser.add_argument('positional')
subparsers.add_parser('subpositional')
parser.parse_args('... |
is there is way(s/w) to delete or automatically corrupt a file(.txt,.exe,.avi.....etc) if i gave that file to someone(other system) after the time specified or set by me?
platform: windows , Linux
If a file can be opened and read, it's going to be nigh impossible to prevent the end user from making a copy of it. What w... |
I have created a PyGTK application that shows a Dialog when the user presses a button.The dialog is loaded in my __init__ method with:
builder = gtk.Builder()
builder.add_from_file("filename")
builder.connect_signals(self)
self.myDialog = builder.get_object("dialog_name")
In the event handler, the dialog is shown wit... |
gmli
Cerise 0.8 - TPE, freelances, artisans
Hello,
je me suis dit qu'une petit présentation pourrait intéresser du monde ici.
Je viens de sortir aujourd'hui la version 0.8 de mon petit soft de gestion d'entreprise (cf. l'article sur le blog http://leblog.cfait.fr/post/2008/09/07/Cerise-08)
Vous pouvez trouver une liste... |
I have a text file like this:
1123411111
Using Python 2.7, I want to turn it into a list of lists of lines, where line breaks divide items in the inner list and empty lines divide items in the outer list. Like so:
[["11","2","3","4"],["11"],["111"]]
And for this purpose, I wrote a generator function that would yield th... |
With this table:
CREATE TABLE test_insert (
col1 INT,
col2 VARCHAR(10),
col3 DATE
)
the following code takes 40 seconds to run:
import pyodbc
from datetime import date
conn = pyodbc.connect('DRIVER={SQL Server Native Client 10.0};'
'SERVER=localhost;DATABASE=test;UID=xxx;PWD=yyy')
rows = []
row = [1, '... |
XML transformation via XSL Transformations (XSLT) is quite popular and indeed powerful. Well-constructed XSL can produce HTML, PDF, XML, and just about any other text format imaginable. XSLT, however, requires that the subject data be a well-structured XML document, which often is not the case. Consequently, developers... |
I have the following dictionary:
student_loan_portfolio = {
'loan1': {'rate': .078, 'balance': 1000, 'payment': 100, 'prepayment': 0},
'loan2': {'rate': .0645, 'balance': 10, 'payment': 5, 'prepayment': 0},
'loan3': {'rate': .0871, 'balance': 250, 'payment': 60, 'prepayment': 0},
'loan4': {'rate': .0842... |
Im just try to build a basic class so that I can learn some more about python. So far I have the following :
class Bodymassindex:
count = 0
def __init__(self,name,weight,height):
self.name = name
self.weight = 14 * weight
self.height = 12 * height
notes = "no notes have been assigned yet"
bmitot... |
I am trying to write my first GAE/Python application that does the following three things:
Displays a form where the user can enter details about themself (index.html)
Stores the submitted form data in the datastore
Retrieves all data from datastore and displays all results above the form (index.html)
However, I'm gett... |
The biggest reason to keep the try/except/finally blocks in the code itself is that error recovery is usually an integral part of the function.
For example, if we had our own int() function:
def MyInt(text):
return int(text)
What should we do if text cannot be converted? Return 0? Return None?
If you have many sim... |
I am using jython with a third party application. The third party application has some builtin libraries foo. To do some (unit) testing we want to run some code outside of the application. Since foo is bound to the application we decided to write our own mock implementation.
However there is one issue, we implemented o... |
I tried to connect bbs with python's library "telnetlib", try to make a robot to answer
the message. While I answered the message,the robot return more than 1 message.These are my
code.
# -*- coding: cp950 -*-
import telnetlib,random
#f= open("ans.txt","r")
ans = [b"oao", b"xd"]
'''while True:
line = f.readline()
if li... |
I have code in which all objects descend from a base object, which I don't plan to instantiate directly. In the __init__() method of my base object I'm trying to perform some magic -- I am trying to decorate, or wrap, every method of the object being initialized. But I'm getting a result that puzzles me when I call the... |
Tony95
Re : Ella : projet de logiciel d'animation Flash & SVG pour Linux
Salut à tous je savais pas trop où poster donc je le fais ici. J'ai un petit soucis en GTK, j'aimerais créer une interface permettant de charger et sauvegarder des fichiers mais j'arrive vraiment pas à m'en sortir pour le code. En gros j'ai une fe... |
I wrote several modules to operate a system for different stuff. Only need the IP address of the system. Now, is it possile to define a class to inherit all functions already developed in other python modules? Thanks,
I'm not sure if this is exactly what you're looking for, but you can
import other_module
class MyClass... |
My context is a very simple filter-like program that streams lines from an input file into an output file, filtering out lines the user (well, me) doesn't want. The filter is rather easy, simply requiring a particular value for some 'column' in the input file. Options are easily expressed with argparse:
parser.add_argu... |
Sorry if this question is too simple; I'm only entering 9th grade.
I'm trying to learn about NoSQL database design. I want to design a Google Datastore model that minimizes the number of read/writes.
Here is a toy example for a blog post and comments in a one-to-many relationship. Which is more efficient - storing all ... |
I have some models like that;
class Ingredient(models.Model):
name = models.CharField(max_length=128)
class Recipe(models.Model):
name = models.CharField(max_length=128)
ingredients = models.ManyToManyField(Ingredient, through='RecipeIngredient')
class RecipeIngredient(models.Model):
recipe = models.For... |
Module re
Support for regular expressions (RE).
This module provides regular expression matching operations similar to
those found in Perl. It supports both 8-bit and Unicode strings; both
the pattern and the strings being processed can contain null bytes and
characters outside the US ASCII range.
Regular expressions ... |
Kedoc
Re : script install wifi BCM94311MCG
Petit point...
Je me suis aperçu ce soir qu'il me suffit d'utiliser l'interrupteur matériel de ma carte pour l'éteindre et la rallumer, un coup au démarrage sous Ubuntu, et je peux ensuite l'utiliser (en wifi ouvert, et en WEP, ça fonctionne).
Je n'ai pas encore bien compris, ... |
How to detect string suffixes and remove these suffixed elements from list?I understand that this looks like an NLP, stemming/lemmatization task but the task requires a simpler function.
Given, i need to remove elements that has s and es suffixes if the non-suffixed items exist in the list:
alist = ['bar','barbar','foo... |
I am using liburl2 with CookieJar / HTTPCookieProcessor in an attempt to simulate a login to a page to automate an upload.
I've seen some questions and answers on this, but nothing which solves my problem. I am losing my cookie when I simulate the login which ends up at a 302 redirect. The 302 response is where the coo... |
tomtom
Re : [HOW TO] adesklets : installation sous Ubuntu Breezy
raaah ! j'ai un probleme d'interpreteur python !
J'ai installé toutes les librairies via synaptic et adesklets aussi.
J'ai DL YAB (Yet Another Bar) et j'ai ca :
[i]tomtom@barad-luin:/mnt/config/programmes/adesklets/yab-0.0.2$ [/i][b]ls -l[/b]
total 56
-rw... |
You can use os.walk to iterate over each file, apply your custom filtering function and copying over only the ones you care.
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree roo... |
Topic: Error 500, Upgrading from OpenSource to Pro
Hi Guys !
Finaly i buyed this Masterpiece of Mailserver and now i upgraded to iRedAdmin Pro.
Used the guide from Zhang.
in my apache log i get this error:
[Thu Oct 07 13:31:22 2010] [error] [client 80.123.169.178] mod_wsgi (pid=3289): Target WSGI script '/usr/share/apa... |
Models
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, ForeignKey
from sqlalchemy import Integer
from sqlalchemy import Unicode
from sqlalchemy import TIMESTAMP
from sqlalchemy.orm import relationship
BaseModel = declarative_base()
class Base(BaseModel):
__tablename__ = 'base'
... |
mastergb
Vpnautoconnect 2.X(Nouvelle version ,bugs, demande d'aide: c'est ici!)
Bonjour à tous,
Suite à l'énorme thread précédent (et à la demande de ljere) , j'aimerais reprendre un sujet vraiment dédié a vpnautoconnect.
Le logiciel n'est plus à présenter. On l'aime (ou pas), il permet entre autre de répondre à une la... |
I agree with Honest Abe that the match(...) in the given examples are different. They are not a one-to-one comparisons and thus, outcomes are vary. To simplify my reply, I use A, B, C, D for those functions in question. Oh yes, we are dealing with 4 functions in re.py instead of 3.
Running this piece of code:
h = re.co... |
tomtom
Re : [HOW TO] adesklets : installation sous Ubuntu Breezy
raaah ! j'ai un probleme d'interpreteur python !
J'ai installé toutes les librairies via synaptic et adesklets aussi.
J'ai DL YAB (Yet Another Bar) et j'ai ca :
[i]tomtom@barad-luin:/mnt/config/programmes/adesklets/yab-0.0.2$ [/i][b]ls -l[/b]
total 56
-rw... |
I frequently make models with Text columns that hold Markdown formatted richtext. My models look like this:
class Document(Base):
id = Column(Integer, primary_key=True)
title = Column(Unicode(250))
description = Column(Text)
description_html = Column(Text)
My edit forms (a) read from and write to descr... |
Itâs all about the entropy
[ For more information on the Eideticker software I'm referring to, see this entry ]
So recently Iâve been exploring new and different methods of measuring things that we care about on FirefoxOS â like startup time or amount of checkerboarding. With Android, where we have a mostly clean... |
I have a custom form that creates a hidden input of a field:
class MPForm( forms.ModelForm ):
def __init__( self, *args, **kwargs ):
super(MPForm, self).__init__( *args, **kwargs )
self.fields['mp_e'].label = "" #the trick :)
class Meta:
model = MeasurementPoint
widgets = { 'mp_e': forms.Hid... |
Can anyone tell me what exactly happens in a Recursion Program.. ??
A function calls itself over and over, until some condition is met.
A silly example: How to walk 100 steps recursively:
function walk(steps) {
if (steps > 0) { // not there yet
take 1 step
walk(steps - 1); // we're 1 step closer, n... |
I'm having a hard time figuring out how to unzip a zip file with 2.4. extract() is not included in 2.4. I'm restricted to using 2.4.4 on my server.
Can someone please provide a simple code example?
You have to use
import zipfile
import os.path
import os
zfile = zipfile.ZipFile("test.zip")
for name in zfile.namelist():
... |
In http://jan.kneschke.de/2007/8/1/mysql-proxy-learns-r-w-splitting we did a first implementation on idea of sending non-transactional reads to the slaves and writes and transactions to the master.
While that was mostly a proof of concept it already worked pretty well. In this second round on R/W splitting several issu... |
Bear in mind that the locking is very expensive, and it happens every time you hand objects around between smart pointers - even when the object is currently owned by one thread (the smart pointer library doesn't know that).
Given this, there may be a rule of thumb applicable here (I'm happy to be corrected!)
If the fo... |
Alex0000
Déconnexion sur Batterie [Samsung]
Bonjour à tous
J'ai un problème récurrent avec mon wifi quelque soit l'os ou la version de celui-ci. Après un petit temps sur batterie ( entre 5min et 1h) il se déconnecte de plus le gestionnaire de connexion ne montre plus aucun wifi.
Sur Windows, l'outils de résolution de p... |
mao-40
Re : TBI + wiimote + ubuntu
En ce qui concerne 'gtkwhiteboard.ico', ce n'est pas l'image de calibration je pense, puisque le logiciel demande de calibrer l'écran avec les 4 coins du bureau et après cela fonctionne bien.
Ah ok, j'essaierai au demain au vidéo-projcteur.
Dernière modification par mao-40 (Le 04/02/2... |
Leo 7
Re : A quoi ressemble votre environnement - printemps/été 2012
J'adore ton unity Mario_26
Est-ce que tu peux me donner le lien du wall STP, je le touve très zoli.
Merci d'avance
A+
hp 625: Ubuntu LTS xfce / Mac Mini ppc G4: Debian stable xfce / Les choses les plus simples sont les meilleures !
Hors ligne
Major Gr... |
Anyways, the idea is the following: you want to change the class attributes before it becomes final -- there are things you just can't do in Python after a class is already declared (Python uses this technique for creating properties -- in my specific use-case I'm using it to overcome some limitations that Django has i... |
I want to write some random numbers into an ascii output file.I generate the numbers with numpy, so the numbers are stored in numpy.array
import numpy as np
random1=np.random.uniform(-1.2,1.2,7e6)
random2=...
random3=...
All three array are of the same size. I used standard file output, but this is really slow. Just a... |
Raze
[Résolu] Conseils partition
Salut !
Je souhaite installer Ubuntu en dual-boot avec Windows 8.1, et malgré mes nombreuses lectures je me pose certaines questions, notamment au niveau du partitionnement du disque ! Je viens donc vous demander quelques conseils.
En effet, à ce que j'ai compris, il est possible de cré... |
PyPN is an extension that allows you to use Python to script almost anything in PN. This can be simple text formatting, or complex macros for automation.
See Install PyPN for installation instructions.
After PyPN is installed, go to View > Window > Scripts (or press Alt+F10). You should be able to see the Scripts menu,... |
PiQuizMachinecode.
The machine
The PiQuizMachine
The Circuit
Each button controller is made from 1/2" PVC parts and a momentary mini push button, connected by a wire to a board.
On the board, one 10K Ohm resistor pulls up the GPIO to high, while the push button is connected to the GPIO on one end and to ground through ... |
I've been getting this error "invalid literal for int() with base 10: 'user3' " when I try to retrieve an object from FacebookProfile.
It doesn't give any error when getting by id or any int datatype.
def index(request):
current_user = request.user
current_username = str(current_user.username)
fbuser=Facebo... |
It's not an easy task to find a vulnerable service and find an exploit for it. It's also not easy to defend against users who might want to exploit your system, if you are a system administrator. However, writing an exploit by yourself, to convert a news line from bug tracker into a working lockpick, is much more diffi... |
I have a string like so: "sometext #Syrup #nshit #thebluntislit"
and i want to get a list of all terms starting with '#'
I used the following code:
import re
line = "blahblahblah #Syrup #nshit #thebluntislit"
ht = re.search(r'#\w*', line)
ht = ht.group(0)
print ht
and i get the following:
#Syrup
I was wondering if the... |
Is it possible for the __new__ method of a Python class A to refer to a (constant) instance of a subclass of A?
To illustrate (motivate?) this question, below is a toy implementation of Lisp-like lists in Perl. A Lisp list is often defined recursively as a pair (aka cons) whose first element is some arbitrary Lisp obje... |
The simple approach to computing the convex hull in 2D.
I’ve found myself coding convex hull algorithms on a few occasions now, so I decided to implement a few and talk about them here, in case someone new to the subject wants to get the quick ‘n’ dirty. The algorithms I will talk about are the Jarvis March (code), the... |
I'm working on problem 401 in project euler, I coded up my solution in python but it's going to take a few days to run, obviously I'll need to speed it up or use a different approach. I came across a solution in Haskell that looks almost identical to my python solution but completes almost instantaneously.
Can someone ... |
This is pretty simple but I'd love a pretty, pythonic way of doing it. Basically, given a dictionary, return the subdictionary that contains only those keys that start with a certain string.
» d = {'Apple': 1, 'Banana': 9, 'Carrot': 6, 'Baboon': 3, 'Duck': 8, 'Baby': 2}
» print slice(d, 'Ba')
{'Banana': 9, 'Baby': 2,... |
This is a simple program that uses OpenCV (in Python) to import an image, convert it to grayscale and display it in a window. Then, when the user clicks a position in the window, a flood-fill is performed from that point. In addition, when the user clicks the point, the program should print the original 2D pixel value ... |
This article is intended for new users of Python.
When going from one language to another, some things have to be unlearned (see Transfer of Learning). What you know from other languages may not be always useful in Python. This page contains some idioms used in Python that I particularly like, and I hope others find us... |
I'm playing around with Tkinter and it works while I am asking just one input after another. Like 'askopenfilename'. But getting many pop-ups isn't so comfy. I would like to build just one Frame to take all inputs at once.
And so far what I found is just the Frame with buttons (from some tutorials) to ask FileName or D... |
anonym_user
Re : Besoin de testeurs pour Pap'rass
Salut,
Excellente idée ce soft !
J'ai juste un petit problème : les doc ne se classe pas dans les chemises que je crée. Après chaque tentative de classement la recherche sur le classeur m'indique qu'il est vide. La recherche par mot clé retrouve le doc mais le document ... |
I am trying to insert values into database table using Python. I have connected to the database server and have gotten the INSERT INTO sql statement to work, however I cannot figure out how to insert values from a list into my database. I think my problem is simple, and just involves using the for-in loop correctly, bu... |
The common use case here is a user uploading a jpeg logo with a white/color background. It's (fairly) simple to switch the white pixels to transparent ones, but this leaves aliasing artifacts. An ideal solution would essentially "undo" the aliasing (given a known background color). At a minimum, the solution must beat ... |
First:
Go to the "Plugins" drop-down menu.
Open the Plugins Manager.
Download PythonScript for Notepad++.
Via the prompt, restart Notepad++.
Next:
Go to Plugins in the drop-down menu.
Click PythonScript->new script``.
Save the script with a .py extension.
Copy and paste this code, then edit it:
#*** IMPORTS ***
fro... |
I'm writing a chat application. Firstly I had loaded my views via Ajax, but then I realized it isn't necessary, because I can use exports in express insted. I think it is a better solution but I don't know now how can I pass a variable from my login form to script.js. Passing username (username = req.body.user;) in roo... |
eddy-14
DVD récents non lus en entier !
Bonjour
Je suis sous ubuntu 13.10
Je viens de recevoir des DVD et VLC ne peut pas les lire. Plus précisément, ils font planter VLC quand le film commence (les pubs passent sans problème bizarrement). Ce n'est que pour les DVD récents, les autres ne posent pas de problème.
J'ai dé... |
If you have to learn a new programming language it is most of the time quite easy. You know the structures and the way you have to think if you want to solve a problem. The first time it might be hard, but the more languages you learn the more simmilarities you'll recognize.
I also have to learn a special variant of ps... |
This is the value overridden via TZ, by symlinking /etc/localtime, or setting a TIMEZONE variable in time-related system configuration files.
I think best bet is to go thru all pytz timezones and check which one matches local timezone, each pytz timezone object contains info about utcoffset and tzname like CDT, EST, sa... |
I would like to be able to convert a string such as "1,2,5-7,10" to a python list such as [1,2,5,6,7,10]. I looked around and found this, but I was wondering if there is a clean and simple way to do this in Python.
>>> def f(x):
... result = []
... for part in x.split(','):
... if '-' in part:
... ... |
How do I get numpy array into python list?
looking for ('foo', 1, 2, 3, 4) series is a numpy array
symbol = 'foo'
def rowp (symbol,series):
rowp=[]
series = series[0:4]
ss = series.tolist
rowp.append(symbol)
rowp.append(ss)
print ro... |
On a Lenovo Thinkpad the trackpad is the red button that acts as a mouse. To set the sensistivity and speed of your trackpad on for ubuntu/debian linux do (as root):
echo -n 180 > /sys/devices/platform/i8042/serio1/speed
echo -n 250 > /sys/devices/platform/i8042/serio1/sensitivity
To have these applied every time you ... |
Do check out Oli's links. You basically see the authenticated username as verified by Basic HTTP Authentication in Django by looking at request.META['REMOTE_USER'].
Update: Tested the proposed patch for ticket #689, which is available up-to-date in telenieko's git repository here. It applies cleanly at least on revisio... |
What's the right way to join two queries on the same table data in SQLAlchemy?
i.e I have a data class defined something like this:
class DataMeasurement(Base):
__tablename__ = 'DataMeasurement'
id = Column(Integer, Sequence('data_measurement_id_seq'), primary_key=True)
data_source = Column(String)
time... |
I'm working on some code that generates all permutations of a given set of characters. Although my code works in Python 2.7 it no longer does in Python 3.x due to many changes in Strings. I'd like to adapt and since I'm new to Python, I was hoping you could give me a little push. =)
My question is, as Python generates ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.