text stringlengths 256 65.5k |
|---|
本网页是 http://webpy.infogami.com/tutorial2.en 的翻译版本,用Firefox获取最佳浏览效果
web.py 0.2 tutorialweb.py 0.2 教程
Starting开始
So you know Python and want to make a website. web.py provides the code to make that easy.既然你已经了解了 Python 并且想做一个网站。web.py 提供了代码使这个过程变得简单。
If you want to do the whole tutorial, you'll need to have installed Pyt... |
Secure Your Wireless with IPsec
Pages: 1, 2
Racoon Likes to Keep Secrets
Instead of manually changing the shared secrets in your /etc/ipsec.conf file, you can keep one shared secret and use the IKE protocol to negotiate a key. Racoon speaks IKE (ISAKMP/Oakley), which is a key management protocol.
I installed Racoon fro... |
Hi :) I wanted to have a every-20 mins-notifier kind of app and decided to develop one by myself using Tomboy notes. I read up about crontab and set a job through the sudo crontab -e command.
*/20 * * * * python /home/phantom/Desktop/alarm.py 2>/home/phantom/Desktop/whatswrong.log
And my python code would go like:
#!/u... |
Let's assume an infinite $n$-dimensional universe with stars distributed according to a Poisson process with density $\lambda$. The probability that there is no nearest neighbour within a hypherspherical volume $V=\alpha_nr^n$ of some star $S$ is $\exp(-\lambda V)=\exp(-\lambda\alpha_nr^n)$. Thus the density for findin... |
In a previous post, I promised to write about Pip and Virtualenv and I’m now finally making good. Others have done this before, but I think I have a little to add. If you develop a Python module and you don’t test it with virtualenv, don’t make your next release until you do.
Configuring the environment
Virtualenv crea... |
I am new to python and Google App Engine. I am currently working on a location based web application, I have used the following sample code http://code.google.com/p/latitudesample/
I was able to run the program in the localhost, however when I deploy the program and try to access the website I get an Internal Server Er... |
Is there another way in numpy to realize scipy.stats.mode function to get the most frequent values in ndarrays along axis?(without importing other modules) i.e.
import numpy as np
from scipy.stats import mode
a = np.array([[[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13,... |
I don't know if there is another term for it, but I mean this: You hold down a mouse button. A rectangle forms when you move the mouse around. The units inside the box get selected when you let go of the mouse button. I need this for a RTS style game I'm working on, but I don't know how to approach it.
I currently have... |
I have a data file which contains thousands of lines and each line has eight elements. Here is a small sample of the data file
-4.00 -0.80 0.1886024468848907E+01 0.1467147621657460E+01 -.1217067274319363E+01 0.7206100000000000E+03 0.7693457688734395E-12 5
-4.00 -0.70 0.1430357986632780E+01 -.... |
I've seen many tutorials for simple rectangle or circle-based collision detection with pygame.
But how can I do more complex collisions with arbitrary polygons?
Is the only option pixel-based collision detection?
Short answer: yep. :P
Long answer: rectangle collisions are built into Pygame. Circle collisions are simple... |
LASER: Lexically- and Semantically-Enriched Ruby
Homepage: http://carboni.ca/projects/p/laser
IRC: irc.freenode.net / #laser
Git: http://github.com/michaeledgar/laser
Author: Michael Edgar
Copyright: 2011
License: AGPL v3.0 w/ Commercial Exceptions. See below.
Latest Version: 0.7.0pre2
Release Date: None, yet.
Synopsis... |
In case you've been wondering: you need to override the unique_error_message method on your model. The unique_check argument is a tuple containing field names that are supposed to be unique together (for regular uniqueness this is a one-element tuple). See the example below for validating the slug field:
class MyModel(... |
sheep
Xubuntu moitié en français moitié en anglais
Bien le bonjour à tous
J'ai remonté un vieux pc pour que mes gosses puissent jouer à leurs jeux sans me piquer le mien
Comme il est vieux j'ai donc installé une xubuntu 12.04, elle fonctionne bien, cependant certains menus ne sont pas traduits en français.
Au début tou... |
I am trying to optimize my python code using pypy. While I am able to import most libraries and run succesfully, I am not able to import GDAL libraries. The same libraries when imported in Python 2.7 run fine.
I have tried adding GDAL location to PYTHONPATH, and even tried downloading GDAL Python bindings to PyPy direc... |
Winners (decided 14/09/14)
Winning answer by Markuz (Python) - 59 votes
Runner up by kuroi neko (PHP) - 52 votes
Introduction
You are in the world of the book Nineteen Eighty-Four by George Orwell.
You are a programmer for the Party and are tasked with writing a program for the telescreens. It should output pro-party m... |
use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
474 users here now
/r/programming is a reddit for discussion and news about computer programming
Guidelines
Please t... |
I have two models Category and Entry. There is another model ExtEntry that inherits from Entry
class Category(models.Model):
title = models.CharField('title', max_length=255)
description = models.TextField('description', blank=True)
...
class Entry(models.Model):
title = models.CharField('title', max_le... |
Overview
The server described in this document can be used to publish one or more directories, each containing any number of AllegroGraph triple stores, through an HTTP interface. Such directories are called 'catalogs'. A user that has access to a catalog can create, read from, write to, and delete the stores in that c... |
import random
def main():
the_number = random.randint(1,100)
guess = 0
no_of_tries = 0
while guess != the_number:
no_of_tries += 1
guess = int(input("Enter your guess: "))
if guess < the_number:
print "--------------------------------------"
print "Guess h... |
naingenieu
CSyD - divisez vos données
Bonjour tout le monde
Je viens vous présenter un projet tout droit tiré de mes cours de maths, j'ai nommé Can Split your Data
Le principe
Ce petit logiciel en python permet de décomposer un mot de passe, une phrase en plusieurs clés qui pourront être, toutes ou en parties, réunies ... |
My answer is O(n^2), but I believe it is accurate, and takes a slightly different approach and looks easier to implement.
Assume the value stored at node i is denoted by VALUE[i]. My idea is to store at each node the sum of the values on the path from root to that node. So for each node i, SUM[i] is sum of path from ro... |
I am currently trying to work with python networking and I have reached a bit of a road block. I am not able to network with any computer but localhost, which is kind-of useless with what networking is concerned. I have tried on my local network, from one computer to another, and I have tried over the internet, both fa... |
drupal
The Acquia Cloud API makes it easy to manage sites on the platform. The API allows you to perform many administrative tasks including creating, destroying and copying databases, deploying code, managing domains and copying files.
Acquia offers 2 official clients. The primary client is a drush plugin which can on... |
I have:
class Profile(models.Model):
user = models.OneToOneField(User)
birthday = models.DateField(null=True)
gender = models.CharField(max_length=140)
profile_picture = models.URLField()
class Follow(models.Model):
follower = models.ForeignKey(User, related_name="who_follows")
followed = mode... |
AnsuzPeorth
[HtmlDesktopTools] Tout pour votre bureau en HTML5/JS/CSS3
Bjr,
N'ayant pas trouvé une taskbar qui me convienne, j'ai codé, pour le fun, une taskbar html. Plutot que de me faire juste ma taskbar, j'ai plutot développé un outils qui permet de faire ses widgets en html pour le bureau, dont ma taskbar.
Ce proj... |
simohamed5130
bureau 3d
bonjour, j ai iinstallé ubuntu 12.04 et je veux personnliser mon bureau en 3d,
puisque je suis debutant , j ai cru que j ai tout fais, j ai suivi les instructions au: http://doc.ubuntu-fr.org/bureaux_3d
pour glxinfo | grep "direct rendering" , la reponse etait : direct rending : yes
puis , j ai ... |
This document explains how to use Eclipse with web2py.
It was tested on the cookbook example.
The only notable things so far are:
__init__.py modules where you want to be able to import thingsfrom your own code. Only models have been tested so far.
One gotcha is make sure you choose the correct case:
return dict(record... |
I'm trying to access the internet on my laptop using wireless tethering option on my android phone. I'm able to make DNS queries and also ping my Gateway but i'm neither able to ping other sites like www.google.com nor access internet. Here is the output of some commands that might help in resolving the issue,
itachi@i... |
AnsuzPeorth
Re : [Gm9diaCenter] Interface graphique pour mediacenter neuf/sfr
Re,
La suppression des logs se fait au démarrage de l'appli, pas du mediacenter ! (en tout cas chez moi ça marche).
Pour le systray, je t'ai ajouté une petit image clicable gnome
J'ai ajouté la possibilité de créer/supprimer les lanceurs depu... |
Hello everybody,
i am using Zenoss Core Version 3.2.0 and want to have a global search function for the interface descriptions. In the IRC Channel hackman238(i think he was Shane Scott) told me that his ZenPack Device Search does this job after a little modifcation.
I have to add "device.os.interfaces.interface.descrip... |
Thanks for everyone's replies. Here is another attempt at summarizing them. Pardon if I say too many "obvious" things: I knew nothing about least squares before, so everything was new to me.
NOT polynomial interpolation
Polynomial interpolation is fitting a polynomial of degree n given n+1 data points, e.g. finding a c... |
I am having some trouble in determining the distance of each node from the start node, or rather getting any information back at all. I get no output from my function, attached in the following link.
#Values to assign to each node
class Node:
distFromSource = infinity
previous = invalid_node
visited = Fa... |
As a temporarily solution, use
pip install requesocks
(it is just requests 0.10.8 patched with foxx's https://github.com/kennethreitz/requests/pull/478, python 2.x).
if is_open('https://github.com/shazow/urllib3/pull/68'): # ;)
import requesocks as requests
else:
import requests
session = requests.session()
se... |
Jima discovered that quassel would respond to a single privmsg containing multiple CTCP requests with multiple NOTICEs, possibly resulting in a denial of service against the IRC connection. Updated packages are available from security.ubuntu.com.
===========================================================
Ubuntu Securi... |
My question is similar to here, I would like to be able to swap out an image on a Tkinter label, but I'm not sure how to do it, except for replacing the widget itself.
Currently, I can display and image like so:
import Tkinter as tk
import ImageTk
root = tk.Tk()
img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Lab... |
Another day, another migration from MySQL to PostgreSQL... or at leastthat's how it feels sometimes. This time again I've been using some quiteold scripts to help me do the migration.
That's how I feel for MySQL users
Migrating the schema
For the schema parts, I've been using mysql2pgsql with success for manyyears. Thi... |
nad
paquets casée
Bonjour,
je comprend pas dans le gestionnaire de paquet quand je veut faire une mise a jours il me dise de corrigee d'abord les paquets casser.
je vois pas il sont ou les paquets casser, si vous pouriez m'aider sa serait super merci
cette erreur et arriver apres que j'ai modifier le fichier source.lis... |
28 9 / 2012
20 8 / 2012
The coordinate mapper, with updated documentation, is now located on this branch, awaiting the merging of Peter’s f_loc4 branch.
I’ve written an entry on coordinate mapping for the Cookbook.
Additionally, at Peter’s suggestion, I’ve written a clarification of strand as it relates to transcriptio... |
I've started to slowly dabble with the Python/C API and after much fiddling and finagling, I was able to build a spam.pyd file.
However, I must be missing something with this process and was hoping that someone could point me in the right direction. I thought that once spam.pyd was created, I could call it from Python ... |
how can a delete a specific entry from a bibtex file based on a cite key using python? I basically want a function that takes two arguments (path to bibtex file and cite key) and deletes the entry that corresponds to the key from the file. I played around with regular expressions but wasn't successful. I also looked a ... |
So as planned, today I added the feature for creating databases. This was one of those sweet features where it ended up on the tip of previous coding, so it took literally a matter of minutes to implement. Just get a name from the users, create the database, then load it in the UI,
def new_database(self, widget, data=N... |
I have installed fedora core 3(heidelberg) on vmware. But I have problems accessing anything from the internet. How do I check if I'm connected to the internet?How do I utilize the internet connection of the host OS?
If you need a more specific answer, ask a more specific question.
This shows I am able to connect to go... |
Geraldo uses ReportLab (&, optionally, PIL) to generate nice reports: http://geraldo.sourceforge.net/
Their examples use Django: http://geraldo.sourceforge.net/docs/tutorial-1.html
Here is an example of how to use in Web2Py:
Model (simplified): db.define_table(customer, Field('name', length=100))
db.define_table(purcha... |
I have this code, that supposed to work but I'm getting strange errors, for other user this code works fine.
# -*- coding: utf-8 -*-
import re, sys
import urllib2
import urllib2_file
user_hash='MTggMzc6T1dZgggggzWXpWbVptggggHTXlOV1F5WWgggggggWT0%3D'
text_file = 'sveikinimas.txt'
postdata = { 'type': '40',
... |
Table Of Contents
Configuring Ethernet Interfaces
Ethernet Interface Configuration Quick Start
Configuring a Layer 2 Ethernet Port
Adding a Description for an Ethernet Port
Configuring the Ethernet Interface Speed and Duplex Mode
Configuring the Ethernet Interface Speed
Setting the Interface Duplex Mode
Designating an ... |
When trying to refresh a materialized view based on a query that uses a mssql table (using the SqlServer Gateway), I run into the following error: After some investigation I found this was caused by a “NOT NULL” constraint on the mview-table. A small scenario:
ORA-12008: error in materialized view refresh path
ORA-0140... |
I was following the same train of thought as suggested in the answer by dwrd, so I tried implementing it in Python. There are a few things to consider that I hadn't thought initially but I think I finally got it working.
Here's the code, it surely needs some polishing up, but it's a start:
def get_score(M, i, j):
"... |
Project: An XML-based JavaScript Ticker
There are many more properties and methods available, and, using these, you can create many client side applications. The main advantage of using XML with JavaScript is that editing data becomes very easy. As XML is structured, it makes the management of content very easy. One ex... |
Ras'
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
Hors ligne
ljere
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
voici le code
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# auteur Gabriel Pettier
# license GPL V3 or later
# sert uniquement a compter le... |
Babdu89
Re : HY-D-V1 un nouveau Desktop
Bonjour...
Alors, comme j'ai toujours du temps, de la place sur mes hdd, et de la suite dans les idées ...
Toujours au sujet de la tentative d'Hybrydiser la Cubuntu 13.04 32 bits ... Voir post ci-dessus .
J'ai réinstallé, j'ai fais les maj système en commande, j'ai été obligé d'i... |
Pylades
Re : /* Topic des codeurs couche-tard [1] */
It works! \o/
Bon, alors, vous en pensez quoi ? On met le planeur ? Avant le titre ? Après ?
“Any if-statement is a goto. As are all structured loops.
“And sometimes structure is good. When it’s good, you should use it.
“And sometimes structure is _bad_, and gets int... |
Generally, a recursive algorithm would do.Start with checking all subsets against start of a given word, if found â add (append) to found values and recurse with remaining part of the word and current found values.Or if it's an end of the string â print found values.
something like that:
all=[]
def frec(word, value... |
I know this is not strictly what the original asker asked, but just because it's not wrapping the entire request body in JSON, doesn't meant it's not RESTFul to use multipart/form-data to post both the JSON and the file (or multiple files) in a single request:
curl -F "metadata=<metadata.json" -F "file=@my-file.tar.gz"... |
Below are five functions of my program to connect to an Ubuntu server using Paramiko. I wrote a command line script in Python that handles this perfectly, but I'm attempting to learn wxPython and I'm having a few challenges. The script works fine if I have it one function, but, being a newb, I'm trying to practice to w... |
Library for stubbing and setting expectations on HTTP requests in Ruby.
Features
Stubbing HTTP requests at low http client lib level (no need to change tests when you change HTTP library)
Setting and verifying expectations on HTTP requests
Matching requests based on method, URI, headers and body
Smart matching of the s... |
March 15, 2012
Getting unit test code coverage in python, and in django, is easy thanks to coverage:
pip install coverage
coverage run manage.py test app1 app2 app3
coverage html --include="my_project/*"
www-browser htmlcov/index.html
A disadvantage of Django’s test runner is that by default it runs tests for all the ... |
Hello First of all let me show you my model:
class ChannelStatus(models.Model):
channel = models.ForeignKey(Channel,unique_for_date="date")
date = models.DateField()
platform = models.ManyToManyField(Platform)
Right now, when I want to make an ChannelStatus entry, there cant be more than one en... |
Creating HTML
You can create and output HTML like this:
from ll.xist import xsc from ll.xist.ns import html, xml, meta node = xsc.Frag( · xml.XML(), · html.DocTypeXHTML10transitional(), · html.html( · · html.head( · · · meta.contenttype(), · · · html.title("Example page") · · ), · · html.body( · · · html.h1("Welcome to... |
Suppose i have :
models.py:
class Person(models.Model):
user = models.OneToOneField(User)
def get_album(self):
return self.album_set.all()
class Album(models.Model):
user = models.ForeignKey(Person)
photo = models.ImageField(upload_to = 'blahblah')
api.py:
class PersonResource(ModelResource):
... |
The function urllib2.urlopen freezes. So my question is simple:
Why does urlopenfreeze my script for ever even though timeout is set?
How can I access data at an URL (in this case: http://api.own3d.tv/live?channel=FnaticTV) without the possibility of my Python process freezing up for all eternity?
This is the part wher... |
I'm pretty much ignorant of OOP jargon and concepts. I know conceptually what an object is, and that objects have methods. I even understand that in python, classes are objects! That's cool, I just don't know what it means. It isn't clicking with me.
I'm currently trying to understand a few detailed answers that I thin... |
So I have this code, and it does what it's supposed to fine. What I want it to do is randomly scale the square by different amounts, which it does. My problem lies with the blit function, my square only seems to scale up because blit doesn't delete the old shape it just copies the new one to the surface.
How can I make... |
I have three models: Customer, Contract, Report
class Customer
pass
class Contract
customer = models.ForeignKey(Customer)
class Report
customer = models.ForeignKey(Customer)
contract = models.ForeignKey(Contract, null=True, blank=True, default=None)
In admin when edit Report I want to select Customer O... |
I'm trying to remote control gpg through a python program via POpen.
I have a file that contains encrypted data which I want to decrypt, modify and write back to disk re-encrypted.
Currently I am storing the decrypted information in a temporary file (which I shred when the program ends). Then I perform my modifications... |
The role of the network administrator is broad and varied. While most of our time is spent with day-to-day operational tasks such as assigning IP addresses and configuring hosts and applications to use an existing network, we'll occasionally be called upon to do some more interesting things.
One of the more interesting... |
What command in Windows emulates the recursive move / rename command from Unix?
Use XP's
for /r %x in (foo) do move "%x" "drive:\path\bar"
To do a recursive rename do:
for /r %x in (*.c) do ren "%x" *.cpp
Example batch:
for /r "< DIR >" %%x in (*.c) do ren "%%x" *.cpp
The built-in XCOPY command is close. It will do ... |
I'm seeking advice about design of my code.
Introduction
I have several classes, each represents one file type, eg: MediaImageFile, MediaAudioFile and generic (and also base class) MediaGenericFile.
Each file have two variants: Master and Version, so I created these classes to define theirs specific behaviour. EDIT: Ve... |
First: your four colour palette (black, green, red, yellow) has no blue component. So, you have to accept that your output image will hardly approximate the input image, unless there is no blue component to start with.
Try this code:
import Image
def estimate_color(c, bit, c_error):
c_new= c - c_error
if c_new... |
I was searching searching for a pure python module which has functionality equalent to PHP GD library. I need to write text on a image file. I know PHP GD library can do that. Does any one know about such module in python too.
Yes: the Python Imaging Library or PIL. It's used by most Python apps which need to do image ... |
senjy
Erreur fatal postfix sur email en spam ou pas
Bonjour,
J'ai installé un serveur postfix et j'utilise un script php maison qui marche, mais le résultat est un peu étrange.
1. Certains mails envoyés partent dans la boite spam de l'utilisateur
2. D'autres envoyés fonctionnent
Dans /var/log tout semble tres bien se p... |
Trying to optimise db model class property name by using name in the property.
Ex.
class terminals(db.Model):
location_code = db.StringProperty()
terminal_code = db.StringProperty(default='')
start_invoice_no = db.IntegerProperty(indexed=False, default=1, name='sin')
next_invoice_no = db.IntegerProperty(ind... |
#1926 Le 06/02/2013, à 18:17
Didier-T
Re : [Conky] Alternative à weather.com (2)
il manquait certaines info
#! /usr/bin/python3
# -*- coding: utf-8 -*-
# Par Didier-T Forum Ubuntu.fr
import urllib.request, os, time, re, sys
from bs4 import BeautifulSoup
homedir = os.path.expanduser('~')
#### initialisation des variable... |
Shanx
Re : /* Topic des codeurs [8] */
Gnagnagna...
J'ai corrigé l'indentation, par contre pour découper le main je vais attendre que le programme fonctionne...
/**** PENDU ****/
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#define TAILLE_MAX 50
void clean_stdin(void);
... |
#0 Re : -1 » [Conky] Alternative à weather.com (3) » Le 17/04/2013, à 14:58
ti_tux
Réponses : 1060
@Didier,
J'ai téléchargé ton nouveau script en python 2, et il ne fonctionne pas chez moi ^^ Je suis passé sur la 13.04 ce week-end donc il me manque peut-être une lib mais je ne vois pas laquelle.
ti_tux@kubuntu:~$ pytho... |
What are metaclasses? What do you use them for?
A metaclass is the class of a class. Like a class defines how an instance of the class behaves, a metaclass defines how a class behaves. A class is an instance of a metaclass.
While in Python you can use arbitrary callables for metaclasses (like Jerub shows), the more use... |
= Introduction =
Welcome, GNU Radio beginners. If you are reading this tutorial, you probably already have some very basic knowledge about how GNU Radio works, what it is and what it can do - and now you want to enter this exciting world of Open Source digital signal processing (DSP) yourself.
This is a tutorial on how... |
Is there any way to know by which Python version the .pyc file was compiled?
I Google out but that doesn't helped me.
Thanks in advance.
You can get the magic number of your Python as follows:
$ python -V
Python 2.6.2
# python
>>> import imp
>>> imp.get_magic().encode('hex')
'd1f20d0a'
To get the magic number for a py... |
I'm trying to build a simple API with the bottle.py (Bottle v0.11.4) web framework. To 'daemonize' the app on my server (Ubuntu 10.04.4), I'm running the shell
nohup python test.py &
, where test.py is the following python script:
import sys
import bottle
from bottle import route, run, request, response, abort, hook
@h... |
I am using Bottle.py for a small web app, and have implemented a login system where a cookie value is checked at the beginning of each request. If the cookie is set, the cookie value is checked against the user database for valid credentials, and string containing the actual username is added to the request object for ... |
July 30th, 2007 at 10:41 am by Dr. Drang
After messing around with my Audio Hijack Pro setup last week, I thought it would be nice to have a command that prints out all my scheduled timers. The usual main page of Audio Hijack Pro shows the timers in the scrolling list on the left side, but doesn’t show the whole schedu... |
Suppose I have a df which has columns of 'ID', 'col_1', 'col_2'. And I define a function :
f = lambda x, y : my_function_expression.
Now I want to apply the f to df's two columns 'col_1', 'col_2' to element-wise calculate a new column 'col_3' , somewhat like :
df['col_3'] = df[['col_1','col_2']].apply(f)
# Pandas giv... |
If I run compix-switch or fusion-icon, and then select xfwm4 from its menu, it refuses to load, terminal gives me these errors:
Code:
* Setting window manager to Xfwm4
** (xfwm4:6218): CRITICAL **: Xfconf could not be initialized
** (xfwm4:6218): WARNING **: Missing data from default files
* Setting window manager to X... |
I think it is good to shuffle the team around. Helps with cross-pollination, and keeps the team area neat. Here is the function that we use to randomize our team making sure that you do not sit next to someone you are already sitting next to.
Note: Only works with teams greater than four. Assign each space in your offi... |
regexp vs indexOf
JavaScript performance comparison
Info
I've increased the text size, since in real life scenarios you usually search for short patterns in a substancially longer text.
Preparation code
<script>
var str = "hello world! This is a longer, albit fixed, text, with hello world! repeaded in it several time... |
ljere
Re : Live Voyager 12.10
merci pour les précisions c'est vraiment cool je plains rodofr si il veut intégrer tout ça
Hors ligne
metalux
Re : Live Voyager 12.10
Le repos aura été de courte durée, qu'est-ce qu'on peut dire des C.....quand on a un coup de barre!
Quelqu'un a testé ce que j'ai exposé au post #314? De mo... |
I wrote a class Person with a metaclass Spell. In the metaclass I change an attribute and it is ok, but if i want to use this new value for another operation, it doesn't work and it use the previous value. How can i fix this?
class Spell(type):
def __new__(cls,classname,super,classdict):
def pph( hours ): r... |
There's two parts to making seamlessly tileable fBm noise like this. First, you need to make the Perlin noise function itself tileable. Here's some Python code for a simple Perlin noise function that works with any period up to 256 (you can trivially extend it as much as you like by modifying the first section):
import... |
Is there a method like isiterable? The only solution I have found so far is to call
hasattr(myObj, '__iter__')
But I am not sure how fool-proof this is.
Duck typing
try:
iterator = iter(theElement)
except TypeError:
# not iterable
else:
# iterable
# for obj in iterator:
# pass
Type checking
Use the Ab... |
Running GUI Applications
Tkinter applications are normal Python scripts, but there are a couple of complications worth knowing about when running graphical applications under Windows. These are discussed in Chapter 3, of Python on Windows, but are important enough to reiterate here; what we say in this section applies ... |
So this solution is probably too specific and too complicated for most users, but none the less it solved my problem.
The first part involved adding a Bookmark called "FileName" where I wanted my identifier. The following macro updates the Bookmark to the file name when the document is opened:
Private Sub Document_Open... |
I have this code :
objects = Event.objects.all()
i = 0
dict = {}
small_dict = {}
for o in objects:
small_dict = {'id': o.id, 'url': o.url, 'name': o.name, 'image': o.image}
dict[str(i+1)] = small_dict
small_dict = {}
return HttpResponse(
simplejson.dumps(dict),
content_type = 'application/javascript... |
I'm working with PyQt and trying to get video from a webcam to play within a QT widget. I've found tutorials for C and Qt, and for python and gtk, but NOTHING for this combo of pyQt and gstreamer. Anybody get this working?
This plays the video fine, but in a separate window:
self.gcam = gst.parse_launch('v4l2src device... |
Using Python's PIL module, we can read an digital image into an array of integers,
from PIL import Image
from numpy import array
img = Image.open('x.jpg')
im = array(img) # im is the array representation of x.jpg
I wonder how does PIL interpret an image as an array? First I tried this
od -tu1 x.jpg
and it indeed gave... |
Advanced OOP: Multimethods
by David Mertz
05/29/2003
Introduction
This article continues a review of advanced object-orientedprogramming concepts. In this installment I examine multipledispatch, which is also called multimethods. Most objectoriented languages--including Python, Perl, Ruby, C++, and Java--areintellectua... |
I have a table Users and a table Friends which maps users to other users as each user can have many friends. This relation is obviously symmetric: if user A is a friend of user B then user B is also a friend of user A, I only store this relation once. The Friends table has additional fields besides the two User ID's so... |
Yes. web2py has something that works like rails routes and a syntax very similar to Django urls. Plus we allow URL rewrite filtering based on the client IP address.
example: create a file called routes.py in web2py/ and write in it something like:
routes_in=(
('^140\.192\.34\.157:.*','/examples/default/index'), # th... |
sefiane
[résolu] Logithèque / Synaptic
Salut !
J'ai besoin de votre aide S.V.P !
Je suis débutant dans Linux , j'ai la version 12.O4 ATS.
Il fonctionnait très bien sans problème, une fois additionner Synaptic, Logithèque ne voulait pas répondre ! Il plantait, lorsque je fermais, une fenêtre apparaît, " logithèque ne ré... |
The JSON Schema Parser (V5.04) cannot handle this JSON (as run in Linqpad):
string data = @"{""payment_methods"":""Amex, Cash, Check, Discover, Mastercard, Visa"",""restaurantmealprice"":"""",""phone"":""(720) 746-9355"",""reviews"":"""",""website"":""http://pl.yext.com/plclick?pid=476af49678&ids=205234&continue=http%3... |
Id like to be able to use markers to render multiple video files. This would be handy when binding markers to camera switches so each camera gets its own video file, is this possible?
Had a request for this, thought it worth making an SE question
Id like to be able to use markers to render multiple video files. This wo... |
I tried to run this piece of code that yielded an error:
#!/usr/bin/python
import smtplib
msg = 'Hello world.'
server = smtplib.SMTP('smtp.gmail.com',587) #port 465 or 587
server.ehlo()
server.starttls()
server.ehlo()
server.login('me@gmail.com','pass')
server.sendmail('me@gmail.com','someoneelse@gmail.com',msg)
server... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.