text stringlengths 256 65.5k |
|---|
I am getting following logcat messages while registering the Android device using cordova push notification plugin.
01-25 19:33:34.871: V/GCMRegistrar(6495): Is registered on server: false
01-25 19:33:34.871: D/GCMRegistrar(6495): resetting backoff for com.example.homework
01-25 19:33:34.941: V/GCMRegistrar(6495): Regi... |
Perhabs Tahoma is a TrueType font, and you need to register it first. According to the user guide of ReportLab you need to do this:
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
pdfmetrics.registerFont(TTFont('Vera', 'Vera.ttf'))
pdfmetrics.registerFont(TTFont('VeraBd', 'VeraBd.t... |
October 25th, 2011 at 6:06 pm by Dr. Drang
I’ve written about this so many times in the past, I’m not sure I can link to every iteration. The idea is to show—on the Desktop via NerdTool—the name, the artist, the rating, the album, and the album artwork of the iTunes track currently playing. Like this:
The album artwork... |
I am appending "00000000" to a string and it works fine for the first time. However, when run second time "Junk Characters" are appended instead of "000000". This is the sample code how I am doing it in the actual program.
File one.py
# File One.py
from two import *
def One():
while(1):
key = Two()
... |
I was wondering if there is an easy way to build an indexable weak ordered set in Python. I tried to build one myself. Here's what I came up with:
"""
An indexable, ordered set of objects, which are held by weak reference.
"""
from nose.tools import *
import blist
import weakref
class WeakOrderedSet(blist.weaksortedset... |
loic_e
Kubuntu Dapper sur Sony VAIO VGN-FE28H
Voici la procédure d'installation utilisée pour installer Kubuntu Dapper sur un Vaio VGN-FE28H:
Caractéristiques:
Processeur Intel Core Duo
Fréquence 1.67 GHz
Quantité de RAM 1 Go
Type de RAM DDR2-SDRAM
Disque dur 160 Go
Puce graphique nVIDIA GeForce 7400 Turbo Cache
Taille... |
I have searched through threads on Stackoverflow and other sites using the Google machine and nothing gives me quite what I am looking for.
I am new programming student using Python 3 so most of my stuff is pretty basic.
I am writing a program that allows me to encrypt and decrypt a text file using the Caeser cipher. T... |
galanga
Re : Qarte arte.tv browser (ex Qarte+7)
@Christophe: content de voir que cela a commencé à fonctionner... Pour le second cas qui fait une erreur, c'est parce qu'il manque un back slash sur le guillemets fermant de ...3789-visual-crop-medium.jpg ; essayez avec cela :
items.append("<item>\n <title>Dominique ... |
I'm designing a model for a posting system where an entry contains an image with or without a comment. An user can reply to it as either a comment or as an image entry as well.
As there can be more properties for ImageEntry, I came up with this design with Polymodel. Not sure if this is the best way to do this. Storage... |
I am trying to use a textarea form entry which I have some javascript code to count and limit the character count, whose max_length and size are dynamic (ie these attributes are alterable after model creation).
In order to include this functionality in the django form textarea widget I suppose I would have to create a ... |
I am very new to Python. I am using the transpose operator in the numpy package:
>>> import numpy as np
>>> X = np.array([[1,2,3],[4,5,6]])
>>> np.T(X)
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
np.T(X)
AttributeError: 'module' object has no attribute 'T'
Why is it that this is an... |
So, I have two models and one holds a foreign key reference to the other:
Model1:
blah = models.ForeignKey(Model2)
I also have the following admins for Model2:
model2admin(models.ModelAdmin)
inline = [model1inline]
model1admin(admin.TabularLine):
def queryset(self, request):
qs = super(model2admin, self).quer... |
Sets or retrieves the text in the grid cells. The text is assigned to the individual cell or to the array of cells depending on the type and the number of arguments in the setCellText() method (see the examples below).
Does not encode the html controls characters (<, >, ", &) - the text containing correct html markup w... |
freechelmi
Re : Pas de lecture de DVD commerciaux sous Ubuntu 12.04 (Presque RESOLU)
Ok donc bien installé.
Peux tu lancer vlc en debug avec :
vlc -vvv
et essayer de lire ton DVD, tu nous colles ensuite le resultat de ton terminal avec http://paste.ubuntu.com/
Hors ligne
ARTAXERXES
Re : Pas de lecture de DVD commerciau... |
Soipacon
[Tuto] Wallpapoz enfin ça marche !!!!
Enfin j'ai trouvé un How To concernant wallpapoz.
C'est trés bien fait et même sans être bilingue c'est facile.
En tout cas chez moi ça marche impec sur Breezy noyau 686.
http://ubuntuforums.org/showthread.php? … =wallpapoz
Hors ligne
Bob Morane
Re : [Tuto] Wallpapoz enfin... |
This is by no means a complete answer, but if there are multiple images in the tif and if you know the size in advance, you can standardize the image samples prior to classifying them. You would cut up the image into all the possible rectangles in the tif.
So when you create a classifier (I don't mention the methods he... |
I have a model with managed = False.
class SampleModel(models.Model):
apple = models.CharField(max_length=30)
orange = models.CharField(max_length=30)
class Meta:
managed = False
I have a unit test which creates a SampleModel, however when I run the test I get:
DatabaseError: no such table: SAMPLE_... |
I'm trying to use the new fbsr_{{appID}} cookie.
I'm using the following functions to parse it, but when I try to get the access_token afterwards, I get 'error validating verification code' message. Is something wrong with these parsing functions? If not, what could be the problem?
more info: I managed to log users in ... |
I am really new to programming...
But here is my question :
I cannot post images but the plot I wish to have is a "crown" (two concentric circle with radius a I mean, mathematically speaking is really easy to define but how can I do it with a python program ?
I thought of something like this :
def Fm1(X, Y):
r =r =... |
Assuming I have a system of three Classes.The GameClass creates instances of both other classes upon initialization.
class FieldClass:
def __init__( self ):
return
def AnswerAQuestion( self ):
return 42
class PlayerClass:
def __init__( self ):
return
def DoMagicHere( self ):
... |
I'm writing a script that will print a random line of text from a file into an XCHAT channel. So far it works fine, but I want to add one last bit of functionality.
I have logs with, for example, "Oct 23 12:07:59 (nickname> " appearing before every line of text. I just want to print the parts of the lines that follow t... |
Ce cours est visible gratuitement en ligne.
Ce cours existe en livre papier.
Ce cours existe en eBook.
Vous pouvez obtenir un certificat de réussite à l'issue de ce cours.
J'ai tout compris !
Jusqu'à présent, nous avons testé des instructions d'une façon linéaire : l'interpréteur exécutait au fur et à mesure le code qu... |
A few days ago, I wrote an article on how to use your home computer to get past internet restrictions with SSH but I didn't cover the aspect of the computer running the SSH sever not having a static IP. So here is how to use DynDNS hostname for your dynamic IP.
The first thing you need to do is create an https://dyndns... |
tonyo
Lancer un petit son en Python
Salut,
je voudrais modifier le desklet mailer (adesklet) pour qu'il joue un petit son lorsqu'un nouveau message est arrivé.
J'ai vu dans le code du desklet qu'il y a un petit script "beep.sh" qui est lancé quand un message est arrivé (mais je ne suis pas sur... )
Donc peut-être, éven... |
This project is archived and is in readonly mode.
psycopg2.connect fails when using spaces in password-keyword
Reported by Martijn Bastiaan | January 2nd, 2012 @ 10:31 PM
Hi all,
Psycopg2 fails when trying to authenticate with spaces in a password. The following code illustrates the problem:
>>> import psycopg2
>>> psy... |
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Ce que j'ai vu sur Internet, c'est l'annulaire, mais ça me semble étrange quand je pose mes doigts sur le clavier.
Pour ma part, j'utilise surtout Alt Gr avec le @ et naturellement, c'est mon pouce qui se pose sur Alt gr et mon index sur @ (plac... |
I'm trying to unstack a dataframe perform operations on it (over time only) and then stack it back together like this:
import pandas as pd
import numpy as np
from itertools import *
time = pd.date_range(pd.datetime(2007,1,1),pd.datetime(2007,1,2))
slot = map(lambda n:"s-"+str(n),reversed(range(2)))
obj = map(lambda n:... |
I'm trying to multiply (add/divide/etc.) two dataframes that have different column labels.
I'm sure this is possible, but what's the best way to do it? I've tried using rename to change the columns on one df first, but (1) I'd rather not do that and (2) my real data has a multiindex on the columns (where only one layer... |
Introdução
web2py[web2py] é um Livre e open-source web framework escrito em Python[python] e programável em Python, para desenvolvimento ágil de aplicações web seguras baseadas em banco de dados. web2py é um framework auto contido, o que significa que ele contém todos os componentes que você precisa para desenvolver co... |
toma222
[HOW TO] adesklets : configuration des desklets
Il existe désormais un article sur le wiki concernant Adesklets donc je vous conseille de vous y fier, ce tutoriel n'étant plus mis à jour.
J'ouvre ce deuxième post au sujet de adesklets, afin de permettre une meilleure lisibilité de l'ensemble.Celui-ci a donc pou... |
spyke
Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr
jerhum oki mais alors je ny arrive pas a les faire tourner justement est ce normale comme wolfenstein , quake4 etc.....
Hors ligne
foxylechou
Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr
il faut autoriser le fichier a être exécuter dan... |
The setup...
Trying to set up a clean Mac os X 10.6 install to develop python/django and I didn't remember running into this on 10.5.
After installing MySQL from the installer on mysql-5.5.8-osx10.6-x86_64.dmg I ran
$ sudo pip install MySQL-python
and it seemed to go smoothly (output below)
Downloading/unpacking MySQL... |
Emails and SMS
Setting up email
Web2py provides the gluon.tools.Mail class to make it easy to send emails using web2py. One can define a mailer with
from gluon.tools import Mail
mail = Mail()
mail.settings.server = 'smtp.example.com:25'
mail.settings.sender = 'you@example.com'
mail.settings.login = 'username:password'
... |
How to exclude form fields if the user is not staff ? I tried this but didn't work , giving an error :
global name 'user' is not defined
class PostForm(ModelForm):
class Meta:
model = Photo
exclude = ['author','featured','published']
def __init__(self, *args, **kwargs):
published = kwarg... |
Introduction
Background
I'm writing a script to upload stuff including files using the multipart/form-data content type defined in RFC 2388. In the long run, I'm trying to provide a simple Python script to do uploads of binary packages for github, which involves sending form-like data to Amazon S3.
Related
This questio... |
I am running through the book "OSGi and Apache Felix 3.0" and have hit a problem where a bundle I am deploying insists that it has a dependency on the wrong version of another bundle. For anyone who has worked through these examples before, I am just at the end of chapter 10 - implementing logging functionality in the ... |
I'm running a python program compiled on windows which receives files as input but have problems when I'm passing file names.
foo.py:
def main():
args = sys.argv[1:]
for i in args:
print i
But when I compile and call it from the command line
\python foo.py *.html
It directly gives me the result of *.html which... |
How to parse a custom string using optparse, instead of command line argument?
I want to parse a string that I get from using raw_input().How can I use optparse for that?
parser = optparse.OptionParser()
# Set up your OptionParser
inp = raw_input("Enter some crap: ")
try: (options, args) = parser.parse_args(shlex.split... |
bowmore
Problème avec une HP Color LaserJet 4550N branchée en Ethernet .
Bonjour à tous.
J'essaye depuis quelques jour de faire fonctionner une imprimante HP Color LaserJet 4550N branchée en Ethernet sur un PC sous Lubuntu 12.04.
N'ayant pas de port USB sur l'imprimante, ni de port série sur ma carte mère, je n'ai que ... |
I'm trying to use Tastypie with ManyToMany relationships using intermediate models (through keyword) (https://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships)
I'm working with these models:
class Point(models.Model):
...
value = models.FloatField(_('Value'), null=True)... |
pandageek
MCedit pour minecraft
bonjour a tous,
je joue à minecraft version linux sous xubuntu et j'aimerai pouvoir utiliser le logiciel MCedit qui sert a éditer les cartes du jeu.
or il ne fonctionne pas malgré mes tentatives :
panda@panda-USB:~/Bureau/MCEdit-stable33-linux$ ./mcedit.sh
RuntimeError: Bad magic number... |
Topic: PostfixCourierIMAP MySQL Virt. hosts + optionals ClamAV & SpamAssassin
Preamble
I take no credit for the immense hardwork done by several people; this howto is built extensively upon their howtos which can (at the time of this writing) be found here:
http://kirb.insanegenius.net/postfix.html
http://www.ezunix.or... |
Issues
ZF-2375: Zend_Db_Statement_Mysqli::_execute() causes too much memory to be allocated.
Description
Zend_Db_Statement_Mysqli::_execute() calls mysqli_stmt_bind_result() *before* calling mysqli_stmt_execute(), and it does not call mysqli_stmt_store_result() or mysqli_stmt_free_result().
Modify the following test ca... |
If you have a lot of those pair things, using frozenset() is NOT a good idea. Use tuples instead.
>>> import sys
>>> fs1 = frozenset([42, 666])
>>> fs2 = frozenset([666, 42])
>>> fs1 == fs2
True
>>> t1 = tuple(sorted([42, 666]))
>>> t2 = tuple(sorted([666, 42]))
>>> t1 == t2
True
>>> sys.getsizeof(fs1)
116
>>> sys.gets... |
I would like to use properties from an inheriting model's Meta class to configure a field defined in an abstract model higher up the inheritance tree:
class NamedModel(models.Model):
class Meta:
abstract = True
verbose_name = 'object'
name = models.CharField("Name",
max_length=200,
... |
evann83
Mode superutilisateur
Bonjour
Me voici avec un soucis que je n'arrive pas a résoudre:
j'aimera utiliser la commande "javac" pour pouvoir compiler un fichier java sur mon bureau mais apparement il n'a pas envie puisque il me demande d'installer la JDK, logique je me suis dis après coups. Me voilà parti pour inst... |
Hello arm navigation gurus,
I am running the latest and greatest Electric arm_navigation Debian packages on an Ubuntu 10.04 machine. Using the planning wizard is a breeze and I have defined one kinematic group for my robot's 6-dof right arm (see here for URDF). Next I tried things out in the planning visualizer and the... |
To get your external ip, you could make a dns query to an opendns server with the special hostname "myip.opendns.com":
from subprocess import check_output
ip = check_output(["dig", "+short", "@resolver1.opendns.com",
"myip.opendns.com"]).decode().strip()
On Windows, you could try nslookup.
There is ... |
Profiling shows this is the slowest segment of my code for a little word game I wrote:
def distance(word1, word2):
difference = 0
for i in range(len(word1)):
if word1[i] != word2[i]:
difference += 1
return difference
def getchildren(word, wordlist):
return [ w for w in wordlist if di... |
Here's a list of non-LISP languages that allow for macros (including those mentioned in other answers) -- the links are to an explanations of the respective macro systems:
Languages that have features that are kind of like macros, or which accomplish more or less the same thing in different ways (namely Smalltalk and I... |
I have a table with alternate row background-color:
tr:nth-child(even) {background: #FFF}
tr:nth-child(odd) {background: #f4f4f4}
The table is comprised of two types of cells, ".main" and ".sub".
I would like the background-color to alternate every other ".main", while all ".sub" rows get the color of the previous ".m... |
If the set of characters were larger, using sets as below might be faster. As it is, this is a bit slower than a.py.
dec = set('1234567890.')
a = '27893jkasnf8u2qrtq2ntkjh8934yt8.298222rwagasjkijw'
for i in xrange(1000000):
''.join(ch for ch in a if ch in dec)
At least on my system, you can save a tiny bit of time... |
The Software Center has a section of For Purchase programs —see screenshot below—,
which is annonying me every time I want to install something.
Is there any way to remove or hide these programs from the Software Center?
Links to answers:
The Software Center has a section of
Is there any way to
For 12.04
1. Ignore the ... |
I have problem using Orthogonal Digitizing button from CAD Tools plugin menu. It moves the first point of the polygon by holding ctrl key pressed and pressing right mouse button till the last angle is squared. Is it possible to change setting to move the last vertex till the last angle is squared?
Sergey, on QGIS 1.7.4... |
pontiac76
[résolu]Google Ok mais pas internet avec Ubuntu 12.04
Bonjour,
J'ai posté hier un message à propos de mon impossibilité d'aller sur internet sauf sur sur google avec mon installation toute neuve d'Ubuntu 12.04 LTS sur un second disque dur de mon pc fixe.
Devant l'absence de réponse, j'ai relu les règles du fo... |
I'm trying to check the value of extracted data against a csv I already have. It will only loop through the rows of the CSV once, I can only check one value of feed.items(). Is there a value I need to reset somewhere? Is there a better/more efficient way to do this? Thanks.
orig = csv.reader(open("googlel.csv", "rb"), ... |
I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can analyze my output. How can I keep it open?
You have a few options:
Start the script from already open cmd window or at the end of script add somethin... |
I've just installed Ubuntu 12.04 and was about to manually install Rawstudio with the packages from SourceForge repo, but I've been stuck with dependency issues and I am short on apt command lines to sort this out.
Here's the report I'v got :
installArchives() failed: dpkg: dependency problems prevent configuration of ... |
I have changed my source to local server. I'm using Ubuntu 12.10.
When I type apt-cache search in terminal, it shows nothing.
When I install lightread it shows Unable to locate package lightread.
When I install lightread manually by python. It shows
python '/home/peng/Downloads/quickly_trunk/setup.py'
Traceback (most ... |
String
Files
String is a global object that may be used to construct String instances.
String objects may be created by calling the constructor new String(). The String object wrapsJavaScript's string primitive data type with the methods described below. The global functionString() can also be called without new in fro... |
Generating Graphics With Piddle
by Michal Wallace
05/31/2001
You probably know by now that Python's flexible data structures make working with complex data a breeze. Did you know Python also makes it a snap to visualize your data in vibrant color?
Thanks to the slew of graphics modules people have built, Python is a ha... |
I'm using the Facebook SDK on Android to post an update to the user's feed. I was able to get it to work when I did not have the Facebook client installed. Now, even after removing the Facebook app, when I try to authorize or open the feed dialog the activity is abrupty killed.
I don't get any message telling me that t... |
If I have an enumerate object x, why does doing the following:
dict(x)
clear all the items in the enumerate sequence?
If you want to create a real sequence from a iterator you can call
stuff = range(5,0,-1)
it = enumerate(stuff)
print dict(it), dict(it) # first consumes all items, so there are none left for the 2nd ca... |
Le Farfadet Spatial
Re : Petit guide pour aider au choix d'un langage
Salut à tous !
Sur amazon, j'ai trouvé ce livre
"Python - Les Fondamentaux du langage - La Programmation pour les scientifiques. de Matthieu Brucher"
Très bon livre, dans la mesure où tu sais déjà programmer et que tu es intéressé par la partie scien... |
If you are a shell addicted person and like Python, then the IPythonwas made just for you. The IPythonprovides a very usefull feature (that may look a bit strange at first) of mixing Python and Shell commandsin a easy and intuitive way. I don’t pretend to say why you should use IPython instead of your current shellbut ... |
I use SQLAlchemy for all python database access. I highly recommend SQLAlchemy.
SA uses pyodbc under the hood when connecting to SQL server databases. It uses other DBAPI libraries to connect to other database, for instance cx_Oracle.
A simplistic example, using SQLAlchemy like you would normally use a DBAPI module:
im... |
lukophron
[python]Monsieur Cinéscript
Salut,
Suite à une demande, j'ai pondu un script python pour mettre à jour la liste des films trouvés sur le topic-jeu Quel film c'est ?
Ça tourne, ça remplit son objectif (et son deuxième objectif qui était de me remettre à apprendre Python ^^)
Maintenant, il y aurait mieux.
Je po... |
Началось все с обычной задачи по работе. Открываю консоль, запускаю dev сервер с веб проектом и получаю вот такое:
Traceback (most recent call last):
File "./manage.py", line 89, in
script.run()
File "/Users/riffm/proj/third-party/werkzeug/script.py", line 168, in run
return func(**arguments)
File "/User... |
Ok, I think you a bit confused. You can use gettext and po/mo files from within appengine, since gettext is exported from Google's django.util implementation (a discussion of this can be found in the google-appengine google group) :
from django.utils.translation import gettext as _
I am not familiar with AppEngine CSV... |
When would you use a Python mixin?
That's not a rhetorical question. I'd like to know in which scenarios a mixin in python really is the best option. I can't seem to think of any, but maybe I'm not thinking outside the box enough.
The basic idea of a mixin is to create a small re-usable class that can "plug-in" to othe... |
languages
wernaeh at April 26th, 2010 19:00 — #1
Hello everyone
Recently, I've been having quite some performance problem with using a large (\~\~500 MB) std::vector\, which is repeatedly getting resized, cleared, and dropped in a tight loop.
Weirdly, the problem comes from the STL that accompanies Visual Studio 2008.
... |
Edit: Let me try to reword and improve my question. The old version is attached at the bottom.
What I am looking for is a way to express and use free functions in a type-generic way. Examples:
abs(x) # maps to x.__abs__()
next(x) # maps to x.__next__() at least in Python 3
-x # maps to x.__neg__()
In these cases... |
I started with the answer by @mgilson and reworked it a bit. I wanted to test the "decision bit" and lookup table techniques as discussed in my answer to the original question: http://stackoverflow.com/a/17782979/166949
I made a few changes to the original. Some were just style things that reflect my personal preferenc... |
#1251 Le 05/02/2012, à 19:35
chaoswizard
Re : TVDownloader: télécharger les médias du net !
Voilà, la version 0.5 est arrivée dans le PPA !
Ubuntu ==> Debian ==> Archlinux
Hors ligne
#1252 Le 05/02/2012, à 20:08
ynad
Re : TVDownloader: télécharger les médias du net !
@Greg_lattice
comme f.x0 avec la même ligne de comma... |
The other night I put (what I think are) the finishing touches of an Undo/Redo stack for Photobomb. This is the second time I've written an Undo/Redo stack, the first time being for the TextEditor Quidget. Neither time was I able to find much guidance for how to approach the problem. I handled it slightly differently e... |
gtk Functions — miscellaneous functions
gtk.AboutDialog Functions
def gtk.about_dialog_set_email_hook(func, data)
def gtk.about_dialog_set_url_hook(func, data)
gtk.AccelGroup Functions
def gtk.accelerator_valid(keyval, modifiers)
def gtk.accelerator_parse(accelerator)
def gtk.accelerator_name(accelerator_k... |
What is an algorithm to get the nth element of a rectangular tiled spiral?
Here's a short and sweet answer using just simple math in pseudocode. No conditionals and no iteration. Given
intRoot=int(sqrt(tileNum));
x=(round(intRoot/2)*(-1^(intRoot+1)))+((-1^(intRoot+1))*(((intRoot*(intRoot+1))-tileNum)-abs((intRoot*(intR... |
Not TeX-related, but since you inquired about a Python script...
#!/usr/bin/env python
# Generates QR code from given text using Google charts API.
import urllib2
import sys
# change those to your heart's content. See http://code.google.com/apis/chart/docs/gallery/qr_codes.html for more info
ENCODING='utf-8'
IMAGE_WIDT... |
Linux has come a long way in the last 10 years. At that time, if you were looking through the main audio and music applications on other operating systems, you would have struggled to find comparable, fully developed, apps on Linux. Nowadays, while no one would say the job was done, they could point to an assortment of... |
Please help (I know that it's a silly question):
I have a list d = [' ABA', ' AAB', ' BAA', ' BAA', ' AAB', ' ABA']. How can I exclude elements that appear more than once?
Convert to a set then back again:
list(set(d))
If order matters, you can pass the values through a dict that remembers the original indices. This a... |
Recently I asked for some help on how to download a file without blocking the GUI. Thanks to everyone who contributed their expertise in the post comments: I now have my program working great.
I wanted to now share my conclusions so that others can benefit from them too. To do this I am going to first explain how this ... |
I use Tastypie for Django's API. but it returns error. my code is bellow.
$.ajax({
type : "POST",
url : "http://192.168.1.130:8000/api/user/author/",
data : '{"first_name": "111","second_name": "222"}',
success: function(){
alert('Submit Success')
},
dataType : 'json',
... |
Is the memory consumed by a process spawned by a multiprocessing.Process going to be released once the process is joined?
The scenario I have in mind is roughly like this:
from multiprocessing import Process
from multiprocessing import Queue
import time
import os
def main():
tasks = Queue()
for task in [1, 18, 1,... |
Is it possible to chain metaclasses?
I have class Model which uses __metaclass__=ModelBase to process its namespace dict. I'm going to inherit from it and "bind" another metaclass so it won't shade the original one.
First approach is to subclass class MyModelBase(ModelBase):
MyModel(Model):
__metaclass__ = MyModelB... |
Certainly, there must be some way to somewhat create a list of words suggested to be included in an index.
I suggest you look at the script make-index.py (and related files) in the scripts folder of the download page at the Stacks Project (http://www.math.columbia.edu/algebraic_geometry/stacks-git/). The index it gener... |
Hello I have the following Model:
class Participation(models.Model):
workflow_activity = models.ForeignKey('WorkflowActivity')
user = models.ForeignKey(User)
role = models.ForeignKey(Role)
current = models.BooleanField()
This is the many-to-many 'through' table.I want to filter instances of workflow_ac... |
I'm trying to use multiprocessing's Pool.map() function to divide out work simultaneously. When I use the following code, it works fine:
import multiprocessing
def f(x):
return x*x
def go():
pool = multiprocessing.Pool(processes=4)
#result = pool.apply_async(self.f, [10])
#print result... |
I really miss something basic about python's logging module.
In the following code, I create a logger object (log) and add to it two handlers. One with 'INFO' level and one with 'WARNING' level. Both of them are supposed to print to stdout. I expect that calling to log.info(msg)will result in one copy of msg in my stdo... |
I have recently started to learn Python and MySQL for web purposes and I have run into a following problem :
I want to pull out from a mysql database one record that contains any text that I enter in param section, howerver I am running into following problem when making a query:
traceback (most recent call last):
Fi... |
no_spleen
Re : Petit guide pour aider au choix d'un langage
Le fichier de maillage est trops gros à poster !
Hors ligne
tshirtman
Re : Petit guide pour aider au choix d'un langage
un code permettant de générer un fichier de ce type alors?
je vais regarder ton code voir si je voit quelque chose de choquant pour les perf... |
The only reason the interpreter would have returned between lines 14 and 18 is that it hit an exception. Because the debugger has a couple of nifty postmortem functions, I modified my script to use one, fired it up to see where it stopped, and started debugging from there. Here is the modified source file; pay special ... |
UPDATE: Thanks so much for all the feedback! I’m going to look at using flock as well, and I’ll write that up soon.
Imagine you have a script that archives a bunch of data by copying it to another box. You use cron to schedule that script to run every hour, because normally, the script finishes in about thirty (30) min... |
PhoneGap + Zepto + Bootstrap
function setupFixedFix() {
if (isFixedBroken()) {
$('.container-fluid').css({'position': 'static'});
$('.actionsbar, .navbar').css({'position': 'absolute'});
fixFixed();
$(window).bind('scroll', fixFixed);
$('.mobile-page').bind('touchend', fixFixed);
}... |
I am new to python and coding in general. I am trying to read from a text file which has path names on each line. I would like to read the text file line by line and split the line strings into drive, path and file name.
Here is my code thus far:
import os,sys, arcpy
## Open the file with read only permit
f = open('C:/... |
If you visit DuckDuck Go API Page, you will find some notes about using the API. The first notes says clearly that:
As this is a Zero-click Info API, most deep queries (non topic names)
will be blank.
An here's the list of those fields:
Abstract: ""
AbstractText: ""
AbstractSource: ""
AbstractURL: ""
Image: ""
Headin... |
I am trying to install wine on a 64-bit Natty.
It was installed, but one of my regular update & dist-upgrades removed it (didn't pay enough attention to which packages would be removed).
Now when I'm trying to install it, I get the following error:
The following packages have unmet dependencies:
wine : Depends: wine1.... |
How would you divide a number by 3 without using *, /, +, -, %, operators?
The number may be signed or unsigned.
There is a simple function I found here. But it's using the
// replaces the + operator
int add(int x, int y) {
while(x) {
int t = (x & y) <<1;
y ^= x;
x = t;
}
return y;
}... |
The code below works (it will eventually pull records from a database via SQL), but I am having trouble understanding why the assert statement in the code below works.
def build_row(table, cols):
"""Build a class that creates instances of specific rows"""
class DataRow:
"""Generic data row class, specia... |
what i'm trying to do is to read each line of the file then put it into other function called handleLine which then creates output, numericgrade calculates the overall percentage and then lettergrade assigns a grade.
for example in file i have "name, last name", classid, exam, final and i want it to output full name, s... |
I parse a .txt like this:
def parse_file(src):
for line in src.readlines():
if re.search('SecId', line):
continue
else:
cols = line.split(',')
Time = cols[4]
output_file.write('{}\n'.format(
Time))
I think cols are lists that... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.