text
stringlengths
256
65.5k
doudoulolita Faire une animation sur la création de jeux vidéo libres Dans le topic Création de jeu vidéo libre - Appel à candidatures, j'ai découvert le créateur de jeu de Ultimate Smash Friends, Tshirtman. Voici ce que je lui ai écrit: Je cherche un jeu que notre Espace Public Numérique pourrait proposer aux jeunes sur Linux, voire les inciter à participer au projet de développement. smile Mais j'ai du mal à installer Ultimate smash friends chez moi sur Ubuntu Studio Jaunty... mad Le lien du paquet en .deb sur http://usf.tuxfamily.org/wiki/Download#Requirements ne fonctionne pas. J'ai finalement trouvé le paquet en .deb sur cette page en suivant le lien indiqué au bas de la précédente (ouf !). Mais à l'install avec Gdebi, il m'indique qu'il manque python-support. Pourtant, j'ai vérifié que j'avais python (version 2.6, faut-il la version 2.3 ?) et j'ai installé python-pygame juste avant. python-support est bien installé (j'ai vérifié dans synaptic), alors ? C'est le genre de problème qui n'incitera pas les jeunes à se mettre sous Linux, ça, le moindre effort leur est insupportable, les pauvres chéris... cool La page d'Ultimate-smash-friends destinée aux développeurs fait un peu peur ! Je dois avouer que moi qui aime dessiner (en utilisant Gimp, Inkscape mais je tate aussi de la 3D avec Blender), j'aimerais participer à titre individuel, mais je n'y comprends goutte ! La discussion s'est poursuivie sur Ultimate Smash Friends: un smash bros like en python Comme le sujet semblait intéresser plusieurs personnes, je propose de continuer la conversation sur la façon de mener cette animation ici. Voici où m'avait menée ma réflexion: Animation: programmation Trouver une animation permettant d'aborder les notions de base de la programmation, outre ses composantes graphiques, me paraît intéressant, à terme. cool En tout cas, l'idée reste de travailler sous Linux et en logiciel libre. Donc XNA, on oublie, désolée LittleWhite. wink L'idée d'un saut pourraît être sympa si ce n'est pas trop complexe, mais on pourrait imaginer des animations progressives et variables suivant l'âge, le niveau et le degré de motivation des jeunes. On a seulement 2 gamins qui pourraient comprendre et apprécier l'aspect mathématique de la programmation , tandis que les autres risquent d'être vite découragés. Il faudra plus graphique ou plus simple pour ceux-là (même moi, les fonctions Sinus et Cosinus, j'ai oublié et je n'aimais pas ça quand j'étais jeune! wink) Mais je vois la possibilité d'animation par étapes de plus en plus complexes: 1 - sous Tuxpaint, il y a un des jeux qui permet de réaliser une petite animation en faisant bouger le personnage. 2 - Sous Kturtle, on fait la même chose mais en code pour déplacer la tortue. 3 - Décomposition graphique du saut - Réalisation des images sur Gimp (ou un programme encore plus simple pour les 8-9 ans), Inkscape ou Blender. 4 - Créer un gif animé placé sur un décor (en HTML avec CSS pour le background) 5 - Afficher les images des étapes à l'aide d'une boucle (PHP ?) 6 - Présenter le langage de programmation contenu dans USF et comment ça fonctionne (moteur de jeu et tout ce que je ne connais pas encore...). 7 - Lire et tenter de comprendre une partie de code dans USF correspondant à un saut. Initiation au Python: Il y a peut-être plus simple que le saut, pour démarrer ? Voici les étapes possibles si on veut en arriver là: 1 - Faire glisser le personnage suivant un seul axe. 2 - Puis sur 2 axes (on glisse sur l'axe Y, on saute tout droit sur l'axe Z et on retombe). 3 - Ensuite, on utilise 2 images pour la marche, ou 1 pour le glissement axe Y et 1 autre pour le saut axe Z 4 - Montrer les courbes sinusoïdale d'un vrai saut dans Blender, etc... Je ne sais pas si Kturtle permet d'initier à ces courbes, mais ce serait peut-être plus simple qu'avec Python, non ? Python Je n'ai pas encore mis les mains et la tête dans Python mais je viens de prendre quelques bouquins à la bibliothèque sur le sujet. Je ne connais pour l'instant que des bribes de PHP et me contente d'essais simples (Mod'imprim ou, encore en phase test Multitours). Je n'ai meme pas encore utilisé pour mes essais une base MySQL, je vais me lancer bientôt (je connais un peu vu qu'on va parfois trafiquer directement dans notre base de donnée au boulot, pour quelques corrections). J'espère que j'y arriverai en python, et si moi j'y arrive, tout le monde peut y arriver ! tongue Faire un jeu texte avec des enfants et des ados me semble impossible dans notre EPN, Tshirtman. Les notres sont difficiles à motiver. mad Jouer, jouer, jouer, d'accord de leur côté, mais participer à une vraie animation construite et sur une certaine durée c'est beaucoup plus difficile pour notre public. sad Kturtle J'ai trouvé moi aussi de mon côté des programmes pour enfants permettant d'apprendre ou tout au moins d'aborder la programmation, basés sur le langage Logo. Kturtle a effectivement l'avantage d'être très facile à installer (dispo dans les sources de Kubuntu et d'Ubuntu). J'ai plus de mal avec Xlogo ou Tangara. C'est peut-être un point de départ avant de passer à + compliqué. Mais on m'a dit que Logo était un peu dépassé, dans le genre langage de programmation très accessible. Qu'en pensez-vous ? Problèmes d'installation Je confirme que le paquet .deb que m'a proposé Tshirtman ne veut pas s'installer avec Gdebi sur ma Ubuntu Studio Jaunty. Il y a des dépendances brisées me dit-il. J'essaierai plus tard l'autre solution, mais avec les gamins, faudra bien sûr que ce soit simple à installer, sous Linux comme sous Windows. Notez que chez nous, les gamins n'ont pas forcément Vista quand ils ont leur propre ordi car ils récupèrent souvent de vieux ordis sous XP ou pire encore. On n'en a aucun qui ait installé Linux pour l'instant, il n'y a qu'à notre EPN qu'ils le voient tourner, et le manque de jeux de haute qualité les fait tiquer. C'est justement là l'intérêt de travailler un jeu libre avec eux, en plus de chercher d'autres jeux libres plus perfectionnés peut-etre, mais moins faciles d'accès que USF pour des animations sur la programmation et/ou le design de jeux. En tout cas, ça n'empêche pas de commencer des animations avant que le jeu soit parfait et facile à installer sur toutes les plateformes et versions, puisque nous les animateurs, on peut s'embêter avec une install plus compliquée. On expliquera que pour l'installer chez eux (pour ceux qui ont un ordi), il faudra attendre un peu que les programmeurs bossent encore. Mes collègues ont été mis tout récemment sur le coup, lors d'une réunion et je leur ai envoyé les liens seulement hier, donc c'est encore jeune comme projet. Dernière modification par doudoulolita (Le 24/04/2010, à 17:09) Hors ligne tshirtman Re : Faire une animation sur la création de jeux vidéo libres bump Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres le problème c'est que l'approche de la boucle est fondamentalement fausse, elle n'a pas de sens dans la réalité d'un jeu vidéo, donc il ne faut pas la présenter à mon avis, ni toute autre solution aussi fausse, avoir expliqué le concept de la boucle de jeu permettrait normalement aux enfants d'en trouver une meilleur (ou moins fausse) directement, autant ne pas les embrouiller. Bon, je reprendrai les étapes après avoir lu un peu sur la conception de jeux et la programmation, pour ne pas faire d'erreurs. Mais dans les exemples de Kturtle, j'ai vu un truc qui me semble ressembler: initialiserépète 3 [ avance 100 tournegauche 120] Est-ce que ce n'est pas une sorte de boucle ? Dernière modification par doudoulolita (Le 24/04/2010, à 17:21) Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres Voici le code que j'ai fait lors d'un essai avec Turtle: initialise taillecanevas 300,300 couleurcanevas 125,10,125 lèvecrayon va 150,120 répète 18 { baissecrayon avance 10 lèvecrayon avance 10 tournedroite 20 } attends 1 va 20,20 écris "J'ai fait tourner la tortue" tournedroite 90 avance 200 attends 1 va 60,170 attends 1 répète 18 { baissecrayon avance 10 lèvecrayon avance 10 tournedroite 20 } va 150,250 tournegauche 90 écris "et de 2 !" tournedroite 90 avance 100 attends 1 message "C'est fini !" initialise taillecanevas 300,300 couleurcanevas 125,10,125 centre C'est dommage que l'on ne puisse pas enregistrer sous forme de gif animé et que j'aie du mal à ouvrir le fichier .turtle à partir de l'explorateur. Ce qui est super, c'est que la doc en ligne est en français et très simple à comprendre. Il y a quelques différences en fonction des versions: contrairement à ce quei est écrit sur la doc, je ne peux pas enregistrer comme page html mais comme une image en png. Mais c'est déjà sympa si on pense à supprimer les dernières lignes du code bas du code (depuis message jusqu'à centre) Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres Je viens de commencer à apprendre Python en suivant le début du livre "Initiation à la programmation avec Pyton et C++" de Yves Bailly, éditions Pearson (2008). Sur la capture d'écran ci-dessous, on voit le fichier dans l'explorateur de fichiers, l'éditeur de texte (kate) où on a écrit le programme qu'on a enregistré sous le nom python1.py et la console (toute noire toute triste, pour l'instant ) où on lance l'interpéteur python puis notre fichier python1.py par cette ligne de commande: python python1.py Le résultat s'affiche juste en dessous, dans la console, après avoir appuyé sur la touche "Entrée" du clavier. Finalement, ça commence assez facilement (d'autant que je connais déjà certains principes grâce à PHP). Il n'y a rien à installer sous Ubuntu car Python est inclus. Le résultat peut même être un peu graphique comme on le voit ici, en utilisant tirets et astérisques, entre autres signes. L'important est de bien écrire les lignes de code dans l'éditeur de texte, d'enregistrer puis de lancer la commande python python1.py dans la console + touche entrée pour voir le résultat. ENCODAGE La première ligne indique l'encodage utilisé, ici utf-8 CHAÎNE Au début, j'ai utilisé des chaines, c.à.d des suites de caractères qu'on met entre guillemets ou entre apostrophes: ex: "Bonjour, Tshirtman !" INSTRUCTION print Pour que cette chaîne s'affiche, on utilise l'instruction print print "Bonjour, Tshirtman !" VARIABLES le jeu est la première variable. On la définit par: jeu_1 = "Ultimate Smash Friends" Pour afficher le nom de jeu, je pourrai écrire: print jeu_1 Le résultat sera:Ultimate Smash Friends Si je remplace "Ultimate Smash Friends" par "Kturtle" dans la définition de la variable jeu_1, le résultat sera:Kturtle Les personnages sont les autres variables. On les définit par: perso_1 = "BiX"perso_2 = "Blob" Pour afficher le nom des 2 personnages, je pourrai écrire: print perso_1 print perso_2 Le résultat sera BiXBlob CONCATÉNATION Je peux mettre tout ça à la suite les uns des autres en utilisant le signe + print "les personnages de " + jeu_1 + " sont " + perso_1 + " et " + perso_2 résultat:les personnages de Ultimate Smash Friends sont BiX et Blob SÉPARATEUR EN TIRETS Mon programme python1.py est assez complexe car il définit aussi une fonction permettant de faire des lignes de séparation en astériques et en tirets. Je ne donnerai pas ici tous les détails, trop complexes pour démarrer. Mais voici comment réaliser une ligne composée de tirets uniquement (ou d'astérisques ou tout autre signe); c'est assez simple. Pour compliquer et parvenir à mon résultat (c'est possible, même sans définir de fonction), vous devrez réfléchir un peu ! Le principe, c'est de multiplier le tiret par le nombre de fois qu'on veut voir ce tiret apparaître. Le tiret est en fait une chaine d'1 seul caractère, donc on doit la mettre entre apostrophes au lieu de guillemets. soit: '-' Ensuite, on utilise * pour effectuer la multiplication. Puis on met un chiffre assez grand pour que la ligne de tirets soit assez longue. 80 tirets, c'est pas mal, non ? Le code sera donc: print '-'*80 Si on veut changer ce chiffre de 80 par un autre facilement, le mieux serait de le transformer en variable nommée nb_tirets EXERCICE Définissez la variable nb_tirets qui représentera le nombre de tirets composant la ligne. Imaginez la manière de coder pour faire une ligne de 20 tirets, en changeant juste la valeur de la variable. Puis faites une ligne de 20 astérisques. Puis concaténez (= aditionnez) les deux. Répétez 3 fois (on peut multiplier le code précédent par 3 en le mettant entre parenthèses). Bon codage ! Dernière modification par doudoulolita (Le 25/04/2010, à 13:39) Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres Le code est encore bien compliqué car je ne sais pas encore lister automatiquement mes personnages, mais j'utilise des fonctions définies en haut du code, que j'appelle ensuite au sein du programme. Il y a un petit problème d'encodage des accents quand je regarde ma page de code dans Firefox, mais chez moi, ça fonctionne comme il faut. Tout ça ne bouge pas beaucoup, mais le côté graphique est amené progressivement. Si on veut faire une ligne de tirets en pouvant changer ensuite le nombre, on met ce nombre comme variable: nb_tirets = 80 print '-'*nb_tirets Je rappelle que le tiret doit être mis entre apostrophes puisqu'il s'agit d'une chaine d'un seul caractère. Il suffira de changer le chiffre 80 par un autre pour avoir une ligne plus courte ou plus longue. FONCTION Mais on peut être amené à réutiliser plusieurs fois ce bout de code, en changeant à chaque fois le nombre de tirets, ce qui oblige à redéfinir la variable à chaque fois et à recopier tout ce code, pas évident ! Si on accumule plusieurs instructions pour un même objet et qu'on a besoin plusieurs fois du même bout de code, une fonction sera vraiment très utile. Le programme fera appel à elle chaque fois qu'il en aura besoin puis reviendra dans le cours normal des instructions. On va donc définir une fonction pour ce bout de code dessinant une ligne composée d'un nombre précis de tirets successifs, ce qui permettra de l'appeler ensuite quand on veut: def Tirets(nb_tirets): chaine_tirets = '-'*nb_tirets return chaine_tirets Ne pas oublier les 2 points après la parenthèse donnant l'argument de la fonction (c.à.d nb_tirets) et les tabulations avant chaine_tirets et return. Ce sont ces indentations (faites avec la touche Tab, dans Kate) qui indiquent que l'on est en train de définir la fonction. L'instruction return permet de faire un calcul, par exemple, sans l'afficher tout de suite. Quant on appelle cette fonction Tirets au sein du programme, on note entre parenthèses le nombre de tirets désiré. On doit mettre l'instruction print dans le programme avant le nom de la fonction car l'instruction return, présente dans la fonction, n'affiche rien. Cela donnera 80 tirets puis 30 tirets: print Tirets(80) print Tirets(30) SUGGÉRER UN ROCHER Un rocher est constitué du tiret vertical | (touche 6 + AltGr) au début et à la fin, et d'un nombre variable de tirets (touche 6, sans autre touche). La façon de réaliser un rocher est définie dans la fonction Rocher(nb_tirets). def Rocher(nb_tirets): chaine_tirets = '|' + '-'*nb_tirets + '|' return chaine_tirets Je rappelle de nouveau que le tiret et le tiret vertical doivent être mis entre apostrophes puisqu'il s'agit pour chacun d'une chaine d'un seul caractère. Il faudra bien sûr appeler la fonction Rocher par l'instruction print Rocher(10) ou print Rocher(5) au sein du code en indiquant le nombre de tirets désirés (dans notre exemple: 10 ou 5) comme argument. ESPACER LES ROCHERS Entre les rochers, il y a des espaces successifs appelés par la fonction Vide, avec en argument le nombre d'espaces (touche espace du clavier, tout bêtement). def Vide(nb_espace): chaine_vide = ' '*nb_espace return chaine_vide Cette fonction est même plus simple que pour réaliser un rocher ! Il faut juste penser à mettre un espace entre les apostrophes de la chaine. La 1ère ligne de rochers comprend donc des vides de taille différente et des rochers de taille différente. print Vide (3) + Rocher(5) + Vide(10) + Rocher(10) + 2*(Vide(5) + Rocher(5)) + "\n" On note que la succession d'un vide de 5 espaces et d'un rocher de 5 tirets est appelée 2 fois (en multipliant le contenu de la parenthèse par 2) comme ci-dessous: - Succession d'un vide de 5 espaces et d'un rocher de 5 tirets: print Vide(5) + Rocher(5) - La même chose appelée 2 fois: print 2*(Vide(5) + Rocher(5)) 2ème LIGNE DE ROCHERS Pour la 2ème ligne de rochers, au lieu de changer la taille des vides "à la main", j'ai additionné le chiffre avec un autre au sein de la parenthèse de la fonction Vide, ou soustrait un nombre d'espaces au premier chiffre. - 1er vide de la 1ère ligne, de 3 espaces: print Vide (3) - 1er vide de la 2ème ligne, de 3 espaces supplémentaires, soit 6 espaces: print Vide (3+3) - 2ème vide de la 1ère ligne, de 10 espaces. Note : Pour cet exemple, l'instruction print ne se met que si vous faites l'essai isolé, sinon il faut concaténer avec le symbole + la ligne de code précédente avec celle-ci : print Vide(10) - 2ème vide de la 2ème ligne, de 7 espaces en moins, soit 3 espaces restants: print Vide(10-7) Il semble logique de ne pas changer la taille des rochers. SYMBOLISER LES PERSONNAGES Au-dessus des rochers, on a fait une ligne où chaque personnage est représenté par une lettre, rappelant sa forme dans le jeu. BiX = O Blob = A Stick = I Il y a des vides appelés par la fonction Vide entre les personnages (leur lettre) et un saut de ligne noté "\n" à la fin de la ligne, code que vous avez remarqué seul dans le fichier à d'autres endroits, concaténé en fin de lignes. print Vide(5) + perso_1 + Vide(15) + perso_2 + Vide(8) + perso_3 + "\n" print "\n" Dernière modification par doudoulolita (Le 25/04/2010, à 13:27) Hors ligne psychederic Re : Faire une animation sur la création de jeux vidéo libres Si vous savez programmer , vous pouvez faire des programmes dans lequel, il n'y a plus besoin de programmer. (laissons la programmation à ceux que ca interresse des huluberlus comme nous, qui ne serons jamais la majorité de la population : point) Pourquoi pas : a la fois du mba vers lua, et du devellopement tout graphique ( comme le jeu spore par exemple et le tout avec les avantages du libre , et d'une base de donnée de ressource libre) Par exemple, dans un premier temps utiliser syntensity, ou refaire un "jeu complet" mugen like avec paintown, c'est peut être ce que cherche les gens : et c'est à leur portée. ( je note aussi qu'il manque aussi une partie scenario, que j'essairai de compléter ) http://doc.ubuntu-fr.org/developpement_de_jeux_video Hors ligne tshirtman Re : Faire une animation sur la création de jeux vidéo libres @doudoulolita: eh ben! sacré démarrage heureux de voir que je t'inspire, j'ai un peu survolé tes explications, tu semble prendre les choses dans le bon sens bonne continuation @psychedric: bizarrement les tentatives pourtant souvent réalisées par des programmeurs très compétends, de créations de langages tout graphiques, n'ont rien donné de très utilisable, en effet, exprimer la même chose avec des boutons et des graphiques qu'avec des mots clées et des suites d'ordres, s'avère être contre productif, il est vrai que la majeur partie de la population ne sera jamais développeur, mais ça ne vient pas du langage utilisé, en fait, il semble qu'on puisse aisément déterminer qui sera potentiellement programmeur et qui ne le sera pas, par un simple test, avant même d'avoir enseigné les bases… ça peut paraitre élitiste, mais c'est malheureusement le cas, enfin être formé à la programmation semble être absoluement insuffisant pour s'assurer d'être un vrai développeur… http://www.codinghorror.com/blog/archives/000635.html http://www.codinghorror.com/blog/2007/02/why-cant-programmers-program.html (et dans les deux, une bonne myriade de liens très instructifs) Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres Merci pour les liens que j'irai voir prochainement. Dans mon optique, il ne s'agit pas que tous les jeunes et toutes les personnes à qui nous proposerions une telle animation deviennent de vrais développeurs. Le but du jeu est juste d'aborder, de faire découvrir la programmation pour que les jeunes comprennent de quoi il s'agit, et qu'ils puissent voir si ça leur plaît vraiment (au cas où ils rêvent de créer des jeux vidéos). Il y a aussi la partie graphique, dans un jeu vidéo qui peut être abordée en participant au développement d'un jeu comme Ultimate Smash Friends <- Sorlo Aujourd'hui, j'ai montré Ultimate Smash Friends et mon personnage Sorlo à mon neveu qui vient tout juste d'avoir 11 ans et cela lui a donné envie d'en créer un lui aussi. Mon neveu dessine plutôt bien et à plein d'idées. Il adore utiliser ma tablette graphique et commence à s'habituer à Gimp (il a Photoshop sur Mac, chez lui, mais il n'y fait pas beaucoup d'ordi). Aujourd'hui, il a griffonné quelques croquis très sympas et il ne parvenait plus à s'arrêter tellement ses idées fusaient ! Comme quoi, un gamin motivé peut partir dans des directions très intéressantes et même s'il ne va pas jusqu'au bout dans la mise au propre, ses idées peuvent être reprises par les adultes s'il est d'accord. C'est sans doute plus complexe pour aborder la programmation, mais les petits logiciels comme Kturtle qui permettent de s'y initier sont déjà bien pour les plus jeunes, et quelques essais permettent de voir si on veut s'y coller ou pas quand on est plus âgé. L'idéal serait d'avoir à un moment un vrai développeur qui vienne faire une intervention, mais il doit être en mesure de se mettre à la portée des jeunes, ce qui n'est pas si facile. Ce qui semble évident pour un adulte peut en effet paraître totalement incompréhensible à un enfant. Même en bases informatique, on voit aussi des adultes peiner devant des choses qui nous semblent aller de soi. L'autre jour, une dame d'environ 60 ans me disait que pour elle, le clic droit ne voulait pas dire cliquer avec le bouton droit mais cliquer en allant tout droit ! Elle s'était même disputée avec son fils à ce sujet... Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres Problème pour installer Syntensity sous Ubuntu Jaunty! Je vais chercher d'autres choses, j'ai vu aussi la possibilité de faire de la programmation en python avec Blender. Mais je dois bien sûr trouver quelque chose de simple en vue de mon projet d'animation. Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres Pour MyPaint, on ne peut pas installer le paquet mypaint comme indiqué dans les pré-requis de la doc d'Ubuntu (lien mort et pas trouvé dans les dépots) Une fois l'install' effectuée, il s'ouvre mais me signale une erreur de programmation. Je ferme cette fenêtre, histoire de lui clouer le bec, et j'essaie de dessiner un peu mais la fenêtre d'erreur revient toutes les 10 secondes... Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres En langage python, pour que le joueur puisse entrer une donnée, voici le code à taper dans un simple éditeur de texte : print "Joueur n°1, tapez votre pseudo: ", pseudo1 = raw_input() print "Bienvenue à", pseudo1, "dans Ultimate Smash Friends, vous êtes le joueur n° 1 !" L'instruction print permet l'affichage de la chaîne de caractère de la 1ère ligne. On se rappelle que ces chaines sont mises entre guillemets. raw_input() permettra d'entrer la donnée pseudo1 dans le programme pour l'utiliser par la suite. Nous l'afficherons dans une phrase grâce à la 3ème ligne. Celle-ci insèrera cette donnée pseudo1 entre 2 chaines de caractères (toujours entre guillemets, souvenez-vous !). La virgule derrière la question, dans le code, permet que votre réponse reste sur la même ligne que la question. Idem pour les virgules avant et après pseudo1 Enregistrez sous le nom de progpseudo.py dans un dossier nommé programmes. Remplacez par le nom de votre propre programme et de votre propre dossier s'il est différent, bien sûr Ouvrez la console (Konsole ou Terminal). Placez vous dans le bon dossier grâce à la commande cd suivie du chemin du dossier (change directory = changer de répertoire). Ex: cd /home/laurence/programmes Tapez sur la touche Entrée du clavier pour entrer dans le répertoire demandé. Ecrivez ce code à la suite dans la console pour appeler votre super programme: python progpseudo.py Tapez sur la touche Entrée pour lancer le programme. La console affiche alors la 1ère ligne, à laquelle vous devez répondre. Répondez puis validez avec la touche Entrée. La console affichera ensuite votre réponse à l'intérieur de la phrase appelée par la 3ème ligne de code. Cette image montre à la fois le code écrit dans l'éditeur de texte et le résultat dans la console. N'oubliez pas que je n'ai tapé mon nom qu'une fois dans la console et nulle part dans le code ! Si vous copiez-collez ces 3 lignes de codes en dessous des précédentes et que vous remplacez le chiffre 1 par le chiffre 2, vous pourrez aussi demander son pseudo au joueur n°2 et l'afficher pareillement. Essayez ! Demandez ensuite le prénom des 2 joueurs puis arrangez-vous pour l'afficher dans une phrase du type:Le pseudo de Laurence est Doudoulolita tandis que le surnom de Jean est Patouille. N'hésitez pas à inventer d'autres questions et d'autres phrases pour vous amuser. Dernière modification par doudoulolita (Le 18/05/2010, à 00:40) Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres print "Joueur n°1, combien de points de vie avez-vous ?", nb_points1 = int(raw_input()) print "Joueur n°2, combien de points de vie avez-vous ?", nb_points2 = int(raw_input()) print "Au début du jeu,", pseudo1, "a", nb_points1, "points de vie,", pseudo2, "en a", nb_points2, "." print "Il y a", \ nb_points1 + nb_points2, \ "points de vie en tout." int(raw_input()) permet d'entrer un chiffre que l'on pourra réutiliser dans un calcul, comme ici avec nb_points1 + nb_points2. Notez qu'il y a 2 parenthèses fermantes à la fin, une pour fermer raw_input, une pour fermer int. Mais n'oubliez pas d'ouvrir les parenthèses avant de les fermer ! On note les \ avant et après le calcul, et les espaces pour indenter les 2 dernières lignes (c'est à dire les décaler vers la droite). Ne pas utiliser la touche Tabulation car il me semble que ça pose problème. Le programme suivant se base sur cet exemple mais l'addition (ici: 5+6 = 11) est placée avant le nombre de points de chaque joueur. Il réutilise aussi le code appris précédemment. Cliquez sur l'image de la console pour voir le code utilisé (écrit dans l'éditeur de texte, donc) Bon, dans un jeu, on ne choisit pas soi-même ses points de vie, mais vous pouvez prendre un dé pour décider de votre réponse ! Quant au nombre de joueurs, si vous le choisissez plus élevé que le nombre choisi par le programmeur pour l'instant (ici je n'en ai prévu que 2...), vous n'aurez pas de questions pour les joueurs 3, 4, etc. A vous de coder pour prévoir 4 joueurs, comme dans le vrai jeu d'Ultimate Smash Friends ! Dernière modification par doudoulolita (Le 20/07/2010, à 19:02) Hors ligne arturototo Re : Faire une animation sur la création de jeux vidéo libres aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaj'y voit plus claire maintenant mercie!!!!!! Artur MOUKHAMEDOV (11 ans) Hors ligne arturototo Re : Faire une animation sur la création de jeux vidéo libres je comprend bien mieu Artur MOUKHAMEDOV (11 ans) Hors ligne tshirtman Re : Faire une animation sur la création de jeux vidéo libres lol, t'as le même avatar que Kanor, je t'ai pris pour lui au début, comme il fait aussi du python ^^, mais ça m'étonnait qu'il ait appris un truc juste là . Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres Mon premier atelier sera sur Blender les 19 et 20 juillet de 14 à 16h à l'Espace libre 13.1. Au programme: création d'une petite barque et intégration dans un fond en vue de créer un décor pour le jeu Ultimate Smash Friends. Deuxième atelier sur la programmation python (B.A.BA) les 22 et 23 juillet de 14 à 16h. Un mini-script python pour Blender trouvé sur Internet complétera quelques exercices en mode texte. Dernière modification par doudoulolita (Le 12/07/2010, à 13:47) Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres Voici une idée de ce que je souhaite réaliser avec les participants à mon atelier Blender du 19 et 20 juillet 2010 (pour adultes et jeunes à partir de 15 ans): Les participants réaliseront une barque sur Blender. Elle est modélisée avec des extrusions, le modificateur Miroir et des redimensionnements utilisant le PET (Outil d'Edition Proportionnelle). Il faudra placer lampe et caméra pour voir la barque de profil. On apprend aussi à utiliser le mode points, le mode arêtes et le mode faces, ainsi que l'outil Couteau (K), et à choisir un rendu en png avec un fond transparent (RGBA). Enfin, on ajoute à la barque un matériau marron et une texture bois. Puis, si on a le temps, les participants insèreront l'image rendue en plusieurs exemplaires avec Gimp sur une image de fond (trouvée sur internet). Ils ajouteront le personnage Sorlo pour se donner une idée de la taille que doit avoir la barque. On utilisera donc l'outil de recadrage, les calques et l'outil de redimensionnement. L'image de fond provient de http://commons.wikimedia.org/wiki/File: … rfeurs.jpg Dernière modification par doudoulolita (Le 12/07/2010, à 13:56) Hors ligne tshirtman Re : Faire une animation sur la création de jeux vidéo libres Oula, l'idée est intéressante mais assez perturbante du point de vue perspective ^^. Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres Comme je l'ai marqué sur l'autre topic sur USF, je n'ai pas eu grand monde à mon animation. Sur les 5/6 inscrits, seulement 2 se sont présentés, un jeune de 15 ans gentil mais qui croit que ça lui sera facile de devenir testeur de jeux, et un adulte qui s'intéressait en fait à la retouche photo sur Gimp. Le jeune a quand même commencé un petit iceberg en vue d'en faire un élement de décor pour USF, avec Blender; ma barque ne le motivait pas beaucoup (et pourtant, sur le plan didactique, il y avait plus à apprendre !) Pour une animation de 2x2h, on ne peut de toute façon pas faire un truc très travaillé. Je voulais surtout leur apprendre à modéliser et texturer la barque et j'ai un peu vite fait l'insertion sur le fond, sans trop me prendre la tête dessus, j'avoue ! L'idéal serait en fait de "fabriquer la mer" avec Blender ou en tout cas de mieux placer les barques sous la camera pour avoir une perspective correcte, effectivement (mais comment placer des repères fiables ?). Il faudrait aussi mettre quelques vagues en bas des barques pour les faire flotter en utilisant une copie du calque et un masque de calque. Mais travailler sur un décor "à plat" (et non un truc en hauteur) n'était peut-être la meilleure idée pour un décor de jeu 2D. Le jeune qui a fait l'iceberg pendant l'animation voudra sans doute faire aussi la mer avec Blender ou avec Gimp et là, je dois dire que je n'ai pas encore étudié la question de la profondeur. On se retrouvera aussi avec un problème de perpective. En fait, la question que je me posais avant de concevoir cette animation, c'était de savoir si je choisissais le thème du décor et que je l'imposais à tous (plus facile avec un groupe de personnes au-delà de 4 ou 5) ou si je partais des idées des participants, ce qui implique qu'ils se mettent d'accord et pour moi, de m'adapter à un truc qu'on n'a pas testé avant. Dans l'un comme l'autre cas, j'ai fait une erreur en oubliant un des principes de base du jeu, qui fonctionne en 2D et dont le décor doit se travailler sur l'axe Z de Blender ! J'espère avoir un peu de monde Jeudi et vendredi pour la programmation, mais si besoin, je m'adapterai aux personnes présentes. De toute façon, la préparation de ces ateliers m'a permis d'acquérir des petites bases sur Python et j'ai même fait un essai de Pygame grâce à des tutos sur le web, donc ce n'est pas du temps perdu. Je me suis aussi acheté le bouquin "The blender Gamekit", en anglais. A suivre... Dernière modification par doudoulolita (Le 20/07/2010, à 18:56) Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres Je me suis amusée à faire encore d'autres petits essais en python en mode texte mais je voulais passer au côté graphique. Dans le livre "Initiation à la programmation" d'Yves Bailly, qui m'a servi de base, les exemples sont donnés avec la bibliothèque Qt. J'ai trouvé des tutos intéressants pour python avec Pygame (en anglais) J'ai suivi les 2 premiers tutos, très simples, de pygame-tutorial et un autre pour apprendre à incorporer une image . Mon code n'est pas super mais ça affiche quelque chose ! Je suppose qu'une fonction pour les rectangles serait bien ou même peut-être existe-t-il quelque chose de "tout fait" dans Pygame. Les chiffres entre parenthèses indiquent d'abord la couleur de la ligne en mode RVB, puis les coordonnées des points de début et de fin (en pixels). Pour trouver les codes de couleurs, choisir une couleur dans le sélecteur de couleur de Gimp et noter les chiffres R,V et B indiqués sur la droite du sélecteur de couleur. Ce que le livre d'Yves Bailly m'a fait comprendre, c'est que pour créer un jeu en python, par ex., il faut d'abord exprimer clairement les choses et définir objets et actions du jeu (en français, tout bêtement !). En les exprimant clairement et de manière détaillée, on voit plus rapidement comment travailler et structurer le code qu'on fera par la suite. Un simple mouvement d'un des éléments du décor nécessite de définir les coordonnées de cet objet, de définir ses modalités de déplacement, d'indiquer ce qui provoque ce déplacement (touche de clavier, par ex); le fait qu'il ait une certaine vitesse implique le temps, et donc peut-être un chronomètre, etc! Dernière modification par doudoulolita (Le 20/07/2010, à 19:16) Hors ligne tshirtman Re : Faire une animation sur la création de jeux vidéo libres Ce que le livre d'Yves Bailly m'a fait comprendre, c'est que pour créer un jeu en python, par ex., il faut d'abord exprimer clairement les choses et définir objets et actions du jeu (en français, tout bêtement !). En les exprimant clairement et de manière détaillée, on voit plus rapidement comment travailler et structurer le code qu'on fera par la suite. tout à fait, c'est vrai pour tout type de programmes, et les jeux ne font pas exceptions, mieux on sait ce qu'on veux faire (et ce n'est pas facile) plus on a de chance de le faire correctement! un jeune de 15 ans gentil mais qui croit que ça lui sera facile de devenir testeur de jeux, c'est facile, sauf si tu veux que ce soit un vrai métier… Dernière modification par tshirtman (Le 20/07/2010, à 19:34) Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres Pour un jeune, je pense que les logiciels libres et en particulier les jeux libres leur offrent une chance formidable de s'entraîner et de vérifier leur motivation au cas où ils souhaiteraient faire de leur passion un métier. Tester, développer, c'est quand même plus facile dans ce cadre qu'au sein d'une entreprise très fermée, non ? Le problème de certains ados, c'est qu'ils pensent que pour être testeur, il suffit juste de jouer et que ce sera des jeux qui les passionnent alors qu'un simple tour sur les forums au sujet de ce métier (ou de cette activité, si on préfère) montre le contraire. Mais que les ados rêvent, c'est normal. Après, s'ils veulent vraiment réaliser leur rêve, il leur faudra se confronter à la réalité et prouver leur motivation pour pouvoir vivre de leur passion. Je dis ça alors qu'ado, je rêvais d'être styliste chez Jean-Paul Gaultier, et que je me suis retrouvée quelques années plus tard simple patronnière dans le Sentier (ceux qui connaissent Paris savent dans quelles conditions on y travaille le plus souvent)... Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres J'ai oublié de dire ici que je n'ai pas eu beaucoup plus de monde pour l'atelier programmation. Un adulte qui pensait qu'il s'agissait de faire des bases de données (et dans son cas, un simple tableur comme calc devait lui suffire, à mon avis), le jeune qui était là pour Blender et deux autres plus jeunes encore. Les jeunes ont eu du mal à s'intéresser à Ultimate Smash Friends et à python ! Celui de 15 ans m'a montré RPG maker dont pour ma part je ne raffole pas mais qui a amusé les autres pour créer des décors très facilement. Le côté programmation des persos sur RPGmaker n'est pas si évident que ça en a l'air, j'ai eu ensuite du mal à reproduire ce que m'avait montré le jeune, qui pourtant semblait super simple. Ce que je n'aime pas dans ce programme, c'est le côté "déjà tout fait" que les jeunes, eux, aiment beaucoup. Ce qui est plutôt pratique, c'est la simplicité de création des décors qui peut plaire aux plus jeunes pour les amener ensuite vers plus de programmation avec les personnages. Je ne sais pas si ce type de jeu permettant de créer un jeu existe en logiciel libre et a ce côté facile et convivial qu'aiment les jeunes. Jusqu'ici nos recherches en matière de jeux intéressants sont un peu stériles. J'ai voulu mettre Yo frankie sur les ordis du boulot et ça ne fonctionne pas alors que chez moi ça marche. C'est sans doute nos ordis du boulot qui pèchent quelque part. J'ai en effet Ubuntu Lucid Lynx comme au boulot mais ma config est supérieure. Dernière modification par doudoulolita (Le 19/08/2010, à 07:29) Hors ligne doudoulolita Re : Faire une animation sur la création de jeux vidéo libres Par hasard, tout récemment, j'ai découvert le jeu Plee the bear mais pour contribuer, c'est encore plus difficile car c'est en python C++. Les tutoriels sont par contre très bien documentés et le jeu présente une cohérence intéressante et un mini scénario.:) A titre perso je vais continuer à apprendre python et pygame. Je verrai plus tard si je peux réunir des jeunes adultes et des ados motivés pour un autre atelier. Dernière modification par doudoulolita (Le 19/08/2010, à 07:31) Hors ligne
One Interface To Rule Them All Python library for interacting with many of the popular cloud service providers using a unified API. Supports more than 30 providers such as Supports more than 30 providers such as Latest stable version: 0.15.1 pip install apache-libcloud Or download it from our servers and install it manually. from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver cls = get_driver(Provider.RACKSPACE) driver = cls('username', 'api key', region='iad') sizes = driver.list_sizes() images = driver.list_images() size = [s for s in sizes if s.id == 'performance1-1'][0] image = [i for i in images if 'Ubuntu 12.04' in i.name][0] node = driver.create_node(name='libcloud', size=size, image=image) print(node) For information on what the code does, click or hover over the line. For more compute examples, see documentation. from libcloud.dns.types import Provider, RecordType from libcloud.dns.providers import get_driver cls = get_driver(Provider.ZERIGO) driver = cls('email', 'api key') zones = driver.list_zones() zone = [zone for zone in zones if zone.domain == 'mydomain.com'][0] record = zone.create_record(name='www', type=RecordType.A, data='127.0.0.1') print(record) For information on what the code does, click or hover over the line. For more DNS examples, see documentation. You can also subscribe and stay up to date using our RSS / Atom feed. See more projects and companies using Libcloud.
Suppose we need to write a function that gives the list of all the subsets of a set. The function and the doctest is given below. And we need to complete the whole definition of the function def subsets(s): """Return a list of the subsets of s. >>> subsets({True, False}) [{False, True}, {False}, {True}, set()] >>> counts = {x for x in range(10)} # A set comprehension >>> subs = subsets(counts) >>> len(subs) 1024 >>> counts in subs True >>> len(counts) 10 """ assert type(s) == set, str(s) + ' is not a set.' if not s: return [set()] element = s.pop() rest = subsets(s) s.add(element) It has to not use any built-in function My approach is to add "element" into rest and return them all, but I am not really familiar how to use set, list in Python.
I'm Paul Bissex. I build web applications using open source software, especially Django. Backstory: In the 1990s I did graphic design for newspapers and magazines. Then I wrote technology commentary and reviews for Wired, Salon.com, Chicago Tribune, and lots of little places you've never heard of. Then I taught photographers how to create good websites. I co-wrote a book (see below) along the way. Current story: I am helping turn a giant media corporation into a digital enterprise. Feel free to email me. I'm co-author of "Python Web Development with Django", an excellent guide to my favorite web framework. Published by Addison-Wesley, it is available from Amazon and your favorite technical bookstore as well. At least 230611pieces of comment spam killed since 2008, mostly viaAkismet. There is a classic set of programming exercises called "Ninety-Nine Prolog Problems". Though somewhat tailored to logic programming, they form an interesting set of exercises for other languages. I've seen adaptations of varying completeness for Haskell, Lisp, Perl 6, and Python. I was reminded of this all by a recent blog post by some bloke called Dave who was using the problems as a way to become more familiar with Python. He used Python's unittest module to test his solutions. I actually played with these same problems in Python a while ago (before I had found that collection on the Python wiki), and like Dave I decided to incorporate tests. Instead of unittest, though, I used doctest, so the test cases live in the docstring with the description of the problem. For example: def p31(n): """ P31 (**) Determine whether a given integer number is prime. >>> p31(7) and p31(2) and p31(31) True >>> p31(1) or p31(4) or p31(9) False """ if n < 2: return False for i in range(2, n/2 + 1): if n % i == 0: return False return True (No, not the most efficient algorithm!) I collected all the problems in a single module. At the end is the code that invokes the doctest runner: if __name__ == '__main__': import doctest doctest.testmod() One motivation for this structure was the idea that I could build a version of the module with just the docstrings and pass function bodies as a blank slate for people who wanted to try their hand at the problems. I got through about 40 problems, but it's unlikely I'll have the time to finish them any time soon (life got busy, and they get harder as you go). The source is here for anyone who feels like continuing the project, or using the doctest idea to enhance the version on the Python wiki. Keep me posted if you do! I'm trying to come up with a good excuse. sqrt not a Python built-in? Not enough coffee? Too much coffee? The story of dpaste.com 2.0 7 comments Booktools 2 comments A different kind of URL shortener 4 comments Spammer The story of dpaste.com 2.0 122 days ago Spammer The story of dpaste.com 2.0 123 days ago orzel The story of dpaste.com 2.0 124 days ago Tim The story of dpaste.com 2.0 125 days ago Bulwinkel Understanding tuples vs. lists in Python 402 days ago Copyright 2014 by Paul Bissex and E-Scribe New Media
I have an error in GAE python API with my app. Error is: File "/base/data/home/apps/s~graph-coloring/coloring.362739865286670993/main.py", line 249, in txn Gfile.put() I have dropped the txn function but it still appears. I have changed also app version, deployed several times but GAE is still calling txn function. What can be the problem? I am running the handler in a backend I have tested on dev-server and it works. Note:It seems that each backend has its own copy of the app? So in order to deploy the app you need also to update each backend? it seems that doing this solved my problem. Can someone confirm this? 2012-10-27 15:43:35.901 invalid handle: 11954713935722084435 Traceback (most recent call last): File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1511, in __call__ rv = self.handle_exception(request, response, e) File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1505, in __call__ rv = self.router.dispatch(request, response) File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1253, in default_dispatcher return route.handler_adapter(request, response) File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1077, in __call__ return handler.dispatch() File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 547, in dispatch return self.handle_exception(e, self.app.debug) File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 545, in dispatch return method(*args, **kwargs) File "/base/data/home/apps/s~graph-coloring/coloring.362739865286670993/main.py", line 252, in post db.run_in_transaction(txn,key,alpha) File "/base/python27_runtime/python27_lib/versions/1/google/appengine/api/datastore.py", line 2433, in RunInTransaction return RunInTransactionOptions(None, function, *args, **kwargs) File "/base/python27_runtime/python27_lib/versions/1/google/appengine/api/datastore.py", line 2571, in RunInTransactionOptions ok, result = _DoOneTry(new_connection, function, args, kwargs) File "/base/python27_runtime/python27_lib/versions/1/google/appengine/api/datastore.py", line 2593, in _DoOneTry result = function(*args, **kwargs) File "/base/data/home/apps/s~graph-coloring/coloring.362739865286670993/main.py", line 249, in txn Gfile.put() File "/base/python27_runtime/python27_lib/versions/1/google/appengine/ext/db/__init__.py", line 1074, in put return datastore.Put(self._entity, **kwargs) File "/base/python27_runtime/python27_lib/versions/1/google/appengine/api/datastore.py", line 579, in Put return PutAsync(entities, **kwargs).get_result() File "/base/python27_runtime/python27_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 604, in get_result return self.__get_result_hook(self) File "/base/python27_runtime/python27_lib/versions/1/google/appengine/datastore/datastore_rpc.py", line 1569, in __put_hook self.check_rpc_success(rpc) File "/base/python27_runtime/python27_lib/versions/1/google/appengine/datastore/datastore_rpc.py", line 1224, in check_rpc_success raise _ToDatastoreError(err) BadRequestError: invalid handle: 11954713935722084435
Sublime Text: One Editor to Rule Them All? Sublime Text is a proprietary, cross-platform text editor designed for people who spend huge amounts of time shuffling code around. A programmer's editor, Sublime Text is a third option to the long-standing "Vi or Emacs" conundrum. Going beyond the basics of syntax highlighting and code folding, Sublime offers a litany of innovative and unique features. With version 3.0 just around the corner, I'm taking you on a tour of Sublime's most compelling features and add-on packages. At the time of this writing, Sublime Text version 2 is $70 US, and the upgrade to version 3 (which is currently in beta) will be paid. Version 2 is downloadable as a trial, allowing you to get a feel for the editor for as long as you need before committing to buy. Because the application is available for Linux, Windows and Mac OS X, you do not need to buy a separate license for each platform. $70 US may seem like a lot for a text editor, but if you spend hundreds of hours a month in front of your editor, it's a worthy investment. Most of the content in this article should apply to either Sublime Text 2 or 3. Sublime Text 3 is not available for pre-purchase evaluation, so if you're new to Sublime Text, you'll be stuck with version 2 for now. You can download Sublime Text from http://www.sublimetext.com. Getting Around in Sublime Text Start Sublime Text, and the first thing you're greeted with is a charcoal editor window. A traditional project sidebar is on the left, and on the right, is what Sublime calls the Minimap. The Minimap is a zoomed-out view of the currently open file, which works a bit like a WYSIWYG scroll bar. Open some source code, and the Minimap provides a useful way of navigating large files visually. Figure 1. Sublime Text Editor Window If you have a directory holding a project to work on, choose File→Open Folder to select the project folder, then save the project by using Project→Save Project As. Consistent with the spirit of Sublime Text, you can tweak the properties of the project simply by opening the .sublime-project file directly and editing its contents. Open files in Sublime Text are shown in tabs reminiscent of Chrome. You can reorder and drag them between open Sublime Text windows, again likein Chrome or Firefox. This feature is particularly nice if you have multiple monitors, as it lets you quickly organize a vast workspace. Ifyou want to focus (on writing a Linux Journal article, perhaps), useView→Enter Distraction Free Mode (Shift-F11) to view your file infull screen with all navigation widgets hidden. Part of Sublime Text's appeal is speed, both in terms of application performance and UI design. A wide array of highly customizable keyboard shortcuts make using the mouse optional. My most frequently used hotkey is called Goto Anything and is available from the Goto→Goto Anything menu item (Ctrl-p). Provided you have the relevant language support installed (more on that later), Goto Anything lets you quickly access files, classes, functions and even regular old variables as you type. For example, I'll open up my project's icongrabber.py file by pressing Ctrl-p, and as I type my desired filename, Sublime Text narrows down possible completions. When using Goto Anything, you can prefix your query with @ to find a symbol, # to search within a file or : to jump to a line number. Unfortunately, Sublime Text does not search symbols in unopened files. Figure 2. As you type the name of your file, Sublime Text narrows down possible completions. A close second in useful keyboard shortcuts is the Command Palette. Similar to the Escape/Command prompt in Emacs, Sublime's Command Palette lets you quickly execute commands internal to Sublime Text or provided by an add-on package you've installed. For example, to toggle word wrap, use Tools→Command Palette (Shift-Ctrl-p) and type "wrap". Sublime is smart enough to suggest "Toggle Word Wrap" as a completion. Notice that Sublime Text also shows keyboard shortcuts for commands that have them. To view a full list of default key bindings, click on the Preferences Menu and choose "Key Bindings - Default". This will open up the system-wide key-binding file. To create your own key-binding preferences, choose "Key Binding - User", and use the same syntax as the default file. Editing Kung Fu Now to the heart of what makes Sublime Text such a powerful editor: its unique alchemy of text editing features. Sublime Text's most praised editing feature is multi-selection, which is a little tricky to wrap your head around at first. Most editors let you select only one contiguous span of text; some let you select text as a block. Sublime Text lets you select multiple noncontiguous spans of text and act on them collectively. After you've begun using this feature, its power will become apparent to you, especially in editing code or any file with a formal syntax. Say, for example, that I'm converting the following source code from Python 2 to 3. The first thing I want to do is rename "raw_input" to just "input": your_name = raw_input('Enter your name: ') print 'Hello,', your_name printer_model = raw_input("What kind of printer do you have?: ") print your_name, 'has a', printer_model Using Sublime Text, such a task is easy. I'll select the first occurrence of "raw_input" and press Ctrl-d. Pay close attention, and you'll notice that both occurrences of raw_input are now selected, each with its own blinking cursor. As I begin to type the word "input", both occurrences are replaced. It is true that such a change could have been accomplished easily with search and replace, but I've only scratched the surface with multiple selection. Next, I'll want to replace the two "print" statements with Python3's "print" function, which means making the commands look likeprint(...). Because the text "print" occurs four times in thisdocument, the last technique won't work, so I'll show you another wayto make multiple selections. I'll begin by positioning my cursor on thefirst print statement. Then, I'll hold Ctrl while clicking on the otherprint statement. Figure 3. The editor cursor is blue, and the mouse pointer is red. By holding down Ctrl and clicking, you can create multiple editor cursors. Although I haven't selected any text, I have two blinking cursors. Whatever I type will effect both lines. I'll type (, press end, and type ). Both lines received those keys, and now my file is Python 3-compliant. There are several other ways of selecting multiple spans of text in Sublime Text, and as you experiment with them, you'll get a feel for how to use them. Ultimately, when used productively, Sublime's multiple selection feature replaces most editor macro, find/replace operations and refactoring operations all at once. Imagine, for example, how you could transform a plain-text list into an HTML <ul> list using multiple selection. If you can picture how this is done, you're starting to grok multiple selection. If not, don't fret: this is a new editor feature. A few trips to YouTube and some video demos will help you get the idea. Search and Replace Forget grepping through your codebase when the time comes for aggressive refactoring. Sublime Text offers a powerful recursive search and replace feature. Recursive search and replace eliminates the need for the GNU grep and find commands for many users. Many editors provide recursive search and replace, although I find Sublime Text really gets it right in a way that few other projects do. Click on Find→Find in Files, and a large search bar will appear at the bottom of your editor. Using the toggle buttons on the left, you can toggle regular expression matching, case sensitivity and whole words. Hover over individual icons to see what they do. You also can select a directory to search and optionally specify replacement text. If you expect many results or plan to refer to your search results over time, toggle the "Use Buffer" icon in the search area. When enabled, Sublime Text will open a summary of search results in its own editor buffer. When using a multihead workstation, I find it useful to put search results in one monitor and code in another. Toggling "Show Context" will include a few lines before and after each hit in the results. Figure 4. Sublime Text can open up your search results in its own buffer. Click on any result to jump to its source. Sublime Text uses Perl-style regular expressions implemented using the Boost C++ library. Sublime Text also supports regular expression replacements. Snippets Despite their best efforts to not repeat themselves, programmers often find themselves typing common blocks of text throughout their projects. Examples include standard class file layouts, unit tests and license warnings programmers put at the top of each file. To support this work flow, Sublime Text features "snippets". Suppose I have a standard unit test layout for my Python projects: """ Unit tests for <MODULE> in <PROJECT>. """ import unittest class UnitTest(unittest.TestCase): def setUp(self): """ Called before each test to set up the environment. """ pass def tearDown(self): """ Called after each test to clean up. """ pass def test<METHOD>(self): pass if __name__ == '__main__': unittest.main() I can use Tools→New Snippet. Sublime Text will give me an example snippet file. I'll modify it to read like this: <snippet> <content><![CDATA[ """ Unit tests for ${1:module} in ${1:project}. """ import unittest class UnitTest(unittest.TestCase): def setUp(self): """ Called before each test to set up the environment. """ pass def tearDown(self): """ Called after each test to clean up. """ pass def test${1:method}(self): pass if __name__ == '__main__': unittest.main() ]]></content> <tabTrigger>unittest</tabTrigger> <scope>source.python</scope> </snippet> Notice that I've made a "tabTrigger" tag and a "scope" tag in my snippet file. Using the settings I've given, any time I'm in a Python file and type the word "unittest", I can press Tab, and the snippet will be inserted where the cursor is. To try it out, I'll save the snippet as "unittest.sublime-snippet" in the default directory. Now I can use the snippet to create unit tests quickly. Packages Galore Sublime Text can be scripted using plugins written in Python. These plugins are stored in packages that can be installed locally using a file manager or your favorite shell. Should you feel the urge to scratch an itch no one else has found, you can write packages in Python (more on that later). I like to think that Sublime walks the fine line between an IDE and a text editor. Its speed and initial simplicity make it suitable for editing /etc files as easily as source code. Sublime's true power, however, is found in add-on packages users can write and install to do everything from synchronizing files over SSH to refactoring code. Basic syntax highlighting is included for major languages, but to make use of Python as a programming tool, I find it's best to install some handy packages. Before anything else, you'll most likely want to install something called Package Control, which is a little bit like apt-get for Sublime Text. Package Control is itself a package that manages downloading, installing, updating and removing other packages. Download Package Control from http://wbond.net/sublime_packages/package_control. To install a package, just use the Tools→Command Palette (Shift-Ctrl-P), and type "Package Control". Along with other actions, "Install Package" will be available as a completion. Finding Coding Errors One of the most compelling features an IDE offers over a text editor is real-time error detection. For example, if you type a Java syntax error into Eclipse, the editor realizes your mistake and warns you about it in real time. SublimeLinter provides similar functionality for a variety of languages inside Sublime Text. Install SublimeLinter using the Package Control "Install Package" command described above or by downloading it from https://github.com/SublimeLinter/SublimeLinter. SublimeLinter wraps native language tools, such as cppcheck for C and xmllint for XML, so you'll need the relevant tool installed for your language. Let's try an XML error. Figure 5. Notice that Sublime Text highlights lines with errors, and in the status bar, it describes the error itself. Can you spot the error in Figure 5? Notice in the gutter of the editor, there's a warning icon. You'll see in the status bar, SublimeLint is explaining the problem: I forgot to close the <head> tag. After fixing the problem, pressing Ctrl-Shift-L will force SublimeLint immediately to rescan the file, and the error will go away. For Python Programmers If you're a Python programmer, your first download for Python Develop undoubtedly will be SublimeRope. SublimeRope combines Python's Rope source code analysis and refactoring library with Sublime Text, offering context-specific completion, refactoring, jumping to symbols using Sublime Text's "Goto Anything" feature and more. Install SublimeRope by using the Package Control "Install Package" command. To test out just one of Sublime Rope's features, try this code: #!/usr/bin/env python2.7 def hello(name): print 'Hello, %s' % name hello(raw_input('Enter your name: ')) Move the cursor over the definition of the hello function. To use a SublimeRope command to rename "hello" to "greet", use the Command Palette (Shift-Ctrl-P) and type "rename". You should notice a "Rope Refactoring: Rename" command. After choosing the Rename command, enter "greeting" as the new name of your function, and notice that the name has been replaced in both places. To explore other features of SublimeRope, including organizing imports and showing documentation of Python methods, just use the Command Palette and type "rope" to see the handful of commands SublimeRope provides. In general, this is a quick way to explore commands provided by packages you add to Sublime Text. Synchronizing Code to a Server As a Web developer, I find myself testing and developing code on servers. Although one way to do this would be to make changes locally and rsync them up to the server after each edit, with a large codebase, this is a painfully slow solution. Another option is to use sshfs to mount a remote filesystem locally, but this too has its problems, especially in terms of latency over a typical broadband connection. Enter Sublime SFTP. Although Sublime SFTP is a $16 "shareware" package, like Sublime Text itself, SFTP support is a justified expense for anyone who uses Sublime Text for a living. At the time of this writing, Sublime SFTP is available only for Sublime Text 2. Install Sublime FTP using the same method as other packages. Use Package Control's "Install Package" command and find the package called just "SFTP" in the list. Figure 6. Sublime SFTP uses your ~/.ssh configuration for authentication. To get started, choose File→SFTP/FTP→Setup Server. Sublime Text will open up a file letting you specify a hostname, user name and so on. Sublime SFTP will use your default SSH keys, so if you've already configured logging in to your remote host, this will be easy. Settings for remote servers are stored as files in ~/.config/sublime-text-2/Packages/User/sftp_servers. Each file in this directory represents a remote server, and files can be directly manipulated to update settings. After configuring a server, you can open files remotely by going to File→SFTP/FTP→Browse Server or mapping a local directory to be synchronized remotely by right-clicking on a directory in your project and choosing SFTP/FTP→Map to Remote. In my experience as a developer, Sublime SFTP is a surprisingly reliable and well-made package, well worth its unusually high price. Where to Go from Here Of course, I've just scratched the surface of Sublime Text's capabilities in this article. I've glossed over or left out many great features, and as you use Sublime Text, you'll find a great deal more. If I've whet your appetite to learn more, try reading the Sublime Text Unofficial Documentation at http://docs.sublimetext.info/en/latest. Forums also are active on http://www.sublimetext.com, and many programmers—especially in the Python community—use the editor actively, making its community robust. Enjoy and happy coding. Geolocation Give new life to old phones and tablets with these tips! Lucidchart Linux Systems Administrator Memory Ordering in Modern Microprocessors, Part I Senior Perl Developer Technical Support Rep Source Code Scanners for Better Code Putlocker!! Watch Begin Again Online 2014 Streaming Full Movie Tech Tip: Really Simple HTTP Server with Python
nam1962 [résolu, du coup tuto] Comment nettoyer mauvaise install de langues Comment peut on récupérer un desktop en francais sous 12.04 ou 12.10 ? Je viens d'installer un Airis pour un ami en Xubuntu 12.04 Tout est total ok, mais le desktop est en anglais (tous les fichiers locale indique pourtant fr_Fr ou fr UTF8). Y a t'il une manip permettant de remettre le francais en langue par défaut? (j'ai même tenté une récup système via alternate) Dernière modification par nam1962 (Le 01/03/2013, à 13:46) Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961 Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis. Score : 49 convertis IRL (leur ai pas donné le choix, aussi...). Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com En ligne tiramiseb Re : [résolu, du coup tuto] Comment nettoyer mauvaise install de langues dans "language support" dans les "system settings", est-ce que ça indique que le support du français est bien installé ? si ce n'est pas le cas, il faut l'installer. Hors ligne david96 Re : [résolu, du coup tuto] Comment nettoyer mauvaise install de langues Et faire une mise à jour, ce qui n'est pas toujours le cas lors d'une installe fraîche (attention, ça peut prendre du temps, mais c'est nécessaire) : sudo apt-get update && sudo apt-get upgrade Hors ligne nam1962 Re : [résolu, du coup tuto] Comment nettoyer mauvaise install de langues Merci, tout cela fut fait. au démarrage il indique "french", dans "prise en charge des langues" aussi. J'ai vérifié dans "locale" et dans ~pam : il n'y a que es lignes fr UT8 ... Toutes les applis sont en francais, le menu des application aussi. Par contre les menus contextuels et tous les menus de type synaptics accessoires ou paramètres sont en anglais ! Par ailleurs j'ai un message curieux à propos des langues : bernard@bernard:~$ sudo apt-get install language-pack-gnome-fr language-support-fr [sudo] password for bernard: Lecture des listes de paquets... Fait Construction de l'arbre des dépendances Lecture des informations d'état... Fait Aucune version du paquet language-support-fr 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: Le paquet « language-support-fr » n'a pas de version susceptible d'être installée bernard@bernard:~$ Dernière modification par nam1962 (Le 16/11/2012, à 13:06) Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961 Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis. Score : 49 convertis IRL (leur ai pas donné le choix, aussi...). Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com En ligne nam1962 Re : [résolu, du coup tuto] Comment nettoyer mauvaise install de langues # 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 restricted main multiverse universe #Added by software-properties ## 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 restricted main multiverse universe #Added by software-properties ## 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 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 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 #Added by software-properties deb http://security.ubuntu.com/ubuntu precise-security main restricted deb-src http://security.ubuntu.com/ubuntu precise-security restricted main multiverse universe #Added by software-properties deb http://security.ubuntu.com/ubuntu precise-security universe deb 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 http://fr.archive.ubuntu.com/ubuntu/ precise-proposed restricted main multiverse universe deb-src http://fr.archive.ubuntu.com/ubuntu/ precise-proposed restricted main multiverse universe #Added by software-properties deb-src http://extras.ubuntu.com/ubuntu precise main Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961 Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis. Score : 49 convertis IRL (leur ai pas donné le choix, aussi...). Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com En ligne nam1962 Re : [résolu, du coup tuto] Comment nettoyer mauvaise install de langues LANG="fr_FR.UTF-8" LANGUAGE="fr_FR:fr" LC_NUMERIC="fr_FR.UTF-8" LC_TIME="fr_FR.UTF-8" LC_MONETARY="fr_FR.UTF-8" LC_PAPER="fr_FR.UTF-8" LC_IDENTIFICATION="fr_FR.UTF-8" LC_NAME="fr_FR.UTF-8" LC_ADDRESS="fr_FR.UTF-8" LC_TELEPHONE="fr_FR.UTF-8" LC_MEASUREMENT="fr_FR.UTF-8" Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961 Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis. Score : 49 convertis IRL (leur ai pas donné le choix, aussi...). Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com En ligne david96 Re : [résolu, du coup tuto] Comment nettoyer mauvaise install de langues Étrange, quelle distribution lui as-tu installé (Ubuntu, kubuntu, Xubuntu, etc…) et sous quelle architecture (32 ou 64 bits) ? Dernière modification par david96 (Le 17/11/2012, à 00:12) Hors ligne nam1962 Re : [résolu, du coup tuto] Comment nettoyer mauvaise install de langues Xubuntu 12.04 32 bits. J'ai loupé la première install en cliquant trop vite (s'est faite en anglais) Puis (bêtement) bidouillé dans tous les sens sans noter. Puis refait une "fresh install" mais comme j'avais pas mal amélioré j'ai remis ma source list et ma liste de paquets Puis tenté une réparation via alternate. Voili, voilà (comme c'est l'outil secondaire d'un ami et son initiation à Linux j'ai envie que ce soit propre, mais en même temps pas envie de tout refaire à zéro : tout bien partitionné avec la /home, le swap et le transfert de ses profils mozilla & datas) Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961 Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis. Score : 49 convertis IRL (leur ai pas donné le choix, aussi...). Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com En ligne david96 Re : [résolu, du coup tuto] Comment nettoyer mauvaise install de langues Ok, le seul bogue que j'ai rencontré sur Xubuntu (je l'ai installé pour mes filles) a été le slide show lors de l'install (il a suffit de le supprimer), mais apparement pour toi ça c'est bien passé, tu as seulement gaffé en mettant l'installe en anglais. Tente alors un conseil de la doc : http://doc.ubuntu-fr.org/migration_vers … _interface Hors ligne nam1962 Re : [résolu, du coup tuto] Comment nettoyer mauvaise install de langues Ok, vu ! Je n'aurais pas osé ! Je fais ça (décocher TOUTES les langues) dès que je le revois et te tiens au courant (début de semaine normalement) Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961 Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis. Score : 49 convertis IRL (leur ai pas donné le choix, aussi...). Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com En ligne nam1962 Re : [résolu, du coup tuto] Comment nettoyer mauvaise install de langues Cela n'a pas fonctionné : en supprimant toute langue, Xubuntu s'est mis en anglais (pourtant pas coché). La réinstall a remis le "french" (c'est comme cela que ça apparait) et ses menus système en anglais, mais pas que : Synaptic et Ubuntu tweak sont en anglais, libre offic, mozilla et le bureau sont en francais, sauf les dossiers qui sont en anglais, etc... Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961 Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis. Score : 49 convertis IRL (leur ai pas donné le choix, aussi...). Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com En ligne david96 Re : [résolu, du coup tuto] Comment nettoyer mauvaise install de langues Tu as coché French par défaut, et ça n'a rien fait ‽ Étrange. Hors ligne nam1962 Re : [résolu, du coup tuto] Comment nettoyer mauvaise install de langues Il n'y a que "french" (Sur tous mes autres Xubuntu, ça s'appelle "français", déjà.) Je sèche complètement : ne vois pas ce qui manque, ni comment l'installer.... Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961 Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis. Score : 49 convertis IRL (leur ai pas donné le choix, aussi...). Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com En ligne nam1962 Re : [résolu, du coup tuto] Comment nettoyer mauvaise install de langues up ! Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961 Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis. Score : 49 convertis IRL (leur ai pas donné le choix, aussi...). Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com En ligne david96 Re : [résolu, du coup tuto] Comment nettoyer mauvaise install de langues * Ouvrez Applications→Système→Prise en charge des langues Si à l'ouverture une fenêtre vous informe que le support linguistique n'est pas installé complètement cliquez sur installer. * Puis installez la langue française(French) ; cochez French et choisissez le comme langue par défaut, puis faites Valider. Si vous trouvez une case à moitié cochée (-) la langue française n'est pas installée pour toutes les autres applications, cochez alors à nouveau la case! Je sais je me répète, mais pour savoir si la case ne serait pas à moitié cochée ? Hors ligne nam1962 Re : [résolu, du coup tuto] Comment nettoyer mauvaise install de langues Merci pour la réponse, je regarde (c'est un autre ordi que celui sur lequel je suis là) Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961 Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis. Score : 49 convertis IRL (leur ai pas donné le choix, aussi...). Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com En ligne nam1962 Re : [résolu, du coup tuto] Comment nettoyer mauvaise install de langues Résolu en faisant : gksudo thunar /var/lib/locales/supported.d/ Puis supprimant les trucs non français. Ensuite gksudo gedit /etc/default/locale Où j'ai corrigé pour avoir cela : LANG="fr_FR.UTF-8" LANGUAGE="fr_FR:fr" LC_NUMERIC="fr_FR.UTF-8" LC_TIME="fr_FR.UTF-8" LC_MONETARY="fr_FR.UTF-8" LC_PAPER="fr_FR.UTF-8" LC_IDENTIFICATION="fr_FR.UTF-8" LC_NAME="fr_FR.UTF-8" LC_ADDRESS="fr_FR.UTF-8" LC_TELEPHONE="fr_FR.UTF-8" LC_MEASUREMENT="fr_FR.UTF-8" Bien sûr on peut remplacer thunar par son gestionnaire de fichier à soi et gedit par son éditeur de texte préféré Ensuite : sudo rm -rfv /usr/lib/locale/* Et enfin : sudo locale-gen Puis : sudo gedit /etc/environment Là, il n'y a rien d'écrit. recopier : LANG="fr_FR.UTF-8" Sources de mes infos : https://www.linuxquestions.org/question … bian-3281/ & http://forum.ubuntu-fr.org/viewtopic.php?pid=9236151 Merci à leurs auteurs PS, fonctionne aussi sous 12.10 Dernière modification par nam1962 (Le 06/09/2014, à 16:40) Mon tuto pour optimiser / finaliser une install : http://forum.ubuntu-fr.org/viewtopic.ph … #p15041961 Xubuntu 14.10 sur portable, 14.04 sur fixe, 14.04 chez mes amis. Score : 49 convertis IRL (leur ai pas donné le choix, aussi...). Un jeune site que j'aime bien, qui fait du T-shirt la nouvelle élégance ...bio en plus : http://goudronblanc.com En ligne david96 Re : [résolu, du coup tuto] Comment nettoyer mauvaise install de langues Génial, merci pour le retour Hors ligne
original post I'm running ubuntu 10.04, using the openbox window manager. There recently appeared a black rectangle with dimensions of about 100x200 pixels that's obscuring the contents of the display. wmctrl -l doesn't list anything that could be causing it. It appears on all desktops. It catches mouse focus, but xkill doesn't make it go away. It doesn't show up in the alt-tab cycle. Setting windows to "always on top" in the z-order does not prevent them from being obscured by this rectangle. Full-screen apps and video are also obscured by the rectangle. So far, the only things that I've found are able to display without having this rectangle in the way are other TTY sessions, meaning that hitting CTRL-ALT-F2 will give a console which is not obscured by the rectangle. xlock. It is unaffected by this issue both when showing a screen saver and when asking for a password. How can I get rid of the rectangle without killing my X session or any processes not responsible for it? Is resistance futile? update Thanks to cYrus I've learned to use xprop to get the PID of the window. It's got a pretty limited set of properties: WM_HINTS(WM_HINTS): Client accepts input or input focus: True Initial state is Normal State. window id # of group leader: 0x2000001 _NET_WM_SYNC_REQUEST_COUNTER(CARDINAL) = 34717614 _NET_WM_WINDOW_TYPE(ATOM) = _NET_WM_WINDOW_TYPE_POPUP_MENU _NET_WM_USER_TIME(CARDINAL) = 354386666 _NET_WM_USER_TIME_WINDOW(WINDOW): window id # 0x211bf8d WM_CLIENT_LEADER(WINDOW): window id # 0x2000001 _NET_WM_PID(CARDINAL) = 16593 WM_LOCALE_NAME(STRING) = "en_CA.utf8" WM_CLIENT_MACHINE(STRING) = "XXXXXX" WM_NORMAL_HINTS(WM_SIZE_HINTS): program specified location: 0, 0 program specified minimum size: 274 by 156 program specified maximum size: 274 by 156 window gravity: NorthWest WM_PROTOCOLS(ATOM): protocols WM_DELETE_WINDOW, WM_TAKE_FOCUS, _NET_WM_PING, _NET_WM_SYNC_REQUEST WM_CLASS(STRING) = "google-chrome", "Google-chrome" WM_ICON_NAME(STRING) = "google-chrome" _NET_WM_ICON_NAME(UTF8_STRING) = 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2d, 0x63, 0x68, 0x72, 0x6f, 0x6d, 0x65 WM_NAME(STRING) = "google-chrome" _NET_WM_NAME(UTF8_STRING) = 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2d, 0x63, 0x68, 0x72, 0x6f, 0x6d, 0x65 The PID given is that of my top-level Chrome process (version 6.0.472.53, for those interested). I'm loathe to kill the process since it may cause me to lose track of the 40+ tabs I've currently got open and their assorted histories, so it would be great if there were some way to close or hide this window. Unfortunately, I'm not well-acquainted with X properties and am not sure how to go about doing this. The window type indicates that it's a popup; I guess it didn't finish doing that. This would explain why it doesn't accept the window focus: i.e. although it catches mouse clicks, subsequent presses of alt-space bring up the window menu for another window. I tried converting its type to NORMAL but I get $ xprop -set _NET_WM_WINDOW_TYPE\(ATOM\) _NET_WM_WINDOW_TYPE_NORMAL xprop: error: unsupported conversion for _NET_WM_WINDOW_TYPE(ATOM) How can I manipulate this embryonic window in a way that will cause it to cease to obstruct the display?
There is matplotlib2tikz, which creates a TikZ/pgfplots file that can be \input in your document. I don't know how well it works, having never used matplotlib, but I have used matlab2tikz from the same author, and that works well. Also, I do not know if matplotlib2tikz supports all the different kinds of plots that matplotlib can create – in the Matlab case there are some limitations I believe. Edit:For reference, here is a brief explanation of installation and use. Having downloaded the files from github, navigate to the folder in a command line, and run python setup.py install to install matplotlib2tikz. In your Python script add from matplotlib2tikz import matplotlib2tikz, and add matplotlib2tikz('filename.tex') after your plot, e.g. from numpy import arange from matplotlib2tikz import matplotlib2tikz import matplotlib.pyplot as plt x = arange(0,10,0.5) plt.plot(x,x**2) plt.title("A lovely plot") plt.ylabel("$y=x^2$") matplotlib2tikz('test.tex') You can also specify the width and height of the plot in the Python script, as mentioned in the readme of matplotlib2tikz.
Modern OpenGL with Haskell July 18, 2013: See a newer article on modern OpenGL and Haskell for the current state of affairs of texture loading, geometry specification and loading, and GLSL binding. This is a Haskell implementation of the ideas presented in chapter two of Joe Groff’s excellent tutorial on modern OpenGL. You may copy and paste this post into a .lhs file, or download it. We begin by importing the necessary libraries. > import Graphics.Rendering.OpenGL > import Graphics.UI.GLUT > import Foreign.Storable (sizeOf) > import Control.Concurrent (threadDelay) > import Control.Applicative We use a very small library for loading TGA images… > import TGA … and a handy utility library for loading data into OpenGL. > import Graphics.GLUtil Optimism dictates that any exit is a successful exit. > import System.Exit (exitWith, ExitCode(ExitSuccess)) Application state is shared between the rendering and animation functions with an IORef. > import Data.IORef (IORef, newIORef, readIORef, modifyIORef) We begin our program by defining the data structures used to carry program state between frames. Shader state is a record of compiled shader programs, the uniform parameters to the shader, and an attribute accessed by the shader. > data Shaders = Shaders { vertexShader :: VertexShader > , fragmentShader :: FragmentShader > , program :: Program > , fadeFactorU :: UniformLocation > , texturesU :: [UniformLocation] > , positionA :: AttribLocation } Application state is carried in a record. State, in this case, is made up of some vertex data, some primitive data (e.g. polygons), two textures, shader state, and a scalar we use to fade between the two textures. > data Resources = Resources { vertexBuffer :: BufferObject > , elementBuffer :: BufferObject > , textures :: [TextureObject] > , shaders :: Shaders > , fadeFactor :: GLfloat } The data that we actually want to render starts life as a list of 2D vertices, > vertexBufferData :: [GLfloat] > vertexBufferData = [-1, -1, 1, -1, -1, 1, 1, 1] and a list of indices into that list, > elementBufferData :: [GLuint] > elementBufferData = [0..3] Textures are prepared by loading them from disk, then setting various texture rendering modes. > makeTexture :: FilePath -> IO TextureObject > makeTexture filename = > do (width,height,pixels) <- readTGA filename > texture <- loadTexture $ texInfo width height TexBGR pixels We set texturing parameters to linear filtering for minification and magnification, while disabling mip mapping. Texture wrapping is set to clamp both horizontally and vertically, S and T, respectively. > textureFilter Texture2D $= ((Linear', Nothing), Linear') > textureWrapMode Texture2D S $= (Mirrored, ClampToEdge) > textureWrapMode Texture2D T $= (Mirrored, ClampToEdge) > return texture Now we can load the data we want to render into OpenGL, and track it using our state record. Shaders are prepared by loading and compiling the individual vertex and fragment shaders, then linking them into a program. We then query the program to get addresses for the uniform parameters and attribute that we will use to communicate data to the shader program. > initShaders = do vs <- loadShader "hello-gl.vert" > fs <- loadShader "hello-gl.frag" > p <- linkShaderProgram [vs] [fs] > Shaders vs fs p > <$> get (uniformLocation p "fade_factor") > <*> mapM (get . uniformLocation p) > ["textures[0]", "textures[1]"] > <*> get (attribLocation p "position") Our global state record is prepared by creating the buffer objects for our vertex and index data, loading the image files to be used as textures, compiling the shader program, and initializing the fadeFactor field to zero. > makeResources = Resources > <$> makeBuffer ArrayBuffer vertexBufferData > <*> makeBuffer ElementArrayBuffer elementBufferData > <*> mapM makeTexture ["hello1.tga", "hello2.tga"] > <*> initShaders > <*> pure 0.0 The interesting part of our program is the function that puts things on the screen. One step in rendering is preparing the textures for our shaders. We do this by activating a texture unit, binding a texture object to the active texture unit, then setting the uniform sampler2D value in the fragment shader to refer to the correct texture unit. > setupTexturing :: Resources -> IO () > setupTexturing r = let [t1, t2] = textures r > [tu1, tu2] = texturesU (shaders r) > in do activeTexture $= TextureUnit 0 > textureBinding Texture2D $= Just t1 > uniform tu1 $= Index1 (0::GLint) > activeTexture $= TextureUnit 1 > textureBinding Texture2D $= Just t2 > uniform tu2 $= Index1 (1::GLint) Geometry rendering begins by binding the buffer containing the vertex data and telling OpenGL how this data is formatted. In our case, each vertex has two floating point fields. > setupGeometry :: Resources -> IO () > setupGeometry r = let posn = positionA (shaders r) > stride = fromIntegral $ sizeOf (undefined::GLfloat) * 2 > vad = VertexArrayDescriptor 2 Float stride offset0 > in do bindBuffer ArrayBuffer $= Just (vertexBuffer r) > vertexAttribPointer posn $= (ToFloat, vad) > vertexAttribArray posn $= Enabled Finally, drawing is effected by clearing the screen, setting the fadeFactor uniform parameter of our shader program, then drawing our textured geometry. > draw :: IORef Resources -> IO () > draw r' = do clearColor $= Color4 1 1 1 1 > clear [ColorBuffer] > r <- readIORef r' > currentProgram $= Just (program (shaders r)) > uniform (fadeFactorU (shaders r)) $= Index1 (fadeFactor r) > setupTexturing r > setupGeometry r > bindBuffer ElementArrayBuffer $= Just (elementBuffer r) > drawElements TriangleStrip 4 UnsignedInt offset0 > swapBuffers The only user interaction we support is exiting when the escape key is pressed. > basicKMHandler :: Key -> KeyState -> Modifiers -> Position -> IO () > basicKMHandler (Char '\27') Down _ _ = exitWith ExitSuccess > basicKMHandler _ _ _ _ = return () The animation callback limits itself to run at less than 100Hz, then sets the fade parameter carried in our application state based on elapsed time. > animate :: IORef Resources -> IdleCallback > animate r = do threadDelay 10000 > milliseconds <- fromIntegral <$> get elapsedTime > let fade = sin (milliseconds * 0.001) * 0.5 + 0.5 > modifyIORef r (\x -> x { fadeFactor = fade }) > postRedisplay Nothing Finally, kick GLUT off to open our window and start things going. > main = do initialDisplayMode $= [DoubleBuffered] > initialWindowSize $= Size 500 500 > (progname,_) <- getArgsAndInitialize > createWindow "Chapter 2" > r <- makeResources >>= newIORef > displayCallback $= draw r > idleCallback $= Just (animate r) > keyboardMouseCallback $= Just basicKMHandler > mainLoop
Hi, From 3 days, I am continuously making my efforts to get this thing to do in Python, which I can easily do in PHP. I just want following lines from PHP file (abc.php) to Python (abc.py). <?php $mind = explode(',', $_GET['mind']); $data = ''; if(in_array('good', $mind)) { $data .= file_get_contents('good.txt'); } if(in_array('bad', $mind)) { $data .= file_get_contents('bad.txt'); } echo ($data); ?> Here whenever I run http://localhost/abc.php?mind=good,bad I get the content combined of good.txt and bad.txt. I would be grateful if anyone can get me the converted lines to Python. So that whenever I run, http://localhost:8080/abc?mind=good,bad it perform the same action as we can do in PHP. I just wrote these lines, but it is waste I think. import cgi from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app class PrintAccordingly(webapp.RequestHandler): def get(self): mind = cgi.escape(self.request.get('mind')) splitted = mind.split(',') self.response.out.write(splitted) application = webapp.WSGIApplication([('/abc?', PrintAccordingly)], debug=False) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
rodofr Re : Voyager 12.04 Ah ! mais voyager n'est pas aussi parfaite que ça !!!:lol: Il y a toujours des erreurs et ainsi va le monde. C'est parfois un problème de droits mais je crois que c'est sur la 32 bits. Je l'ai déjà souligné sur le forum et sur astuces sur mon site. Hors ligne Tux35 Re : Voyager 12.04 Hello Et me revoilà, nouvel utilisateur de Voyager, suite à un post sur le site Le Libriste En effet, ma mise à jour de ma 11-10 vers la 12.04 a complètement déconné, il faut dire que j'avais quelques soucis suite à des installs pas forcément faites dans les règles de l'art....Bref J'en ai donc profité pour tester cette version XFCE, et ma foi, j'aime bien, pas de problèmes particulier sinon celui que je vais exposer...mais qui ne tiens pas à la distrib en elle même Du beau boulot donc, chapeau bas Mr RodofR :) Mon problème viens donc d'une invite GRUB Rescueau démarrage, ce qui me force à laisser le CD d'install dans le lecteur et à choisir manuellement l'entrée " Amorcer sur le DD principal" Pas pratique J'ai ce souci sur mon PC depuis l'apparition de Grub2 et ce quelque soit la distrib installée (ubuntu, debian, pinguy...); avant, cela se passait bien.... Et généralement, je finis par le supprimer pour réinstaller Grub Legacy, le premier du nom....:/ Mais bon, ça ne me satisfait pas, ça devrait fonctionner.... un historique de mes soucis http://forum.ubuntu-fr.org/viewtopic.php?id=376253 Mon Fdisk -l1 disque de 1 TO pour Linux et 2 disques de 80 et 120 Go en NTFS et IDE d'origine installé via des adaptateurs pata/sata, 1 par unité Disk /dev/sda: 1000.2 GB, 1000204886016 bytes 255 têtes, 63 secteurs/piste, 121601 cylindres, total 1953525168 secteurs Unités = secteurs de 1 * 512 = 512 octets Taille de secteur (logique / physique) : 512 octets / 512 octets taille d'E/S (minimale / optimale) : 512 octets / 512 octets Identifiant de disque : 0x00094e51 Périphérique Amorce Début Fin Blocs Id Système /dev/sda1 * 2048 1940959231 970478592 83 Linux /dev/sda2 1940961278 1953523711 6281217 5 Étendue /dev/sda5 1940961280 1953523711 6281216 82 partition d'échange Linux / Solaris Disk /dev/sdb: 120.0 GB, 120034123776 bytes 255 têtes, 63 secteurs/piste, 14593 cylindres, total 234441648 secteurs Unités = secteurs de 1 * 512 = 512 octets Taille de secteur (logique / physique) : 512 octets / 512 octets taille d'E/S (minimale / optimale) : 512 octets / 512 octets Identifiant de disque : 0x000215b5 Périphérique Amorce Début Fin Blocs Id Système /dev/sdb1 2048 234440703 117219328 7 HPFS/NTFS/exFAT Disk /dev/sdc: 80.0 GB, 80026361856 bytes 255 têtes, 63 secteurs/piste, 9729 cylindres, total 156301488 secteurs Unités = secteurs de 1 * 512 = 512 octets Taille de secteur (logique / physique) : 512 octets / 512 octets taille d'E/S (minimale / optimale) : 512 octets / 512 octets Identifiant de disque : 0x0009a76c Périphérique Amorce Début Fin Blocs Id Système /dev/sdc1 63 156296384 78148161 7 HPFS/NTFS/exFAT Disque /dev/sdd : 1028 Mo, 1028653056 octets 16 têtes, 18 secteurs/piste, 6976 cylindres, total 2009088 secteurs Unités = secteurs de 1 * 512 = 512 octets Taille de secteur (logique / physique) : 512 octets / 512 octets taille d'E/S (minimale / optimale) : 512 octets / 512 octets Identifiant de disque : 0x00084f6d Périphérique Amorce Début Fin Blocs Id Système /dev/sdd1 2048 2009087 1003520 b W95 FAT32 J'ai bien sur testé la manip qui consiste à reprendre la main à l'invit Grub Rescue, mais lorsque je rentre Grub rescue > insmod /boot/grub/linux.mod Il me réponds toujours no such disk ; Précisons que le fichier est bien présent....:rolleyes: J'ai également testé le logiciel de la distrib pour réparer le démarage, sans succès ; Voici le fichier Bootinfo généré : http://paste.ubuntu.com/979781/ Merci de vos lumières, j'ai quand même l'impression que ça tiens à pas grand chose.....:mad: Olivier Mint 16 - Petra - bureau Cinnamon - Kernel 3.11.0-12-generic AMD Phenom Quad Core 9550 - CG Sapphire Radeon HD 5770 1Go SSD Kingston 120G0 + HDD Samsung SATA 1 TO Hors ligne Tux35 Re : Voyager 12.04 Bon, je me réponds tout seul... Depuis le temps que ça durait, je me suis subitement dit que ça venait peut être d'un paramétrage de ma carte mère ? pourquoi pas.... J'ai donc remis le boot par défaut sur le DD (avant je bootais sur le DVD en premier et le DD en second) et supprimé la gestion RAID qui de toute façon m'alourdissait l'initialisation du BIOS ET, miracle, ça fonctionne Désolé pour ce post, mais bon, des fois, en postant, ça me remotive pour chercher....LOL Je continue donc ma découverte et mon paramétrage de ma Voyager Olivier Mint 16 - Petra - bureau Cinnamon - Kernel 3.11.0-12-generic AMD Phenom Quad Core 9550 - CG Sapphire Radeon HD 5770 1Go SSD Kingston 120G0 + HDD Samsung SATA 1 TO Hors ligne demdream Re : Voyager 12.04 Un grand merci pour Voyager qui ma réconcilié avec le monde Linux. Après avoir testés Gnome 3 et Unity, j'étais retourné vers Windows 7 vu que ces interfaces ne m'avaient pas du tout convaincu.... Voyager est vraiment jolie, légés et stable. Donc merci pour le boulot réalisés Hors ligne olep Re : Voyager 12.04 Bonjour! Je possède un eeepc équipé d'un atom Z520 et d'une carte graphique GMA500 et qui aujourd'hui, souffre avec win7.... Voyager 12.04 peut-elle mieux fonctionner qu'une ubuntu classique sur ce genre de petit netbooks? Parce que Ubuntu et les gma500, dur dur.... même en mode live... Merci d'avance pour vos avis éclairés! Asrock Extreme4 990FX, AthlonX4-640, CG RADEON HD 6570 Ubuntu64 14.04 depuis le 17/05/2013 à 16h30 environ.... Hors ligne Major Grubert Re : Voyager 12.04 Salut olep. Voyager devrait être plus léger qu'Ubuntu en principe. Cependant sur mon EeePC (atom n450, CG ?, 2Go de mémoire vive), qui était avant sous Voyager, j'ai essayé de mettre Gnome Shell en plus de Voyager et comme ça tournait relativement bien (un peu moins réactif tout de même), j'ai formaté et mis Ubuntu + GS et, à vrai dire, je ne vois pas de différence. Pour être honnête, Ubuntu + GS est même plus réactif que Voyager ! Ça vient peut-être du fait que j'avais mis Voyager 64b et que j'ai mis Ubuntu 32b. En tout cas, avec juste les tâches de fond (dont dropbox, à jour) et le moniteur système, je suis à 10/20% de CPU et 253 Mo de mémoire vive. Donc, chez moi, Ubuntu tourne sur mon EeePC. Maintenant tu peux choisir Voyager qui doit pouvoir descendre plus bas qu'Ubuntu en bidouillant un peu. Pour en savoir plus sur Gnome Shell. . Lenovo Yoga 13 : Windows 8.1 / Ubuntu Gnome 14.04 . Asus x7010 : Ubuntu 14.04 (Gnome Shell) . Asus Eeepc : Xubuntu 14.04 (32b) Hors ligne pascal5 Re : Voyager 12.04 Bonjour, Cela fait une semaine que j'utilise Voyager 64 bits sur mon portable. Depuis 2007, j'utilise Ubuntu en double amorçage avec Windows 7, mais pour des raisons de principes j'ai pris la décision de ne conserver qu'un système libre. Alors me voilà maintenant sur Voyager, que j'aime beaucoup et que je préfère à la version standard tout en étant plus accessible que Debian xfce. Voici les remarques que je peux faire jusqu'à maintenant. 1. Pilote de carte graphique et branchement dans un écran externe en hdmi D'abord, je voulais branché mon moniteur lcd en hdmi dans mon portable et n'utiliser que cet écran que j'ai acquis récemment. J'ai commencé par utiliser les pilotes libres pour la carte graphique nvidia, mais les films en hd ne sont pas fluides, les vidéos sont saccadées. Alors, j'ai installé le pilote propriétaire, mais ça n'a pas été très intuitif pour paramétrer l'écran en hdmi dans nvidia settings. Un problème qui se pose sous xfce (je ne sais pas pour les autres), c'est qu'on doit sauvegarder la configuration dans xorg, et si par exemple on est quelqu'un de mobile et qu'on veut simplement se brancher à un autre écran, il faut tout reconfigurer. Contrairement à Windows, le bouton de mon portable pour basculer d'un écran à l'autre ne fonctionne pas. 2. Clavier externe J'utilise un clavier externe pour mon portable, c'est le k800 de Logitech. Les raccourcis clavier ne sont pas reconnus par défaut. Cependant, j'ai trouvé assez simple de les paramétrer dans la configuration du clavier. La seule chose que je n'ai pas réussi à faire c'est de configurer la touche qui permet d'activer la mise en veille. Si quelqu'un a la solution, ce serait apprécié. L'autre chose c'est que parfois lorsque je redémarre mon ordinateur, la connexion sans fil du clavier et de la souris n'est pas reconnue. Je dois débrancher et rebrancher le module usb. 3. Configuration du vpn J'ai eu de la difficulté à configurer ma connexion vpn avec gnome network manager. Une fois que j'avais importé le fichier de configuration la connexion fonctionnait pour le temps de la session, mais dès que je redémarrais l'ordinateur, la connexion échouait et je ne pouvais pas faire de modification dans les paramètres de la connexion. J'ai finalement trouvé la solution: lorsqu'on importe le fichier de configuration, par défaut la connexion est configurer pour être valable pour tous les utilisateurs; une fois décoché cette option, tout est rentré dans l'ordre. Mais je ne comprend toujours pas pourquoi cela posait problème. 4. Conky C'est vraiment un plus de Voyager de pouvoir avoir les conky: j'ai souvent voulu les utiliser par le passé mais je n'avais pas le temps de m'en occuper. Avec Voyager tout est assez simple. Cependant, j'ai remarqué que pour certains conky, la surveillance de certains paramètres de l'ordinateur de fonctionne pas, en particulier l'espace disque disponible et la connexion internet. Celui que j'utilise maintenant et qui fonctionne parfaitement, c'est le conky #19 (Conkycore). 5. Minitube Hier, j'ai testé Minitube. Je trouve que l'idée de ce logiciel est bonne mais ne semble pas au point. Certaines vidéos fonctionnent et d'autres non. De plus, lorsque l'on clique sur l'option d'afficher les dix vidéos suivantes, rien n'apparaît. 6. Démarrage du bureau après le login Le plus gros problème que j'ai actuellement, c'est que une fois que j'ai entré mon mot de passe à l'écran de login après avoir démarrer l'ordinateur, celui-ci reste en suspend pendant environ 40 secondes. J'aimerais savoir qu'est-ce qui fait bloquer l'ordinateur pour pouvoir commencer à trouver une solution. Quelqu'un pourrait-il me dire s'il y a un mode "verbose" et comment l'activer? Ou mieux encore, quelqu'un sait-il déjà où se trouve le problème? C'est quelques remarques ne changent pas que je trouve l'expérience utilisateur de Voyager globalement positive. Hors ligne olep Re : Voyager 12.04 Salut olep. Voyager devrait être plus léger qu'Ubuntu en principe. Cependant sur mon EeePC (atom n450, CG ?, 2Go de mémoire vive), qui était avant sous Voyager, j'ai essayé de mettre Gnome Shell en plus de Voyager et comme ça tournait relativement bien (un peu moins réactif tout de même), j'ai formaté et mis Ubuntu + GS et, à vrai dire, je ne vois pas de différence. Pour être honnête, Ubuntu + GS est même plus réactif que Voyager ! Ça vient peut-être du fait que j'avais mis Voyager 64b et que j'ai mis Ubuntu 32b. En tout cas, avec juste les tâches de fond (dont dropbox, à jour) et le moniteur système, je suis à 10/20% de CPU et 253 Mo de mémoire vive. Donc, chez moi, Ubuntu tourne sur mon EeePC. Maintenant tu peux choisir Voyager qui doit pouvoir descendre plus bas qu'Ubuntu en bidouillant un peu. Merci pour ces infos! Asrock Extreme4 990FX, AthlonX4-640, CG RADEON HD 6570 Ubuntu64 14.04 depuis le 17/05/2013 à 16h30 environ.... Hors ligne rodofr Re : Voyager 12.04 pascal5@4. Conky vas dans la home cachée à .conky et prend les conkys que tu veux, ouvre le fichier avec leafpad et à own_window_type desktop A la place de desktop testes 'normal' ou 'override' voir aussi "Conky 6. Démarrage du bureau après le login Effaces tes anciennes sessionsclic droit/réparation aide/Suppression Old sessions redémarres la session et voit si cela s'améliore Hors ligne rodofr Re : Voyager 12.04 Nettoyeur du Kernel / super script Le parent pauvre de BleachBit. D'où la nécessité d'installer ce nettoyeur de kernel surtout qu'après la mise à jour de la 12.04, se trouve un second kernel inutile et qui prend de l'espace. Une fois télécharger Kclean.deb cliquer droit dessus et sélectionner ouvrir avec l'installeur Gdebi Une fois le script installé via le .deb, son icône se trouve normalement dans Système/Administration et rechercher kclean Hors ligne pascal5 Re : Voyager 12.04 Merci de m'avoir répondu rodofr. J'ai remplacé Minitube par Gmediafinder et c'est beaucoup mieux. Merci! En ce qui concerne le démarrage de la session, j'ai fait comme tu m'as dit deux fois mais ça ne s'améliore pas. Je ne sais pas si ça peut aider, mais j'ai remarqué que quand je démarre l'ordinateur en mode dépannage, je n'ai pas de problème. Hors ligne pascal5 Re : Voyager 12.04 Pour ceux que ça pourrait intéresser, dans le message #133 je parlais du fait que le raccourci clavier pour mettre l'ordinateur en veille ne fonctionnait pas et j'essayais de trouver la commande pour le configurer dans les paramètres du clavier. En fait, je me suis creusé la tête pour rien, puisqu'il fallait simplement activer l'option correspondante dans le gestionnaire d'énergie, qui est bizarrement désactivée par défaut... Hors ligne irma_ubuntu Re : Voyager 12.04 bonjour je continue de tester voyager dans virtualbox et toujours content de ce ce que je vois juste une question mais peut-être que çà c'est déjà vu : je fais des essais en chargeant des logiciels çà me les installe au bon endroit dans les menus mais les menus ne sont pas du tout rangés par ordre alphabétique ... et çà devient vite la zone pour retrouver une application comment on remédie à cela ? merci Hors ligne popololo Re : Voyager 12.04 bonjour je continue de tester voyager dans virtualbox et toujours content de ce ce que je vois juste une question mais peut-être que çà c'est déjà vu : je fais des essais en chargeant des logiciels çà me les installe au bon endroit dans les menus mais les menus ne sont pas du tout rangés par ordre alphabétique ... et çà devient vite la zone pour retrouver une application comment on remédie à cela ? merci clic droit sur le menu propriétés puis éditer le menu. Hors ligne popololo Re : Voyager 12.04 Kcleaner : Il me semble qu'il est important de garder deux noyau en cas de problème c'est plutôt pratique... Hors ligne rodofr Re : Voyager 12.04 Installer XFCE 4.10 pour Voyager 12.04 Les développeurs de XFCE viennent de sortir un PPA de XFce 4.10 pour Xubuntu 12.04 Precise Je viens de le faire et aucun problème pour Voyager 12.04. J'espère pour vous aussi. Lien ici Alias add ppa:xubuntu-dev/xfce-4.10 update upgrade Réglage voyager 12.04 après mise à jour. La barre AWN annule des icônes. Donc, quitter la barre AWN, clic droit sur la barre et quitter et redémarrer la barre à Menu/Accessoires/Avant Window Navigation Si les applets du panel du haut sont tous à gauche faites : clic droit sur le panel du haut aller à Tableau de bord/préférence du tableau de bord/Greffons/ cliquer sur séparateur (croix rouge) éditer le greffon sélectionner (à droite l’icône tableau) sélectionner Étendre. Voilà et à bientôt Hors ligne leouaf Re : Voyager 12.04 Major Grubert a écrit : Salut olep. Voyager devrait être plus léger qu'Ubuntu en principe. Cependant sur mon EeePC (atom n450, CG ?, 2Go de mémoire vive), qui était avant sous Voyager, j'ai essayé de mettre Gnome Shell en plus de Voyager et comme ça tournait relativement bien (un peu moins réactif tout de même), j'ai formaté et mis Ubuntu + GS et, à vrai dire, je ne vois pas de différence. Pour être honnête, Ubuntu + GS est même plus réactif que Voyager ! Ça vient peut-être du fait que j'avais mis Voyager 64b et que j'ai mis Ubuntu 32b. En tout cas, avec juste les tâches de fond (dont dropbox, à jour) et le moniteur système, je suis à 10/20% de CPU et 253 Mo de mémoire vive. Donc, chez moi, Ubuntu tourne sur mon EeePC. Maintenant tu peux choisir Voyager qui doit pouvoir descendre plus bas qu'Ubuntu en bidouillant un peu. Sans bidouiller et apres mise a jour du noyau 64 Bits (et nettoyage) 315 Mo de Ram utilise sur 2 Go (Ubuntu Gnome Shell 32 Bits 524 Mo), dur de faire mieux avec avec une une interface UserFriendly. Chapeau bas Mister Rodofr. Comme je l'ai dis dans mes posts précédents, bien que je sois peu actif sur le Forum, j'installe Voyager en Dur depuis le début, et je n'ai rien a redire. Fi le terminal et synaptique, tout est la. De la station radio au controle parental. Quoi demandé de plus, Mamie est contente, et la Blonde aussi. Ami rétracteur, a vous de jouer, il me tarde de vous testez. Dernière modification par leouaf (Le 12/05/2012, à 00:17) PC: Double Boot: Chakra - Voyager Debian Unstable Laptop: Manjaro XFCE Hors ligne popololo Re : Voyager 12.04 Install de Xfce 4.10 via le ppa. Léger problème de thème (axiomd). Bordel dans le menu paramètres que je ne peux éditer, de plus il affiche des programmes dans le menu édition qui n'apparaisse pas dans le menu. Verrais comment régler ça demain. Le reste fonctionne bien. J'apprécie de plus en plus Xfce et cette voyager. Hors ligne Hors ligne enebre Re : Voyager 12.04 à fraide Ne sachant pas si tu as réglé le problème pour ton affichage LCD, j'ai trouvé un article dans la doc d' xfce qui pourrait résoudre la situation, je n'ai pas essayé. LCD Hinting On some systems LCD hinting results in better fonts. But because this is not working on all system, this setting is not configurable through the interface. You can set it with a simple query. xfconf-query -c xsettings -p /Xft/Lcdfilter -n -t string -s lcddefault Other possible values are lcdnone, lcddefault, lcdlight and lcdlegacy. You can check if the property is set property, run xrdb -query in a terminal. To fully apply the LCD hinting, it is advised to logout and in again (for restarting the X server). Si tu décide d'essayer cette solution, fais nous part de tes découvertes, merci. Dernière modification par enebre (Le 14/05/2012, à 10:21) Hors ligne popololo Re : Voyager 12.04 Install de Xfce 4.10 via le ppa. Léger problème de thème (axiomd). Bordel dans le menu paramètres que je ne peux éditer, de plus il affiche des programmes dans le menu édition qui n'apparaisse pas dans le menu. Verrais comment régler ça demain. Le reste fonctionne bien. J'apprécie de plus en plus Xfce et cette voyager. Je me réponds donc la solution est : The Uploader a écrit : - le menu paramètres affiche de nouveaux tous les outils de configuration Xfce (ça fait un menu paramètres assez grand) Mais en gros, tu peux modifier /etc/xdg/xdg-xubuntu/menus/xfce-applications.menu pour remplacer : <Not><Category>X-XFCE</Category></Not> <Not><Category>X-XfceSettingsDialog</Category></Not> par <Not><Category>XFCE</Category></Not> <Not><Category>X-XFCE-SettingsDialog</Category></Not> Et ça devrait faire un menu à la Xubuntu. Sur le fil concernant le ppa 4.10 http://forum.ubuntu-fr.org/viewtopic.ph … 1#p9236161 http://forum.ubuntu-fr.org/viewtopic.ph … 1#p9236161 Dernière modification par popololo (Le 12/05/2012, à 21:45) Hors ligne atunoa Re : Voyager 12.04 J'ai fini par abandonner Gnome pour xfce suite à plusieurs avis, dont celui de Linus Torvald himself, qui émettait de sérieux doutes sur l'état psychique des développeurs de Gnome 3 et avait choisi l'alternative Xfce (voir cet article). J'ai hésité à installer la version Debian de Mint, mais j'ai pas apprécié certains propos insultants sur cette distribution-ci, de plus les dépôts d'Ubuntu c'est vachement facile, et puis surtout un forum sur Linux, comme ici, y en a qu'un. L'arrivée de Conky control sur une distribution fort améliorée a suffit à me laisser aller à la tentation. Après une perte de tout (grub absent?) inexpliquée, la seconde fois est la bonne. Surtout que j'avais fait la bêtise de copier mon .Mozilla, perdant toutes les améliorations de Rodofr sur Firefox. (Sauve tes favoris et autres modules à part). Je suis un fan de conky et mon préféré est présent dans la distribution sous le nom de n°20. Mais il manquait un certain détail à corriger. Nous ne sommes plus sur Ubuntu... mais sous Voyager. J'ai profité pour tester le nouveau Gimp, en une seule fenêtre, c'est la légende qui s’en va, en bricolant quelques pictos, à ajouter dans l'horloge. Tu ouvre le dossier Home/ton nom à toi/.conky/conky20/ où tu mets les images (ctrl+h, pour voir les fichiers et dossiers cachés) tu édite le fichier conkyrc et tu change la ligne dans ${image ~/.conky/conky20/new-ubuntu-logo.png en mettant l'image qui te plait le mieux, ce qui devient, par exemple,${image ~/.conky/conky20/xubuntuVoyager3.png Tant que tu y es, tu peux changer le lieu de la météo en cherchant le code de ta ville sur Weather Noa et en le substituant aux 4 lettres majuscules de la fin cette ligne ${weather http://weather.noaa.gov/pub/data/observ … /stations/ EBFS. Pour finir, on peux traduire les HOME, DISK, et autres infos en français, les substituant dans le texte par MAISON, DISQUE ou autres. SI le fini, n'est pas nickel, il y a moyen de jouer sur les "goto" qui précède le mot pour les bouger de place. Cerise sur le gâteau, en enregistrant votre nouvelle configuration du conky, celui-ci se met directement à jour. Ce qui permet d'ajuster l'emplacement au mieux...Une merveille de Didier-T... Merci Rodofr pour cette splendide distribution. Panasonic cf-51 X 2 Obsolescence inconnue, Core Duo T2500 2.0 GHz / 2 Go (c'est court) ; Voyager 13.04 en étant passé par toutes les autres; Hors ligne rodofr Re : Voyager 12.04 Quelques problèmes rencontrés dont je vous rapporte la possible solution conky 11 avec la date et l’heure qui affiche l’heure AM au lieu de PM (genre la il est 22h et ça me dit 10h) bien que l'heure du système soit bonne Ouvrir le terminal et coller sudo leafpad ~/.conky/conky11/Date-Hour changer la dernière ligne par ${voffset 8}${font Ubuntu Light:size=80}${time %H:%M}${font}${voffset -8} puis enregistrer Problème son avec pulseaudio Les problèmes peuvent en partie se régler en purgeant le fichier pulse dans la home qui remettra une config propre par défaut avec redémarrage terminal rm -R ~/.pulse/*redémarrer la session XFCE - Raccourci clavier monter/baisser le son menu / paramètres / gestionnaire de paramètres / clavier Onglet raccourcis des applications et faire ajouter - Monter le son : commande = amixer set Master 2dB+ unmute Valider, une autre fenêtre s'ouvre et appuyer sur la touche concernée par exemple F1 et les deux commandes s'affichent sur un cadre - Baisser le son : commande = amixer set Master 2dB- unmute - Activer/désactiver le son : commande = amixer set Master toggle Redémarrer parfois la session pour activer l'effet Hors ligne daisy-duck Re : Voyager 12.04 Salut, je voudrais tout d'abord féliciter Rodofr pour le travail fourni, la disponibilité et le suivi de sa distribution. Je remercie également les contributeurs permettant de cerner les avantages et les inconvénients. Voyager m'a réconcilié avec Gnu-Linux à l'automne dernier. Je n'irai pas cracher sur la soupe. Toutefois, je n'ai pas réinstallé Voyager 12.04 qui m'a semblé beaucoup trop gourmand en ressources actuellement. Je crois que des questions ont été posées sur l'utilisation de la RAM par Voyager et sauf erreur, je n'ai pas lu de réponse technique satisfaisante à ce sujet, mais plutôt des explications émotionnelles. Préalablement à la sortie de Voyager 12.04, j'ai eu le temps de tester d'autres distributions et environnements. Le constat est assez parlant: Démarrage "à vide" avec configuration et applis identiques sur les dernières versions 64 bits: 92 mo de ram avec Lubuntu. 100-120 avec Xubuntu, SalineOs, LMDE. 270 avec Ubuntu. 300 avec Linux Mint 13. 330-350 avec Voyager. J'ignore ce qu'en pense Rodofr. Bien entendu ce ressenti n'est pas hostile. Cela pourrait être presque une question philosophique sur l'esthétisme, lequel ne devrait pas, à mon mon avis, prendre le pas sur les ressources. Proposer des contenus payants dans la logithèque. Même Windows Update n'aurait jamais osé faire ça. Hors ligne
using window.open to open a popup, the "scrollbars=1" thing is not working in IE8 for some reason (the window opens, its just that the scroll bar that isn't showing). works fine in firefox and chrome here is what I tried: window.open(source, null, "height=200, width=400, scrollbars=yes, scrollbars=1, toolbar=no, resizable=1, menubar=no, location=no"); window.open(source, null, "height=200, width=400"); window.open(source, "blank", "scrollbars=1,toolbar=no,menubar=no,width=200,height=200, "); window.open(source, "FarmQuery", 'resizable=1,scrollbars=1'); window.open(source, '','Height=200px,Width=200px,menubar=no,toolbar=no,scrollbars:yes;') "source" is "http://google.com/" by the way Tests indicate that to set scrollbars, I.E. accepts yes or a non-zero digit. <input type="button" onClick='window.open("http://google.co.uk", "blank", "scrollbars=yes,toolbar=no,menubar=no,width=200,height=200" )', value="Open PopUps">
tbonacco Réponses : 351 Afin d'éviter de compiler OpenCascade, une alternative serait d'utiliser la plateforme SALOME (http://www.salome-platform.org), en cours de développement, dont le composant géométrique est développé à partir de la technologie OpenCascade. #1 Re : -1 » Pb à l'installation de matlab » Le 03/03/2006, à 10:07 #2 Re : -1 » Pb à l'installation de matlab » Le 03/03/2006, à 10:12 tbonacco Réponses : 17 Bonjour, pour info : j'imagine que pour ton TP c'est bien le langage mathlab qu'il ta faut. Par la suite tu peux faire la même chose aussi simplement avec PYTHON. Et tu peux même faire plus de choses. PYTHON c'est libre, c'est gratuit, c'est simple, c'est portable, ça s'interface, c'est largement utilisé dans le calcul scientifique, et ça marche ! Bon courage. #3 Re : -1 » Insertion de code HTML dans latex » Le 10/04/2007, à 15:33 tbonacco Réponses : 6 simple et efficace, merci \lstset{numbers=left, tabsize=2, frame=single, breaklines=true, basicstyle=\ttfamily, numberstyle=\tiny\ttfamily, framexleftmargin=13mm, backgroundcolor=\color{grey}, xleftmargin=12mm} \begin{lstlisting} <html><body> blabla </body></html> \end{lstlisting} et aussi \lstinputlisting{monFichier.html} Et voilà ! C'est aussi simple et efficace ! Sinon, est-ce que quel'un connait les option pour enlever la numérotation ? Merci. #4 Re : -1 » Insertion de code HTML dans latex » Le 10/04/2007, à 16:06 tbonacco Réponses : 6 Ok j'ai trouvé pour la numérotation, il suffit d'ajouter la ligne suivante avant la morceau de code que l'on ne veut plus numéroter: \lstset{numers=none} D'accord, c'est évident. Mais encore fallait -t- il savoir que cela fonctionne. Pour pikachu, j'ai pas encore essayé ta solution. J'ai cependant encore un petit souci, c'est lorsque je veux découper mon code comme ça : mon programme machin il est vachement bien, le spremière 30 lignes c'est comme ça : \lstset{numbers=left} \begin{lstlisting} if machin : alos chose chose++ remove bidule \end{lstlisting} Et enfin on voit que les lignes suivantes sont comme ça : \begin[firstnumber=last]{lstlisting} if machin : alos chose chose++ remove bidule \end{lstlisting} Dans ce cas la numérotation de la deuxième portion de code doit suivre celle de la première. Il se trouve que le premier numéro de la seconde portion et le même que le dernier numéro de la première portion de code. Or j'aimerais que ce soit le même +1. N'y a -t- il pas un moyen de faire un firstnumer=last+1 ? Merci. #5 Re : -1 » Probleme avec les images gif » Le 30/03/2007, à 20:36 tbonacco Réponses : 4 Salut, j'ai le même problème que toi, tu as trouvé une solution ? En fait, j'ai des gif animé sur firefox, et lorsque je les enregistre sur mon bureau et que je les redépose sur internet, il ne le sont plus... alors je sèche vraiment pour le coup. C'est la même chose pour mes gif créé avec gimp... #6 Re : -1 » Configuration double-écran sur portable » Le 07/02/2006, à 15:10 #7 Re : -1 » Configuration double-écran sur portable » Le 15/02/2006, à 12:18 tbonacco Réponses : 10 j'ai pu résoudre le problème en installant l'acceleration 3D ATI. L'affichage sur double écran fonctionne, l'acceleration 3D aussi. Il y a un seul hic : lorsque je tente de visualiser une vidéo (VLC ou Totem) mon serveur X s'écroule et je dois le relancer à la main. Je n'ai pu que constater le bug et je n'ai pas encore chercher d'où cela peut-il venir. Si quelqu'un à une idée je suis preneur. Je n'ai pas le temps mais je pense repasser bientôt pour déposer mon xorg.conf auquel je n'ai pas encore jeter de coup d'oeil non plus. #8 Re : -1 » Gaphor 0.7.1 » Le 13/06/2006, à 17:18 #11 Re : -1 » xorg & sortie vga » Le 08/02/2006, à 00:00 tbonacco Réponses : 1 Bonjour, Depuis la migration vers Dapper, gaphor (editeur UML PYTHON) ne fonctionne plus. Le bug est bien connu. J'ai trouvé une alternative qui vaut ce qu'elle vaut, mais elle a le mérite de fontionner. Lors de l'exécution de gaphor vous avez un message d'erreur qui finit comme ça ... ... ...Traceback (most recent call last): File "/usr/bin/gaphor", line 10, in ? gaphor.main(model) File "/usr/lib/python2.4/site-packages/gaphor/__init__.py", line 48, in main import diagram File "/usr/lib/python2.4/site-packages/gaphor/diagram/__init__.py", line 56, in ? from classifier import ClassifierItem File "/usr/lib/python2.4/site-packages/gaphor/diagram/classifier.py", line 18, in ? from nameditem import NamedItem File "/usr/lib/python2.4/site-packages/gaphor/diagram/nameditem.py", line 9, in ? from elementitem import ElementItem File "/usr/lib/python2.4/site-packages/gaphor/diagram/elementitem.py", line 74, in ? initialize_item(ElementItem) File "/usr/lib/python2.4/site-packages/gaphor/diagram/__init__.py", line 39, in initialize_item if (diacanvas.CanvasItem in bases) or \ AttributeError: 'module' object has no attribute 'CanvasGroup' Si l'on fait un tour dans le fichier /usr/lib/python2.4/site-packages/gaphor/diagram/__init__.py , on peut supprimer la condition du if qui fait planter : (diacanvas.CanvasGroup in bases) or \ En attendant quelque chose de mieux ça fonctionne #13 Re : -1 » [resolu]Installation de UTF-8 pour LaTeX » Le 16/02/2006, à 00:33 tbonacco Réponses : 14 Juste une remarque, il est possible de connaitre l'encodage du fichier avec la commande "file", et de changer l'encodage d'un fichier (cela évite d'ajouter des "/usepackage" et d'installer des paquets) avec la commande "iconv" (cf le man très très clair en l'occurence) tbonacco Réponses : 5 Bonjour, j'ai effectué la mise à jour de breezy vers dapper depuis peu. Je développe des applis en PYTHON. J'ai eu un premier problème avec GAPHOR ( editeur de diagramme UML ) qui ne fonctionne pas sous DAPPER (a priori à cause de diacanvas) et aujourd'hui idle ne se lance pas non plus (. A priori ces bugs sont fixés [url=https://launchpad.net/distros/ubuntu/+source/python-defaults/+bug/24841]ici[url]et [url=https://launchpad.net/bugs/30344]là[url]). tbonacco@lamachine:~$ idle Traceback (most recent call last): File "/usr/bin/idle", line 5, in ? main() File "/usr/lib/python2.4/idlelib/PyShell.py", line 1350, in main root = Tk(className="Idle") File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 1569, in __init__ self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) _tkinter.TclError: this isn't a Tk applicationunknown color name "Black" En fait c'est même carrément Tkinter qui ne fonctionne plus. Quelqu'un a-t-il une solution, meme temporaire à proposer ? Merci d'avance. #16 Re : -1 » probleme de lancement IDLE sous DAPPER[resolu] » Le 22/06/2006, à 12:48 #17 Re : -1 » probleme de lancement IDLE sous DAPPER[resolu] » Le 22/06/2006, à 14:36 tbonacco Réponses : 5 Ok j'ai trouvé la solution, ce n'est pas Xgl... dans /etcX11/xorg.conf Section "Files" # The location of the RGB database. Note, this is the name of the # file minus the extension (like ".txt" or ".db"). There is normally # no need to change the default. RgbPath "/usr/X11R6/lib/X11/rgb" # Multiple FontPath entries are allowed (which are concatenated together), # as well as specifying multiple comma-separated entries in one FontPath # command (or a combination of both methods) La variable RgbPath pointe sur le fichier rgb.txt. Il se trouve que se fichier n'existait pas, mais il était dans /etc/X11/rgb.txt. JIl suffit de faire un lien symbolique sudo ln -s /etc/X11/rgb.txt /usr/X11R6/lib/X11/rgb.txt Et relancer le serveur X #18 Re : -1 » probleme de lancement IDLE sous DAPPER[resolu] » Le 22/06/2006, à 17:36 tbonacco Réponses : 5 J'ai essayé sudo ln -s /etc/X11/rgb.txt /usr/share/X11/ mais comme RgbPath pointe sur "/usr/X11R6/lib/X11/rgb" cela ne fonctionnait pas dans mon cas. Pour info je viens d'installer xgl et compiz, je n'ai pas d'erreur. C'était bien un problème de rgb.txt Merci de ton aide. #19 Re : -1 » kile et html » Le 16/02/2006, à 18:46 #20 Re : -1 » kile et html » Le 21/02/2006, à 11:38 tbonacco Réponses : 7 Bonjour, J'ai décommenté mes lignes de dépots "multiverse" mais sans succès. Finallement j'ai téléchargé les sources de latex2htlm sur http://www.latex2html.org/ et je les ai installées en local sur un compte. Ca fonctionne mais si j'avais le bon dépot ce serait plus propre. Sinon cet outil (latex2html) est vraiment super ! De belle pages bien pro à porté de click sous kile.
enebre Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... bonjour smo, je viens de réinstaller gmf sur mon petit netbook et git clone git://github.com/smolleyes/gmediafinder2.git gmf2 cd gmf2/Gmediafinder python gmediafinder.py je constate que python-mecahanize n'est plus intégré dans les deps, et d'autres dépendences manques aussi... j'ai ajouté ces deux ci mais... après l'install des deps sudo apt-get install python-xlib sudo apt-get install python-mechanize et suivi d'un python gmediafinder.py j'ai encore des erreurs (gmediafinder.py:14991): libglade-WARNING **: unknown attribute `swapped' for <signal>. Traceback (most recent call last): File "gmediafinder.py", line 1096, in <module> app = GsongFinder() File "gmediafinder.py", line 264, in __init__ self.down_btn.hide() AttributeError: 'GsongFinder' object has no attribute 'down_btn' Dernière modification par enebre (Le 13/12/2011, à 14:40) Hors ligne smo Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... ola sudo apt-get install gnome-icon-theme-full dsl je manque cruellement de motivation en ce moment ... ++ ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne smo Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... ola je viens de faire une maj, essayes voir ++ ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne smo Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... ok remaj ! ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne enebre Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... toujours erreur (gmediafinder.py:9979): libglade-WARNING **: unknown attribute `swapped' for <signal>. Traceback (most recent call last): File "gmediafinder.py", line 1108, in <module> app = GsongFinder() File "gmediafinder.py", line 277, in __init__ self.down_menu_btn.hide() AttributeError: 'GsongFinder' object has no attribute 'down_menu_btn' Dernière modification par enebre (Le 14/12/2011, à 22:14) Hors ligne smo Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... Oo bizzarre tout ca ! remaj voir ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne enebre Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... mais j'ai un petit soucis, je ne sais pas encore si c'est persistant, mais je post déjà le retour raceback (most recent call last): File "gmediafinder.py", line 879, in _add_to_playlist link = self.media_link AttributeError: 'GsongFinder' object has no attribute 'media_link' change page <gtk.Notebook object at 0x3bf30a0 (GtkNotebook at 0x3c70150)> <gpointer at 0x3d23d70> Youtube 0 0 0 ---------------update_info----------------- state : 1 ---------------update_info----------------- state : 1 [xcb] Unknown sequence number while processing queue [xcb] Most likely this is a multi-threaded client and XInitThreads has not been called [xcb] Aborting, sorry about that. python: ../../src/xcb_io.c :273 : poll_for_event: L'assertion « !xcb_xlib_threads_sequence_lost » a échoué. Abandon je confirme après re-essai, sur youtube gmf crashe au lancement (gmediafinder.py:10242): libglade-WARNING **: unknown attribute `swapped' for <signal>. ['/home/marc/gmf2/GmediaFinder/lib/engines', '/home/marc/.config/gmediafinder/plugins'] 0 change page <gtk.Notebook object at 0x2c93550 (GtkNotebook at 0x2d10150)> <gpointer at 0x2dc4170> Erreur de segmentation oups ! et ca fonctionne en 640 x 360 Dernière modification par enebre (Le 14/12/2011, à 22:36) Hors ligne smo Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... yep bah ca c est des bugs pas encore cernés on va dire... t en auras forcement pour l instant avec cette version merci pour les retours ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne smo Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... ola joyeux noel too ! bah tu utilises ffmpeg directement enebre... je pense pas ajouter la lecture de fichiers locaux, perso la je suis a fond sur grooveshark et stabilisation de la version avec webkit... a suivre ++ ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne enebre Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... Salut smo, merci bonnes fêtes et pour un monde meilleur, car là ! Je trouve que ça secoue pas mal dehors. Oui bien sur, ffmpeg, j'y pensais plus, j'ai pas trop utilisé les cyber-artefacs ces temps-ci,hôpital et je convalescence. On va devoir parer aux grains... ++ Hors ligne smo Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... ola bah courage mr, rien de grave j espere ! bon grooveshark pete bien , version free on a donc les radios + les plus populaires en ecoute illimitée et j arrive a downloader aussi (enfin!!!!) mais j suis pas sensé le faire... j verrai pour la version illimitée avec login etc me dire ceux que ca interesse je maj le depot gmf2 + les plugins ++ ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne smo Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... ola bon va falloir que j reveille ce topic moi !!! sont ou les testeurs !!!??? alors, je continue mes delires avec webkit.. j ai pousse le delire sur youtube, je post une video pour faire voir ca sera plus simple avis? ++ Dernière modification par smo (Le 28/12/2011, à 21:06) ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne enebre Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... Peux pas tester, gmf ne s'ouvre plus avec les nouveaux plugins, ais je fait une erreur quelque part ? Mais la démonstration de webkit en opération, cà fait vraiment du super boulot. marc@marc-1:~/gmediafinder/GmediaFinder$ python gmediafinder.py Xlib.protocol.request.QueryExtension Traceback (most recent call last): File "gmediafinder.py", line 1933, in <module> app = GsongFinder() File "gmediafinder.py", line 487, in __init__ self.engines_client = Engines(self) File "/home/marc/gmediafinder/GmediaFinder/engines.py", line 20, in __init__ self.load_engines() File "/home/marc/gmediafinder/GmediaFinder/engines.py", line 36, in load_engines self.load_plugins_conf() File "/home/marc/gmediafinder/GmediaFinder/engines.py", line 72, in load_plugins_conf self.init_engine(engine) File "/home/marc/gmediafinder/GmediaFinder/engines.py", line 40, in init_engine module = __import__(modstr, globals(), locals(), ['*']) File "/home/marc/gmediafinder/GmediaFinder/lib/engines/PornHub/PornHub.py", line 10, in <module> from GmediaFinder.lib.functions import * ImportError: No module named functions marc@marc-1:~/gmediafinder/GmediaFinder$ git pull Already up-to-date. Dernière modification par enebre (Le 28/12/2011, à 21:32) Hors ligne Hizoka Hors ligne smo Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... ola marc, copies/colles (hizo tu capteras): cd $HOME/gmediafinder git clone git://github.com/smolleyes/gmediafinder2.git gmf2 cd gmf2/GmediaFinder python gmediafinder.py les dependances (en l etat) logiquement c est : python-gtk2 python-gdata python-gst0.10 gstreamer0.10-ffmpeg libvisual-0.4-0 libvisual-0.4-plugins python-configobj ffmpeg python-mechanize gstreamer0.10-plugins-good gstreamer0.10-plugins-bad python-xlib python-glade2 python-setuptools python-webkit python-jswebkit mplayer vlc pour l instant ca crash pas mal sur youtube... j ai encore du taff pou trouver ce qui fait planter le gui ... dites moi... ++ Dernière modification par smo (Le 28/12/2011, à 21:56) ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne Hizoka Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... perso pas de plantage mais : - je recherche une video - je double clic sur l'une des videos de la liste - je vais dans browser - je choisis une video proposé par youtube - mais il se passe au moins 30 secondes avant que ca ne change de video, pendant ce temps la la 1ere video continue. Hors ligne smo Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... yup j comprend mais j y peux rien la, ca correspond au moment ou le player flash recoit le lien du flux video donc c est que du reseau, ca depend de ta connexion etc la... moi ca va assez vite ca depend ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne Hizoka Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... etrange... via le site youtube, ca prend 5sec... j'ai l'impression que l'interet est assez limité... quelle est ta vision de cette nouvelle possibilité ? Hors ligne smo Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... suis sur le tchat g2s... ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne enebre Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... essai avec youtube, image d'excellente fluidité 128k, très bon signal acoustique, sur ubuntu 11.04 merci pour les lignes de commande Dernière modification par enebre (Le 29/12/2011, à 00:13) Hors ligne sauthess Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... salut à tous, Bon ben moi j'ai le même plantage qu'enebre sur ubuntu 10.04 (dépendances pourtant installées via apt) Je vais essayer 11.10 pour voir... EDIT : sur 11.10 ça marche tout seul (ça y est je viens de comprendre qu'il y avait quelque chose à tester car depuis longtemps la version 1 est à jour est j'avais pas vu qu'il y avait une version 2 ) Je teste tout ça et te fais un retour ASAP. Une idée pour le faire marcher sur 10.04 ? EDIT2 : je viens de comprendre que mon plantage vient du fait que les plugins persos n'étaient pas à jour (quand je les ai ajouté j'avais le même plantage sur 11.10). Je n'ai pas testé sur 10.04 mais à tous les coups ça doit marcher... ++ Dernière modification par sauthess (Le 29/12/2011, à 10:59) Serveur : Debian squeeze openvz, Portable 1 : Arch linux Enlightenment/Cinnamon, Portable 2 : Ubuntu 12.04 unity (aucun Windows depuis 2006 mais je continue à payer les licences OEM à chaque achat par manque de possibilités...) Hors ligne AnsuzPeorth Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... Hello, @smo Suis pas trop dispo en ce moment, en début d'années ca ira mieux @sauthess Si smo n'as pas trop changer de choses, sur la 10.4 ca passe sans soucis. Bien que j'ai vu une dependances python-jswebkit et je sais pas si elle est compatible webkit sous lucid ? Interface graphique pour bash, python ou autre: glade2script Support Tchat: http://chat.jabberfr.org/muckl_int/inde … ade2script (Hors ligne) Hors ligne enebre Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... Pour l'installation de gmf2, j'ai fais cfr post #793 : mkdir ~/gmediafinder cd /gmediafinder git clone git://github.com/smolleyes/gmediafinder2.git gmf2 cd ~/gmediafinder/gmf2/GmediaFinder python gmediafinder.py ensuite j'ai collé les plugins dans le dossier /home/**user**/gmediafinder/gmf2/GmediaFinder/lib/engines/ Je suis içi avec la ubuntu 11.04 ça fonctionne nickel sauf certains plugins qui jump jump jump Dernière modification par enebre (Le 29/12/2011, à 17:23) Hors ligne
Alan Davies is learning Chinese and couldn't find a site that would work out what level of difficulty a text or a vocabulary list would be. So he built a site to do that on PythonAnywhere, our Python-focused PaaS and browser-based programming environment. Bravely enough, he did it in Python 2, which is not renowned for its Unicode support. While he says that "there are a few little things you have to be aware of" Unicode-wise, it turned out to be entirely doable and is now used by people learning Chinese all over the world. There is a standardised test of Mandarin Chinese for foreigners called the HSK. The HSK has six levels, with HSK 1 requiring the ability to work with a vocabulary of 150 Chinese words, and HSK 6 requiring about 5,000 words. It's useful to be able to ask questions about all these word lists: I wanted something that could answer these questions, so I wrote a quick script for myself to use, taking some Chinese text or a vocabulary list, and breaking it down according to the 6 levels of the standardised Chinese HSK exams. I started learning Mandarin Chinese a couple of years ago. Once I got started it was addictive, I think it really appeals to the brain of a programmer because of the highly logical and consistent grammatical structure, with every character pronounced as exactly one syllable. There are many other interesting features such as how the characters are constructed from smaller components which often give hints as to their meaning or pronunciation, a bit like a cryptic crossword clue in each character. One quick example: 马 (pronounced 'ma', ignoring the tones) means horse, and 女 means woman. 妈, which means 'mother', is also pronounced 'ma'. The left side of 妈 gives a hint to its meaning, and the right side to its pronunciation. My script has a few text files as inputs: the HSK words at each level, word and character frequencies, a free Chinese-English dictionary, and a file that gives character composition information (see above). The words and characters at each HSK level are stored in Python set() objects, and when a user vocabulary list has been input the various questions to do with HSK characters in the can be answered with various combinations of the very powerful set operations. The resulting lists are sorted by character or word frequency as appropriate, to keep the more interesting and frequent characters near the top. The in-memory data structures (which are all sets, dictionaries, and arrays) are just pickled to disk, to save re-parsing the source files. I also added the ability to take a block of text and try to turn it into a vocabulary list. Parsing Chinese sentences into words is quite a difficult problem, and not just because it is quite difficult to distinguish between 'words' and 'phrases' sometimes in Chinese (editor's note: Section 5 of this blog post gives you some idea of how hard this is). Secondly, Chinese speakers run 'words' together with pauses between them as we do in English, but when they write these words down there are no spaces between them. There generally isn't too much ambiguity when being read by a fluent Chinese speaker, but for a computer program this is a nightmare. Tokenising Chinese sentences has been the subject of many research projects, and all sorts of statistical, grammatical, and AI techniques have been tried. Another example: the characters 中 (middle), 国 (country), and 人 (person) are each words in their own right. Put them together and you can create the words 中国 (China, the 'Middle Kingdom'), 国人 (compatriot), and 中国人 (Chinese person). All this can of course be in the middle of a sentence with other potential word combinations formed from the first and last character. I chose a simple and crude way to resolve this ambiguity by looking at the frequency of the possible word combinations, it could probably use some more work though, maybe next time I am delayed at an airport! Judging by the feedback I've had, people learning Chinese all over the world. The top countries are the US, China, Thailand, and Germany, and Taiwan. At the moment about 100 unique users per day, as it's really still just in early development. I've shared it with a few people to test it, but if it becomes popular I'll polish it up and host it under my own domain name. The only non standard library module this project uses is Flask, I just wanted the simplest possible framework that would let objects persist on the server between requests, so I could keep some of the data around without re-parsing the data files for every request. The HTML and CSS is as simple as possible at the moment, making it look pretty is not the part that interests me much. Handling Chinese characters with Python 2 Unicode strings is less hassle than I though it would be, but there are a few little things you have to be aware of. You end up being paranoid and prefixing all of your string literals with 'u', a problem that I believe is fixed in Python 3 where all strings are unicode by default. Missing the 'u' prefix will cause some nasty behaviour from the examples below; '1' will output a bit of line noise, 2 will output "\u4e2d" rather than a properly encoded character, and worst of all will 3 and 4 will throw a run-time exception. 5 will usually work correctly depending if your editor has saved the file with the correct encoding, although for safety I stick with 6 and keep my source files in ASCII: print "1: {}".format("中"); print "2: {}".format("\u4e2d"); print "3: {}".format(u"中"); print "4: {}".format(u"\u4e2d"); print u"5: {}".format(u"中"); print u"6: {}".format(u"\u4e2d"); It is also important to specify the encoding of files when reading and writing non-ASCII encodings, otherwise you will have garbled characters. For UTF-8 it is also usually better to include a byte order mark as well. The following code opens files for reading and writing: import codecs infile = codecs.open(infilename, 'r', "utf-8") outfile = codecs.open(outfilename, 'w', "utf-8") outfile.write(codecs.BOM_UTF8.decode("utf8")) I messed about a bit with BASIC on the the BBC Micro and ZX Spectrum when I was young, and then Assembler on the Atari ST. I did a degree in Computer Engineering and started work as a software developer, working in C, then C++, and more recently various .NET languages. I'm now doing a PhD in Finance so any programming I do tends to be econometrics in R, SAS, and Stata. For about 12 years though I have tended to used Python for my own small projects, as I find it very quick and intuitive to write, and very readable. With PythonAnywhere I can log in from anywhere when I have a few minutes and fix a bug or add or improve a feature. And the processing power available is blinding. Drop us a line at [email protected] and we'll have a chat!
FTG [script/python] Nautilus et picasaweb! Bonjour à tous, depuis longtemps je voulais réaliser un petit script python a l'aide des API Google, me permettant d'uploader en 2 temps 3 mouvements un paquet de photos de Nautilus vers Picasaweb par un clic droit de souris. Je n'avais pratiquement rien à faire aujourd hui et je m'y suis attelé et j'ai fini par obtenir un résultat. Ce n'est pas grandiose grandiose mais ca fait le boulot! Est ce que cela interesserait quelqu un que je décrive la marche à suivre ainsi que les outils à installer pour que cela fonctionne sachant que ce n'est vraiment pas compliqué? a+ Hors ligne Jeece Re : [script/python] Nautilus et picasaweb! Salut. Non ça intéresse sûrement personne car Picasa c'est propriétaire et on préfère F-Spot qui fait très bien le boulot. J'rigole hein Dis nous vite vite vite. Et maintenant fait nous la même chose pour flickr ce serait chupa chups. Dernière modification par Jeece (Le 11/05/2008, à 17:46) Content que ça vous plaise ! Hors ligne FTG Re : [script/python] Nautilus et picasaweb! Re à tous, Le but de ce post est d'initier peut etre un projet plus solide qui pourrait voir le jour, à la communauté de trancher Bon voila l'affaire. Ce que vous devez avoir installé sur votre machine: - python 2.4 au moins (de base vous l'avez) - xterm - nautilus-actions (dans les depots debian stable, je pense que sous Ubuntu y aura pas de soucis) Une fois ces trois paquets installés, allez voir du côté de ce lien: http://code.google.com/p/gdata-python-c … loads/list et telechargez la derniere version de gdate-py dans un endroit de votre partition /home/user. Décompresser avec la commande tar xvf puis bien lire INSTALL.TXT ca vaut le coup! Pour les plus préssés d'entre vous lancez tout de suite python setup.py en root. Dans l'INSTALL.TXT il est bien indiqué comment tester si l'installation a bien fonctionné! Copiez le script suivant dans ~/Scripts_python/nom_de_fichier.py # -*- coding: utf-8 -*- # Envoi de photos sur picasaweb # installation de gdata, xterm requise, nautilus-actions # Dans Nautilus Action rentrer # Chemin:: xterm -e python "script" # Parametres:: %M import sys import gdata.photos.service #import gdata.media #import gdata.geo print "####################### Fichiers à envoyer: #################################" for i in range(len(sys.argv)-1): print sys.argv[i+1] print "#############################################################################" print "" print "" email=raw_input("Veuillez entrer votre login Picasa/Google: ") password=raw_input("Veuillez entrer votre mot de passe: ") gd_client = gdata.photos.service.PhotosService() gd_client.email = email gd_client.password = password gd_client.source = 'exampleCo-exampleApp-1' try: gd_client.ProgrammaticLogin() except gdata.service.CaptchaRequired: print('Required Captcha') except gdata.service.BadAuthentication: print('Mauvaise authentification') except gdata_client.Error: print('Probleme de Login') else: nouvelalbum=raw_input("Voulez vous creer un nouvel album? (O/N) ") if nouvelalbum=="O" or nouvelalbum=="o": nom_album=raw_input("Nom de l'album (sans espaces): ") # Verification si l'album existe deja feed = gd_client.GetUserFeed(user="default") for entry in feed.entry: while nom_album.lower()==str(entry.title.text).lower(): print "Cet album existe deja, veuillez entrer un autre nom!" nom_album=raw_input("Nom de l'album (sans espaces): ") acces=raw_input("Acces de l'album (private/public): ") entry = gd_client.InsertAlbum(nom_album, summary='This is an album', access=acces) album_url = '/data/feed/api/user/%s/album/%s' % ('default', nom_album) for i in range(len(sys.argv)-1): entry = gd_client.InsertPhotoSimple(album_url, 'New Photo','Uploaded using FTG loader', sys.argv[i+1], content_type='image/jpeg') print "Photo numero " + str(i+1) + " envoyee!" else: print "Choisissez un album: " feed = gd_client.GetUserFeed(user="default") i=0 for entry in feed.entry: i=i+1 print str(i) + ':: %s, number of photos: %s' % (entry.title.text, entry.numphotos.text) album=raw_input("Veuillez rentrer un numero d'album (Chiffre de 1 a " + str(i) + "): ") i=0 for entry in feed.entry: i=i+1 if str(i)==str(album): nom_album=entry.title.text album_url = '/data/feed/api/user/%s/album/%s' % ('default', nom_album) for j in range(len(sys.argv)-1): entry = gd_client.InsertPhotoSimple(album_url, 'New Photo','Uploaded using FTG loader', sys.argv[j+1], content_type='image/jpeg') print "Photo numero " + str(j+1) + " envoyee!" fin=raw_input("Appuyez sur Entree pour sortir!") Ensuite, ouvrir Menu Gnome>Bureau>Preferences>Configuration des actions de nautilus (issu du paquet nautilus-actions) Cliquer sur Ajouter. Dans Libellé ecrire un truc du genre "Envoyer vers Picasaweb". Dans Chemin, mettre xterm -e python "lien vers le script python que vous avez stockés plus haut" Dans Parametres, mettre %M Fermez le tout! Ensuite allez dans nautilus, selectionnez les photos que vous desirez envoyer vers picasaweb, cliquez droit puis selectionner "Envoyer vers Picasaweb" et suivez les instructions sous xterm!! Bon je suis bien conscient que ce tuto est un peu leger, mais c'est historie de vous en faire profiter au plus vite, a terme je compte developper une petite page web avec screenshots et ameliorer l'emballage avec pourquoi pas du GTK et des options supplémentaires! De plus, le script python est loin d'etre optimisé, mais j'ai codé ca à la va-vite cet apres midi, mais promis je vais améliorer tout ca! Pour tout dysfonctionnement, n'hésitez pas à m'appeler au secours. Pour toute idée supplémentaire, n'hésitez pas à me contacter non plus! Bonne soirée à tous Dernière modification par FTG (Le 11/05/2008, à 19:00) Hors ligne Annala Re : [script/python] Nautilus et picasaweb! Bonjour, Superbe idée, c'est exactement ce que je cherchais. L'installation a l'air de bien se dérouler, c'est tout à la fin que ça coince : en faisant le clic droit, je n'ai pas "Envoyer vers ..." pourtant j'ai configuré nautilus-actions comme indiqué. En cherchant mon erreur, je viens de découvrir dans F-Spot > Fichier >Envoyer vers > Webgallery, Picasaweb, Flickr, CD ... Dernière modification par Annala (Le 12/05/2008, à 17:42) Dell XPS M1530 - Trusty Tahr Hors ligne FTG Re : [script/python] Nautilus et picasaweb! Oui mais le but est de pouvoir envoyer les photos de Nautilus sans passer par un autre logiciel... Hors ligne FTG Re : [script/python] Nautilus et picasaweb! up,pour les curieux Hors ligne Axelap Re : [script/python] Nautilus et picasaweb! Vous n'auriez pas un script pour faire l'inverse des fois ? En effet même avec Picase je n'arrive pas à les récupérer. Je ne me vois pas les enregistret une par une. ps : la galerie est bien à moi et je suis connecté. Axelap, sous Ubuntu depuis début octobre 2008 Hors ligne FTG Re : [script/python] Nautilus et picasaweb! Hola, non désolé je n'ai pas l'inverse pour le moment, mais ca pourrait etre une bonne idée! Hors ligne Axelap Re : [script/python] Nautilus et picasaweb! Je viens de découvrir une extension pour firefox qui peut gérer les connexions à double sens : fire/universal uploader. Axelap, sous Ubuntu depuis début octobre 2008 Hors ligne Sebco Re : [script/python] Nautilus et picasaweb! vachement bien.....ouaip!!! merci et bravo .*´¨;) -->Pour les problemes http://chat.jabberfr.org/muckl_int/index.php?room=ubu-personnalisation ¸.•´¸.•´¨;)¸.•*¨;)-->Le site http://penguincape.org/ (¸.•´ (¸.•´ .•´ : (´¸.•*´¯`*•~--> Wiki --> http://doc.ubuntu-fr.org/tutoriel/personnalisation_cubemodel_wallpaper_dynamique_et_usplash Hanoi - VIETNAM Hors ligne Pedrodelalunabe Re : [script/python] Nautilus et picasaweb! Très efficace l'uploader de firefox. Hors ligne GNU-max Re : [script/python] Nautilus et picasaweb! J'ai repris le script de FTG (merci bcp à lui, j'ai pas changé grand chose) et j'ai ajouté une interface avec zenity (grâce au code de PyZenity de Brian Ramos). J'ai jamais fait de Python alors soyez indulgent. L'essentiel du code est à la fin. # -*- coding: utf-8 -*- # Envoi de photos sur picasaweb # Dépend de : # gdata [ à télécharger sur http://code.google.com/p/gdata-python-client/downloads/list et installer - cf. INSTALL.TXT - ] # nautilus-actions # zenity # Dans Nautilus Action rentrer # Chemin : /usr/bin/python </chemni/vers/script> # Parametres : %M # Conditions : # Types Mime : image/* # Cocher : Apparaît si la selection contient plusieurs fichiers ou dossiers # ######-PyZenity-########## #Afin de ne pas avoir à télécharger et installer le code de PyZenity, je l'ai reproduis en partie ici. ###################################################################################################### # Name: iPyZenity.py # Author: Brian Ramos # Created: 10/17/2005 # Revision Information: # $Date: $ # $Revision: $ # $Author: bramos $ # # Licence: MIT Licence # # Copyright (c) 2005 Brian Ramos # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. ################################################################################ from datetime import date from subprocess import Popen, PIPE from itertools import chain from os import path __all__ = ['GetText','Question', 'Warning', 'ErrorMessage', 'Progress','List' ] zen_exec = 'zenity' def run_zenity(type, *args): return Popen([zen_exec, type] + list(args), stdin=PIPE, stdout=PIPE) def List(column_names, title=None, boolstyle=None, editable=False, select_col=None, sep='|', data=[]): """Present a list of items to select. This will raise a Zenity List Dialog populated with the colomns and rows specified and return either the cell or row that was selected or None if the user hit cancel. column_names - A tuple or list containing the names of the columns. title - The title of the dialog box. boolstyle - Whether the first columns should be a bool option ("checklist", "radiolist") or None if it should be a text field. editable - True if the user can edit the cells. select_col - The column number of the selected cell to return or "ALL" to return the entire row. sep - Token to use as the row separator when parsing Zenity's return. Cells should not contain this token. data - A list or tuple of tuples that contain the cells in the row. The size of the row's tuple must be equal to the number of columns.""" args = [] for column in column_names: args.append('--column=%s' % column) if title: args.append('--title=%s' % title) if boolstyle: if not (boolstyle == 'checklist' or boolstyle == 'radiolist'): raise ValueError('"%s" is not a proper boolean column style.' % boolstyle) args.append('--' + boolstyle) if editable: args.append('--editable') if select_col: args.append('--print-column=%s' % select_col) if sep != '|': args.append('--separator=%s' % sep) for datum in chain(*data): args.append(str(datum)) p = run_zenity('--list', *args) if p.wait() == 0: return p.stdout.read().strip().split(sep) def ErrorMessage(text): """Show an error message dialog to the user. This will raise a Zenity Error Dialog with a description of the error. text - A description of the error.""" run_zenity('--error', '--text=%s' % text).wait() def Question(text): """Ask the user a question. This will raise a Zenity Question Dialog that will present the user with an OK/Cancel dialog box. It returns True if the user clicked OK; False on Cancel. text - The question to ask.""" return run_zenity('--question', '--text=%s' % text).wait() == 0 def Warning(text): """Show a warning message dialog to the user. This will raise a Zenity Warning Dialog with a description of the warning. It returns True if the user clicked OK; False on cancel. text - A description of the warning.""" return run_zenity('--warning', '--text=%s' % text).wait() == 0 def Progress(text='', percentage=0, auto_close=False, pulsate=False): """Show a progress dialog to the user. This will raise a Zenity Progress Dialog. It returns a callback that accepts two arguments. The first is a numeric value of the percent complete. The second is a message about the progress. NOTE: This function sends the SIGHUP signal if the user hits the cancel button. You must connect to this signal if you do not want your application to exit. text - The initial message about the progress. percentage - The initial percentage to set the progress bar to. auto_close - True if the dialog should close automatically if it reaches 100%. pulsate - True is the status should pulsate instead of progress.""" args = [] if text: args.append('--text=%s' % text) if percentage: args.append('--percentage=%s' % percentage) if auto_close: args.append('--auto-close=%s' % auto_close) if pulsate: args.append('--pulsate=%s' % pulsate) p = Popen([zen_exec, '--progress'] + args, stdin=PIPE, stdout=PIPE) def update(percent, message=''): if type(percent) == float: percent = int(percent * 100) p.stdin.write(str(percent) + '\n') if message: p.stdin.write('# %s\n' % message) return p.returncode return update def GetText(text='', entry_text='', password=False): """Get some text from the user. This will raise a Zenity Text Entry Dialog. It returns the text the user entered or None if the user hit cancel. text - A description of the text to enter. entry_text - The initial value of the text entry box. password - True if text entered should be hidden by stars.""" args = [] if text: args.append('--text=%s' % text) if entry_text: args.append('--entry-text=%s' % entry_text) if password: args.append('--hide-text') p = run_zenity('--entry', *args) if p.wait() == 0: return p.stdout.read()[:-1] ######################################################## #####-END of PyZenity-###### import sys import gdata.photos.service #import PyZenity #import bz2 #Paramètres : possibilité de les rentrer en dur email=GetText(text='Email', entry_text='@gmail.com', password=False) password=GetText(text='Mot de passe', entry_text='Picasa', password=True) #key=... ########-Fonction d'envoi des photos-######## def send_photo(album): album_url = '/data/feed/api/user/%s/album/%s' % ('default', album) update=Progress(text='Envoi des photos ...', percentage=0, auto_close=False, pulsate=False) percent=0 for i in range(len(sys.argv)-1): text='Envoi des photos ... ('+str(i+1)+'/'+str(len(sys.argv)-1)+')' print str(percent) update(percent,text) entry = gd_client.InsertPhotoSimple(album_url, 'New Photo','', sys.argv[i+1], content_type='image/jpeg') percent=int(float(i+1)/(len(sys.argv)-1)*100) ############################################# #Connection à picasaweb gd_client = gdata.photos.service.PhotosService() gd_client.email = email #gd_client.password = bz2.decompress(key) gd_client.password = password gd_client.source = 'exampleCo-exampleApp-1' try: gd_client.ProgrammaticLogin() except gdata.service.CaptchaRequired: # print('Required Captcha') ErrorMessage('Required Captcha') except gdata.service.BadAuthentication: # print('Mauvaise authentification') ErrorMessage('Mauvaise authentification') except gdata_client.Error: # print('Probleme de Login') ErrorMessage('Probleme de Login') else: nouvelalbum=Question("Creer un nouvel album ?") if nouvelalbum==True : nom_album=GetText(text='Nom de l\'album (sans espaces): ', entry_text='Nouvel_album', password=False) # Verification si l'album existe deja feed = gd_client.GetUserFeed(user="default") for entry in feed.entry: while nom_album.lower()==str(entry.title.text).lower(): Warning("Cet album existe deja, veuillez entrer un autre nom !") nom_album=GetText(text='Nom de l\'album (sans espaces): ', entry_text='Nouvel_album_2', password=False) #Permissions sur l'album acces="private" #Crée l'album entry = gd_client.InsertAlbum(nom_album, summary='This is an album', access=acces) #Envoi des photos send_photo(nom_album) else: # Choisir un album feed = gd_client.GetUserFeed(user="default") i=0 liste=() for entry in feed.entry: i=i+1 liste = liste + (entry.title.text,) nom_album=(List(('Album',), title=None, boolstyle=None, editable=False, select_col=None, sep='|', data=[liste]))[0] #Envoi des photos send_photo(nom_album) Dernière modification par GNU-max (Le 18/07/2009, à 16:39) Hors ligne GNU-max Re : [script/python] Nautilus et picasaweb! J'ai fait aussi un script bash qui permet de télécharger un album de picasaweb en cliquant sur «Télécharger vers picasa» depuis l'interface web. Désolé pour la longueur du script précédent. #! /bin/bash # Script de téléchargement d'un album Picasa à partir de son uri picasa:// # Equivalent à «Télécharger avec picasa» sur picasaweb #................................................. # Dépends de : Zenity, plugin picasa pour firefox (npPicasa3.so) dispo dans le paquet .deb de Picasa 3 for linux #--1-- # Copier npPicasa3.so dans les dossiers de plugins firefox : #................................................... # sudo cp npPicasa3.so /usr/lib/mozilla/plugins/ # sudo ln -s /usr/lib/mozilla/plugins/npPicasa3.so /usr/lib/firefox/plugins/npPicasa3.so # sudo ln -s /usr/lib/mozilla/plugins/npPicasa3.so /usr/lib/firefox-addons/plugins/npPicasa3.so #................................................... #Verifier le chargement du plugins (taper about:plugins dans firefox) #--2-- # Configurer Firefox [adapter le chemin vers le script] #................................................... # path=$(ls -d /home/$USER/.mozilla/firefox/*.default) # echo -e "user_pref(\"network.protocol-handler.app.picasa\", \"/home/$USER/picasa_down.sh\");\nuser_pref(\"network.protocol-handler.external.picasa\", true);$" > $path/user.js #.................................................... rss_link=$( echo $1 | \ sed " s#picasa://downloadfeed/?url=## s/%25/%/g s/%21/!/g s/%23/#/g s/%24/\$/g s/%26/\&/g s/%27/'\''/g s/%28/(/g s/%29/)/g s/%2A/\*/g s/%2B/+/g s/%2C/,/g s/%2D/-/g s/%2E/\./g s/%2F/\//g s/%3A/:/g s/%3B/;/g s/%3D/=/g s/%3F/?/g s/%40/@/g s/%5B/\[/g s/%5C/\\\/ s/%5D/\]/g s/%5E/\^/g s/%5F/_/g s/%60/\`/g s/%7B/{/g s/%7C/|/g s/%7D/}/g s/%7E/~/g ") DOSSIER=`zenity --file-selection --title="Sélectionnez un dossier de destination" --directory --filename=/home/$USER/` if [ ! "$DOSSIER" ] then exit 1 else wget -q -O - "$rss_link" | sed -e 's/<pheed:imgsrc>/\n/g ; s/<\/pheed:imgsrc>/\n/g' | grep -E '^http' |sed '1d' > /tmp/picasa_down Npics=$(cat /tmp/picasa_down | wc -l) j=1 ( echo "#Téléchargement de l'album ..." for i in $(cat /tmp/picasa_down) do echo "#Téléchargement de l'album : photo $j/$Npics." echo "scale=2 ; $j/$Npics*100"| bc j=$((j+1)) (pidof zenity >/dev/null) && wget -q --directory-prefix="$DOSSIER" "$i" done echo "#Terminé" )| zenity --progress --title="Picasa" --percentage=0 --auto-kill --width=400 fi exit 0 [Edit 10/10/09] Ajout de guillemets à $DOSSIER pour gérer les espaces dans les noms de dossier. Dernière modification par GNU-max (Le 10/10/2009, à 09:04) Hors ligne lylambda Re : [script/python] Nautilus et picasaweb! Salut GNU-max, Tes scripts adaptés de celui de FTG sont exactement ce que je cherche. J'utilise jBrout pour gérer mes photos, ce logiciel étant parfait niveau tagage. Malheureusement le plugin d'export sur picasaweb ne fonctionne plus sur mon système dernièrement. [Pour info, j'obtiens ce message d'erreur : ] Erreur d'upload : 'PicasaWeb' object has no attribute '_PrepareConnection' Le 1er scripts seraient la solution idéale. Néanmoins, ma 1 ère tentative n'a aboutit qu'à un échec : # Dépend de : gdata, nautilus-actions, zenity--> Aprés vérification sur synaptic, j'ai bien ces paquets sur mon ubuntu # Dans Nautilus Action rentrer # Chemin : /usr/bin/python </chemni/vers/script> # Parametres : %M # Conditions : # Types Mime : image/* # Cocher : Apparaît si la selection contient plusieurs fichiers ou dossiers--> j'ai créé une nouvelle action selon les indications ci-dessus (en mettant évidement mon propre chemin de script, celui-ci étant exécutable) Au final, l'intitulé de l'action apparait bien lorsque je clique droit dans Nautilus mais rien ne se passe lorsque je tente de l'activer. Aurais-je oublié un élément important ? Dernière modification par lylambda (Le 04/07/2009, à 13:43) Hors ligne GNU-max Re : [script/python] Nautilus et picasaweb! Salut lylambda, Désolé pour la réponse tardive, je ne passe pas souvent sur le forum. En fait le paquet gdata n'est pas suffisant, il faut installer gdata manuellement comme l'a décrit FTG : Une fois ces trois paquets installés, allez voir du côté de ce lien: http://code.google.com/p/gdata-python-c … loads/list et telechargez la derniere version de gdate-py dans un endroit de votre partition /home/user. Décompresser avec la commande tar xvf puis bien lire INSTALL.TXT ca vaut le coup! Pour les plus préssés d'entre vous lancez tout de suite python setup.py en root. Dans l'INSTALL.TXT il est bien indiqué comment tester si l'installation a bien fonctionné! Merci d'avoir relevé ce point (je modifie la note d'installation en conséquence). J'espère que c'est ça. Dernière modification par GNU-max (Le 18/07/2009, à 16:34) Hors ligne lylambda Re : [script/python] Nautilus et picasaweb! Merci beaucoup pour le retour GNU-max ! Effectivement, si c'est une dépendance qui n'est pas à jour, cela explique le non-fonctionnement du script J'ai tenté de compiler gdata-2.0.0 comme indiquer mais apparemment je manque encore de connaissance. Quand je tape dans mon répertoire de décompression sudo python setup.py cela ne me donne que /usr/lib/python2.6/distutils/dist.py:266: UserWarning: Unknown distribution option: 'install_requires' warnings.warn(msg) usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: setup.py --help [cmd1 cmd2 ...] or: setup.py --help-commands or: setup.py cmd --help error: no commands supplied Par contre taper sudo python setup.py install à plus d'effet avec comme résultat /usr/lib/python2.6/distutils/dist.py:266: UserWarning: Unknown distribution option: 'install_requires' warnings.warn(msg) running install running build running build_py creating build creating build/lib.linux-i686-2.6 creating build/lib.linux-i686-2.6/atom copying src/atom/http.py -> build/lib.linux-i686-2.6/atom copying src/atom/data.py -> build/lib.linux-i686-2.6/atom copying src/atom/mock_service.py -> build/lib.linux-i686-2.6/atom copying src/atom/http_core.py -> build/lib.linux-i686-2.6/atom copying src/atom/mock_http_core.py -> build/lib.linux-i686-2.6/atom copying src/atom/core.py -> build/lib.linux-i686-2.6/atom copying src/atom/client.py -> build/lib.linux-i686-2.6/atom copying src/atom/token_store.py -> build/lib.linux-i686-2.6/atom copying src/atom/http_interface.py -> build/lib.linux-i686-2.6/atom copying src/atom/service.py -> build/lib.linux-i686-2.6/atom copying src/atom/auth.py -> build/lib.linux-i686-2.6/atom copying src/atom/url.py -> build/lib.linux-i686-2.6/atom copying src/atom/__init__.py -> build/lib.linux-i686-2.6/atom copying src/atom/mock_http.py -> build/lib.linux-i686-2.6/atom creating build/lib.linux-i686-2.6/gdata copying src/gdata/data.py -> build/lib.linux-i686-2.6/gdata copying src/gdata/gauth.py -> build/lib.linux-i686-2.6/gdata copying src/gdata/urlfetch.py -> build/lib.linux-i686-2.6/gdata copying src/gdata/test_config.py -> build/lib.linux-i686-2.6/gdata copying src/gdata/sample_util.py -> build/lib.linux-i686-2.6/gdata copying src/gdata/client.py -> build/lib.linux-i686-2.6/gdata copying src/gdata/service.py -> build/lib.linux-i686-2.6/gdata copying src/gdata/auth.py -> build/lib.linux-i686-2.6/gdata copying src/gdata/test_config_template.py -> build/lib.linux-i686-2.6/gdata copying src/gdata/test_data.py -> build/lib.linux-i686-2.6/gdata copying src/gdata/__init__.py -> build/lib.linux-i686-2.6/gdata creating build/lib.linux-i686-2.6/gdata/calendar copying src/gdata/calendar/service.py -> build/lib.linux-i686-2.6/gdata/calendar copying src/gdata/calendar/__init__.py -> build/lib.linux-i686-2.6/gdata/calendar creating build/lib.linux-i686-2.6/gdata/base copying src/gdata/base/service.py -> build/lib.linux-i686-2.6/gdata/base copying src/gdata/base/__init__.py -> build/lib.linux-i686-2.6/gdata/base creating build/lib.linux-i686-2.6/gdata/spreadsheet copying src/gdata/spreadsheet/service.py -> build/lib.linux-i686-2.6/gdata/spreadsheet copying src/gdata/spreadsheet/text_db.py -> build/lib.linux-i686-2.6/gdata/spreadsheet copying src/gdata/spreadsheet/__init__.py -> build/lib.linux-i686-2.6/gdata/spreadsheet creating build/lib.linux-i686-2.6/gdata/apps copying src/gdata/apps/service.py -> build/lib.linux-i686-2.6/gdata/apps copying src/gdata/apps/__init__.py -> build/lib.linux-i686-2.6/gdata/apps creating build/lib.linux-i686-2.6/gdata/apps/emailsettings copying src/gdata/apps/emailsettings/service.py -> build/lib.linux-i686-2.6/gdata/apps/emailsettings copying src/gdata/apps/emailsettings/__init__.py -> build/lib.linux-i686-2.6/gdata/apps/emailsettings creating build/lib.linux-i686-2.6/gdata/apps/migration copying src/gdata/apps/migration/service.py -> build/lib.linux-i686-2.6/gdata/apps/migration copying src/gdata/apps/migration/__init__.py -> build/lib.linux-i686-2.6/gdata/apps/migration creating build/lib.linux-i686-2.6/gdata/apps/groups copying src/gdata/apps/groups/service.py -> build/lib.linux-i686-2.6/gdata/apps/groups copying src/gdata/apps/groups/__init__.py -> build/lib.linux-i686-2.6/gdata/apps/groups creating build/lib.linux-i686-2.6/gdata/docs copying src/gdata/docs/service.py -> build/lib.linux-i686-2.6/gdata/docs copying src/gdata/docs/__init__.py -> build/lib.linux-i686-2.6/gdata/docs creating build/lib.linux-i686-2.6/gdata/codesearch copying src/gdata/codesearch/service.py -> build/lib.linux-i686-2.6/gdata/codesearch copying src/gdata/codesearch/__init__.py -> build/lib.linux-i686-2.6/gdata/codesearch creating build/lib.linux-i686-2.6/gdata/books copying src/gdata/books/service.py -> build/lib.linux-i686-2.6/gdata/books copying src/gdata/books/__init__.py -> build/lib.linux-i686-2.6/gdata/books creating build/lib.linux-i686-2.6/gdata/photos copying src/gdata/photos/service.py -> build/lib.linux-i686-2.6/gdata/photos copying src/gdata/photos/__init__.py -> build/lib.linux-i686-2.6/gdata/photos creating build/lib.linux-i686-2.6/gdata/exif copying src/gdata/exif/__init__.py -> build/lib.linux-i686-2.6/gdata/exif creating build/lib.linux-i686-2.6/gdata/geo copying src/gdata/geo/__init__.py -> build/lib.linux-i686-2.6/gdata/geo creating build/lib.linux-i686-2.6/gdata/media copying src/gdata/media/__init__.py -> build/lib.linux-i686-2.6/gdata/media creating build/lib.linux-i686-2.6/gdata/contacts copying src/gdata/contacts/service.py -> build/lib.linux-i686-2.6/gdata/contacts copying src/gdata/contacts/__init__.py -> build/lib.linux-i686-2.6/gdata/contacts creating build/lib.linux-i686-2.6/gdata/youtube copying src/gdata/youtube/service.py -> build/lib.linux-i686-2.6/gdata/youtube copying src/gdata/youtube/__init__.py -> build/lib.linux-i686-2.6/gdata/youtube creating build/lib.linux-i686-2.6/gdata/webmastertools copying src/gdata/webmastertools/service.py -> build/lib.linux-i686-2.6/gdata/webmastertools copying src/gdata/webmastertools/__init__.py -> build/lib.linux-i686-2.6/gdata/webmastertools creating build/lib.linux-i686-2.6/gdata/blogger copying src/gdata/blogger/data.py -> build/lib.linux-i686-2.6/gdata/blogger copying src/gdata/blogger/client.py -> build/lib.linux-i686-2.6/gdata/blogger copying src/gdata/blogger/service.py -> build/lib.linux-i686-2.6/gdata/blogger copying src/gdata/blogger/__init__.py -> build/lib.linux-i686-2.6/gdata/blogger creating build/lib.linux-i686-2.6/gdata/alt copying src/gdata/alt/appengine.py -> build/lib.linux-i686-2.6/gdata/alt copying src/gdata/alt/app_engine.py -> build/lib.linux-i686-2.6/gdata/alt copying src/gdata/alt/__init__.py -> build/lib.linux-i686-2.6/gdata/alt creating build/lib.linux-i686-2.6/gdata/oauth copying src/gdata/oauth/rsa.py -> build/lib.linux-i686-2.6/gdata/oauth copying src/gdata/oauth/__init__.py -> build/lib.linux-i686-2.6/gdata/oauth creating build/lib.linux-i686-2.6/gdata/tlslite copying src/gdata/tlslite/SessionCache.py -> build/lib.linux-i686-2.6/gdata/tlslite copying src/gdata/tlslite/Session.py -> build/lib.linux-i686-2.6/gdata/tlslite copying src/gdata/tlslite/errors.py -> build/lib.linux-i686-2.6/gdata/tlslite copying src/gdata/tlslite/FileObject.py -> build/lib.linux-i686-2.6/gdata/tlslite copying src/gdata/tlslite/X509CertChain.py -> build/lib.linux-i686-2.6/gdata/tlslite copying src/gdata/tlslite/mathtls.py -> build/lib.linux-i686-2.6/gdata/tlslite copying src/gdata/tlslite/api.py -> build/lib.linux-i686-2.6/gdata/tlslite copying src/gdata/tlslite/BaseDB.py -> build/lib.linux-i686-2.6/gdata/tlslite copying src/gdata/tlslite/TLSRecordLayer.py -> build/lib.linux-i686-2.6/gdata/tlslite copying src/gdata/tlslite/SharedKeyDB.py -> build/lib.linux-i686-2.6/gdata/tlslite copying src/gdata/tlslite/HandshakeSettings.py -> build/lib.linux-i686-2.6/gdata/tlslite copying src/gdata/tlslite/Checker.py -> build/lib.linux-i686-2.6/gdata/tlslite copying src/gdata/tlslite/X509.py -> build/lib.linux-i686-2.6/gdata/tlslite copying src/gdata/tlslite/constants.py -> build/lib.linux-i686-2.6/gdata/tlslite copying src/gdata/tlslite/TLSConnection.py -> build/lib.linux-i686-2.6/gdata/tlslite copying src/gdata/tlslite/messages.py -> build/lib.linux-i686-2.6/gdata/tlslite copying src/gdata/tlslite/__init__.py -> build/lib.linux-i686-2.6/gdata/tlslite copying src/gdata/tlslite/VerifierDB.py -> build/lib.linux-i686-2.6/gdata/tlslite creating build/lib.linux-i686-2.6/gdata/Crypto copying src/gdata/Crypto/test.py -> build/lib.linux-i686-2.6/gdata/Crypto copying src/gdata/Crypto/__init__.py -> build/lib.linux-i686-2.6/gdata/Crypto creating build/lib.linux-i686-2.6/gdata/Crypto/Cipher copying src/gdata/Crypto/Cipher/__init__.py -> build/lib.linux-i686-2.6/gdata/Crypto/Cipher creating build/lib.linux-i686-2.6/gdata/Crypto/Hash copying src/gdata/Crypto/Hash/HMAC.py -> build/lib.linux-i686-2.6/gdata/Crypto/Hash copying src/gdata/Crypto/Hash/MD5.py -> build/lib.linux-i686-2.6/gdata/Crypto/Hash copying src/gdata/Crypto/Hash/SHA.py -> build/lib.linux-i686-2.6/gdata/Crypto/Hash copying src/gdata/Crypto/Hash/__init__.py -> build/lib.linux-i686-2.6/gdata/Crypto/Hash creating build/lib.linux-i686-2.6/gdata/Crypto/Protocol copying src/gdata/Crypto/Protocol/Chaffing.py -> build/lib.linux-i686-2.6/gdata/Crypto/Protocol copying src/gdata/Crypto/Protocol/__init__.py -> build/lib.linux-i686-2.6/gdata/Crypto/Protocol copying src/gdata/Crypto/Protocol/AllOrNothing.py -> build/lib.linux-i686-2.6/gdata/Crypto/Protocol creating build/lib.linux-i686-2.6/gdata/Crypto/PublicKey copying src/gdata/Crypto/PublicKey/pubkey.py -> build/lib.linux-i686-2.6/gdata/Crypto/PublicKey copying src/gdata/Crypto/PublicKey/ElGamal.py -> build/lib.linux-i686-2.6/gdata/Crypto/PublicKey copying src/gdata/Crypto/PublicKey/DSA.py -> build/lib.linux-i686-2.6/gdata/Crypto/PublicKey copying src/gdata/Crypto/PublicKey/__init__.py -> build/lib.linux-i686-2.6/gdata/Crypto/PublicKey copying src/gdata/Crypto/PublicKey/RSA.py -> build/lib.linux-i686-2.6/gdata/Crypto/PublicKey copying src/gdata/Crypto/PublicKey/qNEW.py -> build/lib.linux-i686-2.6/gdata/Crypto/PublicKey creating build/lib.linux-i686-2.6/gdata/Crypto/Util copying src/gdata/Crypto/Util/randpool.py -> build/lib.linux-i686-2.6/gdata/Crypto/Util copying src/gdata/Crypto/Util/test.py -> build/lib.linux-i686-2.6/gdata/Crypto/Util copying src/gdata/Crypto/Util/RFC1751.py -> build/lib.linux-i686-2.6/gdata/Crypto/Util copying src/gdata/Crypto/Util/number.py -> build/lib.linux-i686-2.6/gdata/Crypto/Util copying src/gdata/Crypto/Util/__init__.py -> build/lib.linux-i686-2.6/gdata/Crypto/Util creating build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/Cryptlib_AES.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/Cryptlib_TripleDES.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/keyfactory.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/dateFuncs.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/PyCrypto_AES.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/PyCrypto_RSAKey.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/Python_RSAKey.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/RSAKey.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/codec.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/AES.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/hmac.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/OpenSSL_AES.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/Cryptlib_RC4.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/cryptomath.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/OpenSSL_RSAKey.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/compat.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/TripleDES.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/OpenSSL_TripleDES.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/Python_RC4.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/Python_AES.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/PyCrypto_RC4.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/xmltools.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/RC4.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/OpenSSL_RC4.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/__init__.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/PyCrypto_TripleDES.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/ASN1Parser.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/cipherfactory.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/jython_compat.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils copying src/gdata/tlslite/utils/rijndael.py -> build/lib.linux-i686-2.6/gdata/tlslite/utils creating build/lib.linux-i686-2.6/gdata/tlslite/integration copying src/gdata/tlslite/integration/IMAP4_TLS.py -> build/lib.linux-i686-2.6/gdata/tlslite/integration copying src/gdata/tlslite/integration/TLSAsyncDispatcherMixIn.py -> build/lib.linux-i686-2.6/gdata/tlslite/integration copying src/gdata/tlslite/integration/IntegrationHelper.py -> build/lib.linux-i686-2.6/gdata/tlslite/integration copying src/gdata/tlslite/integration/SMTP_TLS.py -> build/lib.linux-i686-2.6/gdata/tlslite/integration copying src/gdata/tlslite/integration/POP3_TLS.py -> build/lib.linux-i686-2.6/gdata/tlslite/integration copying src/gdata/tlslite/integration/TLSSocketServerMixIn.py -> build/lib.linux-i686-2.6/gdata/tlslite/integration copying src/gdata/tlslite/integration/TLSTwistedProtocolWrapper.py -> build/lib.linux-i686-2.6/gdata/tlslite/integration copying src/gdata/tlslite/integration/HTTPTLSConnection.py -> build/lib.linux-i686-2.6/gdata/tlslite/integration copying src/gdata/tlslite/integration/AsyncStateMachine.py -> build/lib.linux-i686-2.6/gdata/tlslite/integration copying src/gdata/tlslite/integration/ClientHelper.py -> build/lib.linux-i686-2.6/gdata/tlslite/integration copying src/gdata/tlslite/integration/__init__.py -> build/lib.linux-i686-2.6/gdata/tlslite/integration copying src/gdata/tlslite/integration/XMLRPCTransport.py -> build/lib.linux-i686-2.6/gdata/tlslite/integration creating build/lib.linux-i686-2.6/gdata/health copying src/gdata/health/service.py -> build/lib.linux-i686-2.6/gdata/health copying src/gdata/health/__init__.py -> build/lib.linux-i686-2.6/gdata/health creating build/lib.linux-i686-2.6/gdata/analytics copying src/gdata/analytics/service.py -> build/lib.linux-i686-2.6/gdata/analytics copying src/gdata/analytics/__init__.py -> build/lib.linux-i686-2.6/gdata/analytics creating build/lib.linux-i686-2.6/gdata/finance copying src/gdata/finance/service.py -> build/lib.linux-i686-2.6/gdata/finance copying src/gdata/finance/__init__.py -> build/lib.linux-i686-2.6/gdata/finance running install_lib running install_egg_info Removing /usr/local/lib/python2.6/dist-packages/gdata-2.0.0.egg-info Writing /usr/local/lib/python2.6/dist-packages/gdata-2.0.0.egg-info Mais ce ne doit pas être la solution vu qu'au final le script ne s'active toujours pas lorsque je le sélectionne par "clique-droit" dans Nautilus. Bref, je fais une pause pour ce soir et je me replongerais dans l'INSTALL.TXT un peu plus tard. En tout cas, si tu as tout lu jusqu'ici, tu es décidément serviable (et surtout courageux ;-) ! PS: si un petit paquet deb du dernier gdata traine dans le coin, dis lui que je lui offre un CDI illico :-p Hors ligne GNU-max Re : [script/python] Nautilus et picasaweb! Lorsque j'ai fait le script c'était gdata 1.3.3 mais je ne pense pas que ce soit ça. Dans l'INSTALL.TXT il y a une procédure pour tester l'installation : lancer ./tests/run_data_tests.py Essaye d'executer le script en ligne de commande pour voir si il y a un message d'erreur. python picasa_export.py <une image> Hors ligne lylambda Re : [script/python] Nautilus et picasaweb! Désolé de l'absence. Dans mon répertoire de compilation, j'avais bien fait le test ./tests/run_data_tests.py Le résultat a était positif d'après l'INSTALL. Par contre python picasa_export.py <une image> me renvois un message d'erreur, donc je suppose que ça vient de ma manière de rentrer l'action dans Nautilus. Comme j'ai bloqué à ce niveau, j'ai testé l'extension firefox "fire/universal uploader" indiqué précédemment par Axelap. Il me convient parfaitement mais cela me frustre de ne pas avoir réussi à faire fonctionner ton script >_<. Merci encore et promis, je referais un essai lorsque mes compétences se seront améliorées ! Hors ligne GNU-max Re : [script/python] Nautilus et picasaweb! C'est bien si t'as trouvé quelque chose qui te convient. Si tu décides de remettre les mains dans le cambouis, n'hésite pas. J'essayerais de t'aider du mieux que je peux. P.S. Par contre python picasa_export.py <une image> me renvois un message d'erreur, donc je suppose que ça vient de ma manière de rentrer l'action dans Nautilus. Au contraire, cette commande permet d'exécuter le script sans utiliser nautilus-actions, donc de s'affranchir des éventuelles erreurs liées à celui-ci. Par contre d'une manière générale, si on te demande d'essayer une commande c'est justement pour voir quelle erreur(s) s'affiche(nt) Je n'exlcus pas qu'il s'agissent d'une erreur de ma part. Dernière modification par GNU-max (Le 02/08/2009, à 21:11) Hors ligne Qid Re : [script/python] Nautilus et picasaweb! Salut. Non ça intéresse sûrement personne car Picasa c'est propriétaire et on préfère F-Spot qui fait très bien le boulot. au depart j'avais picasa sur ubuntu et quand je suis passé au 3 j'ai eu des mauvaises surprise alors je l'ai désinstallé car entre temp en plus j'avais découvert que f-spot effectivement faisait aussi bine le boulot (pas moyen de mettre de transfere en standby mais bon) enfin voila par contre c'est vrais que la gestion de fspot ne me plaisant pas dutout je ne m'en sert vraiement que pour les transfere vers picasa et dois le revider à chaque fois ... bref faudra que je teste ton truc mais la méthode d'install me plait pas trop "GNU/Linux c'est que du bon mais M$ Windows c'est pas si mal" bientôt 1 Gigabyte P35G W$ & UBUNTU pour moi + Ubuntu-gnome & KLXUbuntu + mint mate & cinamon pour démos1 Zalman de 120Go pour le GUL dont je suis le dépanneur de référence1 tablettes ASUS non rootée : Android 4.2.2 | doc.ubuntu-fr/Qid Hors ligne YvanD Re : [script/python] Nautilus et picasaweb! Ce serait super de créer un clone (enfin de s'inspirer) de nautilus-flirck-uploader mais pour picasa. Hors ligne elephant Re : [script/python] Nautilus et picasaweb! bonjour à tous Je ne suis pas sûre que le problème que je rencontre est le même que ceux évoqués plus haut : depuis plus d'un an, j'ai une galerie picasa gratuite qui me sert de vitrine pour exposer mes peintures. J'ai donc besoin de poster des photos dessus très régulièrement. Or, impossible de faire ça depuis mon ordi (sous Ubuntu). je dois aller dans des internet café. kafkaïen : je clique sur "transférer des fichiers" je tombe sur "Picasa Albums Web ne comporte pas encore de programme de transfert propre à Linux. Pour tenter de transférer des photos avec notre formulaire de transfert via le Web, cliquez sur le bouton Transférer des photos, à droite." J'appuie donc, on me dit de me connecter (alors que je suis connectée), je clique donc sur "me connecter" et je tombe sur "La fonctionnalité que vous avez demandée est actuellement indisponible. Veuillez réessayer ultérieurement." J'ai lu vos échanges, mais je suis une femme des cavernes : je ne m'y connais pas suffisamment en informatiques pour engager les procédures que vous décrivez. en résumé, je cherche un moyen compréhensible pour seulement exporter des fichiers jpeg depuis mon ordi vers Picasa. des suggestions ? merci Hors ligne GNU-max Re : [script/python] Nautilus et picasaweb! Bonjour, Vous avez bien fait de lire les sujets du forum sur picasa. Mais peut-être auriez vous dû créer un nouveau sujet car celui-ci est ancien et contient des informations sûrement obsolètes. Je n'utilise pas Picasa et je ne peux pas vous aider sur votre problème avec l'interface web de Picasa. Pour utiliser Picasa avec Ubuntu vous pouvez essayer les logiciels Shotwell (normalement installé par défaut sur ubuntu) ou Conduit. (source : askubuntu) Hors ligne Hors ligne
I do not have access to ArcMap 10, only 9.3, but I expect that it won't be very different from this. You can create a simple script in Python, that checks your attribute field for different values, and then, for each of them runs a SELECT operation to your original Shapefile. If you are not familiar with python scripting, all you need to do is open you IDLE (the python GUI) create a new file, and copy the code below. After adapting the code for your my_shapefile, outputdir and my_attribute it should work. # Script created to separate one shapefile in multiple ones by one specific # attribute # Example for a Inputfile called "my_shapefile" and a field called "my_attribute" import arcgisscripting # Starts Geoprocessing gp = arcgisscripting.create(9.3) gp.OverWriteOutput = 1 #Set Input Output variables inputFile = u"C:\\GISTemp\\My_Shapefile.shp" #<-- CHANGE outDir = u"C:\\GISTemp\\" #<-- CHANGE # Reads My_shapefile for different values in the attribute rows = gp.searchcursor(inputFile) row = rows.next() attribute_types = set([]) while row: attribute_types.add(row.my_attribute) #<-- CHANGE my_attribute to the name of your attribute row = rows.next() # Output a Shapefile for each different attribute for each_attribute in atribute_types: outSHP = outDir + each_attribute + u".shp" print outSHP gp.Select_analysis (inputFile, outSHP, "\"my_attribute\" = '" + each_attribute + "'") #<-- CHANGE my_attribute to the name of your attribute del rows, row, attribute_types, gp #END
In a decorator method, you can list arguments of the original method in this way: import inspect, itertools def my_decorator(): def decorator(f): def wrapper(*args, **kwargs): # if you want arguments names as a list: args_name = inspect.getargspec(f)[0] print(args_name) # if you want names and values as a dictionary: args_dict = dict(itertools.izip(args_name, args)) print(args_dict) # if you want values as a list: args_values = args_dict.values() print(args_values) If the **kwargs are important for you, then it will be a bit complicated: def wrapper(*args, **kwargs): args_name = list(OrderedDict.fromkeys(inspect.getargspec(f)[0] + kwargs.keys())) args_dict = OrderedDict(list(itertools.izip(args_name, args)) + list(kwargs.iteritems())) args_values = args_dict.values() Example: @my_decorator() def my_function(x, y, z=3): pass my_function(1, y=2, z=3, w=0) # prints: # ['x', 'y', 'z', 'w'] # {'y': 2, 'x': 1, 'z': 3, 'w': 0} # [1, 2, 3, 0]
I have the following code: query = Entry.objects.all() print 'authors ' + repr([x.id for x in authors]) print 'query ' + repr(query) print 'query ids ' + repr([x.author.id for x in query]) query.filter(author__in=authors) print 'filtered ids ' + repr([x.author.id for x in query]) Which outputs this: authors [2] query [<Entry: test>, <Entry: test>] query ids [2, 3] filtered ids [2, 3] Obviously, 3 is not in [2]. So, why filtered ids are [2, 3] and not just [2]? Regards
I am tring to implement google maps using the new google maps api v2 and for some reason i don't see a map. I think that the problem is those two lines of error when i run it on the emulator: E/ActivityThread( 1373): Failed to find provider info for com.google.settings E/ActivityThread( 1373): Failed to find provider info for com.google.android.gsf .gservices when i run the application on the device the following error is produced: Could not find class 'maps.j.k', referenced from method map.y.ae.a My problem looks the same as in this link: http://android-er.blogspot.co.il/2012/12/google-maps-android-api-v2-with-blank.html There it's says that the problem may be my key so i went and reproduced it using the following tutorial: http://android-er.blogspot.co.il/2012/12/displaying-sha1-certificate-fingerprint.html. but this still didn't helped me. the support files are of course add to the project as well as the Google play services lib. I see the same result on the emulator (after adding manually the two file that allow using the google map v2 on the emulator) as well as on the motorola Defy running android 2.2. Maybe I am using the wrong debug.keystore? I am using the one in my User.android folder.If so then how do i find the right file? EDIT: My eclipse says that my debug key is in the default folder. So i renamed the debug.keystore file and ran the Eclipse to recreate it all over again. That resulted in producing a new SHA1 key. I used it to create a new Google Maps API v2 key but the result is still the same. I'm still unable to see the map. EDIT2: Stupid me, I chose Google Map API V2 instead of Google Maps Android API V2. This question can be closed. Thanks. Here are all the code files: xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <fragment xmlns:map="http://schemas.android.com/apk/res-auto" android:id="@+id/map" android:name="com.google.android.gms.maps.SupportMapFragment" android:layout_width="match_parent" android:layout_height="match_parent" map:cameraBearing="112.5" map:cameraTargetLat="-33.796923" map:cameraTargetLng="150.922433" map:cameraTilt="30" map:cameraZoom="13" map:mapType="normal" map:uiCompass="false" map:uiRotateGestures="true" map:uiScrollGestures="false" map:uiTiltGestures="true" map:uiZoomGestures="true" /> </LinearLayout> Map Fragmentactivity class: package com.eadesign.skygiraffefinalv2; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.maps.GoogleMap; import android.os.Bundle; import com.google.android.gms.maps.*; import android.widget.ImageView; import android.widget.TextView; public class Map extends android.support.v4.app.FragmentActivity { private GoogleMap map; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.map); if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()) == 0) { map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); // map.setMapType(GoogleMap.MAP_TYPE_HYBRID); } }} manifest file: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.eadesign.skygiraffefinalv2" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17"/> <permission android:name="com.eadesign.skygiraffefinalv2.permission.MAPS_RECEIVE" android:protectionLevel="signature"/> <uses-permission android:name="com.eadesign.skygiraffefinalv2.permission.MAPS_RECEIVE"/> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-feature android:glEsVersion="0x00020000" android:required="true"/> <application android:allowBackup="true" android:icon="@drawable/sgicon90" android:label="@string/app_name" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"> <activity android:name=".Map" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="My key"/> </application> log from logcat: ent.category.LAUNCHER] flg=0x10000000 cmp=com.eadesign.skygiraffefinalv2/.Map u= 0} from pid 1362 W/WindowManager( 148): Failure taking screenshot for (246x410) to layer 21010 D/AndroidRuntime( 1362): Shutting down VM I/ActivityManager( 148): Start proc com.eadesign.skygiraffefinalv2 for activity com.eadesign.skygiraffefinalv2/.Map: pid=1373 uid=10046 gids={3003, 1015, 1028} D/dalvikvm( 1373): Not late-enabling CheckJNI (already on) D/dalvikvm( 1362): GC_CONCURRENT freed 99K, 77% free 483K/2048K, paused 1ms+1ms, total 13ms D/jdwp ( 1362): Got wake-up signal, bailing out of select D/dalvikvm( 1362): Debugger has detached; object registry had 1 entries E/jdwp ( 1373): Failed sending reply to debugger: Broken pipe D/dalvikvm( 1373): Debugger has detached; object registry had 2 entries E/Trace ( 1373): error opening trace file: No such file or directory (2) D/dalvikvm( 1373): GC_CONCURRENT freed 204K, 3% free 8264K/8519K, paused 89ms+6m s, total 161ms D/dalvikvm( 1373): WAIT_FOR_CONCURRENT_GC blocked 33ms E/ActivityThread( 1373): Failed to find provider info for com.google.settings E/ActivityThread( 1373): Failed to find provider info for com.google.settings D/dalvikvm( 1373): GC_CONCURRENT freed 312K, 5% free 8471K/8839K, paused 82ms+10 5ms, total 268ms E/ActivityThread( 1373): Failed to find provider info for com.google.android.gsf .gservices E/ActivityThread( 1373): Failed to find provider info for com.google.android.gsf .gservices D/dalvikvm( 1373): GC_CONCURRENT freed 227K, 4% free 8797K/9095K, paused 91ms+11 0ms, total 300ms D/libEGL ( 1373): Emulator without GPU support detected. Fallback to software r enderer. I/Choreographer( 1373): Skipped 54 frames! The application may be doing too muc h work on its main thread. D/gralloc_goldfish( 1373): Emulator without GPU emulation detected. D/libEGL ( 1373): loaded /system/lib/egl/libGLES_android.so I/ActivityManager( 148): Displayed com.eadesign.skygiraffefinalv2/.Map: +3s545ms I/Choreographer( 1373): Skipped 75 frames! The application may be doing too muc h work on its main thread.
I am new to python and I am practicing writing classes in terminal I wrote following >>> class Calculator: ... def calculate(self,expression): ... self.value=eval(expression) ... class Talker: as soon as I typed class Talker: as above I get following error File "<stdin>", line 4 class Talker: ^ IndentationError: unindent does not match any outer indentation level I am unable to understand why is this indentation error coming? How do I proceed from here. Based on updates I corrected the error and now I wrote the following class Calculator: ... def calculate(self,evaluate): ... self.value=eval(expression) ... class Talker: ... def talk(self): ... print 'Hi, my value is ', self.value ... class TalkingCalculator(Calculator,Talker): ... pass ... Now I get the error Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 4, in Calculator File "<stdin>", line 7, in Talker NameError: name 'Calculator' is not defined What is this error what did I missed here?
I'm not 100% on this, but doing an outer join and dropping the NAs is the same as an inner join. So in the case of no matching indicies, you just get an empty dataframe. If we modify your example to include one matching record, this appears to be the case: import pandas as pd d1 = pd.DataFrame({ 'i1': [1, 2, 2], 'i2': [1, 1, 2], 'a': [10,20,30]}).set_index(['i1', 'i2']) d2 = pd.DataFrame({ 'i1': [1, 3], 'i2': [1, 2], 'b': [40, 50]}).set_index(['i1', 'i2']) d3 = d1.join(d2, how='outer').dropna() d4 = d1.join(d2, how='inner') Which gives: In [9]: d3 Out[9]: a b i1 i2 1 1 10 40 In [10]: d4 Out[10]: a b i1 i2 1 1 10 40 And so after the outer join + dropna(), you can see how many rows d3 and go from there. Using your original example: import pandas as pd d1 = pd.DataFrame({ 'i1': [1, 2, 2], 'i2': [1, 1, 2], 'a': [10,20,30]}).set_index(['i1', 'i2']) d2 = pd.DataFrame({ 'i1': [3, 3], 'i2': [1, 2], 'b': [40, 50]}).set_index(['i1', 'i2']) d3 = d1.join(d2, how='outer').dropna() print(d3.shape) # no error, shows "(0, 2)"
Google Summer of Code 2011 application for openSUSE Project by Alex Eftimie. AppStream is an initiative of cross-distro collaboration, which aims creating an unified software metadata database, and also a centralized OCS (Open Collaboration Services) user-contributed content database. By this project, a PackageKit backend and integration with constructed metadata will be added to Software Center, providing a solid software management client for AppStream. Software Center (SC) has been proposed as a client for AppStream because it is an established and stable project (reaching version 3.2 and replacing other package management tools in ubuntu's default install). It also has cool features such as Zeitgeist (usage stats) integration, a recommendation system, featured applications, ratings and comments. The current backend of SC is AptDaemon, that takes care of package management over a D-Bus interface. AptDaemon has been designed with an architecture similar to PackageKit, one reason beside not using PackageKit in the first time being incompatibility between it and the apt installation progress (a transaction being uninterruptible, configuration file conflicts cannot be easily solved). PackageKit is project aiming to unify the distribution package management system, in a transparent way for the user. It consists of a daemon and distro-specific package management backends. PackageKit exposes over D-Bus an interface backend agnostic with methods for install/removing/upgrading packages. Beside package installation, the AppStream architecture shows also Mirror, Compose server and OCS server components. The Compose server extracts metadata from desktop files inside packages (this is later reffered as distromatch), construct it and make it available to the Mirror. A Mirror should provide to the client (SC) the metadata and icons retrieved from the Compose server. Existing metadata, used for package installation/removal/dependencies, should not be altered. Development of another client for AppStream has already started (openSUSE App Store or Bretzn). The client, based on MeeGo Garage and libattica is developed using the Qt framework and fits best the KDE desktop. Without duplicating the effort, Software Center can be the Gtk+, GNOME client. Andrei is a begginer to openSUSE, and doesn't know nothing about software packages. The distribution ships with a branded Software Center, PackageKit-enabled (with rpm and zypp backends). Andrei can easily find and manage software applications. Software Center has been designed and developed to fit Ubuntu. To change it is not an easy task, there will be features needing to be disabled/hidden when SC will run on other distribution (for example authorization and purchasing applications). This should be addressed by keeping in touch with SC upstream, and pushing changes gradually, so that they are accepted. Making Software Center and PackageKit work together may raise problems of design compatibility. For example, if during a package installation, a conflict appears and PackageKit solves this conflict asking the user to chose and, in a similar situation, AptDaemon would avoid prompting the user - changes would be needed in Software Center GUI or in PackageKit. This kind of problems will appear after playing a little more with code/reading documentation and familiarizing with PackageKit workflow, and should be resolved using mentor and community feedback. After analysing the source code, and discussing with the developers, this is a simplified design scheme: Two main changes are required: first, use the install/remove PK backend, and second, create a xapian database equivalent with the current apt-xapian-index, to populate it with data from distromatch. The first, PK install backend, should be straightforward to implement, due to similarities between AptDeamon and PackageKit. Work has already been started in Michael Vogt pk-abstraction branch. The backend will extend a BaseInstallBackend, implementing the following methods: class BaseInstallBackend(object): def upgrade(self, pkgname, appname): def remove(self, pkgname, appname): def remove_multiple(self, pkgnames, appnames): def install(self, pkgname, appname): def install_multiple(self, pkgnames, appnames): def apply_changes(self, pkgname, appname): def reload(self, sources_list): The second, Xapian database populated with AppStream distromatch data, will need proper design and integration. Currently, a distromatch mirror can provide a tar.gz archive containing xml metadata and icons. These should be parsed and put into the database SC uses to present applications to the user. Currently the search database (Xapian) is built from apt using this function (in softwarecenter/db/update.py): def update(db, cache, datadir=APP_INSTALL_PATH): # index desktop files in $datadir/desktop/*.desktop update_from_app_install_data(db, cache, datadir) # index files in /var/lib/apt/lists/*AppInfo update_from_var_lib_apt_lists(db, cache) First call fetches application information from .desktop files. This should be replaced by getting this data from the Mirror. The second call updates db with data stored in an apt specific format. This must be replaced by a PackageKit method of getting the package information for the current repository backend. Another functionality needed is downloading distromatch data from the Mirror.Also, SC design requires an Package Information class (currently implemented as AptCache), with the following interface: class BasePkgInfo(object): def is_installed(self, pkgname): def is_available(self, pkgname): def get_addons(self, pkgname, ignore_installed): def open(self): def ready(self): This will be implemented directly by wrapping over PackageKit interface for package information. In addition to these main changes, there will be many small things scatterred around the code, relying on the current ubuntu-only setup, that will need to be discovered and fixed. To fulfill these requirements, I will folow this timeline (the timing is estimative): prior official coding period milestone 1 (first and 2nd week) milestone 2 (3rd to 5th week) python-packagekit bindings;BaseInstallBackend class; AptDaemon and PackageKitInstallBackend pass these tests; milestone 3 (6th to 8th week) BasePkgInfo class; milestone 4 (9th week - ) Distro class, and integrate it with the previous two new backend classes. After the 4th milestone, work should continue on integrating the resulted software with openSUSE distro, testing the resulted code and fixing bugs. I think that using a higher level interface (PK Python bindings) for interacting with D-Bus, is a good idea; when PK D-Bus protocol changes, the bindings will also be updated upstream, and Software Center will benefit from this changes aswell, without requiring modifying the source code. My development will rely on feature-based iterations. Each iteration will be completed when the features are implemented, and tests written for them pass. All changes should be made so that upstream adoption will be easy. I plan to use Bazaar as a version control system, since this is the VCS used by Software Center, and using it will make easier pushing my changes back to the main development branch. If, for some reason, bazaar isn't agreated, my backup VCS is git. I am a student at the University Politehnica of Bucharest, in the first year of the Networks Security Master. For five years I've been using Linux as my primary operating system, and I'm passionate about Free Software and Open Source. Being a ROSEdu[1] member, I have gained experience on team work, nettiquette and community values. My programming language of choice is Python, but I also do C , bash and PHP. Another areas of interest lately, are system administration and distribution packaging. I have basic to intermediate knowledge of GTK+ and the GNOME desktop; one project I started is a thumbnailer for .deb packages[2]; my Graduation Thesis project was a PyGTK application (an paper exam generator and automatic corrector - using OpenCV); unfortunately that project isn't open yet. My Python experience can be also reflected by my contribution to World of USO[3] open source project. This is a web based game for first year students, helping them check their gained knowledge in a fun way. I have participated at designing a new architecture mapped on Django, and wrote most of the actual code. I watched Software Center grow, from the beginnings. On the first release, I contributed the Romanian translation. Some time ago, I also used a snapshot of it as a reference for understanding how a PyGTK application should work, where should the files be placed in the filesystem directory, and other best practices. Recently, I proposed a few patches to SC [4], [5] and [6]. The Software Center Team is a great team and responded positively to my questions; I'm keeping contact with them via IRC and email. What I am expecting to learn during this summer programme, is: working with the community, participating at an cross-distro initiative, using technologies (such as Xapian, D-Bus), and great open source experience. I am confident that I have the required skills and enthusiasm to be the perfect student for this project. For me, this summer is reserved for GSoC; since always I wanted to apply, but I have never got an available summer. Either working on something else, either travelling, but never free to be part of the programme. This GSoC project will be my main activity during the summer; the first two weeks (May 23 to June 5) it will be the Exam period at the university, so I estimate having up to 20 hours per week left for working on GSoC, and maybe taking a few days off); after that, I can commit for a 40 hours per week work time. [1] Romanian Open Source Education [2] http://launchpad.net/deb-thumbnailer [3] http://projects.rosedu.org/projects/wousodjango/ [4] #704719 [5] #575688 [6] #744655
I have two vectors u and v. Is there a way of finding a quaternion representing the rotation from u to v? Quaternion q; vector a = crossproduct(v1, v2) q.xyz = a; q.w = sqrt((v1.Length ^ 2) * (v2.Length ^ 2)) + dotproduct(v1, v2) Don't forget to normalize q Richard is right about there not being a unique rotation, but the above should give the "shortest arc". Which is probably what you need. Half-Way Vector Solution I came up with the solution that I believe Imbrondir was trying to present (albeit with a minor mistake, which was probably why sinisterchipmunk had trouble verifying it). Given that we can construct a quaternion representing a rotation around an axis like so: q.w == cos(angle / 2) q.x == sin(angle / 2) * axis.x q.y == sin(angle / 2) * axis.y q.z == sin(angle / 2) * axis.z And that the dot and cross product of two normalized vectors are: dot == cos(theta) cross.x == sin(theta) * perpendicular.x cross.y == sin(theta) * perpendicular.y cross.z == sin(theta) * perpendicular.z Seeing as a rotation from One solution is to compute a vector half-way between There is a special case, where Pseudo code follows (obviously, in reality the special case would have to account for floating point inaccuracies -- probably by checking the dot products against some threshold rather than an absolute value). Also note that there is // N.B. the arguments are _not_ axis and angle, but rather the // raw scalar-vector components. Quaternion(float w, Vector3 xyz); Quaternion(float w, float x, float y, float z); Quaternion(Vector3 axis, float angle_degrees); Quaternion get_rotation_between(Vector3 u, Vector3 v) { // It is important that the inputs are of equal length when // calculating the half-way vector. u = normalized(u); v = normalized(v); // Unfortunately, we have to check for when u == -v, as u + v // in this case will be (0, 0, 0), which cannot be normalized. if (u == -v) { // 180 degree rotation around any orthogonal vector Vector3 other = (abs(dot(u, X_AXIS)) < 1.0) ? X_AXIS : Y_AXIS; return Quaternion(normalized(cross(u, other)), 180); } Vector3 half = normalized(u + v); return Quaternion(dot(u, half), cross(u, half)); } Half-Way Quaternion Solution This is actually the solution presented in the accepted answer, and it seems to be marginally faster than the half-way vector solution (~20% faster by my measurements, though don't take my word for it). I'm adding it here in case others like myself are interested in an explanation. Essentially, instead of calculating a quaternion using a half-way vector, you can calculate the quaternion which results in twice the required rotation (as detailed in the other solution), and find the quaternion half-way between that and zero degrees. As I explained before, the quaternion for double the required rotation is: q.w == dot(u, v) q.xyz == cross(u, v) And the quaternion for zero rotation is: Calculating the half-way quaternion is simply a matter of summing the quaternions and normalizing the result, just like with vectors. However, as is also the case with vectors, the quaternions must have the same magnitude, otherwise the result will be skewed towards the quaternion with the larger magnitude. A quaternion constructed from the dot and cross product of two vectors will have the same magnitude as those products: q.w = dot(u, v) + sqrt(length_2(u) * length_2(v)) q.xyz = cross(u, v) And then normalize the result. Pseudo code follows: Quaternion get_rotation_between(Vector3 u, Vector3 v) { float k_cos_theta = dot(u, v); float k = sqrt(length_2(u) * length_2(v)); if (k_cos_theta / k == -1) { // 180 degree rotation around any orthogonal vector Vector3 other = (abs(dot(u, X_AXIS)) < 1.0) ? X_AXIS : Y_AXIS; return Quaternion(normalized(cross(u, other)), 180); } return normalized(Quaternion(k_cos_theta + k, cross(u, v))); } The problem as stated is not well-defined: there is not a unique rotation for a given pair of vectors. Consider the case, for example, where u = I'm not much good on Quaternion. However I struggled for hours on this, and could not make Polaris878 solution work. I've tried pre-normalizing v1 and v2. Normalizing q. Normalizing q.xyz. Yet still I don't get it. The result still didn't give me the right result. In the end though I found a solution that did. If it helps anyone else, here's my working (python) code: def diffVectors(v1, v2): """ Get rotation Quaternion between 2 vectors """ v1.normalize(), v2.normalize() v = v1+v2 v.normalize() angle = v.dot(v2) axis = v.cross(v2) return Quaternion( angle, *axis ) A special case must be made if v1 and v2 are paralell like v1 == v2 or v1 == -v2 (with some tolerance), where I believe the solutions should be Quaternion(1, 0,0,0) (no rotation) or Quaternion(0, *v1) (180 degree rotation) From algorithm point of view , the fastest solution looks in pseudocode Quaternion shortest_arc(const vector3& v1, const vector3& v2 ) { // input vectors NOT unit Quaternion q( cross(v1, v2), dot(v1, v2) ); // reducing to half angle q.w += q.magnitude(); // 4 multiplication instead of 6 and more numerical stable // handling close to 180 degree case //... code skipped return q.normalized(); // normalize if you need UNIT quaternion } Be sure that you need unit quaternions (usualy, it is required for interpolation). NOTE: Nonunit quaternions can be used with some operations faster than unit.
#1251 Le 05/02/2012, à 19:35 chaoswizard Re : TVDownloader: télécharger les médias du net ! Voilà, la version 0.5 est arrivée dans le PPA ! Ubuntu ==> Debian ==> Archlinux Hors ligne #1252 Le 05/02/2012, à 20:08 ynad Re : TVDownloader: télécharger les médias du net ! @Greg_lattice comme f.x0 avec la même ligne de commande tout fonctionne sans blème... Hors ligne #1253 Le 06/02/2012, à 19:45 grandtoubab Re : TVDownloader: télécharger les médias du net ! bonsoir Un message d'erreur final alors que le téléchargement est "apparement" complet @ubuntu-desktop:~/Vidéos$ pluzzdl http://www.pluzz.fr/faites-entrer-l-accuse.html [INFO ] PluzzDL.py Début du téléchargement des fragments [CRITICAL] PluzzDL.py Impossible de charger la vidéo @ubuntu-desktop:~/Vidéos$ ls -alrt faites* -rw-r--r-- 1 abc root 265409490 2012-02-06 18:03 faites-entrer-l-accuse.flv @ubuntu-desktop:~/Vidéos$ Malheureusement fichier incomplet, smplayer affiche une durée de 1h10mn 50 s mais la lecture s'arrête à 29 mn 11 s jusqu'à là tout va bien @ubuntu-desktop:~/Vidéos$ pluzzdl -f -b http://www.pluzz.fr/faites-entrer-l-accuse.html [INFO ] PluzzDL.py Début du téléchargement des fragments [INFO ] PluzzDL.py Avancement : 1 % [INFO ] PluzzDL.py Avancement : 2 % [INFO ] PluzzDL.py Avancement : 3 % [INFO ] PluzzDL.py Avancement : 4 % [INFO ] PluzzDL.py Avancement : 5 % [INFO ] PluzzDL.py Avancement : 6 % [INFO ] PluzzDL.py Avancement : 7 % [INFO ] PluzzDL.py Avancement : 8 % [INFO ] PluzzDL.py Avancement : 9 % [INFO ] PluzzDL.py Avancement : 10 % [INFO ] PluzzDL.py Avancement : 11 % [INFO ] PluzzDL.py Avancement : 12 % [INFO ] PluzzDL.py Avancement : 13 % [INFO ] PluzzDL.py Avancement : 14 % [INFO ] PluzzDL.py Avancement : 15 % [INFO ] PluzzDL.py Avancement : 16 % [INFO ] PluzzDL.py Avancement : 17 % [INFO ] PluzzDL.py Avancement : 18 % [INFO ] PluzzDL.py Avancement : 19 % [INFO ] PluzzDL.py Avancement : 20 % [INFO ] PluzzDL.py Avancement : 21 % [INFO ] PluzzDL.py Avancement : 22 % [INFO ] PluzzDL.py Avancement : 23 % [INFO ] PluzzDL.py Avancement : 24 % [INFO ] PluzzDL.py Avancement : 25 % [INFO ] PluzzDL.py Avancement : 26 % [INFO ] PluzzDL.py Avancement : 27 % [INFO ] PluzzDL.py Avancement : 28 % [INFO ] PluzzDL.py Avancement : 29 % [INFO ] PluzzDL.py Avancement : 30 % [INFO ] PluzzDL.py Avancement : 31 % ça se gâte [INFO ] PluzzDL.py Avancement : 32 %[CRITICAL] PluzzDL.py Impossible de charger la vidéo Dernière modification par grandtoubab (Le 06/02/2012, à 20:25) 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 #1254 Le 06/02/2012, à 23:13 k3c Re : TVDownloader: télécharger les médias du net ! Bizarre, pour moi le même téléchargement est OK. Hors ligne #1255 Le 07/02/2012, à 16:30 bibichouchou Re : TVDownloader: télécharger les médias du net ! Bonjour à tous, 1/ j'arrive un peu tard mais voici mon grain de sel pour obtenir la progression. La taille finale du fichier est indiquée dans l'en-tête du fichier flv. On peut y accéder avec flvtool2 comme ceci: flvtool2 -P video_name.flv|grep filesize|grep -oE [0-9]\{1,\} On peut donc comparer la taille actuelle à la taille attendue pour obtenir la progression. Ce n'est pas complétement précis. D'après ce que j'ai remarqué, on peut s'attendre à des décalages de l'ordre de 1 ou 2%. J'imagine que faire appel à un programme tiers n'est pas très pythonique (corrigez-moi, je débute en python) mais je pense que l'on peut écrire un lecteur python des méta-données du flv. 2/ Ensuite, je voudrais savoir s'il est possible de rajouter une option "reprendre", dans le cas d'une connexion défaillante, histoire de ne pas télécharger encore et encore les mêmes fragments. Je ne pense pas que le programme le fasse actuellement et je ne sais pas si on peut le mettre en oeuvre facilement. Initialement, je m'étais écrit un code bash pour récupérer les émissions de pluzz, qui sauvegardait les fragments séparément et concaténait le tout à la fin, approche qui permet de savoir quel est le dernier fragment téléchargé. Le programme de chaoswizard concatène au fur et à mesure les fragments. 3/ est-ce que quelqu'un s'est penché sur le site de rattrapage de bfmtv et a pondu un joli programme ? je m'y suis cassé les dents. Bonne journée à tous ! Dernière modification par bibichouchou (Le 07/02/2012, à 16:50) Hors ligne #1256 Le 07/02/2012, à 16:32 Greg_lattice Re : TVDownloader: télécharger les médias du net ! @Greg_lattice comme f.x0 avec la même ligne de commande tout fonctionne sans blème... Merci je sais pourquoi ça ne fonctionne pas... C'est parce que je suis à l'étranger. Avant on pouvait accéder aux émissions de pluzz, mais apparement depuis 2semaines peu à peu on interdit aux expatriés l'accès à pluzz! Merci quand même!! Hors ligne #1257 Le 07/02/2012, à 18:28 grandtoubab Re : TVDownloader: télécharger les médias du net ! Bizarre, pour moi le même téléchargement est OK. Pire encore @ubuntu-desktop:~/Vidéos$ pluzzdl http://www.pluzz.fr/faites-entrer-l-accuse.html Traceback (most recent call last): File "/usr/share/pluzzdl/main.py", line 74, in <module> PluzzDL( args[ 0 ], options.fragments, options.proxy, options.progressbar ) File "/usr/share/pluzzdl/PluzzDL.py", line 70, in __init__ self.manifest = self.navigateur.getFichier( self.manifestURLToken ) File "/usr/share/pluzzdl/Navigateur.py", line 48, in getFichier page = self.urlOpener.open( requete, timeout = self.timeOut ) File "/usr/lib/python2.7/urllib2.py", line 400, in open response = meth(req, response) File "/usr/lib/python2.7/urllib2.py", line 513, in http_response 'http', request, response, code, msg, hdrs) File "/usr/lib/python2.7/urllib2.py", line 438, in error return self._call_chain(*args) File "/usr/lib/python2.7/urllib2.py", line 372, in _call_chain result = func(*args) File "/usr/lib/python2.7/urllib2.py", line 521, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 404: Not Found @ubuntu-desktop:~/Vidéos$ python --version Python 2.7.2+ @ubuntu-desktop:~/Vidéos$ Dernière modification par grandtoubab (Le 07/02/2012, à 18:35) 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 #1258 Le 07/02/2012, à 18:42 k3c Re : TVDownloader: télécharger les médias du net ! J'ai la version 0.5 de pluzzdl, est-ce ton cas ? Hors ligne #1259 Le 07/02/2012, à 18:49 grandtoubab Re : TVDownloader: télécharger les médias du net ! J'ai la version 0.5 de pluzzdl, est-ce ton cas ? Clic sur l'image que j'ai posté et tu verras que oui. Mais je relance avec l'option -f et ca commence à télécharger (http://code.google.com/p/tvdownloader/wiki/pluzzdl) @ubuntu-desktop:~/Vidéos$ pluzzdl -f http://www.pluzz.fr/faites-entrer-l-accuse.html [INFO ] PluzzDL.py Début du téléchargement des fragments 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 #1260 Le 07/02/2012, à 18:53 k3c Re : TVDownloader: télécharger les médias du net ! @ bibichouchou Pour 3) Récupérer les replay de BFM TV est faisable, vu que Captvty le fait. http://rectv.free.fr/viewforum.php?f=17 Je crois surtout que personne ne s'est penché dessus pour l'instant Hors ligne #1261 Le 07/02/2012, à 18:57 bibichouchou Re : TVDownloader: télécharger les médias du net ! @ k3c et oui j'avais bien vu, c'est pourquoi j'ai bon espoir pour un script pour linux. mais j'ai regardé et pour le coup, c'est hors de mes compétences... je lance une bouteille à la mer ! Hors ligne #1262 Le 07/02/2012, à 19:10 grandtoubab Re : TVDownloader: télécharger les médias du net ! k3c a écrit : J'ai la version 0.5 de pluzzdl, est-ce ton cas ? Clic sur l'image que j'ai posté et tu verras que oui. Mais je relance avec l'option -f et ca commence à télécharger (http://code.google.com/p/tvdownloader/wiki/pluzzdl)<metadata lang=CSV prob=0.07 /> @ubuntu-desktop:~/Vidéos$ pluzzdl -f http://www.pluzz.fr/faites-entrer-l-accuse.html [INFO ] PluzzDL.py Début du téléchargement des fragments Et là le fichier est complet @ubuntu-desktop:~/Vidéos$ pluzzdl -f http://www.pluzz.fr/faites-entrer-l-accuse.html [INFO ] PluzzDL.py Début du téléchargement des fragments [INFO ] PluzzDL.py Fin du téléchargement @ubuntu-desktop:~/Vidéos$ c'est quand même cool de regarder du flash sans entendre le PC ronfler à mort 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 #1263 Le 07/02/2012, à 20:19 k3c Re : TVDownloader: télécharger les médias du net ! @ bibichouchou Un des programmes de récupération de replays sous Windows (TVRR) s'arrête http://rectv.free.fr/viewtopic.php?f=6&t=358 C'est dommage qu'il ne passe pas en open source, et que tout ce code disparaisse... Hors ligne #1264 Le 08/02/2012, à 11:43 k3c Re : TVDownloader: télécharger les médias du net ! Concernant TV5mondeplus, en fait il y a 2 cas - les urls de TV5mondeplus "de base", qui se terminent par -6chiffres. Le fichier .mp4 est dans une balise appleStreamingUrl - les urls de TV5monde Afrique, Asie, Amérique du Sud..., qui se terminent par 5 chiffres. Le fichier .mp4 est dans une balise vidéoUrl d'un fichier .smil J'ai donc fait une nouvelle version de mon script, qui récupère aussi ce deuxième cas de figure. #!/usr/bin/env python # -*- coding:utf-8 -*- # version 0.3 par k3c from lxml import etree from lxml import objectify import subprocess, optparse, re from urllib2 import URLError, Request, urlopen import socket timeout = 10 # timeout en secondes socket.setdefaulttimeout(timeout) usage = "usage: python tv5 [options] <url de l'emission>" parser = optparse.OptionParser( usage = usage ) parser.add_option( "--nocolor", action = 'store_true', default = False, help = 'desactive la couleur dans le terminal' ) parser.add_option( "-v", "--verbose", action = "store_true", default = False, help = 'affiche les informations de debugage' ) ( options, args ) = parser.parse_args() # Vérification du nombre d'arguments if( len( args ) != 1 or args[ 0 ] == "" ): parser.print_help() parser.exit( 1 ) if args[0][-4:] == "?t=1": xargs[0] = args[0][:-4] id = re.findall('[0-9]{5}[0-9]?$',args[0]) #conversion string numérique id = ''.join(id) # les infos sur la vidéo sont accessibles là the_url = "".join('http://www.tv5mondeplus.com/video-xml/get/') + str(id) try: file = urlopen(the_url) except URLError, e: print e.code data = file.read() file.close() root = objectify.fromstring(data) for element in root.iter(): if element.tag == "permalink": titre = element.text tit = titre.split('/')[-1] # on enlève les 7 derniers caractères qui sont - et 6 chiffres pour le nom du fichier et on ajoute tv5_ au début tit = tit[:-6] tit = "tv5_"+tit+".wmv" # 2 cas, la video est sur la balise appleStreamingUrl, ou dans le .smil à # la vidéo est sur appleStreamingUrl if element.tag == "appleStreamingUrl": video = element.text # la vidéo est sur videoUrl, dans un .smil, que l'on va ouvrir # http://fr.wikipedia.org/wiki/Synchronized_Multimedia_Integration_Language if element.tag == "videoUrl": video = element.text try: # exemple de fichier .smil # <?xml version="1.0"?> # <!DOCTYPE smil PUBLIC "-//W3C//DTD SMIL 2.0//EN" "http://www.w3.org/2001/SMIL20/SMIL20.dtd"> # <smil xmlns="http://www.w3.org/2001/SMIL20/Language"> # <head> # <meta name="title" content="COURTS SEJOURS" /> # <meta name="httpBase" content="http://vodhdflash.tv5monde.com/" /> # <meta name="rtmpAuthBase" content="" /> # </head> # <body> # <switch id="tv5_catchup"> # <video src="tv5mondeplus/hq/3137682.mp4" system-bitrate="500000"/> # <video src="tv5mondeplus/bq/3137682.mp4" system-bitrate="300000"/> # </switch> # </body> # </smil> # on enleve la première ligne blanche, sinon le parsing xml se plante video = urlopen(video) video.readline() video = video.read() root = objectify.fromstring(video) # le début de l'emplacement de la vidéo est à httpBase, c'est normalement # http://vodhdflash.tv5monde.com/ for x in root.head.getchildren(): if x.get('name') == 'httpBase': content = x.get('content') #la suite de l'emplacement de la video est à video src, # et on prend la ligne avec le bit-rate le plus élevé # exemple de suite de l'emplacement, à concaténer # tv5mondeplus/hq/3137682.mp4 itc = root.body.switch.getchildren() url = itc.pop() for x in itc: if x.get('system-bitrate') > url.get('system-bitrate'): url = x url = url.get('src') except IOError, e: if hasattr(e, 'reason'): print 'Nous avons échoué à joindre le serveur.' print 'Raison: ', e.reason elif hasattr(e, 'code'): print 'Le serveur n\'a pu satisfaire la demande.' print 'Code d\' erreur : ', e.code args = ['/usr/bin/msdl', content + url , '-o', tit] app = subprocess.Popen(args=args, stdout=open('somefile', 'w')) Dernière modification par k3c (Le 08/02/2012, à 11:47) Hors ligne #1265 Le 08/02/2012, à 15:36 Babar21 Re : TVDownloader: télécharger les médias du net ! Merci pour le script TV5, k3C ! Hors ligne #1266 Le 08/02/2012, à 15:37 Zoulou.4556 Re : TVDownloader: télécharger les médias du net ! Bonjour, je fais un retour de l'utilisation de tvdownloader avec les erreurs suivante : Arte certaines émissions seulement FR Inter et Radio France rien du tout Pluzz rien du tout W9 Replay rien du tout pour le reste c'est ok voilà se que ça donne en console: zoulou@zoulou-Linux:~$ tvdownloader Traceback (most recent call last): File "/usr/lib/python2.7/logging/__init__.py", line 842, in emit msg = self.format(record) File "/usr/lib/python2.7/logging/__init__.py", line 719, in format return fmt.format(record) File "/usr/lib/python2.7/logging/__init__.py", line 464, in format record.message = record.getMessage() File "/usr/lib/python2.7/logging/__init__.py", line 328, in getMessage msg = msg % self.args TypeError: not all arguments converted during string formatting Logged from file APIPrive.py, line 253 Traceback (most recent call last): File "/usr/share/tvdownloader/APIPrive.py", line 251, in pluginRafraichir self.listePluginActif[nomPlugin].rafraichir() File "plugins/W9Replay.py", line 51, in rafraichir page = urllib.urlopen( self.urlFichierXML ) File "/usr/lib/python2.7/urllib.py", line 84, in urlopen return opener.open(url) File "/usr/lib/python2.7/urllib.py", line 205, in open return getattr(self, name)(url) File "/usr/lib/python2.7/urllib.py", line 342, in open_http h.endheaders(data) File "/usr/lib/python2.7/httplib.py", line 951, in endheaders self._send_output(message_body) File "/usr/lib/python2.7/httplib.py", line 811, in _send_output self.send(msg) File "/usr/lib/python2.7/httplib.py", line 773, in send self.connect() File "/usr/lib/python2.7/httplib.py", line 754, in connect self.timeout, self.source_address) File "/usr/lib/python2.7/socket.py", line 553, in create_connection for res in getaddrinfo(host, port, 0, SOCK_STREAM): IOError: [Errno socket error] [Errno -2] Nom ou service inconnu ERROR Navigateur : timed out ERROR Navigateur : timed out ERROR Navigateur : timed out utilisation de tvdownloader sur ubuntu 11.04 64bits. bon courage pour la suite, merci pour vos développements et votre partage. Dernière modification par Zoulou.4556 (Le 08/02/2012, à 15:44) Asus X66IC Manjaro 64bits dual Ubuntu 14.04 64 bits / Dell Latitude D520 Xubuntu 14.04 32 bits/ Aurore BG6-I3-4-H10S1 SSD 120 go +DD 1To Manjaro 64 bits dual Ubuntu 64 bits Hors ligne #1267 Le 08/02/2012, à 16:02 k3c Re : TVDownloader: télécharger les médias du net ! @ Zoulou Pour récupérer les émissions de Pluzz, cela marche très bien, mais il faut utiliser PluzzDL 0.5, en attendant que cela soit à nouveau intégré dans TVDownloader. http://code.google.com/p/tvdownloader/wiki/pluzzdl Puis tu tapes, pour récupérer un Samantha par exemple $ pluzzdl -f http://www.pluzz.fr/samantha-oups-2012-02-07-20h15.html Je télécharge Missing sur W9replay, donc il y a au moins un replay qui fonctionne correctement sur cette chaîne. Est-ce que tu as essayé ce replay-là ? Pour Arte, je télécharge [HD] Son Jarocho de Veracruz, avec Son de Madera au Quai Branly mais effectivement il y a des choses qui ne fonctionnent pas. Je n'utilise jamais les radios, mais je vais regarder. Hors ligne #1268 Le 08/02/2012, à 16:05 Babar21 Re : TVDownloader: télécharger les médias du net ! Pour ce qui ne marche plus (pour l'instant) sur Arte dans TVDownloader, il y a Arte+7 recorder, qui ne fait que ça mais qui le fait bien. Hors ligne #1269 Le 08/02/2012, à 16:18 Zoulou.4556 Re : TVDownloader: télécharger les médias du net ! @k3c, je viens d'essayer avec PluzzDL ça fonctionne sans problème merci pour l'info. @Babar21, je l'utilise effectivement pour Arte, c'était surtout pour un retour que je l ai signalé. merci pour vos réponses. Dernière modification par Zoulou.4556 (Le 08/02/2012, à 16:19) Asus X66IC Manjaro 64bits dual Ubuntu 14.04 64 bits / Dell Latitude D520 Xubuntu 14.04 32 bits/ Aurore BG6-I3-4-H10S1 SSD 120 go +DD 1To Manjaro 64 bits dual Ubuntu 64 bits Hors ligne #1270 Le 08/02/2012, à 19:23 grandtoubab Re : TVDownloader: télécharger les médias du net ! Concernant TV5mondeplus, en fait il y a 2 cas Bord!!! j'ai pas de pot moi @ubuntu-desktop:~/Linux$ python k3c.py http://www.tv5mondeplusafrique.com/#serie_cinema_histoires_droles_et_droles_de_gens 404 Traceback (most recent call last): File "k3c.py", line 32, in <module> data = file.read() TypeError: descriptor 'read' of 'file' object needs an argument Par contre la Rama, je la récupère @ubuntu-desktop:~/Linux$ python k3c.py http://www.tv5mondeplus.com/video/08-02-2012/rama-yade-213995 download [ tv5_rama-yade-.wmv ] @ubuntu-desktop:~/Linux$ Host: [ 195.12.231.32:80 ] connected! DL: 3143308/2147483647 B -- 0% 87.6K/s ETA 06:09:5 DL: 39109792/39109792 B -- 100% 84.0K/s Complete finished!! FINISHED --00:07:46-- Donc y a un troisieme cas celui sans numéro à la fin Dernière modification par grandtoubab (Le 08/02/2012, à 19:50) 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 #1271 Le 08/02/2012, à 20:19 k3c Re : TVDownloader: télécharger les médias du net ! @ Grandtoubab Chic, un cas non géré ! Je regarde... Edit : en fait, sur tv5mondeplus.com, quand on clique sur mappemonde, - on a un certain nombre de reportages visibles sur la carte - on peut aussi sélectionner Afrique, Amérique du Sud, Australie... C'est ces cas que mon script est censé gérer, vu que je n'ai vu que des adresses html se terminant par - et 5 chiffres Dernière modification par k3c (Le 09/02/2012, à 11:18) Hors ligne #1272 Le 12/02/2012, à 16:25 coucou123 Re : TVDownloader: télécharger les médias du net ! Salut, je me permet un petit retour: Quand je télécharge certaines émissions sur M6replay, la barre de téléchargement reviens sans cesse à 0% (à peine passé le cap des 10%). De plsu lorsque le téléchargement est terminé, il s'avère que le fichier est incomplet. Mais sinon, c'est une excellent initiative ce logiciel, d'autant plus que je n'arrive plus à voir quoi que ce soit sur M6Replay ! Precise Pangolin 64bits Lucid Lynx 64bits Hors ligne #1273 Le 13/02/2012, à 09:00 k3c Re : TVDownloader: télécharger les médias du net ! @coucou123 Ca se produit avec quelles émissions sur M6 ? Hier j'ai téléchargé sans problème une série, puis un Turbo. Hors ligne #1274 Le 13/02/2012, à 15:32 coucou123 Re : TVDownloader: télécharger les médias du net ! oups, désolé, en fait il se trouve que l'émission était bien en entier, mais que c'était la barre de défilement de VLC qui n'allait pas jusqu'à la fin. Le fichier est peut-être légèrement corrompu, je ne sais pas... Par contre il est vrai que la barre de progression de téléchargement de TVDownloader bugue un peu. L'émission en question c'était Top Chef (qui dure 2h30), et la barre de progression de téléchargement revenait à zéro dès qu'elle dépassait 9%, ce qui fait qu'il était impossible de savoir quand le téléchargement allait se terminer. Mais sinon, ce logiciel est vraiment chouette. Il faudrait juste que l'on puisse ajouter soi-même des sites, ou alors que le choix s'agrandisse au fil du temps. Peut-être aussi qu'un outil pour signaler les plugins qui ne fonctionnent plus, ce serait pas mal. Merci pour ton boulot, c'est du bon boulot ! Precise Pangolin 64bits Lucid Lynx 64bits Hors ligne #1275 Le 13/02/2012, à 18:53 grandtoubab Re : TVDownloader: télécharger les médias du net ! @ Grandtoubab Chic, un cas non géré ! Je regarde... Edit : en fait, sur tv5mondeplus.com, quand on clique sur mappemonde, - on a un certain nombre de reportages visibles sur la carte - on peut aussi sélectionner Afrique, Amérique du Sud, Australie... C'est ces cas que mon script est censé gérer, vu que je n'ai vu que des adresses html se terminant par - et 5 chiffres Et donc pour le reste c'est foutu? 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
http://www.linuxjournal.com/content/introduction-mapreduce-hadoop-linux When your data and work grow, and you still want to produce results in a timely manner, you start to think big. Your one beefy server reaches its limits. You need a way to spread your work across many computers. You truly need to scale out. Say you have 100 10GB log files from some custom application—roughly a petabyte of data. You do a quick test and estimate it will take your desktop days do grep every line (assuming you even could fit the data on your desktop). And, that's before you add in logic to group by host and calculate totals. Your tried-and-true shell utilities won't help, but MapReduce can handle this without breaking a sweat. First let's look at the raw data. Log lines from the custom application look like this: The log format is hostname, colon, message. Your boss suspects someone evil is trying to brute-force attack the application. The same host trying many different user names may indicate an attack. He wants totals of "invalid user" messages grouped by hostname. Filtering the above log lines should yield: With gigabytes of log files, your trusty shell tools do just fine. For a terabyte, more power is needed. This is a job for Hadoop and MapReduce. Before getting to Hadoop, let's summon some Python and test locally on a small dataset. I'm assuming you have a recent Python installed. I tested with Python 2.7.3 on Ubuntu 12.10. The first program to write consumes log lines from our custom application. Let's call it map.py: map.py prints the hostname, a tab character and the number 1 any time it sees a line containing the string "invalid user". Write the example log lines to log.txt, then test map.py: The output is: Output of map.py will be piped into our next program, reduce.py: reduce.py totals up consecutive lines of a particular host. Let's assume lines are grouped by hostname. If we see the same hostname, we increment a total. If we encounter a different hostname, we print the total so far and reset the total and hostname. When we exhaust standard input, we print the total if necessary. This assumes lines with the same hostname always appear consecutively. They will, and I'll address why later. Test by piping it together with map.py like so: Later, I'll explain why I added sort to the pipeline. This prints: Exactly what we want. A successful test! Our test log lines contain three "invalid user" messages for the host dsl5.example.com. Later we'll get this local test running on a Hadoop cluster. Let's dive a little deeper. What exactly does map.py do? It transforms unstructured log data into tab-separated key-value pairs. It emits a hostname for a key, a tab and the number 1 for a value (again, only for lines with "invalid user" messages). Note that any number of log lines could be fed to any number of instances of the map.py program—each line can be examined independently. Similarly, each output line of map.py can be examined independently. Output from map.py becomes input for reduce.py. The output of reduce.py (hostname, tab, number) looks very similar to its input. This is by design. Key-value pairs may be reduced multiple times, so reduce.py must handle this gracefully. If we were to re-reduce our final answer, we would get the exact same result. This repeatable, predictable behavior of reduce.py is known as idempotence. We just tested with one instance of reduce.py, but you could imagine many instances of reduce.py handling many lines of output from map.py. Note that this works only if lines with the same hostname appear consecutively. In our test, we enforce this constraint by adding sort to the pipeline. This simulates how our code behaves within Hadoop MapReduce. Hadoop will group and sort input to reduce.py similarly. We don't have to bother with how execution will proceed and how many instances of map.py and reduce.py will run. We just follow the MapReduce pattern and Hadoop does the rest. You'll need Java 1.6.x or later (I used OpenJDK 7). The rest can and should be performed as a nonroot user. Download the latest stable Hadoop tarball (see Resources). Don't use a distro-specific (.rpm or .deb) package. I'm assuming you downloaded hadoop-1.0.4.tar.gz. Unpack this and change into the hadoop-1.0.4 directory. The directory hadoop-1.0.4 and the files map.py, reduce.py and log.txt should be in /tmp. If not, adjust the paths in the examples below as necessary. Run the job on Hadoop like so: Hadoop will log some stuff to the console. Look for the following: This means our job completed successfully. I see a file called /tmp/output/part-00000, which contains just what we expect: Now is a good time to pause, smile and reward yourself with a quad-shot grande iced caramel macchiato. You're a rockstar. Figure 1. Here's what we did during the map and reduce steps. The transformations we performed allow us to run many mappers and reducers on as many machines as we want. Hadoop takes care of the gory details. It starts mappers and reducers, passes data between them and spits out the answer. Pseudo-distributed operation requires some configuration. The user you're running Hadoop as must also be able to make SSH passwordless connections to localhost. Installing and configuring this is beyond the scope of this article, but you'll find more information in the "Single Node Setup" tutorial mentioned in Resources. If you started with the 1.0.4 tarball release recommended above, the tutorial should work verbatim on any standard GNU/Linux distribution. If you set up pseudo-distributed (or distributed) Hadoop, you'll gain the benefit of two spartan-but-useful Web interfaces. The NameNode Web interface allows you to browse logs and browse the Hadoop distributed filesystem. The JobTracker Web interface allows you to monitor MapReduce jobs and debug problems. Figure 2. NameNode Web Interface Figure 3. JobTracker Web Interface In Dumbo, our MapReduce implementation becomes: The state machine is gone. Dumbo takes care of grouping by key (hostname). Save the above code in a file called /tmp/smart.py. Install Dumbo. See Resources for a link, and don't worry, it's easy. Once Dumbo is installed, run the code: Finally, examine the output: The content should match our earlier result from Hadoop Streaming. Consider some cases when Hadoop is the wrong tool. Small dataset? Don't bother. In a one-meter race between a rocket and a scooter, the scooter is gone before the rocket's engines are started. Transactional data storage for a Web site? Try MySQL or MongoDB instead. Hadoop also won't help you process data as it arrives. This is often referred to as "real time" or "streaming". For that, consider Storm (see Resources for more information). With practice, you'll quickly be able to discern when Hadoop is the right tool for the job. See http://hadoop.apache.org/docs/current/single_node_setup.html for information on how to run a pseudo-distributed Hadoop cluster. Check out Dumbo at http://projects.dumbotics.com/dumbo if you want to do more with MapReduce in Python. See https://github.com/klbostee/dumbo/wiki/Building-and-installing for install instructions and https://github.com/klbostee/dumbo/wiki/Short-tutorial for an excellent tutorial. See https://github.com/nathanmarz/storm for information on Storm, a real-time distributed computing system. To run Storm and Hadoop and manage both centrally, check out the Mesos project at http://www.mesosproject.org. When your data and work grow, and you still want to produce results in a timely manner, you start to think big. Your one beefy server reaches its limits. You need a way to spread your work across many computers. You truly need to scale out. In pioneer days they used oxen for heavy pulling, and when one ox couldn't budge a log, they didn't try to grow a larger ox. We shouldn't be trying for bigger computers, but for more systems of computers.—Grace HopperClearly, cluster computing is old news. What's changed? Today: We collect more data than ever before. Even small-to-medium-size businesses can benefit from tools like Hadoop and MapReduce. You don't have to have a PhD to create and use your own cluster. Many decent free/libre open-source tools can help you easily cluster commodity hardware. Parallel Problems Let's start with problems that can be divided into smaller independent units of work. These problems are roughly classified as "embarrassingly parallel" and are—as the term suggests—suitable for parallel processing. Examples: Classify e-mail messages as spam. Transcode video. Render an Earth's worth of map tile images. Count logged lines matching a pattern. Figure out errors per day of week for a particular application. MapReduce by Example MapReduce is a coding pattern that abstracts much of the tricky bits of scalable computations. We're free to focus on the problem at hand, but it takes practice. So let's practice! Say you have 100 10GB log files from some custom application—roughly a petabyte of data. You do a quick test and estimate it will take your desktop days do grep every line (assuming you even could fit the data on your desktop). And, that's before you add in logic to group by host and calculate totals. Your tried-and-true shell utilities won't help, but MapReduce can handle this without breaking a sweat. First let's look at the raw data. Log lines from the custom application look like this: localhost: restarting dsl5.example.com: invalid user 'bart' dsl5.example.com: invalid user 'charlie' dsl5.example.com: invalid user 'david' dsl8.example.net: invalid password for user 'admin' dsl8.example.net: user 'admin' logged in The log format is hostname, colon, message. Your boss suspects someone evil is trying to brute-force attack the application. The same host trying many different user names may indicate an attack. He wants totals of "invalid user" messages grouped by hostname. Filtering the above log lines should yield: dsl5.example.com 3 With gigabytes of log files, your trusty shell tools do just fine. For a terabyte, more power is needed. This is a job for Hadoop and MapReduce. Before getting to Hadoop, let's summon some Python and test locally on a small dataset. I'm assuming you have a recent Python installed. I tested with Python 2.7.3 on Ubuntu 12.10. The first program to write consumes log lines from our custom application. Let's call it map.py: #!/usr/bin/python import sys for line in sys.stdin: if 'invalid user' in line: host = line.split(':')[0] print '%s\t%s' % (host, 1) map.py prints the hostname, a tab character and the number 1 any time it sees a line containing the string "invalid user". Write the example log lines to log.txt, then test map.py: chmod 755 map.py./map.py < log.txt The output is: dsl5.example.com 1dsl5.example.com 1dsl5.example.com 1 Output of map.py will be piped into our next program, reduce.py: #!/usr/bin/python import sys last_host = None last_count = 0 host = None for line in sys.stdin: host, count = line.split('\t') count = int(count) if last_host == host: last_count += count else: if last_host: print '%s\t%s' % (last_host, last_count) last_host = host last_count = count if last_host == host: print '%s\t%s' % (last_host, last_count) reduce.py totals up consecutive lines of a particular host. Let's assume lines are grouped by hostname. If we see the same hostname, we increment a total. If we encounter a different hostname, we print the total so far and reset the total and hostname. When we exhaust standard input, we print the total if necessary. This assumes lines with the same hostname always appear consecutively. They will, and I'll address why later. Test by piping it together with map.py like so: chmod 755 reduce.py./map.py < log.txt | sort | ./reduce.py Later, I'll explain why I added sort to the pipeline. This prints: dsl5.example.com 3 Exactly what we want. A successful test! Our test log lines contain three "invalid user" messages for the host dsl5.example.com. Later we'll get this local test running on a Hadoop cluster. Let's dive a little deeper. What exactly does map.py do? It transforms unstructured log data into tab-separated key-value pairs. It emits a hostname for a key, a tab and the number 1 for a value (again, only for lines with "invalid user" messages). Note that any number of log lines could be fed to any number of instances of the map.py program—each line can be examined independently. Similarly, each output line of map.py can be examined independently. Output from map.py becomes input for reduce.py. The output of reduce.py (hostname, tab, number) looks very similar to its input. This is by design. Key-value pairs may be reduced multiple times, so reduce.py must handle this gracefully. If we were to re-reduce our final answer, we would get the exact same result. This repeatable, predictable behavior of reduce.py is known as idempotence. We just tested with one instance of reduce.py, but you could imagine many instances of reduce.py handling many lines of output from map.py. Note that this works only if lines with the same hostname appear consecutively. In our test, we enforce this constraint by adding sort to the pipeline. This simulates how our code behaves within Hadoop MapReduce. Hadoop will group and sort input to reduce.py similarly. We don't have to bother with how execution will proceed and how many instances of map.py and reduce.py will run. We just follow the MapReduce pattern and Hadoop does the rest. MapReduce with Hadoop Hadoop is mostly a Java framework, but the magically awesome Streaming utility allows us to use programs written in other languages. The program must only obey certain conventions for standard input and output (which we've already done). You'll need Java 1.6.x or later (I used OpenJDK 7). The rest can and should be performed as a nonroot user. Download the latest stable Hadoop tarball (see Resources). Don't use a distro-specific (.rpm or .deb) package. I'm assuming you downloaded hadoop-1.0.4.tar.gz. Unpack this and change into the hadoop-1.0.4 directory. The directory hadoop-1.0.4 and the files map.py, reduce.py and log.txt should be in /tmp. If not, adjust the paths in the examples below as necessary. Run the job on Hadoop like so: cd /tmp/hadoop-1.0.4 bin/hadoop jar \ contrib/streaming/hadoop-streaming-1.0.4.jar \ -mapper /tmp/map.py -reducer /tmp/reduce.py \ -input /tmp/log.txt -output /tmp/output Hadoop will log some stuff to the console. Look for the following: ... INFO streaming.StreamJob: map 0% reduce 0% INFO streaming.StreamJob: map 100% reduce 0% INFO streaming.StreamJob: map 100% reduce 100% INFO streaming.StreamJob: Output: /tmp/output This means our job completed successfully. I see a file called /tmp/output/part-00000, which contains just what we expect: dsl5.example.com 3 Now is a good time to pause, smile and reward yourself with a quad-shot grande iced caramel macchiato. You're a rockstar. Figure 1. Here's what we did during the map and reduce steps. The transformations we performed allow us to run many mappers and reducers on as many machines as we want. Hadoop takes care of the gory details. It starts mappers and reducers, passes data between them and spits out the answer. Clustered MapReduce If you've got everything working so far, try starting your own cluster too! Running Hadoop on a single physical machine with multiple Java virtual machines is called pseudo-distributed operation. Pseudo-distributed operation requires some configuration. The user you're running Hadoop as must also be able to make SSH passwordless connections to localhost. Installing and configuring this is beyond the scope of this article, but you'll find more information in the "Single Node Setup" tutorial mentioned in Resources. If you started with the 1.0.4 tarball release recommended above, the tutorial should work verbatim on any standard GNU/Linux distribution. If you set up pseudo-distributed (or distributed) Hadoop, you'll gain the benefit of two spartan-but-useful Web interfaces. The NameNode Web interface allows you to browse logs and browse the Hadoop distributed filesystem. The JobTracker Web interface allows you to monitor MapReduce jobs and debug problems. Figure 2. NameNode Web Interface Figure 3. JobTracker Web Interface Beautifully Simple Python MapReduce You may wonder why reduce.py (above) is a convoluted mini-state machine. This is because hostnames change in the input lines provided by Hadoop. The Dumbo Python library (see Resources) hides this detail of Hadoop. Dumbo lets us focus even more tightly on our mapping and reducing. In Dumbo, our MapReduce implementation becomes: def mapper(key, value): if 'invalid user' in value: yield value.split(':')[0], 1 def reducer(key, values): yield key, sum(values) if __name__ == '__main__': import dumbo dumbo.run(mapper, reducer) The state machine is gone. Dumbo takes care of grouping by key (hostname). Save the above code in a file called /tmp/smart.py. Install Dumbo. See Resources for a link, and don't worry, it's easy. Once Dumbo is installed, run the code: cd /tmp dumbo start smart.py -hadoop hadoop-1.0.4 \ -input log.txt -output totals \ -outputformat text Finally, examine the output: cat totals/part-00000 The content should match our earlier result from Hadoop Streaming. Non-Use Cases Hadoop is great for one-time jobs and off-line batch processing, especially where the data is already in the Hadoop filesystem and will be read many times. My first example makes more sense if you assume this. Perhaps the job must be run daily and must finish within a few minutes. Consider some cases when Hadoop is the wrong tool. Small dataset? Don't bother. In a one-meter race between a rocket and a scooter, the scooter is gone before the rocket's engines are started. Transactional data storage for a Web site? Try MySQL or MongoDB instead. Hadoop also won't help you process data as it arrives. This is often referred to as "real time" or "streaming". For that, consider Storm (see Resources for more information). With practice, you'll quickly be able to discern when Hadoop is the right tool for the job. Resources You can download the latest stable Hadoop tarball from . See http://hadoop.apache.org/docs/current/single_node_setup.html for information on how to run a pseudo-distributed Hadoop cluster. Check out Dumbo at http://projects.dumbotics.com/dumbo if you want to do more with MapReduce in Python. See https://github.com/klbostee/dumbo/wiki/Building-and-installing for install instructions and https://github.com/klbostee/dumbo/wiki/Short-tutorial for an excellent tutorial. See https://github.com/nathanmarz/storm for information on Storm, a real-time distributed computing system. To run Storm and Hadoop and manage both centrally, check out the Mesos project at http://www.mesosproject.org.
In SQLAlchemy, imagine we have a table Foo with a compound primary key, and Bar, which has two foreign key constrains linking it to Foo (each Bar has two Foo objects). My problem is with the relationship function, which makes me repeat the information (in the primaryjoin) which I have already given in the ForeightKeyConstraint (violating DRY). Is there some other way of structuring this so that I don't have to repeat information? Some way of passing the relevant ForeignKeyConstraint to relationship? class Foo(Base): __tablename__ = "Foo" id_1 = Column(Integer, primary_key=True) id_2 = Column(Integer, primary_key=True) class Bar(Base): __tablename__ = "Bar" id = Column(Integer, primary_key=True) foo_1_id_1 = Column(Integer) foo_1_id_2 = Column(Integer) foo_2_id_1 = Column(Integer) foo_2_id_2 = Column(Integer) __table_args__ = ( ForeignKeyConstraint( [foo_1_id_1,foo_1_id_2], [Foo.id_1,Foo.id_2] ), ForeignKeyConstraint( [foo_2_id_1,foo_2_id_2], [Foo.id_1,Foo.id_2] ) ) foo_1 = relationship(Foo,primaryjoin="(Bar.foo_1_id_1 == Foo.id_1) & (Bar.foo_1_id_2 == Foo.id_2)") foo_2 = relationship(Foo,primaryjoin="(Bar.foo_2_id_1 == Foo.id_1) & (Bar.foo_2_id_2 == Foo.id_2)") Thanks.
When using sqlite for django you can checkout your application from source control and run the unit tests without needed to do anything special. But when you switch to using mysql as your database all of the sudden you need to create a database. Why do I need to do this? This is especially weird since the unit tests won't even use that database, they will instead create their own by prefixing the name with 'test_'. This is because Django loads the settings.py file for running the test suite. You can create a separate settings.py file and use it at the time you run the tests. As an example from the django site: --settings=test_sqlite assuming you had a settings.py file called test_sqlite. Go here for more information: If you run tests frequently put the following code in your settings.py: import sys if 'test' in sys.argv: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test' } } I use almost the same solution for test, like @Simon Bächler, but instead of real database I use So it use memory to handle test operations, and thats why it doesn't always create/update/delete the db.
The impressive term partial function application stands for a programming technique that is not nearly as complicated as it sounds. In short words, it refers to creating a new function from any given function by fixating one or more of its arguments. Why write a tutorial about such a simple feature? The actual technique (the what and how) is explained in few words, so I'll go on and contemplate on functional programming style in Python and built-in functions (the why) that are an old hat to seasoned Python coders. I'll also describe a real-world example (the where to use) in a rather free-form way. There's little working code in this tutorial. For those still exploring the vast Python-lands, this tutorial might offer an insight as to where functional thinking and the titular partial function application can be useful, even though it seems rather superfluous at first. The Good Old Log Example To give an example I already used in a previous article of mine (shameless plug: Closures in Python), imagine we want to have a number of logging functions like log_info(), log_warning(), log_error() and so on. These simply print any message passed to them on the screen, but precede each message with a logging level like “info”, “warning” or “error”. There are a number of possible ways to construct them without code repetition. Two of them – using a class and using closures – are presented in the aforementioned article. Here is a third version: from functools import partial def log_template(level, message): print("{}: {}".format(level, message)) log_info = partial(log_template, "info") log_warning = partial(log_template, "warning") log_error = partial(log_template, "error") Let's test it on the Python command line interpreter: >>> log_info("test test test 1 2 3") info: test test test 1 2 3 The usage of the partial function is as intuitive as the example suggests: Simply pass a function and then a number of arguments. The partial function will then return a new function. This new function is like the old function with some of its parameter fixed to the arguments which were passed. The fixation happens from left to right, so in our example, the level parameter was fixed, but message was not, because we have only passed one argument. If we wanted, we could have written log_info = partial(log_template, level="info") as the partial function also takes keyword arguments. That way we can fix any parameter we want (and likewise leave any parameter free, even if it's to the left of a fixed parameter). The official documentation for this feature resides in the Python documentation. There's even a pure-python implementation for the partial function showcased, which behaves almost like the real version (but not quite, as we will see). While all of this is nice and fun, it may leave you, dear reader, wondering Why Would We Ever Need That? As I said before, there are at least two other methods available for producing the same result as above. Both could be easily considered superior, because with these we don't need to import some module. Also, one might claim that with a little more typing, we could have fixated the level parameter just as well with a wrapper function: def log_template(level, message): print("{}: {}".format(level, message)) def log_info(message): return log_template("info", message) def log_warning(message): return log_template("warning", message) def log_error(message): return log_template("error", message) Note that the return is not really needed, because nothing (None) is returned anyways, but this mimics the behavior of the partial function better. A version with lambda expressions allows for less clutter, like so: log_info = lambda message: log_template("info", message) Is there a difference to using a partial object? Indeed, there is, albeit a seemingly small one. Examining Stack Traces Let's consider a rather impractical function throw that takes one argument (that will be fixed later). This function corresponds to the log_template function above. However, all it does is raise an exception: def throw(unused_arg): raise Exception Not very useful, is it? When we execute it, we see >>> throw(True) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in throw Exception And that is the whole purpose of this exercise: To see a stack trace. At the moment the exception was raised there are two frames in our execution stack: One from the command line environment, and one from the throw function. This is very much expected and shouldn't surprise anybody. Let's create a wrapper function that wraps our (unused) argument. This, too, has no purpose other than to show a stack trace. It corresponds to the wrapped versions of log_info and friends. # assume 'throw' is defined as above def throw_wrapper(): return throw(True) Let's watch it do nothing and fail: >>> throw_wrapper() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in throw_wrapper File "<stdin>", line 2, in throw Exception Again, that is very much as we anticipated. Apart from the command line stack frame, there are two functions on the execution stack, which is our throw function and the wrapper function throw_wrapper. Now we construct a partial object with the partial function: from functools import partial # again, assume that 'throw' is defined throw_partial = partial(throw, True) and watch it blow up mindlessly: >>> throw_partial() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in throw Exception This is interesting – we have just one function on the stack: throw, even though we called the function throw_partial. And I'm going to give this away without torturing you with more dummy code: The showcase-version from the Python documentation also does not behave like the actual partial function (and the documentation doesn't claim that it does; it's just there to explain the principle), it, too, shows two function frames on the execution stack. That example also demonstrates another (mis-)feature: The partialized (is that even a word?) function is named the same as the old function, although it is obviously different. If we ever expose such a function as part of our API, we should remember to overwrite the __doc__ attribute of the new function to reflect its new signature and behavior. Note that I normally don't use docstrings in my tutorials because I want to keep the code as short as possible, but for any production code it is very important to document functions, at the very least any kind of public API. So there we have one very practical advantage of using the partial function form functools over our own wrapper: We avoid constructing (and destructing) another stack frame, which is a costly thing to do if done very often (read: It's slow). Now we all know about how “premature optimization is the root of all evil”, but using the partial function is typically not much an effort, really. If the partial version is no more complicated than a wrapper, we might as well use it. The question remains: Are there real-world problems where partial function application is really more convenient than other techniques? Well, I do happen to use it in some of my projects, so these problems do apparently exist. Just recently I happened to stumble over one, and even though the decision to go for partial objects was more due to the deficiencies of the multiprocessing module than to anything else, it was a good opportunity to think about basic functional programming in Python once more. Real-World Example: Crunching Scientific Data Consider a case I encountered while peering over the shoulders of a friend of mine (a physicist): He had a file with a lot of measurements from some kind of experiment (creating black holes, no doubt). These were to be read, then processed with some kind of expensive calculation, and the results were written to disk again. The problem was: It was painfully slow. On a modern computer it took several minutes to do the processing. We reworked the code and brought the time down by an order of magnitude with several tricks. One of them was to use multiple processes to split the calculation onto the many cores of the machine. We don't need to bother thinking about the reading and writing, but let's assume the calculation function looked something like that: def calculate(value): # do some expensive calculations # involving some physical parameters # that are global variables in this script return result This is a very simplified view, of course. The value was a singular measurement (out of thousands) from the file, while the mentioned physical parameters were some kind of global variables in this script. The parameters where not hard-coded, because they were set by the meta-information in the header of the mentioned file. We all know global variables are bad. To defend the physicist in question, the script was actually pretty sane and the use of global variables was somewhat justified (I won't go into detail here). As mentioned, we decided that multi-processing was the way to go to speed this up (multi-threading was no-go because of Python's Global Interpreter Log (GIL)). There are two modules in Python's standard library that offer a process pool: concurrent.futures and multiprocessing. concurrent.futures is a great module built around the concept of futures, but we decided to go with multiprocessing because its simpler and does all that we needed. multiprocessing has a nice Pool class, whose objects have a map method that behaves just like the built-in map function, but spreads the execution across all available processors. Now what does map do? Let's have a small excursions on the basics on functional programming in Python and examine The map Function And Other Functional Goodies One way to look at our problem at hand is: We have a list of values (list_1), and from that we want to construct another list that contains new values (list_2). The new values are not made up from thin air, but we derive them from the old values. This derivation can be expressed as a function (func) that takes an old value and outputs a new one. So we have this: list_1 = [x1, x2, x3, ... , xn] And want to get this: list_2 = [func(x1), func(x2), func(x3), ... , func(xn)] A Python-ish implementation to get list_2 from list_1 could be: # not real executable code! # func takes exactly one argument and returns one list_1 = [x1, x2, x3, ..., xn] list_2 = [] for value in list_1: list_2.append(func(value)) There's an even nicer syntax in Python to do exactly that: We could use a list comprehension: # not real executable code! list_1 = [x1, x2, x3, ..., xn] list_2 = [func(value) for value in list_1] If the function body is just one expression, we could have just used that expression in the list comprehension instead of the function call. There is a third way to construct list_2, and that is with the already mentioned map function: # not real executable code! list_1 = [x1, x2, x3, ..., xn] list_2 = map(func, list_2) All of these examples do the same (almost: The result of map is not actually a list, but an iterator). And if you ask me: I like the last version best. But if you are relatively new to programming or only used to procedural style code, the last line might seem odd to you: Are we really passing the function itself? Yes, we do. Python allows us to do that. Other than in the other two examples, in the map example we never see the function func called – the calling of the function happens somewhere inside the map function. So we don't call the function func with a value, we pass it to the map function together with a list of all values. The map function doesn't only take lists: It takes e.g. range objects: result = map(func, range(10)) it takes generator expressions: squares = (x**2 for x in range(10)) result = map(func, squares) in short: It takes everything that can be iterated over. Both list comprehensions (together with its siblings, dict and set comprehensions as well as it's cousin, generator expressions) and map fall into the general category of functional programming. In this programming paradigm, we don't so much see a program as a series of commands being executed one after another, but rather as as a composition of functions and expressions. Python, while not a full-fledged functional language, offers quite some practical constructs that help with a functional line of thinking. Aside from map, there's filter, the ability to create closures, decorators fall into this category and all the immensely useful tools in the itertools module. A characteristic trait of functional programming is the lack of explicit loops. Now that we have acquired a tiny overview over the functional view on programming, here is The Whole Point: How partial Fits In As you may have noticed, the function passed to map is fed only one value from the list at a time. In other words, you may only use functions that take exactly one argument. If you have a function that takes more – well, bad luck. If there only was a way to fixate all function parameters besides one … OK, no more drama: You have observed the awesome power of partial to fix parameters, and so it's a perfect fit for map, filter, functools.reduce and all the other juicy functional bits Python has to offer. While we could use wrappers or other ways to reduce the amount of function parameters to one, partial is so nice because it goes well with a functional style of coding. Let's go Back To Our Physicists Program At first glance, the calculate function above is a good match for the map method of multiprocessing.Pool. It takes one value, returns one, all is well. Or is it? Notice how I subtly hinted on the existence of physical parameters which were implemented as global variables that are used within the calculate function. As it turned out, we had to refactor the calculate version to not depend on global state so that we could use it with Pool.map. That meant making the physical parameters arguments to our function, which then looked like that: def calculate(value, parameter1, parameter2, parameter3): ... Now it didn't depend on global state any more (which was good), but it still couldn't be used for map because it had multiple parameters (which was bad). My first reaction was to write a closure, but the multiprocessing module has quite some peculiarities, and, as it turned out, not liking closures as functions for Pool.map is one of them. So I remembered the partial function, we fixed the parameters to some values, used the Pool.map method and gained a 10x speed-up. True story. Wrapping Up I have used this real-world example because it is exemplary for almost all uses of partial in my code: Sometimes a functional approach matches the problem at hand best. That is often the case in very mathematical or otherwise algorithmic code that can't convincingly be represented by class-based OO. While this tutorial is a bit thin on content, I hope to have shed some light on the context where partial function application is useful in day-to-day code. On the theoretical side, there's the related subject of currying (wikipedia/currying) you might find interesting as a follow-on. On the practical side, I encourage you to try some of the functional tools Python offers, if you haven't done so already. I hope you enjoyed the article as much as I enjoyed writing it.
I want to use simple grid layout in my kivy program, but I don't appropriate example; here is my code: import kivy from kivy.uix.gridlayout import GridLayout from kivy.app import App from kivy.uix.button import Button layout = GridLayout(cols=2, row_force_default=True, row_default_height=40) layout.add_widget(Button(text='Hello 1', size_hint_x=None, width=100)) layout.add_widget(Button(text='World 1')) layout.add_widget(Button(text='Hello 2', size_hint_x=None, width=100)) layout.add_widget(Button(text='World 2')) raw_input() At the end I cant see any result (Just single white window, without any grid) Thanks for your attention
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.
I think the join syntax is slightly strange: >>> list = ['cow','dog','cat'] >>> print list.join() Traceback (most recent call last): File " AttributeError: 'list' object has no attribute 'join' >>> print join.list() Traceback (most recent call last): File " NameError: name 'join' is not defined >>> print ''.join.list Traceback (most recent call last): File " AttributeError: 'builtin_function_or_method' object has no attribute 'list' >>> print ''.join(list) cowdogcat >>> print ' '.join(list) cow dog cat >>> Ok if you try join a list of ints: >>> ' '.join([12,34,56,78]) Traceback (most recent call last): File " TypeError: sequence item 0: expected string, int found It will not work. What you need is to convert each int into a str. Nasty, I know : >>> ' '.join(map(str,([12,34,56,78]))) '12 34 56 78' Thanks to #python, in partic. dash
It's nearing the end of 2013 and I wanted to look back at some of the goals I set for myself this past year as well as reflect on some of the things that happened over the year. One of the biggest change for me this past year was the increase in running. Running moved from being just excercise to a pastime. My goal for the year was to enter and run in 4 races. I ende up running 6 races. Not only did I run 2 more races than I thought I would, the composition of the races was quite different. Last year at this time I was planning on running my first half marathon along with 3 5k races. I ended up running three half marathons, one 10k, and two 5k races. For all of the races except one of the half marathons I set a personal record. To recap I participated in 6 races, went through two pairs of shoes, ran over 830 miles. It was a good year for running. My work on buckit.io ended up faltering and eventually stopping over the past year. However, I have two new projects that I am currently working on. Emporium.io is a private package repository for python developers. While Verse is a frontend for blogging via github pages. Hopefully, I will have posts on both these projects in the near future. The best thing to happen to me this year was the birth of my second daughter. She was born this summer and has been a joy to watch grow over the past 6 months. My oldest daughter turned two this year and it has been fun to watch her learn to use words to not only talk but to sing as well. Our family had some ups and downs, but it's been a wonderful year all around. I'm very excited to see what the future holds for us. Coming up next, some plans for 2014. I've been traveling over the past few weekends. One of the things that I always try to do before getting on the plane is download the sphinx docs of any projects I might be working with. One thing that I love about the static html sphinx build is that it includes a search feature. However, that search feature only works when running the docs from an http server. If you try and use search when opening the files directly, you will get an error that looks something like this Origin null is not allowed by Access-Control-Allow-Origin. A quick fix is to use the builtin http server that comes from python. It serves local files from whatever directory it is launched in. So go into the html folder of your docs build and run python -m SimpleHTTPServer 8000. After that you should be able to see the docs by going to http://127.0.0.1:8000. One caveat is that you have to change the port for each set of docs you might want to run at a given time. Today I learned something new about custom headers, django and nginx. We have an endpoint in our django app that uses custom headers to validate a request, ala Amazon AWS requests. Basically, the client creates a hash and sets a header with the value. Then on the server side, we validate that the hash is valid and continue on. In development, everything was hunky dory. However, once we started testing in our staging environment, the headers were never getting to our django app. The only difference between the environments was the addition of nginx. After much hair pulling and grousing, we came upon this interesting configuration bit underscores_in_headers. It turns out that nginx will strip any headers it recieves that contain underscores, unless this flag is turned on. Moral of the story, don't use headers with underscores or turn on the flag in nginx. I recently switched the theme here in order to inspire myself to write more content. The only thing I was having issue with was getting code blocks to work correctly. Below is a sample from the markdown reference: require 'redcarpet' markdown = Redcarpet.new("Hello World!") puts markdown.to_html Some python thrown in to see what it looks like import stuff s = "Python syntax highlighting" print s Instead of resolutions, I try to set some personal goals each year. Some years it works, some years it doesn't. Last year I had 2 primary goals and I feel like I achieved each. The first was to end the year weighing under 200 pounds for the first time since high school. I'm happy to report that as of yesterday morning I weight 184 lbs, so unless I somehow consumed a significant amount of food while sleeping last night I met that goal. My second goal was to help organize a local conference. It wasn't quite a conference, but I did help run the Nashville Hack Day, a one day event where developers came together to hangout and share ideas. I recently had some people ask questions about installing django install distribute: curl -O http://python-distribute.org/distribute_setup.py sudo python distribute_setup.py (optional) - you can remove distribute_setup.py install pip: sudo easy_install pip install virtualenv: sudo pip install virtualenv activate virtualenv: mkdir -p ~/envs cd ~/envs virtualenv --no-site-packages --distribute django-env source ~/envs/django-env/bin/activate install django pip install django create new django project cd ~/ django-admin.py start project newproj
What I am trying to do is to get from SqlAlchemy entity definition all it's Column()'s, determine their types and constraints, to be able to pre-validate, convert data and display custom forms to user. How can I introspect it? Example: class Person(Base): ''' Represents Person ''' __tablename__ = 'person' # Columns id = Column(String(8), primary_key=True, default=uid_gen) title = Column(String(512), nullable=False) birth_date = Column(DateTime, nullable=False) I want to get this id, title, birth date, determine their restrictions (such as title is string and max length is 512 or birth_date is datetime etc) Thank you
A long time ago, I wrote a little python script to automatically log me on to the wireless network at my office. Here is the code: #!/opt/local/bin/python from urllib2 import urlopen from ClientForm import ParseResponse try: if "Logged on as" in urlopen("https://MYWIRELESS.com/logon").read(): print "Already logged on." else: forms = ParseResponse(urlopen("https://MYWIRELESS.com/logon"), backwards_compat=False) form = forms[0] form["username"], form["password"] = "ME", "MYPASSWD" urlopen(form.click()) print "Logged on. (probably :-)"; except IOError, e: print "Couldn't connect to wireless login page:\n", e I changed computers recently, and it stopped working. Now, I get the error: File "login.txt", line 4, in <module> from ClientForm import ParseResponse ImportError: No module named ClientForm which makes it look like I don't have some package (ClientForm) installed, so I installed it (sudo port install py-clientform), but I still get the same error. Does anyone have an idea what I'm doing wrong?
I have a problem with my "b" letter in Python shell in OS X. I can't type "b", but "B" worked fine. How can I solve this issue? I have the same issue. This happens when you use the MacPorts version of Python in Snow Leopard. I don't see this issue in Apple's Python that comes with Mac OS X. So, the workaround should be to set /opt/local/lib/python/site-packages:/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/ (or a different Python version) and use Apple's Python. Unfortunately, the workaround is not a wise one. Apple assumes that its version is unchanged when doing upgrades and other functions. Instead, it is recommended that if you wish to upgrade python or expand it that you install a local version, either under I also have the same problem, and I do not use the MacPorts version of python. I am using the latest version of I installed vpython using their latest binary and using their instructions. It comes with an installer so it is point and click. This is a modified version of Python 2.7.1. It is 32 bit version. (I believe they have not ported it to 64 bits). I then installed VPython-Mac-Py2.7-5.71. I followed this by scipy from www.scipy.org and matplotlib from matplotlib.sourceforge.net All of these installations use an installer. When I run python off their development tool, idle, or the vpython variant, vidle, I have no problems. If I open a terminal and run python from a bash shell, the shell will not recognize the "b" key in the keyboard. It will give you a 'bell' sound, instead of typing the 'character b'. However, you can enter the letter 'B'. Looks like this key is mapped to some incorrect non-displayed 'character', possibly the 'bell' character in old ASCII code. I tried changing the emulation to xterm, vt100, vt102. I also played with different encoding schemes like just using UTF-8. I also pressed different combination of special keys like command-b etc. Nothing worked. My only workaround is to write scripts off idle or vidle. I hope this helps clarify the problem. The problematic line in your readline.parse_and_bind("bind ^I rl_complete") # darwin libedit This try: import readline except ImportError: print "Module readline not available." else: import rlcompleter if 'libedit' in readline.__doc__: readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab: complete") First, this did not happen until I updated python 2.7.1 to 2.7.3. That said, the fix is on the line: old line: if(sys.platform == 'darwin'): #FIX new line: if(sys.platform == 'darwin') and 'libedit' in readline.__doc__: #FIX The full code in my ~/.pythonrc import atexit import os try: import readline except ImportError: print "Module readline not available." else: import rlcompleter import sys if(sys.platform == 'darwin') and 'libedit' in readline.__doc__: #FIX # OSX readline.parse_and_bind ("bind ^I rl_complete") else: # Linux readline.parse_and_bind("tab: complete") historyPath = os.path.expanduser("~/.pyhistory") def save_history(historyPath=historyPath): readline.write_history_file(historyPath) if os.path.exists(historyPath): readline.read_history_file(historyPath) atexit.register(save_history) del atexit, save_history, historyPath
I have been struggling to get the emailing to work in Django for logging as well as for 500 and 404 errors and for the life of me I cant get it to work. I have DEBUG=False and all the other settings. I have the below for the email settings: EMAIL_HOST = 'host' EMAIL_PORT = 587 EMAIL_HOST_USER = 'username' EMAIL_HOST_PASSWORD = 'password' EMAIL_SUBJECT_PREFIX = 'something' EMAIL_USE_TLS = True SERVER_EMAIL='[email protected]' I'm using Amazon SES for the above settings. I also have the following: SEND_BROKEN_LINK_EMAILS=True ADMINS = ( ('name', 'email'), ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', ) Is there anything else I'm missing?? Any help is appreciated.
March 22nd, 2011 at 9:37 pm by Dr. Drang The most recent update to iTunes broke some of my BBC Radio 2 scripts, the AppleScript and Python scripts I use with AudioHijack Pro to automate the recording and iTunesifying of shows I like. The failures occurred in the parts of the scripts that add artwork to the saved shows. I could have just deleted those parts—the artwork certainly isn’t a critical feature of the shows—but I like seeing Brian Matthew’s crinkly face smiling out at me from my iPod, so I decided to fix things. The problem was that I was using PICT files, saved in my ~/Pictures/bbc/ folder, as the album artwork. When I first wrote these scripts, I wanted to use PNG files as the artwork, but I couldn’t get them to work, so I was forced into using PICTs. Now that PICTs don’t work anymore, guess what does? This is why my molars are ground down to little stubs. So, back to PNGs. And while I was at it, I decided to clean up the bit of code that sets the path to the artwork file. It used to be a nasty kluge of do shell script and POSIX file; now it’s much cleaner. These lines, set artPath to ((path to pictures folder) as string) & "bbc:60s.png" set theArt to read (file artPath) as picture get the image from the PNG file, and this one set data of artwork 1 of theTrack to theArt saves it as the artwork for the track in iTunes. And since I was updating the AppleScripts, I figured it was worthwhile to update my Radio 2 Python library, too. The library was written to grab the stream URLs and the show tracklists from the Radio 2 website, and was specialized to the shows I was listening to back when I wrote it. Since then, I’ve stopped listening to Trevor Nelson, and Mark Lamarr pulled the plug on his great God’s Jukebox show. I’ve decided to give Bob Harris’s Saturday and Sunday shows a try, so the radio.py library has been expanded. Here’s the current version: python: 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: 'saturday': (5, re.compile(r'Bob Harris Saturday')), 12: 'sunday': (6, re.compile(r'Bob Harris Sunday'))} 13: 14: 15: def recentScheduleURL(showday, day=datetime.date.today()): 16: 'Return the schedule URL for the most recent showday (0=Mon, 6=Sun) on or before day.' 17: 18: if isinstance(showday, tuple): 19: backups = [ (day.weekday() - d) % 7 for d in showday ] 20: backup = datetime.timedelta(min(backups)) 21: else: 22: backup = datetime.timedelta((day.weekday() - showday) % 7) 23: programDay = day - backup 24: return 'http://www.bbc.co.uk/radio2/programmes/schedules/%d/%02d/%02d' % (programDay.year, programDay.month, programDay.day) 25: 26: 27: def programCode(show): 28: 'Return the code of the program page for showname on the most recent showday.' 29: try: 30: schedHTML = urllib.urlopen(recentScheduleURL(showinfo[show][0])).read() 31: schedSoup = BeautifulSoup.BeautifulSoup(schedHTML) 32: return schedSoup.find(name='span', text=showinfo[show][1]).parent.parent['href'].split('/')[-1] 33: except KeyError: 34: return None 35: 36: def trackList(code): 37: 'Return text with the track and artist names for each song played.' 38: 39: # Get all the track info 40: progURL = 'http://bbc.co.uk/programmes/' + code 41: progHTML = urllib.urlopen(progURL).read() 42: progSoup = BeautifulSoup.BeautifulSoup(progHTML) 43: tracklist = progSoup.findAll('div', 'segment music-segment') 44: 45: # Create a list of songs with title and artist. 46: songinfo = [] 47: for t in tracklist: 48: try: 49: track = t.find('span', 'track').string 50: artist = t.find('span', 'artist').string 51: songinfo.append('%s\nby %s' % (track, artist)) 52: except AttributeError: 53: continue 54: 55: # Generate a plain text list of the song information. 56: songs = '\n\n'.join(songinfo) 57: songs = BeautifulSoup.BeautifulStoneSoup(songs, convertEntities=BeautifulSoup.BeautifulStoneSoup.HTML_ENTITIES) 58: 59: # Get the date of the show. 60: bdate = progSoup.find('div', 'date').span.string 61: 62: return '%s\n\n%s' % (bdate, songs) You’ll note I haven’t deleted the Lamarr or Nelson entries. It costs nothing to keep them in, and the entries may come in handy someday. The showinfo dictionary is the means by which the Radio 2 schedule is searched for show codes. For example, Sounds of the 60s appears on the Saturday (weekday number 5) schedule. The recentScheduleURL function returns the URL of the Radio 2 schedule page of the most recent day with a weekday number of the argument showday. The weekday numbers run from 0 for Monday to 6 for Sunday. The programCode function returns the eight-character string that uniquely identifies the show given as the argument. For example, calling programCode('60s') today will return b00zh2mq, which is the code for last Saturday’s episode of Sounds of the 60s. This code is the key to getting all the information about the episode. The episode page, which includes all the songs played on the show is at http://bbc.co.uk/programmes/b00zh2mq and the show is streamed at http://bbc.co.uk/iplayer/console/b00zh2mq Finally, the trackList function takes the program code and returns a nice plain text version of the track listing for the episode. This is what I save as the “lyrics” of the show in iTunes so I can easily get the name and artist of tracks I find interesting. The radio2-stream and radio2-tracklist scripts, which are also in the GitHub repository use the radio2.py library in what I think are obvious ways to return exactly what you’d expect. Running radio2-stream 60s in Terminal today yields http://bbc.co.uk/iplayer/console/b00zh2mq and running radio2-tracklist 60s yields something thats too long to bother posting here, but it starts with Sat 19 Mar 2011Shakin All Overby Johnny Kidd & The PiratesMidnight Confessionsby The Grass Roots and ends, as all the Sounds of the 60s shows do, with Foot Tapperby The Shadows A couple of notes: First, I know there are ways to download BBC shows directly, rather than recording them from streams, but I’ve never gotten them to work reliably. This may be due to limitations the BBC puts on downloads from outside the UK, or it may be due to my own mistakes. Either way, I’ve stuck with AudioHijack Pro because it works for me. Second, it’s very easy to adapt these scripts to other shows on Radio 2 and almost as easy to adapt them to shows on other stations. I talked about that in this post from a couple of years ago.
I want to encrypt few files using python what is the best way I can use gpg/pgp using any standard/famous python libraries? It has a Python interface. Warning: it is a low-level interface, not very Pythonic. If you read French, see examples. Here is one, to check a signature: signed = core.Data(sys.stdin.read()) plain = core.Data() context = core.Context() context.op_verify(signed, None, plain) result = context.op_verify_result() sign = result.signatures while sign: if sign.status != 0: print "BAD signature from:" else: print "Good signature from:" print " uid: ", context.get_key(sign.fpr, 0).uids.uid print " timestamp: ", sign.timestamp print " fingerprint:", sign.fpr sign = sign.next See Google's Keyczar project, which provides a nice set of interfaces to PyCrypto's functionality. I use pyOpenSSL, its a python binding for OpenSSL which has been around for a long time and is very well tested. I did some benchmarks for my application, which is very crypto intensive and it won hands down against pyCrypto. YMMV. I like pyDes (http://twhiteman.netfirms.com/des.html). It's not the quickest, but it's pure Python and works very well for small amounts of encrypted data.
About Python Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components or services. Python supports modules and packages, thereby encouraging program modularity and code reuse. About this article Python’s simple, easy-to-learn syntax can mislead Python developers – especially those who are newer to the language – into missing some of its subtleties and underestimating the power of the diverse Python language. With that in mind, this article presents a “top 10” list of somewhat subtle, harder-to-catch mistakes that can bite even some more advanced Python developers in the rear. (Note: This article is intended for a more advanced audience than Common Mistakes of Python Programmers, which is geared more toward those who are newer to the language.) Common Mistake #1: Misusing expressions as defaults for function arguments Python allows you to specify that a function argument is optional by providing a default value for it. While this is a great feature of the language, it can lead to some confusion when the default value is mutable. For example, consider this Python function definition: >>> def foo(bar=[]): # bar is optional and defaults to [] if not specified ... bar.append("baz") # but this line could be problematic, as we'll see... ... return bar A common mistake is to think that the optional argument will be set to the specified default expression each time the function is called without supplying a value for the optional argument. In the above code, for example, one might expect that calling foo() repeatedly (i.e., without specifying a bar argument) would always return 'baz', since the assumption would be that each time foo() is called (without a bar argument specified) bar is set to [] (i.e., a new empty list). But let’s look at what actually happens when you do this: >>> foo() ["baz"] >>> foo() ["baz", "baz"] >>> foo() ["baz", "baz", "baz"] Huh? Why did it keep appending the default value of "baz" to an existing list each time foo() was called, rather than creating a new list each time? The more advanced Python programming answer is that the default value for a function argument is only evaluated once, at the time that the function is defined. Thus, the bar argument is initialized to its default (i.e., an empty list) only when foo() is first defined, but then calls to foo() (i.e., without a bar argument specified) will continue to use the same list to which bar was originally initialized. FYI, a common workaround for this is as follows: >>> def foo(bar=None): ... if bar is None: # or if not bar: ... bar = [] ... bar.append("baz") ... return bar ... >>> foo() ["baz"] >>> foo() ["baz"] >>> foo() ["baz"] Common Mistake #2: Using class variables incorrectly Consider the following example: >>> class A(object): ... x = 1 ... >>> class B(A): ... pass ... >>> class C(A): ... pass ... >>> print A.x, B.x, C.x 1 1 1 Makes sense. >>> B.x = 2 >>> print A.x, B.x, C.x 1 2 1 Yup, again as expected. >>> A.x = 3 >>> print A.x, B.x, C.x 3 2 3 What the $%#!&?? We only changed A.x. Why did C.x change too? In Python, class variables are internally handled as dictionaries and follow what is often referred to as Method Resolution Order (MRO). So in the above code, since the attribute x is not found in class C, it will be looked up in its base classes (only A in the above example, although Python supports multiple inheritance). In other words, C doesn’t have its own x property, independent of A. Thus, references to C.x are in fact references to A.x. This causes a Python problem unless it’s handled properly. Learn more aout class attributes in Python. Common Mistake #3: Specifying parameters incorrectly for an exception block Suppose you have the following code: >>> try: ... l = ["a", "b"] ... int(l[2]) ... except ValueError, IndexError: # To catch both exceptions, right? ... pass ... Traceback (most recent call last): File "<stdin>", line 3, in <module> IndexError: list index out of range The problem here is that the except statement does not take a list of exceptions specified in this manner. Rather, In Python 2.x, the syntax except Exception, e is used to bind the exception to the optional second parameter specified (in this case e), in order to make it available for further inspection. As a result, in the above code, the IndexError exception is not being caught by the except statement; rather, the exception instead ends up being bound to a parameter named IndexError. The proper way to catch multiple exceptions in an except statement is to specify the first parameter as a tuple containing all exceptions to be caught. Also, for maximum portability, use the as keyword, since that syntax is supported by both Python 2 and Python 3: >>> try: ... l = ["a", "b"] ... int(l[2]) ... except (ValueError, IndexError) as e: ... pass ... >>> Common Mistake #4: Misunderstanding Python scope rules Python scope resolution is based on what is known as the LEGB rule, which is shorthand for Local, Enclosing, Global, Built-in. Seems straightforward enough, right? Well, actually, there are some subtleties to the way this works in Python, which brings us to the common more advanced Python programming problem below. Consider the following: >>> x = 10 >>> def foo(): ... x += 1 ... print x ... >>> foo() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in foo UnboundLocalError: local variable 'x' referenced before assignment What’s the problem? The above error occurs because, when you make an assignment to a variable in a scope, that variable is automatically considered by Python to be local to that scope and shadows any similarly named variable in any outer scope. Many are thereby surprised to get an UnboundLocalError in previously working code when it is modified by adding an assignment statement somewhere in the body of a function. (You can read more about this here.) It is particularly common for this to trip up developers when using lists. Consider the following example: >>> lst = [1, 2, 3] >>> def foo1(): ... lst.append(5) # This works ok... ... >>> foo1() >>> lst [1, 2, 3, 5] >>> lst = [1, 2, 3] >>> def foo2(): ... lst += [5] # ... but this bombs! ... >>> foo2() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in foo UnboundLocalError: local variable 'lst' referenced before assignment Huh? Why did foo2 bomb while foo1 ran fine? The answer is the same as in the prior example problem, but is admittedly more subtle. foo1 is not making an assignment to lst, whereas foo2 is. Remembering that lst += [5] is really just shorthand for lst = lst + [5], we see that we are attempting to assign a value to lst (therefore presumed by Python to be in the local scope). However, the value we are looking to assign to lst is based on lst itself (again, now presumed to be in the local scope), which has not yet been defined. Boom. Common Mistake #5: Modifying a list while iterating over it The problem with the following code should be fairly obvious: >>> odd = lambda x : bool(x % 2) >>> numbers = [n for n in range(10)] >>> for i in range(len(numbers)): ... if odd(numbers[i]): ... del numbers[i] # BAD: Deleting item from a list while iterating over it ... Traceback (most recent call last): File "<stdin>", line 2, in <module> IndexError: list index out of range Deleting an item from a list or array while iterating over it is a Python problem that is well known to any experienced software developer. But while the example above may be fairly obvious, even advanced developers can be unintentionally bitten by this in code that is much more complex. Fortunately, Python incorporates a number of elegant programming paradigms which, when used properly, can result in significantly simplified and streamlined code. A side benefit of this is that simpler code is less likely to be bitten by the accidental-deletion-of-a-list-item-while-iterating-over-it bug. One such paradigm is that of list comprehensions. Moreover, list comprehensions are particularly useful for avoiding this specific problem, as shown by this alternate implementation of the above code which works perfectly: >>> odd = lambda x : bool(x % 2) >>> numbers = [n for n in range(10)] >>> numbers[:] = [n for n in numbers if not odd(n)] # ahh, the beauty of it all >>> numbers [0, 2, 4, 6, 8] Common Mistake #6: Confusing how Python binds variables in closures Considering the following example: >>> def create_multipliers(): ... return [lambda x : i * x for i in range(5)] >>> for multiplier in create_multipliers(): ... print multiplier(2) ... You might expect the following output: 02468 But you actually get: 88888 Surprise! This happens due to Python’s late binding behavior which says that the values of variables used in closures are looked up at the time the inner function is called. So in the above code, whenever any of the returned functions are called, the value of i is looked up in the surrounding scope at the time it is called (and by then, the loop has completed, so i has already been assigned its final value of 4). The solution to this common Python problem is a bit of a hack: >>> def create_multipliers(): ... return [lambda x, i=i : i * x for i in range(5)] ... >>> for multiplier in create_multipliers(): ... print multiplier(2) ... 0 2 4 6 8 Voilà! We are taking advantage of default arguments here to generate anonymous functions in order to achieve the desired behavior. Some would call this elegant. Some would call it subtle. Some hate it. But if you’re a Python developer, it’s important to understand in any case. Common Mistake #7: Creating circular module dependencies Let’s say you have two files, a.py and b.py, each of which imports the other, as follows: In a.py: import b def f(): return b.x print f() And in b.py: import a x = 1 def g(): print a.f() First, let’s try importing a.py: >>> import a 1 Worked just fine. Perhaps that surprises you. After all, we do have a circular import here which presumably should be a problem, shouldn’t it? The answer is that the mere presence of a circular import is not in and of itself a problem in Python. If a module has already been imported, Python is smart enough not to try to re-import it. However, depending on the point at which each module is attempting to access functions or variables defined in the other, you may indeed run into problems. So returning to our example, when we imported a.py, it had no problem importing b.py, since b.py does not require anything from a.py to be defined at the time it is imported. The only reference in b.py to a is the call to a.f(). But that call is in g() and nothing in a.py or b.py invokes g(). So life is good. But what happens if we attempt to import b.py (without having previously imported a.py, that is): >>> import b Traceback (most recent call last): File "<stdin>", line 1, in <module> File "b.py", line 1, in <module> import a File "a.py", line 6, in <module> print f() File "a.py", line 4, in f return b.x AttributeError: 'module' object has no attribute 'x' Uh-oh. That’s not good! The problem here is that, in the process of importing b.py, it attempts to import a.py, which in turn calls f(), which attempts to access b.x. But b.x has not yet been defined. Hence the AttributeError exception. At least one solution to this is quite trivial. Simply modify b.py to import a.py within g(): x = 1 def g(): import a # This will be evaluated only when g() is called print a.f() No when we import it, everything is fine: >>> import b >>> b.g() 1 # Printed a first time since module 'a' calls 'print f()' at the end 1 # Printed a second time, this one is our call to 'g' Common Mistake #8: Name clashing with Python Standard Library modules One of the beauties of Python is the wealth of library modules that it comes with “out of the box”. But as a result, if you’re not consciously avoiding it, it’s not that difficult to run into a name clash between the name of one of your modules and a module with the same name in the standard library that ships with Python (for example, you might have a module named email.py in your code, which would be in conflict with the standard library module of the same name). This can lead to gnarly problems, such as importing another library which in turns tries to import the Python Standard Library version of a module but, since you have a module with the same name, the other package mistakenly imports your version instead of the one within the Python Standard Library. This is where bad Python errors happen. Care should therefore be exercised to avoid using the same names as those in the Python Standard Library modules. It’s way easier for you to change the name of a module within your package than it is to file a Python Enhancement Proposal (PEP) to request a name change upstream and to try and get that approved. Common Mistake #9: Failing to address differences between Python 2 and Python 3 Consider the following file foo.py: import sys def bar(i): if i == 1: raise KeyError(1) if i == 2: raise ValueError(2) def bad(): e = None try: bar(int(sys.argv[1])) except KeyError as e: print('key error') except ValueError as e: print('value error') print(e) bad() On Python 2, this runs fine: $ python foo.py 1key error1$ python foo.py 2value error2 But now let’s give it a whirl on Python 3: $ python3 foo.py 1 key error Traceback (most recent call last): File "foo.py", line 19, in <module> bad() File "foo.py", line 17, in bad print(e) UnboundLocalError: local variable 'e' referenced before assignment What has just happened here? The “problem” is that, in Python 3, the exception object is not accessible beyond the scope of the except block. (The reason for this is that, otherwise, it would keep a reference cycle with the stack frame in memory until the garbage collector runs and purges the references from memory. More technical detail about this is available here). One way to avoid this issue is to maintain a reference to the exception object outside the scope of the except block so that it remains accessible. Here’s a version of the previous example that uses this technique, thereby yielding code that is both Python 2 and Python 3 friendly: import sys def bar(i): if i == 1: raise KeyError(1) if i == 2: raise ValueError(2) def good(): exception = None try: bar(int(sys.argv[1])) except KeyError as e: exception = e print('key error') except ValueError as e: exception = e print('value error') print(exception) good() Running this on Py3k: $ python3 foo.py 1key error1$ python3 foo.py 2value error2 Yippee! (Incidentally, our Python Hiring Guide discusses a number of other important differences to be aware of when migrating code from Python 2 to Python 3.) Common Mistake #10: Misusing the __del__ method Let’s say you had this in a file called mod.py: import foo class Bar(object): ... def __del__(self): foo.cleanup(self.myhandle) And you then tried to do this from another_mod.py: import mod mybar = mod.Bar() You’d get an ugly AttributeError exception. Why? Because, as reported here, when the interpreter shuts down, the module’s global variables are all set to None. As a result, in the above example, at the point that __del__ is invoked, the name foo has already been set to None. A solution to this somewhat more advanced Python programming problem would be to use atexit.register() instead. That way, when your program is finished executing (when exiting normally, that is), your registered handlers are kicked off before the interpreter is shut down. With that understanding, a fix for the above mod.py code might then look something like this: import foo import atexit def cleanup(handle): foo.cleanup(handle) class Bar(object): def __init__(self): ... atexit.register(cleanup, self.myhandle) This implementation provides a clean and reliable way of calling any needed cleanup functionality upon normal program termination. Obviously, it’s up to foo.cleanup to decide what to do with the object bound to the name self.myhandle, but you get the idea. Wrap-up Python is a powerful and flexible language with many mechanisms and paradigms that can greatly improve productivity. As with any software tool or language, though, having a limited understanding or appreciation of its capabilities can sometimes be more of an impediment than a benefit, leaving one in the proverbial state of “knowing enough to be dangerous”. Familiarizing oneself with the key nuances of Python, such as (but by no means limited to) the moderately advanced programming problems raised in this article, will help optimize use of the language while avoiding some of its more common errors. You might also want to check out our Insider’s Guide to Python Interviewing for suggestions on interview questions that can help identify Python experts. We hope you’ve found the pointers in this article helpful and welcome your feedback.
If you are dealing with large areas on the map, you should set geometria = models.PolygonField(srid=4326, null=True, geography=True) As mentioned in geodjango's documentation https://docs.djangoproject.com/en/dev/ref/contrib/gis/model-api/#geography Geography Type In PostGIS 1.5, the geography type was introduced -- it provides native support for spatial features represented with geographic coordinates (e.g., WGS84 longitude/latitude). [7] Unlike the plane used by a geometry type, the geography type uses a spherical representation of its data. Distance and measurement operations performed on a geography column automatically employ great circle arc calculations and return linear units. In other words, when ST_Distance is called on two geographies, a value in meters is returned (as opposed to degrees if called on a geometry column in WGS84). If you do not have geography=True, we are storing things as plain geometries, we will need to do conversion from square degrees (the floating point result you are getting) into a unit of measure you prefer because we cannot calculate area from geographic coordinates. We can instead add a helper method which is in a projected coordinate space to do the transformation: def get_acres(self): """ Returns the area in acres. """ # Convert our geographic polygons (in WGS84) # into a local projection for New York (here EPSG:32118) self.polygon.transform(32118) meters_sq = self.polygon.area.sq_m acres = meters_sq * 0.000247105381 # meters^2 to acres return acres Which projection we use depends on the extent of the data, and how accurate we need the results: here I've illustrated with a specific projection for part of New York, but if your data isn't particularly accurate, you could easily substitute a global projection or just use a simple formula.
DOM creation libraries JavaScript performance comparison Info Tests a number of ways of generating DOM. Preparation code <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script> <script src="https://rawgithub.com/KoryNunn/crel/master/crel.js"> </script> <script src="https://rawgithub.com/joestelmach/laconic/master/laconic.js"> </script> <script src="https://rawgithub.com/creationix/dombuilder/master/dombuilder.js"> </script> <script src="https://rawgithub.com/Humtron/Wee.js/master/wee.js"> </script> <script> Benchmark.prototype.setup = function() {     $('body').append(crel('div', {       'class': 'testDiv'     }));     var testDiv = $('.testDiv')[0]; }; Benchmark.prototype.teardown = function() {     $('.testDiv').remove(); }; </script> Preparation code output Test runner Warning! For accurate results, please disable Firebug before running the tests. (Why?) Java applet disabled. Test Ops/sec pending… laconic // created via https://github.com/KoryNunn/dom-to-js with laconic plugin testDiv.appendChild( $.el.section( $.el.h1("A title"), $.el.h2("A sub title"), $.el.br(), $.el.button({   "class": "things" }, "THING1"), $.el.button({   "class": "things" }, "THING2"), $.el.button({   "class": "things" }, "THING3"), $.el.button({   "class": "things" }, "THING4"), $.el.button({   "class": "things" }, "THING5"), $.el.button({   "class": "things" }, "THING6"), $.el.span({   "class": "majigger" }, $.el.a({   "href": "http://www.google.com" }, "A link")), "Blady bla bla, some text and that.", $.el.table({   "id": "initialtests" }, $.el.thead( $.el.tr( $.el.th("Column header"), $.el.th("another one"), $.el.th("AND ANOTHER"), $.el.th("OMG SO MANY COLUMN HEADERS"))), $.el.tbody( $.el.tr( $.el.td("1"), $.el.td("2"), $.el.td("3"), $.el.td("4")))))); pending… document.createElement // lazily created via https://github.com/KoryNunn/dom-to-js // Probably not the fastest, and definitely not the best way to do it, // but hey, its auto-generated.. testDiv.appendChild((function() {   var element = document.createElement("section");   var child0 = (function() {     var element = document.createElement("h1");     var child0 = document.createTextNode("A title");     element.appendChild(child0);     return element;   })();   element.appendChild(child0);   var child1 = (function() {     var element = document.createElement("h2");     var child0 = document.createTextNode("A sub title");     element.appendChild(child0);     return element;   })();   element.appendChild(child1);   var child2 = (function() {     var element = document.createElement("br");     return element;   })();   element.appendChild(child2);   var child3 = (function() {     var element = document.createElement("button");     element.setAttribute("class", "things");     var child0 = document.createTextNode("THING1");     element.appendChild(child0);     return element;   })();   element.appendChild(child3);   var child4 = (function() {     var element = document.createElement("button");     element.setAttribute("class", "things");     var child0 = document.createTextNode("THING2");     element.appendChild(child0);     return element;   })();   element.appendChild(child4);   var child5 = (function() {     var element = document.createElement("button");     element.setAttribute("class", "things");     var child0 = document.createTextNode("THING3");     element.appendChild(child0);     return element;   })();   element.appendChild(child5);   var child6 = (function() {     var element = document.createElement("button");     element.setAttribute("class", "things");     var child0 = document.createTextNode("THING4");     element.appendChild(child0);     return element;   })();   element.appendChild(child6);   var child7 = (function() {     var element = document.createElement("button");     element.setAttribute("class", "things");     var child0 = document.createTextNode("THING5");     element.appendChild(child0);     return element;   })();   element.appendChild(child7);   var child8 = (function() {     var element = document.createElement("button");     element.setAttribute("class", "things");     var child0 = document.createTextNode("THING6");     element.appendChild(child0);     return element;   })();   element.appendChild(child8);   var child9 = (function() {     var element = document.createElement("span");     element.setAttribute("class", "majigger");     var child0 = (function() {       var element = document.createElement("a");       element.setAttribute("href", "http://www.google.com");       var child0 = document.createTextNode("A link");       element.appendChild(child0);       return element;     })();     element.appendChild(child0);     return element;   })();   element.appendChild(child9);   var child10 = document.createTextNode("Blady bla bla, some text and that.");   element.appendChild(child10);   var child11 = (function() {     var element = document.createElement("table");     element.setAttribute("id", "initialtests");     var child0 = (function() {       var element = document.createElement("thead");       var child0 = (function() {         var element = document.createElement("tr");         var child0 = (function() {           var element = document.createElement("th");           var child0 = document.createTextNode("Column header");           element.appendChild(child0);           return element;         })();         element.appendChild(child0);         var child1 = (function() {           var element = document.createElement("th");           var child0 = document.createTextNode("another one");           element.appendChild(child0);           return element;         })();         element.appendChild(child1);         var child2 = (function() {           var element = document.createElement("th");           var child0 = document.createTextNode("AND ANOTHER");           element.appendChild(child0);           return element;         })();         element.appendChild(child2);         var child3 = (function() {           var element = document.createElement("th");           var child0 = document.createTextNode("OMG SO MANY COLUMN HEADERS");           element.appendChild(child0);           return element;         })();         element.appendChild(child3);         return element;       })();       element.appendChild(child0);       return element;     })();     element.appendChild(child0);     var child1 = (function() {       var element = document.createElement("tbody");       var child0 = (function() {         var element = document.createElement("tr");         var child0 = (function() {           var element = document.createElement("td");           var child0 = document.createTextNode("1");           element.appendChild(child0);           return element;         })();         element.appendChild(child0);         var child1 = (function() {           var element = document.createElement("td");           var child0 = document.createTextNode("2");           element.appendChild(child0);           return element;         })();         element.appendChild(child1);         var child2 = (function() {           var element = document.createElement("td");           var child0 = document.createTextNode("3");           element.appendChild(child0);           return element;         })();         element.appendChild(child2);         var child3 = (function() {           var element = document.createElement("td");           var child0 = document.createTextNode("4");           element.appendChild(child0);           return element;         })();         element.appendChild(child3);         return element;       })();       element.appendChild(child0);       return element;     })();     element.appendChild(child1);     return element;   })();   element.appendChild(child11);   return element; })()); pending… crel testDiv.appendChild( crel('section', crel('h1', "A title"), crel('h2', "A sub title"), crel('br'), crel('button', {   "class": "things" }, "THING1"), crel('button', {   "class": "things" }, "THING2"), crel('button', {   "class": "things" }, "THING3"), crel('button', {   "class": "things" }, "THING4"), crel('button', {   "class": "things" }, "THING5"), crel('button', {   "class": "things" }, "THING6"), crel('span', {   "class": "majigger" }, crel('a', {   "href": "http://www.google.com" }, "A link")), "Blady bla bla, some text and that.", crel('table', {   "id": "initialtests" }, crel('thead', crel('tr', crel('th', "Column header"), crel('th', "another one"), crel('th', "AND ANOTHER"), crel('th', "OMG SO MANY COLUMN HEADERS"))), crel('tbody', crel('tr', crel('td', "1"), crel('td', "2"), crel('td', "3"), crel('td', "4")))))); pending… creationix/dombuilder testDiv.appendChild(domBuilder([   ['section', ['h1', 'A title'],     ['h2', 'A sub title'],     ['br'],     ['button.things', 'THING1'],     ['button.things', 'THING2'],     ['button.things', 'THING3'],     ['button.things', 'THING4'],     ['button.things', 'THING5'],     ['button.things', 'THING6'],     ['span.majigger', ['a',     {       href: 'http://www.google.com'     }, 'A link']], 'Blady bla bla, some text and that.', ['table#initialtests', ['thead', ['tr', ['th', 'Column header'],       ['th', 'Another one'],       ['th', 'And another'],       ['th', 'OMG SO MANY COLUMN HEADERS']     ]],       ['tbody', ['tr', ['td', '1'],         ['td', '2'],         ['td', '3'],         ['td', '4']       ]]     ]   ] ])) pending… Wee.js testDiv.appendChild(         new Wee("section")                 .append(                         new Wee("h1").append("A title").self(),                         new Wee("h2").append("A sub title").self(),                         new Wee("br").self(),                         new Wee("button", { "class": "things" }).append("THING1").self(),                         new Wee("button", { "class": "things" }).append("THING2").self(),                         new Wee("button", { "class": "things" }).append("THING3").self(),                         new Wee("button", { "class": "things" }).append("THING4").self(),                         new Wee("button", { "class": "things" }).append("THING5").self(),                         new Wee("button", { "class": "things" }).append("THING6").self(),                         new Wee("span", { "class": "majigger" }).append(                                 new Wee("a", { "href": "http://www.google.com" }).append("A link").self()                         )                         .self(),                         "Blady bla bla, some text and that.",                         new Wee("table", { "id": "myTable" })                                 .append(                                         new Wee("thead")                                                 .append(                                                         new Wee("tr")                                                                 .append(                                                                         new Wee("th").append("Column header").self(),                                                                         new Wee("th").append("another one").self(),                                                                         new Wee("th").append("AND ANOTHER").self(),                                                                         new Wee("th").append("OMG SO MANY COLUMN HEADERS").self()                                                                 )                                                                 .self()                                                 )                                                 .self(),                                         new Wee("tbody")                                                 .append(                                                         new Wee("tr")                                                                 .append(                                                                         new Wee("td").append("1").self(),                                                                         new Wee("td").append("2").self(),                                                                         new Wee("td").append("3").self(),                                                                         new Wee("td").append("4").self()                                                                 )                                                                 .self()                                                 )                                                 .self()                                 )                                 .self()                 )                 .self() );   pending… Compare results of other browsers Revisions You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page: Revision 1: published by Kory Nunn Revision 2: published by Kory Nunn Revision 3: published Revision 4: published Revision 5: published by Jonathan Buchanan Revision 6: published Revision 7: published by Jeff Mangus Revision 8: published by Emilis Dambauskas Revision 9: published by Emilis Dambauskas Revision 10: published Revision 18: published by Ludovic Urbain Revision 19: published Revision 20: published by Alex Revision 21: published by Kory Revision 22: published by Forest Revision 23: published by Forest Revision 24: published by Forest
Possible Duplicate: How do you split a list into evenly sized chunks in Python? Let us have a list, there is always an even number of elements. We must break it down by pairing. Example: list['1','2','3','4'] need 1,2 and 3,4 Let us have a list, there is always an even number of elements. We must break it down by pairing. Example: list['1','2','3','4'] need 1,2 and 3,4 If you want two halfs of a list. l = [1,2,3,4] print l[:len(l)/2], l[len(l)/2:] >>> [1, 2] [3, 4] If you want split a list by pairs then your question is exact duplicate. >>> L = [1, 2, 3, 4] >>> pairs = zip(L[::2], L[1::2]) >>> print pairs [(1, 2), (3, 4)] Hope this helps You can use something like this too: lVals = xrange(1,101) size = len(lVals) output = ((lVals[i], lVals[i+1] if size > i+1 else None) for i in xrange(0, size, 2)) from itertools import izip_longest data = range(6) data_iters = [iter(data)] * 2 pairs = izip_longest(*data_iters) [pair for pair in pairs] >>> [(0, 1), (2, 3), (4, 5)] The clever part is that the two elements of data_iters refer to the same object. Izip_longest alternately consumes from the two iterators passed as arguments, but since they're referring to the same object, it effectively pairs the elements in the iterator. I take no credit for being clever here, upvote the comment I linked to if you liked my answer. :)
Right now, in emacs' python-mode line continuations are aligned to the end of the previous line, as follows: this_is_a_list_of_django_urls = ('', url(r'^admin/?', include(admin.site.urls)), url(r'^polls/?', include('polls.urls')) ) But I find the above to be pretty ugly. Is there any way to configure emacs' python-mode to autoindent like this: this_is_a_list_of_django_urls = ('', url(r'^admin/?', include(admin.site.urls)), url(r'^polls/?', include('polls.urls')) ) I find the second version to be much easier to read, and so I'd like hitting TAB to only indent by one level, rather than however much it takes to align with the end of the previous line.
I would like to find a Python script that will access an attribute table within a shapefile and either update or replace records inside a field column. More specifically, I would like to use the replace expression to convert a table record like "123-456-789" to "123456789". I have many records to process and would like the best approach to do this task using Python. What you need is an UpdateCursor. Your code would look something like the following: import arcpy # Create update cursor for feature class # rows = arcpy.UpdateCursor("path_to_your_data_here") for row in rows: # Fields from the table can be dynamically accessed from the row object. # Here, the field is named targetField as I don't know your field name targetRow = row.targetField #Assigns value of targetField to string row.targetField = targetRow.translate(None, '-') #Removes the dashes rows.updateRow(row) # Delete cursor and row objects to remove locks on the data # del row del rows If you don't have ArcPy, you can use dbfpy to directly access and edit the attributes in the shape file's dbf file. The syntax is rather simple: from dbfpy import dbf db = dbf.Dbf("your_file.dbf") #Editing a value, assuming you want to edit the first field of the first record rec = db[0] rec["FIRST_FIELD"] = "New value" rec.store() del rec db.close() Good luck! Alternatively and very straight forward you could also open the dbase table (dbf) coming with your shape in excel or libreoffice calc. They should be full editable and therefore you can simply remove all dashes in multiple columns. You may also use Field Calculator with Python expression
The Question is_match:(str, str) -> bool The first parameter is a puzzle and the second is a view. Return True iff the view could be a view of the given puzzle. My Answer I came up with this: def is_match(puzzle, view): if len(puzzle) != len(view): return False if len(puzzle) == len(view): return True I also found this online: def is_match(given_puzzle, view): if len(given_puzzle) != len(view): return False unique_letters = set(ch for ch in view if ch != '^') for (a, b) in zip(given_puzzle, view): if a in unique_letters and a != b: return False return True This issue I am having is that if I input: is_match('blah', 'tr^^') It will return True for both of the given codes. Which must be wrong due to the fact that the characters don't even match only the length of the string does What could i do to fix this?
Analysing recursive functions (or even evaulating them) is a nontrivial task. A (in my opinion) good introduction can be found in Don Knuths Concrete Mathematics. However, let's analyse these examples now: We define a function that gives us the time needed by a function. Let's say that t(n) denotes the time needed by pow(x,n), i.e. a function of n. Then we can conclude, that t(0)=c, because if we call pow(x,0), we have to check wether (n==0), and then return 1, wich can be done in constant time (hence the constant c). Now we consider the other case: n>0. Here we obtain t(n) = d + t(n-1). That's because we have again to check n==1, compute pow(x, n-1, hence (t(n-1)), and multiply the result by x. Checking and multiplying can be done in constant time (constant d), the recursive calculation of pow needs t(n-1). Now we can "expand" the term t(n): t(n) = d + t(n-1) = d + (d + t(n-2)) = d + d + t(n-2) = d + d + d + t(n-3) = ... = d + d + d + ... + t(1) = d + d + d + ... + c So, how long does it take until we reach t(1)? Since we start at t(n) and we subtract 1 in each step, it takes n-1 steps to reach t(n-(n-1)) = t(1). That, on the other hands, means, that we get n-1 times the constant d, and t(1) is evaluated to c. So we obtain: t(n) = ... d + d + d + ... + c = (n-1) * d + c So we get that t(n)=(n-1) * d + c wich is element of O(n). pow2 can be done using Masters theorem. Since we can assume that time functions for algorithms are monotonically increasing. So now we have the time t(n) needed for the computation of pow2(x,n): t(0) = c (since constant time needed fo computation of pow(x,0)) for n>0 we get / t((n-1)/2) + d if n is odd (d is constant cost) t(n) = < \ t(n/2) + d if n is even (d is constant cost) The above can be "simplified" to: t(n) = floor(t(n/2)) + d <= t(n/2) + d (since t is monotonically increasing) So we obtain t(n) <= t(n/2) + d, wich can be solved using the masters theorem to t(n) = O(log n) (see section Application to Popular Algorithms in the wikipedia link, example "Binary Search").
how do I print help info if no arguments are passed to python script? #!/usr/bin/env python import sys for arg in sys.argv: if arg == "do": do this if arg == "" print "usage is bla bla bla" what I'm missing is if arg == "" line that I don't know how to express :(
How can implement the equivalent of a __getattr__ on a class, on a module? Example When calling a function that does not exist in a module's statically defined attributes, I wish to create an instance of a class in that module, and invoke the method on it with the same name as failed in the attribute lookup on the module. class A(object): def salutation(self, accusative): print "hello", accusative # note this function is intentionally on the module, and not the class above def __getattr__(mod, name): return getattr(A(), name) if __name__ == "__main__": # i hope here to have my __getattr__ function above invoked, since # salutation does not exist in the current namespace salutation("world") Which gives: matt@stanley:~/Desktop$ python getattrmod.py Traceback (most recent call last): File "getattrmod.py", line 9, in <module> salutation("world") NameError: name 'salutation' is not defined
ehmicky Stego++, projet de bibliothèque de stéganographie Salut à tous, [Message mis à jour 19/11/11] Je suis actuellement sur un projet de stéganographie (art de dissimuler un message secret dans "quelque chose" (fichier, phrase, etc.) d'apparence banal). Il s'agit de faire une bibliothèque C++, Stego++, qui permette à tout développeur, même connaissant peu la stéganographie, de développer une application de stéganographie, ou de l'utiliser dans son travail. Elle sera sous licence LGPL3 et multi-plateforme (au moins Mac OS X, Windows, GNU/Linux et BSD). L'idée est de faire suivre cela par une commande Unix utilisant Stego++, puis par une appli avec GUI, mais le coeur du projet est la bibliothèque. Je n'ai rencontré que très peu de bibliothèque de stéganographie, et je pense qu'il s'agira de la première en fait qui soit complète (et pas centrée sur un format ou algo donné) et libre. Mes principaux objectifs pour Stego++ : 1) modulaire. De nombreuses méthodes de stego, même très différentes et sur des media très divers (texte, image, video, paquet TCP, système de fichier, etc.) pourront être implémentées sous forme de modules. 2) "secure". Les modules de stego devront répondre à des critères précis et chiffrés en matière de résistance aux attaques stéganalystiques. 3) simple. Un développeur ne connaissant rien en crypto ni en stego doit pouvoir lire la documentation de l'API et pouvoir après une demi-journée coder ce qu'il veut en quelques dizaines de lignes. L'API doit être aussi petite que possible, même si ce but rentrera nécessairement en conflit avec mon désir d'intégrer plusieurs fonctions comme l'authentification, compression, etc. Je suis en pleine recherche (lecture de beaucoup de travaux de recherches (j'en suis déjà à mon quatrième gros bouquin technique), de codes sources (au moins 150 logiciels à lire en diagonal), etc.) pour essayer d'avoir quelque chose de sérieux. Une fois le coeur de la biblio pensée et codée, je vous invite de tout coeur à collaborer ! - code commenté avec Doxygen - deux documentations, une pour l'API publique, une pour les contributeurs - utilisera Sourceforge ou quelque chose de similaire - une documentation supplémentaire vous expliquant les principes de bases de la stégo Pourquoi participer ? Parce que si jamais vous vous intéressez un peu à la crypto, vous serez passionnés par la stégo. De même que la crypto avant les années 70, la stégo reste un outil spécialisé pour agences gouvernementales (NSA, etc.) et groupes terroristes. De même que la crypto ou la robotique par le passé, son utilisation par les entreprises et le citoyen lambda me semblent encore sous-estimée, et il y a un grand essor à venir (et ce serait cool que le mouvement du libre en fasse partie). Je sais que beaucoup d'entre vous sont par ailleurs préoccupés par la mise à mal croissante de l'anonymat et de la liberté sur Internet. Je pense qu'il est possible de défier ces mesures par des logiciels de crypto et de stégo. En tant que développeurs, il est même de notre devoir de développer de tels logiciels pour que le citoyen lambda puisse continuer à utiliser les nouvelles technologies comme des merveilles pour nos libertés (de communication, d'apprentissage, etc.), et non devenir de simples consommateurs apathiques. Et je pense que, de même que la crypto aujourd'hui est aux premières lignes de ce combat (Tor, contournement du Great Chinese Firewall, monnaie cryptographique, etc.), la stégo le sera bientôt. (cf le mouvement cypherpunk) Il y a également plusieurs usages créatifs de la stégo possible : par exemple, je compte intégrer un procédé de watermarking de code GPL, permettant la détection rapide de code propriétaire utilisant du code GPL sans permission. Le projet me prend du temps et la phase implémentation ne sera qu'en dernier et sera courte, pour l'instant j'en suis à la phase apprentissage de bibliothèque/recherches sur la stego/penser à l'interface. Les technos pour l'instant sont : - General : C++ / Boost - Chiffrement : Crypto++ (j'hésite encore avec openssl) - Compression : libzpaq - Versioning : Git - Documentation : Doxygen - Build : CMake - Manipulation d'images : pas encore décidé - Internationalisation : gettext (traductions anglais et chinois prévues) Dernière modification par ehmicky (Le 19/11/2011, à 16:17) Hors ligne Shanx Re : Stego++, projet de bibliothèque de stéganographie Je trouve ça intéressant dans l'idée, même si moi je n'en vois pas trop l'utilité (pour l'utilisateur français lambda). Après, si ça peut être un outil pour lutter contre les dictatures, c'est cool « En vérité, je ne voyage pas, moi, pour atteindre un endroit précis, mais pour marcher : simple plaisir de voyager. » R. L. Stevenson -- Blog et randos Hors ligne lann Re : Stego++, projet de bibliothèque de stéganographie J'avais fait un truc dans le genre au début de mon apprentissage en C++. Les sources sont ici : sources Tout d'abord c'était au temps ou je codais avec les vilains MFC. Je sais c'est très mal mais à l'époque j'étais ignorant. Donc ce code est fait que Windows. Mais il y a peut-être quand même des choses intéressantes. Je crois que ce n'est pas tout à fait de la stéganographie puisque l'image n'est pas altérée, juste les bits qui ne servent pas pour l'affichage du fichier bmp. Et croyez moi, il peut en avoir beaucoup. A+ Hors ligne ehmicky Re : Stego++, projet de bibliothèque de stéganographie @Shanx : oui c'est mon but principal. D'ailleurs, je lis ta signature, et justement un système de fichier stéganographique a été développé par Julian Assange, et il a contribué à populariser la deniable encryption (qui est vraiment une idée ingénieuse). En France, on en a pas encore l'utilité, mais je suis sûr que le jour viendra bien tôt @Iann : merci pour les sources, je vais regarder. J'imagine que tu as modifié des champs de l'header/footer ou modifié la table des couleurs ? Dernière modification par ehmicky (Le 16/01/2011, à 10:33) Hors ligne lann Re : Stego++, projet de bibliothèque de stéganographie Oui c'est ça Et dans les couleurs du dessin, il me semble. A ce que je me rappelle. Hors ligne Chaussette Re : Stego++, projet de bibliothèque de stéganographie je déterre un peu le topic, faire de la sténo sur des images est très facile (dans le principe, le tout c ' est de le faire bien mathématiquement); proposer une gui qui permettrait de choisir une image et une info à coder (image, texte, lien) pour les lier serait facile aussi. Si tu as des connaissances en c ou c++ (bien que je ne vois pas l' intérêt de c++ dans ce genre de traitement ) lance toi ! Si tu veux je te fait ta gui en c/gtk ; le projet m' intéresse. Je peux peut-être aussi t' aider pour le moteur, mais je ne sais pas où tu en es et quels sont tes connaissances. J' imagine que tu sais ce que tu fait. Sinon as tu avancé ? Ce serait bien ..! cordialement chaussette Dernière modification par Chaussette (Le 18/02/2011, à 06:58) Les clowns se marient en grande pompes Hors ligne ehmicky Re : Stego++, projet de bibliothèque de stéganographie En fait j'ai toujours 0 code, mais je suis bien déterminé dans mon projet, parce que la partie "code" va être rapide comme tu le dis ça demande pas masse de code, c'est surtout la recherche avant qui prend du temps. Alors, sinon, en fait effectivement, ce qui est compliqué c'est la stégano elle-même. Parce que le niveau 0 de la stégano, à savoir modifier le bit le plus faible de chaque octet d'une image .bmp, peut être codé en 20 lignes. Par contre, il y a des trucs un peu plus compliqués : - application de principes comme la "deniable encryption" - étude de la stéganalyse pour pouvoir proposer quelque chose qui soit pas détectable par les méthodes statistiques de la stéganalyse (qui est un domaine assez jeune) - stégano "originale" : par exemple, je suis en train d'apprendre l'ASM x86 (et j'ai bien avancé) pour pouvoir dissimuler un message en modifiant une instruction par une/plusieurs autres identiques (ex : add ax,1 -> inc ax). Ce genre de trucs est relativement facilement détectable, et en plus j'ai cru comprendre que ce qui paraît être "à l'oeil" des instructions identiques, peuvent produire des conséquences différentes, par exemple avec plusieurs threads, ou sous des environnements particuliers. Tout ça pour dire que ce que je fais surtout là, c'est apprendre les connaissances en stégano et les bibliothèques nécessaires pour le projet. Pour l'instant j'en suis à : - C++ / Boost. - Gtkmm pour le GUI - Crypto++ pour la crypto - J'hésite encore sur la bibliothèque de manipulation d'images. Je préfère en utiliser une que manipuler directement la mémoire via des pointeurs, parce que c'est beaucoup plus simple pour tout ce qui est manipulation des headers, des coefficients de compression .jpeg, etc. Donc j'hésite d'un côté entre CIMG ou ImageMagick++, et de l'autre libpng et compagnie. - j'ai aussi appris libzpaq qui me permettra de compresser les data à dissimuler avant de les encrypter, ce qui au final dégradera moins le support (image, fichier, etc.) et sera donc moins détectable. - Doxygen pour la doc', Git pour les versions (projet sûrement hébergé sur Github). Ensuite, au niveau de mon planning, je pense : 1) développer le projet avec seulement stégano de fichier .png, .jpeg et .bmp sur le bit le plus faible, et dispo seulement en ligne de commande. 2) mettre en GUI en complément de la ligne de commande. 3) Si vraiment, j'en ai les compétences (ce dont je suis pas sûr), proposer une bibliothèque à partir du projet pour les développeurs qui veulent intégrer de la stégano dans leur propre projet sans se prendre la tête. Je suis vraiment persuadé que la stéganographie peut avoir, comme la crypto, des domaines d'applications bien plus larges que ce qu'on pense. 4) Ajouter de nouvelles méthodes de stégano : utilisation des facteurs de compression .jpeg, encodage de la table des index couleurs .gif, stégano sur fichier texte pur (remplacement de mot, etc.), stégano sur paquet TCP, etc. Donc, en fait pour le C++, y'a deux raisons : 1) J'ai en fait déjà une idée de l'architecture du projet, et j'aimerais faire une abstraction de chaque "méthode" de stégano pour pouvoir facilement ajouter de nouvelles méthodes, bien que complètement différentes d'un point de vue pratique, sans que cela chamboule tout le projet. En gros, une interface pour l'information à dissimuler, une autre pour la manière de la dissimuler (qui inclue la méthode + le "carrier", fichier porteur (même si je réfléchie à d'autres organisations possibles)), ce qui permettra par exemple de dissocier la chose à dissimuler (image, vidéo, texte) du carrier (image, vidéo, texte). Ca a des avantages, mais y'a aussi pas mal de problèmes que j'ai à résoudre. En tout cas, c'est pour ça notamment que j'avais pensé à une approche objet, et vu que la performance compte malgré tout, C++ me semblait le plus aproprié. Faire de la programmation objet en C, façon Glib, me donnerait vraiment un mal de crâne. 2) En conséquence, la plupart des bibliothèques dont j'ai déjà passé du temps à apprendre sont C++. Avec une chose en plus : l'interface (que ce soit GUI ou CLI) doit être "internationalized" pour favoriser l'ajout de nouvelles langues, puisque pour commencer il devrait y avoir au moins une version anglais/français (je peux le faire) ainsi qu'une version chinois probablement (j'ai sans doute un traducteur). Et le chinois contient des considérations de localisation vraiment particulières et pas simples. Donc comme tu le vois, c'est tout un projet, c'est pour ça que j'avais précisé au départ que y'aura pas une ligne de code avant au moins 6 mois. D'un autre côté, cela fait déjà 4/5 mois que je suis dessus quasiment tous les jours, donc ce sera pas un vaporware, la motivation est là depuis déjà un certain temps, et j'ai bien progressé d'ailleurs, même si l'apprentissage de théories et de bibliothèques ne se chiffre pas en lignes de code. En plus, j'ai entrepris de lire le code source des 10/15 projets libres qui existent déjà et de regarder les fonctionnalités des applis proprio existantes, donc ça fait beaucoup de boulot, mais je suis motivé parce que j'ai une amie militante en Chine qui pourrait directement bénéficier du logiciel pour des questions de censure. Donc, pour ton aide, en fait je connais (à peu près) Gtkmm, j'avais pensé le faire, mais ton aide est bien sûr bienvenue (merci), mais faut prendre en considération le fait que le GUI est dans la "phase 2", et aussi le problème entre C et C++. Au contraire, mes projets jusqu'ici sont solos et avoir une contribution serait une bonne expérience, c'est d'ailleurs dans cette optique que j'ai voulu héberger ça sous Github pour favoriser la collaboration (tout en sachant que 70% des projets libres sont solos). Maintenant, peut-être faut-il attendre de voir le projet émerger et que je code la "phase 1", ce qui arrivera pas avant 6 mois, je pense dans une fourchette 6 mois-1 an. Edit : sinon, en fait les trucs qui me rendraient vraiment un coup de main au niveau du moteur, sont au niveau de l'optimisation et tout ce qui touche à des choses trop complexes mathématiquement. J'ai fait des études littéraires, et j'ai un niveau en maths vraiment très mauvais, même si avant d'entreprendre ces études, j'avais un bon niveau et que j'ai appris des choses via l'informatique. Mais dans tout ce qui est algorithmique "très mathématique", je suis pas qualifié. Par ailleurs, l'ajout de nouveaux "modules", comme la stégano sur paquets TCP, ou les 70 autres manières de dissimuler un message sont aussi vraiment bienvenues, en plus si mon architecture est ok, ça devrait s'intégrer sans trop de problèmes, et certains modules peuvent certainement prendre pas plus de 100 à 200 lignes de code. Mais pour ça, il faut déjà avoir fait les phases précédentes. Dernière modification par ehmicky (Le 18/02/2011, à 21:34) Hors ligne Chaussette Re : Stego++, projet de bibliothèque de stéganographie salut, pour les autres méthodes de sténo il faudrait aussi penser à une approche analogique. En imaginant par exemple, que je colle des affiches dans la rue pour prévenir du prochain concert de l' association des chanteurs de yodoll en Chine ( ! ça risquerais plutôt d' attirer l' attention ) Un simple téléphone avec appareil photo et hop, plus qu' a copier ensuite sur l' ordi et traiter avec ton logiciel. Les clowns se marient en grande pompes Hors ligne ehmicky Re : Stego++, projet de bibliothèque de stéganographie Tu veux dire permettre d'utiliser de la reconnaissance de caractères ? Hors ligne ehmicky Re : Stego++, projet de bibliothèque de stéganographie Pourquoi les peuples ont besoin d'outils de stéganographie et de cryptographie libres et simples à utiliser. L'information est une arme, son contrôle un pouvoir. Dernière modification par ehmicky (Le 20/02/2011, à 18:04) Hors ligne Chaussette Re : Stego++, projet de bibliothèque de stéganographie salut, non je parle d' extraire une information stéga dans une donnée qui n' est pas forcement bien capturée/conservée/distribuée. Avec une approche analogique, si l' image par exemple est froissée ou qui lui manque un coin ce n' est pas grave, l' information sera quand même lisible. Et puis il faut imaginer tout les cas ou l' information codée logiciellement, ne transite pas de manière numérique et où il y perte de données; même si ces cas seront rares. Comme la pochette du cd plutôt que le cd lui-même, l' affiche qui subit des intempéries, le t-short ou le drapeau qui déforment l' image.. Tu peux même appliquer ce principe (quoique beaucoup plus difficile) dans des données numériques. Le net à tendance à copier, modifier, redistribuer l' information. Si ta donnée symbiote est tenace elle sera encore lisible. On peut imaginer qu' un nouveau buzz (une vidéo, une image, un texte) contienne de la stéga. Comme tout buzz il va se faire tronquer, hacher menu, et se retrouver dans diverses formes/conteneurs sur la toile. Dernière modification par Chaussette (Le 21/02/2011, à 09:03) Les clowns se marient en grande pompes Hors ligne Nasman Re : Stego++, projet de bibliothèque de stéganographie Il y a un paramètre à prendre en considération, c'est le rapport entre la quantité d'informations dissimulées et la taille du "support". Si on dissimule du texte brut (genre ascii), il sera possible de mettre pas mal d'information dans une image, une vidéo, de la musique..., si on veut dissimuler des choses plus lourdes (films...), ce sera plus dur. Je me suis déjà intéressé à la cryptographie et à la stéganographie et ai fait quelques programmes en assembleur (dont des calculs de transformée de Fourier rapide) - je pourrais peut être être utile. PC fixe et portable avec Precise 64 bits Hors ligne ehmicky Re : Stego++, projet de bibliothèque de stéganographie @Chaussette : ah oui, effectivement, j'y avais pensé, par exemple si on recompresse une image .jpg ou qu'on l'enregistre sous un autre format. Je vais prendre ça en compte ! @Nasman : je pensais calculer un "indice de dégradation" du support (carrier) qui indique à la fois la dégradation visible (ou auditive) du support mais aussi ses chances d'être repéré par une approche statistique, et d'afficher (dans le GUI ou le CLI) des avertissements en conséquences, mais ne pas empêcher le process même si cet indice est faible. Qu'en penses-tu ? Hors ligne Nasman Re : Stego++, projet de bibliothèque de stéganographie Je pensais à une autre chose : les modifications apportées au support ne doivent pas empêcher le fichier support de s'ouvrir correctement. Par exemple un fichier jpg source auquel on "rajoute" des éléments stéganographiques doit toujours avoir une structure de fichier jpg (donc s'ouvrir) et ne pas afficher clairement qu'il a été modifié. Quand on travaille sur une image bitmap (en altérant les bits de poids faible par exemple), on sait que les modifications seront quasiment indétectables. Pour les autres formats compressés ou d'encodage différent il faudra connaitre le principe de codage de l'image pour faire des modifs indétectables. En définitive il y aura deux possibilités : - image bitmap + texte codé, encodage non destructif, expédition, décodage non destructif, extraction du texte - image bitmap, encodage, rajout de texte codé, expédition, extraction du texte dans le deuxième cas l'étape décodage après expédition doit donner quelque chose similaire à l'image bitmap d'origine pour éviter la détection. PC fixe et portable avec Precise 64 bits Hors ligne ehmicky Re : Stego++, projet de bibliothèque de stéganographie En fait la stégano par modification du bit faible sur image .bmp est détectable par analyse statistique (même quand le message est mis en bouillie par un chiffrement symétrique). Sinon, mon but est de pas modifier le format du carrier : un .jpg doit resté .jpg. Donc effectivement pour les .jpg faut s'attaquer au format .jpg, mais y'a vraiment plein d'astuces impressionnantes qui existent déjà, par exemple en modifiant les coefficients de compression des blocs de pixels, en modifiant les headers, etc. C'est pour ça que je voulais utiliser une bibliothèque type libjpeg pour le faire, ce sera plus simple et le code sera plus clair. Hors ligne Airballman Re : Stego++, projet de bibliothèque de stéganographie Tu es en train de créer un soft qui fasse ça du coup ehmicky ? Hors ligne ehmicky Re : Stego++, projet de bibliothèque de stéganographie Oui, cf le topic, j'ai même mis les technos utilisées. Ce sera GPL3 et si y'a une API elle sera licence BSD-like ou LGPL3. Mais faut compter au moins 6 moins (=> septembre) avant de voir quelque chose. Hors ligne ehmicky Re : Stego++, projet de bibliothèque de stéganographie Je continue à étudier les autres logiciels, et je sens que y'a vraiment besoin d'un logiciel de stéganographie. Il y a en fait 150-200 outils déjà existants. Cependant, pour beaucoup d'entre eux, il y a un ou plusieurs de ces problèmes : - plus maintenu (80% d'entre eux). La moitié d'entre eux ne dépasse pas Windows 2000 - pas de GUI - Windows only - stégano faible (beaucoup de modif' sur least-significant bit sur fichier .bmp 24 bits only) - pas d'encryption, ou chiffrement faible (rot13 !) La plupart des outils existants ont au moins 1 de ces défauts, ou bien ne sont pas libres. Jusqu'ici je n'ai pas trouvé d'outils à la fois : - libre - avec GUI - multi-plateforme, et encore maintenu - avec stégano viable + chiffrement viable Je continue ma recherche, j'en trouverai peut-être. En tout cas, si j'en trouve pas, je commence vraiment à me dire que du coup ce sera bien de développer ça pour la communauté. En plus, j'aimerais aussi apporter : - CLI dispo en plus du GUI - une API avec une interface simple, "libstegano" - une documentation sur les outils et techniques de stegano existantes (celle que je fais en ce moment) - essayer de faire le logiciel de manière modulaire pour permettre simplement l'ajout de nouvelles techniques de stégano sous forme de modules. Et favoriser la collaboration avec Doxygen + Git. Je regarde aussi le code source des outils existants pour voir les algorithmes principaux, parce que certains sont très originaux. Dernière modification par ehmicky (Le 27/02/2011, à 17:57) Hors ligne Airballman Re : Stego++, projet de bibliothèque de stéganographie Si tu commences sérieusement à développer, et que tu as des besoins ça m'intéresse que tu le fasses savoir. Je pourrais peut-être te filer un coup de main sur certaines parties. (Par exemple ajout de fonctions de stégano dans ton logiciel . . . ) . Enfin à voir . Voilou. Hors ligne magestik Re : Stego++, projet de bibliothèque de stéganographie Salut, Si ça peut aider, j'avais découvert une technique imparable pour cacher des trucs dans des jpeg. J'avais trouvé ça quand j'ai cherché à comprendre comment fonctionnait le format MPO, qui est un format d'images 3D. Bref, le problème est pas là, mais j'ai réussi assez simplement à cacher du texte dans mon image. Après je mettais du texte "simple" mais après c'est du texte, j'aurais très bien pu le crypter. J'avais même distribué les sources, par contre j'avais pas fait de GUI, mais en GTK, avec glade, ça peut se faire assez rapidement. Si quelqu'un est intéressé, soit par les sources (ça faisait même pas 100 lignes), soit par la méthode en question (que je pourrais pas détailler en précision juste de tête vu que c'était du travail en hexadécimal) demandez moi Ou alors si quelqu'un veut le logiciel en question je peux faire une petite interface GTK et en faire un paquet DEB, pas de problème. Voilà, Magestik Hors ligne ehmicky Re : Stego++, projet de bibliothèque de stéganographie Salut, Effectivement, ce qui m'intéresserait, c'est l'algo lui-même. J'ai lu plusieurs textes sur le sujet, avec notamment surtout des méthodes modifiant les coefficients DCT, et puis des améiorations pour résister à une attaque stéganalystique. Il y a une dizaine d'outils sur ce principe et plusieurs travaux de recherche. C'est intéressant parce que ça résiste un peu aux recompression/recadrages, etc. Merci, tu peux décrire l'algo ou c'est trop long ? Hors ligne magestik Re : Stego++, projet de bibliothèque de stéganographie Ca va pas du tout chercher aussi. Déjà c'est quelque chose que j'ai complétement inventé (ça devait peut-être déjà exister), et comme je l'ai dit ça tient en même pas 200 ligne ... tout les programme en 200 lignes : lecture du texte dans une image (ou on avait déjà écrit), écriture (dans une nouvelle image) et saisie du texte qu'on veut mettre dans l'image. Le principe est très simple : en fait j'ouvrais l'image en hexadécimal, à la fin je rajoutais un header (hexadécimal) JPEG (c'est ça dont je me rappelle plus exactement la séquence, mais je sais même pas si on est obligé de mettre ça.). Et après ce deuxième header tu mettre tout ce que tu veux, pas de problème. Moi je mettais du texte en clair, mais rien ne t'empêche de mettre du texte crypté (avec le cryptage que tu veux) ou même le binaire d'une archive (j'avais essayé et ça avait marché). J'ai essayé d'ouvrir l'image avec plusieurs logiciels : aucun problème l'image s'ouvre comme si de rien n'était. Bon je pense que tu pensais à des choses beaucoup plus compliqué, mais cette méthode permet d'avoir quelque chose simple assez rapidement. Et pour peu que tu crypte ton texte comme il faut, alors pas de problème il devrait être illisible. Je m'y connais pas trop en cryptage, mais en C++ il doit pas manquer de lib pour faire ça. Après à toi de voir ce que tu veux faire. Petit hors-sujet pour ceux que ça intéresse : le format MPO c'est en fait une deuxième image JPEG après une deuxième. Donc on a notre première image avec son header JPEG et quand elle est finie on a notre deuxième header JPEG suivi de l'image en elle même. Si tu veux plus d'infos hésite pas Dernière modification par magestik (Le 01/03/2011, à 15:53) Hors ligne Airballman Re : Stego++, projet de bibliothèque de stéganographie Tu aurais pu mettre un lien vers les sources direct histoire de se faire une idée ^^ Hors ligne Airballman Re : Stego++, projet de bibliothèque de stéganographie Après ehmicky, si j'ai bien compris, en fait ce que tu cherches à faire est de rassembler toutes ces différentes méthodes dans un seul et même endroit et de mettre un joli empaquetage graphique par dessus . Je me trompe? Hors ligne magestik Re : Stego++, projet de bibliothèque de stéganographie Airballman> j'aurais pu, si je les avais mise en ligne. Mais quand j'ai écrit le message j'étais pas chez moi donc pas accès à mes fichiers. Mais maintenant c'est bon, j'ai accès à mes fichiers. Voilà le code en question, du moins ce que j'en ai retrouvé : import binascii image = raw_input() separateur = binascii.unhexlify('FFD8FFE1') f = open(image,'rw') files = f.read() f.write(files + separateur + "TEXTE") f.close() Hors ligne
From the comments at the top: I need to know if the OS is (Open)SUSE so as to use the correct package installer (zypper). If it is DEBIAN (For Example), I will use apt-get... I suggest you directly solve the actual problem. Instead of identifying the OS, identify the package manager available. import os def file_exists(fname): try: os.stat(fname) return True except OSError: return False if file_exists('/usr/bin/zypper'): ... # do the SUSE case elif file_exists('/usr/bin/apt-get'): ... # do the Debian/Ubuntu case elif file_exists('/usr/bin/yum'): ... # do the Red Hat case else: raise OSError, "cannot find a usable package manager" EDIT: Although the code here shows detecting the package manager program, it might be better to detect the main package registry itself. For example, on Debian/Ubuntu systems that use dpkg, there will be a directory /var/lib/dpkg holding the package database; that is a sure sign that dpkg or apt-get are appropriate. I don't know what the equivalent directories are for SUSE and Red Hat and so on, but if you are supporting those you can find out. apt-get has been ported to Red Hat systems, and via a program called alien you can get rpm on Debian systems, and so on. Detecting the package database itself is the most foolproof way of figuring out what package system is in use. If you detect the package manager, then your code will automatically work on all related distros. If you detect the dpkg database, your code will work on Debian, Ubuntu, Linux Mint, and the many other distros based on Debian. If you detect the rpm database, your code will work on Red Hat, Centos, Fedora, Mandriva, and all the many other distros based on RPM.
I have this code from a tutorial: #File called test 1 def sanitize(time_string): 2 if '-' in time_string: 3 splitter = '-' 4 elif ':' in time_string: 5 splitter = ':' 6 else: 7 return(time_string) 8 (mins, secs) = time_string.split(splitter) 9 return(mins + '.' + secs) 10 11 12 13 def get_coach_data(filename): 14 with open(filename) as f: 15 data = f.readline() 16 temp1 = data.strip().split(',') 17 return(Athlete(temp1.pop(0), temp1.pop(0), temp1) 18 19 20 james = get_coach_data('james2.txt') 21 julie = get_coach_data('julie2.txt') 22 mikey = get_coach_data('mikey2.txt') 23 sarah = get_coach_data('sarah2.txt') 24 25 print(james.name+"'s fastest times are: " + str(james.top3())) 26 print(juliename+"'s fastest times are: " + str(julie.top3())) 27 print(mikey.name+"'s fastest times are: " + str(mikey.top3())) 28 print(sarah.name+"'s fastest times are: " + str(sarah.top3())) and I put this class separately because I thought it may have been causing the error: 1 class Athlete: 2 def __init__(self, a_name, a_dob=None, a_times=[]): 3 self.name = a_name 4 self.dob = a_dob 5 self.times = a_times 6 7 def top3(self): 8 return(sorted(set([sanitize(t) for t in self.times]))[0:3]) The error is: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "test.py", line 20 james = get_coach_data('james2.txt') But the error doesn't make any sense. I am new to python. I appreciate anyones help. Thanks in advance.
i have two model which are Post and Profile. i am keepin blog datas which are title,body,owner,slug etc in Post. and keepin' user profile settings which are slogan,email,website etc. in Profile in my index.html page i display user profile infos and post lists in same page. so ; i need to connect these two models each other. when someone goes to 127.0.0.1/blog/username (with or without login) all the data which are belong to user named 'username' must be there. here is my models.py: class Profile(models.Model): slogan = models.TextField(blank=True) twitter = models.CharField(max_length = 100,blank=True) web_site = models.CharField(max_length=100,blank=True) email = models.CharField(max_length = 100,blank=True) def __unicode__(self): return self.slogan class Post(models.Model): owner = models.ForeignKey(User) title = models.CharField(max_length = 100) body = models.TextField() bodyPreview = models.TextField() #preview için body alanı titlePreview = models.CharField(max_length=100) # preview için title alanı slug = AutoSlugField(populate_from='title' ,unique=True) posted = models.DateField(auto_now_add=True) isdraft = models.BooleanField(default=False) def __unicode__(self): return self.title @permalink def get_absolute_url(self): return ('view_blog_post',None,{'postslug':self.slug}) and my index view : def index(request,username): post_list = Post.objects.filter(owner__username=username).filter(isdraft=False).order_by("-posted") p_index = Paginator(post_list,3) #anasayfa için pagination.[her sayfada 3 post] page = request.GET.get('page') try: indexPag = p_index.page(page) except PageNotAnInteger: indexPag = p_index.page(1) except EmptyPage: indexPag = p_index.page(p_index.num_pages) ## i need to get user's profile datas here. ?? return render_to_response('index.html', {'post_list':post_list,'p_index':indexPag,'profile':query}, context_instance = RequestContext(request))
I have a CSV file which is made of words in the first column. (1 word per row) I need to print a list of these words, i.e. CSV File: aandbecausehave Output wanted: "a","and","because","have" I am using python and so far I have the follwing code; text=open('/Users/jessieinchauspe/Dropbox/Smesh/TMT/zipf.csv') text1 = ''.join(ch for ch in text) for word in text1: print '"' + word + '"' +',' This is returning: "a","","a","n",... Whereas I need everything one one line, and not by character but by word. Thank you for your help! EDIT: this is a screenshot of the preview of the CSV file
Python Scripts as a Replacement for Bash Utility Scripts To demonstrate the power of combining Python scripts in a modular andpiped fashion, let's expand further on the problem space. Let's findthe top five users of the service. head is a commandthat allows you tospecify a certain number of lines to display of the standard input itis given. Adding this to the command chain gives the following: $ cat names.log | python namescount.py | sort -rn | head -n 5 This prints only the top five users and ignores the rest. Similarly, toget the five users who use the service least, you can use the tail command, whichtakes the same arguments. The result of the Python commandbeing printed to standard output allows you to build and extend uponits functionality. To demonstrate the modularity of this script, let's once again change the problem space. The service also generates a comma-separated value (CSV) log file that contains a list of e-mail addresses and the comments that each e-mail address made about the service. Here's an example entry: "[email protected]", "This service is great." The task is to provide a way for the service to send a thank-you message to the top ten users in terms of comment frequency. First, you need a script that can read and print a certain column of CSV data. The standard library of Python provides a CSV reader. The Python script below completes this goal: #!/usr/bin/env python # CSV module that comes with the Python standard library import csv import sys if __name__ == "__main__": # The CSV module exposes a reader object that takes # a file object to read. In this example, sys.stdin. csvfile = csv.reader(sys.stdin) # The script should take one argument that is a column number. # Command-line arguments are accessed via sys.argv list. column_number = 0 if len(sys.argv) > 1: column_number = int(sys.argv[1]) # Each row in the CSV file is a list with each # comma-separated value for that line. for row in csvfile: print row[column_number] This script can parse the CSV data and return in plain text thecolumn that is supplied as a command-line argument. It usesprintinstead of sys.stdout.write, asprint, by default, uses standard out asits output file. Let's add this script to the chain. The new script is chained with the others to print out a list of e-mail addresses and their comment frequencies using the command listed below (the .csv log file is assumed to be called emailcomments.csv and the new Python script, csvcolumn.py): $ cat emailcomments.csv | python csvcolumn.py | &rarrhk;python namescount.py | sort -rn | head -n 5 Next, you need a way to send an e-mail. In the Python standard library of functions, you can import smtplib, which is a module that allows you to connect to an SMTP server to send mail. Let's write a simple Python script that uses this library to send a message to each of the top ten e-mail addresses found already: #!/usr/bin/env python import smtplib import sys GMAIL_SMTP_SERVER = "smtp.gmail.com" GMAIL_SMTP_PORT = 587 GMAIL_EMAIL = "Your Gmail Email Goes Here" GMAIL_PASSWORD = "Your Gmail Password Goes Here" def initialize_smtp_server(): ''' This function initializes and greets the smtp server. It logs in using the provided credentials and returns the smtp server object as a result. ''' smtpserver = smtplib.SMTP(GMAIL_SMTP_SERVER, GMAIL_SMTP_PORT) smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo() smtpserver.login(GMAIL_EMAIL, GMAIL_PASSWORD) return smtpserver def send_thank_you_mail(email): to_email = email from_email = GMAIL_EMAIL subj = "Thanks for being an active commenter" # The header consists of the To and From and Subject lines # separated using a newline character header = "To:%s\nFrom:%s\nSubject:%s \n" % (to_email, from_email, subj) # Hard-coded templates are not best practice. msg_body = """ Hi %s, Thank you very much for your repeated comments on our service. The interaction is much appreciated. Thank You.""" % email content = header + "\n" + msg_body smtpserver = initialize_smtp_server() smtpserver.sendmail(from_email, to_email, content) smtpserver.close() if __name__ == "__main__": # for every line of input. for email in sys.stdin.readlines(): send_thank_you_mail(email) This Python script supports contacting any SMTP server, whether local or remote. For ease of use, I have included Gmail's SMTP server, and it should work, provided you give the scripts the correct Gmail credentials. The script uses the functions provided to send mail in smtplib. This again demonstrates the power of using Python at this level. Something like SMTP interaction is easy and readable in Python. Equivalent shell scripts are messy, and such libraries are not as easily accessible, if they exist at all. In order to send the e-mails to the top ten users sorted by commentfrequency, first you must isolate only the e-mail column of the output ofcolumn names. To isolate a certain column in Linux, you use thecutcommand. In the example below, the commands are given in twoseparate chains. For ease of use, I wrote the output into a temporaryfile, which can be loaded into the second chain. This simply makes theprocess more readable (the Python script for sending mail is referredto as sendemail.py): $ cat emailcomments.csv | python csvcolumn.py | &rarrhk;python namescount.py | sort -rn > /tmp/comment_freq $ cat /tmp/comment_freq | head -n 10 | cut -f2 | &rarrhk;python sendemail.py This shows the real power of Python as a utility in a chain of bash commands such as this. Writing scripts that accept input from standard input and write any data out to standard out, allows the developer to chain commands such as these together quickly and easily with a link in the chain often being a Python program. This philosophy of designing a small application that services one purpose fits nicely with the flow of commands being used here. Richard Delaney is a software engineer with Demonware Ireland. Richard works on back-end Web services using Python and the Django Web framework. He has been an avid Linux user and evangelist for the past five years. Geolocation Give new life to old phones and tablets with these tips! Lucidchart Linux Systems Administrator Memory Ordering in Modern Microprocessors, Part I Senior Perl Developer Technical Support Rep Source Code Scanners for Better Code Putlocker!! Watch Begin Again Online 2014 Streaming Full Movie Tech Tip: Really Simple HTTP Server with Python
I use poster.streaminghttp method to upload large file to sharepoint server. My code is working fine for BASIC authentication. But for NTLM, it is not working. How to authenticate ntlm if i use poster. for large file, i should import os import sys import time import base64 import hmac import mimetypes import urllib2 from hashlib import sha1 from poster.streaminghttp import register_openers import base64 def read_data(file_object): while True: r = file_object.read(64 * 1024) if not r: break file_object.close() yield r def upload_file(filename, bucket): print 'start' register_openers() length = os.stat(filename).st_size content_type = mimetypes.guess_type(filename)[0] print 'before' print 'after' input_file = open(filename, 'rb') data = read_data(input_file) request = urllib2.Request(bucket, data=data) base64string = base64.encodestring('IWSSPS\\adm:iws@123') auth_string = "NTLM %s" % base64string request.add_header('Content-Type', content_type) request.add_header('Content-Length', length) request.add_header('Authorization', auth_string) print 'before lamda' request.get_method = lambda: 'PUT' try : urllib2.urlopen(request) except Exception, e: print "Exception",e print "after lambda" upload_file('C:\\largeFile.pdf', "http://10.128.45.36:6864/doctest/ntlmmb.pdf")
Another strange thing - an endless paginator 21 Apr 2014 A little bit about my new program-frankenstein. Now it is an endless Paginator for Django. It sounds crazy, isn't? Standart Django Paginator uses the count() function for the verification of page number. It is converted to the SELECT COUNT(*) ... query, of course. But as I was explained (I really don't know, maybe it's just an exaggeration - you can post your opinion in the commentaries), this is not a such lightweight query, as we want for the paginated rest api, because of the MVCC in PostgreSQL. How we can avoid the extra COUNT(*) query? Don't panic, we can trick the Django. First of all we need to disable count parameter from the api response. We can introduce a custom pagination serializer: # serializers.py class CustomPaginationSerializer(BasePaginationSerializer): next = NextPageField(source='*') previous = PreviousPageField(source='*') # api.py class SomeListView(generics.ListAPIView): model = SomeModel serializer_class = SomeSerializerClass pagination_serializer_class = CustomPaginationSerializer The next our move - disable the page number verification. This can be done by the custom paginator class: class CustomPaginator(Paginator): """ HACK: To avoid unneseccary `SELECT COUNT(*) ...` paginator has an infinity page number and a count of elements. """ def _get_num_pages(self): """ Returns the total number of pages. """ return float('inf') num_pages = property(_get_num_pages) def _get_count(self): """ Returns the total number of objects, across all pages. """ return float('inf') count = property(_get_count) def _get_page(self, *args, **kwargs): return CustomPage(*args, **kwargs) class SomeListView(generics.ListAPIView): model = SomeModel serializer_class = SomeSerializerClass pagination_serializer_class = CustomPaginationSerializer paginator_class = CustomPaginator Oh, goodness - we introduced the infinity number of the pages and the infinity number of elements... But we want also the correct next/prev links, so one more detail: class CustomPage(Page): def has_next(self): """ HACK: Select object_list + 1 element to verify next page existense. """ low = self.object_list.query.__dict__['low_mark'] high = self.object_list.query.__dict__['high_mark'] self.object_list.query.clear_limits() self.object_list.query.set_limits(low=low, high=high+1) try: # len is used only for small portions of data (one page) if len(self.object_list) <= self.paginator.per_page: return False return True finally: # restore initial object_list count self.object_list = self.object_list[:(high-low)] This solution looks very questionable, but exciting for me. If you have something to say about this - welcome! =)
The goal is to get the array of family members made and print out the results in the order created. Is there any way to tidy this up :)? // Our Person constructor function Person(name,age) { this.name=name; this.age=age; } // Now we can make an array of people var family=new Array(); family[0]=new Person("alice", 40); family[1]=new Person("bob", 42); family[2]=new Person("michelle", 8); family[3]=new Person("timmy", 6); // loop through our new array for(i=0;i<family.length;i++) { console.log(family[i].name); } There are some ways to tidy things up. // Our Person constructor This comment doesn't explain anything that isn't already known. Comments should not say what is happening, they should explain the purpose instead, where the code can not be made clear enough to provide such an explanation for you. Instead of explaining what the code is already fully capable of showing you from the code itself, it's better to use comments to explain why things occur, or to provide a broad overview instead. function Person(name,age) Spacing. A space after the comma is best practice to help aid in readability. { Coding techniques from other programming languages, such as putting the curly brace at the start of the next line, is not just a bad idea - it can actually break JavaScript. Due to syntax limitations in JavaScript and how automatic semicolon insertion works, it is a fundamental principle in JavaScript that placing the curly brace at the start of a new line, is a practice that results in more fragile code. this.name=name; this.age=age; Spacing before and after the equals sign is best practice to help improve readability of the code. } That line is good, it has no problems. // Now we can make an array of people Explaining what is happening once again, which is not a good use for comments. var family=new Array(); family[0]=new Person("alice", 40); family[1]=new Person("bob", 42); family[2]=new Person("michelle", 8); family[3]=new Person("timmy", 6); It is preferred for the sake of consistency to use [] instead of new Array. You can also create those new Person objects at the same time as defining the array, for example with: It is also a common convention in JavaScript to use single quotes to delimit strings instead of double. Both work, but single provides more convenience than double. var family = [ new Person('alice', 40), new Person('bob', 42), new Person('michelle', 8), new Person('timmy', 6) ]; Due to the duplication that we see here though, it may be worth considering storing the name/age in an array, and using a loop to create the new Person objects instead. Especially if more people are planned to be added in further development. // loop through our new array Another useless comment. for(i=0;i<family.length;i++) The i variable has not been declared so it is going to be a global one instead. That's a bad mistake. The best way to remedy that is to declare the i variable right at the start of the code, with the other var declaration. Spacing should be added after the for word, which helps to reinforce that it is not a function name being called. Also, spacing before and after the equals sign, after the semicolons, and before and after the less than sign for improved readability. { Should come after the closing parenthesis of the for statement, with a space separating the two. console.log(family[i].name); Be aware that Internet Explorer doesn't support console.log - there are shims though that help to provide support, such as https://github.com/kayahr/console-shim } No troubles with this line So what we end up with is something like the following: // Create and show family info function Person(name, age) { this.name = name; this.age = age; } var family = [ new Person('alice', 40), new Person('bob', 42), new Person('michelle', 8), new Person('timmy', 6) ], i; for (i = 0; i < family.length; i += 1) { console.log(family[i].name); } I have also replaced i++ with i += 1 because I agree with Douglas Crockford, that incrementors and decrementors are not as good to use as other techniques that make it clearer what is going on. For some details, see http://stackoverflow.com/questions/971312/why-avoid-increment-and-decrement-operators-in-javascript Comments-I didn't create the comments. I just kept them there because of being lazy. So I'm ignoring any suggestions for that :). No offense to you. As for readability, I prefer no spaces in stuff such as (name,age). It helps my readability. I was mainly just asking for advice on how to shorten code, which you were able to answer with the array advice. console.log is just the part of the program that I'm supposed to write. I mean, I'm using codecademy.com and they force me to write console.log. Though again, comments based on that don't help me shorten the code. Thank you Paul for the array advice :). Another potential way to do that is to use the forEach method instead, which allows you to simplify things, and you won't need that variable either. family.forEach(function (person) { console.log(person.name); }); The forEach method is available on all modern web browsers. If you want it to succeed on Internet explorer, the forEach documentation page has compatibility code that adds the capability for web browsers that don't know how. Wow, that's some efficient looking code. Thanks for the advice Paul.
galanga Re : Qarte arte.tv browser (ex Qarte+7) @Christophe: content de voir que cela a commencé à fonctionner... Pour le second cas qui fait une erreur, c'est parce qu'il manque un back slash sur le guillemets fermant de ...3789-visual-crop-medium.jpg ; essayez avec cela : items.append("<item>\n <title>Dominique A Vers les Lueurs</title>\n <link>http://liveweb.arte.tv/fr/video/Dominique_A_Vers_les_Lueurs_Lieu_Unique/</link>\n <pubDate>Mon, 01 Aug 2012 01:00:00 +0200</pubDate>\n <description>Description DominiqueA</description>\n <author>DominiqueA</author>\n <enclosure url=\"http://download.liveweb.arte.tv/o21/liveweb/media/event/3789/3789-visual-crop-medium.jpg\" type=\"image/jpeg\" length=\"0\" />\n <itunes:summary>Summary Dominique A</itunes:summary>\n <itunes:explicit>no</itunes:explicit>\n <itunes:author>DominiqueA</itunes:author>\n <itunes:image href=\"http://liveweb.arte.tv/images/podcast_logo.jpg\" />\n</item>") Je vous conseille vivement d'utiliser un éditeur avec coloration syntaxique pour modifier ces fichiers python, cela permet de voir tout de suite ce genre de petite coquille (j'ai utilisé "pluma" sous Linux Mint 13). Sinon j'ai fait une nouvelle version, plus pratique (pour moi...), en rajoutant une fonction qui permet ensuite de n'avoir plus que l'adresse de la page à indiquer pour introduire la page dans Qarte, ici dans la catégorie Classique (ATTENTION A l'INDENTATION EN PYTHON) : #JGN MANUAL ADDITION: if cat == 'Classique': self.JGNAddPersonalItem(videos[cat], "http://liveweb.arte.tv/fr/video/Berlin___Waldbuhne_2012/") self.JGNAddPersonalItem(videos[cat], "http://liveweb.arte.tv/fr/video/Dominique_A_Vers_les_Lueurs_Lieu_Unique/") Note: il faut changer la catégorie dans le "if" si la catégorie Classique ne vous va pas (voir dans le fichier data.py les variables xxxCATEGORIES). Sans le "if", la page devient disponible dans toutes les catégories de Arte Live Web (c'est plus lent...) Cette nouvelle version va parser le lien indiqué pour récupérer les bonnes informations de descriptions, de titre et d'image (pas la date). Le résultat dans Qarte est plus "zoli" et pratique. Voici le fichier modifié, il vous faut rechercher les commentaires commençant par "JGN" pour savoir où mettre ses propres adresses de pages Arte: parsers.py (modified) Cette version du fichier, en plus de la nouvelle manière d'ajouter des pages à soi comme indiqué ci-dessus, fait pour la partie Arte+7 un chargement de toutes les vidéos disponibles de l'émission Karambolage (il y en a une dizaines). Vous pouvez essayer avec d'autres émissions de Arte, si la page de "rattrapage plus loin que le +7" existe comme pour Karambolage. (aparté pour les autres lecteurs: Il faut mettre ce fichier à la place de /usr/share/qarte-1.3.0/parsers.py et pour avoir les droits d'accès en écriture sur ce fichier, il faut faire dans une console : sudo chmod ugo+rw /usr/share/qarte-1.3.0/parsers.py ) Bien sûr, ce qui précède est d'abord pour mon usage personnel, il n'est à utiliser que par ceux qui veulent bidouiller Dernière modification par galanga (Le 19/08/2012, à 08:29) Hors ligne Cristophe Re : Qarte arte.tv browser (ex Qarte+7) Merci Galanga pour la réponse ! Ça a fonctionné juste en ajoutant le backslash. Je testerai pluss tard la nouvelle "bidouille" qui à priori me semble pluss pratique. Si je n'en dis rien, c'est que ça aura fonctionné. Hors ligne homer01 Re : Qarte arte.tv browser (ex Qarte+7) Tout d'abord un grand merci à VinsS pour ce soft et ensuite à galanga pour la modif. J'apporte mon grain de sel, dans ta modif galanga j'ai ajouté l'extraction de la date, donc dans le module parser.py il faut modifier les imports: from email.utils import parsedate, formatdate et ensuite il faut rajouter dans la fonction JGNAddPersonalItem avant le premier try dateRE = re.compile('<div class="infos">.*<strong>Filmé le&nbsp;(([0-9]{2}/){2}[0-9]{4})</strong>', re.DOTALL) après la ligne desc = "No description" ajouter ceci try: s = (dateRE.search(page[0]).group(1)) logger.info(u"JGN: dateRE result: {0}".format(s)) date = formatdate(time.mktime(time.strptime(s.decode('utf-8', 'replace'),"%d/%m/%Y"))).decode('utf-8', 'ignore') except: date = "No date" et enfin modifié la ligne qui commence par items.append comme suit items.append("<item>\n <title>" + title +"</title>\n <link>" + url + "</link>\n <pubDate>" + date + "</pubDate>\n <description>" + desc + "</description>\n <author>Auteur</author>\n <enclosure url=\"http://download.liveweb.arte.tv/o21/liveweb/media/event/" + visualCropNumber + "/" + visualCropNumber + "-visual-crop-small.jpg\" type=\"image/jpeg\" length=\"0\" />\n <itunes:summary>Summary</itunes:summary>\n <itunes:explicit>no</itunes:explicit>\n <itunes:author>Author</itunes:author>\n <itunes:image href=\"http://liveweb.arte.tv/images/podcast_logo.jpg\" />\n</item>") Bon je suis pas super doué en python donc il y peut être moyen de faire mieux. Enfin un truc qui serait bien ce serait de pouvoir: 1- dans l'interface graphique avoir un bouton qui permet d'ajouter l'url directement à la liste de téléchargement ou alors 2- envoyer l'url en ligne de commande au lancement du soft. Je propose çà, parce que c'est principalement ma compagne qui souhaite récupérer des émissions arte. Et je ne la sens pas trop motiver pour aller trifouiller dans le code pour ajouter l'adresse qui l'interresse...... voila bonne journée Hors ligne lyr@d Re : Qarte arte.tv browser (ex Qarte+7) Amis de la Bricole, Bonsoir! D'abord bravo pour ce soft, jviens de tester ça sous Debian 6, et ça m'a tout l'air de marcher ! A quand le .msi??!! En vérité je suis tombé sur sur ce thread en faisant des petites recherches personnelles sans rapport direct avec le sujet. Je réside à l'étranger (Tunisie), et j'aimerai bien ne plus avoir ce message irritant qui me dit que les vidéos de la plate forme de ma chaine tv favorite ne peuvent pas être diffusées à l'étranger, pour quelque obscure raison de droits d'auteurs... Qu'a cela ne tienne, j'installe Squid sur une VM de mon dédié (resté au pays lui, yek yek yek;)), j'allume OpenVPN, je cfg Firefox, touça.... http://www.monip.org/ m'affiche bien mon IP française. Néanmoins, je me fais toujours jeter par arte+7. Vu que vous avez l'air de connaitre la plate forme, je voulais vous demander : A votre avis, il fait comment le truc pour savoir que je suis pas sur le territoire national alors que pour lui j'ai une IP française? - Hypothèse 1 : La page web s'affiche en http donc passe par le proxy, mais la lecture vidéo ouvre une autre connexion (un autre port???) et donc ne passe pas par le proxy ??? Faudrait alors que je trouve le port concerné et paramètre Squid en conséquence... - Hypothèse 2 : Arte +7 détecte que je passe par un proxy et me jette? C'est vrai que http://www.monip.org/ m'affiche IP : <IP_française> puis "Proxy detecté" puis ORG_IP : <IP locale VPN>, donc il peut savoir. Peut être peut on cfg squid pour être complètement transparent...... Hypothèse 1 / Hypothèse 2... Quelqu'un aurait une idée? Sinon, je peux toujours continuer a utiliser ce soft pour télécharger les vidz sur mon serveur et après les rapatrier à la maison... Mais c'est un peu lourd le bureau à distance a travers ma connexion, d'ou ma deuxième question / suggestion : Ce soft sous forme d' interface web??? C'est vachement plus léger, et l'InterOuaibe, c'est l'avenir! (y parait:)) Merci! Dernière modification par lyr@d (Le 26/08/2012, à 01:48) Hors ligne galanga Re : Qarte arte.tv browser (ex Qarte+7) @Cristophe: de rien ! @homer01: merci pour l'ajout de la gestion de la date. Pour ceux qui veulent en profiter, je l'ai intégré dans le fichier parsers.py (même lien que ci-dessus, pensez à recharger la page du lien pour avoir la dernière version). Pour l'option 1-, c'est justement cela que j'avais suggéré au début, avant de me mettre à bidouiller Pour l'option 2-, c'est une bonne idée, et plus facile à implémenter pour les bidouilleurs comme nous. @lyr@d: je ne saurais pas aider plus qu'en disant ceci : a/ avec des outils d'espionnage réseau (comme là ou là, ou tout simplement netstat), peut-être que vous arriverez à voir s'il y a une connexion "souterraine" de la lecture vidéo sur un autre port. b/ pour les proxys, je regarde sur ce site quand j'en ai besoin dans Firefox (je suis en Belgique, une fois) : http://www.xroxy.com/proxy-country-FR.htm (défaut : la liste change tout le temps, les proxys indiqués sont temporaires) et il faut faire gaffe effectivement au type de proxy... et pour la vitesse à la colonne latency. Dernière modification par galanga (Le 29/08/2012, à 19:52) Hors ligne Jarvis Re : Qarte arte.tv browser (ex Qarte+7) Bonjour, un petit script fait à l'arrache pour télécharger les vidéos d'arte tv : #!/usr/bin/perl $arteurl = $ARGV[0]; $file_download = $ARGV[1]; $definition = "hd"; #hd or sd @wget=`wget -qO- $arteurl | grep "http://videos.arte.tv/fr/do_delegate/.*xml"`; @foo = map(/(http:\/\/.*xml)\"/,@wget); @wget2=`wget -qO- @foo | grep fr | grep xml`; @foo2 = map(/(http:\/\/.*xml)\"/,@wget2); @wget3=`wget -qO- @foo2 | grep "$definition" | grep rtmp`; @foo3 = map(/(rtmp:\/\/.*)\</,@wget3); system "rtmpdump -r @foo3 -o $file_download.flv"; ./download-arte.pl url_arte fichier output @ noireaude : si t'es fan de gedit, je te conseille de jeter un œil à Vim (un brin plus complet quand même). Hors ligne mardi_gras Re : Qarte arte.tv browser (ex Qarte+7) Bonjour, @ VinsS, popololo et d'autres j'utilisais qarte+7 sur ubuntu 11.04. je viens de passer sur Voyager 12.04 (Xubuntu) et je ne parviens pas à utiliser qarte. est-ce que qarte fonctionne sous Xubuntu 12.04? il semblerait qu'il y ait un problème avec Xubuntu. quand je tape la commande qarte dans un terminal, j'obtiens : Erreur de segmentation (core dumped) apparemment, d'après le forum, je ne suis pas le seul mais je ne parviens pas à suivre et décrypter... si vous pouvez me donner un coupe de pouce... merci! je suis accroc à ce programme et j'espère que ça va pouvoir s'arranger! Hors ligne lyr@d Re : Qarte arte.tv browser (ex Qarte+7) Merci pour les conseil, et ce script m'a l'air sympathique, je verrai si je peux faire une petite interface web... Donc j'ai trouvé le problème, hypothèse 2, le proxy est détecté par ARTE qui bloque en conséquence. Donc pour la postérité, pour visionner les vidéos arte depuis l'étranger en passant par un serveur perso (loué chez un hébergeur, ou chez le pote resté au pays qui a la fibro) avec squid comme proxy, il faut modifier le paramètre forwarded_for de on (par défaut) à delete. Avec ça, squid n'écrit pas votre adresse IP "locale" (en aval du proxy) dans les requetes http, et arte+7 ne détecte pas l'entourloupe. En espérant que ça soit utile à quelqu'un! Hors ligne mardi_gras Re : Qarte arte.tv browser (ex Qarte+7) [résolu] après avoir relu à tête reposée les posts du forum, je viens de voir que le problème était lié au thème utilisé par voyager (à savoir "ambiance voyager dark"). en utilisant un autre thème, le problème est réglé. pourquoi? comment? j'en sais rien mais ça marche. Hors ligne VinsS Re : Qarte arte.tv browser (ex Qarte+7) Bonjour, On n'a pas chômé durant les vacances à ce que je vois. De prime abord, je dirais qu'il n'y a pas de difficulté à ajouter une possibilité d'entrer un lien de page et de laisser le programme se débrouiller, mais où se situent ces pages par rapport au site http://liveweb.arte.tv/fr ? Parce que si ces pages proviennent des sous-pages "Tous les spectacles", "Tous les évènements", "La Blogothèque", etc., je pensais déjà rajouter ces catégories qui représentent toutes ensemble une centaine de concerts. C'est bien la rentrée donc. Dernière modification par VinsS (Le 06/09/2012, à 08:25) Hors ligne zealand84 Re : Qarte arte.tv browser (ex Qarte+7) Bonjour VinsS et un grand merci pour ce magnifique programme. J'ai été confronté au problème de thème avec pour effet le message d'erreur " Erreur de segmentation (core dumped)" au quel j'ai pu faire face en revenant à un thème installé par défaut sous précise (Ambiance). Ceci dit, vous serait-il possible d'envisager de corriger, un jour ce bug, afin de pouvoir utiliser Qarte avec un thème différent. Je suis autant accro à Qarte qu'à mon thème préféré (Cupertino SL) Encore une fois Bravo et merci pour la qualité de l'indispensable Qarte... Cordialement. Hors ligne VinsS Re : Qarte arte.tv browser (ex Qarte+7) Salut, @ zealand84, ce n'est pas un problème qui provient de Qarte. L'application est censée fonctionner avec n'importe quel thème, la personnalisation de l'interface est faite au moyen de feuilles de style après construction de celle-ci. Il faut lancer Qarte en console avec l'option -d pour savoir ce qui se passe. $ qarte -d Le message d'erreur 'Erreur de segmentation' n'est pas la cause du plantage, ce message est émit par le serveur (Linux himself) suite au plantage de l'appli, les messages d'erreurs de Python et de Qt ne sont pas traduits. Dernière modification par VinsS (Le 08/09/2012, à 13:35) Hors ligne zealand84 Re : Qarte arte.tv browser (ex Qarte+7) Merci VinsS pour ta réponse. Après la mise à jour proposée par le gestionnaire de mise à jour tout fonctionne parfaitement, je ne suis plus en mesure de te donner les infos relative à un "qarte -d" et j'en suis désolé. Je ne manquerais pas de te signaler ce que je pourrais recueillir comme infos dans la suite de l'utilisation de Qarte. Merci à toi. Hors ligne pacbits Re : Qarte arte.tv browser (ex Qarte+7) Salut, Tout d'abord merci pour le développement de ce script/application. Voilà voilà j'ai un gros problème: je vous explique ; J'ai quitté Ubuntu pour Xubuntu, ensuite j'ai découvert Voyager qui est installé depuis hier. Hélas Qarte ne fonctionne pas sur Voyager. Je note que Qarte fonctionnait parfaitement sur Ubuntu et Xubuntu. Lorsque je clique sur Qarte via menu/multimédia : aucun résultat, aucun message d'erreur. Si je tente de l'exécuter via le terminal : j'ai l'erreur "Erreur de segmentation (core dumped)" Et en dernier recours j'essaye qarte -d └─> qarte Erreur de segmentation (core dumped) └─> qarte -d 01:56:31: INFO - qarte Qarte-1.3.0 01:56:31: INFO - qarte Python 2.7.3 on Linux-3.2.0-30-generic-pae-i686-with-Ubuntu-12.04-precise 01:56:31: INFO - qarte File system encoding: UTF-8 01:56:31: INFO - qarte System encoding: utf-8 01:56:31: INFO - qarte Locale encoding: ('fr_FR', 'UTF-8') Erreur de segmentation (core dumped) Est-ce que vous pouvez m'aider à résoudre ce problème. Merci d'avance. Dernière modification par pacbits (Le 11/09/2012, à 02:05) Hors ligne VinsS Re : Qarte arte.tv browser (ex Qarte+7) Dernières nouvelles. J'ai posté [1] une version 1.3.1 qui ne nécessite plus FLVStreamer. C'est donc RTMPdump qui sert aussi pour arte+7. Ceci afin de répondre aux distributions qui considèrent ces deux librairies en conflit. Mageia par exemple. C'est une archive tar.gz, un .deb suivra. Le site arte+7 a opéré ces derniers jours des changements importants au niveau de leur plate-forme. Les mises en ligne d'émission et la réactivité du site s'en sont légèrement ressentis. Par contre, ce qui est plus important comme changement, les trois premiers épisodes des Tudor sont mis en ligne sous un format nécessitant M.$. Silverlight comme visionneuse. Qarte n'est pas du tout conçu pour retrouver les liens des streams destinés à cette visionneuse, hélas. J'ignore s'il s'agit d'un cas particulier ou si cela deviendra la norme. Pour ceux que cela intéressent, Moonlight [2] peut remplacer Silverlight dans la plupart des navigateurs. Hors ligne david96 Re : Qarte arte.tv browser (ex Qarte+7) Mauvais signe tout ça En ligne david96 Re : Qarte arte.tv browser (ex Qarte+7) Espérons le. En ligne finchou Re : Qarte arte.tv browser (ex Qarte+7) david96 a écrit : Mauvais signe tout ça Pas sur en fait, cela semble limité à la série Les Tudor. J'ai aussi constaté ce PB avec les Tudor , j'ai d'abord pensé à un verrouillage type DRM, est-il possible de contourner le PB en utilisant Quarte-1.10 avec Moonlight sur Firefox?? Cordialement Compaq presario 17XL274 CPU Pentium III 600 Mhz HDD 12Gb RAM 512 Mb Linux Mint 13 maya sur base ubuntu 12.04 precise pangolin Hors ligne catalona Re : Qarte arte.tv browser (ex Qarte+7) bonjour a tous je viens d'installer QARTE-1-2 . Avec arte liveWeb je peu enregistrer sans probleme mais avec arte+7 je ne peu que enregistrer "ARTE journal" pour le reste des videos on signal "ERREUR telechargement interrompu" si vous avez la solution merci d'avance Hors ligne VinsS Re : Qarte arte.tv browser (ex Qarte+7) Nouvelle version 1.4.0 Au rayon des nouveautés: Ajout de 'Tracks' et 'La Blogothèque' dans la page Arte Live Web La catégorie Jazz à été complétée du partenaire Jazz Live. La catégorie Musique du Monde à été complétée du partenaire Mondomix. Ajout d'une page pour les autres partenaires d'Arte Live Web, du moins une partie. Ceci représente plus ou moins 500 concerts. D'autres partenaires peuvent être ajoutés sans modification du code, il suffit de poster le nom de ce partenaire sur ce forum. Voir la liste [1] Ajout d'une boîte de dialogue pour entrer directement un lien de vidéo. Dans le menu 'Extra' cliquez 'Custom searching' Entrez l'url de la vidéo et cliquez 'O.K.' Si le lien est valide le nom de la vidéo s'affichera, cliquez 'Add' et elle sera ajoutée au panier de téléchargement de la page 'Extra' Comment trouver un lien de vidéo ? Exemple: je suis sur la page Rock en Seine <http://liveweb.arte.tv/fr/part/Rock_en_Seine/> et j'aimerai télécharger 'Eagles Of Death Metal', je clique droit sur le fond de page et je choisis 'Code source de la page'. Le code s'affiche dans une nouvelle fenêtre. Au début de cette page je trouve le lien de la feuille rss <link rel="alternate" type="application/atom+xml" title="Les dernières vidéos d'ARTE Live Web :: Rock en Seine" href="http://download.liveweb.arte.tv/o21/liveweb/rss/partner-640-fr.rss" /> Je télécharge cette page dans une console avec wget wget http://download.liveweb.arte.tv/o21/liveweb/rss/partner-640-fr.rss J'ouvre ce fichier dans mon bloc-notes et là je cherche le bloc de lignes qui contient le concert qui m'intéresse. Dans mon exemple, ceci: ... <item> <title>Rock en Seine : Eagles Of Death Metal</title> <link>http://liveweb.arte.tv/fr/video/Rock_en_Seine_Eagles_Of_Death_Metal/</link> <pubDate>Sat, 25 Aug 2012 21:00:00 +0200</pubDate> <description>&lt;p&gt;&lt;a href="http://www.eaglesofdeathmetal.com/"&gt;Eagles Of Death Metal&lt;/a&gt; ne joue ni des chansons des &lt;a href="http://www.eaglesband.com/"&gt;Eagles&lt;/a&gt;, ni du death metal. Le nom du groupe semble issu d&amp;rsquo;une conversation avin&amp;eacute;e entre Josh Homme et un quidam dont l&amp;rsquo;histoire n&amp;rsquo;a pas daign&amp;eacute; retenir le nom. Si le groupe est apparu pour la premi&amp;egrave;re fois sur l&amp;rsquo;une des compilations &lt;em&gt;Desert Session&lt;/em&gt; de Josh Homme, et si on le retrouve au sein du groupe ainsi que, ..... Il suffit maintenant de rentrer le contenu des balises <link> </link> soit http://liveweb.arte.tv/fr/video/Rock_en … ath_Metal/ dans la boîte de dialogue du menu 'Extra' et de cliquer O.K. J'ai mis un tar.gz et un all.deb sur mon site [2] et le ppa est en cours. [1] http://liveweb.arte.tv/searchPartner.do … ayElements [2] http://www.oqapy.eu (Téléchargements) Dernière modification par VinsS (Le 24/09/2012, à 21:34) Hors ligne cracolinux Re : Qarte arte.tv browser (ex Qarte+7) VinsS , je te remercie au nom de ma femme car cette feignante ne veut pas s'inscrire sur le forum. Elle se sert de Qarte sans arrêt et je suis obligé de faire le ménage de temps en temps car le disque dur s'en prend plein les dents C'est vraiment très beau et ça fonctionne super bien ! bravo ! .... PS : moi zaussi je me sers de qarte... Pixup : postez vos images vite et bien « Ne devenez jamais pessimiste. Un pessimiste a plus souvent raison qu'un optimiste, mais l'optimiste s'amuse plus — et aucun des deux ne peut arrêter la marche du monde. » R.Heinlein Hors ligne
In a Python program I'm writing I've compared using a for loop and increment variables versus list comprehension with map(itemgetter) and len() when counting entries in dictionaries which are in a list. It takes the same time using a each method. Am I doing something wrong or is there a better approach? Here is a greatly simplified and shortened data structure: list = [ {'key1': True, 'dontcare': False, 'ignoreme': False, 'key2': True, 'filenotfound': 'biscuits and gravy'}, {'key1': False, 'dontcare': False, 'ignoreme': False, 'key2': True, 'filenotfound': 'peaches and cream'}, {'key1': True, 'dontcare': False, 'ignoreme': False, 'key2': False, 'filenotfound': 'Abbott and Costello'}, {'key1': False, 'dontcare': False, 'ignoreme': True, 'key2': False, 'filenotfound': 'over and under'}, {'key1': True, 'dontcare': True, 'ignoreme': False, 'key2': True, 'filenotfound': 'Scotch and... well... neat, thanks'} ] Here is the for loop version: #!/usr/bin/env python # Python 2.6 # count the entries where key1 is True # keep a separate count for the subset that also have key2 True key1 = key2 = 0 for dictionary in list: if dictionary["key1"]: key1 += 1 if dictionary["key2"]: key2 += 1 print "Counts: key1: " + str(key1) + ", subset key2: " + str(key2) Output for the data above: Counts: key1: 3, subset key2: 2 Here is the other, perhaps more Pythonic, version: #!/usr/bin/env python # Python 2.6 # count the entries where key1 is True # keep a separate count for the subset that also have key2 True from operator import itemgetter KEY1 = 0 KEY2 = 1 getentries = itemgetter("key1", "key2") entries = map(getentries, list) key1 = len([x for x in entries if x[KEY1]]) key2 = len([x for x in entries if x[KEY1] and x[KEY2]]) print "Counts: key1: " + str(key1) + ", subset key2: " + str(key2) Output for the data above (same as before): Counts: key1: 3, subset key2: 2 I'm a tiny bit surprised these take the same amount of time. I wonder if there's something faster. I'm sure I'm overlooking something simple. One alternative I've considered is loading the data into a database and doing SQL queries, but the data doesn't need to persist and I'd have to profile the overhead of the data transfer, etc., and a database may not always be available. I have no control over the original form of the data. The code above is not going for style points.
ehmicky Stego++, projet de bibliothèque de stéganographie Salut à tous, [Message mis à jour 19/11/11] Je suis actuellement sur un projet de stéganographie (art de dissimuler un message secret dans "quelque chose" (fichier, phrase, etc.) d'apparence banal). Il s'agit de faire une bibliothèque C++, Stego++, qui permette à tout développeur, même connaissant peu la stéganographie, de développer une application de stéganographie, ou de l'utiliser dans son travail. Elle sera sous licence LGPL3 et multi-plateforme (au moins Mac OS X, Windows, GNU/Linux et BSD). L'idée est de faire suivre cela par une commande Unix utilisant Stego++, puis par une appli avec GUI, mais le coeur du projet est la bibliothèque. Je n'ai rencontré que très peu de bibliothèque de stéganographie, et je pense qu'il s'agira de la première en fait qui soit complète (et pas centrée sur un format ou algo donné) et libre. Mes principaux objectifs pour Stego++ : 1) modulaire. De nombreuses méthodes de stego, même très différentes et sur des media très divers (texte, image, video, paquet TCP, système de fichier, etc.) pourront être implémentées sous forme de modules. 2) "secure". Les modules de stego devront répondre à des critères précis et chiffrés en matière de résistance aux attaques stéganalystiques. 3) simple. Un développeur ne connaissant rien en crypto ni en stego doit pouvoir lire la documentation de l'API et pouvoir après une demi-journée coder ce qu'il veut en quelques dizaines de lignes. L'API doit être aussi petite que possible, même si ce but rentrera nécessairement en conflit avec mon désir d'intégrer plusieurs fonctions comme l'authentification, compression, etc. Je suis en pleine recherche (lecture de beaucoup de travaux de recherches (j'en suis déjà à mon quatrième gros bouquin technique), de codes sources (au moins 150 logiciels à lire en diagonal), etc.) pour essayer d'avoir quelque chose de sérieux. Une fois le coeur de la biblio pensée et codée, je vous invite de tout coeur à collaborer ! - code commenté avec Doxygen - deux documentations, une pour l'API publique, une pour les contributeurs - utilisera Sourceforge ou quelque chose de similaire - une documentation supplémentaire vous expliquant les principes de bases de la stégo Pourquoi participer ? Parce que si jamais vous vous intéressez un peu à la crypto, vous serez passionnés par la stégo. De même que la crypto avant les années 70, la stégo reste un outil spécialisé pour agences gouvernementales (NSA, etc.) et groupes terroristes. De même que la crypto ou la robotique par le passé, son utilisation par les entreprises et le citoyen lambda me semblent encore sous-estimée, et il y a un grand essor à venir (et ce serait cool que le mouvement du libre en fasse partie). Je sais que beaucoup d'entre vous sont par ailleurs préoccupés par la mise à mal croissante de l'anonymat et de la liberté sur Internet. Je pense qu'il est possible de défier ces mesures par des logiciels de crypto et de stégo. En tant que développeurs, il est même de notre devoir de développer de tels logiciels pour que le citoyen lambda puisse continuer à utiliser les nouvelles technologies comme des merveilles pour nos libertés (de communication, d'apprentissage, etc.), et non devenir de simples consommateurs apathiques. Et je pense que, de même que la crypto aujourd'hui est aux premières lignes de ce combat (Tor, contournement du Great Chinese Firewall, monnaie cryptographique, etc.), la stégo le sera bientôt. (cf le mouvement cypherpunk) Il y a également plusieurs usages créatifs de la stégo possible : par exemple, je compte intégrer un procédé de watermarking de code GPL, permettant la détection rapide de code propriétaire utilisant du code GPL sans permission. Le projet me prend du temps et la phase implémentation ne sera qu'en dernier et sera courte, pour l'instant j'en suis à la phase apprentissage de bibliothèque/recherches sur la stego/penser à l'interface. Les technos pour l'instant sont : - General : C++ / Boost - Chiffrement : Crypto++ (j'hésite encore avec openssl) - Compression : libzpaq - Versioning : Git - Documentation : Doxygen - Build : CMake - Manipulation d'images : pas encore décidé - Internationalisation : gettext (traductions anglais et chinois prévues) Dernière modification par ehmicky (Le 19/11/2011, à 16:17) Hors ligne Shanx Re : Stego++, projet de bibliothèque de stéganographie Je trouve ça intéressant dans l'idée, même si moi je n'en vois pas trop l'utilité (pour l'utilisateur français lambda). Après, si ça peut être un outil pour lutter contre les dictatures, c'est cool « En vérité, je ne voyage pas, moi, pour atteindre un endroit précis, mais pour marcher : simple plaisir de voyager. » R. L. Stevenson -- Blog et randos Hors ligne lann Re : Stego++, projet de bibliothèque de stéganographie J'avais fait un truc dans le genre au début de mon apprentissage en C++. Les sources sont ici : sources Tout d'abord c'était au temps ou je codais avec les vilains MFC. Je sais c'est très mal mais à l'époque j'étais ignorant. Donc ce code est fait que Windows. Mais il y a peut-être quand même des choses intéressantes. Je crois que ce n'est pas tout à fait de la stéganographie puisque l'image n'est pas altérée, juste les bits qui ne servent pas pour l'affichage du fichier bmp. Et croyez moi, il peut en avoir beaucoup. A+ Hors ligne ehmicky Re : Stego++, projet de bibliothèque de stéganographie @Shanx : oui c'est mon but principal. D'ailleurs, je lis ta signature, et justement un système de fichier stéganographique a été développé par Julian Assange, et il a contribué à populariser la deniable encryption (qui est vraiment une idée ingénieuse). En France, on en a pas encore l'utilité, mais je suis sûr que le jour viendra bien tôt @Iann : merci pour les sources, je vais regarder. J'imagine que tu as modifié des champs de l'header/footer ou modifié la table des couleurs ? Dernière modification par ehmicky (Le 16/01/2011, à 10:33) Hors ligne lann Re : Stego++, projet de bibliothèque de stéganographie Oui c'est ça Et dans les couleurs du dessin, il me semble. A ce que je me rappelle. Hors ligne Chaussette Re : Stego++, projet de bibliothèque de stéganographie je déterre un peu le topic, faire de la sténo sur des images est très facile (dans le principe, le tout c ' est de le faire bien mathématiquement); proposer une gui qui permettrait de choisir une image et une info à coder (image, texte, lien) pour les lier serait facile aussi. Si tu as des connaissances en c ou c++ (bien que je ne vois pas l' intérêt de c++ dans ce genre de traitement ) lance toi ! Si tu veux je te fait ta gui en c/gtk ; le projet m' intéresse. Je peux peut-être aussi t' aider pour le moteur, mais je ne sais pas où tu en es et quels sont tes connaissances. J' imagine que tu sais ce que tu fait. Sinon as tu avancé ? Ce serait bien ..! cordialement chaussette Dernière modification par Chaussette (Le 18/02/2011, à 06:58) Les clowns se marient en grande pompes Hors ligne ehmicky Re : Stego++, projet de bibliothèque de stéganographie En fait j'ai toujours 0 code, mais je suis bien déterminé dans mon projet, parce que la partie "code" va être rapide comme tu le dis ça demande pas masse de code, c'est surtout la recherche avant qui prend du temps. Alors, sinon, en fait effectivement, ce qui est compliqué c'est la stégano elle-même. Parce que le niveau 0 de la stégano, à savoir modifier le bit le plus faible de chaque octet d'une image .bmp, peut être codé en 20 lignes. Par contre, il y a des trucs un peu plus compliqués : - application de principes comme la "deniable encryption" - étude de la stéganalyse pour pouvoir proposer quelque chose qui soit pas détectable par les méthodes statistiques de la stéganalyse (qui est un domaine assez jeune) - stégano "originale" : par exemple, je suis en train d'apprendre l'ASM x86 (et j'ai bien avancé) pour pouvoir dissimuler un message en modifiant une instruction par une/plusieurs autres identiques (ex : add ax,1 -> inc ax). Ce genre de trucs est relativement facilement détectable, et en plus j'ai cru comprendre que ce qui paraît être "à l'oeil" des instructions identiques, peuvent produire des conséquences différentes, par exemple avec plusieurs threads, ou sous des environnements particuliers. Tout ça pour dire que ce que je fais surtout là, c'est apprendre les connaissances en stégano et les bibliothèques nécessaires pour le projet. Pour l'instant j'en suis à : - C++ / Boost. - Gtkmm pour le GUI - Crypto++ pour la crypto - J'hésite encore sur la bibliothèque de manipulation d'images. Je préfère en utiliser une que manipuler directement la mémoire via des pointeurs, parce que c'est beaucoup plus simple pour tout ce qui est manipulation des headers, des coefficients de compression .jpeg, etc. Donc j'hésite d'un côté entre CIMG ou ImageMagick++, et de l'autre libpng et compagnie. - j'ai aussi appris libzpaq qui me permettra de compresser les data à dissimuler avant de les encrypter, ce qui au final dégradera moins le support (image, fichier, etc.) et sera donc moins détectable. - Doxygen pour la doc', Git pour les versions (projet sûrement hébergé sur Github). Ensuite, au niveau de mon planning, je pense : 1) développer le projet avec seulement stégano de fichier .png, .jpeg et .bmp sur le bit le plus faible, et dispo seulement en ligne de commande. 2) mettre en GUI en complément de la ligne de commande. 3) Si vraiment, j'en ai les compétences (ce dont je suis pas sûr), proposer une bibliothèque à partir du projet pour les développeurs qui veulent intégrer de la stégano dans leur propre projet sans se prendre la tête. Je suis vraiment persuadé que la stéganographie peut avoir, comme la crypto, des domaines d'applications bien plus larges que ce qu'on pense. 4) Ajouter de nouvelles méthodes de stégano : utilisation des facteurs de compression .jpeg, encodage de la table des index couleurs .gif, stégano sur fichier texte pur (remplacement de mot, etc.), stégano sur paquet TCP, etc. Donc, en fait pour le C++, y'a deux raisons : 1) J'ai en fait déjà une idée de l'architecture du projet, et j'aimerais faire une abstraction de chaque "méthode" de stégano pour pouvoir facilement ajouter de nouvelles méthodes, bien que complètement différentes d'un point de vue pratique, sans que cela chamboule tout le projet. En gros, une interface pour l'information à dissimuler, une autre pour la manière de la dissimuler (qui inclue la méthode + le "carrier", fichier porteur (même si je réfléchie à d'autres organisations possibles)), ce qui permettra par exemple de dissocier la chose à dissimuler (image, vidéo, texte) du carrier (image, vidéo, texte). Ca a des avantages, mais y'a aussi pas mal de problèmes que j'ai à résoudre. En tout cas, c'est pour ça notamment que j'avais pensé à une approche objet, et vu que la performance compte malgré tout, C++ me semblait le plus aproprié. Faire de la programmation objet en C, façon Glib, me donnerait vraiment un mal de crâne. 2) En conséquence, la plupart des bibliothèques dont j'ai déjà passé du temps à apprendre sont C++. Avec une chose en plus : l'interface (que ce soit GUI ou CLI) doit être "internationalized" pour favoriser l'ajout de nouvelles langues, puisque pour commencer il devrait y avoir au moins une version anglais/français (je peux le faire) ainsi qu'une version chinois probablement (j'ai sans doute un traducteur). Et le chinois contient des considérations de localisation vraiment particulières et pas simples. Donc comme tu le vois, c'est tout un projet, c'est pour ça que j'avais précisé au départ que y'aura pas une ligne de code avant au moins 6 mois. D'un autre côté, cela fait déjà 4/5 mois que je suis dessus quasiment tous les jours, donc ce sera pas un vaporware, la motivation est là depuis déjà un certain temps, et j'ai bien progressé d'ailleurs, même si l'apprentissage de théories et de bibliothèques ne se chiffre pas en lignes de code. En plus, j'ai entrepris de lire le code source des 10/15 projets libres qui existent déjà et de regarder les fonctionnalités des applis proprio existantes, donc ça fait beaucoup de boulot, mais je suis motivé parce que j'ai une amie militante en Chine qui pourrait directement bénéficier du logiciel pour des questions de censure. Donc, pour ton aide, en fait je connais (à peu près) Gtkmm, j'avais pensé le faire, mais ton aide est bien sûr bienvenue (merci), mais faut prendre en considération le fait que le GUI est dans la "phase 2", et aussi le problème entre C et C++. Au contraire, mes projets jusqu'ici sont solos et avoir une contribution serait une bonne expérience, c'est d'ailleurs dans cette optique que j'ai voulu héberger ça sous Github pour favoriser la collaboration (tout en sachant que 70% des projets libres sont solos). Maintenant, peut-être faut-il attendre de voir le projet émerger et que je code la "phase 1", ce qui arrivera pas avant 6 mois, je pense dans une fourchette 6 mois-1 an. Edit : sinon, en fait les trucs qui me rendraient vraiment un coup de main au niveau du moteur, sont au niveau de l'optimisation et tout ce qui touche à des choses trop complexes mathématiquement. J'ai fait des études littéraires, et j'ai un niveau en maths vraiment très mauvais, même si avant d'entreprendre ces études, j'avais un bon niveau et que j'ai appris des choses via l'informatique. Mais dans tout ce qui est algorithmique "très mathématique", je suis pas qualifié. Par ailleurs, l'ajout de nouveaux "modules", comme la stégano sur paquets TCP, ou les 70 autres manières de dissimuler un message sont aussi vraiment bienvenues, en plus si mon architecture est ok, ça devrait s'intégrer sans trop de problèmes, et certains modules peuvent certainement prendre pas plus de 100 à 200 lignes de code. Mais pour ça, il faut déjà avoir fait les phases précédentes. Dernière modification par ehmicky (Le 18/02/2011, à 21:34) Hors ligne Chaussette Re : Stego++, projet de bibliothèque de stéganographie salut, pour les autres méthodes de sténo il faudrait aussi penser à une approche analogique. En imaginant par exemple, que je colle des affiches dans la rue pour prévenir du prochain concert de l' association des chanteurs de yodoll en Chine ( ! ça risquerais plutôt d' attirer l' attention ) Un simple téléphone avec appareil photo et hop, plus qu' a copier ensuite sur l' ordi et traiter avec ton logiciel. Les clowns se marient en grande pompes Hors ligne ehmicky Re : Stego++, projet de bibliothèque de stéganographie Tu veux dire permettre d'utiliser de la reconnaissance de caractères ? Hors ligne ehmicky Re : Stego++, projet de bibliothèque de stéganographie Pourquoi les peuples ont besoin d'outils de stéganographie et de cryptographie libres et simples à utiliser. L'information est une arme, son contrôle un pouvoir. Dernière modification par ehmicky (Le 20/02/2011, à 18:04) Hors ligne Chaussette Re : Stego++, projet de bibliothèque de stéganographie salut, non je parle d' extraire une information stéga dans une donnée qui n' est pas forcement bien capturée/conservée/distribuée. Avec une approche analogique, si l' image par exemple est froissée ou qui lui manque un coin ce n' est pas grave, l' information sera quand même lisible. Et puis il faut imaginer tout les cas ou l' information codée logiciellement, ne transite pas de manière numérique et où il y perte de données; même si ces cas seront rares. Comme la pochette du cd plutôt que le cd lui-même, l' affiche qui subit des intempéries, le t-short ou le drapeau qui déforment l' image.. Tu peux même appliquer ce principe (quoique beaucoup plus difficile) dans des données numériques. Le net à tendance à copier, modifier, redistribuer l' information. Si ta donnée symbiote est tenace elle sera encore lisible. On peut imaginer qu' un nouveau buzz (une vidéo, une image, un texte) contienne de la stéga. Comme tout buzz il va se faire tronquer, hacher menu, et se retrouver dans diverses formes/conteneurs sur la toile. Dernière modification par Chaussette (Le 21/02/2011, à 09:03) Les clowns se marient en grande pompes Hors ligne Nasman Re : Stego++, projet de bibliothèque de stéganographie Il y a un paramètre à prendre en considération, c'est le rapport entre la quantité d'informations dissimulées et la taille du "support". Si on dissimule du texte brut (genre ascii), il sera possible de mettre pas mal d'information dans une image, une vidéo, de la musique..., si on veut dissimuler des choses plus lourdes (films...), ce sera plus dur. Je me suis déjà intéressé à la cryptographie et à la stéganographie et ai fait quelques programmes en assembleur (dont des calculs de transformée de Fourier rapide) - je pourrais peut être être utile. PC fixe et portable avec Precise 64 bits Hors ligne ehmicky Re : Stego++, projet de bibliothèque de stéganographie @Chaussette : ah oui, effectivement, j'y avais pensé, par exemple si on recompresse une image .jpg ou qu'on l'enregistre sous un autre format. Je vais prendre ça en compte ! @Nasman : je pensais calculer un "indice de dégradation" du support (carrier) qui indique à la fois la dégradation visible (ou auditive) du support mais aussi ses chances d'être repéré par une approche statistique, et d'afficher (dans le GUI ou le CLI) des avertissements en conséquences, mais ne pas empêcher le process même si cet indice est faible. Qu'en penses-tu ? Hors ligne Nasman Re : Stego++, projet de bibliothèque de stéganographie Je pensais à une autre chose : les modifications apportées au support ne doivent pas empêcher le fichier support de s'ouvrir correctement. Par exemple un fichier jpg source auquel on "rajoute" des éléments stéganographiques doit toujours avoir une structure de fichier jpg (donc s'ouvrir) et ne pas afficher clairement qu'il a été modifié. Quand on travaille sur une image bitmap (en altérant les bits de poids faible par exemple), on sait que les modifications seront quasiment indétectables. Pour les autres formats compressés ou d'encodage différent il faudra connaitre le principe de codage de l'image pour faire des modifs indétectables. En définitive il y aura deux possibilités : - image bitmap + texte codé, encodage non destructif, expédition, décodage non destructif, extraction du texte - image bitmap, encodage, rajout de texte codé, expédition, extraction du texte dans le deuxième cas l'étape décodage après expédition doit donner quelque chose similaire à l'image bitmap d'origine pour éviter la détection. PC fixe et portable avec Precise 64 bits Hors ligne ehmicky Re : Stego++, projet de bibliothèque de stéganographie En fait la stégano par modification du bit faible sur image .bmp est détectable par analyse statistique (même quand le message est mis en bouillie par un chiffrement symétrique). Sinon, mon but est de pas modifier le format du carrier : un .jpg doit resté .jpg. Donc effectivement pour les .jpg faut s'attaquer au format .jpg, mais y'a vraiment plein d'astuces impressionnantes qui existent déjà, par exemple en modifiant les coefficients de compression des blocs de pixels, en modifiant les headers, etc. C'est pour ça que je voulais utiliser une bibliothèque type libjpeg pour le faire, ce sera plus simple et le code sera plus clair. Hors ligne Airballman Re : Stego++, projet de bibliothèque de stéganographie Tu es en train de créer un soft qui fasse ça du coup ehmicky ? Hors ligne ehmicky Re : Stego++, projet de bibliothèque de stéganographie Oui, cf le topic, j'ai même mis les technos utilisées. Ce sera GPL3 et si y'a une API elle sera licence BSD-like ou LGPL3. Mais faut compter au moins 6 moins (=> septembre) avant de voir quelque chose. Hors ligne ehmicky Re : Stego++, projet de bibliothèque de stéganographie Je continue à étudier les autres logiciels, et je sens que y'a vraiment besoin d'un logiciel de stéganographie. Il y a en fait 150-200 outils déjà existants. Cependant, pour beaucoup d'entre eux, il y a un ou plusieurs de ces problèmes : - plus maintenu (80% d'entre eux). La moitié d'entre eux ne dépasse pas Windows 2000 - pas de GUI - Windows only - stégano faible (beaucoup de modif' sur least-significant bit sur fichier .bmp 24 bits only) - pas d'encryption, ou chiffrement faible (rot13 !) La plupart des outils existants ont au moins 1 de ces défauts, ou bien ne sont pas libres. Jusqu'ici je n'ai pas trouvé d'outils à la fois : - libre - avec GUI - multi-plateforme, et encore maintenu - avec stégano viable + chiffrement viable Je continue ma recherche, j'en trouverai peut-être. En tout cas, si j'en trouve pas, je commence vraiment à me dire que du coup ce sera bien de développer ça pour la communauté. En plus, j'aimerais aussi apporter : - CLI dispo en plus du GUI - une API avec une interface simple, "libstegano" - une documentation sur les outils et techniques de stegano existantes (celle que je fais en ce moment) - essayer de faire le logiciel de manière modulaire pour permettre simplement l'ajout de nouvelles techniques de stégano sous forme de modules. Et favoriser la collaboration avec Doxygen + Git. Je regarde aussi le code source des outils existants pour voir les algorithmes principaux, parce que certains sont très originaux. Dernière modification par ehmicky (Le 27/02/2011, à 17:57) Hors ligne Airballman Re : Stego++, projet de bibliothèque de stéganographie Si tu commences sérieusement à développer, et que tu as des besoins ça m'intéresse que tu le fasses savoir. Je pourrais peut-être te filer un coup de main sur certaines parties. (Par exemple ajout de fonctions de stégano dans ton logiciel . . . ) . Enfin à voir . Voilou. Hors ligne magestik Re : Stego++, projet de bibliothèque de stéganographie Salut, Si ça peut aider, j'avais découvert une technique imparable pour cacher des trucs dans des jpeg. J'avais trouvé ça quand j'ai cherché à comprendre comment fonctionnait le format MPO, qui est un format d'images 3D. Bref, le problème est pas là, mais j'ai réussi assez simplement à cacher du texte dans mon image. Après je mettais du texte "simple" mais après c'est du texte, j'aurais très bien pu le crypter. J'avais même distribué les sources, par contre j'avais pas fait de GUI, mais en GTK, avec glade, ça peut se faire assez rapidement. Si quelqu'un est intéressé, soit par les sources (ça faisait même pas 100 lignes), soit par la méthode en question (que je pourrais pas détailler en précision juste de tête vu que c'était du travail en hexadécimal) demandez moi Ou alors si quelqu'un veut le logiciel en question je peux faire une petite interface GTK et en faire un paquet DEB, pas de problème. Voilà, Magestik Hors ligne ehmicky Re : Stego++, projet de bibliothèque de stéganographie Salut, Effectivement, ce qui m'intéresserait, c'est l'algo lui-même. J'ai lu plusieurs textes sur le sujet, avec notamment surtout des méthodes modifiant les coefficients DCT, et puis des améiorations pour résister à une attaque stéganalystique. Il y a une dizaine d'outils sur ce principe et plusieurs travaux de recherche. C'est intéressant parce que ça résiste un peu aux recompression/recadrages, etc. Merci, tu peux décrire l'algo ou c'est trop long ? Hors ligne magestik Re : Stego++, projet de bibliothèque de stéganographie Ca va pas du tout chercher aussi. Déjà c'est quelque chose que j'ai complétement inventé (ça devait peut-être déjà exister), et comme je l'ai dit ça tient en même pas 200 ligne ... tout les programme en 200 lignes : lecture du texte dans une image (ou on avait déjà écrit), écriture (dans une nouvelle image) et saisie du texte qu'on veut mettre dans l'image. Le principe est très simple : en fait j'ouvrais l'image en hexadécimal, à la fin je rajoutais un header (hexadécimal) JPEG (c'est ça dont je me rappelle plus exactement la séquence, mais je sais même pas si on est obligé de mettre ça.). Et après ce deuxième header tu mettre tout ce que tu veux, pas de problème. Moi je mettais du texte en clair, mais rien ne t'empêche de mettre du texte crypté (avec le cryptage que tu veux) ou même le binaire d'une archive (j'avais essayé et ça avait marché). J'ai essayé d'ouvrir l'image avec plusieurs logiciels : aucun problème l'image s'ouvre comme si de rien n'était. Bon je pense que tu pensais à des choses beaucoup plus compliqué, mais cette méthode permet d'avoir quelque chose simple assez rapidement. Et pour peu que tu crypte ton texte comme il faut, alors pas de problème il devrait être illisible. Je m'y connais pas trop en cryptage, mais en C++ il doit pas manquer de lib pour faire ça. Après à toi de voir ce que tu veux faire. Petit hors-sujet pour ceux que ça intéresse : le format MPO c'est en fait une deuxième image JPEG après une deuxième. Donc on a notre première image avec son header JPEG et quand elle est finie on a notre deuxième header JPEG suivi de l'image en elle même. Si tu veux plus d'infos hésite pas Dernière modification par magestik (Le 01/03/2011, à 15:53) Hors ligne Airballman Re : Stego++, projet de bibliothèque de stéganographie Tu aurais pu mettre un lien vers les sources direct histoire de se faire une idée ^^ Hors ligne Airballman Re : Stego++, projet de bibliothèque de stéganographie Après ehmicky, si j'ai bien compris, en fait ce que tu cherches à faire est de rassembler toutes ces différentes méthodes dans un seul et même endroit et de mettre un joli empaquetage graphique par dessus . Je me trompe? Hors ligne magestik Re : Stego++, projet de bibliothèque de stéganographie Airballman> j'aurais pu, si je les avais mise en ligne. Mais quand j'ai écrit le message j'étais pas chez moi donc pas accès à mes fichiers. Mais maintenant c'est bon, j'ai accès à mes fichiers. Voilà le code en question, du moins ce que j'en ai retrouvé : import binascii image = raw_input() separateur = binascii.unhexlify('FFD8FFE1') f = open(image,'rw') files = f.read() f.write(files + separateur + "TEXTE") f.close() Hors ligne
Zetsu15 Probléme Gnome Shell Extension Salut A Tous Je Suis Nouveau Sur Le Forum Mais Il Ya Longtemps Que Jai Débuter Avec Ubuntu Jai Installé La Version 11.10 Et Gnome 3.2, jai tout mis a jour, installé gnome tweak tool, les extensions de chez Web upd8, bref tout marché nickel jusqu'a ce que je redémarre ma machine, les extensions marche normalement ( ils sont affichés sur le panneau etc ) mais je ne peut plus y accéder dans gnome tweak tool Quand jaccéde a Shell Extensions il n'affiche aucune extension a part l'install shell extension , dans theme devant la rubrique Shell Théme il ya un ptit triangle en jaune ki affiche "could not list shell extension" jai désinstaller toute les extension, gnome tweak tool, je les ai réinstaller, redémarrer a mainte fois la machine rien n'y fais Voici le rapport du terminal quand je le lance g.t.t gnome-tweak-tool WARNING : Could not list shell extensions Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/gtweak/tweaks/tweak_shell.py", line 62, in __init__ extensions = self._shell.list_extensions() File "/usr/lib/python2.7/dist-packages/gtweak/gshellwrapper.py", line 107, in list_extensions return self._proxy.proxy.ListExtensions() File "/usr/lib/python2.7/dist-packages/gi/overrides/Gio.py", line 148, in __call__ kwargs.get('flags', 0), kwargs.get('timeout', -1), None) File "/usr/lib/python2.7/dist-packages/gi/types.py", line 43, in function return info.invoke(*args, **kwargs) GError: Le délai d'attente est épuisé Aucun schéma connu pour « /desktop/gnome/shell/windows/button_layout » Aucun schéma connu pour « /desktop/gnome/shell/windows/button_layout » WARNING : Error listing extensions Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/gtweak/tweaks/tweak_shell_extensions.py", line 153, in __init__ for extension in shell.list_extensions().values(): File "/usr/lib/python2.7/dist-packages/gtweak/gshellwrapper.py", line 107, in list_extensions return self._proxy.proxy.ListExtensions() File "/usr/lib/python2.7/dist-packages/gi/overrides/Gio.py", line 148, in __call__ kwargs.get('flags', 0), kwargs.get('timeout', -1), None) File "/usr/lib/python2.7/dist-packages/gi/types.py", line 43, in function return info.invoke(*args, **kwargs) GError: Le délai d'attente est épuisé Aucun schéma connu pour « /desktop/gnome/shell/windows/theme » Aucun schéma connu pour « /desktop/gnome/shell/windows/theme » Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed Gtk-CRITICAL **: gtk_widget_get_preferred_height_for_width: assertion `width >= 0' failed Ah oui jai oublié, maintenant je ne vois plus les bouttons maximizer et minimiser, méme s'ils sont encore activé dans g.t.t :s HelP Please (( Dernière modification par Zetsu15 (Le 16/11/2011, à 13:56) Hors ligne stef28 Re : Probléme Gnome Shell Extension J'ai exactement le même problème .... pas de solution en vue ? stef Hors ligne Major Grubert Re : Probléme Gnome Shell Extension Aucune idée. Peut-être que certaines extensions sont incompatibles entre elles et causent le pb ? Les désinstaller toutes. Nettoyer le cache. En installer une. L'activer. Tester (éventuellement avec un redémarrage). Si ça marche passer à la suivante. Mais bon... Pour en savoir plus sur Gnome Shell. . Lenovo Yoga 13 : Windows 8.1 / Ubuntu Gnome 14.04 . Asus x7010 : Ubuntu 14.04 (Gnome Shell) . Asus Eeepc : Xubuntu 14.04 (32b) Hors ligne stef28 Re : Probléme Gnome Shell Extension En fait, j'ai enlevé toutes mes extensions et redémarré ... rien de changé Dernière modification par stef28 (Le 20/11/2011, à 22:37) stef Hors ligne willcoyote Re : Probléme Gnome Shell Extension Salut Pour voir les erreurs avec les extension, il y a une autre solution ALT + F2 et taper : lg puis error touche echap pour quitter ce menu et inutile de redémarrer ALT + F2 puis r pour redemarrer gnome shell archlinux+kde Hors ligne stef28 Re : Probléme Gnome Shell Extension Merci du tuyau ... mais ça ne résous pas mon problème stef Hors ligne Zetsu15 Re : Probléme Gnome Shell Extension Re Salut A Tous Le Monde En Fait J'ai fait Et Refait Toute Les Manip Auparavant Avec LG il affiche Aucune Extensions Installé Alors Que J'en ai Une disaine D'installé Désinstaller Nettoyer Réinstaller Tout Y Compri ( Extensions GTT Gnome Shell ) Rien N'y Fait Du Coup Jai Réinstallé Ubuntu Et Gnome En Espérant Que Ca Se Repdouise Plus Dernière modification par Zetsu15 (Le 20/11/2011, à 23:12) Hors ligne
When trying to upgrade to 13.04 from 12.10, I get the following error: Traceback (most recent call last): File "/usr/bin/do-release-upgrade", line 108, in <module> print(_("Checking for a new Ubuntu release")) UnicodeEncodeError: 'ascii' codec can't encode character '\xf3' in position 32: ordinal not in range(128)
I'm a complete Linux newbie. I've just upgraded from 10.04 to 12.04 LTS and all sorts of things have started to go wrong. One main problem is the fact that I can't add repos. Example: sudo add-apt-repository ppa:team-xbmc outputs: Traceback (most recent call last): File "/usr/bin/add-apt-repository", line 8, in <module> from softwareproperties.SoftwareProperties import SoftwareProperties File "/usr/lib/python2.7/dist-packages/softwareproperties/SoftwareProperties.py", line 53, in <module> from ppa import AddPPASigningKeyThread, expand_ppa_line File "/usr/lib/python2.7/dist-packages/softwareproperties/ppa.py", line 27, in <module> import pycurl ImportError: librtmp.so.0: cannot open shared object file: No such file or directory /etc/apt/sources.list # deb cdrom:[Ubuntu 10.04.1 LTS _Lucid Lynx_ - Release i386 (20100816.1)]/ lucid main restricted # deb cdrom:[Ubuntu 10.04.1 LTS _Lucid Lynx_ - Release i386 (20100816.1)]/ maverick main restricted # See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to # newer versions of the distribution. deb http://archive.ubuntu.com/ubuntu precise main restricted deb-src http://archive.ubuntu.com/ubuntu precise main restricted ## Major bug fix updates produced after the final release of the ## distribution. deb http://archive.ubuntu.com/ubuntu precise-updates main restricted deb-src http://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://archive.ubuntu.com/ubuntu precise universe deb-src http://archive.ubuntu.com/ubuntu precise universe deb http://archive.ubuntu.com/ubuntu precise-updates universe deb-src http://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://archive.ubuntu.com/ubuntu precise multiverse deb-src http://archive.ubuntu.com/ubuntu precise multiverse deb http://archive.ubuntu.com/ubuntu precise-updates multiverse deb-src http://archive.ubuntu.com/ubuntu precise-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-src http://pt.archive.ubuntu.com/ubuntu/ lucid-backports main restricted universe 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 lucid partner # deb-src http://archive.canonical.com/ubuntu lucid partner deb http://archive.ubuntu.com/ubuntu precise-security main restricted deb-src http://archive.ubuntu.com/ubuntu precise-security main restricted deb http://archive.ubuntu.com/ubuntu precise-security universe deb-src http://archive.ubuntu.com/ubuntu precise-security universe deb http://archive.ubuntu.com/ubuntu precise-security multiverse deb-src http://archive.ubuntu.com/ubuntu precise-security multiverse # deb http://ppa.launchpad.net/stebbins/handbrake-snapshots/ubuntu precise main # disabled on upgrade to precise I have no clue what do do next. Should I just scrap this installation and start from scratch or is this fixable? librtmp.so.0 also shows up in error logs I've started to get from XBMC (I'm not sure if this is relevant info). Thanks in advance for any help you can give me!
I'm trying to intercept calls to python's double underscore magic methods in new style classes. This is a trivial example but it show's the intent: class ShowMeList(object): def __init__(self, it): self._data = list(it) def __getattr__(self, name): attr = object.__getattribute__(self._data, name) if callable(attr): def wrapper(*a, **kw): print "before the call" result = attr(*a, **kw) print "after the call" return result return wrapper return attr If I use that proxy object around list I get the expected behavior for non-magic methods but my wrapper function is never called for magic methods. >>> l = ShowMeList(range(8)) >>> l #call to __repr__ <__main__.ShowMeList object at 0x9640eac> >>> l.append(9) before the call after the call >> len(l._data) 9 If I don't inherit from object (first line class ShowMeList:) everything works as expected: >>> l = ShowMeList(range(8)) >>> l #call to __repr__ before the call after the call [0, 1, 2, 3, 4, 5, 6, 7] >>> l.append(9) before the call after the call >> len(l._data) 9 How do I accomplish this intercept with new style classes?
How can I print each individual element of a list on separate lines, with the line number of the element printed before the element? The list information will also be retrieved from a text file. So far I have, import sys with open(sys.argv[1], 'rt') as num: t = num.readlines() print("\n"[:-1].join(t)) Which currently gives the read-out: Blah, blah, blahetc, etc, etcx, x, x But I want this read-out: 1. Blah, blah, blah2. etc, etc, etc3. x, x, x Thanks for you help.
I'm trying to setup the trac, this is the commands that I used: sudo apt-get install trac python-setuptools libapache2-mod-python enscript sudo mkdir /var/www/trac sudo trac-admin /var/www/trac/repos initenv but I'm getting the following error: File "/usr/local/bin/trac-admin", line 5, in <module> from pkg_resources import load_entry_point File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 2659, in <module> parse_requirements(__requires__), Environment() File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 546, in resolve raise DistributionNotFound(req) pkg_resources.DistributionNotFound: Trac==0.12.2
Since its inception eight years ago Jack Dorsey's Twitter has grown into one of the most popular websites on the internet. With over a billion registered users and an average of five hundred million tweets sent per day Twitter is creating incredible amounts of data. Many novel ideas have come out of the question of what to do with all of this data, from predicting stocks to more recently predicting crime. When I was first learning python one of the first libraries I came across was Tweepy, an open source, easy to use python library for accessing the Twitter API. There are three different ways to get access to Twitters enormous amounts of data. First is Twitters search API which allows you to gather tweets which were made in the past. You can collect tweets based on user, keywords, locations, its basically the same as when you are searching for tweets on Twitters website except you are limited to how much you can collect. Twitters streaming API allows you to compile tweets as they are happening in real time. You can use the same type parameters as you can with the search API looking for tweets based on keywords or even geographic locations. The disadvantage of the streaming API is that you are not collecting all of the Tweets that are being sent in real time only a sample of ~1% of the current traffic. The only way to get the full stream of all tweets being sent that match your criteria is the Twitter Firehose. The only way to get access to the Firehose is to go through a third party such as Datasift or the recently acquired by twitter, GNIP. Early on when I was experimenting with Tweepy I began thinking of interesting projects that could come out of all this data I had the the potential of collecting. One idea that always stuck was the thought of collecting tweets during sports games and seeing what could be done with the resulting data. Being a Philadelphia Flyers fan I chose to use Twitters streaming API to collect tweets sent during their last playoff game against the New York Rangers (SPOILER ALERT: they lost). The following code takes all tweets with the keyword 'flyers' and sends the time it was created, text of the tweet, location (if available), and the source of the tweet to a local MongoDB database. I have removed my consumer and secret keys, you can obtain your own by creating an app on twitters dev site. import tweepy import sys import pymongo consumer_key="" consumer_secret="" access_token="" access_token_secret="" auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) class CustomStreamListener(tweepy.StreamListener): def __init__(self, api): self.api = api super(tweepy.StreamListener, self).__init__() self.db = pymongo.MongoClient().Flyers def on_status(self, status): print status.text , "\n" data ={} data['text'] = status.text data['created_at'] = status.created_at data['geo'] = status.geo data['source'] = status.source self.db.Tweets.insert(data) def on_error(self, status_code): print >> sys.stderr, 'Encountered error with status code:', status_code return True # Don't kill the stream def on_timeout(self): print >> sys.stderr, 'Timeout...' return True # Don't kill the stream sapi = tweepy.streaming.Stream(auth, CustomStreamListener(api)) sapi.filter(track=['flyers']) Once you run the script you will see the tweets appear on the terminal window and the MongoDB begin to fill. I use the Robomongo GUI to keep track of this. I ran the script fifteen minutes prior to the beginning of the game and ended it fifteen minutes after for the sake of consistency. By the end I had collected 35,443 tweets. For a little bit of context I was collecting around 7,000 tweets for regular season Flyers games and was able to gather 640,000 during the Super Bowl. Once I had all of the data collected I exported a CSV of everything and began looking at it in iPython. The code below creates a pandas dataframe from the CSV file, makes the created_at column into the index and then converts it to a pandas time series. I also converted the time to EST 12 hour format for graph readability. import pandas as pd from pandas.tseries.resample import TimeGrouper from pandas.tseries.offsets import DateOffset flyers = pd.readcsv('/Users/danielforsyth/Desktop/PHINYRG3.csv') flyers['createdat'] = pd.todatetime(pd.Series(flyers['createdat'])) flyers.setindex('createdat', drop=False, inplace=True) flyers.index = flyers.index.tzlocalize('GMT').tzconvert('EST') flyers.index = flyers.index - DateOffset(hours = 12) flyers.index Next I took a quick look at everything using the head and desrcibe methods built into pandas. flyers.head() flyers.describe() Now it was time to get the data ready to graph. One quick line and the created_at timeseries is in a per minute minute format. flyers1m = flyers['created_at'].resample('1t', how='count') flyers1m.head() You can also quickly find the average amount of tweets per minute. Which in this case was 187. avg = flyers1m.mean() Now that I had all of the data formatted properly I imported Vincent and created a graph. import vincent vincent.core.initialize_notebook() area = vincent.Area(flyers1m) area.colors(brew='Spectral') area.display() As you can see because the search term used here was 'flyers' the results are very biased towards them. The two highest peaks in tweet volume are during the first Flyers goal (700 tweets per minute) and the final Rangers goal by ex-Flyer Dan Carcillo (938 tweets per minute), who doesn't have an exceptionally great reputation. There are also two large peaks at the beginning and end of the game. After I had graphed all of the data I turned to looking at the actual tweets themself. For this process I used NLTK which is a natural language processing library for python. The first steps were to import NLTK, create a list of all the text from the tweets and then create a new list after filtering out all of the stop words (high frequency words that are irrelevant i.e. to, the, also). import nltk from nltk.corpus import stopwords from nltk import FreqDist stop = stopwords.words('english') text = flyers['text'] tokens = [] for txt in text.values: tokens.extend([t.lower().strip(":,.") for t in txt.split()]) filtered_tokens = [w for w in tokens if not w in stop] After we have a list of filtered words we are able to look at the frequency ditribution of the words. Below are the 50 most used words and a frequency plot of the 25 most used words. freqdist = nltk.FreqDist(filteredtokens) freq_dist freq_dist.keys()[:50] freq_dist.plot(25) Next I took a look at the source data that was collected with each tweet. Below are the top fifteen sources, as you can see iPhone users dominate the sample with four times as many tweets as both android and web users. flyers.source.value_counts() The last piece of data I had to look at was the location. Since having location data attatched with your tweets is optional not every tweet includes this information. Out of the 35,443 tweets I had collected only 1,609 had location data. Below is a map of all the tweets I created using Folium You can see almost all of the tweets are concentrated in the Philadelphia area but there are also some areas in both Florida and California with some pretty heavy tweeting. In the future I would like to try putting scripts on EC2 instances and pushing all of the tweets to something like Heroku to automate the process and keep from having everything local. I would also like to try searching for the opposing team simultaneously to see how the results differ from one another. Implementing some D3 visualizations is also somthing I would like to try as well as building a real time web application to watch the data come in as the game is being played. This was a very interesting project with some pretty cool results especially considering I was only using around one percent of all the tweets being sent during the game. If you have any questions, feedback, advice, or corrections please get in touch with me on Twitter or email me at [email protected].
SQLAlchemy Although it sometimes might seem as if relational databases have gone the way of the dinosaur, making way for non-relational (NoSQL) databases, such as MongoDB and Cassandra, a very large number of systems still depend on a relational database. And, although there is no requirement that a relational database use SQL as its query language, it's a rare database product that does not do so. The good news is that SQL is relatively easy to work with, particularly when the queries are straightforward. It's fast and easy to create tables, insert data into them, update that data and write queries that retrieve some or all parts of the data. SQL also makes it fairly easy to combine ("join") information from multiple tables, letting you normalize the data, while keeping speed and flexibility at a maximum. SQL might not be difficult to work with on its own, but you rarely work with it in a vacuum. Usually, your SQL statements reside within a program you have written. The SQL is kept as a text string within the application and is then sent, via a network socket, to the server. There are several problems with this. First, it means you have to mix two different languages within the same program. Inside your Web application, which you've worked hard to write, and which you try to ensure is maintainable, you have code in a totally separate language, inside strings, which you cannot test or maintain directly. Even if the SQL queries weren't written inside strings, you still would be faced with the fact that the majority of your Web application is written in one language, but your data-manipulation routines are written in another language. A Web application contains, no matter how you slice it, components in HTML, CSS and JavaScript, as well as whatever server-side language you're using. Adding SQL to this can only complicate things further. Even if SQL and a typical server-side language were on equal footing in terms of the syntax of a Web application, there's a fundamental mismatch between the ways in which they handle data. SQL operates with rows and columns within tables; everything in a relational database has to fit into this table-centric view of the world. By contrast, modern programming languages have a rich variety of data structures and typically are object-oriented to some degree or another. Libraries that bridge the gap between procedural code and SQL are known as object-relational mappers, or ORMs. ORMs typically represent database records as instances of a particular class. In order to represent 50 records, you would need 50 instances of a class, with the state of each instance reflecting the names, types and values of the columns in that record. There are two basic paradigms for passing data between the object-oriented data structures and the database, both of which were described by Martin Fowler. In the first paradigm, known as Active Record, each instance is tied directly to a row in the database, and the class itself (as well as each object) is responsible for ensuring that the data is saved to the database. In other words, Active Record requires that you create a single class, and that it handles both sides of the object-relational divide. The Active Record class in Ruby on Rails is (not surprisingly) an implementation of this paradigm and provides a great deal of power and flexibility. A second paradigm is known as Data Mapper, and it requires the use of three different object classes: a class that represents the data itself at the object level, a class that represents the database table and a "mapper" object that acts as a go-between, ensuring that the object and relational parts of the system are appropriately synchronized. An excellent and popular example of the Data Mapper paradigm can be found in the SQLAlchemy project. SQLAlchemy has been around for a number of years already, and makes it possible to work with relational databases flexibly from within your Python program, without having to write any SQL. In this article, I take a look at SQLAlchemy, exploring a number of its options and features, and considering how it can be used in Web and other applications. Connecting to a Database Installing SQLAlchemy should be straightforward to anyone who has installed Python packages before. You can get SQLAlchemy from PyPi, the Python Package Index, either by downloading it from http://pypi.python.org or by using the easy_install or pip programs to retrieve and install it. I was able to install it with: pip install sqlalchemy You might need to install SQLAlchemy as root. Or, you can install it into a virtual machine, using the popular virtualenv package for Python, which gives you nonroot control and permissions over a Python environment. You also will need to install a driver for the database you intend to use. My favorite relational database is PostgreSQL, and I use the psycopg Python driver, also available on PyPi and (by extension) via pip. I should note that although I know SQLAlchemy works with Python 3, much of the work I do nowadays is still in Python 2, mostly because that's what my clients are using. My examples, thus, also will be in Python 2, although I believe they will work in Python 3 with little or no change. Let's assume you have a database table, People: CREATE TABLE People (id SERIAL PRIMARY KEY, first_name TEXT, last_name TEXT, email TEXT, birthday DATE); Let's also add some initial records: INSERT INTO People (first_name, last_name, email, birthday) VALUES ('Reuven', 'Lerner', '[email protected]', '1970-jul-14'), ('Foo', 'Bar', '[email protected]', '1970-jan-1'); In order to access this table using SQLAlchemy's ORM, you first need to create a database session object, which itself must be created using an "engine". Each database driver has its own style of URL. In the case of PostgreSQL accessed via the psycopg2 driver, you would use something like this: dburl = 'postgresql+psycopg2://reuven:reuven@localhost/atf' This URL indicates not only the database and driver type, but also my user name and password ("reuven" in both cases), the hostname (localhost) and the name of the database I'll be accessing ("atf"). If the database is not available at the default PostgreSQL port of 5432, you can specify that as well in the URL. You then tell Python to create a new engine based on this URL: from sqlalchemy import create_engine engine = create_engine(dburl) Now that you have the engine defined, you can create a session based on this engine. Doing so requires two steps: first you create a new, custom Session class for this engine, and then you create an instance of the Session class that you will use to access the database: from sqlalchemy.orm import sessionmaker # import sessionmaker class Session = sessionmaker(bind=engine) # make custom session type session = Session() # make instance of session You're now connected to the database! But, that's not quite enough. If you want to map your database table to one or more Python objects, you need to define a class. You do this by defining a normal Python class, with a few subtle changes: The class must inherit from Base, a class returned from the declarative_base function provided by SQLAlchemy. The database columns must be defined as class attributes, as instances of the SQLAlchemy-provided Column class. You connect the class with your database table by defining the __tablename__class-level attribute. For example, the following Python class provides a mapping to the People database table: from sqlalchemy import Column, Integer, String, DateTime from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Person(Base): __tablename__ = 'people' id = Column(Integer, primary_key=True) first_name = Column(String) last_name = Column(String) email = Column(String) birthday = Column(DateTime) def __init__(self, firstname, lastname, email, birthday): self.first_name = firstname self.last_name = lastname self.email = email It might not be obvious at first glance, but this class implements the Data Mapper design pattern. The class attributes that you have defined describe the columns in the database table and can contain a great deal of detail, including indexes, uniqueness requirements and even custom integrity constraints, such as those provided by PostgreSQL. The class itself is a standard Python class. But behind the scenes, because this class inherits from Base, you get anumber of other attributes, including __mapper__, which indicates howyour Python class will be mapped to the database table. You can seethis in an interactive Python shell by asking to see the printedrepresentation of Person.__mapper__: Person.__mapper__ <Mapper at 0x10af5ef90; Person> You now have a session that connects to the database and a table in the database that has been described in Python. You now can execute a query against your table: for p in session.query(Person): print p.first_name That gives the following: ReuvenFoo In other words, session.query is executing a query against thedatabase, without you having to specify the SQL. You also can restrictthe records you'll get, by chaining thefilter_by method to yourquery: for p in session.query(Person).filter_by(id=1): print p.first_name That gives the following: Reuven Note that the filter_by method is not acting on the results ofsession.query. Rather, it is changing the SQL thateventually is sentto the database. You can see this by assigning printing to the queryobject without executing it or putting it in an iteration context: print session.query(Person).filter_by(id=1) SELECT people.id AS people_id, people.first_name AS people_first_name, people.last_name AS people_last_name, people.email AS people_email, people.birthday AS people_birthday FROM people WHERE people.id = :id_1 You also can see from this query that SQLAlchemy binds parameters to variables inside your query, rather than directly placing your values. Not only does this allow you to re-run queries later with different variable values, but it reduces the possibility that you will suffer from an SQL injection attack, which still is surprisingly common. You also can order the results: for person in session.query(Person).order_by('first_name'): print person.first_name Foo Reuven And, you also can do all of the basic "CRUD" activities that you would expect. For example, you can create a new instance of your Person class and then save it to the database: p = Person('newfirst', 'newlast', '[email protected]', '1-jan-2012'); session.add(p) session.commit() Notice how I can handle multiple inserts (or other actions) inside a single transaction by only issuingsession.commit() after addingseveral objects. Similarly, I can update the object and thecorresponding row in the database: p.first_name = '!!!' session.add(p) session.commit() I also can delete the object: session.delete(p) session.commit() Reuven M. Lerner, Linux Journal Senior Columnist, a longtime Web developer, consultant and trainer, is completing his PhD in learning sciences at Northwestern University. Web Development News Geolocation Give new life to old phones and tablets with these tips! Lucidchart Memory Ordering in Modern Microprocessors, Part I Linux Systems Administrator Source Code Scanners for Better Code Senior Perl Developer Technical Support Rep Putlocker!! Watch Begin Again Online 2014 Streaming Full Movie Tech Tip: Really Simple HTTP Server with Python
I'm trying to save comments from an iPhone app that may and nowadays most likely will include emoticons. No matter what I do, I can't save the emoticons to the MySQL database ... Constant Unicode errors. Python 2.6.5 Django 1.2.1 MySQL database (set to utf8 character set for tables and rows) Saving the data to a VARCHAR(255) field The error I keep receiving is: Incorrect string value: '\xF0\x9F\x97\xBC \xF0...' for column 'body' at row 1 The string I'm passing into the database is: test_txt = u"Emoji - \U0001f5fc \U0001f60c \U0001f47b ...".encode('utf-8') Update: Here's the model I'm using: class ItemComment(db.Model): item = db.ForeignKey(Item) user = db.ForeignKey(Profile) body = db.CharField(max_length=255, blank=True, null=True) active = db.BooleanField(default=True) date_added = db.DateTimeField(auto_now_add=True) def __unicode__(self): return "%s" % (self.item) The odd thing is, if I try and pass this to a field that I've created in MySQL and not Django models.py it works fine. But as soon as I register the field in Django models it dies. Is there another way to store these perhaps? Any ideas would be amazing. I could not be more stuck on this ... Update 2: Tracking it in Terminal using the following UPDATE statement (notice the U0001f5fc) UPDATE 'table' SET 'body' = '🗼', WHERE 'table'.'id' = 1 ; args=(u'\U0001f5fc') Using as hardcore as I can get to pass the value: force_unicode(smart_str(value), encoding='utf-8', strings_only=False, errors='ignore') But the error still throws: _mysql_exceptions.Warning: Incorrect string value: '\xF0\x9F\x97\xBC' for column 'body' at row 1 Totally lost!!! Cheers,
I've read here that matplotlib is good at handling large data sets. I'm writing a data processing application and have embedded matplotlib plots into wx and have found matplotlib to be TERRIBLE at handling large amounts of data, both in terms of speed and in terms of memory. Does anyone know a way to speed up (reduce memory footprint of) matplotlib other than downsampling your inputs? To illustrate how bad matplotlib is with memory consider this code: import pylab import numpy a = numpy.arange(int(1e7)) # only 10,000,000 32-bit integers (~40 Mb in memory) # watch your system memory now... pylab.plot(a) # this uses over 230 ADDITIONAL Mb of memory
Chris__ Re : gReemote, télécommande + prog TV pour Freebox HD Merci tocks. Je pense aussi que la meilleur des solutions serait de minimiser dans la zone de notif quand on ferme la fenêtre. Je vais regarder ça dès que j'aurai un peu de temps. Pour réduire la fenêtre j'ai peur que ca commence à compliquer pas mal l'appli qui est quand meme juste censé être une télécommande. Mais je vais réflechir à un moyen de faire ça simple quand meme (oui, j'aime la simplicité !!) Pareil pour l'onglet favoris, je veux pas surcharger les onglets. Je préfère comme c'est pour l'instant, avec le choix d'afficher les favoris à la place des chaînes dans le menu "fichier". A part ça il y a déjà un panel de configuration, même s'il n'y a pas grand chose dedans :-D Il s'étoffe au fur et à mesure. Hors ligne tocks Re : gReemote, télécommande + prog TV pour Freebox HD de rien Chris__, dans le menu fichier j'ai quitter et préférence !!! pas de favoris ? On parle bien de la version 1.5 ? c'est vraie que si il y a déjà remplacement des chaines par les favoris sa me convient parfaitement. Pour l'histoire de la mini télécommande, c'est que comme cela je peut fixer cette fenêtre visible devant toutes les fenêtres et la mettre dans un coin de mon écran . Ci qui a mon sens peut être très pratique. ps : j'ai une freebox hd v2 et pourtant je doit choisir hd v1 pour que sa fonctionne ? Hors ligne Chris__ Re : gReemote, télécommande + prog TV pour Freebox HD Ah non tu n'as pas la dernière version. Elle n'est pour l'instant dispo que par svn. D'ici une petite heure elle sera dispo également en .deb et tar.gz, puisqu'elle arrive à maturation Sinon tu m'as convaincu, j'ai ajouté un mode mini. Pour la Freebox v2, ce n'est pas ca qui change le nom du boitier en fait. Cette option n'est présente que pour les gens possédant plusieurs Freebox HD (oui oui, ca existe !) le premier boitier est alors appelé hd1 et le deuxième hd2. Hors ligne tocks Re : gReemote, télécommande + prog TV pour Freebox HD Ha tu voie c'est une bonne idée la mini télécommande . J'ai hâte de voire le résultat. Pour la freebox hd2 ok, je voie ce que c'est. Mais je ne l'avais pas comprit comme cela. J'avais donc pas la bonne version. Comment je peux rajouter ton svn dans mes mises à jour, pour récupérer automatiquement les nouvelles versions? Y a t'il moyen de gérer cela sous ubuntu ? Dernière modification par tocks (Le 19/05/2010, à 20:20) Hors ligne Chris__ Re : gReemote, télécommande + prog TV pour Freebox HD Et voilà, le gReemote nouveau est arrivé :-p Version 1.60 Je ferai le point sur les nouveautés un peu plus tard, mais elles sont toutes décrites dans les posts précédents normalement. J'espère qu'il n'y aura pas trop de confusion entre le mode mini et le mode zone de notification. J'ai finalement choisi de mettre l'appli dans la barre de notif quand on ferme la fenêtre. Peut-être que je mettrai une option pour pouvoir fermer l'appli complètement en fermant la fenêtre. Ca dépend de vous moi j'aime bien comme ça :-) J'espère que cette version répond à la plupart de vos demandes ! Moi je me suis bien amusé ! Et bien sûr je suis toujours à l'écoute de nouvelles propositions, à condition que ca ne surcharge pas trop la visibilité globale. Je n'ai pas envie de perdre en simplicité par l'ajout de fonctionnalités :-S J'ai déjà la sensation que cette version est plus complexe que la précédente. Hors ligne tocks Re : gReemote, télécommande + prog TV pour Freebox HD j'ai installer la version svn, quelle est la commande pour désinstaller ? running install_scripts copying build/scripts-2.6/greemote -> /usr/local/bin changing mode of /usr/local/bin/greemote to 755 running install_egg_info Removing /usr/local/lib/python2.6/dist-packages/greemote-1.6.egg-info Writing /usr/local/lib/python2.6/dist-packages/greemote-1.6.egg-info beber@beber-laptop:~/23-Logiciel_Prod/greemote$ gre greemote grep beber@beber-laptop:~/23-Logiciel_Prod/greemote$ gre greemote grep tocks@tocks-laptop:~/23-Logiciel_Prod/greemote$ greemote Traceback (most recent call last): File "/usr/local/bin/greemote", line 4, in <module> import libgreemote.greemote, socket File "/usr/local/lib/python2.6/dist-packages/libgreemote/greemote.py", line 5, in <module> import urllib,ConfigParser, os, sys, xmltv, zipfile, time, gobject, socket, pynotify, cPickle ImportError: No module named xmltv tocks@tocks-laptop:~/23-Logiciel_Prod/greemote$ Car après l'installation je me retrouve avec cette erreur ? ps : il me manquais sudo aptitude install python-xmltv , aprés avoir désinstaller le paquet Le logiciel marche en ligne de commande, mais je n'ai plus d'icône pour le lancer ?? Sinon encore bravo la 1.6 est encore mieux, en plus la mini télécommande na pas de bordure et reste en premier plan, c'est du top niveau. idée : la dernière petite chose serais un bouton pour passer en mode mini et la je pense qu'il seras parfait. Dernière modification par tocks (Le 19/05/2010, à 21:23) Hors ligne Kasi Re : gReemote, télécommande + prog TV pour Freebox HD Bon je viens de tester la version 1.6. J'ai pas grand chose à dire, c'est du très bon boulot , rapide, efficace. Tu as corrigé des bugs, apporté des améliorations que je pensais mais que je n'avais pas dit, que demander de plus ! Pour chipoter j'ai qu'en même relevé quelques trucs : - L'application se freeze quelques secondes au démarrage le temps de chargement des chaînes (pas sur que tu puisses y faire quelques chose). - Je choisis des modes vidéos différents, mais je ne vois pas de changements... (dans les options du mode, ça serait bien de surligner celui courant) Peut-être que je n'ai pas compris le fonctionnement. - L'option accès au disque dur ne fonctionne alors que le clic droit qui la touche correspondante de la télécommande fonctionne. - Sur la télécommande, on ne sait pas ce que va provoquer comme action le clic droit. Voila c'est tout pour le moment, bon boulot . Manuel Ubuntu : http://www.framabook.org/ubuntu.html Manuel OpenOffice : http://www.framabook.org/openoffice.html Formation Debian : http://formation-debian.via.ecp.fr/ Guide d'autodéfense numérique : http://guide.boum.org/ Hors ligne tocks Re : gReemote, télécommande + prog TV pour Freebox HD Après utilisation depuis tout a l'heure, j'ai trouver un bug : quand on clic sur le croix, l'application vas bien en zone de notif, quand on clic droit les fonction marchent. Mais je n'arrive pas à réouvrir l'application en double cliquant dessus ??? normale ou pas, quand on ouvre l'application elle est encore ouverte en bas de l'écran (y aurait il moyen de l'ouvrir que dans la zone de notification ?? En tous cas bon boulot. ps : Comment on désinstalle une version svn, pour installer après la nouvelle version ? Dernière modification par tocks (Le 19/05/2010, à 21:41) Hors ligne Kasi Re : gReemote, télécommande + prog TV pour Freebox HD C'est un simple clic sur l'icône pour réouvrir la télécommande. Manuel Ubuntu : http://www.framabook.org/ubuntu.html Manuel OpenOffice : http://www.framabook.org/openoffice.html Formation Debian : http://formation-debian.via.ecp.fr/ Guide d'autodéfense numérique : http://guide.boum.org/ Hors ligne Chris__ Re : gReemote, télécommande + prog TV pour Freebox HD j'ai installer la version svn, quelle est la commande pour désinstaller ? Aie, la question qui fâche :-S A vrai dire je n'ai pas de solution miracle, un package distutils est assez complexe à virer. Ma solution : sudo python setup.py install --record installed_files rm -rf `cat installed_files` Ensuite, installer le paquet .deb C'est un simple clic sur l'icône pour réouvrir la télécommande. Merci j'allais le dire :-) Ca va si le seul bug trouvé pour l'instant n'en est pas un, je souffle un peu ;-) - L'application se freeze quelques secondes au démarrage le temps de chargement des chaînes (pas sur que tu puisses y faire quelques chose). Moui je sais... Si j'ai le temps j'y ferai quelque chose. Ce n'est pas bloquant - Je choisis des modes vidéos différents, mais je ne vois pas de changements... (dans les options du mode, ça serait bien de surligner celui courant) Peut-être que je n'ai pas compris le fonctionnement. Oui c'est peut-etre pas très clair... En fait ce qui est important dans la conf du mode, c'est l'ordre ! On peut déplacer les modes vers le haut ou vers le bas ! Ensuit, quand on clic sur une chaine, ca va directement sur le mode choisi le plus haut. Et en cliquant droit sur une chaine, on peut choisir le mode. - L'option accès au disque dur ne fonctionne alors que le clic droit qui la touche correspondante de la télécommande fonctionne. Oui problème de Free, je ne peux rien y faire tant qu'ils ne font pas de nouveau firmware pour corriger le bug - Sur la télécommande, on ne sait pas ce que va provoquer comme action le clic droit. Ah oui ca je vais le corriger, c'est pas top !! Merci pour vos retours en tout cas ! Dernière modification par Chris__ (Le 19/05/2010, à 22:04) Hors ligne grisouille Re : gReemote, télécommande + prog TV pour Freebox HD un grand Merci, je trouve ça nickel ! (j'ai même rien trouver pour chipoter ) Hors ligne Kasi Re : gReemote, télécommande + prog TV pour Freebox HD Kasi a écrit : - Je choisis des modes vidéos différents, mais je ne vois pas de changements... (dans les options du mode, ça serait bien de surligner celui courant) Peut-être que je n'ai pas compris le fonctionnement. Oui c'est peut-etre pas très clair... En fait ce qui est important dans la conf du mode, c'est l'ordre ! On peut déplacer les modes vers le haut ou vers le bas ! Ensuit, quand on clic sur une chaine, ca va directement sur le mode choisi le plus haut. Et en cliquant droit sur une chaine, on peut choisir le mode. Ah oui d'accord avec les explications ça va mieux, il faudrait peut-être un bulle d'aide pour expliquer le fonctionnement . Kasi a écrit : - L'option accès au disque dur ne fonctionne alors que le clic droit qui la touche correspondante de la télécommande fonctionne. Oui problème de Free, je ne peux rien y faire tant qu'ils ne font pas de nouveau firmware pour corriger le bug Ce que je ne comprends pas c'est pourquoi ça ne marche pas dans le menu alors que ça fonctionne dans la mini télécommande . Manuel Ubuntu : http://www.framabook.org/ubuntu.html Manuel OpenOffice : http://www.framabook.org/openoffice.html Formation Debian : http://formation-debian.via.ecp.fr/ Guide d'autodéfense numérique : http://guide.boum.org/ Hors ligne tocks Re : gReemote, télécommande + prog TV pour Freebox HD C'est impeux barbare la façon de désinstaller un programme de cette manière. Enfin si sa marche pas grave. - Comment cela ce passe pour l'installation d'une nouvelle version? - un simple clic sur la télécommande dans la zone de notification ne rouvre pas l'application chez moi ?? tu as raison, après tous ce travail tu as bien le droit a impeux de repos. Dernière modification par tocks (Le 19/05/2010, à 22:30) Hors ligne Chris__ Re : gReemote, télécommande + prog TV pour Freebox HD Ah oui d'accord avec les explications ça va mieux, il faudrait peut-être un bulle d'aide pour expliquer le fonctionnement . En effet, je note. Ce que je ne comprends pas c'est pourquoi ça ne marche pas dans le menu alors que ça fonctionne dans la mini télécommande . Aaah ok ! Alors je vois d'où vient le problème. Ce sera corrigé. (Chez moi, aucun des deux ne marchait) - Comment cela ce passe pour l'installation d'une nouvelle version? Quand tu installes uniquement depuis svn, ca s'installe par dessus les anciens fichiers. Quand tu installes uniquement depuis deb, il fait ça bien et tout seul, il vire tous les anciens fichiers et installe les nouveaux comme il faut ! Je conseille vraiment d'utiliser le fichier deb pour les gens qui ne sont pas sûrs de ce qu'ils font Plus simple ! - un simple clic sur la télécommande dans la zone de notification ne rouvre pas l'application chez moi ?? Là il y a un bug alors... Est-ce que tu pourrais lancer l'appli en ligne de commande, la mettre en zone de notification, puis essayer de la rouvrir. Ensuite me donner la sortie du terminal ? Merci !! (Un peu, pas impeux :-p) Hors ligne Kasi Re : gReemote, télécommande + prog TV pour Freebox HD Ahhhh "bug" . Paris première est disponible en bas débit sur la freebox mais un clic droit sur la chaîne de ta télécommande ne propose que le mode vidéo normal . Manuel Ubuntu : http://www.framabook.org/ubuntu.html Manuel OpenOffice : http://www.framabook.org/openoffice.html Formation Debian : http://formation-debian.via.ecp.fr/ Guide d'autodéfense numérique : http://guide.boum.org/ Hors ligne Chris__ Re : gReemote, télécommande + prog TV pour Freebox HD Hmmm es-tu sûr qu'il y a une chaîne bas-débit à part pour Paris première ? Si oui quel est son numéro ? (entre 450 et 500) Hors ligne Shura Re : gReemote, télécommande + prog TV pour Freebox HD Bonsoir Chris__, Je suis sous KDE et depuis la v 1.60, ça ne marche plus : shura@desktop:~$ greemote Traceback (most recent call last): File "/usr/bin/greemote", line 4, in <module> import libgreemote.greemote, socket File "/usr/lib/python2.6/dist-packages/libgreemote/greemote.py", line 5, in <module> import urllib,ConfigParser, os, sys, xmltv, zipfile, time, gobject, socket, pynotify, cPickle [b]ImportError: No module named pynotify[/b] Une idée pour que ça marche avec KDE ? Sinon tu peux faire une version QT Hors ligne Kasi Re : gReemote, télécommande + prog TV pour Freebox HD Hmmm es-tu sûr qu'il y a une chaîne bas-débit à part pour Paris première ? Si oui quel est son numéro ? (entre 450 et 500) Oui il y a bien un bas débit mais ce n'est pas dans l'intervalle bas débit... (http://www.freenews.fr/spip.php?article7653) En fait c'est le même numéro que le débit normal (19 pour paris première) avec l'option bas débit disponible dans le mode vidéo. Du coup pas sur que tu puisses le prendre en compte... Manuel Ubuntu : http://www.framabook.org/ubuntu.html Manuel OpenOffice : http://www.framabook.org/openoffice.html Formation Debian : http://formation-debian.via.ecp.fr/ Guide d'autodéfense numérique : http://guide.boum.org/ Hors ligne tocks Re : gReemote, télécommande + prog TV pour Freebox HD Voici le retour du simple clic sur la barre de notif : Télécommande pour Freebox HD. Mise à jour des programmes en cours Mise à jour effectuée avec succès. Traceback (most recent call last): File "/usr/local/lib/python2.6/dist-packages/libgreemote/greemote.py", line 440, in on_clic if window.get_visible(): AttributeError: 'gtk.Window' object has no attribute 'get_visible' Je reste en version svn, il faut bien apprendre de nouvelles choses. Les debs je maitrise, mais les svn j'avais jamais utiliser. Je suis sous ubuntu depuis gusty, alors je test de nouvelles approches. Hors ligne Chris__ Re : gReemote, télécommande + prog TV pour Freebox HD Bonsoir Shura ! En effet désolé, j'ai pas pensé aux KDEciens Essaie de récupérer le deb de la version 1.60 (je viens de le mettre à jour en virant pynotify qui ne servait de toute façons à rien !) Je mettrai également à jour dans le tar.gz plus tard. Hors ligne Chris__ Re : gReemote, télécommande + prog TV pour Freebox HD Merci tocks, étrange que la métode "get_visible" marche chez certains et pas chez d'autres. Surement un truc nouveau. En tout cas je l'ai remplacée par autre chose (sur le svn rien que pour toi ) Pour mettre à jour un svn depuis le dossier racine de l'appli : svn update Hors ligne Shura Re : gReemote, télécommande + prog TV pour Freebox HD Bonsoir Shura ! En effet désolé, j'ai pas pensé aux KDEciens Essaie de récupérer le deb de la version 1.60 (je viens de le mettre à jour en virant pynotify qui ne servait de toute façons à rien !) Je mettrai également à jour dans le tar.gz plus tard. J'ai téléchargé le nouveau .deb, mais il y a une autre erreur maintenant : shura@desktop:~$ greemote Télécommande pour Freebox HD. (greemote:7866): libglade-WARNING **: Error loading image: Couldn't recognize the image file format for file '/usr/lib/python2.6/dist-packages/libgreemote/greemote.svg' (greemote:7866): libglade-WARNING **: could not convert string to type `GdkPixbuf' for property `icon' Traceback (most recent call last): File "/usr/bin/greemote", line 13, in <module> main() File "/usr/bin/greemote", line 10, in main libgreemote.greemote.greemote() File "/usr/lib/python2.6/dist-packages/libgreemote/greemote.py", line 517, in __init__ self.icon = TrackerStatusIcon(self) File "/usr/lib/python2.6/dist-packages/libgreemote/greemote.py", line 376, in __init__ self.set_from_pixbuf(gtk.gdk.pixbuf_new_from_file(determine_path () + "/greemote.svg")) glib.GError: Couldn't recognize the image file format for file '/usr/lib/python2.6/dist-packages/libgreemote/greemote.svg' Hors ligne tocks Re : gReemote, télécommande + prog TV pour Freebox HD Merci Chris__, update à partir du svn, le clic fonctionne bien sur la zone de notification. BRAVO y reste pour moi juste 2 petites choses : - un bouton sur le mode normale, pour passer rapidement au mode mini - et je sais pas si on peut, ne pas afficher l'application dans le tableau de bord du bas ?? En tous cas , je te trouve très réaction et ton application touche presque à la perfection ... Je suis sous karmic, cela a peut être une influence sur cette fonction. Hors ligne Chris__ Re : gReemote, télécommande + prog TV pour Freebox HD ... Bon alors maintenant KDE ne sait pas gérer le SVG ? Encore une fois mis à jour le .deb tocks: Tout est possible, y suffit de demander. Mis à jour svn ET le deb (la fenêtre n'apparaît plus dans la barre en mode minimisée). Pour le bouton j'y ai réflechi, je sais pas trop où le mettre pour que ca surcharge pas la fenêtre en mode non minimisée... Si t'as une idée ? Hors ligne Shura Re : gReemote, télécommande + prog TV pour Freebox HD Même erreur shura@desktop:~/Téléchargements$ greemote Télécommande pour Freebox HD. (greemote:11212): libglade-WARNING **: Error loading image: Couldn't recognize the image file format for file '/usr/lib/python2.6/dist-packages/libgreemote/greemote.svg' (greemote:11212): libglade-WARNING **: could not convert string to type `GdkPixbuf' for property `icon' Traceback (most recent call last): File "/usr/bin/greemote", line 13, in <module> main() File "/usr/bin/greemote", line 10, in main libgreemote.greemote.greemote() File "/usr/lib/python2.6/dist-packages/libgreemote/greemote.py", line 517, in __init__ self.icon = TrackerStatusIcon(self) File "/usr/lib/python2.6/dist-packages/libgreemote/greemote.py", line 376, in __init__ self.set_from_pixbuf(gtk.gdk.pixbuf_new_from_file(determine_path () + "/greemote.svg")) glib.GError: Couldn't recognize the image file format for file '/usr/lib/python2.6/dist-packages/libgreemote/greemote.svg' Mais je ne suis pas à la minute, rassure-toi Hors ligne
I was wondering why this works: sys.path.append('/home/user/django') sys.path.append('/home/user/django/mysite') os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' but this doesn't? sys.path.append('/home/user/django') os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' I thought that adding the django folder would automatically make all projects/folders in it available to python? But apparantly I have to add the project as well, or it gives me the error 'settings not found'. Notice that it doesn't say 'mysite.settings not found' which would indicate it does find my 'mysite' folder..
I have written this program after a lot of effort, and I was wondering about the efficiency of that solution and if it's neat. How plain is this program and is there any better way to rewrite it? import string # Strength of operations: # -> [] (brackets) # 6 -> ~ (negative) # 5 -> @, $, & (average, maximum, minimum) # 4 -> %, ! (modulo, factorial) # 3 -> ^ (power) # 2 -> *, / (multiplication, division) # 1 -> +, - (addition, subtraction) def BinaryOperation(exp, idx): """ Gets an expression and an index of an operator and returns a tuple with (first_value, operator, second_value). """ first_value = 0 second_value = 0 #Get first value idx2 = idx -1 if idx2 == 0: first_value = exp[idx2:idx] else: while (idx2 > 0) and (exp[idx2] in string.digits): idx2 -=1 if (exp[idx2] in ("-")) or (exp[idx2] in string.digits):#-5*3 first_value = exp[idx2:idx] else:#%5*3 first_value = exp[idx2+1:idx] #Get second value idx2 = idx +1 if exp[idx+1] not in string.digits: #If there is something like 1*+5, second_sign will be +. idx2 += 1 #idx2 will begin from the char after the sign. while (idx2 < len(exp)) and (exp[idx2] in string.digits): idx2 += 1 second_value = exp[idx+1:idx2] return (first_value, exp[idx], second_value) def UnaryOperation(exp, idx): """ Gets an expression and an index of an operator and returns a tuple with (operator, value). """ #Get value idx2 = idx+1 if exp[idx+1] not in string.digits: #If there is something like ~-5, second_sign will be -. idx2 += 1 #idx2 will begin from the char after the sign. while (idx2 < len(exp)) and (exp[idx2] in string.digits): idx2 +=1 return (exp[idx], exp[idx+1:idx2]) def Brackets(exp): idx = 0 while idx < len(exp): if exp[idx] == "[": #Brackets close_bracket = exp.find("]") if close_bracket == -1: raise Exception("Missing closing bracket.") exp_brackets = exp[idx+1:close_bracket] value = str(solve(exp_brackets)) exp = exp.replace("[" + exp_brackets + "]", value) idx = 0 #The len has been changed, scan again. idx += 1 return Level6(exp) def Level6(exp): idx = 0 while idx < len(exp): if exp[idx] in ("~"): #Negative sub_exp = UnaryOperation(exp, idx) value = ~int(sub_exp[1]) value = str(value) exp = exp.replace(''.join(sub_exp), value) idx = 0 #The len has been changed, scan again. idx += 1 return Level5(exp) def Level5(exp): idx = 0 while idx < len(exp): if exp[idx] in ("@", "$", "&"): #Average, Maximum and Minimum sub_exp = BinaryOperation(exp, idx) first_value = int(sub_exp[0]) second_value = int(sub_exp[2]) if sub_exp[1] == "@": value = (first_value + second_value)/2 if sub_exp[1] == "$": value = first_value if first_value > second_value else second_value if sub_exp[1] == "&": value = first_value if first_value < second_value else second_value value = str(value) exp = exp.replace(''.join(sub_exp), value) idx = 0 #The len has been changed, scan again. idx += 1 return Level4(exp) def Level4(exp): idx = 0 while idx < len(exp): if exp[idx] in ("%","!"): #Modulo and Factorial if exp[idx] == "%": sub_exp = BinaryOperation(exp, idx) value = int(sub_exp[0]) % int(sub_exp[2]) if exp[idx] == "!": sub_exp = UnaryOperation(exp, idx) value = reduce(lambda x,y:x*y, range(1, int(sub_exp[1])+1)) value = str(value) exp = exp.replace(''.join(sub_exp), value) idx = 0 #The len has been changed, scan again. idx += 1 return Level3(exp) def Level3(exp): idx = 0 while idx < len(exp): if exp[idx] in ("^"): #Power sub_exp = BinaryOperation(exp, idx) value = int(sub_exp[0]) ** int(sub_exp[2]) value = str(value) exp = exp.replace(''.join(sub_exp), value) idx = 0 #The len has been changed, scan again. idx += 1 return Level2(exp) def Level2(exp): idx = 0 while idx < len(exp): if exp[idx] in ("*", "/"): #Multiplication and Division sub_exp = BinaryOperation(exp, idx) if sub_exp[1] == "*": value = int(sub_exp[0]) * int(sub_exp[2]) if sub_exp[1] == "/": value = int(sub_exp[0]) / int(sub_exp[2]) value = str(value) exp = exp.replace(''.join(sub_exp), value) idx = 0 #The len has been changed, scan again. idx += 1 return Level1(exp) def Level1(exp): idx = 0 while idx < len(exp): if (exp[idx] in ("+", "-")) and (idx != 0): #Addition and Subtraction sub_exp = BinaryOperation(exp, idx) if sub_exp[1] == "+": value = int(sub_exp[0]) + int(sub_exp[2]) if sub_exp[1] == "-": value = int(sub_exp[0]) - int(sub_exp[2]) value = str(value) exp = exp.replace(''.join(sub_exp), value) idx = 0 #The len has been changed, scan again. idx += 1 return exp def solve(exp): exp = Brackets(exp) return float(exp) if "." in exp else int(exp) def remove_whitespace(exp): """ Gets a string and removes all whitespaces and tabs """ exp = exp.replace(" ", "") exp = exp.replace("\t", "") return exp while True: exp = raw_input("") exp = remove_whitespace(exp) print solve(exp)
fgin Impossible définir les langues du système/ kcmshell4 language-selector Je viens d'installer 12.10, depuis le DVD d'install. Je veux installer le chinois, pour une utilisation dans toutes las applications. Ibus s'intalle sans problème, de meme que tous les packs de langue. MAIS, impossible de changer les langues du systèmes (et donc de configuer chinois / Ibus). La commande : kcmshell4 language-selector retourne : kcmshell(2650)/python (plugin): Failed to import module Traceback (most recent call last): File "/usr/share/kde4/apps/language-selector/language-selector.py", line 4, in <module> from LanguageSelector.qt.QtLanguageSelector import QtLanguageSelector ImportError: No module named LanguageSelector.qt.QtLanguageSelector kcmshell(2650)/python (plugin): Failed to import module kcmshell(2650)/kcontrol KCModuleLoader::loadModule: This module has no valid entry symbol at all. The reason could be that it's still using K_EXPORT_COMPONENT_FACTORY with a custom X-KDE-FactoryName which is not supported anymore Et l'écran indique "Le service "Langues du système" ne fournit pas d'interface "KCModule" avec le mot clé "language-selector/language-selector.py". J'ai suivi un fil de discussion précèdent ( "[Résolu]language selector" ... en fait pas du tout résolu... ), j'ai réinstallé les languages pack, ibus, python, im-selector. Le problème reste le meme, et j'ai vraiment de besoin de configuer le chinois avec IME ibus :-(. Que puis-je faire ? Hors ligne φlip Re : Impossible définir les langues du système/ kcmshell4 language-selector Essaie ça: sudo apt-get update sudo apt-get install --reinstall python-kde4 sudo apt-get install language-selector-kde language-pack-kde-zh-hans + sans garantie: im-switch -s ibus Dernière modification par φlip (Le 18/12/2012, à 00:24) Hors ligne fgin Re : Impossible définir les langues du système/ kcmshell4 language-selector Merci φlip. Malheureusement aucun effet. - pour la partie update/reinstall, je l'avais déjà faite (pas dans cet ordre).. J'ai réssayé par acquit de conscience mais aucun changement. - pour im-switch, j'ai réinstallé im-switch ( vs im-config), et essayé, mais le problème n'est pas vraiment avec l'IME je crois, mais avant : c'est au moment de définirdes langues supplémentaires dans le système, indépendamment de tout IME qu'on voit le pb ( commandekcmshell4 language-selector) . Y a-t-il des utilisateurs 12.10 qui ont réussi à installer d'autres langues ? Je n'ai vraiment rien fait de particulier à l'install de Kubuntu !... En partant du lien fourni, j'ai l'impression qu'il y a un BUG lié à ceci ( [Bug 1013626] Re: systemsettings crashed with ImportError in /usr/share/kde4/apps/language-selector/language -selector.py: No module named LanguageSelector.qt.QtLanguageSelector - msg#37715), mais je n'arrive pas comprendre ce qu'il y vraiment derrière ce bug, et s'il y a des workarounds. Mais alors je ne devrais vraiment pas etre seul à voir ce problème ?? Toute suggestion est la bienvenue. Hors ligne φlip Re : Impossible définir les langues du système/ kcmshell4 language-selector Ce bug de language -selector.py est effectivement parfaitement connu. Je l'ai eu sur certaines installations. Ce qui me surprend est qu'il subsiste dans une installation Quantal updatée. Plus de souvenir clair de la solution, à part un update. L'origine du problème est la transition python 2->3, language-selector-common dépendant maintenant de python3. que dit ceci: dpkg -l language-selector* python[2-3]*|grep ^i|cut -b4-60|sort Dernière modification par φlip (Le 18/12/2012, à 15:51) Hors ligne fgin Re : Impossible définir les langues du système/ kcmshell4 language-selector Résultat de dpkg -l language-selector* python[2-3]*|grep ^i|cut -b4-60|sort language-selector-common 0.90 language-selector-kde 0.90 python2.7 2.7.3-5ubuntu4 python2.7-minimal 2.7.3-5ubuntu4 python3.2 3.2.3-6ubuntu3 python3.2-minimal 3.2.3-6ubuntu3 python3 3.2.3-5ubuntu1 python3-apport 2.6.1-0ubuntu9 python3-apt 0.8.7ubuntu4 python3-aptdaemon 0.45+bzr861-0u python3-aptdaemon.pkcompat 0.45+bzr861-0u python3-dbus 1.1.1-1 python3-defer 1.0.6-2 python3-distupgrade 1:0.190.4 python3-gdbm 3.3.0-1 python3-gi 3.4.0-1ubuntu0 python3-minimal 3.2.3-5ubuntu1 python3-pkg-resources 0.6.28-1ubuntu python3-problem-report 2.6.1-0ubuntu9 python3-pykde4 4:4.9.3-0ubunt python3-pyqt4 4.9.3-4 python3-sip 4.13.3-2 python3-software-properties 0.92.9 python3-update-manager 1:0.174.3 python3-xkit 0.5.0 Hors ligne φlip Re : Impossible définir les langues du système/ kcmshell4 language-selector Je pense que le mélange des versions python fait de la mayonnaise: 2.7 - 3 - 3.2 python2.7 2.7.3-5ubuntu4 python3 3.2.3-5ubuntu1 python3.2 3.2.3-6ubuntu3 python-kde4 dépend de: python (>= 2.7.1-0ubuntu2), python (<< 2.8) Le problème est que les installations patatoïdales complètes genre DVD installent tellement de choses, que la probabilité de conflit est accrue. La piste intéressante serait de comparer à un autre utilisateur qui fait des installations liveCD complète pour voir s'il a le même problème avec Quantal. Ou qu'un expert Python démerde le sac de nœuds entre versions python 3/3.2 (variables d'environnement etc). Pour information, sans Python 3.2 installé, je n'ai pas ce problème. que dit le retour de ceci: grep -r LanguageSelector.qt.QtLanguageSelector /usr/lib/python* ls /usr/lib/python*/dist-packages/LanguageSelector/qt/QtLanguageSelector.py grep python /usr/share/kde4/apps/language-selector/language-selector.py Et aussi... language-selector-kde est actuellement en version 0.98 (au lieu de 0.90 dans Quantal). Tu ne prendrais pas de grands risques en essayant ceci: cd /tmp wget http://mirror.ovh.net/ubuntu//pool/universe/l/language-selector/language-selector-kde_0.98_all.deb sudo dpkg -i language-selector-kde_0.98_all.deb Dernière modification par φlip (Le 19/12/2012, à 16:52) Hors ligne fgin Re : Impossible définir les langues du système/ kcmshell4 language-selector C'est vraiment sympa de ta part de m'aider sur ce point. Merci. Voici le résultat des commandes. grep -r LanguageSelector.qt.QtLanguageSelector /usr/lib/python* : /usr/lib/python3/dist-packages/language_selector-0.1.egg-info/SOURCES.txt:LanguageSelector/qt/QtLanguageSelector.py /usr/lib/python3/dist-packages/language_selector-0.1.egg-info/SOURCES.txt:LanguageSelector/qt/QtLanguageSelectorGUI.py /usr/lib/python3/dist-packages/LanguageSelector/qt/QtLanguageSelector.py:from LanguageSelector.qt.QtLanguageSelectorGUI import Ui_QtLanguageSelectorGUI ls /usr/lib/python*/dist-packages/LanguageSelector/qt/QtLanguageSelector.py: /usr/lib/python3/dist-packages/LanguageSelector/qt/QtLanguageSelector.py grep python /usr/share/kde4/apps/language-selector/language-selector.py : #!/usr/bin/python3 Quant à ta dernière proposition, j'ai une dépendance avec language-selector-common 0.98 que je n'ai pas réussi à résoudre. dpkg: des problèmes de dépendances empêchent la configuration de language-selector-kde : language-selector-kde dépend de language-selector-common (= 0.98) ; cependant la version de language-selector-common sur le système est 0.90. Je vais essayer de regarder de plus prés les modules Python. Hors ligne φlip Re : Impossible définir les langues du système/ kcmshell4 language-selector "dépendance avec language-selector-common 0.98 que je n'ai pas réussi à résoudre" Oubli de ma part: cd /tmp wget http://mirror.ovh.net/ubuntu//pool/main/l/language-selector/language-selector-common_0.98_all.deb sudo dpkg -i language-selector-common_0.98_all.deb sudo apt-get install -f Dernière modification par φlip (Le 19/12/2012, à 19:36) Hors ligne fgin Re : Impossible définir les langues du système/ kcmshell4 language-selector Merci. ... malheureusement aucun changement. Meme message d'erreur. kcmshell4 language-selector kcmshell(4572)/python (plugin): Failed to import module Traceback (most recent call last): File "/usr/share/kde4/apps/language-selector/language-selector.py", line 4, in <module> from LanguageSelector.qt.QtLanguageSelector import QtLanguageSelector ImportError: No module named LanguageSelector.qt.QtLanguageSelector kcmshell(4572)/python (plugin): Failed to import module kcmshell(4572)/kcontrol KCModuleLoader::loadModule: This module has no valid entry symbol at all. The reason could be that it's still using K_EXPORT_COMPONENT_FACTORY with a custom X-KDE-FactoryName which is not supported anymore [ Je viens de trouver ce bug : Bug 1066771 Re: language-selector-kde unusable qui décrit exactement mon problème... Et apparemment pas de solution. Je me demande si je ne devrais pas retourner sur une version antérieure de KDE, ou essayer Gnome-Deskop en attendant un fix ? Hors ligne φlip Re : Impossible définir les langues du système/ kcmshell4 language-selector Oui ce bug est bien connu, comme déjà dit. Je l'ai connu aussi avec le module imprimante (problème de pythonerie), bien avant Quantal et dans Debian. C'est la transition python 2->3 qui n'est pas clean et stabilisée. Mais ..... pourquoi ce bug n'existe pas dans certaines installations Quantal, et pourquoi dans d'autres ? C'est le point qui reste encore un peu mystérieux pour le moment. Personnellement, je n'installe jamais en "liveCD" et j'ai donc une installation plus propre. Mais je disais: La piste intéressante serait de comparer à un autre utilisateur qui fait des installations liveCD complète pour voir s'il a le même problème avec Quantal. "Je me demande si je ne devrais pas retourner sur une version antérieure de KDE, ou essayer Gnome-Deskop en attendant un fix ?" Ou l'inverse ... pousser vers raring. Mais je dis ça, je dis rien. Dernière modification par φlip (Le 19/12/2012, à 20:14) Hors ligne
How do I remove leading and trailing whitespace from a string in Python? For example: " Hello " --> "Hello"" Hello" --> "Hello""Hello " --> "Hello""Bob has a cat" --> "Bob has a cat" Just one space, or all such spaces? If the second, then strings already have a >>> ' Hello '.strip() 'Hello' >>> ' Hello'.strip() 'Hello' >>> 'Bob has a cat'.strip() 'Bob has a cat' >>> ' Hello '.strip() # ALL spaces at ends removed 'Hello' If you need only to remove one space however, you could do it with: def strip_one_space(s): if s.endswith(" "): s = s[:-1] if s.startswith(" "): s = s[1:] return s >>> strip_one_space(" Hello ") ' Hello' Also, note that >>> " Hello\n".strip(" ") 'Hello\n' As pointed out in answers above myString.strip() will remove all the leading and trailing whitespace characters such as \n, \r, \t, \f, space. For more flexibility use the following More details are available in the docs # remove all leading/trailing commas, periods and hyphens title = title.strip(',.-') myString.strip() You want strip(): myphrases = [ " Hello ", " Hello", "Hello ", "Bob has a cat" ] for phrase in myphrases: print phrase.strip()
Yesterday we released the latest unstable version of MongoDB; the headline feature is basic full-text search. You can read all about MongoDB's full text search in the release notes. This blog had been using a really terrible method for search, involving regular expressions, a full collection scan for every search, and no ranking of results by relevance. I wanted to replace all that cruft with MongoDB's full-text search ASAP. Here's what I did. Plain Text My blog is written in Markdown and displayed as HTML. What I want to actually search is the posts' plain text, so I customized Python's standard HTMLParser to strip tags from the HTML: import re from HTMLParser import HTMLParser whitespace = re.compile('\s+') class HTMLStripTags(HTMLParser): """Strip tags """ def __init__(self, *args, **kwargs): HTMLParser.__init__(self, *args, **kwargs) self.out = "" def handle_data(self, data): self.out += data def handle_entityref(self, name): self.out += '&%s;' % name def handle_charref(self, name): return self.handle_entityref('#' + name) def value(self): # Collapse whitespace return whitespace.sub(' ', self.out).strip() def plain(html): parser = HTMLStripTags() parser.feed(html) return parser.value() The output is imperfect—it adds extra spaces around punctuation and generally creates a small mess—but it's not meant to be published in the New Yorker, it's meant to be indexed. I wrote a script that runs through all my existing posts, extracts the plain text, and stores it in a new field on each document called plain. I also updated my blog's code so it now creates the plain field on each post whenever I save a post. I installed MongoDB 2.3.2 and started it with this command line option: --setParameter textSearchEnabled=true Without that option, creating a text index causes a server error, "text search not enabled". Next I created a text index on posts' titles, category names, tags, and the plain text that I generated above. I can set different relevance weights for each field. The title contributes most to a post's relevance score, followed by categories and tags, and finally the text. In Python, the index declaration looks like: db.posts.create_index( [ ('title', 'text'), ('categories.name', 'text'), ('tags', 'text'), ('plain', 'text') ], weights={ 'title': 10, 'categories.name': 5, 'tags': 5, 'plain': 1 } ) Note that you'll need to install PyMongo from the current master in GitHub or wait for PyMongo 2.4.2 in order to create a text index. PyMongo 2.4.1 and earlier throw an exception: TypeError: second item in each key pair must be ASCENDING, DESCENDING, GEO2D, or GEOHAYSTACK If you don't want to upgrade PyMongo, just use the mongo shell to create the index: db.posts.createIndex( { title: 'text', 'categories.name': 'text', tags: 'text', plain: 'text' }, { weights: { title: 10, 'categories.name': 5, tags: 5, plain: 1 } } )Searching the Index To use the text index I can't do a normal find, I have to run the text command. In my async driver Motor, this looks like: response = yield motor.Op(self.db.command, 'text', 'posts', search=q, filter={'status': 'publish', 'type': 'post'}, projection={ 'display': False, 'original': False, 'plain': False }, limit=50) The q variable is whatever you typed into the search box on the left, like "mongo" or "hamster" or "python's thread locals are weird". The filter option ensures only published posts are returned, and the projection avoids returning large unneeded fields. Results are sorted with the most relevant first, and the limit is applied after the sort. Simple, right? The new text index provides a simple, fully consistent way to do basic search without deploying any extra services. Go read up about it in the release notes.
I am trying to reference a slice of a "global" numpy array via a object attribute. Here is what I think the class structure would be like and it's use case. import numpy class X: def __init__(self, parent): self.parent = parent self.pid = [0, 1, 2] def __getattr__(self, name): if name == 'values': return self.parent.P[self.pid] else: raise AttributeError class Node: def __init__(self): self.P = numpy.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) self._values = X(self) def __getattr__(self, name): if name == 'x': return self._values.values else: raise AttributeError Here is the use case: >>> n = Node() >>> print n.P [ 1 2 3 4 5 6 7 8 9 10] >>> print n.x [1 2 3] >>> print n.x[1:3] [2 3] Which works fine, now I would like to assign values to n.P through the n.x attribute by, >>> n.x = numpy.array([11, 12, 13]) to get, >>> print n.P [ 11 12 13 4 5 6 7 8 9 10] Or assign values to slices by, >>> n.x[1:3] = numpy.array([77, 88]) to get, >>> print n.P [ 11 77 88 4 5 6 7 8 9 10] But for the life of me, I'm struggling to get this assignment working. I thought it would be easy using __setattr__ and __setitem__, but a whole day later I still haven't managed it. Ultimately, n.x will be returned as a multi-dimensional array where the X class will reshape is on return, but is stored in a n.P which is a vector. I have removed this to simplify the problem. I would love some help on this. Has anyone done this before? Or suggest how to do this? Thanks in advance for your help. SOLUTION So after many days of stumbling around I found a solution. I suspect this can be simplified and refined. The solution is to create a X object in your Node object. When it's retrieved, it returns temporary numpy object (Values) with knowledge of it's parent node and pids. The setslice_ function is defined in this update the global P array with the new values. If the X object is is assigned, it doesn't return a Values object but sets the global P values directly. Two points, which may be invalid: 1. The Node and X objects had to be a sub-class of object; 2. if setting a higher dimension array, you need to use __setitem__ instead, which won't work on 1D arrays or lists. As I said I suspect this code can be improves since I'm not sure I fully understand it. I am happy to take improvements and suggestions. Thanks for your help, especially Bago. Here is my final code. import numpy class Values(numpy.ndarray): def __new__(cls, input_array, node, pids): obj = numpy.asarray(input_array).view(cls) obj.node = node obj.pids = pids return obj def __setslice__(self, i, j, values): self.node._set_values(self.pids[i:j], values) class X(object): def __get__(self, instance, owner): p = instance.P[instance.pids] return Values(p, instance, instance.pids) def __set__(self, instance, values): instance.P[instance.pids] = values class Node(object): x = X() def __init__(self, pids=[0, 1, 2]): self.P = numpy.arange(11) self.pids = pids def _set_values(self, pids, values): self.P[pids] = values node = Node(pids=[4, 5, 6, 7]) print '\nInitial State:' print 'P =', node.P print 'x =', node.x print 'x[1:3] =', node.x[1:3] print '\nSetting node.x = [44, 55, 66, 77]:' node.x = [44, 55, 66, 77] print 'P =', node.P print 'x =', node.x print 'x[1:3] =', node.x[1:3] print '\nSetting node.x[1:3] = [100, 200]:' node.x[1:3] = [100, 200] print 'P =', node.P print 'x =', node.x print 'x[1:3] =', node.x[1:3]
Sublime 中安裝 Evernote 外掛,支援 Markdown (Mac) Install Evernote Plugin in Sublime supported Markdown (Mac) 安裝 Evernote 外掛好處 可以直接存取 Evernote 記事,新增、儲存、開啟、更新,不需寫在本機 支援 Markdown (在Sublime寫Markdown格式,Evernote 呈現)(本文利用 Markdown 所寫,寫完後顯示在 Evernote,然後複製到此 Blog貼上) 安裝方法 (In Sublime) 1. 安裝 Package Control 到 Sublime Package Control 官網安裝頁面 Link:PackageControl 複製左半邊的 Code (對照 sublime 的版本, 2 or 3) 到 Sublime 中,按下 Ctrl+` 三個鍵,並貼上剛剛複製的 Code,按Enter,就完成安裝 (等20秒鐘) 註:Code 長這樣: import urllib.request,os,hashlib; h = '7183a2d3e96f11eeadd761d777e62404' + 'e330c659d4bb41d3bdf022e94cab3cd0'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); by = urllib.request.urlopen( 'http://sublime.wbond.net/' + pf.replace(' ', '%20')).read(); dh = hashlib.sha256(by).hexdigest(); print('Error validating download (got %s instead of %s), please try manual install' % (dh, h)) if dh != h else open(os.path.join( ipp, pf), 'wb' ).write(by) 2. 安裝 Evernote Plugin (In Sublime) 按下 (In Mac) cmd+shift+p, (In Windows)ctrl+shift+p,會跳出一個框框 輸入 package control: install package,會剩下一個選項,按 enter,又會有一個輸入框 輸入 evernote,找到Evernote按下 enter,等一下就安裝好摟 這時候按下 cmd(ctrl)+shift+p,輸入evernote就可以看到一堆 evernote 連結的功能摟!! 3. 設定 Evernote 帳號 要先取得 Evernote 授權,請到 Get Evernote API Token 登入後,點選 Create a developer token,會得到Developer token和NoteStore URL,把他記下來 到 Sublime ,點選上面工具列 Sublime Text>Preferences>Package Setting>Evernote>Setting User,後會開啟一個新文字視窗。 新文字視窗內容長的像這樣: { "noteStoreUrl": "https://www.evernote.com/shard/xxx/notestore", "token": "S=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } 把剛剛的 Developer token貼上到token,NoteStore URL貼上到noteStoreUrl並且儲存。這樣就有權限使用 Evernote Plugin 功能 (cmd(ctrl)+shift+p, 輸入搜尋evernote)。 4. 設定 Evernote 功能快速鍵 每次都要搜尋 Evernote 功能很麻煩,所以可以設一些快速鍵,用起來就跟處理一般檔案一樣方便。 到 Sublime ,點選上面工具列 Sublime Text>Preferences>Key Bindings - Users,會打開一個文字視窗。 在裡面輸入快捷鍵以及指令: 類似這樣的 Json 格式: [ { "keys": ["ctrl+e"], "command": "show_overlay", "args": {"overlay": "command_palette", "text": "Evernote: "} }, { "keys": ["ctrl+s"], "command": "send_to_evernote" }, { "keys": ["ctrl+o"], "command": "open_evernote_note" }, { "keys": ["ctrl+u"], "command": "save_evernote_note" }, ] ctrl+e:顯示 Evernote Plugin 所有功能 ctrl+s:儲存新的文章進入 Evernote (要儲存時會要求填寫 Title, Tag, 選擇存放的筆記本) ctrl+o:開啟Evernote筆記 (會要求選 記事本, 記事文章) ctrl+u:更新文章,必須是已經新儲存或是已經打開過的才可以使用 當然,快速鍵的按鍵方式,可以自行更改,也可以覆蓋預設的方法。像是改成 cmd+s,把原本的儲存功能換掉。(還是可用選單的儲存存入本地磁碟) 以上為小弟的安裝過程,希望可以幫助到有需要的人
So, I've been banging my head against the wall the last few days trying to figure out what's wrong with my script. It's suppose to pull weekly flu data from a department of health website, parse it for that week, and then push the data up to our SDE server so that it can be displayed on our Web Mapping application. The data is in a .csv format and the script parses the data just fine, but when it comes to doing a join with a feature class with county outlines I get a Traceback (most recent call last): File "C:\Users\username\Desktop\Projects\flu_mapping\script\flu_data0.6.0.py", >line 55, in arcpy.JoinField_management ("memorycounty", "ID", outputcsv, "Statecode",) File "C:\Program Files (x86)\ArcGIS\Desktop10.1\arcpy\arcpy\management.py", line 5383, >in JoinField raise e RuntimeError: Object: Error in executing tool This wasn't an issues until I started using the open() command to create a new .csv file to parse the data to, instead of manually making one. Here is my code import os import arcpy from arcpy import env import math import numpy import csv import urllib2 import tempfile #working directory fludirectory = 'C:\\Users\\username\\Desktop\\Projects\\flu_mapping\\GIS_data\\' #pull flu data from ND Department of health fludata = urllib2.urlopen ('http://www.ndflu.com/data/weekenddata.txt') #arcpy workspace arcpy.env.workspace = "in_memory" #load data so that numpy can use it rows = numpy.loadtxt(fludata, int, delimiter=",",skiprows=4, usecols =(2,3,4,5,6,7,8,9)) #parse the data and write it to the CSV file createcsv = fludirectory + "\\" + 'output_data.csv' outputcsv = open (createcsv, 'wb') week = max(rows [:,0]) with outputcsv as csvfile: flucsv = csv.writer(csvfile, delimiter=",", quotechar='|', quoting=csv.QUOTE_MINIMAL) flucsv.writerow (["Statecode","flu_num"]) for row in rows: if row[0] == week: countid = row[1] totalflu = sum(row[2:]) csvoutput = '%s, %s' %(countid, totalflu) print csvoutput flucsv.writerow ([countid, totalflu]) outputcsv.close #make a copy of the county dataset #county dataset countydata = fludirectory + "\\" + 'county_ID_code.shp' #make a temporary feature layer arcpy.MakeFeatureLayer_management (countydata, "memorycounty") #join output csvoutput to the in_memory shapefile arcpy.JoinField_management ("memorycounty", "ID", outputcsv, "Statecode",) #test the script arcpy.FeatureClassToFeatureClass_conversion ("memorycounty", fludirectory, 'testoutput.shp') Also at the end I am using Feature Class to Feature Class to see if everything worked (obviously it's not) and that will be replaced by code that pushes the feature class to the SDE server. Thanks for the help!
I get this error on Linux (Ubuntu and CentOS) when executing a stored proc from Perl/DBI/ODBC/FreeTDS to SQL Azure: [unixODBC][FreeTDS][SQL Server]Read from the server failed (SQL-08S01) I don't get this error running the same Perl script on Windows (ODBC/Native) connecting to the same SQL Azure database, and although the proc takes a couple minutes to run, it does complete. Obviously a completely different client/driver environment, but they are both going to the same SQL Azure database and there is no difference in the Perl script itself. Both Perl environments should be similar but obviously the client/drivers will be different. The line which fails is simple - a proc with no parameters which takes data from a staging table and processes it - at the time of failure from Linux call, the environment on SQL Azure is not significantly different than when I test called from Windows (it is completely reproducible when the staging table is loaded with certain data and invoked from Linux): $dbh->do("EXEC procname;") or die $DBI::errstr ; Indications from my searches are that this is some kind of connection issue or timeout. I'm working to improve the proc performance, but the timeout is not set on the Linux machines (so should default to 0). Is there something I can do to stop this error? Here is the log from FreeTDS of a bad run: util.c:156:Changed query state from IDLE to QUERYING write.c:140:tds_put_string converting 27 bytes of "EXEC DWTOOLS.LoadFromStage;" write.c:168:tds_put_string wrote 54 bytes util.c:156:Changed query state from QUERYING to PENDING net.c:741:Sending packet 0000 01 01 00 3e 00 00 01 00-45 00 58 00 45 00 43 00 |...>.... E.X.E.C.| 0010 20 00 44 00 57 00 54 00-4f 00 4f 00 4c 00 53 00 | .D.W.T. O.O.L.S.| 0020 2e 00 4c 00 6f 00 61 00-64 00 46 00 72 00 6f 00 |..L.o.a. d.F.r.o.| 0030 6d 00 53 00 74 00 61 00-67 00 65 00 3b 00 |m.S.t.a. g.e.;.| net.c:1257:GNUTLS: level 4: REC[0x9a833c8]: Sending Packet[5] Application Data(23) with length: 62 net.c:1257:GNUTLS: level 7: WRITE: enqueued 101 bytes for 0x9a574b8. Total 101 bytes. net.c:1257:GNUTLS: level 7: WRITE FLUSH: 101 bytes in buffer. net.c:1240:in tds_push_func net.c:1257:GNUTLS: level 7: WRITE: wrote 101 bytes, 0 bytes left. net.c:1257:GNUTLS: level 4: REC[0x9a833c8]: Sent Packet[6] Application Data(23) with length: 101 token.c:540:tds_process_tokens(0x9a574b8, 0xbfcb9ca8, 0xbfcb9cac, 0x6914) util.c:156:Changed query state from PENDING to READING net.c:1199:in tds_pull_func util.c:331:tdserror(0x9a54e80, 0x9a574b8, 20004, 104) odbc.c:2270:msgno 20004 20003 util.c:361:tdserror: client library returned TDS_INT_CANCEL(2) util.c:384:tdserror: returning TDS_INT_CANCEL(2) util.c:156:Changed query state from READING to DEAD net.c:1257:GNUTLS: level 7: READ: -1 returned from 0x9a574b8, errno=104 gerrno=0 net.c:1257:GNUTLS: level 2: ASSERT: gnutls_buffers.c:344 net.c:1257:GNUTLS: level 2: ASSERT: gnutls_buffers.c:625 net.c:1257:GNUTLS: level 2: ASSERT: gnutls_record.c:969 token.c:555:processing result tokens. marker is 0() token.c:122:tds_process_default_tokens() marker is 0() token.c:125:leaving tds_process_default_tokens() connection dead util.c:104:logic error: cannot change query state from DEAD to PENDING odbc.c:3534:odbc_process_tokens: tds_process_tokens returned 0 odbc.c:3535: result_type=4055, TDS_DONE_COUNT=0, TDS_DONE_ERROR=0 odbc.c:3374:_SQLExecute: odbc_process_tokens returned result_type 4048 odbc.c:3450:SQLExecute: bad results error.c:517:SQLGetDiagRec(3, 0x9a89fe8, 1, 0xbfcb9ce6, 0xbfcb98b8, 0xbfcb9ae6, 512, 0xbfcb98bc) error.c:566:SQLGetDiagRec: "[FreeTDS][SQL Server]Read from the server failed" error.c:517:SQLGetDiagRec(3, 0x9a89fe8, 2, 0xbfcb9ce6, 0xbfcb98b8, 0xbfcb9ae6, 512, 0xbfcb98bc) odbc.c:3980:SQLFreeHandle(3, 0x9a89fe8) odbc.c:4075:_SQLFreeStmt(0x9a89fe8, 1, 0) odbc.c:4718:_SQLGetConnectAttr(0x9a55d78, 102, 0xbfcb9e90, -5, (nil)) odbc.c:2240:SQLDisconnect(0x9a55d78) mem.c:615:tds_free_all_results() net.c:1257:GNUTLS: level 6: BUF[HSK]: Cleared Data from buffer net.c:1257:GNUTLS: level 4: REC[0x9a833c8]: Epoch #1 freed odbc.c:3980:SQLFreeHandle(2, 0x9a55d78) odbc.c:4006:_SQLFreeConnect(0x9a55d78) odbc.c:3980:SQLFreeHandle(1, 0x9a552f0) odbc.c:4050:_SQLFreeEnv(0x9a552f0) Here is the log from a good run - the same proc, just slightly different data - there seems to be no error running the proc from Windows: util.c:156:Changed query state from IDLE to QUERYING write.c:140:tds_put_string converting 27 bytes of "EXEC DWTOOLS.LoadFromStage;" write.c:168:tds_put_string wrote 54 bytes util.c:156:Changed query state from QUERYING to PENDING net.c:741:Sending packet 0000 01 01 00 3e 00 00 01 00-45 00 58 00 45 00 43 00 |...>.... E.X.E.C.| 0010 20 00 44 00 57 00 54 00-4f 00 4f 00 4c 00 53 00 | .D.W.T. O.O.L.S.| 0020 2e 00 4c 00 6f 00 61 00-64 00 46 00 72 00 6f 00 |..L.o.a. d.F.r.o.| 0030 6d 00 53 00 74 00 61 00-67 00 65 00 3b 00 |m.S.t.a. g.e.;.| net.c:1257:GNUTLS: level 4: REC[0x96ed3c8]: Sending Packet[5] Application Data(23) with length: 62 net.c:1257:GNUTLS: level 7: WRITE: enqueued 101 bytes for 0x96c14b8. Total 101 bytes. net.c:1257:GNUTLS: level 7: WRITE FLUSH: 101 bytes in buffer. net.c:1240:in tds_push_func net.c:1257:GNUTLS: level 7: WRITE: wrote 101 bytes, 0 bytes left. net.c:1257:GNUTLS: level 4: REC[0x96ed3c8]: Sent Packet[6] Application Data(23) with length: 101 token.c:540:tds_process_tokens(0x96c14b8, 0xbfd5aeb8, 0xbfd5aebc, 0x6914) util.c:156:Changed query state from PENDING to READING net.c:1199:in tds_pull_func net.c:1257:GNUTLS: level 7: READ: Got 5 bytes from 0x96c14b8 net.c:1257:GNUTLS: level 7: READ: read 5 bytes from 0x96c14b8 net.c:1257:GNUTLS: level 7: RB: Have 0 bytes into buffer. Adding 5 bytes. net.c:1257:GNUTLS: level 7: RB: Requested 5 bytes net.c:1257:GNUTLS: level 4: REC[0x96ed3c8]: Expected Packet[5] Application Data(23) with length: 8 net.c:1257:GNUTLS: level 4: REC[0x96ed3c8]: Received Packet[5] Application Data(23) with length: 48 net.c:1199:in tds_pull_func net.c:1257:GNUTLS: level 7: READ: Got 48 bytes from 0x96c14b8 net.c:1257:GNUTLS: level 7: READ: read 48 bytes from 0x96c14b8 net.c:1257:GNUTLS: level 7: RB: Have 5 bytes into buffer. Adding 48 bytes. net.c:1257:GNUTLS: level 7: RB: Requested 53 bytes net.c:1257:GNUTLS: level 4: REC[0x96ed3c8]: Decrypted Packet[5] Application Data(23) with length: 22 net.c:1257:GNUTLS: level 6: BUF[REC]: Inserted 22 bytes of Data(23) net.c:1257:GNUTLS: level 6: BUFFER[REC][AD]: Read 8 bytes of Data(23) net.c:555:Received header 0000 04 01 00 16 03 2f 01 00- |...../..| net.c:1257:GNUTLS: level 6: BUFFER[REC][AD]: Read 14 bytes of Data(23) net.c:609:Received packet 0000 04 01 00 16 03 2f 01 00-79 00 00 00 00 fe 00 00 |...../.. y.......| 0010 e0 00 00 00 00 00 - |......| token.c:555:processing result tokens. marker is 79(RETURNSTATUS) token.c:690:tds_process_tokens: return status is 0 util.c:156:Changed query state from READING to PENDING odbc.c:3534:odbc_process_tokens: tds_process_tokens returned 1 odbc.c:3535: result_type=4043, TDS_DONE_COUNT=0, TDS_DONE_ERROR=0 token.c:540:tds_process_tokens(0x96c14b8, 0xbfd5aeb8, 0xbfd5aebc, 0x6914) util.c:156:Changed query state from PENDING to READING token.c:555:processing result tokens. marker is fe(DONEPROC) token.c:2339:tds_process_end: more_results = 0 was_cancelled = 0 error = 0 done_count_valid = 0 token.c:2355:tds_process_end() state set to TDS_IDLE util.c:156:Changed query state from READING to IDLE token.c:2370: rows_affected = 0 util.c:104:logic error: cannot change query state from IDLE to PENDING odbc.c:3534:odbc_process_tokens: tds_process_tokens returned 1 odbc.c:3535: result_type=4053, TDS_DONE_COUNT=0, TDS_DONE_ERROR=0 odbc.c:3578:odbc_process_tokens: processed TDS_DONEPROC_RESULT token.c:540:tds_process_tokens(0x96c14b8, 0xbfd5aeb8, 0xbfd5aebc, 0x26914) token.c:543:tds_process_tokens() state is COMPLETED odbc.c:3534:odbc_process_tokens: tds_process_tokens returned 2 odbc.c:3535: result_type=4052, TDS_DONE_COUNT=0, TDS_DONE_ERROR=0 odbc.c:3374:_SQLExecute: odbc_process_tokens returned result_type 4046 odbc.c:4506:_SQLRowCount(0x96f3fe8, 0xbfd5b0b8) odbc.c:4525:SQLRowCount returns 0, row count -1 odbc.c:3980:SQLFreeHandle(3, 0x96f3fe8) odbc.c:4075:_SQLFreeStmt(0x96f3fe8, 1, 0) odbc.c:4718:_SQLGetConnectAttr(0x96bfd78, 102, 0xbfd5b240, -5, (nil)) odbc.c:2240:SQLDisconnect(0x96bfd78) mem.c:615:tds_free_all_results() net.c:1257:GNUTLS: level 6: BUF[HSK]: Cleared Data from buffer net.c:1257:GNUTLS: level 4: REC[0x96ed3c8]: Epoch #1 freed util.c:156:Changed query state from IDLE to DEAD odbc.c:3980:SQLFreeHandle(2, 0x96bfd78) odbc.c:4006:_SQLFreeConnect(0x96bfd78) odbc.c:3980:SQLFreeHandle(1, 0x96bf2f0) odbc.c:4050:_SQLFreeEnv(0x96bf2f0)
luc765 Re : Synthèse vocale SVOX Pico Merci à frafra et tuxmuraille, pour votre travail. J'utilisais espeak avec mbrola, la qualité de SVOX est nettement meilleure J'ai installé gSpeech sur Lucid via la compilation pour SVOX. Tout est parfait. Dans l'utilisation est-il possible de modifier la vitesse de lecture par un paramètre ?? Hors ligne frafa Re : Synthèse vocale SVOX Pico Bonjour, pas prévu dans SVOX,.. pico2wave -? Usage: pico2wave <words> -w, --wave=filename Write output to this WAV file -l, --lang=lang Language (default: "en-US") Help options: -?, --help Show this help message --usage Display brief usage message Hors ligne frafa Re : Synthèse vocale SVOX Pico si tu est courrageux il traine un patch ... http://www.rockbox.org/tracker/11803 pas testé de mon coté Hors ligne luc765 Re : Synthèse vocale SVOX Pico Bonsoir tuxmuraille et Frafa, Je rentre dans le détail mais le dictionnaire phonétique inclus dans gSpeech n'est pas pris en compte chez moi. Y-a-t'il une astuce qui m'échappe ?? luc765 Hors ligne Tuxmouraille Re : Synthèse vocale SVOX Pico Bonjour luc765, Tu peux télécharger ici. Le dictionnaire phonétique doit être mis dans le dossier ~/.config/gSpeech avec le fichier de configuration gspeech.conf. Ce fichier a deux options. Par défaut gSpeech utilise la langue de l'environnement graphique pour la synthèse, et l'AppIndicator (la nouvelle zone de notification de Ubuntu) si elle est installée dans l'environnement graphique. - useappindicator = 1 ne change rien au comportement par défaut, 0 force l'usage de la zone de notification - defaultlanguage = force l'usage d'une langue de synthèse: de-de, fr-FR, etc... Merci pour tes retours. Par d Hors ligne luc765 Re : Synthèse vocale SVOX Pico Merci tuxmuraille et Frafa pour le suivi. Concernant le dictionnaire phonétique complémentaire inclus dans gSpeech je ne suis pas parvenu à activer sa prise en compte. Ceci est probablement lié au fait que je suis un petit belge (sans gouvernement) et donc la langue choisie pour le système Ubunru est fr-BE (echo $LANG donne fr_BE.utf8). fr_BE. n'étant pas pris en compte dans le script gSpeech.py j'ai changé, peut-être un peu brutalement, la ligne 401 du script.py de DefaultLang = "en-US" en DefaultLang = "fr-FR" A part cela tout est nickel. Hors ligne Tuxmouraille Re : Synthèse vocale SVOX Pico Bonsoir, gSpeech ne prend pas en compte fr-BE, car le synthétiseur SVOX Pico ne le supporte pas. Je pense ajouter le support pour d'autre synthétiseur vocaux mais pas pour le moment. Normalement gSpeech doit se caler sur en-US en l’absence de fr-BE, ce que tu doit faire c'est configurer l'option "defaultlanguage = fr-FR" dans le fichier ~/.config/gSpeech/gSpeech.conf et mettre ton dictionnaire dans le même dossier. Hors ligne ssm2017 Re : Synthèse vocale SVOX Pico salut merci pour toutes ces infos. le script fonctionne mais je n'arrive pas à trouver comment changer de la voix feminine vers la masculine. une idee ? Hors ligne cataclop Re : Synthèse vocale SVOX Pico Bonjour, Je commence par remercier pour les explications données dans ce fuseau (qui m'ont été fort utiles) et par m'excuser pour cet abominable "remontage". Je me suis cependant heurté à une limitation de pico2wave (apparemment) : il semble ne pas admettre de texte de plus de 2¹⁵ caractères (soit 32768). C'est beaucoup pour des synthèses ponctuelles, mais outrepasser cette limitation me permettrait d'enregistrer des textes longs pour les écouter sans ordinateur. Au-delà de cette limite, j'obtiens le message suivant : Cannot put Text (-102): invalid argument supplied Merci d'avance à ceux qui pourraient m'indiquer une solution. HP Pavilion dv6-6090ef - Core i7 I7-2630QM 2 GHz - 6 Go RAM Ubuntu Quantal Hors ligne KER747 Re : Synthèse vocale SVOX Pico Bonjour, Je cherche un synthétiseur vocal qui marche bien avec une voix comparable à celle d'accapella: http://www.acapela-group.fr/text-to-spe … -demo.html J'ai essayé gspeaker mais la voix n'est pas terrible. Je pense à essayer pico svox mais l'intallation semble compliqué et ce topic date apparemment. Comment l'installer et est-ce le bon à installer? Ma première page: www.aerozone.tk Hors ligne cataclop Re : Synthèse vocale SVOX Pico Si quelqu'un se heurtait au même problème que moi : j'ai trouvé un contournement en modifiant gSpeech.py. Voici le patch (il faut, pour que cela fonctionne, installer sox) : --- gSpeech2.py 2013-02-26 16:17:57.633682124 +0100 +++ gSpeech.py 2013-02-26 17:13:35.469609167 +0100 @@ -248,14 +248,14 @@ pynotify.Notification(APPNAME, _(u"I'm reading the text. One moment please."), self.icon).show() if widget.get_label() == _(u"From X.org") : - str = gtk.clipboard_get(selection="PRIMARY").wait_for_text() + texte = gtk.clipboard_get(selection="PRIMARY").wait_for_text() else : - str = gtk.clipboard_get(selection="CLIPBOARD").wait_for_text() + texte = gtk.clipboard_get(selection="CLIPBOARD").wait_for_text() #~ str = str.lower() - str = str.replace('\"', '') - str = str.replace('`', '') - str = str.replace('´', '') + texte = texte.replace('\"', '') + texte = texte.replace('`', '') + texte = texte.replace('´', '') dic = CONFIGDIR + '/' + self.lang + '.dic' if os.path.exists(dic) : @@ -266,10 +266,16 @@ good = line.split('=')[1] except : good = ' ' - str = str.replace(bad, good) - - os.system('pico2wave -l %s -w %s \"%s\" ' % ( self.lang, SPEECH, str )) - + texte = texte.replace(bad, good) + discours = texte.split('\n') + i = 0 + fichiers = '' + for texte in discours: + i += 1 + fichier = CACHEFOLDER + 'speech' + str(i) + '.wav' + fichiers = fichiers + ' ' + fichier + os.system('pico2wave -l %s -w %s \"%s\" ' % ( self.lang, fichier, texte )) + os.system('sox %s %s' % ( fichiers, SPEECH )) player = self.onPlayer(SPEECH) self.player.set_state(gst.STATE_PLAYING) Modification : j'avais fait le diff à l'envers… C'est corrigé ! Autre modification : le patch du post #65 est plus efficace, annule et remplace celui-ci. Dernière modification par cataclop (Le 28/02/2013, à 23:34) HP Pavilion dv6-6090ef - Core i7 I7-2630QM 2 GHz - 6 Go RAM Ubuntu Quantal Hors ligne Tuxmouraille Re : Synthèse vocale SVOX Pico Bonjour, Je cherche un synthétiseur vocal qui marche bien avec une voix comparable à celle d'accapella: http://www.acapela-group.fr/text-to-spe … -demo.html J'ai essayé gspeaker mais la voix n'est pas terrible. Je pense à essayer pico svox mais l'intallation semble compliqué et ce topic date apparemment. Comment l'installer et est-ce le bon à installer? A ma connaissance il n'existe pas de synthétiseur vocale libre équivalent aux synthétiseur commerciaux, en particulier acapela. Pico Svox est le synthétiseur de Android, bien qu'il y est le logiciel pico2wave pour réaliser les conversions, c'est avant un bibliothèque partagée à intégrer dans un programme. A part Pico il existe mbrola, encore plus compliqué à installé qui permet d'avoir des voix proches de celles de acapela. Hors ligne Tuxmouraille Re : Synthèse vocale SVOX Pico Bonjour cataclop, 1) Tu as exécuté la commande patch à l'envers. 2) gSpeech n'est pas prévue pour des textes longs, tu devrais développer ton propre programme. 3) La méthode que tu utilise n'est à mon humble avis pas bonne. Il est peu efficace de découpé ton texte ligne par ligne. 4) En revanche merci, parce que c'est complètement idiot d'avoir appelé ma variable str. Hors ligne cataclop Re : Synthèse vocale SVOX Pico Bonjour Tuxmouraille, 1) Corrigé dans ma dernière édition (c'est tout moi, ce genre d'erreur…) 2) Sans doute, mais ceci dépasse largement mes compétences en python ! Disons qu'au moins, comme ça, j'arrive à un résultat. 3) Tout-à-fait d'accord ; l'avantage de découper par ligne est que je suis (à peu près) sûr de ne pas découper une phrase ou un mot bêtement. J'aurais peut-être dû découper phrase par phrase (en utilisant '.' au lieu de '\n'), puis "rattacher" mes phrases jusqu'à obtenir une chaîne proche des 32768 caractères. 4) Je t'en prie : je l'ai d'abord fait pour essayer d'y comprendre quelque chose… HP Pavilion dv6-6090ef - Core i7 I7-2630QM 2 GHz - 6 Go RAM Ubuntu Quantal Hors ligne cataclop Re : Synthèse vocale SVOX Pico Je n'ai pas pu m'empêcher d'expérimenter l'idée 3). De la sorte, je passe d'environ 20 secondes de traitement à environ 15 secondes pour un texte de 36128 caractères. Voici donc le nouveau patch : --- gSpeech.old 2013-02-26 16:17:57.633682124 +0100 +++ gSpeech.py 2013-02-28 11:09:14.737670234 +0100 @@ -248,14 +248,14 @@ pynotify.Notification(APPNAME, _(u"I'm reading the text. One moment please."), self.icon).show() if widget.get_label() == _(u"From X.org") : - str = gtk.clipboard_get(selection="PRIMARY").wait_for_text() + texte = gtk.clipboard_get(selection="PRIMARY").wait_for_text() else : - str = gtk.clipboard_get(selection="CLIPBOARD").wait_for_text() + texte = gtk.clipboard_get(selection="CLIPBOARD").wait_for_text() #~ str = str.lower() - str = str.replace('\"', '') - str = str.replace('`', '') - str = str.replace('´', '') + texte = texte.replace('\"', '') + texte = texte.replace('`', '') + texte = texte.replace('´', '') dic = CONFIGDIR + '/' + self.lang + '.dic' if os.path.exists(dic) : @@ -266,12 +266,25 @@ good = line.split('=')[1] except : good = ' ' - str = str.replace(bad, good) - - os.system('pico2wave -l %s -w %s \"%s\" ' % ( self.lang, SPEECH, str )) - + texte = texte.replace(bad, good) + discours = texte.split('.') + i = 0 + fichiers = [] + texte = '' + while i < len(discours): + if len(texte) < 30000: + texte += discours[i] + '. ' + if len(texte) > 30000 or i == len(discours) - 1: + fichier = CACHEFOLDER + 'speech' + str(i) + '.wav' + fichiers.append(fichier) + os.system('pico2wave -l %s -w %s \"%s\" ' % ( self.lang, fichier, texte )) + texte = '' + i += 1 + os.system('sox %s %s' % ( ' '.join(fichiers), SPEECH )) player = self.onPlayer(SPEECH) self.player.set_state(gst.STATE_PLAYING) + for fichier in fichiers: + os.remove(fichier) # player fonction def onPlayer(self,file): Modification : Petit changement pour nettoyer tous les fichiers temporaires que ma méthode avait rajoutés, et pour restaurer la possibilité de lire des textes courts… Dernière modification par cataclop (Le 01/03/2013, à 12:13) HP Pavilion dv6-6090ef - Core i7 I7-2630QM 2 GHz - 6 Go RAM Ubuntu Quantal Hors ligne cataclop Re : Synthèse vocale SVOX Pico Juste pour donner un ordre d'idée : j'ai fait le test avec un texte de 178573 mots (791222 caractères sans compter les espaces) : − il a fallu (sur ma machine, en n'utilisant qu'un seul processeur puisque je ne sais pas utiliser le multitâche en python) environ 10 minutes de traitement avant que la lecture ne commence ; − 35 wav intermédiaires d'environ 50 Mo chacun ont été produits ; − le wav final pèse environ 1,75 Go pour 15h18 de lecture. Bref, la performance de pico2wave couplé avec gSpeech me semble tout de même honnête ! Un grand merci à frafra et à Tuxmouraille pour tout ce travail ! HP Pavilion dv6-6090ef - Core i7 I7-2630QM 2 GHz - 6 Go RAM Ubuntu Quantal Hors ligne cataclop Re : Synthèse vocale SVOX Pico Une petite question, au cas où : existe-t-il une voix française masculine pour pico2wave ? HP Pavilion dv6-6090ef - Core i7 I7-2630QM 2 GHz - 6 Go RAM Ubuntu Quantal Hors ligne Tuxmouraille Re : Synthèse vocale SVOX Pico Bonjour cataclop, Je ne suis pas non plus développeur. gSpeech est un de mes projets d'apprentissage Python. Il existe beaucoup de documentation sur Python et PyGTK. Si tu as déjà programmé tu te rendras compte que Python est assez simple. Si tu veux apprendre sérieusement il y a le siteduzero et l'excellente "Apprendre à programmer avec Python". A ma connaissance il n'existe pas de voix masculine pour Pico. Regardes du côté de mbrola, je croit que ce projet est à l'origine du synthétiseur vocale de acapela. Je pense que tu peux créer un script bash: 1) tu découpe le texte en textes plus courts 2) dans une boucle 3) tu stokes le contenue de chaque nouveaux fichiers dans une variable 4) tu utilise cette variable pour généré le fichier wave 5) hors de la boucle 6) tu concatènes les wave 7) optionnel: tu convertis en flac, ogg ou mp3 pour gagner de la place. Si tu arrives à faire une découpage par chapitre tu peux aussi conserver un wave par chapitre. A condition que chaque chapitre fasse moins de 2¹⁵ caractères. Quel est le format source de ton texte? Dernière modification par Tuxmouraille (Le 01/03/2013, à 18:37) Hors ligne cataclop Re : Synthèse vocale SVOX Pico Bonsoir Tuxmouraille, Bien sûr que je pourrais faire tout ça, mais… pourquoi réinventer la roue ? Je ne suis pas informaticien, si ce n'est à mes heures perdues. Puisqu'une modification de 20 lignes m'amène au même résultat, je ne vais pas me lancer dans des dizaines de lignes de bash ou de python pour faire en définitive moins bien ! GSpeech s'intègre très bien dans l'interface, et la dernière étape que tu me suggères est facile à intégrer dans le clic droit de Nautilus grâce aux scripts (paquet nautilus-script-audio-convert). Comme ton logiciel est sous Gpl, j'en ai profité pour l'adapter à mon besoin. Conformément à l'esprit du libre et à la lettre de la licence, je mets à disposition mon travail pour les autres ; s'ils en profitent, tant mieux, j'en serai content. Sinon, eh bien ! je n'aurai rien perdu. Merci encore pour ton travail et ta disponibilité. Dernière modification par cataclop (Le 01/03/2013, à 22:11) HP Pavilion dv6-6090ef - Core i7 I7-2630QM 2 GHz - 6 Go RAM Ubuntu Quantal Hors ligne KER747 Re : Synthèse vocale SVOX Pico Ok, Merci Ma première page: www.aerozone.tk Hors ligne ian57 Re : Synthèse vocale SVOX Pico @tuxmouraille : merci pour ton travail, la version 0.4.5 est vraiment super bien. Juste une remarque : il me manque une raccourcis clavier pour la lecture. Je vais jeter un oeil à tes sources pour voir si je peux le faire ;-). encore super merci pour ce programme voila avec SHIFT-l on peut lire le texte selectionné dans l'interface graphique (et SHIFT-m pour le presse papier) ( ne marche que si la fenêtre multimédia est visible et possède le focus : le code modifié est le suivant (http://www.pygtk.org/pygtk2tutorial/sec … ators.html) : à partir de la ligne 325 # Create an accelerator group self.accelgroup = gtk.AccelGroup() # Add the accelerator group to the toplevel window self.window.add_accel_group(self.accelgroup) #~ button = gtk.Button(stock = gtk.STOCK_EXECUTE) #~ Label=button.get_children()[0] #~ Label=Label.get_children()[0].get_children()[1] #~ Label=Label.set_label(_(u"From ClipBoard")) #~ button.connect("clicked", gSpeech.onExecute) button = gtk.Button(_(u"From ClipBoard")) button.connect("clicked", gSpeech.onExecute) button.add_accelerator("clicked",self.accelgroup , ord('m'), gtk.gdk.SHIFT_MASK, gtk.ACCEL_VISIBLE) self.window.vbox.pack_start(button, expand=False, fill=False) #~ button = gtk.Button(stock = gtk.STOCK_EXECUTE) #~ Label=button.get_children()[0] #~ Label=Label.get_children()[0].get_children()[1] #~ Label=Label.set_label(_(u"From X.org")) button = gtk.Button(_(u"From X.org")) button.connect("clicked", gSpeech.onExecute) button.add_accelerator("clicked",self.accelgroup , ord('l'), gtk.gdk.SHIFT_MASK, gtk.ACCEL_VISIBLE) self.window.vbox.pack_start(button, expand=False, fill=False) Faudrait trouver un truc pour que le raccourcis soit directement dirigé vers ton appli, pour éviter de faire le focus : Peut être un début de solution avec https://code.google.com/p/autokey/ Dernière modification par ian57 (Le 14/03/2013, à 18:14) Ouvrir c'est pourrir un pneu... Hors ligne Tuxmouraille Re : Synthèse vocale SVOX Pico Bonsoir, @cataclop, et ceux qui veulent si coller, cf les modifs de cataclop: Si vous arrivez à modifier le code afin qu'il qui ne génère des fichiers wav que pour des portions de textes comprenant des paragraphes complets avec un nombres de caractères le plus proche de 2¹⁵, j'ajouterai le patch. @ian57: je te remercie pour le code. Je voulais le faire mais je n'ai jamais pris le temps de m'y mettre. Pour le problème de focus tu devrais regarder du côté du code de Terra Terminal. N.B.: je n'ai pas beaucoup de temps en ce moment, j’ai une connexion Internet toute pourrie, en HotSpot. Je serai quand même ravis de m'y remettre, dans les limites de mes possibilités. Dernière modification par Tuxmouraille (Le 14/03/2013, à 22:17) Hors ligne temps Re : Synthèse vocale SVOX Pico Bonjour, J'ai créé une base de données des différents sons phonétiques API, chacun des son ne pèse que quelques kilo, pensez-vous qu'il est possible de remplacer votre base de son par la mienne ? En d'autres mots, de remplacer vos fichiers audio de base par les miens dans votre projet ? Cordialement Parce que l'USB bootable est le support des systèmes experts, Parce que l'USB bootable contient sa propre image au démarrage. L'USB bootable permet de créer un monde à la dimension de son imagination Hors ligne ian57 Re : Synthèse vocale SVOX Pico Bonsoir, Pour le problème de focus tu devrais regarder du côté du code de Terra Terminal. Yop effectivement ya un truc pas mal intéressant http://bazaar.launchpad.net/~ozcanesen/ … ad:/terra/ le rep globalhotkeys... je vais regarder comment cela marche pour essayer de l'intégrer. Ouvrir c'est pourrir un pneu... Hors ligne Tuxmouraille Re : Synthèse vocale SVOX Pico Bonjour, J'ai créé une base de données des différents sons phonétiques API, chacun des son ne pèse que quelques kilo, pensez-vous qu'il est possible de remplacer votre base de son par la mienne ? En d'autres mots, de remplacer vos fichiers audio de base par les miens dans votre projet ? Cordialement Bonjour, gSpeech ne génère pas les fichiers de son, il utilise l'application pico2wave pour ça. Je ne pense donc pas qu'il soit possible d'utiliser ta base. Hors ligne
Python does not continue to replace the same line in the terminal, but it replaces "name" and adds the progress bar to a new line which results in a huge stack of progress bars...this only happens when I use "\n" before "name". How can I get the result to look like this? [### ] 4%name2 python mylist = ['name1', 'name2', 'name3',...'name66'] for name in mylist: sys.stdout.write('\r[%-66s] %d%%' % ('#'*prog, (prog*1.51515151515))+'\n'+name) sys.stdout.flush()
I need the best way to inspect HTTP response headers with Selenium. I looked around the Selenium docs and didn't see any straightforward way to do it. Help is highly appreciated. I've answered this question a couple times on StackOverflow. Search my previous answers to dig it up. The key that you have to write some custom Java code that extends ProxyHandler and SeleniumServer. You also need to use a release AFTER 1.0 beta 2. As to the people who ask captureNetworkTraffic() API in DefaultSelenium captures http request/response headers and you can access them in html/xml/plain format. Here is sample code: Selenium s = new DefaultSelenium(...); s.start("captureNetworkTraffic=true"); s.open("http://www.google.com"); String xml = s.captureNetworkTraffic("xml"); // html, plain s.stop(); I would not use Selenium for this type of test and suggest that you solve a variety of testing issues with different tools. what we do is: Its worth spending time breaking out the responsibility of testing different aspects of the system using these different tools since using only Selenium can cause issues: There are also some techniques - which you may or may not have come across - which you can use to make your Selenium tests more resilient. What I did to handle this using Selenium (not Selenium RC) was to convert the HTML tests into JSP and then utilize Java where needed to read headers or do whatever stuff that JavaScript (selenium is just Javascript) couldn't do. Perhaps you could give a few details about how you plan to use Selenium? It seems to me that it can be very useful to test HTTP response headers from selenium. Not in 100% of the cases, perhaps ... but there certainly are some. If you are checking out a sequence of pages, it seems like it would be useful to test some response headers as part of that testing (Content-Type and Pragma leap to mind). I came up with a workaround which uses an embedded proxy, courtesy of the Proxoid project. Its lightweight, unlike practically every other alternative out there (like BrowserMob or even LittleProxy) See the HOWTO, with code, here: http://www.supermind.org/blog/968/howto-collect-webdriver-http-request-and-response-headers Well, i was hoping to find out whether Accept-Encoding property from HTTP head contains "gzip", because in our company, we compress CSS and JS files in our web application by gzip and we want to test it by Selenim after each commit. Read the session cookies from Selenium and then use a real HTTP library outside of Selenium to request the specific page. Here is the Python code: # get session cookies from Selenium cookies = {} for s_cookie in self.selenium.get_cookies(): cookies[s_cookie["name"]]=s_cookie["value"] # request the pdf using the cookies: response = requests.get(self.full_url('/vms/business_unit/2002/operational_unit/200202/guest/40/bill/pdf/'), cookies = cookies) self.assertEqual(response.headers["content-type"], "application/pdf")
1. Issues Your code fails in the following corner cases: a and b on the same day, for example: >>> a = datetime(2012, 11, 22, 8) >>> a.weekday() 3 # Thursday >>> seconds_between(a, a + timedelta(seconds = 100)) 54100.0 # Expected 100 a or b at the weekend, for example: >>> a = datetime(2012, 11, 17, 8) >>> a.weekday() 5 # Saturday >>> seconds_between(a, a + timedelta(seconds = 100)) 21700.0 # Expected 0 a after STOP_HOUR or b before START_HOUR, for example: >>> a = datetime(2012, 11, 19, 23) >>> a.weekday() 0 # Monday >>> seconds_between(a, a + timedelta(hours = 2)) 28800.0 # Expected 0 Also, you count the weekdays by looping over all the days between the start and end of the interval. That means that the computation time is proportional to the size of the interval: >>> from timeit import timeit >>> a = datetime(1, 1, 1) >>> timeit(lambda:seconds_between(a, a + timedelta(days=999999)), number=1) 1.7254137992858887 For comparison, in this extreme case the revised code below is about 100,000 times faster: >>> timeit(lambda:office_time_between(a, a + timedelta(days=999999)), number=100000) 1.6366889476776123 The break even point is about 4 days: >>> timeit(lambda:seconds_between(a, a + timedelta(days=4)), number=100000) 1.5806620121002197 >>> timeit(lambda:office_time_between(a, a + timedelta(days=4)), number=100000) 1.5950188636779785 2. Improvements barracel's answer has two very good ideas, which I adopted: compute the sum in seconds rather than days; add up whole days and subtract part days if necessary. and I made the following additional improvements: handle corner cases correctly; run in constant time regardless of how far apart a and b are; compute the sum as a timedelta object rather than an integer; move common code out into functions for clarity; docstrings! 3. Revised code from datetime import datetime, timedelta def clamp(t, start, end): "Return `t` clamped to the range [`start`, `end`]." return max(start, min(end, t)) def day_part(t): "Return timedelta between midnight and `t`." return t - t.replace(hour = 0, minute = 0, second = 0) def office_time_between(a, b, start = timedelta(hours = 8), stop = timedelta(hours = 17)): """ Return the total office time between `a` and `b` as a timedelta object. Office time consists of weekdays from `start` to `stop` (default: 08:00 to 17:00). """ zero = timedelta(0) assert(zero <= start <= stop <= timedelta(1)) office_day = stop - start days = (b - a).days + 1 weeks = days // 7 extra = (max(0, 5 - a.weekday()) + min(5, 1 + b.weekday())) % 5 weekdays = weeks * 5 + extra total = office_day * weekdays if a.weekday() < 5: total -= clamp(day_part(a) - start, zero, office_day) if b.weekday() < 5: total -= clamp(stop - day_part(b), zero, office_day) return total
How do I create a GUID in Python that is platform independent? I hear there is a method using ActivePython on Windows but it's Windows only because it uses COM. Is there a method using plain Python? "The uuid module, in Python 2.5 and up, provides RFC compliant UUID generation. See the module docs and the RFC for details." If you're using Python 2.5 or later, the Ex: >>> import uuid >>> uuid.uuid1() UUID('5a35a426-f7ce-11dd-abd2-0017f227cfc7') I use GUIDs as random keys for database type operations. The hexadecimal form, with the dashes and extra characters seem unnecessarily long to me. But I also like that strings representing hexadecimal numbers are very safe in that they do not contain characters that can cause problems in some situations such as '+','=', etc.. Instead of hexadecimal, I use a url-safe base64 string. The following does not conform to any UUID/GUID spec though (other than having the required amount of randomness). import base64 import uuid # get a UUID - URL safe, Base64 def get_a_uuid(): r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes) return r_uuid.replace('=', '')
toma222 [HOW TO] adesklets : installation sous Ubuntu Dapper et Edgy Il existe désormais un article sur le wiki concernant Adesklets donc je vous conseille de vous y fier, ce tutoriel n'étant plus mis à jour. Je poste ce sujet en complément du sujet sur l'installation de adesklets sous Breezy. Je ne reviendrais pas sur les qualités de ce logiciel. Installation Par les dépôts : Sous Dapper, vous pouvez utiliser la version (0.5.0) disponible dans les dépôts. sudo apt-get install adesklets Pour utiliser certains desklets (System Monitor en particulier), il vous faudra également les paquets suivant : sudo apt-get install libstatgrab6 python-statgrab Compilation manuelle : Il vous faudra les paquets suivants : sudo apt-get install python-dev libncurses5-dev libreadline5-dev libimlib2 libimlib2-dev xlibs-dev build-essential libstatgrab6 python-statgrab Les paquets en -dev et le paquet build-essential ne servent qu'à la compilation, vous pourrez les désinstaller après si vous souhaitez économiser de la place. Si vous souhaitez avoir la dernière version (0.6.1), téléchargez-la ici. Décompressez l'archive dans votre home par exemple. Dans un terminal, vous vous placer dans le répertoire créé cd /home/votre_nom/adesklets-0.6.1 par exemple. Ensuite, ./configure make sudo make install Une fois tous vos desklets enregistrés (se reporter au post concernant la configuration des desklets), il suffit de taper : adesklets --nautilus Pour qu'il se lance au démarrage, dans le menu Système/Préférences/Sessions, onglet «programmes au démarrage» il faut ajouter adesklets --nautilus. Vu que pour moi il ne se lançait toujours pas, j'ai mis adesklets --nautilus -d X (ou X est un délais en secondes, 2s semblant juste, mettre 10 ou 15). Note : si vous utilisez les pilotes béta Nvidia avec Beryl, les desklets apparaîtront sur fond noir. Ils'agit d'un bug connu qui n'a pas de solution pour le moment. Merci à Syfou pour ses conseils. Dernière modification par toma222 (Le 01/08/2007, à 18:59) Hors ligne toma222 Re : [HOW TO] adesklets : installation sous Ubuntu Dapper et Edgy Nouvelle version 0.6.1 qui apporte des corrections mineures. Hors ligne skateinmars Re : [HOW TO] adesklets : installation sous Ubuntu Dapper et Edgy Merci, j'avais pas vu que libstatgrab etait integre a la distrib Hors ligne JamesXB Re : [HOW TO] adesklets : installation sous Ubuntu Dapper et Edgy Bonjour, j'ai cette erreur en compilant: james@james:~$ cd /home/james/Desktop/adesklets-0.6.1 james@james:~/Desktop/adesklets-0.6.1$ ./configure make sudo make install configure: WARNING: you should use --build, --host, --target configure: WARNING: you should use --build, --host, --target configure: WARNING: you should use --build, --host, --target configure: WARNING: you should use --build, --host, --target checking for a BSD-compatible install... /usr/bin/install -c checking whether build environment is sane... yes checking for gawk... no checking for mawk... mawk checking whether make sets $(MAKE)... yes checking whether to enable maintainer-specific portions of Makefiles... no checking for style of include used by make... GNU checking for make-gcc... no checking for gcc... no checking for make-cc... no checking for cc... no checking for cc... no checking for make-cl... no checking for cl... no configure: error: no acceptable C compiler found in $PATH See `config.log' for more details. james@james:~/Desktop/adesklets-0.6.1$ merci de votre aide. Hors ligne Stemp Re : [HOW TO] adesklets : installation sous Ubuntu Dapper et Edgy ./configure make sudo make install ??? C'est ./configure puis make puis sudo make install Mais avant tout, tu n'as pas de compilateur. Installe donc le paquet build-essential. Hors ligne JamesXB Re : [HOW TO] adesklets : installation sous Ubuntu Dapper et Edgy Merci stemp j'ai encore une petite erreur a resoudre ici: http://pastebin.com/733434 ces surement pas grand chose Sympa de votre aide. Dernière modification par JamesXB (Le 27/06/2006, à 19:47) Hors ligne toma222 Re : [HOW TO] adesklets : installation sous Ubuntu Dapper et Edgy J'ai modifier un peu le tuto afin de ne pas installer toutes les dépendances si on utilise la version des dépôts. Hors ligne tiεuM Re : [HOW TO] adesklets : installation sous Ubuntu Dapper et Edgy J'espère que c'est bien ici qu'il faut poster pour ses problèmes...parce que j'en ai malgré le tuto (que j'ai suivi à la trace). je vous envoie ce que j'obtiens. Au début j'avais pas mal de no et j'ai installé tous les packages qu'i demandait...enfin j'espère En tout cas s'il y avait une bonne volonté pour m'aider ça m'arrangerait grandement. ~/adesklets-0.6.1$ ./configure checking for a BSD-compatible install... /usr/bin/install -c checking whether build environment is sane... yes checking for gawk... gawk checking whether make sets $(MAKE)... yes checking whether to enable maintainer-specific portions of Makefiles... no checking for style of include used by make... GNU checking for gcc... gcc checking for C compiler default output file name... a.out checking whether the C compiler works... yes checking whether we are cross compiling... no checking for suffix of executables... checking for suffix of object files... o checking whether we are using the GNU C compiler... yes checking whether gcc accepts -g... yes checking for gcc option to accept ANSI C... none needed checking dependency style of gcc... gcc3 checking how to run the C preprocessor... gcc -E checking for gcc... (cached) gcc checking whether we are using the GNU C compiler... (cached) yes checking whether gcc accepts -g... (cached) yes checking for gcc option to accept ANSI C... (cached) none needed checking dependency style of gcc... (cached) gcc3 checking for flex... flex checking for yywrap in -lfl... yes checking lex output file root... lex.yy checking whether yytext is a pointer... yes checking for bison... bison -y checking for a BSD-compatible install... /usr/bin/install -c checking for a Python interpreter with version >= 2.3... python checking for python... /usr/bin/python checking for python version... 2.4 checking for python platform... linux2 checking for python script directory... ${prefix}/lib/python2.4/site-packages checking for python extension module directory... ${exec_prefix}/lib/python2.4/site-packages checking for Python include path... /usr/include/python2.4 checking for Python library path... /usr/lib/python2.4/config checking python extra libraries... checking for sigprocmask... yes checking for perl... /usr/bin/perl checking for perl version greater than or equal to 5.8.2... ok checking for perl module IPC::Open3... ok checking for help2man... /usr/bin/help2man checking for tidy... /usr/bin/tidy checking for doxygen... /usr/bin/doxygen checking for ISO C99 warnings generation... yes checking for egrep... grep -E checking for ANSI C header files... yes checking for sys/types.h... yes checking for sys/stat.h... yes checking for stdlib.h... yes checking for string.h... yes checking for memory.h... yes checking for strings.h... yes checking for inttypes.h... yes checking for stdint.h... yes checking for unistd.h... yes checking stdio.h usability... yes checking stdio.h presence... yes checking for stdio.h... yes checking stdarg.h usability... yes checking stdarg.h presence... yes checking for stdarg.h... yes checking errno.h usability... yes checking errno.h presence... yes checking for errno.h... yes checking fcntl.h usability... yes checking fcntl.h presence... yes checking for fcntl.h... yes checking signal.h usability... yes checking signal.h presence... yes checking for signal.h... yes checking time.h usability... yes checking time.h presence... yes checking for time.h... yes checking math.h usability... yes checking math.h presence... yes checking for math.h... yes checking sys/time.h usability... yes checking sys/time.h presence... yes checking for sys/time.h... yes checking for sys/types.h... (cached) yes checking for sys/stat.h... (cached) yes checking grp.h usability... yes checking grp.h presence... yes checking for grp.h... yes checking pwd.h usability... yes checking pwd.h presence... yes checking for pwd.h... yes checking libgen.h usability... yes checking libgen.h presence... yes checking for libgen.h... yes checking dirent.h usability... yes checking dirent.h presence... yes checking for dirent.h... yes checking iconv.h usability... yes checking iconv.h presence... yes checking for iconv.h... yes checking for debugging symbols generation... no checking for sigkill timeout... yes checking for polling frequency... checking for bc... yes checking for lock files directory setting... yes checking for control modifier on context menu... no checking for legacy fake root window detection code... no checking for frontend shell driver... yes checking for date... (cached) yes checking for uname... (cached) yes checking for tputs in -lncurses... yes checking for readline in -lreadline... yes checking for add_history in -lhistory... yes checking for free_history_entry in -lhistory... yes checking for history max command lenght... yes checking for pkg-config... /usr/bin/pkg-config checking for fontconfig... no configure: WARNING: ----------------------------------------------------- `fontconfig' was not found on your system. Although `adesklets' will work anyway system-wide automatic font detection will not occur: it is therefore quite possible that only the default font provided with the package will display. ----------------------------------------------------- checking for fork... yes checking for X... libraries /usr/X11R6/lib, headers checking for XOpenDisplay in -lX11... yes checking for imlib2-config... /usr/bin/imlib2-config checking for imlib2 - version >= 1.1.2... yes checking for imlib2... checking for imlib2 - version >= 1.2.0... yes checking for imlib2 program linking with ad-hoc flags... yes checking for uint typedef in standard library... yes configure: creating ./config.status config.status: creating Makefile config.status: creating src/Makefile config.status: creating data/Makefile config.status: creating utils/Makefile config.status: creating doc/Makefile config.status: creating doc/adesklets_checkin.1 config.status: creating doc/adesklets_submit.1 config.status: creating doc/htmldoc.sh config.status: creating doc/imlib2/Makefile config.status: creating scripting/Makefile config.status: creating scripting/protoize.sh config.status: creating scripting/python/Makefile config.status: creating scripting/python/config.h config.status: creating scripting/python/setup.py config.status: creating scripting/perl/Makefile config.status: creating scripting/perl/Makefile.PL config.status: creating scripting/perl/updateproto.pl config.status: creating utils/adesklets_frontend.sh config.status: creating src/config.h config.status: executing depfiles commands Mieux vaut être belle et rebelle que moche et re-moche Hors ligne toma222 Re : [HOW TO] adesklets : installation sous Ubuntu Dapper et Edgy Bonjour, Je ne vois pas de soucis dans le log que tu nous as mis. Tu as fait le make ensuite ? Hors ligne tiεuM Re : [HOW TO] adesklets : installation sous Ubuntu Dapper et Edgy oups j'ai oublié de préciser...c'est l'histoire du fontconfig qui me tracassait... parce que quand je regarde dans synaptic il est bien installé (d'ailleurs je l'ai réinstallé pour la peine) Dernière modification par tiεuM (Le 06/07/2006, à 19:16) Mieux vaut être belle et rebelle que moche et re-moche Hors ligne toma222 Re : [HOW TO] adesklets : installation sous Ubuntu Dapper et Edgy Pas de soucis, il s'agit uniquement d'un warning. Au pire tu auras à changer les polices VeraBd en Vera pour tes desklets. Hors ligne Kdenc Re : [HOW TO] adesklets : installation sous Ubuntu Dapper et Edgy Bonjour, j'ai installer simplement adesklets via synaptic, et quand je tape la commande adesklets --nautilus rien ne se passe. Pourriez vous m'éclairer ? Merci d'avance toma222 Re : [HOW TO] adesklets : installation sous Ubuntu Dapper et Edgy Bonjour, Question bête, tu as installé des desklets ? Dans le cas contraire vas voir le poste concernant la configuration des desklets (tu trouveras le lien dans le tuto de la première page). Hors ligne kryss Re : [HOW TO] adesklets : installation sous Ubuntu Dapper et Edgy bon j ai essayé gdesklets, j arrivais pas a mettre un affichages des flux rss sur le bureau (erreur : pas de capteur rss grab, je sais pas ce que ca veut dire et j ai pas compris comment resoudre le probleme). j ai donc decidé de passer a adesklets, je suis ce que vous avez mis en haut pas a pas, c est cool tout marche sauf que j arrive pas a le lancer. comme le monsieur d en haut, Kdenc. j ai installé des desklets avec desklets installer mais comme j arrive pas a lancer adesklets... bref, je sais pas si quelqu un peut m aider, tout ce que je voulais c etait eviter de passer par liferea ou blam feed reader pour gerer mes flux rss, juste les avoir deja affiché sur le bureau. inutile de preciser que je suis au bord du gouffre merci a tous! Hors ligne toma222 Re : [HOW TO] adesklets : installation sous Ubuntu Dapper et Edgy Salut, En fait le truc c'est que quand tu lances adesklets, tu n'as rien (à part les desklets). Je veux dire qu'il n'y a pas d'interface comme sous gdesklets. J'imagine que tu as installé newsfeed. Je ne l'ai jamais utilisé alors on va y aller étape par étape. J'ai regardé le readme, déjà il te faut feedparser (python-feedparser dans Synaptic). Ensuite il te faudra le configurer en éditant le fichier config.txt : gedit ~/.desklets/newsfeed-0.0.4/config.txt Hors ligne kryss Re : [HOW TO] adesklets : installation sous Ubuntu Dapper et Edgy j ai pas de fichier config.txt mais un newsfeed.py et le contenu de ce fichier est le suivant : #! /usr/bin/env python """ -------------------------------------------------------------------------------- Copyright (C) 2005 Alessio Carenini <[email protected]> for the code Released under the GPL, version 2. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies of the Software and its documentation and acknowledgment shall be given in the documentation and software packages that this Software was used. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- RSS/ATOM news feed desklets Tested on adesklet-0.4.0 with python-2.3.4 Required feedparser.py from www.feedparser.org Just run this script from its final location on you disk to start the desklet. -------------------------------------------------------------------------------- """ #------------------------------------------------------------------------------- import adesklets from os import getenv, system from os.path import join, dirname import feedparser import textwrap #------------------------------------------------------------------------------- class Config(adesklets.ConfigFile): """ This is newsfeed.py desklet configuration file; for each desklet, you only have to write down the minimal delay between updates (in seconds: less than 300 will be ignored), the URL of the feed and the size of the desklet Details: sizeX,sizeY: width and height head_font, head_font_height: font for news title item_font, item_font_height: font for news details url: rss/atom newsfeed url line_spacing: pixels between two lines borderX, borderY: area reserved to borders interactive: if True, enables highlighting of news details and calling selected browser browser: browser to call for viewing selected news """ cfg_default = { 'sizeX':400, 'sizeY':600, 'delay':600, 'url':'http://slashdot.org/index.rss', 'head_font':'VeraBd', 'head_font_height':8, 'head_font_color':'ffff00', 'item_font':'Vera', 'item_font_height':8, 'item_font_color':'02c601', 'selected_font_color':'ffffff', 'title_font':'VeraBd', 'title_font_height':12, 'title_font_color':'ffe600', 'line_spacing':5, 'interactive':False, 'browser':'firefox', 'managed':True, 'borderX':7, 'borderY':7 } def __init__(self,id,filename): adesklets.ConfigFile.__init__(self,id,filename) def color(self,string): colors = [eval('0x%s' % string[i*2:i*2+2]) for i in range(len(string)/2)] if (len(colors) != 4): colors += [255] return colors #------------------------------------------------------------------------------- class Events(adesklets.Events_handler): def __init__(self, basedir): if len(basedir)==0: self.basedir='.' else: self.basedir=basedir self.w = None self.buffer= None self.id= None self.delay=None self.item_pos=None self.selected_item=None self.feed=None self.modified=None self.error_flag=0 adesklets.Events_handler.__init__(self) def __del__(self): adesklets.Events_handler.__del__(self) def ready(self): # Real initialisation take place here self.config=Config(adesklets.get_id(), join(self.basedir,'config.txt')) if self.config['delay']<300: self.config['delay']=300 self.x=self.config['sizeX'] self.y=self.config['sizeY'] self.url=self.config['url'] # Font config self.h_font=self.config['head_font'] self.h_font_height=self.config['head_font_height'] self.h_font_color=self.config.color(self.config['head_font_color']) self.i_font=self.config['item_font'] self.i_font_height=self.config['item_font_height'] self.i_font_color=self.config.color(self.config['item_font_color']) self.sel_font_color=self.config.color(self.config['selected_font_color']) self.t_font=self.config['title_font'] self.t_font_height=self.config['title_font_height'] self.t_font_color=self.config.color(self.config['title_font_color']) self.line_spacing=self.config['line_spacing'] self.interactive=self.config['interactive'] self.borderX=self.config['borderX'] self.borderY=self.config['borderY'] self.browser=self.config['browser'] adesklets.add_path_to_font_path(join(self.basedir)) self.buffer=adesklets.create_image(self.x,self.y) # Set the window property adesklets.window_resize(self.x,self.y) adesklets.window_set_transparency(True) if (self.config['managed']): adesklets.window_reset(adesklets.WINDOW_MANAGED) adesklets.menu_add_separator() adesklets.menu_add_item('Configure') adesklets.menu_add_item('Update feed') adesklets.window_show() def alarm(self): self.block() self.feed=self.update_feed() self._display() self.unblock() # One second adjustment to make sure everything will be fine return self.config['delay']+1 def menu_fire(self, delayed, menu_id, item): if item=='Configure': editor=getenv('EDITOR') if editor: system('xterm -e %s %s/config.txt &' % (editor, self.basedir)) if item=='Update feed': self.block() self.feed=self.update_feed() self._display() self.unblock() def _display(self): self.set_buffer_image() if self.feed.bozo==1: self.error_flag=1 self.draw_error_info() else: self.error_flag=0 self.draw_info() self.copy_to_desklet() def set_buffer_image(self): # Reset the whole buffer image in transparent black adesklets.context_set_image(self.buffer) adesklets.context_set_color(0,0,0,0) adesklets.context_set_blend(False) adesklets.image_fill_rectangle(0,0,self.x,self.y) adesklets.context_set_blend(True) self.draw_borders() #--------------- Item selection and viewing --------------- def fire_browser(self,item): system(self.browser+' '+self.feed['items'][self.selected_item].link) def button_release(self, delayed, x, y, button): if (button==1)&(self.interactive): self.select_item(x,y) self.fire_browser(self.selected_item) def select_item(self,x,y): prev_selected=self.selected_item for i in range(len(self.item_pos)): if (self.item_pos[i]!=[]): y_start=self.item_pos[i][0] y_end=self.item_pos[i][1] if (y>y_start)&(y<y_end): self.selected_item=i if (prev_selected!=self.selected_item): if (prev_selected>-1): self.redraw_news_content(prev_selected,0) self.redraw_news_content(self.selected_item,1) def motion_notify(self, delayed, x, y): if (self.error_flag==0): if (not delayed)&(self.interactive): self.select_item(x,y) def leave_notify(self, delayed, x, y): if (self.error_flag==0): self.selected_item=-1 self._display() #------------- Drawing functions ------------- def draw_info(self): self.item_pos=[] total_feeds=len(self.feed['items'])-1 if total_feeds>20: total_feeds=20 self.item_pos=[[] for i in range (total_feeds)] self.y_current=self.draw_title() for item in range(total_feeds): if (self.draw_news_header(item)==0): if (item==self.selected_item): ret=self.draw_news_content(item,1) else: ret=self.draw_news_content(item,0) if (ret==1): return else: return def copy_to_desklet(self): # Copy everything from the buffer image to the real foreground image adesklets.context_set_image(0) adesklets.context_set_blend(False) adesklets.blend_image_onto_image(self.buffer,1,0,0,self.x,self.y,0,0,self.x,self.y) adesklets.context_set_blend(True) # Free all fonts used adesklets.fonts_reset_all() def draw_error_info(self): adesklets.context_set_font(adesklets.load_font(self.t_font+'/'+str(self.t_font_height))) adesklets.context_set_color(*self.h_font_color) adesklets.text_draw(45,15,'News: Error fetching news!') icon=adesklets.load_image(join(self.basedir,'img/news.png')) adesklets.blend_image_onto_image(icon,1,0,0,68,60,11,10,30,30) adesklets.free_image(icon) adesklets.context_set_font(adesklets.load_font('VeraBd/8')) adesklets.context_set_color(*self.t_font_color) adesklets.text_draw(12,40,'Error: '+str(self.feed.bozo_exception)) def draw_news_header(self,item): adesklets.context_set_font(adesklets.load_font(self.h_font+'/'+str(self.h_font_height))) feed_title=str(self.feed['items'][item]['title']) text_x=12 text_y=self.line_spacing+self.y_current adesklets.context_set_color(*self.h_font_color) if ((text_y+self.line_spacing+self.h_font_height)<self.y): adesklets.text_draw(text_x,text_y,feed_title) return 0 else: return 1 def redraw_news_content(self,item,selected): if (selected==0): image=adesklets.load_image(join(self.basedir,'img/dark.png')) header_space=self.line_spacing+self.h_font_height xstart=self.borderX ystart=self.item_pos[item][0]+1.5*header_space width=self.x-2*self.borderX height=self.item_pos[item][1]-self.item_pos[item][0]-header_space adesklets.blend_image_onto_image(image,0,0,0,80,80,xstart,ystart,width,height) adesklets.free_image(image) adesklets.context_set_color(*self.i_font_color) else: adesklets.context_set_color(*self.sel_font_color) current=0 header_space=self.line_spacing+self.h_font_height adesklets.context_set_font(adesklets.load_font(self.i_font+'/'+str(self.i_font_height))) feed_content=str(self.feed['items'][item]['description']) feed_lines= self.string_to_paragraph(feed_content) for i in range(len(feed_lines)): text_x=15 text_y=header_space+self.item_pos[item][0]+self.line_spacing+(self.line_spacing+self.i_font_height)*current if ((text_y+self.line_spacing+self.i_font_height)<self.y): adesklets.text_draw(text_x,text_y,feed_lines[i]) current+=1 else: return 1 def draw_news_content(self,item,selected): last=0 if (selected==0): adesklets.context_set_color(*self.i_font_color) else: adesklets.context_set_color(*self.selected_font_color) current=0 header_space=self.line_spacing+self.h_font_height adesklets.context_set_font(adesklets.load_font(self.i_font+'/'+str(self.i_font_height))) feed_content=str(self.feed['items'][item]['description']) feed_lines= self.string_to_paragraph(feed_content) for i in range(len(feed_lines)): text_x=15 text_y=header_space+self.y_current+self.line_spacing+(self.line_spacing+self.i_font_height)*current if ((text_y+self.line_spacing+self.i_font_height)<self.y): adesklets.text_draw(text_x,text_y,feed_lines[i]) current+=1 else: self.item_pos[item].append(self.y_current) self.item_pos[item].append(self.y-self.borderY) return 1 y_start,self.y_current=self.calculate_bounds(self.y_current,feed_lines) self.item_pos[item].append(y_start) self.item_pos[item].append(self.y_current) return 0 def draw_title(self): adesklets.context_set_font(adesklets.load_font(self.t_font+'/'+str(self.t_font_height))) adesklets.context_set_color(*self.t_font_color) adesklets.text_draw(45,15,'News: '+str(self.feed['feed']['title'])) icon=adesklets.load_image(join(self.basedir,'img/news.png')) adesklets.blend_image_onto_image(icon,1,0,0,68,60,11,10,30,30) adesklets.free_image(icon) return 45 def draw_borders(self): image=adesklets.load_image(join(self.basedir,'img/dark.png')) adesklets.blend_image_onto_image(image,1,0,0,80,80,0,0,self.x,self.y) adesklets.free_image(image) image=adesklets.load_image(join(self.basedir,'img/e-light.png')) adesklets.blend_image_onto_image(image,1,0,0,15,10, self.x-self.borderX,self.borderY, self.borderX,self.y-(2*self.borderY)) adesklets.free_image(image) image=adesklets.load_image(join(self.basedir,'img/w-light.png')) adesklets.blend_image_onto_image(image,1,0,0,15,10, 0,self.borderY, self.borderX,self.y-(2*self.borderY)) adesklets.free_image(image) image=adesklets.load_image(join(self.basedir,'img/n-light.png')) adesklets.blend_image_onto_image(image,1,0,0,10,9, self.borderX,0, self.x-(2*self.borderX),self.borderY) adesklets.free_image(image) image=adesklets.load_image(join(self.basedir,'img/ne-light.png')) adesklets.blend_image_onto_image(image,1,0,0,15,9, self.x-self.borderX,0, self.borderX,self.borderY) adesklets.free_image(image) image=adesklets.load_image(join(self.basedir,'img/nw-light.png')) adesklets.blend_image_onto_image(image,1,0,0,15,9, 0,0, self.borderX,self.borderY) adesklets.free_image(image) image=adesklets.load_image(join(self.basedir,'img/sw-light.png')) adesklets.blend_image_onto_image(image,1,0,0,15,9, 0,self.y-self.borderY, self.borderX,self.borderY) adesklets.free_image(image) image=adesklets.load_image(join(self.basedir,'img/s-light.png')) adesklets.blend_image_onto_image(image,1,0,0,10,9, self.borderX,self.y-self.borderY, self.x-(2*self.borderX),self.borderY) adesklets.free_image(image) image=adesklets.load_image(join(self.basedir,'img/se-light.png')) adesklets.blend_image_onto_image(image,1,0,0,15,9, self.x-self.borderX,self.y-self.borderY, self.borderX,self.borderY) adesklets.free_image(image) #-------------- Utility methods ----------------- def string_to_paragraph(self,string): string_size=adesklets.get_text_size(string) char_per_line=(self.x-2*self.borderX)/adesklets.get_text_size('x')[0] lines=len(string)/char_per_line limit=char_per_line result=[] result=textwrap.wrap(string,char_per_line) return result def calculate_bounds(self,y_start,paragraph): item_space=len(paragraph)*(self.line_spacing+self.i_font_height) header_space=self.line_spacing+self.h_font_height return y_start,y_start+item_space+header_space def update_feed(self): # Parse url if (self.modified==None): return feedparser.parse(self.url) else: temp_feed=feedparser.parse(self.url,modified=self.feed.modified) if (temp_feed.status=='304'): return self.feed else: return temp_feed #------------------------------------------------------------------------------- if hasattr(adesklets,'version_check'): Events(dirname(__file__)).pause() else: raise RuntimeError, 'You need adesklets >= 0.4.0. See README.' je sais pas si ca t aide... Hors ligne toma222 Re : [HOW TO] adesklets : installation sous Ubuntu Dapper et Edgy Heu non, pas vraiment (pense à mettre des balises Code pour limiter la taille). Le fichier config.txt va apparaître lorsque tu auras lancé le desklet pour la première fois. Donc dans ton terminal : cd ~/.desklets/newsfeed-0.0.4/config.txt ./newsfeed.py Ensuite tu fais t pour test et tu auras sans doute une belle erreur. Mais ton fichier config.txt sera créé. Hors ligne kryss Re : [HOW TO] adesklets : installation sous Ubuntu Dapper et Edgy fallait enlever le config.txt a la fin je suppose donc voila ce que ca me donne dans le terminal : Do you want to (r)egister this desklet or to (t)est it? t Now testing... ============================================================ If you do not see anything (or just an initial flicker in the top left corner of your screen), try `--help', and see the FAQ: `info adesklets'. ============================================================ Traceback (most recent call last): File "./newsfeed.py", line 419, in ? Events(dirname(__file__)).pause() File "./newsfeed.py", line 109, in __init__ adesklets.Events_handler.__init__(self) File "/usr/lib/python2.4/site-packages/adesklets/events_handler.py", line 158, in __init__ self._alarm() File "/usr/lib/python2.4/site-packages/adesklets/events_handler.py", line 296, in _alarm timeout=self.alarm() File "./newsfeed.py", line 157, in alarm self._display() File "./newsfeed.py", line 180, in _display self.draw_info() File "./newsfeed.py", line 238, in draw_info ret=self.draw_news_content(item,0) File "./newsfeed.py", line 313, in draw_news_content feed_lines= self.string_to_paragraph(feed_content) File "./newsfeed.py", line 394, in string_to_paragraph char_per_line=(self.x-2*self.borderX)/adesklets.get_text_size('x')[0] File "/usr/lib/python2.4/site-packages/adesklets/commands.py", line 516, in ge t_text_size return comm.out() File "/usr/lib/python2.4/site-packages/adesklets/commands_handler.py", line 10 3, in out raise ADESKLETSError(4,message) adesklets.error_handler.ADESKLETSError: adesklets command error - syntax error a coté, une fenetre bleue s est creee puis s est refermée Hors ligne kryss Re : [HOW TO] adesklets : installation sous Ubuntu Dapper et Edgy et sinon mon fichier config a bien ete crée. le voici : # -*- coding: ASCII -*- # #This is newsfeed.py desklet configuration file; for each desklet, #you only have to write down the minimal delay between updates #(in seconds: less than 300 will be ignored), the URL of the feed #and the size of the desklet #Details: # sizeX,sizeY: width and height # head_font, head_font_height: font for news title # item_font, item_font_height: font for news details # url: rss/atom newsfeed url # line_spacing: pixels between two lines # borderX, borderY: area reserved to borders # interactive: if True, enables highlighting of news details and calling # selected browser # browser: browser to call for viewing selected news # id0 = {'borderX': 7, 'borderY': 7, 'browser': 'firefox', 'delay': 600, 'head_font': 'VeraBd', 'head_font_color': 'ffff00', 'head_font_height': 8, 'interactive': False, 'item_font': 'Vera', 'item_font_color': '02c601', 'item_font_height': 8, 'line_spacing': 5, 'managed': True, 'selected_font_color': 'ffffff', 'sizeX': 400, 'sizeY': 600, 'title_font': 'VeraBd', 'title_font_color': 'ffe600', 'title_font_height': 12, 'url': 'http://slashdot.org/index.rss'} il me semble que je t ai pas remercié de te pencher sur mon cas... merci! Hors ligne toma222 Re : [HOW TO] adesklets : installation sous Ubuntu Dapper et Edgy De rien . Par contre j'ai une mauvaise nouvelle, je n'arrive pas à faire fonctionner ce desklet. J'ai la même erreur que toi et je n'arrive pas à la corriger. En se reportant à ce post, il semblerait que nous ne soyons pas les seuls. Tu peux essayer les solutions proposées (changer les VeraBd en Vera dans le config.txt), mais chez moi ça n'a rien changé. Hors ligne shiønn Re : [HOW TO] adesklets : installation sous Ubuntu Dapper et Edgy petite question: il fonctionne sous XGL ? personnelement il ne se lance pas How many people can read hex, if only me dead people can read hex ? Hors ligne toma222 Re : [HOW TO] adesklets : installation sous Ubuntu Dapper et Edgy Salut, Oui il n'y a pas de problème avec Xgl. Ton problème vient sans doute d'ailleurs. Hors ligne kryss Re : [HOW TO] adesklets : installation sous Ubuntu Dapper et Edgy heu... qu est ce que c est xgl? j ai remplacé la police VeraB par Vera et ca marche toujours pas... je vois pas du tout ce qui peut marcher la. tout ce que je voulais c etait avoir mes flux rss sur le bureau, moi Hors ligne toma222 Re : [HOW TO] adesklets : installation sous Ubuntu Dapper et Edgy Xgl c'est ce qui permet d'avoir ce genre de choses. Désolé de pas pouvoir t'aider pour ton problème, je ne vois pas de solution. Tu pourrais demander de l'aide à Syfou (le développeur de adesklets) mais malheureusement ce n'est pas lui qui a écrit ce desklet et il a l'air également impuissant sur ce problème. Donc j'imagine qu'il va falloir que tu trouves d'autres solutions. Hors ligne
toto2849 Connexion VPN automatique (NetworkManager) Bonjour,:D -Actuellement en stage il met demandé de mettre en place une connexion VPN qui se lance automatiquement au démarrage du pc ne laissant juste à l'utilisateur une boite de dialogue demandant login+pass.:rolleyes: -J'ai déjà installé le plugin "network-manager-pptp" tout est ok la connexion fonctionne ! Cependant j'aimerais que celle-ci se lance d'elle même au démarrage du système malheureusement j'ai beau cocher la case "connexion automatique" rien n'y fait ! Bref je me penche actuellement sur une solution qui puisse en ligne de commande lancer la connexion VPN ! -Le must serait que l'on affiche une boite de dialogue au démarrage demandant les login (user+pass) puis de lancer la connexion dans la foulé. Si la demande des identifiants se fait par l'intermédiaire d'un script shell en console cela me conviendra amplement. Voila voila merci à ceux qui auront le courage de lire ce message jusqu'à la fin et merci à ceux qui pourrons m'éclairer ! (n'hésiter pas à me demander plus de précision si besoin...) Cordialement, Anthony Hors ligne toto2849 Re : Connexion VPN automatique (NetworkManager) UP personne ? J'ai vu ceci sur le site suivant... mais RIEN ! Je ne sais pas comment activer automatiquement cette connexion.... Quelques infos peu utile ... http://projects.gnome.org/NetworkManage … Connection Dernière modification par toto2849 (Le 04/06/2009, à 22:19) Hors ligne toto2849 Re : Connexion VPN automatique (NetworkManager) Décidément personne peut m'aider ?? Hors ligne toto2849 Re : Connexion VPN automatique (NetworkManager) hop un UP pour la route....:rolleyes: Hors ligne killman Re : Connexion VPN automatique (NetworkManager) je n' ai pas eu le temps de me pencher sur la question, mais tu devrais essayer de rédiger un script qui lance la connexion cliente sur le vpn, si tu veux automatiser ça. Hors ligne toto2849 Re : Connexion VPN automatique (NetworkManager) -Tout d'abord merci d'avoir répondu à mon problème car j'ai cru que tout le monde s'en foutait... -Donc pour te répondre, oui en effet c'est ce que j'ai pensé aussi; d'ailleurs j'en ai commencé un morceau mais je ne connait pas les raccourcis me permettant de lancer en shell la connexion vpn de NetworkManager... Bien entendu si quelqu'un peut me proposer une méthode alternative qui ne passerait pas par ce gestionnaire cela me conviendra aussi ! Voici pour le moment ce que j'ai pu faire....mais je connais pas grand chose en script: #!/bin/sh #saisie des login echo "Saisir nom d'utilisateur : " read utilisateur echo "Saisir mot de passe : " read -s passe #lancement de la connexion vpn org.freedesktop.NetworkManager.ppp_starter ...mais cela est faux... Comme dit plus haut j'ai trouvé sur leur site 2/3 truc comme "org.freedesktop.NetworkManager.VPN.Connection" mais es applicable pour lancer une connexion par la console ? j'ai tenté mais rien...peut être un soucis de syntaxe ? Hors ligne coredump Re : Connexion VPN automatique (NetworkManager) Moi, j'ai une solution avec NetworkManager. Il s'agit d'un service qui utilise d-bus pour piloter le NetworkManager. Le principe est assez simple, mais le script est assez complexe. ... Suite aux différents échanges qui ont été fait sur le sujet, j'utilise ce post, pour proposer une solution simple et accessible aux néophytes. Cette solution permet de lancer automatiquement une connexion vpn et qu'elle se reconnecte automatiquement en cas de coupure. Remarques : - Cette solution n'est pas forcément compatible avec d'ancienne version d'ubuntu. - Pour une utilisation avancée, voir les autres posts de cette discussion, en particulier le post #28 (http://forum.ubuntu-fr.org/viewtopic.ph … 7#p3225667) de Papou qui propose des scripts qui permettent de lancer la connexion automatique "à la demande". - Pour ceux qui auraient déjà mis en place le script connection-service, celui-ci a un peu évolué, il faut donc le mettre à jour. Voici, la démarche, en deux étapes, à suivre : - ajouter ce script exécutable 02-loop-vpn dans /etc/NetworkManager/dispatcher.d/ en ayant pris soin de renseigner le nom de la connexion vpn /etc/NetworkManager/dispatcher.d/02-loop-vpn : #!/bin/bash # Script de lancement de connection VPN avec verification CONNECTION_NAME="Connexion VPN 1" while ! connection-service "$CONNECTION_NAME" status do connection-service "$CONNECTION_NAME" start sleep 30 done Soit, en ligne de commande : sudo gedit /etc/NetworkManager/dispatcher.d/02-loop-vpn copier/coller le code ci-dessus dans le fichier, et renseigner le champ CONNECTION_NAME avec le nom utilisé par le Network Manager pour votre connexion sudo chmod +x /etc/NetworkManager/dispatcher.d/02-loop-vpn - ajouter ce script exécutable connection-service dans /usr/local/bin/ /usr/local/bin/connection-service : #!/bin/bash ############ # SETTINGS # ############ get_connections_paths() { dbus-send --system --print-reply --dest="$1" "/org/freedesktop/NetworkManagerSettings" "org.freedesktop.NetworkManagerSettings.ListConnections" \ | grep "object path" | cut -d '"' -f2 } get_connection_settings() { dbus-send --system --print-reply --dest="$1" "$2" org.freedesktop.NetworkManagerSettings.Connection.GetSettings } get_connection_string_setting() { echo "$1" | grep -A 1 \""$2"\" | grep variant | cut -d '"' -f2 } get_connection_id() { get_connection_string_setting "$1" "id" } get_connection_type() { get_connection_string_setting "$1" "type" } get_device_type_by_connection_type() { echo "$1" | grep -q "ethernet" && echo 1 && return echo "$1" | grep -q "wireless" && echo 2 && return echo 0 } find_connection_path() { for connection_path in `get_connections_paths "$1"` do connection_settings=`get_connection_settings "$1" "$connection_path"` connection_settings_id=`get_connection_id "$connection_settings"` [ "$connection_settings_id" = "$2" ] && echo "$1" "$connection_path" done } find_connection_path_everywhere() { find_connection_path "org.freedesktop.NetworkManagerSystemSettings" "$1" find_connection_path "org.freedesktop.NetworkManagerUserSettings" "$1" } print_connections_ids() { for connection_path in `get_connections_paths "$1"` do connection_settings=`get_connection_settings "$1" "$connection_path"` connection_settings_id=`get_connection_id "$connection_settings"` echo "$connection_settings_id" done } print_connections_ids_everywhere() { print_connections_ids "org.freedesktop.NetworkManagerSystemSettings" print_connections_ids "org.freedesktop.NetworkManagerUserSettings" } ########### # DEVICES # ########### get_devices_paths() { dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "/org/freedesktop/NetworkManager" "org.freedesktop.NetworkManager.GetDevices" \ | grep "object path" | cut -d '"' -f2 } get_device_property() { dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "$1" "org.freedesktop.DBus.Properties.Get" string:"org.freedesktop.NetworkManager.Device" string:"$2" \ | grep variant | awk '{print $3}' } get_device_type() { get_device_property "$1" "DeviceType" } get_device_path_by_device_type() { device_path_by_device_type="/" for device_path in `get_devices_paths` do device_type=`get_device_type "$device_path"` [ "$device_type" = "$1" ] && device_path_by_device_type="$device_path" done echo "$device_path_by_device_type" } ####################### # ACTIVES CONNECTIONS # ####################### get_actives_connections_paths() { dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "/org/freedesktop/NetworkManager" "org.freedesktop.DBus.Properties.Get" string:"org.freedesktop.NetworkManager" string:"ActiveConnections" \ | grep "object path" | cut -d '"' -f2 } get_last_active_connection_path() { get_actives_connections_paths | tail -n 1 } get_parent_connection_path_by_device_type() { parent_connection_path="/" [ "$1" = 0 ] && parent_connection_path=`get_last_active_connection_path` echo "$parent_connection_path" } get_active_connection_property() { dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "$1" "org.freedesktop.DBus.Properties.Get" string:"org.freedesktop.NetworkManager.Connection.Active" string:"$2" \ | grep variant | awk -F '"' '{print $2}' } get_active_connection_service() { get_active_connection_property "$1" "ServiceName" } get_active_connection_path() { get_active_connection_property "$1" "Connection" } get_active_connection_path_by_connection_path() { for active_connection_path in `get_actives_connections_paths` do service=`get_active_connection_service $active_connection_path` path=`get_active_connection_path $active_connection_path` [ "$service" = "$1" ] && [ "$path" = "$2" ] && echo "$active_connection_path" done } print_actives_connections_ids() { for active_connection_path in `get_actives_connections_paths` do service=`get_active_connection_service $active_connection_path` path=`get_active_connection_path $active_connection_path` connection_settings=`get_connection_settings "$service" "$path"` connection_settings_id=`get_connection_id "$connection_settings"` echo "$connection_settings_id" done } ############## # START/STOP # ############## start_connection() { my_connection_complete_path=`find_connection_path_everywhere "$1"` my_connection_settings=`get_connection_settings $my_connection_complete_path` my_connection_type=`get_connection_type "$my_connection_settings"` my_connection_device_type=`get_device_type_by_connection_type "$my_connection_type"` my_connection_service=`echo $my_connection_complete_path | awk '{print $1}'` my_connection_path=`echo $my_connection_complete_path | awk '{print $2}'` my_connection_device_path=`get_device_path_by_device_type "$my_connection_device_type"` my_parent_connection_path=`get_parent_connection_path_by_device_type "$my_connection_device_type"` echo "connection_service=$my_connection_service" echo "connection_path=$my_connection_path" echo "connection_device_path=$my_connection_device_path" echo "parent_connection_path=$my_parent_connection_path" dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" /org/freedesktop/NetworkManager "org.freedesktop.NetworkManager.ActivateConnection" string:"$my_connection_service" objpath:"$my_connection_path" objpath:"$my_connection_device_path" objpath:"$my_parent_connection_path" } stop_connection() { my_connection_complete_path=`find_connection_path_everywhere "$1"` my_active_connection_path=`get_active_connection_path_by_connection_path $my_connection_complete_path` echo "active_connection_path=$my_active_connection_path" dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" /org/freedesktop/NetworkManager "org.freedesktop.NetworkManager.DeactivateConnection" objpath:"$my_active_connection_path" } ######## # MAIN # ######## invalid_arguments() { echo "Usage: `basename "$0"` connexion_name start|stop" echo "Connexion disponibles:" print_connections_ids_everywhere echo "Connexion actives:" print_actives_connections_ids exit 0 } [ "$#" != 2 ] && invalid_arguments case "$2" in "start") start_connection "$1" ;; "stop") stop_connection "$1" ;; "restart") stop_connection "$1" start_connection "$1" ;; "status") if print_actives_connections_ids | grep -q -x "$1" then echo "Connexion \"$1\" active" exit 0 else echo "Connexion \"$1\" inactive" exit 1 fi ;; *) invalid_arguments ;; esac Soit, en ligne de commande : sudo gedit /usr/local/bin/connection-service copier/coller le code ci-dessus dans le fichier, puis sudo chmod +x /usr/local/bin/connection-service Enjoy it! Dernière modification par coredump (Le 30/01/2010, à 11:21) Hors ligne legrosschmoll Re : Connexion VPN automatique (NetworkManager) Ca n'a pas l'air d 'intéresser toto2849 mais moi oui. Si tu pouvais poster ta solution Merci d'avance Precise sur W500 Hors ligne coredump Re : Connexion VPN automatique (NetworkManager) Désolé, si je réponds un peu tard, ça fait un moment que je consulte pas le forum. Voici ma solution, si ça t'intéresse toujours ou si ça intéresse quelqu'un d'autre. L'origine du problème a deux sources par rapport au VPN avec Network Manager : - quand on coche "Connecter automatiquement", ceci n'est pas pris en compte - quand on coche "Disponible pour tous les utilisateurs", la connexion ne marche pas (à cause d'une histoire de clé quand on regarde les logs) (En général, je trouve que le Network Manager a de légers disfonctionnements qui démontrent à mon avis quelques problèmes de conceptions ...) Les scripts que je propose tente de remédier à cela. Leur but est de connecter automatiquement le VPN et de le reconnecter automatiquement si il se déconnecte. (Avec de légères modifications, ça pourrait se comporter différemment selon le besoin.) Le principe est de se lancer et de s'arrêter en fonction d'une autre connexion parente (eth0 par exemple). Puis de surveiller d-bus pour voir : - si les paramètres de la connexion VPN sont disponibles (quand l'utilisateur se connecte) - si la connexion VPN ne s'est pas déconnectée Il y a deux scripts : 02-service-vpn -> à mettre dans /etc/NetworkManager/dispatcher.d/ (lance ou arrête "checkVPN" en fonction de la connexion parente) checkVPN -> à mettre dans /usr/local/bin/ (script python qui surveille que la connexion VPN soit toujours bien connecter) Tous deux doivent être exécutables. checkVPN dépend d'un autre fichier : nm_utils.py -> à mettre dans /usr/local/bin/ (outils pour piloter le nm en python) Il y a deux champs à renseigner dans le script 02-service-vpn : ETH_INTERFACE_NAME : l'interface de la connexion parente (par exemple : eth0) VPN_CONNECTION_NAME : le nom de la connexion VPN qui a été renseigner dans le network manager (Pour que ça marche pour plusieurs utilisateurs, il faut pour chacun définir la connexion VPN.) (Il y a aussi la possibilité de décommenter des lignes pour avoir des traces.) /etc/NetworkManager/dispatcher.d/02-service-vpn : #!/bin/bash ETH_INTERFACE_NAME="eth0" # The name of the VPN connection to activate VPN_CONNECTION_NAME="Connexion VPN" # Or the uuid of the VPN connection to activate #VPN_CONNECTION_NAME="UUID=abcf8915-bb27-4634-94e6-04c65261a73e" SERVICE_VPN_LOG="/dev/null" #SERVICE_VPN_LOG="/tmp/serviceVPN.log" CHECK_VPN_LOG="/dev/null" #CHECK_VPN_LOG="/tmp/checkVPN.log" echo `date`": $0 $@" >> "$SERVICE_VPN_LOG" [ "$1" != "$ETH_INTERFACE_NAME" ] && exit 0 case "$2" in "up") echo "Starting CheckVPN ... ("`which checkVPN`")" >> "$SERVICE_VPN_LOG" # On vérifie que checkVPN ne tourne pas déjà if [ "`pgrep checkVPN`" == "" ] then echo "CheckVPN started." >> "$SERVICE_VPN_LOG" checkVPN "$VPN_CONNECTION_NAME" > "$CHECK_VPN_LOG" 2>&1 & else echo "CheckVPN already running !" >> "$SERVICE_VPN_LOG" fi ;; "down") echo "Stoping checkVPN ..." >> "$SERVICE_VPN_LOG" if [ "`pgrep checkVPN`" == "" ] then echo "CheckVPN not running !" >> "$SERVICE_VPN_LOG" else pkill checkVPN echo "CheckVPN stopped." >> "$SERVICE_VPN_LOG" fi ;; *) echo "Nothing to do" >> "$SERVICE_VPN_LOG" ;; esac /usr/local/bin/checkVPN : #!/usr/bin/python -u # coding=UTF-8 import sys import dbus from dbus.mainloop.glib import DBusGMainLoop import gobject from nm_utils import * VPN_CONNECTION_UUID = VPN_CONNECTION_NAME = None # Default values : # The name of the VPN connection to activate #VPN_CONNECTION_NAME = "Connexion VPN 1" # or the uuid of the VPN connection to activate #VPN_CONNECTION_UUID = "fabf8915-bb27-4634-94e6-04c65261a73e" if len(sys.argv) > 1: vpn_argument = sys.argv[1] VPN_CONNECTION_UUID = VPN_CONNECTION_NAME = None if (vpn_argument[:5] == "UUID="): VPN_CONNECTION_UUID = vpn_argument[5:] print "VPN_CONNECTION_UUID=%s" % (VPN_CONNECTION_UUID) else: VPN_CONNECTION_NAME = vpn_argument print "VPN_CONNECTION_NAME=%s" % (VPN_CONNECTION_NAME) if (not VPN_CONNECTION_UUID) and (not VPN_CONNECTION_NAME): print "Usage : "+sys.argv[0]+" connexion_vpn_name" print "Liste des connexions diponibles :" print_connections_infos() sys.exit(1) vpn_connection_infos = {'vpn_connection_settings': None, 'vpn_connection_path': None} def get_vpn_connection_settings(): if VPN_CONNECTION_UUID: return get_connection_settings_by_uuid(VPN_CONNECTION_UUID) if VPN_CONNECTION_NAME: return get_connection_settings_by_name(VPN_CONNECTION_NAME) return None def get_vpn_connection_path(): if VPN_CONNECTION_UUID: return get_active_connection_path_by_uuid(VPN_CONNECTION_UUID) if VPN_CONNECTION_NAME: return get_active_connection_path_by_name(VPN_CONNECTION_NAME) return None def get_eth_active_connection_path(): try: active_connections_paths = get_active_connections_paths() active_connections_paths_count = len(active_connections_paths) if active_connections_paths_count == 0: return None return active_connections_paths[active_connections_paths_count-1] except Exception as exception: print exception return None def update_vpn_connection_settings(): vpn_connection_settings = get_vpn_connection_settings() vpn_connection_infos['vpn_connection_settings'] = vpn_connection_settings print "update_vpn_connection_settings=%s" % get_connection_infos(vpn_connection_settings) def update_vpn_connection_path(): vpn_connection_path = get_vpn_connection_path() vpn_connection_infos['vpn_connection_path'] = vpn_connection_path print "update_vpn_connection_path: vpn_connection_path=%s" % vpn_connection_path def start_connection(settings, active_connection_path): def reply_handler(opath): vpn_connection_path = opath vpn_connection_infos['vpn_connection_path'] = vpn_connection_path def error_handler(*args): print args proxy = dbus.SystemBus().get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager') iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManager') iface.ActivateConnection(get_connection_settings_type(settings), get_connection_settings_path(settings), dbus.ObjectPath("/"), active_connection_path, reply_handler=reply_handler, error_handler=error_handler) def checkVPN(): vpn_connection_settings = vpn_connection_infos['vpn_connection_settings'] # Do nothing if vpn connection settings don't exist print "checkVPN: vpn_connection_settings=%s" % get_connection_infos(vpn_connection_settings) if not vpn_connection_settings: return vpn_connection_path = vpn_connection_infos['vpn_connection_path'] # Do nothing if vpn connection already exist print "checkVPN: vpn_connection_path=%s" % vpn_connection_path if vpn_connection_path: return eth_connection_path = get_eth_active_connection_path() print "checkVPN: eth_connection_path=%s" % eth_connection_path # Do nothing if eth connection don't exist if not eth_connection_path: return start_connection(vpn_connection_settings, eth_connection_path) def handle_connection_settings_changed(): print "handle_connection_settings_changed" update_vpn_connection_settings() checkVPN() def handle_connections_changed(): print "handle_connections_changed" update_vpn_connection_path() checkVPN() def all_signal_receiver(*args, **kwargs): if (kwargs['dbus_interface'] == "org.freedesktop.NetworkManagerSettings"): handle_connection_settings_changed() if (kwargs['dbus_interface'] == "org.freedesktop.NetworkManagerSettings.Connection")\ and (kwargs['signal_name'] == "Updated"): handle_connection_settings_changed() if (kwargs['dbus_interface'] == "org.freedesktop.NetworkManager")\ and (kwargs['signal_name'] == "PropertiesChanged")\ and args[0].has_key('ActiveConnections'): handle_connections_changed() DBusGMainLoop(set_as_default=True) dbus.SystemBus().add_signal_receiver(all_signal_receiver, interface_keyword='dbus_interface', member_keyword='signal_name') update_vpn_connection_settings() update_vpn_connection_path() checkVPN() gobject.MainLoop().run() /usr/local/bin/nm_utils.py : # coding=UTF-8 import dbus # Get connection settings from settings type and settings path # (settings type is 'org.freedesktop.NetworkManagerSystemSettings' or 'org.freedesktop.NetworkManagerUserSettings') def get_connection_settings(settings_type, settings_path): proxy = dbus.SystemBus().get_object(settings_type, settings_path) iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManagerSettings.Connection') settings = iface.GetSettings() settings['settings-type'] = settings_type settings['settings-path'] = settings_path return settings # Get differents informations from connection settings def get_connection_settings_type(settings): return settings['settings-type'] def get_connection_settings_path(settings): return settings['settings-path'] def get_connection_settings_uuid(settings): return settings['connection']['uuid'] def get_connection_settings_name(settings): return settings['connection']['id'] # Get all settings paths associated to a type of settings def get_connections_settings_paths(settings_type): try: proxy = dbus.SystemBus().get_object(settings_type, '/org/freedesktop/NetworkManagerSettings') iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.NetworkManagerSettings') return iface.ListConnections() except Exception as exception: print " !!! get_connections_settings_paths:" print exception return [] # Get all connections settings associated to a type of settings def get_connections_settings_by_type(settings_type): connections_settings = [] for settings_path in get_connections_settings_paths(settings_type): connection_settings = get_connection_settings(settings_type, settings_path) connections_settings.append(connection_settings) return connections_settings # Get all connections settings def get_all_connections_settings(): return get_connections_settings_by_type('org.freedesktop.NetworkManagerUserSettings') + \ get_connections_settings_by_type('org.freedesktop.NetworkManagerSystemSettings') # Get the esssential informations of the connection def get_connection_infos(settings): if settings: conn = settings['connection'] return "%s (type=%s, UUID=%s)" % (conn['id'], conn['type'], conn['uuid']) else: return None # Print the list of connections def print_connections_infos(): for connection_settings in get_all_connections_settings(): print get_connection_infos(connection_settings) # Get connection settings from the settings UUID def get_connection_settings_by_uuid(uuid): try: for settings in get_all_connections_settings(): if get_connection_settings_uuid(settings) == uuid: return settings except Exception as exception: print exception return None # Get connection settings from the settings UUID def get_connection_settings_by_name(name): try: for settings in get_all_connections_settings(): if get_connection_settings_name(settings) == name: return settings except Exception as exception: print exception return None # Get list of active connections paths def get_active_connections_paths(): proxy = dbus.SystemBus().get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager') iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.DBus.Properties') return iface.Get('org.freedesktop.NetworkManager', 'ActiveConnections') # Get connection settings from the connection path def get_connection_settings_by_connection_path(connection_path): proxy = dbus.SystemBus().get_object('org.freedesktop.NetworkManager', connection_path) iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.DBus.Properties') settings_type = iface.Get('org.freedesktop.NetworkManager.Connection.Active', 'ServiceName') settings_path = iface.Get('org.freedesktop.NetworkManager.Connection.Active', 'Connection') return get_connection_settings(settings_type, settings_path) # Get list of active connections paths def get_active_connections_settings(): actives_connections_settings = [] for connection_path in get_active_connections_paths(): settings = get_connection_settings_by_connection_path(connection_path) settings['connection-path'] = connection_path actives_connections_settings.append(settings) return actives_connections_settings # Look for connexion path in active connexions with particular uuid def get_active_connection_path_by_uuid(uuid): try: for connection_path in get_active_connections_paths(): settings = get_connection_settings_by_connection_path(connection_path) if get_connection_settings_uuid(settings) == uuid: return connection_path except Exception as exception: print exception return None # Look for connexion path in active connexions with particular name def get_active_connection_path_by_name(name): try: for connection_path in get_active_connections_paths(): settings = get_connection_settings_by_connection_path(connection_path) if get_connection_settings_name(settings) == name: return connection_path except Exception as exception: print exception return None Voilà, ça peut certainement être amélioré ou généralisé, mais j'espère au moins que ça pourra te dépanner. Hors ligne ElFabio Re : Connexion VPN automatique (NetworkManager) En tout cas, ca en dépanne d'autres ! merci bp pour ce boulot coredump, ca marche nickel, et c'est en plus trés propre, pas grand chose à redire, si ce n'est merci ! Hors ligne coredump Re : Connexion VPN automatique (NetworkManager) Merci ElFabio pour ton soutien et content que ça puisse te servir. Une solution plus propre serait de trouver une correction au niveau du network manager ou de l'applet (est-ce que l'applet KDE marche ?). Si j'avais un peu de temps et plus d'expérience dans la rédaction d'articles, j'aurais bien fait un tuto sur l'utilisation de d-bus pour contrôler le NM, car la documentation à ce sujet est assez maigre sur le net. Voici quand même quelques liens qui m'ont été utiles : - http://doc.ubuntu-fr.org/networkmanager … e_commande - http://doc.ubuntu-fr.org/dbus - http://old.nabble.com/dbus-and-OpenVPN- … 05375.html - http://projects.gnome.org/NetworkManage … /spec.html - http://linuxfr.org/forums/15/27406.html - http://dbus.freedesktop.org/doc/dbus-py … orial.html Je recommande aussi l'interface graphique d-feet pour s'exercer à utiliser d-bus (pratique aussi pour retrouver les API des services). (Quand on veut être "listener" - à l'écoute - d'un service, la commande dbus-monitor aussi est pratique.) Et pour ceux qui voudraient piloter NM à l'aide de d-bus, voici quelques exemples de lignes de commande qui permettent de le faire : Afficher la liste des chemins des définitions des connexion selon leurs appartenances (système - disponibles pour tous les utilisateurs / personnel - propre à l'utilisateur) : dbus-send --system --print-reply --dest=org.freedesktop.NetworkManagerSystemSettings "/org/freedesktop/NetworkManagerSettings" \ org.freedesktop.NetworkManagerSettings.ListConnections (ou --dest="org.freedesktop.NetworkManagerUserSettings") Afficher les paramètres d'une connexion selon son appartenance et connaissant son chemin dbus-send --system --print-reply --dest=org.freedesktop.NetworkManagerSystemSettings "/org/freedesktop/NetworkManagerSettings/0" \ org.freedesktop.NetworkManagerSettings.Connection.GetSettings (ou --dest="org.freedesktop.NetworkManagerUserSettings") Afficher la liste des chemins des connexions actives : dbus-send --system --print-reply --dest=org.freedesktop.NetworkManager "/org/freedesktop/NetworkManager" \ org.freedesktop.DBus.Properties.Get string:"org.freedesktop.NetworkManager" string:"ActiveConnections" Afficher une propriété d'une connexion active connaissant son chemin : dbus-send --system --print-reply --dest=org.freedesktop.NetworkManager "/org/freedesktop/NetworkManager/ActiveConnection/2" \ org.freedesktop.DBus.Properties.Get string:"org.freedesktop.NetworkManager.Connection.Active" string:"nom_de_la_propriete" "nom_de_la_propriete" est à renseigner. Par exemple, "nom_de_la_propriete" peut-être "ServiceName" ou "Connection" pour connaître l'appartenance et le chemin de la définition de la connexion. Arrêter une connection active connaissant son chemin : dbus-send --system --print-reply --dest=org.freedesktop.NetworkManager "/org/freedesktop/NetworkManager" \ org.freedesktop.NetworkManager.DeactivateConnection objpath:"/org/freedesktop/NetworkManager/ActiveConnection/2" Démarrer une connexion : dbus-send --system --print-reply --dest=org.freedesktop.NetworkManager "/org/freedesktop/NetworkManager" \ org.freedesktop.NetworkManager.ActivateConnection string:"org.freedesktop.NetworkManagerSystemSettings" objpath:"/org/freedesktop/NetworkManagerSettings/0" objpath:"/org/freedesktop/NetworkManager/Devices/0" objpath:"/" ou dans le cas d'une connection vpn : dbus-send --system --print-reply --dest=org.freedesktop.NetworkManager "/org/freedesktop/NetworkManager" \ org.freedesktop.NetworkManager.ActivateConnection string:"org.freedesktop.NetworkManagerUserSettings" objpath:"/org/freedesktop/NetworkManagerSettings/1" objpath:"/" objpath:"/org/freedesktop/NetworkManager/ActiveConnection/2" Le problème de cette commande est qu'il faut passer en argument de la commande le chemin du device (ethN ou rien pour le vpn) et le chemin de la connexion active dont elle dépend (si elle n'utilise pas de device). Malheureusement ces informations ne sont pas évidentes à déduire. Pour terminer voici un exemple de script utilisant ces commandes et permettant de démarrer ou d'arrêter une connexion en lui passant le nom de la connexion. Pour l'utiliser, nommer le fichier "connection-service", le rendre exécutable et placer le dans "/usr/local/bin/", puis taper : connection-service "nom_de_la_connexion" start|stop Par exemple : connection-service "Connection VPN 1" start /usr/local/bin/connection-service : #!/bin/bash ############ # SETTINGS # ############ get_connections_paths() { dbus-send --system --print-reply --dest="$1" "/org/freedesktop/NetworkManagerSettings" "org.freedesktop.NetworkManagerSettings.ListConnections" \ | grep "object path" | cut -d '"' -f2 } get_connection_settings() { dbus-send --system --print-reply --dest="$1" "$2" org.freedesktop.NetworkManagerSettings.Connection.GetSettings } get_connection_string_setting() { echo "$1" | grep -A 1 \""$2"\" | grep variant | cut -d '"' -f2 } get_connection_id() { get_connection_string_setting "$1" "id" } get_connection_type() { get_connection_string_setting "$1" "type" } get_device_type_by_connection_type() { echo "$1" | grep -q "ethernet" && echo 1 && return echo "$1" | grep -q "wireless" && echo 2 && return echo 0 } find_connection_path() { for connection_path in `get_connections_paths "$1"` do connection_settings=`get_connection_settings "$1" "$connection_path"` connection_settings_id=`get_connection_id "$connection_settings"` [ "$connection_settings_id" = "$2" ] && echo "$1" "$connection_path" done } find_connection_path_everywhere() { find_connection_path "org.freedesktop.NetworkManagerSystemSettings" "$1" find_connection_path "org.freedesktop.NetworkManagerUserSettings" "$1" } print_connections_ids() { for connection_path in `get_connections_paths "$1"` do connection_settings=`get_connection_settings "$1" "$connection_path"` connection_settings_id=`get_connection_id "$connection_settings"` echo "$connection_settings_id" done } print_connections_ids_everywhere() { print_connections_ids "org.freedesktop.NetworkManagerSystemSettings" print_connections_ids "org.freedesktop.NetworkManagerUserSettings" } ########### # DEVICES # ########### get_devices_paths() { dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "/org/freedesktop/NetworkManager" "org.freedesktop.NetworkManager.GetDevices" \ | grep "object path" | cut -d '"' -f2 } get_device_property() { dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "$1" "org.freedesktop.DBus.Properties.Get" string:"org.freedesktop.NetworkManager.Device" string:"$2" \ | grep variant | awk '{print $3}' } get_device_type() { get_device_property "$1" "DeviceType" } get_device_path_by_device_type() { device_path_by_device_type="/" for device_path in `get_devices_paths` do device_type=`get_device_type "$device_path"` [ "$device_type" = "$1" ] && device_path_by_device_type="$device_path" done echo "$device_path_by_device_type" } ####################### # ACTIVES CONNECTIONS # ####################### get_actives_connections_paths() { dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "/org/freedesktop/NetworkManager" "org.freedesktop.DBus.Properties.Get" string:"org.freedesktop.NetworkManager" string:"ActiveConnections" \ | grep "object path" | cut -d '"' -f2 } get_last_active_connection_path() { get_actives_connections_paths | tail -n 1 } get_parent_connection_path_by_device_type() { parent_connection_path="/" [ "$1" = 0 ] && parent_connection_path=`get_last_active_connection_path` echo "$parent_connection_path" } get_active_connection_property() { dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" "$1" "org.freedesktop.DBus.Properties.Get" string:"org.freedesktop.NetworkManager.Connection.Active" string:"$2" \ | grep variant | awk -F '"' '{print $2}' } get_active_connection_service() { get_active_connection_property "$1" "ServiceName" } get_active_connection_path() { get_active_connection_property "$1" "Connection" } get_active_connection_path_by_connection_path() { for active_connection_path in `get_actives_connections_paths` do service=`get_active_connection_service $active_connection_path` path=`get_active_connection_path $active_connection_path` [ "$service" = "$1" ] && [ "$path" = "$2" ] && echo "$active_connection_path" done } print_actives_connections_ids() { for active_connection_path in `get_actives_connections_paths` do service=`get_active_connection_service $active_connection_path` path=`get_active_connection_path $active_connection_path` connection_settings=`get_connection_settings "$service" "$path"` connection_settings_id=`get_connection_id "$connection_settings"` echo "$connection_settings_id" done } ############## # START/STOP # ############## start_connection() { my_connection_complete_path=`find_connection_path_everywhere "$1"` my_connection_settings=`get_connection_settings $my_connection_complete_path` my_connection_type=`get_connection_type "$my_connection_settings"` my_connection_device_type=`get_device_type_by_connection_type "$my_connection_type"` my_connection_service=`echo $my_connection_complete_path | awk '{print $1}'` my_connection_path=`echo $my_connection_complete_path | awk '{print $2}'` my_connection_device_path=`get_device_path_by_device_type "$my_connection_device_type"` my_parent_connection_path=`get_parent_connection_path_by_device_type "$my_connection_device_type"` echo "connection_service=$my_connection_service" echo "connection_path=$my_connection_path" echo "connection_device_path=$my_connection_device_path" echo "parent_connection_path=$my_parent_connection_path" dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" /org/freedesktop/NetworkManager "org.freedesktop.NetworkManager.ActivateConnection" string:"$my_connection_service" objpath:"$my_connection_path" objpath:"$my_connection_device_path" objpath:"$my_parent_connection_path" } stop_connection() { my_connection_complete_path=`find_connection_path_everywhere "$1"` my_active_connection_path=`get_active_connection_path_by_connection_path $my_connection_complete_path` echo "active_connection_path=$my_active_connection_path" dbus-send --system --print-reply --dest="org.freedesktop.NetworkManager" /org/freedesktop/NetworkManager "org.freedesktop.NetworkManager.DeactivateConnection" objpath:"$my_active_connection_path" } ######## # MAIN # ######## invalid_arguments() { echo "Usage: `basename "$0"` connexion_name start|stop" echo "Connexion disponibles:" print_connections_ids_everywhere echo "Connexion actives:" print_actives_connections_ids exit 0 } [ "$#" != 2 ] && invalid_arguments case "$2" in "start") start_connection "$1" ;; "stop") stop_connection "$1" ;; "restart") stop_connection "$1" start_connection "$1" ;; "status") if print_actives_connections_ids | grep -q -x "$1" then echo "Connexion \"$1\" active" exit 0 else echo "Connexion \"$1\" inactive" exit 1 fi ;; *) invalid_arguments ;; esac Dernière modification par coredump (Le 28/01/2010, à 13:21) Hors ligne ElFabio Re : Connexion VPN automatique (NetworkManager) effectivement, tu as bien potassé ton d-bus ! et de rien pour le soutien, c'est le moins que je puisse faire, surtout que j'utilise maintenant ton script tous les jours ! vraiment exactement ce que je recherchais ! Hors ligne coredump Re : Connexion VPN automatique (NetworkManager) Par les temps qui courent, il vaut mieux surfer bien couvert Hors ligne Brunod Re : Connexion VPN automatique (NetworkManager) Salut, Je te félicite anticipativement parce que là, en congé, je n'en ai pas besoin; mais à la rentrée, faudra que je me penche dessus ! Merci ! Wanted : >>> un emploi dans la sécurité informatique et réseau <<< Windows est un système d'exploitation de l'homme par l'ordinateur. Linux, c'est le contraire ... --> état de la conversion : 36 pc linux Hors ligne coredump Re : Connexion VPN automatique (NetworkManager) À noter, que le script "connection-service" défini dans mon post #11 ci-dessus peut aussi être utilisé pour connecter automatiquement le VPN. Pour cela, créer un script "vpn-autostart" exécutable dans "/usr/local/bin/", /usr/local/bin/vpn-autostart : #!/bin/bash # Délai de 10 secondes pour laisser le temps à nm-applet de démarrer sleep 10 && connection-service "Connection VPN 1" start Ajouter ensuite un programme "VPN" dans la liste des "Applications au démarrage" avec comme commande : vpn-autostart Ceci démarrera la connexion "Connection VPN 1" à l'ouverture de la session. Et pour reconnecter automatiquement la connexion en cas de coupure, ajouter ce script "02-loop-vpn" exécutable dans "/etc/NetworkManager/dispatcher.d/": /etc/NetworkManager/dispatcher.d/02-loop-vpn : #!/bin/bash [ "$2" = "vpn-down" ] && vpn-autostart Et voilà ! Hors ligne lynn Re : Connexion VPN automatique (NetworkManager) Bonjour, Merci à toi coredump pour ces scripts de connection automatique pour VPN. Ils fonctionnent parfaitement Comme tu le dis si bien : - quand on coche "Connecter automatiquement", ceci n'est pas pris en compte - quand on coche "Disponible pour tous les utilisateurs", la connexion ne marche pas (à cause d'une histoire de clé quand on regarde les logs) A quand un Network Manager complètement fonctionnel ? Parce que c'est vrai que ce genre de "détails" est quand même bien ch...t. En attendant, merci encore coredump et je pense que ce post va intéresser pas mal de monde .....:P Linux est la solution ! Au fait, c'est quoi ton problème ? Ubuntu 14.04 - 64 bits - Ubuntu 14.10 - 64 bits - Utopic Unicorn Hors ligne ElFabio Re : Connexion VPN automatique (NetworkManager) Merci encore une fois coredump pour ce tutoriel trés pratique et directement utilisable, j'en profite pour abuser un peu de tes compétences pour te poser une question concernant l'usage de tes scripts (j'utilise en particulier checkVPN) : aprés maintenant plusieurs jours d'utilisation, je remarque qu'au fur et à mesure de mes reconnexions automatique à mon provider VPN (lors d'une déconnexion), le débit global des téléchargements (dans mon client torrent préféré...) a tendance à se contracter fortement (divisé par 2 ou 3), et un simple redémarrage du PC permet de revenir à un débit normal. Pour info je me connecte en WiFi, et peut être n'est ce pas du à l'utilisation de tes scripts, mais est ce que ca ne pourrait pas venir d'un "engorgement" de process qui s'accumulent en taches de fond suite à de multiples déconnexion/reconnexion VPN, je ne pense pas trop parce qu'en faisant un ps aux je n'en trouve pas trace et qu'en plus ton script me parait vraiment trés propre, mais je n'ai pas d'explications plausibles... est ce que tu aurais déjà rencontré le même genre de soucis ou aurais tu une idée de leur origine ? Je te souhaite une trés bonne année, Hors ligne rogerjm Re : Connexion VPN automatique (NetworkManager) Bravo coredump pour ce post (qui n'est pas loin d'être un article ). Tout ce que tu y as décrit m'a été très utile pour configurer mon VPN et le lancer automatiquement, mais aussi m'a appris plein de choses. Bonne année Hors ligne coredump Re : Connexion VPN automatique (NetworkManager) Bonne année à tous ! Au sujet de ton problème, ElFabio, je ne pense pas pouvoir t'aider beaucoup. À vue de nez, voici mes impressions : - Concernant le script de reconnexion, ça m'étonnerait qu'il puisse provoquer un "engorgement". La plupart du temps il est au repos (en attente d'évènements) et quand il bosse, il ne fait jamais que quelques petites opérations. Le seul petit souci que je verrais, serait le délai de reconnexion. En cas de coupure, il cherche instantanément à se reconnecter et ce n'est peut-être pas très bon. J'ai remarqué qu'en cas de coupure, la reconnexion ne se fait pas toujours à la première tentative. Le fait d'envoyer des requêtes de reconnexion aussi proches n'est peut-être pas très bon. En même temps, une fois qu'il s'est reconnecté, je n'ai pas observé pour ma part de diminution de la bande passante. Mais, si tu veux chercher dans cette voie, tu peux essayer avec l'autre méthode (elle n'utilise pas de process en fond de tâche) et jouer sur le délai de reconnection. Les autres pistes pourraient venir à mon avis de la connexion Wifi, du client torrent ou du service VPN : - Pour la connexion Wifi, j'ai entendu dire que le peer-to-peer n'est pas très bon. J'ai eu à une époque un fournisseur internet wifi qui interdisait de faire du peer-to-peer sur son réseau (sinon ça le faisait planter). De cette époque, j'ai pris l'habitude de faire du warez, je n'utilise les torrents que de façon ponctuel, donc je n'ai pas trop d'expérience à ce sujet. Tout ce que je peux te dire, c'est que je ne rencontre pas ce problème avec les boards warez et JDownloader. Pour explorer cette piste, il faudrait que tu es la possibilité de tester la différence avec une connexion filaire, ou consulter les forums sur les torrents et le Wifi. - Pour le client torrent, peut-être que le fait d'avoir des coupures le perturbe. Une possibilité pourrait être de le relancer quand tu observes une diminution de débit et voir si ça change quelque chose. Ou voir si tu observes aussi sur cette baisse de débit sur un test de bande passante (avec speedtest.net, par exemple). - Le fournisseur VPN peut-être aussi offre de moins bon service au bout d'une certaine durée de connexion. Là, si tu as la possibilité d'essayer une autre connexion VPN pour voir la différence. Ou provoquer volontairement les coupures VPN depuis l'applet du Network Manager pour voir si ce sont bien les coupures qui font baisser le débit. En gros, essaye de voir, et si c'est possible, si ton problème persiste : - sans vpn (mais ça, tu le sais surement déjà) - ou avec une connexion réseau filaire - ou en redémarrant le client torrent - ou en redémarrant le Network Manager (sudo service network-manager restart, NetworkManager pour les versions d'ubuntu plus anciennes) - ou en espaçant les délais entre les reconnections - ou avec un autre fournisseur VPN (personnellement, j'utilise HideMyNet, un peu payant) ça t'aidera peut-être mieux à localiser ton problème qu'en redémarrant le pc. Bonne chance ! Dernière modification par coredump (Le 02/01/2010, à 12:14) Hors ligne ElFabio Re : Connexion VPN automatique (NetworkManager) Déjà je te remercie pour avoir pris autant de temps pour me répondre, je vais essayer de reparcourir les pistes que tu as mentionné mais, effectivement, ce sont également sensiblement les mêmes que celles que j'avais regardé jusque-là. Mes premieres impresssions tendraient à confirmer les tiennes, le probléme semblerait effectivement provenir davantage de la connexion en Wifi, puisque j'utilise également tes scripts sur un PC fixe en ethernet avec le même provider VPN, et je ne rencontre pas ce genre de problème. J'avais déjà éliminé la piste du provider VPN dont je suis personnellement trés satisfait (il s'agit de TorrentFreedom), et d'ailleurs le fait qu'en redémarrant le PC je retrouve un débit normal tend également à confirmer que le pb ne vient pas de là. D'ailleurs je n'ai pas, comme tu le mentionnes pour toi, de problémes de connexion particulier au VPN, la connexion se fait trés rapidement, par contre, en revanche, il se produit des déconnexions au VPN de façon trés régulière voire périodique (presque toutes les 30mn), ce qui me fait également pencher vers un probléme WiFi ou plutôt de passerelle (Livebox dans mon cas actuel) voire de FAI... Je vais par contre également regarder du côté de ton 2eme script pour voir si j'observe des changements. En tout cas, merci pour ton temps et ta réponse, ca me permet de disposer d'un 2eme avis "éclairé" sur le sujet ! Hors ligne hybernatus Re : Connexion VPN automatique (NetworkManager) Fiou... merci pour ce script et tout ton boulot, je me suis abonné hier à Ipredator (ayant trouvé un super tuto, et n'y connaissant rien en réseaux, j'ai fait au plus simple ^^ ) et j'ai remarqué qu'il se déconnecte de temps en temps... ce qui est un peu c*n tout de même quand on veut une connexion sécurisée et anonyme je trouve J'essairai d'appliquer ça dès que je trouve la motiv merci ! Mes photos: http://www.hyb.me/photos Hors ligne ElFabio Re : Connexion VPN automatique (NetworkManager) Salut coredump, je reviens juste vers toi pour te faire un petit debriefing : ta deuxiéme solution (via connection-service) a résolu mes problémes de "coupure" intempestive et réguliére du VPN, je l'ai un peu aménagé à ma sauce, notamment pour disposer d'une connexion 'manuelle' au VPN et non un lancement automatique au démarrage, mais, que ce soit en Wi-Fi ou en Ethernet, cela fonctionne maintenant parfaitement. Donc encore merci pour ton travail, et bonne continuation ! Hors ligne Papou Re : Connexion VPN automatique (NetworkManager) Merci Coredump pour ces scripts très utiles. La reconnection automatique c'est nickel .... sauf quand c'est le modem qui décroche de l'ADSL et met un peu de temps pour redémarrer, la reconnection au VPN n'aboutit alors pas et l'accès internet se retrouve en direct quelques secondes plus tard. Serait-il possible de faire encore mieux ? Un pour tous et tous pour un, les petits ruisseaux feront les grandes rivières ... Hors ligne coredump Re : Connexion VPN automatique (NetworkManager) Tout d'abord merci ElFabio pour ton retour d'expérience. A mon avis : - la première solution (en python) est plus fiable, car le service tourne en tâche de fond et ne dépend pas de la connexion de l'utilisateur, mais plus complexe et donc plus difficile à maintenir, - la deuxième (en shell) est plus simple et plus clair, et donc plus adaptable et plus facile à maintenir, et par expérience marche bien. Et en définitif, je conseillerai donc plutôt celle-ci. Pour rappel, cette méthode est décrite dans le post #15 avec le script "connection-service" de la fin du poste #11. (Si je trouve un peut de temps, j'en ferais bien la synthèse dans un tuto ...) Ensuite par rapport à Papou, si tu veux que le vpn se reconnecte quand ta connexion adsl se reconnecte (j'imagine que tu utilises la deuxième méthode et qu'il ne s'agit pas d'une connexion adsl pppoe ?), tu peux essayer d'ajouter cette ligne dans le script /etc/NetworkManager/dispatcher.d/02-loop-vpn : [ "$2" = "up" ] && vpn-autostart (Pour voir si ça marche, tu peux essayer en redémarrant à la main ton modem en cours de connexion.) Dernière modification par coredump (Le 18/01/2010, à 15:45) Hors ligne Papou Re : Connexion VPN automatique (NetworkManager) coredump, Merci pour ta réponse. j'utilise la deuxième méthode et il s'agit d'une connexion adsl pppoe. L'inconvénient d'ajouter la ligne "[ "$2" = "up" ] && vpn-autostart" est qu'il devient alors impossible de déconnecter volontairement le VPN pour les applications qui ne le supporte pas (sauf a écrire un script de déconnexion volontaire qui va déplacer le fichier 02-loop-vpn en dehors de dispatcher). D'autre part, il me semble avoir remarqué que le problème est que la connection VPN échoue parfois (timeout d'environ 10 sec ? ) et qu'il n'y a alors pas de deuxième essai. Un pour tous et tous pour un, les petits ruisseaux feront les grandes rivières ... Hors ligne
Setting Up Your Own PyPi Server Ever had problems with PyPi being unreachable? Dislike dealing with requirement.txt files just to support a git repository? For a low low price of FREE, and an hour of labor, get your very own PyPi server and solve all of your worries! Set up Chishop We're going to jump right into this one. Start by setting up Chishop. Currently the best way is to do so using the DISQUS fork as it contains several fixes. Expect to see all of the hard work in the various forks merged upstream as soon as we get some proper docs going. Follow the instructions in the README to configure Chishop, and your PyPi index. Now you're going to want to tweak some things that are on by default. For starters, you're probably going to want to proxy the official PyPi repository, and this can be done by enabling a simple flag in your newly created settings.py: DJANGOPYPI_PROXY_MISSING = True There are many other configuration options, but you're going to have to read the source for those. Configure PIP/Setuptools/Buildout Now that you've got a sexy PyPi server up and running, you'll probably want to configure the default index locations for your package managers. It took me a bit of Googling but then I stumpled upon an awesome post by Jacob Kaplan-Moss about dealing with PyPi when it goes down, which describes procedures for configuring PyPi mirrors. Let's start with pip, which stores its configuration in ~/.pip/pip.conf: [global] index-url = http://my.chishop/simple Next up, setuptools, located in ~/.pydistutils.cfg: [easy_install] index_url = http://my.chishop/simple And finally, if you use buildout, tweak your buildout.cfg: [buildout] index = http://my.chishop/simple Use It Now that you have a fully functioning PyPi, kill off your requirements files and build a real setup.py. Hopefully as a bit of inspiration, here's a snippet from Sentry's: #!/usr/bin/env python try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages tests_require = [ 'django', 'django-celery', 'south', 'django-haystack', 'whoosh', ] setup( name='django-sentry', version='1.6.8.1', author='David Cramer', author_email='[email protected]', url='http://github.com/dcramer/django-sentry', description = 'Exception Logging to a Database in Django', packages=find_packages(exclude="example_project"), zip_safe=False, install_requires=[ 'django-paging>=0.2.2', 'django-indexer==0.2.1', 'uuid', ], dependency_links=[ 'https://github.com/disqus/django-haystack/tarball/master#egg=django-haystack', ], tests_require=tests_require, extras_require={'test': tests_require}, test_suite='sentry.runtests.runtests', include_package_data=True, classifiers=[ 'Framework :: Django', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Operating System :: OS Independent', 'Topic :: Software Development' ], )
AnsuzPeorth [HtmlDesktopTools] Tout pour votre bureau en HTML5/JS/CSS3 Bjr, N'ayant pas trouvé une taskbar qui me convienne, j'ai codé, pour le fun, une taskbar html. Plutot que de me faire juste ma taskbar, j'ai plutot développé un outils qui permet de faire ses widgets en html pour le bureau, dont ma taskbar. Ce projet est en cours de développement, ckdevelop s'en sert pour refaire son bureau fleex, ca qui me permet d'avoir qqles retours. Je post donc ce soft en esperant avoir d'autres retours, d'autres idées qui permettrait d'améliorer l'ensemble. Juste un peu de connaissances en html/css/js, une pointe de bash ou de python pour rendre le tout dynamique, suffit. Il tourne depuis un moment chez moi, et pas de gros bug trouvé. Je cherche également une 'super' idée de menu, dans l'exemple fourni (mon bureau actuel), le menu est gnome-like, pas top ... L'exemple fourni est constitué de 4 widgets, taskbar, menu, bottom (moniteur systeme) et background (2 bureaux virtuel nécessaires). Il a été fait sous et pour gnome, les dameons dbus utilisés (pour le son, montage, démontage partition, extinction) sont des daemons lancés que sous gnome (à ma connaissance). La norme freedesktop est respecté. Un problème de gestion de bureaux virtuel sous openbox n'est pas résolu (pas essayé encore !) Si vous voulez essayé sous d'autres WM, il faudra commenter certaine ligne dans le fichier HtmlDesktopTools.ini. Des readme sont dans chaque dossier pour expliquer le fonctionnement. Il suffit de lancer HtmlDesktopTools.py en console (de préférence pour y voir ce qui se passe), kill via moniteur systeme obligatoire ou via console pkill -f HtmlDesktopTools.py Archive: Premier exemple: (plus simple) http://gwebradio.googlecode.com/files/ConkyLike.tar.gzDépendances: python-webkit Cette exemple se passe des daemons gnome et wnck, il est plus simple que le suivant. HDT est plus à jour dans cette archive. Il est composé d'une simple barre de lancement et d'un conky-like. Deuxième exemple: http://gwebradio.googlecode.com/files/H … 0.1.tar.gzDépendances: python-webkitDépendances applets: taskbar: python-wnck device: dbus Udisks session: dbus ConsoleKit, UPower, DisplayManager, SessionManager son: dbus org.ayatana.indicator.sound Sous ubuntu (gnome), il suffit d'ajouter python-webkit et python-wnck. Il n'est pas conseillé de lancer plusieurs HDT, il suffit de coller les widgets voulus dans leur dossier et de renseigner le HtmlDesktopTools.ini README principal: Cette outil sert à afficher des widgets Html sur le bureau qui permettent le lancement de commandes système. Une communication inter-widgets est établie grace à des commandes spéciales, des applets python ou via dbus depuis n'importe quelle autre application. Il est possible de se servir de HtmlDesktopTools pour afficher une simple boite avec un peu de code html venant du web (site jamendo par exemple), de se faire une Deskbar, des panels, un bureaux ou tout autre possibilité offerte par les applets. Le moteur de rendu web embarqué est webkit, html5 et css3 supporté. Applets/tools disponibles par défaut: --------------------------------------- Applets: Taskbar: Gère les fenêtre ouvertes et les bureaux. SoundControl: Gère le son SessionManager: Gestion de la session (shutdown, reboot, etc, etc) MonitorSyteme: daemon qui surveille usage cpu, reseau et memoire DbusDeviceDaemon: Gestion des disques durs/amovibles (liste/montage/démontage) Tools: getdesktopentries.py: module ou executable python pour récupérer les entrées desktop du système. get_web_info.sh: petit sh pour surveiller état de la poubelle, ping et ip web (c'est un exemple d'utilisation dbus et daemon d'un widget) Fonctionnement: ----------------- Chaque widget html, doit avoir au minimum, un fichier HTML et un fichier ini portant le même nom. L'appel à une commande spéciale ou lancement d'une application depuis un widget, se fait par de simple liens html clickés par l'user ou simulé par javascript. Ces liens auront un prefixe spéciale pour chaque action souhaité. Chaque widget peut lancer des executables avant d'ouvrir sa page html, lancer des daemons une fois la page chargé ou encore importer des applets python ( à renseigner dans le fichier ini du widget correspondant ). Chaque widget a lancer devra être renseigner dans le HtmlDesktopTools.ini Communication: ---------------- Les commandes spéciales: Ce sont les préfixes qu'il faudra utiliser pour les liens html. Par exemple, pour lancer firefox depuis un widget: <a href="execute:Firefox">Lancer moi</a> Dbus service: Chaque widget lance un service dbus qui porte son nom. Il est possible d'appeler des fonctions javascript du widget via cette interface. Les applets python: Ils sont lancés en arrière plan, ils permettent une communication dans les 2 sens. Ils sont requis pour des taches complexes ou pour agir selon les actions user. Par exemple, l'applet MonitorSysteme refresh les données toutes les secondes, il aurait été possible de faire un daemon bash qui utilise dbus pour refresh le html, mais la consommation en ressource système serait énorme (lancement de dbus-send chaque secondes), alors qu'un applet modifie directement le html via webkit. Les applets sont aussi nécessaires si ils ont besoin d'agir selon les actions user, comme la Taskbar par exemple. Commandes spéciales: ------------------------ execute: [ execute:commande ] Lance une application système. geometry: [ geometry:width height x y ] Déplace est redimensionne le widget. Cette commande sera souvent utilisé, gtk ne redimensionne et ne place pas automatiquement sa fenêtre selon le html affiché dans webkit. communicate: [ communicate:themeName:JScommande ] Appel des fonctions javascript d'autres widgets. ex: communicate:AnsuzBottom:modifBackground('red') loaduri: [ loaduri:themeName:FileName ] Charge un fichier html d'un widget. Le fichier html chargé devra se trouver dans le dossier du widget correspondant. ex: loaduri:AnsuzBottom:index1.html applet: [ applet:themeName:AppletName:AppletCommande ] Appel une commande d'un applet. Le widget correspondant aura évidemment indiqué l'applet à charger dans son environnement dans son fichier .ini. Voir les commandes disponibles pour chaque applet dans leur README. ex: applet:AnsuzMenu:DbusDeviceDaemon:device_clicked_cb(arg) cmdgtk: [ cmdgtk:themeName:commande ] ex: cmdgtk:AnsuzBottom:show Agit directement sur gtk via qqles commandes: show Affiche la fenêtre à l'écran hide Cache la fenêtre above Force la fenêtre à rester derrière (desktop) unabove Annule above below Force la fenêtre à rester au premier plan (popup) unbelow Annule below present Affiche la fenêtre, elle sera unminimise si besoin et raise sur le bureau actuel. Dbus Service --------------- service: com.ansuzbus.HtmlDesktop path: /com/ansuzbus/HtmlDesktop/ThemeName cmd: com.ansuzbus.HtmlDesktop.Send Arguments: string (FonctionJS), array:string (liste d'options à passer à la fonction JS) Exemple: (voir ./AnsuzBottom/get_web_info.sh) ThemeName: AnsuzBottom. Fonction JS a appeler: modifyWebInfo(ping, ip) args: ping (0.025), ip (178.05.05.05) dbus-send --session --print-reply --dest=com.ansuzbus.HtmlDesktop \ /com/ansuzbus/HtmlDesktop/AnsuzBottom com.ansuzbus.HtmlDesktop.Send \ string:'modifyWebInfo' array:string:"0.025","178.05.05.05" Les applets python --------------------- Voir README du dossier applets. PS: Petite précision, les html/JS à modifier sont dans le dossier widgets ! Dernière modification par AnsuzPeorth (Le 10/09/2011, à 13:55) Hors ligne CKDevelop Re : [HtmlDesktopTools] Tout pour votre bureau en HTML5/JS/CSS3 parfait Ansuz, c'est cool, ta déposé HDT, je vais pouvoir faire des retour sans avoir à attendre de pouvoir te choper en ligne Home -> Debian Jessie & Home server -> Debian Wheezy Office -> Ubuntu 14.04 & Office server -> Ubuntu 12.04 Embedded -> Raspbian / Debian Wheezy Hors ligne AnsuzPeorth Re : [HtmlDesktopTools] Tout pour votre bureau en HTML5/JS/CSS3 parfait Ansuz, c'est cool, ta déposé HDT, je vais pouvoir faire des retour sans avoir à attendre de pouvoir te choper en ligne Pour infos, il y a qqles différences par rapport à la version que tu as: - plus de zombie - moins d'icone pour la taskbar (je prends celles des classApp) - drag&drop - Gestion des erreurs dbus (si pas de bus lancé) J'attends de voir ton fleex avec impatience ! PS: je gratte pas dessus en ce moment, mais je vais m'y remettre ! Ou pas Hors ligne CKDevelop Re : [HtmlDesktopTools] Tout pour votre bureau en HTML5/JS/CSS3 pareille Ansuz, j'ai pris du recul pendant la fin des vacances, car bon les gosses prime là je retourne dessus dans la semaine, mais bon j'ai quand même bien regardé ta source et je commence à me repérer, ce qui est déjà pas mal bon je t'avouerais avoir du mal avec xdg, qui est plus difficile à prendre en main que Gnome-menu, mais ta raison à 100% je vais généraliser au maximum fleex pour éviter des conflits bidon en tous cas je me répète mais ta bien fait de poster ton moteur HDT ++ Dernière modification par CKDevelop (Le 05/09/2011, à 14:59) Home -> Debian Jessie & Home server -> Debian Wheezy Office -> Ubuntu 14.04 & Office server -> Ubuntu 12.04 Embedded -> Raspbian / Debian Wheezy Hors ligne AnsuzPeorth Re : [HtmlDesktopTools] Tout pour votre bureau en HTML5/JS/CSS3 Bjr, J'ai un peu modifier HDT et un exemple plus simple ... Ca risque de moins effrayer ceux qui veulent se lancer (premier post modifié) Dernière modification par AnsuzPeorth (Le 10/09/2011, à 13:56) Hors ligne Linux64 Re : [HtmlDesktopTools] Tout pour votre bureau en HTML5/JS/CSS3 Excellent, je vais suivre de prêt Ca fonctionne avec Gnome-shell ? Serveur : Debian Lenny | PC : Ubuntu 10.10 | Smartphone : Maemo5 (basé sur Debian !) Hors ligne AnsuzPeorth Re : [HtmlDesktopTools] Tout pour votre bureau en HTML5/JS/CSS3 Excellent, je vais suivre de prêt Ben ca ne va plus trop bouger je pense, pas bcp de monde derrière. En l'état, il fait ce que je veux, j'ai ma taskbar, mon menu, mes multi-bureaux et mes infos sytemes ... Le "moteur" est ok, ca tourne depuis pas mal de temps, sans soucis. Il faut juste faire des html/JS à son gout, c'est tout ! Ca fonctionne avec Gnome-shell ? Ben c'est codé pour gtk2. Je ferais une version gtk3 pour la prochaine LTS. (mais devrait pas avoir trop de taf pour modifier le tout). Donc si t'es sous gtk3 et que tu n'as pas les libs gtk2, ca n'ira pas. Comme je suis sous gtk2 et que j'ai la flemme d'upgrade maintenant, faudra attendre le moi avril. Hors ligne n3o51 Re : [HtmlDesktopTools] Tout pour votre bureau en HTML5/JS/CSS3 excellent du as dev d'autre widget ? J'ai un bug sur le portable mais c'est simplement que mon ecran sur le portable est plus petit.Par contre j'ai l'impression que le multi bug sans compiz activé Dernière modification par n3o51 (Le 06/02/2012, à 19:53) Welcome to the real world ________________________________ Hors ligne AnsuzPeorth Re : [HtmlDesktopTools] Tout pour votre bureau en HTML5/JS/CSS3 Non, j'ai pas dev d'autres widgets, pas le temps/envie ... L'exemple 2 est mon bureau depuis, et j'ai pas de soucis particulier (me suis même trop bien habitué à ma taskbar, j'ai pas trouvé d'équivalent ...) Pour la taille, il faut aller gratter dans les fichiers de config (bien que ce soit automatique, mais certain widgets sont fixe...) Et le multibureaux, doit surement poser soucis avec unity ou gnome-shell, c sur ... C'est dev sous gtk2 et gnome2, je n'y ai pas gratté depuis. J'ai pas de retour d'users, donc pour débugger, c'pas simple ! Hors ligne n3o51 Re : [HtmlDesktopTools] Tout pour votre bureau en HTML5/JS/CSS3 Ok Pour le multi je clique sur les flèches et rien ne ce passe alors qu'avec compiz sa fonctionne mais pas avec le composite de metacity Welcome to the real world ________________________________ Hors ligne AnsuzPeorth Re : [HtmlDesktopTools] Tout pour votre bureau en HTML5/JS/CSS3 Ok Pour le multi je clique sur les flèches et rien ne ce passe alors qu'avec compiz sa fonctionne mais pas avec le composite de metacity J'avais rencontré ce soucis uniquement sous openbox (qui ne gère pas les bureaux comme tout le monde !!!) Hors ligne abelthorne Re : [HtmlDesktopTools] Tout pour votre bureau en HTML5/JS/CSS3 Je sais pas si quelqu'un a déjà posté ça ni si c'est le sujet le plus approprié mais je viens de tomber sur une vidéo de Madbox où il montre une bureau HTML qui tourne sur SliTaz : http://www.youtube.com/watch?v=FjjbJ0sfAME Hors ligne AnsuzPeorth Re : [HtmlDesktopTools] Tout pour votre bureau en HTML5/JS/CSS3 Je sais pas si quelqu'un a déjà posté ça ni si c'est le sujet le plus approprié mais je viens de tomber sur une vidéo de Madbox où il montre une bureau HTML qui tourne sur SliTaz : http://www.youtube.com/watch?v=FjjbJ0sfAME Hummm, ca ressemble à fleex tout ça ... Faut dire que ca vient de adeskbar, et adcomp avait participé au début de fleex. Par contre, l'outils que je propose c'est pas la même chose, cet outils permet de faire ce genre de bureau, en exemple, j'ai mis mon bureau, mais tout le monde peut faire le sien, et bien plus, html/css/bash/python/JS ... J'inclus les daemons dbus system (montage, démontage, extinction ..), plus mes propres daemon, ca permet une communication complète. Hors ligne cedric_neo Re : [HtmlDesktopTools] Tout pour votre bureau en HTML5/JS/CSS3 bonjour , j'ai été très intéressé par le concept et l'idée . Mais je ne trouve aucune information concernant la licence ? l'auteur pourrait il la préciser ? merci par avance.. cédric Hors ligne AnsuzPeorth Re : [HtmlDesktopTools] Tout pour votre bureau en HTML5/JS/CSS3 bonjour , j'ai été très intéressé par le concept et l'idée . Mais je ne trouve aucune information concernant la licence ? l'auteur pourrait il la préciser ? merci par avance.. cédric C'est un oubli, c'est la licence gpl. Je t'ai répondu au mail. Je modifierai dès que je serai rentré chez moi ! Hors ligne cedric_neo Re : [HtmlDesktopTools] Tout pour votre bureau en HTML5/JS/CSS3 bonjour à tous, j'ai étudier plus en profondeur le fonctionnement des HtmlDesktopTools sur lesquels s'appuye mon projet. il me reste cependant quelques question ou incompréhension. tout d'abord, je pense avoir compris que le fonctionnement du système d'appel de fonction distante lié à commlink est dépendant de cette ligne de code self.webview.connect("navigation-policy-decision-requested", self.nav_request) présente dans la définition de la class MakeWindows de la lib widgets. Cela semble lier l'évènement click souris à l'exécution de la fonction nav_request. Cependant je ne comprend pas comment l'on récupère les paramètres de la requête notamment l'uri. Dans la ligne de cote précédent, aucun paramètres n'apparait. D'autre part, il me semble comprendre que dans la définition de la fonction nav_request le morceau de code getattr(self, fonction)(uri, name) permet l'exécution d'une des fonctions définies juste après dans la définition de la class widgets du fichier du même nom. Si fonction contient execute alors la fonction execute est appelé avec les paramètres uri et name présent dans l'uri fourni par l'appel a commlink dans le fichier html. Cependant je ne comprend pas le fonctionnement de cet appel getattr sur l'exécution de la fonction execute par exemple. voilà mes question pour le moment. Je pense que pour bien comprendre les dysfonctionnements futur de mes appels aux différent éléments et programmes externes, il me faut mieux comprendre le fonctionnement interne du système. merci par avance et bonne et belle journée ensoleillée (on peut enfin ranger les palmes). cédric Hors ligne AnsuzPeorth Re : [HtmlDesktopTools] Tout pour votre bureau en HTML5/JS/CSS3 Bjr, J'ai pas pu répondre plus vite, dsl, j'étais pas la. Je ne sais pas si ça va t'aider de comprendre ma façon de faire, mais bref ... Cependant je ne comprend pas comment l'on récupère les paramètres de la requête notamment l'uri. Dans la ligne de cote précédent, aucun paramètres n'apparait. La ligne connecte le signal, les paramètres sont envoyés par webkit. Cependant je ne comprend pas le fonctionnement de cet appel getattr sur l'exécution de la fonction execute par exemple. getattr fait comme un eval, il remplace une suite de if elif ... J'aime bien procédé comme ça, c'est plus propre, mais plus galère à débugguer ! Tu peux voir que je découpe l'uri pou en extraire la commande (execute par exemple), et donc j'appelle la fonction execute via getattr. Cette fonction appelle une autre fonction en arriere plan, qui lance une commande systeme. Les autres fonctions (geometry, communincate, etc,etc) sont 'spécialisées', elles agissent sur le soft directement (les differents widgets). Je ne sais pas si j'ai été clair !!! Mais bon, c'est pas vital de comprendre cette partie, logiquement, tu n'a rien à y faire PS: tu peux virer tous les print dans le code, je passe par la fonction DEBUG pour le retour dans le terminal, lorsque ton soft sera ok, il te suffit de passer la variable debug à False pour ne plus avoir de sortie vers le terminal. C'est pas encore très propre le code, vu que personne n'utilise ce soft, je n'y étais pas retourné. Mais lorsque ton soft sera ok, je mettrais au propre (le code ne changera pas, juste les détails comme les print inutiles seront enlevés ou remplacer les tab par des espaces, enfin, des détails ...) Hors ligne cedric_neo Re : [HtmlDesktopTools] Tout pour votre bureau en HTML5/JS/CSS3 Merci pour tes réponses, ça confirme ce que je pensais avoir compris... Je suis pas encore un spécialiste de python (je suis un programmeur java à la base. Mais python commence à bien me séduire). sinon je sais que c'est pas indispensable de connaitre le fonctionnement interne pour l'utiliser mais bon on se refait j'aime comprendre comment ca fonctionne ca me rassure. Et puis je compte bien participer ensuite à l'évolution du fonctionnement, peut être l'ajout de petite chose qui me manquerons un jour et donc récourir au fonctionnement natif. Même si tu penses avoir fait un système uniquement pour ajouter une barre ou un background moi j'y vois un support pour développer des application performante en python avec interface en html5. je pense que c'est une voix prometeuse et en plus en libre. Je compte pas m'arrêter à ma première utilisation de ce système. D'où ma question sur la licence. La en ce moment je me bat avec ayatana (enfin avec son absence de ma kubuntu). Merci je reviens vite avec plein de nouvelles questions. bonne journée, cédric Hors ligne AnsuzPeorth Re : [HtmlDesktopTools] Tout pour votre bureau en HTML5/JS/CSS3 Et puis je compte bien participer ensuite à l'évolution du fonctionnement, peut être l'ajout de petite chose qui me manquerons un jour et donc récourir au fonctionnement natif. les applets sont là pour ça, ajouter des fonctionnalités, accessible depuis n'importe quel widget ... Même si tu penses avoir fait un système uniquement pour ajouter une barre ou un background moi j'y vois un support pour développer des application performante en python avec interface en html5. je pense que c'est une voix prometeuse et en plus en libre. Nop, ce n'est pas juste pour faire une barre et un background, mais j'ai mis en place un systeme pour faire ce que l'on veut, avec une communication interne de tous les modules et widget. On peut faire des applis avec interface html5, mais on peut mixer avec du bash, du python ou autre ... Enfin, on peut en faire ce que l'on veut ! html5,ccs3, JS, bash, python, qui communique dans tout les sens, avec tout ça, dur d'être limité ! Je compte pas m'arrêter à ma première utilisation de ce système. D'où ma question sur la licence. Si tu changes de nom et que tu respectes gpl, pas de soucis, peut être juste signaler que c'est un fork de HtmlDesktopTools, par principe ... Hors ligne cedric_neo Re : [HtmlDesktopTools] Tout pour votre bureau en HTML5/JS/CSS3 pas de problème pour signaler que c'est un fork de HtmlDesktopTools Le principe du libre est de toujours dire qui a fait quoi. Pour le moment, j'embarque HtmlDesktopTools tel quel a un détail prêt à savoir j'ai rajouté une partie quit (que je supprimerai après ) dans le code suivant def cmdgtk(self, uri, name): self.debug('[ NAVIGATION REQUESTED ] -> gtk: -> %s' % uri) uri = urllib.unquote(uri) pr, name, cmd = uri.split(':') if cmd == 'show': cmd = 'self.master.%s.window.show()' % name elif cmd == 'hide': cmd = 'self.master.%s.window.hide()' % name elif cmd == 'above': cmd = 'self.master.%s.window.set_keep_above(True)' % name elif cmd == 'unabove': cmd = 'self.master.%s.window.set_keep_above(False)' % name elif cmd == 'below': cmd = 'self.master.%s.window.set_keep_below(True)' % name elif cmd == 'unbelow': cmd = 'self.master.%s.window.set_keep_below(False)' % name elif cmd == 'present': cmd = 'self.master.%s.window.present()' % name eval(cmd) En effet, j'arrive pas a faire fonctionner la fonction mainquit. voilà voilà .... note : je suis en train de voir si on peut s'échanger des flux vidéos avec le systèmes tel quel ou si il faudra lui rajouter quelque chose ou passer par des pipes ou de socket interne ou je ne sais trop quel idée tordue. C'est en ca que je parlais d'évolution. Merci pour toutes ces réponses. Et à bientot pour de nouvelles aventures... cédric Hors ligne AnsuzPeorth Re : [HtmlDesktopTools] Tout pour votre bureau en HTML5/JS/CSS3 Pour le moment, j'embarque HtmlDesktopTools tel quel a un détail prêt à savoir j'ai rajouté une partie quit (que je supprimerai après ) dans le code suivant Pourquoi ajouter une partie quit ? Si tu fait un gtk.mainquit(), tu ne pourras plus le relancer (car les differents widget sont lancés au démarrage, après, ca sera plus possible de les relancer), enfin, si j'ai bien compris ta modification !!! Je suppose que tu veux faire des appli indépendante, comme un environnement normal ? Avec un lancement et une fin (quit). Je n'ai pas codé de la sorte, pour arriver à un truc un peu pret similaire, il faudrait procéder comme suit: Créer un widget qui servira de container, comme une boite de dialogue normal mais vide, et selon l'application, tu charge le html correspondant. Si tu as besoin d'agir selon user, tu crées un applet où les fonctions seront accessibles de partout, mais dans notre cas, nécessaire seulement depuis le html de l'appli en cours. Donc, tu n'as pas besoin de fonction quit, mais tu fais un show ou hide a la place, et tu change le html selon l'appli appelée. Je sais pas si je suis clair .... ? Par exemple, tu veux ajouter un calendrier avec agenda, tu a donc ton widget (boite vide), tu crée un applet calendar où se trouveront toutes les fonctions necessaires, lorsque tu voudra quitter cette appli, un simple hide suffira, si tu dois faire des actions avant de quitter, elles se trouveront dans l'applet. Ensuite, si tu dois appeller une autre application, il suffit de charger le html correspondant et show le widget. Si tu compte avoir bcp d'appli, il faudra peut être que je modifie le code, car actuellement, toutes tes appli seront en mémoires (enfin elles seront importées avec le widget) ... C'est pas terrible, ca sera rapide à l'affichage, mais ca bouffera un peu de ram (bien que les pc de maintenant embarque bcp de ram) ! C'est vrai que j'ai codé ce soft pour avoir un environnement modifiable à souhait, mais pas pour avoir des centaines d'applications qui ne doivent pas être lancé au démarrage, bien qu'il ne faudrait pas grand chose pour y arriver ... Un simple applet qui crée la window gtk et webkit, qu'on pourra lancer et fermer à souhait, à étudier et mettre en place si nécessaire ! note : je suis en train de voir si on peut s'échanger des flux vidéos avec le systèmes tel quel ou si il faudra lui rajouter quelque chose ou passer par des pipes ou de socket interne ou je ne sais trop quel idée tordue. C'est en ca que je parlais d'évolution. Je comprends pas ce que tu veux faire ! Echanger des flux vidéos avec le système ?! PS: tu peux voir dans ma signature si je suis connecté sur la room, ça sera plus simple pour échanger ! A savoir que je ne suis pas tjrs dispo, même si j'apparais connecté ! Hors ligne cedric_neo Re : [HtmlDesktopTools] Tout pour votre bureau en HTML5/JS/CSS3 Tu es hyper réactif dis donc bon la j'suis en train de me prendre la tête avec le bus dbus de gestion du son (ayatana que je pensais crée en installant indicator-sound). tu peux noté que je suis débutant dans le domaine de dbus... je l'ai découvert avec ton projet... si si c'est possible. Pour la fonction quit c'était juste pour faire un bouton qui tu l'appli. J'ai voulu créer ce bouton une nuit. j'ai créé ça je me suis pas encore demandé si ça pouvait être mieux fait. De toute façon , ça doit disparaitre. Mon appli sera lancé au démarrage de la session. Une fenêtre unique. Pour le moment, les parties de l'appli apparaissent et disparaisse grace au display de CSS. (block ou none). Mais je réfléchi à faire maigrir mon fichier html en incluant que le template nécessaire au moment nécessaire avec innerHtml. Oui effectivement mon appli consiste simplifier fortement la présentation et le lancement d'appli adaptée ou développée explicitement pour mon système. Je suis d'accord que unity pourrait peut être le faire mais je voulais pas d'une usine a gaz et j'aime bien tout controler. L'appli principale a pour but d'être modulaire. Donc effectivement je me posais la question de savoir si le chargement de toute les applet au lancement n'allait pas poser problèmes en terme de mémoire (il est prévu que ça tourne sur un pc avec processeur basse consommation AMD E350. Je veux la plus faible conso possible.) L'histoire de la video vient du fait que je veux tenter d'adapter GAJIM (qui est développer en python) pour lui donner une interface intégré au système en cours de développement. L'idée (c'est qu'une préréflexion, la toute prochaine applet en développement étant le client mail, le vidéo tchat passera après) est de faire du code de gajim une applet et de transmetrre le flux vidéo entrant de l'applet vers une fenêtre webkit. De même, le choix du correspondant et de l'activiation ou non de la vidéo, du réglage du micro ect devront être controlé par des bouton de l'interface principale webkit. voilà pourquoi je cherche à échanger un flux vidéo entre une applet et une fenêtre webkit cédric Hors ligne cedric_neo Re : [HtmlDesktopTools] Tout pour votre bureau en HTML5/JS/CSS3 pour info, voilà ce que j'obtiens systèmatiquement. [ DbusActions ][ __init__ ] SessionManager[ SoundControl ][ ERROR ] SoundControl dbus service doesn't exist !!![ DbusActions ][ __init__ ][ SoundControl ] cédric Hors ligne AnsuzPeorth Re : [HtmlDesktopTools] Tout pour votre bureau en HTML5/JS/CSS3 bon la j'suis en train de me prendre la tête avec le bus dbus de gestion du son (ayatana que je pensais crée en installant indicator-sound). C'est du gnome, qui respecte la norme freedesktop, peut être ca t'aideras ? http://www.freedesktop.org/wiki/Softwar … uildDebian mais je voulais pas d'une usine a gaz Pourtant, HDT se pose là comme usine à gaz L'appli principale a pour but d'être modulaire. Donc effectivement je me posais la question de savoir si le chargement de toute les applet au lancement n'allait pas poser problèmes en terme de mémoire (il est prévu que ça tourne sur un pc avec processeur basse consommation AMD E350. Je veux la plus faible conso possible.) Faut relativiser, les applet seront chargés, mais ca bouffe pas non plus de tonnes de ram, ce qui consomme bcp de ram, c'est l'affichage graphique, et ici, on à juste une window, avec webkit, donc ca sera jamais énorme ! L'histoire de la video vient du fait que je veux tenter d'adapter GAJIM (qui est développer en python) pour lui donner une interface intégré au système en cours de développement. L'idée (c'est qu'une préréflexion, la toute prochaine applet en développement étant le client mail, le vidéo tchat passera après) est de faire du code de gajim une applet et de transmetrre le flux vidéo entrant de l'applet vers une fenêtre webkit. De même, le choix du correspondant et de l'activiation ou non de la vidéo, du réglage du micro ect devront être controlé par des bouton de l'interface principale webkit. Gajim utilise aussi dbus, installe d-feet, peut être que dbus te semblera plus clair ! Pour la vidéos conférence, j'y avait pensé m'y coller, mais pas le temps ... Tu compte utiliser koi pour la vidéo ? Perso, je m'étais pencher sur gstreamer qui peut envoyer de la vidéo et du son en udp ou rtscp, doit avoir moyen de se coté là (mais gstreamer, encore un très gros morceau ...) Mais c'est une bonne idée de faire de la videconférence sans devoir installer un tas de soft different, que tout soit simple d'accès à madame michu ... Sinon, pour envoyer de la vidéo vers webkit, un simple lien dans le lecteur html devrait suffire. Hors ligne cedric_neo Re : [HtmlDesktopTools] Tout pour votre bureau en HTML5/JS/CSS3 je trouve pas HDT comme un usine a gaz j'ai mis un peu de temps a m'y mettre parce que j'avais pas programmé depuis pas mal de temps et que j'(apprend python et que je connaisais pas webkit ni les webview.... Mais maintenant ca me semble plutot propre et simple de prise en main. Et ca sépare tres bien le modèle/controleur, de la vue ... Pour ce qui est de la video conférence, je comptais utiliser directement gajim pour faire tout le boulot ... normalement il gere la video conference sur jabber. Même si à ce jour, je n'ai pas encore réussi à le faire fonctionner en vidéo conf depuis ma kubuntu.. Je veux juste refaire l'interface mais garder le gros du boulot qui a été fait sur la vidéo conf dans gajim plutot que réinventer la roue. je regarde ce que tu m'a filé J'ai change mon window-manager pour gnome sur une session mais rien de neuf (je sais démarrer gnome sur une kubuntu faut chercher les emmerdes)... j'installe d-feet et je vois. mais bon il n'ya pas de problème il n'y a que des solutions. Mais bon comme mon client mail a une partie sonore je voudrais que ca tourne. allez j'y retourne cédric Hors ligne
smo Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... ola ok cool je vais regarder ca apres, la j en fais un "normalement" c est un peu (beaucoup...) plus complique pour les ppa j vous tiens au jus ! et whoue si vous avez des idees, hesitez pas hein ... j aimerais bien avoir des visualisations quand c est un son qui est lu a la place du lecteur video pas que ca reste vide en tout cas ! ++ Dernière modification par smo (Le 19/12/2010, à 21:17) ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne smo Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... ola bon j ai rajoute le paquet dans mon ppa ! (GALERE!!!!) infos ajoutées au post 1 faut que je refasse des screenshots... Pensez a faire un sudo python setup.py uninstall avant d installer le ppa ++ Dernière modification par smo (Le 20/12/2010, à 08:24) ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne Merle Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... Pensez a faire un setup.py uninstall avant d installer le ppa Salut j'ai ça quand j'entre la commande : root@marijo-Inspiron-530s:~/gmediafinder# setup.py uninstall setup.py : commande introuvable Hors ligne smo Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... Yup sudo python setup.py uninstall Pour être plus précis ... ++ ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne Merle Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... Pas de veine : root@marijo-Inspiron-530s:~/gmediafinder# sudo python setup.py uninstall running uninstall warning: uninstall: Could not read installed files list .installed_files Hors ligne smo Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... ola non tant mieux c est que t avais rien d installé... tu peux utiliser le ppa sans soucis... ++ ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne Merle Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... Salut j'ai des problèmes avec le moteur tagoo.ru : Quand je fais une première recherche sur "draconian" le logiciel ferme tout seul : tagoo.ru engine selected ** Gdk:ERROR:/build/buildd/gtk+2.0-2.22.0/gdk/gdkregion-generic.c:1110:miUnionNonO: assertion failed: (y1 < y2) je réouvre et je refais la même recherche : julien@marijo-Inspiron-530s:~$ gmediafinder ** Message: pygobject_register_sinkfunc is deprecated (GstObject) /usr/local/lib/python2.6/dist-packages/GmediaFinder/gmediafinder.py:71: GtkWarning: IA__gtk_radio_button_set_group: assertion `!g_slist_find (group, radio_button)' failed self.gladeGui = gtk.glade.XML(constants.glade_file, None ,constants.app_name) tagoo.ru engine selected Unhandled exception in thread started by <bound method GsongFinder.analyse_links of <GmediaFinder.gmediafinder.GsongFinder object at 0xb7778c4c>> Traceback (most recent call last): File "/usr/local/lib/python2.6/dist-packages/GmediaFinder/gmediafinder.py", line 541, in analyse_links self.add_sound(name, link_list[i) File "/usr/local/lib/python2.6/dist-packages/GmediaFinder/gmediafinder.py", line 643, in add_sound img = gtk.gdk.pixbuf_new_from_file_at_scale(os.path.join(self.img_path,'sound.png'), 64,64, 1) glib.GError: Impossible d'ouvrir le fichier « /usr/local/share/gmediafinder/sound.png » : Aucun fichier ou dossier de ce type /usr/local/lib/python2.6/dist-packages/GmediaFinder/gmediafinder.py:228: Warning: unable to set property `text' of type `gchararray' from value of type `GdkPixbuf' gtk.main() Dernière modification par Merle (Le 21/12/2010, à 13:15) Hors ligne smo Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... Yup T as une vieille version ... Refais le sudo setup.py install suivi d' un sudo setup.py uninstall Et réinstalles le paquet Deb du ppa ++ ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne Merle Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... root@marijo-Inspiron-530s:~# cd /home/julien/gmediafinder root@marijo-Inspiron-530s:~/gmediafinder# sudo setup.py install sudo: setup.py: command not found Hors ligne smo Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... Ola 1/ qu est ce que tu fais en compte root? 2/ tu fais sudo python setup.py install et uninstall après T as (j'ai) oublie le python ...;) ++ Dernière modification par smo (Le 22/12/2010, à 02:54) ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne bargeot5999 Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... ça a l'air bon comme petit soft....bonne continuation Hors ligne smo Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... hello petite maj avec differents petits fix... surtout pour Windows mais aussi ubuntu juste a mettre a jour par apt/synaptic etc... le soft marche nickel sur windows aussi! (apres 1 heure pour installer l environnement python/gtk etc... calvaire) sauf la video de youtube qui s affiche sur tout le gui, bug de gtk apparemment sinon ca roule...) ++ Dernière modification par smo (Le 27/12/2010, à 06:16) ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne smo Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... ola bon j ai refait un deb (en cours sur launchpad) - ajout des visualisations sur les sons - qqes fix - malheureusement tagoo.ru est down !!! donc retiré ... je vais chercher d autres sites plus tard pour voir... assurez vous d avoir libvisual-0.4-plugins et libvisual-0.4 installé ( j ajouterais au prochain deb...) a+ ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne frenchy82 Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... Salut smo, En faisant un git pull je n'ai pas de mise à jour. Tu ne passes plus par git ? Hors ligne smo Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... Ola Yup j ai oublie de maj le git j te fais ça apres ++ ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne frenchy82 Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... Ok merci, cela marche super Juste un petit truc : je ne suis pas sur que quand tu quittes GMF il libere la mémoire. Il semblerait que le processus python reste actif avec aux alentours de 80 Mo mais je peux me tromper Un petit bouton pour arrêter la recherche serait un petit plus PS: Je viens de voir cette news sur le site de Korben. Non pas que le soft soit intéressant par rapport au tient (il en est bien loin), mais le site à pas mal de mp3. Hors ligne smo Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... ola frenchy - je n ais pas remarqué ce problem de sortie avec python, je vais regarder de plus pres mais ca m etonnerait (sauf plantage) - grooveshark c est mort, c est du flash et l api est assez obscure/introuvable j utilise que des sites avec des liens directs vers les mp3 ou des api au point comme youtube un bouton arreter la recherche ? pour youtube ? pour le soft, y a 3 soucis... 1/ si j utilise playbin2 on a l affichage de la duree du morceau qui marche nickel mais pas de visualisations du tout... 2/ si j utilise playbin 1 on a les visualisations mais la duree du morceau et donc la progression ne s affiche pas tout le temps, RELOU actuellement j ai donc laissé sur playbin... 3/ pour dilandau et l ajout d autres moteurs et les problemes de parsing de page html, ca vient de beautifulsoup 3.1 qui a ete (betement pour moi) mis dans maverick voir lucid alors qu il est fait pour python3 que pas grand monde utilise encore et ca fou le bordel, c est de la que viennent les soucis de lecture des pages html !!! je suis repasse en 3.0.8 et tout marche nickel mais des que je vais faire un apt-get upgrade y va me remettre la 3.1, donc faut que je cherche un moyen d interdire l installation de la version 3.1 et force la 3.0.8 depuis mon ppa ou truc du genre... voila pour les infos, j ai rajoute un moteur mais je ne posterais plus de maj tant que ces soucis ne seront pas regles ++ ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne smo Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... solution 1: j ai testé la version 3.2 qui remarche correctement (debile...) du coup je fais mon propre paquet deb de cette librairie dans mon ppa comme ca tout le monde pourra l avoir et voila edit: bon cool, ca marche pepere et ca prend le dessus sur le paquet ubuntu comme il se doit et ca corrige donc le plus gros bug du soft... du coup je post une maj avec un nouveau moteur, iwantmuzik.com si vous trouvez des sites avec des mp3 en lien direct postez les !!! reste a voir cette histoire de playbin/playbin2 ... ++ Dernière modification par smo (Le 30/12/2010, à 04:13) ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne frenchy82 Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... Salut, Je viens d'installer gmf par le depot. Aucun probeme avec l'installation mais par contre j'ai bien un soucis de processus qui ne se ferme pas. Je lance gmf, je le ferme par la croix et j'ai bien un processus gmf qui reste actif. Si je le relance j'ai du coup un 2eme processus actif et ainsi de suite. Je ne sais si quelqu'un d'autre peut le confirmer? EDIT : si je lance gmediafinder par la console ** Message: pygobject_register_sinkfunc is deprecated (GstObject) /usr/lib/pymodules/python2.6/GmediaFinder/gmediafinder.py:73: GtkWarning: IA__gtk_radio_button_set_group: assertion `!g_slist_find (group, radio_button)' failed self.gladeGui = gtk.glade.XML(constants.glade_file, None ,constants.app_name) ^CTraceback (most recent call last): File "/usr/bin/gmediafinder", line 26, in <module> gmediafinder.GsongFinder() File "/usr/lib/pymodules/python2.6/GmediaFinder/gmediafinder.py", line 242, in __init__ gobject.MainLoop().run() KeyboardInterrupt Le "KeyboardInterrupt", c'est parce que je dois faire un ctrl C pour reprendre la main sur la console après avoir quitté gmf en sachant que les lignes Traceback (most recent call last): File "/usr/bin/gmediafinder", line 26, in <module> gmediafinder.GsongFinder() File "/usr/lib/pymodules/python2.6/GmediaFinder/gmediafinder.py", line 242, in __init__ gobject.MainLoop().run() apparaissent apres le controle break Dernière modification par frenchy82 (Le 30/12/2010, à 09:00) Hors ligne smo Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... Ola Ok frenchy merci pour le retour je regarde ça en détail ce soir ++ ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne smo Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... ola bon je viens de faire un push dans le git et un nouveau deb est en cours, c est la fete!!, au menu : - bug de la barre de progression et recuperation de la durée du morceau corrigé (cool!!) et ca fixe le probleme de bloquage du curseur quand on avance/recule dans le son par la meme occasion! - bug de sortie du soft corrigé aussi j avais pas fait gaffe... merci frenchy pour le retour ! - fix sur l activation des options loop et continue, ca ne marchait pas correctement... - tagoo.ru reouvert donc remis en place !!! (cool) - j ai aussi reorganisé chouilla la position des boutons dans le gui, j attend vos avis la dessus...!! please !! voila, pour moi en gros y a plus de bug ! hormis quelques warnings... ! j ai passé le bouzin en version 0.2 (faut que je fasse un about dialog quand meme..) bon reveillon a tout le monde ++ Dernière modification par smo (Le 31/12/2010, à 05:05) ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne frenchy82 Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... Tout marche nickel maintenant, félicitation Vraiment, c'est un super soft! Hors ligne frenchy82 Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... Salut smo, J'imagine que le plein ecran s'annonce plutot complexe Tu penses que ce serait faisable d'avoir un bouton "ouvrir la video dans le lecteur video par defaut" Hors ligne smo Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... ola bah je vais bien y arriver y a un ptit truc qui doit m échapper normalement c est tout bête a faire ça me dit pas trop de faire un bouton ouvrir ... Je vous tiens au courant ++ ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne smo Re : Gmediafinder : Youtube/dailymotion/vimeo.. sans flash et bien plus.... re bon ja i pris ca pour un défi frenchy Ajout du mode fullscreen ! suis assez content d moi sur ce coup la ... ptite video de demo : restera pt etre un fonction pour cacher automatiquement le petit player... (la j vois pas comment faire..) creation du deb en cours sur le ppa edit: finalement j ai aussi reussi a cacher le petit player automatiquement pour resumer : - pour entrer en fulllscreen, soit double cliquer dans la video, soit touche f - pour sortir, double clique ou touche echap - par defaut la barre de controle reste affichee, si pas de mouvement de souris pdt 5 sec elle disparait OU simplement mettre la souris tout en bas pour l afficher ou la cacher nouveau deb online sur le ppa, enjoy ++ Dernière modification par smo (Le 08/01/2011, à 04:40) ht5streamer, streaming youtube/dailymotion...: http://forum.ubuntu-fr.org/viewtopic.php?id=1299461 / http://ht5streamer.free.fr ubukey, createur ubuntu customisé: http://forum.ubuntu-fr.org/viewtopic.php?id=360408 tchat: ##ubuntu-fr-geek sur irc (irc.ubuntu.com) ME PAYER UNE BIERE !! :D : http://gtk-apps.org/content/donate.php?content=138588 Hors ligne
Leenuks Impossible de faire apt-get update Bonjour à tous,:) Je suis debutant sous linux, je m'adresse donc à vous pour m'aider. En effet je souhaite utiliser ubuntu pour mettre en place Nagios (c'est mal partie !!):P J'aimerais utiliser la commande apt-get update mais elle me retourne un message d'erreur le voici : root@ubuntu:/etc/apt# apt-get update Réception de : 1 http://security.ubuntu.com breezy-security Release.gpg [189B] Réception de : 2 http://fr.archive.ubuntu.com breezy Release.gpg [189B] Réception de : 3 http://fr.archive.ubuntu.com breezy-updates Release.gpg [189B] Atteint http://security.ubuntu.com breezy-security Release Atteint http://fr.archive.ubuntu.com breezy Release Atteint http://security.ubuntu.com breezy-security/main Packages Atteint http://fr.archive.ubuntu.com breezy-updates Release Atteint http://security.ubuntu.com breezy-security/restricted Packages Atteint http://security.ubuntu.com breezy-security/main Sources Atteint http://security.ubuntu.com breezy-security/restricted Sources Ign http://fr.archive.ubuntu.com breezy/main Packages Atteint http://fr.archive.ubuntu.com breezy/restricted Packages Ign http://fr.archive.ubuntu.com breezy/main Sources Atteint http://fr.archive.ubuntu.com breezy/restricted Sources Atteint http://fr.archive.ubuntu.com breezy-updates/main Packages Atteint http://fr.archive.ubuntu.com breezy-updates/restricted Packages Atteint http://fr.archive.ubuntu.com breezy-updates/main Sources Atteint http://fr.archive.ubuntu.com breezy-updates/restricted Sources Réception de : 4 http://fr.archive.ubuntu.com breezy/main Packages [767kB] Réception de : 5 http://fr.archive.ubuntu.com breezy/main Sources [305kB] 99% [4 Packages gzip 0] gzip: stdin: not in gzip format Err http://fr.archive.ubuntu.com breezy/main Packages Le sous-processus gzip a renvoyé un code d'erreur (1) 99% [5 Sources gzip 0] gzip: stdin: not in gzip format Err http://fr.archive.ubuntu.com breezy/main Sources Le sous-processus gzip a renvoyé un code d'erreur (1) 5o réceptionnés en 1s (3o/s) Impossible de récupérer http://fr.archive.ubuntu.com/ubuntu/dists/breezy/main/binary-i386/Packages.gz Le sous-processus gzip a renvoyé un code d'erreur (1) Impossible de récupérer http://fr.archive.ubuntu.com/ubuntu/dists/breezy/main/source/Sources.gz Le sous-processus gzip a renvoyé un code d'erreur (1) Lecture des listes de paquets... Fait W: Impossible de localiser la liste des paquets sources http://fr.archive.ubuntu.com breezy/main Packages (/var/lib/apt/lists/fr.archive.ubuntu.com_ubuntu_dists_breezy_main_binary-i386_Packages) - stat (2 Aucun fichier ou répertoire de ce type) W: Vous pouvez lancer « apt-get update » pour corriger ces problèmes. 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. Voici egalement ma source list : deb cdrom:[Ubuntu 5.10 _Breezy Badger_ - Release i386 (20051012)]/ breezy main restricted deb http://fr.archive.ubuntu.com/ubuntu breezy main restricted deb-src http://fr.archive.ubuntu.com/ubuntu breezy main restricted ## Major bug fix updates produced after the final release of the ## distribution. deb http://fr.archive.ubuntu.com/ubuntu breezy-updates main restricted deb-src http://fr.archive.ubuntu.com/ubuntu breezy-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 breezy universe # deb-src http://fr.archive.ubuntu.com/ubuntu breezy universe ## 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 breezy-backports main restricted universe multiverse # deb-src http://fr.archive.ubuntu.com/ubuntu breezy-backports main restricted universe multiverse deb http://security.ubuntu.com/ubuntu breezy-security main restricted deb-src http://security.ubuntu.com/ubuntu breezy-security main restricted # deb http://security.ubuntu.com/ubuntu breezy-security universe # deb-src http://security.ubuntu.com/ubuntu breezy-security universe J'aimerais comprendre pourquoi je n'arrive à utiliser cette commande. Merci pour votre aide, @ plux Hors ligne Hors ligne Leenuks Re : Impossible de faire apt-get update J'ai reessayer aujourdhui ca fonctionne nickel !! pourtant je n'ai rien fais de special surement un souci sur leurs serveurs. Merki, Hors ligne bapoumba Re : Impossible de faire apt-get update salut leenuks donc si ça va, tu peux éditer ton premier post (modifier) et inclure [résolu] dans le titre ? merci | Ubuntu Forums | J'aime les fraises. Hors ligne lost-in-the-shell Re : Impossible de faire apt-get update et au passage : utilise sudo, ne te connecte pas en tant que root (quand c'est qu'ils comprendront ça...) Linux user #401253 - Ubuntu user #3023 . Nick sur IRC : naji. Pensez à adhérer au Comité de lutte contre le SMS. Hors ligne
The common use case here is a user uploading a jpeg logo with a white/color background. It's (fairly) simple to switch the white pixels to transparent ones, but this leaves aliasing artifacts. An ideal solution would essentially "undo" the aliasing (given a known background color). At a minimum, the solution must beat the bg_removal script for ImageMagick (http://imagemagick.org/Usage/scripts/bg_removal). The "Color to Alpha" algorithm in GIMP looks like it does a pretty good job. The source is GPL and can be found here. A demonstration of what the GIMP algorithm does with something like a logo is here, and the GIMP manual page for Color-to-Alpha is here. It looks like the most straightforward way to do this programmatically would be to use GIMP batch mode. As promised, here's a working solution for the common white --> alpha use case. This is running on an Ubuntu 10.04.1 LTS server with the standard GIMP installation (2.6.8). from gimpfu import * def run(input_filepath): image = pdb.gimp_file_load(input_filepath, input_filepath) image.disable_undo() layer = image.active_layer if not layer.is_rgb: pdb.gimp_image_convert_rgb(image) white = gimpcolor.RGB(1.0, 1.0, 1.0, 1.0) bg_color = pdb.gimp_image_pick_color(image, layer, 0, 0, True, False, 0) if bg_color == white: pdb.plug_in_colortoalpha(image, layer, bg_color) layer_copy = layer.copy() image.add_layer(layer_copy) image.merge_visible_layers(CLIP_TO_IMAGE) pdb.file_png_save_defaults(image, image.active_layer, input_filepath, input_filepath) run('%(input_filepath)s') I execute this code from Python (within Django) using the subprocess module (code_as_string is the above code as a string, with input_filepath inserted: gimp_args = (settings.PATH_TO_GIMP, '-i', '--batch-interpreter=python-fu-eval', '-b', code_as_string, '-b', 'from gimpfu import pdb; pdb.gimp_quit(True)') environ = os.environ.copy() environ['GIMP2_DIRECTORY'] = settings.PATH_TO_GIMP_DIR p = subprocess.Popen(gimp_args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=environ) rc = p.wait() if rc: logging.error(p.stdout.read())
rezzakilla Re : [Info] Installation du driver Libre ATI Radeon Je dis ça comme ça...mais ça marche terrible sur ma 7500.....:D Hors ligne hugo69 Re : [Info] Installation du driver Libre ATI Radeon ton tuto est dans la doc officielle mais ca naide pas beaucoup ma 9700ATI Hercules à fonctionner correctement. Si je mets les drivers propritaire, les soft de tele ne se lance plus et certains plugins visualisations sur xxms sont capable de me planter lordi en full screen si je met les radeon ca semble etre stable mais je gagne rien en qualite, genre les screensaver et autres. donc avec ma 9700 payé 3500f il ya kelkes temps deja , c vrai, je peux profiter des performance dune mx2 en gros. ca et grip ki tourne à 3 à lheure sont les gros defaut ke je trouve a ubuntu pour linstannt. Mais sinon pour le reste, rien a redire. en tout cas bravo pour le tuto Hors ligne Stemp Re : [Info] Installation du driver Libre ATI Radeon Merci Par contre il est vrai que ce tutoriel est plutôt destiné au cartes ati jusqu'à la 9200. Concernant ta carte, tu as essayé les nouveaux drivers sur le site ati.com ? Hors ligne hugo69 Re : [Info] Installation du driver Libre ATI Radeon non jai pas essayé, je suis pas un pro de la compilation ou de la conversion .rpm en .deb meme si cest pas forcement un obstacle dans le deuxieme cas. par contre niveau compatibilité, jen sais rien. Jai vu ca, jai dl les X.Org 6.8 puisque je sui ssous x11et non pas xfree https://support.ati.com/ics/support/def … derID=3959 en fait jy connais rien et jai peur de me retrouver sous console au redemarrage et detre incapable de resoudre et de me retaper linstallation de la totale. jai ouvert ca pour pas polluer: http://forum.ubuntu-fr.org/viewtopic.ph … 904#p45904 deja je sais ke cette methode est valadble jusqua 9200 au moin je peu deja leliminer et ke la solution serai plus vers les drivers ati merci Hors ligne NicoA380 Re : [Info] Installation du driver Libre ATI Radeon Attention à ne pas tomber dans le panneau comme moi. J'ai installé les driver proprio d' ATI fglrx en croyant que ça allait changer quelque chose sur ma Radeon 8500. J'y ai cru un moment, mais j'avais une appli OpenGL qui ne voulait plus démarrer, il fait appel à une fonction buggué d'OpenGL. J'ai cherché pendant une journée à retourner sur le driver libre ATI, en retirant fglrx dans Synaptic, et en restaurant mon premier xorg.conf . Résultat, la cata, toutes les applis 3D sacadaient à mourrir, et glxgears fournissait un score en dessous de 100 fps. J'ai fini par relire la procédure d'installation de fglrx, et là ... mais oui !!! le fichier /etc/modules !! il fallait rajouter fglrx en premier à l'installation, mais il faut évidement la retirer pour repasser en driver libre ! Un reboot plus tard, je retrouve mes applis 3D toutes fluides, et un score autour de 1500 fps à glxgear, à peu près le même que celui avec le driver fglrx. Tout ce blabla pour dire : oubliez pas de retirer fglrx du fichier /etc/modules quand vous repassez au driver libre 'ati'. Dernière modification par NicoA380 (Le 25/06/2005, à 09:54) Hors ligne Aito Re : [Info] Installation du driver Libre ATI Radeon Hello la foule, Heu juste pour être sur d'avoir bien compris : J'ai une Radeon X600 Pro, donc d'apres ta liste le driver 'radeon' ne la supporte qu'en 2D (je suis hyperrrrrrrrrrr content....) Et fglrx alors il supporte quelles cartes ? A+ Hors ligne Stemp Re : [Info] Installation du driver Libre ATI Radeon Salut, Le driver propirètaire fglrx supporte la 3d sur les cartes à partir de la série 8500. Donc c'est bon pour les X600, mais il est préférable d'utiliser l'installateur de drivers du site ati (8.14.13) Hors ligne Francois_Gregoire Re : [Info] Installation du driver Libre ATI Radeon ok ca marche, merci pour l'astuce... j'ai du modifier quelques valeurs pour que ca tourne, mais c'est bon.. pour info j'ai une radeon Mobility M6 LY.. Qu'as du changer car moi m'as mobility M6 ne marche pas en direct rendering. Voici ce que glxinfo me dit: francois@ubuntu:~$ glxinfo name of display: :0.0 display: :0 screen: 0 direct rendering: No server glx vendor string: SGI server glx version string: 1.2 server glx extensions: GLX_ARB_multisample, GLX_EXT_visual_info, GLX_EXT_visual_rating, GLX_EXT_import_context, GLX_OML_swap_method, GLX_SGI_make_current_read, GLX_SGIS_multisample, GLX_SGIX_fbconfig client glx vendor string: SGI client glx version string: 1.4 client glx extensions: GLX_ARB_get_proc_address, GLX_ARB_multisample, GLX_EXT_import_context, GLX_EXT_visual_info, GLX_EXT_visual_rating, GLX_MESA_allocate_memory, GLX_MESA_swap_control, GLX_MESA_swap_frame_usage, GLX_OML_swap_method, GLX_OML_sync_control, GLX_SGI_make_current_read, GLX_SGI_swap_control, GLX_SGI_video_sync, GLX_SGIS_multisample, GLX_SGIX_fbconfig, GLX_SGIX_pbuffer, GLX_SGIX_visual_select_group GLX extensions: GLX_ARB_get_proc_address, GLX_ARB_multisample, GLX_EXT_import_context, GLX_EXT_visual_info, GLX_EXT_visual_rating, GLX_OML_swap_method, GLX_SGI_make_current_read, GLX_SGIS_multisample, GLX_SGIX_fbconfig, GLX_SGIX_visual_select_group OpenGL vendor string: Mesa project: www.mesa3d.org OpenGL renderer string: Mesa GLX Indirect OpenGL version string: 1.2 (1.5 Mesa 6.2.1) OpenGL extensions: GL_ARB_depth_texture, GL_ARB_imaging, GL_ARB_multitexture, GL_ARB_point_parameters, GL_ARB_point_sprite, GL_ARB_shadow, GL_ARB_shadow_ambient, GL_ARB_texture_border_clamp, GL_ARB_texture_cube_map, GL_ARB_texture_env_add, GL_ARB_texture_env_combine, GL_ARB_texture_env_crossbar, GL_ARB_texture_env_dot3, GL_ARB_texture_mirrored_repeat, GL_ARB_transpose_matrix, GL_ARB_window_pos, GL_EXT_abgr, GL_EXT_bgra, GL_EXT_blend_color, GL_EXT_blend_func_separate, GL_EXT_blend_logic_op, GL_EXT_blend_minmax, GL_EXT_blend_subtract, GL_EXT_clip_volume_hint, GL_EXT_copy_texture, GL_EXT_draw_range_elements, GL_EXT_fog_coord, GL_EXT_multi_draw_arrays, GL_EXT_packed_pixels, GL_EXT_point_parameters, GL_EXT_polygon_offset, GL_EXT_rescale_normal, GL_EXT_secondary_color, GL_EXT_separate_specular_color, GL_EXT_shadow_funcs, GL_EXT_stencil_two_side, GL_EXT_stencil_wrap, GL_EXT_subtexture, GL_EXT_texture, GL_EXT_texture3D, GL_EXT_texture_edge_clamp, GL_EXT_texture_env_add, GL_EXT_texture_env_combine, GL_EXT_texture_env_dot3, GL_EXT_texture_lod_bias, GL_EXT_texture_object, GL_EXT_texture_rectangle, GL_EXT_vertex_array, GL_APPLE_packed_pixels, GL_ATI_texture_env_combine3, GL_ATI_texture_mirror_once, GL_ATIX_texture_env_combine3, GL_IBM_texture_mirrored_repeat, GL_INGR_blend_func_separate, GL_MESA_pack_invert, GL_MESA_ycbcr_texture, GL_NV_blend_square, GL_NV_point_sprite, GL_NV_texgen_reflection, GL_NV_texture_rectangle, GL_SGIS_generate_mipmap, GL_SGIS_texture_border_clamp, GL_SGIS_texture_edge_clamp, GL_SGIS_texture_lod, GL_SGIX_depth_texture, GL_SGIX_shadow, GL_SGIX_shadow_ambient, GL_SUN_multi_draw_arrays glu version: 1.3 glu extensions: GLU_EXT_nurbs_tessellator, GLU_EXT_object_space_tess visual x bf lv rg d st colorbuffer ax dp st accumbuffer ms cav id dep cl sp sz l ci b ro r g b a bf th cl r g b a ns b eat ---------------------------------------------------------------------- 0x23 24 tc 0 24 0 r y . 8 8 8 0 0 16 0 0 0 0 0 0 0 None 0x24 24 tc 0 24 0 r y . 8 8 8 0 0 16 8 16 16 16 0 0 0 None 0x25 24 tc 0 32 0 r y . 8 8 8 8 0 16 8 16 16 16 16 0 0 None 0x26 24 tc 0 32 0 r . . 8 8 8 8 0 16 8 16 16 16 16 0 0 None 0x27 24 dc 0 24 0 r y . 8 8 8 0 0 16 0 0 0 0 0 0 0 None 0x28 24 dc 0 24 0 r y . 8 8 8 0 0 16 8 16 16 16 0 0 0 None 0x29 24 dc 0 32 0 r y . 8 8 8 8 0 16 8 16 16 16 16 0 0 None 0x2a 24 dc 0 32 0 r . . 8 8 8 8 0 16 8 16 16 16 16 0 0 None Donc on vas bien que le direct renderin est a no. Mais si je regarde mon /etc/X11/xorg.conf: # /etc/X11/xorg.conf (xorg X Window System server configuration file) # # This file was generated by dexconf, the Debian X Configuration tool, using # values from the debconf database. # # Edit this file with caution, and see the /etc/X11/xorg.conf manual page. # (Type "man /etc/X11/xorg.conf" at the shell prompt.) # # This file is automatically updated on xserver-xorg package upgrades *only* # if it has not been modified since the last upgrade of the xserver-xorg # package. # # If you have edited this file but would like it to be automatically updated # again, run the following commands: # # cp /etc/X11/xorg.conf /etc/X11/xorg.conf.custom # sudo sh -c 'md5sum /etc/X11/xorg.conf >/var/lib/xfree86/xorg.conf.md5sum' # sudo dpkg-reconfigure xserver-xorg Section "Files" FontPath "unix/:7100" # local font server # if the local font server has problems, we can fall back on these FontPath "/usr/lib/X11/fonts/misc" FontPath "/usr/lib/X11/fonts/cyrillic" FontPath "/usr/lib/X11/fonts/100dpi/:unscaled" FontPath "/usr/lib/X11/fonts/75dpi/:unscaled" FontPath "/usr/lib/X11/fonts/Type1" FontPath "/usr/lib/X11/fonts/CID" FontPath "/usr/lib/X11/fonts/100dpi" FontPath "/usr/lib/X11/fonts/75dpi" # paths to defoma fonts FontPath "/var/lib/defoma/x-ttcidfont-conf.d/dirs/TrueType" FontPath "/var/lib/defoma/x-ttcidfont-conf.d/dirs/CID" EndSection Section "Module" Load "bitmap" Load "dbe" Load "ddc" Load "dri" Load "extmod" Load "freetype" Load "glx" Load "int10" Load "record" Load "type1" Load "vbe" EndSection Section "Extensions" Option "RENDER" "Enable" EndSection Section "InputDevice" Identifier "Generic Keyboard" Driver "keyboard" Option "CoreKeyboard" Option "XkbRules" "xorg" Option "XkbModel" "pc104" Option "XkbLayout" "us" EndSection Section "InputDevice" Identifier "Configured Mouse" Driver "mouse" Option "CorePointer" Option "Device" "/dev/input/mice" Option "Protocol" "ImPS/2" Option "Emulate3Buttons" "true" Option "ZAxisMapping" "4 5" EndSection Section "InputDevice" Identifier "Synaptics Touchpad" Driver "synaptics" Option "SendCoreEvents" "true" Option "Device" "/dev/psaux" Option "Protocol" "auto-dev" Option "HorizScrollDelta" "0" Option "MaxTapTime" "0" EndSection Section "Device" Identifier "ATI Technologies, Inc. Radeon Mobility 9000 (M6 LY)" ChipID 0x4c59 Driver "radeon" Option "AGPMode" "4" Option "AGPSize" "64" # default: 8 Option "RingSize" "8" Option "BufferSize" "2" Option "EnablePageFlip" "True" Option "EnableDepthMoves" "True" Option "RenderAccel" "true" BusID "PCI:1:0:0" EndSection Section "Monitor" Identifier "Generic Monitor" Option "DPMS" EndSection Section "Screen" Identifier "Default Screen" Device "ATI Technologies, Inc. Radeon Mobility 9000 (M6 LY)" Monitor "Generic Monitor" DefaultDepth 24 SubSection "Display" Depth 1 Modes "1400x1050" EndSubSection SubSection "Display" Depth 4 Modes "1400x1050" EndSubSection SubSection "Display" Depth 8 Modes "1400x1050" EndSubSection SubSection "Display" Depth 15 Modes "1400x1050" EndSubSection SubSection "Display" Depth 16 Modes "1400x1050" EndSubSection SubSection "Display" Depth 24 Modes "1400x1050" EndSubSection EndSection Section "ServerLayout" Identifier "Default Layout" Screen "Default Screen" InputDevice "Generic Keyboard" InputDevice "Configured Mouse" InputDevice "Synaptics Touchpad" EndSection Section "DRI" Mode 0666 EndSection Tous est selon la procedure. Je me demande bien ce que je fais de travers... Quelqu'un a une suggestion? car disons que 250 a glxgears c'est pas fameux avec un laptop P3 1.2gig avec 512megs de ram.... Francois Francois_Gregoire Re : [Info] Installation du driver Libre ATI Radeon Tu n'aurais pas installé les drivers fglrx et oublié de les enlever par hasard ? Nope. Je n'ai pas installer les fglrx et j'ai meme verifier dans symantics pour etre sur. Et non ni moi, ni l'installation de base n'avons installe les drivers proprietaire de ATi. Francois_Gregoire Re : [Info] Installation du driver Libre ATI Radeon Bon, bon, il faudrait voir le fichier /var/log/Xorg.0.log Essaie de trouver l'erreur, ça aidera surement Selon Xorg.0.log, il semble que 1400x1050 24bits sois trop pour le maigre 16megs que m'as carte video possede... Reste a trouver ou je peux essayer de mettre 16bits voir. Je vais essayer de le mettre par defaut dans xorg.conf a 16bits voir si ca marche. Hors ligne Stemp Re : [Info] Installation du driver Libre ATI Radeon Nope pas le bon message d'erreur Le fait d'utiliser les modes 1400x1050 ou/et 24 bits, ne gêne en rien le fait d'utiliser l'accélération graphique de la radeon. OpenGL vendor string: Mesa project: www.mesa3d.orgOpenGL renderer string: Mesa GLX IndirectOpenGL version string: 1.2 (1.5 Mesa 6.2.1 Là est ton problème. Recherche "render" dans ta log Hors ligne Francois_Gregoire Re : [Info] Installation du driver Libre ATI Radeon Nope pas le bon message d'erreur Le fait d'utiliser les modes 1400x1050 ou/et 24 bits, ne gêne en rien le fait d'utiliser l'accélération graphique de la radeon. Ca marcher. Le probleme avec la M6 sur un portable Dell qui contient seulement 16megs ne peux marcher en 1400x1050 24bits. Trop d'information selon le log de Xorg.0.log que cette configuration demande 17.5megs. Donc en changant le mode 24bits en 16bits dans /etc/X11/xorg.conf de default 24bits en 16bits, ca marche en 1400x1050. Pourquoi garder le 1400x1050 au loei de la descendre? Tres simple, c<est la resolution native d'un inspiron 4100 ou latitude C610 ou dans mon cas un inspiron 4100 hacker en latitude C610 . maintenant au lieu d'avoir 200fps dans glxgears j'ai 800fps. C'est loins des 1500-2000 que j'ai vu sur le forum mais bon, m'as resolution est quand meme plus haute que 800x600 Hors ligne Stemp Re : [Info] Installation du driver Libre ATI Radeon Et glxinfo ne te donnes plus : OpenGL vendor string: Mesa project: www.mesa3d.org OpenGL renderer string: Mesa GLX Indirect OpenGL version string: 1.2 (1.5 Mesa 6.2.1) ????? Je ne comprends pas pourquoi ta résolution modifie le "Rendering" !! Mais bon, très bonne info Hors ligne Francois_Gregoire Re : [Info] Installation du driver Libre ATI Radeon Et glxinfo ne te donnes plus : OpenGL vendor string: Mesa project: www.mesa3d.org OpenGL renderer string: Mesa GLX Indirect OpenGL version string: 1.2 (1.5 Mesa 6.2.1) ????? Je ne comprends pas pourquoi ta résolution modifie le "Rendering" !! Mais bon, très bonne info Voici mon glxinfo apres le changement de 24bits a 16bits du au manque de memoire francois@ubuntu:~$ glxinfo name of display: :0.0 display: :0 screen: 0 direct rendering: Yes server glx vendor string: SGI server glx version string: 1.2 server glx extensions: GLX_ARB_multisample, GLX_EXT_visual_info, GLX_EXT_visual_rating, GLX_EXT_import_context, GLX_OML_swap_method, GLX_SGI_make_current_read, GLX_SGIS_multisample, GLX_SGIX_fbconfig client glx vendor string: SGI client glx version string: 1.4 client glx extensions: GLX_ARB_get_proc_address, GLX_ARB_multisample, GLX_EXT_import_context, GLX_EXT_visual_info, GLX_EXT_visual_rating, GLX_MESA_allocate_memory, GLX_MESA_swap_control, GLX_MESA_swap_frame_usage, GLX_OML_swap_method, GLX_OML_sync_control, GLX_SGI_make_current_read, GLX_SGI_swap_control, GLX_SGI_video_sync, GLX_SGIS_multisample, GLX_SGIX_fbconfig, GLX_SGIX_pbuffer, GLX_SGIX_visual_select_group GLX extensions: GLX_ARB_get_proc_address, GLX_ARB_multisample, GLX_EXT_import_context, GLX_EXT_visual_info, GLX_EXT_visual_rating, GLX_MESA_swap_control, GLX_MESA_swap_frame_usage, GLX_OML_swap_method, GLX_SGI_video_sync, GLX_SGIS_multisample, GLX_SGIX_fbconfig OpenGL vendor string: Tungsten Graphics, Inc. OpenGL renderer string: Mesa DRI Radeon 20040929 AGP 4x x86/MMX/SSE NO-TCL OpenGL version string: 1.2 Mesa 6.2.1 OpenGL extensions: GL_ARB_imaging, GL_ARB_multisample, GL_ARB_multitexture, GL_ARB_texture_border_clamp, GL_ARB_texture_compression, GL_ARB_texture_env_add, GL_ARB_texture_env_combine, GL_ARB_texture_env_crossbar, GL_ARB_texture_env_dot3, GL_ARB_texture_mirrored_repeat, GL_ARB_texture_rectangle, GL_ARB_transpose_matrix, GL_ARB_window_pos, GL_EXT_abgr, GL_EXT_bgra, GL_EXT_blend_color, GL_EXT_blend_logic_op, GL_EXT_blend_minmax, GL_EXT_blend_subtract, GL_EXT_clip_volume_hint, GL_EXT_compiled_vertex_array, GL_EXT_convolution, GL_EXT_copy_texture, GL_EXT_draw_range_elements, GL_EXT_histogram, GL_EXT_packed_pixels, GL_EXT_polygon_offset, GL_EXT_rescale_normal, GL_EXT_secondary_color, GL_EXT_separate_specular_color, GL_EXT_subtexture, GL_EXT_texture, GL_EXT_texture3D, GL_EXT_texture_edge_clamp, GL_EXT_texture_env_add, GL_EXT_texture_env_combine, GL_EXT_texture_env_dot3, GL_EXT_texture_filter_anisotropic, GL_EXT_texture_lod_bias, GL_EXT_texture_mirror_clamp, GL_EXT_texture_object, GL_EXT_texture_rectangle, GL_EXT_vertex_array, GL_APPLE_packed_pixels, GL_ATI_texture_env_combine3, GL_ATI_texture_mirror_once, GL_IBM_rasterpos_clip, GL_IBM_texture_mirrored_repeat, GL_MESA_ycbcr_texture, GL_MESA_window_pos, GL_NV_blend_square, GL_NV_light_max_exponent, GL_NV_texture_rectangle, GL_NV_texgen_reflection, GL_SGI_color_matrix, GL_SGI_color_table, GL_SGIS_generate_mipmap, GL_SGIS_texture_border_clamp, GL_SGIS_texture_edge_clamp, GL_SGIS_texture_lod glu version: 1.3 glu extensions: GLU_EXT_nurbs_tessellator, GLU_EXT_object_space_tess visual x bf lv rg d st colorbuffer ax dp st accumbuffer ms cav id dep cl sp sz l ci b ro r g b a bf th cl r g b a ns b eat ---------------------------------------------------------------------- 0x23 16 tc 0 16 0 r . . 5 6 5 0 0 16 0 0 0 0 0 0 0 None 0x24 16 tc 0 16 0 r . . 5 6 5 0 0 16 8 0 0 0 0 0 0 Slow 0x25 16 tc 0 16 0 r . . 5 6 5 0 0 16 0 16 16 16 0 0 0 Slow 0x26 16 tc 0 16 0 r . . 5 6 5 0 0 16 8 16 16 16 0 0 0 Slow 0x27 16 tc 0 16 0 r y . 5 6 5 0 0 16 0 0 0 0 0 0 0 None 0x28 16 tc 0 16 0 r y . 5 6 5 0 0 16 8 0 0 0 0 0 0 Slow 0x29 16 tc 0 16 0 r y . 5 6 5 0 0 16 0 16 16 16 0 0 0 Slow 0x2a 16 tc 0 16 0 r y . 5 6 5 0 0 16 8 16 16 16 0 0 0 Slow 0x2b 16 dc 0 16 0 r . . 5 6 5 0 0 16 0 0 0 0 0 0 0 None 0x2c 16 dc 0 16 0 r . . 5 6 5 0 0 16 8 0 0 0 0 0 0 Slow 0x2d 16 dc 0 16 0 r . . 5 6 5 0 0 16 0 16 16 16 0 0 0 Slow 0x2e 16 dc 0 16 0 r . . 5 6 5 0 0 16 8 16 16 16 0 0 0 Slow 0x2f 16 dc 0 16 0 r y . 5 6 5 0 0 16 0 0 0 0 0 0 0 None 0x30 16 dc 0 16 0 r y . 5 6 5 0 0 16 8 0 0 0 0 0 0 Slow 0x31 16 dc 0 16 0 r y . 5 6 5 0 0 16 0 16 16 16 0 0 0 Slow 0x32 16 dc 0 16 0 r y . 5 6 5 0 0 16 8 16 16 16 0 0 0 Slow Dernière modification par Francois_Gregoire (Le 03/07/2005, à 01:53) Hors ligne Aito Re : [Info] Installation du driver Libre ATI Radeon Hello la foule Pour Stemp : Tu dis : Le driver propirètaire fglrx supporte la 3d sur les cartes à partir de la série 8500. Donc c'est bon pour les X600, mais il est préférable d'utiliser l'installateur de drivers du site ati (8.14.13) Ha ?? Merci pour l'info, décidément je ne comprend rien à l'organisation de la gamme ATI Sinon à propos du driver proprio J'ai suivi tes conseil je l'ai téléchargé et installé. Tout se passe relativement bien : install automatique : ras fglrxconfig : je répond du mieux que je peux en prennant souvent les choix proposés et redémmare X, et la à glxgears je suis passé d'environ 500 à environ 150 !!! (sans compter les problème de clavier et autres) J'ai donc mis les main dans le xorg.conf pour en fair eun mixte entre celui d'origine et celui proposé par ATI J4ai fini avec qq chose qui fonctionne sans pb mais toujours avec un glxgears à 150 !! Je fais quoi docteur ? j'abat la bete ? Personne n'a une radeon X600 Pro dans le coin ? Merci pour l'aide A+ Aito Hors ligne Stemp Re : [Info] Installation du driver Libre ATI Radeon Vérifie que tu as bien un fichier fglrx.ko dans le répertoire /etc/modules/fglrx/ et que tu n'as pas de ce fichier dans le répertoire /etc/modules/2.610....(ta version de kernel) Hors ligne Aito Re : [Info] Installation du driver Libre ATI Radeon heu... c'est pas plutot dans /lib/modules ? dans /lib.modules : j'ai bien un fglrx.ko qui est un lien vers fglrx.2.6.10-5-686.ko qui est dans le meme répertoire puis 2 autres (des fichiers pas des liens) dans : /lib/modules/2.6.10-5-686/kernel/drivers/video$ et /lib/modules/2.6.10-5-686/kernel/drivers/char/drm$ Hors ligne Stemp Re : [Info] Installation du driver Libre ATI Radeon Ooops.....c'était pour voir si tu suivais bien Et pas de répertoire /lib/modules/fglrx ??? Normalement l'installateur ATI crée ce répertoire pour y compiler le nouveau fichier fglrx.ko Hors ligne Aito Re : [Info] Installation du driver Libre ATI Radeon si si pardon c bien dans /lib/modules/fglrx pas dans /lib/modules tout court je fais quoi maintenant ??:rolleyes: Hors ligne insan Re : [Info] Installation du driver Libre ATI Radeon Bonjour à tous ! J'ai une carte Radeon 9200 Pro (RV280) mais j'ai un problème de résolution car pendant le démarrage à un moment donnée j'attends longtemps pour que ça poursuive avec cette ligne : *ror : Temporary Failure in name resolution [Fail] Donc je me suis dit peut-être que cette procédure décrite ici résoudrait ce problème avec les avantages qu'elle apporte ... mais j'ai une question : Concernant les drivers propriétaires, les deux paquets importants à virer sont : xorg-driver-fglrx et fglrx-control. mais moi, j'ai dans Synaptic : - dans "installés" : xorg-common et xorg-driver-synaptics. - Et dans "non installés" : fglrx-control et fglrx-kernel-source. Dois-je alors me contenter de désinstaller les 2 paquets dans la rubrique "installés" et puis, évidemment, faire les modifications indiquées dans le premier post ? Autre question : C'est quoi glxgears ? Merci infiniment par avance ! Hors ligne
(in case you're curious about motivation: this will be used in a scons build to generate a C file containing a GUID) I found the question about generating a GUID in python. But I don't really know much about programming python. Could someone help me convert this to a string of the form "{0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**, 0x**}" where the **'s are filled in with the GUID bytes in 2-digit hex form? def getInitializer(someUUID): hexByteList = [??? for b in someUUID.bytes] return '{'+(', '.join(hexByteList))+'}' I'm not sure what to use for the "???" above.
The standard approach for using variable values in SQLite queries is the "question mark style", like this: import sqlite3 with sqlite3.connect(":memory:") as connection: connection.execute("CREATE TABLE foo(bar)") connection.execute("INSERT INTO foo(bar) VALUES (?)", ("cow",)) print(list(connection.execute("SELECT * from foo"))) # prints [(u'cow',)] However, this only works for substituting values into queries. It fails when used for table or column names: import sqlite3 with sqlite3.connect(":memory:") as connection: connection.execute("CREATE TABLE foo(?)", ("bar",)) # raises sqlite3.OperationalError: near "?": syntax error Neither the sqlite3 module nor PEP 249 mention a function for escaping names or values. Presumably this is to discourage users from assembling their queries with strings, but it leaves me at a loss. What function or technique is most appropriate for using variable names for columns or tables in SQLite? I'd would strongly prefer to do able to do this without any other dependencies, since I'll be using it in my own wrapper. I looked for but couldn't find a clear and complete description of the relevant part of SQLite's syntax, to use to write my own function. I want to be sure this will work for any identifier permitted by SQLite, so a trial-and-error solution is too uncertain for me. SQLite uses " to quote identifiers but I'm not sure that just escaping them is sufficient. PHP's sqlite_escape_string function's documentation suggests that certain binary data may need to be escaped as well, but that may be a quirk of the PHP library.
I'm fairly new to python, so I apologize in advance if this is something simple I'm missing. I'm trying to post data to a multipart form in python. The script runs, but it won't post. I'm not sure what I'm doing wrong. import urllib, urllib2 from poster.encode import multipart_encode from poster.streaminghttp import register_openers def toqueXF(): register_openers() url = "http://localhost/trunk/admin/new.php" values = {'form':open('/test.pdf'), 'bandingxml':open('/banding.xml'), 'desc':'description'} data, headers = multipart_encode(values) request = urllib2.Request(url, data, headers) response = urllib2.urlopen(request) the_page = response.read() print the_page When I call this, the print gives me the html of the page, as if I ran "urllib2.urlopen(url)" and didn't post any data: <form enctype="multipart/form-data" action="" method="post"> <p><input type="hidden" name="MAX_FILE_SIZE" value="1000000000" /></p> <p>Select PDF file to create form from: <input name="form" type="file" /></p> <p>(Optional): Select banding XML file: <input name="bandingxml" type="file" /></p> <p>Enter description of form: <input name="desc" type="text"/><br/></p> <p><input type="submit" value="Upload form" /></p> </form> poster is to encode the data to multipart/form data and can be found here: http://atlee.ca/software/poster/index.html I found the code to use poster here: Using MultipartPostHandler to POST form-data with Python If anyone's curious, I'm trying to automatically post a pdf and xml banding file after they're generated for queXF (an opensource optical mark recognition software). http://quexf.sourceforge.net/
I've bought a new laptop (dell inspiron 15 3521) with windows 8. Since I mainly use linux I removed the 7 partitions windows 8 apparently needed and made 4 partitions using a pmagic live usb (windows 80 gb, linux 80 gb, data 150 gb, swap 8 gb) and since I had some problems with getting it to boot from a dvd I installed linux first without problems. But when I got the dvd to work (legacy mode and the a driver on a usb plugged in during installation Serial-ATA_Driver_85FV7_WN_11.7.0.1013_A01) it gave an error (windows cannot be installed on this disk. The selected disk is of the GPT partition style.). To fix this I removed all partitions (including the ubuntu partition) and made a new one. windows also made a dedicated windows partition of 100mb. After the timely installation of windows 7 I got out my ubuntu 13.04 usb drive and preformed a live boot. When I got to the point of creating a new partition (using the ubuntu 13.04 installer) for linux the partition manager didn't show any partitions on the drive at all only 320 gb of 'unallocated space'. I was however able to mount the partitions on the drive. So I know they are there and that ubuntu can see them. So I booted with my pmagic live usb and the partition editor promted me with the following question: Warning: /dev/sda contains GPT signatures, indicating that it has a GPT table. However, it does not have a valid fake msdos partition table, as it should. Perhaps it was corrupted -- possibly by a program that doesn't understand GPT partition tables. Or perhaps you deleted the GPT table, and are now using an msdos partition table. Is this a GPT partition table? Yes/No? Who can help me to fix this problem?
Rport is an R package that greatly facilitates common tasks found in many R Business Intelligence apps. It bridges R and SQL analytics similarly to how Rails bridges Ruby and Web Development. Introduction Handling multiple database connections within one R session Caching results from long SQL statements in development Parallel jobs processing Building UNIX executables Organizing the growing codebase While R supports all these, there isn’t a framework to contain the repeated code that you’ll end up with when building a multi-projects analytics app. For our needs we built such a framework and this article presents it. We named it Rport and it’s open-sourced as an R extension. Quick Start Rport is distributed as an R package and you can get the most up-to-date version from GitHub, directly from within an R session: > library(devtools) > install_github('rport', 'adeven') Then if you want to set up a fresh Rport app do: > library(rport) > rport.app.new('BI kingdom', root.dir='~/my_apps/') # help(rport.app.new) for full list of options This will create the file structure of a clean Rport app. Next you’ll probably want to start setting up different projects for this and that in your new Rport app. To do this: > rport.project.new('weekly kpi report', root.dir='~/my_apps/bi_kingdom') # again help(rport.project.new) for more Now you’ve bootstrapped your first Rport app with one project in it for reporting Weekly KPIs. The generators created some code for you already so you can already see some output by going: $ cd ~/my_apps/bi_kingdom $ ./bin/weekly_kpi_report.R Go ahead and browse those generated files, they’re well commented and you will find some next steps there too. Rport Apps Now that you’ve set up an Rport app, let’s take a more detailed look at it. An Rport app would likely contain multiple projects, often serving different purposes. You might have: Cron jobs for analytics, reports, calculation and other tasks. A lot of one-off exploration scripts Asynchronous processing of tasks from web apps Standalone web services Others An Rport app with two projects might have the following folder structure: .├── bin│ ├── apptrace_newsletter│ └── new_apps_report├── config│ └── database.yml│ └── settings.R├── doc├── lib│ ├── functions│ │ ├── apptrace_newsletter│ │ │ └── main.R│ │ └── new_apps_report│ │ └── main.R│ └── opts│ ├── apptrace_newsletter.R│ └── new_apps_report.R├── log├── script└── spec For an illustration of Rport’s features we created a Demo Rport App. Make sure you refer to it along with reading this post. Rport Features Rport will take care of tedious background tasks, while you can focus on the actual explorations and analytics of your data. Let’s introduce the core features of the package below. Database Connectivity If you’re directly interfacing R’s SQL drivers, you’ll likely find yourself oftenusing the dbGetQuery(connection, query) routine, meaning that you need tocarry your connection object around every time you issue a database query. Multiple Connections Handling Using Rport in the scenario above, you’ll define all your connections in aconfig/database.yml file, similarly to what you’d do in other frameworks (e.g.Rails). The difference here is that with Rport you can not only define multipleenvironments, but also multiple connections within each environment. 1 2 3 4 5 6 7 8 9 10 11 12 13 # bootstrap production environment rport('production') # use the handy accessor method for the `read` connection, generated by Rport dat <- rport.read('select me from you') # access another database and get more data: old.dat <- rport.backup('select me from old_you') # `dat` and `old.dat` are now `data.table` objects with results from the # `production->read` and `production->backup` connections respectively Few things are worth mentioning in this snippet: Rport created the rport.readandrport.backupmethods magically based on thereadandbackupdatabase configurations in theconfig/database.yml. Check out the Example app to see more of this. You can have as many database configurations as you like and combine results from all of them into a single R session. We use this feature a lot when doing adjust.io <-> apptrace stuff or when we offload heavy reads to a replication server. Note that different configurations could also mean entirely different database servers. Nothing stops you from having PostgreSQL and MySQL results brought together in R by Rport. And you wouldn’t even care about the underlying connection mechanics, because Rport will do that for you. Rport works with the Data Table package and all the results returned from database queries are data.tableobjects. If you’re wondering why we introduced this dependency, just check out this fantastic package from the link above. Caching Query Results When working on scripts, you might want to load larger chunks of raw data into memory and crunch them in R (ideally with Data Table) to produce your results. When just ‘playing’ or exploring the raw data, you won’t really want to wait for an unchanged SQL query to run again when rerunning a script to test your R code. Rport’s connection accessors allow you to cache results using R’s load andsave routines. 1 2 3 4 5 6 7 rport('development') # Read the data in memory only if not found in the cache. dat <- rport.read('select app_id, rank from application_ranks', cache=TRUE) # do crazy crunching on `dat` This query will now only run once and subsequent executions of the script will read and return the cached R object from the file system. To ensure that nothing bad ever happens to you using this caching, it only works in development and it logs clearly when reading from cache. Furthermore, it works on a per-connection basis, so the same queries under different connections will be cached separately. Parallel report compilation Since R 2.15 the parallel package is part of R Core. Rport provides somewrappers around that package to address specific use cases. For example a newsletter or report will likely be constituted of several independent items that could probably be generated independently to gain performance. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 rport('production') users.stats <- function(opts) { sql <- ' SELECT count(*) FROM users WHERE created_at >= %s ' rport.apptrace(sprintf(sql, opts$start_date)) } products.stats <- function(opts) { sql <- ' SELECT count(*) FROM products WHERE created_at >= %s ' rport.apptrace(sprintf(sql, opts$start_date)) } rport.bootstrap('parallel', cluster.size=8) # run the components in parallel result = rport.parallel ( useres = { users.stats, opts }, products = { products.stats, opts } ) # result is now a list with the results like: # list (users=data.table(..), products=data.table(..)) Working with Executables Executables are a common interface to our Rport apps. We use them to schedule cron jobs (e.g. reports generation, aggregations, etc.) or to run other analytics tasks. Rport uses Rscript for creation of cross-platform executables. CLI options Rport manages CLI options using the R standard lib optparse package and theconvention of placing opts files under lib/opts/my_script_name.R. Check whatrport.project.new() generated for you above or the sample appfor an illustration. Logging Rport writes a lot about what it’s doing either interactively or in log files. You can use these logs to get an idea about query and script execution times as well as debugging. The convention for executables is that all output is sinked (including outputfrom parallel workers) to log/my_script_name.log. Summary Rport is an ambitious project under ongoing development. Be sure to follow the GitHub repository for all updates.