text
stringlengths 256
65.5k
|
|---|
You can use the db.rename_column function.
class Migration:
def forwards(self, orm):
# Rename 'name' field to 'full_name'
db.rename_column('app_foo', 'name', 'full_name')
def backwards(self, orm):
# Rename 'full_name' field to 'name'
db.rename_column('app_foo', 'full_name', 'name')
The first argument of db.rename_column is the table name, so it's important to remember how Django creates table names:
Django automatically derives the name of the database table from the name of your model class and the app that contains it. A model's database table name is constructed by joining the model's "app label" -- the name you used in manage.py startapp -- to the model's class name, with an underscore between them.
In the case where you have a multi-worded, camel-cased model name, such as ProjectItem, the table name will be app_projectitem (i.e., an underscore will not be inserted between project and item even though they are camel-cased).
|
I have a dictionary of keys like A1-A15, B1-B15 etc. Running dictionary.keys().sort() results in A1, A10, A11 ...
def sort_keys(dictionary):
keys = dictionary.keys()
keys.sort()
return map(dictionary.get, keys)
How do I sort it so that they get in the right order, ie A1, A2, A3 ... ?
|
Mike Yavel
Blender
Suite à mon passage sous Ubuntu HH et à diverses mises à jour, je n'arrive plus à lancer Blender. Pour résoudre le problème, je suis allé sous Synaptic et j'ai sélectionné Blender pour une désinstallation complète. Puis, j'ai essayé de le ré-installé mais j'avais oublié qu'il fallait faire un sodo apt-get install blender. Je suis donc passé par Synaptic qui ne trouve pas les paquets. J' ai essayé ensuite de l'installer par le site officiel mais j'ai mal du m'y prendre car ça n'a pas fonctionné non plus. Ensuite j'ai essayé sudo apt-get install et voila le message de la console:
Lecture des listes de paquets... Fait
Construction de l'arbre des dépendances
Lecture des informations d'état... Fait
Aucune version du paquet blender n'est disponible, mais il existe dans la base
de données. Cela signifie en général que le paquet est manquant, qu'il est devenu obsolète
ou qu'il n'est disponible que sur une autre source
E: Aucun paquet ne correspond au paquet blender
Est-ce que quelqu' un peut m'aider à me dépatouiller ? ( désinstaller proprement tout ce qui touche à Blender et le ré-installer correctement )
D'avance, merci.
Ubuntu 8.04
AMD Athlon XP 1600+
2 Go de RAM
Hors ligne
Bjo
Re : Blender
Hihi ! C'est que le paquet Blender ne serai pas dans les dépots ?
J'ai le même avec Cinepaint.
Et libmagick++9
XFCE. c'est sympa.
Hors ligne
Mike Yavel
Re : Blender
Et comment on fait pour le remettre dans les dépôts ?
Ubuntu 8.04
AMD Athlon XP 1600+
2 Go de RAM
Hors ligne
Michel38
Re : Blender
Blender est dans les dépôts:
michel@michel-laptop:~$ apt-cache search blender
blender - Very fast and versatile 3D modeller/renderer
create-resources - shared resources for use by creative applications
drqueue - distributed render queue manager
libpano12-bin - panorama tools utilities
spe - Stani's Python Editor
whitedune-docs - documentation for whitedune
wings3d - Nendo-inspired 3D polygon mesh modeller
yafray - a modern, xml-speaking raytracing-based rendering system
blender-ogrexml - Export depuis Blender vers Ogre
Montres-nous ton sources.list
Dernière modification par Michel38 (Le 04/05/2008, à 15:14)
Every day is a school day ... Your Ubuntu User number is # 572
Portable ASUS Dual Core T2130 de chez Iventive - 1.86 GHz - RAM:2 Go - DD 160 Go - Hardy Heron 8.04.4 LTS - Noyau 2.6.24.24 Generic - LiveBox Sagem 4 Mo
Mon Blog http://mdoucet.wordpress.com/
Hors ligne
Bjo
Re : Blender
OUi il est dans la liste mais pas quand on veut l'installer...
(je le dis parce que j'ai le même soucis avec d'autres log)
XFCE. c'est sympa.
Hors ligne
Michel38
Re : Blender
OUi il est dans la liste mais pas quand on veut l'installer...
(je le dis parce que j'ai le même soucis avec d'autres log)
Montres-nous ton sources.list
Every day is a school day ... Your Ubuntu User number is # 572
Portable ASUS Dual Core T2130 de chez Iventive - 1.86 GHz - RAM:2 Go - DD 160 Go - Hardy Heron 8.04.4 LTS - Noyau 2.6.24.24 Generic - LiveBox Sagem 4 Mo
Mon Blog http://mdoucet.wordpress.com/
Hors ligne
Mike Yavel
Re : Blender
## deb cdrom:[Ubuntu 7.10 _Gutsy Gibbon_ - Release i386 (20071016)]/ gutsy main restricted
###############################
## DEPOTS HARDY OFFICIELS #
###############################
####################
deb http://fr.archive.ubuntu.com/ubuntu/ hardy main universe restricted multiverse
## deb-src http://fr.archive.ubuntu.com/ubuntu/ hardy main restricted
deb http://fr.archive.ubuntu.com/ubuntu/ hardy-updates main universe restricted multiverse
## deb-src http://fr.archive.ubuntu.com/ubuntu/ hardy-updates main restricted
deb http://security.ubuntu.com/ubuntu hardy-security main universe restricted multiverse
## deb-src http://security.ubuntu.com/ubuntu hardy-security main restricted
## UNIVERSE
## deb-src http://fr.archive.ubuntu.com/ubuntu/ hardy universe
## deb-src http://fr.archive.ubuntu.com/ubuntu/ hardy-updates universe
## deb-src http://security.ubuntu.com/ubuntu hardy-security universe
## MULTIVERSE
## deb-src http://fr.archive.ubuntu.com/ubuntu/ hardy multiverse
## deb-src http://fr.archive.ubuntu.com/ubuntu/ hardy-updates multiverse
## deb-src http://security.ubuntu.com/ubuntu hardy-security multiverse
## BACKPORTS
## deb http://fr.archive.ubuntu.com/ubuntu/ hardy-backports main restricted universe multiverse
## deb-src http://fr.archive.ubuntu.com/ubuntu/ hardy-backports main restricted universe multiverse
## PROPOSED
deb http://fr.archive.ubuntu.com/ubuntu/ hardy-proposed main universe restricted multiverse
## deb-src http://fr.archive.ubuntu.com/ubuntu/ hardy-proposed restricted main universe multiverse
## CANONICAL
deb http://archive.canonical.com/ubuntu gutsy partner
####################
###################################
## DEPOTS HARDY NON OFFICIELS #
###################################
####################
## GISS TV
## deb http://giss.tv/~vale/ubuntu32 ./
## deb-src http://giss.tv/~vale/ubuntu32 ./
####################
####################
## AKIRAD
deb http://repository.akirad.net akirad-hardy main
## deb-src http://repository.akirad.net akirad-hardy main
####################
####################
## ETERNITY SCREENSAVER
deb http://parker1.co.uk/apt hardy main
##deb-src http://parker1.co.uk/apt hardy main
####################
Ubuntu 8.04
AMD Athlon XP 1600+
2 Go de RAM
Hors ligne
Michel38
Re : Blender
Re,
Ton sources.list semble complet .... je n'utilise pas blender mais je viens de l'installer ... c'est çà ?
... donc je ne sais pas ce qui se passe chez toi ?
Every day is a school day ... Your Ubuntu User number is # 572
Portable ASUS Dual Core T2130 de chez Iventive - 1.86 GHz - RAM:2 Go - DD 160 Go - Hardy Heron 8.04.4 LTS - Noyau 2.6.24.24 Generic - LiveBox Sagem 4 Mo
Mon Blog http://mdoucet.wordpress.com/
Hors ligne
Mike Yavel
Re : Blender
Oui, c'est bien ça. Heureux que ça fonctionne chez toi...:rolleyes:
Ubuntu 8.04
AMD Athlon XP 1600+
2 Go de RAM
Hors ligne
Michel38
Re : Blender
Oui, c'est bien ça. Heureux que ça fonctionne chez toi...:rolleyes:
Re,
Tu as essayé en virant tous les fr. de tes dépôts pour utiliser les dépôts internationaux ?
Every day is a school day ... Your Ubuntu User number is # 572
Portable ASUS Dual Core T2130 de chez Iventive - 1.86 GHz - RAM:2 Go - DD 160 Go - Hardy Heron 8.04.4 LTS - Noyau 2.6.24.24 Generic - LiveBox Sagem 4 Mo
Mon Blog http://mdoucet.wordpress.com/
Hors ligne
Mike Yavel
Re : Blender
Comment ça ? Tu peux être plus précis sur la démarche à suivre ?
Ubuntu 8.04
AMD Athlon XP 1600+
2 Go de RAM
Hors ligne
Michel38
Re : Blender
Comment ça ? Tu peux être plus précis sur la démarche à suivre ?
Dans ton sources.list, tu vires tous les fr. après http://
Every day is a school day ... Your Ubuntu User number is # 572
Portable ASUS Dual Core T2130 de chez Iventive - 1.86 GHz - RAM:2 Go - DD 160 Go - Hardy Heron 8.04.4 LTS - Noyau 2.6.24.24 Generic - LiveBox Sagem 4 Mo
Mon Blog http://mdoucet.wordpress.com/
Hors ligne
Neuro
Re : Blender
Voilà le mien, et j' ai blender avec :
#Dépôts principaux
deb http://fr.archive.ubuntu.com/ubuntu/ hardy main restricted
deb http://security.ubuntu.com/ubuntu hardy-security main restricted
deb http://fr.archive.ubuntu.com/ubuntu/ hardy-updates main restricted
# Dépôts de sources (uniquement utiles pour télécharger les sources avec apt-get source. Dans ce cas enlever les #)
# deb-src http://fr.archive.ubuntu.com/ubuntu/ hardy main restricted
# deb-src http://security.ubuntu.com/ubuntu hardy-security main restricted
# deb-src http://fr.archive.ubuntu.com/ubuntu/ hardy-updates main restricted
#Dépôts Universe et Multiverse
deb http://fr.archive.ubuntu.com/ubuntu/ hardy universe multiverse
deb http://security.ubuntu.com/ubuntu hardy-security universe multiverse
deb http://fr.archive.ubuntu.com/ubuntu/ hardy-updates universe multiverse
# Dépôts de sources (uniquement utiles pour télécharger les sources avec apt-get source. Dans ce cas enlever les #)
# deb-src http://fr.archive.ubuntu.com/ubuntu/ hardy universe multiverse
# deb-src http://security.ubuntu.com/ubuntu hardy-security universe multiverse
# deb-src http://fr.archive.ubuntu.com/ubuntu/ hardy-updates universe multiverse
#Dépôts Backports
deb http://fr.archive.ubuntu.com/ubuntu/ hardy-backports main restricted universe multiverse
# Dépôts de sources (uniquement utiles pour télécharger les sources avec apt-get source. Dans ce cas enlever les #)
# deb-src http://fr.archive.ubuntu.com/ubuntu/ hardy-backports main restricted universe multiverse
#Dépôt commercial
## Commercial
deb http://archive.canonical.com/ubuntu hardy partner
## Sources
# deb-src http://archive.canonical.com/ubuntu hardy partner
#Dépôts Medibuntu
## Key : wget -q http://fr.packages.medibuntu.org/medibuntu-key.gpg -O- | sudo apt-key add -
#Kubuntu
# Key : wget -q http://people.ubuntu.com/~jriddell/kubuntu-packages-jriddell-key.gpg -O- | sudo apt-key add -
#Proposed
deb http://fr.archive.ubuntu.com/ubuntu/ hardy-proposed main restricted universe multiverse
# Dépôts de sources (uniquement utiles pour télécharger les sources avec apt-get source. Dans ce cas enlever les #)
# deb-src http://fr.archive.ubuntu.com/ubuntu/ hardy-proposed main restricted universe multiverse
#Dépôts Innotek Virtual Box
# Key : wget -q http://www.virtualbox.org/debian/innotek.asc -O- | sudo apt-key add -
## VirtualBox
# Le dépôt pour Ubuntu 8.04 LTS n'est pas encore disponible.
# Utilisez le dépôt pour Ubuntu 7.10.
deb http://www.virtualbox.org/debian gutsy non-free
#Dépôts Wine
# Key : wget -q http://wine.budgetdedicated.com/apt/387EE263.gpg -O- | sudo apt-key add -
## Wine
# voir http://www.winehq.org/site/download-deb
deb http://wine.budgetdedicated.com/apt hardy main
## Dépôts de sources (uniquement utiles pour télécharger les sources avec
## apt-get source. Dans ce cas enlever les #)
# deb-src http://wine.budgetdedicated.com/apt hardy main
#########################################
### Depot Wicd
deb http://apt.wicd.net hardy extras
#########################################
### Depot Awn / Cairo dock
deb http://ppa.launchpad.net/reacocard-awn/ubuntu hardy main
deb http://repository.cairo-dock.org/ubuntu gutsy cairo-dock
##second-life
deb http://ubuntu.cafuego.net hardy-cafuego secondlife
deb-src http://ubuntu.cafuego.net hardy-cafuego secondlife
Faire un :
gksudo gedit /etc/apt/sources.list
pour éditer son source.list
Puis :
sudo apt-get update
Enfin:
sudo apt-get upgrade
Et voilà Blender sera dans synaptic.
Dernière modification par Neuro (Le 04/05/2008, à 16:41)
Hors ligne
Mike Yavel
Re : Blender
Neuro, tu me dis d'éditer mon sources.list mais...qu'est ce que je dois changer ?
Ubuntu 8.04
AMD Athlon XP 1600+
2 Go de RAM
Hors ligne
Neuro
Re : Blender
Neuro, tu me dis d'éditer mon sources.list mais...qu'est ce que je dois changer ?
Remplace ton source.list par le mien.
gksudo gedit /etc/apt/sources.list
Tu sauvgarde le nouveau, et tu fait les commandes qui suivent :
sudo apt-get update
Puis :
sudo apt-get upgrade
Dés lors tu aura de nouveau Blender dans synaptic.
Il faut ajouter les clés comme suit :
Toujours dans le terminal :
wget -q http://fr.packages.medibuntu.org/medibuntu-key.gpg -O- | sudo apt-key add -
wget -q http://www.virtualbox.org/debian/innotek.asc -O- | sudo apt-key add -
wget -q http://wine.budgetdedicated.com/apt/387EE263.gpg -O- | sudo apt-key add -
Dernière modification par Neuro (Le 04/05/2008, à 21:00)
Hors ligne
Mike Yavel
Re : Blender
C'est quoi ces clés ?
Est ce je dois taper ça dans le terminal après l'installation en passant par Synaptic? et ce que je dois le faire avant ? Je ne me souviens pas d'avoir installé ces clés la première fois que j'ai installé Blender...pourquoi faut-il les installer maintenant ?
Ubuntu 8.04
AMD Athlon XP 1600+
2 Go de RAM
Hors ligne
Neuro
Re : Blender
C'est quoi ces clés ?
Les clés servent a pouvoir récupérer les paquets des dépôts, il faut importer une clé d'authentification (clé GPG). Cette clé a aussi pour but de vérifier que tout paquet provenant du dépôt est un paquet valide, autorisé à s'y trouver.
Dernière modification par Neuro (Le 04/05/2008, à 21:47)
Hors ligne
Neuro
Re : Blender
Ajoute les clés avec le terminal. Après tu fait les commandes : sudo apt-get update et sudo apt-get upgrade .
Et seulement après tu pourra utiliser Synaptic
Hors ligne
Neuro
Re : Blender
pourquoi faut-il les installer maintenant ?
Car si tu ajoute pas les clés tu aura un message d' erreur qui apparaîtra avec Synaptic.
Hors ligne
Mike Yavel
Re : Blender
Donc, il faut les installer avant d'installer Blender en passant par Synaptic? C'est bien ça ?
Ubuntu 8.04
AMD Athlon XP 1600+
2 Go de RAM
Hors ligne
Neuro
Re : Blender
Ouep ! Synaptic c' est en dernier. Tu aura sûrement des mises à jours a faire avec ce nouveau source.list.
Hors ligne
Mike Yavel
Re : Blender
Je reçois des messages d'erreurs lors de l'update et de l'upgrade:
michael@michael:~$ sudo apt-get update
Atteint http://security.ubuntu.com hardy-security Release.gpg
Ign http://security.ubuntu.com hardy-security/main Translation-fr
Atteint http://archive.canonical.com hardy Release.gpg
Ign http://archive.canonical.com hardy/partner Translation-fr
Réception de : 1 http://www.virtualbox.org gutsy Release.gpg [189B]
Ign http://www.virtualbox.org gutsy/non-free Translation-fr
Réception de : 2 http://wine.budgetdedicated.com hardy Release.gpg [191B]
Ign http://wine.budgetdedicated.com hardy/main Translation-fr
Ign http://repository.cairo-dock.org gutsy Release.gpg
Ign http://repository.cairo-dock.org gutsy/cairo-dock Translation-fr
Ign http://ppa.launchpad.net hardy Release.gpg
Ign http://ppa.launchpad.net hardy/main Translation-fr
Ign http://security.ubuntu.com hardy-security/restricted Translation-fr
Ign http://security.ubuntu.com hardy-security/universe Translation-fr
Ign http://security.ubuntu.com hardy-security/multiverse Translation-fr
Atteint http://security.ubuntu.com hardy-security Release
Atteint http://archive.canonical.com hardy Release
Ign http://repository.cairo-dock.org gutsy Release
Réception de : 3 http://www.virtualbox.org gutsy Release [700B]
Réception de : 4 http://wine.budgetdedicated.com hardy Release [1013B]
Réception de : 5 http://ppa.launchpad.net hardy Release [27,6kB]
Ign http://repository.cairo-dock.org gutsy/cairo-dock Packages
Ign http://ppa.launchpad.net hardy/main Packages
Atteint http://security.ubuntu.com hardy-security/main Packages
Atteint http://repository.cairo-dock.org gutsy/cairo-dock Packages
Atteint http://archive.canonical.com hardy/partner Packages
Atteint http://www.virtualbox.org gutsy/non-free Packages
Atteint http://ppa.launchpad.net hardy/main Packages
Atteint http://security.ubuntu.com hardy-security/restricted Packages
Atteint http://security.ubuntu.com hardy-security/universe Packages
Atteint http://security.ubuntu.com hardy-security/multiverse Packages
Ign http://wine.budgetdedicated.com hardy/main Packages
Ign http://apt.wicd.net hardy Release.gpg
Ign http://apt.wicd.net hardy/extras Translation-fr
Atteint http://wine.budgetdedicated.com hardy/main Packages
Réception de : 6 http://apt.wicd.net hardy Release [29,1kB]
Réception de : 7 http://ubuntu.cafuego.net hardy-cafuego Release.gpg [189B]
Ign http://ubuntu.cafuego.net hardy-cafuego/secondlife Translation-fr
Ign http://fr.archive.ubuntu.com hardy Release.gpg
Atteint http://apt.wicd.net hardy/extras Packages
Ign http://fr.archive.ubuntu.com hardy/main Translation-fr
Réception de : 8 http://ubuntu.cafuego.net hardy-cafuego Release [23,7kB]
Ign http://fr.archive.ubuntu.com hardy/restricted Translation-fr
Ign http://ubuntu.cafuego.net hardy-cafuego Release
Atteint http://ubuntu.cafuego.net hardy-cafuego/secondlife Packages
Atteint http://ubuntu.cafuego.net hardy-cafuego/secondlife Sources
Ign http://fr.archive.ubuntu.com hardy/universe Translation-fr
Ign http://fr.archive.ubuntu.com hardy/multiverse Translation-fr
Réception de : 9 http://fr.archive.ubuntu.com hardy-updates Release.gpg [191B]
Ign http://fr.archive.ubuntu.com hardy-updates/main Translation-fr
Ign http://fr.archive.ubuntu.com hardy-updates/restricted Translation-fr
Ign http://fr.archive.ubuntu.com hardy-updates/universe Translation-fr
Ign http://fr.archive.ubuntu.com hardy-updates/multiverse Translation-fr
Atteint http://fr.archive.ubuntu.com hardy-backports Release.gpg
Ign http://fr.archive.ubuntu.com hardy-backports/main Translation-fr
Ign http://fr.archive.ubuntu.com hardy-backports/restricted Translation-fr
Ign http://fr.archive.ubuntu.com hardy-backports/universe Translation-fr
Ign http://fr.archive.ubuntu.com hardy-backports/multiverse Translation-fr
Ign http://fr.archive.ubuntu.com hardy-proposed Release.gpg
Ign http://fr.archive.ubuntu.com hardy-proposed/main Translation-fr
Ign http://fr.archive.ubuntu.com hardy-proposed/restricted Translation-fr
Réception de : 10 http://fr.archive.ubuntu.com hardy-proposed/universe Translation-fr [193kB]
Réception de : 11 http://fr.archive.ubuntu.com hardy-proposed/multiverse Translation-fr [4875B]
Ign http://fr.archive.ubuntu.com hardy Release
Ign http://fr.archive.ubuntu.com hardy-updates Release
Atteint http://fr.archive.ubuntu.com hardy-backports Release
Atteint http://fr.archive.ubuntu.com hardy-proposed Release
Atteint http://fr.archive.ubuntu.com hardy/main Packages
Atteint http://fr.archive.ubuntu.com hardy/restricted Packages
Atteint http://fr.archive.ubuntu.com hardy/universe Packages
Atteint http://fr.archive.ubuntu.com hardy/multiverse Packages
Atteint http://fr.archive.ubuntu.com hardy-updates/main Packages
Atteint http://fr.archive.ubuntu.com hardy-updates/restricted Packages
Atteint http://fr.archive.ubuntu.com hardy-updates/universe Packages
Atteint http://fr.archive.ubuntu.com hardy-updates/multiverse Packages
Ign http://fr.archive.ubuntu.com hardy-backports/main Packages
Atteint http://fr.archive.ubuntu.com hardy-backports/restricted Packages
Atteint http://fr.archive.ubuntu.com hardy-backports/universe Packages
Ign http://fr.archive.ubuntu.com hardy-backports/multiverse Packages
Ign http://fr.archive.ubuntu.com hardy-proposed/main Packages
Ign http://fr.archive.ubuntu.com hardy-proposed/restricted Packages
Ign http://fr.archive.ubuntu.com hardy-proposed/universe Packages
Ign http://fr.archive.ubuntu.com hardy-proposed/multiverse Packages
Err http://fr.archive.ubuntu.com hardy-backports/main Packages
503 Service Temporarily Unavailable
Err http://fr.archive.ubuntu.com hardy-backports/multiverse Packages
503 Service Temporarily Unavailable
Err http://fr.archive.ubuntu.com hardy-proposed/main Packages
503 Service Temporarily Unavailable
Err http://fr.archive.ubuntu.com hardy-proposed/restricted Packages
503 Service Temporarily Unavailable
Err http://fr.archive.ubuntu.com hardy-proposed/universe Packages
503 Service Temporarily Unavailable
Atteint http://fr.archive.ubuntu.com hardy-proposed/multiverse Packages
222ko réceptionnés en 16s (13,1ko/s)
W: GPG error: http://ubuntu.cafuego.net hardy-cafuego Release: Les signatures suivantes n'ont pas pu être vérifiées car la clé publique n'est pas disponible : NO_PUBKEY 81600957AF425CB5
W: Impossible de récupérer http://fr.archive.ubuntu.com/ubuntu/dists/hardy-backports/main/binary-i386/Packages.gz 503 Service Temporarily Unavailable
W: Impossible de récupérer http://fr.archive.ubuntu.com/ubuntu/dists/hardy-backports/multiverse/binary-i386/Packages.gz 503 Service Temporarily Unavailable
W: Impossible de récupérer http://fr.archive.ubuntu.com/ubuntu/dists/hardy-proposed/main/binary-i386/Packages.gz 503 Service Temporarily Unavailable
W: Impossible de récupérer http://fr.archive.ubuntu.com/ubuntu/dists/hardy-proposed/restricted/binary-i386/Packages.gz 503 Service Temporarily Unavailable
W: Impossible de récupérer http://fr.archive.ubuntu.com/ubuntu/dists/hardy-proposed/universe/binary-i386/Packages.gz 503 Service Temporarily Unavailable
E: Le téléchargement de quelques fichiers d'index a échoué, ils ont été ignorés, ou les anciens ont été utilisés à la place.
E: Impossible de verrouiller /var/lib/dpkg/lock - open (11 Ressource temporairement non disponible)
E: Unable to lock the administration directory (/var/lib/dpkg/), is another process using it?
michael@michael:~$ sudo apt-get upgrade
E: Impossible de verrouiller /var/lib/dpkg/lock - open (11 Ressource temporairement non disponible)
E: Unable to lock the administration directory (/var/lib/dpkg/), is another process using it?
Ubuntu 8.04
AMD Athlon XP 1600+
2 Go de RAM
Hors ligne
NicoA380
Re : Blender
J'ai installé et utilisé Blender hier.
Mes dépôts sont configuré sur le mirroir de Free :
Synaptic > Configuration > Dépôts > Télécharger depuis > Autre > ftp free
Hors ligne
Mike Yavel
Re : Blender
J'ai essayé ta méthode Nico et j'ai l'erreur suivante:
W: GPG error: http://ubuntu.cafuego.net hardy-cafuego Release: Les signatures suivantes n'ont pas pu être vérifiées car la clé publique n'est pas disponible : NO_PUBKEY 81600957AF425CB5
Ubuntu 8.04
AMD Athlon XP 1600+
2 Go de RAM
Hors ligne
Neuro
Re : Blender
J'ai essayé ta méthode Nico et j'ai l'erreur suivante:
W: GPG error: http://ubuntu.cafuego.net hardy-cafuego Release: Les signatures suivantes n'ont pas pu être vérifiées car la clé publique n'est pas disponible : NO_PUBKEY 81600957AF425CB5
Oups ! Tiens voilà la clé:
wget http://ubuntu.cafuego.net/AF425CB5.gpg -O- | sudo apt-key add -
Hors ligne
|
I am a newbie. So starting to learn python, I tried to generate random values by passing in a negative and positive number.
Let say -1, 1. Can someone let me know how I should do this in python.
Thanks in advance
>>> import random
>>> random.uniform(-1, 1)
0.4779007751444888
>>> random.uniform(-1, 1)
-0.10028581710574902
import random
def r(minimum, maximum):
return minimum + (maximum - minimum) * random.random()
print r(-1, 1)
EDIT: @San4ez's
Anyway,
def uniform(self, a, b):
"Get a random number in the range [a, b) or [a, b] depending on rounding."
return a + (b-a) * self.random()
Most languages have a function that will return a random number in the range [0, 1], which you can then manipulate to suite the range you need. In python, the function is
import random
random_number = random.random() * 2 - 1
By doubling the number we get a range of [0, 2], and by subtracting one from it, we get [-1, 1].
if you want integer in a specified range:
print random.randrange(-1, 2)
it uses the same convention as
You can also do something like this
import random
random.choice([-1, 1])
|
Python 3.2 in case that matters...
The following code shows that the "concrete class" can either implement some_method as a static method or an instance method:
import abc
class SomeAbstractClass(metaclass=abc.ABCMeta):
@abc.abstractmethod
def some_method(self): pass
class ValidConcreteClass1(SomeAbstractClass):
@staticmethod
def some_method():
print("foo!")
class ValidConcreteClass2(SomeAbstractClass):
def some_method(self):
print("foo!")
ValidConcreteClass1.some_method()
instance = ValidConcreteClass2()
instance.some_method()
My question is, can I force the implementation of some_method to be static in the inheriting class?
I noticed @abc.abstractstaticmethod and thought this was the answer but the following code still runs just fine. I would think it would reject ValidConreteClass2 because some_method is not static:
import abc
class SomeAbstractClass(metaclass=abc.ABCMeta):
@abc.abstractstaticmethod
def some_method(self): pass
class ValidConcreteClass1(SomeAbstractClass):
@staticmethod
def some_method():
print("foo!")
class ValidConcreteClass2(SomeAbstractClass):
def some_method(self):
print("foo!")
ValidConcreteClass1.some_method()
instance = ValidConcreteClass2()
instance.some_method()
|
After you've made your .scheme or .schemedef file (see Add Support for Your Language) there's still something missing from that authentic professional feeling when programming with your newly defined language. For that you need to create an auto-indenter.
Please note: You need to have PyPN installed for this to work! See Install PyPN for further instructions.
To create an auto-indenter you must make a new Python script that PN recognizes as an indenter. Throughout this tutorial I'm going to use The Elder Scrolls scripting language for Oblivion as an example (_here should be tes.schemedef file but the site don't allow me to upload it_). More information about it can be found at http:_cs.elderscrolls.com/constwiki/index.php/Portal:Scripting.
Every auto-indenter must import at least the following (in most cases these are enough too):
import scintilla from pypn.decorators import indenter
After the imports we define the indenter function. Let's see the start of that definition from the example before further explanation:
@indenter("tes") def tes_indent(c, doc):
The first line tells PyPN that the following function is meant to be an indenter. The string in parentheses must match the name of the scheme or schemedef of the language we're trying to indent. The second line is regular Python. You can name the function what ever you like but descriptive names like ''tes_indent'' have advantages. The function must have two parameters - their naming doesn't matter but as PyPN already uses ''c'' and ''doc'' for them there's no reason to change.
In Oblivion scripts the indentation is made by keywords. There are few keywords that start a block that gets indented and there are other keywords that end such blocks and cause unindentation. Easiest way to define them in Python is to use a list. I find it best to define these outside of the function.
# Keywords that cause indentation. i_kws = ['scriptname', 'scn', 'begin', 'if', 'elseif'] # Keywords that cause unindentation. u_kws = ['end', 'endif']
Lines starting with ''#'' are Python comments. Variable names are again inconsequential - just use what you consider descriptive. In Python lists are surrounded by brackets and list items are separated by commas. As Oblivion scripts are not case-sensitive it's easiest to type the keywords in lowercase.
People like different tabwidths for indentation and such preferences often vary from language to language. To ease that we define one more variable before we move on to function itself (I've used tabwidth of two because that's how most of the code in their Wiki is indented but in most cases I'd prefer four):
# Tabwidth used for indentation. tab = 2
To be able to auto-indent we need quite a bit of data from our document. Depending on how your language is indented you may need more or less than we do in our example but you should get the idea. Let's have the next bit of code before further explanation (I've included some of the stuff from earlier so that you know where to place this):
@indenter("tes") def tes_indent(c, doc): sci = scintilla.Scintilla(doc) pos = sci.CurrentPos l_cur = sci.LineFromPosition(pos) t_start = sci.PositionFromLine(l_cur - 1) t_end = pos - 1 txt = sci.GetText(t_start, t_end) kw = txt.split()[0].lower()
In almost every PyPN script we a have variable that is set to ''scintilla.Scintilla(doc)'' (or more often actually ''scintilla.Scintilla(pn.CurrentDoc())''). We need it to use Scintilla's functions through PyPN.
For our needs we need to know the following about our document:
With this information at hand we can move on.
First, let's figure out what we're trying to do. Here's the logic in pseudo language:
if [first word on previous line] == [a block starting keyword] -> indent current line elseif [first word on previous line] == [a block ending keyword] -> unindent previous and current line
So obviously we're going to need some if statements. Let's see some code before further explanation:
if kw in i_kws: c_ind = sci.GetLineIndentation(l_cur) p_ind = sci.GetLineIndentation(l_cur-1) if c_ind == p_ind or c_ind == 0: c_ind += tab sci.IndentLine(l_cur, c_ind)
This is the if clause for indentation. First we check if the word ''kw'' is among those that start an indented block. Then we get the indentation levels for current and previous line with ''sci.GetLineIndentation()'' and check that either both lines are equally indented or that the current line is not indented at all. If either of these is correct current line is indented by the amount defined in our variable ''tab''.
elif kw in u_kws: c_ind = sci.GetLineIndentation(l_cur) p_ind = sci.GetLineIndentation(l_cur-2) if c_ind == p_ind: c_ind -= tab sci.IndentLine(l_cur, c_ind) sci.IndentLine(l_cur-1, c_ind)
Code for unindentation is very similar. Most notable differences are that we unindent both current and previous line, and due to that we use the line before previous when comparing indentation levels of lines (otherwise we'd unindent twice on Windows where EOL is marked by ''\n\r''). Also ''kw'' is obviously searched from the list containing block ending keywords.
import scintilla from pypn.decorators import indenter # Keywords that cause indentation. i_kws = ['scriptname', 'scn', 'begin', 'if', 'elseif'] # Keywords that cause unindentation. u_kws = ['end', 'endif'] # Tabwidth used for indentation. tab = 2 @indenter("tes") def tes_indent(c, doc): sci = scintilla.Scintilla(doc) pos = sci.CurrentPos l_cur = sci.LineFromPosition(pos) t_start = sci.PositionFromLine(l_cur - 1) t_end = pos - 1 txt = sci.GetText(t_start, t_end) kw = txt.split()[0].lower() if kw in i_kws: c_ind = sci.GetLineIndentation(l_cur) p_ind = sci.GetLineIndentation(l_cur-1) if c_ind == p_ind or c_ind == 0: c_ind += tab sci.IndentLine(l_cur, c_ind) elif kw in u_kws: c_ind = sci.GetLineIndentation(l_cur) p_ind = sci.GetLineIndentation(l_cur-2) if c_ind == p_ind: c_ind -= tab sci.IndentLine(l_cur, c_ind) sci.IndentLine(l_cur-1, c_ind)
With the current lack of documentation and some bugs in PyPN creating scripts is often about learning from errors. I used the Python indenter that comes with PyPN as a some sort of a starting point (I must notify that there is a redundant piece of code in that one - there is no need to check if the character is EOL as that's already done in ''pypn.glue''). PN source code and Scintilla documentation were also essential. I hope someone finds this useful.
|
oliver2004
problème wifi avec portable HP nx6125...
Salut à tous, je viens d'installer sans trop de mal Kubuntu 7.10 sur mon portable HP Compaq nx6125 (j'ai de la chance il n'est pas tatoué...). Aparemment tout marche sur la machine... sauf le wifi... j'en ai pas besoin là maintenant mais j'en aurai sûrement besoin et de toutes façons, c'est agréable que tout fonctionne. La carte est fonctionnelle puisqu'aucun problème sous windows, mais rien à faire pour la faire marcher sous Kubuntu. J'ai suivi le tuto http://doc.ubuntu-fr.org/materiel/liste … paq_nx6125 mais rien n'y fait. Voici ce que j'obtiens avec les commandes indiquées sur le sujet épinglé.
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=7.10
DISTRIB_CODENAME=gutsy
DISTRIB_DESCRIPTION="Ubuntu 7.10"
olivier@kubuntu:~$ lsusb
Bus 003 Device 001: ID 0000:0000
Bus 002 Device 005: ID 05a4:9862 Ortek Technology, Inc.
Bus 002 Device 004: ID 05e3:1205 Genesys Logic, Inc. Afilias Optical Mouse H3003
Bus 002 Device 003: ID 05a4:9837 Ortek Technology, Inc.
Bus 002 Device 002: ID 08ff:2580 AuthenTec, Inc.
Bus 002 Device 001: ID 0000:0000
Bus 001 Device 001: ID 0000:0000
olivier@kubuntu:~$ lspci
00:00.0 Host bridge: ATI Technologies Inc RS480 Host Bridge (rev 01)
00:01.0 PCI bridge: ATI Technologies Inc RS480 PCI Bridge
00:04.0 PCI bridge: ATI Technologies Inc RS480 PCI Bridge
00:05.0 PCI bridge: ATI Technologies Inc RS480 PCI Bridge
00:13.0 USB Controller: ATI Technologies Inc IXP SB400 USB Host Controller
00:13.1 USB Controller: ATI Technologies Inc IXP SB400 USB Host Controller
00:13.2 USB Controller: ATI Technologies Inc IXP SB400 USB2 Host Controller
00:14.0 SMBus: ATI Technologies Inc IXP SB400 SMBus Controller (rev 11)
00:14.1 IDE interface: ATI Technologies Inc Standard Dual Channel PCI IDE Controller
00:14.3 ISA bridge: ATI Technologies Inc IXP SB400 PCI-ISA Bridge
00:14.4 PCI bridge: ATI Technologies Inc IXP SB400 PCI-PCI Bridge
00:14.5 Multimedia audio controller: ATI Technologies Inc IXP SB400 AC'97 Audio Controller (rev 02)
00:14.6 Modem: ATI Technologies Inc SB400 AC'97 Modem Controller (rev 02)
00:18.0 Host bridge: Advanced Micro Devices [AMD] K8 [Athlon64/Opteron] HyperTransport Technology Configuration
00:18.1 Host bridge: Advanced Micro Devices [AMD] K8 [Athlon64/Opteron] Address Map
00:18.2 Host bridge: Advanced Micro Devices [AMD] K8 [Athlon64/Opteron] DRAM Controller
00:18.3 Host bridge: Advanced Micro Devices [AMD] K8 [Athlon64/Opteron] Miscellaneous Control
01:05.0 VGA compatible controller: ATI Technologies Inc Radeon XPRESS 200M 5955 (PCIE)
02:01.0 Ethernet controller: Broadcom Corporation NetXtreme BCM5788 Gigabit Ethernet (rev 03)
02:02.0 Network controller: Broadcom Corporation BCM4318 [AirForce One 54g] 802.11g Wireless LAN Controller (rev 02)
02:04.0 CardBus bridge: Texas Instruments PCIxx21/x515 Cardbus Controller
02:04.2 FireWire (IEEE 1394): Texas Instruments OHCI Compliant IEEE 1394 Host Controller
02:04.3 Mass storage controller: Texas Instruments PCIxx21 Integrated FlashMedia Controller
02:04.4 Generic system peripheral [0805]: Texas Instruments PCI6411/6421/6611/6621/7411/7421/7611/7621 Secure Digital Controller
olivier@kubuntu:~$ sudo lshw -C network
[sudo] password for olivier:
*-network:0
description: Ethernet interface
product: NetXtreme BCM5788 Gigabit Ethernet
vendor: Broadcom Corporation
physical id: 1
bus info: pci@0000:02:01.0
logical name: eth0
version: 03
serial: 00:0f:b0:b9:7c:f6
size: 100MB/s
capacity: 1GB/s
width: 32 bits
clock: 66MHz
capabilities: pm vpd msi bus_master cap_list ethernet physical mii 10bt 10bt-fd 100bt 100bt-fd 1000bt 1000bt-fd autonegotiation
configuration: autonegotiation=on broadcast=yes driver=tg3 driverversion=3.77 duplex=full firmware=5788-v3.26 ip=192.168.1.21 latency=64 link=yes mingnt=64 module=tg3 multicast=yes port=twisted pair speed=100MB/s
*-network:1 UNCLAIMED
description: Network controller
product: BCM4318 [AirForce One 54g] 802.11g Wireless LAN Controller
vendor: Broadcom Corporation
physical id: 2
bus info: pci@0000:02:02.0
version: 02
width: 32 bits
clock: 33MHz
capabilities: bus_master
configuration: latency=64
olivier@kubuntu:~$ lsmod
Module Size Used by
sg 41384 0
ipv6 317192 8
af_packet 28172 2
rfcomm 47656 2
l2cap 28672 11 rfcomm
bluetooth 63876 4 rfcomm,l2cap
radeon 129824 2
drm 106408 3 radeon
ppdev 11272 0
powernow_k8 16608 0
cpufreq_stats 8160 0
cpufreq_ondemand 10896 0
cpufreq_powersave 3072 0
cpufreq_userspace 6048 0
freq_table 6464 3 powernow_k8,cpufreq_stats,cpufreq_ondemand
cpufreq_conservative 9608 0
video 21140 0
battery 12424 0
sbs 21520 0
container 6400 0
button 10400 0
dock 12264 0
ac 7304 0
ndiswrapper 233632 0
sbp2 27144 0
lp 15048 0
joydev 13440 0
pcmcia 46232 0
snd_atiixp 24084 2
snd_seq_dummy 5380 0
tifm_7xx1 10112 0
tifm_core 13832 1 tifm_7xx1
sdhci 21004 0
mmc_core 33416 1 sdhci
pcspkr 4608 0
xpad 11400 0
parport_pc 41896 1
parport 44172 3 ppdev,lp,parport_pc
serio_raw 9092 0
psmouse 45596 0
k8temp 7680 0
snd_seq_oss 36864 0
yenta_socket 30220 1
rsrc_nonstatic 14208 1 yenta_socket
pcmcia_core 46628 3 pcmcia,yenta_socket,rsrc_nonstatic
snd_seq_midi 11008 0
snd_rawmidi 29824 1 snd_seq_midi
snd_atiixp_modem 19468 1
snd_ac97_codec 122200 2 snd_atiixp,snd_atiixp_modem
ac97_bus 4096 1 snd_ac97_codec
snd_seq_midi_event 9984 2 snd_seq_oss,snd_seq_midi
snd_pcm_oss 50048 0
snd_mixer_oss 20096 1 snd_pcm_oss
snd_seq 62496 6 snd_seq_dummy,snd_seq_oss,snd_seq_midi,snd_seq_midi_event
snd_seq_device 10260 5 snd_seq_dummy,snd_seq_oss,snd_seq_midi,snd_rawmidi,snd_seq
snd_pcm 94344 4 snd_atiixp,snd_atiixp_modem,snd_ac97_codec,snd_pcm_oss
snd_timer 27272 2 snd_seq,snd_pcm
snd 69288 17 snd_atiixp,snd_seq_oss,snd_rawmidi,snd_atiixp_modem,snd_ac97_codec,snd_pcm_oss,snd_mixer_oss,snd_seq,snd_seq_device,snd_pcm,snd_timer
soundcore 10272 1 snd
snd_page_alloc 12560 3 snd_atiixp,snd_atiixp_modem,snd_pcm
i2c_piix4 11020 0
i2c_core 30208 1 i2c_piix4
shpchp 38300 0
pci_hotplug 36612 1 shpchp
evdev 13056 7
ext3 146576 2
jbd 69360 1 ext3
mbcache 11272 1 ext3
ide_cd 35488 0
cdrom 41768 1 ide_cd
ide_disk 20352 6
ata_generic 9988 0
libata 138928 1 ata_generic
scsi_mod 172856 3 sg,sbp2,libata
usbhid 32576 0
hid 33408 1 usbhid
ohci1394 38984 0
ieee1394 109528 2 sbp2,ohci1394
tg3 118788 0
atiixp 7824 0 [permanent]
ide_core 141200 3 ide_cd,ide_disk,atiixp
ehci_hcd 40076 0
ohci_hcd 25092 0
usbcore 161584 6 ndiswrapper,xpad,usbhid,ehci_hcd,ohci_hcd
thermal 16528 0
processor 36232 2 powernow_k8,thermal
fan 6920 0
fuse 52528 5
apparmor 47008 0
commoncap 9472 1 apparmor
olivier@kubuntu:~$ iwconfig
lo no wireless extensions.
eth0 no wireless extensions.
olivier@kubuntu:~$ ifconfig
eth0 Lien encap:Ethernet HWaddr 00:0F:B0:B9:7C:F6
inet adr:192.168.1.21 Bcast:192.168.1.255 Masque:255.255.255.0
adr inet6: fe80::20f:b0ff:feb9:7cf6/64 Scope:Lien
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
Packets reçus:252387 erreurs:0 :0 overruns:0 frame:0
TX packets:177429 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 lg file transmission:1000
Octets reçus:275552682 (262.7 MB) Octets transmis:18439639 (17.5 MB)
Interruption:10
lo Lien encap:Boucle locale
inet adr:127.0.0.1 Masque:255.0.0.0
adr inet6: ::1/128 Scope:Hà´te
UP LOOPBACK RUNNING MTU:16436 Metric:1
Packets reçus:20 erreurs:0 :0 overruns:0 frame:0
TX packets:20 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 lg file transmission:0
Octets reçus:1620 (1.5 KB) Octets transmis:1620 (1.5 KB)
olivier@kubuntu:~$ iwlist scan
lo Interface doesn't support scanning.
eth0 Interface doesn't support scanning.
olivier@kubuntu:~$ uname -r -m
2.6.22-14-generic x86_64
olivier@kubuntu:~$ cat /etc/network/interfaces
auto lo
iface lo inet loopback
Donc apparemment, si j'ai bien compris, le driver est bien installé mais la carte pas reconnue?
Si quelqu'un pouvais me donner une piste??
Merci d'avance :)
Dans les bureaux: Ubuntu Serveur Edition 10.04
Mon laptop: Kubuntu 14.04 sur DELL Inspiron 14 (Ubuntu 12.04 à l'achat)
Autres machines dans les bureaux: Kubuntu 14.04 sur 2 Compaq CQ42, Kubuntu 14.04 sur HP 550, Kubuntu 14.04 sur DELL Inspiron 14, Lubuntu 12.04 sur Compaq Netbook CQ10-600la...
Sur très vielle tour: Lubuntu 12.04... ça tourne rond
Hors ligne
willy78
Re : problème wifi avec portable HP nx6125...
lspci:
00:0b.0 Network controller: Broadcom Corporation BCM4318 [AirForce One 54g] 802.11g Wireless LAN Controller (rev 02)
Tous ça avec une connection active
On télecharge le driver adequat (bcmwl5):
cd
wget http://dlsvr03.asus.com/pub/ASUS/wireless/WL-100g-03/Driverv3100640.zip
unzip Driverv3100640.zip
Ensuite on installe ndiswrapper:
sudo apt-get install ndiswrapper-utils-1.9
on charge le driver dans ndiswrapper
sudo ndiswrapper -i ~/Driver/WinXP/bcmwl5.inf
et on verifie s'il est bien chargé (avant de faire quoi que ce soi d'autres)
ndiswrapper -l #C'est un petit L
si il affiche un truc qui ressemble à ça:
bcmwl5 : driver installed
device (14E4:4318) present (alternate driver: bcm43xx)
Tu peux continuer!
pour décharger le module chargé automatiquement par Gutsy
sudo rmmod bcm43xx
pour charger ndiswrapper
sudo ndiswrapper -m
sudo modprobe ndiswrapper
Blacklister le module chargé automatiquement par gutsy
echo 'blacklist bcm43xx' | sudo tee -a /etc/modprobe.d/blacklist
Mettre ndiswrapper dans la liste des modules chargés au démarrage:
echo 'ndiswrapper' | sudo tee -a /etc/modules
modif du fichier interfaces
echo -e 'auto lo\niface lo inet loopback\n' | sudo tee /etc/network/interfaces
et connecte toi avec network-manager (2 tv en haut a droite à coté de l'heure)!
Hors ligne
oliver2004
Re : problème wifi avec portable HP nx6125...
Salut, merci pour la réponse.:)
Voici où j'en suis, ça bloque quelque part:
olivier@kubuntu:~$ wget http://dlsvr03.asus.com/pub/ASUS/wireless/WL-100g-03/Driverv3100640.zip
--10:49:00-- http://dlsvr03.asus.com/pub/ASUS/wireless/WL-100g-03/Driverv3100640.zip
=> `Driverv3100640.zip'
Résolution de dlsvr03.asus.com... 122.213.112.90
Connexion vers dlsvr03.asus.com|122.213.112.90|:80... connecté.
requête HTTP transmise, en attente de la réponse... 200 OK
Longueur: 926 968 (905K) [application/x-zip-compressed]
100%[====================================>] 926 968 141.47K/s ETA 00:00
10:49:07 (141.27 KB/s) - « Driverv3100640.zip » sauvegardé [926968/926968]
--> Téléchargement du fichier, ok
olivier@kubuntu:~$ unzip Driverv3100640.zip
Archive: Driverv3100640.zip
creating: Driver/
creating: Driver/WinXP/
inflating: Driver/WinXP/bcm43xx.cat
inflating: Driver/WinXP/bcmwl5.inf
inflating: Driver/WinXP/bcmwl5.sys
creating: Driver/WinME/
extracting: Driver/WinME/bcm43xxa.cat
inflating: Driver/WinME/bcmwl5.sys
inflating: Driver/WinME/bcmwl5a.inf
creating: Driver/Win98/
extracting: Driver/Win98/bcm43xxa.cat
inflating: Driver/Win98/bcmwl5.sys
inflating: Driver/Win98/bcmwl5a.inf
creating: Driver/Win2K/
inflating: Driver/Win2K/bcm43xx.cat
inflating: Driver/Win2K/bcmwl5.inf
inflating: Driver/Win2K/bcmwl5.sys
--> Dezipage du fichier ok.
olivier@kubuntu:~$ sudo apt-get install ndiswrapper-utils-1.9
[sudo] password for olivier:
Lecture des listes de paquets... Fait
Construction de l'arbre des dépendances
Lecture des informations d'état... Fait
ndiswrapper-utils-1.9 est déjà la plus récente version disponible.
Les paquets suivants ont été installés automatiquement et ne sont plus nécessaires :
python-cairo python-gtk2 python-numeric
Veuillez utiliser « apt-get autoremove » pour les supprimer.
0 mis à jour, 0 nouvellement installés, 0 à enlever et 0 non mis à jour.
--> Installation de ndiswrapper-utils-1.9 , ok.
olivier@kubuntu:~$ sudo ndiswrapper -i ~/Driver/WinXP/bcmwl5.inf
installing bcmwl5 ...
forcing parameter IBSSGMode from 0 to 2
forcing parameter IBSSGMode from 0 to 2
forcing parameter IBSSGMode from 0 to 2
forcing parameter IBSSGMode from 0 to 2
forcing parameter IBSSGMode from 0 to 2
forcing parameter IBSSGMode from 0 to 2
forcing parameter IBSSGMode from 0 to 2
forcing parameter IBSSGMode from 0 to 2
forcing parameter IBSSGMode from 0 to 2
forcing parameter IBSSGMode from 0 to 2
forcing parameter IBSSGMode from 0 to 2
olivier@kubuntu:~$ ndiswrapper -l
bcmwl5 : driver installed
device (14E4:4318) present (alternate driver: bcm43xx)
bcmwl5a : driver installed
device (14E4:4318) present (alternate driver: bcm43xx)
--> Chargement du driver et vérification ok.
olivier@kubuntu:~$ sudo rmmod bcm43xx
ERROR: Module bcm43xx does not exist in /proc/modules #### ERREUR
En fait j'ai éditer le fichier /proc/modules avec kate et il est vide, il n'y a rien dedans.
olivier@kubuntu:~$ sudo ndiswrapper -m
module configuration already contains alias directive ### Il y a déjà une directive de configuration
olivier@kubuntu:~$ sudo modprobe ndiswrapper
olivier@kubuntu:~$ echo 'blacklist bcm43xx' | sudo tee -a /etc/modprobe.d/blacklist
blacklist bcm43xx
--> Ok, le bcm43xx est bien blacklisté....
Le fichier /proc/modules reste vide, rien dessus. C'est normal?
J'ai donc essayé de me connecter à travers KNetworkManager mais l'onglet Network reste inactif.:/
Dernière modification par oliver2004 (Le 03/02/2008, à 13:02)
Dans les bureaux: Ubuntu Serveur Edition 10.04
Mon laptop: Kubuntu 14.04 sur DELL Inspiron 14 (Ubuntu 12.04 à l'achat)
Autres machines dans les bureaux: Kubuntu 14.04 sur 2 Compaq CQ42, Kubuntu 14.04 sur HP 550, Kubuntu 14.04 sur DELL Inspiron 14, Lubuntu 12.04 sur Compaq Netbook CQ10-600la...
Sur très vielle tour: Lubuntu 12.04... ça tourne rond
Hors ligne
willy78
Re : problème wifi avec portable HP nx6125...
il y a un driver de trop d'o๠problème!
sudo ndiswrapper -e bcmwl5a
reboot et donnes ces retour
sudo lshw -C network
iwlist scanning
Pour proc/module aucune importance! si bcm43xx est déjà blacklister suite a ton essaie avec le driver bcmwl5a normal qu'il ne soit pas charger et c'est tant mieux!
Dernière modification par willy78 (Le 03/02/2008, à 13:43)
Hors ligne
oliver2004
Re : problème wifi avec portable HP nx6125...
Voici les retours
[sudo] password for olivier:
*-network:0
description: Ethernet interface
product: NetXtreme BCM5788 Gigabit Ethernet
vendor: Broadcom Corporation
physical id: 1
bus info: pci@0000:02:01.0
logical name: eth0
version: 03
serial: 00:0f:b0:b9:7c:f6
size: 100MB/s
capacity: 1GB/s
width: 32 bits
clock: 66MHz
capabilities: pm vpd msi bus_master cap_list ethernet physical mii 10bt 10bt-fd 100bt 100bt-fd 1000bt 1000bt-fd autonegotiation
configuration: autonegotiation=on broadcast=yes driver=tg3 driverversion=3.77 duplex=full firmware=5788-v3.26 ip=192.168.1.21 latency=64 link=yes mingnt=64 module=tg3 multicast=yes port=twisted pair speed=100MB/s
*-network:1 UNCLAIMED
description: Network controller
product: BCM4318 [AirForce One 54g] 802.11g Wireless LAN Controller
vendor: Broadcom Corporation
physical id: 2
bus info: pci@0000:02:02.0
version: 02
width: 32 bits
clock: 33MHz
capabilities: bus_master
configuration: latency=64
olivier@kubuntu:~$ iwlist scanning
lo Interface doesn't support scanning.
eth0 Interface doesn't support scanning.
Apparemment ça ne va toujours pas
Uhm, je vois ceci: width: 32 bits, je suis en 64 bits, ne serait-ce pas ça l'erreur?
Dernière modification par oliver2004 (Le 03/02/2008, à 13:53)
Dans les bureaux: Ubuntu Serveur Edition 10.04
Mon laptop: Kubuntu 14.04 sur DELL Inspiron 14 (Ubuntu 12.04 à l'achat)
Autres machines dans les bureaux: Kubuntu 14.04 sur 2 Compaq CQ42, Kubuntu 14.04 sur HP 550, Kubuntu 14.04 sur DELL Inspiron 14, Lubuntu 12.04 sur Compaq Netbook CQ10-600la...
Sur très vielle tour: Lubuntu 12.04... ça tourne rond
Hors ligne
willy78
Re : problème wifi avec portable HP nx6125...
sudo modprobe -r ndiswrapper
sudo modprobe ndiswrapper
et retour de
sudo lshw -C network
iwlist scanning
Hors ligne
oliver2004
Re : problème wifi avec portable HP nx6125...
olivier@kubuntu:~$ sudo modprobe -r ndiswrapper
olivier@kubuntu:~$ sudo modprobe ndiswrapper
olivier@kubuntu:~$ sudo lshw -C network
*-network:0
description: Ethernet interface
product: NetXtreme BCM5788 Gigabit Ethernet
vendor: Broadcom Corporation
physical id: 1
bus info: pci@0000:02:01.0
logical name: eth0
version: 03
serial: 00:0f:b0:b9:7c:f6
size: 100MB/s
capacity: 1GB/s
width: 32 bits
clock: 66MHz
capabilities: pm vpd msi bus_master cap_list ethernet physical mii 10bt 10bt-fd 100bt 100bt-fd 1000bt 1000bt-fd autonegotiation
configuration: autonegotiation=on broadcast=yes driver=tg3 driverversion=3.77 duplex=full firmware=5788-v3.26 ip=192.168.1.21 latency=64 link=yes mingnt=64 module=tg3 multicast=yes port=twisted pair speed=100MB/s
*-network:1 UNCLAIMED
description: Network controller
product: BCM4318 [AirForce One 54g] 802.11g Wireless LAN Controller
vendor: Broadcom Corporation
physical id: 2
bus info: pci@0000:02:02.0
version: 02
width: 32 bits
clock: 33MHz
capabilities: bus_master
configuration: latency=64
olivier@kubuntu:~$ iwlist scanning
lo Interface doesn't support scanning.
eth0 Interface doesn't support scanning.
Au mème point je pense.
Dans les bureaux: Ubuntu Serveur Edition 10.04
Mon laptop: Kubuntu 14.04 sur DELL Inspiron 14 (Ubuntu 12.04 à l'achat)
Autres machines dans les bureaux: Kubuntu 14.04 sur 2 Compaq CQ42, Kubuntu 14.04 sur HP 550, Kubuntu 14.04 sur DELL Inspiron 14, Lubuntu 12.04 sur Compaq Netbook CQ10-600la...
Sur très vielle tour: Lubuntu 12.04... ça tourne rond
Hors ligne
willy78
Re : problème wifi avec portable HP nx6125...
§Mince j'avais pas vu tu es en 64 bits donc c'est mort pour ndiswrapper, dommage c'est la meilleur soluce!
il faut passer par les driver proprio et donc virer bcm43xx du fichier blacklist:
sudo gedit /etc/modprobe.d/blacklist
et vire toutes les lignes avec
blacklist bcm43xx
ensuite va dans le menu
Système > Administration > Gestionnaire de pilotes propriétaires
et tu coches le pilotes de ta carte (il faut quand même un connection ethernet!)
si ça marche pas passe en 32 bits (le 64 bits c'est pas du tout au point et pas que sous linux il faut attendre quelque années avant de prendre cette solution!)
Hors ligne
oliver2004
Re : problème wifi avec portable HP nx6125...
Ah zut... bon, donc il va sans doute que je refasse une install en 32 bits? bon, c'est con mais tant pis, moi qui avait réussi à configurer mon système... 32 bits est sans doute plus stable de toutes façons. En attendant, j'ai essayé d'activer le pilote du modem mais le message est le suivant: "les sources logicielles pour le paquet sl-modem-daemon ne sont pas activées"
O๠puis-je trouver ces sources pour les activer?
Dans les bureaux: Ubuntu Serveur Edition 10.04
Mon laptop: Kubuntu 14.04 sur DELL Inspiron 14 (Ubuntu 12.04 à l'achat)
Autres machines dans les bureaux: Kubuntu 14.04 sur 2 Compaq CQ42, Kubuntu 14.04 sur HP 550, Kubuntu 14.04 sur DELL Inspiron 14, Lubuntu 12.04 sur Compaq Netbook CQ10-600la...
Sur très vielle tour: Lubuntu 12.04... ça tourne rond
Hors ligne
willy78
Re : problème wifi avec portable HP nx6125...
je sais pas de quelle modem tu parles
mais fais ça pour voir on ne sais jamais
sudo apt-get install sl-modem-daemon
Hors ligne
oliver2004
Re : problème wifi avec portable HP nx6125...
Ben c'est le seul truc qui reste à installer dans les pilotes propriétaires. Donc j'ai supposé que c'était ça mais après quelques recherches, je vois que c'est le modem fax... donc rien à voir avec le wifi...
Je pense donc passer à 32 bits... le téléchargement est d'ailleurs déjà terminé, mais pas de cd vierge à portée de main...
Je pensais que c'était mieux de passer à 64 bits pour tirer parti de toutes les ressources du système, mais si c'est pas encore au point autant rester à 32 bits... :)
Je recommencerai l'install du wifi après, je tiens au courant merci en tout cas pour ton aide.
Dans les bureaux: Ubuntu Serveur Edition 10.04
Mon laptop: Kubuntu 14.04 sur DELL Inspiron 14 (Ubuntu 12.04 à l'achat)
Autres machines dans les bureaux: Kubuntu 14.04 sur 2 Compaq CQ42, Kubuntu 14.04 sur HP 550, Kubuntu 14.04 sur DELL Inspiron 14, Lubuntu 12.04 sur Compaq Netbook CQ10-600la...
Sur très vielle tour: Lubuntu 12.04... ça tourne rond
Hors ligne
willy78
Re : problème wifi avec portable HP nx6125...
ok salut et a plus sur ce topic au cas ou
Pour le 64 bits il faut avoir du bol avec le matériel sinon c'est la croix et la bannière.
En plus les logiciel ne sont pas encore vraiment porter en 64 bits juste du code 32 bits compiler en 64 bits donc coté optimisation ça sert a rien au mieux 4 a 10 % de mieux!
Hors ligne
oliver2004
Re : problème wifi avec portable HP nx6125...
Vu, oui, effectivement, ça ne sert pas encore à grand chose donc, en plus si ça bloque sur certains trucs... je passe donc à 32 bits, on attendra pour me 64 bits... Merci willy78
Dans les bureaux: Ubuntu Serveur Edition 10.04
Mon laptop: Kubuntu 14.04 sur DELL Inspiron 14 (Ubuntu 12.04 à l'achat)
Autres machines dans les bureaux: Kubuntu 14.04 sur 2 Compaq CQ42, Kubuntu 14.04 sur HP 550, Kubuntu 14.04 sur DELL Inspiron 14, Lubuntu 12.04 sur Compaq Netbook CQ10-600la...
Sur très vielle tour: Lubuntu 12.04... ça tourne rond
Hors ligne
oliver2004
Re : problème wifi avec portable HP nx6125...
Salut à nouveau,:)
Je suis donc passé à la distribution en 32bits et j'ai refait les manip pour le carte wifi. Aucune erreur n'apparait, je peux maintenant allumer et éteindre le bouton du wifi sur le portable... auparavant, celui-ci restait allumé ou éteint sans changement...
Par contre le wifi ne marche pas mieux... l'onglet Network dans KNetwork Manager n'est toujours pas activé.
Ai-je raté quelque chose?
olivier@kubuntu:~$ sudo lshw -C network
*-network:0
description: Ethernet interface
product: NetXtreme BCM5788 Gigabit Ethernet
vendor: Broadcom Corporation
physical id: 1
bus info: pci@0000:02:01.0
logical name: eth0
version: 03
serial: 00:0f:b0:b9:7c:f6
size: 100MB/s
capacity: 1GB/s
width: 32 bits
clock: 66MHz
capabilities: pm vpd msi bus_master cap_list ethernet physical mii 10bt 10bt-fd 100bt 100bt-fd 1000bt 1000bt-fd autonegotiation
configuration: autonegotiation=on broadcast=yes driver=tg3 driverversion=3.77 duplex=full firmware=5788-v3.26 ip=192.168.1.21 latency=64 link=yes mingnt=64 module=tg3 multicast=yes port=twisted pair speed=100MB/s
*-network:1
description: Wireless interface
product: BCM4318 [AirForce One 54g] 802.11g Wireless LAN Controller
vendor: Broadcom Corporation
physical id: 2
bus info: pci@0000:02:02.0
logical name: eth1
version: 02
serial: 00:14:a5:2a:02:4d
width: 32 bits
clock: 33MHz
capabilities: bus_master ethernet physical wireless
configuration: broadcast=yes driver=ndiswrapper+bcmwl5 driverversion=1.45+ASUS,02/11/2005, 3.100.64.0 latency=64 link=no module=ndiswrapper multicast=yes wireless=IEEE 802.11g
olivier@kubuntu:~$ iwlist scanning
lo Interface doesn't support scanning.
eth0 Interface doesn't support scanning.
eth1 Scan completed :
Cell 01 - Address: 00:1A:6B:C1:51:D1
ESSID:"Livebox-6547"
Protocol:IEEE 802.11g
Mode:Managed
Frequency:2.457 GHz (Channel 10)
Quality:78/100 Signal level:-46 dBm Noise level:-96 dBm
Encryption key:on
Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 6 Mb/s
9 Mb/s; 12 Mb/s; 18 Mb/s; 24 Mb/s; 36 Mb/s
48 Mb/s; 54 Mb/s
Extra:bcn_int=100
Extra:atim=0
Cell 02 - Address: 00:14:A4:6C:AD:EE
ESSID:"WANADOO-B330"
Protocol:IEEE 802.11g
Mode:Managed
Frequency:2.412 GHz (Channel 1)
Quality:40/100 Signal level:-70 dBm Noise level:-96 dBm
Encryption key:on
Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 18 Mb/s
24 Mb/s; 36 Mb/s; 54 Mb/s; 6 Mb/s; 9 Mb/s
12 Mb/s; 48 Mb/s
Extra:bcn_int=100
Extra:atim=0
Cell 03 - Address: 00:11:24:62:10:1D
ESSID:"Cabinet Bonnel"
Protocol:IEEE 802.11g
Mode:Managed
Frequency:2.437 GHz (Channel 6)
Quality:60/100 Signal level:-57 dBm Noise level:-96 dBm
Encryption key:on
Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 6 Mb/s
9 Mb/s; 12 Mb/s; 18 Mb/s; 24 Mb/s; 36 Mb/s
48 Mb/s; 54 Mb/s
Extra:bcn_int=100
Extra:atim=0
IE: WPA Version 1
Group Cipher : WEP-40
Pairwise Ciphers (1) : WEP-40
Authentication Suites (1) : PSK
Il y a donc du progrès mais ça manque encore... Auriez vous une piste?:P
Dernière modification par oliver2004 (Le 06/02/2008, à 13:56)
Dans les bureaux: Ubuntu Serveur Edition 10.04
Mon laptop: Kubuntu 14.04 sur DELL Inspiron 14 (Ubuntu 12.04 à l'achat)
Autres machines dans les bureaux: Kubuntu 14.04 sur 2 Compaq CQ42, Kubuntu 14.04 sur HP 550, Kubuntu 14.04 sur DELL Inspiron 14, Lubuntu 12.04 sur Compaq Netbook CQ10-600la...
Sur très vielle tour: Lubuntu 12.04... ça tourne rond
Hors ligne
willy78
Re : problème wifi avec portable HP nx6125...
Ah si là ça marche il scan les reseaux!
Cela a-t-il été fait?
Blacklister le module chargé automatiquement par gutsy
echo 'blacklist bcm43xx' | sudo tee -a /etc/modprobe.d/blacklist
Mettre ndiswrapper dans la liste des modules chargés au démarrage:
echo 'ndiswrapper' | sudo tee -a /etc/modules
modif du fichier interfaces
echo -e 'auto lo\niface lo inet loopback\n' | sudo tee /etc/network/interfaces
et connecte toi avec network-manager (2 tv en haut a droite à coté de l'heure)!
Dernière modification par willy78 (Le 06/02/2008, à 13:59)
Hors ligne
oliver2004
Re : problème wifi avec portable HP nx6125...
Salut, oui, tout a été fait.
En fait je crois avoir fait une bourde... j'ai installé bêtement wilan, ce qui apparemment a désinstallé knetwormanager... j'ai desintallé à nouveau wilan et réinstallé knetworkmanager... il est donc installé, j'ai activé eth1, qui correspond à la wifi... donc quand j'ouvre maintenant knetworkmanager ben plus aucun onglet est actif à par le premier... alors qu'avant tous étaient actifs sauf celui de la wifi... Dans Device il me met: No active device... uhmmm, pas facile.
Re testage:
*-network:0
description: Ethernet interface
product: NetXtreme BCM5788 Gigabit Ethernet
vendor: Broadcom Corporation
physical id: 1
bus info: pci@0000:02:01.0
logical name: eth0
version: 03
serial: 00:0f:b0:b9:7c:f6
size: 100MB/s
capacity: 1GB/s
width: 32 bits
clock: 66MHz
capabilities: pm vpd msi bus_master cap_list ethernet physical mii 10bt 10bt-fd 100bt 100bt-fd 1000bt 1000bt-fd autonegotiation
configuration: autonegotiation=on broadcast=yes driver=tg3 driverversion=3.77 duplex=full firmware=5788-v3.26 ip=192.168.1.21 latency=64 link=yes mingnt=64 module=tg3 multicast=yes port=twisted pair speed=100MB/s
*-network:1
description: Wireless interface
product: BCM4318 [AirForce One 54g] 802.11g Wireless LAN Controller
vendor: Broadcom Corporation
physical id: 2
bus info: pci@0000:02:02.0
logical name: eth1
version: 02
serial: 00:14:a5:2a:02:4d
width: 32 bits
clock: 33MHz
capabilities: bus_master ethernet physical wireless
configuration: broadcast=yes driver=ndiswrapper+bcmwl5 driverversion=1.45+ASUS,02/11/2005, 3.100.64.0 latency=64 link=no module=ndiswrapper multicast=yes wireless=IEEE 802.11g
olivier@kubuntu:~$ iwlist scanning
lo Interface doesn't support scanning.
eth0 Interface doesn't support scanning.
eth1 Scan completed :
Cell 01 - Address: 00:1A:6B:C1:51:D1
ESSID:"Livebox-6547"
Protocol:IEEE 802.11g
Mode:Managed
Frequency:2.457 GHz (Channel 10)
Quality:81/100 Signal level:-44 dBm Noise level:-96 dBm
Encryption key:on
Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 6 Mb/s
9 Mb/s; 12 Mb/s; 18 Mb/s; 24 Mb/s; 36 Mb/s
48 Mb/s; 54 Mb/s
Extra:bcn_int=100
Extra:atim=0
Cell 02 - Address: 00:14:A4:6C:AD:EE
ESSID:"WANADOO-B330"
Protocol:IEEE 802.11g
Mode:Managed
Frequency:2.412 GHz (Channel 1)
Quality:37/100 Signal level:-72 dBm Noise level:-96 dBm
Encryption key:on
Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 18 Mb/s
24 Mb/s; 36 Mb/s; 54 Mb/s; 6 Mb/s; 9 Mb/s
12 Mb/s; 48 Mb/s
Extra:bcn_int=100
Extra:atim=0
Cell 03 - Address: 00:11:24:62:10:1D
ESSID:"Cabinet Bonnel"
Protocol:IEEE 802.11g
Mode:Managed
Frequency:2.437 GHz (Channel 6)
Quality:64/100 Signal level:-55 dBm Noise level:-96 dBm
Encryption key:on
Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 6 Mb/s
9 Mb/s; 12 Mb/s; 18 Mb/s; 24 Mb/s; 36 Mb/s
48 Mb/s; 54 Mb/s
Extra:bcn_int=100
Extra:atim=0
IE: WPA Version 1
Group Cipher : WEP-40
Pairwise Ciphers (1) : WEP-40
Authentication Suites (1) : PSK
Cell 04 - Address: 00:13:46:6F:C7:84
ESSID:"FPH"
Protocol:IEEE 802.11g
Mode:Managed
Frequency:2.457 GHz (Channel 10)
Quality:6/100 Signal level:-92 dBm Noise level:-96 dBm
Encryption key:on
Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 6 Mb/s
12 Mb/s; 24 Mb/s; 36 Mb/s; 9 Mb/s; 18 Mb/s
48 Mb/s; 54 Mb/s
Extra:bcn_int=100
Extra:atim=0
En fait si je comprends bien, les différentes "Cell", c'est les différents réseaux wifi qu'il y a dans le coin?? ma live box en tout cas est bien détectée.
Ou bien alors il faut faire une manip avec la livebox?
Dernière modification par oliver2004 (Le 06/02/2008, à 15:09)
Dans les bureaux: Ubuntu Serveur Edition 10.04
Mon laptop: Kubuntu 14.04 sur DELL Inspiron 14 (Ubuntu 12.04 à l'achat)
Autres machines dans les bureaux: Kubuntu 14.04 sur 2 Compaq CQ42, Kubuntu 14.04 sur HP 550, Kubuntu 14.04 sur DELL Inspiron 14, Lubuntu 12.04 sur Compaq Netbook CQ10-600la...
Sur très vielle tour: Lubuntu 12.04... ça tourne rond
Hors ligne
oliver2004
Re : problème wifi avec portable HP nx6125...
Up?
Dans les bureaux: Ubuntu Serveur Edition 10.04
Mon laptop: Kubuntu 14.04 sur DELL Inspiron 14 (Ubuntu 12.04 à l'achat)
Autres machines dans les bureaux: Kubuntu 14.04 sur 2 Compaq CQ42, Kubuntu 14.04 sur HP 550, Kubuntu 14.04 sur DELL Inspiron 14, Lubuntu 12.04 sur Compaq Netbook CQ10-600la...
Sur très vielle tour: Lubuntu 12.04... ça tourne rond
Hors ligne
willy78
Re : problème wifi avec portable HP nx6125...
Tu dit j'ai activé eth1, c'est a dire?
bon sinon enligne de commande fais ça:
sudo iwconfig eth1 essid Livebox-6547
sudo iwconfig eth1 key Ta_clé_secrete
sudo dhclient eth1
donnes le retour de la dernière commande!
Hors ligne
oliver2004
Re : problème wifi avec portable HP nx6125...
Salut willy78
Par "activer eth1" c'est dans knetwork manager, configuration manuelle, interfaces réseaux. eth1 était desactivé, donc je me suis imaginé que ça pouvait pas marcher comme ça... j'ai donc activé l'interface mais sans plus de résultats.
Voila le retour de la dernière commande:
olivier@kubuntu:~$ sudo dhclient eth1
Internet Systems Consortium DHCP Client V3.0.5
Copyright 2004-2006 Internet Systems Consortium.
All rights reserved.
For info, please visit http://www.isc.org/sw/dhcp/
Listening on LPF/eth1/00:14:a5:2a:02:4d
Sending on LPF/eth1/00:14:a5:2a:02:4d
Sending on Socket/fallback
DHCPDISCOVER on eth1 to 255.255.255.255 port 67 interval 5
DHCPOFFER from 192.168.1.1
DHCPREQUEST on eth1 to 255.255.255.255 port 67
DHCPACK from 192.168.1.1
bound to 192.168.1.10 -- renewal in 249034 seconds.
Il a l'air d'y y avoir une réponse par contre... je n'ai toujours pas internet en wifi...
Dernière modification par oliver2004 (Le 07/02/2008, à 10:33)
Dans les bureaux: Ubuntu Serveur Edition 10.04
Mon laptop: Kubuntu 14.04 sur DELL Inspiron 14 (Ubuntu 12.04 à l'achat)
Autres machines dans les bureaux: Kubuntu 14.04 sur 2 Compaq CQ42, Kubuntu 14.04 sur HP 550, Kubuntu 14.04 sur DELL Inspiron 14, Lubuntu 12.04 sur Compaq Netbook CQ10-600la...
Sur très vielle tour: Lubuntu 12.04... ça tourne rond
Hors ligne
willy78
Re : problème wifi avec portable HP nx6125...
c'est exactement ce qu'il ne faut pas faire (ne pas utiliser configuration manuel)
C'est incompatible avec knetworkmanager le fichier /etc/network/interfaces ne doit comporter que ça:
auto lo
iface lo inet loopback
La configuration manuel écrit des données dans ce fichier et donc knetworkmanager ne peux plus gérer la connection!
bound to 192.168.1.10 -- renewal in 249034 seconds.
Ceci veut dire que tu es connecter! mais en manuel donc ça marche
cette commande:
echo -e 'auto lo\niface lo inet loopback\n' | sudo tee /etc/network/interfaces
rétabli ce qu'il faut dans le fichier interfaces
après cette commande, attends 1 mn, ensuite tu cliques gauche sur knetworkmanager (sous kde, je crois qu'il est en bas a droite a coté de l'heure) et tu cliques sur ton reseau qui devrais apparaitre!
Hors ligne
|
Extensions
firebird_fdw 0.2.3
A PostgreSQL foreign data wrapper (FDW) for Firebird
README
Contents
Firebird Foreign Data Wrapper for PostgreSQL
This is an experimental foreign data wrapper (FDW) to connect PostgreSQL to Firebird. It provides basic functionality, including both read (SELECT) and write (INSERT/UPDATE/DELETE) support. However it is still very much work-in-progress; USE AT YOUR OWN RISK.
firebird_fdw will work with PostgreSQL 9.2 or later (it was developed against the current development version). Write support is only available in PostgreSQL 9.3 and later.
It was written for Firebird 2.5 and will probably work with Firebird 2.0 or later. It should work with earlier versions if the 'disable_pushdowns' option is set (see below).
Supported platforms
firebird_fdw was developed on Linux and OS X, and should run on any reasonably POSIX-compliant system.
Installation
Prerequisites:
Firebird client library (libfbclient) and API header file (ibase.h)
libfq, a slightly saner API wrapper for the Firebird C API; see: https://github.com/ibarwick/libfq
The Firebird include/library files often end up in non-standard locations; PG_CPPFLAGS and SHLIB_LINK can be used to provide the appropriate flags. For OS X they would look something like this:
export PG_CPPFLAGS="-I /Library/Frameworks/Firebird.framework/Versions/A/Headers/"
export SHLIB_LINK="-L/Library/Frameworks/Firebird.framework/Versions/A/Libraries/"
firebird_fdw is installed as a PostgreSQL extension; it requires the pg_config binary for the target installation to be in the shell path.
The usual 'make && make install' should take care of the actual compilation.
Usage
NOTE: these options are provisional and may change
firebird_fdw accepts the following options:
'address':
The Firebird server's address (default: localhost)
'database':
The name of the database to connect to
'username':
The username to connect as (not case-sensitive)
'password':
The user's password (note that Firebird only recognizes the first 8
characters of a password)
'table_name':
The Firebird table name (not case-sensitive). Cannot be used together
with the 'query' option.
'query':
A Firebird SQL statement producing a result set which can be treated
like a table. Cannot be used together with the 'table_name' option.
'column_name':
The Firebird column name (not case-sensitive).
'updatable':
Boolean value indicating whether the foreign server as a whole,
or an individual table, is updatable. Default is true. Note that
table-level settings override server-level settings.
'disable_pushdowns':
Turns off pushdowns of WHERE clause elements to Firebird. Useful
mainly for debugging and benchmarking.
Note that while PostgreSQL allows a foreign table to be defined without any columns, firebird_fdw will raise an error as soon as any operations are carried out on it.
Example
Install the extension:
CREATE EXTENSION firebird_fdw;
CREATE FOREIGN DATA WRAPPER firebird
HANDLER firebird_fdw_handler
VALIDATOR firebird_fdw_validator;
Create a foreign server with appropriate configuration:
CREATE SERVER firebird_server
FOREIGN DATA WRAPPER firebird
OPTIONS (
address 'localhost',
database '/path/to/database'
);
Create an appropriate user mapping:
CREATE USER MAPPING FOR CURRENT_USER SERVER firebird_server
OPTIONS(username 'sysdba', password 'masterke');
Create a foreign table referencing the Firebird table_name 'fdw_test':
CREATE FOREIGN TABLE fb_test(
id SMALLINT,
val VARCHAR(2048)
)
SERVER firebird_server
OPTIONS(
table_name 'fdw_test'
);
As above, but with aliased column names:
CREATE FOREIGN TABLE fb_test_table(
id SMALLINT OPTIONS (column_name 'test_id'),
val VARCHAR(2048) OPTIONS (column_name 'test_val')
)
SERVER firebird_server
OPTIONS(
table_name 'fdw_test'
);
Create a foreign table as a Firebird query:
CREATE FOREIGN TABLE fb_test_query(
id SMALLINT,
val VARCHAR(2048)
)
SERVER firebird_server
OPTIONS(
query 'SELECT id, val FROM fdw_test'
);
Features
UPDATE and DELETE statements use Firebird's row identifier RDB$DB_KEY to operate on arbitrary rows
ANALYZE support
pushdown of some WHERE clause conditions to Firebird (including translation of built-in functions)
Connection caching
Limitations
Many; among the more egregious:
No explicit character set/encoding support
No support for some Firebird datatypes (BLOB, ARRAY)
See also file "BUGS" for known issues.
Useful links
Source
https://github.com/ibarwick/firebird_fdw (public mirror)
http://pgxn.org/dist/firebird_fdw/
Documentation
http://www.postgresql.org/docs/current/interactive/ddl-foreign-data.html
http://www.postgresql.org/docs/current/interactive/sql-createforeigndatawrapper.html
http://www.postgresql.org/docs/current/interactive/sql-createforeigntable.html
http://www.postgresql.org/docs/current/interactive/fdwhandler.html
http://www.postgresql.org/docs/current/interactive/postgres-fdw.html
Other FDWs
https://wiki.postgresql.org/wiki/Fdw
http://pgxn.org/tag/fdw/
If you appreciate PostgreSQL's psql client, why not try fbsql, a psql-style client for Firebird? See: https://github.com/ibarwick/fbsql for details.
|
I created a simple program using a glade .xml file and it, whenever I run the program, it crashes!
Here's the Python code:
#!/usr/bin/env python
import pygtk
pygtk.require("2.0")
import gtk
class TutorialApp(object):
def __init__(self):
builder = gtk.Builder()
builder.add_from_file("tutorial.xml")
builder.connect_signals({ "on_window_destroy" : gtk.main_quit })
self.window = builder.get_object("window")
self.window.show()
if __name__ == "__main__":
app = TutorialApp()
gtk.main()
The .xml file is rather extensive, so I can't post it in a readable form, but here it is.
<?xml version="1.0" encoding="UTF-8"?>
<interface>
<!-- interface-requires gtk+ 3.0 -->
<object class="GtkWindow" id="window1">
<property name="can_focus">False</property>
<child>
<object class="GtkBox" id="box1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="orientation">vertical</property>
<child>
<object class="GtkMenuBar" id="menubar1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<child>
<object class="GtkMenuItem" id="menuitem1">
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">_File</property>
<property name="use_underline">True</property>
<child type="submenu">
<object class="GtkMenu" id="menu1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<child>
<object class="GtkImageMenuItem" id="imagemenuitem1">
<property name="label">gtk-new</property>
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
</object>
</child>
<child>
<object class="GtkImageMenuItem" id="imagemenuitem2">
<property name="label">gtk-open</property>
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
</object>
</child>
<child>
<object class="GtkImageMenuItem" id="imagemenuitem3">
<property name="label">gtk-save</property>
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
</object>
</child>
<child>
<object class="GtkImageMenuItem" id="imagemenuitem4">
<property name="label">gtk-save-as</property>
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
</object>
</child>
<child>
<object class="GtkSeparatorMenuItem" id="separatormenuitem1">
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
</object>
</child>
<child>
<object class="GtkImageMenuItem" id="imagemenuitem5">
<property name="label">gtk-quit</property>
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
</object>
</child>
</object>
</child>
</object>
</child>
<child>
<object class="GtkMenuItem" id="menuitem2">
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">_Edit</property>
<property name="use_underline">True</property>
<child type="submenu">
<object class="GtkMenu" id="menu2">
<property name="visible">True</property>
<property name="can_focus">False</property>
<child>
<object class="GtkImageMenuItem" id="imagemenuitem6">
<property name="label">gtk-cut</property>
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
</object>
</child>
<child>
<object class="GtkImageMenuItem" id="imagemenuitem7">
<property name="label">gtk-copy</property>
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
</object>
</child>
<child>
<object class="GtkImageMenuItem" id="imagemenuitem8">
<property name="label">gtk-paste</property>
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
</object>
</child>
<child>
<object class="GtkImageMenuItem" id="imagemenuitem9">
<property name="label">gtk-delete</property>
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
</object>
</child>
</object>
</child>
</object>
</child>
<child>
<object class="GtkMenuItem" id="menuitem3">
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">_View</property>
<property name="use_underline">True</property>
</object>
</child>
<child>
<object class="GtkMenuItem" id="menuitem4">
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">_Help</property>
<property name="use_underline">True</property>
<child type="submenu">
<object class="GtkMenu" id="menu3">
<property name="visible">True</property>
<property name="can_focus">False</property>
<child>
<object class="GtkImageMenuItem" id="imagemenuitem10">
<property name="label">gtk-about</property>
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="use_underline">True</property>
<property name="use_stock">True</property>
</object>
</child>
</object>
</child>
</object>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">0</property>
</packing>
</child>
<child>
<object class="GtkScrolledWindow" id="scrolledwindow1">
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="shadow_type">in</property>
<child>
<object class="GtkTextView" id="textview1">
<property name="visible">True</property>
<property name="can_focus">True</property>
</object>
</child>
</object>
<packing>
<property name="expand">True</property>
<property name="fill">True</property>
<property name="position">1</property>
</packing>
</child>
<child>
<object class="GtkStatusbar" id="statusbar1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="orientation">vertical</property>
<property name="spacing">2</property>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">2</property>
</packing>
</child>
</object>
</child>
</object>
</interface>
Maybe I can get help, if not I'll continue trying to debug it on my own.
|
I have not been able to install Pymunk and Pygame for the same version of python. I have tried binaries, source installs, fink, and Macports, for system python, python 2.6, and python 2.7, with 32 and 64 bit versions.
In some cases the pymunk unit tests cause a segmentation fault, in some cases I get symptoms similar to Issue 42, and in some I cannot import pymunk because libchipmunk.dylib is an incompatible architecture.
When I can install pymunk, I cannot install or compile pygame with extended image (pygame.image.get_extended() == 0) or font support, which largely defeats the purpose of using pygame and pymunk together. On some versions of python, such as 2.7 64 bit, I get
building 'pygame.imageext' extension
gcc-4.0 -fno-strict-aliasing -fno-common -dynamic -arch i386 -arch ppc -arch x86_64 -g -O2 -DNDEBUG -g -O3 -Ddarwin -I/Library/Frameworks/SDL.framework/Versions/Current/Headers -I/Library/Frameworks/SDL_image.framework/Versions/Current/Headers -I/usr/local/include -I/usr/local/include -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c src/imageext.c -o build/temp.macosx-10.5-fat3-2.7/src/imageext.o
/usr/libexec/gcc/powerpc-apple-darwin10/4.0.1/as: assembler (/usr/bin/../libexec/gcc/darwin/ppc/as or /usr/bin/../local/libexec/gcc/darwin/ppc/as) for architecture ppc not installed
Installed assemblers are:
/usr/bin/../libexec/gcc/darwin/x86_64/as for architecture x86_64
/usr/bin/../libexec/gcc/darwin/i386/as for architecture i386
lipo: can't open input file: /var/tmp//ccuP0D3r.out (No such file or directory)
error: command 'gcc-4.0' failed with exit status 1
When importing pygame, I sometimes get:
from pygame.base import *
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so, 2): no suitable image found. Did find:
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so: no matching architecture in universal wrapper
I haven't had any issues on Ubuntu or Windows, so I think the problem is OS X-specific.
I am somewhat new to makefiles and compile flags, and I have been trying to set up these two modules for three days, so if someone could provide me with a detailed installation procedure that actually works for them, including the relevant .bash_profile and environment variables, I would be extremely grateful.
Edit: I reinstalled python, pygame, and chipmunk+pymunk, and this is the error I am getting with Python 2.7 (32 bit):
$ python2.7-32 flipper.py
Loading chipmunk for Darwin (32bit) [/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/libchipmunk.dylib]
2011-10-03 19:03:08.862 Python[3683:60f] Warning once: This application, or a library it uses, is using NSQuickDrawView, which has been deprecated. Apps should cease use of QuickDraw and move to Quartz.
Initializing cpSpace - Chipmunk v6.0.1 (Debug Enabled)
Compile with -DNDEBUG defined to disable debug mode and runtime assertion checks
Traceback (most recent call last):
File "flipper.py", line 35, in <module>
space.add_static(static_lines)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/__init__.py", line 288, in add_static
self.add_static(oo)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/__init__.py", line 285, in add_static
self._add_static_shape(o)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/__init__.py", line 327, in _add_static_shape
assert static_shape._hashid_private not in self._static_shapes, "shape already added to space"
AssertionError: shape already added to space
Edit 2: Despite changing the setup.py file to only link for 32-bit, I am getting some odd behavior:
$ sudo python setup.py build_chipmunk
running build_chipmunk
compiling chipmunk...
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/chipmunk.c -o chipmunk_src/chipmunk.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpArbiter.c -o chipmunk_src/cpArbiter.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpArray.c -o chipmunk_src/cpArray.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpBB.c -o chipmunk_src/cpBB.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpBBTree.c -o chipmunk_src/cpBBTree.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpBody.c -o chipmunk_src/cpBody.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpCollision.c -o chipmunk_src/cpCollision.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpHashSet.c -o chipmunk_src/cpHashSet.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpPolyShape.c -o chipmunk_src/cpPolyShape.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpShape.c -o chipmunk_src/cpShape.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpSpace.c -o chipmunk_src/cpSpace.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpSpaceComponent.c -o chipmunk_src/cpSpaceComponent.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpSpaceHash.c -o chipmunk_src/cpSpaceHash.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpSpaceQuery.c -o chipmunk_src/cpSpaceQuery.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpSpaceStep.c -o chipmunk_src/cpSpaceStep.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpSpatialIndex.c -o chipmunk_src/cpSpatialIndex.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpSweep1D.c -o chipmunk_src/cpSweep1D.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpVect.c -o chipmunk_src/cpVect.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpConstraint.c -o chipmunk_src/constraints/cpConstraint.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpDampedRotarySpring.c -o chipmunk_src/constraints/cpDampedRotarySpring.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpDampedSpring.c -o chipmunk_src/constraints/cpDampedSpring.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpGearJoint.c -o chipmunk_src/constraints/cpGearJoint.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpGrooveJoint.c -o chipmunk_src/constraints/cpGrooveJoint.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpPinJoint.c -o chipmunk_src/constraints/cpPinJoint.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpPivotJoint.c -o chipmunk_src/constraints/cpPivotJoint.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpRatchetJoint.c -o chipmunk_src/constraints/cpRatchetJoint.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpRotaryLimitJoint.c -o chipmunk_src/constraints/cpRotaryLimitJoint.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpSimpleMotor.c -o chipmunk_src/constraints/cpSimpleMotor.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -arch x86_64 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpSlideJoint.c -o chipmunk_src/constraints/cpSlideJoint.o
cc -dynamiclib -arch i386 chipmunk_src/chipmunk.o chipmunk_src/cpArbiter.o chipmunk_src/cpArray.o chipmunk_src/cpBB.o chipmunk_src/cpBBTree.o chipmunk_src/cpBody.o chipmunk_src/cpCollision.o chipmunk_src/cpHashSet.o chipmunk_src/cpPolyShape.o chipmunk_src/cpShape.o chipmunk_src/cpSpace.o chipmunk_src/cpSpaceComponent.o chipmunk_src/cpSpaceHash.o chipmunk_src/cpSpaceQuery.o chipmunk_src/cpSpaceStep.o chipmunk_src/cpSpatialIndex.o chipmunk_src/cpSweep1D.o chipmunk_src/cpVect.o chipmunk_src/constraints/cpConstraint.o chipmunk_src/constraints/cpDampedRotarySpring.o chipmunk_src/constraints/cpDampedSpring.o chipmunk_src/constraints/cpGearJoint.o chipmunk_src/constraints/cpGrooveJoint.o chipmunk_src/constraints/cpPinJoint.o chipmunk_src/constraints/cpPivotJoint.o chipmunk_src/constraints/cpRatchetJoint.o chipmunk_src/constraints/cpRotaryLimitJoint.o chipmunk_src/constraints/cpSimpleMotor.o chipmunk_src/constraints/cpSlideJoint.o -o pymunk/libchipmunk.dylib
$ python2.7-32
Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pymunk
Loading chipmunk for Darwin (32bit) [/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/libchipmunk.dylib]
>>> s = pymunk.Space()
Initializing cpSpace - Chipmunk v6.0.1 (Debug Enabled)
Compile with -DNDEBUG defined to disable debug mode and runtime assertion checks
>>> c1 = pymunk.Circle(s.static_body, 1)
>>> s.add(c1)
>>> c2 = pymunk.Circle(s.static_body, 2)
>>> s.add(c2) #No error!
$ sudo python setup.py install
$ python2.7-32 unittests.py
Loading chipmunk for Darwin (32bit) [/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/libchipmunk.dylib]
testing pymunk version 2.0.0
Initializing cpSpace - Chipmunk v6.0.1 (Debug Enabled)
Compile with -DNDEBUG defined to disable debug mode and runtime assertion checks
FFFFSegmentation fault
$ python2.7-32 flipper.py
Loading chipmunk for Darwin (32bit) [/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/libchipmunk.dylib]
2011-10-04 13:49:45.653 Python[6430:60f] Warning once: This application, or a library it uses, is using NSQuickDrawView, which has been deprecated. Apps should cease use of QuickDraw and move to Quartz.
Initializing cpSpace - Chipmunk v6.0.1 (Debug Enabled)
Compile with -DNDEBUG defined to disable debug mode and runtime assertion checks
Traceback (most recent call last):
File "flipper.py", line 35, in <module>
space.add_static(static_lines)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/__init__.py", line 288, in add_static
self.add_static(oo)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/__init__.py", line 285, in add_static
self._add_static_shape(o)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/__init__.py", line 327, in _add_static_shape
assert static_shape._hashid_private not in self._static_shapes, "shape already added to space"
AssertionError: shape already added to space
Edit 3: Chipmunk now built and linked for x86, but I am getting the same errors:
$sudo python2.7-32 setup.py build_chipmunk
running build_chipmunk
compiling chipmunk...
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/chipmunk.c -o chipmunk_src/chipmunk.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpArbiter.c -o chipmunk_src/cpArbiter.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpArray.c -o chipmunk_src/cpArray.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpBB.c -o chipmunk_src/cpBB.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpBBTree.c -o chipmunk_src/cpBBTree.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpBody.c -o chipmunk_src/cpBody.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpCollision.c -o chipmunk_src/cpCollision.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpHashSet.c -o chipmunk_src/cpHashSet.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpPolyShape.c -o chipmunk_src/cpPolyShape.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpShape.c -o chipmunk_src/cpShape.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpSpace.c -o chipmunk_src/cpSpace.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpSpaceComponent.c -o chipmunk_src/cpSpaceComponent.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpSpaceHash.c -o chipmunk_src/cpSpaceHash.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpSpaceQuery.c -o chipmunk_src/cpSpaceQuery.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpSpaceStep.c -o chipmunk_src/cpSpaceStep.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpSpatialIndex.c -o chipmunk_src/cpSpatialIndex.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpSweep1D.c -o chipmunk_src/cpSweep1D.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/cpVect.c -o chipmunk_src/cpVect.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpConstraint.c -o chipmunk_src/constraints/cpConstraint.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpDampedRotarySpring.c -o chipmunk_src/constraints/cpDampedRotarySpring.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpDampedSpring.c -o chipmunk_src/constraints/cpDampedSpring.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpGearJoint.c -o chipmunk_src/constraints/cpGearJoint.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpGrooveJoint.c -o chipmunk_src/constraints/cpGrooveJoint.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpPinJoint.c -o chipmunk_src/constraints/cpPinJoint.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpPivotJoint.c -o chipmunk_src/constraints/cpPivotJoint.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpRatchetJoint.c -o chipmunk_src/constraints/cpRatchetJoint.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpRotaryLimitJoint.c -o chipmunk_src/constraints/cpRotaryLimitJoint.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpSimpleMotor.c -o chipmunk_src/constraints/cpSimpleMotor.o
cc -O3 -std=gnu99 -ffast-math -fPIC -DCHIPMUNK_FFI -arch i386 -Ichipmunk_src/include/chipmunk -c chipmunk_src/constraints/cpSlideJoint.c -o chipmunk_src/constraints/cpSlideJoint.o
cc -dynamiclib -arch i386 chipmunk_src/chipmunk.o chipmunk_src/cpArbiter.o chipmunk_src/cpArray.o chipmunk_src/cpBB.o chipmunk_src/cpBBTree.o chipmunk_src/cpBody.o chipmunk_src/cpCollision.o chipmunk_src/cpHashSet.o chipmunk_src/cpPolyShape.o chipmunk_src/cpShape.o chipmunk_src/cpSpace.o chipmunk_src/cpSpaceComponent.o chipmunk_src/cpSpaceHash.o chipmunk_src/cpSpaceQuery.o chipmunk_src/cpSpaceStep.o chipmunk_src/cpSpatialIndex.o chipmunk_src/cpSweep1D.o chipmunk_src/cpVect.o chipmunk_src/constraints/cpConstraint.o chipmunk_src/constraints/cpDampedRotarySpring.o chipmunk_src/constraints/cpDampedSpring.o chipmunk_src/constraints/cpGearJoint.o chipmunk_src/constraints/cpGrooveJoint.o chipmunk_src/constraints/cpPinJoint.o chipmunk_src/constraints/cpPivotJoint.o chipmunk_src/constraints/cpRatchetJoint.o chipmunk_src/constraints/cpRotaryLimitJoint.o chipmunk_src/constraints/cpSimpleMotor.o chipmunk_src/constraints/cpSlideJoint.o -o pymunk/libchipmunk.dylib
$ sudo python2.7-32 setup.py install
running install
running build
running build_py
copying pymunk/libchipmunk.dylib -> build/lib/pymunk
running install_lib
copying build/lib/pymunk/libchipmunk.dylib -> /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk
running install_egg_info
Removing /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk-2.0.0-py2.7.egg-info
Writing /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk-2.0.0-py2.7.egg-info
$ python2.7-32 flipper.py
Loading chipmunk for Darwin (32bit) [/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/libchipmunk.dylib]
2011-10-05 01:15:15.972 Python[3183:60f] Warning once: This application, or a library it uses, is using NSQuickDrawView, which has been deprecated. Apps should cease use of QuickDraw and move to Quartz.
Initializing cpSpace - Chipmunk v6.0.1 (Debug Enabled)
Compile with -DNDEBUG defined to disable debug mode and runtime assertion checks
Traceback (most recent call last):
File "flipper.py", line 35, in <module>
space.add_static(static_lines)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/__init__.py", line 288, in add_static
self.add_static(oo)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/__init__.py", line 285, in add_static
self._add_static_shape(o)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/__init__.py", line 327, in _add_static_shape
assert static_shape._hashid_private not in self._static_shapes, "shape already added to space"
$ python2.7-32 unittests.py
Loading chipmunk for Darwin (32bit) [/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/libchipmunk.dylib]
testing pymunk version 2.0.0
Initializing cpSpace - Chipmunk v6.0.1 (Debug Enabled)
Compile with -DNDEBUG defined to disable debug mode and runtime assertion checks
FFFFSegmentation fault
Edit 4: Verification of versions and executable types:
$ file /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/libchipmunk.dylib
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymunk/libchipmunk.dylib: Mach-O dynamically linked shared library i386
$ file "$( "$(which python2.7-32)" -c "import sys;print(sys.executable)" )"
/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python: Mach-O universal binary with 2 architectures
/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python (for architecture i386): Mach-O executable i386
/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python (for architecture x86_64): Mach-O 64-bit executable x86_64
$ python2.7-32 -c "import sys;print('%x'%sys.maxint)"
7fffffff
Thanks in advance,
Julian Ceipek
|
Selected ramblings of a geospatial tech nerd
Best bang for your analytical buck
As (geo)data scientists, we spend much of our time working with data models that try (with varying degrees of success) to capture some essential truth about the world while still being as simple as possible to provide a useful abstraction. Inevitably, complexity starts to creep into every model and we don’t often stop to assess the value added by that complexity. When working with models that require a large number of parameters and a huge domain of potential inputs that are expensive to collect, it becomes difficult to answer the question:
What parameters of the model are the most sensitive?
In other words, if I am going to spend my resources obtaining/refining data for this model, where should I focus my efforts in order to get the best bang for the buck? If I spend weeks working on deriving a single parameter for the model, I want some assurance that the parameter is critically important to the model’s prediction. The flip-side, of course, is that if a parameter is not that important to the model’s predictive power, I could save some time by perhaps just using some quick-and-dirty approximation.
SALib: a python module for testing model sensitivity
I was thrilled to find SALib which implements a number of vetted methods for quantitatively assessing parameter sensitivity. There are three basic steps to running SALib:
Define the parameters to test, define their domain of possible values and generate nsets of randomized input parameters.
Run the model ntimes and capture the results.
Analyze the results to identify the most/least sensitive parameters.
I’ll leave the details of these steps to the SALib documentation. The beauty of the SALib approach is that you have the flexibility[1] to run any model in any way you want, so long as you can manipulate the inputs and outputs adequately.
Case Study: Climate effects on forestry
I wanted to compare a forest growth and yield model under different climate change scenarios in order to assess what the most sensitive climate-related variables were. I identified 4 variables:
Climate model (4 global circulation models)
Representative Concentration Pathways (RCPs; 3 different emission trajectories)
Mortality factor for species viability (0 to 1)
Mortality factor for equivalent elevation change (0 to 1)
In this case, I was using the Forest Vegetation Simulator(FVS) which requires a configuration file for every model iteration. So, for Step 2, I had to iterate through each set of input variables and use them to generate an appropriate configuration file. This involved translating the real numbers from the samples into categorical variables in some cases. Finally, in order to get the result of the model iteration, I had to parse the outputs of FVS and do some post-processing to obtain the variable of interest (the average volume of standing timber over 100 years). So the flexibility of SALib comes at a slight cost: unless your model works directly with the file formatted for SALib, the input and outputs may require some data manipulation.
After running the all required iterations of the model[2] I was able to analyze the results and assess the sensitivity of the four parameters.
Here’s the output of SALib’s analysis (formatted slightly for readability):
Parameter First_Order First_Order_Conf Total_Order Total_Order_Confcirculation 0.193685 0.041254 0.477032 0.034803rcp 0.517451 0.047054 0.783094 0.049091mortviab -0.007791 0.006993 0.013050 0.007081mortelev -0.005971 0.005510 0.007162 0.006693
The first order effects represent the effect of that parameter alone. The total order effects are arguably more relevant to understanding the overall interaction of that parameter with your model. The “Conf” columns represent confidence and can be interpreted as error bars.
In this case, we interpret the output as follows:
Parameter Total Order Effect
circulation 0.47 +- 0.03 (moderate influence)
rcp 0.78 +- 0.05 (dominant parameter)
mortviab 0.01 +- 0.007 (weak influence)
mortelev 0.007 +- 0.006 (weak influence)
We can graph each of the input parameters against the results to visualize this:
Note that the ‘mortelev’ component is basically flat (as the factor increases, the result stays the same) whereas the choice of ‘rcp’ has a heavy influence (as emissions increase to the highest level, the resulting prediction for timber volumes are noticeably decreased).
The conclusion is that the climate variables, particularly the RCPs related to human-caused emissions, were the strongest determinants[1] of tree growth for this particular forest stand. This ran counter to our initial intuition that the mortality factors would play a large role in the model. Based on this sensitivity analysis, we may be able to avoid wasting effort on refining parameters that are of minor consequence to the output.
Footnotes:
Compared to more tightly integrated, model-specific methods of sensitivity analysis
20 thousand iterations took approximately 8 hours; sensitivity analysis generally requires lots of processing
Note that the influence of a parameter says nothing about direct causality
Simple leaftlet-based template for mapping tabular point data on a slippy map
Anyone who’s worked with spatial data and the web has run across the need to take some simple tabular data and put points on an interactive map. It’s the fundamental ”Hello World” of web mapping. Yet I always find myself spending way too much time solving this seemingly simple problem. When you consider zoom levels, attributes, interactivity, clustering, querying, etc… it becomes apparent that interactive maps require a bit more legwork. But that functionality is fairly consistent case-to-case so I’ve developed a generalized solution that works for the majority of basic use cases out there:
The idea is pretty generic but useful for most point marker maps:
Data is in tabular delimited-text (csv, etc.) with two required columns: latandlng
Points are plotted on full-screen Leaflet map
Point markers are clustered dynamically based on zoom level.
Clicking on a point cluster will zoom into the extent of the underlying features.
Hovering on the point will display the name.
Clicking will display a popup with columns/properties displayed as an html table.
Full text filtering with typeahead
Completely client-side javascript with all dependencies included or linked via CDN
Usage
Grab the leaflet-simple-csv zip file and unzip it to a location accessible through a web server.
Copy the config.js.templatetoconfig.js
Visit the index.html page to confirm everything is working with the built-in example.
Customize your config.jsfor your dataset.
An example config:
var dataUrl = 'data/data.csv';
var maxZoom = 9;
var fieldSeparator = '|';
var baseUrl = 'http://otile{s}.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.jpg';
var baseAttribution = 'Data, imagery and map information provided by <a href="http://open.mapquest.co.uk" target="_blank">MapQuest</a>, <a href="http://www.openstreetmap.org/" target="_blank">OpenStreetMap</a> and contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/" target="_blank">CC-BY-SA</a>';
var subdomains = '1234';
var clusterOptions = {showCoverageOnHover: false, maxClusterRadius: 50};
var labelColumn = "Name";
var opacity = 1.0;
The example dataset:
Country|Name|lat|lng|AltitudeUnited States|New York City|40.7142691|-74.0059738|2.0United States|Los Angeles|34.0522342|-118.2436829|115.0United States|Chicago|41.8500330|-87.6500549|181.0United States|Houston|29.7632836|-95.3632736|15.0...
I make no claims that this is the “right” way to do it but leveraging 100% client-side javascript libraries and native delimited-text formats seems like the simplest approach. Many of the features included here (clustering, filtering) are useful enough to apply to most situations and hopefully you’ll find it useful.
A common task in many of my data workflows involves summarizing geospatial raster datasets based on vector geometries (i.e. zonal statistics). Despite many alternatives (starspan, the QGIS Zonal Statistics plugin, ArcPy and R) there were none that were
open source
fast enough
flexible enough
worked with python data structures
We’d written a wrapper around starspan for madrona (see madrona.raster_stats ) but relying on shell calls and an aging, unmaintained C++ code base was not cutting it.
So I set out to create a solution using numpy, GDAL and python. The rasterstats package was born.
Example
Let’s jump into an example. I’ve got a polygon shapefile of continental US state boundaries and a raster dataset of annual precipitation from the North American Environmental Atlas.
>>> states = "/data/workspace/rasterstats_blog/boundaries_contus.shp"
>>> precip = "/data/workspace/rasterstats_blog/NA_Annual_Precipitation_GRID/NA_Annual_Precipitation/data/na_anprecip/hdr.adf"
The raster_stats function is the main entry point. Provide a vector and a raster as input and expect a list of dicts, one for each input feature.
>>> from rasterstats import raster_stats
>>> rain_stats = raster_stats(states, precip, stats="*", copy_properties=True)
>>> len(rain_stats) # continental US; 48 states plus District of Columbia
49
Print out the stats for a given state:
>>> [x for x in rain_stats if x['NAME'] == "Oregon"][0]
{'COUNTRY': 'USA',
'EDIT': 'NEW',
'EDIT_DATE': '20060803',
'NAME': 'Oregon',
'STATEABB': 'US-OR',
'Shape_Area': 250563567264.0,
'Shape_Leng': 2366783.00361,
'UIDENT': 124704,
'__fid__': 35,
'count': 250510,
'majority': 263,
'max': 3193.0,
'mean': 779.2223903237395,
'median': 461.0,
'min': 205.0,
'minority': 3193,
'range': 2988.0,
'std': 631.539502512283,
'sum': 195203001.0,
'unique': 2865}
Find the three driest states:
>>> [(x['NAME'], x['mean']) for x in
sorted(rain_stats, key=lambda k: k['mean'])[:3]]
[('Nevada', 248.23814034118908),
('Utah', 317.668743027571),
('Arizona', 320.6157232064074)]
And write the data out to a csv.
from rasterstats import stats_to_csv
with open('out.csv', 'w') as fh:
fh.write(stats_to_csv(rain_stats))
Geo interface
The basic usage above shows the path of an entire OGR vector layer as the first argument. But raster-stats also supports other vector features/geometries.
Well-Known Text/Binary
GeoJSON string and mappings
Any python object that supports the geo_interface
Single objects or iterables
In this example, I use a geojson-like python mapping to specify a single geometry
>>> geom = {'coordinates': [[
[-594335.108537269, -570957.932799394],
[-422374.54395311, -593387.5716581973],
[-444804.1828119133, -765348.1362423564],
[-631717.839968608, -735441.9510972851],
[-594335.108537269, -570957.932799394]]],
'type': 'Polygon'}
>>> raster_stats(geom, precip, stats="min median max")
[{'__fid__': 0, 'max': 1011.0, 'median': 451.0, 'min': 229.0}]
Categorical
We’re not limited to descriptive statistics for continuous rasters either; we can get unique pixel counts for categorical rasters as well. In this example, we’ve got a raster of 2005 land cover (i.e. general vegetation type).
Note that we can specify only the stats that make sense and the categorical=True provides a count of each pixel value.
>>> landcover = "/data/workspace/rasterstats_blog/NA_LandCover_2005.img"
>>> veg_stats = raster_stats(states, landcover,
stats="count majority minority unique",
copy_properties=True,
nodata_value=0,
categorical=True)
>>> [x for x in veg_stats if x['NAME'] == "Oregon"][0]
{1: 999956,
3: 6,
5: 3005,
6: 198535,
8: 2270805,
10: 126199,
14: 20883,
15: 301884,
16: 17452,
17: 39246,
18: 28872,
19: 2174,
'COUNTRY': 'USA',
'EDIT': 'NEW',
'EDIT_DATE': '20060803',
'NAME': 'Oregon',
'STATEABB': 'US-OR',
'Shape_Area': 250563567264.0,
'Shape_Leng': 2366783.00361,
'UIDENT': 124704,
'__fid__': 35,
'count': 4009017,
'majority': 8,
'minority': 3,
'unique': 12}
Of course the pixel values alone don’t make much sense. We need to interpret the pixel values as land cover classes:
Value, Class_name
1 Temperate or sub-polar needleleaf forest
2 Sub-polar taiga needleleaf forest
3 Tropical or sub-tropical broadleaf evergreen
4 Tropical or sub-tropical broadleaf deciduous
5 Temperate or sub-polar broadleaf deciduous
6 Mixed Forest
7 Tropical or sub-tropical shrubland
8 Temperate or sub-polar shrubland
9 Tropical or sub-tropical grassland
10 Temperate or sub-polar grassland
11 Sub-polar or polar shrubland-lichen-moss
12 Sub-polar or polar grassland-lichen-moss
13 Sub-polar or polar barren-lichen-moss
14 Wetland
15 Cropland
16 Barren Lands
17 Urban and Built-up
18 Water
19 Snow and Ice
So, for our Oregon example above we can see that, despite Oregon’s reputation as a lush green landscape, the majority land cover class (#8) is “Temperate or sub- polar shrubland” at 2.27m pixels out of 4 millions total.
There’s a lot more functionality that isn’t covered in this post but you get the picture… please check it out and let me know what you think.
We’ve begun to rely on the interactivity provided by UTFGrids in many of our recent web maps. (Quick recap: UTFGrids are “invisible” map tiles that allow direct interactivity with feature attributes without querying the server.) Earlier this year, I created the initial OpenLayers UTFGrid support and was glad to see it accepted into OpenLayer 2.12 (with some enhancements).
With the client-side javascript support in place, the only missing piece in the workflow was to create the UTFGrid .json files. We had expirimented with several alternate UTFGrid renderers but Mapnik’s rendering was by far the fastest and produced the best results. Using Tilemill was a convenient way to leverage the Mapnik UTFGrid renderer but it came at the cost of a somewhat circuitious and manual workflow:
Load the data up into Tilemill,
Configure interactivity fields
Export to .mbtiles
Convert to .json files
What we really needed was a script to take a polygon shapefile and render the UTFGrids directly to files. Mapnik would provide the rendering while the Global Map Tiles python module would provide the logic for going back and forth between geographic coordinates and tile grid coordinates. From there it’s just a matter of determining the extent of the data set and, for a specified set of zoom levels, looping through and using Mapnik to render the UTFGrid to a .json file in Z/X/Y.json directory structure.
If we have a mercator polygon shapefile of ecoregions and want to render UTFGrids for zoom levels 3 through 5 using the dom_desc and div_desc attributes, we could use a command like
$ ./create_utfgrids.py test_data/bailey_merc.shp 3 5 ecoregions -f dom_desc,div_desc
WARNING:
This script assumes a polygon shapefile in spherical mercator projection.
If any of these assumptions are not true, don't count on the results!
* Processing Zoom Level 3
* Processing Zoom Level 4
* Processing Zoom Level 5
and inspect the output (e.g. zoom level 5, X=20, Y=18)
$ cat ecoregions/5/20/18.json | python -mjson.tool
{
"data": {
"192": {
"div_desc": "RAINFOREST REGIME MOUNTAINS",
"dom_desc": "HUMID TROPICAL DOMAIN"
},
...
"grid": [
" !!!!!!!!!#####$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%",
...
Some caveats:
This currently only works for polygon datasets in a Web Mercator projection.
It’s only tested with shapefiles as it assumes a single-layer datasource at the moment. Full OGR Datasource support would not be too difficult to add for PostGIS, etc.
It assumes a top-origin tile scheme (as do OSM and Google Maps). Supporting TMS bottom-origin schemes in the future should be straightforward.
Requires OGR and Mapnik >= 2.0 with python bindings. Finding windows binaries for the required version of Mapnik may be difficult so using OSX/Linux is recommended at this time.
Many thanks to Dane Springmeyer for his help on UTFGrid related matters and and to Klokan Petr Přidal for his MapTiler docs
Madrona: A software framework for effective place-based decision making
My work at Ecotrust mainly revolves around creating web-based spatial analysis tools - software to bring data-driven science to the place-based descision making process. This began several years ago when I joined the MarineMap team. Since working with Ecotrust, we’ve taken the MarineMap software far beyond it’s original niche. What was once a specific tool for marine protected area planning has now become a powerful framework for all sorts of web-based spatial tools in the realms of marine, forestry, conservation planning, aquatic habitat restoration, etc. So, in a sense, Madrona is a recognition of that evolution.
Over the last year we’ve distilled the best ideas from our most successful tools into a suite of software building blocks that can be mixed and matched to create cutting-edge software for decision support and spatial planning at any scale. These building blocks are already at the heart of our work and now we’re ready to share them with you.
So what is Madrona from a developer’s perspective?
A set of pythondjangoapps that provide models, views and templates for representing spatial features and solving problems specific to spatial decision tools.
A RESTful APIfor accessing spatial features
A collection of javascriptlibraries (based on JQuery) to provide a web-based interface to the API.
In short, we think its a great platform for spatial tools and we want to open it up to the wider developer audience. Ecotrust already has many madrona-based apps in the wild (with many more in development) but we’re hoping to get other folks using (and contributing to) the Madrona framework in the future.
|
JavaScript
juhusoldat — 2010-03-15T10:43:57-04:00 — #1
Hi!
Im making a little picture presentation and i have currently this working code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Pilt</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<style type="text/css">
#picdiv {
text-align: center;
}
</style>
<SCRIPT type="text/javascript">
var num=1
img1 = new Image ()
img1.src = "pic/pic1.jpg"
img2 = new Image ()
img2.src = "pic/pic2.jpg"
img3 = new Image ()
img3.src = "pic/pic3.jpg"
img4 = new Image ()
img4.src = "pic/pic4.jpg"
function slideshowForward()
{
num=num+1
if (num==5)
{num=1}
document.mypic.src=eval("img"+num+".src")
}
function slideshowBack()
{
num=num-1
if (num==0)
{num=4}
document.mypic.src=eval("img"+num+".src")
}
</SCRIPT>
</head>
<body>
<div id="picdiv">
<IMG SRC="pic/pic1.jpg" alt="" NAME="mypic" BORDER=0 align="middle" >
<br />
<A HREF="JavaScript:slideshowBack()">Last</a> | <A HREF="JavaScript:slideshowForward()">Next</a>
</div>
</body>
</html>
how do i alter my code to make "Last" link unclickable when im on pic1 and "Next" link unclickable when im on pic4?
Im probably just on the verge of getting it done but ive run to dead end in my mind apparently:)
With best wishes,
J.
siteguru — 2010-03-15T10:49:38-04:00 — #2
function slideshowForward()
{
if (num==4)
{ return }
num=num+1
document.mypic.src=eval("img"+num+".src")
}
function slideshowBack()
{
if (num==1)
{ return }
num=num-1
document.mypic.src=eval("img"+num+".src")
}
Doesn't make the link non-clickable, but stops any action happening.
juhusoldat — 2010-03-15T10:59:58-04:00 — #3
Thaks for the swift reply!
But im still wondering, if i want to make that link unclickable text instead of just "doing nothing", is it a much of a hassle?
J.
semantic7 — 2010-03-15T11:10:25-04:00 — #4
Yes it is possible and there are many ways to do it. Here is one way to do it. Following is the markup...
<p><a href="" title="Next">Next</a>Next</a>
Now you could style the p tag to appear as a disabled button and the a tag as the active button and use absolute position to place it on top of the text inside p tag. When the condition is met you can hide the a tag which would make the underlying disabled button visible showing its no longer active.
juhusoldat — 2010-03-15T12:03:41-04:00 — #5
Any chance you could find couple minutes to clarify how exactly to do that? Im quite new here to html sadly.
J.
johnny_dipin — 2010-03-15T17:36:51-04:00 — #6
Hi Here is small code to make a button disable button. I am not sure how to make it work for a link
<html>
<script>
function enableButton(){
var buttonId = document.getElementById("someId");
buttonId.disabled = false;
}
function disableButton(){
var buttonId = document.getElementById("someId");
buttonId.disabled = true;
}
</script>
<body>
<button id="someId" type="button">Click Me!</button>
<a href="#" onclick="enableButton()">Enable button</a>
<a href="#" onclick="disableButton()">Disable button</a>
</body>
</html>
paul_wilkins — 2010-03-15T18:50:29-04:00 — #7
You can make a link disabled by returning false from its onclick event.
With your code from the original post, the simple way to do that is to GET RID OF THE JAVASCRIPT PROTOCOL!!
Pardon that outburst. There is not nor ever has been a good reason to use it.
As I was saying, the simple way is to use the inline onclick event of the link.
<a href="#" onclick="return slideshowBack()">Last</a>
and then to update slideshowBack so that it only goes back when it's appropriate.
function slideshowBack() {
if (num > 0) {
num -= 1;
document.mypic.src=eval("img"+num+".src");
}
return false;
}
Returning false prevents the default action for the link from taking place. This allows the script to run, but prevents the link (to "#") from being followed.
A better way is then to remove the inline onclick event from the HTML code completely, and to attach it via scripting just before the </body> tag.
And finally the ultimate, is to ensure that the page works appropriately without scripting, and then to use scripting to update the page to add scripting links, and to achieve the better user experience.
bbyrdhouse — 2011-02-26T22:33:57-05:00 — #8
Hi,
Suppose you are pulling in content from a RSS feed and you want to deactivate all links from the content (including the Title).
You don't actually have access to the file to add the onclick command to each link and it would very time consuming if you did.
Surely there is a fool-proof way of de-linking links that get pulled in from parsing an xml page.
paul_wilkins — 2011-02-27T01:34:04-05:00 — #9
There is a pretty foolproof way. On the container where the content is written to the page, you place an event handler that disables all clicks.
<div id="rss-content">
RSS feed content displayed here
...
</div>
Now attach an onclick event, where anchor element clicks are cancelled.
document.getElementById('rss-content').onclick = function (evt) {
evt = evt || window.event;
targ = evt.target || evt.srcElement;
if (targ.nodeType === 3) { // handle Opera bug
targ = targ.parentNode;
}
if (targ.NodeType === 1 && targ.nodeName === 'A') {
return false;
}
}
Or, you could just cancel all clicks in the rss content area, regardless of what the target is:
document.getElementById('rss-content').onclick = function (evt) {
return false;
}
|
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, with the sample scripts listed.
Double click on a line in the Scripts window to run that script.
To edit the scripts, go to "\Program Files\Programmer's Notepad\Scripts" and look at text.py. There you'll see the source code for the sample scripts, and you can add your own. You may have to restart PN to show changes.
The PyPN extension makes it pretty easy to add your own features to Programmer's Notepad. PyPN exposes the underlying Scintilla interface to Python and this results in a very powerful scripting ability. The PyPN programmer has the PN objects, Scintilla editor, and the entire installed Python library ready for import.
To begin, start by creating a new document and selecting the "Python" scheme. Once the scheme is set to Python type pnscriptfile into the document, then press Ctrl+Alt+Space. This should auto-fill the document with this basic code template:
############################################################################### ## Script description ## By: your name here import pn import scintilla from pypn.decorators import script @script() def (): """ What this does """ pass
The top part of the file is a header area where you can fill in some information about your script, which may help should you decide to share your script or refer back to it at some point in the future.
The next few lines are the standard imports needed for most PyPN scripts. These will give you access to the pn library, the scintilla library, and will expose the @script() decorator that you can see on the next line down.
The script decorator allows PN to parse out some meta-data from the script file that lets your script appear in the list of scripts on the Scripts window (Alt+F10). Generally this would have the syntax: @script("Script Name", "Group")
However if this is left blank it will default to the name of the method for "Script Name" and will put the script in the "Python" group.
The next line is where you define you method. In this case lets create the method HelloPN.
############################################################################### ## Hello Programmer's Notepad ## By: PyPN Programmer import pn import scintilla from pypn.decorators import script @script() def HelloPN(): """ Say Hello To Programmer's Notepad """ newDoc = pn.NewDocument(None) editor = scintilla.Scintilla(newDoc) message = "Hello Programmer's Notepad!" editor.BeginUndoAction() editor.AppendText(len(message), message) editor.EndUndoAction() pass
Save this file as HelloPN.py inside of the <Programmers Notepad Home Dir>\scripts directory. Once saved, exit Programmer's Notepad and restart. When you bring up the scripts window you should see a new script under the Python group. Double clicking on this script will run it. If you do not see the script, then look in the output window for a Python error which may help you in determining what went wrong.
Taking a look at the method just defined:
python""" Say Hello To Programmer's Notepad """
The three quotes on an empty line begins a documentation comment. So this line aids in documenting what the script does.
pythonnewDoc = pn.NewDocument(None)
This line instructs PN to create a new document with no schema. Had we used pn.NewDocument("Python") we would have created a new Python document. Had we used pn.CurrentDoc() we not have created a new document but found a reference to the current document -- allowing us to append our message to the end of whatever document was currently selected.
pythoneditor = scintilla.Scintilla(newDoc)
To edit documents we need access to the Scintilla interface. This line creates a Scintilla editor object for the document we just created. We need an editor object to access the text of a document.
pythonmessage = "Hello Programmer's Notepad!"
This created a string with our message text in it. We will use this string to insert our message into the document.
pythoneditor.BeginUndoAction()
It is never any fun when an editor preforms an action that cannot be undone. This line will establish an "undo point" so that the user can undo the operation that our script did to the document. The user will be able to undo any operations preformed between this point and when the EndUndoAction() is called. In this case, pressing Ctrl-Z on the new document should remove our message.
pythoneditor.AppendText(len(message), message)
This line will append our message to the end of the document. The AppendText(len, text) function takes two arguments. The first parameter is the number of characters you would like it to take from the text string provided in the second parameter.
pythoneditor.EndUndoAction()
This line will mark and end of undo operations. It is advisable to ensure that you always make changes to documents inside of an undo block so that the user can revert any changes should they be disappointed in the results.
pass
This line has no effect. The pass statement in Python has no operation and is merely used as a place holder or marker. In this case it serves as a marker for the end of the current function. It can be removed with no effect upon the functionality or logic of the code.
For a list of user generated scripts please see the List of User-Submitted PyPN Scripts.
The PyPN API pages.
|
The only way I can find would require you to write a bit of Python code.
This is the site that provides a module for Pythonhttp://code.google.com/p/pygooglevoice/
This page gives you details on how to set a message to read. Look for the Mark function under the Message section.sphinxdoc. github.com/pygooglevoice/api.html#message
I would write the script for you but I do not know enough Python to make an attempt.
Hope that helps some.
EDIT: shouldn't belittle my abilities. Here is a script to set everything to read.
from googlevoice import Voice,util
voice = Voice()
voice.login('YOUR USERNAME', 'YOUR PASSWORD')
while True :
folder = voice.search('is:unread')
if folder.totalSize <= 0 :
break
util.print_(folder.totalSize)
for message in folder.messages:
util.print_(message)
message.mark(1)
UPDATE - gygooglevoice needs a change in its settings page to work properly, otherwise you will get a login error. Change needed is referenced here: http://code.google.com/p/pygooglevoice/issues/detail?id=64#c4 (just update the Login URL)
|
By default web2py stores tickets (errors) on the local file system. This is because most of the tickets are caused by database failures. Anyway You can move the tickets to a database by creating a script like:
import os, time, stat, datetime
from gluon.restricted import RestrictedErro()
db=SQLDB('postgres....')
db.define_table('ticket',
SQLField('name'),
SQLField('date_saved','datetime'),
SQLField('layer'),
SQLField('traceback','text'),
SQLField('code','text'))
path='applications/yourapp/errors/'
while 1:
for file in os.listdit(path):
e=RestrictedError()
e.load(path+file)
t=datetime.fromtimestamp(os.stat(path+file)[stat.ST_MTIME])
db.ticket.insert(date_saved=t,name=file,layer=e.layer,traceback=e.traceback,code=e.code)
os.unlink(path+file)
db.commit()
time.sleep(300)
and run it with
python web2py.py -S yourapp -M -R yourscript.py
This is just an example.
No concurrency problems because tickets would always be stored locally and in db moved every 5 minutes.
This solution decauples the problem of storing a ticket in case of database failure from your app that would create meta-tickets
|
I have the following code that fails to display object images. But displays normal images fine.
My Model
class News(models.Model):
title-----------
image = models.ImageField(upload_to='images')
body------------
Template tag coding
from django import template
register = template.Library()
from ----.models import ---
def funct(num):
myobjects = News.objects.all()[:num]
return {'objects': myobjects}
register.inclusion_tag('news/template.html')(funct)
template coding
{% for object in objects %}
<li>{{ object.title }}</li>
<li><img src="{{ MEDIA_URL }}images/{{ object.image }}" alt="image" /></li>
<li>{{ object.body }}</p></li>
{% endfor %}
This code outputs all the variable information such as title and body in a list however it does not display the associated image. I have tried numerous variations on this code with no success. This is strange because when an image is called from the image folder in the following manner
<img src="{{ MEDIA_URL }}images/star.jpg" />
Everything works fine. The problems occur when its a model image being called. Any help fixing this issue is much appreciated
|
I'm having a issue when using pydev for testing where my tests keep hanging. I've dug into the issue and know what the root cause is. I've provided samples of the code below that can be used to reproduce the issue.
I'm mainly testing on Centos 6.3, python 2.7, eclipse juno, pydev 2.7.1, however the issue also occours on windows 7 with similar setup.
I have a python script that operates as a process launcher for server different threads (all inside third party libraries, so I cant resign that side of the system).
To ensure that all the threads have finished at the end of my process.py i have a section of code that attempts to join all threads before exiting.
for t in threading.enumerate():
if t.getName() != 'MainThread':
t.join()
This works fine in normal production code.
The issue occours when running tests in PyUnit in eclipse with pydev. Extra threads are being added to python that result in my tests hanging.
If i launch my program using Run As -> Python Run , my code runs as expected and exits fine. If I launch my program using Run As -> Python unit-test, the test always hangs.
If i look at whats threads are available the issue becomes clear. Using the test code sample provided, I can see when just running the test as a python run, the following threads are shown (as expected)
Thread: <bound method _MainThread.getName of <_MainThread(MainThread, started 140268135126784)>>
Thread: <bound method ThreadClass.getName of <ThreadClass(Thread A, started 140268006471424)>>
Thread: <bound method ThreadClass.getName of <ThreadClass(Thread B, started 140267927631616)>>
When I run my tests as a unit-test
Thread: <bound method _MainThread.getName of <_MainThread(MainThread, started 139904571213568)>>
Thread: <bound method WriterThread.getName of <WriterThread(pydevd.Writer, started daemon 139904379361024)>>
Thread: <bound method ThreadClass.getName of <ThreadClass(Thread A, started 139904130479872)>>
Thread: <bound method ThreadClass.getName of <ThreadClass(Thread B, started 139904119990016)>>
Thread: <bound method PyDBCommandThread.getName of <PyDBCommandThread(pydevd.CommandThread, started daemon 139904358381312)>>
Thread: <bound method ReaderThread.getName of <ReaderThread(pydevd.Reader, started daemon 139904368871168)>>
Thread: <bound method ServerComm.getName of <ServerComm(Thread-4, started 139904345736960)>>
The extra threads added by python appear to break this code. When my code attempts to join the ServerComm or pydev.Writer it hangs.
I know I could attempt to not join these threads by name, however that way i'm changing production code to deal with this and I'm not too keen on that solution. Has anyone else come across this before and found a good workaround? Any help in this would be much appreciated. Below is sample code for the issue.
Sample test_process.py
import sys
import traceback
import unittest
class TestUBProcessManager(unittest.TestCase):
def setUp(self):
pass
def runTest(self):
globalsDict = {'sys':sys, '__name__':'__main__'}
haveException = False
try:
execfile('Process.py', globalsDict)
except Exception, detail:
haveException = True
traceback.print_exc()
self.assertFalse(haveException)
if __name__ == '__main__':
unittest.main()
Sample Process.py
import threading
import time
class ThreadClass(threading.Thread):
def __init__(self, threadName, threadRunCount,threadSleep):
threading.Thread.__init__(self)
self.name = threadName;
self.runCount = threadRunCount;
self.sleepTime = threadSleep;
def run(self):
for i in range (1,self.runCount):
print "\t",self.name, "Working";
time.sleep(self.sleepTime);
class Launcher(object):
def __init__(self):
print "Init Threads";
self.threadA = ThreadClass("Thread A",3,2)
self.threadB = ThreadClass("Thread B",7,2)
def launchProcess(self):
print "Starting Threads";
self.threadA.start();
self.threadB.start();
time.sleep(2);
if __name__ == '__main__':
launcher = Launcher()
try:
launcher.launchProcess()
finally:
print "Available Threads Needed To Finish"
for t in threading.enumerate():
print "Thread: ",t.getName
print "Attempt to join threads to ensure all threads are finished"
for t in threading.enumerate():
print "About To Join : ",t.getName
if t.getName() != 'MainThread':
t.join()
print "All Done"
|
This is only my second day of learning Python 3.3 so I admit I have a lot to learn.
In short, I have two lists: List1 is full of odd numbers, List2 is full of even numbers. They are the same length (each has five numbers).
I want to create List4 that contains [1,2,3,4,5,6,â¦] by combining each element of List1 with the same element from List2, and incrementing a counter. I guessed to use Append. My problem lies by the comment near the end.
I have many more functions to learn about, but I would be most grateful if someone could assist. My program can no doubt be made slicker, but that can come later.
Thank you!
# Fill list with odd numbers up to 10
a = -1
list1 = []
while a < 10:
a += 2
print (a)
list1.append(a)
print ("a = ", a, "\nList 1 = ", list1)
# Fill list with even numbers up to 10
a = 0
list2 = []
while a < 10:
a += 2
print (a)
list2.append(a)
print ("a = ", a, "\nList2 = ", list2)
#Combine the lists side by side
list3 = []
list3 = list1 + list2
print ('List 3 = ', list3)
#Now combine them in numerical order
list4 = []
for i in range (len(list1)):
list4.append(list1[i] + list2[i]) #Here is the problem
print (list4) #Here the List4 is gradually filled up
i += 1
print ("List4 = ", list4)
|
I'm having some difficulties with AjaxForm file upload and the app engine blobstore. I suspect the difficulty is because the blobstore upload handler (subclass of blobstore_handlers.BlobstoreUploadHandler) mandates a redirect response, rather than returning any content, but I'm not sure. I'm expecting to get an XML document to work with, and it appears to arrive as expected to the browser, but I just can't get hold of it - details below.
My app engine blobstore upload handler is as follows -
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload_files = self.get_uploads('file') # 'file' is file upload field in the form
blob_info = upload_files[0]
entity_key = self.request.get("entityKey")
// Update a datastore entity with the blobkey (not shown)
// redirect to the uri for the updated entity
self.redirect('%s.xml' % entity_key)
The final redirect is to a uri in my application that returns an xml document. Looking at the server output, there is no indication that anything is wrong - the redirect is serviced, and it returns the xml document as expected, with the correct mime type - so the form submission looks good, and the server response to that submission looks good.
My client side code using ajaxForm looks as follows (sorry its a little obtuse, I dont think the problem is here though)-
// Create the form
var dialogForm = $("<form method='POST' enctype='multipart/form-data'>")
.append("<span>Upload File: </span><input type='file' name='file'/><br>")
.append("<input type='hidden' name='entityKey' value='" + entityKey + "'/>")
.append("<input type='hidden' name='entityField' value='image'/>")
.append("<input type='button' value='Wait...' disabled='disabled'/>");;
dialogForm.ajaxForm();
// Turn the form button into a nice jQuery UI button and add a click handler
$("input[type=button]", dialogForm[0]).button()
.click(function() {
log.info("Posting to : " + dialogForm.attr('action'));
dialogForm.ajaxSubmit({
success: function(responseText, statusText, xhr, $form) {
log.info("Response: " + responseText + ", statusText: " + statusText + ", xhr: " + goog.debug.expose(xhr) + ", form:" + goog.debug.expose($form));
}
});
});
I set the 'action' on the form (and enable the button) afterwards -
$.get('/blob_upload_url', function(data) {
dialogForm.attr("action", data);
$("input[type=button]", dialogForm[0]).attr("value", "Upload").button("option", "disabled", false);
};
I'm using a little google closure in there as well for logging and exposing objects. Everything looks good - as expected it is posting correctly to the server, and the success function is called. If I watch the document structure in Chrome dev tools, I can see the iFrame being created briefly to handle the file upload and response.
The problem is that I never get the xml document in the response. The log output is as follows -
[ 18.642s] [Panel] Response: null, statusText: success, xhr: 0 = [object HTMLFormElement]
length = 1
selector =
jquery = 1.4.2, form:0 = [object HTMLFormElement]
length = 1
selector =
jquery = 1.4.2
Resource interpreted as document but transferred with MIME type application/xml [ABCdefGH]
The complaint by chrome about the mime type is probably super relevant, but I'm not making the connection :) - at least it means that it is getting the xml document at some point. In Chrome resources view, you can see the POST, and that the response is a 302 redirect, and then the subsequent GET request - the header of which looks fine -
Request URL:http://localhost:8081/_ah/upload/ABCdefGH
Request Method:GET
Status Code:200 OK
Request Headers
Referer:http://localhost:8081/
User-Agent:Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_4; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.70 Safari/533.4
Response Headers
Cache-Control:no-cache
Content-Length:2325
Content-Type:application/xml
Date:Sun, 20 Jun 2010 20:47:39 GMT
Expires:Fri, 01 Jan 1990 00:00:00 GMT
Server:Development/1.0
Chrome resources view won't show me the content of that document (just blank) but firefox does and the xml document looks fine. Firefox gives the same end result however - null for the ajaxSubmit() responseText.
I figure I'm just having a brain fade here somewhere, but it's really got me stumped. Any pointers for getting that xml document would be great - cheers,
Colin
|
pilepoil
Asus X59SL problème accès internet (seulement Google, BNP)
Salut,
J'ai depuis peu de temps le Asus X59SL.
J'ai mis un double boot Ubuntu et Vista.
Sous Vista, pas de soucis d'accès à internet.
Sous Ubuntu 8.10 64 bits, j'ai accès uniquement à Google et à BNP (et peut être d'autres, mais pas nombreux).
J'ai fait des recherches sur le forum, mais les différentes solutions ne m'ont pas permis de résoudre quoique ce soit.
J'ai également rebooté ma freebox qui est configurée en mode routeur.
Voilà, si quelqu'un a une grande idée.
Merci.
- Asus X59SL ; Pentium T3200 ; ATI Mobility Radeon HD3470 ; HD 160G & 3G RAM
. . . Ubuntu Intrepid Ibex 8.10 (Amd 64 bits) + Vista OS
- Acer 5612WLMi ; core duo T2300E ; GeForce Go 7300 TC ; HD 120G & 2G RAM
. . . Ubuntu Jaunty Jackalope 9.04 (32bits) + XP via VirtualBox
Hors ligne
Honni
Re : Asus X59SL problème accès internet (seulement Google, BNP)
J'ai le même problème j'ai essayer pas mal de chose mais rien a faire.
La carte de ce portable est une atheros.
Perso des fois (rarement) tout internet marche qd je suis branché en réseau mais je n'ai pas compris pk donc impossible de faire fonctionner non stop de plus ce qui m'intéresse est de pouvoir est de pouvoir me connecter en wifi (normal avec un portable). De même aucun pb sur vista pour ce connecter (le monde a l'envers). Et le problème est le mm pour Ubuntu 8.10 32bit.
J'ai donc testé avec Ubuntu 8.02 le résultat... bien pire pas du tout moyen de me connecter. Sur le port Ethernet principal de ma freebox le Ubuntu hésite entre me dire qu'il ni a pas de connexion et le fait de demander une adresse réseau (sachant que sa fonctionne tres bien sur mon fixe qui est lui sur Ubuntu 8.02). une fois connecter a l'un des 4 autre port Ethernet de la freebox => Connexion à un réseau câblé mais pas moyen d'accéder a internet et aucun moyen de rentrer ma clef wep...
A ce taper la tête contre les mures et j'ai vraiment besoin qu'Ubuntu marche bien et partout (chez moi, fac avec cette saleté de vpn...) donc... HELP pleaseeeeee, je suis sous vista je vais finir mal la sans votre aide
pilepoil
Re : Asus X59SL problème accès internet (seulement Google, BNP)
Salut,
Moi, j'ai remarqué un problème au niveau des TTL de ping, et ce aussi bien sur ubuntu que sous windows.
Il y a un TTL de 122 ce qui veut dire qu'il est passé par 133 routeurs différents. Bizarre non ?
Pour google, le TTL est de 242, ce qui parait plus normal.
Sur ubuntu :
nana@nana-pc:~$ ping free.fr
PING free.fr (212.27.48.10) 56(84) bytes of data.
64 bytes from www.free.fr (212.27.48.10): icmp_seq=1 ttl=122 time=63.2 ms
64 bytes from www.free.fr (212.27.48.10): icmp_seq=2 ttl=122 time=66.2 ms
64 bytes from www.free.fr (212.27.48.10): icmp_seq=3 ttl=122 time=70.2 ms
64 bytes from www.free.fr (212.27.48.10): icmp_seq=4 ttl=122 time=63.4 ms
64 bytes from www.free.fr (212.27.48.10): icmp_seq=5 ttl=122 time=65.2 ms
64 bytes from www.free.fr (212.27.48.10): icmp_seq=6 ttl=122 time=70.8 ms
64 bytes from www.free.fr (212.27.48.10): icmp_seq=7 ttl=122 time=64.1 ms
Sur un autre PC sous windows (XP) :
C:\Documents and Settings\doom>ping free.fr
Envoi d'une requête 'ping' sur free.fr [212.27.48.10] avec 32 octets de données
:
Réponse de 212.27.48.10 : octets=32 temps=62 ms TTL=122
Réponse de 212.27.48.10 : octets=32 temps=71 ms TTL=122
Réponse de 212.27.48.10 : octets=32 temps=71 ms TTL=122
Réponse de 212.27.48.10 : octets=32 temps=69 ms TTL=122
Statistiques Ping pour 212.27.48.10:
Paquets : envoyés = 4, reçus = 4, perdus = 0 (perte 0%),
Durée approximative des boucles en millisecondes :
Minimum = 62ms, Maximum = 71ms, Moyenne = 68ms
mais le traceroute donne moins de saut :
C:\Documents and Settings\doom>tracert free.fr
Détermination de l'itinéraire vers free.fr [212.27.48.10]
avec un maximum de 30 sauts :
1 2 ms 1 ms <1 ms 192.168.0.254
2 54 ms 51 ms 51 ms 88.xxx.xxx.254
3 * 52 ms 60 ms 213.228.9.254
4 59 ms 59 ms 60 ms bordeaux-6k-1-v804.intf.routers.proxad.net [212.
27.50.85]
5 66 ms 65 ms * bzn-crs16-1-be1100.intf.routers.proxad.net [212.
27.51.57]
6 63 ms 63 ms 73 ms bzn-6k-sys-po20.intf.routers.proxad.net [212.27.
51.70]
7 74 ms 64 ms 64 ms www.free.fr [212.27.48.10]
Itinéraire déterminé.
C:\Documents and Settings\doom>
Vraiment bizarre !!!
Dernière modification par pilepoil (Le 08/01/2009, à 17:51)
- Asus X59SL ; Pentium T3200 ; ATI Mobility Radeon HD3470 ; HD 160G & 3G RAM
. . . Ubuntu Intrepid Ibex 8.10 (Amd 64 bits) + Vista OS
- Acer 5612WLMi ; core duo T2300E ; GeForce Go 7300 TC ; HD 120G & 2G RAM
. . . Ubuntu Jaunty Jackalope 9.04 (32bits) + XP via VirtualBox
Hors ligne
pilepoil
Re : Asus X59SL problème accès internet (seulement Google, BNP)
En fait, je pense que free doit répondre au requete de ping avec un TTL forgé à 128.
Donc 128-7=121, à part le 1 qui traine quelque part, c'est bon.
- Asus X59SL ; Pentium T3200 ; ATI Mobility Radeon HD3470 ; HD 160G & 3G RAM
. . . Ubuntu Intrepid Ibex 8.10 (Amd 64 bits) + Vista OS
- Acer 5612WLMi ; core duo T2300E ; GeForce Go 7300 TC ; HD 120G & 2G RAM
. . . Ubuntu Jaunty Jackalope 9.04 (32bits) + XP via VirtualBox
Hors ligne
pilepoil
Re : Asus X59SL problème accès internet (seulement Google, BNP)
Le traceroute via ubuntu est bizarre car vers free, cela ne semble jamais aboutir (c'est reproductible).
(Notez que pour windows, cela abouti au 7ème saut).
Ci-dessous li'mage du traceroute (attention, longue à charger).
Dernière modification par pilepoil (Le 08/01/2009, à 18:19)
- Asus X59SL ; Pentium T3200 ; ATI Mobility Radeon HD3470 ; HD 160G & 3G RAM
. . . Ubuntu Intrepid Ibex 8.10 (Amd 64 bits) + Vista OS
- Acer 5612WLMi ; core duo T2300E ; GeForce Go 7300 TC ; HD 120G & 2G RAM
. . . Ubuntu Jaunty Jackalope 9.04 (32bits) + XP via VirtualBox
Hors ligne
pilepoil
Re : Asus X59SL problème accès internet (seulement Google, BNP)
En fait, le problème se produit lors d'un reboot sous Vista puis retour à Ubuntu, comme le montre la séquence de test ci-dessous (notez que j'ai rebooté au moins dix fois de Ubuntu->Ubuntu avant d'effectuer ce test et tout c'est toujours passé correctement).
asus allumé, branchement du port ethernet
connexion à ubuntu-fr.org (OK)
connexion à portail.free.fr (OK)
fermeture de firefox
reboot asus Ubuntu->Ubuntu
lancement firefox
connexion à ubuntu-fr.org (OK)
connexion à portail.free.fr (OK)
recherche ubuntu sur google (OK)
et accès à ubuntu-fr par lien google (OK)
fermeture de firefox
reboot asus Ubuntu->Vista
lancement firefox
connexion à ubuntu-fr.org (OK)
connexion à portail.free.fr (OK)
recherche ubuntu sur google (OK)
et accès à ubuntu-fr par lien google (OK)
fermeture de firefox
reboot asus Vista->Ubuntu (raté en fait, je l'ai mis en veille)
reboot asus Vista->Ubuntu
lancement firefox
connexion à ubuntu-fr.org (marche pas)
connexion à portail.free.fr (marche pas)
recherche ubuntu sur google (marche !!! (en fait c'était vraisemblablement en cache cf plus bas))
et accès à ubuntu-fr par lien google (marche !!!!!!)
accès à la page téléchargement ubuntu (=> marche pas.!!!)
accès à la page revendeur ubuntu (=> marche pas.!!!)
recherche ubuntu sur google (marche !!!)
et accès à ubuntu-fr par lien google (marche !!!!!!)
fermeture de firefox
reboot asus Ubuntu->Ubuntu
(la routine check of drives se lance. Pourquoi ???)
lancement firefox
connexion à ubuntu-fr.org
accès à la page téléchargement ubuntu (=> marche pas.!!!)
connexion à portail.free.fr (=> marche pas.!!!)
recherche ubuntu sur google (marche)
et accès à ubuntu-fr par lien google (marche)
effacement cache et session d'identification
accès à ubuntu-fr par lien google (marche plus !!!!)
fermeture de firefox
deconnexion du cable ethernet
reconnexion du cable ethernet
lancement firefox
connexion à ubuntu-fr.org
icone réseau avec une croix et plus rien n'est accessible (même pas google.fr).
fermeture de firefox
reboot asus Ubuntu->Ubuntu
toujours la croix sur l'icone réseau
lancement firefox
recherche ubuntu sur google (marche pas)
ifconfig (pas d'inet pour eth0)
sudo ifdown eth0 (refusé)
sudo ifup eth0 (refusé)
extinction du asus
reboot freebox (arret/marche)
attente fin reboot freebox
demarrage du Asus Ubuntu
Toujours la croix sur l'icone réseau.
lancement firefox
recherche ubuntu sur google (marche pas)
désactivation mode itinérant -> passage DHCP (=> pas mieux)
réactivation du mode itinérant (=>pas mieux)
clic droit sur l'icone réseau > décoche activer le réseau
clic droit sur l'icone réseau > recoche activer le réseau (=> pas mieux)
rebranche correctement le cable :D => icone reseau OK
recherche ubuntu sur google (marche)
et accès à ubuntu-fr par lien google (marche pas)
ifconfig
déconnection port éthernet du Asus
passage du port freebox 1 au port eth 3
reconnection port éthernet du Asus
Toujours pas mieux et là j'abandonne !
Quelqu'un a t'il une idée ????
Dernière modification par pilepoil (Le 08/01/2009, à 19:57)
- Asus X59SL ; Pentium T3200 ; ATI Mobility Radeon HD3470 ; HD 160G & 3G RAM
. . . Ubuntu Intrepid Ibex 8.10 (Amd 64 bits) + Vista OS
- Acer 5612WLMi ; core duo T2300E ; GeForce Go 7300 TC ; HD 120G & 2G RAM
. . . Ubuntu Jaunty Jackalope 9.04 (32bits) + XP via VirtualBox
Hors ligne
pilepoil
Re : Asus X59SL problème accès internet (seulement Google, BNP)
Pour ceux que ça intéresse, j'ai a dispo une capture wireshark : ici (le login et le mot de passe sont ubuntu)
Dernière modification par pilepoil (Le 09/01/2009, à 01:51)
- Asus X59SL ; Pentium T3200 ; ATI Mobility Radeon HD3470 ; HD 160G & 3G RAM
. . . Ubuntu Intrepid Ibex 8.10 (Amd 64 bits) + Vista OS
- Acer 5612WLMi ; core duo T2300E ; GeForce Go 7300 TC ; HD 120G & 2G RAM
. . . Ubuntu Jaunty Jackalope 9.04 (32bits) + XP via VirtualBox
Hors ligne
pilepoil
Re : Asus X59SL problème accès internet (seulement Google, BNP)
voici le résultat du ifconfig quand je n'ai accès qu'à google !
Notez les erreurs sur eth0
nana@nana-pc:~$ ifconfig
ath0 Link encap:Ethernet HWaddr 00:22:43:xx:xx:f0
adr inet6: fe80::222:43ff:xxxx:89f0/64 Scope:Lien
UP BROADCAST MULTICAST MTU:1500 Metric:1
Packets reçus:0 erreurs:0 :0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 lg file transmission:0
Octets reçus:0 (0.0 B) Octets transmis:0 (0.0 B)
eth0 Link encap:Ethernet HWaddr 00:23:54:xx:xx:2a
inet adr:192.168.0.11 Bcast:192.168.0.255 Masque:255.255.255.0
adr inet6: fe80::223:54ff:xxxx:b02a/64 Scope:Lien
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
Packets reçus:63 erreurs:22 :0 overruns:0 frame:22
TX packets:79 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 lg file transmission:1000
Octets reçus:23893 (23.8 KB) Octets transmis:12806 (12.8 KB)
Interruption:19 Adresse de base:0xdead
lo Link encap:Boucle locale
inet adr:127.0.0.1 Masque:255.0.0.0
adr inet6: ::1/128 Scope:Hôte
UP LOOPBACK RUNNING MTU:16436 Metric:1
Packets reçus:14 erreurs:0 :0 overruns:0 frame:0
TX packets:14 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 lg file transmission:0
Octets reçus:964 (964.0 B) Octets transmis:964 (964.0 B)
wifi0 Link encap:UNSPEC HWaddr 00-22-43-xx-xx-F0-00-00-00-00-00-00-00-00-00-00
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
Packets reçus:0 erreurs:0 :0 overruns:0 frame:0
TX packets:604 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 lg file transmission:280
Octets reçus:0 (0.0 B) Octets transmis:27784 (27.7 KB)
Interruption:16
nana@nana-pc:~$
Dernière modification par pilepoil (Le 09/01/2009, à 01:42)
- Asus X59SL ; Pentium T3200 ; ATI Mobility Radeon HD3470 ; HD 160G & 3G RAM
. . . Ubuntu Intrepid Ibex 8.10 (Amd 64 bits) + Vista OS
- Acer 5612WLMi ; core duo T2300E ; GeForce Go 7300 TC ; HD 120G & 2G RAM
. . . Ubuntu Jaunty Jackalope 9.04 (32bits) + XP via VirtualBox
Hors ligne
laurentb
Re : Asus X59SL problème accès internet (seulement Google, BNP)
Salut à tous,
j'ai acheté cet appareil, et j'ai compilé toutes les infos de mon install dans la doc ici, avec notament ce qu'il faut savoir pour avoir un wifi ok à 100%.
http://doc.ubuntu-fr.org/asus_x59sl
avec ma freebox HD wifi, j'utilise
sudo wifi-radar
et la connexion est nickelle.
Laurent
Laurent Bellegarde, professeur de SVT, 64 Bayonne, France
GNU/Linux a l'ecole : www.abuledu.org
lprod.org, Montage audio et vidéo libre
Lugs : www.euskalug.org, www.abul.org
Hors ligne
pilepoil
Re : Asus X59SL problème accès internet (seulement Google, BNP)
Salut Laurent,
On connaissait déjà ta documentation sur le wiki. C'est d'ailleurs grâce à cette page que notre choix s'est porté sur ce PC (on voulait être sûr d'acheter un portable "compatible" Ubuntu).
Nous, on souhaite le faire marcher en éthernet filaire (avec le câble) et pas en wifi.
Si je comprend bien, toi, tu n'as pas de double-boot. D'après ce que nous avons pu voir, le problème est dû au double-boot, donc normal que t'es pas vu le soucis.
Pour info, notre freebox est également une HD.
Merci.
- Asus X59SL ; Pentium T3200 ; ATI Mobility Radeon HD3470 ; HD 160G & 3G RAM
. . . Ubuntu Intrepid Ibex 8.10 (Amd 64 bits) + Vista OS
- Acer 5612WLMi ; core duo T2300E ; GeForce Go 7300 TC ; HD 120G & 2G RAM
. . . Ubuntu Jaunty Jackalope 9.04 (32bits) + XP via VirtualBox
Hors ligne
zebulon25
Re : Asus X59SL problème accès internet (seulement Google, BNP)
Bonjour,
Pour info :
j'ai exactement le même problème avec l'asus X71s en éthernet, je possède une freebox HD, je n'ai pas Vista, ubuntu 8.10(32bits) est en 'monoboot', mais je ne peux que surfer sur google et la BNP (??? en plus la page d'accueil).
J'ai redémarrer la freebox mais je n'ai pas fait de hardereboot.
Parfois la connexion ethernet(je n'ai même pas essayer le wifi) est reconnue, parfois non, j'essaierai le scénario proposé plus haut ce soir.
j'ai essayé Mandriva One (livecd) en pensant que le problème vienne de network-manager mais cela ne change rien.
Je ferai un test avec ubuntu 8.10 64 bits, 9.04 64bits alpha 3 et fedora 64bits (on ne sait jamais).
Est-ce que quelqu'un a réussi à trouver une parade?
Pb bios? Pb drivers?
merci pour les infos.
Dernière modification par zebulon25 (Le 20/01/2009, à 14:22)
Hors ligne
6nome
Re : Asus X59SL problème accès internet (seulement Google, BNP)
Bonjours,
Une amie à acheter cette asus aussi d'ailleur j'ai demandé le remboursement de vista pour n'utilisé que ubuntu mais le problème c'est que idem je peut pas allez plus loin, firefox ne peut pas affiché autre chose que google (même la page de mon routeur ne s'affiche pas) pire encore impossible de téléchargé la liste des dépot synaptic donc pas possible de le mettre en francais, pas possible de mettre à jours et pas possible d'installé le wifi je suis dans une impasse.
laurentb
Le 11/01/2009, à 17:49
Salut à tous,
j'ai acheté cet appareil, et j'ai compilé toutes les infos de mon install dans la doc ici, avec notament ce qu'il faut savoir pour avoir un wifi ok à 100%.
http://doc.ubuntu-fr.org/asus_x59sl wink
avec ma freebox HD wifi, j'utilise
Code:
sudo wifi-radar
et la connexion est nickelle.
Laurent
J'ai bien lu la doc mais bon comment faire sans synaptic. Impossible de mettre à jour la liste de mes dépots donc le sudo apt-get impossible.
J'espère qu'une solution va vite se débloqué (si je trouve quoique soit de mon coté je posterai au plus vite sur le forum) surtout que j'insite les gens à se tourné vers le libre et de demandé le remboursement de leur windows assez délicat comme situation
Hors ligne
6nome
Re : Asus X59SL problème accès internet (seulement Google, BNP)
Pour dépanné se que j'ai pu faire c'est de compilé le driver Atheros de la carte wifi (sur la doc Atheros AR5007EG n'ayant pas internet sur l'asus je me suis aidé d'une clé usb et d'un autre ordi) internet fonctionne normalement. La personne compte bien utilisé le wifi mais c'est toujours embettant de savoir que le RJ45 fonctionne pas sur son ordi. Je posterai si je trouve une solution sur le sujet.
Hors ligne
laurentb
Re : Asus X59SL problème accès internet (seulement Google, BNP)
Salut à tous,
je complète mes infos sur cet appareil.
hardy 64 bits, filaire 100% ok, wifi ok après compilation
intrepid 32 bits, filaire 100% ok, wifi ??? pas détecté semble-t-il, je cherche...
intrepid 64 bits, filaire semble-t-il reconnu, tout semble normal, mais rien ne sort sur le net... wifi pas reconnu aussi.
je poursuis mes tests.
Laurent
Laurent Bellegarde, professeur de SVT, 64 Bayonne, France
GNU/Linux a l'ecole : www.abuledu.org
lprod.org, Montage audio et vidéo libre
Lugs : www.euskalug.org, www.abul.org
Hors ligne
pilepoil
Re : Asus X59SL problème accès internet (seulement Google, BNP)
Laurentb,
On peut savoir pourquoi tu t'es permis de me supprimer des utilisateurs de ce PC dans cet article ???
Nous, on est en intrepid 64bits filaire et ça marche pas. Tu l'as d'ailleurs toi même écrit.
Dernière modification par pilepoil (Le 30/04/2009, à 22:54)
- Asus X59SL ; Pentium T3200 ; ATI Mobility Radeon HD3470 ; HD 160G & 3G RAM
. . . Ubuntu Intrepid Ibex 8.10 (Amd 64 bits) + Vista OS
- Acer 5612WLMi ; core duo T2300E ; GeForce Go 7300 TC ; HD 120G & 2G RAM
. . . Ubuntu Jaunty Jackalope 9.04 (32bits) + XP via VirtualBox
Hors ligne
|
I’ve shown how you can grab data from SPSS and use it in Python commands, and I figured a post about the opposite process (taking data in Python and turning it into an SPSS data file) would be useful. A few different motivating examples are:
Creating a set of permutations using the itertools Python library (see 1 and 2 for examples)
Identifying isolated neighborhoods in a set of network data and returning those to an SPSS data file
Grabbing items from the Google Places API
So first as a simple illustration, lets make a set of simple data in Python as a list of lists.
BEGIN PROGRAM Python. MyData = [(1,2,'A'),(4,5,'B'),(7,8,'C')] END PROGRAM.
Now to export this data into SPSS you can use spss.StartDataStep(), append variables using varlist.append and then add cases using cases.append (see the Python programming PDF that comes with SPSS in the help to peruse all of these functions plus the documentation). This particular codes adds in 3 variables (two numeric and one string) and then loops through the data python object and adds those cases to the define SPSS dataset.
BEGIN PROGRAM Python.
import spss
spss.StartDataStep() #start the data setp
MyDatasetObj = spss.Dataset(name=None) #define the data object
MyDatasetObj.varlist.append('X1',0) #add in 3 variables
MyDatasetObj.varlist.append('X2',0)
MyDatasetObj.varlist.append('X3',1)
for i in MyData: #add cases in a loop
MyDatasetObj.cases.append(i)
spss.EndDataStep()
END PROGRAM.
Here this will create a SPSS dataset and give it a generic name of the form xDataset? where ? will be an incrementing number based on the session history of naming datasets. To specify the name beforehand you need to use the SPSS command DATASET DECLARE X. and then place the dataset name as the option in the spss.Dataset(name='X') command.
As linked above I have had to do this a few times from Python objects, so I decided to make a bit of a simpler SPSS function to take care of this work for me.
BEGIN PROGRAM Python.
#Export to SPSS dataset function
import spss
def SPSSData(data,vars,types,name=None):
VarDict = zip(vars,types) #combining variables and
#formats into tuples
spss.StartDataStep()
datasetObj = spss.Dataset(name=name) #if you give a name,
#needs to be declared
#appending variables to dataset
for i in VarDict:
datasetObj.varlist.append(i[0],i[1])
#now the data
for j in data:
datasetObj.cases.append(list(j))
spss.EndDataStep()
END PROGRAM.
This code takes an arbitrary Python object (data), and two lists, one of the SPSS variable names and the other of the format for the SPSS variables (either 0 for numeric or an integer for the size of the strings). To transform the data to SPSS, it needs a list of the same dimension as the variables you have defined, so this works for any data object that can be iterated over and that can be coerced to returning a list. Or more simply, if list(data[0]) returns a list of the same dimensions for the variables you defined, you can pass the data object to this function. This won’t work for all situations, but will for quite a few.
So with the permutation examples I previously linked to, we can use the itertools library to create a set of all the different permutations of string ABC. Then I define a set of variables and formats as lists, and then we can use the SPSSData function I created to make a new dataset.
DATASET DECLARE Combo.
BEGIN PROGRAM Python.
import itertools
YourSet = 'ABC'
YourLen = 3
x = itertools.permutations(YourSet,YourLen)
v = ['X1','X2','X3']
t = [1,1,1]
SPSSData(data=x,vars=v,types=t,name='Combo')
END PROGRAM.
This work flow is not optimal if you are creating the data in a loop (such as in the Google Places API example I linked to earlier), but works well for static python objects, such as the object returned by itertools.
|
[SOLVED - Provided example contains the answer!] I am trying to implement a program which is started in fullscreen and does not allow any userinput (wether mouse nor keyboard) because it just reacts on UDEV-Signals, when a usb-stick or cd is inserted. I want to prevent, that a user puts in a keyboard / mouse and does somethin weird with the workstation. The only case, that a keyboard is needed, is when an administrator inserts a keyboard and presses CTRL-T, so my program opens a terminal-window.
I work with a Debian (Squeeze) + Gnome-Desktop-Environment.
I tried to use XLib, which works fine for grabbing all Keyboard-Events, but I cannot ungrab my keyboard, when my program opens my terminal (which works also perfectly), so the user cannot use the shell unless the keyboard-fetching is turned off.
here are some crucial code-fragments:
class ScanWSClient(gtk.Window):
def __init__(self, url):
# current display
disp = Display()
self.display = disp
gtk.Window.__init__(self)
self.terminal_window = None
self.kb_handler = KeyboardHandler(self).start()
#self.fullscreen()
self._browser= webkit.WebView()
self.add(self._browser)
self.connect('destroy', gtk.main_quit)
self._browser.open(url)
self.show_all()
class KeyboardHandler(threading.Thread):
def __init__(self, scanws_client):
super(KeyboardHandler,self).__init__()
self.running = True
self.daemon = True
self.terminal_window = None
self.scanws_client = scanws_client #
def run(self):
root = self.scanws_client.display.screen().root
while self.running:
event = root.display.next_event()
self.handle_event(event)
time.sleep(1)
def handle_event(self,aEvent):
keycode = aEvent.detail
state = aEvent.state
key_type = aEvent.type
if keycode == 28 and key_type == X.KeyPress:
if self.scanws_client.terminal_window == None:
self.scanws_client.terminal_window = TerminalWindow(self.scanws_client, "Administrative Shell started...Type *exit* to return to the locked workstation")
else:
self.scanws_client.terminal_window.present()
self.scanws_client.display.flush() #THIS FLUSH IS NECESSARY TO UNGRAB THE KEYBOARD LATER ON!!!
self.scanws_client.display.ungrab_keyboard(1, X.CurrentTime)
print "Key: %s / Mask: %s / Type: %s" % (keycode, state, key_type)
print self.scanws_client.terminal_window
In my threaded KeyboardHandler, I fetch all xlib-queued events and check with my function "handle_event", if there is CTRL-T pressed. If so, I open my terminal and ungrab my keyboard (doesnt work):
self.scanws_client.display.ungrab_keyboard(1, X.CurrentTime)
Who can tell me why I cannot ungrab my silly Keyboard? (this question is cookie provided ;) )
|
I've implemented full-text search using pg_search gem for my Rails application
My migration to create index looks like
execute(<<-'eosql'.strip)
CREATE index mytable_fts_idx
ON mytable
USING gin(
(setweight(to_tsvector('english', coalesce("mytable"."name", '')), 'A') ||
' ' ||
setweight(to_tsvector('english', coalesce("mytable"."description",'')), 'B')
)
)
eosql
And my controller code looks like
pg_search_scope :full_text_search,
:against => [
:name, :description],
:using => {
:tsearch => {
:prefix => true,
:dictionary => "english",
:any_word => true
}
}
which works totally fine locally on Postgres 9.0.4. However, when I deploy the same to heroku and search for a sample query 'test', it throws up an error
PGError: ERROR: syntax error in tsquery: "' test ':*"
SELECT COUNT(count_column) FROM (SELECT 1 AS count_column FROM "mytable" WHERE (((to_tsvector('english', coalesce("mytable"."name", '')) || to_tsvector('english', coalesce("mytable"."description", ''))) @@ (to_tsquery('english', ''' ' || 'test' || ' ''' || ':*')))) LIMIT 12 OFFSET 0) subquery_for_count ):
Any suggestions on where I'm wrong and what I should be looking at to fix this error? Thanks.
|
If you just want the strings:
print("\n".join(element for element, count in c.most_common(10)))
If you want the strings and the counts printed in the form ('foo', 11):
print ("\n".join(str(element_and_count)
for element_and_count in c.most_common(10)))
If you want the strings and counts in some other format of your choice:
print ("\n".join("{}: {}".format(element, count)
for element, count in c.most_common(10)))
Why? The most_common function returns (element, count) pairs. Those things are tuples, not strings. You can't just join tuples together. You can, of course, convert it to a string (option #2 above), but that only works if you actually want the format ('foo', 11) for each line. To get the other two options, you want to ignore half the tuple and use the other, or write your own format expression.
In any case, you want to do something to each member of the sequence returned by most_common. The Pythonic way to do that is with a list comprehension or generator expression.
Meanwhile, you should learn how to debug these kinds of cases. When join gives you a TypeError, break it up into pieces until you find the one that stores working (and try it with 2 instead of 10, just so there's less to read):
>>> print("\n".join(c.most_common(2)))
TypeError: sequence item 0: expected str instance, tuple found
>>> c.most_common(2)
[('I', 4), ('man', 1)]
Aha! Each thing in the list is a tuple of two things, not just a string. Why?
>>> help(c.most_common)
most_common(self, n=None) method of collections.Counter instance
List the n most common elements and their counts from the most
common to the least. If n is None, then list all element counts.
>>> Counter('abcdeabcdabcaba').most_common(3)
[('a', 5), ('b', 4), ('c', 3)]
OK, so it returns the most common elements and their counts. I just want the elements. So:
>>> [element for element, count in c.most_common(2)]
['I', 'man']
Now that's something I can join:
>>> '\n'.join([element for element, count in c.most_common(2)])
'I\nman'
And I don't need both brackets and parents (I can just use an expression instead of a list comprehension):
>>> '\n'.join(element for element, count in c.most_common(2))
'I\nman'
And now, I can print it:
>>> print('\n'.join(element for element, count in c.most_common(2)))
I
man
And now that it's working, print all 10:
>>> print('\n'.join(element for element, count in c.most_common(10)))
|
Ok here's the story. I save big float numbers in an xml file. for example 0.016780745002189634. Numbers are saved correctly in file but when i parse the xml and i read them , some of them , (i pressume the largest ones) sax breaks them into two different numbers. Like: 0.016780 and 745002189634 . I am using utf-8 encoding if it has something to do, tried also iso same problem with different results thought. Thanks in advance
import xml.sax
from xml.sax.saxutils import XMLGenerator
from xml.sax.xmlreader import AttributesNSImpl
floattosave = 0.016780745002189634
def xmlindex():
logger = XMLGenerator(open('.\\a.xml','w'), 'utf-8')
logger.startDocument()
attrs = AttributesNSImpl({}, {})
logger.startElementNS((None,'Articles'), 'Articles', attrs)
attr_vals = {
(None, 'id'): str(1)
}
attr_qnames = {
(None, 'id'): 'id'
}
attrs = AttributesNSImpl(attr_vals, attr_qnames)
logger.startElementNS((None, 'Article'), u'Article', attrs)
attr_vals1 = {
(None, 'word'): 'lalala'
}
attr_qnames1 = {
(None, 'word'): 'word'}
attrs1 = AttributesNSImpl(attr_vals1, attr_qnames1)
logger.startElementNS((None, 'Lemma'), 'Lemma', attrs1)
logger.characters(repr(floattosave))
logger.endElementNS((None, 'Lemma'), 'Lemma')
logger.endElementNS((None, 'Article'), 'Article')
logger.endElementNS((None, 'Articles'), 'Articles')
logger.endDocument()
class myhandler(xml.sax.ContentHandler):
def __init__(self):
xml.sax.ContentHandler.__init__(self)
self.w = 0
self.child = 0
def startElement(self,name,attrs):
if name == 'Article':
self.child = 1
if name == 'Lemma':
self.child = 2
def characters(self, content):
if self.child == 2:
print content
a = float(content)
print a
xmlindex()
xml.sax.parse(open('.\\a.xml'),myhandler())
Hmm i doing something like that but for many more elements . This is one is working good , i guess somewhere else is the problem . I ll look into it. You helped a lot tkx
|
In Python 2, a common (old, legacy) idiom is to use map to join iterators of uneven length using the form map(None,iter,iter,...) like so:
>>> map(None,xrange(5),xrange(10,12))
[(0, 10), (1, 11), (2, None), (3, None), (4, None)]
In Python 2, it is extended so that the longest iterator is the length of the returned list and if one is shorter than the other it is padded with None.
In Python 3, this is different. First, you cannot use None as an argument for the callable in position 1:
>>> list(map(None, range(5),range(10,12)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
OK -- I can fix that like so:
>>> def f(*x): return x
...
>>> list(map(f, *(range(5),range(10,12))))
[(0, 10), (1, 11)]
But now, I have a different problem: map returns the shortest iterator's length -- no longer padded with None.
As I port Python 2 code to Python 3, this is not a terrible rare idiom and I have not figured out an easy in place solution.
Unfortunately, the 2to3 tools does not pick this up -- unhelpfully suggesting:
-map(None,xrange(5),xrange(10,18))
+list(map(None,list(range(5)),list(range(10,18))))
Suggestions?
Edit
There is some discussion of how common this idiom is. See this SO post.
I am updating legacy code written when I was still in high school. Look at the 2003 Python tutorials being written and discussed by Raymond Hettinger with this specific behavior of map being pointed out...
|
This is a simple python wsgi server that prints out Hello guys!!! on 0.0.0.0:8080.
from wsgiref.simple_server import make_server
content = 'Hello guys!!!'
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/plain')])
return [content]
server = make_server('0.0.0.0', 8080, application)
server.serve_forever()
Several questions arise when looking at this code:
How can the
make_serverfunction work with just the function nameapplication? I don't see how this does anything else then return the"<function application at 0x7f71686286e0>"string (application.__repr__() methodof function object).
Why does the application function definition define
environas an argument when it isn't used inside this function and isn't even set in anapplicationfunction call later on?
From what I understand the
start_responseargument in the function definition is used here as a sort of identifier that this will be the name of the function that sets other properties later needed in themake_serverfunction call. Where is that functionality defined in the standard library? (I have checked the source of the relevant modules but I don't understand where this it is done exactly)
Observations: Changing the argument environ in the function definition does not change anything in the behaviour of the code, the start_response argument however has to have the same name as start_response in the body of the application function.
I know os.environ is a dictionary but I can't find where it is called in the python standard library. If the environ argument is necessary and the only viable first argument, I don't understand why they would require you to explicitly name a first argument(environ) every time, it gives you the illusion that using a different argument affects its behaviour. I am aware of the "better explicit then implicit"-python policy but here I think it is useless and confusing.
Edit
Because of Ned's answer I now understand by looking at the source that make_server('0.0.0.0', 8080, application) creates an instance of WSGIServer such as wsgiref.simple_server.WSGIServer((host, port), handler_class)). Looking deeper I found that the initialisation method is inherited from BaseServer . BaseServer instances have server_address and RequestHandlerClass as instance variables among others.The function object application is stored in the application class variable of WSGIServer.
But I still can't find where else this application class variable is used somewhere in the python source. (I 've searched through all modules that contain class definitions of parent classes of WSGIServer) Does anybody know where it is used? Finding that could potentially answer all my questions.
|
I am using urllib2 to post data to a form. The problem is that the form replies with a 302 redirect. According to Python HTTPRedirectHandler the redirect handler will take the request and convert it from POST to GET and follow the 301 or 302. I would like to preserve the POST method and the data passed to the opener. I made an unsuccessful attempt at a custom HTTPRedirectHandler by simply adding data=req.get_data() to the new Request.
I am sure this has been done before so I thought I would make a post.
Here is my HTTPRedirectHandler that does not work
class MyHTTPRedirectHandler(urllib2.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
"""Return a Request or None in response to a redirect.
This is called by the http_error_30x methods when a
redirection response is received. If a redirection should
take place, return a new Request to allow http_error_30x to
perform the redirect. Otherwise, raise HTTPError if no-one
else should try to handle this url. Return None if you can't
but another Handler might.
"""
m = req.get_method()
if (code in (301, 302, 303, 307) and m in ("GET", "HEAD")
or code in (301, 302, 303) and m == "POST"):
# Strictly (according to RFC 2616), 301 or 302 in response
# to a POST MUST NOT cause a redirection without confirmation
# from the user (of urllib2, in this case). In practice,
# essentially all clients do redirect in this case, so we
# do the same.
# be conciliant with URIs containing a space
newurl = newurl.replace(' ', '%20')
return Request(newurl,
headers=req.headers,
data=req.get_data(),
origin_req_host=req.get_origin_req_host(),
unverifiable=True)
else:
raise HTTPError(req.get_full_url(), code, msg, headers, fp)
|
I installed Python 2.6.2 earlier on a Windows XP machine and run the following code:
import urllib2
import urllib
page = urllib2.Request('http://www.python.org/fish.html')
urllib2.urlopen( page )
I get the following error.
Traceback (most recent call last):<br>
File "C:\Python26\test3.py", line 6, in <module><br>
urllib2.urlopen( page )<br>
File "C:\Python26\lib\urllib2.py", line 124, in urlopen<br>
return _opener.open(url, data, timeout)<br>
File "C:\Python26\lib\urllib2.py", line 383, in open<br>
response = self._open(req, data)<br>
File "C:\Python26\lib\urllib2.py", line 401, in _open<br>
'_open', req)<br>
File "C:\Python26\lib\urllib2.py", line 361, in _call_chain<br>
result = func(*args)<br>
File "C:\Python26\lib\urllib2.py", line 1130, in http_open<br>
return self.do_open(httplib.HTTPConnection, req)<br>
File "C:\Python26\lib\urllib2.py", line 1105, in do_open<br>
raise URLError(err)<br>
URLError: <urlopen error [Errno 11001] getaddrinfo failed><br><br><br>
|
I m trying to generate heatmaps for the some data. I need the positive to have a gradient of blue and negative a gradient of red.
import matplotlib.pyplot as plt
import numpy as np
arr = array([[ 2.155, 3.093, -5.377, 7.973, 6.564, 6.348, 10.279,
1.536],
[ 0.355, -2.848, 0.65 , 6.877, 1.08 , 4.001, 11.427, 0. ],
[ -4.23 , -2.855, -2.507, 2.44 , 2.78 , 1.163, 27.868, 0. ],
[ -5.373, 1.429, -4.247, -3.534, -7.044, 0.688, 3.255, 0. ],
[ -5.364, -3.792, -3.203, -7.212, -5.303, 0.928, -3.028, 0. ],
[ 1.257, -5.088, -4.209, -8.229, -3.4 , -7.856, -29.007, 0. ],
[ -2.956, -4.787, -0.855, -7.551, -5.735, -3.882, -4.183, 0. ],
[ -4.307, -19.643, -0.422, -5.797, -12.939, -9.516, 4.866, 0. ],
[-22.003, -20.167, -17.983, -46.882, -44.439, 2.678, 3.308, 0. ],
[ -4.706, -8.41 , 0.885, -12.78 , -13.647, 10.902, 6.622, 0. ],
[ -6.822, -2.396, 2.941, 3.965, -5.588, 14.765, 11.879, 0. ],
[ -2.674, 0.173, 8.768, 9.349, 4.73 , 10.9 , 12.983, 0. ]])
x_header = [2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014]
y_header = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
fig, ax = plt.subplots()
heatmap = plt.pcolor(arr, cmap = 'RdBu')
ax.set_xticks(np.arange(arr.shape[1]), minor=False)
ax.set_yticks(np.arange(arr.shape[0])+0.5, minor=False)
ax.set_xticklabels(x_header)
ax.set_yticklabels(y_header)
ax.xaxis.tick_top()
ax.invert_yaxis()
plt.show()
However, I do not get the gradient of my choice. I get the figure below. If you notice most of the negative values are having a blue gradient, and only a few values are having red gradient. Is there any way to force the use of a particular color gradient for positive values and another color for negative values exclusively?
Thanks.
|
I'm trying to read from a PS3 controller in python on Ubuntu and I'm not having much luck. I started with the ps3joy driver from Willow Garage (http://www.ros.org/wiki/ps3joy) which supposedly publishes all the important bits of the PS3 controller to something I had never heard of called "uinput". Apparently it's a linux feature that allows userspace drivers to provide system events. ...Why the WG driver requires root access given that it's supposedly a userspace driver is beyond me, but that's not my question.
Anyway, the current state of me trying to get it to work is that I've got the driver working, and I've verified that it responds to button presses on the controller, but I don't know how to pull any of that data out so I can use it.
My first guess was to use pygame to (hopefully) read from /dev/uinput (which I'm pretty sure is where the driver sends the data):
from pygame import joystick
if not joystick.get_init():
joystick.init()
js = joystick.Joystick(0) # there is only one joystick... even if the driver isn't running(!)
js.init()
print js.get_numbuttons() # perhaps coincidentally correctly prints 17 which is the number of buttons on a PS3 controller
for i in range(js.get_numaxes()):
print js.get_axis(i) # always prints 0, no matter what I'm doing with the controller
but it didn't work. The most telling part of the problem is that it does the same thing if I don't have the WG driver running at all.
I'm sure this is something easy, that I'm just not reading the right information, but googling has not helped me find what the right information is and I'm getting tired and desperate.
|
Emesene is an instant messenger for the WLM (Windows Live Messenger) network which works on both Windows and Linux.
Emesene 1.5 brings a lot of new features and bugfixes, most notable being the webcam (video) support. Changes in 1.5:
* Compatible with the latest Window Live Messenger(tm)
* New plugin set (Plus! colors, Notifications, Mail check, etc.)
* HTTP connection and proxy support
* @msn accounts support
* Better contact list management with Privacy Tab and ability to reject users
* Improved Offline Messaging experience
* Support for msn groups
* No more gui locks
* Experimental webcam support with a configurator
* New layout options and improved usability along with customization
* Tons of new languages supported
Emesene 1.5 brings a lot of new features and bugfixes, most notable being the webcam (video) support. Changes in 1.5:
* Compatible with the latest Window Live Messenger(tm)
* New plugin set (Plus! colors, Notifications, Mail check, etc.)
* HTTP connection and proxy support
* @msn accounts support
* Better contact list management with Privacy Tab and ability to reject users
* Improved Offline Messaging experience
* Support for msn groups
* No more gui locks
* Experimental webcam support with a configurator
* New layout options and improved usability along with customization
* Tons of new languages supported
To install Emesene 1.5 in Ubuntu:
1. Add the Launchpad PPA repository:
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E2314809
sudo echo "deb http://ppa.launchpad.net/bjfs/ppa/ubuntu jaunty main" | sudo tee -a /etc/apt/sources.list
2. Install Emesene
sudo apt-get update && sudo apt-get install emesene
or if you already have Emesene installed and need to upgrade:
sudo apt-get update && sudo apt-get upgrade
For other Linux distributions, download the source code from HERE.
How to run Emesene as Root
Before you follow any of the below steps, you show know that YOU MUST NOT LOG IN AS ROOT. If you still chose to do so, then read on.
Emesene refuses to start when you are logged in as root. In fact, if you runt it in a terminal, the following text is displayed:
To make Emesene run as root, press Alt + F2 and type:
Then search for "I refuse to run as root" in that file. Comment that line, the line before and after it, using the "#" symbol. Like this:
[via ubuntu tips]
Emesene refuses to start when you are logged in as root. In fact, if you runt it in a terminal, the following text is displayed:
I refuse to run as root
To make Emesene run as root, press Alt + F2 and type:
gksu gedit /usr/share/python-support/emesene/Controller.py
Then search for "I refuse to run as root" in that file. Comment that line, the line before and after it, using the "#" symbol. Like this:
def debug(msg):
'''print a debug message'''
print 'Controller: ' + msg
def main():
# if os.name == 'posix' and os.getuid() == 0:
# print "I refuse to run as root"
# return
try:
path = os.path.dirname(__file__) or sys.path[0]
except NameError:
path = sys.path[0]
[via ubuntu tips]
|
I am trying to write a function to post form data and save returned cookie info in a file so that the next time the page is visited, the cookie information is sent to the server (i.e. normal browser behavior).
I wrote this relatively easily in C++ using curlib, but have spent almost an entire day trying to write this in Python, using urllib2 - and still no success.
This is what I have so far:
import urllib, urllib2
import logging
# the path and filename to save your cookies in
COOKIEFILE = 'cookies.lwp'
cj = None
ClientCookie = None
cookielib = None
logger = logging.getLogger(__name__)
# Let's see if cookielib is available
try:
import cookielib
except ImportError:
logger.debug('importing cookielib failed. Trying ClientCookie')
try:
import ClientCookie
except ImportError:
logger.debug('ClientCookie isn\'t available either')
urlopen = urllib2.urlopen
Request = urllib2.Request
else:
logger.debug('imported ClientCookie succesfully')
urlopen = ClientCookie.urlopen
Request = ClientCookie.Request
cj = ClientCookie.LWPCookieJar()
else:
logger.debug('Successfully imported cookielib')
urlopen = urllib2.urlopen
Request = urllib2.Request
# This is a subclass of FileCookieJar
# that has useful load and save methods
cj = cookielib.LWPCookieJar()
login_params = {'name': 'anon', 'password': 'pass' }
def login(theurl, login_params):
init_cookies();
data = urllib.urlencode(login_params)
txheaders = {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}
try:
# create a request object
req = Request(theurl, data, txheaders)
# and open it to return a handle on the url
handle = urlopen(req)
except IOError, e:
log.debug('Failed to open "%s".' % theurl)
if hasattr(e, 'code'):
log.debug('Failed with error code - %s.' % e.code)
elif hasattr(e, 'reason'):
log.debug("The error object has the following 'reason' attribute :"+e.reason)
sys.exit()
else:
if cj is None:
log.debug('We don\'t have a cookie library available - sorry.')
else:
print 'These are the cookies we have received so far :'
for index, cookie in enumerate(cj):
print index, ' : ', cookie
# save the cookies again
cj.save(COOKIEFILE)
#return the data
return handle.read()
# FIXME: I need to fix this so that it takes into account any cookie data we may have stored
def get_page(*args, **query):
if len(args) != 1:
raise ValueError(
"post_page() takes exactly 1 argument (%d given)" % len(args)
)
url = args[0]
query = urllib.urlencode(list(query.iteritems()))
if not url.endswith('/') and query:
url += '/'
if query:
url += "?" + query
resource = urllib.urlopen(url)
logger.debug('GET url "%s" => "%s", code %d' % (url,
resource.url,
resource.code))
return resource.read()
When I attempt to log in, I pass the correct username and pwd,. yet the login fails, and no cookie data is saved.
My two questions are:
can anyone see whats wrong with the login() function, and how may I fix it?
how may I modify the get_page() function to make use of any cookie info I have saved ?
|
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
@hook('after_request')
def enable_cors():
response.headers['Access-Control-Allow-Origin'] = '*'
@route('/')
def ping():
return 'Up and running!'
if __name__ == '__main__':
run(host=<my_ip>, port=3000)
I'm running into the following issue:
This works initially but the server stops responding after some time (~24hours). Unfortunately, the logs don't contain any revealing error messages.
The only way I have been able to reproduce the issue is when I try to run a second script on my Ubuntu server that creates another server listening to a different port (ie.: exactly the same script as above but port=3001). If I send a request to the newly created server, I also do not get a response and the connection eventually times out.
Any suggestions are greatly appreciated. I'm new to this, so if there's something fundamentally wrong with this approach, any links to reference guides would also be appreciated. Thank you!
|
Summary
AsyncIO is the new hot topic for Python 3.4 which was just recently released. In my opinion, AsyncIO is a big game changer for Python. Where it makes sense, many libraries are sure to port some or all of their code to take advantage of it. I'm going to show you my version of a client and server I wrote after digesting section 18.5 of the Python documentation and looking at a few examples on the web.
Requirements
You will need Python 3.4 to run the sample files, or install asyncio (pip install asyncio) for Python 3.3. There is a backport of asyncio for 2.6+ but I didn't test my code on there.
Quickstart
Clone from git or save the files below
$ git clone https://gist.github.com/9627160.git
Open a Terminal (or command prompt) window.
$ python server.py
Open another Terminal (or command prompt) window and run.
$ python client.py
Server
"""
server.py - AsyncIO Server using StreamReader and StreamWriter
example in another terminal:
$ nc localhost 2991
HELLO
WORLD
READY
one
ECHO 1: one
two
ECHO 2: two
three
ECHO 3: three
four
ECHO 4: four
five
ECHO 5: five
six
ECHO 6: six
seven
ECHO 7: seven
eight
ECHO 8: eight
nine
ECHO 9: nine
ten
ECHO 10: ten
bye
BYE
$
"""
import asyncio
import logging
log = logging.getLogger(__name__)
clients = {} # task -> (reader, writer)
def accept_client(client_reader, client_writer):
task = asyncio.Task(handle_client(client_reader, client_writer))
clients[task] = (client_reader, client_writer)
def client_done(task):
del clients[task]
client_writer.close()
log.info("End Connection")
log.info("New Connection")
task.add_done_callback(client_done)
@asyncio.coroutine
def handle_client(client_reader, client_writer):
# send a hello to let the client know they are connected
client_writer.write("HELLO\n".encode())
# give client a chance to respond, timeout after 10 seconds
data = yield from asyncio.wait_for(client_reader.readline(),
timeout=10.0)
if data is None:
log.warning("Expected WORLD, received None")
return
sdata = data.decode().rstrip()
log.info("Received %s", sdata)
if sdata != "WORLD":
log.warning("Expected WORLD, received '%s'", sdata)
return
# now be an echo back server until client sends a bye
i = 0 # sequence number
# let client know we are ready
client_writer.write("READY\n".encode())
while True:
i = i + 1
# wait for input from client
data = yield from asyncio.wait_for(client_reader.readline(),
timeout=10.0)
if data is None:
log.warning("Received no data")
# exit echo loop and disconnect
return
sdata = data.decode().rstrip()
if sdata.upper() == 'BYE':
client_writer.write("BYE\n".encode())
break
response = ("ECHO %d: %s\n" % (i, sdata))
client_writer.write(response.encode())
def main():
loop = asyncio.get_event_loop()
f = asyncio.start_server(accept_client, host=None, port=2991)
loop.run_until_complete(f)
loop.run_forever()
if __name__ == '__main__':
log = logging.getLogger("")
formatter = logging.Formatter("%(asctime)s %(levelname)s " +
"[%(module)s:%(lineno)d] %(message)s")
# setup console logging
log.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
log.addHandler(ch)
main()
Client
"""
client.py - AsyncIO Server using StreamReader and StreamWriter
This will create 200 client connections to a server running server.py
It will handshake and run similar to this:
Server: HELLO
Client: WORLD
Server: READY
Client: one
Server: ECHO 1: one
...
Client: six
Server: ECHO 6: six
Client: BYE
Server: BYE
"""
import asyncio
import logging
log = logging.getLogger(__name__)
clients = {} # task -> (reader, writer)
def make_connection(host, port):
task = asyncio.Task(handle_client(host, port))
clients[task] = (host, port)
def client_done(task):
del clients[task]
log.info("Client Task Finished")
if len(clients) == 0:
log.info("clients is empty, stopping loop.")
loop = asyncio.get_event_loop()
loop.stop()
log.info("New Client Task")
task.add_done_callback(client_done)
@asyncio.coroutine
def handle_client(host, port):
log.info("Connecting to %s %d", host, port)
client_reader, client_writer = yield from asyncio.open_connection(host,
port)
log.info("Connected to %s %d", host, port)
try:
# looking for a hello
# give client a chance to respond, timeout after 10 seconds
data = yield from asyncio.wait_for(client_reader.readline(),
timeout=10.0)
if data is None:
log.warning("Expected HELLO, received None")
return
sdata = data.decode().rstrip().upper()
log.info("Received %s", sdata)
if sdata != "HELLO":
log.warning("Expected HELLO, received '%s'", sdata)
return
# send back a WORLD
client_writer.write("WORLD\n".encode())
# wait for a READY
data = yield from asyncio.wait_for(client_reader.readline(),
timeout=10.0)
if data is None:
log.warning("Expected READY, received None")
return
sdata = data.decode().rstrip().upper()
if sdata != "READY":
log.warning("Expected READY, received '%s'", sdata)
return
echostrings = ['one', 'two', 'three', 'four', 'five', 'six']
for echostring in echostrings:
# send each string and get a reply, it should be an echo back
client_writer.write(("%s\n" % echostring).encode())
data = yield from asyncio.wait_for(client_reader.readline(),
timeout=10.0)
if data is None:
log.warning("Echo received None")
return
sdata = data.decode().rstrip()
log.info(sdata)
# send BYE to disconnect gracefully
client_writer.write("BYE\n".encode())
# receive BYE confirmation
data = yield from asyncio.wait_for(client_reader.readline(),
timeout=10.0)
sdata = data.decode().rstrip().upper()
log.info("Received '%s'" % sdata)
finally:
log.info("Disconnecting from %s %d", host, port)
client_writer.close()
log.info("Disconnected from %s %d", host, port)
def main():
log.info("MAIN begin")
loop = asyncio.get_event_loop()
for x in range(200):
make_connection('localhost', 2991)
loop.run_forever()
log.info("MAIN end")
if __name__ == '__main__':
log = logging.getLogger("")
formatter = logging.Formatter("%(asctime)s %(levelname)s " +
"[%(module)s:%(lineno)d] %(message)s")
# setup console logging
log.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
log.addHandler(ch)
main()
|
ADcomp
Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo]
Yep ..
@ all : lien pour les sources rectifié ( )
@ frafa :
-add n'importe quoi, puis fermer fenetre sans ajout, ajoute quand meme une entrée vide. tu devrait gerer ca...
+1
-et si pas trop galere a coder avoir acces aux reglages d'un plug-in via clic droir direct sur adeskbar...
pour la prochaine version ( demande pas mal de changement )
il me semble que avant genre 1 clic sur plug term affichait et un second clic masquait, c'estait mieux comca je trouve..
non .. pas de changement. le plugin disparait s'il perd le focus ou sur second clic. A ajouter dans les options ..
@ Kookaburra : faut aussi que je dorme parfois .. mais c tout a fait envisageable
@ fran : je regarde pour 'fake transparency' .. surement une tatouille à l'enregistrement de la conf.
---
Astuce pour le plugin 'desktop' :
clic gauche : afiiche l'application
clic molette : maximize/restore
clic droit : minimize/restore
Test pour le plugin volume :
si le plugin s'affiche pas , qqu'un peut tester en modifiant la variable 'control=Master' du plugin ( ~/.config/adeskbar/default.cfg ) et remplacer par 'control=Volume' ou 'control=PCM' ?
penser aussi en cas de bug , de lancer adeskbar depuis une console et de copier/coller si erreur
A+
Dernière modification par ADcomp (Le 18/05/2010, à 19:47)
Hors ligne
Kookaburra
Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo]
@ Kookaburra : faut aussi que je dorme parfois .. mais c tout a fait envisageable
Quoi ? Que lis-je ?
Les développeurs dorment parfois ? On m'aurait menti ?
Remboursez nos invitations, remboursez nos invitations, remboursez nos invitations !!! (référence à un film, culte pour certains, à chier pour d'autres )
On va dire que je te propose des rajouts pour la version 3.0, celle-là même qui renverra au placard Cairo-Dock et autre Avant-Windows-Navigator
Dernière modification par Kookaburra (Le 18/05/2010, à 20:38)
Portable17p : CrunchBangLinux // EeePC : ArchLinux
Openbox Addict : http://kookadimi.deviantart.com
Mes photos : http://www.fluidr.com/photos/kookadimi/setsVotre téléphone mobile dispose de plus de puissance que l'ensemble des ordinateurs de la NASA en 1969. La NASA a lancé un homme sur la Lune. Vous lancez un oiseau sur des cochons...
Hors ligne
Kookaburra
Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo]
Test pour le plugin volume :
si le plugin s'affiche pas , qqu'un peut tester en modifiant la variable 'control=Master' du plugin ( ~/.config/adeskbar/default.cfg ) et remplacer par 'control=Volume' ou 'control=PCM' ?
penser aussi en cas de bug , de lancer adeskbar depuis une console et de copier/coller si erreur
A+
En fait, j'ai pas ce que tu proposes dans le fichier, je n'ai que ça :
[LAUNCHER/1274207421]
cmd=@volume
name=Volume Mixer
icon=images/plugins/volume.png
Et dans le terminal, ça donne ça :
┌────[dimitri@geekEee]─────────────────────[20:34:11]────┐
└───>(/home/dimitri) $ adeskbar
Traceback (most recent call last):
File "/usr/share/adeskbar/adesk/bar.py", line 90, in load_plugin
exec("import plugins.%s as plugin" % p)
File "<string>", line 1, in <module>
File "/usr/share/adeskbar/plugins/volume.py", line 4, in <module>
import alsaaudio as alsa
ImportError: No module named alsaaudio
Il doit me manquer un paquet, mais je ne sais pas lequel (mon son fonctionne bien pourtant ...)
Portable17p : CrunchBangLinux // EeePC : ArchLinux
Openbox Addict : http://kookadimi.deviantart.com
Mes photos : http://www.fluidr.com/photos/kookadimi/setsVotre téléphone mobile dispose de plus de puissance que l'ensemble des ordinateurs de la NASA en 1969. La NASA a lancé un homme sur la Lune. Vous lancez un oiseau sur des cochons...
Hors ligne
rc_outside
Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo]
Je copie mon edit qui ne passe pas chez moi :
la config du module mixer n'apparait pas dans la fenêtre chez moi. Voici l'erreur en console :
EE - 'volume': 'tuple' object has no attribute 'index'
Traceback (most recent call last):
File "/usr/share/adeskbar/adesk/barconf.py", line 900, in __init__
self.plugin_conf = plugin_conf.config(self.conf, self.ind)
File "/usr/share/adeskbar/plugins/conf/volume.py", line 54, in __init__
self.mixer.set_active(mixer_list.index(mixer))
AttributeError: 'tuple' object has no attribute 'index'
Je commence à me dire que mon installation ou ma configuration niveau son sont foireuses.
Hors ligne
ADcomp
Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo]
import alsaaudio as alsa
ImportError: No module named alsaaudio
Il doit me manquer un paquet, mais je ne sais pas lequel (mon son fonctionne bien pourtant ...)
...
Dépendances:
ADeskBar : python , python-gtk2 , python-cairo ( usually already installed )
plugins : desktop => python-wnck , volume => python-alsaaudio et terminal => python-vte<metadata lang=Batchfile prob=0.09 />
sudo apt-get install python-wnck python-alsaaudio python-vte
Hors ligne
Kookaburra
Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo]
Perdu
(ça ne vient pas de python-alsaaudio, je l'avais déjà ...)
┌────[dimitri@geekEee]────────────────[22:15:15]────┐
└───>(/home/dimitri) $ sudo apt-get install python-alsaaudio
Lecture des listes de paquets... Fait
Construction de l'arbre des dépendances
Lecture des informations d'état... Fait
python-alsaaudio est déjà la plus récente version disponible.
0 mis à jour, 0 nouvellement installés, 0 à enlever et 0 non mis à jour.
(Ne pas oublier que je suis sous un dérivé d'UNR 9.04 mais avec le noyau Linux "2.6.32.9-1-jolicloud-atom", je ne sais si ça peut mettre le bordel ???
Portable17p : CrunchBangLinux // EeePC : ArchLinux
Openbox Addict : http://kookadimi.deviantart.com
Mes photos : http://www.fluidr.com/photos/kookadimi/setsVotre téléphone mobile dispose de plus de puissance que l'ensemble des ordinateurs de la NASA en 1969. La NASA a lancé un homme sur la Lune. Vous lancez un oiseau sur des cochons...
Hors ligne
ADcomp
Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo]
@ rc_outside : bizarre ca .. tu utilise quelle version pour python ? parce que ca fonctionne avec 2.6
@ Kookaburra : yep .. surement un prob' de version. pas de 9.04 sous la main pour tester
Hors ligne
rc_outside
Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo]
J'ai bien python 2.6 installé mais étant encore en expérimental, le métapaquet "python" par défaut dans ma sid renvoie à la 2.5. Mais ça devrait quand même fonctionner non ?
Hors ligne
ADcomp
Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo]
@ rc_outside : pas grave .. je fais regarder pour que ca fonctionne de toute façon .. mais demain
Hors ligne
frafa
Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo]
@ rc_outside
tu as essayé de lancer genre comca:
PATH=$(which python2.6):$PATH adeskbar
Hors ligne
Kookaburra
Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo]
@ Kookaburra : yep .. surement un prob' de version. pas de 9.04 sous la main pour tester
Surement oui ...
┌────[dimitri@geekEee]────────────────────────────────[09:08:54]────┐
───>(/home/dimitri) $ aptitude show python-alsaaudio
Paquet : python-alsaaudio
Nouveau: oui
État: installé
Automatiquement installé: non
Version : 0.2-1ubuntu2
Priorité : optionnel
Section : universe/sound
Responsable : Ubuntu MOTU Developers <ubuntu-motu@lists.ubuntu.com>
Taille décompressée : 356k
Dépend: python (< 2.7), python (>= 2.5), python-support (>= 0.7.1), libasound2 (> 1.0.18), libc6 (>= 2.4)
Description : Alsa bindings for Python
The PyAlsaAudio package contains bindings for the ALSA sound api.
Portable17p : CrunchBangLinux // EeePC : ArchLinux
Openbox Addict : http://kookadimi.deviantart.com
Mes photos : http://www.fluidr.com/photos/kookadimi/setsVotre téléphone mobile dispose de plus de puissance que l'ensemble des ordinateurs de la NASA en 1969. La NASA a lancé un homme sur la Lune. Vous lancez un oiseau sur des cochons...
Hors ligne
rc_outside
Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo]
Idem frafa, même erreur... il doit peut-être me manquer un paquet python dans ma sid ?
Edit : après réinstall d'adeskbar, le mixer fonctionne, il règle bien le son, c'est juste que je n'accède pas à la config avec toujours le même message en console. Donc c'est pas trop génant
Dernière modification par rc_outside (Le 19/05/2010, à 14:39)
Hors ligne
ADcomp
Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo]
Update ..
* (Kookaburra) nouvelle option : Intellihide [ besoin de python-wnck ]
* (frafa) """ add n'importe quoi, puis fermer fenetre sans ajout, ajoute quand meme une entrée vide """ : réglé
* (rc_outside) j'ai modifié le code , maintenant cela devrait fonctionner
--
Paquet deb : adeskbar.0.22-all.deb
Source : adeskbar_0.22.tar.bz2
Video - Intellihide : http://www.youtube.com/watch?v=vQD_qV_PRSY
Dernière modification par ADcomp (Le 20/05/2010, à 14:13)
Hors ligne
rc_outside
Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo]
parfait chez moi merci
Hors ligne
frafa
Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo]
Salut
et merci pour ta réactivité
j'ai un bug avec "Fake Transparency is no composite"
avec effect activé pas de souci par contre si je teste sans
et que dans adeskbar je coche "Fake Transparency is no composite"
j'obtiens un gel des nenu (pas des fenetres) j'ai pas regardé le code tu active quoi xcompmgr ?
(je suis en dual-screen +proprio nvidia) que je teste dans ecran primaire ou secondaire meme bug généré...
(c'est avec le . deb sous Ubuntu lucid ce bug.)
Hors ligne
ADcomp
Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo]
salut .. merci pour les retours
@frafa : bug trouvé ( déjà dit par fran ) .. et rectifié. update dès que possible
Dernière modification par ADcomp (Le 20/05/2010, à 18:06)
Hors ligne
frafa
Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo]
ok
Hors ligne
sam7
Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo]
déjà la 0.22 ! tu avances drôlement vite merci ... je n'ai pas encore eu le temps de l'installer ... mais si il change si rapidement, je le ferais dans une machine virtuelle alors ... ça sera donc "un peu plus tard" (je n'ai pas encore terminé ma "multiréinstallation )
Dernière modification par sam7 (Le 20/05/2010, à 23:19)
Hors ligne
ADcomp
Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo]
bug dans la nouvelle option Intellihide si l'application s'ouvre directement en max. ( comment j'ai loupé ca ? ). + prob. 'Fake trans' résolu
Deb : adeskbar.0.22-1-all.deb
Source : adeskbar_0.22-1.tar.bz2
Dernière modification par ADcomp (Le 21/05/2010, à 00:43)
Hors ligne
Kookaburra
Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo]
J'adore l'option "Intellihide", quelle bonne idée !
Merci pour cette implémentation rapide, c'est sympa
Portable17p : CrunchBangLinux // EeePC : ArchLinux
Openbox Addict : http://kookadimi.deviantart.com
Mes photos : http://www.fluidr.com/photos/kookadimi/setsVotre téléphone mobile dispose de plus de puissance que l'ensemble des ordinateurs de la NASA en 1969. La NASA a lancé un homme sur la Lune. Vous lancez un oiseau sur des cochons...
Hors ligne
frenchy82
Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo]
Bonjour,
En tout premier, félicitation, cette aplli est sincerement géniale
Je n'utilise pas de composit au vue des pales performances de mon ordi et avec adeskbar pas de probleme.
Sous lubuntu j'ai du remplacer thunar par pcmanfm pour les bookmarks.
J'avais un bug d'affichage au lancement de l'ordi, et il semble qu'en forcant un délais de 15 secondes au premier lancement de adeskbar cela règle le problème (a confirmer)
Reste juste deux problèmes (vraiment mineurs)
- l'applet son n'apparait pas (j'ai testé les modifs ci dessus) en sachant que sous lubuntu c'est aumix qui est utilisé
- l'applet de recherche web lance firefox alors que sous lubuntu c'est chromium le navigateur par defaut
Merci encore pour elle
PS: L'option intellihide est magique
Hors ligne
uboops
Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo]
Bonjour,
Bravo pour cette appli., elle est très sympa !
Juste une petite suggestion cosmétique pour l'instant:
Il serait sympa que le facteur de zoom puisse allé au delà de +40% (1.40) genre +100% (2.00), et qu'il y ait une option afin que l'icône précédant et l'icône suivant puissent avoir un facteur de zoom divisé par 2.
genre: si zoom factor icône n = +40%, alors zoom factor de icône n-1 et n+1 = +20% (voir éventuellement n-2 et n+2 = +10%), afin d'avoir un effet de "vague" ou de "Olaaa".
Dernière modification par uboops (Le 22/05/2010, à 12:42)
Tout comme, Ce qui a créé l'Univers (...dont l'Homme) est Patrimoine Universel, tout ce qui a été créé par l'Homme "via ce créateur" doit être au minimum Patrimoine de l'Humanité !
Hors ligne
Leyna
Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo]
Bonjour,
J'ai installé la toute dernière version, que du bonheur! Une vraie fluidité d'utilisation! En plus le thème par défaut est vraiment beau c'est la première fois que je ne me jette pas sur les paramètres pour bidouiller à ma sauce
Par contre le plugin volume ne s'affiche même pas chez moi. Les autres plugins marchent.
La proposition de uboops me paraît intéressante, ça pourrait être fun comme effet!
Bravo & merci pour ce beau travail ADcomp!
Hors ligne
uboops
Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo]
...Par contre le plugin volume ne s'affiche même pas chez moi. Les autres plugins marchent....
Pour info, moi aussi, j'ai le même problème, dans le terminal j'ai:
adeskbar
** (adeskbar:969): WARNING **: Trying to register gtype 'WnckWindowState' as enum when in fact it is of type 'GFlags'
** (adeskbar:969): WARNING **: Trying to register gtype 'WnckWindowActions' as enum when in fact it is of type 'GFlags'
** (adeskbar:969): WARNING **: Trying to register gtype 'WnckWindowMoveResizeMask' as enum when in fact it is of type 'GFlags'
Traceback (most recent call last):
File "/usr/share/adeskbar/adesk/bar.py", line 90, in load_plugin
exec("import plugins.%s as plugin" % p)
File "<string>", line 1, in <module>
File "/usr/share/adeskbar/plugins/volume.py", line 4, in <module>
import alsaaudio as alsa
ImportError: No module named alsaaudio
- WxH : 536 66 - XxY : 372 933
Tout comme, Ce qui a créé l'Univers (...dont l'Homme) est Patrimoine Universel, tout ce qui a été créé par l'Homme "via ce créateur" doit être au minimum Patrimoine de l'Humanité !
Hors ligne
ADcomp
Re : ADesk Bar : Barre de lancement rapide [python/gtk/cairo]
hello tout le monde ..
Merci tout plein pour les commentaires super sympa
Comme je l'ai dit , le plugin volume a encore besoin de qques ajustements. en cours
Pour ce qui est de l'effet vague/olaaa , je suis pas trop fan mais bon j'ai déjà testé quand même ( je code pas que pour moi )
Mais le code n'est pas du tout adapté pour cela , effet de saccade assuré ! il faudra refaire toute la partie 'dessine moi un joli icone sur la barre' et la gestion des évènements ( sur-vol souris , clic , etc .. ) . Donc pas pour tout de suite ..
A+
--
EDIT :
@ uboops : peut-être ca
...
Dépendances:
ADeskBar : python , python-gtk2 , python-cairo ( usually already installed )
plugins : desktop => python-wnck , volume => python-alsaaudio et terminal => python-vte<metadata lang=Batchfile prob=0.09 />
sudo apt-get install python-wnck python-alsaaudio python-vte
Dernière modification par ADcomp (Le 22/05/2010, à 13:32)
Hors ligne
|
I'd like to generate matrices of size mxn and rank r, with elements coming from a specified finite set, e.g. {0,1} or {1,2,3,4,5}. I want them to be "random" in some very loose sense of that word, i.e. I want to get a variety of possible outputs from the algorithm with distribution vaguely similar to the distribution of all matrices over that set of elements with the specified rank.
In fact, I don't actually care that it has rank r, just that it's close to a matrix of rank r (measured by the Frobenius norm).
When the set at hand is the reals, I've been doing the following, which is perfectly adequate for my needs: generate matrices U of size mxr and V of nxr, with elements independently sampled from e.g. Normal(0, 2). Then U V' is an mxn matrix of rank r (well, <= r, but I think it's r with high probability).
If I just do that and then round to binary / 1-5, though, the rank increases.
It's also possible to get a lower-rank approximation to a matrix by doing an SVD and taking the first r singular values. Those values, though, won't lie in the desired set, and rounding them will again increase the rank.
This question is related, but accepted answer isn't "random," and the other answer suggests SVD, which doesn't work here as noted.
One possibility I've thought of is to make r linearly independent row or column vectors from the set and then get the rest of the matrix by linear combinations of those. I'm not really clear, though, either on how to get "random" linearly independent vectors, or how to combine them in a quasirandom way after that.
(Not that it's super-relevant, but I'm doing this in numpy.)
Update: I've tried the approach suggested by EMS in the comments, with this simple implementation:
real = np.dot(np.random.normal(0, 1, (10, 3)), np.random.normal(0, 1, (3, 10)))
bin = (real > .5).astype(int)
rank = np.linalg.matrix_rank(bin)
niter = 0
while rank > des_rank:
cand_changes = np.zeros((21, 5))
for n in range(20):
i, j = random.randrange(5), random.randrange(5)
v = 1 - bin[i,j]
x = bin.copy()
x[i, j] = v
x_rank = np.linalg.matrix_rank(x)
cand_changes[n,:] = (i, j, v, x_rank, max((rank + 1e-4) - x_rank, 0))
cand_changes[-1,:] = (0, 0, bin[0,0], rank, 1e-4)
cdf = np.cumsum(cand_changes[:,-1])
cdf /= cdf[-1]
i, j, v, rank, score = cand_changes[np.searchsorted(cdf, random.random()), :]
bin[i, j] = v
niter += 1
if niter % 1000 == 0:
print(niter, rank)
It works quickly for small matrices but falls apart for e.g. 10x10 -- it seems to get stuck at rank 6 or 7, at least for hundreds of thousands of iterations.
It seems like this might work better with a better (ie less-flat) objective function, but I don't know what that would be.
I've also tried a simple rejection method for building up the matrix:
def fill_matrix(m, n, r, vals):
assert m >= r and n >= r
trans = False
if m > n: # more columns than rows I think is better
m, n = n, m
trans = True
get_vec = lambda: np.array([random.choice(vals) for i in range(n)])
vecs = []
n_rejects = 0
# fill in r linearly independent rows
while len(vecs) < r:
v = get_vec()
if np.linalg.matrix_rank(np.vstack(vecs + [v])) > len(vecs):
vecs.append(v)
else:
n_rejects += 1
print("have {} independent ({} rejects)".format(r, n_rejects))
# fill in the rest of the dependent rows
while len(vecs) < m:
v = get_vec()
if np.linalg.matrix_rank(np.vstack(vecs + [v])) > len(vecs):
n_rejects += 1
if n_rejects % 1000 == 0:
print(n_rejects)
else:
vecs.append(v)
print("done ({} total rejects)".format(n_rejects))
m = np.vstack(vecs)
return m.T if trans else m
This works okay for e.g. 10x10 binary matrices with any rank, but not for 0-4 matrices or much larger binaries with lower rank. (For example, getting a 20x20 binary matrix of rank 15 took me 42,000 rejections; with 20x20 of rank 10, it took 1.2 million.)
This is clearly because the space spanned by the first r rows is too small a portion of the space I'm sampling from, e.g. {0,1}^10, in these cases.
We want the intersection of the span of the first r rows with the set of valid values.So we could try sampling from the span and looking for valid values, but since the span involves real-valued coefficients that's never going to find us valid vectors (even if we normalize so that e.g. the first component is in the valid set).
Maybe this can be formulated as an integer programming problem, or something?
|
I have produced a Python script which creates multiple buffers of specific (listed) featureclasses within a geodatabase. This is achieved by running each feature through a for loop.
I would like to know if/how it would be possible to list featureclasses from more than one geodatabase?
Currently I am using env.workspace to specify the single geodatabase. Listing the features and then running them through the 'for loop'. A possible problem might be that many of the featureclasses in the various geodatabases have the same name.
import arcpy
import os.path
import tempfile
from arcpy import env
# sets the workspace to my gdb
arcpy.env.workspace = "C:/GIS Home/Mining Features (MATTHEW).gdb"
# Output workspace and temp location is defined
output_workspace = "C:/GIS Home/project_1"
temp_workspace = tempfile.mkdtemp()
# list of features to buffer in gdb
fcList = ["Adit_Metalliferous", "Shaft_Metalliferous", "Quarry_Metalliferous", "Dump_Metalliferous", "Engine_House", "Goffan_Working", "Lode_Surface_Outcrop", "Lode_Undefined_Elevation", "Mine_Level", "Mine_Raise", "Portal", "Reported_Subsidence", "Secured_Feature", "Tunnel"]
#create empty lists for output
l_250 = []
l_500 = []
l_750 = []
for featureClass in fcList:
b250 = os.path.join(temp_workspace, featureClass + "_b250.shp") # make temp output file
b500 = os.path.join(temp_workspace, featureClass + "_b500.shp") # make temp output file
b750 = os.path.join(temp_workspace, featureClass + "_b750.shp") # make temp output file
arcpy.Buffer_analysis(featureClass, b250, 250, "", "", "ALL") # carry out buffer
arcpy.Buffer_analysis(featureClass, b500, 500, "", "", "ALL") # carry out buffer
arcpy.Buffer_analysis(featureClass, b750, 750, "", "", "ALL") # carry out buffer
l_250.append(b250) # append the buffer to the l_250 list
l_500.append(b500) # append the buffer to the l_500 list
l_750.append(b750) # append the buffer to the l_750 list
merge_250 = os.path.join(temp_workspace, "250_merge.shp")
arcpy.Merge_management(l_250, merge_250)
merge_500 = os.path.join(temp_workspace, "500_merge.shp")
arcpy.Merge_management(l_500, merge_500)
merge_750 = os.path.join(temp_workspace, "750_merge.shp")
arcpy.Merge_management(l_750, merge_750)
dissolve_250 = os.path.join(output_workspace, "250_dissolve.shp") # create 250_dissolve.shp for final output
arcpy.Dissolve_management(merge_250, dissolve_250)
dissolve_500 = os.path.join(output_workspace, "500_dissolve.shp") # create 500_dissolve.shp for final output
arcpy.Dissolve_management(merge_500, dissolve_500)
dissolve_750 = os.path.join(output_workspace, "750_dissolve.shp") # create 750_dissolve.shp for final output
arcpy.Dissolve_management(merge_750, dissolve_750)
|
Possible Duplicate:
Hyperref warning - Token not allowed in a PDF string
The following code:
\subsection{The classes $\mathcal{L}(\gamma)$}
generates the errors:
Package hyperref Warning: Token not allowed in a PDF string (PDFDocEncoding):
(hyperref) removing `math shift' on input line 1938.
Package hyperref Warning: Token not allowed in a PDF string (PDFDocEncoding):
(hyperref) removing `\gamma' on input line 1938.
Package hyperref Warning: Token not allowed in a PDF string (PDFDocEncoding):
(hyperref) removing `math shift' on input line 1938.
What do I have to do to keep \gamma in the subsection, so that it is also listed in the table of contents?
|
I've got a model like this:
class Talk(BaseModel):
title = models.CharField(max_length=200)
mp3 = models.FileField(upload_to = u'talks/', max_length=200)
seconds = models.IntegerField(blank = True, null = True)
I want to validate before saving that the uploaded file is an MP3, like this:
def is_mp3(path_to_file):
from mutagen.mp3 import MP3
audio = MP3(path_to_file)
return not audio.info.sketchy
Once I'm sure I've got an MP3, I want to save the length of the talk in the seconds attribute, like this:
audio = MP3(path_to_file)
self.seconds = audio.info.length
The problem is, before saving, the uploaded file doesn't have a path (see this ticket, closed as wontfix), so I can't process the MP3.
I'd like to raise a nice validation error so that ModelForms can display a helpful error ("You idiot, you didn't upload an MP3" or something).
Any idea how I can go about accessing the file before it's saved?
p.s. If anyone knows a better way of validating files are MP3s I'm all ears - I also want to be able to mess around with ID3 data (set the artist, album, title and probably album art, so I need it to be processable by mutagen).
|
Components and plugins
Components and plugins are relatively new features of web2py, and there is some disagreement between developers about what they are and what they should be. Most of the confusion stems from the different uses of these terms in other software projects and from the fact that developers are still working to finalize the specifications.
However, plugin support is an important feature and we need to provide some definitions. These definitions are not meant to be final, just consistent with the programming patterns we want to discuss in this chapter.
We will try to address two issues here:
How can we build modular applications that minimize server load and maximize code reuse?
How can we distribute pieces of code in a more or less plugin-and-play fashion?
Components address the first issue; plugins address the second.
Components, LOAD and Ajax
Acomponentis a functionally autonomous part of a web page.
A component may be composed of modules, controllers and views, but there is no strict requirement other than, when embedded in a web page, it must be localized within an html tag (for example a DIV, a SPAN, or an IFRAME) and it must perform its task independently of the rest of the page. We are specifically interested in components that are loaded in the page and communicate with the component controller function via Ajax.
An example of a component is a "comments component" that is contained into a DIV and shows users' comments and a post-new-comment form. When the form is submitted, it is sent to the server via Ajax, the list is updated, and the comment is stored server-side in the database. The DIV content is refreshed without reloading the rest of the page.
LOAD
The web2py LOAD function makes this easy to do without explicit JavaScript/Ajax knowledge or programming.
Our goal is to be able to develop web applications by assembling components into page layouts.
Consider a simple web2py app "test" that extends the default scaffolding app with a custom model in file "models/db_comments.py":
db.define_table('comment_post',
Field('body','text',label='Your comment'),
auth.signature)
one action in "controllers/comments.py"
@auth.requires_login()
def post():
return dict(form=SQLFORM(db.comment_post).process(),
comments=db(db.comment_post).select())
and the corresponding "views/comments/post.html"
{{extend 'layout.html'}}
{{for post in comments:}}
<div class="post">
On {{=post.created_on}} {{=post.created_by.first_name}}
says <span class="post_body">{{=post.body}}</span>
</div>
{{pass}}
{{=form}}
You can access it as usual at:
http://127.0.0.1:8000/test/comments/post
So far there is nothing special in this action, but we can turn it into a component by defining a new view with extension ".load" that does not extend the layout.
Hence we create a "views/comments/post.load":
{{for post in comments:}}
<div class="post">
On {{=post.created_on}} {{=post.created_by.first_name}}
says <blockquote class="post_body">{{=post.body}}</blockquote>
</div>
{{pass}}
{{=form}}
We can access it at the URL
http://127.0.0.1:8000/test/comments/post.load
This is a component that we can embed into any other page by simply doing
{{=LOAD('comments','post.load',ajax=True)}}
For example in "controllers/default.py" we can edit
def index():
return dict()
and in the corresponding view add the component:
{{extend 'layout.html'}}
{{=LOAD('comments','post.load',ajax=True)}}
Visiting the page
http://127.0.0.1:8000/test/default/index
will show the normal content and the comments component:
The {{=LOAD(...)}} component is rendered as follows:
<script type="text/javascript"><!--
web2py_component("/test/comment/post.load","c282718984176")
//--></script><div id="c282718984176">loading...</div>
(the actual generated code depends on the options passed to the LOAD function).
The web2py_component(url,id) function is defined in "web2py_ajax.html" and it performs all the magic: it calls the url via Ajax and embeds the response into the DIV with corresponding id; it traps every form submission into the DIV and submits those forms via Ajax. The Ajax target is always the DIV itself.
LOAD signature
The full signature of the LOAD helper is the following:
LOAD(c=None, f='index', args=[], vars={},
extension=None, target=None,
ajax=False, ajax_trap=False,
url=None,user_signature=False,
timeout=None, times=1,
content='loading...',**attr):
Here:
the first two arguments candfare the controller and the function that we want to call respectively.
argsandvarsare the arguments and variables that we want to pass to the function. The former is a list, the latter is a dictionary.
extensionis an optional extension. Notice that the extension can also be passed as part of the function as inf='index.load'.
targetis theidof the target DIV. If it is not specified a random targetidis generated.
ajaxshould be set toTrueif the DIV has to be filled via Ajax and toFalseif the DIV has to be filled before the current page is returned (thus avoiding the Ajax call).
ajax_trap=Truemeans that any form submission in the DIV must be captured and submitted via Ajax, and the response must be rendered inside the DIV.ajax_trap=Falseindicates that forms must be submitted normally, thus reloading the entire page.ajax_trapis ignored and assumed to beTrueifajax=True.
url, if specified, overrides the values ofc,f,args,vars, andextensionand loads the component at theurl. It is used to load as components pages served by other applications (which may or may not be created with web2py).
user_signaturedefaults to False but, if you are logged in, it should be set to True. This will make sure the ajax callback is digitally signed. This is documented in chapter 4.
timesspecifies how many times the component is to be requested. Use "infinity" to keep loading the component continuously. This option is useful for triggering regular routines for a given document request.
timeoutsets the time to wait in milliseconds before starting the request or the frequency iftimesis greater than 1.
contentis the content to be displayed while performing the ajax call. It can be a helper as incontent=IMG(..).
optional **attr(attributes) can be passed to the containedDIV.
If no .load view is specified, there is a generic.load that renders the dictionary returned by the action without layout. It works best if the dictionary contains a single item.
If you LOAD a component having the .load extension and the corresponding controller function redirects to another action (for example a login form), the .load extension propagates and the new url (the one to redirect too) is also loaded with a .load extension.
Redirect from a component
To redirect from a component, use this:
redirect(URL(...),client_side=True)
but note that the redirected URL will default to the extension of the component. See notes about the argument extension in the URL function in Chapter 4
Reload page via redirect after component submission
If you call an action via Ajax and you want the action to force a redirect of the parent page you can do it with a redirect from the LOADed controller function. If you want to reload the parent page, you can redirect to it. The parent URL is known (see Client-Server component communications )
so after processing the form submit, the controller function reloads the parent page via redirect:
if form.process().accepted:
...
redirect( request.env.http_web2py_component_location,client_side=True)
Note that the section below, Client-Server component communications, describes how the component can return javascript, which could be used for more sophisticated actions when the component is submitted. The specific case of reloading another component is described next.
Reload another component
If you use multiple components on a page, you may want the submission of one component to reload another. You do this by getting the submitted component to return some javascript.
It's possible to hard-code the target DIV, but in this recipe we use a query-string variable to inform the submitting-controller which component we want to reload. It's identified by the id of the DIV containing the target component. In this case, the DIV has id 'map'. Note that it is necessary to use target='map' in the LOAD of the target; without this, the target id is randomised and reload() won't work. See LOAD signature above.
In the view, do this:
{{=LOAD('default','submitting_component.load',ajax=True,vars={'reload_div':'map'})}}
The controller belonging to the submitting component needs to send javascript back, so just add this to the existing controller code when processing the submit:
if form.process().accepted:
...
if request.vars.reload_div:
response.js = "jQuery('#%s').get(0).reload()" % request.vars.reload_div
(Of course, remove the redirect if you were using the approach of the previous section.)
That's it. web2py's javascript libraries look after the reload. This could be generalised to handle multiple components with javascript looking like:
jQuery('#div1,#div2,#div3').get(0).reload()
For more information about response.js see Client-Server component communications (below).
Ajax post does not support multipart forms
Because Ajax post does not support multipart forms, i.e. file uploads, upload fields will not work with the LOAD component. You could be fooled into thinking it would work because upload fields will function normally if POST is done from the individual component's .load view. Instead, uploads are done with ajax-compatible 3rd-party widgets and web2py manual upload store commands.
LOAD and Client-Server component communications
When the action of a component is called via Ajax, web2py passes two HTTP headers with the request:
web2py-component-location
web2py-component-element
which can be accessed by the action via the variables:
request.env.http_web2py_component_locationrequest.env.http_web2py_component_element
The latter is also accessible via:
request.cid
The former contains the URL of the page that called the component action. The latter contains the id of the DIV that will contain the response.
The component action can also store data in two special HTTP response headers that will be interpreted by the full page upon response. They are:
web2py-component-flash
web2py-component-command
and they can be set via:
response.headers['web2py-component-flash']='....'
response.headers['web2py-component-command']='...'
or (if the action is called by a component) automatically via:
response.flash='...'response.js='...'
The former contains text that you want to be flashed upon response. The latter contains JavaScript code that you want to be executed upon response. It cannot contain newlines.
As an example, let's define a contact form component in "controllers/contact/ask.py" that allows the user to ask a question. The component will email the question to the system administrator, flash a "thank you" message, and remove the component from the page:
def ask():
form=SQLFORM.factory(
Field('your_email',requires=IS_EMAIL()),
Field('question',requires=IS_NOT_EMPTY()))
if form.process().accepted:
if mail.send(to='admin@example.com',
subject='from %s' % form.vars.your_email,
message = form.vars.question):
response.flash = 'Thank you'
response.js = "jQuery('#%s').hide()" % request.cid
else:
form.errors.your_email = "Unable to send the email"
return dict(form=form)
The first four lines define the form and accept it. The mail object used for sending is defined in the default scaffolding application. The last four lines implement all the component-specific logic by getting data from the HTTP request headers and setting the HTTP response headers.
Now you can embed this contact form in any page via
{{=LOAD('contact','ask.load',ajax=True)}}
Notice that we did not define a .load view for our ask component. We do not have to because it returns a single object (form) and therefore the "generic.load" will do just fine. Remember that generic views are a development tool. In production you should copy "views/generic.load" into "views/contact/ask.load".
user_signature argument:
{{=LOAD('contact','ask.load',ajax=True,user_signature=True)}}
which add a digital signature to the URL. The digital signature must then be validated using a decorator in the callback function:
@auth.requires_signature()
def ask(): ...
Trapped Ajax links and the A Helper
Normally a link is not trapped, and by clicking in a link inside a component, the entire linked page is loaded. Sometimes you want the linked page to be loaded inside the component. This can be achieved using the A helper:
{{=A('linked page',_href='http://example.com',cid=request.cid)}}
If cid is specified, the linked page is loaded via Ajax. The cid is the id of the html element where to place the loaded page content. In this case we set it to request.cid, i.e. the id of the component that generates the link. The linked page can be and usually is an internal URL generated using the URL helper .
Plugins
Apluginis any subset of the files of an application.
and we really mean any:
A plugin is not a module, is not a model, it is not a controller, is not a view, yet it may contain modules, models, controllers and/or views.
A plugin does not need to be functionally autonomous and it may depend on other plugins or specific user code.
A pluginis not aplugins systemand therefore has no concept of registration nor isolation, although we will give rules to try to achieve some isolation.
We are talking about a plugin for your app, not a plugin for web2py.
So why is it called a plugin? Because it provides a mechanism for packing a subset of an app and unpacking it over another app (i.e. plug-in). Under this definition, any file in your app can be treated as a plugin.
When the app is distributed, its plugins are packed and distributed with it.
In practice, the admin provides an interface for packing and unpacking plugins separately from your app. Files and folder of your application that have names with the prefix plugin_name can be packed together into a file called:
web2py.plugin.name.w2p
and distributed together.
The files that compose a plugin are not treated by web2py any differently than other files except that admin understands from their names that they are meant to be distributed together, and it displays them in a separate page:
Yet as a matter of fact, by the definition above, these plugins are more general than those recognized as such by admin.
In practice we will only be concerned with two types of plugins:
Component Plugins. These are plugins that contain components as defined in the previous section. A component plugin can contain one or more components. We can think for example of aplugin_commentsthat contains thecommentscomponent proposed above. Another example could beplugin_taggingthat contains ataggingcomponent and atag-cloudcomponent that share some database tables also defined by the plugin.
Layout Plugins. These are plugins that contain a layout view and the static files required by such layout. When the plugin is applied it gives the app a new look and feel.
By the above definitions, the components created in the previous section, for example "controllers/contact.py", are already plugins. We can move them from one app to another and use the components they define. Yet they are not recognized as such by admin because there is nothing that labels them as plugins. So there are two problems we need to solve:
Name the plugin files using a convention, so that admincan recognize them as belonging to the same plugin
If the plugin has model files, establish a convention so that the objects it defines do not pollute the namespace and do not conflict with each other.
Let's assume a plugin is called name. Here are the rules that should be followed:
Rule 1: Plugin models and controllers should be called, respectively
models/plugin_name.py
controllers/plugin_name.py
and plugin views, modules, static, and private files should be in folders called, respectively:
views/plugin_name/
modules/plugin_name/
static/plugin_name/
private/plugin_name/
Rule 2: Plugin models can only define objects with names that start with
plugin_name
PluginName
_
Rule 3: Plugin models can only define session variables with names that start with
session.plugin_name
session.PluginName
Rule 4: Plugins should include license and documentation. These should be placed in:
static/plugin_name/license.html
static/plugin_name/about.html
Rule 5: The plugin can only rely on the existence of the global objects defined in scaffolding "db.py", i.e.
a database connection called db
an Authinstance calledauth
a Crudinstance calledcrud
a Serviceinstance calledservice
Some plugins may be more sophisticated and have a configuration parameter in case more than one db instance exists.
Rule 6: If a plugin needs configuration parameters, these should be set via a PluginManager as described below.
By following the above rules we can make sure that:
adminrecognizes all theplugin_namefiles and folder as part of a single entity.
plugins do not interfere with each other.
The rules above do not solve the problem of plugin versions and dependencies. That is beyond our scope.
Component plugins
Component plugins are plugins that define components. Components usually access the database and define with their own models.
Here we turn the previous comments component into a comments_plugin by using the same code we wrote before, but following all of the previous rules.
First, we create a model called "models/plugin_comments.py":
db.define_table('plugin_comments_comment',
Field('body','text', label='Your comment'),
auth.signature)
def plugin_comments():
return LOAD('plugin_comments','post',ajax=True)
(notice the last two lines define a function that will simplify the embedding of the plugin)
Second, we define a "controllers/plugin_comments.py"
def post():
if not auth.user:
return A('login to comment',_href=URL('default','user/login'))
comment = db.plugin_comments_comment
return dict(form=SQLFORM(comment).process(),
comments=db(comment).select())
Third, we create a view called "views/plugin_comments/post.load":
{{for comment in comments:}}
<div class="comment">
on {{=comment.created_on}} {{=comment.created_by.first_name}}
says <span class="comment_body">{{=comment.body}}</span>
</div>
{{pass}}
{{=form}}
Now we can use admin to pack the plugin for distribution. Admin will save this plugin as:
web2py.plugin.comments.w2p
We can use the plugin in any view by simply installing the plugin via the edit page in admin and adding this to our own views
{{=plugin_comments()}}
Of course we can make the plugin more sophisticated by having components that take parameters and configuration options. The more complex the components, the more difficult it becomes to avoid name collisions. The Plugin Manager described below is designed to avoid this problem.
Plugin manager
The PluginManager is a class defined in gluon.tools. Before we explain how it works inside, we will explain how to use it.
Here we consider the previous plugin_comments and we make it better. We want to be able to customize:
db.plugin_comments_comment.body.label
without having to edit the plugin code itself.
Here is how we can do it:
First, rewrite the plugin "models/plugin_comments.py" in this way:
def _():
from gluon.tools import PluginManager
plugins = PluginManager('comments', body_label='Your comment')
db.define_table('plugin_comments_comment',
Field('body','text',label=plugins.comments.body_label),
auth.signature)
return lambda: LOAD('plugin_comments','post.load',ajax=True)
plugin_comments = _()
Notice how all the code except the table definition is encapsulated in a single function called _ so that it does not pollute the global namespace. Also notice how the function creates an instance of a PluginManager.
Now in any other model in your app, for example in "models/db.py", you can configure this plugin as follows:
from gluon.tools import PluginManager
plugins = PluginManager()
plugins.comments.body_label = T('Post a comment')
The plugins object is already instantiated in the default scaffolding app in "models/db.py"
The PluginManager object is a thread-level singleton Storage object of Storage objects. That means you can instantiate as many as you like within the same application but (whether they have the same name or not) they act as if there were a single PluginManager instance.
In particular each plugin file can make its own PluginManager object and register itself and its default parameters with it:
plugins = PluginManager('name', param1='value', param2='value')
You can override these parameters elsewhere (for example in "models/db.py") with the code:
plugins = PluginManager()
plugins.name.param1 = 'other value'
You can configure multiple plugins in one place.
plugins = PluginManager()
plugins.name.param1 = '...'
plugins.name.param2 = '...'
plugins.name1.param3 = '...'
plugins.name2.param4 = '...'
plugins.name3.param5 = '...'
When the plugin is defined, the PluginManager must take arguments: the plugin name and optional named arguments which are default parameters. However, when the plugins are configured, the PluginManager constructor must take no arguments. The configuration must precede the definition of the plugin (i.e. it must be in a model file that comes first alphabetically).
Layout plugins
Layout plugins are simpler than component plugins because usually they do not contain code, but only views and static files. Yet you should still follow good practice:
First, create a folder called "static/plugin_layout_name/" (where name is the name of your layout) and place all your static files there.
Second, create a layout file called "views/plugin_layout_name/layout.html" that contains your layout and links the images, CSS and JavaScript files in "static/plugin_layout_name/"
Third, modify the "views/layout.html" so that it simply reads:
{{extend 'plugin_layout_name/layout.html'}}
{{include}}
The benefit of this design is that users of this plugin can install multiple layouts and choose which one to apply simply by editing "views/layout.html". Moreover, "views/layout.html" will not be packed by admin together with the plugin, so there is no risk that the plugin will override the user's code in the previously installed layout.
Plugin repositories, plugin install via admin
While there is no single repository of web2py plugins you can find many of them at one of the following URLs:
http://web2pyslices.com (this is the leading repository and is integrated to the web2py admin application for one-click installs)
http://web2py.com/plugins
http://web2py.com/layouts
Recent versions of web2py admin allow automatic fetch and install of plugins from web2pyslices. To add a plugin to an app, edit it via the admin application, and choose Download Plugins, currently at the bottom of the screen.
To publish your own plugins, make an account at web2pyslices.
Here is a screenshot showing some of the auto-installable plugins:
top
|
I implemented a FTP Server in Python using pyftpdlib.ftpserver
This works fine with mput/put operations but fails with mget/get. Following exception is thrown:
[]10.203.200.136:62408 Connected. 10.203.200.136:62408 ==> 220 pyftpdlib 0.5.2 ready. 10.203.200.136:62408 <== USER user 10.203.200.136:62408 ==> 331 Username ok, send password. 10.203.200.136:62408 <== PASS
**10.203.200.136:62408 ==> 230 Login successful. [user]@10.203.200.136:62408 User user logged in. 10.203.200.136:62408 <== TYPE A 10.203.200.136:62408 ==> 200 Type set to: ASCII. 10.203.200.136:62408 <== PORT 10,203,200,136,243,206 10.203.200.136:62408 ==> 200 Active data connection established. 10.203.200.136:62408 <== NLST RS.pcap [user]@10.203.200.136:62408 OK NLST "/RS.pcap". Transfer starting. 10.203.200.136:62408 ==> 125 Data connection already open. Transfer starting. 10.203.200.136:62408 ==> 226 Transfer complete. 10.203.200.136:62408 <== TYPE A 10.203.200.136:62408 ==> 200 Type set to: ASCII. 10.203.200.136:62408 <== PORT 10,203,200,136,243,208 10.203.200.136:62408 ==> 200 Active data connection established. 10.203.200.136:62408 <== RETR RS.pcap [user]@10.203.200.136:62408 OK RETR "/RS.pcap". Download starting. 10.203.200.136:62408 ==> 125 Data connection already open. Transfer starting. 10.203.200.136:62408 ==> 426 Internal error; transfer aborted.
Traceback (most recent call last):
File "C:\Python31\lib\asynchat.py", line 244, in initiate_send
data = buffer(first, 0, obs)
File "C:\Python31\lib\asynchat.py", line 56, in buffer
memoryview(obj)
TypeError: cannot make memory view because object does not have the buffer interface
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python31\lib\pyftpdlib\ftpserver.py", line 2077, in push_dtp_data
self.data_channel.push_with_producer(data)
File "C:\Python31\lib\asynchat.py", line 211, in push_with_producer
self.initiate_send()
File "C:\Python31\lib\asynchat.py", line 246, in initiate_send
data = first.more()
File "C:\Python31\lib\pyftpdlib\ftpserver.py", line 1143, in more
return bytes(data, BYTES_ENCODING)
TypeError: encoding or errors without a string argument
Now in asynchat.py (which is called internally), in initiate_send, buffer is called which throws an exception when memoryview(obj) is done; obj being a FileProducer type of object.
Can anyone please suggest what possible error is it? Is there a problem in python library? How to solve it?
|
July 21st, 2009 at 6:30 pm by Dr. Drang
Update 9/21/09
While all the logic and thinking behind the scripts in this post is still true, the scripts themselves have been updated. I’ve put everything in a GitHub repository to make it easy to download all at once.
For years I’ve been recording BBC Radio 2’s music shows with Rogue Amoeba’s Audio Hijack Pro. I import the recordings into iTunes and transfer them to my iPod or iPhone to listen to while biking, driving, or working. More recently, I’ve been copying the tracklists from some shows’ web pages and adding that to the iTunes Lyrics field so I can quickly look up the song I’m listening to. And, of course, I’ve been working on ways to automate the process.
In the past couple of months, Radio 2 revamped its web site; the web pages for all the shows now have a uniform layout, with links to the Listen Again streams and lists of the songs played. This makes the site much easier to use, and it also gives me an opportunity to automate my recordings. This post describes my recording setup and the various scripts I use to do the recording and extract the song lists.
I’ve described this sort of thing before, but that was before the Radio 2 web redesign. This post supersedes that earlier work.
Radio 2 web layout
Before the redesign, each show on Radio 2 had its own web page, or set of web pages. Typically, these pages would have a link to the Listen Again stream of the most recent episode. They might also include a list of the songs played in that most recent episode. The nice thing about this arrangement, for the purposes of automation, was that each show had a single URL for its Listen Again stream and a single URL for its general information page. The bad thing about the arrangement was that each show’s information page was organized in its own way; if you wanted to screen scrape the song list, you had to write a different scraping program for each show.
Now things are different. Instead of a page for each show, there’s a page for each episode of each show. The list of songs played on that episode are contained within a particular <div>. The title and artist of each song is set inside <span> tags with classes that identify the type of information.
If the episode was aired within the past week, its page will also have a link to the streaming audio of that episode. Because this layout is the same for every show, we can write a single script to scrape the song list from any show. The only problem for automating this process is finding the URL for episode you want to record.
The key to finding episode URLs is the daily schedule page. Its URL is based on the date—today’s is http://www.bbc.co.uk/radio2/programmes/schedules/2009/07/21. The daily schedule page has links to every program broadcast that day, and its layout is logical and easy to scrape. Here, for example, is the schedule for last Saturday:
Each episode has a unique eight-character code associated with it. The code is part of the URL for the stream and part of the URL for the program page with the playlist. We’ll use both of these URLs to do our recording and post-processing.
Strategy
Audio Hijack Pro can be scheduled to record streams at our convenience—in the middle of the night, for example. To do that, it needs the URL of the stream we want to record. If this is a static URL, we just give it that; but if it changes from day to day or week to week—as the Radio 2 streams do—we need to write an AppleScript that will deliver the current URL to Audio Hijack Pro. The name and location of that script is entered on Audio Hijack Pro’s Input tab.
Audio Hijack Pro can also run scripts to post-process a track after it’s been recorded. We’ll use this capability to:
extract the list of songs from the program page and turn it into plain text
import the recorded show into iTunes
set the lyrics of the show to the song list
set the “Remember playback position” option
set the “Skip when shuffling” option
The name of the post-processing script is entered on Audio Hijack Pro’s Recording tab.
Unfortunately, the URL-finding script and the post-processing script have to be written in AppleScript because that’s the only kind of script Audio Hijack Pro understands. Since only the brave or the stupid would attempt serious HTML parsing and text processing in AppleScript, we’ll do the heavy lifting in Python, and then write AppleScripts that use do shell script to run the Python code.
Since both the URL-finding script and the post-processing script need the program’s eight-character code, we’ll write a Python module that contains all the programming needed to get that code, and we’ll import that module into both of the scripts.
Module
The Radio 2 module consists of three parts:
a dictionary with information about the shows I’m interested in;
a function that returns the URL for the schedule page with the most recent episode of a given show; and
a function that returns the eight-character code for that episode.
Here’s the module:
1: import datetime
2: import urllib
3: import BeautifulSoup
4: import re
5:
6: # The particulars for the shows we're interested in.
7: showinfo = {'jukebox': (5, 'Mark Lamarr'),
8: '70s': (6, re.compile(r'Sounds of the 70s')),
9: '60s': (5, re.compile(r'Sounds of the 60s')),
10: 'soul': (2, 'Trevor Nelson')}
11:
12:
13: def recentScheduleURL(showday, day=datetime.date.today()):
14: 'Return the schedule URL for the most recent showday (0=Mon, 6=Sun) on or before day.'
15:
16: backup = datetime.timedelta((day.weekday() - showday) % 7)
17: programDay = day - backup
18: return 'http://www.bbc.co.uk/radio2/programmes/schedules/%d/%02d/%02d' % (programDay.year, programDay.month, programDay.day)
19:
20:
21: def programCode(show):
22: 'Return the code of the program page for showname on the most recent showday.'
23: try:
24: schedHTML = urllib.urlopen(recentScheduleURL(showinfo[show][0])).read()
25: schedSoup = BeautifulSoup.BeautifulSoup(schedHTML)
26: return schedSoup.find(name='span', text=showinfo[show][1]).parent.parent['href'].split('/')[-1]
27: except KeyError:
28: return None
The recentSchedule function makes use of what we know about the form of the URL for the daily schedule page. If we call recentScheduleURL(5) today, it will return
http://www.bbc.co.uk/radio2/programmes/schedules/2009/07/18
which is the schedule for last Saturday, the most recent Saturday (5) on or before today.
The programCode function opens the URL returned by recentScheduleURL and parses the HTML to find the link to the show of interest. It then pulls the eight-character episode code out of that link.
The programCode function uses the show day and name (which can be either a string or a regular expression), which are kept in the showinfo dictionary. I have the information for only four shows in that dictionary, but it can easily be extended.
The name of the module is “radio.py,” and it should be put in the /Library/Python/2.5/site-packages directory.
(If you’re on Linux or Windows, and want to modify my scripts to work on your system, you’ll have to put “radio.py” in the appropriate site-packages directory on your hard drive. You can find it by launching an interactive session of Python and executing
>>> import sys
>>> for p in sys.path:
... print p
...
This will print out the full path name of each directory Python searches for modules, one per line. The one that ends with site-packages is the one you want.)
Script for getting the streaming URL
Now that we have the “radio2.py” module, writing a script that returns the URL of the audio stream of the most recent episode of a given show is easy. Here’s the Python program, called “radio2-stream” and kept in my ~/bin directory.
1: #!/usr/bin/python
2:
3: import radio2
4: import sys
5:
6: # Set the info from the command line argument.
7: show = sys.argv[1]
8:
9: print 'http://bbc.co.uk/iplayer/console/' + radio2.programCode(show)
It takes as its sole argument a string that identifies the show of interest. The strings it recognizes are the keys of the showinfo dictionary defined in “radio.py.”
“jukebox” for Mark Lamarr’s God’s Jukebox program
“70s” for Johnny Walker’s Sounds of the 70s
“60s” for Brian matthew’s Sounds of the 60s
“soul” for Trevor Nelson’s eponymous soul/funk show
If I execute
radio2-stream jukebox
today, I get
http://bbc.co.uk/iplayer/console/b00lqcgw
With this Python script in place, we can write the AppleScript wrapper that AHP will run to get the streaming URL for God’s Jukebox.
return do shell script "~/bin/radio2-stream jukebox"
This is the entire “God’s Jukebox URL” script shown in the Audio Hijack Pro Input tab above. It can be stored anywhere; I keep it in the ~/Library/Scripts/Applications/Audio Hijack Pro folder.
Script for getting the playlist
The Python script for extracting the playlist from the episode page is called “radio2-tracklist” and is kept in my ~/bin directory.
1: #!/usr/bin/python
2:
3: import radio2
4: import sys
5: from BeautifulSoup import BeautifulSoup, BeautifulStoneSoup
6: from urllib import urlopen
7:
8: def trackList(show):
9: 'Return text with the track and artist names for each song played.'
10:
11: # Get all the track info
12: progURL = 'http://bbc.co.uk/programmes/' + radio2.programCode(show)
13: progHTML = urlopen(progURL).read()
14: progSoup = BeautifulSoup(progHTML)
15: tracklist = progSoup.findAll('div', 'summary')
16:
17: # Create a list of songs with title and artist.
18: songinfo = []
19: for t in tracklist:
20: track = t.find('span', 'track').string
21: artist = t.find('span', 'artist').string
22: songinfo.append('%s\nby %s' % (track, artist))
23:
24: # Generate a plain text list of the song information.
25: songs = '\n\n'.join(songinfo)
26: songs = BeautifulStoneSoup(songs, convertEntities=BeautifulStoneSoup.HTML_ENTITIES)
27:
28: # Get the date of the show.
29: bdate = progSoup.find('div', 'date').span.string
30:
31: return '%s\n\n%s' % (bdate, songs)
32:
33: # Set the info from the command line argument.
34: show = sys.argv[1]
35:
36: print trackList(show).encode('utf-8')
Like “radio2-stream,” it takes as its single argument the string identifying the show of interest. It uses the programCode function of “radio.py” to construct the URL of the episode page and BeautifulSoup to parse the page’s HTML and get the title and artist for each track in the playlist. It then spits this information out in the form
Song Titleby Artist
with a blank line between each track. The episode date is put at the beginning of the output.
So if we execute
radio2-tracklist jukebox
today, we’ll get
Sat 18 Jul 2009Backlashby Freddie HubbardWorries In The Danceby Frankie PaulRan Kan Kanby Tito Puente
and so on.
Update 9/3/09
A week or so ago, Radio 2 changed its internal nomenclature. The div with the tracklist, which used to have an id of type-musicsegment, now has an id of summary. That change is now reflected in Line 15 of radio2-tracklist.
Script for importing into iTunes
With “radio2-tracklist” in place, we can write the AppleScript that AHP will run after the show is recorded. Because there’s no way to pass arguments to an AHP Recording Script, we’ll have to write a separate one for each show. For God’s Jukebox, the script looks like this:
1: (* Audio Hijack Script *** (C) Copyright 2003-2007, Rogue Amoeba Software, LLC
2: "set shufflable" and "set bookmarkable" lines added on 20070725
3: "add to Radio shows" line added on 20080904
4: song list processing updated on 20090715 *)
5:
6: on process(theArgs)
7:
8: --Get the list of songs from the BBC Radio 2 page
9: try
10: set songlist to do shell script "~/bin/radio2-tracklist jukebox"
11: on error
12: set songlist to "Couldn't retrieve song list"
13: end try
14:
15:
16: --Coerce args to be a list
17: if class of theArgs is not list then
18: set theArgs to {theArgs}
19: end if
20:
21: --Into iTunes ye files shall go
22: tell application "iTunes"
23: set theFile to item 1 of theArgs
24: set aTrack to (add theFile)
25: delay 60
26: set bookmarkable of aTrack to true
27: set shufflable of aTrack to false
28:
29: add (get location of aTrack) to playlist "Radio shows"
30: set lyrics of aTrack to songlist
31:
32: end tell
33:
34: end process
This is the “God’s Jukebox” script shown in the Audio Hijack Pro Recording tab screenshot above. It has to be kept in the ~/Library/Application Support/Audio Hijack Pro/Recording Scripts folder in order to be accessible through the popup menu.
As the comments at the top of the script indicate, this is just an extended version of the sample script Rogue Amoeba provides for importing AHP recordings into iTunes. The additions are
Lines 8–13, which execute “radio2-tracklist” and put the output into the songlistvariable.
Line 25, which is an ad hocdelay that gives iTunes a chance to import the track before changing its settings.
Line 26, which is equivalent to setting the “Remember playback position” option.
Line 27, which is equivalent to setting the “Skip when shuffling” option.
Line 29, which puts the new track into the “Radio shows” playlist.
Line 30, which sets the lyrics of the track to the contents of the songlistvariable.
If you know your way around iTunes, you may be wondering why we’re putting the song list in the lyrics field instead of the “long description” field. The long description field does seem like the perfect place for this information, but unfortunately, the iPhone doesn’t display it. So we have to use the lyrics field instead.
And so…
This system—a commercial program that calls AppleScripts that call Python scripts that call a Python module—is more complex than most of the programming I show on this blog, but it provides a seamless experience once it’s set up. The programs get recorded, popped into iTunes with song lists, and put into an iTunes playlist that’s synced to my iPod/iPhone the next time it’s docked. It took a some effort to get it working, but it’s been smooth sailing ever since.
|
chaoswizard
Re : TVDownloader: télécharger les médias du net !
Bonsoir,
Non ce n'est pas possible, RtmpDump (et je suppose Flvstreamer) n'arrive pas à parser l'URL si elle n'est pas découpée.
J'avais étudié ce problème en mettant au point Arte Live Web pour TVO.
Bon courage pour votre projet
Je viens pourtant de tester, ça marche.
Ça ne doit pas marcher qu'avec certaines URL.
RTMPDump v2.3
(c) 2010 Andrej Stepanchuk, Howard Chu, The Flvstreamer Team; license: GPL
ERROR: You must specify a hostname (--host) or url (-r "rtmp://host[:port]/playpath") containing a hostname
Dernière modification par chaoswizard (Le 26/07/2010, à 20:03)
Ubuntu ==> Debian ==> Archlinux
Hors ligne
BmD_Online
Re : TVDownloader: télécharger les médias du net !
Est-ce que tu ne peux pas aussi le faire avec :
import urllib
urllib.unquote( chaine )
Je viens justement de découvrir ça !
En fait, c'est mon premier programme en python et je ne connais pas toutes les fonctions utilisables. J'avance à tâtons.
Hors ligne
chaoswizard
Re : TVDownloader: télécharger les médias du net !
chaoswizard a écrit :
Est-ce que tu ne peux pas aussi le faire avec :
import urllib
urllib.unquote( chaine )
Je viens justement de découvrir ça !
En fait, c'est mon premier programme en python et je ne connais pas toutes les fonctions utilisables. J'avance à tâtons.
Ce n'est pas un problème ; l'essentiel, c'est d'avoir des personnes de bonne volonté pour nous aider à faire les plugins.
Ubuntu ==> Debian ==> Archlinux
Hors ligne
BmD_Online
Re : TVDownloader: télécharger les médias du net !
Alors, voilà un premier jet pour le plugin arte. Il marche, dans le sens où il fournit la liste des émissions avec les liens qu'il faut.
Par contre, les téléchargements ne marchent pas, pour les raisons évoquées plus haut.
Pour Arte+7, c'est une autre erreur qu'on a :
Connecting ...
ERROR: HandleCtrl: Ignoring SWFVerification request, no CRYPTO support!
Starting download at: 0.000 kB
(...)
ERROR: RTMP_ReadPacket, failed to read RTMP packet header
Download may be incomplete (downloaded about 2.20%), try resuming
Fichier plugins/Arte.py
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
#########################################
# Licence : GPL2 ; voir fichier LICENSE #
#########################################
#~ Ce programme est libre, vous pouvez le redistribuer et/ou le modifier selon les termes de la Licence Publique Générale GNU publiée par la Free Software Foundation (version 2 ou bien toute autre version ultérieure choisie par vous).
#~ Ce programme est distribué car potentiellement utile, mais SANS AUCUNE GARANTIE, ni explicite ni implicite, y compris les garanties de commercialisation ou d'adaptation dans un but spécifique. Reportez-vous à la Licence Publique Générale GNU pour plus de détails.
#~ Vous devez avoir reçu une copie de la Licence Publique Générale GNU en même temps que ce programme ; si ce n'est pas le cas, écrivez à la Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, États-Unis.
###########
# Modules #
###########
import os
from Plugin import Plugin
from Fichier import Fichier
from Web import Web
from urllib import quote,unquote
import re,unicodedata
import time,rfc822 # for RFC822 datetime format (rss feed)
from htmlentitydefs import name2codepoint
##########
# Classe #
##########
class Arte( Plugin ):
"""Classe abstraite Plugin dont doit heriter chacun des plugins"""
##
## Arte Live Web
##
#
# A/ Recherche des émissions
#
# 1. On liste les catégories à partir de la page d'accueil.
# Chaque catégorie est une "émission" de la chaine Arte Live Web
#
# B/ Recherche des fichiers d'une émission
#
# 1. On recherche la page du flux RSS à partir de la page de la catégorie choisie.
# 2. On extrait la liste des fichiers (les pages de chaque enregistrement proposé)
# 3. On recherche le numéro eventID à partir de la page de l'enregistrement
# 4. On recherche les détails de l'enregistrement dans la page xml associée à l'eventID
#
##
## Arte+7
##
## Utilisation de la méthode de Pascal92
## http://www.encodage.org/phpBB/viewtopic.php?f=26&t=90
##
#
# A/ Recherche des émissions
#
# 1. On liste les chaines à partir de la page d'accueil.
# Chaque chaine est une "émission" de la chaine Arte+7
#
# B/ Recherche des fichiers d'une émission
#
# 1. On charge la page spéciale "videoArtePlusSeptChaineBaseUrl" contenant les fichiers de la chaine choisie
# 2. On extrait la liste des fichiers (les pages ainsi que nom et date de chaque enregistrement proposé)
# 3. On recherche le numéro de référence de la vidéo à partir de la page de l'enregistrement
# 4. On recherche les détails de l'enregistrement dans la page xml associée à la référence
#
##
## Arte Live Web
##
nomArteLiveWeb = "Arte Live Web"
# Page permettant de lister les catégories
listeArteLiveWebCategoriesUrl = "http://liveweb.arte.tv/"
# Expression régulière pour extraire les catégories
listeArteLiveWebCategoriesPattern = re.compile("<a href=\"http://liveweb.arte.tv/fr/cat/(.*?)\">(.*?)</a>", re.DOTALL)
# Rang dans le résultat de l'expression régulière précédente
categorieArteLiveWeb_LIEN = 0
categorieArteLiveWeb_NOM = 1
# Base de la page catégorie, permettant de retrouver le lien du flux RSS
videoArteLiveWebCategorieBaseUrl = "http://liveweb.arte.tv/fr/cat/"
# Expression régulière pour extraire le lien du flux RSS
videoArteLiveWebRSSPattern = re.compile("<a href=\"(http://download.liveweb.arte.tv/o21/liveweb/rss/home.*?\.rss)\"", re.DOTALL)
# Expression régulière pour extraire le lien vers la page de la video, ainsi que sa date
videoArteLiveWebVideosPattern = re.compile("<link>(http://liveweb.arte.tv/fr/video/.*?)</link>.*?<pubDate>(.*?)</pubDate>", re.DOTALL)
#~ videoArteLiveWebEventIDPattern = re.compile("eventID=(.*?)&")
#~ videoArteLiveWebEventIDPattern = re.compile("new LwEvent('(.*?)', '');")
videoArteLiveWebEventIDPattern = re.compile("/media/event/(.*?)/", re.DOTALL)
videoArteLiveWebInfosBaseUrl = "http://arte.vo.llnwd.net/o21/liveweb/events/event-" # ".xml"
videoArteLiveWebTitrePattern = re.compile("<nameFr>(.*?)</nameFr>", re.DOTALL)
videoArteLiveWebLienPattern = re.compile("<urlHd>(.*?)</urlHd>", re.DOTALL)
#~ videoArteLiveWebDatePattern = re.compile("<dateEvent>(.*?)</dateEvent>", re.DOTALL)
##
## Arte+7
##
nomArtePlusSept = "Arte+7"
# Page permettant de lister les chaines
listeArtePlusSeptChainesUrl = "http://videos.arte.tv/fr/videos/arte7"
# Expression régulière pour extraire les chaines
listeArtePlusSeptChainesPattern = re.compile("<a href=\"/fr/videos/chaines/(.*?)\".*?>(.*?)</a>", re.DOTALL)
# Rang dans le résultat de l'expression régulière précédente
categorieArtePlusSept_LIEN = 0
categorieArtePlusSept_NOM = 1
# Expression régulière pour extraire le channelID du lien de la chaine
chaineArtePlusSeptChannelIDPattern = re.compile(".*?/index-(.*?)\.html", re.DOTALL)
# Base de la page chaine, permettant de retrouver les fichiers (lien donné par "listViewUrl" dans la page principale)
videoArtePlusSeptChaineBaseUrl = "http://videos.arte.tv/fr/do_delegate/videos/arte7/index-3211552,view,asList.html?hash=fr/list/date//1/250/channel-%channel%-program-"
# Expression régulière pour extraire le lien vers la page de la video, son titre ainsi que sa date
videoArtePlusSeptVideosPattern = re.compile("<a href=\"(/fr/videos/.*?\.html)\"><span class=\"teaserTitle\">(.*?)</span></a>.*?<td class=\"col2\"><em>(.*?)</em></td>", re.DOTALL)
# Base de la page permettant de rechercher la référence de la video
videoArtePlusSeptVideoBaseUrl = "http://videos.arte.tv"
# Expression régulière pour extraire la référence de la vidéo à lire
videoArtePlusSeptVideoRefPattern = re.compile("addToPlaylistOpen {ajaxUrl:'/fr/do_addToPlaylist/videos/.*?-(.*?)\.html'}", re.DOTALL)
# Base de la page XML décrivant la vidéo, ses liens
videoArtePlusSeptXMLBaseURL = "http://videos.arte.tv/fr/do_delegate/videos/360_geo-%video%,view,asPlayerXml.xml"
videoArtePlusSeptLienPattern = re.compile("<url quality=\"hd\">(.*?)</url>", re.DOTALL)
# Nombre maximum de fichiers à rechercher (0 = aucune limite)
maxDepth = 0
# Ordre des éléments dans le tuple "chaine"
chaine_NOM = 1
chaine_LIEN = 0
nom = "Arte"
url = "http://www.arte.tv/"
def __init__( self ):
Plugin.__init__(self)
cache = self.chargerCache()
if cache:
self.listeChaines = cache
else:
self.listeChaines = {}
self.rafraichir()
self.listeFichiers = {}
def htmlentitydecode(self, s):
# http://wiki.python.org/moin/EscapingHtml
return re.sub('&(%s);' % '|'.join(name2codepoint),
lambda m: unichr(name2codepoint[m.group(1)]), s)
def rafraichir( self ):
self.afficher("Création de la liste des chaines...")
web = Web()
##
## Arte Live Web
##
self.afficher("Récupération de la liste des catégories "+self.nomArteLiveWeb+"...")
# On crée la chaine
self.listeChaines[self.nomArteLiveWeb] = []
# On recherche toutes les catégories
for item in re.findall(self.listeArteLiveWebCategoriesPattern, web.getPage(self.listeArteLiveWebCategoriesUrl)):
lien = item[self.categorieArteLiveWeb_LIEN]
nom = item[self.categorieArteLiveWeb_NOM]
nom = unicode(nom, "iso-8859-1", "replace")
itemLive = []
itemLive.insert (self.chaine_LIEN, lien)
itemLive.insert (self.chaine_NOM, nom)
# On ajoute la catégorie trouvée si elle n'est pas déjà présente
if (itemLive not in self.listeChaines[self.nomArteLiveWeb]):
self.listeChaines[self.nomArteLiveWeb].append(itemLive)
##
## Arte+7
##
self.afficher("Récupération de la liste des chaines "+self.nomArtePlusSept+"...")
# On crée la chaine
self.listeChaines[self.nomArtePlusSept] = []
# On recherche toutes les catégories
for item in re.findall(self.listeArtePlusSeptChainesPattern, web.getPage(self.listeArtePlusSeptChainesUrl)):
lien = item[self.categorieArtePlusSept_LIEN]
nom = item[self.categorieArtePlusSept_NOM]
nom = unicode(nom, "utf8", "replace")
nom = self.htmlentitydecode(nom)
#~ nom = unquote(nom)
itemPlusSept = []
itemPlusSept.insert (self.chaine_LIEN, lien)
itemPlusSept.insert (self.chaine_NOM, nom)
# On ajoute la catégorie trouvée si elle n'est pas déjà présente
if (itemPlusSept not in self.listeChaines[self.nomArtePlusSept]):
self.listeChaines[self.nomArtePlusSept].append(itemPlusSept)
self.sauvegarderCache(self.listeChaines)
def getLienEmission(self, emission):
emission = unicode( emission, "utf8", "replace" )
# Cherche dans quelle chaine se trouve l'émission
#~ self.afficher("Recherche de : "+emission)
#~ for chaine in self.listeChaines.keys():
#~ #~ self.afficher("Chaine : "+chaine)
chaine = self.derniereChaine
for item in self.listeChaines[chaine]:
s = item[self.chaine_NOM]
#~ s = unicode( s, "utf8", "replace" )
#~ self.afficher("Item : "+s)
if (cmp(s, emission)==0):
s = item[self.chaine_LIEN]
if (s==""):
return None
else:
#~ return self.videoArteLiveWebCategorieBaseUrl+quote(s.encode( 'ascii','ignore' ))
return quote(s.encode( 'ascii','ignore' ))
def listerChaines( self ):
t = self.listeChaines.keys()
t.sort()
return t
def listerEmissions( self, chaine ):
t = []
self.derniereChaine = chaine
if self.listeChaines.has_key(chaine):
for item in self.listeChaines[chaine]:
s = item[self.chaine_NOM]
#~ t.append(s.decode("iso-8859-1"))
t.append(s)
t.sort()
return t
def listerFichiersArteLiveWeb( self, emission ):
"""Renvoi la liste des fichiers disponibles pour une emission donnnee"""
# Renvoi la liste des fichiers (utilisation de la classe Fichier)
# [ Fichier ( nom, date, lien) , Fichier( ... ), ... ]
if self.listeFichiers.has_key(emission):
return self.listeFichiers[emission]
web = Web()
lien = self.getLienEmission(emission)
if lien == None:
self.afficher ("Erreur de recherche du lien pour \""+emission+"\"")
else:
self.afficher("Récupération de la liste des fichiers pour \""+emission+"\"...")
# Reconstitution du lien complet
lien = self.videoArteLiveWebCategorieBaseUrl+lien
# On recherche l'adresse de la page RSS
self.afficher ("Recherche du flux RSS \""+emission+"\" à l'adresse "+lien)
feedURL = re.search(self.videoArteLiveWebRSSPattern, web.getPage(lien)).group(1)
# On recherche toutes les émissions contenues dans le flux RSS
self.afficher ("Recherche des émissions dans le flux : "+feedURL)
videos = re.findall(self.videoArteLiveWebVideosPattern, web.getPage(feedURL))
liste = []
if videos == None:
return liste
# Pour chacune des vidéos trouvées
curDepth = 0
for fichier in videos:
#~ curDepth = curDepth+1
curDepth += 1
if (self.maxDepth>0 and curDepth>self.maxDepth):
break
self.afficher ("Émission trouvée "+fichier[0])
# Recherche de l'eventID dans la page de l'emission
fichierInfosEventID_match = re.search (self.videoArteLiveWebEventIDPattern, web.getPage(fichier[0]))
if fichierInfosEventID_match == None:
continue
self.afficher ("... eventID : "+fichierInfosEventID_match.group(1))
# Chargement de la page XML de l'eventID trouvé
fichierInfos = web.getPage(self.videoArteLiveWebInfosBaseUrl+fichierInfosEventID_match.group(1)+".xml")
titre = re.search(self.videoArteLiveWebTitrePattern, fichierInfos)
if titre != None:
titre = titre.group(1)
else:
continue
lien = re.search(self.videoArteLiveWebLienPattern, fichierInfos)
if lien != None:
lien = lien.group(1)
else:
continue
#~ date = re.search(self.videoDatePattern, fichierInfos)
date = fichier[1]
if date != None:
rfc_date = rfc822.parsedate(date)
# Format année/mois/jour, mieux pour effectuer un tri
date = str(rfc_date[0])+"/"+str(rfc_date[1]).zfill(2)+"/"+str(rfc_date[2]).zfill(2)
else:
continue
if not(lien):
continue
self.afficher ("... Titre : "+titre)
self.afficher ("... Date : "+date)
self.afficher ("... Lien : "+lien)
liste.append(Fichier(titre, date, lien))
self.afficher(str(len(liste))+" fichiers trouvés.")
self.listeFichiers[emission] = liste
return liste
def listerFichiersArtePlusSept( self, emission ):
"""Renvoi la liste des fichiers disponibles pour une emission donnnee"""
# Renvoi la liste des fichiers (utilisation de la classe Fichier)
# [ Fichier ( nom, date, lien) , Fichier( ... ), ... ]
if self.listeFichiers.has_key(emission):
return self.listeFichiers[emission]
web = Web()
# Code de la "chaine" Arte+7
channel = re.search (self.chaineArtePlusSeptChannelIDPattern, self.getLienEmission(emission)).group(1)
# Construction du lien contenant toutes les émissions de cette chaine
lien = self.videoArtePlusSeptChaineBaseUrl.replace ("%channel%", channel)
if lien == None:
self.afficher ("Erreur de recherche du lien pour \""+emission+"\"")
else:
self.afficher("Récupération de la liste des fichiers pour \""+emission+"\"...")
# On recherche toutes les émissions de la chaine
self.afficher ("Recherche des émissions de la chaine \""+emission+"\" à l'adresse "+lien)
videos = re.findall(self.videoArtePlusSeptVideosPattern, web.getPage(lien))
liste = []
if videos == None:
return liste
# Pour chacune des vidéos trouvées
curDepth = 0
for fichier in videos:
#~ curDepth = curDepth+1
curDepth += 1
if (self.maxDepth>0 and curDepth>self.maxDepth):
break
self.afficher ("Émission trouvée "+fichier[0])
# Recherche de la référence de la vidéo dans la page de l'emission
fichierInfosVideoRef_match = re.search (self.videoArtePlusSeptVideoRefPattern, web.getPage(self.videoArtePlusSeptVideoBaseUrl+fichier[0]))
if fichierInfosVideoRef_match == None:
continue
self.afficher ("... videoRef : "+fichierInfosVideoRef_match.group(1))
#~ # Chargement de la page XML de la référence trouvée
fichierInfos = web.getPage(self.videoArtePlusSeptXMLBaseURL.replace("%video%",fichierInfosVideoRef_match.group(1)))
#~ file = open(self.fichierCache+"_web", "w")
#~ file.write (fichierInfos)
#~ file.close()
titre = fichier[1]
lien = re.search(self.videoArtePlusSeptLienPattern, fichierInfos)
if lien != None:
lien = lien.group(1)
else:
continue
date = fichier[2]
if not(lien):
continue
self.afficher ("... Titre : "+titre)
self.afficher ("... Date : "+date)
self.afficher ("... Lien : "+lien)
liste.append(Fichier(titre, date, lien))
self.afficher(str(len(liste))+" fichiers trouvés.")
self.listeFichiers[emission] = liste
return liste
def listerFichiers( self, emission ):
if (self.derniereChaine == self.nomArteLiveWeb):
return self.listerFichiersArteLiveWeb (emission)
elif (self.derniereChaine == self.nomArtePlusSept):
return self.listerFichiersArtePlusSept (emission)
else:
self.afficher("Chaine non prise en compte actuellement")
Hors ligne
sonydesouza
Re : TVDownloader: télécharger les médias du net !
Génial,
Je m'abonne !
Hors ligne
pascal92
Re : TVDownloader: télécharger les médias du net !
Pour Arte+7, c'est une autre erreur qu'on a :
Connecting ...
ERROR: HandleCtrl: Ignoring SWFVerification request, no CRYPTO support!
Starting download at: 0.000 kB
(...)
ERROR: RTMP_ReadPacket, failed to read RTMP packet header
Download may be incomplete (downloaded about 2.20%), try resuming
Pour Arte+7 il est nécessaire d'indiquer le player, le mieux est de le retrouver dans la page de l'émission mais celui-ci semble être toujours le même, actuellement :
-- swfVfy "http://videos.arte.tv/blob/web/i18n/view/player_8-3188338-data-4746614.swf"
@+
Hors ligne
BmD_Online
Re : TVDownloader: télécharger les médias du net !
BmD_Online a écrit :
Pour Arte+7, c'est une autre erreur qu'on a :
Connecting ...
ERROR: HandleCtrl: Ignoring SWFVerification request, no CRYPTO support!
Starting download at: 0.000 kB
(...)
ERROR: RTMP_ReadPacket, failed to read RTMP packet header
Download may be incomplete (downloaded about 2.20%), try resuming
Pour Arte+7 il est nécessaire d'indiquer le player, le mieux est de le retrouver dans la page de l'émission mais celui-ci semble être toujours le même, actuellement :
-- swfVfy "http://videos.arte.tv/blob/web/i18n/view/player_8-3188338-data-4746614.swf"
@+
A voir comment intégrer ça à l'appli ? Comment le plugin peut-il transmettre cette information au programme principal ?
Il faudrait ajouter ça dans la classe Fichier. Genre une propriété player, vide par défaut.
Hors ligne
chaoswizard
Re : TVDownloader: télécharger les médias du net !
A voir comment intégrer ça à l'appli ? Comment le plugin peut-il transmettre cette information au programme principal ?
Il faudrait ajouter ça dans la classe Fichier. Genre une propriété player, vide par défaut.
Pour l'instant, en rajoutant directement l'option au lien, ça doit passer.
Ubuntu ==> Debian ==> Archlinux
Hors ligne
S00000
Re : TVDownloader: télécharger les médias du net !
Amélioration: Choix du dossier de téléchargement.
Mon /home est plein
Hors ligne
chaoswizard
Re : TVDownloader: télécharger les médias du net !
Amélioration: Choix du dossier de téléchargement.
Mon /home est plein
Oui, cette option de devrait pas tarder (pas dans la prochaine version mais bientôt !)
Ubuntu ==> Debian ==> Archlinux
Hors ligne
Vermouth
Re : TVDownloader: télécharger les médias du net !
La version 0.2 est maintenant disponible !
Suivez le lien de la première page ou cliquer ici.
Pour les plugins que vous créez, me contacter pour que je les mettes sur le site. On créera une page de wiki dédié aux plugins.
PS: pour ceux qui veulent développer un plugin, lisez la très courte documentation disponible dans /usr/share/doc/tvdownloader après installation du paquet.
Dernière modification par Vermouth (Le 27/07/2010, à 12:48)
Hors ligne
Emralegna
Re : TVDownloader: télécharger les médias du net !
Bonjour,
Je le télécharge depuis le dépôt SVN mais il semble vouloir chercher dans [/i]/usr/share/tvdownloader alors qu'il est dans mon [i]/home, certe dans tvdownloader/usr/share/tvdownloader :
[~/tvdownloader/usr/share/tvdownloader] 10 07-27 12:55PM
% ./Main.py
Traceback (most recent call last):
File "./Main.py", line 27, in <module>
os.chdir( "/usr/share/tvdownloader" )
OSError: [Errno 2] No such file or directory: '/usr/share/tvdownloader'
Il ne faudrait peut-être reprendre la même structure de répertoire pour plus de lisibilité.
Hors ligne
ludovic889
Re : TVDownloader: télécharger les médias du net !
bonjour
j'ai tenté pluzz/france 2/jt 13 h/26-juillet
et j'obtiens
sh: msdl: Permission denied
Ce n'est pas grave de ne pas avoir l'heure si on a le temps.
Hors ligne
chaoswizard
Re : TVDownloader: télécharger les médias du net !
Bonjour,
Je le télécharge depuis le dépôt SVN mais il semble vouloir chercher dans [/i]/usr/share/tvdownloader
alors qu'il est dans mon [i]/home, certe danstvdownloader/usr/share/tvdownloader:<metadata lang=Shell prob=0.10 />
[~/tvdownloader/usr/share/tvdownloader] 10 07-27 12:55PM
% ./Main.py
Traceback (most recent call last):
File "./Main.py", line 27, in <module>
os.chdir( "/usr/share/tvdownloader" )
OSError: [Errno 2] No such file or directory: '/usr/share/tvdownloader'
Il ne faudrait peut-être reprendre la même structure de répertoire pour plus de lisibilité.
Oulà oui mais non, n'utilisez pas la verison SVN ; prenez les paquets !
ludovic889 a écrit :
bonjour
j'ai tenté pluzz/france 2/jt 13 h/26-juillet
et j'obtienssh: msdl: Permission denied
Il manque sans doute un petit chmod dans le script post install du paquet, on rajoute ça !
Dernière modification par chaoswizard (Le 27/07/2010, à 13:16)
Ubuntu ==> Debian ==> Archlinux
Hors ligne
Vermouth
Re : TVDownloader: télécharger les médias du net !
Problème avec msdl corrigé.
Hors ligne
ludovic889
Re : TVDownloader: télécharger les médias du net !
Problème avec msdl corrigé.
merci !!
entre temps, j'y suis parvenu tout seul
je télécharge un peu pour voir ce que ça donne
Ce n'est pas grave de ne pas avoir l'heure si on a le temps.
Hors ligne
Emralegna
Re : TVDownloader: télécharger les médias du net !
Emralegna a écrit :
Bonjour,
Je le télécharge depuis le dépôt SVN mais il semble vouloir chercher dans [/i]/usr/share/tvdownloader
alors qu'il est dans mon [i]/home, certe danstvdownloader/usr/share/tvdownloader:<metadata lang=Shell prob=0.10 />
[~/tvdownloader/usr/share/tvdownloader] 10 07-27 12:55PM
% ./Main.py
Traceback (most recent call last):
File "./Main.py", line 27, in <module>
os.chdir( "/usr/share/tvdownloader" )
OSError: [Errno 2] No such file or directory: '/usr/share/tvdownloader'
Il ne faudrait peut-être reprendre la même structure de répertoire pour plus de lisibilité.
Oulà oui mais non, n'utilisez pas la verison SVN ; prenez les paquets !
Oui mais non, il n'y a pas que des systèmes .deb compatibles. Ce qui n'a pas de dépôts je le compile à partir des sources, et ce qui ne se compile pas je le préserve dans un dossier fait pour ; c'est bien plus facile à gérer ainsi qu'à mettre à jour.
Puis avec tous les projets que je suis s'il fallait aller sur tous les sites (à la Windows) pour récupérer le .deb/.rmp/.jenesaisquoi, j'ai pas fini…
Ce n'est pas possible de rendre le dépôt de source fonctionnel ?
Dernière modification par Emralegna (Le 27/07/2010, à 22:35)
Hors ligne
Vermouth
Re : TVDownloader: télécharger les médias du net !
Ce n'est pas possible de rendre le dépôt de source fonctionnel ?
Si ça peut se faire avec un scipt (Make) d'installation mais je n'ai pas encore eu le temps de faire !
Si, en attendant, tu veut que ça marche, met en commentaire la ligne qui pose problème.
Par contre les icônes ne seront peut être pas afficher (because arborescence imposé par Qt Designer et qu'on ne garde pas la même pour le deb).
Hors ligne
Emralegna
Re : TVDownloader: télécharger les médias du net !
Pourquoi un script d'installation ? Je ne veux en rien l'installer car là ça devient aussi difficile à maintenir (en plus de te donner davantage de boulot à faire un script). C'est un programme python, on devrait juste pouvoir l'exécuter dans son propre répertoire non ?
(Ou j'ai râté quelque chose ? )
Dernière modification par Emralegna (Le 27/07/2010, à 22:41)
Hors ligne
BmD_Online
Re : TVDownloader: télécharger les médias du net !
chaoswizard a écrit :
Est-ce que tu ne peux pas aussi le faire avec :
import urllib
urllib.unquote( chaine )
Je viens justement de découvrir ça !
En fait, c'est mon premier programme en python et je ne connais pas toutes les fonctions utilisables. J'avance à tâtons.
Alors, finalement je viens de comprendre que unquote permet juste de "tansformer" une url, en remplaçant les caractères spéciaux.
Ce qu'il me faut, c'est un décodage des entités html (dans une page, pas une url). Genre pour l'espace, & pour le &, etc...
Et ça, urllib ne sait pas le faire.
Je reste donc pour l'instant avec ma fonction qui va bien "htmlentitydecode".
A coté, j'ai remplacé les web.getPage par self.getPage.
Je vais maintenant voir pour passer le player pour les liens arte+7.
Hors ligne
jajaX
Re : TVDownloader: télécharger les médias du net !
La version 0.2 est maintenant disponible !
Suivez le lien de la première page ou cliquer ici.
Pour les plugins que vous créez, me contacter pour que je les mettes sur le site. On créera une page de wiki dédié aux plugins.
PS: pour ceux qui veulent développer un plugin, lisez la très courte documentation disponible dans /usr/share/doc/tvdownloader après installation du paquet.
salut
problème de dépendance sous lucid pour cette version (avec le deb) :
error : dépendance non satisfaite : rtmpdump (>=2.3)
@+ jajaX [Membre de Breizhtux : LUG de Saint Brieuc]ACER Aspire 8930G 904G50Bn & HP dv7 2230f sous Kubuntu 14.04 The Trusty Tahr (64 bits) & KDE SC 4.13.2/Amarok 2.8ACER Aspire 5612 WLMI & HP Compaq NX6310 sous kubuntu 14.04 The Trusty Tahr (32 bits) & KDE SC 4.13.2/Amarok 2.8
Hors ligne
BmD_Online
Re : TVDownloader: télécharger les médias du net !
Vermouth a écrit :
La version 0.2 est maintenant disponible !
Suivez le lien de la première page ou cliquer ici.
Pour les plugins que vous créez, me contacter pour que je les mettes sur le site. On créera une page de wiki dédié aux plugins.
PS: pour ceux qui veulent développer un plugin, lisez la très courte documentation disponible dans /usr/share/doc/tvdownloader après installation du paquet.
salut
problème de dépendance sous lucid pour cette version (avec le deb) :
error : dépendance non satisfaite : rtmpdump (>=2.3)
Il faut installer la dernière version, qui se trouve ici :
http://security.ubuntu.com/ubuntu/pool/universe/r/rtmpdump/
Il serait pas mal de mettre ce lien dans le premier post du topic.
A la limite, on pourrait également noter le lien de flvstreamer :
http://security.ubuntu.com/ubuntu/pool/universe/f/flvstreamer/
Hors ligne
jajaX
Re : TVDownloader: télécharger les médias du net !
merci c'est tout bon
@+ jajaX [Membre de Breizhtux : LUG de Saint Brieuc]ACER Aspire 8930G 904G50Bn & HP dv7 2230f sous Kubuntu 14.04 The Trusty Tahr (64 bits) & KDE SC 4.13.2/Amarok 2.8ACER Aspire 5612 WLMI & HP Compaq NX6310 sous kubuntu 14.04 The Trusty Tahr (32 bits) & KDE SC 4.13.2/Amarok 2.8
Hors ligne
clapico
Re : TVDownloader: télécharger les médias du net !
abonnement
http://www.clapico.com/ : mon p'tit blog avec mes p'tits trucs et mes p'tites découvertes de p'tit Ubuntéro
Hors ligne
Vermouth
Re : TVDownloader: télécharger les médias du net !
Il faut installer la dernière version, qui se trouve ici :
http://security.ubuntu.com/ubuntu/pool/universe/r/rtmpdump/
Il serait pas mal de mettre ce lien dans le premier post du topic.
A la limite, on pourrait également noter le lien de flvstreamer :
http://security.ubuntu.com/ubuntu/pool/universe/f/flvstreamer/
Autant pour moi j'ai oublier.
Je vais corriger.
Sinon flvstreamer on ne l'utilisera plus. (edit)
Ce qu'il me faut, c'est un décodage des entités html (dans une page, pas une url). Genre pour l'espace, & pour le &, etc..
Ça c'est réglé. Ça arrive avec la prochaine version.
Dernière modification par Vermouth (Le 28/07/2010, à 12:09)
Hors ligne
|
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Bibliographie:
- La 3D libre avec Blender d'Olivier Saraja - ed Eyrolles - 35 € pour la 1ère édition. Disponible à la FNAC ou chez Eyrolles pour la 4ème édition.
- Blender, Créez des animations 3D de Marie-France et Jean-Michel Soler - ed. Pearson, coll le Logiciel Libre - Chez Eyrolles ou à la FNAC - 19 € seulement
- Introducing Character animation with Blender de Tony Mullen - ed Sybex coll Serious Kill - 2007 - chez Eyrolles - environ 40€
- The Blender gamekit - 2nd edition - édité par Casten Wartmann et la Blender Fondation - 2008 - acheté à la librairie Eyrolles à Paris pour environ 33 €
- Initiation à la programmation avec Python et C++ de Yves Bailly - ed. Pearson, coll. Le programmeur - 2008 - 21 € - se trouve facilement, à la FNAC ou chez Eyrolles.
- Beginning Game developpement with Python and Pygame de Will Mc Gugan - Ed. Apress - environ 35€ à la librairie Eyrolles - voir aussi (en anglais) le site de l'auteur, Will McGugan
Dernière modification par doudoulolita (Le 07/02/2011, à 22:44)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
- Cours du Site du Zéro sur Pygame
- Guide du débutant de Pygame et http://fr.wikibooks.org/wiki/Pygame/Gui … 3%A9butant
- Blog sur Pygame
- Mettre une image avec Pygame
- Tuto complexe sur Pygame
- Pygame -The python game book (anglais)
Dernière modification par doudoulolita (Le 28/07/2011, à 17:05)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
J'ai commenté les scripts le plus possible, en particulier les plus compliqués. La lecture du livre ou de tutos sur Pygame est cependant indispensable pour bien comprendre les étapes.
Je reprends les exercices proposés dans le livre avec de touts petits changements et en utilisant le nounours Miks, un personnage que j'ai créé pour le jeu Ultimate Smash Friends et un décor en cours de création également.
Les mouvements du personnages sont encore bien limités et il ne bouge pas les jambes, mais c'est un début !
Ici, on déplace Miks avec les touches du pavé directionnelles (les flèches)
Dans le programme 08, le nounours ne peut descendre en dessous du sol, il faudrait évidemment qu'il se cogne aussi contre les vaisseaux spatiaux.
Dernière modification par doudoulolita (Le 08/02/2011, à 02:06)
Hors ligne
tshirtman
Re : Faire une animation sur la création de jeux vidéo libres
salut, je pense qu'il y a une erreur dans ton lien, j'ai une 404.
pour les collisions, j'utilise la methode collidelist() sur le rectangle qui donne l'emplacement du personnage, et je passe en paramettre la liste des rectangles qui forment le niveau, si le résultat est différent de -1, alors il est en collision avec un rectangle, et il faut donc annuler son mouvement précédent… (enfin ça c'est le plus simple, dans usf, la conséquence est légèrement plus complexe).
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Mon dernier essai sur Pygame a pour but de réaliser un mini jeu de maniement de la souris pour des enfants de maternelles.
Le jeu contient une image d'arrière-plan contenant des rectangles bleus et des ronds rouges sur fond blanc. L'image est réalisée avec Gimp.
Le curseur de la souris est représenté par un nounours en position statique et neutre.
Quand l'enfant passe sur les parties blanches, c'est ce curseur qui apparaît.
Quand l'enfant passe la souris dans un rectangle bleu (sans cliquer), le curseur présente le nounours tout heureux (image fixe en png).
Quand l'enfant passe la souris dans un rond rouge, toujours le nounours, mais tout triste (troisième image fixe).
Jusque-là, tout se passe bien et je suis assez satisfaite de mon code.
Ensuite, je souhaite donner le choix entre 2 images d'arrière-plan, composées chacune de rectangles bleus et de ronds rouges sur fond blanc disposés différemment.
Lorsque l'on ouvre le jeu, l'écran présente les 2 arrière-plans en réduction. En dessous, les chiffres 1 et 2 sont inscrits pour indiquer quelle touche du pavé numérique activer. Bref, je propose 2 niveaux !
Je parviens à ce que l'écran affiche le bon arrière-plan quand on appuis sur la touche 1 ou 2 mais dès que la souris bouge (ce qui est pourtant le but du jeu), l'écran d'accueil revient !
Je ne parviens pas à conserver le choix du niveau et à continuer le jeu.
Voici mon code:
#!/usr/bin/ env python
# -*- coding: utf-8 -*-
# définit les images choisies pour l'arrière-plan et la souris
image_arriereplan = 'arriereplan.png'
image_arriereplan1 = 'arriereplan_rouge_bleu.png'
image_arriereplan2 = 'arriereplan_rouge_bleu2.png'
image_souris1 = 'miks_static.png'
image_souris2 = 'miks_smackup2.png'
image_souris3 = 'miks_roll2.png'
def rendu_miks():
# définit la position de la souris
x, y = pygame.mouse.get_pos()
# échantillonne la couleur
couleur_ecran = screen.get_at((x, y))
if couleur_ecran == (0, 0, 255, 255):
x-= souris2.get_width() / 2
y-= souris2.get_height() / 2
screen.blit(souris2, (x,y))
elif couleur_ecran == (255, 0, 0, 255):
x-= souris3.get_width() / 2
y-= souris3.get_height() / 2
screen.blit(souris3, (x,y))
else:
x-= souris1.get_width() / 2
y-= souris1.get_height() / 2
screen.blit(souris1, (x,y))
# importe la bibliothèque Pygame
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
# définit la taille de la fenêtre et son titre
screen = pygame.display.set_mode((800, 600), 0, 32)
pygame.display.set_caption("Miks aime le bleu")
# charge les images
arriereplan = pygame.image.load(image_arriereplan).convert()
arriereplan1 = pygame.image.load(image_arriereplan1).convert()
arriereplan2 = pygame.image.load(image_arriereplan2).convert()
souris1 = pygame.image.load(image_souris1).convert_alpha()
souris2 = pygame.image.load(image_souris2).convert_alpha()
souris3 = pygame.image.load(image_souris3).convert_alpha()
while True:
# pour fermer la fenêtre
for event in pygame.event.get():
if event.type == QUIT:
exit()
screen.blit(arriereplan, (0, 0))
rendu_miks()
# affiche l'image d'arrière-plan
if event.type == KEYDOWN:
if event.key == K_KP1:
screen.blit(arriereplan1, (0, 0))
rendu_miks()
elif event.key == K_KP2:
screen.blit(arriereplan2, (0, 0))
rendu_miks()
else:
screen.blit(arriereplan, (0, 0))
rendu_miks()
if event.type == KEYUP:
if event.key == K_KP1:
screen.blit(arriereplan1, (0, 0))
rendu_miks()
elif event.key == K_KP2:
screen.blit(arriereplan2, (0, 0))
rendu_miks()
else:
screen.blit(arriereplan, (0, 0))
rendu_miks()
pygame.display.update()
Hors ligne
tshirtman
Re : Faire une animation sur la création de jeux vidéo libres
je pense que tu veux plutot affecter arriereplan1, 2 ou 3 en à arriereplan en fonction de tes choix… si tu ne le dessine qu'une fois, il sera effacé dès la prochaine itération dans la boucle.
Hors ligne
LittleWhite
Re : Faire une animation sur la création de jeux vidéo libres
Bon je ne sais pas si il fallait ne pas donner la réponse, mais bon ... comme je n'avais pas compris ce qu'avais dit tshirtman, j'ai du lire le code (qui est simple, en plus du python, c'est du bonheur)
Une solution possible, c'est de faire en sorte que l'image de fond à dessiner soit sauvegardé dans une variable. Lorsque l'enfant appuie sur '1', on remplace cette variable par l'image que vous voulez afficher, et puis pour la touche '2' c'est pareil.
Du coup, pour le fond, au lieu d'avoir des images blitter un peu partout dans le code, on ne fait qu'un appel au blit().
(Vous vous recouvriez la première image du fond ... lors de l'appuie sur une touche, sauf que ce n'etait que lors de l'appuie sur la touche, et jamais plus)
Linux ou mourir
Pour avoir des problemes : demarrer Windows
Script de compression multi archive : http://forum.ubuntu-fr.org/viewtopic.php?id=225297
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Voici (avec un peu de retard !) l'image d'arrière-plan d'accueil qui présente les 2 arrières-plans sur lequel l'enfant va balader sa souris:
Toutes les autres images sont là : programme-miks
Dernière modification par doudoulolita (Le 05/11/2010, à 19:40)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Je crois que je commence à voir comment faire grâce aux conseils prodigués mais ça ne marche pas encore.
Je commence par ça (une fois que toutes les images ont été définies et uploadées et que la fonction d'affichage de la souris rendu_miks est définie.)
# récupère les touches pressées
key_pressed = pygame.key.get_pressed()
#affiche l'arrière-plan
arriereplan_x = [arriereplan, arriereplan1, arriereplan2]
i = 0
screen.blit(arriereplan_x[i], (0, 0))
rendu_miks()
Mais en fait, il faudrait qu'au début, j'ai un moyen de dire:
"Si aucune touche n'est pressée, i = 0"
ensuite, je poursuis avec:
# choisit l'image d'arrière-plan selon la touche
if key_pressed[K_KP1]:
i = 1
elif key_pressed[K_KP2]:
i = 2
Suis-je sur la bonne voie ? L'arrière-plan 0 apparaît ainsi que le nounours qui change selon les couleurs sur les petites vignettes de la page d'accueil, mais quand j'appuie sur les touches, il ne se passe rien, comme s'il ne tenait pas compte de la variable i pour blitter.
Dernière modification par doudoulolita (Le 05/11/2010, à 19:42)
Hors ligne
tshirtman
Re : Faire une animation sur la création de jeux vidéo libres
ah, là ton problème est de définir ce que veux dire "aucune touche n'est pressée" l'ordinateur va passer dans cette boucle des centaines de fois par secondes, et la plupart du temps, aucune touche n'aura été pressé depuis son dernier passage, donc il remettra i à 0.
Mais tu as un autre problème plus important (qui fait que tu ne voit jamais les images au lieu d'un bref instant), le dessin du fond et du persos doit être après les if/elif sur les touches, sinon i sera toujours à 0 à ce moment là.
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
"aucune touche n'est pressée" est effectivement réducteur, je comprends ce que tu veux dire et y ai même pensé ensuite dans le métro !
Dans le cas de mon petit programme, cela signifie plutôt: "tant qu'aucune touche n'a été pressée" (et surtout pas la touche 1 ou la touche 2 !)
J'ai testé en dessinant mon arrière-plan avec "screen.blit" dans les if et elif, mais alors, il n'y a que du noir avant qu'on n'appuie sur une touche.
Si j'ajoute le screen.blit dans le if et dans le elif en plus de celui déjà défini avant avec i = 0, je me retrouve comme auparavant à voir apparaître mon nouvel arrière-plan juste au moment de presser la touche 1 ou 2 et pas plus, donc l'intérêt de la variable est perdu.
C'est pour cela que j'aimerais lui dire que i = 0 si aucune touche n'a encore été pressée depuis le début du jeu, et cela avant de lui dire de changer i en fonction des touches 1 et 2...
Bon, je refais quelques essais mais c'est dingue comment un truc qui pouvait sembler facile à faire devient compliqué !
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Erreur de ma part: l'écran n'est pas noir si je screen.blit après les if et elif, en rajoutant un else. Par contre, toujours le même souci d'image qui disparaît dès que la touche remonte.
Idem si j'utilise if event.type == KEYDOWN puis if event.key == K_KP1, etc.
Dernière modification par doudoulolita (Le 08/11/2010, à 18:07)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
J'en suis à essayer ça mais le résultat reste identique:
# récupère les touches pressées
touche_pressee = pygame.key.get_pressed()
# choisit l'image d'arrière-plan selon la touche
if touche_pressee[K_KP1]:
while not touche_pressee[K_KP2]:
i = 1
screen.blit(arriereplan_x[i], (0, 0))
rendu_miks()
break
elif touche_pressee[K_KP2]:
while not touche_pressee[K_KP1]:
i = 2
screen.blit(arriereplan_x[i], (0, 0))
rendu_miks()
break
else:
i = 0
screen.blit(arriereplan_x[i], (0, 0))
rendu_miks()
Ca ne marche que si on garde le doigt appuyé sur les touches 1 ou 2 !
Dernière modification par doudoulolita (Le 09/11/2010, à 01:37)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Je commence à penser que la seule solution est de se baser sur le temps pour blitter à chaque frame mais je ne maîtrise pas bien pygame.time.
Les exemples que je trouve sont basés sur la distance et la vitesse, hors ici, je fais du surplace !
Hors ligne
tshirtman
Re : Faire une animation sur la création de jeux vidéo libres
tu complique un peu les choses…
# récupère les touches pressées
touche_pressee = pygame.key.get_pressed()
# choisit l'image d'arrière-plan selon la touche
if touche_pressee[K_KP1]:
i = 1
elif touche_pressee[K_KP2]:
i = 2
else:
i = 0
screen.blit(arriereplan_x[i], (0, 0))
rendu_miks()
revient au même, déjà…
si tu veux que l'image reste tant qu'on a pas appuyé l'autre touche:
#quelque part avant ta boucle de jeu
i = 0
# récupère les touches pressées
touche_pressee = pygame.key.get_pressed()
# choisit l'image d'arrière-plan selon la touche
if touche_pressee[K_KP1]:
i = 1
elif touche_pressee[K_KP2]:
i = 2
screen.blit(arriereplan_x[i], (0, 0))
rendu_miks()
ou si tu veux attendre un peu avant de remettre l'image de base:
#quelque part avant ta boucle de jeu
t = pygame.time.time()
# récupère les touches pressées
touche_pressee = pygame.key.get_pressed()
# choisit l'image d'arrière-plan selon la touche
if touche_pressee[K_KP1]:
t = pygame.time.time()+1000 # 1 seconde dans le future
i = 1
elif touche_pressee[K_KP2]:
t = pygame.time.time()+1000 # 1 seconde dans le future
i = 2
else:
if t < pygame.time.time(): # temps dépassé
i = 0
screen.blit(arriereplan_x[i], (0, 0))
rendu_miks()
code non testé, mais je pense que ça doit être ça.
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Ca ressemble plus à ce que j'avais fait avant et c'est beaucoup plus simple. Par contre, le screen.blit (unique) se place après les 2 conditions if et elif , et non dedans, et c'est ça qui change tout.
Il fallait surtout mettre i = 0 avant la boucle (c.à.d avant While True) et non à l'intérieur. C'est pour ça que les arrière-plans ne restaient pas sur l'écran.
Voici donc le code final:
#!/usr/bin/ env python
# -*- coding: utf-8 -*-
# définit les images choisies pour l'arrière-plan et la souris
image_arriereplan = 'arriereplan.png'
image_arriereplan1 = 'arriereplan_rouge_bleu.png'
image_arriereplan2 = 'arriereplan_rouge_bleu2.png'
image_souris1 = 'miks_static.png'
image_souris2 = 'miks_smackup2.png'
image_souris3 = 'miks_roll2.png'
def rendu_miks():
# définit la position de la souris
x, y = pygame.mouse.get_pos()
# échantillonne la couleur
couleur_ecran = screen.get_at((x, y))
# tableau des images utilisées pour la souris
souris_x = [souris1, souris2, souris3]
k = 0
if couleur_ecran == (0, 0, 255, 255):
k = 1
elif couleur_ecran == (255, 0, 0, 255):
k = 2
x-= souris_x[k].get_width() / 2
y-= souris_x[k].get_height() / 2
screen.blit(souris_x[k], (x,y))
# importe la bibliothèque Pygame
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
# définit la taille de la fenêtre et son titre
screen = pygame.display.set_mode((800, 600), 0, 32)
pygame.display.set_caption("Miks aime le bleu")
# charge les images
arriereplan = pygame.image.load(image_arriereplan).convert()
arriereplan1 = pygame.image.load(image_arriereplan1).convert()
arriereplan2 = pygame.image.load(image_arriereplan2).convert()
souris1 = pygame.image.load(image_souris1).convert_alpha()
souris2 = pygame.image.load(image_souris2).convert_alpha()
souris3 = pygame.image.load(image_souris3).convert_alpha()
i = 0
while True:
# pour fermer la fenêtre
for event in pygame.event.get():
if event.type == QUIT:
exit()
# récupère les touches pressées
touche_pressee = pygame.key.get_pressed()
#affiche l'arrière-plan
arriereplan_x = [arriereplan, arriereplan1, arriereplan2]
# choisit l'image d'arrière-plan selon la touche
if touche_pressee[K_KP1]:
i = 1
elif touche_pressee[K_KP2]:
i = 2
screen.blit(arriereplan_x[i], (0, 0))
rendu_miks()
pygame.display.update()
Rappel: Images de ce jeu
Un grand merci pour ton aide
Dernière modification par doudoulolita (Le 10/11/2010, à 00:33)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
J'ai repris le tout en utilisant les couleurs du logiciel de dessin pour enfants Tuxpaint, et en adaptant la taille de l'écran et des nounours.
- Bleu Tuxpaint = (50, 100, 255)
- Rouge Tuxpaint = (255, 0, 0)
- Taille écran Tuxpaint = 608 * 472 px
- Largeur grosse brosse: environ 38 px
Ainsi, les enfants (de maternelles) pourront dessiner deux fonds bien à eux avec les grosses brosses ou l'outil formes de Tuxpaint, et il suffira de renommer leurs images en arriereplan1 et arriereplan2, puis de les placer dans le dossier du jeu à la place des miennes.
Peut-être peut-on trouver une fonction pour faire ça dans le jeu mais les noms des images sauvegardées par Tuxpaint sont compliqués et en partie aléatoires (genre 20101109234420.png). Par défaut, elles sont sauvegardées dans /home/user/.tuxpaint/saved. Mon souci sera ensuite de trouver comment utiliser os.path (au cas où par exemple je prépare un lanceur sur le bureau alors que le dossier est placé ailleurs) je n'ai pas tout pigé, une fois de plus.
Dans cette nouvelle version, les petits arrières-plans sur la page d'accueil sont arriereplan1 et arriereplan2 resizées de moitié environ, grâce à une fonction de Pygame, puis blittées sur un unique rectangle vert (ça évoque une bordure). En d'autres termes, la page d'accueil est transformée automatiquement si on change les images arriereplan1 et arriereplan2 dans le dossier du jeu (en conservant le même nom). Sympa, non ?
Les chiffres 1 et 2 sont dessinés auparavant avec Gimp sur "arriereplan.png". On pourrait peut-être même les dessiner avec Tuxpaint ou mieux, dans le jeu lui-même, mais je n'y ai pas pensé sur le moment.
La touche 0 permet de revenir à l'accueil.
J'ai tout fait à mon boulot mais n'ai pas eu le temps de copier mes fichiers. Pour ceux qui veulent essayer de trouver la solution, ça fera un petit exercice en attendant de voir ce que j'ai fait.
Tshirman est hors concours, il est trop calé !
Dernière modification par doudoulolita (Le 10/11/2010, à 00:45)
Hors ligne
tshirtman
Re : Faire une animation sur la création de jeux vidéo libres
ah, du coup je cherche pas ^^, bon courage
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Voici le code pour utiliser des images de fond faites avec Tuxpaint.
image_souris1 = 'miks_static.png' - réduire à 26*37px (avec Gimp) image_souris2 = 'miks_smackup2.png'- réduire à 49*50px image_souris3 = 'miks_roll2.png'- réduire à 36*33px
#!/usr/bin/ env python
# -*- coding: utf-8 -*-
def rendu_miks():
# définit la position de la souris
x, y = pygame.mouse.get_pos()
# échantillonne la couleur
couleur_ecran = screen.get_at((x, y))
# tableau des images utilisées pour la souris
souris_x = [souris1, souris2, souris3]
k = 0
if couleur_ecran == (50, 100, 255, 255):
k = 1
elif couleur_ecran == (255, 0, 0, 255):
k = 2
x-= souris_x[k].get_width() / 2
y-= souris_x[k].get_height() / 2
screen.blit(souris_x[k], (x,y))
# importe la bibliothèque Pygame
import pygame
from pygame.locals import *
from sys import exit
import os.path
# définit les images choisies pour l'arrière-plan et la souris
image_arriereplan = 'arriereplan.png'
image_arriereplan1 = 'arriereplan1.png'
image_arriereplan2 = 'arriereplan2.png'
image_souris1 = 'miks_static.png'
image_souris2 = 'miks_smackup2.png'
image_souris3 = 'miks_roll2.png'
pygame.init()
# définit la taille de la fenêtre et son titre
screen = pygame.display.set_mode((608, 472), 0, 32)
pygame.display.set_caption("Miks aime le bleu")
# charge les images
arriereplan = pygame.image.load(image_arriereplan).convert()
arriereplan1 = pygame.image.load(image_arriereplan1).convert()
arriereplan2 = pygame.image.load(image_arriereplan2).convert()
souris1 = pygame.image.load(image_souris1).convert_alpha()
souris2 = pygame.image.load(image_souris2).convert_alpha()
souris3 = pygame.image.load(image_souris3).convert_alpha()
largeur_arriereplan = arriereplan.get_width()
hauteur_arriereplan = arriereplan.get_height()
print largeur_arriereplan
print hauteur_arriereplan
width = largeur_arriereplan/2-18
height = hauteur_arriereplan/2-12
print width
print height
arriereplan1p = pygame.transform.scale(arriereplan1, (width, height))
arriereplan2p = pygame.transform.scale(arriereplan2, (width, height))
i = 0
while True:
# pour fermer la fenêtre
for event in pygame.event.get():
if event.type == QUIT:
exit()
# récupère les touches pressées
touche_pressee = pygame.key.get_pressed()
#affiche l'arrière-plan
arriereplan_x = [arriereplan, arriereplan1, arriereplan2]
# choisit l'image d'arrière-plan selon la touche
if touche_pressee[K_KP1]:
i = 1
elif touche_pressee[K_KP2]:
i = 2
elif touche_pressee[K_KP0]:
i = 0
screen.blit(arriereplan_x[i], (0, 0))
rendu_miks()
Rect = (6, 16, largeur_arriereplan-12, height+12)
if i == 0:
pygame.draw.rect(screen, (0, 255, 0), Rect, 0)
screen.blit(arriereplan1p, (10, 20))
screen.blit(arriereplan2p, ((width+24), 20))
k = 0
rendu_miks()
pygame.display.update()
image_arriereplan = 'arriereplan.png'
Tshirtman, peut-être peux-tu m'aider à trouver comment uploader presque automatiquement dans le jeu les images de Tuxpaint sans que l'enfant (ou l'adulte) ait à les renommer lui-même à la main ?
Après, je vais essayer de mettre des points pour que l'enfant gagne ou non suivant les endroits survolés. A suivre !
Dernière modification par doudoulolita (Le 16/11/2010, à 13:06)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Encore une avancée dans mon code après bien des soucis.
Dans le code, il faudra changer le chemin des images en fonction de l'emplacement où vous les avez mises. Ca permet d'ajouter un lanceur sur le bureau, par exemple, avec la commande :
python chemin/nom_fichier.py
Vous remplacez 'chemin' par l'emplacement de votre fichier.
J'ai ajouté un compteur de score qui est positif quand on est dans le bleu et négatif dans le rouge. Quand ça atteint un certain seuil, une image de victoire ou une image de défaite apparaisse.
Pour utiliser ce code, il faut ajouter 2 images à celles qu'il y avait déjà dans Programme Miks et penser à redimensionner les nounours comme indiqué dans le post précédent:
- defaite.png
- victoire.png
J'ai essayé de commenter un maximum mais il peut y avoir des erreurs à force de traficoter le code
#!/usr/bin/ env python
# -*- coding: utf-8 -*-
# importe la bibliothèque Pygame
import pygame
from pygame.locals import *
from sys import exit
import os.path
# indique le chemin des images
chemin = '/home/doudoulolita/programmation/'
# définit les images choisies pour l'arrière-plan et la souris sans le chemin de leur dossier
nom_image_arriereplan = 'arriereplan.png'
nom_image_arriereplan1 = 'arriereplan1.png'
nom_image_arriereplan2 = 'arriereplan2.png'
nom_image_victoire = 'tux_victoire.png'
nom_image_defaite = 'tux_defaite.png'
nom_image_souris1 = 'miks_static.png'
nom_image_souris2 = 'miks_smackup2.png'
nom_image_souris3 = 'miks_roll2.png'
# définit les images choisies pour l'arrière-plan et la souris avec le chemin du dossier
image_arriereplan = chemin + nom_image_arriereplan
image_arriereplan1 = chemin + nom_image_arriereplan1
image_arriereplan2 = chemin + nom_image_arriereplan2
image_victoire = chemin + nom_image_victoire
image_defaite = chemin + nom_image_defaite
image_souris1 = chemin + nom_image_souris1
image_souris2 = chemin + nom_image_souris2
image_souris3 = chemin + nom_image_souris33
# appelle la fonction horloge
clock = pygame.time.Clock()
temps = pygame.time.get_ticks()
#initialise pygame
pygame.init()
# initialise les variables
i = 0
k = 0
# définit la taille de la fenêtre
screen = pygame.display.set_mode((608, 472), 0, 32)
# donne le titre de la fenêtre
pygame.display.set_caption("Miks aime le bleu")
# charge les images
arriereplan = pygame.image.load(image_arriereplan).convert()
arriereplan1 = pygame.image.load(image_arriereplan1).convert()
arriereplan2 = pygame.image.load(image_arriereplan2).convert()
victoire = pygame.image.load(image_victoire).convert()
defaite = pygame.image.load(image_defaite).convert()
souris1 = pygame.image.load(image_souris1).convert_alpha()
souris2 = pygame.image.load(image_souris2).convert_alpha()
souris3 = pygame.image.load(image_souris3).convert_alpha()
# récupère la largeur et la hauteur de l'image d'arrière-plan
largeur_arriereplan = arriereplan.get_width()
hauteur_arriereplan = arriereplan.get_height()
# divise et réduit la largeur et la hauteur d'arrière-plan
width = largeur_arriereplan/2-18
height = hauteur_arriereplan/2-12
# crée les vignettes de la page accueil
arriereplan1p = pygame.transform.scale(arriereplan1, (width, height))
arriereplan2p = pygame.transform.scale(arriereplan2, (width, height))
# définit les couleurs
bleu = (50, 100, 255, 255)
rouge = (255, 0, 0, 255)
# indique les scores maximums et minimums
score_max = 5000
score_min = -5000
# fonction d'affichage de la souris suivant la couleur de l'arrière-plan
def rendu_miks():
# k est la position dans le tableau initialisée à 0
k = 0
# si la couleur est bleue, change k et donc l'image de la souris
if couleur_ecran == bleu:
k = 1
# si la couleur est rouge, change k et donc l'image de la souris
elif couleur_ecran == rouge:
k = 2
# affiche l'image de la souris
screen.blit(souris_x[k], (x,y))
def verifie_score():
print score
# si le score dépasse le maximum, affiche l'image de la victoire
if score > score_max:
screen.blit(victoire, (0, 0))
# si le score est inférieur au minimum, affiche l'image de la défaite
elif score < score_min:
screen.blit(defaite, (0, 0))
while True:
# pour fermer la fenêtre
for event in pygame.event.get():
if event.type == QUIT:
exit()
temps +=1
# récupère les touches pressées
touche_pressee = pygame.key.get_pressed()
#tableau des images pour l'arrière-plan
arriereplan_x = [arriereplan, arriereplan1, arriereplan2]
# choisit l'image d'arrière-plan selon la touche
if touche_pressee[K_KP1]:
i = 1
elif touche_pressee[K_KP2]:
i = 2
elif touche_pressee[K_KP0]:
i = 0
# affiche l'arrière-plan
screen.blit(arriereplan_x[i], (0, 0))
# définit la position de la souris
x, y = pygame.mouse.get_pos()
# échantillonne la couleur
couleur_ecran = screen.get_at((x, y))
# tableau des images utilisées pour la souris
souris_x = [souris1, souris2, souris3]
# Place le curseur de la souris au centre de l'image
x-= souris_x[k].get_width() / 2
y-= souris_x[k].get_height() / 2
# appelle la fonction d'affichage de la souris puis du score suivant la couleur de l'arrière-plan puis affiche la fonction de verification du score
if i == 1 or i == 2:
score = temps
# si la couleur est bleue, le score est positif
if couleur_ecran == bleu:
score = temps
# si la couleur est rouge, le score est négatif
if couleur_ecran == rouge:
score = -temps
rendu_miks()
verifie_score()
# Définit les dimensions du rectangle de la page d'accueil
Rect = (6, 16, largeur_arriereplan-12, height+12)
# Affiche le rectangle, les vignettes et la souris sur la page d'accueil
if i == 0:
pygame.draw.rect(screen, (0, 255, 0), Rect, 0)
screen.blit(arriereplan1p, (10, 20))
screen.blit(arriereplan2p, ((width+24), 20))
k = 0
rendu_miks()
# réactualise l'affichage
pygame.display.flip()
score = 0
Il y a encore pas mal de défauts, j'en suis consciente mais j'ai du mal à savoir où initialiser les variables et comment gérer les fonctions.
De temps en temps, le résultat ne correspond pas à ce que je voulais et pourtant, ce que je fais me paraît plutôt logique.
J'ai aussi des soucis avec les indentations, qui sont soit 4 espaces, soit 1 tabulation, et ça met un peu le bazar quand on rouvre Gedit pour travailler sur un fichier en .py.
A un moment, le programme fonctionnait une fois mais pas plus! Je pense qu'il s'agissait d'un problème avec le temps: temps = pygame.time.get_ticks()
Dernière modification par doudoulolita (Le 19/11/2010, à 02:23)
Hors ligne
tshirtman
Re : Faire une animation sur la création de jeux vidéo libres
Si tu veux t'y retrouver plus facilement, fais des fonctions, courtes, qui font une seule chose, avec un nom explicite (moins de 20 lignes), qui initialisent les variables dont elles ont besoin pour travailler, et sont les seuls à les utiliser, ces fonctions doivent uniquement produire des résultat avec "return" il ne faut pas utiliser de variables globales (ou alors pour les choses qui ne changent pas du tout au cours du jeu, comme les images).
et ton main aussi doit être le plus court possible, en appelant une ou des fonctions que tu aura définis pour simplifier les choses.
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Ce qui est bien quand on participe à un jeu comme USF, c'est que grâce aux critiques constructives, on apprend non seulement à améliorer sa technique, mais aussi à comprendre l'esprit d'un jeu de plate-formes quand on n'est pas habitué.
Pour mes animations avec les jeunes à mon boulot, sur le thème "création de jeux vidéo", je dois bien comprendre tout ça.
L'autre jour, j'ai montré mes essais sur Pixie à un groupe mixte (12/14 ans).
Les filles sont restées alors que les garçons se sont désintéressés. Je suis sûre que si j'avais aussi montré Possum ou Xeon, je les captais.
On voit bien les différences dans les attentes quant à un jeu (plus baston pour les garçons, plus cool pour les filles) et les identifications suivant le sexe des jeunes.
Ça peut paraître sexiste comme réflexion (ce qui est totalement contraire à ma nature ) mais en groupe tout au moins, ça se constate rapidement.
Dernière modification par doudoulolita (Le 27/11/2010, à 14:15)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
J'ai trouvé dans le magazine Linux Pratique n°62 (nov/dec 2010) un article sur le logiciel Scratch.
Je n'ai pas réussi à installer le ppa sous Lucid Lynx mais par contre, aucun souci avec le .deb proposé sur le site.
Le personnage du chat mis par défaut fait vraiment très enfantin alors que le logiciel se veut destiné à des teenagers (collège en particulier).
Mais les autres objets proposés sont mieux et j'ai pu même uploader Awesome Possum pour le faire marcher dans le Scratch, ce qui est bien sympa. C'est beaucoup plus perfectionné que Kturtle en tout cas.
Ca fonctionne très simplement je trouve, par blocs, ce qui fait que ce n'est pas trop aride. Il y a des trucs un peu bizarre avec les conditions mais j'ai sans doute fait des erreurs de jeunesse.
Dernière modification par doudoulolita (Le 30/11/2010, à 12:28)
Hors ligne
doudoulolita
Re : Faire une animation sur la création de jeux vidéo libres
Avant de poursuivre mon jeu avec la souris qui se transforme selon la couleur, j'ai voulu étudier ce que c'est qu'une classe et en ai créé une vraiment très simple puisqu'elle ne fait pour l'instant que donner le nom du personnage. J'espère un jour en faire un sprite, c'est-à-dire une personnage qui bouge !
#!/usr/bin/ env python
# -*- coding: utf-8 -*-
# donne le nom de l'image d'arrière-plan
image_arriere_plan = 'arriereplan.png'
# importe la bibliothèque Pygame
import pygame
from pygame.locals import *
from sys import exit
class Sprite:
""" Un sprite vraiment, vraiment simple """
def __init__(self, nom):
""" le sprite n'est défini que par son nom """
self.nom = nom
def imprime_nom(self):
""" donne le nom du sprite dans la console """
print self.nom
def affiche_nom(self):
""" affiche le nom du sprite à l'écran après avoir choisi la police et avoir transformé le texte en une image à blitter"""
ma_police = pygame.font.SysFont("arial", 30)
surface_texte = ma_police.render(self.nom, True, (0,0,0))
screen.blit(surface_texte, (10, 10))
#initialise pygame
pygame.init()
# définit la taille de la fenêtre
screen = pygame.display.set_mode((608, 472), 0, 32)
# donne le titre de la fenêtre
pygame.display.set_caption("Le nom de Miks")
# uploade l'image d'arrière-plan
arriereplan = pygame.image.load(image_arriere_plan).convert()
# le sprite est défini par sa classe suivie de son nom entre parenthèses - ne pas oublier les guillemets
sprite = Sprite("Miks")
while True:
# pour fermer la fenêtre
for event in pygame.event.get():
if event.type == QUIT:
exit()
# affiche l'image d'arriere-plan
screen.blit(arriereplan, (0,0))
# utilise successivement les 2 fonctions d'affichage du nom du sprite
sprite.imprime_nom()
sprite.affiche_nom()
# réactualise l'affichage
pygame.display.update()
Tout ça est à la fois simple et compliqué, tout dépend si vous débutez ou non.
La première fonction (def) s'appelle init précédé et suivi de 2 underscores. Ne pas oublier l'espace entre def et les premiers underscores.
Cette classe peut être réutilisée pour "Blob", "Bix" ou tout autre à condition de changer le nom dans
sprite = Sprite("Miks")
Hors ligne
tshirtman
Re : Faire une animation sur la création de jeux vidéo libres
Ce qui est dommage ici, c'est que tu refabrique ma_police à chaque appel de affiche_nom, il serait plus intéressant de faire cette opération dans __init__
self.police = pygame.font.SysFont("arial", 30)
et de changer affiche_nom ainsi:
def affiche_nom(self):
""" affiche le nom du sprite à l'écran après avoir choisi la police et avoir transformé le texte en une image à blitter"""
surface_texte = self.police.render(self.nom, True, (0,0,0))
screen.blit(surface_texte, (10, 10))
(on peut faire d'ailleurs de même avec "surface_texte" et faire seulement le blit à chaque fois au lieu du rendu et du blit, si le nom ne change jamais.
c'est meilleurs pour les performances .
Hors ligne
|
A quick performance test showing Lutz's solution is the best:
import time
def speed_test(func):
def wrapper(*args, **kwargs):
t1 = time.time()
for x in xrange(5000):
results = func(*args, **kwargs)
t2 = time.time()
print '%s took %0.3f ms' % (func.func_name, (t2-t1)*1000.0)
return results
return wrapper
@speed_test
def compare_bitwise(x, y):
set_x = frozenset(x)
set_y = frozenset(y)
return set_x & set_y
@speed_test
def compare_listcomp(x, y):
return [i for i, j in zip(x, y) if i == j]
@speed_test
def compare_intersect(x, y):
return frozenset(x).intersection(y)
# Comparing short lists
a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
compare_bitwise(a, b)
compare_listcomp(a, b)
compare_intersect(a, b)
# Comparing longer lists
import random
a = random.sample(xrange(100000), 10000)
b = random.sample(xrange(100000), 10000)
compare_bitwise(a, b)
compare_listcomp(a, b)
compare_intersect(a, b)
These are the results on my machine:
# Short list:
compare_bitwise took 10.145 ms
compare_listcomp took 11.157 ms
compare_intersect took 7.461 ms
# Long list:
compare_bitwise took 11203.709 ms
compare_listcomp took 17361.736 ms
compare_intersect took 6833.768 ms
Obviously, any artificial performance test should be taken with a grain of salt, but since the set().intersection() answer is at least as fast as the other solutions, and also the most readable, it should be the standard solution for this common problem.
|
Implementing Tagging in a Django Application
my motivation
Although I’ve used many Web based applications that employ tagging, I’ve yet to create an application of my own with this feature. But now, I have two potential projects on the horizon that could benefit from tagging, and I’m thinking about how to best implement this, both in the database and user interface layers.
So, I thought I would explore how to implement tagging in my own applications, from scratch, and write about them on this blog. Therefore, I won’t pretend I have all the answers–or even necessarily any good answers–but I will simply be trying to think through how to approach implementing tagging, and I will welcome any constructive feedback on those thoughts.
I also see this as an opportunity to further explore Django, a rapid Web development framework that has captured my imagination, even though I have barely scratched the surface of its capabilities. I have also been sipping on the REST Kool-Aid recently, and would therefore also like to try my hand at implementing tagging in Django RESTfully. Finally, I want to delve more deeply into AJAX programming and learn about how to create effective Selenium tests
This might seem like a lot of new stuff to learn and implement all at once (think: high risk of failure, or at least confusion), but I believe the problem domain I’m tackling is small and well defined, and I’ll be taking it piece by piece, in a divide and conquer strategy that should also effectively mitigate the risks. I’m thinking of exploring the implementation in several posts over the coming weeks, starting with database design and setting up the initial project, moving on to designing the controller layer RESTfully, and then on to implementing simple, then more advanced, user interface functions.
Furthermore, I’ll be starting the implementation very simply, perhaps even naively, and only adding complexity as needed, to try to really get at the essence of implementing tagging. I also hope that those who have more experience with the tools and approaches I use will let me know if I start to travel too far down the wrong road. I’ll keep the posts and source code up to date to reflect this feedback.
Ultimately, I believe that to truly understand a particular tool or design approach, you have to implement it meaningfully. Only then can you evaluate it on its own merits and compare it to alternatives. This is my goal here.
beginning analysis
When I started learning to program applications professionally, I was taught to begin designing the database first (assuming a database was used, which it typically was). This, or object modeling, is still how I approach designing new projects, after a sufficient requirements gathering phase. The data model is the layer upon which all others are built, so weaknesses in its design tend to ripple out into the application. And in cases like this, in which I am exploring concepts that are new to me, boiling the problem domain down into simple types of data and their relationships provides a gentler starting point. You may prefer to do object modeling first instead, which essentially accomplishes the same goals.
So, let’s begin with the things that we want to tag, which might be Web sites (represented by their addresses and associated titles), images, or any other discreet thing you can imagine. I don’t want to get hung up on what these particular things are, so lets just call these things “items”. We will also have users who are doing the actual tagging, and we want to track who is adding tags to what items so that later we can display just the tags that a particular user has entered, for example.
Then of course, there are the tags themselves. Lets start with the obvious: items can be assigned many tags, and likewise, users can assign many tags. So, we can think of this as a many-to-many relationship between items and users that is bridged by tags:
[items] --< [tags] >-- [users]
This is my attempt to render an entity-relationship diagram (ERD) with Crow’s Feet notation in ASCII, so read this as:
["one" table] --< ["many" table]
(Let me know if this is not easily readable, and I will break down and create images of real ERDs.)
This start is OK, but to use tags effectively in our application, the tags themselves should be stored as unique values in a table so we can do things like easily see all items assigned a particular tag. To make this type of querying easier, we can normalize the database further by recognizing that a particular tag may be assigned by many users and likewise, a particular tag may be assigned to many items. So, there is really a many-to-many relationship between items and tags and a many-to-many relationship between users and tags:
[items] --< [items_tags] >-- [tags] --< [users_tags] >-- [users]
Now, (I think) I’m on to something. But its still not quite right, because in this model, I have broken the association between users and items, so that, for example, there is no real way to tell when a particular user assigned a particular tag to a particular item. In addition to knowing when an item was tagged by a user, there may be other metadata I want to capture around this event. So, a further refinement might look like this:
[tags] | ^ [items] --< [tag_assignment] >-- [users]
This looks more straightforward.
I probably haven’t blown anyone’s mind with this, and I definitely won’t with the next section either, when I’ll simply set the stage for continuing this exploration in a Django project. Hopefully, by the end, we’ll have a solid foundation to build upon in later posts.
let’s get this party started
After designing the data model layer, I feel like I have enough basic understanding of the problem space to plunge into Django. At this point, I’ll assume you know Python, have some basic familiarity with Django (take a few minutes and look at the Django tutorial) and have Django installed as well as a locally running MySQL server instance. Basically, this section will be a condensed version of part one of the Django tutorial, customized for this particular project.
Within Eclipse, I created a new Python project through PyDev called tagging_exploration, and on the command line, I created a Django project within that directory, also called tagging_exploration for simplicity:
django-admin.py startproject tagging_exploration
Don’t get too hung up on the two project names. The Eclipse project name simply allows Eclipse to manage all our code, while the Django project is Django’s way of organizing closely related applications. In this case, we’ll start with only one application in our project, called “tagging” which will be our focus. So, on the command line, go into the Django “tagging_exploration” project and run this:
python manage.py startapp tagging
This creates an application directory called “tagging” where we’ll be coding. To let Django know about this application, modify the settings.py file in the tagging_exploration Django project directory so it looks like this:
INSTALLED_APPS = ( 'tagging_exploration.tagging', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', )
Essentially, I added our application first in the list. The next four applications are there by default, and I added the famed django.contrib.admin application at the end, simply because its so useful, and eventually, we can use it to verify that our basic setup is working. And since it comes with Django, we get it for free.
Now, within the tagging application directory is a models.py module within which we can begin to define our data model:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Tags(models.Model):
tag_name = models.CharField(maxlength=255)
class Items(models.Model):
item_name = models.CharField(maxlength=255)
added_on = models.DateTimeField(core=True)
class Users(models.Model):
user = models.OneToOneField(User)
class Tag_Assignment(models.Model):
assigned_on = models.DateTimeField(core=True)
item = models.ForeignKey(Items)
tag = models.ForeignKey(Tags)
user = models.ForeignKey(Users)
This is about as bare as a Django model can be, but its a good starting point. With this, we can let Django create the underlying database for us, and later on, Django will also manage the object relational mapping for us in the application code using these classes as a guide. Consult the Django model documentation for a complete explanation of what I have done here as well as instructions for customizing how the admin interface functions.
Otherwise, all I’ve done is try to faithfully implement the ERD above. Again, the “items” can be anything for the purposes of this demonstration, so I simply gave them a name field. The only thing that may look odd is how the Users class is defined: I am importing and extending the User model from the bundled django.contrib.auth to automatically gain access to that application’s functionality within our tagging application. For a more detailed explanation of this approach read “Django tips: extending the User model” from the B-List.
Moving on, we’ll need to create an initially empty database, also called tagging_exploration, along with appropriate user privileges to allow Django access. So, on the command line, connect to your MySQL instance as root and run this:
use mysql;
drop database if exists tagging_exploration;
create database tagging_exploration;
GRANT ALL
ON tagging_exploration.*
TO tag_user@'localhost'
IDENTIFIED BY 'tag_pass';
exit;
I granted “all” permissions because Django will be creating fields and indexes in tables among other things, and therefore needs fairly liberal privileges. To inform Django about this database, open the settings.py file in the tagging Django project, and modify the following lines accordingly:
DATABASE_ENGINE = 'mysql' DATABASE_NAME = 'tagging_exploration' DATABASE_USER = 'tag_user' DATABASE_PASSWORD = 'tag_pass'
Also, add this line to settings.py to inform Django about our custom Users class:
AUTH_PROFILE_MODULE = 'tagging.Users'
We can now create our application by running the following from the tagging_exploration Django project directory:
python manage.py syncdb
It will ask you to create a superuser account for the django.contrib.auth application. Provide a username and password and remember it. You’ll need this information to access the administrative interface.
what now?
This is a good stopping point for this post, but it would be nice to actually see something for our effort. Lets peek into the Django admin interface and kick the tires on our data model. First, open the urls.py module in the Django project directory and uncomment the following line of code as instructed:
# Uncomment this for admin:
(r'^admin/', include('django.contrib.admin.urls')),
And let’s also elaborate our model code to give the admin application hints for how we want it to handle our model code. For example, to tell Django that we want to use the admin interface for a particular class, simply add an empty “Admin” inner class to an existing model class, like this:
class Tags(models.Model):
tag_name = models.CharField(maxlength=255)
class Admin: pass
This is enough to provide the default functionality in the admin interface for Tags. But options can also be added, as explained in Django’s model documentation, to further control how the admin interface functions. Here is a more interesting models.py for the admin interface that will expose Tags and Items:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Tags(models.Model):
tag_name = models.CharField(maxlength=255)
def __str__(self):
return self.tag_name
class Admin:
list_display = ('tag_name',)
search_fields = ['tag_name']
class Meta:
verbose_name_plural = 'Tags'
class Items(models.Model):
item_name = models.CharField(maxlength=255)
added_on = models.DateTimeField(core=True)
def __str__(self):
return self.item_name
class Admin:
list_display = ('item_name', 'added_on')
search_fields = ['item_name']
class Meta:
verbose_name_plural = 'Items'
ordering = ['item_name']
class Users(models.Model):
user = models.OneToOneField(User)
class Tag_Assignment(models.Model):
assigned_on = models.DateTimeField(core=True, auto_now_add=True)
item = models.ForeignKey(Items)
tag = models.ForeignKey(Tags)
user = models.ForeignKey(Users)
Now, from the project directory, run this from the command line:
python manage.py runserver
By default, this will launch a standalone Django development server on port 8000, but you can add a custom port number to the end of the command to run it elsewhere. Otherwise, open your browser to http://127.0.0.1:8000/admin, login with the superuser account you created above and begin poking around the data model we created.
what next?
In the next post, I am going to begin implementing some simple use cases, trying to design URL’s in Django that are RESTful, and probably at least exploring some simple generic views.
resources
This work is licensed under a Creative Commons Attribution - ShareAlike 2.5 License.
|
Is there a way to add a show desktop button in Tint2?
Offline
You can't really add a button to tint2, but you can tweak openbox to show desktop when you double-click the desktop. This is how I do it:
<mousebind action="DoubleClick" button="Left"> <action name="ToggleShowDesktop"/></mousebind>
add this after the following line in ~/.config/openbox/rc.xml
<context name="Desktop">
Offline
another solution is to add in your menu.xml an entry with
<item label="Show desktop">
<action name="ToggleShowDesktop"/>
</item>
and in tint2rc, use wm_menu = 1.
So when you right clic on the panel openbox's menu popup.
That's why we don't have launcher in tint2. The WM's menu is so easy and so powerful.
Offline
excellent
Offline
Offline
You can't really add a button to tint2, but you can tweak openbox to show desktop when you double-click the desktop. This is how I do it:
<mousebind action="DoubleClick" button="Left"> <action name="ToggleShowDesktop"/> </mousebind>
add this after the following line in ~/.config/openbox/rc.xml
<context name="Desktop">
This seemed promising but, why would I want to show desktop if I'm already seeing it? I mean you need to double-click on the desktop to show it. What I want is to be able to minimize all windows at once even if Firefox or Abiword or anything else is maximized. Super+D worked well, but is there a way to prevent it from hiding Conky? I need to minimize all windows at once, but no need to hide conky.
Last edited by Nico3d3 (2010-02-11 00:55:10)
Offline
Offline
^ Which brings us back to the keyboard shortcut. Or are you using a tablet PC or something else that doesn't have a physical keyboard?
Even with the panel shortcut, since Tint2 is on the bottom desktop layer, you might have to move an open window to get to the show desktop button. You might want to consider an "always on top" panel like xfce4-panel if you really need a panel shortcut.
Offline
but is there a way to prevent it from hiding Conky? I need to minimize all windows at once, but no need to hide conky.
Edit your conky config and make sure "own_window" is set to no.
Offline
You can't really add a button to tint2, but you can tweak openbox to show desktop when you double-click the desktop. This is how I do it:
<mousebind action="DoubleClick" button="Left"> <action name="ToggleShowDesktop"/> </mousebind>
add this after the following line in ~/.config/openbox/rc.xml
<context name="Desktop">
Thanks thats just what I've been looking for since I've gone panel-less, I had an entry in the menu but a double click is a much better idea
This seemed promising but, why would I want to show desktop if I'm already seeing it? I mean you need to double-click on the desktop to show it. What I want is to be able to minimize all windows at once even if Firefox or Abiword or anything else is maximized.
I believe that (not 100% sure) by default there is a 1 pixel margin at the top of the screen, so that if you move the mouse to the very top edge of your screen and click you are clicking on the desktop even if you've got something maximised - try right clicking at the very top and you should get the right click menu, if not you can change the margins by menu>Preferences>Openbox Config>GUI Config Tool>Margins
I've now got mine set up with a 1 pixel margin on all sides so the mouse is always close to the right click menu/double click to show desktop. Hope this helps...
Last edited by Eamon (2010-02-11 13:02:09)
Offline
This seemed promising but, why would I want to show desktop if I'm already seeing it? I mean you need to double-click on the desktop to show it. What I want is to be able to minimize all windows at once even if Firefox or Abiword or anything else is maximized.
I never maximize my windows since my first 1024x768 screen, but that's me.
Last edited by danielrmt (2010-02-11 13:50:58)
Offline
Hello,
I like tint2 very much, although I am using crunchbang panel which is everything I need but I miss the transparency of Tint2.
Coming back to the "Show desktop" question. Could it be possible to create a script that shows an icon near the volume icon, and if you click that icon it would issue the command Win+D ?
Cheers
discovery
p.s. waiting eagerly for the final release of CHB 10 based on Debian..
Offline
^ You could have an instance of xfce4-panel running in the bottom corner with just the Show Desktop applet. Expect it to be skinned according to your GTK theme, so you'd probably want to adjust your Tint2 to match. I do something similar with Weather Update.
Offline
^ You could have an instance of xfce4-panel running in the bottom corner with just the Show Desktop applet. Expect it to be skinned according to your GTK theme, so you'd probably want to adjust your Tint2 to match. I do something similar with Weather Update.
That is a nice tip. My intention is to get rid of xfce4 in openbox and simply use Tint2. Hmm.. I wished Tint2 was customizable enough to include a "Show Desktop" icon. Well i guess Super+D is my most used key combination in Crunch now...:)
Offline
Another way to input keyboard combinations from a launcher, menu item or even a script is to install xdotool from the repositories. Then use the command eg 'xdotool key super+d' in your launcher.
Now, I'd like to know how to make a custom system tray icon...
Offline
If you use Tint2, you can add a command to be launched when the clock is clicked.
My configuration looks like this:
# CLOCK---------------------------------------------
time1_format = %a %e
time1_font = sans 16
#time2_format = %k %M
#time2_font = sans 8
clock_font_color = #ffffff 76
clock_padding = 4 4
clock_background_id = 1
clock_lclick_command = catfish
clock_rclick_command = sunbird
and opens, believe it or not, catfish and sunbird respectively.
Last edited by zengrapefruit (2010-03-22 13:37:45)
Offline
@zengrapefruit
Great tip... But what terminal command is to be used in order to show the Desktop? How can we issue Super+D command in terminal?
Offline
The steps in this link will give you a little executable that you can call to toggle the desktop. After completing the steps, place the newly created 'sdtoggle' file in ~/bin and set the right or left click for the tint2 clock to sdtoggle and you should be good to go.
--
...old school #! user now mostly running Arch
jpope.org
Offline
well, I think I am good in copying tips from other and google is excellent in helping in this...:D
Here is my method in turning the clock in "show desktop" button.
The following instructions should work for other Linux distributions / desktop environments too.
1. Install wmctrl:
sudo apt-get install wmctrl
2. Create an empty file "show_desktop.sh".
sudo nano /bin/show_desktop.sh
Paste the following code inside this file:
#!/bin/sh
if wmctrl -m | grep "mode: ON"; then
exec wmctrl -k off
else
exec wmctrl -k on
fi
save the file with Control+O in nano and make it executable. To do this, open a terminal and:
sudo chmod +x /bin/show_desktop.sh
Then, we need to modify Tint2 configuration. Following the excelllent tip from zengrapefruit I added the last two lines under clock session:
#---------------------------------------------
# CLOCK
#---------------------------------------------
time1_format = %H:%M
time1_font = sans 8
time2_format = %A %d %B
time2_font = sans 6
clock_font_color = #ffffff 76
clock_padding = 4 4
clock_background_id = 0clock_lclick_command = /bin/show_desktop.shclock_rclick_command = /bin/show_desktop.sh
It works...:)
P.s. Now that I am finding the perfect combination of CB 9.04 I am a little hesitant to move to the Startler although my desire is to move to Debian.
Last edited by discovery (2010-03-23 18:08:16)
Offline
P.s. Now that I am finding the perfect combination of CB 9.04 I am a little hesitant to move to the Startler although my desire is to move to Debian
+1 !
Offline
Another tip, simplier...
After installing xdotool (sudo apt-get install xdotool) you can add these lines to tint2 config on clock section:
clock_lclick_command = xdotool key super+D
clock_rclick_command = xdotool key super+space
Left click will show the desktop and the right click on clock will show the menu...
I think this is a much simpler solution.
cheers
Last edited by discovery (2010-03-23 21:52:15)
Offline
Hello all
I know this thread is quite old, but I was looking for a similar solution and I came across this thread by Googling.
Hello,
I like tint2 very much, although I am using crunchbang panel which is everything I need but I miss the transparency of Tint2.
Coming back to the "Show desktop" question. Could it be possible to create a script that shows an icon near the volume icon, and if you click that icon it would issue the command Win+D ?
Cheers
discovery
This is exactly what I thought, so I have done the script. In fact this script can be used to create any similar launcher for tint2. It requires xdotool to work. Simply copy the code into a file and save with a filename of your choice eg showdesktop.py. You can alter the icon if you don't like it. Then make the script executable and add to your openbox autostart.sh.
#!/usr/bin/env python
# Show desktop system tray launcher for use with Openbox & tint2 (or other panels)
import gtk
import os
class StatusIcon:
def __init__(self):
self.statusicon = gtk.StatusIcon()
self.statusicon.set_from_file("/usr/share/icons/gnome/22x22/apps/preferences-system-windows.png")
self.statusicon.set_tooltip("Show Desktop")
self.statusicon.connect("activate", self.left_click_event)
self.statusicon.connect("popup-menu", self.right_click_event)
def right_click_event(self, icon, button, time):
menu = gtk.Menu()
about = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
quit = gtk.ImageMenuItem(gtk.STOCK_QUIT)
about.connect("activate", self.show_about_dialog)
quit.connect("activate", gtk.main_quit)
menu.append(about)
menu.append(quit)
menu.show_all()
menu.popup(None, None, gtk.status_icon_position_menu, button, time, self.statusicon)
def left_click_event(self, event):
os.system('xdotool key super+d')
def show_about_dialog(self, widget):
about_dialog = gtk.AboutDialog()
about_dialog.set_destroy_with_parent(True)
about_dialog.set_program_name("Tint2 Show Desktop Icon")
about_dialog.set_version("0.1")
about_dialog.set_comments('A simple system tray icon so that you can show the desktop and iconify all open windows.\n\nDesigned specifically for tint2 and Openbox.\n\nYou will need the keybinding Super+D set up to ToggleShowDesktop in your Openbox rc.xml, but this is the default.')
about_dialog.set_authors(["richjack, 2010 \nReleased under GPL v2 or later"])
about_dialog.run()
about_dialog.destroy()
StatusIcon()
gtk.main()
The icon sits in the system tray on any panel including tint2.
Enjoy
Offline
This is exactly what I thought, so I have done the script. In fact this script can be used to create any similar launcher for tint2. It requires xdotool to work. Simply copy the code into a file and save with a filename of your choice eg showdesktop.py.
You can alter the icon if you don't like it.Then make the script executable and add to your openbox autostart.sh.
Excellent script! But I don't like your icon!
So instead of this one:
self.statusicon.set_from_file("/usr/share/icons/gnome/22x22/apps/preferences-system-windows.png")
better this one (IMHO):
self.statusicon.set_from_file("/usr/share/icons/gnome/22x22/places/user-desktop.png")
Last edited by boromeus (2010-09-14 21:27:01)
Offline
Offline
|
Using instruction I try to connect Python + uWSGI.
I made default project in a folder /home/sanya/django/pasteurl.However, have opened it in a browser I get
uWSGI Errorwsgi application not found
Logs contain the following:
binding on TCP port: 9001
your server socket listen backlog is limited to 64 connections
added /home/sanya/django/pasteurl to pythonpath.
initializing hooks...done.
...getting the applications list from the 'django' module...
uwsgi.applications dictionary is not defined, trying with the "applications" one...
applications dictionary is not defined, trying with the "application" callable.
static applications not defined, you have to use the dynamic one...
spawned uWSGI master process (pid: 7637)
spawned uWSGI worker 1 (pid: 7646)
spawned uWSGI worker 2 (pid: 7647)
spawned uWSGI worker 3 (pid: 7648)
spawned uWSGI worker 4 (pid: 7649)
File /home/sanya/django/pasteurl/django.wsgi
import os
import django.core.handlers.wsgi
# init django settings
os.environ['DJANGO_SETTINGS_MODULE'] = 'pasteurl.settings'
# define wsgi app
application = django.core.handlers.wsgi.WSGIHandler()
# mount this application at the webroot
# applications = { '/': 'application' }
As I realised, it's something wrong with this application dictionary
|
Using regular expressions!
>>> import re
>>> s = "ABCDXYv"
>>> re.findall(r'.{1,2}',s,re.DOTALL)
['AB', 'CD', 'XY', 'v']
I know it has been a while, but I came back to this and was curious about which method was better; mine: r'.{1,2}' or Jon's r'..?'. On the surface, Jon's looks much nicer, and I thought it would be much faster than mine, but I was surprised to find otherwise, so I thought I would share:
>>> import timeit
>>> timeit.Timer("re.findall(r'.{1,2}', 'ABCDXYv')", setup='import re').repeat()
[1.9064299485802252, 1.8369554649334674, 1.8548105833383772]
>>> timeit.Timer("re.findall(r'..?', 'ABCDXYv')", setup='import re').repeat()
[1.9142223469651611, 1.8670038395145383, 1.85781945659771]
Which shows that indeed r'.{1,2}' is the better/faster choice. (But only slightly)
|
I was saving a piece of work I had worked on for 2 hours.
After I saved it my computer shut off when I got it back up and running I try to open my drawing and this happens.
Traceback (most recent call last): File
"/usr/share/mypaint/gui/filehandling.py", line 306,
open_cb(self=<gui.filehandling.FileHandler object>, action=<gtk.Action
object at 0x8c44054 (GtkAction at 0x89d1dc0)>)
dialog.hide()
self.open_file(dialog.get_filename().decode('utf-8'))
finally: variables: {'decode': (None, []), 'dialog.get_filename': ('local', <built-in method get_filename of
gtk.FileChooserDialog object at 0x955a43c>), 'self.open_file':
('local', <bound method FileHandler.wrapper of
<gui.filehandling.FileHandler object at 0x8c30dac>>)} File
"/usr/share/mypaint/gui/drawwindow.py", line 43,
wrapper(self=<gui.filehandling.FileHandler object>,
*args=(u'/home/jen/icyblue.ora',), **kwargs={})
try:
func(self, *args, **kwargs)
finally: variables: {'self': ('local', <gui.filehandling.FileHandler object at 0x8c30dac>), 'args': ('local',
(u'/home/jen/icyblue.ora',)), 'func': ('local', <function open_file at
0x8bda844>), 'kwargs': ('local', {})} File
"/usr/share/mypaint/gui/filehandling.py", line 227,
open_file(self=<gui.filehandling.FileHandler object>,
filename=u'/home/jen/icyblue.ora')
try:
self.doc.model.load(filename)
except document.SaveLoadError, e: variables: {'self.doc.model.load': ('local', <bound method Document.load of
<lib.document.Document instance at 0x8c30e2c>>), 'filename': ('local',
u'/home/jen/icyblue.ora')} File
"/usr/share/mypaint/lib/document.py", line 284,
load(self=<lib.document.Document instance>,
filename=u'/home/jen/icyblue.ora')
try:
load(filename)
except gobject.GError, e: variables: {'load': ('local', <bound method Document.load_ora of <lib.document.Document instance at
0x8c30e2c>>), 'filename': ('local', u'/home/jen/icyblue.ora')} File
"/usr/share/mypaint/lib/document.py", line 450,
load_ora(self=<lib.document.Document instance>,
filename=u'/home/jen/icyblue.ora')
tempdir = tempfile.mkdtemp('mypaint')
z = zipfile.ZipFile(filename)
print 'mimetype:', z.read('mimetype').strip() variables: {'zipfile.ZipFile': ('global', <class zipfile.ZipFile at 0x8863b6c>),
'z': (None, []), 'filename': ('local', u'/home/jen/icyblue.ora')}
File "/usr/lib/python2.7/zipfile.py", line 710,
__init__(self=<zipfile.ZipFile instance>, file=u'/home/jen/icyblue.ora', mode='r', compression=0,
allowZip64=False)
if key == 'r':
self._GetContents()
elif key == 'w': variables: {'self._GetContents': ('local', <bound method ZipFile._GetContents of <zipfile.ZipFile
instance at 0x95629ec>>)} File "/usr/lib/python2.7/zipfile.py", line
744, _GetContents(self=<zipfile.ZipFile instance>)
try:
self._RealGetContents()
except BadZipfile: variables: {'self._RealGetContents': ('local', <bound method ZipFile._RealGetContents of <zipfile.ZipFile
instance at 0x95629ec>>)} File "/usr/lib/python2.7/zipfile.py", line
759, _RealGetContents(self=<zipfile.ZipFile instance>)
if not endrec:
raise BadZipfile, "File is not a zip file"
if self.debug > 1: variables: {'BadZipfile': ('global', <class 'zipfile.BadZipfile'>)} BadZipfile: File is not a zip file
if there is any way I can retrieve my drawing please assist me for I do not know how to fix this problem, thank you ubuntu forums!
|
Recently I have been trying to learn WebPy and when attempting to use a template in the tutorial (http://webpy.org/docs/0.3/tutorial) I come across this error when trying to access the page.
File "/Library/Python/2.7/site-packages/web.py-0.37-py2.7.egg/web/application.py", line 239, in process
return self.handle()
File "/Library/Python/2.7/site-packages/web.py-0.37-py2.7.egg/web/application.py", line 230, in handle
return self._delegate(fn, self.fvars, args)
File "/Library/Python/2.7/site-packages/web.py-0.37-py2.7.egg/web/application.py", line 420, in _delegate
return handle_class(cls)
File "/Library/Python/2.7/site-packages/web.py-0.37-py2.7.egg/web/application.py", line 396, in handle_class
return tocall(*args)
File "/Users/clement/Desktop/#Minecraft/index2.py", line 14, in GET
return render.index(name)
File "/Library/Python/2.7/site-packages/web.py-0.37-py2.7.egg/web/template.py", line 1017, in __getattr__
t = self._template(name)
File "/Library/Python/2.7/site-packages/web.py-0.37-py2.7.egg/web/template.py", line 1014, in _template
return self._load_template(name)
File "/Library/Python/2.7/site-packages/web.py-0.37-py2.7.egg/web/template.py", line 1001, in _load_template
raise AttributeError, "No template named " + name
AttributeError: No template named index
I've looked at this Question on SOF but I couldn't get it to work in my situation. I've spent about 4 hours trying to figure this out and have attempted to rework the way I launch the service which is usually done by:
Macintosh-2:~ clement$ python /Users/clement/Desktop/\#Minecraft/index.py
Thanks!
|
I need to extract data from HTML-files. The files in question are, most likely, automatically generated. I have uploaded the code of one of these files to Pastebin: http://pastebin.com/9Nj2Edfv. This is the link to the actual page: http://eur-lex.europa.eu/Notice.do?checktexts=checkbox&val=60504%3Acs&pos=1&page=1&lang=en&pgs=10&nbl=1&list=60504%3Acs%2C&hwords=&action=GO&visu=%23texte
The data I need to extract is found under the different headings.
This is what I have so far:
from BeautifulSoup import BeautifulSoup
ecj_data = open("data\ecj_1.html",'r').read()
soup = BeautifulSoup(ecj_data)
celex = soup.find('h1')
auth_lang = soup('ul', limit=14)[13].li
procedure = soup('ul', limit=20)[17].li
print "Celex number:", celex.renderContents(),
print "Authentic language:", auth_lang
print "Type of procedure:", procedure
I have all the data stored locally which is the reason it opens the file ecj_1.html.
The Celex number and the Authentic language works somewhat good.
celex returns
"Celex number: 61977J0059"
auth_lang returns "Authentic language: <li>French</li>"
I need just the contents of the h1 tag (not the break at the end).
[Also, I need auth_lang to return just "French", and not the <li>-tags.]This is not a problem anymore. I realized I could just add ".text" to the end of "auth_lang".
Procedure on the other hand returns this:
Type of procedure: <li>
<strong>Type of procedure:</strong>
<br />
Reference for a preliminary ruling
</li>
which is quite wrong as I just need it to return "Reference for a preliminary ruling".
Is there any way I can achieve this?
Second edit:I replaced celex = soup.find('h1') with celex = soup('h1', limit=2)[0] and added .text to the print celex.
|
Gemnoc
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Une autre demande pour Ellypsis, pourrais-tu démarrer FreeCAD de cette façon dans le terminal :
freecad --write-log
Ceci va enregistrer un fichier journal FreeCAD.log dans le dossier ~/.FreeCAD, ouvres-le et postes le contenu ici.
J'ai testé rapidement le Sketcher dernière mouture, c'est super. Les contraintes sont désormais appliquées de façon automatique (peut être désactivé), et un indicateur de contrainte s'affiche à côté du curseur lors de la création de géométries. Il ne manque plus grand chose pour que le Sketcher soit pleinement fonctionnel, notamment la possibilité d'appliquer des contraintes à des éléments externes (arêtes de faces d'un solide par exemple).
Hors ligne
Ellypsis
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Salut,
Je suis de retour de mon petit weekend en montagne, je vais donc pouvoir m'y remettre
Pour ta première commande, voilà ce que j'obtiens :
mathieu@Ellypsis:~$ freecad -t 0
FreeCAD 0.12, Libs: 0.12R4478 (Launchpad)
© Juergen Riegel, Werner Mayer, Yorik van Havre 2001-2011
##### #### ### ####
# # # # # #
# ## #### #### # # # # #
#### # # # # # # # ##### # #
# # #### #### # # # # #
# # # # # # # # # ## ## ##
# # #### #### ### # # #### ## ## ##
Importing project files......
Importing project files...... (100.0 %)33.0 %)
Importing project files...... (100.0 %)
Importing project files...... (100.0 %)
Importing project files...... (100.0 %)
Importing project files...... (100.0 %)
Importing project files...... (100.0 %)
Importing project files...... (100.0 %)
Importing project files...... (100.0 %)
Call from Python thread (not synchronized): count=10.0 %)16.0 %)
Call from Python thread (not synchronized): count=2
Call from Python thread (not synchronized): count=3
Call from Python thread (not synchronized): count=4
Call from Python thread (not synchronized): count=5
Call from Python thread (not synchronized): count=6
Call from Python thread (not synchronized): count=7
Call from Python thread (not synchronized): count=8
Call from Python thread (not synchronized): count=9
Call from Python thread (not synchronized): count=10
10
. Printing message
Printing error
Printing warning
.Call from Python thread: count=1
Call from Python thread: count=2
Call from Python thread: count=3
Call from Python thread: count=4
Call from Python thread: count=5
Call from Python thread: count=6
Call from Python thread: count=7
Call from Python thread: count=8
Call from Python thread: count=9
Call from Python thread: count=10
10
........create mesh structure......
saving...... (99.0 %)
Write mesh to /tmp/mesh.stl (99.0 %)
Create mesh instance
create mesh structure......
Checking indices...... (100.0 %)
Checking topology...... (100.0 %)
Mesh loaded successfully. (100.0 %)
Create mesh instance
create mesh structure......
Checking indices...... (100.0 %)
Checking topology...... (100.0 %)
Mesh loaded successfully. (100.0 %)
.Create sphere (10.0,140)...
Create sphere (10.0,160)...
create mesh structure......
... destroy sphere (99.0 %)
create mesh structure......
... destroy sphere (99.0 %)
.create mesh structure......
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
....
----------------------------------------------------------------------
Ran 45 tests in 18.371s
OK
mathieu@Ellypsis:~$ (100.0 %)
Maintenant, le fichier FreeCAD.log :
Msg: FreeCAD 0.12, Libs: 0.12R4478 (Launchpad)
© Juergen Riegel, Werner Mayer, Yorik van Havre 2001-2011
##### #### ### ####
# # # # # #
# ## #### #### # # # # #
#### # # # # # # # ##### # #
# # #### #### # # # # #
# # # # # # # # # ## ## ##
# # #### #### ### # # #### ## ## ##
Log: Time = Mon Sep 5 16:44:05 2011
Log: AppDataSkipVendor = true
Log: AppHomePath = /usr/lib/freecad/
Log: AppIcon = freecad
Log: BinPath = /usr/lib/freecad/bin/
Log: BuildRepositoryURL = https://code.launchpad.net/~vcs-imports/freecad/trunk
Log: BuildRevision = 4478 (Launchpad)
Log: BuildRevisionDate = 2011/08/28 22:00:32
Log: BuildVersionMajor = 0
Log: BuildVersionMinor = 12
Log: ConsoleBanner = © Juergen Riegel, Werner Mayer, Yorik van Havre 2001-2011
##### #### ### ####
# # # # # #
# ## #### #### # # # # #
#### # # # # # # # ##### # #
# # #### #### # # # # #
# # # # # # # # # ## ## ##
# # #### #### ### # # #### ## ## ##
Log: Debug = 0
Log: DocPath = /usr/lib/freecad/doc/
Log: ExeName = FreeCAD
Log: ExeVendor = FreeCAD
Log: ExeVersion = 0.12
Log: LoggingFile = 1
Log: LoggingFileName = /home/mathieu/.FreeCAD/FreeCAD.log
Log: MaintainerUrl = http://apps.sourceforge.net/mediawiki/free-cad/index.php?title=Main_Page
Log: PATH = /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
Log: PYTHONPATH =
Log: PythonSearchPath = :/usr/bin/../lib/python2.6/:/usr/bin/../lib/python2.6/plat-linux2:/usr/bin/../lib/python2.6/lib-tk:/usr/bin/../lib/python2.6/lib-old:/usr/bin/../lib/python2.6/lib-dynload
Log: RunMode = Gui
Log: SplashAlignment = Bottom|Left
Log: SplashPicture = freecadsplash
Log: SplashTextColor = #ffffff
Log: StartWorkbench = StartWorkbench
Log: SystemParameter = /home/mathieu/.FreeCAD/system.cfg
Log: UserAppData = /home/mathieu/.FreeCAD/
Log: UserHomePath = /home/mathieu
Log: UserParameter = /home/mathieu/.FreeCAD/user.cfg
Log: Verbose =
Log: Create Application
Log: Init: starting App::FreeCADInit.py
Log: Init: Searching for modules...
Log: Init: Initializing /usr/lib/freecad/Mod/Sketcher... done
Log: Init: Initializing /home/mathieu/Téléchargements(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.config(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.face(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/ReverseEngineering... done
Log: Init: Initializing /home/mathieu/.profile(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/Image... done
Log: Init: Initializing /home/mathieu/.gtk-bookmarks(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/PartDesign... done
Log: Init: Initializing /home/mathieu/.bash_aliases(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.dbus(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.fontconfig(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/Musique(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.gconf(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.recently-used.xbel(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/Images(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.pulse-cookie(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.pulse(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.bash_logout(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/VirtualBox(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.adobe(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/Web... done
Log: Init: Initializing /home/mathieu/Documents(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/MeshPart... done
Log: Init: Initializing /home/mathieu/.evolution(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.mplayer(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/Fem... done
Log: Init: Initializing /home/mathieu/.gksu.lock(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.cache(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.compiz(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/Start... done
Log: Init: Initializing /home/mathieu/.ICEauthority(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/Draft... done
Log: Init: Initializing /home/mathieu/.gnome2(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/Test... done
Log: Init: Initializing /usr/lib/freecad/Mod/Import... done
Log: Init: Initializing /home/mathieu/.thumbnails(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.sudo_as_admin_successful(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.openoffice.org(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.icons(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.conkyrc(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.FreeCAD(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/Complete... done
Log: Init: Initializing /home/mathieu/.thunderbird(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.gimp-2.6(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.gstreamer-0.10(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.libreoffice(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/brideur(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/Bureau(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/Raytracing... done
Log: Init: Initializing /home/mathieu/.nautilus(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.gconfd(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/Mesh... done
Log: Init: Initializing /home/mathieu/.xsession-errors(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.gegl-0.0(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.macromedia(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/Part... done
Log: Init: Initializing /home/mathieu/TrackMania(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/Arch... done
Log: Init: Initializing /home/mathieu/.local(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.bash_history(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.hidden(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.synaptic(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.gvfs(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.xsession-errors.old(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/Vidéos(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/Robot... done
Log: Init: Initializing /home/mathieu/.bashrc(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/Points... done
Log: Init: Initializing /home/mathieu/.gnome2_private(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.mozilla(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/TmForever(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.esd_auth(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/Inspection... done
Log: Init: Initializing /usr/lib/freecad/Mod/Drawing... done
Log: Init: Initializing /home/mathieu/.themes(Init.py not found)... ignore
Log: Using /usr/lib/freecad/Mod as module path!
Log: System path after init:
Log: /usr/lib/freecad/bin
Log: /usr/lib/freecad/Mod/Sketcher
Log: /home/mathieu/Téléchargements
Log: /home/mathieu/.config
Log: /home/mathieu/.face
Log: /usr/lib/freecad/Mod/ReverseEngineering
Log: /home/mathieu/.profile
Log: /usr/lib/freecad/Mod/Image
Log: /home/mathieu/.gtk-bookmarks
Log: /usr/lib/freecad/Mod/PartDesign
Log: /home/mathieu/.bash_aliases
Log: /home/mathieu/.dbus
Log: /home/mathieu/.fontconfig
Log: /home/mathieu/Musique
Log: /home/mathieu/.gconf
Log: /home/mathieu/.recently-used.xbel
Log: /home/mathieu/Images
Log: /home/mathieu/.pulse-cookie
Log: /home/mathieu/.pulse
Log: /home/mathieu/.bash_logout
Log: /home/mathieu/VirtualBox
Log: /home/mathieu/.adobe
Log: /usr/lib/freecad/Mod/Web
Log: /home/mathieu/Documents
Log: /usr/lib/freecad/Mod/MeshPart
Log: /home/mathieu/.evolution
Log: /home/mathieu/.mplayer
Log: /usr/lib/freecad/Mod/Fem
Log: /home/mathieu/.gksu.lock
Log: /home/mathieu/.cache
Log: /home/mathieu/.compiz
Log: /usr/lib/freecad/Mod/Start
Log: /home/mathieu/.ICEauthority
Log: /usr/lib/freecad/Mod/Draft
Log: /home/mathieu/.gnome2
Log: /usr/lib/freecad/Mod/Test
Log: /usr/lib/freecad/Mod/Import
Log: /home/mathieu/.thumbnails
Log: /home/mathieu/.sudo_as_admin_successful
Log: /home/mathieu/.openoffice.org
Log: /home/mathieu/.icons
Log: /home/mathieu/.conkyrc
Log: /home/mathieu/.FreeCAD
Log: /usr/lib/freecad/Mod/Complete
Log: /home/mathieu/.thunderbird
Log: /home/mathieu/.gimp-2.6
Log: /home/mathieu/.gstreamer-0.10
Log: /home/mathieu/.libreoffice
Log: /home/mathieu/brideur
Log: /home/mathieu/Bureau
Log: /usr/lib/freecad/Mod/Raytracing
Log: /home/mathieu/.nautilus
Log: /home/mathieu/.gconfd
Log: /usr/lib/freecad/Mod/Mesh
Log: /home/mathieu/.xsession-errors
Log: /home/mathieu/.gegl-0.0
Log: /home/mathieu/.macromedia
Log: /usr/lib/freecad/Mod/Part
Log: /home/mathieu/TrackMania
Log: /usr/lib/freecad/Mod/Arch
Log: /home/mathieu/.local
Log: /home/mathieu/.bash_history
Log: /home/mathieu/.hidden
Log: /home/mathieu/.synaptic
Log: /home/mathieu/.gvfs
Log: /home/mathieu/.xsession-errors.old
Log: /home/mathieu/Vidéos
Log: /usr/lib/freecad/Mod/Robot
Log: /home/mathieu/.bashrc
Log: /usr/lib/freecad/Mod/Points
Log: /home/mathieu/.gnome2_private
Log: /home/mathieu/.mozilla
Log: /home/mathieu/TmForever
Log: /home/mathieu/.esd_auth
Log: /usr/lib/freecad/Mod/Inspection
Log: /usr/lib/freecad/Mod/Drawing
Log: /home/mathieu/.themes
Log: /usr/local/sbin
Log: /usr/local/bin
Log: /usr/sbin
Log: /usr/bin
Log: /sbin
Log: /bin
Log: /usr/games
Log: Init: App::FreeCADInit.py done
Log: Init: Creating Gui::Application and QApplication
Log: X Error: BadRequest (invalid request code or no such operation) 1
Extension: 136 (Uknown extension)
Minor opcode: 19 (Unknown request)
Resource id: 0x5200004
Log: X Error: BadRequest (invalid request code or no such operation) 1
Extension: 136 (Uknown extension)
Minor opcode: 19 (Unknown request)
Resource id: 0x5200004
Log: X Error: BadRequest (invalid request code or no such operation) 1
Extension: 136 (Uknown extension)
Minor opcode: 14 (Unknown request)
Resource id: 0x5200004
Log: QGLTempContext: No GL capable X visuals available.
Log: This system does not support framebuffer objectsLog: X Error: BadRequest (invalid request code or no such operation) 1
Extension: 136 (Uknown extension)
Minor opcode: 19 (Unknown request)
Resource id: 0x5200004
Log: X Error: BadRequest (invalid request code or no such operation) 1
Extension: 136 (Uknown extension)
Minor opcode: 19 (Unknown request)
Resource id: 0x5200004
Log: X Error: BadRequest (invalid request code or no such operation) 1
Extension: 136 (Uknown extension)
Minor opcode: 14 (Unknown request)
Resource id: 0x5200004
Err: Illegal storage access...Err:
Sinon, j'ai hâte de pouvoir tester ça, vous devez fournir un énorme travail.
Bonne continuation dans votre projet.
Dernière modification par Ellypsis (Le 05/09/2011, à 16:46)
Un Geek sportif
Hors ligne
Gemnoc
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Salut,
J'ai vu que tu avais posté sur le forum de FreeCAD. Ton premier résultat est identique au mien, cependant ton second montre qu'il y a un problème. Un truc que je trouve curieux, dans la série des « Log: Init: Initializing... », ça ne me semble pas normal qu'il cherche dans autant de sous-dossiers de ton home. Chez moi, seuls les répertoires système sous /usr sont initialisés.
Mais la raison du blocage est la suivante :
Log: QGLTempContext: No GL capable X visuals available.
Manifestement, il y a un problème avec le pilote graphique, qui ne semble pas avoir activé l'accélération graphique. Tu confirmes que tu as activé le pilote propriétaire, et que les effets visuels sont activés ?
Dernière modification par Gemnoc (Le 05/09/2011, à 17:26)
Hors ligne
Ellypsis
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Le pilote propriétaire est bien activé, mais effectivement, en essayant d'activer les effets visuels, j'ai un problème avec l'accélération graphique, soucis que je n'avais pas avant.
Ce serait donc un problème matériel. En ce moment, j'accumule pas mal de problème, ça commence à me gonfler (mplayer, metacity, carte graphique...).
Je cherche une solution à mon problème et te tiens au courant.
Un Geek sportif
Hors ligne
Ellypsis
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Je viens de réinstaller les pilotes propriétaire, et c'est bon, tout les problème que j'avais ont été résolu (freecad, mplayer, metacity).
J'ai donc pu lancer FreeCAD sans problème.
Je suis vraiment désolé de vous avoir fais poireauter pour une conner** de ce genre -_-''
Dans tous les cas, je vais suivre l'évolution de FreeCAD avec intérêt, j'ai déjà pu constater qu ele logiciel était fluide, avec pas mal de fonctionnalité.
Merci pour votre travail!
Un Geek sportif
Hors ligne
Gemnoc
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Salut,
Content que la résolution du problème fut aussi simple.
Pour ma part je ne fais pas grand chose, à part contribuer à faire connaître le projet. J'aimerais bien aider à la programmation, mais je n'y connais rien. Je voulais apprendre le langage Python afin d'avoir accès aux fonctionnalités qui ne sont pas encore disponibles dans l'interface graphique, mais au rythme où le développement avance, je n'en aurai peut-être pas besoin !
Hors ligne
Alain16
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Bonjour,
Je viens de prendre contact avec le logiciel,
je l'utiliserai pour du dessin mécanique 2D
ayant souvent besoin de mêmes éléments je recherche une bibliothèque de dessin,j'ai pas vu, cela existe t'il ?
installation, lancement aucun soucis
Alain
Hors ligne
Gemnoc
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Salut,
Il me semble qu'il n'y a aucune bibliothèque actuellement. À la base FreeCAD est surtout un outil destiné à la 3D ; si tu ne compte travailler qu'en 2D, je crois que tu serais mieux avec QCad qui dispose déjà d'une bibliothèque d'éléments mécaniques.
Hors ligne
Alain16
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Salut,
je vais aller voir QCad
merci
Hors ligne
captaineflam
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Et non mon cher jcg, cela ne fait plus mal de parler de çà depuis que Dassault a développé son logiciel.
Le meilleur et gratuit : Drafsight. Une copie conforme d'Autocad, convivial et simple d'utilisation. Disponible sous tous les windows, les linux et mac! Merci Dassault.
http://www.3ds.com/fr/products/draftsig … raftsight/
Technicien DAO-SIG
Acer Aspire 7220
Lubuntu 13.10
Hors ligne
Gemnoc
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
J'ai l'impression que captaineflam s'est trompé de sujet, je n'ai pas vu de jcg dans cette enfilade.
Et puis DraftSight a déjà été mentionné à maintes reprises (ou est-ce dans le sujet « AutoCAD-Like »?)... D'autre part, sachant le contenu discutable du CLUF (prenez donc la peine de le lire !), certains préférerons uns solution libre certes moins évoluée et conviviale, mais plus respectueuse de leurs valeurs.
Hors ligne
captaineflam
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Tu tappe là ou ça fait mal
Tu trouveras pas grand chose de qualité malheureusement.
C'est quoi ça, il ne s'appelle pas jcg peut-être!? Il faut lire les discussions mon cher.
Voici le titre du sujet : Logiciel de CAO 2D/3D (Conception Mecanique). Ce n'est pas logiciel libre dao.
Je donne donc mon avis sur le sujet posté. Si tu veux créer un sujet sur les logiciels libres, vas-y!
Dernière modification par captaineflam (Le 08/09/2011, à 12:47)
Technicien DAO-SIG
Acer Aspire 7220
Lubuntu 13.10
Hors ligne
captaineflam
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Pour la question du libre, je ne vois pas du tout l'intérêt de s'obstiner à vouloir utiliser un logiciel libre pour ce genre de logiciel.
Au contraire, si des boîtes privées investissent pour mettre gratuitement des logiciels à notre disposition on ne peut que s'en réjouir.
De plus Dassault n'interdit pas le fait d'utiliser son logiciel à des fins commerciales, ce qui est plutôt rare de nos jours de la part de grands groupes, faire des cadeaux....
Technicien DAO-SIG
Acer Aspire 7220
Lubuntu 13.10
Hors ligne
Pirrote
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Il est certes remarquable que des logiciel de ce type soit distribuer gratuitement. Toutefois, je pense que de tels logiciels doivent pouvoir se trouvé en libre. Ceci permettra à chacun d'utiliser ce logiciel et étudier sont code afin d'y apporter des corrections ou apporter des plugins facilement.
Pirrote
Pour promouvoir les Logiciels Libres et Linux à Poitiers, Rejoignez-nous:
- Site : http://www.app3l.org
Vous avez trouvé la solution à vos problèmes, postez-là et pensez à mettre [RÉSOLU] sur les titres de vos post
Hors ligne
sam7
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
J'ai l'impression que captaineflam s'est trompé de sujet, je n'ai pas vu de jcg dans cette enfilade.
Et puis DraftSight a déjà été mentionné à maintes reprises (ou est-ce dans le sujet « AutoCAD-Like »?)... D'autre part, sachant le contenu discutable du CLUF (prenez donc la peine de le lire !), certains préférerons uns solution libre certes moins évoluée et conviviale, mais plus respectueuse de leurs valeurs.
tu as bien raison quand j'ai commencer à le lire ... j'ai vite déchanté et je ne suis pas allé jusqu'à la fin de ma lecture & j'ai cliqué sur "annuler".
Hors ligne
Gemnoc
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
jcg a écrit :
Tu tappe là ou ça fait mal
Tu trouveras pas grand chose de qualité malheureusement.
C'est quoi ça, il ne s'appelle pas jcg peut-être!? Il faut lire les discussions mon cher.
Dis donc le farceur, tu te rends compte que tu as répondu au second message de cette enfilade de 12 pages et plus de 290 réponses, et que ce message DATE DE 2006 ?????
De un, est-ce que j'ai le droit de ne pas me rappeler les réponses d'il y a plus de 5 ans ?
(Petit cours sur les forums et les notifications de nouvelles réponses par courriel, auxquelles la plupart de ceux qui échangent dans ce sujet sont abonnés : les liens envoient toujours vers la dernière réponse reçue, donc la toute fin du sujet, pas le début. Ça va, tu piges ?)
De deux, si tu es pour déterrer d'aussi vieilles réponses, c'est trop compliqué de citer le message au passage ?
De trois, la réponse de jcg était tout à fait justifiée il y a 5 ans, car il n'y avait ni de Bricscad, ni de ARES, ni de DrafSight. Tu as donc deux trains de retard !!!
Pffff. La crédibilité de captaineflam = un gros zéro.
Hors ligne
YannUbuntu
Hors ligne
captaineflam
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
j'ai pas à être crédible ou pas tête de bite, t'es à une compétition ou quoi!?
Donnes moi ton msn que je vienne te montrer si je suis crédible.
Technicien DAO-SIG
Acer Aspire 7220
Lubuntu 13.10
Hors ligne
captaineflam
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Et comme je t'ai dit si tu veux parler d'autre chose ouvre un nouveau sujet, c'est valable pour toi aussi le tocard qui perd 5 minutes le temps que ça monte au cerveau.
Technicien DAO-SIG
Acer Aspire 7220
Lubuntu 13.10
Hors ligne
peterp@n
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Oua captainflam ! Ne t'enflammes pas comme ça !
@Gemnoc et aux autres qui préfèrent le libre :
Je commence à tester FreeCAD depuis qu'il y a le module Architecture. Savez vous si il est prévu un module associé pour du calcul de structure ? Et un autre module pour du métré ?
Ubuntu 12.04 64bits, Raspbian “wheezy”, Tango Studio sauce debian
Un bureau d'études techniques pour le bâtiment avec des logiciels libre.
Entreprise de construction bois. - Formations FreeCAD (logiciel 3d)
Hors ligne
slasher-fun
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
captaineflam nous a quitté pour quelques temps, merci de revenir au sujet initial (s'il y en avait un)
Hors ligne
Gemnoc
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Mais quel abruti ce captaineflam.
D'autre part, c'est clair qu'il n'a absolument rien compris de la philosophie d'Ubuntu et de GNU/Linux en général. Beaucoup de gens (la plupart ?) sont attirés sur cette plateforme parce qu'ils veulent s'affranchir des pratiques du logiciel commercial. Or, DraftSight bien que gratuit opère sous le même modèle. Qui dit qu'ils vont continuer à offrir leur logiciel gratuitement dans 2 ans, 5 ans ? Je l'ai déjà mentionné, ce n'est pas par altruisme que Dassault a décidé d'offrir DraftSight gratuitement, mais dans le cadre de sa stratégie de concurrence et de marketing face à Autodesk et son produit-phare AutoCAD. Le but principal est d'attirer des clients utilisateurs d'AutoCAD vers SolidWorks en leur disant, cessez de payer pour de la 2D, achetez-vous plutôt des licences de SolidWorks et utilisez DraftSight pour vos dessins DWG existants. Qu'aucune interdiction d'utiliser le logiciel à des fins commerciales ne soit imposée était donc logique, et il n'y a pas de cadeau ici. Mais si dans 5 ans, Dassault décidait de changer de stratégie et de ne fournir DraftSight qu'avec SolidWorks ? Car c'était le cas avec DWGEditor, qui a précédé DraftSight.
Il est indéniable qu'à l'heure actuelle, il n'existe aucun logiciel libre sous Linux qui soit au niveau de DraftSight. Il n'y a même pas de logiciel libre qui puisse ouvrir les fichiers DWG. Je comprends donc tout à fait ceux qui feront le choix d'accepter le CLUF de DraftSight, de fournir leur adresse de courriel et de l'utiliser. Je l'ai fait moi-même, bien qu'il soit extrêmement rare que je me serve de DraftSight.
Mais, nous sommes sur un forum consacré à Ubuntu, et de ce fait, il m'apparaît tout à fait justifié de mentionner cette réalité, et l'alternative, afin que ceux que ça intéresse fassent leur choix en toute connaissance de cause.
Dernière modification par Gemnoc (Le 10/09/2011, à 18:25)
Hors ligne
Gemnoc
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Je commence à tester FreeCAD depuis qu'il y a le module Architecture. Savez vous si il est prévu un module associé pour du calcul de structure ? Et un autre module pour du métré ?
Salut peterp@n,
À ma connaissance il n'y a rien de prévu officiellement, bien que ça pourrait être ajouté si quelqu'un avec les connaissances se portait volontaire. Le module Architecture est développé à temps perdu par Yorik, un architecte qui est l'auteur du module Draft (Mise en plan). Peut-être a-t-il prévu un module de métré, car son but est d'offrir des fonctionnalités de BIM. Cependant il est l'unique contributeur à ce sous-projet, ça pourrait prendre bien du temps.
L'équipe de développement de FreeCAD est très réduite, et se concentre en ce moment sur les outils de création de pièces mécaniques. Elle a bénéficié cet été du travail assidu de deux contributeurs qui se sont greffés au projet, et qui ont fait avancer rapidement le module Sketcher. Ils ont même commencé à travailler sur le module PartDesign. Mais je crois qu'il a été décidé de bientôt geler les fonctionnalités de ces deux modules et de se concentrer sur le déboguage afin de planifier la sortie d'une version finale 0.12.
Hors ligne
Gemnoc
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Bonsoir / bonne nuit / bon matin amateurs de CAO,
Des nouvelles sur le développement de FreeCAD. Un mois s'est écoulé depuis que j'ai posté ma première vidéo, et les améliorations au Sketcher* sont impressionnantes ! Voici les principales :
Dans le cas d'une esquisse sans support, une fenêtre de dialogue demande le choix d'un plan de travail
La case "popup" qui permet de saisir une valeur pour les contraintes dimensionnelles pré-selectionne maintenant la valeur, il suffit de saisir la dimension désirée (préalablement il fallait sélectionner manuellement la valeur par défaut)
Nouveaux outils ajoutés : ligne de construction, congé ("fillet"), ajuster ("trim")
Contraintes appliquées automatiquement lors du dessin avec le mode "Auto constraints" et l'indicateur visuel à côté du pointeur
L'esquisse passe au vert lorsqu'elle est pleinement contrainte
Nouveauté d'hier : une boîte texte "Sketcher Messages" indique le nombre de degrés de liberté restant afin de contraindre pleinement l'esquisse.
Le module PartDesign s'est vu ajouter un nouveau dialogue dans l'onglet Tâches lors de la création d'une extrusion. Les outils "Poche" et "Extrusion" devraient aussi être peaufinés avant la sortie de la v0.12 finale, et la traduction française mise à jour.
Désolé, la vidéo est un peu longue (4min28). On voit aussi encore quelques bogues, notamment la grille de dessin qui disparaît et réapparaît, ou encore l'esquisse qui ne devient pleinement contrainte qu'en modifiant une des dimensions ajoutées avec la contrainte « verrou ».
*J'attends toujours vos commentaires sur ma suggestion de traduction pour « Sketcher » : Esquisseur ?
Édition : vidéo ajoutée.
Dernière modification par Gemnoc (Le 21/09/2011, à 03:55)
Hors ligne
|
I have a list and want to pass thru django raw sql.
Here is my list
region = ['US','CA','UK']
I am pasting a part of raw sql here.
results = MMCode.objects.raw('select assigner, assignee from mm_code where date between %s and %s and country_code in %s',[fromdate,todate,region])
Now it gives the below error, when i execute it in django python shell
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 1412, in __iter__
query = iter(self.query)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 73, in __iter__
self._execute_query()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 87, in _execute_query
self.cursor.execute(self.sql, self.params)
File "/usr/local/lib/python2.6/dist-packages/django/db/backends/util.py", line 15, in execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.6/dist-packages/django/db/backends/mysql/base.py", line 86, in execute
return self.cursor.execute(query, args)
File "/usr/lib/pymodules/python2.6/MySQLdb/cursors.py", line 166, in execute
self.errorhandler(self, exc, value)
File "/usr/lib/pymodules/python2.6/MySQLdb/connections.py", line 35, in defaulterrorhandler
raise errorclass, errorvalue
DatabaseError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1")
I have tried by passing the tuple also but there is no use. Can some one help me.
Thanks Vikram
|
I need to write a function that takes an original list of unique values and a resulting list:
[0,1,2,3][0,3,1,2]
and detect that only a single element was moved then report exactly what was moved where. If the resulting list is not the result of moving exactly one item from source to destination, this code should fail.
Here are some examples:
[0,1,2,3][0,3,1,2]
location 3 was moved to location 1
Failure cases (not exactly one move could be detected) include:
[4,1,2,3][1,3,1,2]
(before/after have different items)
[1,1,2,3][1,3,1,2]
(before has duplicate values)
[4,5,1,2,3][1,3,1,2]
(before/after not the same size)
My basic approach is to iterate both lists simultaneously until there's a difference. If the destination list has a different item, then we see if the next item matches the source lists current item. This indicates that something has been inserted at this point. We then move forward the destination list and proceed. We notice removals in a similar process. If the we've decided its not an insertion, that is two items are not equal but the source does NOT continue in the destination list, then we treat it as a removal.
In the case of an insertion, we only move the destination list forward. We expect the rest of the dest list/src list to match up until we detect a removal. In the case of detecting a removal, we move forward the source list. If both elements are equal, we move them both forward.
For example:
original: result: 1----------4 // not equal, peek ahead and compare 1==1, this is just an insertion 2--- \-----1 // 1 == 1 same 3-- \------2 // 2 == 2 same 4- \-------3 // 3 == 3 same \-------- // result exhausted, removaloriginal: result: 1----\-----4 // not equal, peek ahead and compare 1==1, this is an insertion, move just result ahead 1 2--\ \----1 // 1 == 1 same 3-\ \------2 // 2 == 2 same 4\ \-------3 // 3 == 3 same \-------- // result exhausted, removaloriginal: result: 1----\-----4 // not equal, peek ahead and compare 1==1, this is an insertion, move just result ahead 1 2--\ \----1 // 1 == 1 same 3-\ \------2 // 2 == 2 same 4\ \-------3 // 3 == 3 same \-------- // result exhausted, removaloriginal: result: 1----------1 // 1 == 1 2--\ ------3 // 2 != 3, but peek ahead 2==2 insertion at 1, move just result ahead 1 3-\ \------2 // 2 == 2 same 4\ \-------4 // 3 != 4 removal \-------- // result exhausted
Here's my solution so far. It uses an iterator I created that comes with bells and whistles to peek ahead, get the current value, get the current index etc:
class _ListIter(object):
""" Iterate a list, expose some information such as
the current index (.index()) and the current value (.curr())"""
def __init__(self, l):
self.l = l
self._idx = 0
def __iter__(self):
return self
def next(self):
self._idx += 1
if (self._idx > len(self.l)):
raise StopIteration
val = self.l[self._idx - 1]
return val
def index(self):
""" Return index of current value, -1 if next hasn't
been called yet"""
return self._idx - 1
def curr(self):
""" Return current value, None if next hasn't
been called yet"""
if self.index() == -1 or self.exhausted():
return None
else:
return self.l[self.index()]
def peek(self):
if self.index() + 1 >= len(self.l):
return None
return self.l[self.index() + 1]
def numLeft(self):
return len(self.l) - self._idx
def exhausted(self):
return (self._idx > len(self.l))
In this module are some helper functions:
def _fwd(*args):
for arg in args:
try:
next(arg)
except StopIteration:
pass
def _areListsCandidates(original, result):
origSet = set(original)
resSet = set(result)
return (len(original) == len(result) == len(origSet) == len(resSet)) and (origSet == resSet)
And finally the algorithm implemented itself:
def findMove(original, result):
if (not _areListsCandidates(original, result)):
return None
orig, res = _ListIter(original), _ListIter(result)
fromVal, toVal, fromIdx, toIdx = None, None, None, None
_fwd(orig, res)
while not (orig.exhausted() and res.exhausted()):
def isInsertion():
if orig.curr() != res.curr():
return orig.exhausted() or (res.numLeft() > 0 and orig.curr() == res.peek())
return False
def isRemoval():
return (orig.exhausted() or orig.curr() != res.curr())
if isInsertion():
toVal, toIdx = res.curr(), res.index()
_fwd(res)
elif isRemoval():
fromVal, fromIdx = orig.curr(), orig.index()
_fwd(orig)
else:
_fwd(orig, res)
if (fromIdx is not None and toIdx is not None and fromVal == toVal):
return (fromIdx, toIdx)
I fully expect somebody to point me to a Python library I missed or to 3 lines of itertools craziness that does this more intelligently.
I would like feedback on the approach used and style. I feel like I should be doing something more intelligently here, or there's an approach I'm not familiar with for this problem. I also feel like the code isn't terribly pythonic or elegant.
To help, here are my tests:
from findMove import findMove
from copy import copy
def testBackToFront():
(fromIdx, toIdx) = findMove(original=[1,2,3,4], result=[4,1,2,3])
assert(fromIdx == 3)
assert(toIdx == 0)
def testFrontToBack():
(fromIdx, toIdx) = findMove(original=[4,1,2,3], result=[1,2,3,4])
assert(fromIdx == 0)
assert(toIdx == 3)
def testMove():
# Arbitrarilly reposition where insValue comes from
# and goes to
original = [1,2,3,5,6,7,8,9]
result = [1,2,3,5,6,7,8,9]
insValue = 4
for origIdx in range(len(original) + 1):
origCpy = copy(original)
origCpy.insert(origIdx, insValue)
for insIdx in range(len(original) + 1):
resCpy = copy(result)
resCpy.insert(insIdx, insValue)
if (resCpy != origCpy):
(fromIdx, toIdx) = findMove(origCpy, resCpy)
if fromIdx < toIdx:
if abs(origIdx - insIdx) == 1:
assert(fromIdx == origIdx or fromIdx == insIdx)
assert(toIdx == insIdx or toIdx == origIdx)
assert(toIdx != fromIdx)
else:
assert(fromIdx == origIdx)
assert(toIdx == insIdx)
def testEmptyLists():
assert(findMove([], []) is None)
def testEqualLists():
assert(findMove([1], [1]) is None)
def testSmallLists():
(fromIdx, toIdx) = findMove([2,1], [1,2])
assert(fromIdx == 1 or fromIdx == 0)
assert(toIdx == 0 or toIdx == 1)
assert(toIdx != fromIdx)
def testDiffLenFails():
res = findMove(original=[1,2,3,4], result=[4,1,2,3,5])
assert(res is None)
def testDiffValsFails():
res = findMove(original=[1,2,3,4], result=[1,2,3,5])
assert(res is None)
def testDups():
res = findMove(original=[1,1,3,4], result=[1,1,4,3])
assert(res is None)
res = findMove(original=[1,1,1,1], result=[1,1,1,2])
assert(res is None)
|
jbfabin
mise à jour / téléchargement des paquets impossibles
Bonjour, quand je veux mettre à jour mon système, j'obtiens le message :"le téléchargement des informations du dépot a échoué".
si quelqu'un peut m'aider, je lui serai reconnaissant.
PS : au terminal, j'obtiens ces messages :
W: Impossible de récupérer http://extras.ubuntu.com/ubuntu/dists/n … ce/Sources 404 Not Found
W: Impossible de récupérer http://extras.ubuntu.com/ubuntu/dists/n … 6/Packages 404 Not Found
E: Le téléchargement de quelques fichiers d'index a échoué, ils ont été ignorés, ou les anciens ont été utilisés à la place.
Hors ligne
ljere
Re : mise à jour / téléchargement des paquets impossibles
merci de donner le retour de
cat /etc/apt/sources.list
ls /etc/apt/sources.list.d
cat /etc/apt/sources.list.d/*
merci de mettre le retour de ces commandes entre des balises code c'est l'icone <> au dessus de la zone de texte
Hors ligne
jbfabin
Re : mise à jour / téléchargement des paquets impossibles
Bonjour, merci de m'avoir répondu.
Voici le retour de "cat /etc/apt/sources.list" :
jbfabin@jbfabin-Q310:~$ cat /etc/apt/sources.list
# deb cdrom:[Ubuntu 11.04 _Natty Narwhal_ - Release i386 (20110427.1)]/ natty main restricted
# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
deb http://fr.archive.ubuntu.com/ubuntu/ natty main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu/ natty main restricted
## Major bug fix updates produced after the final release of the
## distribution.
deb http://fr.archive.ubuntu.com/ubuntu/ natty-updates main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu/ natty-updates main restricted
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team. Also, please note that software in universe WILL NOT receive any
## review or updates from the Ubuntu security team.
deb http://fr.archive.ubuntu.com/ubuntu/ natty universe
deb-src http://fr.archive.ubuntu.com/ubuntu/ natty universe
deb http://fr.archive.ubuntu.com/ubuntu/ natty-updates universe
deb-src http://fr.archive.ubuntu.com/ubuntu/ natty-updates universe
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
deb http://fr.archive.ubuntu.com/ubuntu/ natty multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ natty multiverse
deb http://fr.archive.ubuntu.com/ubuntu/ natty-updates multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ natty-updates multiverse
## Uncomment the following two lines to add software from the 'backports'
## repository.
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
# deb http://fr.archive.ubuntu.com/ubuntu/ natty-backports main restricted universe multiverse
# deb-src http://fr.archive.ubuntu.com/ubuntu/ natty-backports main restricted universe multiverse
deb http://security.ubuntu.com/ubuntu natty-security main restricted
deb-src http://security.ubuntu.com/ubuntu natty-security main restricted
deb http://security.ubuntu.com/ubuntu natty-security universe
deb-src http://security.ubuntu.com/ubuntu natty-security universe
deb http://security.ubuntu.com/ubuntu natty-security multiverse
deb-src http://security.ubuntu.com/ubuntu natty-security multiverse
## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
deb http://archive.canonical.com/ubuntu natty partner
deb-src http://archive.canonical.com/ubuntu natty partner
## This software is not part of Ubuntu, but is offered by third-party
## developers who want to ship their latest software.
deb http://extras.ubuntu.com/ubuntu natty main
deb-src http://extras.ubuntu.com/ubuntu natty main
deb http://fr.archive.ubuntu.com/ubuntu/ natty-proposed restricted main multiverse universe
Voici le retour de "ls /etc/apt/sources.list.d" :
jbfabin@jbfabin-Q310:~$ ls /etc/apt/sources.list.d
opera.list opera.list.save
Et le retour de "cat /etc/apt/sources.list.d/*" :
jbfabin@jbfabin-Q310:~$ cat /etc/apt/sources.list.d/*
# This file makes sure that Opera Browser is kept up-to-date
# as part of regular system upgrades
deb http://deb.opera.com/opera/ stable non-free #Opera Browser (final releases)
# The line above will make sure you get all final public releases.
# Uncomment the following line if you want to get alpha and beta
# releases, too.
# deb http://deb.opera.com/opera-beta/ stable non-free #Opera Browser (beta releases)
# This file makes sure that Opera Browser is kept up-to-date
# as part of regular system upgrades
deb http://deb.opera.com/opera/ stable non-free #Opera Browser (final releases)
# The line above will make sure you get all final public releases.
# Uncomment the following line if you want to get alpha and beta
# releases, too.
# deb http://deb.opera.com/opera-beta/ stable non-free #Opera Browser (beta releases)
Hors ligne
ljere
Re : mise à jour / téléchargement des paquets impossibles
en effet tu es encore sur natty qui n'est plus soutenu tu dois soit passer sur oneiric ou precise
regarde ici migration_natty_oneiric
Hors ligne
jbfabin
Re : mise à jour / téléchargement des paquets impossibles
je voulais rester sur la version 11.04, car je trouve que mon ordinateur est plus lent avec les versions récentes d'ubuntu. Il n'y a pas moyen d'arranger ça ?
Hors ligne
ljere
Re : mise à jour / téléchargement des paquets impossibles
si utiliser un environnement plus léger comme xfce ou lxde
Hors ligne
Korak
Re : mise à jour / téléchargement des paquets impossibles
Bonjour,
Je te conseille de passer sous Ubuntu 12.04 (Precise) qui est une version LTS maintenue pendant 5 ans (jusqu'en avril 2017).
Sauf si ton PC n'est pas assez puissant. Peux-tu nous dire ce qu'il a dans le coco:
- Processeur?
- Taille de la RAM?
- Carte graphique?
OS: Ubuntu 14.04 64 bits + Windows 8.1 64 bits en dualboot (BIOS UEFI, Secure Boot activé et table de partitions GPT)
PC portable HP Pavilion g7-2335sb: Processeur: AMD A4-4300M APU Carte graphique: AMD Radeon HD 7420G Mémoire vive: 6 Go RAM
Je suis Parrain-Linux
Hors ligne
jbfabin
Re : mise à jour / téléchargement des paquets impossibles
Voilà les caractéristiques de mon PC :
la RAM : 2,9GO
processeur (2) : Intel(R) Core(TM)2 Duo CPU P8400 @2,26GHz
carte graphique : GeForce 9200M GS
Hors ligne
Korak
Re : mise à jour / téléchargement des paquets impossibles
Pour moi, ton PC doit faire tourner correctement Ubuntu 12.04.
OS: Ubuntu 14.04 64 bits + Windows 8.1 64 bits en dualboot (BIOS UEFI, Secure Boot activé et table de partitions GPT)
PC portable HP Pavilion g7-2335sb: Processeur: AMD A4-4300M APU Carte graphique: AMD Radeon HD 7420G Mémoire vive: 6 Go RAM
Je suis Parrain-Linux
Hors ligne
jbfabin
Re : mise à jour / téléchargement des paquets impossibles
ok, merci.
J'imagine par contre que si j'installe cette version, je perdrais tous mes réglages actuelles et que je devrais mettre mes documents sur un autre disque.
Hors ligne
Korak
Re : mise à jour / téléchargement des paquets impossibles
Personnellement, je préfère faire une nouvelle installation. Ça permet d'avoir un nouveau système tout propre et du coup de virer tout ce que l'on utilise plus. Par après, on installe les logiciels désirés au fur et à mesure des besoins.
Maintenant, tu peux éventuellement tenter de faire une mise-à-niveau vers Ubuntu 11.10 puis une mise-à-niveau vers Ubuntu 12.04 (chose que je n'apprécie pas trop mais qui conserve tes réglages et documents).
De toute façon, il est vachement conseillé de faire une sauvegarde des données sur un support externe avant de faire quoi que ce soit d'autre. On ne sait jamais ce qui peut arriver lors de la mise-à-niveau.
OS: Ubuntu 14.04 64 bits + Windows 8.1 64 bits en dualboot (BIOS UEFI, Secure Boot activé et table de partitions GPT)
PC portable HP Pavilion g7-2335sb: Processeur: AMD A4-4300M APU Carte graphique: AMD Radeon HD 7420G Mémoire vive: 6 Go RAM
Je suis Parrain-Linux
Hors ligne
jbfabin
Re : mise à jour / téléchargement des paquets impossibles
Merci de tes conseils, je pense que je vais faire une nouvelle installation.
Hors ligne
|
corgx
questions de newbie
J'ai plusieurs questions à propos de l'installation de fichiers dans ubuntu et j'ai décidé de les poser ici car ça concerne principalement les lecteurs:
-Je n'ai pas compris comment foctionne synaptic: les paquets qu'il propose sont-ils stockés sur mon ordinateur où il les télécharge avant de les installer ? Et si c'est le cas à partir de quoi?
-Est ce que le plugin mplayer pour firefox peut lire les vidéos comme windows media player (notamment ici
-Je n'arrive pas à utiliser le guide car pour beaucoup de programme, il demande de modifier un fichier pour pouvoir installer un paquet supplementaire, or mon fichier ne correspond pas à celui présenté dans le guide. De plus est-ce que ces paquets supplémentaires apparaissent dans synaptic ?
-Comment fonctinnent les codecs: est ce que tous les lecteurs utilisent les mêmes où faut-il les réinstaller à chaque fois ?
-Est ce que la console est indispansabla pour faire fonctionner linux, comme semble l'indiquer le guide ? et si oui où pourrais-je trouver une doculmentation sur les commandes, plutôt que de copier bêtement celles du guide
Je précise que j'ai déjà cherché des réponses, dans ce forum et ailleur, mais je n'en ai pas trouvé,
Hors ligne
laurent
Re : questions de newbie
Salut
1. Synaptic est un logiciel qui permet d'installer les progs. Ca tu l'avais compris. En fait, il existe des dépots contenant les "paquets" (en gros: les logiciels) sur internet (serveurs http ou ftp). Synaptic se connecte à ses serveurs et obtient la liste des paquets présents dans les différents dépots que tu lui as indiqué. Par la suite, lorsque tu sélectionne un paquet, il le télécharge et l'installe. Aussi simple que ça.
Plus d'infos:
http://www.ubuntu-fr.org/articles/introduction_synaptic/
http://www.ubuntu-fr.org/articles/systeme_depot/
2. Oui, il y a moyen de la manière dont tu le présente. On peut installer mplayer et son plugin pour firefox. Là où le bât blesse, c'est pour le format: bien que le wma soit partiellement supporté, ce n'est pas toujours ça. Hélas, ce format propriétaire de microsoft se répand de plus en plus et les codecs libres ne sont pas toujours efficaces à 100%. Tu peux remercier le type avec les lunettes et le grand sourire.
3. Comprends pas pourquoi ça ne marche pas. Peut-être n'as-tu pas activé les dépots nécessaires. Et concernant l'absence des fichiers à éditer, ça me parait plus qu'étrange. Pourrais-tu dire lesquels. Et es-tu sous ubuntu ou kubuntu. Auquel cas, tu devras utiliser kate ou kwrite et non gedit.
4. Non, bienvenue dans un système centralisé, et pas bordelique. Toutes les librairies sont gérées par synaptic qui fait le lien entre tous les paquets installé lors de l'install. Rien n'existe en doublon. Concernant les codecs, de manière plus précise, certains logiciels (xine) se basent sur des codecs pour les divx, tandis que mplayer ou vlc en utilisent d'autres (ffmpeg) mais je pense pas que ce soit le but de ta question.
5. Non, une console n'est pas indispensable. Simplement, il est quand meme beaucoup plus aisé de dire aux gens de taper un truc dans leur terminal, plutot que de dire "allez dans le répertoire gnagnagna, ouvrez le fichier, taper ça dedans..." (gedit /lerépertoire/lefichier = bien plus simple) ou encore "sélectionnez les paquet brol, truc et chose" alors que apt-get brol truc chose est plus court.
Remarque générale, à prendre avec philosophie: il va te falloir te défaire de tes habitudes windowsiennes et ne plus y faire référence. Ca ne sert à rien, mieux vaut tout réapprendre depuis le début plutot que de vouloir "faire le lien"
www.lea-linux.org => tu devrais y trouver les commandes de base du terminal.
Laurent, petit belge explorant la banquise
Hors ligne
moijbt
Re : questions de newbie
On va prendre les questions dans l'ordre:
1) Synaptic: Les paquets qu'il te propose proviennet d'internet. Ils sont stockés sur des serveurs auquel ton ordi a accès par les adresses que tu as rentré dans le fichier /etc/apt/sources.list . Ils sont téléchargés avant d'être installé mais tout celà se fait automatiquement.
2)plugin mplayer chez moi ca marche pour les guignols à l'adresse que tu m'as donné donc la réponse est oui
3) le guide je comprends pas ce que tu veut dire...
4) les codecs une bonne partie d'entre eux seront installés avec xine (lecteur vidéo) le reste se trouve dans le paquet w32codecs, tu ne les installe qu'une seule fois.
5) la console Je pense qu'on peut à peu près tout faire sans mais c'est tellement plus efficace et plus rapide avec que je te conseille d'apprendre à t'en servir. Si vraiment tu y es allergique, ca doit être possible de fonctionner sans. Pour en apprendre beaucoup sur les commandes et sur Linux en général, je te conseille le Lea-book que tu trouveras à cette adresse :www.lea-linux.org
Enfin, la chose la plus importante est l'envie et la motivation, Linux n'est pas facile au début, il faut perdre ses réflexes windowsiens mais ce forum est là pour te guider et l'apprentissage est très rapide !
Bon Courage !
EDIT: Et merde, encore grillé ! Je t'aurai un jour Laurent !
Dernière modification par moijbt (Le 11/06/2005, à 17:06)
Hors ligne
laurent
Re : questions de newbie
EDIT: Et merde, encore grillé ! Je t'aurai un jour Laurent !
Tu peux toujours courir, lol
Au moins ce qui est bien cest qu'on est super cohérent. La classe!
Laurent, petit belge explorant la banquise
Hors ligne
corgx
Re : questions de newbie
merci por vos réponses. Pour le guide, je n'arrive pas à activer ces dépots, justement:il demande ici de modifier lefichier sources.liste mais le mien ne corespond pas à celui présenté, du coup je ne sais pas comment le modifier
voici mon fichier:
deb cdrom:[Ubuntu 5.04 _Hoary Hedgehog_ - Release i386 (20050407)]/ hoary main restricted
deb http://fr.archive.ubuntu.com/ubuntu hoary main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu hoary main restricted
## Major bug fix updates produced after the final release of the
## distribution.
deb http://fr.archive.ubuntu.com/ubuntu hoary-updates main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu hoary-updates main restricted
## Uncomment the following two lines to add software from the 'universe'
## repository.
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## universe WILL NOT receive any review or updates from the Ubuntu security
## team.
# deb http://fr.archive.ubuntu.com/ubuntu hoary universe
# deb-src http://fr.archive.ubuntu.com/ubuntu hoary universe
deb http://security.ubuntu.com/ubuntu hoary-security main restricted
deb-src http://security.ubuntu.com/ubuntu hoary-security main restricted
# deb http://security.ubuntu.com/ubuntu hoary-security universe
# deb-src http://security.ubuntu.com/ubuntu hoary-security universe
Sinon, j'ai une autre question: j'ai installé realplayer mais je n'ait pas de racourcis dans le menu applications, donc je me demande commant en ajouter un, faut il l'installer dans un répertoire particulier ?
Dernière modification par corgx (Le 11/06/2005, à 19:39)
Hors ligne
laurent
Re : questions de newbie
Salut, ton fichier sources.list est un fichier tout ce qu'il y a de plus normal... Pas de prob de ce côté...
=> pour ajouter un dépot, tu copies juste la ligne qui commence par deb dans ce fichier...
=> pour en activer un, tu retires le # devant la ligne ou tu le fais via synaptic
pour éditer le menu:
sudo apt-get install smeg
smeg
Laurent, petit belge explorant la banquise
Hors ligne
|
Is there a way to find out if the user has entered any data in the terminal window without having to use the blocking stdin.
I am implementing a chat client using twisted python and the client code should display messages from other connected clients. As soon as the client enters a message and hits enter, i want it to run an event driven loop, which sends the message to the server, which then broadcasts it to every other client.
In short, I am trying to look for a way to detect when the user hits ENTER or enters some text in the terminal without having to block the program.
UPDATE: Client code so far..
class MyClientProtocol( protocol.Protocol ):
def sendData( self ):
message = raw_input( 'Enter Message: ' )
if message and ( message != "quit()" ):
logging.debug( " ...Sending %s ...", message )
self.transport.write( str( message ) )
else:
self.transport.loseConnection()
def connectionMade( self ):
print "Connection made to server!"
def dataReceived( self, msg ):
print msg
self.sendData()
class MyClientFactory( protocol.ClientFactory ):
protocol = MyClientProtocol
clientConnectionLost = clientConnectionFailed = lambda self, connector, reason: reactor.stop()
reactor.connectTCP( HOST, PORT, MyClientFactory() )
reactor.run()
This code only currently only accepts the user input after receiving something from back from the server, as i am calling sendData in dataReceived. Any suggestions on how i can make this pick up user entered data, plus also keep getting data from the server?
|
michcauch
my-weather-indicator ne fonctionne plus après mise à jour
my-weather-indicator ne fonctionne plus, juste après une mise à jour de my-weather-indicator sous 12.04. J'ai ce message d'erreur quand je le lance depuis un terminal :
michel@bureau:~$ my-weather-indicator
Traceback (most recent call last):
File "/usr/bin/my-weather-indicator", line 26, in <module>
import gi
ImportError: No module named gi
michel@bureau:~$
Je l'ai désinstallé et réinstallé, même message.
Je l'ai désinstallé, réinstallé, purgé les fichiers de configuration, même message.
Une idée ?
Dernière modification par michcauch (Le 22/12/2012, à 12:34)
Cordialement
Michel
___
Ubuntu 14.04 sur Lenovo ThinkPad Edge E320 et Xubuntu 13.10 sur PC fixe.
Hors ligne
DAnGk41
Re : my-weather-indicator ne fonctionne plus après mise à jour
Moi même chose, d'abord ce fut "minimize-unminimise", maintenant "my weather indocator", autant de petits trucs énervants, j'en viens presque à redouter les mises à jour.... (12.04.1 lts)
Hors ligne
ljere
Re : my-weather-indicator ne fonctionne plus après mise à jour
essaye
sudo apt-get install python3-gi python3-dbus python3-cairo
Hors ligne
DAnGk41
Re : my-weather-indicator ne fonctionne plus après mise à jour
Merci, ça fonctionne, par contre, quand on tape le lieu pour la recherche, ça ne fonctionne pas.
Hors ligne
ljere
Re : my-weather-indicator ne fonctionne plus après mise à jour
sans message d'erreur je ne peux pas aider
Hors ligne
DAnGk41
Re : my-weather-indicator ne fonctionne plus après mise à jour
Il n'y a pas de message d'erreur, simplement quand on tape le lieu, et qu'on clique "rechercher", ça ne bouge pas, avant ça mettait le lieu sur la carte et on validait, mais là aucune recherche, rien ne bouge sur la carte.
Hors ligne
michcauch
Re : my-weather-indicator ne fonctionne plus après mise à jour
Chez moi tout fonctionne bien maintenant, merci ljere.
Je passerai le fil en résolu quand DAnGk41 aura résolu son problème.
DAnGk41, as-tu réessayé ?
Cordialement
Michel
___
Ubuntu 14.04 sur Lenovo ThinkPad Edge E320 et Xubuntu 13.10 sur PC fixe.
Hors ligne
ljere
Re : my-weather-indicator ne fonctionne plus après mise à jour
ok DAnGk41
on va vérifier ton sources.list pour commencer
cat /etc/apt/sources.list
ls /etc/apt/sources.list.d
cat /etc/apt/sources.list.d/*
Hors ligne
DAnGk41
Re : my-weather-indicator ne fonctionne plus après mise à jour
daan@daan-desktop:~$ cat /etc/apt/sources.list
# deb cdrom:[Ubuntu 12.04 _Precise Pangolin_ - Release i386 (20120930)]/ precise main restricted
# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
deb http://fr.archive.ubuntu.com/ubuntu/ precise main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu/ precise main restricted
## Major bug fix updates produced after the final release of the
## distribution.
deb http://fr.archive.ubuntu.com/ubuntu/ precise-updates main restricted
deb-src http://fr.archive.ubuntu.com/ubuntu/ precise-updates main restricted
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team. Also, please note that software in universe WILL NOT receive any
## review or updates from the Ubuntu security team.
deb http://fr.archive.ubuntu.com/ubuntu/ precise universe
deb-src http://fr.archive.ubuntu.com/ubuntu/ precise universe
deb http://fr.archive.ubuntu.com/ubuntu/ precise-updates universe
deb-src http://fr.archive.ubuntu.com/ubuntu/ precise-updates universe
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
deb http://fr.archive.ubuntu.com/ubuntu/ precise multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ precise multiverse
deb http://fr.archive.ubuntu.com/ubuntu/ precise-updates multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ precise-updates multiverse
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
deb http://fr.archive.ubuntu.com/ubuntu/ precise-backports main restricted universe multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ precise-backports main restricted universe multiverse
deb http://security.ubuntu.com/ubuntu precise-security main restricted
deb-src http://security.ubuntu.com/ubuntu precise-security main restricted
deb http://security.ubuntu.com/ubuntu precise-security universe
deb-src http://security.ubuntu.com/ubuntu precise-security universe
deb http://security.ubuntu.com/ubuntu precise-security multiverse
deb-src http://security.ubuntu.com/ubuntu precise-security multiverse
## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
# deb http://archive.canonical.com/ubuntu precise partner
# deb-src http://archive.canonical.com/ubuntu precise partner
## This software is not part of Ubuntu, but is offered by third-party
## developers who want to ship their latest software.
deb http://extras.ubuntu.com/ubuntu precise main
deb-src http://extras.ubuntu.com/ubuntu precise main
deb http://liveusb.info/multisystem/depot all main
deb-src http://liveusb.info/multisystem/depot all main
deb http://download.virtualbox.org/virtualbox/debian precise non-free contrib
daan@daan-desktop:~$
daan@daan-desktop:~$ ls /etc/apt/sources.list.d
atareao-atareao-precise.list
atareao-atareao-precise.list.save
atareao-colorgetter-precise.list
atareao-colorgetter-precise.list.save
f-muriana-ubuntu-builder-precise.list
f-muriana-ubuntu-builder-precise.list.save
google-earth.list
google-earth.list.save
hydr0g3n-qbittorrent-unstable-precise.list
hydr0g3n-qbittorrent-unstable-precise.list.save
ikarosdev-unity-revamped-precise.list
ikarosdev-unity-revamped-precise.list.save
ojno-unity-minimize-on-click-precise.list
ojno-unity-minimize-on-click-precise.list.save
otto-kesselgulasch-gimp-precise.list
otto-kesselgulasch-gimp-precise.list.save
stebbins-handbrake-snapshots-precise.list
stebbins-handbrake-snapshots-precise.list.save
tualatrix-ppa-precise.list
tualatrix-ppa-precise.list.save
yannubuntu-boot-repair-precise.list
yannubuntu-boot-repair-precise.list.save
daan@daan-desktop:~$
daan@daan-desktop:~$ cat /etc/apt/sources.list.d/*
deb http://ppa.launchpad.net/atareao/atareao/ubuntu precise main
deb-src http://ppa.launchpad.net/atareao/atareao/ubuntu precise main
deb http://ppa.launchpad.net/atareao/atareao/ubuntu precise main
deb-src http://ppa.launchpad.net/atareao/atareao/ubuntu precise main
deb http://ppa.launchpad.net/atareao/colorgetter/ubuntu precise main
deb-src http://ppa.launchpad.net/atareao/colorgetter/ubuntu precise main
deb http://ppa.launchpad.net/atareao/colorgetter/ubuntu precise main
deb-src http://ppa.launchpad.net/atareao/colorgetter/ubuntu precise main
deb http://ppa.launchpad.net/f-muriana/ubuntu-builder/ubuntu precise main
deb-src http://ppa.launchpad.net/f-muriana/ubuntu-builder/ubuntu precise main
deb http://ppa.launchpad.net/f-muriana/ubuntu-builder/ubuntu precise main
deb-src http://ppa.launchpad.net/f-muriana/ubuntu-builder/ubuntu precise main
### THIS FILE IS AUTOMATICALLY CONFIGURED ###
# You may comment out this entry, but any other modifications may be lost.
deb http://dl.google.com/linux/earth/deb/ stable main
### THIS FILE IS AUTOMATICALLY CONFIGURED ###
# You may comment out this entry, but any other modifications may be lost.
deb http://dl.google.com/linux/earth/deb/ stable main
deb http://ppa.launchpad.net/hydr0g3n/qbittorrent-unstable/ubuntu precise main
deb-src http://ppa.launchpad.net/hydr0g3n/qbittorrent-unstable/ubuntu precise main
deb http://ppa.launchpad.net/hydr0g3n/qbittorrent-unstable/ubuntu precise main
deb-src http://ppa.launchpad.net/hydr0g3n/qbittorrent-unstable/ubuntu precise main
# deb http://ppa.launchpad.net/ikarosdev/unity-revamped/ubuntu precise main
# deb-src http://ppa.launchpad.net/ikarosdev/unity-revamped/ubuntu precise main
# deb http://ppa.launchpad.net/ikarosdev/unity-revamped/ubuntu precise main
# deb-src http://ppa.launchpad.net/ikarosdev/unity-revamped/ubuntu precise main
deb http://ppa.launchpad.net/ojno/unity-minimize-on-click/ubuntu precise main
deb-src http://ppa.launchpad.net/ojno/unity-minimize-on-click/ubuntu precise main
deb http://ppa.launchpad.net/ojno/unity-minimize-on-click/ubuntu precise main
deb-src http://ppa.launchpad.net/ojno/unity-minimize-on-click/ubuntu precise main
deb http://ppa.launchpad.net/otto-kesselgulasch/gimp/ubuntu precise main
deb-src http://ppa.launchpad.net/otto-kesselgulasch/gimp/ubuntu precise main
deb http://ppa.launchpad.net/otto-kesselgulasch/gimp/ubuntu precise main
deb-src http://ppa.launchpad.net/otto-kesselgulasch/gimp/ubuntu precise main
deb http://ppa.launchpad.net/stebbins/handbrake-snapshots/ubuntu precise main
deb-src http://ppa.launchpad.net/stebbins/handbrake-snapshots/ubuntu precise main
deb http://ppa.launchpad.net/stebbins/handbrake-snapshots/ubuntu precise main
deb-src http://ppa.launchpad.net/stebbins/handbrake-snapshots/ubuntu precise main
deb http://ppa.launchpad.net/tualatrix/ppa/ubuntu precise main
deb-src http://ppa.launchpad.net/tualatrix/ppa/ubuntu precise main
deb http://ppa.launchpad.net/tualatrix/ppa/ubuntu precise main
deb-src http://ppa.launchpad.net/tualatrix/ppa/ubuntu precise main
deb http://ppa.launchpad.net/yannubuntu/boot-repair/ubuntu precise main
deb-src http://ppa.launchpad.net/yannubuntu/boot-repair/ubuntu precise main
deb http://ppa.launchpad.net/yannubuntu/boot-repair/ubuntu precise main
deb-src http://ppa.launchpad.net/yannubuntu/boot-repair/ubuntu precise main
daan@daan-desktop:~$
Hors ligne
ljere
Re : my-weather-indicator ne fonctionne plus après mise à jour
ça c'est bon maintenant
cat ~/.xsession-errors
Hors ligne
DAnGk41
Re : my-weather-indicator ne fonctionne plus après mise à jour
désolé pour le retard à répondre, j'avais des "obligations" ailleurs....
(sol:2897): Gtk-WARNING **: Theme file for default has no name
(sol:2897): Gtk-WARNING **: Theme file for default has no directories
(sol:2904): Gtk-WARNING **: Theme file for default has no name
(sol:2904): Gtk-WARNING **: Theme file for default has no directories
(firefox:2910): Gtk-WARNING **: Theme file for default has no name
(firefox:2910): Gtk-WARNING **: Theme file for default has no directories
(sol:2997): Gtk-WARNING **: Theme file for default has no name
(sol:2997): Gtk-WARNING **: Theme file for default has no directories
(firefox:3004): Gtk-WARNING **: Theme file for default has no name
(firefox:3004): Gtk-WARNING **: Theme file for default has no directories
(firefox:3064): Gtk-WARNING **: Theme file for default has no name
(firefox:3064): Gtk-WARNING **: Theme file for default has no directories
(gnome-terminal:3130): Gtk-WARNING **: Theme file for default has no name
(gnome-terminal:3130): Gtk-WARNING **: Theme file for default has no directories
(sol:3159): Gtk-WARNING **: Theme file for default has no name
(sol:3159): Gtk-WARNING **: Theme file for default has no directories
(firefox:3169): Gtk-WARNING **: Theme file for default has no name
(firefox:3169): Gtk-WARNING **: Theme file for default has no directories
(firefox:3217): Gtk-WARNING **: Theme file for default has no name
(firefox:3217): Gtk-WARNING **: Theme file for default has no directories
(update-manager:3270): Gtk-WARNING **: Theme file for default has no name
(update-manager:3270): Gtk-WARNING **: Theme file for default has no directories
(firefox:3376): Gtk-WARNING **: Theme file for default has no name
(firefox:3376): Gtk-WARNING **: Theme file for default has no directories
(sol:3446): Gtk-WARNING **: Theme file for default has no name
(sol:3446): Gtk-WARNING **: Theme file for default has no directories
(sol:3457): Gtk-WARNING **: Theme file for default has no name
(sol:3457): Gtk-WARNING **: Theme file for default has no directories
(firefox:3463): Gtk-WARNING **: Theme file for default has no name
(firefox:3463): Gtk-WARNING **: Theme file for default has no directories
(sol:3514): Gtk-WARNING **: Theme file for default has no name
(sol:3514): Gtk-WARNING **: Theme file for default has no directories
(firefox:3561): Gtk-WARNING **: Theme file for default has no name
(firefox:3561): Gtk-WARNING **: Theme file for default has no directories
(firefox:3633): Gtk-WARNING **: Theme file for default has no name
(firefox:3633): Gtk-WARNING **: Theme file for default has no directories
(sol:3706): Gtk-WARNING **: Theme file for default has no name
(sol:3706): Gtk-WARNING **: Theme file for default has no directories
(firefox:3712): Gtk-WARNING **: Theme file for default has no name
(firefox:3712): Gtk-WARNING **: Theme file for default has no directories
(gnome-terminal:3761): Gtk-WARNING **: Theme file for default has no name
(gnome-terminal:3761): Gtk-WARNING **: Theme file for default has no directories
daan@daan-desktop:~$ bluetooth-applet:2333): Gtk-WARNING **: Theme file for default has no directories
bash: Erreur de syntaxe près du symbole inattendu « ) »
daan@daan-desktop:~$
daan@daan-desktop:~$ ** Message: applet now removed from the notification area
brother : commande introuvable
daan@daan-desktop:~$
daan@daan-desktop:~$ (nautilus:2332): Gtk-WARNING **: Theme file for default has no name
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (nautilus:2332): Gtk-WARNING **: Theme file for default has no directories
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (nm-applet:2329): Gtk-WARNING **: Theme file for default has no name
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (nm-applet:2329): Gtk-WARNING **: Theme file for default has no directories
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$ ** Message: using fallback from indicator to GtkStatusIcon
brother : commande introuvable
daan@daan-desktop:~$ Initializing opengl options...done
Initializing : commande introuvable
daan@daan-desktop:~$ Initializing decor options...done
Initializing : commande introuvable
daan@daan-desktop:~$ Initializing vpswitch options...done
Initializing : commande introuvable
daan@daan-desktop:~$ Initializing grid options...done
Initializing : commande introuvable
daan@daan-desktop:~$ Initializing gnomecompat options...done
Initializing : commande introuvable
daan@daan-desktop:~$ Initializing resize options...done
Initializing : commande introuvable
daan@daan-desktop:~$ Initializing place options...done
Initializing : commande introuvable
daan@daan-desktop:~$ Initializing animation options...done
Initializing : commande introuvable
daan@daan-desktop:~$ I/O warning : failed to load external entity "/home/daan/.compiz/session/10d438814843fbd01b13561714577425500000022430038"
bash: I/O: Aucun fichier ou dossier de ce type
daan@daan-desktop:~$ Initializing session options...done
e
Initializing : commande introuvable
daan@daan-desktop:~$ /usr/lib/python2.7/dist-packages/radiotray/SysTray.py:185: GtkWarning: Theme file for default has no name
bash: /usr/lib/python2.7/dist-packages/radiotray/SysTray.py:185:: Aucun fichier ou dossier de ce type
daan@daan-desktop:~$
daan@daan-desktop:~$ gtk.main()
> /usr/lib/python2.7/dist-packages/radiotray/SysTray.py:185: GtkWarning: Theme file for default has no directories
bash: Erreur de syntaxe près du symbole inattendu « /usr/lib/python2.7/dist-packages/radiotray/SysTray.py:185: »
daan@daan-desktop:~$
daan@daan-desktop:~$ gtk.main()
> Initializing unitymtgrabhandles options...done
bash: Erreur de syntaxe près du symbole inattendu « Initializing »
daan@daan-desktop:~$ Initializing move options...done
Initializing : commande introuvable
daan@daan-desktop:~$ Initializing mousepoll options...done
Initializing : commande introuvable
daan@daan-desktop:~$ Initializing workarounds options...done
Initializing : commande introuvable
daan@daan-desktop:~$ Initializing wall options...done
Initializing : commande introuvable
daan@daan-desktop:~$ Initializing wobbly options...done
Initializing : commande introuvable
daan@daan-desktop:~$ Initializing fade options...done
Initializing : commande introuvable
daan@daan-desktop:~$ compiz (expo) - Warn: failed to bind image to texture
bash: Erreur de syntaxe près du symbole inattendu « expo »
daan@daan-desktop:~$ Initializing expo options...done
Initializing : commande introuvable
daan@daan-desktop:~$ Initializing ezoom options...done
Initializing : commande introuvable
daan@daan-desktop:~$ Initializing scale options...done
Initializing : commande introuvable
daan@daan-desktop:~$
daan@daan-desktop:~$ (compiz:2312): GConf-CRITICAL **: gconf_client_add_dir: assertion `gconf_valid_key (dirname, NULL)' failed
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$ Initializing unityshell options...done
Initializing : commande introuvable
daan@daan-desktop:~$ Setting Update "main_menu_key"
Setting : commande introuvable
daan@daan-desktop:~$ Setting Update "run_key"
Setting : commande introuvable
daan@daan-desktop:~$ Setting Update "launcher_opacity"
Setting : commande introuvable
daan@daan-desktop:~$ Setting Update "icon_size"
Setting : commande introuvable
daan@daan-desktop:~$ Setting Update "show_desktop_icon"
Setting : commande introuvable
daan@daan-desktop:~$
daan@daan-desktop:~$ (my-weather-indicator:2336): Gtk-WARNING **: Theme file for default has no name
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (my-weather-indicator:2336): Gtk-WARNING **: Theme file for default has no directories
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$ ** Message: moving back from GtkStatusIcon to indicator
brother : commande introuvable
daan@daan-desktop:~$
daan@daan-desktop:~$ (gnome-settings-daemon:2297): Gtk-WARNING **: Theme file for default has no name
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (gnome-settings-daemon:2297): Gtk-WARNING **: Theme file for default has no directories
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (sol:2573): Gtk-WARNING **: Theme file for default has no name
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (sol:2573): Gtk-WARNING **: Theme file for default has no directories
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ ** (gnome-screensaver:2582): WARNING **: l'économiseur d'écran est déjà en cours de fonctionnement pour cette session
bash: Erreur de syntaxe près du symbole inattendu « gnome-screensaver:2582 »
daan@daan-desktop:~$ /opt/libreoffice3.6/program/../ure-link/lib/libstdc++.so.6: version `GLIBCXX_3.4.11' not found (required by /usr/lib/i386-linux-gnu/libproxy.so.1)
> Failed to load module: /usr/lib/i386-linux-gnu/gio/modules/libgiolibproxy.so
>
> ** (nautilus:2332): WARNING **: Error calling current_status: Method "current_status" with signature "" on interface "com.ubuntuone.SyncDaemon.Status" doesn't exist
>
>
> ** (nautilus:2332): CRITICAL **: syncdaemon_status_info_get_online: assertion `SYNCDAEMON_IS_STATUS_INFO (sinfo)' failed
bash: Erreur de syntaxe près du symbole inattendu « ( »
daan@daan-desktop:~$
daan@daan-desktop:~$ (firefox:2757): Gtk-WARNING **: Theme file for default has no name
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (firefox:2757): Gtk-WARNING **: Theme file for default has no directories
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (soffice:2702): Gtk-WARNING **: Theme file for default has no name
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (soffice:2702): Gtk-WARNING **: Theme file for default has no directories
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (sol:2897): Gtk-WARNING **: Theme file for default has no name
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (sol:2897): Gtk-WARNING **: Theme file for default has no directories
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (sol:2904): Gtk-WARNING **: Theme file for default has no name
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (sol:2904): Gtk-WARNING **: Theme file for default has no directories
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (firefox:2910): Gtk-WARNING **: Theme file for default has no name
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (firefox:2910): Gtk-WARNING **: Theme file for default has no directories
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (sol:2997): Gtk-WARNING **: Theme file for default has no name
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (sol:2997): Gtk-WARNING **: Theme file for default has no directories
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (firefox:3004): Gtk-WARNING **: Theme file for default has no name
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (firefox:3004): Gtk-WARNING **: Theme file for default has no directories
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (firefox:3064): Gtk-WARNING **: Theme file for default has no name
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (firefox:3064): Gtk-WARNING **: Theme file
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (gnome-terminal:3130): Gtk-WARNING **: Theme file for de
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (gnome-terminal:3130): Gtk-WARNING **: Theme file for default has
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (sol:3159): Gtk-WARNING **: Theme file for default has no name
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (sol:3159
>
>
> (firefox:3169): Gtk-WARNING **: Theme file for default has no name
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (firefox:3217): Gtk-WARNING **: Theme file for default has no name
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (fire
>
>
> (update-manager:3270): Gtk-WARNING **: Theme file for def
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (update-manager:3270): Gtk-WARNI
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (firefox:3376): Gtk-WARNING **:
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (firefox:3376): Gtk-WARNING **: Th
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (sol:3446): Gtk-WARNING **: Th
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (sol:3446): Gtk-WARNING **: Theme fil
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (sol:3457): Gtk-WARNING **: Them
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (sol:3457): Gtk-WARNING **: The
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (firefox:3463): Gtk-WARNING **: The
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (firefox:3463): Gtk-WARNING **: Theme file for default has no directories
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (sol:3514): Gtk-WARNING **: Theme file for
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (sol:3514): Gtk-WARNING **: Theme
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (firefox:3561): Gtk-WARNING **: Theme file for default has no name
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (firefox:3561): Gtk-WARNING **: Th
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (firefox:36
>
>
> (firefox:3633): Gtk-WARNING **: Theme file for default has no directories
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (sol:3706): Gtk-WARNING **: Theme
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (sol:3706):
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (firefox:3712): Gtk-WARNING **: Theme file f
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (firefox:3712): Gtk-WARNING **
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (gnome-terminal:3761): Gtk-WARNING
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$
daan@daan-desktop:~$ (gnome-terminal:3761): Gtk-WARNING **
bash: Erreur de syntaxe près du symbole inattendu « : »
daan@daan-desktop:~$
daan@daan-desktop:~$ daan@daan-desktop:~$
daan@daan-desktop:~$ : commande introuvable
daan@daan-desktop:~$
Hors ligne
ljere
Re : my-weather-indicator ne fonctionne plus après mise à jour
c'est incroyable j'ai jamais vu autant d'erreur tu as fait quoi pour avoir autant d'erreur
Hors ligne
DAnGk41
Re : my-weather-indicator ne fonctionne plus après mise à jour
Heu... hihi je suis un peu "cascadeur", et germaine michu était sans doute mon arrière grand mère (mais soit dit en passant, mon buntu fonctionne impec... étonnant non ?)
Edit : non en fait il s'agit d'une distro que j'ai un peu transformé avec ubuntu builder, afin d'avoir les logiciels dont je me sers direct à l'install, je pense que ça vient de ça, ces erreurs "no files etc..." je les ai eues en faisant ma distro (mais bon, tant que ça fonctionne hein...) si un jour j'ai un problème sérieux, bin je réinstallerai.
Dernière modification par DAnGk41 (Le 22/12/2012, à 16:21)
Hors ligne
ljere
Re : my-weather-indicator ne fonctionne plus après mise à jour
en ce cas la je vois mal comment t'aider
Hors ligne
DAnGk41
Re : my-weather-indicator ne fonctionne plus après mise à jour
bah ! pas grave, my weather indicator fonctionne avec la réinstallation de python 3, le seul problème est que je ne peux pas mettre le lieu exact, il me met le lieu d'où il voit ma connexion (à environ 120 km de chez moi en ce moment) mais bon, la météo se ressemble d'où il me trouve et où je suis, pas trop important. et merci de t'être penché sur mon problème, bonnes fêtes de fin d'année.
Hors ligne
ljere
Re : my-weather-indicator ne fonctionne plus après mise à jour
bonnes fêtes de fin d'année à toi aussi
Hors ligne
DAnGk41
Re : my-weather-indicator ne fonctionne plus après mise à jour
Sniff... my-weather-indicator ne fonctionne encore plus après (sans doute) mises à jour
Hors ligne
DAnGk41
Re : my-weather-indicator ne fonctionne plus après mise à jour
bon, ça refonctionne, je l'ai désinstallé, purgé et réinstallé depuis synaptic.
Hors ligne
Squashfs
Re : my-weather-indicator ne fonctionne plus après mise à jour
Salut à tous.
Il faut choisir " yahoo! " dans Préférences, services météorologiques.
Avec " Open Weather Map " ça ne marche pas aujourd'hui.
Dernière modification par Squashfs (Le 06/03/2013, à 20:56)
Hors ligne
DAnGk41
Re : my-weather-indicator ne fonctionne plus après mise à jour
Salut à tous.
Il faut choisir " yahoo! " dans Préférences, services météorologiques.
Avec " Open Weather Map " ça ne marche pas aujourd'hui.
Le problème n'était pas là, simplement my-weather-indicator ne voulait tout simplement pas se lancer.
Dernière modification par DAnGk41 (Le 06/03/2013, à 21:00)
Hors ligne
Squashfs
Re : my-weather-indicator ne fonctionne plus après mise à jour
my-weather-indicator n'arrive pas a se lancer tant qu'il ne reçoit pas les infos météo.
C'est pour cela qu'en changeant le service météorologique, tout rentre dans l'ordre.
Hors ligne
DAnGk41
Re : my-weather-indicator ne fonctionne plus après mise à jour
my-weather-indicator n'arrive pas a se lancer tant qu'il ne reçoit pas les infos météo.
C'est pour cela qu'en changeant le service météorologique, tout rentre dans l'ordre.
Oui mais le problème, c'est que s'il ne se lance pas, je ne vois pas comment aller dans "préférences" pour changer le service météo... Ceci dit, après réinstallation, ça a à nouveau fonctionné sur "open weather map".
Hors ligne
Squashfs
Re : my-weather-indicator ne fonctionne plus après mise à jour
Pas besoin de faire une réinstallation, il suffit juste de supprimer le fichier :
my-weather-indicator.conf
Qui est dans le dossier :
/home/user/.config/my-weather-indicator
Ensuite quitter et relancer " my-weather-indicator ", ce qui va démarrer une nouvelle configuration de " my-weather-indicator ".
Et enfin, il faut choisir son service météorologique préféré.
Dernière modification par Squashfs (Le 07/03/2013, à 04:21)
Hors ligne
grandtoubab
Re : my-weather-indicator ne fonctionne plus après mise à jour
Salut,
Quelques difficultés depuis 2/3 jours, rien avec "Yahoo", pas de prévisions avec "OpenWeather Map".
Heureusement que je suis passé par là car en mettant Yahoo ça ne se lançait plus du tout et il m'a fallu supprimer le fichier de configuration:
~/.config/my-weather-indicator$sudo rm my-weather-indicator.conf
Linux tout seul sur le disque dur Acer Aspire T650 :=))
RAM: 1,7 Gio, CPU: Intel® Pentium(R) 4 CPU 3.06GHz × 2. Carte graphique Gallium 0.4 on ATI RC410 (Radeon Xpress200)
Partition 1: Debian Jessie & Gnome Version 3.12, kernel 3.16.2-031602-generic
Partition 2: Ubuntu Trusty 14.04 & Unity
Hors ligne
|
I am looking to discover the best possible practice for building up a file tree inside a GAE/python.
It seems rather efficient to keep everything in one file and route everything there via WSGI.
Though for a complex and multifaceted site it makes sense to have distinct files serving different purposes.
I ran into some weird complications when I had many urls listed in the app.yaml
handlers:- url: /favicon\.ico static_files: favicon.ico upload: favicon\.ico- url: /unit3.* script: unit3.app- url: /birthday.* script: birthday.app- url: /signup.* script: signup.app- url: /rot13.* script: rot13.app- url: /welcome.* script: signup.app- url: .* script: main.applibraries:- name: webapp2 version: "2.5.1"- name: jinja2 version: latest
and then having to duplicate those paths in separate .py files
app = webapp2.WSGIApplication([('/signup',SignUpHandler),
('/welcome',WelcomeHandler),
('/signup/.*', NotFoundPageHandler)]
,debug=True)
Is it weird that I think having to detail the routing of the url twice or more is cumbersome? Is there a way to have distinct files (html, css, py, js) and then have the app.yaml connect all the dots with the routing?
|
Maybe I miss-understand the question, but can't you just do this (python 2.7.1)?
test file:
"""
DOC STRING!!
"""
def hello():
'doc string'
print 'hello'
hello()
Interactive session:
>>> M = ast.parse(''.join(open('test.py')))
>>> ast.get_docstring(M)
'DOC STRING!!'
You can also walk through the ast, looking for the slot the doc string would be in.
>>> M._fields
('body',)
>>> M.body
[<_ast.Expr object at 0x10e5ac710>, <_ast.FunctionDef object at 0x10e5ac790>, <_ast.Expr object at 0x10e5ac910>]
>>> # doc would be in the first slot
>>> M.body[0]._fields
('value',)
>>> M.body[0].value
<_ast.Str object at 0x10e5ac750>
>>> # it contains a string object, so maybe it's the doc string
>>> M.body[0].value._fields
('s',)
>>> M.body[0].value.s
'\nDOC STRING!!\n'
|
I have to integrate my application with an existing (not modifiable) Python script which sends the JSON messages without '\0' or any other "end-of-message" character. Is there any better way to handle incoming messages that just to read data from the socket byte after byte and count brackets? In this application sending { or } in message content is illegal due to the protocol so this code works fine but seems to me ugly:
int i = 0;
int brackets = 0;
byte[] msg = new byte[4096];
do
{
byte chunk = reader.readByte();
msg[i++] = chunk;
if (chunk == 123) // check if '{'
brackets++;
else if (chunk == 125) // check if '}'
brackets--;
} while ( brackets > 0);
byte[] finalMsg = Arrays.copyOfRange(msg, 0, i);
EDIT Python code:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((server_ip, server_port))
logging.info('Connected to: %s', (server_ip, server_port))
s.send(json.dumps(data))
logging.info('Sent message: %s', json.dumps(data))
I analyse text using bytes because this script sends each character as a single byte and as far as I know char is 2 bytes long in Java. When I tried to receive data char-after-char I was not able to compare them with { and }.
|
I have the following class hierarchy in Django, using multi-table inheritance:
class Vehicle(models.Model):
name = models.CharField(blank=True)
class Car(Vehicle):
color = models.CharField(blank=True)
As I use multi-table inheritance, at the database level, there two database tables, one for Vehicle and another for Car. There is also a OneToOne relationship between them.
I have some Car objects on my database. I want to cast these objects to Vehicle, and delete the "Car" part of them. I want that none of these "ex-Cars" appear if I do Car.objects.all().
To obtain the superclass instance, I can do:
car = Car()
vehicle = car.vehicle
But how can I safely delete the "car" object without deleting the "vehicle" object?
I have found some answers related to downcasting (creating a child class instance from a superclass instance and storing it on db, see: Django model inheritance: create sub-instance of existing instance (downcast)?), but I have not found an answer yet about this case.
|
Edit: Since it appears that there's either no solution, or I'm doing something so non-standard that nobody knows - I'll revise my question to also ask: What is the best way to accomplish logging when a python app is making a lot of system calls?
My app has two modes. In interactive mode, I want all output to go to the screen as well as to a log file, including output from any system calls. In daemon mode, all output goes to the log. Daemon mode works great using os.dup2(). I can't find a way to "tee" all output to a log in interactive mode, without modifying each and every system call.
In other words, I want the functionality of the command line 'tee' for any output generated by a python app, including system call output.
To clarify:
To redirect all output I do something like this, and it works great:
# open our log file
so = se = open("%s.log" % self.name, 'w', 0)
# re-open stdout without buffering
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
# redirect stdout and stderr to the log file opened above
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
The nice thing about this is that it requires no special print calls from the rest of the code. The code also runs some shell commands, so it's nice not having to deal with each of their output individually as well.
Simply, I want to do the same, except duplicate instead of redirect.
At first blush, I thought that simply reversing the dup2's should work. Why doesn't it? Here's my test:
import os, sys
### my broken solution:
so = se = open("a.log", 'w', 0)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
os.dup2(sys.stdout.fileno(), so.fileno())
os.dup2(sys.stderr.fileno(), se.fileno())
###
print "kljhf sdf"
os.spawnve("P_WAIT", "/bin/ls", ["/bin/ls"], {})
os.execve("/bin/ls", ["/bin/ls"], os.environ)
The file "a.log" should be identical to what was displayed on the screen.
|
I'm using App Engine with Python. In order to store the images of my users, I write them directly to the blobstore as indicated in Google documentation.
My code is below:
# Image insertion in the blobstore
file_name = files.blobstore.create(mime_type='image/jpeg')
with files.open(file_name, 'a') as f:
f.write(self.imageContent)
files.finalize(file_name)
self.blobKey = files.blobstore.get_blob_key(file_name)
logging.info("Blobkey: "+str(self.blobKey))
The problem is erratic. I don't change anything and since yesterday sometimes it works sometimes it doesn't work. Why? As I print the blobkey (last line of my code), I can see whether the image has been saved into the blobstore or not.
When it works, I have the following line displayed:
Blobkey: AMIfv94p1cFdqkZa3AhZUF2Tf76szVEwpGgwOpN...
When it doesn't work, I have this in my logs:
Blobkey: None
Last detail: images (self.imageContent) are preprocessed and converted into .JPEG before each write.
EDIT:
Everytime, the images are stored in the blobstore (I can see them in the blobviewer in the Administration console). So that's the get_blob_key function which is malfunctioning...
I would like to know what should I do in such a situation? Am I doing something wrong that makes App Engine behavior erratic. How can I solve this out?
|
I'm working on using gevent and tornado inside the same application so that libraries that doesn't support tornado's ioloop can be subdued to use gevent to act asynchronously. I thought I'd need to run two real systems threads, one dedicated to Tornado's ioloop and another dedicated to gevent's loop. However, trying to call any gevent function inside a system thread returns not implemented Error, gevent cannot be used inside threads. Therefore, I tried monkey patching threading as well, as the following snippet shows
from gevent import monkey; monkey.patch_all()
from random import choice
import gevent
import requests
import tornado.ioloop
import tornado.web
import threading
import Queue
q = Queue.Queue()
i = 0
def synchronous_get_url(url, callback=None):
global i
i += 1
d = i
print('bar %d getting %s' % (d, url))
requests.get(url)
print('bar %d finished getting %s' % (d, url))
if callback:
callback()
class GreenEventLoop(threading.Thread):
daemon = True
def run(self):
while True:
url, callback = q.get()
gevent.spawn(synchronous_get_url, url, callback)
continuing...
class MainHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
print 'Received get request'
urls = [
'http://google.com',
'http://apple.com',
'http://microsoft.com',
'http://github.com',
'http://sourceforge.com',
]
q.put((choice(urls), self._on_fetch), block=False)
self.write("submitted url to queue")
def _on_fetch(self):
print 'Finishing in the handler\n'
try:
self.finish()
except:
pass
# Start GEvent Loop
green_loop = GreenEventLoop()
green_loop.start()
# Start Tornado Loop
application = tornado.web.Application([
(r"/", MainHandler),
], debug=True)
application.listen(7001)
tornado.ioloop.IOLoop.instance().start()
In a separate process, on the command line, I run the following.
from gevent import monkey; monkey.patch_all()
import gevent
import requests
count = 0
def get_stuff(i):
global count
res = requests.get('http://localhost:7000/')
count += 1
print count, res, i
lets = [gevent.spawn(get_stuff, i) for i in range(15)]
gevent.joinall(lets)
This allows retrieves 15 urls simultaneously, and return the response as they are received. What I don't quite understand is why the above code works at all. If threading is patched by gevent and turned into green threads, that means there's only ever a single thread running at a time, which means that while gevent is off fetching new responses, tornado's ioloop would block and not handle new requests until the old one has returned. Can someone explain how gevent would interact with Tornado's ioloop?
|
I need to do some HTML parsing with python. After some research lxml seems to be my best choice but I am having a hard time finding examples that help me with what I am trying to do. this is why i am hear. I need to scrape a page for all of its viewable text.. strip out all tags and javascript.. I need it to leave me with what text is viewable. sounds simple enough.. i did it with the HTMLParser but its not handling javascript well
class HTML2Text(HTMLParser.HTMLParser):
def __init__(self):
HTMLParser.HTMLParser.__init__(self)
self.output = cStringIO.StringIO()
def get_text(self):
return self.output.getvalue()
def handle_data(self, data):
self.output.write(data)
def ParseHTML(source):
p = HTML2Text()
p.feed(source)
text = p.get_text()
return text
Any Ideas for a way to do this with lxml or a better way to do it HTMLParser.. HTMLParser would be best because no additional libs are needed.. thanks everyone
Scott F.
|
The goal of my test is to assert that a popup does not appear after certain actions. Previously to test if the popup exist, i have used exception handling.
try:
self.driver.find_element_by_id("fancybox-close").click()
except Exception ('ElementNotVisibleException'):
print "No popup"
This works fine for the test : to assert if popup exists.
But as soon as i change the goal to : assert if popup does not exist
the exception handling solution becomes very expensive (exception handling takes a lot of time in python) and a test that would execute in 3 secs now takes up to a minute.
Is there a way around this? A quicker way to check if an element does not exist using webdriver python binding ?
|
I have periodic data with the index being a floating point number like so:
time = [0, 0.1, 0.21, 0.31, 0.40, 0.49, 0.51, 0.6, 0.71, 0.82, 0.93]
voltage = [1, -1, 1.1, -0.9, 1, -1, 0.9,-1.2, 0.95, -1.1, 1.11]
df = DataFrame(data=voltage, index=time, columns=['voltage'])
df.plot(marker='o')
I want to create a cross(df, y_val, direction='rise' | 'fall' | 'cross') function that returns an array of times (indexes) with all the interpolated points where the voltage values equal y_val. For 'rise' only the values where the slope is positive are returned; for 'fall' only the values with a negative slope are retured; for 'cross' both are returned. So if y_val=0 and direction='cross' then an array with 10 values would be returned with the X values of the crossing points (the first one being about 0.025).
I was thinking this could be done with an iterator but was wondering if there was a better way to do this.
Thanks. I'm loving Pandas and the Pandas community.
|
I've a problem with my Matplotlib graph.
My Programm:
I read sensor data and save it in a csv file with one decimal place (00.0)
after saving I readout the individual data into a list
my list is called tempList and the numbers are float
My Plot:
plt.plot(tempList, color='r', linewidth=2.0)
plt.xticks(range(len(tempList)), timeList2, size='small', rotation=20)
plt.axis('auto')
plt.xlabel('Time')
plt.ylabel('degree Celsius')
plt.title('Temperature')
plt.grid(True)
plt.savefig('img/temp.png', format='png', transparent = True)
plt.close()
My result:
http://s24.postimg.org/5ewu74w51/temp.png
My List:
[20.3, 20.4, 20.4, 20.4, 20.4, 20.4, 20.4, 20.4, 20.4, 20.4]
if I make a list with int's everything works, but since I need thoose decimal places I can't use int.
I already tried to set 'ylim' but it doesn't work
EDIT:thanks for the help
I removed the 'plt.axis('auto')'
the solution:
minTemp = math.ceil(min(tempList))
minTemp = round(minTemp, 1)
maxTemp = math.ceil(max(tempList))
maxTemp = round(maxTemp, 1)
plt.ylim((minTemp-1), (maxTemp+1))
plt.ylim((minTemp-1), (maxTemp+1))
|
I can't read body from POST request on Google app engine application whenever I send string which contains colon ":"
This is my request handler class:
class MessageSync(webapp.RequestHandler):
def post(self):
print self.request.body
Ad this is my testing script:
import httplib2
json_works = '{"works"}'
json_doesnt_work = '{"sux": "test"}'
h = httplib2.Http()
resp, content = h.request('http://localhost:8080/msg',
'POST',
json_works ,
headers={'Content-Type': 'application/json'})
print content
If I use variable json_works request body gets printed, but if I use json_doest_work I won't get any response to console. Except if I print whole request object I get this:
POST /msg
Content-Length: 134
Content-Type: application/json
Host: localhost:8080
User-Agent: Python-httplib2/$Rev$
{"sux": "test"}
Why the hack I can't get just body? Thanks!
|
I just found this answer on the Web:
import unicodedata
def remove_accents(input_str):
nkfd_form = unicodedata.normalize('NFKD', input_str)
only_ascii = nkfd_form.encode('ASCII', 'ignore')
return only_ascii
It works fine (for French, for example), but I think the second step (removing the accents) could be handled better than dropping the non-ASCII characters, because this will fail for some languages (Greek, for example). The best solution would probably be to explicitly remove the unicode characters that are tagged as being diacritics.
Edit: this does the trick:
import unicodedata
def remove_accents(input_str):
nkfd_form = unicodedata.normalize('NFKD', input_str)
return u"".join([c for c in nkfd_form if not unicodedata.combining(c)])
unicodedata.combining(c) will return true if the character c can be combined with the preceding character, that is mainly if it's a diacritic.
Edit 2: remove_accents expects a unicode string, not a byte string. If you have a byte string, then you must decode it into a unicode string like this:
encoding = "utf-8" # or iso-8859-15, or cp1252, or whatever encoding you use
byte_string = b"café" # or simply "café" before python 3.
unicode_string = byte_string.decode(encoding)
|
Bioinformatics, the use of computers in biological research, is the newest wrinkle on one of the oldest pursuits--trying to uncover the secret of life. While we may not know all of life's secrets, at the very least computers are helping us understand many of the biological processes that take place inside of living things. In fact, the use of computers in biological research has risen to such a degree that computer programming has now become an important and almost essential skill for today's biologists.
The purpose of this article is to introduce Python as a useful and viable development language for the computer programming needs of the bioinformatics community. In this introduction, we'll identify some of the advantages of using Python for bioinformatics. Then we'll create and demonstrate examples of working code to get you started. In subsequent articles we'll explore some significant bioinformatics projects that make use of Python.
Because scientists have long relied on the open availability of each other's research results, it was only natural that they would turn to Open Source software when it came time to apply computer processes to the study of biological processes. One of the first Open Source languages to gain popularity among biologists was Perl. Perl gained a foothold in bioinformatics based on its strong text processing facilities, which were ideally suited to analyzing early sequence data. To its credit, Perl has a history of successful use in bioinformatics and is still a very useful tool for biological research.
In comparison to Perl, Python is a relative newcomer to bioinformatics, but is steadily gaining in popularity. A few of the reasons for this popularity are the:
The Python language was designed to be as simple and accessible as possible, without giving up any of the power needed to develop sophisticated applications. Python's clean, consistent syntax leaves it free from the subtleties and nuances that can make other languages difficult to learn and programs written in those languages difficult to comprehend.
Python's dynamic nature adds to its accessibility. For example, Python doesn't require you to declare variables before you use them, and the same variable can refer to objects of different types over the course of its existence. Python can be also be used interactively, allowing you to familiarize yourself with the language of any Python modules in an interactive session where each command produces immediate results.
Related Reading
Python also has excellent support for the object-oriented style of programming. We'll show an example of this capability at the end of this article, but the basic idea is that object-orientation often provides a better way to organize the data and functionality within your programs. As the data and analytical techniques used in bioinformatics have become more complex, the value of object-oriented language features has risen.
In addition, Python integrates well with systems written in other languages, such as C, C++, Java and Fortran. One of the main benefits of C is speed. When a programmer needs an algorithm to run as fast as possible, they can code it in C or C++ and make it available to Python as an extension module. To the programmer, these are indistinguishable from pure Python modules. Similar utilities exist that make the large body of scientific algorithms coded in Fortran accessible to Python programs.
Java has become popular as a cross-platform and Web development language. The Python interpreter is now available in two variations: one version written in C, and the other version, known as Jython, written in Java. Jython allows Java programmers to write programs using the Python syntax and dynamic language features, and it allows Python programmers to use existing code developed in Java. These are just a few examples of the many ways Python is able to leverage and extend existing code written in other languages.
So while Perl is more well established in the bioinformatics community, many biologists and bioinformaticians are also turning to Python as it gains in popularity. To get a better sense of what Python has to offer, we'll look at examples of Python code that highlight some of its features. But first, we need to cover some of the basic biology that we'll touch on in the examples.
One of the goals of molecular biology is to understand the processes that take place within the cells of living organisms. One such process is the creation of proteins, some of the most basic raw materials of all living things. Almost every process within a living creature makes use of, or is influenced by, these large, complex molecular structures. There are thousands of different proteins and we have barely begun to understand them in any detail. One thing we do know is that the creation of proteins is determined by the information encoded within the genetic material in each cell, called DNA.
DNA is a linear structure made up of a sequence of molecules called nucleotides or bases. Four nucleotides appear in DNA: adenine, cytosine, guanine, and thymine. These nucleotides are usually represented by their initials, A, C, G and T. DNA is actually composed of two strands of these nucleotides wound around each other in the famous double helix shape.
The sequence of a single strand of DNA can be represented as a sequence of alphabetical characters identifying each base in the sequence, such as ACCTTGGCACCT. Due to their chemical attractions, the nucleotides always appear in pairs, also called base pairs, such that adenine (A) always pairs up with thymine (T), and cytosine (C) always pairs up with guanine (G). Because of this base-pairing characteristic, we can easily determine the complementary, or opposite, strand of any single-stranded DNA sequence.
A simplified view of how DNA determines the creation of a protein goes something like this. A section of DNA called a gene contains the encoded information about the protein to create. Through the process of transcription, the two DNA strands along a gene separate, and the gene is copied. This single-stranded copy is called RNA, or, more precisely, messenger RNA. It is identical to the original gene sequence, except that the nucleotide uracil (U) appears in place of thymine (T).
Once formed, the messenger RNA moves to a structure in the cell known as a ribosome. The ribosome moves along the messenger RNA, reading its sequence three nucleotides at a time. Each group of three nucleotides, called a codon, determines which of 20 amino acids gets assembled by the ribosome into a protein. Like DNA and RNA, proteins are linear structures that can be represented by a text string. Where DNA and RNA use a four-character alphabet, proteins require a 20-character alphabet to represent each amino acid in a protein sequence.
Now that we've covered some of the basics of molecular biology, let's take a look at Python to see how its language features can be used to deal with biological research data. We mentioned that DNA, RNA, and proteins are all linear sequences that can be easily represented in a computer-friendly fashion. Python has several built-in structures for handling sequences. Three that we will look at are strings, lists, and dictionaries. To do that, we first need to introduce the Python shell.
There are a couple of different ways to run Python code. One way, which should be familiar to anyone with experience in another language, is to enter lines of Python code into a text file and save it with a .py extension. That program file can then be run from an operating system prompt, or by double-clicking on the file, depending on your setup. The other way is to interact with the Python interpreter in a Python shell, where you can enter lines of code, hit return, and get a immediate response back from Python.
Building GUI Applications with PythonCard and PyCrust -- Developing the GUI for a Python application is often a tedious and time-consuming process. This is the exact opposite of how Python programmers would describe other aspects of software development using Python. In this article, Patrick O'Brien explains how PythonCard and PyCrust, the graphical Python shell, ease the GUI development process.
The Python shell is a great environment in which to learn the Python language and to explore new programming concepts. There are even graphical Python shells that will colorize your code, pop up a list of autocompletion options as you type, display all the variables currently available to your program, and help out in any number of other ways. The Python shell that we will use here is called PyCrust, and it comes with the wxPython GUI toolkit.
When you start a Python shell, you will be prompted to enter a line of Python code. The main prompt is ">>> " (without the quotes). If the Python code you are entering requires more than one line, subsequent lines will display the secondary prompt of "... " Let's see what this looks like in PyCrust.
The initial view of the PyCrust shell.
After we've entered some examples of Python code in the PyCrust shell, it may look like this:
A popup listing available methods for the 'dna' object.
Let's take a look at the example code in more detail. The first thing we did was to create a string and assign it to a variable. Strings in Python are sequences of characters. You create a string literal by enclosing the characters in single ('), double (") or triple (''' or """) quotes. In the example we assigned the string literal CTGACCACTTTACGAGGTTAGC to the variable named dna.
>>> dna = 'CTGACCACTTTACGAGGTTAGC'
Then we simply typed the name of the variable, and Python responded by displaying the value of that variable, surrounding the value with quotes to remind us that the value is a string.
>>> dna 'CTGACCACTTTACGAGGTTAGC'
A Python string has several built-in capabilities. One of them is the ability to return a copy of itself with all lowercase letters. These capabilities are known as methods. To invoke a method of an object, use the dot syntax. That is, you type the name of the variable (which in this case is a reference to a string object) followed by the dot (.) operator, then the name of the method followed by opening and closing parentheses.
>>> dna.lower()
'ctgaccactttacgaggttagc'
You can access part of a string using the indexing operator s[i]. Indexing begins at zero, so s[0] returns the first character in the string, s[1] returns the second, and so on.
>>> dna[0] 'C' >>> dna[1] 'T' >>> dna[2] 'G' >>> dna[3] 'A'
The final line in our screen shot shows PyCrust's autocompletion feature, whereby a list of valid methods (and properties) of an object are displayed when a dot is typed following an object variable. As you can see, Python lists have many built-in capabilities that you can experiment with in the Python shell. Now let's look at one of the other Python sequence types, the list.
Where Python strings are limited to characters, Python lists have no limitations. Python lists are ordered sequences of arbitrary Python objects, including other lists. In addition, you can insert, delete and replace elements in a list. Lists are written as a series of objects, separated by commas, inside of square brackets. Let's look at some lists, and some operations you can perform on lists.
>>> bases = ['A', 'C', 'G', 'T']
>>> bases
['A', 'C', 'G', 'T']
>>> bases.append('U')
>>> bases
['A', 'C', 'G', 'T', 'U']
>>> bases.reverse()
>>> bases
['U', 'T', 'G', 'C', 'A']
>>> bases[0]
'U'
>>> bases[1]
'T'
>>> bases.remove('U')
>>> bases
['T', 'G', 'C', 'A']
>>> bases.sort()
>>> bases
['A', 'C', 'G', 'T']
In this example we created a list of single characters that we called bases. Then we added an element to the end, reversed the order of all the elements, retrieved elements by their index position, removed an element with the value 'U', and sorted the elements. Removing an element from a list illustrates a situation where we need to supply the remove() method with an additional piece of information, namely the value that we want to remove from the list. As you can see in the picture below, PyCrust takes advantage of Python's ability to let us know what is required for most operations by displaying that information in a call tip pop-up window.
A tooltip showing usage of the 'remove' method.
We've talked about objects having methods, such as the remove() method of a list object, and how a method performs a task and, perhaps, returns a result. Python has another very similar feature, called a function. About the only difference between a function and a method is that a function isn't associated with a particular object.
Note: Whether something should be defined as a function or a method is, in part, a design choice. In fact, we're going to create several functions below and then re-define them as methods as a way of demonstrating Python's support for object-oriented programming.
Functions perform an operation on one or more values and return a result. Python comes with many pre-defined functions, as well as the ability to define your own functions. Let's look at a couple of the built-in functions: len() returns the number of items in a sequence; dir() returns a list of strings representing the attributes of an object; list() returns a new list initialized from some other sequence.
>>> dna = 'CTGACCACTTTACGAGGTTAGC'
>>> bases = ['A', 'C', 'G', 'T']
>>> len(dna)
22
>>> len(bases)
4
>>> dir(dna)
['__add__', '__class__', '__contains__', '__delattr__',
'__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__',
'__getslice__', '__gt__', '__hash__', '__init__', '__le__',
'__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__',
'__repr__', '__rmul__', '__setattr__', '__str__', 'capitalize',
'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs',
'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower',
'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower',
'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rstrip', 'split',
'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper']
>>> dir(bases)
['__add__', '__class__', '__contains__', '__delattr__',
'__delitem__', '__delslice__', '__doc__', '__eq__', '__ge__',
'__getattribute__', '__getitem__', '__getslice__', '__gt__',
'__hash__', '__iadd__', '__imul__', '__init__', '__le__', '__len__',
'__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__repr__',
'__rmul__', '__setattr__', '__setitem__', '__setslice__', '__str__',
'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
'reverse', 'sort']
>>> list(dna)
['C', 'T', 'G', 'A', 'C', 'C', 'A', 'C', 'T', 'T', 'T',
'A', 'C', 'G', 'A', 'G', 'G', 'T', 'T', 'A', 'G', 'C']
Next, we're going to define some functions of our own that will perform useful operations on biological sequence data.
Here is the process for creating your own function in Python. The first line begins with the keyword def, is followed by the name of the function and any arguments (expected input values) surrounded by parentheses, and ends with a colon. Subsequent lines make up the body of the function and must be indented. If a string comment appears in the first line of the body, it becomes part of the documentation for the function. The last line of a function returns a result.
Let's define some functions in the PyCrust shell. Then we can try each function with some sample data and see the result returned by the function.
>>> def transcribe(dna):
... """Return dna string as rna string."""
... return dna.replace('T', 'U')
...
>>> transcribe('CCGGAAGAGCTTACTTAG')
'CCGGAAGAGCUUACUUAG'
In this example we created a function, called transcribe that expects a string representing a DNA sequence. Strings have a replace() method that will return a copy of the original string with each occurence of one character replaced by another. In three lines of code we've given ourselves a consistent way to transcribe a string of DNA into RNA. Let's create another function. How about reverse?
>>> def reverse(s):
... """Return the sequence string in reverse order."""
... letters = list(s)
... letters.reverse()
... return ''.join(letters)
...
>>> reverse('CCGGAAGAGCTTACTTAG')
'GATTCATTCGAGAAGGCC'
There are a few new things in this function that need explanation. First, we've used an argument name of "s" instead of "dna". You can name your arguments whatever you like in Python. It is something of a convention to use short names based on their expected value or meaning. So "s" for string is fairly common in Python code. The other reason to use "s" instead of "dna" in this example is that this function works correctly on any string, not just strings representing dna sequences. So "s" is a better reflection of the generic utility of this function than "dna".
You can see that the reverse function takes in a string, creates a list based on the string, and reverses the order of the list. Now we need to put the list back together as a string so we can return a string. Python string objects have a join() method that joins together a list into a string, separating each list element by a string value. Since we do not want any character as a separator, we use the join() method on an empty string, represented by two quotes ('' or "").
In order to calculate the complement of a DNA sequence, we need a way to map each of the four bases to its complement. For that, we'll use another Python sequence structure called a dictionary.
A Python dictionary has the same benefit as a regular paper dictionary. It allows you to quickly locate the value (definition) associated with a key (word). Dictionaries are denoted by curly braces and contain a comma-separated sequence of key:value pairs. Dictionaries are not ordered. Instead, dictionary values are accessed by their key value, rather than their position in the sequence. Let's look at some of the methods supported by dictionaries.
>>> basecomplement = {'A': 'T', 'C': 'G', 'T': 'A', 'G': 'C'}
>>> basecomplement.keys()
['A', 'C', 'T', 'G']
>>> basecomplement.values()
['T', 'G', 'A', 'C']
>>> basecomplement['A']
'T'
>>> basecomplement['C']
'G'
>>> for base in basecomplement.keys():
... print "The complement of", base, "is", basecomplement[base]
...
The complement of A is T
The complement of C is G
The complement of T is A
The complement of G is C
>>> for base in basecomplement:
... print "The complement of", base, "is", basecomplement[base]
...
The complement of A is T
The complement of C is G
The complement of T is A
The complement of G is C
In this example we also introduced the concept of a for loop, which cycles over the keys of the basecomplement dictionary. Python's for loop can iterate over any sequence. In this example it assigns the first value from the list returned by keys() to the variable named base, executes the print statement, then repeats the process for each subsequent value in the list. In the second for loop example, you can see that when we simply specify "for base in basecomplement" Python defaults to looping over the basecomplement dictionary's keys.
The next example will demonstrate one other technique we will need in our complement function. It's a relatively new feature of Python, called list comprehensions.
>>> letters = list('CCGGAAGAGCTTACTTAG')
>>> [basecomplement[base] for base in letters]
['G', 'G', 'C', 'C', 'T', 'T', 'C', 'T', 'C',
'G', 'A', 'A', 'T', 'G', 'A', 'A', 'T', 'C']
A list comprehension returns a list and works similarly to a for loop, but in a much more compact and efficient format. In this case it allows us to return a new list where each base in the original list of letters has been replaced with its complement, which we retrieved from the basecomplement dictionary. Let's see how we put this all together.
>>> def complement(s):
... """Return the complementary sequence string."""
... basecomplement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'}
... letters = list(s)
... letters = [basecomplement[base] for base in letters]
... return ''.join(letters)
...
>>> complement('CCGGAAGAGCTTACTTAG')
'GGCCTTCTCGAATGAATC'
Now that we've got a reverse function and a complement function, we have the building blocks for a reversecomplement function.
>>> def reversecomplement(s):
... """Return the reverse complement of the dna string."""
... s = reverse(s)
... s = complement(s)
... return s
...
>>> reversecomplement('CCGGAAGAGCTTACTTAG')
'CTAAGTAAGCTCTTCCGG'
It can also be useful to know the percentage of DNA composed of G and C bases. String objects have a count() method that returns the number of character occurences. With that information, calculating the percentage is a simple matter of applying some mathematical calculations.
>>> def gc(s):
... """Return the percentage of dna composed of G+C."""
... gc = s.count('G') + s.count('C')
... return gc * 100.0 / len(s)
...
>>> gc('CCGGAAGAGCTTACTTAG')
50.0
>>> gc('CCGGAAGAGCTTACTTAGTTA')
42.857142857142854
Since DNA can be divided into three character segments (codons), a function that returned a list of codons would also be useful. Another simple mathematical calculation determines the ending point for our codons in case the DNA string is not evenly divisible by three. The range() function returns a list of numbers from a beginning point to an ending point, incrementing by some value, in this case 3. This arithmetic progression is used inside a list comprehension combined with string slicing to produce a list of three character strings.
>>> def codons(s):
... """Return list of codons for the dna string."""
... end = len(s) - (len(s) % 3) - 1
... codons = [s[i:i+3] for i in range(0, end, 3)]
... return codons
...
>>> codons('CCGGAAGAGCTTACTTAG')
['CCG', 'GAA', 'GAG', 'CTT', 'ACT', 'TAG']
String slicing is similar to string indexing. Instead of retrieving a single character, string slicing allows us to retrieve sections of characters from a starting position up to, but not including, an ending position. The syntax is s[i:j], where i is the starting position and j is the ending position. So s[0:3] returns a string containing the characters in index positions 0, 1, and 2.
>>> s = 'CCGGAAGAGCTTACTTAG' >>> s[0:3] 'CCG' >>> s[3:6] 'GAA' >>> s[6:9] 'GAG' >>> s[9:12] 'CTT'
Here is one final, interesting, note about functions. Functions themselves are objects. That means we can examine their attributes using dir(), just like we did for strings and lists. One of the more useful attributes of a function object is its documentation string, which gets stored in its __doc__ property.
>>> dir(transcribe)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__',
'__get__', '__getattribute__', '__hash__', '__init__', '__name__',
'__new__', '__reduce__', '__repr__', '__setattr__', '__str__',
'func_closure', 'func_code', 'func_defaults', 'func_dict',
'func_doc', 'func_globals', 'func_name']
>>> transcribe.__doc__
'Return dna string as rna string.'
Don't worry if this last example is a bit esoteric. The main point of showing it was to emphasize that Python is very powerful and consistent, that everything in Python is an object, and that objects can be inspected on the fly. The result is that as you learn Python you will find that unfamiliar objects often behave exactly as you would expect them to behave the very first time you use them. This is a powerful feeling that's not experienced often enough when using other programming languages.
We've seen how to create simple objects, like strings, lists, dictionaries, and functions. Next we're going to look at how we can create our own custom objects with properties and methods that we define.
To create your own custom objects, you must define a sort of template, or cookie cutter, called a class. You do so in Python using the class statement, followed by the name of the class and a colon. Following this, the body of the class definition contains the properties and methods that will be available for all object instances that are based on this class.
Let's take all the functions that we've created so far and recast them as methods of a DNA class. Then we'll see how to create DNA objects based on our DNA class. While we could do all this from the Python shell, instead we will place this code into a bio.py file and show how we can use this file from the Python shell. The contents of our bio.py file, which Python calls a module, look like this.
class DNA:
"""Class representing DNA as a string sequence."""
basecomplement = {'A': 'T', 'C': 'G', 'T': 'A', 'G': 'C'}
def __init__(self, s):
"""Create DNA instance initialized to string s."""
self.seq = s
def transcribe(self):
"""Return as rna string."""
return self.seq.replace('T', 'U')
def reverse(self):
"""Return dna string in reverse order."""
letters = list(self.seq)
letters.reverse()
return ''.join(letters)
def complement(self):
"""Return the complementary dna string."""
letters = list(self.seq)
letters = [self.basecomplement[base] for base in letters]
return ''.join(letters)
def reversecomplement(self):
"""Return the reverse complement of the dna string."""
letters = list(self.seq)
letters.reverse()
letters = [self.basecomplement[base] for base in letters]
return ''.join(letters)
def gc(self):
"""Return the percentage of dna composed of G+C."""
s = self.seq
gc = s.count('G') + s.count('C')
return gc * 100.0 / len(s)
def codons(self):
"""Return list of codons for the dna string."""
s = self.seq
end = len(s) - (len(s) % 3) - 1
codons = [s[i:i+3] for i in range(0, end, 3)]
return codons
Much of this should look familiar based on our existing functions. Class definitions do add a few new elements that we need to cover. Let's look at how to use this new class before exploring the extra details.
We create object instances by calling the class, much like we would call a function. The first thing we need to do is make the Python shell aware of this class definition. We do that by importing the DNA class definition from our bio.py module. Then we create an instance of the DNA class, passing in the initial string value. From that point on the object keeps track of its own sequence value, and we simply call the methods that are defined for that object.
>>> from bio import DNA
>>> dna1 = DNA('CGACAAGGATTAGTAGTTTAC')
>>> dna1.transcribe()
'CGACAAGGAUUAGUAGUUUAC'
>>> dna1.reverse()
'CATTTGATGATTAGGAACAGC'
>>> dna1.complement()
'GCTGTTCCTAATCATCAAATG'
>>> dna1.reversecomplement()
'GTAAACTACTAATCCTTGTCG'
>>> dna1.gc()
38.095238095238095
>>> dna1.codons()
['CGA', 'CAA', 'GGA', 'TTA', 'GTA', 'GTT', 'TAC']
Since a class acts as a kind of template that's used to create multiple object instances, we need the ability, inside a class method, to refer to the specific object instance on which the method is called. To accommodate this need, Python automatically passes the object instance as the first argument to each method. The convention in the Python community is to name that first argument "self." That's why you see "self" as the first argument in all the method definitions of our DNA class.
The other thing to note is that the __init__() method. Python calls this specially named method when creating instances of the class. In our example, DNA.__init__ expects to receive a string argument, which we then store as a property of the object instance, self.seq.
We made one other change when we moved our functions into class methods. We moved the basecomplement dictionary definition out of the complement() method and into the class definition. As part of the class definition, the dictionary is only created once, rather than each time the method is called. The dictionary is shared by all instances of the class, and it can be used by more than one method. This is in contrast to the seq property, for which each object instance will have its own unique value.
As you can see, classes provide a effective way to group related data and functionality. Let's finish our shell session by creating a few more DNA instances.
>>> dna2 = DNA('ACGGGAGGACGGGAAAATTACTAGCACCCGCATAGACTT')
>>> dna2.codons()
['ACG', 'GGA', 'GGA', 'CGG', 'GAA', 'AAT', 'TAC', 'TAG',
'CAC', 'CCG', 'CAT', 'AGA', 'CTT']
>>> dna3 = DNA(dna1.seq + dna2.seq)
>>> dna3.reversecomplement()
'AAGTCTATGCGGGTGCTAGTAATTTTCCCGTCCTCCCGTGTAAACTACTAATCCTTGTCG'
>>> dna4 = DNA(dna3.reversecomplement())
>>> dna4.codons()
['AAG', 'TCT', 'ATG', 'CGG', 'GTG', 'CTA', 'GTA', 'ATT',
'TTC', 'CCG', 'TCC', 'TCC', 'CGT', 'GTA', 'AAC', 'TAC',
'TAA', 'TCC', 'TTG', 'TCG']
Even with this rudimentary class definition, manipulated from the Python shell, we can start to see Python's potential for analyzing biological data in a clear, coherent fashion, with a minimum of syntactic overhead.
Python is a popular, open source programming language with much to offer the bioinformatics community. At the same time, Python came late to the bioinformatics party and may never rise to level of popularity of Perl. Choice is always a good thing, though, and Python offers a viable, reliable option for biologists and professional programmers alike. We hope this article gives you a reason to take a closer look at Python.
If you like what you've seen of Python, here are some additional resources to explore.
Patrick O'Brien is an independent software developer and trainer, specializing in the Python programming language. He is the creator of PyCrust, a developer on the PythonCard project, and leader of the PyPerSyst project. He may be reached at pobrien@orbtech.com.
Return to the Python DevCenter.
Copyright © 2009 O'Reilly Media, Inc.
|
grim7reaper
Re : Besoin de conseils pour débuter en python
Merci, cette documentation me semble plutôt complète et complexe pour un débutant python
Complexe, non je ne pense pas.
Du moins ce n’est pas le but.
Outre ce cadre universitaire assez réduit, ce cours s’adresse à toute personne désireuse d’apprendre Python en tant que premier langage de programmation.
On parle bien de la même chose (à savoir, ça) ?
Dernière modification par grim7reaper (Le 14/12/2012, à 12:56)
Hors ligne
brital
Re : Besoin de conseils pour débuter en python
Oui c'est de çà que je parlais...
Mais quand j'ai écrit mon dernier post, je n'avais dit que mes premières impressions. Maintenant que je parcours ce pdf plus sérieusement, il me semble bien fait, et me convient parfaitement.
Hors ligne
compte supprimé
Re : Besoin de conseils pour débuter en python
Sinon, j'ai appris Python avec ça. Le but du tuto est d'être accessible et utile autant aux débutants qu'aux programmeurs expérimentés.
brital
Re : Besoin de conseils pour débuter en python
Merci
Existe t'il des exemples d'applications avec tuto?
Hors ligne
Korak
Re : Besoin de conseils pour débuter en python
OS: Ubuntu 14.04 64 bits + Windows 8.1 64 bits en dualboot (BIOS UEFI, Secure Boot activé et table de partitions GPT)
PC portable HP Pavilion g7-2335sb: Processeur: AMD A4-4300M APU Carte graphique: AMD Radeon HD 7420G Mémoire vive: 6 Go RAM
Je suis Parrain-Linux
Hors ligne
brital
Re : Besoin de conseils pour débuter en python
Les liens pour télécharger les exemples de codehttp://python.developpez.com/sources/
Je suis aussi à la recherche d'une documentation sur la bibliothèque standard de python, si possible en Français ...
Dernière modification par brital (Le 17/12/2012, à 14:37)
Hors ligne
compte supprimé
Re : Besoin de conseils pour débuter en python
Il y a la doc officielle, même si elle n'est pas en français, c'est je pense la meilleure façon de se renseigner. Il y a même des tutos pour débuter (en anglais aussi).
Korak
Re : Besoin de conseils pour débuter en python
Tu ne trouve rien sur ce site?
OS: Ubuntu 14.04 64 bits + Windows 8.1 64 bits en dualboot (BIOS UEFI, Secure Boot activé et table de partitions GPT)
PC portable HP Pavilion g7-2335sb: Processeur: AMD A4-4300M APU Carte graphique: AMD Radeon HD 7420G Mémoire vive: 6 Go RAM
Je suis Parrain-Linux
Hors ligne
brital
Re : Besoin de conseils pour débuter en python
oui j'ai trouvé
Quelqu'un pourrait me dire comment on se sert du générateur de documentation de geany?
Comment peut on s'assurer que geany lance le script en python3 et non pas dans une ancienne version de python?
J'ai commencé a étudier python(variable, type, boucle, condition, liste, ...) avec l'excellent livre de Gérard Swinnen http://inforef.be/swi/python.htm et maintenant je commence les fonctions, je trouve vraiment ce langage vraiment facile à apprendre.
J'ai un petit souci avec la fonction print(), par exemple dans le programme suivant:
t1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12]
t2 = ['Janvier', 'Fevrier', 'Mars', 'Avril', 'Mai', 'Juin','Juillet',
'Aout', 'Septembre', 'Octobre', 'Novembre', 'Decembre']
t3 = []
n = 0
while n < len(t1) :
t3.append(t1[n])
t3.append(t2[n])
n= n+ 1
print(t3)
#affiche le résultat:
>>>[1, 'Janvier', 2, 'Fevrier', 3, 'Mars', 4, 'Avril', 5, 'Mai', 6, 'Juin', 7, 'Jui
llet', 8, 'Aout', 9, 'Septembre', 10, 'Octobre', 12, 'Novembre']
,
Je voudrais formater l'affichage du texte à l'écran pour le rendre plus "propre" dans le genre de çà:
>>>1, janvier 2, Fevrier, 3, Mars 4, Avril, ...
Ou afficher les mois de l'année en deux colonnes...
Dernière modification par brital (Le 20/12/2012, à 16:46)
Hors ligne
VinsS
Re : Besoin de conseils pour débuter en python
# -*- coding: utf-8 -*-
t1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12]
t2 = ['Janvier', 'Fevrier', 'Mars', 'Avril', 'Mai', 'Juin','Juillet',
'Aout', 'Septembre', 'Octobre', 'Novembre', 'Decembre']
# Méthode longue
t3 = []
for i, t in enumerate(t1):
t3.append(str(t))
t3.append(t2[i])
ch = ', '.join(t3)
print(ch)
# Méthode simple (ou compliquée selon le point de vue)
ch = ', '.join(['%s, %s' %(str(x), z) for x, z in [y for y in zip(t1, t2)]])
print(ch)
Bon apocalypse Python.
Hors ligne
brital
Re : Besoin de conseils pour débuter en python
Merci
Maintenant, j'ai un autre problème:
J'ai installé pygame par synaptic, et quand j'essaye l'exemple de code suivant:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys, pygame
pygame.init()
size = width, height = 320, 240
speed = [2, 2]
black = 0, 0, 0
screen = pygame.display.set_mode(size)
ball = pygame.image.load("ball.bmp")
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()
Quand je lance le programme j'ai le message d'erreur suivant:
File "pygame.py", line 3, in <module>
import sys, pygame
File "/home/alex/Bureau/python/exercice/pygame.py", line 4, in <module>
pygame.init()
AttributeError: 'module' object has no attribute 'init'
J'ai lu quelque part que le dépôt python-pygame (1.9.1) qui se trouve dans synaptic est conçu pour tourner sur python2.6...
Moi, j'utilise python3.2 et sur le site officiel je ne trouve pas la version de pygame qui tourne avec cette version de python(http://www.pygame.org/download.shtml).
Quelqu'un pourrais t'il m'indiquer la marche à suivre pour installer pygame pour python3.2?
Hors ligne
VinsS
Re : Besoin de conseils pour débuter en python
D'après cette page
http://www.pygame.org/wiki/CompileUbunt … ompilation
ceci devrait aller
sudo apt-get install python3-dev libsdl-image1.2-dev libsdl-mixer1.2-dev libsdl-ttf2.0-dev libsdl1.2-dev libsmpeg-dev python-numpy subversion libportmidi-dev ffmpeg libswscale-dev libavformat-dev libavcodec-dev
hg clone https://bitbucket.org/pygame/pygame
cd pygame
python3 setup.py build
sudo python3 setup.py install
Hors ligne
brital
Re : Besoin de conseils pour débuter en python
Merci , mais j'ai pas trop compris à quoi sert la commande hg clone...
pygame semble être installé correctement maintenant
Mais quand je lance ce programme depuis Geany:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys, pygame
pygame.init()
size = width, height = 320, 240
speed = [2, 2]
black = 0, 0, 0
screen = pygame.display.set_mode(size)
ball = pygame.image.load("ball.bmp")
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()
j'ai ce message d'érreur:
File "pygame-exemple.py", line 4, in <module>
import pygame
ImportError: No module named pygame
Et quand je lance le programme avec la commande: python3 pygame-exemple dans un terminal çà fonctionne...
Comment ça ce fait que çà ne marche depuis Geany???
Dernière modification par brital (Le 23/12/2012, à 19:54)
Hors ligne
|
I have the following code:
settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'tectcom',
'USER': 'test',
'PASSWORD': '***146***',
'HOST': '',
'PORT': '',
},
'cdr': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'ast',
'USER': '123',
'PASSWORD': '654',
'HOST': '',
'PORT': '',
}
views.py
def cdr_user(request):
cursor = connections['cdr'].cursor()
calls = cursor.execute('SELECT * FROM cdr')
return render_to_response("cdr_user.html",
{'result':calls }, context_instance=RequestContext(request))
cdr_user.html
{% for res in result %}
{{ res.billsec }}<br />
{% endfor %}
The table is like that:
+-------------+--------------+------+-----+---------------------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------------------+-------+
| calldate | datetime | NO | MUL | 0000-00-00 00:00:00 | |
| clid | varchar(80) | NO | | | |
| src | varchar(80) | NO | | | |
| dst | varchar(80) | NO | MUL | | |
| dcontext | varchar(80) | NO | | | |
| channel | varchar(80) | NO | | | |
| dstchannel | varchar(80) | NO | | | |
| lastapp | varchar(80) | NO | | | |
| lastdata | varchar(80) | NO | | | |
| duration | int(11) | NO | | 0 | |
| billsec | int(11) | NO | | 0 | |
| disposition | varchar(45) | NO | | | |
| amaflags | int(11) | NO | | 0 | |
| accountcode | varchar(20) | NO | MUL | | |
| userfield | varchar(255) | NO | | | |
| uniqueid | varchar(32) | NO | | | |
| linkedid | varchar(32) | NO | | | |
| sequence | varchar(32) | NO | | | |
| peeraccount | varchar(32) | NO | | | |
+-------------+--------------+------+-----+---------------------+-------+
The problem is that I get a "Exception Value: 'long' object is not iterable"
TypeError at /cdr_user/
'long' object is not iterable
Request Method: GET
Request URL: http://localhost:8000/cdr_user/
Django Version: 1.4.1
Exception Type: TypeError
Exception Value:
'long' object is not iterable
Exception Location: /usr/local/lib/python2.7/site-packages/django/template/defaulttags.py in render, line 144
Python Executable: /usr/local/bin/python
Python Version: 2.7.0
Python Path:
['/home/tectadmin/cdr/billing',
'/usr/local/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg',
'/usr/local/lib/python2.7/site-packages/pip-1.0-py2.7.egg',
'/usr/local/lib/python2.7/site-packages/django_endless_pagination-1.1-py2.7.egg',
'/usr/local/lib/python27.zip',
'/usr/local/lib/python2.7',
'/usr/local/lib/python2.7/plat-linux2',
'/usr/local/lib/python2.7/lib-tk',
'/usr/local/lib/python2.7/lib-old',
'/usr/local/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/site-packages']
Server time: Sab, 1 Set 2012 19:56:10 -0300
Error during template rendering
In template /home/tectadmin/cdr/billing/config/templates/cdr_user.html, error at line 21
'long' object is not iterable
11 text-indent: 6em;
12 }
13 </style>
14 {% extends "index_cliente.html" %}
15 {% load endless %}
16 {% block title %}CDR{% endblock %}
17 {% block content %}
18
19
20
21 {% for res in result %}
22
23 {{ res.billsec }}<br />
24
25 {% endfor %}
26
27
28
29
30 <br />
31 <form name="input" action="/user_cdr/" method="et" >
Traceback Switch to copy-and-paste view
/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py in get_response
response = callback(request, *callback_args, **callback_kwargs) ...
â–¶ Local vars
/home/tectadmin/cdr/billing/config/views.py in cdr_user
{'result':result }, context_instance=RequestContext(request)) ...
â–¶ Local vars
How do I make result iterable to show it in my template? I've seen https://docs.djangoproject.com/en/dev/topics/db/sql/ and also other documentation, but I'm still lost in the code.
Thank you.
|
I have Nginx serving my static Django files which is being run on Gunicorn. I am trying to serve MP3 files and get them to have the head 206 so that they will be accepted by Apple for podcasting. At the moment the audio files are in my static directory and are served straight through Nginx. This is the response i get:
HTTP/1.1 200 OK
Server: nginx/1.2.1
Date: Wed, 30 Jan 2013 07:12:36 GMT
Content-Type: audio/mpeg
Content-Length: 22094968
Connection: keep-alive
Last-Modified: Wed, 30 Jan 2013 05:43:57 GMT
Can someone help with the correct way to serve mp3 files so that byte-ranges will be accepted.
Update: This is the code in my view that serves the file through Django
response = HttpResponse(file.read(), mimetype=mimetype)
response["Content-Disposition"]= "filename=%s" % os.path.split(s)[1]
response["Accept-Ranges"]="bytes"
response.status_code = 206
return response
|
According to the Python documentation it has to do with the accuracy of the time function in different operating systems:
The default timer function is platform
dependent. On Windows, time.clock()
has microsecond granularity but
time.time()âs granularity is 1/60th of
a second; on Unix, time.clock() has
1/100th of a second granularity and
time.time() is much more precise. On
either platform, the default timer
functions measure wall clock time, not
the CPU time. This means that other
processes running on the same computer
may interfere with the timing ... On Unix, you can
use time.clock() to measure CPU time.
To pull directly from timeit.py's code:
if sys.platform == "win32":
# On Windows, the best timer is time.clock()
default_timer = time.clock
else:
# On most other platforms the best timer is time.time()
default_timer = time.time
In addition, it deals directly with setting up the runtime code for you. If you use time you have to do it yourself. This, of course saves you time
Timeit's setup:
def inner(_it, _timer):
#Your setup code
%(setup)s
_t0 = _timer()
for _i in _it:
#The code you want to time
%(stmt)s
_t1 = _timer()
return _t1 - _t0
|
Захотелось мне поведать как использовать связь ManyToMany, начал я значит писать пост, но так как я хотел его детализировать то он слишком разросся... И я решил сначала написать пост о том, как создавать первый проект и приложение на Django, чтобы потом ссылаться сюда.
-- начинал я этот пост писать еще в том году, да все руки не доходили его закончить, спасибо vasa_c за терпение
Устанавливаем Django
cd /tmp
wget -O Django-1.1.1.tar.gz http://www.djangoproject.com/download/1.1.1/tarball/
tar -xzvf Django-1.1.1.tar.gz
cd Django-1.1.1
sudo python setup.py install
Для Ubuntu:
apt-get install python-mysqldb
Для FreeBSD
cd /usr/ports/databases/py-MySQLdb
make install clean
А для Windows можно скачать тут.
Создаем наш первый проект
Допустим, что имя проекта у нас будет "myproject":
cd /www
django-admin.py startproject myproject
Теперь создайте себе новую БД "myproject":
CREATE DATABASE `myproject` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
И отредактируйте "/www/myproject/settings.py", заменив только соответствующие части:
# ~*~ coding: utf-8 ~*~
...
# Настройки БД
DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'myproject' # Or path to database file if using sqlite3.
DATABASE_USER = 'username' # Not used with sqlite3.
DATABASE_PASSWORD = 'password' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
...
# Путь до каталога, где лежат наши медиа файлы (css, js, images)
MEDIA_ROOT = '/www/myproject/static/'
...
# URL медиа файлов (css, js, images)
MEDIA_URL = '/'
...
# URL медиа файлов админки (css, js, images, etc)
ADMIN_MEDIA_PREFIX = '/admin-media/'
...
# Путь до каталога с шаблонами
TEMPLATE_DIRS = (
"/www/myproject/blog/templates",
)
...
# Установленные приложения в нашем проекте
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'myproject.blog',
)
# в конец добавлено две строки, первая подключает джанговскую админку,
# а второе наше приложение, которое мы ниже опишем
Для чего я ставлю в начале строки "#~ ~ coding: utf-8 ~~" читайте тут.
Создаем наше первое приложение
После того, как вы создали проект, надо создать приложение, если у вас проект состоит из одного приложения - можете его назвать "main".
Создаем приложение "blog":
cd /www/myproject
python manage.py startapp blog
Файл модели
Теперь перейдем к разработке модели нашего приложения, отредактируем "/www/myproject/blog/models.py". У нас будет пока одна сущность, это Посты в Блоге:
# ~*~ coding: utf-8 ~*~
# импортируем класс модели
from django.db import models
# и админки
from django.contrib import admin
'''
Blog posts
'''
class Post(models.Model):
# название поста
title = models.CharField(max_length=100)
# содержимое поста
text = models.TextField()
# функция необходима для того, чтобы при выводе объекта Post
# как строки выводился вместо этого его title
def __unicode__(self):
return self.title;
'''
Класс для админки, тут будут дополнительные атрибуты необходимые для админки
'''
class PostAdmin(admin.ModelAdmin):
# в таблице списка постов выводить только колонку title, если вы добавите еще одно имя поля, то и оно выведется
list_display = ('title',)
# связываем эту модель с моделью PostAdmin
admin.site.register(Post, PostAdmin)
Вы можете все что связано с админкой вынести вПосле создания файла моделей, вам необходимо запустить синхронизацию с БД, для того чтобы создались структуры данных:admins.pyи импортировать его, чтобы избавится от лишнего кода
cd /www/myproject
python manage.py syncdb
Для более детального изучения команд manage.py введите:python manage.py help syncdb
Вы так же можете создавать свои команды, но об этом поговорим не в этот раз.
syncdb создаст таблицы в вашей БД, а также при первой инициализации попросит создать рутовую учетную запись для вашего проекта в django (это будет админский аккаунт):
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table auth_message
Creating table django_content_type
Creating table django_session
Creating table django_site
Creating table django_admin_log
Creating table blog_post
You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (Leave blank to use 'root'):
E-mail address: mail@example.com
Password:
Password (again):
Superuser created successfully.
Installing index for auth.Permission model
Installing index for auth.Message model
Installing index for admin.LogEntry model
Когда вы создадите новый класс модели вам будет необходимо вновь запустить syncdb. Если вы внесли изменения в уже синхронизированное приложение, а именно в его модель, то syncdb НЕ внесет их в вашу БД, для этого используйте sqlall и другие sql* комманды:
python manage.py sqlall название_приложения (например: blog)
Или попробуйте расширение для Django Django Evolution (для этого необходимо его установить в вашу систему и добавить в INSTALLED_APPS - "django_evolution").
Файл урлов
Для навигации по вашему проекту вам нужен роутер (URL диспетчер). Отредактируем "/www/myproject/urls.py":
# ~*~ coding: utf-8 ~*~
# импортируем админку
from django.contrib import admin
# Makes the patterns() function available
from django.conf.urls.defaults import *
# импортируем наши вьюхи (см. ниже описание файла вьюх)
from myproject.blog.views import main_page, get_post
# Above we used admin.autodiscover() to automatically load the INSTALLED_APPS admin.py modules
admin.autodiscover()
urlpatterns = patterns('',
# Если ничего не введено, то отдаем управление mainpage вьюхе
(r'^$', main_page),
# Если передан id поста, то отдаем управление get_post вьюхе
(r'^post/([0-9]{1,5})', get_post),
# Если введен /admin/, то идем в админку
(r'^admin/', include(admin.site.urls)),
)
Вы конечно можете отредактировать локальный для приложения "blog" - urls.py ("/www/myproject/blog/urls.py"), но тогда вам надо будет импортировать "/www/myproject/blog/urls.py" в корневом "urls.py". Либо вы можете его определить в settings.py (ROOT_URLCONF).
Файл вьюхи
Ту роль, которую играет "Controller" в MVC, в Django играет роль View. Почему это так читайте тут. Отредактируем "/www/myproject/blog/views.py":
# ~*~ coding: utf-8 ~*~
# функция генерирующая 404 страницу
from django.http import Http404
# функция отрисовки страницы, принимающая путь до шаблона и данные помещенные в шаблон
from django.shortcuts import render_to_response
# наша модель
from myproject.blog.models import Post
def main_page (request):
# Получаем список постов
posts = Post.objects.all()
# отрисовываем
return render_to_response('list.html', {"posts": posts})
def get_post (request, post_id):
try:
# выбираем конкретный пост, pk - primary key
post = Post.objects.get(pk=post_id)
except Post.DoesNotExist:
# если такого поста нет, то генерируем 404
raise Http404
# отрисовываем
return render_to_response('single.html', {"title": post.title, "text": post.text})
Вывод в шаблоне
В Django очень мощный и гибкий шаблонизатор, у него даже есть аналог на PHP - Twig, что говорит о его удобстве (был бы неудобным - не копировали бы), хотя Twig по слухам сильно хуже.Однако, есть более крутой шаблонизатор для Django - Jinja2, с более высокой производительностью и более гибкими возможностями. Описывать Jinja я не буду, ведь не это цель сего поста, поэтому делюсь только ссылочками:
С более полными возможностями Django Template вы можете познакомится на официальной странице.
В Django Template поддерживается наследование, поэтому мы напишем общий шаблон и будем его использовать base.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>{% block title %}Default{% endblock %} / MyProject</title>
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>
Шаблон вывода списка постов list.html:
{% extends "base.html" %}
{% block title %}List!{% endblock %}
{% block content %}
<ul style="list-style-type:none">
{% for post in posts %}
<li style="padding-left:10px;{% if forloop.counter0|divisibleby:"4" %}background-color:#E1F3C9{% endif %}">
<a href="/post/{{ post.id }}/">{{ post.title }}</a>
<p>{{ post.text }}</p>
</li>
{% endfor %}
</ul>
</div>
{% endblock %}
Шаблон вывода одной записи single.html:
{% extends "base.html" %}
{% block title %}{{ title }}{% endblock %}
{% block content %}
<h1>{{ title }}</h1>
<div>
{{ text }}
</div>
{% endblock %}
Nginx
Теперь настроим Nginx для того, чтобы запуская "manage.py runserver" нам не прописывать порт в URL и чтобы использовать нормальное имя хоста, хотя вы может вполне без это обойтись. Но я очень рекомендую использовать Nginx.
server {
listen 80;
server_name myproject.loc;
location ^~ /admin-media {
alias /usr/local/lib/python2.6/dist-packages/django/contrib/admin/media;
}
location /static/ {
root /www/myproject/static/;
}
location ~* \.(jpg|jpeg|gif|png|ico|css|zip|js|swf)$ {
root /www/myproject/static/;
expires 7d;
}
location / {
proxy_pass http://127.0.0.1:8001/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
Добавить в "/etc/hosts" ваш хост:
127.0.0.1 myproject.loc
И перезагрузить Nginx:
# в новых версиях nginx можно послать сигнал
nginx -s reload
# или для ubuntu/debian через скрипт инициализации
service nginx restart
/etc/init.d/nginx restart
# или для freebsd
/usr/local/etc/rc.d/nginx restart
Запускаем веб-сервер проекта на 8001 порту, так как мы туда будем проксировать из Nginx:
cd /www/myproject
python manage.py runserver 8001
Вы можете скачать архив с исходниками проекта тут
Вот мы и познакомились с первым приложение на Django, как я и обещал в начале этого поста следующая статья будет о ManyToMany, где мы подключим к нашему "Блогу" возможность создавать и выводить теги, а также расскажу более полно о возможностях моделях и ORM, View и о URL диспетере.
P.S. Пост дописывал в торопях, если найдете любые ошибки - обязательно отпишитесь в комментарии, спасибо!
|
I'm currently writing up some basic tests to ensure pages in a medium sized Django application are GETting and POSTing correctly. However, using django.test.client.Client isn't reliably failing when it should be. It returns a 302 response even when there's obviously placed errors in my code.
in my app/urls.py:
url(r'^mymodel/create/$',
views.MyModelView.as_view(),
name = 'my_model_create'),
Then, in attempts to intentionally create a 500 response, I did the following:
class MyModelCreateView(MyModelView, CreateView):
def post(self, request, *args, **kwargs):
print self.hello
self.object = MyModel()
return super(MyModelCreateView, self).post(request, *args, **kwargs)
Obviously, the view doesn't have any object called hello. This fails as expected when trying to send the request through the browser.
and even went as far as replacing "print self.hello" with
return HttpResponse(status = 500)
and yet, I still get the following:
#We have a model called Client, so it
#is imported as RequestClient to avoid conflicts
In [1]: from django.test.client import Client as RequestClient
In [2]: client = RequestClient()
In [3]: response = client.post("/app/mymodel/create/")
In [4]: response.status_code
Out[4]: 302
Clearly the problem here is between the keyboard and the chair, since there's no reason Client()/RequestClient() shouldn't return a 500 error if done correctly. Even some problems arise as I receive 302 responses for POST requests instead of 200 responses, but that may be because we're using HttpRedirect.
Does anyone out there know what may be the problem here? For reference I'm on Python 2.7 and Django 1.5 (though I may need to be compatible with Django 1.4).
|
PHP
lostty84 — 2013-10-14T07:41:24-04:00 — #1
hello, i have been trying to get a newline in an email, i have tried '\r\
' and i have also tried \
\
, i dont know where i am getting it wrong, and also i included a transaction amount ($tranx_amt) in the email, and it is coming up with 4 decimal places. the markup is below.
$body = " Hello $cust_id\\r\
";
$body .= "We are happy to inform you that your order has been placed,\
\
Thanks for the making the payment of $tranx_amt ,\
\
Your Payment reference no is $orderno";.
this is the header (the email also contains tables in the body thats why the html type is in the heading)
$headers = "From: donotreply@reacheasy.co.uk\\r\
"
. 'MIME-Version: 1.0' . "\\r\
"
. 'Content-type: text/html; charset=iso-8859-1' . "\\r\
"
. 'Bcc:notification@grant.co.uk' . "\\r\
";
any ideas on the new line and the decimal places.
cheers
lemon_juice — 2013-10-14T08:55:48-04:00 — #2
If you are sending 'Content-type: text/html' then your message is in HTML. Newline in HTML is accomplished with the <br> tag.
lostty84 — 2013-10-14T09:13:34-04:00 — #3
lostty84 — 2013-10-14T09:36:49-04:00 — #4
thank for the info, please do you have any idea with the extra decimal points . intead of 7560.58 it is showing in the email as 7560.5800
spikez — 2013-10-14T09:41:43-04:00 — #5
Use number_format() on your amount.
$body .= "We are happy to inform you that your order has been placed,\
\
Thanks for the making the payment of ". number_format($tranx_amt, 2, '.') ." ,<br />Your Payment reference no is $orderno";.
lostty84 — 2013-10-14T10:07:08-04:00 — #6
it is not recognizing the transaction amount it, the result is
Hello username
We are happy to inform you that your order has been placed, Thanks for the making the payment of ,
Your Payment reference no is 63749966
lemon_juice — 2013-10-14T17:25:02-04:00 — #7
number_format() cannot accept 3 parameters, there need to be 1, 2 or 4, like this:
number_format($tranx_amt, 2, '.', '')
BTW, if you use Content-type: text/plain then you can use \
as the newline.
lostty84 — 2013-10-16T14:38:55-04:00 — #8
|
I'm familiar with the following questions:
It seems that the answers in these questions have the luxury of being able to fiddle with the exact shrinking of the axis so that the legend fits.
Shrinking the axes, however, is not an ideal solution because it makes the data smaller making it actually more difficult to interpret; particularly when its complex and there are lots of things going on ... hence needing a large legend
The example of a complex legend in the documentation demonstrates the need for this because the legend in their plot actually completely obscures multiple data points.
What I would like to be able to do is dynamically expand the size of the figure box to accommodate the expanding figure legend.
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-2*np.pi, 2*np.pi, 0.1)
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(x, np.sin(x), label='Sine')
ax.plot(x, np.cos(x), label='Cosine')
ax.plot(x, np.arctan(x), label='Inverse tan')
lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,0))
ax.grid('on')
Notice how the final label 'Inverse tan' is actually outside the figure box (and looks badly cutoff - not publication quality!)
Finally, I've been told that this is normal behaviour in R and LaTeX, so I'm a little confused why this is so difficult in python... Is there a historical reason? Is Matlab equally poor on this matter?
I have the (only slightly) longer version of this code on pastebin http://pastebin.com/grVjc007
|
Gemnoc
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Une autre demande pour Ellypsis, pourrais-tu démarrer FreeCAD de cette façon dans le terminal :
freecad --write-log
Ceci va enregistrer un fichier journal FreeCAD.log dans le dossier ~/.FreeCAD, ouvres-le et postes le contenu ici.
J'ai testé rapidement le Sketcher dernière mouture, c'est super. Les contraintes sont désormais appliquées de façon automatique (peut être désactivé), et un indicateur de contrainte s'affiche à côté du curseur lors de la création de géométries. Il ne manque plus grand chose pour que le Sketcher soit pleinement fonctionnel, notamment la possibilité d'appliquer des contraintes à des éléments externes (arêtes de faces d'un solide par exemple).
Hors ligne
Ellypsis
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Salut,
Je suis de retour de mon petit weekend en montagne, je vais donc pouvoir m'y remettre
Pour ta première commande, voilà ce que j'obtiens :
mathieu@Ellypsis:~$ freecad -t 0
FreeCAD 0.12, Libs: 0.12R4478 (Launchpad)
© Juergen Riegel, Werner Mayer, Yorik van Havre 2001-2011
##### #### ### ####
# # # # # #
# ## #### #### # # # # #
#### # # # # # # # ##### # #
# # #### #### # # # # #
# # # # # # # # # ## ## ##
# # #### #### ### # # #### ## ## ##
Importing project files......
Importing project files...... (100.0 %)33.0 %)
Importing project files...... (100.0 %)
Importing project files...... (100.0 %)
Importing project files...... (100.0 %)
Importing project files...... (100.0 %)
Importing project files...... (100.0 %)
Importing project files...... (100.0 %)
Importing project files...... (100.0 %)
Call from Python thread (not synchronized): count=10.0 %)16.0 %)
Call from Python thread (not synchronized): count=2
Call from Python thread (not synchronized): count=3
Call from Python thread (not synchronized): count=4
Call from Python thread (not synchronized): count=5
Call from Python thread (not synchronized): count=6
Call from Python thread (not synchronized): count=7
Call from Python thread (not synchronized): count=8
Call from Python thread (not synchronized): count=9
Call from Python thread (not synchronized): count=10
10
. Printing message
Printing error
Printing warning
.Call from Python thread: count=1
Call from Python thread: count=2
Call from Python thread: count=3
Call from Python thread: count=4
Call from Python thread: count=5
Call from Python thread: count=6
Call from Python thread: count=7
Call from Python thread: count=8
Call from Python thread: count=9
Call from Python thread: count=10
10
........create mesh structure......
saving...... (99.0 %)
Write mesh to /tmp/mesh.stl (99.0 %)
Create mesh instance
create mesh structure......
Checking indices...... (100.0 %)
Checking topology...... (100.0 %)
Mesh loaded successfully. (100.0 %)
Create mesh instance
create mesh structure......
Checking indices...... (100.0 %)
Checking topology...... (100.0 %)
Mesh loaded successfully. (100.0 %)
.Create sphere (10.0,140)...
Create sphere (10.0,160)...
create mesh structure......
... destroy sphere (99.0 %)
create mesh structure......
... destroy sphere (99.0 %)
.create mesh structure......
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
create mesh structure...... (100.0 %)
....
----------------------------------------------------------------------
Ran 45 tests in 18.371s
OK
mathieu@Ellypsis:~$ (100.0 %)
Maintenant, le fichier FreeCAD.log :
Msg: FreeCAD 0.12, Libs: 0.12R4478 (Launchpad)
© Juergen Riegel, Werner Mayer, Yorik van Havre 2001-2011
##### #### ### ####
# # # # # #
# ## #### #### # # # # #
#### # # # # # # # ##### # #
# # #### #### # # # # #
# # # # # # # # # ## ## ##
# # #### #### ### # # #### ## ## ##
Log: Time = Mon Sep 5 16:44:05 2011
Log: AppDataSkipVendor = true
Log: AppHomePath = /usr/lib/freecad/
Log: AppIcon = freecad
Log: BinPath = /usr/lib/freecad/bin/
Log: BuildRepositoryURL = https://code.launchpad.net/~vcs-imports/freecad/trunk
Log: BuildRevision = 4478 (Launchpad)
Log: BuildRevisionDate = 2011/08/28 22:00:32
Log: BuildVersionMajor = 0
Log: BuildVersionMinor = 12
Log: ConsoleBanner = © Juergen Riegel, Werner Mayer, Yorik van Havre 2001-2011
##### #### ### ####
# # # # # #
# ## #### #### # # # # #
#### # # # # # # # ##### # #
# # #### #### # # # # #
# # # # # # # # # ## ## ##
# # #### #### ### # # #### ## ## ##
Log: Debug = 0
Log: DocPath = /usr/lib/freecad/doc/
Log: ExeName = FreeCAD
Log: ExeVendor = FreeCAD
Log: ExeVersion = 0.12
Log: LoggingFile = 1
Log: LoggingFileName = /home/mathieu/.FreeCAD/FreeCAD.log
Log: MaintainerUrl = http://apps.sourceforge.net/mediawiki/free-cad/index.php?title=Main_Page
Log: PATH = /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
Log: PYTHONPATH =
Log: PythonSearchPath = :/usr/bin/../lib/python2.6/:/usr/bin/../lib/python2.6/plat-linux2:/usr/bin/../lib/python2.6/lib-tk:/usr/bin/../lib/python2.6/lib-old:/usr/bin/../lib/python2.6/lib-dynload
Log: RunMode = Gui
Log: SplashAlignment = Bottom|Left
Log: SplashPicture = freecadsplash
Log: SplashTextColor = #ffffff
Log: StartWorkbench = StartWorkbench
Log: SystemParameter = /home/mathieu/.FreeCAD/system.cfg
Log: UserAppData = /home/mathieu/.FreeCAD/
Log: UserHomePath = /home/mathieu
Log: UserParameter = /home/mathieu/.FreeCAD/user.cfg
Log: Verbose =
Log: Create Application
Log: Init: starting App::FreeCADInit.py
Log: Init: Searching for modules...
Log: Init: Initializing /usr/lib/freecad/Mod/Sketcher... done
Log: Init: Initializing /home/mathieu/Téléchargements(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.config(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.face(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/ReverseEngineering... done
Log: Init: Initializing /home/mathieu/.profile(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/Image... done
Log: Init: Initializing /home/mathieu/.gtk-bookmarks(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/PartDesign... done
Log: Init: Initializing /home/mathieu/.bash_aliases(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.dbus(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.fontconfig(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/Musique(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.gconf(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.recently-used.xbel(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/Images(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.pulse-cookie(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.pulse(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.bash_logout(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/VirtualBox(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.adobe(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/Web... done
Log: Init: Initializing /home/mathieu/Documents(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/MeshPart... done
Log: Init: Initializing /home/mathieu/.evolution(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.mplayer(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/Fem... done
Log: Init: Initializing /home/mathieu/.gksu.lock(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.cache(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.compiz(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/Start... done
Log: Init: Initializing /home/mathieu/.ICEauthority(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/Draft... done
Log: Init: Initializing /home/mathieu/.gnome2(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/Test... done
Log: Init: Initializing /usr/lib/freecad/Mod/Import... done
Log: Init: Initializing /home/mathieu/.thumbnails(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.sudo_as_admin_successful(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.openoffice.org(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.icons(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.conkyrc(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.FreeCAD(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/Complete... done
Log: Init: Initializing /home/mathieu/.thunderbird(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.gimp-2.6(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.gstreamer-0.10(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.libreoffice(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/brideur(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/Bureau(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/Raytracing... done
Log: Init: Initializing /home/mathieu/.nautilus(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.gconfd(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/Mesh... done
Log: Init: Initializing /home/mathieu/.xsession-errors(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.gegl-0.0(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.macromedia(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/Part... done
Log: Init: Initializing /home/mathieu/TrackMania(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/Arch... done
Log: Init: Initializing /home/mathieu/.local(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.bash_history(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.hidden(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.synaptic(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.gvfs(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.xsession-errors.old(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/Vidéos(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/Robot... done
Log: Init: Initializing /home/mathieu/.bashrc(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/Points... done
Log: Init: Initializing /home/mathieu/.gnome2_private(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.mozilla(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/TmForever(Init.py not found)... ignore
Log: Init: Initializing /home/mathieu/.esd_auth(Init.py not found)... ignore
Log: Init: Initializing /usr/lib/freecad/Mod/Inspection... done
Log: Init: Initializing /usr/lib/freecad/Mod/Drawing... done
Log: Init: Initializing /home/mathieu/.themes(Init.py not found)... ignore
Log: Using /usr/lib/freecad/Mod as module path!
Log: System path after init:
Log: /usr/lib/freecad/bin
Log: /usr/lib/freecad/Mod/Sketcher
Log: /home/mathieu/Téléchargements
Log: /home/mathieu/.config
Log: /home/mathieu/.face
Log: /usr/lib/freecad/Mod/ReverseEngineering
Log: /home/mathieu/.profile
Log: /usr/lib/freecad/Mod/Image
Log: /home/mathieu/.gtk-bookmarks
Log: /usr/lib/freecad/Mod/PartDesign
Log: /home/mathieu/.bash_aliases
Log: /home/mathieu/.dbus
Log: /home/mathieu/.fontconfig
Log: /home/mathieu/Musique
Log: /home/mathieu/.gconf
Log: /home/mathieu/.recently-used.xbel
Log: /home/mathieu/Images
Log: /home/mathieu/.pulse-cookie
Log: /home/mathieu/.pulse
Log: /home/mathieu/.bash_logout
Log: /home/mathieu/VirtualBox
Log: /home/mathieu/.adobe
Log: /usr/lib/freecad/Mod/Web
Log: /home/mathieu/Documents
Log: /usr/lib/freecad/Mod/MeshPart
Log: /home/mathieu/.evolution
Log: /home/mathieu/.mplayer
Log: /usr/lib/freecad/Mod/Fem
Log: /home/mathieu/.gksu.lock
Log: /home/mathieu/.cache
Log: /home/mathieu/.compiz
Log: /usr/lib/freecad/Mod/Start
Log: /home/mathieu/.ICEauthority
Log: /usr/lib/freecad/Mod/Draft
Log: /home/mathieu/.gnome2
Log: /usr/lib/freecad/Mod/Test
Log: /usr/lib/freecad/Mod/Import
Log: /home/mathieu/.thumbnails
Log: /home/mathieu/.sudo_as_admin_successful
Log: /home/mathieu/.openoffice.org
Log: /home/mathieu/.icons
Log: /home/mathieu/.conkyrc
Log: /home/mathieu/.FreeCAD
Log: /usr/lib/freecad/Mod/Complete
Log: /home/mathieu/.thunderbird
Log: /home/mathieu/.gimp-2.6
Log: /home/mathieu/.gstreamer-0.10
Log: /home/mathieu/.libreoffice
Log: /home/mathieu/brideur
Log: /home/mathieu/Bureau
Log: /usr/lib/freecad/Mod/Raytracing
Log: /home/mathieu/.nautilus
Log: /home/mathieu/.gconfd
Log: /usr/lib/freecad/Mod/Mesh
Log: /home/mathieu/.xsession-errors
Log: /home/mathieu/.gegl-0.0
Log: /home/mathieu/.macromedia
Log: /usr/lib/freecad/Mod/Part
Log: /home/mathieu/TrackMania
Log: /usr/lib/freecad/Mod/Arch
Log: /home/mathieu/.local
Log: /home/mathieu/.bash_history
Log: /home/mathieu/.hidden
Log: /home/mathieu/.synaptic
Log: /home/mathieu/.gvfs
Log: /home/mathieu/.xsession-errors.old
Log: /home/mathieu/Vidéos
Log: /usr/lib/freecad/Mod/Robot
Log: /home/mathieu/.bashrc
Log: /usr/lib/freecad/Mod/Points
Log: /home/mathieu/.gnome2_private
Log: /home/mathieu/.mozilla
Log: /home/mathieu/TmForever
Log: /home/mathieu/.esd_auth
Log: /usr/lib/freecad/Mod/Inspection
Log: /usr/lib/freecad/Mod/Drawing
Log: /home/mathieu/.themes
Log: /usr/local/sbin
Log: /usr/local/bin
Log: /usr/sbin
Log: /usr/bin
Log: /sbin
Log: /bin
Log: /usr/games
Log: Init: App::FreeCADInit.py done
Log: Init: Creating Gui::Application and QApplication
Log: X Error: BadRequest (invalid request code or no such operation) 1
Extension: 136 (Uknown extension)
Minor opcode: 19 (Unknown request)
Resource id: 0x5200004
Log: X Error: BadRequest (invalid request code or no such operation) 1
Extension: 136 (Uknown extension)
Minor opcode: 19 (Unknown request)
Resource id: 0x5200004
Log: X Error: BadRequest (invalid request code or no such operation) 1
Extension: 136 (Uknown extension)
Minor opcode: 14 (Unknown request)
Resource id: 0x5200004
Log: QGLTempContext: No GL capable X visuals available.
Log: This system does not support framebuffer objectsLog: X Error: BadRequest (invalid request code or no such operation) 1
Extension: 136 (Uknown extension)
Minor opcode: 19 (Unknown request)
Resource id: 0x5200004
Log: X Error: BadRequest (invalid request code or no such operation) 1
Extension: 136 (Uknown extension)
Minor opcode: 19 (Unknown request)
Resource id: 0x5200004
Log: X Error: BadRequest (invalid request code or no such operation) 1
Extension: 136 (Uknown extension)
Minor opcode: 14 (Unknown request)
Resource id: 0x5200004
Err: Illegal storage access...Err:
Sinon, j'ai hâte de pouvoir tester ça, vous devez fournir un énorme travail.
Bonne continuation dans votre projet.
Dernière modification par Ellypsis (Le 05/09/2011, à 16:46)
Un Geek sportif
Hors ligne
Gemnoc
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Salut,
J'ai vu que tu avais posté sur le forum de FreeCAD. Ton premier résultat est identique au mien, cependant ton second montre qu'il y a un problème. Un truc que je trouve curieux, dans la série des « Log: Init: Initializing... », ça ne me semble pas normal qu'il cherche dans autant de sous-dossiers de ton home. Chez moi, seuls les répertoires système sous /usr sont initialisés.
Mais la raison du blocage est la suivante :
Log: QGLTempContext: No GL capable X visuals available.
Manifestement, il y a un problème avec le pilote graphique, qui ne semble pas avoir activé l'accélération graphique. Tu confirmes que tu as activé le pilote propriétaire, et que les effets visuels sont activés ?
Dernière modification par Gemnoc (Le 05/09/2011, à 17:26)
Hors ligne
Ellypsis
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Le pilote propriétaire est bien activé, mais effectivement, en essayant d'activer les effets visuels, j'ai un problème avec l'accélération graphique, soucis que je n'avais pas avant.
Ce serait donc un problème matériel. En ce moment, j'accumule pas mal de problème, ça commence à me gonfler (mplayer, metacity, carte graphique...).
Je cherche une solution à mon problème et te tiens au courant.
Un Geek sportif
Hors ligne
Ellypsis
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Je viens de réinstaller les pilotes propriétaire, et c'est bon, tout les problème que j'avais ont été résolu (freecad, mplayer, metacity).
J'ai donc pu lancer FreeCAD sans problème.
Je suis vraiment désolé de vous avoir fais poireauter pour une conner** de ce genre -_-''
Dans tous les cas, je vais suivre l'évolution de FreeCAD avec intérêt, j'ai déjà pu constater qu ele logiciel était fluide, avec pas mal de fonctionnalité.
Merci pour votre travail!
Un Geek sportif
Hors ligne
Gemnoc
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Salut,
Content que la résolution du problème fut aussi simple.
Pour ma part je ne fais pas grand chose, à part contribuer à faire connaître le projet. J'aimerais bien aider à la programmation, mais je n'y connais rien. Je voulais apprendre le langage Python afin d'avoir accès aux fonctionnalités qui ne sont pas encore disponibles dans l'interface graphique, mais au rythme où le développement avance, je n'en aurai peut-être pas besoin !
Hors ligne
Alain16
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Bonjour,
Je viens de prendre contact avec le logiciel,
je l'utiliserai pour du dessin mécanique 2D
ayant souvent besoin de mêmes éléments je recherche une bibliothèque de dessin,j'ai pas vu, cela existe t'il ?
installation, lancement aucun soucis
Alain
Hors ligne
Gemnoc
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Salut,
Il me semble qu'il n'y a aucune bibliothèque actuellement. À la base FreeCAD est surtout un outil destiné à la 3D ; si tu ne compte travailler qu'en 2D, je crois que tu serais mieux avec QCad qui dispose déjà d'une bibliothèque d'éléments mécaniques.
Hors ligne
Alain16
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Salut,
je vais aller voir QCad
merci
Hors ligne
captaineflam
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Et non mon cher jcg, cela ne fait plus mal de parler de çà depuis que Dassault a développé son logiciel.
Le meilleur et gratuit : Drafsight. Une copie conforme d'Autocad, convivial et simple d'utilisation. Disponible sous tous les windows, les linux et mac! Merci Dassault.
http://www.3ds.com/fr/products/draftsig … raftsight/
Technicien DAO-SIG
Acer Aspire 7220
Lubuntu 13.10
Hors ligne
Gemnoc
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
J'ai l'impression que captaineflam s'est trompé de sujet, je n'ai pas vu de jcg dans cette enfilade.
Et puis DraftSight a déjà été mentionné à maintes reprises (ou est-ce dans le sujet « AutoCAD-Like »?)... D'autre part, sachant le contenu discutable du CLUF (prenez donc la peine de le lire !), certains préférerons uns solution libre certes moins évoluée et conviviale, mais plus respectueuse de leurs valeurs.
Hors ligne
captaineflam
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Tu tappe là ou ça fait mal
Tu trouveras pas grand chose de qualité malheureusement.
C'est quoi ça, il ne s'appelle pas jcg peut-être!? Il faut lire les discussions mon cher.
Voici le titre du sujet : Logiciel de CAO 2D/3D (Conception Mecanique). Ce n'est pas logiciel libre dao.
Je donne donc mon avis sur le sujet posté. Si tu veux créer un sujet sur les logiciels libres, vas-y!
Dernière modification par captaineflam (Le 08/09/2011, à 12:47)
Technicien DAO-SIG
Acer Aspire 7220
Lubuntu 13.10
Hors ligne
captaineflam
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Pour la question du libre, je ne vois pas du tout l'intérêt de s'obstiner à vouloir utiliser un logiciel libre pour ce genre de logiciel.
Au contraire, si des boîtes privées investissent pour mettre gratuitement des logiciels à notre disposition on ne peut que s'en réjouir.
De plus Dassault n'interdit pas le fait d'utiliser son logiciel à des fins commerciales, ce qui est plutôt rare de nos jours de la part de grands groupes, faire des cadeaux....
Technicien DAO-SIG
Acer Aspire 7220
Lubuntu 13.10
Hors ligne
Pirrote
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Il est certes remarquable que des logiciel de ce type soit distribuer gratuitement. Toutefois, je pense que de tels logiciels doivent pouvoir se trouvé en libre. Ceci permettra à chacun d'utiliser ce logiciel et étudier sont code afin d'y apporter des corrections ou apporter des plugins facilement.
Pirrote
Pour promouvoir les Logiciels Libres et Linux à Poitiers, Rejoignez-nous:
- Site : http://www.app3l.org
Vous avez trouvé la solution à vos problèmes, postez-là et pensez à mettre [RÉSOLU] sur les titres de vos post
Hors ligne
sam7
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
J'ai l'impression que captaineflam s'est trompé de sujet, je n'ai pas vu de jcg dans cette enfilade.
Et puis DraftSight a déjà été mentionné à maintes reprises (ou est-ce dans le sujet « AutoCAD-Like »?)... D'autre part, sachant le contenu discutable du CLUF (prenez donc la peine de le lire !), certains préférerons uns solution libre certes moins évoluée et conviviale, mais plus respectueuse de leurs valeurs.
tu as bien raison quand j'ai commencer à le lire ... j'ai vite déchanté et je ne suis pas allé jusqu'à la fin de ma lecture & j'ai cliqué sur "annuler".
Hors ligne
Gemnoc
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
jcg a écrit :
Tu tappe là ou ça fait mal
Tu trouveras pas grand chose de qualité malheureusement.
C'est quoi ça, il ne s'appelle pas jcg peut-être!? Il faut lire les discussions mon cher.
Dis donc le farceur, tu te rends compte que tu as répondu au second message de cette enfilade de 12 pages et plus de 290 réponses, et que ce message DATE DE 2006 ?????
De un, est-ce que j'ai le droit de ne pas me rappeler les réponses d'il y a plus de 5 ans ?
(Petit cours sur les forums et les notifications de nouvelles réponses par courriel, auxquelles la plupart de ceux qui échangent dans ce sujet sont abonnés : les liens envoient toujours vers la dernière réponse reçue, donc la toute fin du sujet, pas le début. Ça va, tu piges ?)
De deux, si tu es pour déterrer d'aussi vieilles réponses, c'est trop compliqué de citer le message au passage ?
De trois, la réponse de jcg était tout à fait justifiée il y a 5 ans, car il n'y avait ni de Bricscad, ni de ARES, ni de DrafSight. Tu as donc deux trains de retard !!!
Pffff. La crédibilité de captaineflam = un gros zéro.
Hors ligne
YannUbuntu
Hors ligne
captaineflam
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
j'ai pas à être crédible ou pas tête de bite, t'es à une compétition ou quoi!?
Donnes moi ton msn que je vienne te montrer si je suis crédible.
Technicien DAO-SIG
Acer Aspire 7220
Lubuntu 13.10
Hors ligne
captaineflam
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Et comme je t'ai dit si tu veux parler d'autre chose ouvre un nouveau sujet, c'est valable pour toi aussi le tocard qui perd 5 minutes le temps que ça monte au cerveau.
Technicien DAO-SIG
Acer Aspire 7220
Lubuntu 13.10
Hors ligne
peterp@n
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Oua captainflam ! Ne t'enflammes pas comme ça !
@Gemnoc et aux autres qui préfèrent le libre :
Je commence à tester FreeCAD depuis qu'il y a le module Architecture. Savez vous si il est prévu un module associé pour du calcul de structure ? Et un autre module pour du métré ?
Ubuntu 12.04 64bits, Raspbian “wheezy”, Tango Studio sauce debian
Un bureau d'études techniques pour le bâtiment avec des logiciels libre.
Entreprise de construction bois. - Formations FreeCAD (logiciel 3d)
Hors ligne
slasher-fun
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
captaineflam nous a quitté pour quelques temps, merci de revenir au sujet initial (s'il y en avait un)
Hors ligne
Gemnoc
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Mais quel abruti ce captaineflam.
D'autre part, c'est clair qu'il n'a absolument rien compris de la philosophie d'Ubuntu et de GNU/Linux en général. Beaucoup de gens (la plupart ?) sont attirés sur cette plateforme parce qu'ils veulent s'affranchir des pratiques du logiciel commercial. Or, DraftSight bien que gratuit opère sous le même modèle. Qui dit qu'ils vont continuer à offrir leur logiciel gratuitement dans 2 ans, 5 ans ? Je l'ai déjà mentionné, ce n'est pas par altruisme que Dassault a décidé d'offrir DraftSight gratuitement, mais dans le cadre de sa stratégie de concurrence et de marketing face à Autodesk et son produit-phare AutoCAD. Le but principal est d'attirer des clients utilisateurs d'AutoCAD vers SolidWorks en leur disant, cessez de payer pour de la 2D, achetez-vous plutôt des licences de SolidWorks et utilisez DraftSight pour vos dessins DWG existants. Qu'aucune interdiction d'utiliser le logiciel à des fins commerciales ne soit imposée était donc logique, et il n'y a pas de cadeau ici. Mais si dans 5 ans, Dassault décidait de changer de stratégie et de ne fournir DraftSight qu'avec SolidWorks ? Car c'était le cas avec DWGEditor, qui a précédé DraftSight.
Il est indéniable qu'à l'heure actuelle, il n'existe aucun logiciel libre sous Linux qui soit au niveau de DraftSight. Il n'y a même pas de logiciel libre qui puisse ouvrir les fichiers DWG. Je comprends donc tout à fait ceux qui feront le choix d'accepter le CLUF de DraftSight, de fournir leur adresse de courriel et de l'utiliser. Je l'ai fait moi-même, bien qu'il soit extrêmement rare que je me serve de DraftSight.
Mais, nous sommes sur un forum consacré à Ubuntu, et de ce fait, il m'apparaît tout à fait justifié de mentionner cette réalité, et l'alternative, afin que ceux que ça intéresse fassent leur choix en toute connaissance de cause.
Dernière modification par Gemnoc (Le 10/09/2011, à 18:25)
Hors ligne
Gemnoc
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Je commence à tester FreeCAD depuis qu'il y a le module Architecture. Savez vous si il est prévu un module associé pour du calcul de structure ? Et un autre module pour du métré ?
Salut peterp@n,
À ma connaissance il n'y a rien de prévu officiellement, bien que ça pourrait être ajouté si quelqu'un avec les connaissances se portait volontaire. Le module Architecture est développé à temps perdu par Yorik, un architecte qui est l'auteur du module Draft (Mise en plan). Peut-être a-t-il prévu un module de métré, car son but est d'offrir des fonctionnalités de BIM. Cependant il est l'unique contributeur à ce sous-projet, ça pourrait prendre bien du temps.
L'équipe de développement de FreeCAD est très réduite, et se concentre en ce moment sur les outils de création de pièces mécaniques. Elle a bénéficié cet été du travail assidu de deux contributeurs qui se sont greffés au projet, et qui ont fait avancer rapidement le module Sketcher. Ils ont même commencé à travailler sur le module PartDesign. Mais je crois qu'il a été décidé de bientôt geler les fonctionnalités de ces deux modules et de se concentrer sur le déboguage afin de planifier la sortie d'une version finale 0.12.
Hors ligne
Gemnoc
Re : Logiciel de CAO 2D/3D (Conception Mecanique)
Bonsoir / bonne nuit / bon matin amateurs de CAO,
Des nouvelles sur le développement de FreeCAD. Un mois s'est écoulé depuis que j'ai posté ma première vidéo, et les améliorations au Sketcher* sont impressionnantes ! Voici les principales :
Dans le cas d'une esquisse sans support, une fenêtre de dialogue demande le choix d'un plan de travail
La case "popup" qui permet de saisir une valeur pour les contraintes dimensionnelles pré-selectionne maintenant la valeur, il suffit de saisir la dimension désirée (préalablement il fallait sélectionner manuellement la valeur par défaut)
Nouveaux outils ajoutés : ligne de construction, congé ("fillet"), ajuster ("trim")
Contraintes appliquées automatiquement lors du dessin avec le mode "Auto constraints" et l'indicateur visuel à côté du pointeur
L'esquisse passe au vert lorsqu'elle est pleinement contrainte
Nouveauté d'hier : une boîte texte "Sketcher Messages" indique le nombre de degrés de liberté restant afin de contraindre pleinement l'esquisse.
Le module PartDesign s'est vu ajouter un nouveau dialogue dans l'onglet Tâches lors de la création d'une extrusion. Les outils "Poche" et "Extrusion" devraient aussi être peaufinés avant la sortie de la v0.12 finale, et la traduction française mise à jour.
Désolé, la vidéo est un peu longue (4min28). On voit aussi encore quelques bogues, notamment la grille de dessin qui disparaît et réapparaît, ou encore l'esquisse qui ne devient pleinement contrainte qu'en modifiant une des dimensions ajoutées avec la contrainte « verrou ».
*J'attends toujours vos commentaires sur ma suggestion de traduction pour « Sketcher » : Esquisseur ?
Édition : vidéo ajoutée.
Dernière modification par Gemnoc (Le 21/09/2011, à 03:55)
Hors ligne
|
The tracker in the lower-right corner (highlighted in red) reports y-values relative to the y-axis on the right.
How can I get the tracker to report y-values relative to the y-axis on the left instead?
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(6)
numdata = 100
t = np.linspace(0.05, 0.11, numdata)
y1 = np.cumsum(np.random.random(numdata) - 0.5) * 40000
y2 = np.cumsum(np.random.random(numdata) - 0.5) * 0.002
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
ax1.plot(t, y1, 'r-', label='y1')
ax2.plot(t, y2, 'g-', label='y2')
ax1.legend()
plt.show()
I know swapping y1 with y2 will make the tracker report y1-values,but this also places the y1 tickmarks on the right-hand side, which is not what I want to happen.
ax1.plot(t, y2, 'g-', label='y2')
ax2.plot(t, y1, 'r-', label='y1')
|
I need to integrate spell check mechanism in Django application. I found that Haystack has "Spelling Suggestions" method to use it. So I have installed latest dev version(2.0.0 beta) of haysatck with Django(1.4.1).
I have downloaded apache-solr-3.6.0 and configured as like in doc.
schema.xml
./manage.py build_solr_schema > solr-3.6.0/example/solr/conf/schema.xml
myapps/mysearch_index.py
from haystack import indexes
class MovieIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True,use_template=True)
# other field definition
suggestions = indexes.FacetCharField()
def prepare(self, obj):
prepared_data = super(NoteIndex, self).prepare(obj)
prepared_data['suggestions'] = prepared_data['text']
return prepared_data
solrconfig.xml
<searchComponent name="spellcheck" class="solr.SpellCheckComponent">
<str name="queryAnalyzerFieldType">textSpell</str>
<lst name="spellchecker">
<str name="name">default</str>
<str name="field">suggestions</str>
<str name="spellcheckIndexDir">./spellchecker</str>
<str name="accuracy">0.7</str>
<str name="buildOnCommit">true</str>
</lst>
</searchComponent>
<requestHandler name="/spell" class="solr.SearchHandler">
<lst name="defaults">
<str name="spellcheck.dictionary">default</str>
<str name="spellcheck.onlyMorePopular">false</str>
<str name="spellcheck.extendedResults">false</str>
<str name="spellcheck.count">1</str>
</lst>
<arr name="last-components">
<str>spellcheck</str>
</arr>
</requestHandler>
settings.py
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.solr_backend.SolrEngine',
'URL': 'http://127.0.0.1:8983/solr',
'TIMEOUT': 60 * 5,
'INCLUDE_SPELLING': True,
},
}
Restart the solr search engine
cd examples/solr
java -jar start.jar
Rebuild the index
python manage.py rebuild_index# 9905 entries indexed
Testing through django shell
In [1]: from haystack.query import SearchQuerySet
In [2]: len(SearchQuerySet())
Out[3]: 9905
In [4]: sqs = SearchQuerySet().auto_query('spider')
In [5]: suggestion = sqs.spelling_suggestion()
In [6]: print suggestion
None
In [7]:
I have gone though several bolgs and forum and tried of lot of settings, But spelling_suggestion is always None.
Can anyone help me?
Thanks for reading this post
|
g_barthe
interface python et apprentissage boa constrictor
Bonjour,
Je voudrais commencer à developper qq applications (avec interfaces graphiques) en python (pour windows et linux). Je recherche donc un éditeur qui permettrait de realiser l'interface de maniere simple et non en code pur. J'ai bien trouvé "wxglade" mais la lib wx n'a pas l'air d'etre présente de base avec python sur tous les environnements. (je peux me tromper) mais sous windows apparement je ne l'ai pas.
Il y a la librairie tk qui a l'air d'être prise en compte de manière générale mais la les éditeurs que j'ai trouvé"vtcl" n'arrive pas a se decompresser sous windows et comme je suis amené a developper sous ubuntu et windows je voudrais etre sur une librairie qui soit intégrée facilement à mon environnement de prog.
Y a t'il un avantage d'une librairie par rapport a l'autre ?
merci à vous et j'espère que j'ai été clair.
Dernière modification par g_barthe (Le 02/05/2006, à 18:18)
Mon forum perso sur le génie climatique http://le-genie-climatique.positifforum.com/
Le forum des travaux manuels : http://pausebroderie.fr/
Hors ligne
PierreR
Re : interface python et apprentissage boa constrictor
Pour TKinter, il y a peut être COBRA, mais je ne l'ai jamais utilisé.
Sinon, tu dois pouvoir utiliser GTK avec glade. GTK est le toolkit graphique utilisé par Gnome et il existe sous ubuntu et windows (mais pas mac OS). Il est plus complexe -- dans le sens offre plus de fonctionnalités -- que TKinter mais tout dépend de ce que tu veux faire -- GTK n'est pas installé par défaut sous windows par exemple (mais python non plus donc bon).
Hors ligne
g_barthe
Re : interface python et apprentissage boa constrictor
bonjour
j'ai reussi a faire fonctionner qq scripts python sous ubuntu avec la lib wx. Mais j'ai installé vtcl depuis synaptic d'ubuntu en gros c'est glade pour me facilité la tâche de création de l'interface mais il exporte le code source uniquement en C et pas python. La vie d'un nouveau pythonien n'est pas facile tous les jours. Je crois que je vais rester à la création manuelle de l'interface et non pas graphique car je n'arrive pas a comprendre le fonctionnement de vtcl et je ne trouve pas de tuto sur le net.
Je cherche à faire une application un peu scientifique avec qq calculs pour mon boulot en génie climatique (calculs de clim, chauffage, ventilation). En gros ce sera des boutons de validation, zone de saisie...
Merci à vous
Mon forum perso sur le génie climatique http://le-genie-climatique.positifforum.com/
Le forum des travaux manuels : http://pausebroderie.fr/
Hors ligne
bipede
Re : interface python et apprentissage boa constrictor
Si tu veux tester un bon rad pour python et wxPython, essaies boa-constructor.
C'est le meilleur à l'heure actuelle. Et il est dans les dépôts...
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
Je peux que recommander d'écrire son code dans un éditeur. Les avantages sont si nombreux.
Pour un bon début : http://wiki.wxpython.org/
PierreR
Re : interface python et apprentissage boa constrictor
Oui, mais là on parlait de l'interface graphique et à écrire à la main c'est vraiment prise de tête quand le truc devient un peu gros.
Désolé de m'être trompé plus haut, je voulais effectivement parler de boa (et pas cobra). Sinon pour glade, il ne faut pas générer le code -- même en C c'est déconseillé et plus supporté depuis un moment -- mais utiliser libglade qui a je crois un wrapper python.
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
@PierreR
Oui, mais là on parlait de l'interface graphique et à écrire à la main c'est vraiment prise de tête quand le truc devient un peu gros.
---
Pas du tout, c'est justement l'inverse qui se produit. Quelle est ton expérience? Sur quoi te bases-tu ? Argumentes !
Etant intimement lié à wxPython, je peux te dire que cette question a été posée des dizaines et des dizaines de fois sur la liste des wxPython users (et revient régulièrement). C'est toujours la même réponse qui revient. La même que celle que j'ai donné.
PS: ...mais là on parlait de l'interface graphique... wxPython ne s'occupe que de l'interface graphique.
PierreR
Re : interface python et apprentissage boa constrictor
Heu, il y du y avoir un quiproquo, je voulais dire que quand on fait une interface graphique, à partir du moment ou le truc devient un peu gros (i.e. s'il y a plus d'un champ de texte et deux boutons) c'est très appréciable de disposer d'une interface graphique comme Glade.
Pour répondre à ta question, je dois avouer que je n'ai jamais utilisé wxwidgets (que ce soit en python ou en C++). Quand je faisais du python, je me contentais de Tkinter et c'est vrai que j'écrivais tout à la main et que je suis encore vivant.
Mais un des avantages que je vois aux éditeurs graphiques et de limiter à 0 u presque le risque de mélanger dans le code ce qui a trait à l'interface graphique et le reste rendant très facile un redesign complet de la dite interface même par quelqu'un qui n'aurai jamais touché une ligne de code. Je pensais au début que ce genre d'outils n'était qu'un "truc de feignant" promesse d'interfaces graphiques déguelasses. mais j'ai récemment participé à un projet qui utilise libglade (en C, je ne sais pas ce que ça donne en python mais ça doit être au moins aussi facile d'utilisation) et j'ai pu faire des changements très profond dans l'interface graphique en seulement quelques heures (et quelques centaines de clics et seulement une grosse dizaine de lignes de codes modifiées).
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
PierreR
Bon si tu le dis.
Quand je remanie complètement une interface graphique contenant disons 10 - 50 contrôles, il me faut tout au plus 10 minutes et à peu près zéro clics de souris et le code application - partie calcul - n'est pas mélangé avec celui de l'interface graphique.
Ajouter deux paires - texte et texte d'entrée - à une fenêtre de dialogue qui en contient déjà 10, dois bien prendre 2 bonnes minutes.
Chacun sa méthode. Je dois dire que j'utilise des "sizers".
PierreR
Re : interface python et apprentissage boa constrictor
Effectivement, les gouts et les couleurs !
Mais je suis d'accord que pour quelqu'un de soigneux -- contrairement à moi -- tout écrire à la main est tout aussi jouable et présente certains avantages. Personellement, j'apprécie particulièrement quand j'utilise glade de voir en direct le résultat, de pouvoir tester le redimensionnement, etc sans avoir à recompiler quoi que ce soit -- en C ou C++, effectivement, la question ne se pose pas avec Python -- et donc sans attendre.
Mais je reconnais effectivement que c'est plus un gout et un avis personnel que quelque chose d'indiscutable, dans le même genre, je n'ai jamais été un grand fan des traitements de texte wysywyg comme openoffice -- je préfère LaTeX ou des éditeurs de page web du même genre alors qu'en fait pour qulqu'un de soigneux ce sont sûrement des outils qui permettent d'arriver aux même résultat avec peut être moins d'effort.
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
PierreR
Ta remarque concernant Python est très judicieuse. En effet, Python étant interprété, il me suffit d'un F5 (run script) dans mon éditeur pour voir le résultat.
J'apprécie aussi ta remarque à propos de LaTeX. Je suis du même avis, mais n'avait pas osé mettre le sujet sur la table (analogie).
Un point que j'affectionne particulièrement quand on travail à la main: la possibilité de créer aisément un classe dérivée d'un classe de base. C'est quelque chose que je fais très souvent et que je vois chez beaucoup de personnes avec qui j'échange du code. Par exemple: un contrôle d'entrée de texte qui n'accepte que les lettres minuscules ou un nombre.
Une petite question. Quand tu parles de "tester le redimensionnement". Cela signifierait-t-il que tu places les contrôles en définissant leurs positions en "pixels" ?
aleph
Re : interface python et apprentissage boa constrictor
Honte de mon orthographe...
PierreR
Re : interface python et apprentissage boa constrictor
On est quitte, je vois que j'ai fait une quantité de fautes de frappe proprement hallucinante.
Pour l'orienté objet, j'avoue qu'en C je n'ai pas encore vraiment pris l'habitude et en C++ je n'ai jamais fait de grosses interfaces graphiques mais j'entend bien l'argument. Notons toutefois qu'il y a toujours la possibilité de faire cela en laissant un "trou" avec l'interface graphique qu'on remplit ensuite à la main -- il y a même un "widget" special pour ça dans glade je crois.
Pour la dernière question, non je ne place jamais les widgets avec des positions absolues, je voulais dire vérifier que j'ai bien choisies les propriétés d'expansion des widgets de ma fenêtre et que c'est bien la vue arborescente et pas le bouton fermer qui occupe toute la place quand on l'agrandit par exemple -- mais ceci est peut être simplement du à mon inexpérience de GTK.
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
PierreR
Merci.
g_barthe
Re : interface python et apprentissage boa constrictor
Bonjour,
J'ai installé boa constrictor sur windows au bureau tout va bien et sur ma machine ubuntu breezy chez moi. Jusque la tout va bien. petit bémol sur Ubuntu ou les éléments de l'interface sont tronqués même en etendant les fenetres mais bon passons.
J'ai testé un exemple trouvé sur le net sous windows et ca fonctionne mais sous linux non. Alors la je me pose des questions sur la portabilité. Doit-on faire qqch de précis. Je joins le code :
fichier Frame1.py :
#Boa:Frame:Frame1
import wx
def create(parent):
return Frame1(parent)
[wxID_FRAME1, wxID_FRAME1STATUSBAR1,
] = [wx.NewId() for _init_ctrls in range(2)]
[wxID_FRAME1MENUFILEITEMS0, wxID_FRAME1MENUFILEITEMS1,
wxID_FRAME1MENUFILEITEMS2, wxID_FRAME1MENUFILEITEMS3,
wxID_FRAME1MENUFILEITEMS4,
] = [wx.NewId() for _init_coll_menuFile_Items in range(5)]
[wxID_FRAME1MENUHELPABOUT] = [wx.NewId() for _init_coll_menuHelp_Items in range(1)]
class Frame1(wx.Frame):
def _init_coll_menuBar1_Menus(self, parent):
# generated method, don't edit
parent.Append(menu=self.menuFile, title='File')
parent.Append(menu=self.menuHelp, title='Help')
def _init_coll_menuHelp_Items(self, parent):
# generated method, don't edit
parent.Append(help='Display general information about Notebook',
id=wxID_FRAME1MENUHELPABOUT, kind=wx.ITEM_NORMAL, text='About')
self.Bind(wx.EVT_MENU, self.OnMenuHelpAboutMenu,
id=wxID_FRAME1MENUHELPABOUT)
def _init_coll_menuFile_Items(self, parent):
# generated method, don't edit
parent.Append(help='', id=wxID_FRAME1MENUFILEITEMS0,
kind=wx.ITEM_NORMAL, text='Open')
parent.Append(help='', id=wxID_FRAME1MENUFILEITEMS1,
kind=wx.ITEM_NORMAL, text='Save')
parent.Append(help='', id=wxID_FRAME1MENUFILEITEMS2,
kind=wx.ITEM_NORMAL, text='Save As')
parent.Append(help='', id=wxID_FRAME1MENUFILEITEMS3,
kind=wx.ITEM_NORMAL, text='Close')
parent.Append(help='', id=wxID_FRAME1MENUFILEITEMS4,
kind=wx.ITEM_NORMAL, text='Exit')
self.Bind(wx.EVT_MENU, self.OnMenuFileItems0Menu,
id=wxID_FRAME1MENUFILEITEMS0)
self.Bind(wx.EVT_MENU, self.OnMenuFileItems1Menu,
id=wxID_FRAME1MENUFILEITEMS1)
self.Bind(wx.EVT_MENU, self.OnMenuFileItems2Menu,
id=wxID_FRAME1MENUFILEITEMS2)
self.Bind(wx.EVT_MENU, self.OnMenuFileItems3Menu,
id=wxID_FRAME1MENUFILEITEMS3)
self.Bind(wx.EVT_MENU, self.OnMenuFileItems4Menu,
id=wxID_FRAME1MENUFILEITEMS4)
def _init_coll_statusBar1_Fields(self, parent):
# generated method, don't edit
parent.SetFieldsCount(1)
parent.SetStatusText(number=0, text='Status')
parent.SetStatusWidths([-1])
def _init_utils(self):
# generated method, don't edit
self.menuFile = wx.Menu(title='')
self.menuHelp = wx.Menu(title='')
self.menuBar1 = wx.MenuBar()
self._init_coll_menuFile_Items(self.menuFile)
self._init_coll_menuHelp_Items(self.menuHelp)
self._init_coll_menuBar1_Menus(self.menuBar1)
def _init_ctrls(self, prnt):
# generated method, don't edit
wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt,
pos=wx.Point(466, 359), size=wx.Size(400, 250),
style=wx.DEFAULT_FRAME_STYLE, title='G\xe9nie climatique')
self._init_utils()
self.SetClientSize(wx.Size(392, 216))
self.SetMenuBar(self.menuBar1)
self.statusBar1 = wx.StatusBar(id=wxID_FRAME1STATUSBAR1,
name='statusBar1', parent=self, style=0)
self._init_coll_statusBar1_Fields(self.statusBar1)
self.SetStatusBar(self.statusBar1)
def __init__(self, parent):
self._init_ctrls(parent)
def OnMenuFileItems0Menu(self, event):
event.Skip()
def OnMenuFileItems1Menu(self, event):
event.Skip()
def OnMenuFileItems2Menu(self, event):
event.Skip()
def OnMenuFileItems3Menu(self, event):
event.Skip()
def OnMenuFileItems4Menu(self, event):
event.Skip()
def OnMenuHelpAboutMenu(self, event):
event.Skip()
fichier App1.py :
#Boa:App:BoaApp
import wx
import Frame1
modules ={'Frame1': [1, 'Main frame of Application', 'Frame1.py']}
class BoaApp(wx.App):
def OnInit(self):
wx.InitAllImageHandlers()
self.main = Frame1.create(None)
self.main.Show()
self.SetTopWindow(self.main)
return True
def main():
application = BoaApp(0)
application.MainLoop()
if __name__ == '__main__':
main()
Mon forum perso sur le génie climatique http://le-genie-climatique.positifforum.com/
Le forum des travaux manuels : http://pausebroderie.fr/
Hors ligne
bipede
Re : interface python et apprentissage boa constrictor
C'est un problème de codage de caractères :
si tu changes ta ligne :
style=wx.DEFAULT_FRAME_STYLE, title='G\xe9nie climatique')
dans Frame1.py par :
style=wx.DEFAULT_FRAME_STYLE, title='Génie climatique')
Et que tu ajoutes la ligne :
#-*- coding: utf8 -*-
En première ligne de tes deux scripts, ça va marcher...
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
Boa ou les dix doigts ?
La même application écrite à la main. Pour moi, il n'y a pas photo quant à la clarté du code.
Sans compter les imperfections (erreur) dans le code généré par boa.
# -*- coding: iso-8859-1 -*-
#--------------------------------------------------------------------
# Name: simple.py
# Purpose: Small demo
# Author: Jean-Michel Fauth, Switzerland
# Copyright:
# Licence: None, free software
#--------------------------------------------------------------------
# os dev: w2k sp4
# py dev: Python 2.4.2
# wx dev: wxPython 2.6.3.2
# Revision: 2 May 2006
#--------------------------------------------------------------------
import wx
class MyPanel(wx.Panel):
def __init__(self, parent, id):
wx.Panel.__init__(self, parent, id, wx.DefaultPosition, wx.DefaultSize)
class MyFrame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, (300, 200))
self.CentreOnScreen()
# menus
menu1 = wx.Menu()
menu101 = menu1.Append(101, '&Open...\tCtrl+o', 'Ouvre un fichier')
menu103 = menu1.Append(102, '&Save as...\tCtrl+s', 'Enregistre un fichier sous')
menu102 = menu1.Append(103, 'Save\tCtrl+s', 'Enregistre le fichier courant')
menu104 = menu1.Append(104, '&Close')
menu105 = menu1.Append(105, '&Exit', 'Quitte cette application')
menu2 = wx.Menu()
menu201 = menu2.Append(201, '&About...', 'A propos')
menuBar = wx.MenuBar()
menuBar.Append(menu1, '&File')
menuBar.Append(menu2, '&Help')
self.SetMenuBar(menuBar)
# statusbar
sb = wx.StatusBar(self, wx.NewId())
self.SetStatusBar(sb)
self.Bind(wx.EVT_MENU, self.OnMenu101, menu101)
self.Bind(wx.EVT_MENU, self.OnMenu102, menu102)
self.Bind(wx.EVT_MENU, self.OnMenu103, menu103)
self.Bind(wx.EVT_MENU, self.OnMenu104, menu104)
self.Bind(wx.EVT_MENU, self.OnMenu105, menu105)
self.Bind(wx.EVT_MENU, self.OnMenu201, menu201)
# panel contenant les widgets
self.pa = MyPanel(self, wx.NewId())
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
def OnMenu101(self, event):
print 'Menu101'
def OnMenu102(self, event):
print 'Menu102'
def OnMenu103(self, event):
print 'Menu103'
def OnMenu104(self, event):
print 'Menu104'
def OnMenu105(self, event):
print 'Menu105'
self.OnCloseWindow(None)
def OnMenu201(self, event):
print 'Menu201'
def OnCloseWindow(self, event):
self.Destroy()
class MyApp(wx.App):
def OnInit(self):
frame = MyFrame(None, -1, 'Génie climatique')
frame.Show(True)
self.SetTopWindow(frame)
return True
def main():
app = MyApp(False)
app.MainLoop()
if __name__ == '__main__':
main()
#eof
bipede
Re : interface python et apprentissage boa constrictor
Boa ou les dix doigts ?
La même application écrite à la main. Pour moi, il n'y a pas photo quant à la clarté du code.
Sans compter les imperfections (erreur) dans le code généré par boa.
Tu prêches un convaincu
Mais notre ami veut utiliser un RAD.
Quant au code généré par Boa, il n'est pas si sale que cela, et je trouve que l'objet y est bien utilisé...
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
bipede :
Quant au code généré par Boa, il n'est pas si sale que cela, et je trouve que l'objet y est bien utilisé...
---
Il est même très propre, c'est à dire bien conçu. Ce que je veux montrer ici est que l'utilisation d'un IDE n'est pas la panacée.
Le code généré par Boa doit faire deux choses:
- écrire le code de l'application.
- écrire le code de façon à ce que Boa puisque le récupérer et l'éditer à nouveau. D'où une certaine lourdeur. Une structure de code qui ne correspond pas à ce que l'application est censée faire, mais une structure qui est plus conforme à Boa.
Quelques autres commentaires en vrac :
- wx.InitAllImageHandlers() n'est par nécessaire, cette tâche est effectuée en interne par OnInit(), voir wxPython doc. Cette tâche est exécutée deux fois !
- event.Skip() dans les menus est inutile. Un "pass" eut été suffisant. A quoi bon surcharger, la queue des événements. Il faut bien que Boa mette quelque chose.
- Boa ne génère pas l'événement OnCloseWindow(), très important dans la pratique. Cette partie du code doit de toute façon est rajoutée à la main.
- Mon code avait des doc strings dans le function (triple double quoted strings). Il semblerait que ces doc strings se soient perdus en route !
Ma conclusion :
On en arrive à cette absurdité où seuls les personnes sachant développer à la main sont à même de comprendre correctement le code généré par Boa.
Ceci est vrai pour tous les IDEs.
Je ne peux que recommander une visite chez wxPython.org et télécharger la demo.
aleph
Re : interface python et apprentissage boa constrictor
Petite remarque annexe:
L'IDE ne se nomme pas Boa constrictor, mais Boa constructor. En espérant que vous ayez compris la subtilité du nom.
g_barthe
Re : interface python et apprentissage boa constrictor
Je vous remercie tous pour ces différentes remarques et je sais très bien que les IDE ne sont pas une solution très propre. Moi même pour du HTML je fais tout à la main, je gère mieux ce que je fais je trouve. Mais la n'y connaissant rien à python je voulais déjà créer un joli interface graphique de manière rapide sans trop avoir à comprendre la construction ce que je ferais pour le coeur du programme bien sur. Par la suite oui je redécortiquerais la partie interface pour la recoder de manière simple sans boa.
Mon forum perso sur le génie climatique http://le-genie-climatique.positifforum.com/
Le forum des travaux manuels : http://pausebroderie.fr/
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
Permets moi d'insister. Est-ce que tu as la demo de wxPython ?
Tous les widgets expliqués, le code pour chaque widget, modification et essai, tout ceci interactivement...sans jamais quitter l'application.
g_barthe
Re : interface python et apprentissage boa constrictor
je viens de le télécharger et effectivement je connaissais pas et ca m'a l'air très instructif et très bien fait. Je vais me pencher ( pas top qd meme) bon c nul, sur cette doc et continuer mon apprentissage et je vous tiendrais au courant de l'evolution.
Merci de votre aide.
Mon forum perso sur le génie climatique http://le-genie-climatique.positifforum.com/
Le forum des travaux manuels : http://pausebroderie.fr/
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
Enfin ! Si j'ose dire. Comme cela fait bientôt 5 ans que je contribue assez fidèlement au projet wxPython, cela me fait plaisir. Je suis sous win, tu me pardonneras.
Bonne continuation.
bipede
Re : interface python et apprentissage boa constrictor
- wx.InitAllImageHandlers() n'est par nécessaire, cette tâche est effectuée en interne par OnInit(), voir wxPython doc. Cette tâche est exécutée deux fois !
Même si sur le reste je suis complètement d'accord avec toi, sur ce point précis non. L'initialisation des handlers d'images n'est pas automatique, et on doit l'ajouter à la méthode OnInit() de la classe wx.App si on veut que tous les formats d'images soient reconnus (j'ai expérimenté).
Je suis content de rencontrer un contributeur au projet wxpython dont je suis un adepte forcené .
Il est dommage que tu ne travailles que sur windows, car j'ai pu constater des différences de comportement de certains wxWidgets entre les deux OS que je n'ai jamais pu m'expliquer.
Hors ligne
|
I am seeing a very unusual behavior in python.. Kindly let me know what am i doing wrong!!
bc = [[0]*(n+1)]*(n+1)
for i in range(n+1):
bc[i][i] = 1
print (bc)
Output
[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
I am trying to initialize the diagonal elements of two dimensional array to 1, but it is initializing all the elements with 1. I think I am doing something wrong with accessing two dimensional Array..
Also, kindly let me know how can I use two loops to access all the elements of two dimensional array.. my next step..
Thanks.
|
I have a huge list of networks (called A) and I need to check if the addresses of these networks are present in another network list (called B) :
The format of the two lists is the following:
Liste A
1.2.3.4
145.2.3.0/24
6.5.0.0/16
3.4.1.0/24
Liste B
1.5.6.7
10.0.3.0/24
1.2.3.0/24
3.4.0.0/16
Expected result of the intersection of two lists A â© B: etc
1.2.3.4
3.4.1.0/24
My first test was naively:
List all ips with ipaddr module
Put the IPs for each list in two set
do to the intersection of the two set.
This method works with small lists. However, this solution is not suitable with thousands of networks (ie several million IP addresses) because I don't have enough memory. Moreover, this solution is not suitable with IPv6 networks.
What is the most effective way to do the intersection of the two lists?
Addition: I have also to repeat this between list A and other lists as B : A â© C, A â© D, etc.
I'm open to all suggestions, even with pig :-)
Solution :
def chunks(l, n):
for i in xrange(0, len(l), n):
yield l[i:i+n]
res = []
for chunk_a in chunks(A, 1000):
for chunk_b in chunks(B, 1000):
C = IPSet(chunk_a) & IPSet(chunk_b)
if C > IPSet([]):
res.append(C)
|
I followed the Haystack tutorial to set up for Whoosh
>>> pip install whoosh
settings.py
import os
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
'PATH': os.path.join(os.path.dirname(__file__), 'whoosh_index'),
},
}
and I am getting an empty list
>>> list(ix.searcher().documents())
[]
Following is my code for searcher_indexes.py
from haystack import indexes
from view_links.models import Projdb
class ProjdbIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
title = indexes.CharField(model_attr='title')
author = indexes.CharField(model_attr = 'owner')
# pub_date = indexes.DateTimeField(model_attr='date_start')
def get_model(self):
return Projdb
def index_queryset(self,using=None):
"""Used when the entire index for model is updated."""
return self.get_model().objects.all()#filter(pub_date__lte=datetime.datetime.now())
I was previously able to get results for elasticsearch but when I shifted to Whoosh I am getting no results.
Thank you for your time. If you require further information, please let me know.
EDIT:
I am getting results now and here are two things I learned.
I need to register the app whose model is being used for indexing.
If a Model's class is misspelled in search_indexes.py, running the python manage.py rebuild_indexdoes not throw any error and you will get zero indexed objects
|
I have a fairly simple plotting routine that looks like this:
from __future__ import division
import datetime
import matplotlib
matplotlib.use('Agg')
from matplotlib.pyplot import figure, plot, show, legend, close, savefig, rcParams
import numpy
from globalconstants import *
def plotColumns(columnNumbers, t, out, showFig=False, filenamePrefix=None, saveFig=True, saveThumb=True):
lineProps = ['b', 'r', 'g', 'c', 'm', 'y', 'k', 'b--', 'r--', 'g--', 'c--', 'm--', 'y--', 'k--', 'g--', 'b.-', 'r.-', 'g.-', 'c.-', 'm.-', 'y.-', 'k.-']
rcParams['figure.figsize'] = (13,11)
for i in columnNumbers:
plot(t, out[:,i], lineProps[i])
legendStrings = list(numpy.zeros(NUMCOMPONENTS))
legendStrings[GLUCOSE] = 'GLUCOSE'
legendStrings[CELLULOSE] = 'CELLULOSE'
legendStrings[STARCH] = 'STARCH'
legendStrings[ACETATE] = 'ACETATE'
legendStrings[BUTYRATE] = 'BUTYRATE'
legendStrings[SUCCINATE] = 'SUCCINATE'
legendStrings[HYDROGEN] = 'HYDROGEN'
legendStrings[PROPIONATE] = 'PROPIONATE'
legendStrings[METHANE] = "METHANE"
legendStrings[RUMINOCOCCUS] = 'RUMINOCOCCUS'
legendStrings[METHANOBACTERIUM] = "METHANOBACTERIUM"
legendStrings[BACTEROIDES] = 'BACTEROIDES'
legendStrings[SELENOMONAS] = 'SELENOMONAS'
legendStrings[CLOSTRIDIUM] = 'CLOSTRIDIUM'
legendStrings = [legendStrings[i] for i in columnNumbers]
legend(legendStrings, loc='best')
dt = datetime.datetime.now()
dtAsString = dt.strftime('%d-%m-%Y_%H-%M-%S')
if filenamePrefix is None:
filenamePrefix = ''
if filenamePrefix != '' and filenamePrefix[-1] != '_':
filenamePrefix += '_'
if saveFig:
savefig(filenamePrefix+dtAsString+'.eps')
if saveThumb:
savefig(filenamePrefix+dtAsString+'.png', dpi=300)
if showFig: f.show()
close('all')
When I plot this in single iterations, it works fine. However, the moment I put it in a loop, matplotlib throws a hissy fit...
Traceback (most recent call last):
File "c4hm_param_variation_h2_conc.py", line 148, in <module>
plotColumns(columnNumbers, timeVector, out, showFig=False, filenamePrefix='c
4hm_param_variation_h2_conc_'+str(hydrogen_conc), saveFig=False, saveThumb=True)
File "D:\phdproject\alexander paper\python\v3\plotcolumns.py", line 48, in plo
tColumns
savefig(filenamePrefix+dtAsString+'.png', dpi=300)
File "C:\Python25\lib\site-packages\matplotlib\pyplot.py", line 356, in savefi
g
return fig.savefig(*args, **kwargs)
File "C:\Python25\lib\site-packages\matplotlib\figure.py", line 1032, in savef
ig
self.canvas.print_figure(*args, **kwargs)
File "C:\Python25\lib\site-packages\matplotlib\backend_bases.py", line 1476, i
n print_figure
**kwargs)
File "C:\Python25\lib\site-packages\matplotlib\backends\backend_agg.py", line
358, in print_png
FigureCanvasAgg.draw(self)
File "C:\Python25\lib\site-packages\matplotlib\backends\backend_agg.py", line
314, in draw
self.figure.draw(self.renderer)
File "C:\Python25\lib\site-packages\matplotlib\artist.py", line 46, in draw_wr
apper
draw(artist, renderer, *kl)
File "C:\Python25\lib\site-packages\matplotlib\figure.py", line 773, in draw
for a in self.axes: a.draw(renderer)
File "C:\Python25\lib\site-packages\matplotlib\artist.py", line 46, in draw_wr
apper
draw(artist, renderer, *kl)
File "C:\Python25\lib\site-packages\matplotlib\axes.py", line 1735, in draw
a.draw(renderer)
File "C:\Python25\lib\site-packages\matplotlib\artist.py", line 46, in draw_wr
apper
draw(artist, renderer, *kl)
File "C:\Python25\lib\site-packages\matplotlib\legend.py", line 374, in draw
bbox = self._legend_box.get_window_extent(renderer)
File "C:\Python25\lib\site-packages\matplotlib\offsetbox.py", line 209, in get
_window_extent
px, py = self.get_offset(w, h, xd, yd)
File "C:\Python25\lib\site-packages\matplotlib\offsetbox.py", line 162, in get
_offset
return self._offset(width, height, xdescent, ydescent)
File "C:\Python25\lib\site-packages\matplotlib\legend.py", line 360, in findof
fset
return _findoffset(width, height, xdescent, ydescent, renderer)
File "C:\Python25\lib\site-packages\matplotlib\legend.py", line 325, in _findo
ffset_best
ox, oy = self._find_best_position(width, height, renderer)
File "C:\Python25\lib\site-packages\matplotlib\legend.py", line 817, in _find_
best_position
verts, bboxes, lines = self._auto_legend_data()
File "C:\Python25\lib\site-packages\matplotlib\legend.py", line 669, in _auto_
legend_data
tpath = trans.transform_path(path)
File "C:\Python25\lib\site-packages\matplotlib\transforms.py", line 1911, in t
ransform_path
self._a.transform_path(path))
File "C:\Python25\lib\site-packages\matplotlib\transforms.py", line 1122, in t
ransform_path
return Path(self.transform(path.vertices), path.codes,
File "C:\Python25\lib\site-packages\matplotlib\transforms.py", line 1402, in t
ransform
return affine_transform(points, mtx)
MemoryError: Could not allocate memory for path
This happens on iteration 2 (counting from 1), if that makes a difference. The code is running on Windows XP 32-bit with python 2.5 and matplotlib 0.99.1, numpy 1.3.0 and scipy 0.7.1.
EDIT: The code has now been updated to reflect the fact that the crash actually occurs at the call to legend(). Commenting that call out solves the problem, though obviously, I would still like to be able to put a legend on my graphs...
|
I'm using GoogleApp Engine and occasionally when I send a query to BigQuery via the JSON API, I will get incorrect results. It is usually only confined to a single table within BigQuery (I make a new table for every batch job that is created). When I run into this issue in production, I log the Query i submitted and try running it via the BigQuery dashboard which runs longer than expected but returns the expected results.
There is nothing in the response indicating an issue. the jobComplete comes back as True but I see no rows, just the jobReference, schema, and totalRows = 0.
In such situations is is appropriate to do a call to get the job results even though I should expect the current call to return the results?
Relevant Code:
http = httplib2.Http(memcache)
self.credentials = AppAssertionCredentials(scope='https://www.googleapis.com/auth/bigquery')
self.http = self.credentials.authorize(http=http)
self.service = build('bigquery','v2',http=self.http)
jobs = self.service.jobs()
result = jobs.query(projectId=settings.GOOGLE_APIS_PROJECT_ID,
body={'query': query}).execute()
Response:
{u'totalRows': u'0', u'kind': u'bigquery#queryResponse', u'jobComplete': True, u'jobReference': {u'projectId': u'<REMOVED>', u'jobId': u'<REMOVED>'}, u'schema': {u'fields': [<REMOVED>]}}
No matter how many times I try to re-run the query in production, the same results are returned (Could this be due to the caching done via memcache with incorrect results being cached as a response?)
|
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 into the way, and using a goto is just much clearer.”
Linus Torvalds – 12 janvier 2003
Hors ligne
helly
Re : /* Topic des codeurs couche-tard [1] */
Après
Hors ligne
samυncle
Re : /* Topic des codeurs couche-tard [1] */
avant (faut de la contestation)
Hello world
Hors ligne
Pylades
Re : /* Topic des codeurs couche-tard [1] */
Il reste l’avis de cinq habitués ici à prendre en compte (grim7reaper, gnuuat, tshirtman, nesthib, le n@nyl@nd). Donc quand on aura eu tous les avis il ne pourra pas y avoir d’égalité.
“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 into the way, and using a goto is just much clearer.”
Linus Torvalds – 12 janvier 2003
Hors ligne
helly
Re : /* Topic des codeurs couche-tard [1] */
Sauf si deux font avant
Deux après
Et un ne se prononce pas
Hors ligne
nesthib
Re : /* Topic des codeurs couche-tard [1] */
moi j'aime bien les ..:: ::..
sinon z'avez testé mon détecteur de double-connectés ?
à ce sujet j'avais un problème existentiel : quelle est la meilleure méthode pour ne garder QUE les doublons dans une liste ?
Hors ligne
Pylades
Re : /* Topic des codeurs couche-tard [1] */
Ou si un demande carrément autre chose.
D’ailleurs, moi je pense que ça surchargerait le titre du fil, je ne suis pas pour. Les crochets suffisent, je pense, à distinguer les codeurs des plopeurs.
Édit :
à ce sujet j'avais un problème existentiel : quelle est la meilleure méthode pour ne garder QUE les doublons dans une liste ?
sort | uniq -d
?
Dernière modification par Pylade (Le 13/06/2010, à 11:35)
“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 into the way, and using a goto is just much clearer.”
Linus Torvalds – 12 janvier 2003
Hors ligne
xapantu
Re : /* Topic des codeurs couche-tard [1] */
liste des affreux planteurs du forum :Yannick@AMD64MikeSierra01
Hors ligne
helly
Re : /* Topic des codeurs couche-tard [1] */
File "./doubleurs.py", line 15
for user in unique:
^
IndentationError: expected an indented block
Hors ligne
nesthib
Re : /* Topic des codeurs couche-tard [1] */
nesthib a écrit :
à ce sujet j'avais un problème existentiel : quelle est la meilleure méthode pour ne garder QUE les doublons dans une liste ?
sort | uniq -d
?
euh…
1- je fais pas ça en bash mais en python
2- je voulais plutôt dire d'un côté algo
File "./doubleurs.py", line 15
for user in unique:
^
IndentationError: expected an indented block
t'as raté ton copier-coller
Hors ligne
nesthib
Re : /* Topic des codeurs couche-tard [1] */
je veux pas les éliminer mais les garder sinon c'est ce que j'ai fait, j'ai utilisé set comme base pour déterminer les doublons
edit : merci pour le lien, c'est quand même plus pratique ^^
Dernière modification par nesthib (Le 13/06/2010, à 12:01)
Hors ligne
Kanor
Re : /* Topic des codeurs couche-tard [1] */
Ah oui je viens de voir pour l'histoire du set ..
edit
je te propose ça
>>> from operator import groupby
>>> gg = [1,32,3,4,5,2,53,32,43,1]
>>> gg.sort()
>>> [ a for a, b in groupby(gg) if len(list(b)) > 1]
[1, 32]
Dernière modification par Kanor (Le 13/06/2010, à 12:08)
Hors ligne
Pylades
Re : /* Topic des codeurs couche-tard [1] */
euh…
1- je fais pas ça en bash mais en python
2- je voulais plutôt dire d'un côté algo
sort et uniq sont des commandes existant sous forme de binaires exécutables (dans /usr/bin/)…
“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 into the way, and using a goto is just much clearer.”
Linus Torvalds – 12 janvier 2003
Hors ligne
nesthib
Re : /* Topic des codeurs couche-tard [1] */
oui abus de langage Pylade mais tu as compris ce qui m'intéresse c'est l'algo (et non je ne vais pas aller voir les sources de uniq )
Hors ligne
Pylades
Re : /* Topic des codeurs couche-tard [1] */
« Pourquoi faire simple lorsque l’on peut faire compliqué ? »
…
“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 into the way, and using a goto is just much clearer.”
Linus Torvalds – 12 janvier 2003
Hors ligne
Pylades
Re : /* Topic des codeurs couche-tard [1] */
Ben tu as déjà une commande qui fait ça, et tu veux carrément recoder, mais un truc qui ne fait qu’une partie de ce que faisait la commande. Ça fait un peu Shadok.
“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 into the way, and using a goto is just much clearer.”
Linus Torvalds – 12 janvier 2003
Hors ligne
nesthib
Re : /* Topic des codeurs couche-tard [1] */
euh nan… je cherche juste à m'instruire sur le meilleur algo / la meilleure méthode.
après en pratique j'ai utilisé les outils déjà dispo
Hors ligne
grim7reaper
Re : /* Topic des codeurs couche-tard [1] */
Hello World !
It works!\o/
Ta lib est terminée ?
Bon, alors, vous en pensez quoi ? On met le planeur ? Avant le titre ? Après ?
Les deux mon général, je suis pour la symétrie \o/.
Bon la symétrie ne sera pas parfaite car je ne crois pas qu'on puisse faire le planeur dans les deux sens, mais je m'en contenterai .
à ce sujet j'avais un problème existentiel : quelle est la meilleure méthode pour ne garder QUE les doublons dans une liste ?
Là tout de suite à la levée du canapé, je dirais qu'un parcours séquentiel avec comparaison du nom courant avec le suivant à chaque itération ça pourrait le faire. Ça fonctionne vu que ta liste est triée (par ordre alphabétique), si tu as le courant égal au suivant c'est un doublon donc tu le gardes (tu le mets dans une autre liste par exemple, ou tu le laisses si tu préfères supprimer les non-doublon) et tu avance de 2 cases, sinon tu fais ce que tu as à faire (suppression du non-doublon, ou les laisser dans la liste) et tu passes au mot suivant.
Si ce n'est pas trié c'est plus complexe.
Dernière modification par grim7reaper (Le 13/06/2010, à 19:21)
Hors ligne
helly
Re : /* Topic des codeurs couche-tard [1] */
Bon, ce soir /me se met à l'épurage/correction d'un vieux programme de chat que j'avais fait il y avait 2ans, à l'époque où je savais pas faire la différence entre du C et du C++
Hors ligne
grim7reaper
Re : /* Topic des codeurs couche-tard [1] */
Bah moi ce soir je glande \o/, je l'ai bien mérité.
.
.
.
Ha wait !
On me dis à l'oreillette qu'il faut que je potasse mon traitement du signal et que je termine un TP à rendre.
Bon bah on verra la glandouille une autre fois alors .
Hors ligne
helly
Re : /* Topic des codeurs couche-tard [1] */
Mais quand est ce que tu es en vacances toi ?
T'as pris l'option «sans grandes vacances» ?
(si t'as payé pour avoir cette option, tu t'es fait avoir )
Hors ligne
helly
Re : /* Topic des codeurs couche-tard [1] */
Hey les gens, y'a moyen de mettre une variable en const dans une classe ? genre
class plop
{
private : const int p;
}
Le problème c'est que quand je déclare comme ça, il en veut pas
Alors que j'en aurai besoin pour une variable que je n'affecte qu'une seule fois pour cette classe, et ensuite j'ai plus besoin de la faire varier…
(une constante quoi )
Hors ligne
grim7reaper
Re : /* Topic des codeurs couche-tard [1] */
Mais quand est ce que tu es en vacances toi ?
Dans 2 semaines.
Là j'ai une semaine de révision puis une semaine d'exam.
T'as pris l'option «sans grandes vacances» ?
Déconne pas, c'est la dernière année où j'ai les «grandes vacances»
Hey les gens, y'a moyen de mettre une variable en const dans une classe ? genre
class plop
{
private : const int p;
}
Le problème c'est que quand je déclare comme ça, il en veut pas
Alors que j'en aurai besoin pour une variable que je n'affecte qu'une seule fois pour cette classe, et ensuite j'ai plus besoin de la faire varier…
(une constante quoi )
C'est normal, une constante doit avoir sa valeur fixée à la compilation (c'est la définition même d'une constante, elle à une valeur au lancement du programme puis n'en change pas). Il faut que tu l'initialises.
Si tu veux une variable qui est associée à la classe (commune à tout les objets), je crois qu'il faut regarder du côté de static.
Dernière modification par grim7reaper (Le 13/06/2010, à 21:31)
Hors ligne
|
I'm a true n00b (amateur, learning Python for fun), so as a programming exercise (to test my newfound knowledge of OAuth and App Engine), I adapted Mike Knapp's OAuth on App Engine code and was able to successfully get a request token and exchange it for an access token from Twitter.
However, when I attempted to do the same for Google's various APIs, I consistently receive HTTP 400 error with a cryptic error msg of "signature_invalid base_string" followed by my base_string. After hours of fiddling to no avail, I checked Google's OAuth Playground and saw that the OAuth Playground could pull a request token using my consumer key and secret (and exchange for an access token, etc).
I even found that when I copied verbatim the oauth_nonce, oauth_callback and oauth_timestamp values for successful OAuth Playground runs that I was unable to replicate the oauth_signature that the Playground was generating.
Questions (4, very related):
What causes a "signature_invalid base_string" error in an initial request_token pull?
What is different between the Twitter request token process and Google's OAuth API request token process?
Why are the oauth_nonce's I'm generating (i.e. 15321613214272404748 usingstr(getrandbits(64))) so much shorter than the oauth_nonce's the OAuth Playground generates (i.e. f23d148edd312aac6984c6639ddab3fb)
Why can't I replicate the OAuth Playground's signatures even when all the parameters are the same?
Thanks, would much appreciate some help
Edit: adding code pertaining to the encoding (apologies for the choppiness, but I broke out each of these steps so that I could inspect into each to see if anything weird was happening at any step); the first function is preparing a dictionary of parameters and the basestring itself; the second is the actual encoding
def prepareParameters(method, url, oauth_callback, consumer_key, oauth_token = None, oauth_verifier = None, scopes = None, oauth_version = "1.0", extra_parameters = None):
def encode(text):
return urlquote(str(text), '')
parameters = {
'oauth_consumer_key': consumer_key,
'oauth_signature_method': 'HMAC-SHA1',
'oauth_timestamp': str(int(time())),
'oauth_nonce': str(getrandbits(64)),
'oauth_version': oauth_version
}
if scopes:
if not isinstance(scopes, (list, tuple)):
scopes = [scopes,]
scopestring = ' '.join([str(scope) for scope in scopes])
parameters['scope'] = scopestring
if oauth_callback:
parameters['oauth_callback'] = oauth_callback
if oauth_token:
parameters['oauth_token'] = oauth_token
if oauth_verifier:
parameters['oauth_verifier'] = oauth_veriifer
if extra_parameters:
parameters.update(extra_parameters)
for k,v in parameters.items():
if isinstance(v, unicode):
parameters[k] = v.encode('utf8')
parametersstring = '&'.join(['%s=%s' % (encode(k), encode(parameters[k])) for k in sorted(parameters)])
basestring = '&'.join((method, encode(url), encode(parametersstring)))
return parameters, basestring
def encodeBaseString(basestring, consumer_secret, parameters, token_secret = ''):
key = '%s&%s' % (consumer_secret, token_secret)
signature = hmac(key, basestring, sha1)
encoded = signature.digest().encode('base64').strip()
parameters['oauth_signature'] = encoded
return parameters, encoded
|
The following is the simplest code I could come up with that allowed me to position the image at position (0, 0, -10):
#!/usr/bin/env python
import pyglet
from pyglet.gl import *
window = pyglet.window.Window()
glEnable(GL_DEPTH_TEST)
image = pyglet.image.load('imgs/appfolio.png')
texture = image.get_texture()
glEnable(texture.target)
glBindTexture(texture.target, texture.id)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width, image.height,
0, GL_RGBA, GL_UNSIGNED_BYTE,
image.get_image_data().get_data('RGBA', image.width * 4))
rect_w = float(image.width) / image.height
rect_h = 1
@window.event
def on_draw():
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
glTranslatef(0, 0, -10)
glBindTexture(texture.target, texture.id)
glBegin(GL_QUADS)
glTexCoord2f(0.0, 0.0); glVertex3f(-rect_w, -rect_h, 0.0)
glTexCoord2f(1.0, 0.0); glVertex3f( rect_w, -rect_h, 0.0)
glTexCoord2f(1.0, 1.0); glVertex3f( rect_w, rect_h, 0.0)
glTexCoord2f(0.0, 1.0); glVertex3f(-rect_w, rect_h, 0.0)
glEnd()
def on_resize(width, height):
glViewport(0, 0, width, height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(65.0, width/float(height), 0.1, 1000.0)
glMatrixMode(GL_MODELVIEW)
window.on_resize = on_resize # we need to replace so can't use @window.event
pyglet.app.run()
The most difficult part I found was that the on_resize function had to be replaced in order to work as I expected it to, as the default orthographic projection doesn't work.
I found Jess Hill's pyglet conversion of the NeHe tutorial on texture mapping to be most helpful.
The complete logo visualization code can be found at a blog entry I just wrote titled, "Moving Images in 3D Space with Pyglet".
|
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_WIDTH=200
IMAGE_HEIGHT=200
def make_magic_url(text):
# spaces in the text should be replaced with "+". probably other control symbols need to be handled in special way.
return 'http://chart.apis.google.com/chart?chs=%dx%d&cht=qr&choe=%s&chl=%s' %(IMAGE_WIDTH, IMAGE_HEIGHT, ENCODING, text.replace(" ", "+"))
def makeQR(text, dest):
print make_magic_url(text)
myfig=urllib2.urlopen(make_magic_url(text))
output=open(dest, 'wb')
output.write(myfig.read())
output.close()
text=sys.argv[1]
dest=sys.argv[2]
makeQR(text, dest)
Save this as fetchqr.py, or some such. Usage is simple:
python fetchqr.py 'http://tex.stackexchange.com/questions/1429/latex-package-to-generate-qr-codes' '/tmp/myfig.png'
And you'd get something like:
This works on Python 2.6 under Windows, but I imagine it shouldn't be a a problem with older Python versions. Not sure about Python 3.x though.
If you're using something like a Makefile to run your project, then you should be able to generate those on the fly as needed -- maybe create a file with stuff to QR-code, then run all the entries through the grinder in one go.
The code is free for the taking.
|
JDMK and Legacy IT Management
by Stephen B. Morris
02/16/2005
Consolidation, integration, refactoring, and migration are some of today's popular data center catchwords. All of these words reflect some kind of renewal or replacement process--the old is either substantially modified or thrown in the garbage and replaced with the new. However, in many cases, we are often stuck with old equipment and software. We must continue to extract more services from aging infrastructure and still make reasonable claim to them being manageable.
Java Dynamic Management Kit (JDMK) is a framework for the creation of Java-based management software and legacy SNMP-based systems. It extends Java Management Extensions (JMX), which allows instrumented applications to remotely monitor resources throughout the network.
One of the files I'll use contains a list of managed objects, which can be referenced by JDMK code. The following listing is an excerpt from a generated Java file, called RFC1213_MIBOidTable.java (available in the sample code, in the Resources section below). This file is generated with reference to a specified standard MIB file.
//Metadata definitions for managed objects of interest
new SnmpOidRecord("ifInOctets", "1.3.6.1.2.1.2.2.1.10", "C"),
new SnmpOidRecord("ifLastChange", "1.3.6.1.2.1.2.2.1.9", "T"),
new SnmpOidRecord("ifOperStatus", "1.3.6.1.2.1.2.2.1.8", "I"),
The symbols in each
SnmpOidRecord can be directly accessed by network management software. This is our interface into the managed network devices.
Later, I'll look at ways in which JDMK can provide something of a management makeover for legacy devices. As we'll see, it's reasonably easy and inexpensive to produce entry-level management tools. Such tools may even help IT managers to gain a deeper understanding of the dynamics of their networks and the services that sit on top of them.
One other take-away for readers is the use of the adapter pattern as a means of accessing the JDMK API. This increases the level of abstraction in the way we use the standard APIs.
An Unenviable Inheritance
Imagine you've just been promoted to network manager with a staff of two. You're now responsible for all of the computing devices on a site with 200 people spread across four departments. Part of the task is also connection the corporate WAN, telephony system support, PC upgrades, application deployment, server support, etc. Basically, you've got to concentrate on everything!
Let's assume Figure 1 is the hypothetical network for which you've become responsible.
Figure 1. An enterprise network
In Figure 1, we see a schematic diagram of a single building with three floors. The devices on each floor are connected into a switch--in many cases, these individual links will each have bandwidth of 10Mbps and terminate in a wiring closet (not shown). The switches in turn are connected (via Links 1, 2, and 3) to a floor-level switch (F1 for floor 1, F2 for floor 2, and F3 for floor 3). In turn, each floor-level switch is connected by a high-speed link to a core switch. The latter might then be connected to a WAN link or a service provider network.
Looking at Figure 1, we can immediately discern some possible problem areas. The following items represent single points of failure:
Links 1, 2 or 3
The links between the core switch and the floor-level switch
The individual switches
Remember that a network is only ever as strong as its weakest link--this means that our network is vulnerable. It's the job of the network designer to try to balance service continuity against the cost of providing redundancy. In Figure 1, there are some weak points that might profit from a review! I'll focus on these by writing some JDMK code to help us see when problems have occurred and when problems might be just about to occur.
Related Reading
Getting Started
An important requirement in any IT manager's job is identifying the weak points in the network. This involves a careful combination of talking to your users and your predecessor (if possible) and instigating data collection. Every network has its very own folklore! Certain network links may periodically become overloaded; one or two routers or switches may be a little flaky; a server may be past its sell-by date, etc.
A considerate predecessor might well pass on such vital information to you as you embark on your new job. Let's assume your predecessor is a kindly soul who wants to help you make an orderly transition into your new role. Further, let's assume that she tells you to "Watch out for Link 1--it tends to become congested, and the folks on Floor 1 get a little angsty." This is important insider know-how, and we'll put it to use in the Java code later on.
In many cases, networks are held together by a fragile combination of scripts and insider know-how. What I hope to show in this article is that it is pretty straightforward to produce some JDMK tools that will assist you in holding your own against the network you manage. There is, of course, no real substitute for a well-designed and well-maintained network, but even in this rare case, our Java tools might provide some assistance.
Standard Applications May Help
HP OpenView Network Node Manager (NNM) provides a widely used application that is found in both enterprise and service provider networks. It provides some useful features, including automatic discovery and mapping of network devices, receipt of notification messages, and the ability to add your own proprietary software. In short, NNM provides a GUI that allows you to see your network. If NNM is available to you, then it may prove invaluable in discovering and monitoring your network. If not, then don't despair!
The key to effective IT management is selective use of automated tools. If you have access to high-end application software, then use it. As we move into an era of autonomic computing, it will increasingly be the case that systems and software will execute some or all of their own management. Get aboard this bandwagon early by maximizing your use of software solutions in your IT management tasks!
Creating Software to Ease the Management Task
Using JDMK, we can create software that both listens for events and pro-actively reads device status. In this article, I'll be focusing on the latter, just to illustrate the principles.
To begin with, I'll write a simple program that looks at a specific network link and tries to determine if it's prone to congestion. We do this by sampling and averaging some SNMP counters on an interface at one end of this link. These are standard objects that are maintained by the SNMP entity running on the device. Sometimes, the SNMP entity is not running by default--in this case, I'll assume the network manager (i.e., your predecessor!) has chosen to run SNMP on all of those devices where it is available. Let's now describe the simple requirements for the code.
Our Selected Set of Management Requirements
We want to create some software that fulfils the following simple requirements:
Return the operational status of a specified interface.
Calculate the traffic level for a specified interface.
Determine if a specified link is approaching a state of congestion.
An interface usually has an administrative state and an operational state. The administrative state is the one desired by the network manager; i.e., "I want this interface to be up." The operational state is the actual state of the interface. Try to think about the operational state as the network's response to the requested state. If the administrative state is up and the operational state is down, then we know there's a problem.
The interface type I'll be using is Ethernet, specifically 10Mbps (or 10,000,000bps). I'll be retrieving a snapshot of the count of incoming bits received at an interface at one end of Link 1 in Figure 1. This will give us an instantaneous picture of the inward traffic level at that interface. Then, we'll wait a bit and retrieve the same counter value. The difference between these two values gives us the required utilization value. Let's have a look at some source code now.
The Source Code
The Java class I use is called RequestData. It contains a main() method and makes use of the following JDMK resources (among others):
import com.sun.management.snmp.SnmpDefinitions;
import com.sun.management.snmp.SnmpOid;
import com.sun.management.snmp.SnmpVarBindList;
import com.sun.management.snmp.manager.SnmpPeer;
To begin with, I initialize the SNMP Manager API. This allows us to access the generated table mentioned in the introduction.
final SnmpOidTableSupport oidTable =
new RFC1213_MIBOidTable();
SnmpOid.setSnmpOidTable(oidTable);
Next, I create an SnmpPeer object. This represents the entity with which we will communicate. Note that this uses the port passed in as a command-line parameter.
final SnmpPeer agent =
new SnmpPeer(host, Integer.parseInt(port));
We must now create a communications session with the remote entity. This requires us to specify SNMP community strings. These data elements are then associated with the agent.
final SnmpParameters params =
new SnmpParameters("public", "private");
agent.setParams(params);
We're nearly there! We now have to build the session to manage the data request and then we're ready to create the data request list (or variable binding list).
final SnmpSession session =
new SnmpSession("SyncManager session");
session.setDefaultPeer(agent);
final SnmpVarBindList list =
new SnmpVarBindList(
"SyncManager varbind list");
The program is a single JDMK class that builds an SNMP request message. This message specifies four objects of interest, using the following code:
// A description of the host device
list.addVarBind("sysDescr.0");
// The operational state of interface 1
list.addVarBind("ifOperStatus.1");
// The number of incoming octets on interface 1
list.addVarBind("ifInOctets.1");
// The speed of interface 1
list.addVarBind("ifSpeed.1");
Our four required objects are packed into an SNMP getRequest message and sent to the receiving entity as follows:
SnmpRequest request =
session.snmpGetRequest(null, list);
We now retrieve the same set of objects twice; the difference in time between the samples is found using this Java code:
// Calculate the time between messages
long oldTime = date1.getTime();
long newTime = new Date().getTime();
long elapsed = (newTime - oldTime) / MS_DIVIDEND;
println("Elapsed time in seconds " + elapsed);
In this section, we get the most recent time and subtract a time value recorded just before the first retrieval. This gives us a rough estimate of the elapsed time between the data samples.
When the returned data is displayed, we see the following major elements:
Value : 25625, Object ID : 1.3.6.1.2.1.2.2.1.5.1 (Syntax : Gauge32)
Value : 10000000
>> Press Enter to resend the request.
Elapsed time in seconds 16
Value : 26005, Object ID : 1.3.6.1.2.1.2.2.1.5.1 (Syntax : Gauge32)
Value : 10000000
The three bold data items above represent the two values of the ifInOctets object taken at an interval of 16 seconds. The selected interface (which supports a speed of 10,000,000bps) has received 25625 octets (or bytes) at the time T1 and 26005 octets at the time T2. To determine the incoming link utilization, we apply the following formula:
Incoming Link % Utilization = ((T2 octets - T1 octets) * 8 * 100) / (ifSpeed * Sample speed)
Plugging in the values above gives us a utilization of (26005 - 25625) * 8 * 100/(10,000,000 * 16), or 0.0019 percent.
Clearly, the interface is very lightly loaded on the incoming side! A similar measurement can be made for the outgoing direction (using the ifOutOctets object instead). Then, both values can be summed to determine the overall loading. Obviously, care is required in drawing any conclusions from the figures (they are instantaneous snapshots of data that can change rapidly), but they do provide some minimal level of understanding of the loading on the interface.
Plying this program with diligence and observing loading trends over a period of a day might lead us to understand why the outgoing network manager made the comment concerning Link 1. In any case, it means that you are beginning to learn about the secrets that the network holds in store! Extending this approach to other regions of the network should help in acquiring a broader understanding again.
Running the Example
To run the example program, you'll need to install JDMK. Free evaluation copies can be downloaded from Sun Microsystems, though these copies expire after 90 days. So don't be too leisurely about running this code! Alternatively, if you win a couple of lotteries, you might be tempted to purchase JDMK.
In either case, just follow the instructions in the examples\current\Snmp\Manager\ReadMe file and the example should compile and run successfully. I used JDMK version 5.1. Also, there's detail and further Java examples in my book, Network Management, MIBs & MPLS: Principles, Design & Implementation--no lottery win required!
Remember: Use Patterns
I strongly encourage using the adapter pattern to hide the complexity of the JDMK API. Really, JDMK isn't complex per se, but it is proprietary. For this reason, it's important to not litter your application code with calls into such an API. The adapter provides a useful model for achieving this noble design aim.
The adapter serves to insulate the application code from the details of the JDMK (or other) technology. Your code then calls into the adapter, rather than directly using the JDMK interface. So, if you later decide to change from JDMK and use another technology, any required changes to your code will have been minimized ahead of time.
Further details on the adapter pattern and its applications can be found in design pattern books, such as O'Reilly's Head First Design Patterns.
Conclusions
Supporting legacy systems and equipment is difficult and unforgiving, particularly as IT budgets and staffing levels are squeezed. However, nothing is too much of a challenge for a game Java developer! Using some simple concepts from network management and SNMP, it's possible to quickly create some quite powerful JDMK-based software tools. These tools can be used to keep an eye on troublesome corners of your network, while you get on with more interesting tasks. They might also help you troubleshoot in times of difficulty.
I've barely scratched the surface of what's possible with JDMK: you can employ notifications, create your own agents as well as managers, use browsers to access the management infrastructure, etc. However, perhaps more importantly, what we have seen on the one hand is the conceptual simplicity of network management, and on the other the potentially boundless complexity of running a network. Both endeavors must meet at a common boundary, and JDMK provides a fertile ground for this.
Resources
Sample code for this article
JDMK
HP OpenView Network Node Manager
Network Management, MIBs & MPLS: Principles, Design & Implementation, by Stephen Morris
Stephen B. Morris is an independent writer/consultant based in Ireland.
Return to ONJava.com.
Comments on this article
Trackback from http://alexis-develle.k9.pl/
JDMK and Legacy IT Management
2005-09-30 07:49:39 [View]
Good start, but
2005-02-16 17:19:45 hexghost [View]
Good start, but
2005-02-21 04:36:07 Stephen1 [View]
Good start, but
2005-03-09 16:53:45 leeschumacher [View]
|
You must give a presentation tomorrow and you haven't prepared any figures yet; you must document your last project and you need to plot your most hairy class hierarchies; you are asked to provide ten slightly different variations of the same picture; you are pathologically unable to put your finger on a mouse and draw anything more complex than a square. In all these cases, don't worry! dot can save your day!
dot?
dot is a tool to generate nice-looking diagrams with a minimum of effort. It's part of GraphViz, an open source project developed at AT&T and released under an MIT license. It is a high-quality and mature product, with very good documentation and support, available on all major platforms, including Unix/Linux, Windows, and Mac. There is an official home page and a supporting mailing list.
dot?
First of all, let me make clear that dot is not just another paint program, nor a vector graphics program. dot is a scriptable, batch-oriented graphing tool; it is to vector drawing programs as LaTeX is to word processors. If you want to control every single pixel in your diagram, or if you are an artistic person who likes to draw free hand, then dot is not for you. dot is a tool for the lazy developer, the one who wants the job done with the minimum effort and without caring too much about the details.
Since dot is not a WYSIWYG tool—even if it comes with a WYSIWYG tool, dotty—it is not primarily an interactive tool. Its strength is the ability to generate diagrams programmatically. To fulfill this aim, dot uses a simple but powerful graph description language. Give dot very high level instructions and it will draw the diagrams for you, taking into account all the low level details. Though you have a large choice of customization options and can control the final output in many ways, it is not at all easy to force dot to produce exactly what you want, down to the pixel.
Linux/Unix System Administration Certification -- Would you like to polish your system administration skills online and receive credit from the University of Illinois? Learn how to administer Linux/Unix systems and gain real experience with a root access account. The four-course series covers the Unix file system, networking, Unix services, and scripting. It's all at the O'Reilly Learning Lab.
Expecting that would mean to fight with the tool. You should think of dot as a kind of smart boy, who likes to do things his own way and who is very good at it, but becomes nervous if the master tries to put too much pressure on him. The right attitude with dot (just as with LaTeX) is to trust it and let it to do the job. At the end, when dot has finished, you can always refine the graph by hand. (dotty, the dot diagram interactive editor, comes with GraphViz and can read and generate dot code.) In most cases, you do not need to do anything manually, since dot works pretty well. The best approach is to customize dot options, so that you can programmatically generate one or one hundred diagrams with the least effort.
dot is especially useful in repetitive and automatic tasks, since it easy to generate dot code. For instance, dot comes in handy for automatic documentation of code. UML tools can also do this work, but dot has an advantage over them in terms of ease of use, a flatter learning curve, and greater flexibility. On top of that, dot is very fast and can generate very complicated diagrams in fractions of second.
dot
dot code has a C-ish syntax and is quite readable even to people who have not read the manual. For instance, this dot script:
graph hello {
// Comment: Hello World from ``dot``
// a graph with a single node Node1
Node1 [label="Hello, World!"]
}
generates the image shown in Figure 1.
Figure 1. "Hello, World!" from GraphViz
Save this code in a file called hello.dot. You can then generate the graph and display it with a simple one-liner:
$ dot hello.dot -Tps | gv -
The -Tps option generates PostScript code, which is then piped to the ghostview utility. I've run my examples on a Linux machine with ghostview installed, but dot works equally well under Windows, so you may trivially adapt the examples.
If you're satisfied with the output, save it to a file:
$ dot hello.dot -Tps -o hello.ps
You'll probably want to tweak the options, for instance adding colors and changing the font size. This is not difficult:
graph hello2 {
// Hello World with nice colors and big fonts
Node1 [label="Hello, World!", color=Blue, fontcolor=Red,
fontsize=24, shape=box]
}
This draws a blue square with a red label, shown in Figure 2.
Figure 2. A stylish greeting
You can use any font or color available to X11.
Editor's note: or presumably to Windows, if you're not running an X server.
dot is quite tolerant: the language is case insensitive and quoting the options color="Blue", shape="box" will work too. Moreover, in order to please C fans, you can use semicolons to terminate statements; dot will ignore them.
dot
A generic dot graph is composed of nodes and edges. Our hello.dot example contains a single node and no edges. Edges enter in the game when there are relationships between nodes, for instance hierarchical relationships as in this example, which produced Figure 3:
digraph simple_hierarchy {
B [label="The boss"] // node B
E [label="The employee"] // node E
B->E [label="commands", fontcolor=darkgreen] // edge B->E
}
Figure 3. A hierarchical relationship
dot is especially good at drawing directed graphs, where there is a natural direction. (GraphViz also includes the similar neato tool to produce undirected graphs). In this example the direction is from the boss, who commands, to the employee, who obeys. Of course dot gives you the freedom to revert social hierarchies, as seen in Figure 4:
digraph revolution {
B [label="The boss"] // node B
E [label="The employee"] // node E
B->E [label="commands", dir=back, fontcolor=red]
// revert arrow direction
}
Figure 4. An inverted hierarchy
Sometimes, you want to put things of the same importance on the same level. Use the rank option, as in the following example, which describes a hierarchy with a boss, two employees, John and Jack, of the same rank, and a lower ranked employee Al who works for John. See Figure 5 for the results.
digraph hierarchy {
nodesep=1.0 // increases the separation between nodes
node [color=Red,fontname=Courier]
edge [color=Blue, style=dashed] //setup options
Boss->{ John Jack } // the boss has two employees
{rank=same; John Jack} //they have the same rank
John -> Al // John has a subordinate
John->Jack [dir=both] // but is still on the same level as Jack
}
Figure 5. A multi-level organizational chart
This example shows a nifty feature of dot: if you forget to give explicit labels, it will use the name of the nodes as default labels. You can also set the default colors and style for nodes and edges respectively. It is even possible to control the separation between (all) nodes by tuning the nodesep option. I'll leave it as an exercise for the reader to see what happens without the rank option (hint: you get a very ugly graph).
dot is quite sophisticated, with dozen of options which you can find in the excellent documentation. In particular, the man page (man dot) is especially useful and well done. The documentation also explains how to draw graphs containing subgraphs. However, those advanced features are outside the scope of this brief article.
We'll discuss another feature instead: the ability to generate output in different formats. Depending on your requirements, different formats can be more or less suitable. For the purpose of generating printed documentation, the PostScript format is quite handy. On the other hand, if you're producing documentation to convert to HTML format and put on a Web page, PNG format can be handy. It is quite trivial to select an output format with the -T output format type flag:
$ dot hello.dot -Tpng -o hello.png
There are many others available formats, including all the common ones such as GIF, JPG, WBMP, FIG and more exotic ones.
dot Code
dot is not a real programming language, but it is pretty easy to interface dot with a real programming language. Bindings exist for many programming languages—including Java, Perl, and Python. A more lightweight alternative is just to generate the dot code from your preferred language. Doing so will allow you to automate the entire graph generation.
Here is a simple Python example using this technique. This example script shows how to draw Python class hierarchies with the least effort; it may help you in documenting your code.
# dot.py
"Require Python 2.3 (or 2.2. with from __future__ import generators)"
def dotcode(cls):
setup='node [color=Green,fontcolor=Blue,fontname=Courier]\n'
name='hierarchy_of_%s' % cls.__name__
code='\n'.join(codegenerator(cls))
return "digraph %s{\n\n%s\n%s\n}" % (name, setup, code)
def codegenerator(cls):
"Returns a line of dot code at each iteration."
# works for new style classes; see my Cookbook
# recipe for a more general solution
for c in cls.__mro__:
bases=c.__bases__
if bases: # generate edges parent -> child
yield ''.join([' %s -> %s\n' % ( b.__name__,c.__name__)
for b in bases])
if len(bases) > 1: # put all parents on the same level
yield " {rank=same; %s}\n" % ''.join(
['%s ' % b.__name__ for b in bases])
if __name__=="__main__":
# returns the dot code generating a simple diamond hierarchy
class A(object): pass
class B(A): pass
class C(A): pass
class D(B,C): pass
print dotcode(D)
The function dotcode takes a class and returns the dot source code needed to plot the genealogical tree of that class. codegenerator generates the code, traversing the list of the ancestors of the class (in the Method Resolution Order of the class) and determining the edges and the nodes of the hierarchy. codegenerator is a generator which returns an iterator yielding a line of dot code at each iteration. Generators are a cool recent addition to Python; they come particularly handy for the purpose of generating text or source code.
The output of the script is the following self-explanatory dot code:
digraph hierarchy_of_D {
node [color=Green,fontcolor=Blue,font=Courier]
B -> D
C -> D
{rank=same; B C }
A -> B
A -> C
object -> A
}
Now the simple one-liner:
$ python dot.py | dot -Tpng -o x.png
generates Figure 6.
Figure 6. A Python class diagram
You may download dot and the others tool coming with GraphViz at the official GraphViz homepage. You will also find plenty of documentation and links to the mailing list.
Perl bindings (thanks to Leon Brocard) and Python bindings (thanks to Manos Renieris) are available. Also, Ero Carrera has written a professional-looking Python interface to dot.
The script dot.py I presented in this article is rather minimalistic. This is on purpose. My Python Cookbook recipe, Drawing inheritance diagrams with Dot, presents a much more sophisticated version with additional examples.
Michele Simionato is employed by Partecs, an open source company headquartered in Rome. He is actively developing web applications in the Zope/Plone framework.
Return to the LinuxDevCenter.com.
Copyright © 2009 O'Reilly Media, Inc.
|
#6 Re : -1 » message d'erreur » Le 13/09/2014, à 04:44
#7 Re : -1 » [RÉSOLU] Supprimer les anciens noyaux » Le 11/09/2014, à 05:46
nesthib
Réponses : 16
Désolé, pas de commande magique.
Mais si :
kernel_clean () {
KEEP=2
KERNELS=($(dpkg -l | awk '/ii linux-image-[0-9]\./{gsub("-generic","",$2); print $2}'))
KERNELS_TO_REMOVE=(${KERNELS[@]:0:${#KERNELS[@]}-$KEEP})
sudo apt-get remove ${KERNELS_TO_REMOVE[@]} ${KERNELS_TO_REMOVE[@]/image/headers}
}
#8 Re : -1 » [resolu] Ameliorer la commande chmod » Le 09/09/2014, à 04:26
#9 Re : -1 » Changer son pseudo » Le 06/09/2014, à 21:13
nesthib
Réponses : 10
Ta description n'est pas très claire… (en particulier, comment fais-tu correspondre une description à une valeur ?).
Pourrais-tu donner un exemple concret et explicite ?
Ce que je comprends est que tu veux concaténer ligne à ligne 2 listes, tu peux faire ainsi :
fichier1
12345
fichier2
ligne Aligne Bligne Cligne Dligne E
et pour les fusionner :
paste -d ' ' fichier1 fichier21 ligne A2 ligne B3 ligne C4 ligne D5 ligne E
Bien entendu, tu n'as pas besoin d'avoir des fichiers temporaires, l'entrée de paste peut être lue sur la sortie d'une ou deux commandes.
nesthib
Réponses : 10
Tu peux toujours stocker le tout dans une variable :
VAR=$(echo start ; pwd ; date ; echo stop)
echo "$VAR"
tr 'a-z' 'A-Z' <<<"$VAR"
Mais je pense que tu te méprends sur le fonctionnement du shell. La notion de « commande non finie » n'a pas vraiment de sens pour ce que tu cherches à faire. Il est parfaitement inutile d'utiliser un fichier ou une variable comme stockage temporaire si tout ce que tu veux faire est traiter du texte et l'afficher (à moins de travailler sur des données énormes).
Si ce que tu veux faire est générer du texte, le trier et l'afficher, tu peux enchaîner les commandes. Tu peux renvoyer la sortie d'une boucle vers une commande.
Un exemple (stupide) :
for i in {1..10} ; do echo $i ; done | shuf
Tu devrais expliquer en détail ce que tu cherches à faire (ce que fait ta commande, pourquoi trier, etc.), on ne peut pas vraiment t'aider si tu ne donnes pas le but de ton script
nesthib
Réponses : 10
La dernière commande remplace simplement les minuscules par des majuscules, c'était un simple exemple pour te montrer quoi faire avec la variable (pour l'afficher ou l'envoyer à une commande).
C'est toi qui parlait de commande non finie (message #4, « puisque je n'ai pas fini de l'utiliser »).
Ubuntu et un shell sont deux choses très différentes, (tu as un shell sous tous les autres unix et même sous windows), mais pas de soucis, tu as le droit d'être débutant
Oui, tu peux renvoyer le contenu de la boucle vers une commande, et même faire des dizaines d'autres choses. Généralement, quand on commence à faire des scripts, on utilises des méthodes compliquées, peu efficaces, tordues… c'est pour ça que tu devrais expliquer le but de ton script. On pourrait sûrement te proposer une méthode efficace, parce que là j'ai le pressentiment que tu fais compliqué pour quelque chose qui pourrait sûrement être simple.
NB. si tu veux savoir ce que fait une commande lance :
commande --helpman commande
#13 Re : -1 » [Résolu] dépendances manquantes essayez d'utiliser l'option -f » Le 04/09/2014, à 14:07
nesthib
Réponses : 5
La commande pacman ne fonctionnera pas sur Ubuntu. Je te conseille de faire attention aux commandes que tu lances, si tu ne fais pas attention tu risques d'endommager ton système et tes données…
L'erreur que tu obtiens avec libc6 est plutôt inquiétante, j'espère que tu n'as pas cassé le gestionnaire de paquets.
Lance la commande suivante et donnes-en le retour complet :
sudo apt-get update
sudo apt-get dist-upgrade
Si jamais tu n'as pas la possibilité de copier/coller facilement, lance la commande :
(sudo apt-get update
sudo apt-get dist-upgrade) >/home/[ton nom d'utilisateur/sortie_apt.txt
puis démarre avec un liveCD/USB pour accéder au fichier sortie_apt.txt dans le home
#14 Re : -1 » Problème commande sed » Le 04/09/2014, à 13:55
nesthib
Réponses : 13
Veux-tu décrypter ou déchiffrer ? Le premier signifie que tu n'as pas la clé pour déchiffrer le message et que tu dois donc la casser, le second signifie que tu as la clé.
Ton système de chiffrement est appelé Chiffre de César. Il s'agit d'une substitution mono-alphabétique, qui ne présente aucune sécurité car il est extrêmement facile à casser par analyse de fréquence des lettres ou par test de toutes les possibilités (26). Il y a d'ailleurs une commande pour casser ce chiffrement :
caesar <<<"Uwua wkl mf ewkksyw kwujwl"
#15 Re : -1 » Compilation de fichier sous Latex » Le 03/09/2014, à 23:27
nesthib
Réponses : 2
Quand tu as un problème avec LaTeX, tu devrais fournir un exemple complet (qui compile, ou donne l'erreur que tu as), pas seulement quelques lignes. Ici on ne sait même pas quelle classe tu utilises (book, memoir ?)
\input ou \include ne changera rien sur la mise en forme du document, ces commandes permettent simplement de diviser ton documents en plusieurs fichiers, \input agissant comme si tu collait le contenu du document lié à l'emplacement de la commande \input, et \include étant un peu plus évolué (ne recompile pas la partie liée si celle ci n'a pas été modifiée). Je te conseille de n'utiliser que \include dans la partie principale du document, et \input dans les sous parties.
En admettant que tu utilises la classe memoir, ou similaire, si tu ne veux pas qu'un chapitre soit numéroté, utilise la version « étoilée » de la commande chapter :
\chapter*{Introduction}
#16 Re : -1 » [RESOLU] Annuler des commandes "copier-coller" » Le 04/09/2014, à 13:44
nesthib
Réponses : 4
Tu peux désinstaller pipelight avec la commande :
sudo apt-get purge pipelight
et supprimer les dépôts avec :
sudo apt-add-repository -r ppa:ehoover/compholio
sudo apt-add-repository -r ppa:mqchael/pipelight
A priori, la présence du dépôt ne change rien à la température de ton ordinateur, c'est sûrement l'utilisation intensive du processeur qui génère la chaleur. Si tu arrêtes de visionner des films avec cette application la température devrait rester normale. Tu peux dépoussiérer délicatement ta machine pour améliorer le refroidissement (en utilisant par exemple une bombe d'air).
Pourquoi as-tu besoin de silverlight pour regarder ton film ?
NB. Attention à ne pas copier coller des commandes trouvées sur le web sans savoir ce qu'elles font, c'est le meilleur moyen de casser son système, en particulier si les commandes comportent le mot-clé « sudo ».
#17 Re : -1 » Script shell » Le 03/09/2014, à 05:17
nesthib
Réponses : 10
Si tu fais un lanceur, il ne sera pas possible de demander le mot de passe. Une solution est de remplacer sudo par gksudo pour que la demande de mot de passe se fasse de façon graphique.
Une autre solution pourrait être de paramétrer sudo pour autoriser le lancement de la commande sans mot de passe.
Enfin, il est possible de faire comme le conseille jplemoine, à savoir paramétrer une tâche cron
#18 Re : -1 » Script shell » Le 03/09/2014, à 16:01
nesthib
Réponses : 10
@jplemoine : autant il n'est pas conseillé d'utiliser sudo pour les commandes graphiques, autant il n'y a pas de soucis pour utiliser gksudo avec une ligne de commande. Les droits root sont nécessaires parce qu'il veut sauvegarder tout le disque (à bas niveau).
@bertyves : d'ailleurs c'est voulu la sauvegarde totale du système de fichiers ? Ou tu fais comme ça parce que tu ne sais pas comment faire autrement ? Tu peux regarder du côté de rsync pour une sauvegarde au niveau des fichiers (et pas du système de fichiers).
#19 Re : -1 » [ Résolu ] Commande CP dans plusieurs dossiers » Le 02/09/2014, à 15:30
nesthib
Réponses : 9
@αjet : et surtout la tienne risque de faire n'importe quoi, tu n'échappes pas la variable $dest, si elle contient des espaces ça ne fera pas le comportement attendu
@Elève linuxien : attention de poster dans les bonnes catégories, tu es HS dans « Trucs, astuces et scripts utiles », je déplace…
#20 Re : -1 » [Résolu] Executer un script local avec ssh » Le 28/08/2014, à 06:09
nesthib
Réponses : 11
Peux-tu expliquer ce que tu cherches à faire (pourquoi vouloir afficher un texte sur un terminal distant ?)
Il est possible d'envoyer du texte ou le retour d'une commande sur un terminal (ou plutôt pseudo-terminal) donné. La première chose est de déterminer l'identifiant du terminal disant avec la commande who.
Tu verras des lignes du genre :
utilisateur pts/0 2014-08-28 00:00 (hôte connecté)
Ici, l'identifiant est pts/0
Tu peux ensuite envoyer du texte arbitraire en faisant :
ssh utilisateur@hôte_distant 'echo "bonjour" >/dev/pts/0'
Tu peux également envoyer des commande (ou le contenu d'un script) et les faire exécuter par n'importe quel programme distant :
echo 'echo $(whoami) a lancé une commande le $(date)' | ssh utilisateur@hôte_distant 'bash >/dev/pts/0'
echo 'print((1+4)/2)' | ssh utilisateur@hôte_distant "python >/dev/pts/0"
cat script.sh | ssh utilisateur@hôte_distant "bash >/dev/pts/0"
Attention, envoyer comme ça du texte arbitraire vers un terminal risque d'interférer avec l'affichage si le terminal est utilisé pour d'autres commandes (tout sera mélangé). Note également que tu ne peux accéder au terminal que si tu as les droits de l'utilisateur qui le possède.
#21 Re : -1 » [Résolu] Executer un script local avec ssh » Le 28/08/2014, à 13:20
nesthib
Réponses : 11
Aucune idée, c'est censé faire quoi ton application ? En tout cas je pense que c'est une mauvaise pratique d'écrire comme ça sur le terminal sans passer par le shell qu'il contient.
En ce qui concerne screen, ça fonctionne bien pour partager une session, mais c'est une autre approche (que je valide, c'est vraiment très pratique !).
#22 Re : -1 » [Résolu] Executer un script local avec ssh » Le 28/08/2014, à 22:45
nesthib
Réponses : 11
Ta BDD elle est accessible par le réseau ? (Quel SGBD utilises-tu ?)
Le plus simple serait peut être de faire un tunnel ssh entre les deux machines… Sinon, selon le type de BDD tu peux aussi monter localement la partie du système de fichier distant qui t'intéresse.
Quoi qu'il en soit, l'exécution de commandes à distance est une chose, mais je ne vois pas l'intérêt de déporter l'affichage sur le terminal distant…
nesthib
Réponses : 17
@melixgaro : ne fais jamais de try/except sans spécifier l'erreur attendue. Dans ton cas tu peux avoir une KeyError, donc spécifie-le, ceci t'évitera des bugs silencieux.
Une petite suggestion, utilise une base de données sqlite :
import sqlite3
# cette partie n'est à exécuter qu'une seule fois pour créer la base de données
elements = [(1, 'Hydrogen', 'H'), (2, 'Helium', 'He'), (3, 'Lithium', 'Li')]
db = sqlite3.connect('/tmp/periodic.db')
c = db2.cursor()
c.execute('CREATE TABLE elements (Id INT, Name TEXT, Symbol TEXT)')
c.executemany('INSERT INTO elements VALUES(?, ?, ?)', elements)
db.commit()
db.close()
# Cette fonction permet de chercher dans la base par nom ou par symbole
def get_elem(text):
db = sqlite3.connect('periodic.db')
with db:
c = db.cursor()
n = c.execute('SELECT Id from elements WHERE (Symbol is ? OR Name is ?)', (text,)*2).fetchone()
return n[0] if n else None
La fonction s'utilise de la façon suivante :
>>> get_elem('H')
1
>>> get_elem('Helium')
2
>>> get_elem('Water')
>>>
La base de données te permettra d'ajouter des informations supplémentaires pour chaque élément (dans la table elements ou dans une table séparée)
|
This post is a summary of some things I learned trying to understand what the logo above means, after I discovered it on the copyright page of Introducing James Joyce (1942). Introducing is a brief selection of Joyce’s works (including selections from Dubliners, Portrait, Ulysses, and Finnegans Wake) selected and introduced (very briefly) by T. S. Eliot.
The Book Production War Econcomy Standard
The British War Economy Standard was established as a way of saving paper during the Second World War and economizing book production. Indeed, even as the war drove up demand for books1, the supply of books was constricted drastically. This reduced supply of books owes to a number of factors (a reduced labor force as individuals enlisted; a shift in printing capacity to military projects, etc.), but chief among them was the rationing of paper.2 In England,
Paper was rationed, beginning in March 1940, when publishers were allowed only 60 percent of what they had used in 1938-39. The proportion fell to 37.5 percent by January 1, 1942, when the Book Production War Economy Agreement took effect. The scheme mandated smaller type, less white space, and inferior papers and bindings. It resulted in some remarkably ugly books, but it conserved raw materials. (Rose 351)
While rationing occurred in the United States, under the direction of the War Production Board, rules for paper use seem to have been comparatively liberal.3 In Britain, by contrast, a more severe shortage led to the Book Production War Economy Agreement—an agreement between the British government and publishers which apportioned paper among publishers (based on their 1938-39 usage4) and spelled out standards for paper conservation. Valerie Holman’s Print for Victory tells the story of books in England during the second World War in detail, and includes extension discussions of the BPWEA. As an appendeix, she includes some of the details of the BPWEA. It is my chief source in this post; its a great work with truly excellent illustrations.
The BPWEA included a variety of measures for reducing, and rationalizing, paper use. For instance, as the war continued, a process evolved for prioritizing certain types of books over others (by affording an additional paper ration for books deemed “essential,” see Holman 83ff). But it also included rules for making the most efficient use of each page: “Publishers decided to focus their attention on the printed page, looking at books not as they were, but as they might be if less white space surrounded the text and the type size was reduced so that more could be printed on less paper” (Holman 72).
Measuring Paper Use
The BPWEA established rules for the maximum weight of paper and boards for binding.The weights both are based on the weight of a ream of quad crown—40"x30"—sheets. Which is not an easy measure to imagine, unless you happen to have a paper factory handy. It also required:
“preliminary matter” must not exceed four pages (introductions, tables of contents, and so on may be regarded as part of the text, not preliminary matter)
Chapter Headings and Breaks “must not be extravagantly displayed and must start not lower on the page than the height of the third line of the text on a full page. There must be no blank page between chapters. In fiction, chapters must be run on with a gap of not more than eight lines…” (qtd. in Holman 271).
For instance, this volume, USSR: Her Life and People, published in 1943 under the BPWAE, shows a chapter break that is decidedly not extravagant:
Additionally a book must meet one of two “typographical standards”:
Type-to-page Ratio and Maximum Type Size: “The percentage of type-area to the page-area (untrimmed) must not be less than 58 per cent” (Holman 268). Additionally, this provision specifices maximum type sizes and leading; thus a book measuring 8.75" by 5.625"—a demy octavo—or larger can have type no larger than 11 point, with 1 point leading. A small book (smaller than crown ocatvo, 7.5" by 5in") must have type set no small than 11 pt, with (!) no leading. (The agreement includes exceptions for Children’s and Educational Books, as well as for books under 64 pages).
Minimum Words per Page: Alternatively, one could meet the typographic standards by demonstrating a minimum number of words per page. The type-area must be a minimum of 55 (rather than 58) percent of the page; but one must also meet a minimum number of words per page based on format (e.g. 478 words per page for a page measuring 8.75" by 5.625"; 375 for a crown octavo volume, etc). It also includes a procedure for estimating words per page.
A book had to meet one of those two typographical standards—meaning, in effect, a publisher could choose to have wider margins but guarantee a certain number of words per page (the second standard), or a publisher could decide to have smaller margins (a larger type-area and type-to-page ratio) and stick with specified contraints for type size and leading.
Additionally, there were other exceptions: for works printed for export; for books printed as part of a pre-existing multivolume set or series, etc.
Did these contraints produce, as Rose suggests, “some remarkably ugly books”? The effects of these requirements were significant enough that one member of the Publisher’s War Emergency Committee worried that the standard was making books unreadable: “We must at all costs study the eyesight of readers,” he wrote in a letter to the Board of Trade at the beginning of 1943, “Already I have received complaints from our own Services and from the American Services that the type used in many of our books is too small” (qtd. in Holman 74).
What does this look like in practice? Here is a page from Introducing James Joyce:
One can feel the difference in the book: it is very thin; the boards are light (it has an unusual degree of bend for a book published in boards, feeling halfway between a hardcover and paperback). It has very little preliminary matter: the book has a blank free endpaper, a half-title page (with blank verso), and a title page (with copyright information and BPWEA statement on the verso) before the main text begins. The paper is indeed thin; if you look closely you can see through the page, to the type on the opposite side of the page.
And what about the typographical standards? The page measures 7 inches by 4.75 inches. According to the BPWEA, it must have a minimum of 332.5 words per page. That calculation is made by multiplying the total area of the page by 10 words per square inch; the BPWEA specifices a slightly different requirement of words/in^2 for other formats. Per the BPWEA, estimatation of the number of words per page for a volume must be based on a count of 10 consecutive lines, taken from 10 random pages. For Introducing Joyce I got an average of 106.5 words per ten lines; 35 lines per page, means an average of 372.75 words per page. This figure is well above the BPWEA requirement; I imagine that the excerpts from Finnegans Wake contribute to surprisingly large number (they have very few paragraph breaks or short lines, and so have consistently full lines).
Introducing Joyce also meets the type-to-page ratio. By my measurement, the type area is 62.5% of the page area.
For comparison, consider this page from Boot and Saddle in Africa, published in 1943 (when the BPWEA was in full swing), but published and printed in the US.
It’s copyright page declares that “This book has been manufactured in this form in compliance with orders of the War Production Board for the conservation of paper and other materials necessary for the prosecution of the War.” Yet, these requirements were far less stringent than their British counterparts. The paper of this volume is heavier (obvious in the image below), and the leading is visibly greater; chapters are started on a new page. By my measurement the type-space takes up only 47% of the page, and so fails the type-to-page requirement. The pages measure 5.5" by 8", placing it in the same category of format as Introducing James Joyce—if published under the BPWEA, it should have 10 words per square inch, or 440 words per page. Using the estimatation formula descried in the BPWEA, however, Boot and Saddle has an average of 277.2 words per page.
Here are the pages side by side, with scale preserved.
The type-area of Introducing is the same size as Boot and Saddle, even though the page itself is much smaller. The type is likewise much smaller.
Computing Paper Use
I was curious whether one could compare the relative amounts of ink per page; a little bit of Python can approximate this. We have images of pages; if we sort the pixels in each vertical column by color, we can compare the total amount of black on one page to another. You could also simply sort the pixels by treating the images as a one dimensional arrays—that is, as just lists of numbers—I found this less helpful because the margins makes it harder to compare the images as a glance.
Here is what the relevant bit of code looks like:
# We use the Python Image Library
from PIL import Image
# Open the image, in PNG format.
image = Image.open('introducing-james-joyce_page90.png')
# Load the pixel data from the image into
# a list we can manipulate.
pixels = list(image.getdata())
# Get the dimensions of the image; Image provides a tuple
(width, height) = image.size
# In order to sort by column, we will extract each column
# of the image separately and then sort it.
# First, loop through each "column" in the image's width.
for column in range(0, width):
# We'll build a list for just this column.
pixelColumn = []
# This loop extracts the color values for a column
# by adding each pixel, for each "row" within the
# current colum to a list.
for pixel in range(0, height):
pixelColumn.append(pixels[x*width+column])
# Now we sort the list we just generated.
# The "sorting" I leave to a built-in Python function.
pixelColumn = sorted(pixelColumn,reverse=True)
# Now our data is sorted, but its in a list, divorced
# from the rest of the image. We need to load it back
# into the image itself; we use the same loop as before
# but moving the now re-ordereddata in the opposite
# direction.
for pixel in range(0, height):
pixels[x*width+column] = pixelColumn[pixel]
# And push that altered data back to the Image object,
# which we can now show() or save().
image.putdata(pixels)
You can see this code, modified to take a command line argument, at github. (You’ll need Python and the Python Image Library installed to run it though.)
Here are the output images for the page of Introducing James Joyce and Boot and Saddle:
One could boil this down further to a single number using some sort of “average” to try to measure how much of a page is occupied by ink. For instance, using a function described on this StackOverflow thread, the page of Introducing James Joyce has a brightness average of 219.938548387, while Boot and Saddle is 225.179950898 Those values, I assume, are out of 255—where 0 is completely black and 255 is completely white.; that greater level of brightness represents the less crowded (or less efficiently used) page. Though the difference in number seems rather slight and certainly doesn’t capture the difference in paper use the way the average words per page statistic does.
This is an an odd, and not entirely successful, way of looking at this data; the (admittedly unpleasant to perform) calculationsThe numbing image of some poor clerk or assistant counting blocks of ten lines all day…) the BPWEA recommends better capture the amount of linguistic information compressed into physical space; though the analyses of the brightness of the images do have the advantage of registering something that the typographical standards of the BPWEA calculations do not: the effect of the print bleeding through the thin paper, visible, for instance, in the middle-gray tones in the sorted Introducing image.
Book Formats and Reading
Of course, looking at these images, one realizes that book format and expectations have changed quite a bit; while Introducing James Joyce, seems cramped on the page, and the paper is clearly too thin, it is still far more recognizable than Boot and Saddle which feels like a brick beside it—its heft and liberal use of whitespace are actually relatively alien to a reader used to the formats of genre novels, Bantam paperbacks, and Norton Critical Editions. The Penguin paperback format (which, in my estimation, Introducing is far closer to than the older format of Boot and Saddle) emerged just prior to the period of these restrictions and so is certainly not a product of the war. One might hazard, however, that the requirements of the BPWEA helped cement certain expectations for our experience of the page. While, as Rose, contends, these standards produced some ugly books, they also may have improved book design overall. Holman notes, “Although books published in the Second World War are more often remembered for their typographical severity than for their visual richness, it was a period in which the need to convey information swiftly and succinctly placed a premium on good design” (112).
And indeed, Brandt suggests a very specific salutary effect of the US’s own (more limited) paper rationing: Brandt’s essay is a sort of ranty screed about how the United States is “culturally” “one of the backward nations of the world” (88), but I’ll take his observations on book formats.
Publishers took as a first step, and a most desirable one, the making of thinner books. During the lush twenties publishers adopted the British practice of bulking books, on the theory that bookstore customers would feel that they were getting more for their money if the bulk were greater. The customer naturally was confused by seeing two books at the same price, one twice the thickness of the other; and, unless he were truly discriminating, he tended to buy the bulkier. The bulked book created a real space problem for libraries as well as for the individual collectors. Under weight restrictions, publishers had to yield to the use of lighter papers, with the result that the buyer who was accumulating a library could afford, on a space basis, to buy more books. (102)
(I wish I knew more about the extent to which “bulky books” were a “British practice,” and what that history is.) Whether or not space was really the premium Brandt suggests, it does seem plausible that the restrictions of the BPWEA (and the milder American I, of course, have said nothing about continental book publishing, or publishing elsewhere in the British colonies, or in Japan, or North Africa, or the Middle East—all of which was, no doubt, affected. It is worth noting that because of the costs under the BPWEA, some British publishers moved their printing to India. regime) did affect our own present expectations for print formats.
Notes
1—“The stress of World War II actually increased demand for books, out of a need for distraction, for understanding the world situation, or for somethign to do during long blackouts. In Halifax, public library loans jumped from 716,000 in 1938 to just over a million in 1945… In February 1940, 62 percent of adults were reading a book, falling to 51 percent in 1941 and 45 percent in 1946-7” (Rose 350-51). I’m not entirely sure what that figure about adults “reading a book” means.
2—In part the paper shortage was a function of the fact that most of the paper used in British printing used esparto grass, imported from North Africa, then under French colonial control.
3—The early years of the war are described by Joseph Brandt as a boom-time for American book publishers. “Publishers have never before enjoyed either such extraordinary prosperity or such extraorindary difficulties in producing books… Book sales had increased in 1943 form 20 to 30 percent over 1942, even though questions of paper rationing and manufacturing were assuming ever more serious proportions” (101). The chief effects Brandt describes are an attempt to save paper by reducing paper weight. “The War Production Board… issued a curtailed order for the book-publishing industry, which in 1944 was increased. Publishers were permitted to use only 75 per cent of the weight of paper they had used in 1942” (101-102). This is a less drastic reduction and one that applies only to paper weight used in the interest of reducing overall; it does not seem to be put an absolute cap on paper usage, nor does Brandt mention any specifically typographical requirements.
4—One rather perverse effect of this accounting is that a publisher who happened to have an especially good year in 1938-39 continued to reap the benefit of that expanded ration throughout the war yers and beyond. One such publisher was Hutchinson, who had a best-seller with Hitler’s Mein Kampf that year (see Holman 12, 252-254).
Works Cited
Brandt, Joseph. “War and the Book Trade.” Book and Libraries in Wartime. Ed. Pierce Butler. Chicago: U of Chicago P. 1945. Print.
Holman, Valerie. Print for Victory: Book Publishing in England, 1939-1945. London: British Library, 2008. Print.
Lambie, Thomas. Boot and Saddle in Africa. Philadelphia: Blakiston Co. 1943. Print.
Rose, Jonathan. “Modernity and Print I: Britain 1890-1970.” A Companion to the History of the Book. Malden, MA: Blackwell, 2007. 341–353. Print.
|
leYB
Re : lexmark x2670
Que dit :
ls -l /usr/local/lexmark/lxk08/bin/printdriver
-rwxr-xr-x 1 root bin 63851 2008-11-06 09:47 /usr/local/lexmark/lxk08/bin/printdriver
Hors ligne
leYB
Re : lexmark x2670
En changeant le groupe c'est toujours pareil?
sudo chgrp root /usr/local/lexmark/lxk08/bin/printdriver
Cela donne:
~$ sudo chgrp root /usr/local/lexmark/lxk08/bin/printdriver
Je vérifie les droits et permissions ensuite:
~$ ls -l /usr/local/lexmark/lxk08/bin/printdriver
-rwxr-xr-x 1 root root 63851 2008-11-06 09:47 /usr/local/lexmark/lxk08/bin/printdriver
J'ai testé la réimpression et c'est toujours impossible comme on peut voir dans /var/log/cups/error_log:
E [29/Jan/2012:11:30:27 +0100] -2600-Series: Directory "/usr/local/lexmark/lxk08/bin" has insecure permissions (040775/uid=0/gid=2).
E [29/Jan/2012:11:30:27 +0100] [Job 6] Unable to start filter "/usr/local/lexmark/lxk08/bin/printdriver" - Success.
E [29/Jan/2012:11:30:27 +0100] [Job 6] Stopping job because the scheduler could not execute a filter.
Dernière modification par leYB (Le 29/01/2012, à 12:39)
Hors ligne
demonipuch
Re : lexmark x2670
Directory "/usr/local/lexmark/lxk08/bin" has insecure permissions (040775/uid=0/gid=2).
Il faudrait peut-être modifier aussi les permissions du dossier :
chmod 755 /usr/local/lexmark/lxk08/bin
voire
chmod -R 755 /usr/local/lexmark/lxk08/bin
pour modifier les permissions du dossier et de son contenu.
Si ca ne marche toujours pas alors je n'ai pas d'autres idées... Contactez le support de Lexmark peut-être
Hors ligne
leYB
Re : lexmark x2670
Directory "/usr/local/lexmark/lxk08/bin" has insecure permissions (040775/uid=0/gid=2).
Il faudrait peut-être modifier aussi les permissions du dossier :
chmod 755 /usr/local/lexmark/lxk08/bin
voire
chmod -R 755 /usr/local/lexmark/lxk08/bin
pour modifier les permissions du dossier et de son contenu.
Si ca ne marche toujours pas alors je n'ai pas d'autres idées... Contactez le support de Lexmark peut-être
Ton aide a permis de résoudre la moitié des problèmes, puisque un nouveau est apparu.
Grâce à toi, je n'ai plus de messages de type "problème de filtre: driver insécurisé" et je t'en remercie!
Mais notre ennemi Lexmark a plus d'un tour dans son sac puisque maintenant que les droits sont valides: j'ai droit à un nouveau message familier lui aussi des "Lexmarkiens" sous 11.10: "The printer cannot communicate with the computer"
Extrait de var/log/cups/error_log: (à scroller pour en voir l'entièreté)
D [29/Jan/2012:15:04:07 +0100] [Job 8] Job restarted by user.
D [29/Jan/2012:15:04:07 +0100] [Job 8] job-sheets=none,none
D [29/Jan/2012:15:04:07 +0100] [Job 8] argv[0]="Lexmark_2600_Series"
D [29/Jan/2012:15:04:07 +0100] [Job 8] argv[1]="8"
D [29/Jan/2012:15:04:07 +0100] [Job 8] argv[2]="yannis"
D [29/Jan/2012:15:04:07 +0100] [Job 8] argv[3]="Page de test"
D [29/Jan/2012:15:04:07 +0100] [Job 8] argv[4]="1"
D [29/Jan/2012:15:04:07 +0100] [Job 8] argv[5]="job-uuid=urn:uuid:4cc0d717-ac13-30ca-72ce-7e3b92dabedd job-originating-host-name=localhost time-at-creation=1327845358 time-at-processing=1327845801 AP_D_InputSlot="
D [29/Jan/2012:15:04:07 +0100] [Job 8] argv[6]="/var/spool/cups/d00008-001"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[0]="CUPS_CACHEDIR=/var/cache/cups"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[1]="CUPS_DATADIR=/usr/share/cups"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[2]="CUPS_DOCROOT=/usr/share/cups/doc-root"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[3]="CUPS_FONTPATH=/usr/share/cups/fonts"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[4]="CUPS_REQUESTROOT=/var/spool/cups"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[5]="CUPS_SERVERBIN=/usr/lib/cups"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[6]="CUPS_SERVERROOT=/etc/cups"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[7]="CUPS_STATEDIR=/var/run/cups"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[8]="HOME=/var/spool/cups/tmp"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[9]="PATH=/usr/lib/cups/filter:/usr/bin:/usr/sbin:/bin:/usr/bin"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[10]="SERVER_ADMIN=root@PCY"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[11]="SOFTWARE=CUPS/1.5.0"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[12]="TMPDIR=/var/spool/cups/tmp"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[13]="USER=root"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[14]="CUPS_SERVER=/var/run/cups/cups.sock"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[15]="CUPS_ENCRYPTION=IfRequested"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[16]="IPP_PORT=631"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[17]="CHARSET=utf-8"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[18]="LANG=fr_FR.UTF-8"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[19]="PPD=/etc/cups/ppd/Lexmark_2600_Series.ppd"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[20]="RIP_MAX_CACHE=128m"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[21]="CONTENT_TYPE=application/vnd.cups-banner"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[22]="DEVICE_URI=usb://Lexmark/2600%20Series?serial=3053730C5917301&interface=1"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[23]="PRINTER_INFO=Lexmark 2600 Series"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[24]="PRINTER_LOCATION="
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[25]="PRINTER=Lexmark_2600_Series"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[26]="PRINTER_STATE_REASONS=none"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[27]="CUPS_FILETYPE=document"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[28]="FINAL_CONTENT_TYPE=printer/Lexmark_2600_Series"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[29]="AUTH_I****"
D [29/Jan/2012:15:04:07 +0100] [Job 8] Started filter /usr/lib/cups/filter/bannertops (PID 11762)
D [29/Jan/2012:15:04:07 +0100] [Job 8] Started filter /usr/lib/cups/filter/pstopdf (PID 11763)
D [29/Jan/2012:15:04:07 +0100] [Job 8] Started filter /usr/lib/cups/filter/pdftopdf (PID 11764)
D [29/Jan/2012:15:04:07 +0100] [Job 8] Started filter /usr/lib/cups/filter/gstoraster (PID 11765)
D [29/Jan/2012:15:04:07 +0100] [Job 8] Started filter /usr/local/lexmark/lxk08/bin/printdriver (PID 11767)
D [29/Jan/2012:15:04:07 +0100] [Job 8] Started backend /usr/lib/cups/backend/usb (PID 11768)
D [29/Jan/2012:15:04:07 +0100] [Job 8] Restarted by "yannis".
D [29/Jan/2012:15:04:07 +0100] [Job 8] pstopdf 5 args: 8 yannis Page de test 1 job-uuid=urn:uuid:4cc0d717-ac13-30ca-72ce-7e3b92dabedd job-originating-host-name=localhost time-at-creation=1327845358 time-at-processing=1327845801 AP_D_InputSlot=
D [29/Jan/2012:15:04:07 +0100] [Job 8] PPD: /etc/cups/ppd/Lexmark_2600_Series.ppd
D [29/Jan/2012:15:04:07 +0100] [Job 8] load_banner(filename="/var/spool/cups/d00008-001")
D [29/Jan/2012:15:04:07 +0100] [Job 8] 1 #CUPS-BANNER
D [29/Jan/2012:15:04:07 +0100] [Job 8] 2 Show printer-name printer-info printer-location printer-make-and-model printer-driver-name printer-driver-version paper-size imageable-area
D [29/Jan/2012:15:04:07 +0100] [Job 8] 3 Header Printer Test Page
D [29/Jan/2012:15:04:07 +0100] [Job 8] 4 Footer Printer Test Page
D [29/Jan/2012:15:04:07 +0100] [Job 8] 5 Notice CUPS 1.5.0.
D [29/Jan/2012:15:04:07 +0100] [Job 8] 6 Image images/cups.png
D [29/Jan/2012:15:04:07 +0100] [Job 8] 7 Image images/color-wheel.png
D [29/Jan/2012:15:04:07 +0100] [Job 8] Page = 595x842; 10,36 to 586,837
D [29/Jan/2012:15:04:07 +0100] [Job 8] print_device
D [29/Jan/2012:15:04:07 +0100] [Job 8] usb_find_busses=7
D [29/Jan/2012:15:04:07 +0100] [Job 8] PNG image: 128x128x8, color_type=6 (RGB+ALPHA)
D [29/Jan/2012:15:04:07 +0100] [Job 8] PNG image: 192x128x8, color_type=2 (RGB)
D [29/Jan/2012:15:04:07 +0100] [Job 8] Resolution:
D [29/Jan/2012:15:04:07 +0100] [Job 8] Page size: A4
D [29/Jan/2012:15:04:07 +0100] [Job 8] Width: 595.20, height: 841.80, absolute margins: 9.60, 36.00, 585.60, 837.00
D [29/Jan/2012:15:04:07 +0100] [Job 8] Relative margins: 9.60, 36.00, 9.60, 4.80
D [29/Jan/2012:15:04:07 +0100] [Job 8] PPD options: -dDEVICEWIDTHPOINTS=595.20 -dDEVICEHEIGHTPOINTS=841.80
D [29/Jan/2012:15:04:07 +0100] [Job 8] PostScript to be injected:
D [29/Jan/2012:15:04:07 +0100] [Job 8] Running cat | /usr/bin/gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dCompatibilityLevel=1.3 -dAutoRotatePages=/None -dAutoFilterColorImages=false -dNOPLATFONTS -dPARANOIDSAFER -dNOINTERPOLATE -sstdout=%stderr -dColorImageFilter=/FlateEncode -dPDFSETTINGS=/printer -dColorConversionStrategy=/LeaveColorUnchanged -dDoNumCopies -dDEVICEWIDTHPOINTS=595.20 -dDEVICEHEIGHTPOINTS=841.80 -sOutputFile=- -c .setpdfwrite -f -
D [29/Jan/2012:15:04:07 +0100] [Job 8] usb_find_devices=13
D [29/Jan/2012:15:04:07 +0100] [Job 8] STATE: +connecting-to-device
D [29/Jan/2012:15:04:07 +0100] [Job 8] STATE: -connecting-to-device
D [29/Jan/2012:15:04:07 +0100] [Job 8] PPD uses qualifier 'Color.Plain.'
D [29/Jan/2012:15:04:07 +0100] [Job 8] Calling FindDeviceById(Lexmark_2600_Series)
D [29/Jan/2012:15:04:07 +0100] [Job 8] Failed to send: org.freedesktop.DBus.Error.AccessDenied:Rejected send message, 1 matched rules; type="method_call", sender=":1.197" (uid=7 pid=11765 comm="Lexmark_2600_Series 8 yannis Page de test 1 job-uu") interface="org.freedesktop.ColorManager" member="FindDeviceById" error name="(unset)" requested_reply="0" destination="org.freedesktop.ColorManager" (uid=102 pid=996 comm="/usr/lib/i386-linux-gnu/colord/colord ")
D [29/Jan/2012:15:04:07 +0100] [Job 8] Failed to get profile filename!
D [29/Jan/2012:15:04:07 +0100] [Job 8] no profiles specified in PPD
D [29/Jan/2012:15:04:07 +0100] [Job 8] Set job-printer-state-message to "no profiles specified in PPD", current level=INFO
D [29/Jan/2012:15:04:07 +0100] [Job 8] Ghostscript command line: /usr/bin/gs -dQUIET -dPARANOIDSAFER -dNOPAUSE -dBATCH -dNOINTERPOLATE -sDEVICE=cups -sstdout=%stderr -sOutputFile=%stdout -sOutputType=2 -r600x600 -dDEVICEWIDTHPOINTS=595 -dDEVICEHEIGHTPOINTS=841 -dcupsMediaType=1 -dcupsBitsPerColor=8 -dcupsColorOrder=0 -dcupsColorSpace=1 -dcupsCompression=8 -dcupsRowStep=1 -scupsPageSizeName=A4 -I/usr/share/cups/fonts -c -f -_
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[0]="CUPS_CACHEDIR=/var/cache/cups"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[1]="CUPS_DATADIR=/usr/share/cups"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[2]="CUPS_DOCROOT=/usr/share/cups/doc-root"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[3]="CUPS_FONTPATH=/usr/share/cups/fonts"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[4]="CUPS_REQUESTROOT=/var/spool/cups"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[5]="CUPS_SERVERBIN=/usr/lib/cups"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[6]="CUPS_SERVERROOT=/etc/cups"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[7]="CUPS_STATEDIR=/var/run/cups"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[8]="HOME=/var/spool/cups/tmp"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[9]="PATH=/usr/lib/cups/filter:/usr/bin:/usr/sbin:/bin:/usr/bin"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[10]="SERVER_ADMIN=root@PCY"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[11]="SOFTWARE=CUPS/1.5.0"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[12]="USER=root"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[13]="CUPS_SERVER=/var/run/cups/cups.sock"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[14]="CUPS_ENCRYPTION=IfRequested"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[15]="IPP_PORT=631"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[16]="CHARSET=utf-8"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[17]="LANG=fr_FR.UTF-8"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[18]="PPD=/etc/cups/ppd/Lexmark_2600_Series.ppd"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[19]="RIP_MAX_CACHE=128m"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[20]="CONTENT_TYPE=application/vnd.cups-banner"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[21]="DEVICE_URI=usb://Lexmark/2600%20Series?serial=3053730C5917301&interface=1"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[22]="PRINTER_INFO=Lexmark 2600 Series"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[23]="PRINTER_LOCATION="
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[24]="PRINTER=Lexmark_2600_Series"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[25]="PRINTER_STATE_REASONS=none"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[26]="CUPS_FILETYPE=document"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[27]="FINAL_CONTENT_TYPE=printer/Lexmark_2600_Series"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[28]="AUTH_INFO_REQUIRED=none"
D [29/Jan/2012:15:04:07 +0100] [Job 8] Start rendering...
D [29/Jan/2012:15:04:07 +0100] [Job 8] Set job-printer-state-message to "Start rendering...", current level=INFO
D [29/Jan/2012:15:04:07 +0100] [Job 8] Processing page 1...
D [29/Jan/2012:15:04:07 +0100] [Job 8] Set job-printer-state-message to "Processing page 1...", current level=INFO
D [29/Jan/2012:15:04:07 +0100] [Job 8] Set job-printer-state-message to "The Printer cannot communicate with the computer.", current level=ERROR
D [29/Jan/2012:15:04:07 +0100] [Job 8] End of messages
D [29/Jan/2012:15:04:07 +0100] [Job 8] printer-state=3(idle)
D [29/Jan/2012:15:04:07 +0100] [Job 8] printer-state-message="The Printer cannot communicate with the computer."
D [29/Jan/2012:15:04:07 +0100] [Job 8] printer-state-reasons=none
J'ai bien vérifié sur CUPS, ma machine est reconnue et connectée, les câbles USB aussi, j'ai rebooté mon PC au cas où et voilà!
Si tu as d'autres pistes à explorer, je suis ton homme.
En attendant, je vais faire un mail salé à Lexmark Corp...
Hors ligne
leYB
Re : lexmark x2670
UP!
Toujours pas de réponse de lexmark depuis une semaine... Et vous, vous avez des idées?
Hors ligne
leYB
Re : lexmark x2670
Voilà, Lexmark a répondu... Voilà ce que j'ai reçu.
On ne peut faire plus clair et concis!
Utilisateurs Ubuntu, si vous voulez une imprimante Lexmark, PASSEZ VOTRE CHEMIN, Y'A RIEN À VOIR!!
"Demande reçue par e-mail le : 29.01.2012
Dossier n° : 1-7XXXXXXXX1
Madame, Monsieur,
Merci d’avoir contacté le support technique de Lexmark concernant votre imprimante Lexmark X2670 ayant le numéro de série 5XXXX01.
Nous tenons à vous informer que nous ne supportons pas le système d’exploitation Linux.
Si vous avez d’autres questions n’hésitez pas à contacter notre support technique par téléphone au :
Tél. : 01.55.17.41.69.
Fax : 01.55.69.57.63.
Du lundi au vendredi : 9h à 18h
Afin de vous répondre dans les meilleurs délais, Lexmark vous prie de ne modifier ni le sujet ni le contenu de l’e-mail original et de toujours répondre à la même adresse e-mail.
Veuillez répondre à cet e-mail en utilisant le bouton de réponse afin de sauvegarder notre correspondance antérieure.
Cordialement,
Sihame DAKHCH
Support Technique Lexmark
Tél : 01.55.17.41.69.
Fax : 01.55.69.57.63.
www.lexmark.fr
[THREAD ID:1-3JLRQW3]
**********Message d'origine**********
Bonjour,
Pour commencer, une précision: je suis sous système d'exploitation UBUNTU 11.10, dérivée de Debian. Ne trouvant pas Ubuntu dans votre liste, je me suis inscrit sous Debian/GNU. Les deux systèmes sont cousins mais pas totalement identiques, je vous prie de bien vouloir me préciser si vos réponses concernent Debian ou Ubuntu spécifiquement, et bien évidemment je souhaite qu'elles fonctionnent sous Ubuntu version 11.10.
Cela fait plusieurs fois que je "bidouille" pour me servir de la X2670 à cause de l'ancienneté du driver (en passant, inaccessible via la version française de votre site), vous serait-il donc possible de le mettre à jour en fonction des conditions actuelles de ce système d'exploitation afin de nous simplifier son utilisation?
Ubuntu est l'un des OS les plus répandus dans le monde quand même!!
Je suis vraiment mécontent de votre politique d'abandon de cet OS.Pourquoi agir de la sorte?
Cette fois-ci encore, je suis bloqué! Malgré mes recherches ainsi que celle de l'aide de la communauté Ubuntu,impossible de pouvoir utiliser l'imprimante et le scanner depuis mon passage à la version 11.10. La version actuelle de CUPS que j'utilise est la 1.5.pour votre information.
Après avoir difficilement résolu un problème de droits utilisateurs du driver qui m'empêchait de la faire fonctionner, je me retrouve maintenant avec un message qui indique que ma machine ne peut communiquer avec mon PC, alors que CUPS la détecte connectée, que le câble USB neuf l'est également et même après un reboot de mon PC.
Je me doute que vous ne mettrez pas à jour le driver dans la seconde, à défaut merci de me fournir des façons de faire fonctionner une X2670 sous Ubuntu 11.10 (imprimante ET scanner) pour que je puisse entraider à mon tour et ENFIN TRAVAILLER SANS PERDRE MON TEMPS.
Cordialement."
J'ai bien fait de commander une HP moi, ne voyant rien venir de la part de Lexmark!
Dernière modification par leYB (Le 10/02/2012, à 23:01)
Hors ligne
z0u
Re : lexmark x2670
hello, me revoilà (à nouveau...), les versions d'ubuntu avancent mais mes difficultés persistent avec cette imprimante... cette fois je suis sous la 12.04 (32bits), à laquelle je compte bien ne plus toucher avant un moment si j'arrive enfin à faire marcher cette Lexmark !!
alors voilà, l'installation du pilote semble vouloir se lancer mais s'interrompt avant de commencer avec un message me disant que la version 1.2 ou ultérieure de CUPS est nécessaire pour l’installation. Or selon ce que j'ai pu voir dans la logithèque, c'est la version cups 1.5.3 qui est déjà présente dans la 12.04. J'ai toujours le driver qui a fonctionné sur des versions plus anciennes, il doit quand même y avoir moyen de le faire ,fonctionner, non ?
La grande question que je me pose est donc : pourquoi ça coince ? et comment expliquer gentiment à mon ordinateur qu'il peut à nouveau (et pour de bon) être ami avec mon imprimante ? peut-on repasser à une version antérieure de CUPS, et si oui comment faut-il s'y prendre ?
Et dire que j'ai fait fonctionner cette imprimante sans problème avec des versions antérieures à la 10.04...
Dernière modification par z0u (Le 19/01/2013, à 11:19)
Hors ligne
z0u
Re : lexmark x2670
juste un petit up, en reprenant ma dernière question : est-t-il possible de repasser à une version antérieure de CUPS, car il semblerait que ce soit de là que vienne le problème ? et si oui comment faut-il s'y prendre ?
merci pour votre aide
Hors ligne
z0u
Re : lexmark x2670
et encore un petit up...
au passage, voici le message d'erreur qui s'affiche au début de l'installation.
The installer has detected the operating system does not meet CUPS minimum version requirements. Please install CUPS version 1.2 or higher and run the installer again.
Hors ligne
navtex
Re : lexmark x2670
Voyager 14.04 sur Dell vostro 1720 2.66GHz × 2 - Ram 4Gio
Voyager- 14.04 sur Asus X56V 2.16GHz × 2 - Ram 3,9 Gio
Xubuntu 14.04 sur Panasonic CF-M34 PIII 0,93Ghz 500Mo
(Keep the wind in your back) mon ébauche blog- http://voiliershy.wordpress.com/
En ligne
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.