text
stringlengths
256
65.5k
What is wrong? Please,somebody says me,what I have to write instead of application/x-abiwordAbiWord. Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> f=open('a.abw','r').read() >>> from lxml import etree >>> doc=etree.fromstring >>> from lxml import html >>> doc=html.fromstring >>> doc <function fromstring at 0x0113B858 >>> print(''.join(doc.xpath('//text()')) application/x-abiwordAbiWord SyntaxError: invalid syntax
I have a function that returns information in seconds, but I need to store that information in hours:minutes:seconds. Is there an easy way to convert the seconds to this format in python? or you can do >>> import datetime >>> str(datetime.timedelta(seconds=666)) '0:11:06' By using the m, s = divmod(seconds, 60) h, m = divmod(m, 60) print "%d:%02d:%02d" % (h, m, s) I can hardly name that an easy way (at least I can't remember the syntax), but it is possible to use time.strftime, which gives more control over formatting: >>> import time >>> time.strftime("%H:%M:%S", time.gmtime(666)) '00:11:06' gmtime is used to convert seconds to special tuple format that
I'm fairly new to python (and completely new to Python OO), but I'm working with a fairly complicated class that I'm struggling to understand but that I need to edit. To help understand what's going on I'm trying to pull data out of an object but everything I do is just returning "classname object at address". Could someone explain to me how I'd go about printing, say, the vertex field in this object: class Halfedge(object): def __init__(self, edge=None, marker=Edge.LEFT): self.left = None # left Halfedge in the edge list self.right = None # right Halfedge in the edge list self.qnext = None # priority queue linked list pointer self.edge = edge # edge list Edge self.marker = marker self.vertex = None # Site() self.ystar = BIG_FLOAT def __eq__(self, other): return self.ystar == other.ystar and \ self.vertex.x == other.vertex.x def __lt__(self, other): if self.ystar == other.ystar: return self.vertex.x < other.vertex.x else: return self.ystar < other.ystar def left_reg(self, default): if not self.edge: return default elif self.marker == Edge.LEFT: return self.edge.reg[Edge.LEFT] else: return self.edge.reg[Edge.RIGHT] def right_reg(self, default): if not self.edge: return default elif self.marker == Edge.LEFT: return self.edge.reg[Edge.RIGHT] else: return self.edge.reg[Edge.LEFT] def is_point_right_of(self, point): """Returns True if <point> is to right of halfedge. """ edge = self.edge topsite = edge.reg[1] right_of_site = point.x > topsite.x if(right_of_site and self.marker == Edge.LEFT): return True if(not right_of_site and self.marker == Edge.RIGHT): return False if(edge.a == 1.0): dyp = point.y - topsite.y dxp = point.x - topsite.x fast = 0 if ((not right_of_site and edge.b < 0.0) or \ (right_of_site and edge.b >= 0.0)): above = dyp >= edge.b * dxp fast = above else: above = point.x + point.y * edge.b > edge.c if(edge.b < 0.0): above = not above if (not above): fast = 1 if (not fast): dxs = topsite.x - (edge.reg[0]).x above = (edge.b * (dxp*dxp - dyp*dyp)) < \ (dxs*dyp*(1.0+2.0*dxp/dxs + edge.b*edge.b)) if(edge.b < 0.0): above = not above else: # edge.b == 1.0 yl = edge.c - edge.a * point.x t1 = point.y - yl t2 = point.x - topsite.x t3 = yl - topsite.y above = t1*t1 > t2*t2 + t3*t3 if(self.marker == Edge.LEFT): return above else: return not above def intersect(self, other): """Create a new site where the Halfedges edge1 and edge2 intersect. """ edge1 = self.edge edge2 = other.edge if (edge1 is None) or (edge2 is None): return None # if the two edges bisect the same parent return None if edge1.reg[1] is edge2.reg[1]: return None d = edge1.a * edge2.b - edge1.b * edge2.a if almost_equal(d, 0.0): return None intersect_x = (edge1.c * edge2.b - edge2.c * edge1.b) / d intersect_y = (edge2.c * edge1.a - edge1.c * edge2.a) / d if edge1.reg[1] < edge2.reg[1]: halfedge = self edge = edge1 else: halfedge = other edge = edge2 right_of_site = intersect_x >= edge.reg[1].x if ((right_of_site and halfedge.marker == Edge.LEFT) or (not right_of_site and halfedge.marker == Edge.RIGHT)): return None # create a new site at the point of intersection - this is a new # vector event waiting to happen return Site((intersect_x, intersect_y)) I know this is pretty simple stuff, but thanks for any help. Edit: The entire class I'm using can be found at:
After working on some test code for open ID authentication, I had a break and when I came back, found myself faced with this bizarre warning message from GAE: Error: UnauthorizedYour client does not have permission to the requested URL /. Here is the code I am using for both the .pl code and the .yaml version: 1 runtime: python api_version: 1 builtins: - remote_api: on handlers: - url: / script: do_openid_login.py login: required auth_fail_action: unauthorized - url: /_ah/login_required script: do_openid_login.py login: required auth_fail_action: unauthorized and class MyLogin(webapp.RequestHandler): def get(self): user = users.get_current_user() if user: greeting = ("Welcome, %s %s %s! (<a href=\"%s\">sign out</a>)" % (user.nickname(), user.email(), user.user_id(), users.create_logout_url("/"))) else: greeting = ("<a href=\"%s\">Sign in or register</a>." % users.create_login_url("/")) self.response.out.write("<html><body>%s</body></html>" % greeting) application = webapp.WSGIApplication([ ('/', MyLogin), ], debug=True) def main(): run_wsgi_app(application) if __name__ == '__main__': main() Is there something that has changed? or have I done something stupid? Thanks.
Inspired by this post on how to create mirror images with Paperclip, I decided to write up how to do the same thing with CarrierWave. It's a nice example of how CarrierWave's Uploader class makes manipulating files very easy. This assumes you've already generated an uploader and probably mounted it on a model somewhere. If this doesn't make sense to you, check out the CarrierWave documentation. Add this method to you uploader: def add_mirror_effect(mirror_length) manipulate! do |img| mirror_rows = img.rows * mirror_length gradient = Magick::GradientFill.new(0, 0, mirror_rows, 0, "#888", "#000") gradient = Magick::Image.new(img.columns, mirror_rows, gradient) gradient.matte = false flipped = img.flip flipped.matte = true flipped.composite!(gradient, 0, 0, Magick::CopyOpacityCompositeOp) new_frame = Magick::Image.new(img.columns, img.rows + mirror_rows) new_frame.composite!(img, 0, 0, Magick::OverCompositeOp) new_frame.composite!(flipped, 0, img.rows, Magick::OverCompositeOp) new_frame end end This will first create a gradient. It will then flip the image and use that gradient as the alpha channel for the flipped image. Finally it will create a new image, putting the original, and the faded out mirror image together. Next, add a version to your Uploader, which calls the new add_mirror_effect method: version :with_mirror do process :add_mirror_effect => 0.2end That's it! The end result should look something like this: class AvatarUploader < CarrierWave::Uploader::Base include CarrierWave::RMagick version :with_mirror do process :resize_to_fill => [200, 200] process :add_mirror_effect => 0.2 end private def add_mirror_effect(mirror_length) manipulate! do |img| mirror_rows = img.rows * mirror_length gradient = Magick::GradientFill.new(0, 0, mirror_rows, 0, "#888", "#000") gradient = Magick::Image.new(img.columns, mirror_rows, gradient) gradient.matte = false flipped = img.flip flipped.matte = true flipped.composite!(gradient, 0, 0, Magick::CopyOpacityCompositeOp) new_frame = Magick::Image.new(img.columns, img.rows + mirror_rows) new_frame.composite!(img, 0, 0, Magick::OverCompositeOp) new_frame.composite!(flipped, 0, img.rows, Magick::OverCompositeOp) end end end For extra props, put the add_mirror_effect method in a module and include it in your Uploader.
inconnu Re : Petit guide pour aider au choix d'un langage Encore une fois merci pour toutes ces références (j'ai déjà trois bouquins de 300 pages à m'infuser ). Bon c'est quand même passionnant, dès fois un peu complexe, mais je suis globalement assez surpris de la qualité. Pour tout dire, je ne pensais pas qu'il existait des ouvrages en Français, aussi complet et accessible au débutant. Par exemple sur l'architecture de l'ordinateur. Je voulais vous demander, à tout hasard hein, si vous connaissiez une référence d'un bouquin ou d'un site, sur l'assembleur ? Ou peut être que le bouquin sur l'architecture de l'ordinateur va aborder ce langage de manière suffisante (j'en suis aux microinstructions ) ? Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! Je voulais vous demander, à tout hasard hein, si vous connaissiez une référence d'un bouquin ou d'un site, sur l'assembleur ? Ou peut être que le bouquin sur l'architecture de l'ordinateur va aborder ce langage de manière suffisante (j'en suis aux microinstructions ) ? Bon, d'abord, ce n'est pas une question pour les débutants, donc je ne vais pas l'ajouter à la présentation. Sinon, pour répondre à ta question, cela dépend fondamentalement de l'architecture à laquelle tu t'intéresses. Tu sais déjà programmer, donc tu as surtout besoin des jeux d'instructions et de savoir comment fonctionne le matériel. En conséquence, je te conseille de regarder les documentations des constructeurs et, en effet, des ouvrages génériques sur les architectures (par exemple ce qu'il y a dans la présentation du début de ce fil de discussion). De mon temps, il y avait La Bible PC de Michäel TISCHER, mais je crois que ce livre n'est plus édité. Tu peux déjà jeter un œil vers : Assembleur x86 Kip R. IRVINE Campus Press Cela dit, ce livre est vraiment orienté DOS (et architecture x86). Si tu n'as pas de problème avec l'anglais, tu peux aller voir ce site : Il y a de quoi faire. Juste une dernière chose : au vu des architectures actuelles et des capacités qui sont celles des compilateurs désormais, l'assembleur n'est plus le moyen de faire les programmes les plus rapides. De plus, l'assembleur n'est pas, par définition, portable. En revanche, cela reste toujours le moyen d'accéder finement au matériel. Je te conseille donc de ne pas chercher à faire des programmes entiers en assembleur, mais de t'habituer à coder en assembleur les parties spécifiques où tu as besoin de cet accès. Voilà, j'espère que cela aide. À bientôt. Le Farfadet Spatial L'antre du farfadet : http://le.farfadet.spatial.free.fr/ Textes, musiques et peintures Hors ligne tshirtman Re : Petit guide pour aider au choix d'un langage tiens j'étais passé à coté de ça, je traîne pas assez sur le forum (enfin pas assez partout). C'est sympa comme idée, et ça peut en effet aider un débutant, mais je suis un peu déçus par certaines mise en avant ou en retrait, tu fais le choix de donner ton avis sur les langage, ce qui ouvre donc à la critique de ces avis . Personnelement je pense que conseiller le PHP comme "excellent choix" sans préciser plus est dangereux, car s'il a l'avantage de la simplicité du déploiement (apache mod_php présent partout), c'est loin d'être un bon langage, il est bourré de problèmes syntaxiques et encourage les mauvaises pratiques, l'avis est je pense à nuancer sérieusement. Python (bon, je suis fan, "full disclosur") par contre est clairement mis en retrait, alors que c'est un langage d'une grande clarté, complètement objet, très fonctionnel (et très doué pour d'autre paradigmes), très indiqué pour le débutant, mais en effet, le swinnen n'est pas une bonne référence, les bouquins de tarek sont mieux. Bref, à mon sens, parmis les premiers langage a soumettre à un débutant, du fait de sa simplicité, la richesse de sa std, la clarté de sa syntax, le dynamisme de sa comunauté, et j'en passe. Le c++, bon, comme beaucoup de gens t'es fan, et tu l'indique en gros, comme la solution à tous les problèmes… tu nuances quand même: ce n'est pas un langage pour débutant (ouf), il faut quand même être clair, s'il peut servir de solution à pratiquement tous les développement possible (mais quel langage moderne ne peut pas y prétendre?) il est clairement peu clair, trop complexe, personne ne le maitrise à fond, toute entreprise s'en servant sérieusement en interne, pose des règles très strictes à son utilisation, pour que tout le monde s'en serve pareil (sinon personne ne parle le même c++) (voir par exemple les règles de codage pour le c++ chez google ). Et s'il était si parfait, le java (qui le le porte a un niveau supérieur) n'aurait pas eu un tel succès, mais le java a ses propres problèmes. Bref, je pense pas mal de mal de c++ (et ceci m'a aidé à savoir pourquoi). Mais je le répète, excellente initiative. Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! tu fais le choix de donner ton avis sur les langage Ce n'est pas un choix, il est tout simplement impossible de faire autrement : ce n'est pas la peine de se le cacher, à partir du moment où quelqu'un donne un conseil pour le choix d'un langage, il donne son avis. Cela dit, j'ai essayé d'être aussi objectif que possible, d'une part. D'autre part, il est clairement indiqué dès le départ qu'il y a nécessairement une part de subjectivité dans la présentation. D'ailleurs, ton intervention, je ne t'en fais pas le reproche, est très fortement marquée par ta propre subjectivité. Personnelement je pense que conseiller le PHP comme "excellent choix" Ce n'est pas ce qui est écrit : Pour le web, PHP (en général couplé à MySQL) est un très bon choix. Je ne vois pas en quoi c'est faux. Même si, oui, Python est un langage plus sérieux. sans préciser plus est dangereux, car s'il a l'avantage de la simplicité du déploiement (apache mod_php présent partout), c'est loin d'être un bon langage, il est bourré de problèmes syntaxiques et encourage les mauvaises pratiques, l'avis est je pense à nuancer sérieusement. Je reconnais bien là le Python-maniaque ! Cela dit, d'accord : que penses-tu qu'il faudrait indiquer ? Python (bon, je suis fan, "full disclosur") par contre est clairement mis en retrait Il n'est certainement pas mis en retrait. Je ne vois pas ce qui te permet de dire cela. Par contre, je trouve que les Python-maniaques ont tendance à vouloir absolument que l'on dise que Python est le meilleur langage du monde. Python a des qualités, mais il n'existe pas de langage parfait pour tout, Python pas plus que les autres. Le c++, bon, comme beaucoup de gens t'es fan Là encore, je ne sais pas ce qui te permet de dire ça. En tout cas, ce n'est certainement pas vrai. S'il se trouve que c'est le langage que j'utilise le plus souvent, c'est en raison d'un choix pragmatique, certainement pas parce que je pense que c'est le meilleur langage du monde, ni mon préféré, ni celui que je vais utiliser dans toutes les situations. et tu l'indique en gros, comme la solution à tous les problèmes… J'indique clairement qu'il est difficile, mal enseigné et qu'il n'est pas adapté pour débuter : en quoi cela sous-entend que ce serait la solution à tous les problèmes ? Et s'il était si parfait, le java (qui le le porte a un niveau supérieur) n'aurait pas eu un tel succès, mais le java a ses propres problèmes. Encore une fois, je n'ai jamais pensé ni affirmé que C++ est parfait. Ensuite, Java et C++ ne sont pas concurrents, leurs domaines d'applications ne sont absolument pas les mêmes. Java n'est pas le niveau supérieur de C++. Les concurrents, à l'heure actuelle, de C++ sont C et Fortran, les concurrents de Java sont C# et Objective-C. Bon, tu adores Python et déteste C++. Il n'empêche que C++ a de vrais qualités et que Python ne peut servir à tout. Lorsque l'on montre les indéniables qualités de C++, cela ne veut pas dire qu'on dit qu'il est la solution pour tout. À l'inverse, si on ne dit pas que Python est le seul langage à considérer, cela ne veut pas dire qu'on le met en retrait. À bientôt. Le Farfadet Spatial L'antre du farfadet : http://le.farfadet.spatial.free.fr/ Textes, musiques et peintures Hors ligne tshirtman Re : Petit guide pour aider au choix d'un langage sans vouloir entrer dans une polémique stérile, les quelques points qui me font pensé que ton jugement de python, comme de C++, sont biaisés… Dans à peu près le même domaine que Perl, mais avec peut-être une syntaxe plus claire : Python. on lit ici que python sert grosso modo aux mêmes choses que perl (principalement des petits scripts systeme, un peu de web, mais perl est clairement en perte de vitesse de ce coté là) et que ça syntaxe est *peut être* plus claire que celle de l'un des languages considéré comme l'un des plus cryptiques existant… pour un langage généralement loué pour sa clarté c'est un peu fort… pour un langage de plus en plus adopté par les scientifiques en remplacement du fortran qu'ils trainent depuis 30ans, pour un langage énormément utilisé dans le web, dans les applis industrielles, dans le dev d'outil graphique, dans de plus en plus de jeux vidéos… c'est quand même un peu fort de le comparer aux mêmes utilisations que perl… Enfin, un langage extrêmement versatile et généraliste, là j'aurais pus m'attendre à ce que tu parle de python… mais non c'est bien le classique c++, le langage du futur d'il y a 20ans, qui n'a pas atteins ses objectifs de pdm malgré le fait qu'il s'appuie honteusement sur le succès du C sans en reprendre les principaux avantages, simplicité et cohérence, sans apporter un modèle objet complet… bref, sans le mériter… edit: sur l'aspect plus constructif, je pense que faire un peu de mise en forme (séparation des langages en sections, avec titre en gras, lien vers le site du langage…) pourrais donner une meilleur visibilité en langages en bas de liste, qui sont un peu perdus dans le flou, pour qui n'a pas encore lus l'ensemble d'une traite. Dernière modification par tshirtman (Le 14/03/2010, à 21:59) Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! on lit ici que python sert grosso modo aux mêmes choses que perl (principalement des petits scripts systeme, un peu de web, mais perl est clairement en perte de vitesse de ce coté là) et que ça syntaxe est *peut être* plus claire que celle de l'un des languages considéré comme l'un des plus cryptiques existant… pour un langage généralement loué pour sa clarté c'est un peu fort… L'argument de lisibilité n'est pas facile à manipuler, raison pour laquelle j'ai mis le « peut-être ». Aujourd'hui, il est indéniable que Python, Perl et Ruby ont des domaines d'applications semblables et, pour l'instant, aucun n'a vraiment pris le pas sur les autres, en dépit de l'effet de loupe de Ubuntu. Même si, personnellement, je suis plus intéressé par Python, je pense qu'aujourd'hui, dans une présentation, on ne peut pas passer l'un des trois sous silence et il reste encore pertinent de les comparer les uns aux autres. pour un langage de plus en plus adopté par les scientifiques en remplacement du fortran qu'ils trainent depuis 30ans Python ne vient pas en remplacement de Fortran pour les scientifiques. Il vient plutôt en remplacement de Matlab ou de R. De plus, il reste inadéquat pour pas mal de cas : par exemple, il est inapproprié au calcul numérique intensif. pour un langage énormément utilisé dans le web, dans les applis industrielles, dans le dev d'outil graphique, dans de plus en plus de jeux vidéos… c'est quand même un peu fort de le comparer aux mêmes utilisations que perl… Hé bien Perl est utilisé dans le web, dans des applications industrielles, dans le développement d'outils graphiques, dans des jeux vidéos... Chez pas mal de scientifique également. Du coup, il est parfaitement pertinent de les comparer dans ce cadre. Enfin, un langage extrêmement versatile et généraliste, là j'aurais pus m'attendre à ce que tu parle de python… mais non c'est bien le classique c++ Hé bien, il est incontestable que C++ est extrêmement versatile, à tel point que son créateur l'a vu utilisé dans des domaines qu'il n'envisageait pas (voir Le Langage C++ de Bjarne STROUSTRUP). Je suis désolé, mais, pas plus que C++, je n'ai pas que Python dans la tête. le langage du futur d'il y a 20ans, qui n'a pas atteinds ses objectifs de pdm malgrès le fait qu'il s'appuis honteusement sur le succès du C sans en reprendre les principaux avantages, simplicité et cohérence, sans apporter un modele objet complet… bref, sans le mériter… Donc, c'est moi qui ait un point de vue partial et biaisé... Déjà, je ne sais pas où tu as trouvé le moindre objectif de parts de marché pour C++, qui est à l'origine un projet marginal, dont le succès a surpris (voir The Design and Evolution of C++ de Bjarne STROUSTRUP). On est très loin des ambitions de CPL à son époque ou de D plus récemment. Ensuite, ce n'est pas honteux de s'appuyer sur le passé, au contraire, c'est une bonne chose, c'est même une pratique nécessaire. Enfin, le modèle objet était balbutiant aux début de C++ et c'est notamment l'expérience acquise avec ce langage qui a permis de le faire évoluer et à devenir mature. Inutile d'essayer : je ne dirais pas que Python est le meilleur langage du monde parfait pour tout, ni non plus que C++ est lamentable. Ni l'une ni l'autre de ces affirmations n'est vraie, ceci d'un point de vue parfaitement objectif. Par contre, si tu me donnais les précautions que tu voudrais que je donne concernant PHP, je serais intéressé. À bientôt. Le Farfadet Spatial L'antre du farfadet : http://le.farfadet.spatial.free.fr/ Textes, musiques et peintures Hors ligne tshirtman Re : Petit guide pour aider au choix d'un langage Le nom C++ n'a pas été choisit au hasard, j'ai pas lus le bouquin (de référence) de Bjarn en entier (j'avoue que son style, de même que la syntaxe de son langage m'a assommé), mais j'ai bien lus le début, le but est bien de dire "c'est comme le C, mais avec des classes, mais en moins bricolage que 'C with classes'" C, à l'époque était le roi du monde… mais bon oui, on va dire que c'était un petit projet (comme C en 1968-9, c'est marrant). Quand je parle de s'appuyer sur le succès je ne parle pas de technique (même si le C++ à fait des erreurs du fait de vouloir rester compatible avec C) mais de marketing, le succès en entreprise du C++ (même partiel) est largement du au fait qu'il soit "presque C, mais avec des trucs en plus, donc ça peut servir" dans la tête de beaucoup de gens (tu constate toi même qu'il est très mal enseigné la plupart du temps) et donc profite d'un aura qu'il ne mérite pas. Pour le python dans les calculs numériques, numpy ne doit pas t'être étranger, c'est puissant… certes il faut être capable d'exprimer tes problèmes de façons matricielles, mais c'est vraiment rapide… Certes on peut aller plus vite, notamment en C, mais autant coder un module C spécialisé dans les calculs qu'on a a faire (si numpy ne convient pas), et faire tout le code autour en python. Pour PHP, j'aurais tendance à dire "un langage extrêmement répandus pour le WEB, facile à apprendre, mais souffrant d'un syntaxe assez peu cohérente, et de failles de sécurité récurrentes si employés sans une extrême rigueur", ou un truc du genre… disons qu'un langage conçus pour faire compteur de pages de CV à la base… ben ça donne ça… Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! Quand je parle de s'appuyer sur le succès je ne parle pas de technique (même si le C++ à fait des erreurs du fait de vouloir rester compatible avec C) mais de marketing C++ n'appartient à personne, comment parler de marketing ? Pour le python dans les calculs numériques, numpy ne doit pas t'être étranger, c'est puissant… certes il faut être capable d'exprimer tes problèmes de façons matricielles, mais c'est vraiment rapide… Certes on peut aller plus vite, notamment en C, mais autant coder un module C spécialisé dans les calculs qu'on a a faire (si numpy ne convient pas), et faire tout le code autour en python. Bof. Non, vraiment, il faut se rendre compte qu'absolument tous les langages, Python inclus, ont leurs limites et leurs domaines d'application. En dépit de la qualité de Numpy, Python n'est pas du tout adapté au calcul numérique à haute performance. Il n'a de toute façon pas été conçu pour cela et ce n'est pas l'objectif de Numpy -- il s'agit plutôt d'un moyen de le rendre très concurrentiel par rapport à Matlab. Pour PHP, j'aurais tendance à dire "un langage extrêmement répandus pour le WEB, facile à apprendre, mais souffrant d'un syntaxe assez peu cohérente, et de failles de sécurité récurrentes si employés sans une extrême rigueur", ou un truc du genre… disons qu'un langage conçus pour faire compteur de pages de CV à la base… ben ça donne ça… À la base, PHP est une collection de scripts qui ont été développés pour un site personnel. Il a rencontré un vrai succès parce qu'il a été le bon langage au bon moment. Finalement, c'est la même histoire que C et C++. Alors, oui, il est permissif et il faut faire attention à la façon dont on code avec. Cela dit, c'est plus un problème de faire attention aux références que l'on donne à son sujet. Pour moi, cela n'empêche qu'il demeure une bonne porte d'entrée à la programmation. Veux-tu dire que tu le déconseillerais à un débutant ? Mais alors, pour quelqu'un qui veut faire du web dynamique et seulement du web dynamique, que lui conseiller ? Sachant que c'est tout de même moins immédiat avec Python, qui n'est d'ailleurs pas proposé par tous les hébergeurs. Bon, je suis désolé, mais je ne vois pas ce que je peux faire de tout cela. À bientôt. Le Farfadet Spatial L'antre du farfadet : http://le.farfadet.spatial.free.fr/ Textes, musiques et peintures Hors ligne tshirtman Re : Petit guide pour aider au choix d'un langage Bah, tu en fais ce que tu veux, j'ai dis ce que j'avais à dire ^^. Non, vraiment, il faut se rendre compte qu'absolument tous les langages, Python inclus, ont leurs limites et leurs domaines d'application c'est vachement dogmatique, et ça me fait penser que tu cherche un domaine ou python ne serait pas le roi juste par ce que pour toi ce n'est pas possible de se dire "general purpose" et de tenir le paris… Sinon, juste sur la forme edit: sur l'aspect plus constructif, je pense que faire un peu de mise en forme (séparation des langages en sections, avec titre en gras, lien vers le site du langage…) pourrais donner une meilleur visibilité en langages en bas de liste, qui sont un peu perdus dans le flou, pour qui n'a pas encore lus l'ensemble d'une traite. c'est moins une affaire de gout personnels que de clarté, je pense pas que ce soit trop controversé comme opinion. a++ Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! Non, vraiment, il faut se rendre compte qu'absolument tous les langages, Python inclus, ont leurs limites et leurs domaines d'application c'est vachement dogmatique, et ça me fait penser que tu cherche un domaine ou python ne serait pas le roi juste par ce que pour toi ce n'est pas possible de se dire "general purpose" et de tenir le paris… Ça-y-est, je vais me faire taxer de dogmatisme... Depuis les années 60, on a vu plein de langage dont l'ambition affichée était de devenir le langage parfait pour tout. Il y a eu PL/I ou CPL, par exemple. Tous ont été des échecs retentissant : non seulement ils n'ont jamais réussi à s'imposer, mais en plus, ils n'ont jamais fait disparaître les langages qu'ils entendaient supplanter, à savoir principalement Fortran et Cobol. Ces expériences répétées me font, mais pas seulement moi, considérer avec beaucoup de circonspection toutes les tentatives qui prétendent réaliser un tel objectif. D'autant que différents domaines d'applications peuvent avoir des besoins contradictoires en matière de langage de programmation. Toujours est-il qu'aujourd'hui il n'existe pas de langage parfait pour tout. Ce n'a d'ailleurs jamais été l'objectif de Python. Il n'est notamment pas approprié au calcul numérique intensif, comme déjà dit ici, même s'il est pertinent de l'utiliser dans les traitements périphériques. Python n'est pas adapté à la programmation système. Python n'est pas non plus nécessairement le meilleur choix dans de l'embarqué -- non, dans ce cas, je ne crois pas que C++ ni même C soit un bon choix. Et ainsi de suite, j'arrête l'inventaire à la Prévert. Vraiment, il est important, si l'on apprécie un langage et que l'on veut vraiment le servir, de bien se rendre compte qu'il a un certain domaine d'application et de bien cerner ce domaine. Parce que, lorsque quelqu'un a un problème particulier, lui dire sans chercher à analyser le problème « utilise Python, c'est parfait pour tout », c'est non seulement dogmatique, mais en plus un bon moyen de le dégouter du langage lorsque, sans faire attention, on lui a conseillé ce langage alors qu'il n'est justement pas approprié au problème. je pense que faire un peu de mise en forme (séparation des langages en sections, avec titre en gras, lien vers le site du langage…) pourrais donner une meilleur visibilité en langages en bas de liste, qui sont un peu perdus dans le flou, pour qui n'a pas encore lus l'ensemble d'une traite. Ça, en revanche, c'est une remarque que je vais prendre en compte. À bientôt. Le Farfadet Spatial L'antre du farfadet : http://le.farfadet.spatial.free.fr/ Textes, musiques et peintures Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage Bonjour, Cela m'intéresserai pas mal si un fan de python pour le calcul scientifique pouvait faire un petit code de benchmark pour que l'on puisse comparer avec le c++ ou le fortran. tshirtman, tu te sentirais capable de faire un code python réalisant, par exemple, - le remplissage d'une matrice carrée M de taille n avec des nombres aléatoires - le produit matriciel MxM - L'affichage du temps de calcul ? Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! - L'affichage du temps de calcul ? Faire du benchmark est intéressant, c'est certain. Cela dit, il vaut mieux éviter de faire afficher le temps de calcul par le code lui-même et avoir recours à la fonction « time ». Le reste du code n'est pas difficile à faire. Par contre, il faut prendre une taille de matrice conséquente pour pouvoir dire quelque chose. Également, cela ne serait qu'une étape, il faudrait songer à une application un peu plus réaliste. En tout cas, ça m'intéresse aussi. Une simple multiplication matricielle doit ressembler à ça (je laisse à un Python-manique le soin de sortir un meilleur code) : import numpy A = numpy.random.rand(100000,100000) B = numpy.random.rand(100000,100000) C = A * B print C Je n'ai pas testé. À bientôt. Le Farfadet Spatial L'antre du farfadet : http://le.farfadet.spatial.free.fr/ Textes, musiques et peintures Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage Ton code à l'air de marcher. Je vais faire quelques tests. Juste une question, les matrices de numpy sont des simples ou double précision ? Hors ligne tshirtman Re : Petit guide pour aider au choix d'un langage Ce qui est bien en python c'est que quand on a un code simple et clair, c'est el général le code optimal pour la tache... le tiens me parait tout à fait correct, j'ai juste enlevé le print, qui élimine tout intéret au bench, vu la lenteur des IO en général, et des terminaux en particulier. Tu t'es posé la question de la taille mémoire nécessaire pour ce code? ^^ 100000*100000 int ça fait 10 000 000 000 de fois 32bits, j'ai peur de manquer de ram là (en fait il me laisse pas faire, ça doit être pour ça ^^) t'as une lib en C++ qui te fais ça? J'ai divisé par 100 (un 0 de chaque coté) et c'est encore un peu long (sur mon eeepc), mais ça passe. Si quelqu'un veux bien me donner un code C++ équivalent, que je bench… savoir si c'est des facteurs ou des magnitudes la différence de perf… si c'est des facteurs < 10 je vois vraiment pas pourquoi quiconque se donnerait le mal de faire ça en C++ ^^. pour l'embarqué en effet python est un peu gros (problème de stdlib énorme) mais il y a des solutions comme Cython ou ShedSkin, qui compilent du Python en C/C++ relativement optimisé, tout python n'est pas implémenté mais c'est très correct… je lance avec time et je te dis quand ça se termine. Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage Voila, J'ai utilisé des matrices 1000 x 1000 pour que cela tienne en mémoire (Le farfadet doit avoir plus l'habitude des matrices creuses), et j'ai réalisé la multiplication 10 fois. Le code python import numpy for i in range(10): A = numpy.random.rand(1000,1000) B = numpy.random.rand(1000,1000) C = A * B le résultat time python matmul.py real 0m0.791suser 0m0.640ssys 0m0.148s le code fortran PROGRAM TEST IMPLICIT NONE DOUBLE PRECISION :: A(1000,1000),B(1000,1000),C(1000,1000) INTEGER :: i DO i=1,10 CALL random_number(A) CALL random_number(B) CALL dgemm('N','N', 1000, 1000, 1000, 1 , A , 1000 , B , 1000 , 1 , C , 1000) END DO END PROGRAM TEST Le résultat time ./matmul real 0m0.415suser 0m0.384ssys 0m0.016s Ce code fortran a été compilé avec l'intel fortran et l'implémentation MKL de blas, ce qui fait peut être la différence... Hors ligne tshirtman Re : Petit guide pour aider au choix d'un langage avec des matrices de 10000*10000 c'est vachement plus long ^^ (sur eeepc901). real 9m36.119suser 0m27.438ssys 0m23.717 edit: sur ma machine de boulot (E8200 @ 2.66GHz), c'est bien plus raisonnable: real 0m8.727suser 0m6.848ssys 0m1.664s j'installe fortran-compiler, j'ai jamais touché à ce langage ^^. Dernière modification par tshirtman (Le 15/03/2010, à 11:47) Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage tshirtman, le petit exemple plus haut m'a séduit par la simplicité du langage. Et je me demande si je ne vais pas me prêter au même exercice que récemment avec le C++, c'est à dire écrire un petit code FEM en python, pour comparer les avantages et inconvénients (voir le post "de l'utilité de la POO en calcul scientifique"). Sur amazon, j'ai trouvé ce livre "Python - Les Fondamentaux du langage - La Programmation pour les scientifiques. de Matthieu Brucher" Le connais-tu ? Connais-tu une autre référence moderne ? Ce qui m'attire dans ce livre est qu'il semble spécifiquement orienté sur le calcul scientifique. Hors ligne tshirtman Re : Petit guide pour aider au choix d'un langage Content de voir que le langage te plaît . Non je ne le connais pas, et je n'ai pas spécialement lus de livres sur le sujet, mon utilisation de python est plus généraliste, j'ai lus beaucoup d'articles sur l'utilisation du python dans les sciences (biologie, physique…), mais je pourrais difficilement te recommander un livre (je suis plus "net" que bouquins pour apprendre). ps: Pourrais tu m'indiquer la ligne exacte avec laquelle tu as compilé ton code fortran plus haut? que je compare le produit matriciel de 10000² sur ma machine? ^^ Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage en fait j'utilise le compilateur INTEL FORTRAN et les librairies MKL d'intel. J'ai un makefile que j'utilise pour tous mes programmes fortran F= /opt/intel/FORTRAN/11.1/064/bin/ia32/ifort I = /opt/intel/mkl/10.2.4.032/include/32 L = /opt/intel/mkl/10.2.4.032/lib/32 matmul : matmul.f90 $F -O4 -o matmul matmul.f90 -I$I -L$L -lmkl_blas95 -lmkl_lapack95 -lmkl_intel -lmkl_sequential -lmkl_solver -lmkl_lapack -lmkl_core -liomp5 -lguide -lpthread -lm J'ai voulu compiler l'exemple avec gfortran et l'implémentation debian de blas, mais c'est extrêmement lent chez moi, je ne comprend pas pourquoi, voila ce que j'ai fait gfortran -O4 -o matmul matmul.f90 -L/usr/lib -lblas J'ai l'impression que gfortran n'aime pas les grosses matrices, ce qui serait le comble pour un compilateur destiné uniquement à du calcul numérique ! Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage Les compilateurs INTEL pour C++ et fortran sont gratuits sur linux Hors ligne tshirtman Re : Petit guide pour aider au choix d'un langage ok, téléchargement en cours ^^ (quasi 700mo en tout, c'est du lourd, je sais pas comment on faisait du fortran en 1957, huhu). Dernière modification par tshirtman (Le 15/03/2010, à 16:40) Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage et t'as essayé avec gfortran ? Hors ligne tshirtman Re : Petit guide pour aider au choix d'un langage ça compile, et ça s'exécute, mais c'est bien plus lent que python là… real 4m45.748suser 4m44.974ssys 0m0.748s là ou python mets moins d'une seconde (j'en suis resté au 1000x1000 là) Dernière modification par tshirtman (Le 15/03/2010, à 17:01) Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage Ben oui, apparemment gfortran est très mauvais. Rien ne sert d'avoir un bon langage si l'on a pas un bon compilo !!! Hors ligne tshirtman Re : Petit guide pour aider au choix d'un langage on peut parler de pypy pour les perfs de python aussi http://speed.pypy.org/overview/ pfff il faut libstdc++5 maintenant… ok, un problème de lib à l'exécution maintenant, c'est vachement fun a installer ce truc ^^ Dernière modification par tshirtman (Le 15/03/2010, à 17:31) Hors ligne
In the following code in __getattr__() if a refered variable is not found it would give an error.Similarly how to check whether a method exist or not import string import logging class Dynamo: def __init__(self,x): print "In Init def" self.x=x def __repr__(self): print self.x def __str__(self): print self.x def __int__(self): print "In Init def" def __getattr__(self, key): print "In getattr" if key == 'color': return 'PapayaWhip' else: raise AttributeError dyn = Dynamo('1') print dyn.color dyn.color = 'LemonChiffon' print dyn.color dyn.__int__() dyn.mymethod() //How to check whether this exist or not
siscard Re : Open Office, Reconnaissance de caractères, Xsane, Kooka et Cie... L'erreur de segmentation est revenue comme elle avait disparue. Si quelqu'un a une idée, je suis preneur. Tout ce que j'ai trouvé, c'est que le logiciel essaie d'utiliser un espace de mémoire qui ne lui est pas attribué; alors cela provient peut-être d'ailleurs, mais ou? Je ne suis pas encore expert dans Linux ni Ubuntu que j'utilise seulement depuis quelques mois. Merci Dernière modification par siscard (Le 24/11/2011, à 17:35) Hors ligne siscard Re : Open Office, Reconnaissance de caractères, Xsane, Kooka et Cie... Par acquis de conscience, et après avoir essayé sans succès de nombreuses manips suggérées dans le forum, j'ai installé cuneiform (0.7.0) avec Magick sur mon vieux portable (10 ans et il supporte bien U11.04) aussi, mais lui n'a pas subi les outrages que j'ai fait subir au fixe (notamment tentative de mise à niveau vers 11.10 puis retour en arrière) Résultat identique Erreur de Segmentation. Alors, il y a peut-être un pb à la source (j'utilise Synaptic pour l'installation). Y-a-t-il quelqu'un ici ??? quelqu'un ici ??? un ici ??? ici ??? Dernière modification par siscard (Le 24/11/2011, à 17:37) Hors ligne ub821 Re : Open Office, Reconnaissance de caractères, Xsane, Kooka et Cie... Bonjour à Toutes et Tous de ROC Avant toute chose, puisqu'en première page et premier post, rien n'est indiqué et que cela date de 2006, modifié 2008, tel que c'est décrit dans le premier post, çà "doit" fonctionner ? Ou bien alors, je me "tape" les 20 pages pour apprendre à la fin, que bon... je n'ai qu'à "circuler" et que çà gazouille que dans certains cas... et au scan d'une page en ROC, une belle boite de dialogue qui indique : "Erreur de processus enfant" : Failed to execute OCR command : xsane2tess -l fra: Aucun fichier ou dossier de ce type Merci d'avoir pris le temps de lire, et surtout... de répondre sur ce sujet Dernière modification par ub821 (Le 29/04/2012, à 15:54) Cordialement Bernard Debian 7.0 Asus P4P800, P4 2,6Ghz, Seagate laptop SSHD 500Go, Nvidia GF 6200 512 Mo Hors ligne nabla Re : Open Office, Reconnaissance de caractères, Xsane, Kooka et Cie... Bonjour, Pour ne pas laisser "ub821" sans réponse, je m'y colle ;-) Je ne suis que Linuxien ; pas informaticien. Je tripatouille un peu en lignes de commandes mais uniquement grâce aux forums. Un mec normal quoi. Actuellement sous Linux ubuntu 10.4 depuis qu'il est sorti soit Ubuntu 10.04.4 LTS (Linux version 2.6.32-41-generic). ça tourne sur un Dell Inspiron 1525 de 2008. J'utilise Xsane Image Scaner en mode numérisation d'images et en OCR avec bonheur et bons résultats ... après être passé à xsane2tess à la place de GOCR. Ma commande OCR est modifiée en "xsane2tess -l fra" (dans Xsan, "préférences" --> "configuration" --> onglet "OCR") Je le redis, ça marche du 'tonnerre de dieu' avec du texte noir sur fond blanc. Comme mon ordi principal est sous Mac, Ubuntu et Xsane sont ma seule solution pour faire de la ROC et cela me satisfait pleinement. @+ P.S. : j'ai même essayé de faire de la ROC depuis images, photos et PDF = ça marche plutôt bien si fichier de bonne qualité visuelle. Hors ligne Papy Octet Re : Open Office, Reconnaissance de caractères, Xsane, Kooka et Cie... Bonjour, Moi, j'utilise XSane pour mon scanner puis, pour la reconnaissance des caractères, c'est gscan2pdf qui s'y colle. Il permet de sortir un document pdf - comme son nom l'indique - mais aussi un fichier texte .rtf. Comme l'indique nabla, il faut un peu "retravailler" la page scannée pour augmenter un max les contrastes et enlever la couleur. Un scan en tons de gris à 300 pixels/pouce est recommandé pour s'assurer une reconnaissance acceptable et un fichier pas trop gros. Personnellement, en tons de gris, je montre à 400 PPP (pixels par pouce) lors du scan puis j'augmente le contraste et j'enregistre l'image. Puis je lance gscan2pdf en réglant les paramètres de sortie vers un fichier .rtf que je peux exploiter ultérieurement. Je suis sous Ubuntu 11.10 64 bits. A+ AMD A6-3500 HD6530D 2.1 ghz Triple core FM1 3mb - CM GIGABYTE GA-A75M-UD2H - 8 GiO ram DDR3 - HDD 1TO WD GREEN + WD Gaviar Black 1TO + externe IOMEGA 500GiO - Carte écran nvidia GeForce 210 Silent avec 1GiO cache DDR3 - Ubuntu Portable HP - Intel Centrino - 1 Go DDR2 - DD 120 Go - Mint 14 Imprim. Samsung ML-1670 et CLP-315, scanner Epson Perfection V30, ... Linuxgraphic.org, LibreOffice.org Hors ligne compte supprimé Re : Open Office, Reconnaissance de caractères, Xsane, Kooka et Cie... Sinon, pour tesseract, y'a comme interface graphique OCRfeeder, qui est à mon avis ce qui se fait de mieux en logiciel d'OCR sur GNU/linux (export en .odt, correction d'image avec unpaper, détection automatique des paragraphes...). Papy Octet Re : Open Office, Reconnaissance de caractères, Xsane, Kooka et Cie... Ah !? Je ne connaissais pas celui-là. Faudra que j'essaie alors. Merci monsieurweller. Dernière modification par Papy Octet (Le 30/04/2012, à 06:44) AMD A6-3500 HD6530D 2.1 ghz Triple core FM1 3mb - CM GIGABYTE GA-A75M-UD2H - 8 GiO ram DDR3 - HDD 1TO WD GREEN + WD Gaviar Black 1TO + externe IOMEGA 500GiO - Carte écran nvidia GeForce 210 Silent avec 1GiO cache DDR3 - Ubuntu Portable HP - Intel Centrino - 1 Go DDR2 - DD 120 Go - Mint 14 Imprim. Samsung ML-1670 et CLP-315, scanner Epson Perfection V30, ... Linuxgraphic.org, LibreOffice.org Hors ligne ub821 Re : Open Office, Reconnaissance de caractères, Xsane, Kooka et Cie... Bonjour et un grand MERCI à vous trois pour vos réponses @nabla : rassures toi, je suis tout comme toi, pas informaticien mais tripatouilleur en tout @Papy Octet : tout comme toi, j'suis Grand Père @monsieurweller : tu donnes l'envie avec OCRfeeder, et tu me nous laisses sur notre faim... Heureusement que Papy Octet donne des liens, toutefois c'est en languasses estrangère... et moi et langue hiche, et encore plus l'all ment... bouhhh çà fait plus que çà... non, non... encore plus... Tout cela pour dire, que sans le traducteur de chromium, j'serais ben enquiquiné Si tu avais le lien de chargement de OCRfeeder, ce serait gentil de nous le confier:) Dans la doc de ubuntu, point de OCRfeeder ! En attendant... j'ai installé le paquet tesseract de b52 version 2.04 et tester si cela faisait de la ROC... et il me crée bien un fichier .txt mais vide !!! Voici la commande, des fois que je ma trompé [bernard@bernard-desktop:~] $ tesseract ~/out.tiff test2 -lwt fra Tesseract Open Source OCR Engine modif command line by b52 imagename outputbase [ -l lang OR -lwt lang] [configfile [[+|-]varfile]... -l = Lang Without Tiff -lwt = Lang With Tiff Tesseract Open Source OCR Engine [bernard@bernard-desktop:~] $ [bernard@bernard-desktop:~] $ tesseract ~/out.tif test2 -lwt fra Tesseract Open Source OCR Engine modif command line by b52 imagename outputbase [ -l lang OR -lwt lang] [configfile [[+|-]varfile]... -l = Lang Without Tiff -lwt = Lang With Tiff Tesseract Open Source OCR Engine check_legal_image_size:Error:Only 1,2,4,5,6,8 bpp are supported:32 Erreur de segmentation [bernard@bernard-desktop:~] $ tesseract ~/out.tiff test2 -lwt fra Tesseract Open Source OCR Engine modif command line by b52 imagename outputbase [ -l lang OR -lwt lang] [configfile [[+|-]varfile]... -l = Lang Without Tiff -lwt = Lang With Tiff Tesseract Open Source OCR Engine [bernard@bernard-desktop:~] $ en changeant l'extension du fichier, puisque j'ai lu que TIF était moins ou plus reconnu que TIFF, toutefois, rien n'y fait... ! Toujours en attendant, Je vais tester gscan2pdf... des fois que... A bientôt Cordialement Bernard Debian 7.0 Asus P4P800, P4 2,6Ghz, Seagate laptop SSHD 500Go, Nvidia GF 6200 512 Mo Hors ligne ub821 Re : Open Office, Reconnaissance de caractères, Xsane, Kooka et Cie... Bonjour Il y a aussi cette interface graphique sur Debian que je n'ai pas essayée. Merci Roger J'ai chargé ce programme, mais... il me dit : Erreur : Dépendance non satisfaite : libaspell15 (>= 0.60.7~201101707) Et là... le gros moment de sollitude, car impossible à trouver la mise à jour de ce bousin... Purée de purée... ! à force d'à force, je trouve libaspell15 et au moment de l'installer, il me dit : Erreur : <<aspell>> : dépendance cassé avec libaspell15 (=0.60.6-3ubuntu1) Toujours en cherchant... sur cette discussion : http://forum.ubuntu-fr.org/viewtopic.php?id=626931 j'ai pris l'ancienne version de yagf et il m'installe cuneiform, je teste et bouhhhhhhh que c'est laid !!! Bon, vala où j'en suis... c'est à dire toujours au même point... aucun ROC ! Aller... j'vais défiler... c'est le 1er Mai Cordialement Bernard Debian 7.0 Asus P4P800, P4 2,6Ghz, Seagate laptop SSHD 500Go, Nvidia GF 6200 512 Mo Hors ligne compte supprimé Re : Open Office, Reconnaissance de caractères, Xsane, Kooka et Cie... Bonjour Il y a aussi cette interface graphique sur Debian que je n'ai pas essayée. De ce que je me souviens de mes tests, cette interface est surtout utile pour cuneiform, un système d'OCR libre russe, sympa mais quand même bien moins efficace que tesseract. @monsieurweller : tu donnes l'envie avec OCRfeeder, et tu me nous laisses sur notre faim... Il est dans les dépôts d'ubuntu 12.04. Sinon, son site officiel (avec des captures d'écran) : https://live.gnome.org/OCRFeeder ub821 Re : Open Office, Reconnaissance de caractères, Xsane, Kooka et Cie... Bonsoir Je te remercie Comme indiqué dans ma signature, j'suis en 10.04.4LTS, voilà le pourquoi il était invisible dans le synaptic... aussi, souhaitons qu'il fonctionne bien sous ma version ! Je testerai demain et donnerai le résultat Encore Merci Cordialement Bernard Debian 7.0 Asus P4P800, P4 2,6Ghz, Seagate laptop SSHD 500Go, Nvidia GF 6200 512 Mo Hors ligne compte supprimé Re : Open Office, Reconnaissance de caractères, Xsane, Kooka et Cie... Pour ubuntu 10.04, ce ppa le propose (peut-être pas la dernière version toutefois) : https://launchpad.net/~alex-p/+archive/notesalexp-lucid Pour l'installer via le ppa, dans un terminal : sudo add-apt-repository ppa:alex-p/notesalexp-lucid sudo apt-get update sudo apt-get install ocrfeeder ub821 Re : Open Office, Reconnaissance de caractères, Xsane, Kooka et Cie... Pour ubuntu 10.04, ce ppa le propose (peut-être pas la dernière version toutefois) : https://launchpad.net/~alex-p/+archive/notesalexp-lucid Pour l'installer via le ppa, dans un terminal : sudo add-apt-repository ppa:alex-p/notesalexp-lucid sudo apt-get update sudo apt-get install ocrfeeder Encore Merci Et voui... ce ppa, je le méconnaissais ! J'ai vu ce qu'il contenait, et il y a quelques paquets sympa J'ai mis à jour Merci pour le partage Cordialement Bernard Debian 7.0 Asus P4P800, P4 2,6Ghz, Seagate laptop SSHD 500Go, Nvidia GF 6200 512 Mo Hors ligne ub821 Re : Open Office, Reconnaissance de caractères, Xsane, Kooka et Cie... le retour... celui d'expérience OCRFeeder est bien là, dans la section bureautique... ??? !!! bon... pourquoi pas après tout Le hic, c'est que je le sélectionne et... rien ! Je vérifie par htop ce qui se passe et rien de spécial apparaît en ligne ! Y a-t-il une manière de contrôler si OCRFeeder est correctement installé et que tous les paquets dont il a besoin, sont présents et liés ? J'ai testé sur un texte quelconque, avec gscan2pdf, avec tesseract de sélectionné, et le résultat est moyen... il faut tout reprendre et corriger à la mano... ! Maintenant, tous ceux que j'ai installé et qui sont non fonctionnels, genre yagf et ses dépendances qu'il a eu besoin, y a-t-il une manière "propre" de le supprimer, sans faire des boulettes... car à part dans le riz, ou le couscous... j'aime mieux éviter... A bientôt Dernière modification par ub821 (Le 02/05/2012, à 16:51) Cordialement Bernard Debian 7.0 Asus P4P800, P4 2,6Ghz, Seagate laptop SSHD 500Go, Nvidia GF 6200 512 Mo Hors ligne compte supprimé Re : Open Office, Reconnaissance de caractères, Xsane, Kooka et Cie... Pour OCRfeeder : il te renvoie vraiment rien, si tu le lances via un terminal ? Et il n'a pas posé de problème de dépendances (genre gtk3) à l'installation ? Sinon, je testerais sur l'ordi familial (encore sous 10.04) ce W.E. ub821 Re : Open Office, Reconnaissance de caractères, Xsane, Kooka et Cie... Pour OCRfeeder : il te renvoie vraiment rien, si tu le lances via un terminal ? Et il n'a pas posé de problème de dépendances (genre gtk3) à l'installation ? Sinon, je testerais sur l'ordi familial (encore sous 10.04) ce W.E. J'ai fait le test par l'icône et en ligne de commande, résultat = commande introuvable ! Il n'a posé aucun problème de dépendance à l'install ! et je te remercie de tester cette fin de semaine... après le vote... hein... Dernière modification par ub821 (Le 03/05/2012, à 09:13) Cordialement Bernard Debian 7.0 Asus P4P800, P4 2,6Ghz, Seagate laptop SSHD 500Go, Nvidia GF 6200 512 Mo Hors ligne compte supprimé Re : Open Office, Reconnaissance de caractères, Xsane, Kooka et Cie... Sinon, essaie de lancer ça : /usr/bin/ocrfeeder Ou encore ça : /usr/local/bin/ocrfeeder ub821 Re : Open Office, Reconnaissance de caractères, Xsane, Kooka et Cie... Sinon, essaie de lancer ça : /usr/bin/ocrfeeder Ou encore ça : /usr/local/bin/ocrfeeder Merci Je l'ai désinstallé et suis en train de le réinstaller, en notant toutes les dépendances, paquets suggérés, recommandés... et il y en a un... paquet... Je ferai un retour d'expérience, lorsque tout sera réinstallé Cordialement Bernard Debian 7.0 Asus P4P800, P4 2,6Ghz, Seagate laptop SSHD 500Go, Nvidia GF 6200 512 Mo Hors ligne ub821 Re : Open Office, Reconnaissance de caractères, Xsane, Kooka et Cie... Le retour... J'ai réinstallé OCRFeeder ainsi que tous les paquets suggérés, et recommandés au fur et à mesure des suggestions et recommandations... Au clic sur l'icône OCRFeeder = rien ne se passe, confirmé par htop ! Maintenant par les lignes de commandes : [bernard@bernard-desktop:~] $ ocrfeeder Traceback (most recent call last): File "/usr/bin/ocrfeeder", line 31, in <module> from ocrfeeder.studio.studioBuilder import Studio File "/usr/lib/pymodules/python2.6/ocrfeeder/studio/studioBuilder.py", line 27, in <module> from widgetModeler import SourceImagesListStore, \ File "/usr/lib/pymodules/python2.6/ocrfeeder/studio/widgetModeler.py", line 23, in <module> from ocrfeeder.feeder.documentGeneration import OdtGenerator, HtmlGenerator, PlaintextGenerator, PdfGenerator File "/usr/lib/pymodules/python2.6/ocrfeeder/feeder/documentGeneration.py", line 33, in <module> from reportlab.pdfgen import canvas ImportError: No module named reportlab.pdfgen [bernard@bernard-desktop:~] $ Puis en suivant tes suggestions : [bernard@bernard-desktop:~] $ /usr/bin/ocrfeeder Traceback (most recent call last): File "/usr/bin/ocrfeeder", line 31, in <module> from ocrfeeder.studio.studioBuilder import Studio File "/usr/lib/pymodules/python2.6/ocrfeeder/studio/studioBuilder.py", line 27, in <module> from widgetModeler import SourceImagesListStore, \ File "/usr/lib/pymodules/python2.6/ocrfeeder/studio/widgetModeler.py", line 23, in <module> from ocrfeeder.feeder.documentGeneration import OdtGenerator, HtmlGenerator, PlaintextGenerator, PdfGenerator File "/usr/lib/pymodules/python2.6/ocrfeeder/feeder/documentGeneration.py", line 33, in <module> from reportlab.pdfgen import canvas ImportError: No module named reportlab.pdfgen [bernard@bernard-desktop:~] $ [bernard@bernard-desktop:~] $ /usr/local/bin/ocrfeeder bash: /usr/local/bin/ocrfeeder: Aucun fichier ou dossier de ce type [bernard@bernard-desktop:~] $ Je constate qu'il y a des lignes 'line' dans quelques fichiers, qui sont mises en évidence... ont-elles des anomalies ? si oui, de quelle manière puis-je, ou pas... les solutionner, si solution il y a Merci d'avance pour le coup de main Cordialement Bernard Debian 7.0 Asus P4P800, P4 2,6Ghz, Seagate laptop SSHD 500Go, Nvidia GF 6200 512 Mo Hors ligne compte supprimé Re : Open Office, Reconnaissance de caractères, Xsane, Kooka et Cie... Essaie d'installer le paquet python-reportlab. ub821 Re : Open Office, Reconnaissance de caractères, Xsane, Kooka et Cie... Essaie d'installer le paquet python-reportlab. Merci pour la suggestion, voici le résultat : [bernard@bernard-desktop:~] $ sudo apt-get install python-reportlab [sudo] password for bernard: Lecture des listes de paquets... Fait Construction de l'arbre des dépendances Lecture des informations d'état... Fait Paquets suggérés : python-egenix-mxtexttools python-reportlab-doc Paquets recommandés : python-reportlab-accel python-renderpm Les NOUVEAUX paquets suivants seront installés : python-reportlab 0 mis à jour, 1 nouvellement installés, 0 à enlever et 0 non mis à jour. 1 partiellement installés ou enlevés. Il est nécessaire de prendre 543ko dans les archives. Après cette opération, 2 593ko d'espace disque supplémentaires seront utilisés. Réception de : 1 http://fr.archive.ubuntu.com/ubuntu/ lucid/main python-reportlab 2.4-1 [543kB] 543ko réceptionnés en 11s (48,2ko/s) Sélection du paquet python-reportlab précédemment désélectionné. (Lecture de la base de données... 223387 fichiers et répertoires déjà installés.) Dépaquetage de python-reportlab (à partir de .../python-reportlab_2.4-1_all.deb) ... Paramétrage de libatlas3gf-3dnow (3.6.0-24ubuntu1) ... dpkg : erreur de traitement de libatlas3gf-3dnow (--configure) : le sous-processus script post-installation installé a retourné une erreur de sortie d'état 30 Paramétrage de python-reportlab (2.4-1) ... Traitement des actions différées (« triggers ») pour « python-central »... Des erreurs ont été rencontrées pendant l'exécution : libatlas3gf-3dnow Pré-raccordement des bibliothèques en cours, veuillez patienter... E: Sub-process /usr/bin/dpkg returned an error code (1) [bernard@bernard-desktop:~] $ Il y a libatlas3gf-3dnow qui pose apparemment problème ! Au cours de l'installation, il y a eu un bel écran bleu... çà faisait longtemps qui m'informait qu'il était empêché de s'installer, j'ai fait ok et cela a continuer l'installation des autres paquets ! Si ce paquet est inutile, je peux le supprimer ! non ? au point où j'en suis, je peux tester... Cordialement Bernard Debian 7.0 Asus P4P800, P4 2,6Ghz, Seagate laptop SSHD 500Go, Nvidia GF 6200 512 Mo Hors ligne compte supprimé Re : Open Office, Reconnaissance de caractères, Xsane, Kooka et Cie... Oui, essaie de supprimer ce paquet "libatlas3gf-3dnow" : je sais pas à quoi il sert, mais il bloque tout. Mais avant, vérifie s'il ne dégage pas au passage d'autres trucs plus vitaux. ub821 Re : Open Office, Reconnaissance de caractères, Xsane, Kooka et Cie... Oui, essaie de supprimer ce paquet "libatlas3gf-3dnow" : je sais pas à quoi il sert, mais il bloque tout. Mais avant, vérifie s'il ne dégage pas au passage d'autres trucs plus vitaux. Ayé... je viens de le supprimer avec synaptic, il n'y a eu que lui, aucun autre paquet ou dépendance ! Je retente l'essai Cordialement Bernard Debian 7.0 Asus P4P800, P4 2,6Ghz, Seagate laptop SSHD 500Go, Nvidia GF 6200 512 Mo Hors ligne ub821 Re : Open Office, Reconnaissance de caractères, Xsane, Kooka et Cie... C'était bien libatlas3gf-3dnow qui bloquait la ROC ! Je viens de faire un essais avec OCRFeeder, et il s'en sort pas trop mal... pas mal de rectif à faire, mais... j'évite de trop me plaindre... il est gratuit Encore Merci à vous tous Cordialement Bernard Debian 7.0 Asus P4P800, P4 2,6Ghz, Seagate laptop SSHD 500Go, Nvidia GF 6200 512 Mo Hors ligne
use the following search parameters to narrow your results: e.g. subreddit:aww site:imgur.com dog subreddit:aww site:imgur.com dog see the search faq for details. advanced search: by author, subreddit... 490 users here now /r/programming is a reddit for discussion and news about computer programming Guidelines Please try to keep submissions on topic and of high quality. Just because it has a computer in it doesn't make it programming. Memes and image macros are not acceptable forms of content. If there is no code in your link, it probably doesn't belong here. App demos should include code and/or architecture discussion. Please follow proper reddiquette. Info Do you have a question? Check out /r/learnprogramming, /r/cscareerquestions, or stackoverflow. Do you have something funny to share with fellow programmers? Please take it to /r/ProgrammerHumor/. For posting job listings, please visit /r/forhire or /r/jobbit. Check out our faq. It could use some updating. If you're an all-star hacker (or even just beginning), why not join the discussion at /r/redditdev and steal our reddit code! Related reddits /r/technology /r/learnprogramming /r/coding /r/compsci /r/dailyprogrammer /r/netsec /r/webdev /r/web_design /r/gamedev /r/cscareerquestions /r/reverseengineering /r/startups /r/techsupport Specific languages An attempt to filter youtube comment spam using Bayes (github.com) submitted 2 years ago by c0c0c0 [–][deleted] 2 years ago* (20 children) [deleted] [–]c0c0c0[S] 3 points4 points5 points 2 years ago (0 children) Hey, thanks for your suggestions. There has been a lot of good discussion in this thread and I've got a lot of feedback & ideas to look at and evaluate. Couple points: I agree that the log probabilities is a better way to do it, however since I use only the 10 most significant tokens to calculate the probability, in practice it will never underflow. Also , I tested the model on youtube comments that were completely separate from the comments that it was trained on. I perhaps should re-word that in the readme to make it clearer. [–]brucifer 4 points5 points6 points 2 years ago (9 children) I have to disagree with a few points here. Firstly, double weighting certain words is completely contrary to the nature of a Bayes net. The nice thing about a Bayes net is that you don't have to teach it which words are relevant--it learns for itself. If "http" is very highly associated with spam, then the probabilities will reflect that. Naive Bayes is popular because it's easy AND effective. Using Naive Bayes, you can, within a day, write a program that will get 98% success and less than 2% false positives on email spam (I did this last weekend). Doubtless, there are better techniques, but Naive Bayes is not too shabby. Finally, the author did not test the model on training data. The model was tested on a selection of comments from outside the training corpus. Laplace smoothing and log sums are good ideas, though. [–][deleted] 2 years ago (6 children) [–]ItsAConspiracy 3 points4 points5 points 2 years ago (4 children) Paul Graham reported similar results back when he introduced the idea. Naive Bayes is a bayes net, according to Daphne Koller. It's just that the network is structured with one node that has no outgoing edges, and all the other nodes having a single edge pointing to the first node. [–][deleted] 2 years ago (3 children) [–]ItsAConspiracy 1 point2 points3 points 2 years ago (2 children) That graph structure implies the independence between nodes, for as long as the central node is unobserved. Koller explained the general bayesian network first, then had one 15-minute lecture in which she said "btw, here's a simple bayesian network called Naive Bayes, or alternatively, Idiot Bayes." After that she didn't mention it again. I think Graham just gave it a run and reported the percentages he got, rather than getting real thorough. But even if his numbers were good, it wouldn't be surprising if he got better results simply from being the first to use the technique, before spammers adapted. Looks like there's some interesting stuff in that paper, I'll read it more closely later. [–]couldthisbeart 2 points3 points4 points 2 years ago (1 child) You have it backwards. The independence assumption is that the features are independent given the class. The edges should point from the class node to the feature nodes. [–]ItsAConspiracy 0 points1 point2 points 2 years ago (0 children) Just reviewed the video and you are correct. [–]brucifer 1 point2 points3 points 2 years ago (0 children) Sorry, it was a brain fart. I actually meant Naive Bayes Classifier. As for my results, I'm using the CEAS 2008 Live Spam Challenge Laboratory Corpus. The training set is approximately 3000 ham/spam emails. With my current version, I am getting 97.7% accuracy (0.0% false positives, 2.9% false negatives) after running over 40,000 emails. I prioritized reducing false negatives over reducing false positives, though, so it's not hard to get less than 1% false positives, but the false negatives go up to around 1% (which is kinda unacceptable). Currently, I'm trying to get the false negatives down and rewrite the code to be more mathematically valid and less hacky. [–]thisisjimmy 0 points1 point2 points 2 years ago (1 child) I'm wondering, why would log sums help prevent underflow? Doubles can have an exponent as small as 10-308. Is this not sufficient? The problem is not entirely with underflow. You also need to worry about accumulating rounding errors. However, underflow is also a serious concern. For example, when calculating the probability that an email is spam, you have to first calculate the probability of seeing all of the words in the email, given that it's spam (and then again for if it's not spam). Suppose in your training corpus, you encounter 10,000 unique tokens and the email you want to classify has 100 unique tokens. If each token has only occurred only a few times in your corpus, you're looking at something on the order of (1/10000)100 = 10-400 [–]ruinercollector 7 points8 points9 points 2 years ago (1 child) There is so much dickishness to your post, I'm not sure where to start. Different smoothing techniques are better for different applications. Paul Graham's approach that the author uses has proven to be pretty good. Also Laplace smoothing is not necessarily +1. α can be any number of values. Yes, but don't be a dick about it. Punctuation has an individual isolated significance in analyzing spam. Exclamation marks have a higher probability in spam by themselves. So, yes, actually it does make sense. Unigrams are n-grams. He can consider using higher order n-grams, but he's not wrong for not doing so, and several bayesian spam filters have been successful in doing so. A naive bayes filter is like 10 lines of code. It's hardly wheel reinvention not to dig up a library that would include much more. Particularly when he's using an uncommon smoothing method and a simpler lambda weighting system than most libraries would provide. No, no, no. Naive Bayes is not "popular because it's easy, but actually a piece of shit." In fact, it's quite far from the bubble-sort of NLP that you make it out to be. It is absolutely the correct method for certain tasks exactly like this one. When you need decent performance over a very large training corpus and a set of conditions for classification that are not easily generalizable, naive bayes is the right answer. Again, yes, but don't be a dick about it. TL;DR: Intro to NLP isnt' a license to be a dick. [–]Mr_Smartypants 0 points1 point2 points 2 years ago (6 children) Use Laplace smoothing (i.e., +1) Use Laplace smoothing (i.e., +1) I've had good success with + 0.1 instead of + 1.0. probabilities are smaller but still not zero. [–][deleted] 2 years ago (5 children) [–]Mr_Smartypants 0 points1 point2 points 2 years ago (4 children) I can't tell if you're agreeing with me or contradicting me.... I'm stating that it does have an effect, and it is a simple parameter to tune, e.g. though cross-validation. [–]Mr_Smartypants 0 points1 point2 points 2 years ago (2 children) Lol! It "doesn't matter" exactly inasmuch as one doesn't care about the error rate! [–][deleted] 2 years ago (1 child) [–]Mr_Smartypants 0 points1 point2 points 2 years ago (0 children) Error bars would have been useful (and simulated data always makes me uncomfortable) , but yes, that was of interest! [–]DataWraith 14 points15 points16 points 2 years ago* (22 children) Cool. The biggest problem seems to be unreliable training data, but after that it could probably be further improved with some pseudo-words that are determined by statistics, such as average word-length (high for run-together text), ratio of uppercase characters to lowercase characters, ratio of punctuation characters to alphanumeric characters, length of the comment, ratio of words not found in a dictionary, etc. The parser should also shorten repeated characters ("looooooooooool" -> "looool") to reduce duplicate entries in the dictionary. [–]c0c0c0[S] 5 points6 points7 points 2 years ago (6 children) Good ideas! I hadn't thought of removing the dupe characters like that. That should clean things up quite a bit [–]python-fan 6 points7 points8 points 2 years ago (2 children) Paul Graham found, when creating his email spam filter, that stemming removed information that was helpful for classifier performance. Link [–]PendingPhysics 0 points1 point2 points 2 years ago (0 children) Cool. Thanks for linking. [–]Chemical_Scum 0 points1 point2 points 2 years ago (0 children) I'd accept that for emoticons, as different emoticons would fit in different contexts, but an email address/web link is meaningless to the context. It is like a NAME token. [–]DataWraith 0 points1 point2 points 2 years ago (0 children) 1) You should add a prior - this will handle the case where a+b==0 in a way that has a natural probabilistic interpretation 1) You should add a prior - this will handle the case where a+b==0 in a way that has a natural probabilistic interpretation He's already using a prior, 0.4. [Link] [–]ruinercollector 0 points1 point2 points 2 years ago (0 children) It's an idea, but prior work has shown that stop words and stemming end up sucking for spam detection. [–]Lorem_Ipsum 5 points6 points7 points 2 years ago (8 children) I remember a Firefox extension I had that just filtered everything by punctuation. Any comment that lacked proper capitals, or contained repeating punctuation marks was simply removed. Except it allowed fake comments and spam through as long as it was punctuated. [–]UncertainCat 3 points4 points5 points 2 years ago (1 child) So, you could still see "Please visit our website, http://5z8.info/whitepower_k6w4jv_begin-bank-account-xfer to purchase quality penis enlargement pills." I think spam would be better if it were punctuated. [–]Lorem_Ipsum 0 points1 point2 points 2 years ago (0 children) I think so, it might have had some other parameters for filtering things as well. [–]miggyb 2 points3 points4 points 2 years ago (2 children) the problem is the whole brevity is the soul of wit thing where short comments can be worth reading without having any capitalization or punctuation [–]Slime0 5 points6 points7 points 2 years ago (1 child) A lack of capitalization and punctuation is not brevity. [–]miggyb 1 point2 points3 points 2 years ago (0 children) but many times it just takes one word to get your point across Sounds like the Strunk & White computer virus... [–]unoriginal42 2 points3 points4 points 2 years ago (5 children) The parser should also shorten repeated characters ("looooooooooool" -> "looool") to reduce duplicate entries in the dictionary. You might want to look at stemming. I wonder if there is a library that'll be able to stem something like v1agra => viagra. Since you're using python - take a peak at the NLTK [–]DataWraith 1 point2 points3 points 2 years ago* (4 children) You might want to look at stemming. I wonder if there is a library that'll be able to stem something like v1agra => viagra. You might want to look at stemming. I wonder if there is a library that'll be able to stem something like v1agra => viagra. Stemming tends to not be useful for naive bayesian classifiers, unless you have very little data to work with. It can actually hurt, as it would in your example: a doctor might need to write about viagra in an email, but if it's spelled v1agra, it's almost certainly spam. Edit: You could make the same argument with regards to squeezing out repeated characters after four occurrences, but I feel that in that case the accuracy you gain from aggregating (more data per "word") outweights the accuracy you lose from not counting them separately. [–]unoriginal42 0 points1 point2 points 2 years ago (3 children) a doctor might need to write about viagra in an email a doctor might need to write about viagra in an email I don't think you'd need to worry about this on youtube. AFAIK you want to minimize duplicate tokens which we could consider the same so as to increase the affect of those token - spammy or not. Perhaps you'd even want to go as far as changing any link to be [URL] on the basis that posts with links are more likely to be spam. [–]DataWraith 1 point2 points3 points 2 years ago* (1 child) AFAIK you want to minimize duplicate tokens which we could consider the same so as to increase the affect of those token - spammy or not. Yes, you want to minimize duplicate tokens, but not at the expense of discriminative power. I guess my point then was that I would not consider "www.google.com" the same as "[URL]", "loan" the same as "mortgage", "v1agra" the same as "viagra", "house" the same as "housing", even though these are related to each other. I would however consider "loooooooooooool" the same as "loooool" the same as "looool" (but not the same as "lol") and "khaaaaaaaaaaaan" the same as "khaaaan" (but not the same as "khan"). It's a matter of where you draw the line. <edit>: I was thinking of this Paul Graham essay when I brought up my doctor/viagra example: Misspellings end up having higher spam probabilities than the words they're intended to conceal. In my filter the spam probability of "Viagra" is .9848, and of "V1agra" .9998. For this kind of trick to work, you have to be the first person to use nearly every misspelling in a spam. The odds of doing that are low, and if you fail you merely teach the filter all the new misspellings. Misspellings end up having higher spam probabilities than the words they're intended to conceal. In my filter the spam probability of "Viagra" is .9848, and of "V1agra" .9998. For this kind of trick to work, you have to be the first person to use nearly every misspelling in a spam. The odds of doing that are low, and if you fail you merely teach the filter all the new misspellings. </edit> Perhaps you'd even want to go as far as changing any link to be [URL] on the basis that posts with links are more likely to be spam. I would add a separate "contains-url" token, while leaving the original url intact. Additional data doesn't hurt you (at worst it gets a useless .5 probability), but tossing data out (by replacing with a placeholder) is another matter entirely. Granted, it's probably not going to matter for Youtube comments, but in the general case it might. [–]unoriginal42 1 point2 points3 points 2 years ago (0 children) It's a matter of where you draw the line. I completely agree. I suppose I'm discounting too many of the things that we would think of as hallmarks of spam by being very aggressive with the stemming. On the other hand, I don't know if the large 'surface area' of stem words in youtubish would mean it'd be hard to get any sort of decent accuracy with OP's training set of ~3000. I like the idea of adding new words. Perhaps even something like account age in months could be considered. I hadn't read that Graham essay before, thanks. [–]anonemouse2010 0 points1 point2 points 2 years ago (0 children) I don't think you'd need to worry about this on youtube. I don't think you'd need to worry about this on youtube. You would if it was a doctor talking about ED. [–]Rebelgecko 3 points4 points5 points 2 years ago (1 child) I think StupidFilter did something similar, although that project seems to be dead. [–]gfixler 0 points1 point2 points 2 years ago (0 children) I've used YouTube Comment Snob in the past. Now it works on other websites, too, and it's just called Comment Snob. [–]ruinercollector 6 points7 points8 points 2 years ago* (0 children) A more classical approach with LaPlace smoothing: let v = count of unique words in your full corpus (good and bad) let wg = word count in the good corpus let wb = word count in the bad corpus let lambdaGood = function or factor for weighting good score ((w)=> 2 in the case he used.) let lambdaBad = function or factor for weighting bad score ((w)=> 1 in the case he used.) goodScore = (countInGood(w) + 1) / (wg + v) * lambdaGood(w) badScore = (countInBad(w) + 1) / (wb + v) * lambdaBad(w) isSpam = badScore > goodScore Might be worth a shot. [–]roboduck 2 points3 points4 points 2 years ago (1 child) Use F-score, not simple false-positive / false-negative rates to measure how good your algorithm performs. [–]ruinercollector 1 point2 points3 points 2 years ago (0 children) F-Score is entirely based on false-positive and false-negative ratios. Yes, it's a more formally correct way to measure your progress, and it gives you one number to look at, but it doesn't really give you any new information. [–]tomovo 13 points14 points15 points 2 years ago (0 children) Here's a faster and more effective version of a general youtube comment filter: comment.junk = YES; [–]AeroNotix 2 points3 points4 points 2 years ago (0 children) def comment_classifier(comment_str): """ Classifies a youtube comment on whether or not it is spam. """ return True [–]ggtsu_00 1 point2 points3 points 2 years ago (0 children) It would be interesting to use this to sort comments instead of flagging them as spam. That way, false positives don't really matter as they just show up lower on the list. I did something similar to this for finding out if registration emails/usernames are randomly generated by spam bots and just used the scores from the classifier to just sort the list to manually pick through it later. Having 90% of the spam show up at the bottom of the list really made it easy to go through by hand. [–]mogrim 1 point2 points3 points 2 years ago (0 children) Nice, looks like a fun project. (And please, please: ignore some of the idiots on this thread, who seem to have no idea how to phrase a reasonable criticism without coming across as an arrogant idiot...) [–]010011000111 1 point2 points3 points 2 years ago (0 children) looking at the comments here, it would be very nice to have a comment filter that removed abrasive and rude comments from people who think they are gods gift to the world. It would remove at least half of these comments. [–]parad0xchild 0 points1 point2 points 2 years ago (2 children) Are you trying to use this to filter all comments that would be considered spam eventually. So that when someone uploads a video they can use this to see potentially legitimate comments that are coming in and ignore the potential spam? Just wondering because you state "sometimes they will mark as spam a comment that is really just a troll", which leads me to think this doesn't filter out "troll" comments, but someone looking to filter new comments wouldn't want to see those either. Just curious, this is interesting and I think it could be quite effective eventually. [–]influenztial 4 points5 points6 points 2 years ago (1 child) He's referring to the data he gets from the youtube API, as his training set includes the preclassified "spam" markers in that data. Now those comments that are marked as spam can tend to be from people either frustrated with a dissenting opinion or from a troll. Or from bots who purposefully just mark everyone as spam. If the OP had the time I'm sure a much better training set would improve the accuracy a good deal, but acquiring these datasets specifically for your purpose can be tricky. Keep at the naive bayes, maybe try some bigrams (even though the improvement they give is neglible in most cases). Maybe if you've got a lot of time on your hands, find a way to incorporate account age with the comment, as most spam bots will be of lower age than legitimate accounts. [–]parad0xchild 0 points1 point2 points 2 years ago (0 children) Ah alright. [–]rlbond86 0 points1 point2 points 2 years ago (0 children) I can't tell from the readme. What is your model you are using? [–]ieeaaauuuuooooo 0 points1 point2 points 2 years ago (0 children) when working with twitter spammers detection i found this useful list: http://codex.wordpress.org/Spam_Words maybe you could use them as special attributes or so.also, agreed with logain2006, testing with training set is pointless, search for a spam detection corpus and use the train/test clasical approach. finally, if you looking for some nice results forget about naive independence assumption. try some SVM :) [–]useCOTS676 -2 points-1 points0 points 2 years ago (1 child) Use a spam filter. Plain and simple. Use bogofilter, use CRM, use a machine learning library. Why? Because you are going to suffer from floating point underflow and overflow. Your Bayesian calculations will quickly blow up. Given 150 words of 0.001 probability each you will bottom out on floating point precision. Why? Because you're multiplying floats like a doofus. Use off the shelf tools that already solve these issues. They solve these problems that you obviously didn't think about. FYI log(abc) = log(a) + log(b) + log(c) <--- also more representable with IEEE floating point. SUMMARY: You have made NAIVE mistakes implementing NAIVE BAYES. Use off the shelf components to avoid these errors. ...or just fix the problem by adding the log probabilities. that works too. his NAIVE mistakes are pretty easy to fix, and it's probably a valuable learning experience for him to do so. [+]lw9k comment score below threshold-6 points-5 points-4 points 2 years ago (3 children) I can filter comments with a mathematician?! Seriously though, it's naive Bayes' theorem. [–]PendingPhysics 5 points6 points7 points 2 years ago (1 child) Specifically, it's a naive Bayes classifier, which makes the naive Bayes assumption - here, that all words (or features) are independent given the class (e.g. spam or not spam). [–]davebees 4 points5 points6 points 2 years ago (0 children) People frequently shorten the names of theorems like that. 'We can work out the length of A by Pythagoras', etc. [+]ifjdivjfijv comment score below threshold-6 points-5 points-4 points 2 years ago (0 children) The way you code is horrible. [+]onlyfaggotsusereddit comment score below threshold-11 points-10 points-9 points 2 years ago (0 children) Moron, you just put on a blocker for the whole youtube comment system onto your browser. Nobody worth listening to comments on youtube videos anyway, and if you argue with that you aren't worth listening to. Use of this site constitutes acceptance of our User Agreement {Genitive} and Privacy Policy {Genitive}. © 2014 reddit inc. All rights reserved. REDDIT and the ALIEN Logo are registered trademarks of reddit inc. all it takes is a username and password for more information, see our privacy policy. create account is it really that easy? only one way to find out... already have an account and just want to login? login π Rendered by PID 21397 on app-38 at 2014-09-19 22:45:59.564629+00:00 running d16e201 country code: US.
I have a window with a push-button. Once the button is clicked , I would like to change the position of line that is initially drawn.This is my code till now. import sys from PyQt4 import QtGui , QtCore class trial(QtGui.QWidget): def __init__(self): super(trial , self).__init__() self.window() def window(self): self.a = 0 button = QtGui.QPushButton('Push') button.setCheckable(True) button.clicked.connect(self.fun) grid = QtGui.QGridLayout() grid.addWidget(button , 0 , 0) self.setLayout(grid) self.setWindowTitle('Trial') self.setGeometry(500 , 500 , 500 , 500) self.show() def fun(self , text): if text == 1: self.a = 0 else: self.a = 1 def paintEvent(self , e): qp = QtGui.QPainter() qp.begin(self) pen = QtGui.QPen(QtCore.Qt.red , 5 , QtCore.Qt.SolidLine) qp.setPen(pen) if self.a == 0: qp.drawLine(20 , 20 , 20 , 480) else: qp.drawLine(480 , 20 , 480 , 480) qp.end() if __name__ == '__main__': app = QtGui.QApplication(sys.argv) t = trial() sys.exit(app.exec_()) I know my code looks a bit awkward but I'm facing the following problems. 1. It takes quite a bit of time after the button is pressed for the line to change position. 2.Also how do I rub the line that is previously drawn. It would be nice if someone could modify the code for me.Thanks.
tiramiseb Re : configuration des DNS S'il-te-plait, pour des citations utilise la balise "[ quote ]" et non la balise "[ code ]", c'est pénible de devoir défiler horizontalement pour lire les phrases que tu cites... Hors ligne kr2sis Re : configuration des DNS ça y est je sui perdu...:o est ce qu'on peut faire doucement stp ? - doubitchou est non révélé au publique... ok - dans mon fichier /etc/hosts, j'ai ajouté une ligne : [IP publique serveur] doubitchou.fr....ok - pas besoin de créer un fichier de zone chez Gandi...ok je suis vraiment navré seb et je ne remets pas en quetsion tes explications que j'ai réussi à suivre jusqu'à symposion.fr, mais là pour moi tout change dans le cadre d'un nouveau virtual host et je ne sais pas comment on peut enregistrer un autre site .. le dernier encart est whois oki mais n'y a-t-il pas un formulaire ou un fichier qui fasse que doubitchou réponde présent ? apres modif du fichier /etc/hosts, j'a eu ce retour de commande : PING doubitchou.fr (84.101.105.63) 56(84) bytes of data. 64 bytes from doubitchou.fr (84.101.105.63): icmp_req=1 ttl=64 time=0.607 ms 64 bytes from doubitchou.fr (84.101.105.63): icmp_req=2 ttl=64 time=0.508 ms 64 bytes from doubitchou.fr (84.101.105.63): icmp_req=3 ttl=64 time=0.516 ms 64 bytes from doubitchou.fr (84.101.105.63): icmp_req=4 ttl=64 time=0.512 ms 64 bytes from doubitchou.fr (84.101.105.63): icmp_req=5 ttl=64 time=0.531 ms 64 bytes from doubitchou.fr (84.101.105.63): icmp_req=6 ttl=64 time=0.742 ms 64 bytes from doubitchou.fr (84.101.105.63): icmp_req=7 ttl=64 time=0.559 ms 64 bytes from doubitchou.fr (84.101.105.63): icmp_req=8 ttl=64 time=0.591 ms 64 bytes from doubitchou.fr (84.101.105.63): icmp_req=9 ttl=64 time=0.529 ms 64 bytes from doubitchou.fr (84.101.105.63): icmp_req=10 ttl=64 time=0.682 ms 64 bytes from doubitchou.fr (84.101.105.63): icmp_req=11 ttl=64 time=0.598 ms ^C --- doubitchou.fr ping statistics --- 11 packets transmitted, 11 received, 0% packet loss, time 9998ms rtt min/avg/max/mdev = 0.508/0.579/0.742/0.076 ms Hors ligne tiramiseb Re : configuration des DNS Tu as "acheté" symposion.fr auprès d'un registrar, Gandi en l'occurrence. Si tu veux que doubitchou.fr soit disponible pour tout le monde sur Internet, tu dois "acheter" doubitchou.fr de la même manière. Si tu ne veux desservir doubitchou.fr que pour toi, pour faire des tests par exemple, tu peux : - soit te contenter de modifier le fichier /etc/hosts de ton poste client afin de lui dire de pointer vers l'adresse de ton serveur ; - soit mettre en place un serveur DNS local, que ton poste client interrogerait pour obtenir les résolutions DNS qu'il demande. Hors ligne tiramiseb Re : configuration des DNS Tu as tout fait avec succès pour symposion.fr, je ne vois pas ce que tu ne comprends pas quand on remplace symposion.fr par doubitchou.fr... Le fonctionnement est le même. Hors ligne kr2sis Re : configuration des DNS no bah du coup, j'avai compris alors... mais pourquoi je lis partotu qu'il est possible d'avoir plusieurs sites sur un meme serveur et qu'on ne parle pas d'achat de nom de domaine ? je me suis pris la tete comme un barge pour rien puisque comme tu dis j'avais tout fait et le succes je te le laisse car sans toi, j'aurais sombré dans une mélancolie douce et stupide, voire une dépression et tentative de suicide avec horizo et chocolat donc je ne m'obstine plus a chercher comment aoir un autre nom de domaine, je l'achete ou je passe en sous-domaine...c'est ça ? en totu cas un grand mercipour toute l'aide qur tu as pu m'apporter Hors ligne Brunod Re : configuration des DNS ..., je l'achete ou je passe en sous-domaine...c'est ça ? ... Ou tu le fais passer gratuitement par noip, dyndns etc en prenant un suffixe de chez eux. 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 kr2sis Re : configuration des DNS beh ca m'interesse pas vraiment étant donné que le but pour moi d'avoir créé un serveur web, c'etait d'etre en total autonomie et liberté.... donc les nom à rallonge, perso je trouve ca laid, donc j'aviserai quand je pourrait accéder a ce site déjà Hors ligne tiramiseb Re : configuration des DNS mais pourquoi je lis partotu qu'il est possible d'avoir plusieurs sites sur un meme serveur et qu'on ne parle pas d'achat de nom de domaine ? L'achat et la configuration de noms de domaine, c'est une autre question, ce n'est pas nécessairement lié, c'est pourquoi les documentations n'en traitent pas. je l'achete ou je passe en sous-domaine...c'est ça ? Exact. Hors ligne kr2sis Re : configuration des DNS bon, nom de domaine acheté le 26 février et toujours pas visible en public... il se passe quelque chose qu eje ne coprends pas... Hors ligne tiramiseb Re : configuration des DNS Tu parles du domaine symposion.fr ? Chez moi, ce domaine se résoud correctement de la manière suivante : $ host symposion.frsymposion.fr has address 84.101.105.63symposion.fr mail is handled by 50 fb.mail.gandi.net.symposion.fr mail is handled by 10 spool.mail.gandi.net. Par contre, il ne semble pas y avoir de sous-domaine "www" dans ce domaine : $ host www.symposion.fr Host www.symposion.fr not found: 3(NXDOMAIN) Par ailleurs, l'adresse pointé par "symposion.fr" (84.101.105.63, qui est une machine chez SFR (reverse DNS "63.105.101.84.rev.sfr.net")) ne semble desservir aucun service (j'ai testé les connexions suivantes sur cette adresse : HTTP, HTTPS, SSH, SMTP, IMAP, POP). Hors ligne kr2sis Re : configuration des DNS le truc c'est que le logiciel (DUC) de no-ip m'indique cet ip :86.71.56.58 et c'est l'autre ip que j'ai noté dans la feuille de zone chez moi rien ne passe (via le local et l'externe (tel portable orange) et je ne comprends pas ce que tu veux dire dans la dernière partie de ton dernier post ... cela signifie quoi stp ? et u'est ce que je dois faire pour résoudre le probleme si il y a un probleme... merci losque je fais ifconfig ou ipconfig, j'obtiens l'ip 192.168.1.54 ; adresse que j'ai statifié dans la box. est ce que je peux mettre cet ip à la place de celle que me révèle no-ip ?? je ne comprends plus rien avec ces ip et le role de no-ip... des dynDNS ok ! mais si ca change tout le temps, il faut que je change mes config tout le temps....:mad: pas cool Dernière modification par kr2sis (Le 01/03/2013, à 13:39) Hors ligne tiramiseb Re : configuration des DNS Reprenons du début : 1/ où se trouve, physiquement, ton serveur ? 2/ comment as-tu configuré les entrées DNS dans l'interface de Gandi ? Hors ligne kr2sis Re : configuration des DNS le serveur est chez moi la config Gandi, je vais voir ca de suite j'ai touché à 2 ligne @ A 84.101.105.63 www CNAME share-wood.zapto.org share..... et l'ip sont issue de mon inscription no-ip Dernière modification par kr2sis (Le 01/03/2013, à 13:44) Hors ligne tiramiseb Re : configuration des DNS le serveur est chez moi Tu es chez quel opérateur ? Avec les adresses que tu donnes, il semble que tu es chez SFR, probablement avec une Neufbox, c'est ça ? Hors ligne kr2sis Re : configuration des DNS oui je suis chez SFR chez moi et neufbox NB4 Hors ligne tiramiseb Re : configuration des DNS Donc tu as un problème. Une adresse IP chez SFR n'est pas fixe : SFR ne fournit que des adresses IP dynamiques. En pratique il y a de fortes chances que ton adresse IP ne change pas souvent, mais ça peut arriver ; c'est peut-être pour ça qu'actuellemnt tu as des problèmes. Dans ces cas, on préconise un système de type DynDNS. Heureusement, des gars voulaient quelque chose avec Gandi et Gandi propose des fonctionnalités avancées intéressantes, en l'occurrence une API qui permet de faire reconfigurer ton entrée DNS automatiquement. Tu pourras donc trouver à l'adresse suivante un outil permettant de gérer ton DNS de manière dynamique avec Gandi : https://github.com/Chralu/gandyn Par contre je ne pourrai pas t'aider dans la mise en œuvre de cet outil, je ne le connais pas. Hors ligne kr2sis Re : configuration des DNS et no-ip dans tout ca ? Hors ligne tiramiseb Re : configuration des DNS Il semble que ton truc chez No-IP est aussi une solution (plus tarabiscotée) pour ce problème. Je ne connais pas ce service. Dans ce cas, ton problème est peut-être plutôt là : as-tu bien activé ta dernière configuration dans l'interface de Gandi ? Dernière modification par tiramiseb (Le 01/03/2013, à 13:51) Hors ligne tiramiseb Re : configuration des DNS Par ailleurs, entre ces deux solutions je préconiserais fortement d'utiliser Gandyn, qui est plus direct que No-IP car il travaille directement avec les serveurs de Gandi. Hors ligne kr2sis Re : configuration des DNS oki donc faut que je vois avec le service client qui ne me repond pas... je vais essayé de leur telephoner dans ce cas.. donc ce que tu dis pour sfr est valable pour tous ceux qui sont abos chez eux ?? bon à savoir si on me demande.. merci à toi le reste de ma config, je n'y touche pas alors ? (mis à part le fichier de zone une fois le tout installé correctement) Hors ligne tiramiseb Re : configuration des DNS oki donc faut que je vois avec le service client qui ne me repond pas... je vais essayé de leur telephoner dans ce cas.. Tu parles de Gandi ? Si tu as des difficultés à utiliser leurs outils, oui il faut leur demander... Cependant : Tu n'as pas répondu à ma question, tu ne m'as pas dit si tu as bien activé la dernière version de la configuration de tes DNS... donc ce que tu dis pour sfr est valable pour tous ceux qui sont abos chez eux ?? bon à savoir si on me demande.. C'est valable pour tous ceux qui sont chez SFR et chez n'importe quel autre FAI qui n'assure pas des adresses IP fixes. Ceux qui fournissent des IP fixes à ma connaissance en France sont (la liste n'est certainement pas exhaustive) : - Free Telecom - Bouygues - Orange Pro, sur demande - Nerim - OVH Ceux qui ne fournissent PAS d'IP fixe (la liste n'est pas exhaustive) : - Orange (sauf pro) - SFR - Numericable - certainement plein d'autres encore le reste de ma config, je n'y touche pas alors ? (mis à part le fichier de zone une fois le tout installé correctement) Dans la mesure où http://86.71.56.58/ semble bien marcher, en effet ta config je ne pense pas qu'il faille y toucher. Dernière modification par tiramiseb (Le 01/03/2013, à 14:01) Hors ligne kr2sis Re : configuration des DNS Tu n'as pas répondu à ma question, tu ne m'as pas dit si tu as bien activé la dernière version de la configuration de tes DNS... tu veux dire entrer la nouvelle IP ? je vais le faire de ce pas dis-moi question surement bete : ne serait-il pas judicieux de ma part de ne pas signaler d'ip (vu qu'elle change) mais plutot seulement le nom de domaine fourni par no-ip (qui corrrespond à chaque ip dynamique dans mon fichier de zone ?? Dernière modification par kr2sis (Le 01/03/2013, à 14:14) Hors ligne tiramiseb Re : configuration des DNS Tu n'as pas répondu à ma question, tu ne m'as pas dit si tu as bien activé la dernière version de la configuration de tes DNS... tu veux dire entrer la nouvelle IP ? je vais le faire de ce pas Je veux dire : as-tu bien cliqué sur le bouton "Activer" dans l'écran de configuration ? Et as-tu bien attendu 48h après avoir cliqué sur ce bouton ? ne serait-il pas judicieux de ma part de ne pas signaler d'ip (vu qu'elle change) mais plutot seulement le nom de domaine fourni par no-ip (qui corrrespond à chaque ip dynamique dans mon fichier de zone ?? Oui, dans le cas du service fourni par no-IP c'est ce qu'il faut faire. Si tu utilises Gandyn, c'est l'outil qui va lui-même automatiquement configurer Gandi à chaque changement d'adresse IP. Hors ligne kr2sis Re : configuration des DNS Je veux dire : as-tu bien cliqué sur le bouton "Activer" dans l'écran de configuration ? dans l'interface, c'est la ligne qui dit "Numéro de version active" ? si oui c'est actif oui (dsl je suis perdu dans cet interface ) Hors ligne kr2sis Re : configuration des DNS je ne vois plus le site de l'exterieur .. tu le vois toi ? stp Hors ligne
I am using inlineformset_factory to create fields for a many to many relationship between Clients and Sessions, with an intermediary Attendance model. I have the following in my views file: AttendanceFormset = inlineformset_factory( Session, Attendance, formset=BaseAttendanceFormSet, exclude=('user'), extra=1, max_num=10, ) session = Session(user=request.user) formset = AttendanceFormset(request.POST, instance=session) And, as I needed to override one of the form fields, I added the following to the formset base class: class BaseAttendanceFormSet(BaseFormSet): def add_fields(self, form, index): super(BaseAttendanceFormSet, self).add_fields(form, index) form.fields['client'] = forms.ModelChoiceField( queryset=Client.objects.filter(user=2)) Now, the form works correctly, but I need to pass a value into the formset so that I can filter the clients displayed based the current user rather than just using the id 2. Can anyone help? Any advice appreciated. Thanks. EDIT For anyone reading, this is what worked for me: def get_field_qs(field, **kwargs): if field.name == 'client': return forms.ModelChoiceField(queryset=Client.objects.filter(user=request.user)) return field.formfield(**kwargs)
I am trying to add memcache to my webapp deployed on GAE, and to do this I am using memcache.Client() to prevent damage from any racing conditions: from google.appengine.api import memcache client = memcache.Client() class BlogFront(BlogHandler): def get(self): global client val = client.gets(FRONT_PAGE_KEY) posts = list() if val is not None: posts = list(val) else: posts = db.GqlQuery("select * from Post order by created desc limit 10") client.cas(FRONT_PAGE_KEY, list(posts)) self.render('front.html', posts = posts) To test the problem I have a front page for a blog that displays the 10 most recent entries. If there is nothing in the cache, I hit the DB with a request, otherwise I just present the cached results to the user. The problem is that no matter what I do, I always get val == None, thus meaning that I always hit the database with a useless request. I have sifted through the documentation: https://developers.google.com/appengine/docs/python/memcache/ https://developers.google.com/appengine/docs/python/memcache/clientclass http://neopythonic.blogspot.pt/2011/08/compare-and-set-in-memcache.html And it appears that I am doing everything correctly. What am I missing? (PS: I am a python newb, if this is a retarded error, please bear with me xD )
I have what I think can be only a synchronizing problem in this Python code. The code is intended to apply a minimax algorithm to a Tic Tac Toe game, implemented with parallel processes instead of a single process exploring all the possible moves one by one. Before labeling it as a really bad idea, I've been required to do so. Assume that unknown methods do exaclty what they suggest with their name, and assume that they work properly (they have been manually tested). The only method I'm not 100% sure of is this one, here's the code: def q_elems(queue): li = [] while not queue.empty(): li.append(queue.get()) return li Game board is represented with a simple Board class (extends list class).SimpleQueue and Process classes are imported from the multiprocessing Python module.H function is the heuristic function I implemented: it returns positive values for boards good for player MAX, negative for MIN and 0 for a tie. Here's the algorithm code: def minimax(board: Board, depth: int, turn: int, queue: SimpleQueue) -> int: queue.put(10000) if is_winning(board) or is_tie(board) or depth == 0: queue.put(H(board)) return local_queue = SimpleQueue() prcs_list = [] for child_brd in possible_moves(board, MAX if turn == TURN_MAX else MIN): p = Process(target=minimax, args=( Board(child_brd), # board depth - 1, # depth TURN_MIN if turn == TURN_MAX else TURN_MAX, # turn local_queue) # queue ) prcs_list.append(p) [p.start() for p in prcs_list] [p.join() for p in prcs_list] # turn was MAX if turn == TURN_MAX: queue.put(max(q_elems(local_queue))) return # turn was MIN else: queue.put(min(q_elems(local_queue))) return Main method is simply: k = SimpleQueue() minimax(b, MINIMAX_DEPTH, turn=TURN_MAX, queue=k) I often meet this kind of errors: Traceback (most recent call last): File "game.py", line 202, in <module> minimax(b, MINIMAX_DEPTH, turn=TURN_MAX, queue=k) File "game.py", line 182, in minimax queue.put(max(q_elems(local_queue))) ValueError: max() arg is an empty sequence but not always. Is there a mistake in the recursive method? I really can't figure it out. My idea was to build a local queue for every turn, and then extract the max/min value from that queue to bring it to the "upper" queue, the queue from the preceding turn.
Analyzing Sound Files Pages: 1, 2 The tool Natural sounds are comprised of many frequencies with varying amplitudes. It is the complex interaction of both frequency and amplitude varied across time that makes sound pleasant to hear. But no matter how complex the sound, the FFT can be used to decompose it and to estimate the frequency content. Performing this analysis on samples of data through the length of a recording, we can get a measure of the frequency content of a signal over time. The resulting plot is known as a sonogram or a spectrogram. The plot shows the relationship between time (x-axis), frequency (y-axis), and power (color -- red is high power, blue low power). The following plot shows the analysis of a file containing chirped whistles (I was doing my bird interpretation). The green and blue colors show the lower powered frequencies. The red color shows the variable frequency of the chirps. Figure 2. The analysis of a file containing chirped whistles. The code for the program follows. You can view the complete program from here. I'll explain it as we go along: Basic imports from Numeric import * from MLab import * from FFT import * from dislin import * import wave import sys import struct We use the open method from the wave module to open a wave file and assign it to a file pointer, fp. Using information about the file, we then calculate some basic constants to use in our analysis of the file. The length of the fft is passed in as a command line argument and should always be a power of two: # open the wave file fp = wave.open(sys.argv[1],"rb") sample_rate = fp.getframerate() total_num_samps = fp.getnframes() fft_length = int(sys.argv[2]) num_fft = (total_num_samps / fft_length ) - 2 We are going to need a matrix to store temporary results. Making it here allows for more efficient operation later: # create temporary working array temp = zeros((num_fft,fft_length),Float) The data from the wave file is stored as packed numbers in a binary form. We will read the entire file into the temporary array we just created. As each section is read in, we unpack it into a floating-point value. Notice that we are storing it into a two-dimensional array where each row contains fft_length samples. # read in the data from the file for i in range(num_fft): tempb = fp.readframes(fft_length); temp[i,:] = array(struct.unpack("%dB"%(fft_length), \ tempb),Float) - 128.0 fp.close() Although not necessary, the next step multiplies each row of the data matrix by a "window" function. The window is used to mitigate some numerical side effects of the FFT. Since we are multiplying a vector and a matrix, we are taking advantage of broadcasting here! # Window the data temp = temp * hamming(fft_length) We again make use of the real_fft() function, which is optimized for real (as opposed to complex) data. Notice that we are taking the FFT of the entire array, which defaults to taking the individual FFT of each row. The 10*log10 is again used to convert the output into the logarithmic scale. The addition of the constant (1E-20) solves the problem of log10(0) being undefined. Rather than check each argument for 0, we just add a small inconsequential value to guarantee that the 0 case never arises. There is a lot of work going on here. This is where the muscle is applied. The result is an array that contains the energy values found in each of the frequencies across each of the rows (sections of the time signal). # Transform with the FFT, Return Power freq_pwr = 10*log10(1e-20+abs(real_fft(temp,fft_length))) Now we use DISLIN for plotting! Most of the work is to get the scales correct. Using the contour Quickplot function, we are going to take a look at all of the rows of the array at the same time. The conshade function will plot rows against columns in a color plot where the color relates to the magnitude of the element (in our case, the energy in a particular frequency during a particular part of the file). # Plot the result n_out_pts = (fft_length / 2) + 1 y_axis = 0.5*float(sample_rate) / n_out_pts * \ arange(n_out_pts) x_axis = (total_num_samps / float(sample_rate)) / \ num_fft * arange(num_fft) setvar('X',"Time (sec)") setvar('Y',"Frequency (Hertz)") conshade(freq_pwr,x_axis,y_axis) disfin() That's it! The whole function is only 40 lines of code. Running the tool Either type in the commands or download the full version -- I called my program pysono.py. Once in hand, the tool is simple to try out. First use the sound recorder on your PC to generate a sound file (the tool works best for files less than 60 seconds long). Then at the command prompt type: pysono.py <filename> <fft_size> Use the name of the wave file you are analyzing for filename and the length of the FFT to use for fft_size. Remember it must be a power of two. Give it a try! Using the tool, I analyzed the first 60 seconds of a recording of The Very Thought of You sung by Natalie Cole. The loosely parallel lines show that her voice has several frequencies present -- these are harmonics and are what give the sound quality. Figure 3. the first 60 seconds of a recording of End game Using techniques explored throughout this series of articles on Numeric Python, we have created a complete, useful application in only 40 lines of code. With the tool in hand, you can now analyze different wave files. Try saying the same words at different pitches (one in normal tone, the other in falsetto) -- do the sonograms look the same? Analyze the same file with varying sizes of FFTs. Can you see the difference in ability to measure frequencies? The mathematics behind the code comes from the field of DSP (digital signal processing). For more information search the web for "DSP". A good place to start is Digital Signal Processing Central. Eric Hagemann specializes in fast algorithms for crunching numbers on all varieties of computers from embedded to mainframe. Read more Numerically Python columns. Discuss this article in the O'Reilly Network Python Forum. Return to the Python DevCenter.
I should define a function pad_with_n_chars(s, n, c) that takes astring 's', an integer 'n', and a character 'c' and returnsa string consisting of 's' padded with 'c' to create astring with a centered 's' of length 'n'. For example,pad_with_n_chars(”dog”, 5, ”x”) should return thestring "xdogx". I should define a function With Python2.6 or better, there's no need to define your own function; the string format method can do all this for you: In [18]: '{s:{c}^{n}}'.format(s='dog',n=5,c='x') Out[18]: 'xdogx' It looks like you're only looking for pointers, not a complete solution. So here's one: You can multiply strings in python: >>> "A" * 4 'AAAA' Additionally I would use better names, instead of well, since this is a homework question, you probably won't understand what's going on if you use the "batteries" that are included. def pad_with_n_chars(s, n, c): r=n - len(s) if r%2==0: pad=r/2*c return pad + s + pad else: print "what to do if odd ? " #return 1 print pad_with_n_chars("doggy",9,"y") Alternatively, when you are not schooling anymore. >>> "dog".center(5,"x") 'xdogx' print '=' * 60 header = lambda x: '%s%s%s' % ('=' * (abs(int(len(x)) - 60) / 2 ),x,'=' * (abs(int(len(x)) - 60) / 2 ) ) print header("Bayors") >>> dir(string) ['Formatter', 'Template', '_TemplateMetaclass', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_float', '_idmap', '_idmapL', '_int', '_long', '_multimap', '_re', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'atof', 'atof_error', 'atoi', 'atoi_error', 'atol', 'atol_error', 'capitalize', 'capwords', 'center', 'count', 'digits', 'expandtabs', 'find', 'hexdigits', 'index', 'index_error', 'join', 'joinfields', 'letters', 'ljust', 'lower', 'lowercase', 'lstrip', 'maketrans', 'octdigits', 'printable', 'punctuation', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitfields', 'strip', 'swapcase', 'translate', 'upper', 'uppercase', 'whitespace', 'zfill'] I think you should be able to spot a first clue here...
HowToDPorts DPorts and pkgng Dports is DragonFly's own third-party software build system. It is based on FreeBSD's Ports Collection. Differences between ports and DPorts are intentionally kept to a minimum, both to maintain familiarity for mutual users of both operating systems and also to leverage the tremendous amount of work the FreeBSD contributors put into ports. DPorts can and does feature ports unique to DragonFly, so it's truly a native system. The pkgng tool called "pkg" is a modern and fast binary package manager. It was developed for FreeBSD, but PC-BSD used it in production first, followed soon after by DragonFly. In the future, it will be the only binary package manager on FreeBSD, just it is the only port manager in DPorts. pkgng is not a replacement for port management tools like ports-mgmt/portmaster or ports-mgmt/portupgrade. While ports-mgmt/portmaster and ports-mgmt/portupgrade can install third-party software from both binary packages and DPorts, pkgng installs only binary packages. On the other hand, many people use pkgng by itself and never install the optional portupgrade or portmaster tools. Getting started with pkgng DragonFly daily snapshots and Releases (starting with 3.4) come with pkgng already installed. Upgrades from earlier releases, however, will not have it. If the "pkg" program is missing on the system for any reason, it can be quickly bootstrapped without having to build it from source or even having dports installed: # make pkg-bootstrap # rehash # pkg-static install -y pkg # rehash If pkgsrc has ever been installed on the system, make sure all binaries produced by it have been removed: # rm -rf /usr/pkg Currently it's necessary to manually install the configuration file, but this requirement should disappear in the future. After installing the configuration file, you may want to open it up and edit it to select a different mirror. Configuring pkgng Older versions of pkgng saved their configuration at /usr/local/etc/pkg.conf; this file made reference to a PACKAGESITE. pkgng will still work based on this file, but will output errors: # pkg update pkg: PACKAGESITE in pkg.conf is deprecated. Please create a repository configuration file Updating repository catalogue pkg: Warning: use of http:// URL scheme with SRV records is deprecated: switch to pkg+http:// If you do not see these errors, then skip to "Now, navigate to /usr/local/etc/pkg/repos/", otherwise: Listen to the errors: hash out the packagesite line, save the file, and move on. This can be done with vi: # vi /usr/local/etc/pkg.conf There will be two lines in the file like this: # Default Dports package server (California) PACKAGESITE: http://mirror-master.dragonflybsd.org/dports/${ABI}/LATEST Hash out the offending line: # Default Dports package server (California) # PACKAGESITE: http://mirror-master.dragonflybsd.org/dports/${ABI}/LATEST Note that, as of time of writing, there are two working package repositories: # Default Dports package server (California) # PACKAGESITE: http://mirror-master.dragonflybsd.org/dports/${ABI}/LATEST # European mirrors [...] #PACKAGESITE: http://dfly.schlundtech.de/dports/${ABI}/LATEST Test their performance---we will be using the fastest one. This may, or may not, be the one closest to you (the California site for the New World, the German site for the Old World). # ping schlundtech.de PING schlundtech.de (85.236.36.90): 56 data bytes 64 bytes from 85.236.36.90: icmp_seq=0 ttl=49 time=101.433 ms 64 bytes from 85.236.36.90: icmp_seq=1 ttl=49 time=59.177 ms 64 bytes from 85.236.36.90: icmp_seq=2 ttl=49 time=79.550 ms 64 bytes from 85.236.36.90: icmp_seq=3 ttl=49 time=88.268 ms 64 bytes from 85.236.36.90: icmp_seq=4 ttl=49 time=120.060 ms [...] --- schlundtech.de ping statistics --- 20 packets transmitted, 19 packets received, 5.0% packet loss round-trip min/avg/max/stddev = 49.555/96.064/186.662/33.559 ms # ping mirror-master.dragonflybsd.org PING avalon.dragonflybsd.org (199.233.90.72): 56 data bytes 64 bytes from 199.233.90.72: icmp_seq=0 ttl=47 time=208.013 ms 64 bytes from 199.233.90.72: icmp_seq=1 ttl=47 time=256.441 ms 64 bytes from 199.233.90.72: icmp_seq=2 ttl=47 time=281.436 ms 64 bytes from 199.233.90.72: icmp_seq=3 ttl=47 time=281.103 ms 64 bytes from 199.233.90.72: icmp_seq=4 ttl=47 time=285.440 ms [...] --- avalon.dragonflybsd.org ping statistics --- 19 packets transmitted, 19 packets received, 0.0% packet loss round-trip min/avg/max/stddev = 208.013/264.017/334.180/31.549 ms Now, navigate to /usr/local/etc/pkg/repos/ and rename one of the configuration file samples you find there. df-latest.conf will make pkg use the newest available binaries while df-release.conf points to binaries built at the time of the release. The latter is frozen so you will not get any updates. Edit the one you renamed: # cd /usr/local/etc/pkg/repos/ # ls df-latest.conf.sample df-releases.conf.sample # cp -v df-latest.conf.sample df-latest.conf df-latest.conf.sample -> df-latest.conf # chmod -v 644 df-latest.conf df-latest.conf # vi df-latest.conf Enable whichever server was faster (Avalon is American, SchlundTech is German), and pkg+ to the url and SRV to mirror_type: Avalon: { url : pkg+http://mirror-master.dragonflybsd.org/dports/${ABI}/LATEST, mirror_type : SRV [...] enabled : no } SchlundTech: { url : pkg+http://dfly.schlundtech.de/dports/${ABI}/LATEST, mirror_type : SRV [...] enabled : yes } Before using, consult the man page (man pkg) and then try these examples: # pkg search editors# pkg install vim Basic pkgng Operations Usage information for pkgng is available in the pkg(8) manual page, or by running pkg without additional arguments. Each pkgng command argument is documented in a command-specific manual page. To read the manual page for pkg install, for example, run either: # pkg help install # man pkg-install Obtaining Information About Installed Packages with pkgng Information about the packages installed on a system can be viewed by running pkg info. Similar to pkg_info(1), the package version and description for all packages will be listed. Information about a specific package is available by running: # pkg info packagename For example, to see which version of pkgng is installed on the system, run: # pkg info pkg pkg-1.0.12 New generation package manager Installing and Removing Packages with pkgng In general, most DragonFly users will install binary packages by typing: # pkg install <packagename> For example, to install curl: # pkg install curl Updating repository catalogue Repository catalogue is up-to-date, no need to fetch fresh copy The following packages will be installed: Installing ca_root_nss: 3.13.5 Installing curl: 7.24.0 The installation will require 4 MB more space 1 MB to be downloaded Proceed with installing packages [y/N]: y ca_root_nss-3.13.5.txz 100% 255KB 255.1KB/s 255.1KB/s 00:00 curl-7.24.0.txz 100% 1108KB 1.1MB/s 1.1MB/s 00:00 Checking integrity... done Installing ca_root_nss-3.13.5... done Installing curl-7.24.0... done The new package and any additional packages that were installed as dependencies can be seen in the installed packages list: # pkg info ca_root_nss-3.13.5 The root certificate bundle from the Mozilla Project curl-7.24.0 Non-interactive tool to get files from FTP, GOPHER, HTTP(S) servers pkg-1.0.12 New generation package manager Packages that are no longer needed can be removed with pkg delete. For example, if it turns out that curl is not needed after all: # pkg delete curl The following packages will be deleted: curl-7.24.0_1 The deletion will free 3 MB Proceed with deleting packages [y/N]: y Deleting curl-7.24.0_1... done Upgrading Installed Packages with pkgng Packages that are outdated can be found with pkg version. If a local ports tree does not exist, pkg-version(8) will use the remote repository catalogue, otherwise the local ports tree will be used to identify package versions. Packages can be upgraded to newer versions with pkgng. Suppose a new version of curl has been released. The local package can be upgraded to the new version: # pkg upgrade Updating repository catalogue repo.txz 100% 297KB 296.5KB/s 296.5KB/s 00:00 The following packages will be upgraded: Upgrading curl: 7.24.0 -> 7.24.0_1 1 MB to be downloaded Proceed with upgrading packages [y/N]: y curl-7.24.0_1.txz 100% 1108KB 1.1MB/s 1.1MB/s 00:00 Checking integrity... done Upgrading curl from 7.24.0 to 7.24.0_1... done Auditing Installed Packages with pkgng Occasionally, software vulnerabilities may be discovered in software within DPorts. pkgng includes built-in auditing. To audit the software installed on the system, type: # pkg audit -F Advanced pkgng Operations Automatically Removing Leaf Dependencies with pkgng Removing a package may leave behind unnecessary dependencies, like security/ca_root_nss in the example above. Such packages are still installed, but nothing depends on them any more. Unneeded packages that were installed as dependencies can be automatically detected and removed: # pkg autoremove Packages to be autoremoved: ca_root_nss-3.13.5 The autoremoval will free 723 kB Proceed with autoremoval of packages [y/N]: y Deinstalling ca_root_nss-3.13.5... done Backing Up the pkgng Package Database pkgng includes its own package database backup mechanism. To manually back up the package database contents, type: # pkg backup -d <pkgng.db> Additionally, pkgng includes a periodic(8) script to automatically back up the package database daily if daily_backup_pkgng_enable is set to YES in periodic.conf(5). To prevent the pkg_install periodic script from also backing up the package database, set daily_backup_pkgdb_enable to NO in periodic.conf(5). To restore the contents of a previous package database backup, run: # pkg backup -r </path/to/pkgng.db> Removing Stale pkgng Packages By default, pkgng stores binary packages in a cache directory as defined by PKG_CACHEDIR in pkg.conf(5). When upgrading packages with pkg upgrade, old versions of the upgraded packages are not automatically removed. To remove the outdated binary packages, type: # pkg clean Modifying pkgng Package Metadata pkgng has a built-in command to update package origins. For example, if lang/php5 was originally at version 5.3, but has been renamed to lang/php53 for the inclusion of version 5.4, the package database can be updated to deal with this. For pkgng, the syntax is: # pkg set -o <category/oldport>:<category/newport> For example, to change the package origin for the above example, type: # pkg set -o lang/php5:lang/php53 As another example, to update lang/ruby18 to lang/ruby19, type: # pkg set -o lang/ruby18:lang/ruby19 As a final example, to change the origin of the libglut shared libraries from graphics/libglut to graphics/freeglut, type: # pkg set -o graphics/libglut:graphics/freeglut Note: When changing package origins, in most cases it is important to reinstall packages that are dependent on the package that has had the origin changed. To force a reinstallation of dependent packages, type: # pkg install -Rf graphics/freeglut Building DPorts from source The average user will probably not build packages from source. However, it's easy to do and it can be done even when packages have already been pre-installed on the system. Common reasons to build from source are: The port is new and there's no pre-binary available yet The pre-built binaries use the default options and the user needs a package built with a different set of options Testing FreeBSD port in order to patch them and submit to DPorts The user just prefers building from source Installing DPorts tree DragonFly 3.4 or later is the minimum version that can build DPorts from source. It's probably that pkgsrc binaries are already installed because it comes bootstrapped with new systems. It is necessary to rename /usr/pkg directory so that the existing pkgsrc binary tools and libraries don’t get accidentally used while building DPorts, causing breakage. For the installation of the DPorts tree, type: # cd /usr # make dports-create-shallow If the /usr/pkg directory has already been renamed, git won’t be in the search path any more. One option is to download a tarball of DPorts and unpack it. To do this, type: # cd /usr # make dports-download For future updates, pull delta changes via git is fastest, so it is suggested to convert the static tree to a git repository by typing: # cd /usr/dports/devel/git # make install # cd /usr # rm -rf /usr/dports # make dports-create-shallow The git repository is hosted on the github account of John Marino. Final thoughts Building from source works similar to ports and pkgsrc: cd into the appropriate program's directory, and type 'make'. 'make install' to install the software, 'make clean' to clean up work files, and so on. Use 'make config-recursive' if you want to set all the port's options, and the options of its dependencies, immediately instead of during the build. To take all the default build options and avoid getting the pop-up dialog box, set NO_DIALOG=yes on either the command line or the make.conf file. If you just want to set the options for one package, and accept the default for all of its dependencies, do 'make config' in the package in you want non-default options, and then 'make NO_DIALOG=yes'. Note that this is only necessary if you want to build from source with a non-default set of options, or if no pre-built binary package is available yet.
I'm a fairly new Python programmer (started 3 days ago). I'm working as a apprentice for a civil engineer and he asked me to do some simpler tasks for his program, as of the objective I should work with is to not allow numbers from inputs in certain glade objects. The code I've been struggling with creating is as such: def testOmHeltal (self, number1): textviewResultat = self.builder.get_object("textviewResultat") text = gtk.TextBuffer() try: #print number1.get_text() #temp = number1.get_text() + number1.get_text() temp = float(number1.get_text()) except ValueError: text.set_text("ERROR: Endast Nummer") self.builder.get_object("hboxWarning").show() self.builder.get_object("image12").show() self.builder.get_object("textviewResultat").set_buffer(text) return 0 self.builder.get_object("hboxWarning").hide() self.builder.get_object("image12").hide() def quit(self, widget): sys.exit(0) This code is called upon at the location of the glade object with this line: self.testOmHeltal(entryGladeObject) Now to the problem at hand, I allways get an Float error as such: File "bvf.py", line 393, in utfora +float(entryTjockleksskyddslager.get_text<>>>> ValueError: invalid literal for float<>: 0.04e 0.04e is the invalid input and line 393 is a piece of my Chiefs code, since all he uses is float all the time and I shouldn't meddle with it too much I'm kind of panicking alittle.. I understand that float can only start and end with a number to not give an error, but since my "code" bit wants an error(or rather, an exception) to start the 'hboxWarning' and 'image12' of someone using a letter instead of the supposed number, I'm at a loss at what to do >< Instead of showing my error with hboxWarning and image12, nothing happens at all... Any hints or advice would help alot.
Marrrrrrrie Pas de scroll avec le touchpad (ubuntu 12.04) Bonjour, Je viens d'installer ubuntu 12.04 sur un Dell latitude E6330. Il y a un seul problème majeur : le scroll sur le côté droit du touchpad ne fonctionne pas. Le scroll-down marche avec une souris externe. Dans les paramètres systèmes il semble que mon touchpad soit reconnu comme une souris. J'ai aussi essayé gsynaptics mais cocher ou décocher la case "utiliser la molette" ne change rien... Avez-vous une idée pour m'aider ? Merci beaucoup ! Marie Hors ligne gguillaume017 Re : Pas de scroll avec le touchpad (ubuntu 12.04) Bienvenue au club Essaie avec Synaptiks, une appli KDE qui marche du tonnerre pour les Touchpad ! Dernière modification par gguillaume017 (Le 07/08/2012, à 22:32) Marrrrrrrie Re : Pas de scroll avec le touchpad (ubuntu 12.04) Salut ! Merci pour ta réponse. J'ai installé Synaptiks, mais quand je le lance je reçois le message d'erreur suivant: "No touchpad found No touchpad was found in this system. If the system has a touchpad, please make sure that the synaptics driver is properly installed and configured. If your touchpad is not found though the driver is installed and configured correctly, please compile detailed information about your touchpad hardware and report this issue." Et dans paramètres systèmes il y a une souris. Mon touchpad à l'air reconnu comme une souris et pas comme un touchpad ! Comment faire pour changer ça ? Marie Hors ligne Marrrrrrrie Re : Pas de scroll avec le touchpad (ubuntu 12.04) Voilà ce que donne xinput list : ⎡ Virtual core pointer id=2 [master pointer (3)] ⎜ ↳ Virtual core XTEST pointer id=4 [slave pointer (2)] ⎜ ↳ PS/2 Generic Mouse id=12 [slave pointer (2)] ⎣ Virtual core keyboard id=3 [master keyboard (2)] ↳ Virtual core XTEST keyboard id=5 [slave keyboard (3)] ↳ Power Button id=6 [slave keyboard (3)] ↳ Video Bus id=7 [slave keyboard (3)] ↳ Power Button id=8 [slave keyboard (3)] ↳ Sleep Button id=9 [slave keyboard (3)] ↳ Integrated Webcam id=10 [slave keyboard (3)] ↳ AT Translated Set 2 keyboard id=11 [slave keyboard (3)] ↳ Dell WMI hotkeys Puis un xinput --list-props 12 donne : Device 'PS/2 Generic Mouse': Device Enabled (132): 1 Coordinate Transformation Matrix (134): 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000 Device Accel Profile (256): 0 Device Accel Constant Deceleration (257): 1.000000 Device Accel Adaptive Deceleration (258): 1.000000 Device Accel Velocity Scaling (259): 10.000000 Device Product ID (252): 2, 1 Device Node (253): "/dev/input/event7" Evdev Axis Inversion (260): 0, 0 Evdev Axes Swap (262): 0 Axis Labels (263): "Rel X" (142), "Rel Y" (143) Button Labels (264): "Button Left" (135), "Button Middle" (136), "Button Right" (137), "Button Wheel Up" (138), "Button Wheel Down" (139) Evdev Middle Button Emulation (265): 0 Evdev Middle Button Timeout (266): 50 Evdev Third Button Emulation (267): 0 Evdev Third Button Emulation Timeout (268): 1000 Evdev Third Button Emulation Button (269): 3 Evdev Third Button Emulation Threshold (270): 20 Evdev Wheel Emulation (271): 0 Evdev Wheel Emulation Axes (272): 0, 0, 4, 5 Evdev Wheel Emulation Inertia (273): 10 Evdev Wheel Emulation Timeout (274): 200 Evdev Wheel Emulation Button (275): 4 Evdev Drag Lock Buttons (276): 0 où apparement il y a des possibilités d'émulation de molette etc... comment les activer ? Et un cat /proc/bus/input/devices : I: Bus=0011 Vendor=0002 Product=0001 Version=0000 N: Name="PS/2 Generic Mouse" P: Phys=isa0060/serio1/input0 S: Sysfs=/devices/platform/i8042/serio1/input/input7 U: Uniq= H: Handlers=mouse0 event7 B: PROP=0 B: EV=7 B: KEY=70000 0 0 0 0 B: REL=3 Du coup, synaptiks ne voit pas de touchpad. De plus je n'ai pas de fichier xorg.conf (merci ubuntu nouveau), donc je ne peux pas appliquer les solutions que j'ai pu trouver sur le net. Une solution qui pourrait marcher serait de faire comme décrit ici : https://wiki.archlinux.org/index.php/Touchpad_Synaptics , qui consisterait en fait à installer le paquet "synaptics" qui dans les anciennes versions de ubuntu, non ? Mais je ne sais pas comment installer ce synaptics : est-ce que c'est l'équivalent du synaptiks dont on m'a parlé ? Dernière modification par Marrrrrrrie (Le 11/08/2012, à 10:00) Hors ligne Marrrrrrrie Re : Pas de scroll avec le touchpad (ubuntu 12.04) Bump ! Problème relou et pas résolu... Si vous avez une idée, je suis preneuse ! Merci ! Marie Hors ligne stevens4c Re : Pas de scroll avec le touchpad (ubuntu 12.04) salut que te renvois la commande xinput list lorsque la souris n est pas branchée perso lorsque je vais dans parametre systeme j ai une icone souris et pave tactile et je peux activer les défilements Hors ligne Marrrrrrrie Re : Pas de scroll avec le touchpad (ubuntu 12.04) Salut stevens4c, et merci de ta réponse ! Voici le résultat des deux commandes: marie@pc:~> xinput list ⎡ Virtual core pointer id=2 [master pointer (3)] ⎜ ↳ Virtual core XTEST pointer id=4 [slave pointer (2)] ⎜ ↳ PS/2 Generic Mouse id=13 [slave pointer (2)] ⎣ Virtual core keyboard id=3 [master keyboard (2)] ↳ Virtual core XTEST keyboard id=5 [slave keyboard (3)] ↳ Power Button id=6 [slave keyboard (3)] ↳ Video Bus id=7 [slave keyboard (3)] ↳ Power Button id=8 [slave keyboard (3)] ↳ Sleep Button id=9 [slave keyboard (3)] ↳ Integrated Webcam id=11 [slave keyboard (3)] ↳ AT Translated Set 2 keyboard id=12 [slave keyboard (3)] ↳ Dell WMI hotkeys id=14 [slave keyboard (3)] Il semble que mon touchpad soit uniquement reconnu comme une souris ! PS/2 Generic Mouse c'est le touchpad, il n'y avait pas de souris branchée au moment de la commande. marie@pc:~> synclient Couldn't find synaptics properties. No synaptics driver loaded? Est-ce que ca veut dire que j'ai tout simplement pas installé un truc ? Merci de ton aide, et désolée d'avoir tardé pour la réponse ! Marie Hors ligne stevens4c Re : Pas de scroll avec le touchpad (ubuntu 12.04) je pense que ton touchpad est branché sur un port usb on peu le savoir en tapant cette ligne dans une commande lsusb ensuite il faut refaire ce que tu as fais la première fois, tu tapes xinput list-props 13 Hors ligne Marrrrrrrie Re : Pas de scroll avec le touchpad (ubuntu 12.04) Salut Stevens4c, Voici le résultat des deux commandes: marie@pc:~> lsusb Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub Bus 001 Device 003: ID 413c:8197 Dell Computer Corp. Bus 001 Device 004: ID 1bcf:2895 Sunplus Innovation Technology Inc. Bus 002 Device 003: ID 0a5c:5801 Broadcom Corp. BCM5880 Secure Applications Processor with fingerprint swipe sensor marie@pc:~> xinput list-props 13 Device 'AT Translated Set 2 keyboard': Device Enabled (132): 1 Coordinate Transformation Matrix (134): 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000 Device Product ID (252): 1, 1 Device Node (253): "/dev/input/event4" Est-ce que ça indique que le touchpad est branché sur un port usb ? Merci beaucoup ! Marie Hors ligne Marrrrrrrie Re : Pas de scroll avec le touchpad (ubuntu 12.04) Salut, Apparemment gsynaptics a été remplacé par gpointing-device-settings pour ma version. Je l'ai installé, et quand je le lance, mon touchpad est reconnu comme une souris: J'ai essayé de cocher les différentes cases, mais ça n'active jamais le scroll ! Merci, Marie Hors ligne kej Re : Pas de scroll avec le touchpad (ubuntu 12.04) Pour apporter des éléments de non réponse, j'ai eu (avec un ordi proche : latitude E6420) le meme soucis au tout debut avec un archlinux : touchpad qui marche mais pas de scroll. Il etait reconnu comme une souris PS2. Par contre tout a été reglé avec les drivers synaptics pour arch ( https://wiki.archlinux.org/index.php/Touchpad_Synaptics )... qui n'existent donc plus pour ubuntu, remplacés par le gpointing device qui ne marche pas... Peut-etre qu'il existe la possibilité de retrouver des anciens paquets synaptics depreciés mais qui fonctionnent encore ? Hors ligne Marrrrrrrie Re : Pas de scroll avec le touchpad (ubuntu 12.04) Non, synclient n'a pas l'air installé ! marie@pc:~> synclient Couldn't find synaptics properties. No synaptics driver loaded? Hors ligne stevens4c Re : Pas de scroll avec le touchpad (ubuntu 12.04) bon alors si tu as bien la version 12.04 c est la meme que la mienne tu vas dans la logitheque ubuntu et tu tapes pour la recherche: syncl tu devrais trouver ceci: Pilote de pavé tactile Synaptics pour le serveur X.Org si ce n est pas installe alors installe le. Dernière modification par stevens4c (Le 19/10/2012, à 00:20) Hors ligne Marrrrrrrie Re : Pas de scroll avec le touchpad (ubuntu 12.04) Oui c'est bien ça! Mais ce paquet est déjà installé Hors ligne stevens4c Re : Pas de scroll avec le touchpad (ubuntu 12.04) essaie de télécharger dans la ludothèque ce fichier Pilote de pavé tactile Synaptics pour le serveur X.Org xserver-xorg-input-synaptics:i386 la commande man synaptics donne quoi? Hors ligne Marrrrrrrie Re : Pas de scroll avec le touchpad (ubuntu 12.04) Lorsque j'essaie d'installer xserver-xorg-input-synaptics:i386 dans la logithèque, le paquet existe bien, mais ubuntu refuse de l'installer, car il y a des paquets supplémentaires requis qui sont non-installables, notamment 'xorg-input-abi-16', et là ça dépasse un peu mes compétences J'ai aussi désinstallé puis réinstallé le paquet xserver-xorg-input-synaptics, mais la commande synclient donne toujours la même chose... Par contre quand je fais man synaptics, ça marche, je vois le man ! Dernière modification par Marrrrrrrie (Le 21/10/2012, à 15:37) Hors ligne stevens4c Re : Pas de scroll avec le touchpad (ubuntu 12.04) egrep -i 'synap|alps|etps' /proc/bus/input/devices dis moi ce que te renvoi cette commande Hors ligne Marrrrrrrie Re : Pas de scroll avec le touchpad (ubuntu 12.04) Voici le man synaptics SYNAPTICS(4) SYNAPTICS(4) NAME synaptics - touchpad input driver SYNOPSIS Section "InputDevice" Identifier "devname" Driver "synaptics" Option "Device" "devpath" Option "Path" "path" ... EndSection DESCRIPTION synaptics is an Xorg input driver for touchpads. Even though touchpads can be handled by the normal evdev or mouse drivers, this driver allows more advanced features of the touchpad to become available. Some bene‐ fits would be: · Movement with adjustable, non-linear acceleration and speed. · Button events through short touching of the touchpad. · Double-Button events through double short touching of the touchpad. · Dragging through short touching and holding down the finger on the touchpad (tap-and-drag gesture). · Middle and right button events on the upper and lower corner of the touchpad. · Vertical scrolling (button four and five events) through moving the finger on the right side of the touchpad. · The up/down button sends button four/five events. · Horizontal scrolling (button six and seven events) through moving the finger on the lower side of the touchpad. · The multi-buttons send button four/five events for vertical scrolling and button six/seven events for horizontal scrolling. · Adjustable finger detection. · Multifinger taps: two finger for right button and three finger for middle button events. (Needs hardware support. Not all models implement this feature.) · Pressure-dependent motion speed. Note that depending on the touchpad firmware, some of these features might be available even without using the synaptics driver. Note also that some functions are not available on all touchpad models, because they need support from the touchpad hardware/firmware. (Multifinger taps for example.) The name "synaptics" is historical and the driver still provides the synaptics protocol parsing code. Under Linux however, the hardware- specifics are handled by the kernel and this driver will work for any touchpad that has a working kernel driver. If your device is recognized as "PS/2 Mouse" or similar, the kernel driver does not support your device and this driver will only provide limited functionality. CONFIGURATION OPTIONS Please refer to xorg.conf(5) for general configuration details and for options that can be used with all input drivers. This section only covers configuration details specific to this driver. The following driver Options are supported: Option "Device" "string" This option specifies the device file in your "/dev" directory which will be used to access the physical device. Normally you should use something like "/dev/input/eventX", where X is some integer. Option "Protocol" "string" Specifies which kernel driver will be used by this driver. This is the list of supported drivers and their default use scenar‐ ios. auto-dev automatic, default (recommend) event Linux 2.6 kernel events psaux raw device access (Linux 2.4) psm FreeBSD psm driver Option "SHMConfig" "boolean" Switch on/off shared memory for run-time debugging. This option does not have an effect on run-time configuration anymore and is only useful for hardware event debugging. Option "LeftEdge" "integer" X coordinate for left edge. Property: "Synaptics Edges" Option "RightEdge" "integer" X coordinate for right edge. Property: "Synaptics Edges" Option "TopEdge" "integer" Y coordinate for top edge. Property: "Synaptics Edges" Option "BottomEdge" "integer" Y coordinate for bottom edge. Property: "Synaptics Edges" Option "FingerLow" "integer" When finger pressure drops below this value, the driver counts it as a release. Property: "Synaptics Finger" Option "FingerHigh" "integer" When finger pressure goes above this value, the driver counts it as a touch. Property: "Synaptics Finger" Option "FingerPress" "integer" When finger pressure goes above this value, the driver counts it as a press. Currently a press is equivalent to putting the touchpad in trackstick emulation mode. Property: "Synaptics Fin‐ ger" Option "MaxTapTime" "integer" Maximum time (in milliseconds) for detecting a tap. Property: "Synaptics Tap Durations" Option "MaxTapMove" "integer" Maximum movement of the finger for detecting a tap. Property: "Synaptics Tap Move" Option "MaxDoubleTapTime" "integer" Maximum time (in milliseconds) for detecting a double tap. Prop‐ erty: "Synaptics Tap Durations" Option "ClickTime" "integer" The duration of the mouse click generated by tapping. Property: "Synaptics Tap Durations" Option "ClickPad" "boolean" Whether the device is a click pad. See ClickPad support for more details. Property: "Synaptics ClickPad" Option "FastTaps" "boolean" Makes the driver react faster to a single tap, but also makes double clicks caused by double tapping slower. Property: "Synap‐ tics Tap FastTap" Option "VertEdgeScroll" "boolean" Enable vertical scrolling when dragging along the right edge. Property: "Synaptics Edge Scrolling" Option "HorizEdgeScroll" "boolean" Enable horizontal scrolling when dragging along the bottom edge. Property: "Synaptics Edge Scrolling" Option "CornerCoasting" "boolean" Enable edge scrolling to continue while the finger stays in an edge corner. Property: "Synaptics Edge Scrolling" Option "VertTwoFingerScroll" "boolean" Enable vertical scrolling when dragging with two fingers any‐ where on the touchpad. Property: "Synaptics Two-Finger Scrolling" Option "HorizTwoFingerScroll" "boolean" Enable horizontal scrolling when dragging with two fingers any‐ where on the touchpad. Property: "Synaptics Two-Finger Scrolling" Option "VertScrollDelta" "integer" Move distance of the finger for a scroll event. Property: "Synaptics Scrolling Distance" Option "HorizScrollDelta" "integer" Move distance of the finger for a scroll event. Property: "Synaptics Scrolling Distance" Option "EdgeMotionMinZ" "integer" Finger pressure at which minimum edge motion speed is set. Prop‐ erty: "Synaptics Edge Motion Pressure" Option "EdgeMotionMaxZ" "integer" Finger pressure at which maximum edge motion speed is set. Prop‐ erty: "Synaptics Edge Motion Pressure" Option "EdgeMotionMinSpeed" "integer" Slowest setting for edge motion speed. Property: "Synaptics Edge Motion Speed" Option "EdgeMotionMaxSpeed" "integer" Fastest setting for edge motion speed. Property: "Synaptics Edge Motion Speed" Option "EdgeMotionUseAlways" "boolean" If on, edge motion is also used for normal movements. If off, edge motion is used only when dragging. Property: "Synaptics Edge Motion Always" Option "MinSpeed" "float" Minimum speed factor. Property: "Synaptics Move Speed" Option "MaxSpeed" "float" Maximum speed factor. Property: "Synaptics Move Speed" Option "AccelFactor" "float" Acceleration factor for normal pointer movements. Property: "Synaptics Move Speed" Option "TrackstickSpeed" "float" Speed scale when in trackstick emulation mode. Property: "Synap‐ tics Move Speed" Option "PressureMotionMinZ" "integer" Finger pressure at which minimum pressure motion factor is applied. Property: "Synaptics Pressure Motion" Option "PressureMotionMaxZ" "integer" Finger pressure at which maximum pressure motion factor is applied. Property: "Synaptics Pressure Motion" Option "PressureMotionMinFactor" "integer" Lowest setting for pressure motion factor. Property: "Synaptics Pressure Motion Factor" Option "PressureMotionMaxFactor" "integer" Greatest setting for pressure motion factor. Property: "Synap‐ tics Pressure Motion Factor" Option "HorizHysteresis" "integer" The minimum horizontal HW distance required to generate motion events. Can be specified as a percentage. Increase if noise motion is a problem for you. Zero is disabled. Default: 0.5 percent of the diagonal or (in case of evdev) the appropriate "fuzz" as advertised by the device. Option "VertHysteresis" "integer" The minimum vertical HW distance required to generate motion events. See HorizHysteresis. Option "UpDownScrolling" "boolean" If on, the up/down buttons generate button 4/5 events. If off, the up button generates a double click and the down button gen‐ erates a button 2 event. This option is only available for touchpads with physical scroll buttons. Property: "Synaptics Button Scrolling" Option "LeftRightScrolling" "boolean" If on, the left/right buttons generate button 6/7 events. If off, the left/right buttons both generate button 2 events. This option is only available for touchpads with physical scroll but‐ tons. Property: "Synaptics Button Scrolling" Option "UpDownScrollRepeat" "boolean" If on, and the up/down buttons are used for scrolling (UpDown‐ Scrolling), these buttons will send auto-repeating 4/5 events, with the delay between repeats determined by ScrollButtonRepeat. This option is only available for touchpads with physical scroll buttons. Property: "Synaptics Button Scrolling Repeat" Option "LeftRightScrollRepeat" "boolean" If on, and the left/right buttons are used for scrolling (Left‐ RightScrolling), these buttons will send auto-repeating 6/7 events, with the delay between repeats determined by ScrollBut‐ tonRepeat. This option is only available for touchpads with physical scroll buttons. Property: "Synaptics Button Scrolling Repeat" Option "ScrollButtonRepeat" "integer" The number of milliseconds between repeats of button events 4-7 from the up/down/left/right scroll buttons. This option is only available for touchpads with physical scroll buttons. Property: "Synaptics Button Scrolling Time" Option "EmulateMidButtonTime" "integer" Maximum time (in milliseconds) for middle button emulation. Property: "Synaptics Middle Button Timeout" Option "EmulateTwoFingerMinZ" "integer" For touchpads not capable of detecting multiple fingers but are capable of detecting finger pressure and width, this sets the Z pressure threshold. When both Z pressure and W width thresholds are crossed, a two finger press will be emulated. This defaults to a value that disables emulation on touchpads with real two- finger detection and defaults to a value that enables emulation on remaining touchpads that support pressure and width support. Property: "Synaptics Two-Finger Pressure" Option "EmulateTwoFingerMinW" "integer" For touchpads not capable of detecting multiple fingers but are capable of detecting finger width and pressure, this sets the W width threshold. When both W width and Z pressure thresholds are crossed, a two finger press will be emulated. This feature works best with (PalmDetect) off. Property: "Synaptics Two-Fin‐ ger Width" Option "TouchpadOff" "integer" Switch off the touchpad. Valid values are: 0 Touchpad is enabled 1 Touchpad is switched off 2 Only tapping and scrolling is switched off Property: "Synaptics Off" Option "LockedDrags" "boolean" If off, a tap-and-drag gesture ends when you release the finger. If on, the gesture is active until you tap a second time, or until LockedDragTimeout expires. Property: "Synaptics Locked Drags" Option "LockedDragTimeout" "integer" This parameter specifies how long it takes (in milliseconds) for the LockedDrags mode to be automatically turned off after the finger is released from the touchpad. Property: "Synaptics Locked Drags Timeout" Option "RTCornerButton" "integer" Which mouse button is reported on a right top corner tap. Set to 0 to disable. Property: "Synaptics Tap Action" Option "RBCornerButton" "integer" Which mouse button is reported on a right bottom corner tap. Set to 0 to disable. Property: "Synaptics Tap Action" Option "LTCornerButton" "integer" Which mouse button is reported on a left top corner tap. Set to 0 to disable. Property: "Synaptics Tap Action" Option "LBCornerButton" "integer" Which mouse button is reported on a left bottom corner tap. Set to 0 to disable. Property: "Synaptics Tap Action" Option "TapButton1" "integer" Which mouse button is reported on a non-corner one-finger tap. Set to 0 to disable. Property: "Synaptics Tap Action" Option "TapButton2" "integer" Which mouse button is reported on a non-corner two-finger tap. Set to 0 to disable. Property: "Synaptics Tap Action" Option "TapButton3" "integer" Which mouse button is reported on a non-corner three-finger tap. Set to 0 to disable. Property: "Synaptics Tap Action" Option "ClickFinger1" "integer" Which mouse button is reported when left-clicking with one fin‐ ger. Set to 0 to disable. Property: "Synaptics Click Action" Option "ClickFinger2" "integer" Which mouse button is reported when left-clicking with two fin‐ gers. Set to 0 to disable. Property: "Synaptics Click Action" Option "ClickFinger3" "integer" Which mouse button is reported when left-clicking with three fingers. Set to 0 to disable. Property: "Synaptics Click Action" Option "CircularScrolling" "boolean" If on, circular scrolling is used. Property: "Synaptics Circular Scrolling" Option "CircScrollDelta" "float" Move angle (radians) of finger to generate a scroll event. Prop‐ erty: "Synaptics Circular Scrolling Distance" Option "CircScrollTrigger" "integer" Trigger region on the touchpad to start circular scrolling 0 All Edges 1 Top Edge 2 Top Right Corner 3 Right Edge 4 Bottom Right Corner 5 Bottom Edge 6 Bottom Left Corner 7 Left Edge 8 Top Left Corner Property: "Synaptics Circular Scrolling Trigger" Option "CircularPad" "boolean" Instead of being a rectangle, the edge is the ellipse enclosed by the Left/Right/Top/BottomEdge parameters. For circular touchpads. Property: "Synaptics Circular Pad" Option "PalmDetect" "boolean" If palm detection should be enabled. Note that this also requires hardware/firmware support from the touchpad. Property: "Synaptics Palm Detection" Option "PalmMinWidth" "integer" Minimum finger width at which touch is considered a palm. Prop‐ erty: "Synaptics Palm Dimensions" Option "PalmMinZ" "integer" Minimum finger pressure at which touch is considered a palm. Property: "Synaptics Palm Dimensions" Option "CoastingSpeed" "float" Your finger needs to produce this many scrolls per second in order to start coasting. The default is 20 which should prevent you from starting coasting unintentionally. 0 disables coast‐ ing. Property: "Synaptics Coasting Speed" Option "CoastingFriction" "float" Number of scrolls/second² to decrease the coasting speed. Default is 50. Property: "Synaptics Coasting Speed" Option "SingleTapTimeout" "integer" Timeout after a tap to recognize it as a single tap. Property: "Synaptics Tap Durations" Option "GrabEventDevice" "boolean" If GrabEventDevice is true, the driver will grab the event device for exclusive use when using the linux 2.6 event proto‐ col. When using other protocols, this option has no effect. Grabbing the event device means that no other user space or ker‐ nel space program sees the touchpad events. This is desirable if the X config file includes /dev/input/mice as an input device, but is undesirable if you want to monitor the device from user space. When changing this parameter with the syn‐ client program, the change will not take effect until the synap‐ tics driver is disabled and reenabled. This can be achieved by switching to a text console and then switching back to X. Option "TapAndDragGesture" "boolean" Switch on/off the tap-and-drag gesture. This gesture is an alternative way of dragging. It is performed by tapping (touch‐ ing and releasing the finger), then touching again and moving the finger on the touchpad. The gesture is enabled by default and can be disabled by setting the TapAndDragGesture option to false. Property: "Synaptics Gestures" Option ®esolutionDetect" "" boolean " Allow or prevent the synaptics driver from reporting the size of the touchpad to the X server. The X server normally uses this information to scale movements so that touchpad movement corresponds visually to mouse cursor movements on the screen. However, in some rare cases where the touchpad height/width ratio is significantly different from the laptop, it can cause the mouse cursor to skip pixels in the X or Y axis. This option allows disabling this scaling behavior, which can provide smoother mouse movement in such cases. Prop‐ erty: "Synaptics Resolution Detect" Option "VertResolution" "integer" Resolution of X coordinates in units/millimeter. The value is used together with HorizResolution to compensate unequal verti‐ cal and horizontal sensitivity. Setting VertResolution and HorizResolution equal values means no compensation. Default value is read from the touchpad or set to 1 if value could not be read. Property: "Synaptics Pad Resolution" Option "HorizResolution" "integer" Resolution of Y coordinates in units/millimeter. The value is used together with VertResolution to compensate unequal vertical and horizontal sensitivity. Setting VertResolution and HorizRes‐ olution equal values means no compensation. Default value is read from the touchpad or set to 1 if value could not be read. Property: "Synaptics Pad Resolution" Option "AreaLeftEdge" "integer" Ignore movements, scrolling and tapping which take place left of this edge. The option is disabled by default and can be enabled by setting the AreaLeftEdge option to any integer value other than zero. If supported by the server (version 1.9 and later), the edge may be specified in percent of the total width of the touchpad. Property: "Synaptics Area" Option "AreaRightEdge" "integer" Ignore movements, scrolling and tapping which take place right of this edge. The option is disabled by default and can be enabled by setting the AreaRightEdge option to any integer value other than zero. If supported by the server (version 1.9 and later), the edge may be specified in percent of the total width of the touchpad. Property: "Synaptics Area" Option "AreaTopEdge" "integer" Ignore movements, scrolling and tapping which take place above this edge. The option is disabled by default and can be enabled by setting the AreaTopEdge option to any integer value other than zero. If supported by the server (version 1.9 and later), the edge may be specified in percent of the total height of the touchpad. Property: "Synaptics Area" Option "AreaBottomEdge" "integer" Ignore movements, scrolling and tapping which take place below this edge. The option is disabled by default and can be enabled by setting the AreaBottomEdge option to any integer value other than zero. If supported by the server (version 1.9 and later), the edge may be specified in percent of the total height of the touchpad. Property: "Synaptics Area" Option "SoftButtonAreas" "RBL RBR RBT RBB MBL MBR MBT MBB" This option is only available on ClickPad devices. Enable soft button click area support on ClickPad devices. The first four parameters are the left, right, top, bottom edge of the right button, respectively, the second four parameters are the left, right, top, bottom edge of the middle button, respectively. Any of the values may be given as percentage of the touchpad width or height, whichever applies. If any edge is set to 0, the but‐ ton is assumed to extend to infinity in the given direction. Setting all values to 0 disables soft button areas. Property: "Synaptics Soft Button Areas" CONFIGURATION DETAILS Area handling The LeftEdge, RightEdge, TopEdge and BottomEdge parameters are used to define the edge and corner areas of the touchpad. The parameters split the touchpad area in 9 pieces, like this: │ │ │ LeftEdge │ RightEdge ┌─────└─────────────└───┐ Physical top edge │ 1 │ 2 │ 3 │ └─────└─────────────└───┘ TopEdge │ │ │ │ │ 4 │ 5 │ 6 │ │ │ │ │ └─────└─────────────└───┘ BottomEdge │ 7 │ 8 │ 9 │ └─────└─────────────└───┘ Physical bottom edge │Physical left edge │ Physical right edge Coordinates to the left of LeftEdge are part of the left edge (areas 1, 4 and 7), coordinates to the left of LeftEdge and above TopEdge (area 1) are part of the upper left corner, etc. A good way to find appropriate edge parameters is to enable the SHMCon‐ fig option and run "synclient -m 1" to see the x/y coordinates corre‐ sponding to different positions on the touchpad. The perceived physical edges may be adjusted with the AreaLeftEdge, AreaRightEdge, AreaTopEdge, and AreaBottomEdge options. If these values are set to something other than the physical edges, input in the space between the area edge and the respective physical edge is ignored. Note that this reduces the available space on the touchpad. Tapping A tap event happens when the finger is touched and released in a time interval shorter than MaxTapTime, and the touch and release coordinates are less than MaxTapMove units apart. A "touch" event happens when the Z value goes above FingerHigh, and an "untouch" event happens when the Z value goes below FingerLow. The MaxDoubleTapTime parameter has the same function as the MaxTapTime parameter, but for the second, third, etc tap in a tap sequence. If you can't perform double clicks fast enough (for example, xmms depends on fast double clicks), try reducing this parameter. If you can't get word selection to work in xterm (ie button down, button up, button down, move mouse), try increasing this parameter. The ClickTime parameter controls the delay between the button down and button up X events generated in response to a tap event. A too long value can cause undesirable autorepeat in scroll bars and a too small value means that visual feedback from the gui application you are interacting with is harder to see. For this parameter to have any effect, "FastTaps" has to be disabled. Acceleration The MinSpeed, MaxSpeed and AccelFactor parameters control the pointer motion speed. The speed value defines the scaling between touchpad coordinates and screen coordinates. When moving the finger very slowly, the MinSpeed value is used, when moving very fast the MaxSpeed value is used. When moving the finger at moderate speed, you get a pointer motion speed somewhere between MinSpeed and MaxSpeed. If you don't want any acceleration, set MinSpeed and MaxSpeed to the same value. The MinSpeed, MaxSpeed and AccelFactor parameters don't have any effect on scrolling speed. Scrolling speed is determined solely from the VertScrollDelta and HorizScrollDelta parameters. To disable vertical or horizontal scrolling, set VertScrollDelta or HorizScrollDelta to zero. To invert the direction of vertical or horizontal scrolling, set VertScrollDelta or HorizScrollDelta to a negative value. Acceleration is mostly handled outside the driver, thus the driver will translate MinSpeed into constant deceleration and adapt MaxSpeed at startup time. This ensures you can user the other acceleration pro‐ files, albeit without pressure motion. However the numbers at runtime will likely be different from any options you may have set. Pressure motion When pressure motion is activated, the cursor motion speed depends on the pressure exerted on the touchpad (the more pressure exerted on the touchpad, the faster the pointer). More precisely the speed is first calculated according to MinSpeed, MaxSpeed and AccelFactor, and then is multiplied by a sensitivity factor. The sensitivity factor can be adjusted using the PressureMotion parame‐ ters. If the pressure is below PressureMotionMinZ, PressureMotionMin‐ Factor is used, and if the pressure is greater than PressureMotionMaxZ, PressureMotionMaxFactor is used. By default, PressureMotionMinZ and PressureMotionMaxZ are equal to EdgeMotionMinZ and EdgeMotionMaxZ. For a pressure value between PressureMotionMinZ and PressureMotionMaxZ, the factor is increased linearly. Edge motion When hitting an edge, movement can be automatically continued. If EdgeMotionUseAlways is false, edge motion is only used when dragging. With EdgeMotionUseAlways set to true, it is also used for normal cursor movements. Edge motion speed is calculated by taking into account the amount of pressure applied to the touchpad. The sensitivity can be adjusted using the EdgeMotion parameters. If the pressure is below EdgeMotion‐ MinZ, EdgeMotionMinSpeed is used, and if the pressure is greater than EdgeMotionMaxZ, EdgeMotionMaxSpeed is used. For a pressure value between EdgeMotionMinZ and EdgeMotionMaxZ, the speed is increased lin‐ early. Middle button emulation Since most synaptics touchpad models don't have a button that corre‐ sponds to the middle button on a mouse, the driver can emulate middle mouse button events. If you press both the left and right mouse but‐ tons at almost the same time (no more than EmulateMidButtonTime mil‐ liseconds apart) the driver generates a middle mouse button event. Circular scrolling Circular scrolling acts like a scrolling wheel on the touchpad. Scrolling is engaged when a drag starts in the given CircScrollTrigger region, which can be all edges, a particular side, or a particular cor‐ ner. Once scrolling is engaged, moving your finger in clockwise cir‐ cles around the center of the touchpad will generate scroll down events and counter clockwise motion will generate scroll up events. Lifting your finger will disengage circular scrolling. Use tight circles near the center of the pad for fast scrolling and large circles for better control. When used together with vertical scrolling, hitting the upper or lower right corner will seamlessly switch over from vertical to cir‐ cular scrolling. Coasting Coasting is enabled by setting the CoastingSpeed parameter to a non- zero value. Coasting comes in two flavors: conventional (finger off) coasting, and corner (finger on) coasting. Conventional coasting is enabled when coasting is enabled, and Corner‐ Coasting is set to false. When conventional coasting is enabled, hori‐ zontal/vertical scrolling can continue after the finger is released from the lower/right edge of the touchpad. The driver computes the scrolling speed corresponding to the finger speed immediately before the finger leaves the touchpad. If this scrolling speed is larger than the CoastingSpeed parameter (measured in scroll events per second), the scrolling will continue with the same speed in the same direction until the finger touches the touchpad again. Corner coasting is enabled when coasting is enabled, and CornerCoasting is set to true. When corner coasting is enabled, edge scrolling can continue as long as the finger stays in a corner. Coasting begins when the finger enters the corner, and continues until the finger leaves the corner. CornerCoasting takes precedence over the seamless switch from edge scrolling to circular scrolling. That is, if CornerCoasting is active, scrolling will stop, and circular scrolling will not start, when the finger leaves the corner. Noise cancellation The synaptics has a built-in noise cancellation based on hysteresis. This means that incoming coordinates actually shift a box of predefined dimensions such that it covers the incoming coordinate, and only the boxes own center is used as input. Obviously, the smaller the box the better, but the likelyhood of noise motion coming through also increases. Trackstick mode Trackstick emulation mode is entered when pressing the finger hard on the touchpad. The FingerPress parameter controls the minimum required finger pressure. If the finger hasn't moved more than MaxTapMove after MaxTapTime has elapsed, trackstick mode is entered. In this mode, mov‐ ing the finger slightly in any direction gives a speed vector that moves the pointer. The TrackstickSpeed parameter controls the ratio between pointer speed and finger movement distance. Trackstick mode is exited when the finger pressure drops below FingerLow or when the fin‐ ger is moved further than MaxTapMove away from the initial position. ClickPad support A click pad device has button(s) integrated into the touchpad surface. The user must press downward on the touchpad in order to generated a button press. ClickPad support is enabled if the option ClickPad is set or the property is set at runtime. On some platforms, this option will be set automatically if the kernel detects a matching device. On Linux, the device must have the INPUT_PROP_BUTTONPAD property set. ClickPads do not support middle mouse button emulation. If enabling ClickPad support at runime, the user must also set the middle mouse button timeout to 0. If auto-detected, middle mouse button emulation is disabled by the driver. ClickPads provide software emulated buttons through Option SoftBut‐ tonAreas. These buttons enable areas on the touchpad to perform as right or middle mouse button. When the user performs a click within a defined soft button area, a right or middle click is performed. DEVICE PROPERTIES Synaptics 1.0 and higher support input device properties if the driver is running on X server 1.6 or higher. On these driver versions, Option "SHMConfig" is not needed to enable run-time configuration. The syn‐ client tool shipped with synaptics version 1.1 uses input device prop‐ erties by default. Properties supported: Synaptics Edges 32 bit, 4 values, left, right, top, bottom. Synaptics Finger 32 bit, 3 values, low, high, press. Synaptics Tap Time 32 bit. Synaptics Tap Move 32 bit. Synaptics Tap Durations 32 bit, 3 values, single touch timeout, max tapping time for double taps, duration of a single click. Synaptics ClickPad 8 bit (Bool). Synaptics Tap FastTap 8 bit (BOOL). Synaptics Middle Button Timeout 32 bit. Synaptics Two-Finger Pressure 32 bit. Synaptics Two-Finger Width 32 bit. Synaptics Scrolling Distance 32 bit, 2 values, vert, horiz. Synaptics Edge Scrolling 8 bit (BOOL), 3 values, vertical, horizontal, corner. Synaptics Two-Finger Scrolling 8 bit (BOOL), 2 values, vertical, horizontal. Synaptics Move Speed FLOAT, 4 values, min, max, accel, trackstick. Synaptics Edge Motion Pressure 32 bit, 2 values, min, max. Synaptics Edge Motion Speed 32 bit, 2 values, min, max. Synaptics Edge Motion Always 8 bit (BOOL). Synaptics Button Scrolling 8 bit (BOOL), 2 values, updown, leftright. Synaptics Button Scrolling Repeat 8 bit (BOOL), 2 values, updown, leftright. Synaptics Button Scrolling Time 32 bit. Synaptics Off 8 bit, valid values (0, 1, 2). Synaptics Locked Drags 8 bit (BOOL). Synaptics Locked Drags Timeout 32 bit. Synaptics Tap Action 8 bit, up to MAX_TAP values (see synaptics.h), 0 disables an element. order: RT, RB, LT, LB, F1, F2, F3. Synaptics Click Action 8 bit, up to MAX_CLICK values (see synaptics.h), 0 disables an element. order: Finger 1, 2, 3. Synaptics Circular Scrolling 8 bit (BOOL). Synaptics Circular Scrolling Distance FLOAT. Synaptics Circular Scrolling Trigger 8 bit, valid values 0..8 (inclusive) order: any edge, top, top + right, right, right + bottom, bottom, bottom + left, left, left + top. Synaptics Circular Pad 8 bit (BOOL). Synaptics Palm Detection 8 bit (BOOL). Synaptics Palm Dimensions 32 bit, 2 values, width, z. Synaptics Coasting Speed FLOAT, 2 values, speed, friction. Synaptics Pressure Motion 32 bit, 2 values, min, max. Synaptics Pressure Motion Factor FLOAT, 2 values, min, max. Synaptics Resolution Detect 8 bit (BOOL). Synaptics Grab Event Device 8 bit (BOOL). Synaptics Gestures 8 bit (BOOL), 1 value, tap-and-drag. Synaptics Area The AreaLeftEdge, AreaRightEdge, AreaTopEdge and AreaBottomEdge parameters are used to define the edges of the active area of the touchpad. All movements, scrolling and tapping which take place outside of this area will be ignored. This property is disabled by default. 32 bit, 4 values, left, right, top, bottom. 0 disables an ele‐ ment. Synaptics Soft Button Areas This property is only available on ClickPad devices. The Right and middle soft button areas are used to support right and mid‐ dle click actions on a ClickPad device. Providing 0 for all val‐ ues of a given button disables the button area. 32 bit, 8 values, RBL, RBR, RBT, RBB, MBL, MBR, MBT, MBB. Synaptics Capabilities This read-only property expresses the physical capability of the touchpad, most notably whether the touchpad hardware supports multi-finger tapping and scrolling. 8 bit (BOOL), 7 values (read-only), has left button, has middle button, has right button, two-finger detection, three-finger detection, pressure detection, and finger/palm width detection. Synaptics Pad Resolution 32 bit unsigned, 2 values (read-only), vertical, horizontal in units/millimeter. NOTES Configuration through InputClass sections is recommended in X servers 1.8 and later. See xorg.conf.d(5) for more details. An example xorg.conf.d snippet is provided in ${sourcecode}/conf/50-synaptics.conf Configuration through hal fdi files is recommended in X servers 1.5, 1.6 and 1.7. An example hal policy file is provided in ${source‐ code}/conf/11-x11-synaptics.fdi If either of Protocol "auto-dev" (default) or Protocol "event" is used, the driver initializes defaults based on the capabilities reported by the kernel driver. Acceleration, edges and resolution are based on the dimensions reported by the kernel. If the kernel reports multi-finger detection, two-finger vertical scrolling is enabled, horizontal two- finger scrolling is disabled and edge scrolling is disabled. If no multi-finger capabilities are reported, edge scrolling is enabled for both horizontal and vertical scrolling. Tapping is disabled by default for touchpads with one or more physical buttons. To enable it you need to map tap actions to buttons. See the "TapButton1", "TapButton2" and "TapButton3" options. Button mapping for physical buttons is handled in the server. If the device is switched to left-handed (an in-server mapping of physical buttons 1, 2, 3 to the logical buttons 3, 2, 1, respectively), both physical and TapButtons are affected. To counteract this, the TapBut‐ tons need to be set up in reverse order (TapButton1=3, TapButton2=1). REMOVED OPTIONS The following options are no longer part of the driver configuration: Option "Repeater" "string" Option "HistorySize" "integer" Option "SpecialScrollAreaRight" "boolean" Option "GuestMouseOff" "boolean" AUTHORS Peter Osterlund <petero2@telia.com> and many others. SEE ALSO Xorg(1), xorg.conf(5), Xserver(1), X(7), synclient(1), syndaemon(1) X Version 11 xf86-input-synaptics 1.6.2 SYNAPTICS(4) Et egrep -i 'synap|alps|etps' /proc/bus/input/devices ne renvoie rien... Hors ligne stevens4c Re : Pas de scroll avec le touchpad (ubuntu 12.04) ton touchpad n est pas reconnu de toute evidence. peut etre qu une réinstallation de ubuntu pourrait debloquer la situation. sans brancher de souris biensur. sinon là je vois pas trop quoi faire. c est etrange qu il ne soit pas reconnu Hors ligne
I'm looking for a way to set a time limit, a countdown. I will use this function to control the amount of time the user can run a while loop. Here's an example of how it's doing to run. def run(strings, timeout=30): while timeout > 0: input = raw_input("prompts that will continue prompting as long as not timed out") if input != strings: #do something here, maybe be able to deduct off timer. else: score += 1 print "%d /r" % timeout #print timeout return score My example may not be very neat, but it's the general idea. The timeout will control the loop. Can this be done for the timer library? Do I need a separate thread to handle the time while my function runs (prompting user)?
Your gpu is an awesome thing, it can do all kind of calculations, very fast. For example, instead of telling it exactly how you want each pixels to be, you can throw textures and vertices at it, and have it correctly deduce how this things will have to look. To do this, though, you must tell it what part of the texture will be stuck to each vertice. This is usually denoted using texture coordinates. Texture coordinates, like usual coordinates, indicate the place of something. Instead of noting them x and y, they are often called u and v, which allows to clearly note what parts of an equation relate to each. While kivy offers you high level canvas instructions, it gives you a pretty good access to lower level features, and you can actually manipulate the texture coordinates of your Rectangle instructions. This allow for cheap zooming, repeat-scrolling, and other image manipulations, since your gpu is doing all the actual work. tex_coords = u, v, u + w, v, u + w, v + h, u, v + h which is better understood as: tex_coords = [ u, v, u + w, v, u + w, v + h, u, v + h] considering a default tex_coords value, where u and v = 0, and w and h = 1 (all values are relatives, so usually between 0 and 1). u, v + h-------u + w, v + h| |u, v-----------u + w, v which means the 4 angles of your texture, will be on the 4 angles of your rectangle, how dull! One way to play with different values, is to create a little app showing you the effect of deformations. from kivy.app import App from kivy.lang import Builder from kivy.uix.widget import Widget from kivy.properties import ObjectProperty, ListProperty from kivy.core.image import Image as CoreImage kv = ''' #:import chain itertools.chain RootWidget: canvas: Color: rgba: 1, 1, 1, 1 Rectangle: pos: root.pos size: root.size texture: app.texture # here is our usage of the calculated texture coordinates # we devide by 100 because we took the input with a 100x100 # rectangle as default value tex_coords: [x / 100. for x in chain(*root.points)] PushMatrix # translate the rectangle to make it easier to play with Translate: xy: root.width / 2, root.height / 2 Color: rgba: 1, 0, 0, .5 Line: points: chain(*root.points + root.points[:1]) width: 2 PopMatrix ''' def dist(point, pos): return ((point[0] - pos[0]) ** 2 + (point[1] - pos[1]) ** 2) # ** .5 # who cares about square root here? it doesn't change the order class RootWidget(Widget): # the default values, a 100x100 square, displayed around the middle of the screen points = ListProperty([[0, 0], [100, 0], [100, 100], [0, 100]]) def on_touch_down(self, touch, *args): # compensate the translation done in canvas pos = touch.pos[0] - self.width / 2, touch.pos[1] - self.height / 2 touch.ud['point'] = min( range(4), key=lambda x: dist(self.points[x], pos)) def on_touch_move(self, touch, *args): # compensate the translation done in canvas pos = touch.pos[0] - self.width / 2, touch.pos[1] - self.height / 2 # update the point self.points[touch.ud['point']] = pos class TexCoordsApp(App): texture = ObjectProperty(None) def build(self): self.root = Builder.load_string(kv) self.texture = CoreImage.load( 'GrassGreenTexture0002.jpg').texture self.texture.wrap = 'repeat' return self.root if __name__ == '__main__': TexCoordsApp().run() The texture have been scrapped on the web and is not very interesting, but you can find it here. Of course, this is much more a learning device (helful because these transformation are not quite straighforward for our brains) than a practical application, but a lot more can be done. Here is, for example, a little infinite scroll app uting this concept.
I have the following code, which has the following two problems: Traceback (most recent call last): File "C:\Users\v\workspace\first\src\tests.py", line 1, in <module> class Animal: File "C:\Users\v\workspace\first\src\tests.py", line 39, in Animal File "C:\Users\v\workspace\first\src\tests.py", line 31, in main dog = Animal() NameError: global name 'Animal' is not defined This code is from a tutorial, and in the tutorial it works fine. I have the Python 2.7 and use the PyDev plugin for Eclipse. class Animal: __hungry = "yes" __name = "no name" __owner = "no owner" def __init__(self): pass def set_owner(self,newOwner): self.__owner= newOwner return def get_owner(self): return self.__owner def set_name(self,newName): self.__name= newName return def get_name(self): return self.__name def noise(self): print('errr') return def __hiddenmethod(self): print("hard to find") def main(): dog = Animal() dog.set_owner('Sue') print dog.get_owner() dog.noise() if __name__ =='__main__':main()
Your configurations are correct. If you are using the https://github.com/pythonforfacebook/facebook-sdk You will need to make some changes to the example code. The example.py file defines "get" and "post" methods under the HomeHandler class. The "get" will not work when the page is running as a Canvas App inside Facebook.com, though it will work when the page is directly called by a browser. Facebook loads the Canvas App into its iframe using a POST request containing the signed_request argument as detailed here:https://developers.facebook.com/docs/howtos/login/signed-request/ The first step you can take to fix the example.py file is as follows. This will at least get code showing up inside Facebook: Comment out the original "post" method: #def post(self): #url = self.request.get('url') #file = urllib2.urlopen(url) #graph = facebook.GraphAPI(self.current_user['access_token']) #response = graph.put_photo(file, "Test Image") #photo_url = ("http://www.facebook.com/" #"photo.php?fbid={0}".format(response['id'])) #self.redirect(str(photo_url)) Duplicate the "get" method as the "post" method, now both get and post are: def post(self): template = jinja_environment.get_template('example.html') self.response.out.write(template.render(dict( facebook_app_id=FACEBOOK_APP_ID, current_user=self.current_user ))) Once that is done, you can test within Facebook. "example.html" should display in the iframe, however, by default, "example.html" asks for an image URL to upload. That will no longer work since the original "post" method is commented out. To fix the functionality, you'll need to create if/then statements in the def post(self): method to handle requests. For instance, you may want to re-integrate the original "post" method by checking for the 'url' argument - using self.request.get('url') - if it is there, then you know you are receiving an image URL and should branch to the original "post" code
djara Re : Récupération de windows après insttallation de ubuntu 12.10 64bit Merci. Je te tiens informer dans quelques minutes du résultats. Merci Hors ligne djara Re : Récupération de windows après insttallation de ubuntu 12.10 64bit Voila ce que j'ai obtenu en reprenant avec la version officiel le lien : http://paste.ubuntu.com/1429853/ ADDITIONAL INFORMATION : =================== log of boot-repair 2012-12-13__15h09 =================== boot-repair version : 3.195~ppa28~quantal boot-sav version : 3.195~ppa28~quantal glade2script version : 3.2.2~ppa45~quantal boot-sav-extra version : 3.195~ppa28~quantal boot-repair is executed in live-session (Ubuntu 12.10, quantal, Ubuntu, x86_64) CPU op-mode(s): 32-bit, 64-bit BOOT_IMAGE=/casper/vmlinuz.efi.signed file=/cdrom/preseed/ubuntu.seed boot=casper quiet splash -- Hors ligne djara Re : Récupération de windows après insttallation de ubuntu 12.10 64bit Dans ce lien il y a ce message aussi dont je fais une copie : ======================== Unknown MBRs/Boot Sectors/etc: ======================== Unknown BootLoader on sda2 00000000 eb 58 90 4d 53 44 4f 53 35 2e 30 00 02 08 fe 1b |.X.MSDOS5.0.....| 00000010 02 00 00 00 00 f8 00 00 3f 00 ff 00 00 88 0c 00 |........?.......| 00000020 00 20 08 00 01 02 00 00 00 00 00 00 02 00 00 00 |. ..............| 00000030 01 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| 00000040 80 00 29 17 0c f1 78 4e 4f 20 4e 41 4d 45 20 20 |..)...xNO NAME | 00000050 20 20 46 41 54 33 32 20 20 20 33 c9 8e d1 bc f4 | FAT32 3.....| 00000060 7b 8e c1 8e d9 bd 00 7c 88 56 40 88 4e 02 8a 56 |{......|.V@.N..V| 00000070 40 b4 41 bb aa 55 cd 13 72 10 81 fb 55 aa 75 0a |@.A..U..r...U.u.| 00000080 f6 c1 01 74 05 fe 46 02 eb 2d 8a 56 40 b4 08 cd |...t..F..-. Hors ligne malbo Re : Récupération de windows après insttallation de ubuntu 12.10 64bit Il faut démarrer ton PC sur le disque dur en mode UEFI et dans le menu Grub au démarrage (ça ressemble à cette vue), si tu choisis l'entrée "Windows UEFI loader" de ce menu, qu'est-ce que qui se passe ? et si tu choisis l'entrée "Windows Boot UEFI bootx64.efi.bkp", qu'est-ce qui se passe ? Dernière modification par malbo (Le 13/12/2012, à 17:42) MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04 Hors ligne djara Re : Récupération de windows après insttallation de ubuntu 12.10 64bit OK. Je l'essai. Merci Hors ligne Babdu89 Re : Récupération de windows après insttallation de ubuntu 12.10 64bit Bonsoir ... Vu dans le dernier rapport boot info ... secteur de démarrage du hdd => No boot loader is installed in the MBR of /dev/sda. Normal çà? ... vu dans le boot loader de Seven ,partition /sda4 sda4: __________________________________________________________________________ File system: ntfs Boot sector type: Windows Vista/7: NTFS Boot sector info: No errors found in the Boot Parameter Block. Operating System: Boot files: /bootmgr /Boot/BCD /Windows/System32/winload.exe /wubildr/ubuntu/winboot/wubildr/wubildr.mbr /ubuntu/winboot/wubildr.mbr Serait ce des restes d'une installation via Wubi? ... Il n'y a pas de partition virtuelle Ubuntu du à l'installation via Wubi ... Et çà en fin de rapport A broken Wubi has been detected. Please fix it this way: https://wiki.ubuntu.com/WubiGuide#Cannot_boot_into_Ubuntu Exemple d'une install ,via Wubi ,chez moi ,toujours opérationnelle ... sdb6: __________________________________________________________________________ File system: ntfs Boot sector type: Windows Vista/7: NTFS Boot sector info: No errors found in the Boot Parameter Block. Operating System: Boot files: /ubuntu/winboot/wubildr /ubuntu/winboot/wubildr.mbr /ubuntu/disks/root.disk /ubuntu/disks/swap.disk sdb6/Wubi: _____________________________________________________________________ File system: ext4 Boot sector type: - Boot sector info: Operating System: Ubuntu 11.04 Boot files: /boot/grub/grub.cfg /etc/fstab sdb7: __________________________________________________________________________ @ malbo ... Est ce gênant pour le démarrage de Seven , à ton avis? ... @+. Babdu89 . Dernière modification par Babdu89 (Le 13/12/2012, à 18:16) J'ai découvert Ubuntu avec la 07.10.... Et alors?!... Depuis je regarde de temps en temps si Windows marche toujours.... Hors ligne djara Re : Récupération de windows après insttallation de ubuntu 12.10 64bit Qaund je clique sur Windows UEFI loader il envoie un message en disant à la fin cannot load image File path : ACP(a0341do,0) .............................................../File(bootmgfw.efi.bkp) La même chose pour Windows Boot UEFI bootx64.efi.bkp Mais cette fois ci c'est le fichier bootx64.efi.bkp qui est indexé. En regardant le contenu du lien je voie les éléments suivant : Windows UEFI loader et Windows Boot UEFI bootx64.efi.bkp dans le fichier grub insérer en image dans le lien. J'ai fais une capture d'écran de cette zône que je n'arrive pas à envoyer pour le moement Hors ligne djara Re : Récupération de windows après insttallation de ubuntu 12.10 64bit Voici l'image. Je ne 'sest pas si ça va s'afficher [img]/tmp/guest-FjBbG7/Bureau/Capture du 2012-12-13 17:12:45.png[/img] Hors ligne djara Re : Récupération de windows après insttallation de ubuntu 12.10 64bit Enfin voici une copie de la partie concernée menuentry "Windows UEFI loader" { search --fs-uuid --no-floppy --set=root 78F1-0C17 chainloader (${root})/EFI/Microsoft/Boot/bootmgfw.efi.bkp } menuentry "Windows Boot UEFI bootx64.efi.bkp" { search --fs-uuid --no-floppy --set=root 78F1-0C17 chainloader (${root})/EFI/Boot/bootx64.efi.bkp } Hors ligne djara Re : Récupération de windows après insttallation de ubuntu 12.10 64bit Je désepère... Hors ligne malbo Re : Récupération de windows après insttallation de ubuntu 12.10 64bit Je ne sais pas pourquoi ça ne fonctionne pas. Est-ce que tu souhaites attendre que le concepteur de Boot-Repair (YannUbuntu) puisse intervenir pour t'aider ici ou bien tu souhaites retrouver en priorité et urgemment l'accès à Win8 (mais provisoirement, tu n'auras plus l'accès à Ubuntu). Dis-moi ce que tu souhaites parce que si tu souhaites retrouver l'accès à Win8, je peux te proposer quelque chose (mais tu n'auras plus l'accès à Ubuntu, hein?). MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04 Hors ligne djara Re : Récupération de windows après insttallation de ubuntu 12.10 64bit Je veux d'abord avoir accès à windows8. Après je peux reinstaller ubuntu car je n'est pas données sur ubuntu. Hors ligne djara Re : Récupération de windows après insttallation de ubuntu 12.10 64bit Tu redonne l'espoir Merci Hors ligne malbo Re : Récupération de windows après insttallation de ubuntu 12.10 64bit Le principe de fonctionnement de Boot-Repair est expliqué là : http://ubuntuforums.org/showpost.php?p= … tcount=637 La partie utile pour comprendre ce qui t'intéresse présentement c'est ça : 5) if either the Microsoft/Boot/bootmgfw.efi or Boot/bootx64.efi is present and is original (there is no Microsoft/Boot/bootmgfw.efi.grb or Boot/bootx64.efi.grb file), the "Backup and rename EFI file" option will rename the file to *.efi.bkp , and copy the grub efi file instead. Eg, if there is Microsoft/Boot/bootmgfw.efi but no Microsoft/Boot/bootmgfw.efi.grb , it will rename Microsoft/Boot/bootmgfw.efi to Microsoft/Boot/bootmgfw.efi.bkp , then copy the grub efi file to Microsoft/Boot/bootmgfw.efi. Tu n'es pas obligé de comprendre ce qui est expliqué dans le lien parce que je vais te dire ce qu'il faut faire mais c'est seulement si tu veux savoir pourquoi je te propose ça. 1) Il faut opérer depuis une session live de Ubuntu 2) ouvrir la partition sda2 et renommer le fichier /EFI/Boot/bootx64.efi en /EFI/Boot/bootx64.efi_sauv et renommer le fichier /EFI/Boot/bootx64.efi.bkp en /EFI/Boot/bootx64.efi (tu as juste à supprimer l'extension .bkp à la fin). Quand tu auras fait cela, tu auras rétabli le fichier d'origine de Windows 8 qui se trouvait là avant que Boot-Repair fasse son œuvre. 3) toujours dans la partition sda2, renommer le fichier /EFI/Microsoft/Boot/bootmgfw.efi en /EFI/Microsoft/Boot/bootmgfw.efi_sauv et renommer le fichier /EFI/Microsoft/Boot/bootmgfw.efi.bkp en /EFI/Microsoft/Boot/bootmgfw.efi (même principe que ci-dessus, tu as juste à virer l'extension .bkp à la fin). Là aussi, tu auras remis en service le fichier d'origine Win8 qui se trouvait là. Au redémarrage, ça devrait démarrer direct sous Windows 8. Si ça ne le faisait pas, je te prie de poster un nouveau Boot-Info pour que je tente de comprendre ce qui se passe. Edit : en fouillant dans le forum, je pense que l'item 2) que je propose n'est pas indispensable et que c'est l'item 3) qui est nécessaire et suffisant (comme moi). Cela dit, tant que tu as les mains dans le cambouis, je te suggère de faire tout ce que j'ai proposé, item 2 compris Dernière modification par malbo (Le 13/12/2012, à 20:22) MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04 Hors ligne djara Re : Récupération de windows après insttallation de ubuntu 12.10 64bit Merci. Comment monter sda2? Hors ligne malbo Re : Récupération de windows après insttallation de ubuntu 12.10 64bit tu peux le faire en tapant "disk" dans la recherche et l'application disks (ou disques) dois t'être proposée. Elle te permettra de faire le montage de sda2 (tu vas trouver en cherchant quelques secondes). Pour savoir si sda2 est montée, tu ouvres le moniteur système (tape "mon" dans la recherche et l’application te sera proposée), dans l'onglet "system", tu trouveras /dev/sda2 avec son point de montage. Ensuite, il faut ouvrir Nautilus (tu tapes "nau" dans le champ de recherche et la petite maison sera proposée : c'est Nautilus) et tu navigues jusqu'au point de montage de sda2 que tu auras bien noté dans le moniteur système et tu fais le boulot. Dernière modification par malbo (Le 13/12/2012, à 20:34) MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04 Hors ligne djara Re : Récupération de windows après insttallation de ubuntu 12.10 64bit Par le présent message je voudrais te dire merci. J'arrive à redémarrer sur windows8. Une fois encore merci pour ta disponibilité. Maintenant, je voudrais savoir pour la suite comment faire. Car j'aime travailler avec ubuntu et je ne voudrais pas prendre le risque de recommencer l'installation seule sans guide formelle. Hors ligne malbo Re : Récupération de windows après insttallation de ubuntu 12.10 64bit Moi, je t'ai sorti de l'eau mais j'arrête ma contribution pour l'instant. Je vais me poser et tâcher de retrouver la confiance en Boot-Repair parce que je n'ai toujours pas compris pourquoi tu n'avais pas réussi à réparer ton dual-boot. MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04 Hors ligne Babdu89 Re : Récupération de windows après insttallation de ubuntu 12.10 64bit Bonsoir... @ malbo ... j'avais posé une question post#31 ,j'attendais une réponse de ta part, peux tu me dire ce que tu en penses? ...Merci @+. Babdu89 . J'ai découvert Ubuntu avec la 07.10.... Et alors?!... Depuis je regarde de temps en temps si Windows marche toujours.... Hors ligne malbo Re : Récupération de windows après insttallation de ubuntu 12.10 64bit Babdu89, Excuse-moi d'avoir oublié de te répondre. Wubi ne peut pas fonctionner dans un Windows installé en mode EFI. Je pense que djara a dû faire l'essai et que ça n'a jamais pu marcher : je n'en ai pas fait mention plus haut parce que ça ne peut pas gêner à ma connaissance. Mais YannUbuntu pourra peut-être confirmer. MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04 Hors ligne djara Re : Récupération de windows après insttallation de ubuntu 12.10 64bit Babdu89 Au départ pour essayer j'avais voulu donc émuler mon ubuntu sous windows. Mais je n'est pas compris ce qui se passait et j'ai abandonné Hors ligne malbo Re : Récupération de windows après insttallation de ubuntu 12.10 64bit djara, En attendant de trouver une solution plus satisfaisante pour toi, je te propose une solution provisoire pour démarrer ton Ubuntu installé. Je m'appuie sur le post suivant qui est relatif à un PC HP pour te décrire la manipulation : http://www.eightforums.com/installation … post157771 Au démarrage du PC, tu appuies immédiatement sur la touche Echap et tu dois voir apparaître ce menu : f1 system informationf2 system diagnosticsf9 boot device optionsf10 bios setupf11 system recovery Pour lancer "Boot Device Options", tu appuies sur la touche de fonction F9 Là, tu peux voir apparaître plusieurs lignes de choix. Si tu vois une ligne appelée "ubuntu" (ou UEFI ubuntu ou quelque chose avec "ubuntu" dans la désignation), tu peux la sélectionner et valider : ça devrait pouvoir démarrer Ubuntu et tout ce que je détaille dans la suite de ce post est inutile pour toi. Si tu n'as pas ce choix "ubuntu", tu peux sélectionner la ligne : Boot From EFI File et tu pourras naviguer de proche en proche jusqu'au fichier /EFI/ubuntu/shimx64.efi de la façon que je vais tenter de détailler. Je ne sais pas comment ça va se présenter concrètement à l'écran mais souvent tu vois une proposition qui commence par : VOLUME XXX il y a plein de caractères à la place de XXX, c'est illisible mais ça désigne ton disque dur (plus précisément, la 2ème partition de ton disque dur qui est la partition EFI). Tu sélectionnes et ensuite, tu vois : EFI tu sélectionnes et ensuite tu vois tout le contenu de EFI c'est à dire que d'après ce que je vois de ton Boot-Info, tu devrais voir : BootubuntuHPMicrosoft Tu sélectionnes ubuntu et tu devrais voir : grubx64.efishimx64.efi Tu sélectionnes "shimx64.efi" et tu valides. Normalement, tu dois démarrer sur Ubuntu (ça serait bien que tu essaies le choix "grubx64.efi" lors d'un essai suivant pour vérifier s'il conduit au même résultat ou bien s'il ne fonctionne pas) . Edit : pour ton info : le fichier shimx64.efi est le fichier qui permet de démarrer avec la fonctionnalité "Secure Boot" activée dans le système UEFI de ta machine. Bien qu'il porte un nom différent, il est identique au fichier qui te permettait de démarrer sur Ubuntu auparavant. Il n'y a donc aucune raison que ça ne fonctionne pas puisque ça a déjà marché. Dernière modification par malbo (Le 14/12/2012, à 09:01) MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04 Hors ligne djara Re : Récupération de windows après insttallation de ubuntu 12.10 64bit Merci malbo. La première option marche directement. Hors ligne malbo Re : Récupération de windows après insttallation de ubuntu 12.10 64bit Bonne nouvelle. Le choix proposé c'est "UEFI:ubuntu" ou c'est proposé sous une autre dénomination ? Si cet ordi doit être démarré prioritairement sous Windows 8, c'est le cas si c'est un ordi à usage familial et que tu es le seul à te connecter sous Ubuntu et que tous les autres membres de la famille se connectent sous Windows 8, tu peux rester comme ça. Si par contre tu es le seul utilisateur de cet ordi et que tu l'utilises principalement sous Ubuntu, il conviendrait d'agir dans les réglages de ton "Bios" pour modifier le démarrage par défaut afin qu'il se fasse sur ubuntu et pas sur Windows. En cherchant un peu, tu devrais trouver comment faire. Dernière modification par malbo (Le 14/12/2012, à 17:26) MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04 Hors ligne djara Re : Récupération de windows après insttallation de ubuntu 12.10 64bit Le choix proposé est Ubuntu avec des numéros et lettres entre parenthèses. Il y a exactement deux lignes concernant ubuntu ayant les mêmes références. Je travaille normalement sous ubuntu et je presque la seule personne à utiliser ce poste. Qu'est-ce qui m'as amené malheureusement à travailler sous Windows. En fait je développe une application java qui doit détecter une caméra et j'effectue des captures à partir de l'interface graphique conçu. Malheureusement la détection de ma caméra sous linux(ubuntu) à partir d'un code java pose problème. Je suis actuellement triste en travaillant sous windows à cause de ce problème. Hors ligne
Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! Sur amazon, j'ai trouvé ce livre "Python - Les Fondamentaux du langage - La Programmation pour les scientifiques. de Matthieu Brucher" Très bon livre, dans la mesure où tu sais déjà programmer et que tu es intéressé par la partie scientifique, il te conviendra parfaitement. Après, je ne suis pas un grand spécialiste de Python, mais il me semble faire une bonne présentation du langage. Certains trouvent que le niveau y est un peu soutenu. Il semble avoir plutôt bonne presse chez les habitués de Python. Quelques réponses pèle-mêle : Ce n'est pas tant que je suis habitué à des matrices creuses (même si j'en utilise pas mal), mais à faire des benchmarks sur des machines dédiés au calcul et pour ne pas être trop perturbé par les à-côtés, il vaut mieux faire des calculs un peu long. Oui, j'ai déjà inversé des matrices 100000x100000 -- oui, c'est long. Si j'ai ajouté un affichage, c'est parce que je suis habitué à utiliser des options de compilations agressives et, sur des benchmarks, le risque est que le code ne fasse plus rien. Cela dit, il vaut mieux, en effet, n'afficher qu'une seule case de la matrice. Par contre, je pense que Python remplace avantageusement Matlab : on évite d'être dépendant d'un fournisseur, Python est capable de faire tout ce que Matlab peut faire, mais en étant plus généraliste. D'autant qu'il s'interface très bien avec Fortran, C et C++ (utiliser Boost.Python). Par contre, on peut être amené dans certain cas à devoir coder des éléments pour lesquelles il existe déjà une bibliothèque sous Matlab. Cela dit, je suis désolé, mais je ne connais pas assez bien Python pour pouvoir faire une présentation exhaustive de ses bibliothèques dédiés aux scientifiques. À bientôt. Le Farfadet Spatial L'antre du farfadet : http://le.farfadet.spatial.free.fr/ Textes, musiques et peintures Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage J'ai commandé le livre. Après lecture, je posterai un avis (je ne sais pas quel est le meilleur post pour cela). J'envisagerai alors plus sérieusement la possibilité de coder un projet plus complexe en python, pour comparer. Pour ce qui est de notre benchmark, la différence entre python et le fortran compilé avec les produits INTEL ne semble pas énorme (sur ce cas simple, il est vrai). Je vais même voir s'il n'y a pas moyen de recompiler numpy avec MKL. Je vais aussi essayer de comprendre pourquoi gfortran donne de si mauvais résultats. Et... je vais aussi un peu travailler ! Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! Je vais aussi essayer de comprendre pourquoi gfortran donne de si mauvais résultats. Je préfère G95 à GFortran. À bientôt. Le Farfadet Spatial L'antre du farfadet : http://le.farfadet.spatial.free.fr/ Textes, musiques et peintures Hors ligne tshirtman Re : Petit guide pour aider au choix d'un langage Après lecture, je posterai un avis (je ne sais pas quel est le meilleur post pour cela) * le HS ayant peut être assez duré (mes excuses, ce n'était pas l'intention), le mieux sera sans doute d'ouvrir un nouveau post (sauf si Le Farfadet Spacial pense le contraire, c'est son sujet). Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! le HS ayant peut être assez duré (mes excuses, ce n'était pas l'intention), le mieux sera sans doute d'ouvrir un nouveau post (sauf si Le Farfadet Spacial pense le contraire, c'est son sujet). Il n'est sans doute pas nécessaire d'ouvrir un sujet juste pour la critique d'un seul livre et certains scientifiques peuvent venir ici alors qu'ils cherchent un langage adapté à leurs besoins : alors, ce livre pourrait les intéresser, donc il reste sans doute pertinent de donner son avis ici. À bientôt. Le Farfadet Spatial L'antre du farfadet : http://le.farfadet.spatial.free.fr/ Textes, musiques et peintures Hors ligne mydjey Re : Petit guide pour aider au choix d'un langage Je reviens dans ce topic demander quelques infos. J'ai commencé la prog il y'a quelques temps avec le C. Même si le bouquin que j'utilise est très didactique.... Comment dire ? C'est chaud le C et un peu décourageant. Début de semaine je suis tombé sur un site qui explique les bases du python. Waoou ! En 2 heures on va dire, j'ai fait ce que j'ai mis plus d'une semaine à apprendre en C. Ma question :Quelle est pour vous le bouquin le plus sympa pour débuter avec python ? Sachant que pour le moment je dispose de ses 3 bouquins en pdf : * Le Swinnen * A byte of Python * Plongez au cœur de python (dive into python) Bien que très connu, j'ai lu que vous trouviez le Swinnen bof, bof. Des 3 lequel vous parait le mieux ? J'ai aussi vu que Farfadet Spatial propose : Python : Petit guide à l'usage du développeur agile J'ai regardé un peu les commentaires sur Amazon. Et je me demande si il est bien écris pour le débutant en programmation ce bouquin ? Il explique les bases de python ? Les boucles, les conditions, donne des explications sur la programmation OO, comment mettre en place son code dans Linux etc... ? Merci pour vos avis. Mon site : http://mydjey.eu/ Hors ligne tshirtman Re : Petit guide pour aider au choix d'un langage /me a "python - syntaxe, conception et optimisation" de tarek ziadé, qui prends vraiment par la main, depuis les bases jusqu'a un niveau intermédiaire (mais tout à fait solide), mais bon, c'est un bouquin irl, pas un pdf. (mais bon, ça à l'aire de bien correspondre à ta demande). pour le développement agile, je suppose que le bouquin se focalise plus sur des pratiques de développement en général encouragé dans la communauté python, l'écriture de test unitairs, l'intégration continue, ce genre de choses… enfin, je pense que les boucle et toute la base du langage, le tuto python en ligne (en anglais mais bon) est tout à fait adapté. edit: correction du titre. Dernière modification par tshirtman (Le 17/03/2010, à 00:47) Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage Attention, il y a une erreur dans notre petit benchmark. Le code python ci-dessus produit des array, et l'opérateur * sur des array réalise la multiplication élément par élément, et non la multiplication matricielle. Pour obtenir la multiplication matricielle, il faut utiliser le type matrix from numpy import * for i in range(10): A = matrix(random.rand(1000,1000)) B = matrix(random.rand(1000,1000)) C = A * B ce qui donne time python test.pyreal 0m17.783suser 0m17.561ssys 0m0.200s Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! Attention, il y a une erreur dans notre petit benchmark. Comme quoi, il fallait se méfier, mais je vous avais prévenus : je n'avais pas testé. ce qui donne time python test.py real 0m17.783s user 0m17.561s sys 0m0.200s Hé bien, je dois dire que je ne m'y attendais pas du tout, je n'étais pas resté là-dessus. Peux-tu faire ce test plusieurs fois (par exemple trois fois), faire la moyenne, puis donner la valeur. Cela ne va pas être trop éloigné, mais cela permettra d'avoir un chiffre assez indépendant du système. Ce serait bien de comparer avec la même chose en Fortran sur le même système. Après, il faudra voir avec une application plus réaliste, comme un petit code d'éléments finis, mais je suis prêt à réviser mon point de vue s'il s'avère que la concurrence est possible. À bientôt. Le Farfadet Spatial L'antre du farfadet : http://le.farfadet.spatial.free.fr/ Textes, musiques et peintures Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage J'ai réalisé le test 4 fois en python et 4 fois en fortran Résultats Fortran REAL : 0.50875USER : 0.40900SYS : 0.01900 Résultats Python REAL : 17.959USER : 17.431SYS : 0.1680 Il y a quand même une nette différence. J'essaye de compiler numpy avec les librairies MKL mais je n'y suis pas encore arrivé. Si tu en as le temps, peux-tu écrire le même code en C++ pour comparer ? J'ai reçu le livre mentionné plus haut hier. Je l'ai déjà pas mal parcouru et pour l'instant mon impression est plutôt négative. Je formulerai un avis plus honnête après une lecture complète. Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage Attention, il semble qu'il y aie encore une erreur, mais cette fois dans mon code FORTRAN, il semble qu'il ne calcule pas du tout le produit, ce qui explique sa grande rapidité ! Si j'utilise la fonction intrinsèque matmul plutot que blas, fortran met 13 secondes. Si je compile numpy avec ATLAS, celui met 7 secondes... Bref, rien de concluant pour les bench. Tout dépend des librairies utilisées. En effet pour l'instant c'est en python que je vais le plus vite pour faire mon produit ! j'ai commencé un code FEM en python, je vous tiens au courant. Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! Si tu en as le temps, peux-tu écrire le même code en C++ pour comparer ? Ma soutenance a lieu lundi, il faudra attendre un peu. N'hésitez pas à me relancer en fin de semaine si je n'ai rien fourni. Bref, rien de concluant pour les bench. Ce n'est guère surprenant. j'ai commencé un code FEM en python, je vous tiens au courant. Oui, c'est plutôt un tel code qui permet de juger. Pour là où j'en suis resté, le facteur de ralentissement de Python le rend impropre pour faire plus qu'un modèle jouet -- c'est-à-dire, pour ceux qui pensent qu'il s'agit d'un terme péjoratif, d'un modèle exploratoire pour étudier certains points théoriques. À bientôt. Le Farfadet Spatial L'antre du farfadet : http://le.farfadet.spatial.free.fr/ Textes, musiques et peintures Hors ligne tshirtman Re : Petit guide pour aider au choix d'un langage c'est-à-dire, pour ceux qui pensent qu'il s'agit d'un terme péjoratif, d'un modèle exploratoire pour étudier certains points théoriques. la simplicité du language et sa proximité avec les expression mathématique a en effet cet avantage, permettre de comparer simplement plusieurs algos en termes d'efficacité, quitte à réimplémenter dans un language plus rapide si nécessaire, l'algo qui aura été trouvé le plus rapide. Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! la simplicité du language et sa proximité avec les expression mathématique a en effet cet avantage, permettre de comparer simplement plusieurs algos en termes d'efficacité, quitte à réimplémenter dans un language plus rapide si nécessaire, l'algo qui aura été trouvé le plus rapide. C'est-à-dire que pour les algorithmes, il y a l'analyse de complexité en temps et en espace, c'est beaucoup plus significatif qu'une implémentation, qui peut être bogué, entre autre. Non, un modèle-jouet, c'est surtout utilisé pour étudier un phénomène particulier en entrant autant que possible dans un cas idéal, c'est-à-dire en l'isolant de tout autre phénomène. Il existe des choses basées sur Python pour réaliser cela facilement et efficacement, mais je ne retrouve plus le nom. À bientôt. Le Farfadet Spatial Édition : je suis en train de me dire qu'on pourrait penser qu'il y a acharnement, je précise donc que je n'ai aucune dent contre Tshirtman -- ni contre Python, d'ailleurs. Dernière modification par Le Farfadet Spatial (Le 21/03/2010, à 01:15) L'antre du farfadet : http://le.farfadet.spatial.free.fr/ Textes, musiques et peintures Hors ligne tshirtman Re : Petit guide pour aider au choix d'un langage je le prends pas comme de l'acharnement, et je pense qu'on pourrait tout à fait penser la même chose de mes interventions ^^, tu as des choses intéressantes à dire sur l'intérêt des langages pour diverses utilisations, on peut être d'accord ou pas, mais il n'y a pas de mal à les dire. en effet, mon interventions sur les algos était réductrice par rapport au concept de modele objet. Pour ce dont tu parles sans retrouver le nom, tu penses peut être au mocking pour simuler l'environnement autour du cas étudié? bien que ce ne soit pas spécifique au python je pense. Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage Bonne chance pour ta soutenance Farfardet ! Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! Pour ce dont tu parles sans retrouver le nom, tu penses peut être au mocking pour simuler l'environnement autour du cas étudié? bien que ce ne soit pas spécifique au python je pense. Non, ce n'est pas ça. C'est quelque chose de purement éléments-finis. J'essayerais de chercher le nom. En gros, tu écris les équations dirigeant ton modèle et les conditions aux limites sous une forme très proche de la façon naturelle d'écrire des équations, tu donnes ton maillage et tout le reste est automatique. Pour ceux qui connaissent, un équivalent de FreeFEM, mais en Python. Bonne chance pour ta soutenance Farfardet ! Merci. À bientôt. Le Farfadet Spatial L'antre du farfadet : http://le.farfadet.spatial.free.fr/ Textes, musiques et peintures Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage l'interface de getfem++ pour python peut être ? Hors ligne Le Farfadet Spatial Re : Petit guide pour aider au choix d'un langage Salut à tous ! l'interface de getfem++ pour python peut être ? Non plus... J'essayerais de retrouver. À bientôt. Le Farfadet Spatial L'antre du farfadet : http://le.farfadet.spatial.free.fr/ Textes, musiques et peintures Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage Bonjour, J'ai avancé dans l'écriture d'un code FEM en python, et pour l'instant un gros problème apparaît. Les fonctions optimisées de numpy sont très rapides, elles ne posent pas de problème. Par contre, les performances de python se font sentir pour tout ce qui est autour ! Principalement, la vitesse d'accès aux éléments d'un dictionnaire ou la vitesse d'itération sur des listes rend l'entreprise inenvisageable pour des problèmes de taille raisonnable. Par exemple, pour un maillage de 10 000 tetrahèdres, il faut presque une heure juste pour construire la matrice ! Je vais écrire un exemple minimal pour que tout cela soit plus concret. Hors ligne tshirtman Re : Petit guide pour aider au choix d'un langage Si tu as des problèmes de ce coté là, l'utilisation de psyco peut aider beaucoup. import psyco psyco.full() Au début de ton code, rien à faire de plus. Malheureusement, ça ne marche que sur x86 (ça réalise de la compilation just in time, le projet pypy promet de résoudre ça et d'amener de telles performances sur toutes les plateformes.) Dernière modification par tshirtman (Le 26/03/2010, à 12:59) Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage Malheureusement, cela n'a pas l'air ce changer quoi que soit chez moi. Je vais essayer plusieurs choses 1) Pour l'instant j'utilise des dictionnaires qui prennent des objets comme clés. J'ai lu quelque part que les dictionnaires allaient plus vite en prenant des caractères. Je vais essayer de modifier cela 2) Les itérations sur des listes d'objet semblent extrêmement lentes. Est-ce qu'il n'y a pas une astuce pour booster cela, en définissant mieux les __hash__ ou quelque chose du genre ? 3) Je vais installer python 3 pour voir ! Pour en revenir au sujet du post, si je ne résous pas ces problèmes, je ne conseillerai pas Python pour du calcul scientifique de "moyenne performance" Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage Pas de problème, mais c'est un peu long et complexe Voici les classes définissant les objets géométriques class node: """ node class """ def __init__(self,num,x,y,z): self._globNum = num self._x = x self._y = y self._z = z def getNum(self): return self._globNum def getXYZ(self): return (self._x,self._y,self._z) def numberOfNodes(self): return 1 def getInterpolation(self,U,u,v,w): return u(1) ######################################################################## class line(node): """ line class """ def __init__(self,num,tag,partition,node1,node2): self._globNum = num self._tag = tag self._partition = partition self._node1 = node1 self._node2 = node2 def getNum(self): return self._globNum def getXYZ(self): return (self._x,self._y,self._z) def getTag(self): return self._tag def getPartition(self): return self._partition def getNodes(self): return [self._node1,self._node2] def numberOfNodes(self): return 2 def getShapesFunctions(self,u,v,w): shf = [ 0.5 * (1-u), 0.5 * (1+u) ] return shf def getGradShapesFunctions(self,u,v,w): gx = [-0.5 , 0.5] gy = [ 0.0 , 0.0] gz = [ 0.0 , 0.0] gdsf = [ gx , gy , gz] return gdsf def getInterpolation(self,U,u,v,w): shf = self.getShapesFunctions(u,v,w) value = shf(0) * U(0) + shf(1) * U(1) return value ######################################################################## class triangle(node): """ triangle class """ def __init__(self,num,tag,partition,node1,node2,node3): self._globNum = num self._tag = tag self._partition = partition self._node1 = node1 self._node2 = node2 self._node3 = node3 def getNum(self): return self._globNum def getXYZ(self): return (self._x,self._y,self._z) def getTag(self): return self._tag def getPartition(self): return self._partition def getNodes(self): return [self._node1,self._node2,self._node3] def numberOfNodes(self): return 3 def getShapesFunctions(self,u,v,w): shf = [ (1 - u - v) , u , v ] return shf def getGradShapesFunctions(self,u,v,w): gx = [ -1.0 , 1.0 , 0.0] gy = [ -1.0 , 0.0 , 1.0] gz = [ 0.0 , 0.0 , 0.0] gdsf = [ gx , gy , gz] return gdsf def getInterpolation(self,U,u,v,w): shf = self.getShapesFunctions(u,v,w) value = shf(0) * U(0) + shf(1) * U(1) + shf(2) * U(2) return value ######################################################################### class tetrahedron(node): """ tetrahedron class """ def __init__(self,num,tag,partition,node1,node2,node3,node4): self._globNum = num self._tag = tag self._partition = partition self._node1 = node1 self._node2 = node2 self._node3 = node3 self._node4 = node4 def getNum(self): return self._globNum def getXYZ(self): return (self._x,self._y,self._z) def getTag(self): return self._tag def getPartition(self): return self._partition def getNodes(self): return [self._node1,self._node2,self._node3,self._node4] def numberOfNodes(self): return 4 def getShapesFunctions(self,u,v,w): shf = [ (1 - u - v - w) , u , v , w] return shf def getGradShapesFunctions(self,u,v,w): gx = [ -1.0 , 1.0 , 0.0 , 0.0 ] gy = [ -1.0 , 0.0 , 1.0 , 0.0 ] gz = [ -1.0 , 0.0 , 0.0 , 1.0 ] gdsf = [ gx , gy , gz] return gdsf def getInterpolation(self,U,u,v,w): shf = self.getShapesFunctions(u,v,w) value = shf(0) * U(0) + shf(1) * U(1) + shf(2) * U(2) + shf(3) * U(3) return value ######################################################################################## La classe définissant le maillage from geom import * class mesh : """ mesh class """ def __init__(self,file_name): """ constructor of the mesh class, from a gmsh file """ self._NODES = [] self._LINES = [] self._TRIANGLES = [] self._TETRAHEDRONS = [] #open the file f = open(file_name,"r") # nodes lecture str = "a" while str != "$Nodes": str = f.readline().strip() self._numNodes = int(f.readline()) for i in xrange(self._numNodes): str = f.readline().strip().split() n = node(int(str[0]) , float(str[1]) , float(str[2]) , float(str[3])) self._NODES.append(n) str = f.readline() # elements lecture str = f.readline() self._numElements = int(f.readline()) for i in xrange(self._numElements): str = f.readline().strip().split() if str[1] == "1": num = int(str[0]) tag = int(str[3]) partition = int(str[5]) numNode1 = int(str[6]) - 1 numNode2 = int(str[7]) - 1 node1 = self._NODES[numNode1] node2 = self._NODES[numNode2] n = line(num,tag,partition,node1,node2) self._LINES.append(n) elif str[1] == "2": num = int(str[0]) tag = int(str[3]) partition = int(str[5]) numNode1 = int(str[6]) - 1 numNode2 = int(str[7]) - 1 numNode3 = int(str[8]) - 1 node1 = self._NODES[numNode1] node2 = self._NODES[numNode2] node3 = self._NODES[numNode3] n = triangle(num,tag,partition,node1,node2,node3) self._TRIANGLES.append(n) elif str[1] == "4": num = int(str[0]) tag = int(str[3]) partition = int(str[5]) numNode1 = int(str[6]) - 1 numNode2 = int(str[7]) - 1 numNode3 = int(str[8]) - 1 numNode4 = int(str[9]) - 1 node1 = self._NODES[numNode1] node2 = self._NODES[numNode2] node3 = self._NODES[numNode3] node4 = self._NODES[numNode4] n = tetrahedron(num,tag,partition,node1,node2,node3,node4) self._TETRAHEDRONS.append(n) else: if str[1] != "15": print "There are non implemented type of element in the mesh" print "-Mesh reading" print "Mesh file name :", file_name print "Number of nodes :", self._numNodes print "Number of lines :", len(self._LINES) print "Number of triangles :", len(self._TRIANGLES) print "Number of tetrahedrons :", len(self._TETRAHEDRONS) print "-End of mesh reading " # close the file f.close() def getNumNodes(self): return self._numNodes def getElementsByTag(self,dim,tag): """ function returning a list of elements of dimension 'dim' and tag 'tag' """ elements = [] if dim == 1: for line in self._LINES: if line.getTag() == tag: elements.append(line) elif dim == 2: for triangle in self._TRIANGLES: if triangle.getTag() == tag: elements.append(triangle) elif dim == 3: for tetrahedron in self._TETRAHEDRONS: if tetrahedron.getTag() == tag: elements.append(tetrahedron) return elements def getVerticesByTag(self,dim,tag): """ function returning a list a elements if dimension 'dim' and tag 'tag' """ elements = self.getElementsByTag(dim,tag) vertices = set([]) for elem in elements : a = elem.getNodes() vertices.update(a) return vertices ############################################################################################## La classe gérant les degrés de libertés from geom import * from collections import * from linear_system import * class dofkey: def __init__(self,node,name): self._node = node self._name = name def __eq__(self,other): node = other.getNode() name = other.getName() if (self._node == node) and (self._name == name): return True else: return False def __hash__(self): value = hash(self._name) return value def getNode(self): return self._node def getName(self): return self._name class dof_manager: def __init__(self): self._numbering = defaultdict() self._fixed = defaultdict() def fixVertex(self,node,name,val): dof = dofkey(node,name) self._fixed[dof]=val def numberVertex(self,node,name): dof = dofkey(node,name) if self._fixed.get(dof,"_") == "_": self._numbering[dof]=(len(self._numbering)) def fixVertices(self,nodes,name,val): fix = self.fixVertex for node in nodes: fix(node,name,val) def numberVertices(self,nodes,name): number = self.numberVertex for node in nodes: number(node,name) def getNumberingSize(self): return len(self._numbering) def getFixedSize(self): return len(self._fixed) def linkToLinearSystem(self,lsys): self._lsys = lsys def fixInSolution(self,node,name,val): dof = dofkey(node,name) num = self._numbering.get(dof,-1) if not num == -1: self._lsys.fixInSolution(num,val) def addToMatrix(self,dofi,dofj,val): if (dofi in self._numbering.keys()): if (dofj in self._numbering.keys()): R = self._numbering[dofi] C = self._numbering[dofj] self._lsys.addToMatrix(R,C,val) else: R = self._numbering[dofi] F = self._fixed[dofj] self._lsys.addToRHS(R,-val*F) def addToRHS(self,dofi,val): if (dofi in self._numbering.keys()): R = self._numbering[dofi] self._lsys.addToRHS(R,val) def assembleInMatrix(self,node1,node2,n,local): unknows = ["RHO","P","UX","UY","UZ","Y","e","eps","T","k","h","YEQ","DEFF"] for i in xrange(n-1): f = "X" + str(i+1) unknows.append(f) unknows.append("XN") for i in xrange(n-1): f = "T" + str(i+1) unknows.append(f) unknows.append("TN") for i in xrange(13+2*n): dofi = dofkey(node1,unknows[i]) for j in xrange(13+2*n): dofj = dofkey(node2,unknows[j]) self.addToMatrix(dofi,dofj,local[i,j]) def assembleInVector(self,node1,n,local): unknows = ["RHO","P","UX","UY","UZ","Y","e","eps","T","k","h","DEFF"] for i in xrange(n-1): f = "X" + str(i+1) unknows.append(f) unknows.append("XN") for i in xrange(n-1): f = "T" + str(i+1) unknows.append(f) unknows.append("TN") for i in xrange(13+2*n): dofi = dofkey(node1,unknows[i]) self.addToRHS(dofi,local[i]) def getNewDofValue(self,node,name): dof = dofkey(node,name) if (dof in self._numbering.keys()): R = self._numbering[dof] val = self._lsys.getFromNewSolution(R) else: val = self._fixed[dof] return val def getOldDofValue(self,node,name): dof = dofkey(node,name) if (dof in self._numbering.keys()): R = self._numbering[dof] val = self._lsys.getFromOldSolution(R) else: val = self._fixed[dof] return val def systemSolve(self): self._lsys.solve() def getSolution(self): return self._lsys.getSolution() Hors ligne no_spleen Re : Petit guide pour aider au choix d'un langage le programme principal, qui ne fait que numéroter les variables # -*- coding: utf8 -*- # from geom import * from mesh import * from dof_manager import * # Paramètres du problème # nombre de noeuds dans les grains n = 10 # incrément d'espace dans les grains dr = 0.0008 # incrément de temps dT = 10 #Températures de l'air à l'entrée Ta = [50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50] #Teneur en eau de l'air a l'entrée Y = 0.005 #Vitesse de l'air Va = 1.0 # Lecture du maillage maillage = mesh("lit.msh") # Obtention des différents éléments Entree_1 = maillage.getVerticesByTag(2,40) Entree_2 = maillage.getVerticesByTag(2,29) Entree_3 = maillage.getVerticesByTag(2,18) Entree_4 = maillage.getVerticesByTag(2,95) Entree_5 = maillage.getVerticesByTag(2,84) Entree_6 = maillage.getVerticesByTag(2,66) Entree_7 = maillage.getVerticesByTag(2,55) Entree_8 = maillage.getVerticesByTag(2,44) Entree_9 = maillage.getVerticesByTag(2,48) Entree_10 = maillage.getVerticesByTag(2,36) Entree_11 = maillage.getVerticesByTag(2,25) Entree_12 = maillage.getVerticesByTag(2,14) Entree_13 = maillage.getVerticesByTag(2,91) Entree_14 = maillage.getVerticesByTag(2,80) Entree_15 = maillage.getVerticesByTag(2,70) Entree_16 = maillage.getVerticesByTag(2,59) Entree_17 = maillage.getVerticesByTag(2,112) Parois = maillage.getVerticesByTag(2,601) Sortie = maillage.getVerticesByTag(2,602) Elements = maillage.getVerticesByTag(3,603) # Assembleur print "\n-Begining of assembler building-" assem = dof_manager() for i in xrange(17): Entree = "Entree_" + str(i+1) assem.fixVertices(Entree,"UX",0) assem.fixVertices(Entree,"UY",0) assem.fixVertices(Entree,"UZ",Va) assem.fixVertices(Entree,"T" ,Ta[i]) assem.fixVertices(Entree,"Y" ,Y) assem.fixVertices(Parois,"UX",0) assem.fixVertices(Parois,"UY",0) assem.fixVertices(Parois,"UZ",0) assem.fixVertices(Sortie,"P",101325) assem.numberVertices(Elements,"RHO") assem.numberVertices(Elements,"P") assem.numberVertices(Elements,"UX") assem.numberVertices(Elements,"UY") assem.numberVertices(Elements,"UZ") assem.numberVertices(Elements,"Y") assem.numberVertices(Elements,"e") assem.numberVertices(Elements,"eps") assem.numberVertices(Elements,"T") assem.numberVertices(Elements,"k") assem.numberVertices(Elements,"h") assem.numberVertices(Elements,"YEQ") assem.numberVertices(Elements,"DEFF") assem.numberVertices(Elements,"X1") for i in xrange(2,n): f = "X" + str(i) assem.numberVertices(Elements,f) assem.numberVertices(Elements,"XN") assem.numberVertices(Elements,"T1") for i in xrange(2,n): f = "T" + str(i) assem.numberVertices(Elements,f) assem.numberVertices(Elements,"TN") print "-End of assembler building-\n" Hors ligne
I've been trying (and failing) to figure out how to send email via Python. Trying the example from here: http://docs.python.org/library/smtplib.html#smtplib.SMTP but added the line server = smtplib.SMTP_SSL('smtp.gmail.com', 465) after I got a bounceback about not having an SSL connection. Now I'm getting this: Traceback (most recent call last): File "C:/Python26/08_emailconnects/12_29_EmailSendExample_NotWorkingYet.py", line 37, in <module> server = smtplib.SMTP('smtp.gmail.com', 65) File "C:\Python26\lib\smtplib.py", line 239, in __init__ (code, msg) = self.connect(host, port) File "C:\Python26\lib\smtplib.py", line 295, in connect self.sock = self._get_socket(host, port, self.timeout) File "C:\Python26\lib\smtplib.py", line 273, in _get_socket return socket.create_connection((port, host), timeout) File "C:\Python26\lib\socket.py", line 512, in create_connection raise error, msg error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond >>> Thoughts? server = smtplib.SMTP("smtp.google.com", 495) gives me a timeout error. just smtplib.smtp("smtp.google.com", 495) gives me "SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol" (see below). I'm trying different ports and now I'm getting a completely new error. I'll just post the whole bit of code, I'm probably making some rookie mistake. " import smtplib mailuser = 'MYEMAIL@gmail.com' mailpasswd = 'MYPASSWORD' fromaddr = 'MYEMAIL@gmail.com' toaddrs = 'MYEMAIL2@gmail.com' msg = 'Hooooorah!' print msg server = smtplib.SMTP_SSL('smtp.google.com') server = smtplib.SMTP_SSL_PORT=587 server.user(mailuser) server.pass_(mailpasswd) server.set_debuglevel(1) server.sendmail(fromaddr, toaddrs, msg) server.quit() " and then I get this error message: " Traceback (most recent call last): File "C:/Python26/08_emailconnects/12_29_eMAILSendtryin_stripped.py", line 16, in <module> server = smtplib.SMTP_SSL('smtp.google.com') File "C:\Python26\lib\smtplib.py", line 749, in __init__ SMTP.__init__(self, host, port, local_hostname, timeout) File "C:\Python26\lib\smtplib.py", line 239, in __init__ (code, msg) = self.connect(host, port) File "C:\Python26\lib\smtplib.py", line 295, in connect self.sock = self._get_socket(host, port, self.timeout) File "C:\Python26\lib\smtplib.py", line 755, in _get_socket self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile) File "C:\Python26\lib\ssl.py", line 350, in wrap_socket suppress_ragged_eofs=suppress_ragged_eofs) File "C:\Python26\lib\ssl.py", line 118, in __init__ self.do_handshake() File "C:\Python26\lib\ssl.py", line 293, in do_handshake self._sslobj.do_handshake() SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol " note that actually the which looks like "server = smtplib.SMTPSSLPORT=587" is actually "server = smtplib.SMTP underscore SSL underscore PORT=587", there's some sort of formatting thing going on here.
Officially, web2py recommends using doctests to test your controllers. Doctest, however, is not always the ideal way to test your code. Doctests are especially inept at handling database-driven controllers, where it's important to return the database to a known state before running each test. After a long discussion on the mailing list this article was created to provide a clear explanation of how to do unit testing in web2py using Python's unittest module. A thorough introduction to the unittest module can be found here. Let's look at a sample unit test script, then break it down to understand what it's doing. The purpose of this article is to demonstrate how to use Python's unittest module with web2py projects. Unlike other such examples on the Internet, this one shows how to test controllers that interact with a database. import unittest from gluon.globals import Request execfile("applications/api/controllers/10.py", globals()) db(db.game.id>0).delete() # Clear the database db.commit() class TestListActiveGames(unittest.TestCase): def setUp(self): request = Request() # Use a clean Request object def testListActiveGames(self): # Set variables for the test function request.post_vars["game_id"] = 1 request.post_vars["username"] = "spiffytech" resp = list_active_games() db.commit() self.assertEquals(0, len(resp["games"])) suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestListActiveGames)) unittest.TextTestRunner(verbosity=2).run(suite) Before we continue, you should know how to execute this script: python web2py.py -S api -M -R applications/api/tests/test.py Fill in the name of your own application after -S, and the location of your test script. We use web2py.py to call our script because it sets up the operating environment for us; it brings in our database and gives us all of the variables that are normally passed into the controller, like request. Let's break down the above example: import unittest from gluon.globals import Request # So we can reset the request for each test The first line, predictably, imports the unittest module. The second line imports web2py's Request object. We want this to be available so we can use a fresh, clean, unmodified Request object in every test. execfile("applications/api/controllers/10.py", globals()) Just like in the web2py shell, unit test scripts don't automatically have access to your controllers. This line executes your controller file, bringing all of the function declarations into the local namespace. Passing globals() to the execfile() command lets your controllers see your database. db(db.game.id>0).delete() # Clear the database db.commit() Unit testing with a database is only useful if the database looks the same when your tests run. These lines empty the database. In your unit tests, you must run db.commit() in order for any db.update(), db.insert(), or db.delete() commands to take effect. web2py automatically runs db.commit() when a controller's function finishes, which is why you don't usually have to do it yourself. Not so in external scripts. You must also run db.commit() after calling any controller function that changes the database. There is no harm in calling db.commit() after all controller functions, just to be safe. class TestListActiveGames(unittest.TestCase): def setUp(self): Unit test suites are composed of classes whose names start with "Test". Each class has it's own setUp() function which is run before each test. You can use the setUp() function to set up any variables or conditions you need for every test in the class. request = Request() # Use a clean Request object It's important to clean up your mess between tests. In our simple example, the only thing in the operating environment we're changing is the global request object each controller function sees and works with. def testListActiveGames(self): # Set variables for the test function The unittest module will run any function whose name starts with 'test'. Here, we've given our test function a name that describes what it's testing. request.post_vars["game_id"] = 1 request.post_vars["username"] = "spiffytech" These lines set up the variables needed by the function we're testing. post_vars is a dictionary that, in your controller, contains the values a user's browsers sent via POST. The controller function we're testing expects to see POST values, so we set them up. resp = list_active_games() db.commit() self.assertEquals(0, len(resp["games"])) Now we actually test something! list_active_games() is a function in my controller. The function returns a dict of values, just like most web2py controller functions. I've captured the dict in a variable named resp, short for "response". It doesn't matter what you name the variable, as long as the name is meaningful. The second line commits any changes to the database made by list_active_games(). The third line represents the heart of unit testing: making sure the output from a function is what we expect it to be. Since our test class, TestListActiveGames, is derived from unittest.TestCase the self object has a number of functions for testing values. Here, we use the basic assertEquals() function which, just like it sounds, checks that two values match. Unlike Python's regular assert() function, assertEquals() (and other unittest assert functions) prints useful information to the command line when assertions fail. suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestListActiveGames)) unittest.TextTestRunner(verbosity=2).run(suite) These last few lines get the unit tests started. We define a group (or "suite") of unit tests, then add to the suite all of our test classes. Here, we only have one test class, but if we had more, you'd simply repeat the second line with each classes name. If you've used the unittest module before and wonder why we're not simply calling unittest.main(), see the Background section below. The big problem with the above example is that it works on the database you're using to develop your application. Anything your tests do to the database (including the big fat "delete all" near the top of the script) will affect your development site. To fix this, we need to tell web2py to create a copy of our database that we can safely use for testing. It's pretty simple: Append this code to the bottom of db.py # Create a test database that's laid out just like the "real" database import copy test_db = DAL('sqlite://testing.sqlite') # Name and location of the test DB file for tablename in db.tables: # Copy tables! table_copy = [copy.copy(f) for f in db[tablename]] test_db.define_table(tablename, *table_copy) Modify test.py to use the test DB ... from gluon.globals import Request db = test_db # Rename the test database so that functions will use it instead of the real database ... unittest moduleunittest normally works Unit tests are normally stored in a standalone Python script. The script imports the unittest module, some tests are defined, and a couple lines at the bottom of the file run the tests when the script is executed. Here's an example: import unittest import myprogram # Import the code you want these unit tests to test class TestStuff(unittest.TestCase): def setUp(self): self.something = 5 def testSomeFunction(self): result = myprogram.somefunction(self.something) self.assertEquals(result, 10) result = myprogram.somefunction(result) self.assertEquals(result, 20) # Run the unit tests if the script is being executed from the command line if __name__ == "__main__": unittest.main() This script would be called from the command line like so: python my_tests.py Explicit is better than implicit. Flat is better than nested. Namespaces are one honking great idea -- let's do more of those! - Excerpted from the Zen of Python web2py forgoes some staples of Pythonic programing philosophy in favor of being easy to teach and easy to use use. Some people think this winds results in "magic". Rather than treating each .py file as a module which is imported (a la Django), web2py sets up a ready-to-use environment behind the scenes before giving control over to the web developer. The developer sees their database and built-in web2py functions magically available in the controller, and rejoices. This is convenient when developing web applications, but causes problems for external scripts. The normal command to run unit tests, unittest.main(), gets confused because it's run in the scope of web2py.py, rather than in the scope of a standalone script. unittest.main() also gets confused because web2py.py passes all of the command line arguments to test.py, and the unittest module doesn't know what to do with web2py.py's command line flags. We have to do a few things different to get unit testing working with web2py: Steps 1 and 2 are mandatory, and step 3 is a byproduct of the way I chose to solve 1 and 2. AlterEgo 213 shows a different way to set up the environment for unit tests than the way I describe. In AlterEgo 213, the test script handles the setup of the whole web2py environment. However, this clutters up the code with lots of stuff that you can delegate to web2py.py instead. The tradeoff is that you lose the ability to specify what test to run from the command line. *Note that AlterEgo 213 is incomplete. Several changes must be made to it in order for your controllers to see your database. This complicates the code more than I cared for.
I have to read an XML file in Python and grab various things, and I ran into a frustrating error with Unicode Encode Error that I couldn't figure out even with googling. Here are snippets of my code: #!/usr/bin/python # coding: utf-8 from xml.dom.minidom import parseString with open('data.txt','w') as fout: #do a lot of stuff nameObj = data.getElementsByTagName('name')[0] name = nameObj.childNodes[0].nodeValue #... do more stuff fout.write(','.join((name,bunch of other stuff)) This spectacularly crashes when a name entry I am parsing contains a Euro sign. Here is the error: UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in position 60: ordinal not in range(128) I understand why Euro sign will screw it up (because it's at 128, right?), but I thought doing # coding: utf-8 would fix that. I also tried adding .encode(utf-8) so that the name looks instead like name = nameObj.childNodes[0].nodeValue.encode(utf-8) But that doesn't work either. What am I doing wrong? (I am using Python 2.7.3 if anyone wants to know) EDIT: Python crashes out on the fout.write() line -- it will go through fine where the name field is like: <name>United States, USD</name> But will crap out on name fields like: <name>France, € </name>
Ayu Grub ne se lance pas Bonsoir, J'ai installé windows 7 et Xubuntu 11.10 sur un nouveau pc avec cette configuration:CM: Asus P8H67 B3Processeur: i5 2500kDD: 1TO 7200 RPMRAM: 2x4GOCG: Gigabyte GeForce GTX 560 Mais je boot toujours sur windows et Grub ne se lance pas j'ai essayé de réinstaller grub depuis une session live avec sudo grub-install /dev/sda ça me renvoi: /usr/sbin/grub-probe : erreur : cannot find a device for /boot/grub (is /dev mounted?). et sudo fdisk -l me renvoi: Attention : identifiant de table de partitions GPT (GUID) détecté sur « /dev/sda » ! L'utilitaire sfdisk ne prend pas GPT en charge. Utilisez GNU Parted. 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 : 0x648ad58f Périphérique Amorce Début Fin Blocs Id Système /dev/sda1 1 1953525167 976762583+ ee GPT et sudo os-prober me renvoi: (ça ne montre pas windows ? O.o) /dev/sda4:Ubuntu 11.10 (11.10):Ubuntu:linux et le script boot_info_script.sh me renvoi: Boot Info Script 0.60 from 17 May 2011 ============================= Boot Info Summary: =============================== => Grub2 (v1.99) is installed in the MBR of /dev/sda and looks at sector 423401960 of the same hard drive for core.img. core.img is at this location and looks for on this drive. sda1: __________________________________________________________________________ File system: vfat Boot sector type: Unknown Boot sector info: No errors found in the Boot Parameter Block. Operating System: Boot files: sda2: __________________________________________________________________________ File system: Boot sector type: - Boot sector info: Mounting failed: mount : type de système de fichiers «  » inconnu sda3: __________________________________________________________________________ File system: ntfs Boot sector type: Windows Vista/7 Boot sector info: No errors found in the Boot Parameter Block. Operating System: Windows 7 Boot files: /Windows/System32/winload.exe sda4: __________________________________________________________________________ File system: ext4 Boot sector type: - Boot sector info: Operating System: Ubuntu 11.10 Boot files: /boot/grub/grub.cfg /etc/fstab /boot/grub/core.img sda5: __________________________________________________________________________ File system: swap Boot sector type: - Boot sector info: sda6: __________________________________________________________________________ File system: ntfs Boot sector type: Windows Vista/7 Boot sector info: No errors found in the Boot Parameter Block. Operating System: Boot files: ============================ Drive/Partition Info: ============================= Drive: sda _____________________________________________________________________ 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 Partition Boot Start Sector End Sector # of Sectors Id System /dev/sda1 1 1,953,525,167 1,953,525,167 ee GPT GUID Partition Table detected. Partition Start Sector End Sector # of Sectors System /dev/sda1 2,048 206,847 204,800 EFI System partition /dev/sda2 206,848 468,991 262,144 Microsoft Reserved Partition (Windows) /dev/sda3 468,992 409,602,047 409,133,056 Data partition (Windows/Linux) /dev/sda4 409,602,048 800,227,048 390,625,001 Data partition (Windows/Linux) /dev/sda5 800,227,049 817,023,924 16,796,876 Swap partition (Linux) /dev/sda6 817,025,024 1,953,523,711 1,136,498,688 Data partition (Windows/Linux) "blkid" output: ________________________________________________________________ Device UUID TYPE LABEL /dev/loop0 squashfs /dev/sda1 C425-C856 vfat /dev/sda3 04242E1C242E116A ntfs /dev/sda4 73768a23-3767-4c6c-bb8d-3a2afbb7bda2 ext4 /dev/sda5 cdfeeba6-3426-4109-a3de-86412dc29a09 swap /dev/sda6 505AA4295AA40DB2 ntfs Data ================================ Mount points: ================================= Device Mount_Point Type Options /dev/loop0 /rofs squashfs (ro,noatime) /dev/sda3 /media/04242E1C242E116A fuseblk (rw,nosuid,nodev,allow_other,blksize=4096,default_permissions) /dev/sda4 /media/73768a23-3767-4c6c-bb8d-3a2afbb7bda2 ext4 (rw,nosuid,nodev,uhelper=udisks) /dev/sda6 /media/Data fuseblk (rw,nosuid,nodev,allow_other,blksize=4096,default_permissions) /dev/sr0 /cdrom iso9660 (ro,noatime) =========================== sda4/boot/grub/grub.cfg: =========================== -------------------------------------------------------------------------------- # # DO NOT EDIT THIS FILE # # It is automatically generated by grub-mkconfig using templates # from /etc/grub.d and settings from /etc/default/grub # ### BEGIN /etc/grub.d/00_header ### if [ -s $prefix/grubenv ]; then set have_grubenv=true load_env fi set default="0" if [ "${prev_saved_entry}" ]; then set saved_entry="${prev_saved_entry}" save_env saved_entry set prev_saved_entry= save_env prev_saved_entry set boot_once=true fi function savedefault { if [ -z "${boot_once}" ]; then saved_entry="${chosen}" save_env saved_entry fi } function recordfail { set recordfail=1 if [ -n "${have_grubenv}" ]; then if [ -z "${boot_once}" ]; then save_env recordfail; fi; fi } function load_video { insmod vbe insmod vga insmod video_bochs insmod video_cirrus } insmod part_gpt insmod ext2 set root='(hd0,gpt4)' search --no-floppy --fs-uuid --set=root 73768a23-3767-4c6c-bb8d-3a2afbb7bda2 if loadfont /usr/share/grub/unicode.pf2 ; then set gfxmode=auto load_video insmod gfxterm insmod part_gpt insmod ext2 set root='(hd0,gpt4)' search --no-floppy --fs-uuid --set=root 73768a23-3767-4c6c-bb8d-3a2afbb7bda2 set locale_dir=($root)/boot/grub/locale set lang=fr_FR insmod gettext fi terminal_output gfxterm if [ "${recordfail}" = 1 ]; then set timeout=-1 else set timeout=10 fi ### END /etc/grub.d/00_header ### ### BEGIN /etc/grub.d/05_debian_theme ### set menu_color_normal=white/black set menu_color_highlight=black/light-gray ### END /etc/grub.d/05_debian_theme ### ### BEGIN /etc/grub.d/10_linux ### if [ ${recordfail} != 1 ]; then if [ -e ${prefix}/gfxblacklist.txt ]; then if hwmatch ${prefix}/gfxblacklist.txt 3; then if [ ${match} = 0 ]; then set linux_gfx_mode=keep else set linux_gfx_mode=text fi else set linux_gfx_mode=text fi else set linux_gfx_mode=keep fi else set linux_gfx_mode=text fi export linux_gfx_mode if [ "$linux_gfx_mode" != "text" ]; then load_video; fi menuentry 'Ubuntu, avec Linux 3.0.0-12-generic' --class ubuntu --class gnu-linux --class gnu --class os { recordfail set gfxpayload=$linux_gfx_mode insmod gzio insmod part_gpt insmod ext2 set root='(hd0,gpt4)' search --no-floppy --fs-uuid --set=root 73768a23-3767-4c6c-bb8d-3a2afbb7bda2 linux /boot/vmlinuz-3.0.0-12-generic root=UUID=73768a23-3767-4c6c-bb8d-3a2afbb7bda2 ro quiet splash vt.handoff=7 initrd /boot/initrd.img-3.0.0-12-generic } menuentry 'Ubuntu, avec Linux 3.0.0-12-generic (mode de dépannage)' --class ubuntu --class gnu-linux --class gnu --class os { recordfail insmod gzio insmod part_gpt insmod ext2 set root='(hd0,gpt4)' search --no-floppy --fs-uuid --set=root 73768a23-3767-4c6c-bb8d-3a2afbb7bda2 echo 'Chargement de Linux 3.0.0-12-generic ...' linux /boot/vmlinuz-3.0.0-12-generic root=UUID=73768a23-3767-4c6c-bb8d-3a2afbb7bda2 ro recovery nomodeset echo 'Chargement du disque mémoire initial ...' initrd /boot/initrd.img-3.0.0-12-generic } ### END /etc/grub.d/10_linux ### ### BEGIN /etc/grub.d/20_linux_xen ### ### END /etc/grub.d/20_linux_xen ### ### BEGIN /etc/grub.d/20_memtest86+ ### menuentry "Memory test (memtest86+)" { insmod part_gpt insmod ext2 set root='(hd0,gpt4)' search --no-floppy --fs-uuid --set=root 73768a23-3767-4c6c-bb8d-3a2afbb7bda2 linux16 /boot/memtest86+.bin } menuentry "Memory test (memtest86+, serial console 115200)" { insmod part_gpt insmod ext2 set root='(hd0,gpt4)' search --no-floppy --fs-uuid --set=root 73768a23-3767-4c6c-bb8d-3a2afbb7bda2 linux16 /boot/memtest86+.bin console=ttyS0,115200n8 } ### END /etc/grub.d/20_memtest86+ ### ### BEGIN /etc/grub.d/30_os-prober ### if [ "x${timeout}" != "x-1" ]; then if keystatus; then if keystatus --shift; then set timeout=-1 else set timeout=0 fi else if sleep --interruptible 3 ; then set timeout=0 fi fi fi ### END /etc/grub.d/30_os-prober ### ### BEGIN /etc/grub.d/40_custom ### # This file provides an easy way to add custom menu entries. Simply type the # menu entries you want to add after this comment. Be careful not to change # the 'exec tail' line above. ### END /etc/grub.d/40_custom ### ### BEGIN /etc/grub.d/41_custom ### if [ -f $prefix/custom.cfg ]; then source $prefix/custom.cfg; fi ### END /etc/grub.d/41_custom ### -------------------------------------------------------------------------------- =============================== sda4/etc/fstab: ================================ -------------------------------------------------------------------------------- # /etc/fstab: static file system information. # # Use 'blkid' to print the universally unique identifier for a # device; this may be used with UUID= as a more robust way to name devices # that works even if disks are added and removed. See fstab(5). # # <file system> <mount point> <type> <options> <dump> <pass> proc /proc proc nodev,noexec,nosuid 0 0 # / was on /dev/sda4 during installation UUID=73768a23-3767-4c6c-bb8d-3a2afbb7bda2 / ext4 errors=remount-ro 0 1 # swap was on /dev/sda5 during installation UUID=cdfeeba6-3426-4109-a3de-86412dc29a09 none swap sw 0 0 -------------------------------------------------------------------------------- =================== sda4: Location of files loaded by Grub: ==================== GiB - GB File Fragment(s) = boot/grub/core.img 1 = boot/grub/grub.cfg 1 = boot/initrd.img-3.0.0-12-generic 2 = boot/vmlinuz-3.0.0-12-generic 1 = initrd.img 2 = vmlinuz 1 ======================== Unknown MBRs/Boot Sectors/etc: ======================== Unknown BootLoader on sda1 00000000 eb 58 90 4d 53 44 4f 53 35 2e 30 00 02 02 fe 19 |.X.MSDOS5.0.....| 00000010 02 00 00 00 00 f8 00 00 3f 00 ff 00 00 08 00 00 |........?.......| 00000020 00 20 03 00 01 03 00 00 00 00 00 00 02 00 00 00 |. ..............| 00000030 01 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| 00000040 80 00 29 56 c8 25 c4 4e 4f 20 4e 41 4d 45 20 20 |..)V.%.NO NAME | 00000050 20 20 46 41 54 33 32 20 20 20 33 c9 8e d1 bc f4 | FAT32 3.....| 00000060 7b 8e c1 8e d9 bd 00 7c 88 4e 02 8a 56 40 b4 41 |{......|.N..V@.A| 00000070 bb aa 55 cd 13 72 10 81 fb 55 aa 75 0a f6 c1 01 |..U..r...U.u....| 00000080 74 05 fe 46 02 eb 2d 8a 56 40 b4 08 cd 13 73 05 |t..F..-.V@....s.| 00000090 b9 ff ff 8a f1 66 0f b6 c6 40 66 0f b6 d1 80 e2 |.....f...@f.....| 000000a0 3f f7 e2 86 cd c0 ed 06 41 66 0f b7 c9 66 f7 e1 |?.......Af...f..| 000000b0 66 89 46 f8 83 7e 16 00 75 38 83 7e 2a 00 77 32 |f.F..~..u8.~*.w2| 000000c0 66 8b 46 1c 66 83 c0 0c bb 00 80 b9 01 00 e8 2b |f.F.f..........+| 000000d0 00 e9 2c 03 a0 fa 7d b4 7d 8b f0 ac 84 c0 74 17 |..,...}.}.....t.| 000000e0 3c ff 74 09 b4 0e bb 07 00 cd 10 eb ee a0 fb 7d |<.t............}| 000000f0 eb e5 a0 f9 7d eb e0 98 cd 16 cd 19 66 60 80 7e |....}.......f`.~| 00000100 02 00 0f 84 20 00 66 6a 00 66 50 06 53 66 68 10 |.... .fj.fP.Sfh.| 00000110 00 01 00 b4 42 8a 56 40 8b f4 cd 13 66 58 66 58 |....B.V@....fXfX| 00000120 66 58 66 58 eb 33 66 3b 46 f8 72 03 f9 eb 2a 66 |fXfX.3f;F.r...*f| 00000130 33 d2 66 0f b7 4e 18 66 f7 f1 fe c2 8a ca 66 8b |3.f..N.f......f.| 00000140 d0 66 c1 ea 10 f7 76 1a 86 d6 8a 56 40 8a e8 c0 |.f....v....V@...| 00000150 e4 06 0a cc b8 01 02 cd 13 66 61 0f 82 75 ff 81 |.........fa..u..| 00000160 c3 00 02 66 40 49 75 94 c3 42 4f 4f 54 4d 47 52 |...f@Iu..BOOTMGR| 00000170 20 20 20 20 00 00 00 00 00 00 00 00 00 00 00 00 | ............| 00000180 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| * 000001a0 00 00 00 00 00 00 00 00 00 00 00 00 0d 0a 52 65 |..............Re| 000001b0 74 69 72 65 7a 20 6c 65 20 64 69 73 71 75 65 ff |tirez le disque.| 000001c0 0d 0a 45 72 72 2e 20 64 69 73 71 75 65 ff 0d 0a |..Err. disque...| 000001d0 50 72 65 73 73 65 7a 20 75 6e 65 20 74 6f 75 63 |Pressez une touc| 000001e0 68 65 20 70 6f 75 72 20 72 65 64 82 6d 61 72 72 |he pour red.marr| 000001f0 65 72 0d 0a 00 00 00 00 00 ac c0 ce 00 00 55 aa |er............U.| 00000200 =============================== StdErr Messages: =============================== unlzma: Decoder error awk: cmd. line:36: Math support is not compiled in awk: cmd. line:36: Math support is not compiled in awk: cmd. line:36: Math support is not compiled in awk: cmd. line:36: Math support is not compiled in awk: cmd. line:36: Math support is not compiled in awk: cmd. line:36: Math support is not compiled in En attente de votre réponse. Merci d'avance! Dernière modification par Ayu (Le 27/11/2011, à 23:05) Que vous m'aspergiez d’alcool et de nourritures, que vous me crachiez à la figure, ça passe encore, mais il y as des limites !! Je ne tolère pas que l'ont maltraite un ami! - Akagami no Shanks Hors ligne xabilon Re : Grub ne se lance pas Salut Je ne sais pas si c'est le fait que la table de partitions soit en GPT qui fait ça, mais on dirait que le BIOS démarre sur le boot-sector de sda1 plutôt que sur le MBR de sda. Consulte déjà les options de démarrage de ton BIOS. C'est malheureusement la première fois que j'entends parler de ce type de table de partitions ... Pour passer un sujet en résolu : modifiez le premier message et ajoutez [Résolu] au titre. En ligne malbo Re : Grub ne se lance pas Ayu, Je m'intéresse à UEFI mais je débute dans l'apprentissage et je ne connais pas l'EFI Boot de Asus autrement que par l'intermédiaire de Google. Je viens de lire ça : http://support.asus.com/Search/KDetail. … 19D871&t=2 Je voudrais savoir pratiquement comment tu démarres actuellement sous Windows par rapport à ce qui est décrit dans ce lien : peux-tu aller dans le réglages avancés et vérifier que c'est bien "Windows Boot Manager" qui est en priorité de Boot ? Edit : je te parle de UEFI parce que ta carte-mère est équipée de UEFI au lieu de BIOS. On trouve des infos sur ton matériel dans cette partie de la documentation anglaise de Ubuntu : https://help.ubuntu.com/community/UEFIB … chitecture Il y est dit que les carte-mère H67 de Asus utilisent ce type de logiciel UEFI. Par conséquent, toutes les vieilles méthodes utilisées avec le Bios ne sont pas utilisables. En particulier, on n'installe pas Grub dans le MBR comme ça a été fait dans ton disque dur, comme on peut voir dans le résultat que tu as posté : Boot Info Script 0.60 from 17 May 2011 ============================= Boot Info Summary: =============================== => Grub2 (v1.99) is installed in the MBR of /dev/sda and looks at sector 423401960 of the same hard drive for core.img. core.img is at this location and looks for on this drive. C'est à dire que Grub2 installé dans le MBR du disque dur comme il est spécifié dans la documentation du site, ça ne marche pas avec une carte-mère UEFI. Pour l'instant tu peux le laisser en place mais le système UEFI ne pourra pas l'exploiter. Dans un système UEFI, le paramétrage du multi-boot, ça se fait dans la partition EFI (ta partition sda1). Le principe, c'est que dans cette partition, il doit y avoir tous les fichiers nécessaires pour pouvoir démarrer tous les OS du PC. A l'heure actuelle, c'est dans cette partition EFI que se trouve le fichier qui permet de démarrer Win7. Le but du jeu, c'est qu'un fichier permettant de démarrer Ubuntu se trouve également dans cette partition EFI. Et normalement, lors de l'installation de Ubuntu, l'installateur devrait automatiquement créer le dossier et le fichier qui va bien dans la partition EFI. Mais j'ai de gros doutes dans ton cas et dans la discussion dont je donne le lien ci-dessous, il est mentionné l'hypothèse que pour une raison ou une autre, Ubuntu n'ait pas pu détecter le système UEFI et ait malencontreusement fait une installation classique avec grub-pc au lieu de faire l'installation avec grub-efi qui est sensé fabriquer le fichier qui va bien dans la partition EFI. C'est le système bâtard dont il est question dans cette cette discussion : http://ubuntuforums.org/showthread.php?t=1770885 Cammer Pants semble avoir un partitionnement très semblable au tien en ce qui concerne sda1 et sda2, pourtant ce n'est pas la même carte-mère (la sienne est Gigabyte GA-870A-USB3). Dans ce post de la même discussion, srs5694 - qui est spécialiste de ces pb UEFI - donne des explications. Dernière modification par malbo (Le 28/11/2011, à 13:42) MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04 Hors ligne Ayu Re : Grub ne se lance pas Bonsoir, Merci pour vos réponses. peux-tu aller dans le réglages avancés et vérifier que c'est bien "Windows Boot Manager" qui est en priorité de Boot ? Oui c'est bien ça, pour le reste je comprend pas trop comment régler le problème. Dernière modification par Ayu (Le 28/11/2011, à 20:48) Que vous m'aspergiez d’alcool et de nourritures, que vous me crachiez à la figure, ça passe encore, mais il y as des limites !! Je ne tolère pas que l'ont maltraite un ami! - Akagami no Shanks Hors ligne malbo Re : Grub ne se lance pas Peux-tu démarrer sur un support live de Ubuntu 11.10, monter la partition sda1 avec l'utilitaire de disque et vérifier si elle contient bien un fichier grubx64.efi dans le chemin EFI/ubuntu/ (si tu préfères, tu peux aussi vérifier la chose depuis Windows puisque la partition EFI est visible depuis Windows). Le but du jeu, c'est d'avoir les éléments pour pouvoir booter sur ce fichier .efi par l’intermédiaire de ton Système UEFI. En général, c'est très simple mais il faut avoir quelques directives et le fabricant de ton PC doit pouvoir te donner l'info si tu ne t'en sors pas à l'instinct. Moi, je l'ai fait dans un PC virtuel (avec VirtualBox) donc avec un système UEFI virtuel et c'est assez simple à condition d'avoir quelques indications. Je me suis aidé de cette doc (§ 4.1 Using Boot Maintenance Menu:) : http://software.intel.com/en-us/article … scripting/ et c'est ce qui m'a permis de créer une nouvelle entrée dans le Boot manager (voir chapitre D : installation de Ubuntu 11.10 depuis la session live ) : http://forum.ubuntu-fr.org/viewtopic.ph … 1#p7189161 il y a vraiment très peu de manipulations à faire. Dernière modification par malbo (Le 28/11/2011, à 21:38) MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04 Hors ligne Ayu Re : Grub ne se lance pas Je ne retrouve pas le fichier grubx64.efi par contre je peux booter sur linux en choisissant ça dans le bios il faut à chaque fois que je rentre dans le bios pour choisir mon OS Que vous m'aspergiez d’alcool et de nourritures, que vous me crachiez à la figure, ça passe encore, mais il y as des limites !! Je ne tolère pas que l'ont maltraite un ami! - Akagami no Shanks Hors ligne malbo Re : Grub ne se lance pas par contre je peux booter sur linux en choisissant ça dans le bios il faut à chaque fois que je rentre dans le bios pour choisir mon OS Cette entrée de ton "Bios" qui te permet de booter sur linux, elle a été créée automatiquement par l'installateur de Ubuntu ou bien c'est toi qui a dû la paramétrer à la main (un peu comme j'explique dans mon post précédent) ? L'entrée pour Win7 dans ton "Bios" est désignée par "Windows Boot Manager". Comment est désignée l'entrée pour Ubuntu ? Quand tu choisis de démarrer sur Ubuntu, juste avant que Ubuntu démarre, en appuyant rapidement sur la touche Echap tu dois pouvoir faire apparaître le menu Grub. est-ce bien le cas ? Dernière modification par malbo (Le 29/11/2011, à 07:25) MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04 Hors ligne Ayu Re : Grub ne se lance pas Bonjour, l'entrée à été crée automatiquement L'entrée Win8 c'est bien "Windows Boot Manager" Par contre si je sélectionne un boot sur le DD (SATA: ST31000524AS) depuis le bios (et cela sans grub) Linux se lance Dernière modification par Ayu (Le 29/11/2011, à 11:02) Que vous m'aspergiez d’alcool et de nourritures, que vous me crachiez à la figure, ça passe encore, mais il y as des limites !! Je ne tolère pas que l'ont maltraite un ami! - Akagami no Shanks Hors ligne malbo Re : Grub ne se lance pas Par contre si je sélectionne un boot sur le DD (SATA: ST31000524AS) depuis le bios (et cela sans grub) Linux se lance Arrivé dans Ubuntu, peux-tu ouvrir un terminal et passer cette commande : dmesg | grep EFI Chez moi depuis une session Ubuntu dans un système Bios (mon PC Acer), ça donne ça : dmesg | grep EFI [ 1.241248] EFI Variables Facility v0.08 2004-May-17 Ce qui indique bien que Ubuntu a démarré dans un système Bios Par contre, si j'ouvre un session Ubuntu dans un système UEFI (dans un PC virtuel par VirtualBox), voici ce que j'obtiens : dmesg | grep EFI [ 0.000000] EFI v2.10 by VBOX 64 [ 0.000000] Kernel-defined memdesc doesn't match the one from EFI! [ 0.000000] EFI: mem00: type=7, attr=0xf, range=[0x0000000000000000-0x00000000000a0000) (0MB) [ 0.000000] EFI: mem01: type=2, attr=0xf, range=[0x0000000000100000-0x000000000056e000) (4MB) [ 0.000000] EFI: mem02: type=7, attr=0xf, range=[0x000000000056e000-0x000000000f9d9000) (244MB) [ 0.000000] EFI: mem03: type=2, attr=0xf, range=[0x000000000f9d9000-0x000000001f000000) (246MB) [ 0.000000] EFI: mem04: type=3, attr=0xf, range=[0x000000001f000000-0x000000001f00e000) (0MB) [ 0.000000] EFI: mem05: type=7, attr=0xf, range=[0x000000001f00e000-0x00000000365ae000) (373MB) [ 0.000000] EFI: mem06: type=2, attr=0xf, range=[0x00000000365ae000-0x00000000372cf000) (13MB) [ 0.000000] EFI: mem07: type=7, attr=0xf, range=[0x00000000372cf000-0x000000003d8bc000) (101MB) [ 0.000000] EFI: mem08: type=4, attr=0xf, range=[0x000000003d8bc000-0x000000003dc9f000) (3MB) [ 0.000000] EFI: mem09: type=7, attr=0xf, range=[0x000000003dc9f000-0x000000003dcb0000) (0MB) [ 0.000000] EFI: mem10: type=4, attr=0xf, range=[0x000000003dcb0000-0x000000003dcca000) (0MB) [ 0.000000] EFI: mem11: type=7, attr=0xf, range=[0x000000003dcca000-0x000000003dcda000) (0MB) [ 0.000000] EFI: mem12: type=4, attr=0xf, range=[0x000000003dcda000-0x000000003dcf6000) (0MB) [ 0.000000] EFI: mem13: type=7, attr=0xf, range=[0x000000003dcf6000-0x000000003dd4d000) (0MB) [ 0.000000] EFI: mem14: type=4, attr=0xf, range=[0x000000003dd4d000-0x000000003de05000) (0MB) [ 0.000000] EFI: mem15: type=7, attr=0xf, range=[0x000000003de05000-0x000000003de50000) (0MB) [ 0.000000] EFI: mem16: type=1, attr=0xf, range=[0x000000003de50000-0x000000003de70000) (0MB) [ 0.000000] EFI: mem17: type=4, attr=0xf, range=[0x000000003de70000-0x000000003de71000) (0MB) [ 0.000000] EFI: mem18: type=7, attr=0xf, range=[0x000000003de71000-0x000000003de95000) (0MB) [ 0.000000] EFI: mem19: type=2, attr=0xf, range=[0x000000003de95000-0x000000003de9b000) (0MB) [ 0.000000] EFI: mem20: type=4, attr=0xf, range=[0x000000003de9b000-0x000000003dea1000) (0MB) [ 0.000000] EFI: mem21: type=7, attr=0xf, range=[0x000000003dea1000-0x000000003dea4000) (0MB) [ 0.000000] EFI: mem22: type=2, attr=0xf, range=[0x000000003dea4000-0x000000003dea7000) (0MB) [ 0.000000] EFI: mem23: type=4, attr=0xf, range=[0x000000003dea7000-0x000000003deb1000) (0MB) [ 0.000000] EFI: mem24: type=2, attr=0xf, range=[0x000000003deb1000-0x000000003deba000) (0MB) [ 0.000000] EFI: mem25: type=7, attr=0xf, range=[0x000000003deba000-0x000000003debb000) (0MB) [ 0.000000] EFI: mem26: type=4, attr=0xf, range=[0x000000003debb000-0x000000003e7e7000) (9MB) [ 0.000000] EFI: mem27: type=3, attr=0xf, range=[0x000000003e7e7000-0x000000003e951000) (1MB) [ 0.000000] EFI: mem28: type=4, attr=0xf, range=[0x000000003e951000-0x000000003e952000) (0MB) [ 0.000000] EFI: mem29: type=3, attr=0xf, range=[0x000000003e952000-0x000000003e9d3000) (0MB) [ 0.000000] EFI: mem30: type=5, attr=0x800000000000000f, range=[0x000000003e9d3000-0x000000003e9f6000) (0MB) [ 0.000000] EFI: mem31: type=3, attr=0xf, range=[0x000000003e9f6000-0x000000003ea20000) (0MB) [ 0.000000] EFI: mem32: type=5, attr=0x800000000000000f, range=[0x000000003ea20000-0x000000003ea35000) (0MB) [ 0.000000] EFI: mem33: type=0, attr=0xf, range=[0x000000003ea35000-0x000000003ea36000) (0MB) [ 0.000000] EFI: mem34: type=4, attr=0xf, range=[0x000000003ea36000-0x000000003eed3000) (4MB) [ 0.000000] EFI: mem35: type=3, attr=0xf, range=[0x000000003eed3000-0x000000003eede000) (0MB) [ 0.000000] EFI: mem36: type=4, attr=0xf, range=[0x000000003eede000-0x000000003f83f000) (9MB) [ 0.000000] EFI: mem37: type=7, attr=0xf, range=[0x000000003f83f000-0x000000003f843000) (0MB) [ 0.000000] EFI: mem38: type=3, attr=0xf, range=[0x000000003f843000-0x000000003f8be000) (0MB) [ 0.000000] EFI: mem39: type=5, attr=0x800000000000000f, range=[0x000000003f8be000-0x000000003f8cc000) (0MB) [ 0.000000] EFI: mem40: type=3, attr=0xf, range=[0x000000003f8cc000-0x000000003f913000) (0MB) [ 0.000000] EFI: mem41: type=5, attr=0x800000000000000f, range=[0x000000003f913000-0x000000003f922000) (0MB) [ 0.000000] EFI: mem42: type=3, attr=0xf, range=[0x000000003f922000-0x000000003f92f000) (0MB) [ 0.000000] EFI: mem43: type=5, attr=0x800000000000000f, range=[0x000000003f92f000-0x000000003f933000) (0MB) [ 0.000000] EFI: mem44: type=5, attr=0x800000000000000f, range=[0x000000003f933000-0x000000003f94f000) (0MB) [ 0.000000] EFI: mem45: type=6, attr=0x800000000000000f, range=[0x000000003f94f000-0x000000003f985000) (0MB) [ 0.000000] EFI: mem46: type=6, attr=0x800000000000000f, range=[0x000000003f985000-0x000000003f99f000) (0MB) [ 0.000000] EFI: mem47: type=9, attr=0xf, range=[0x000000003f99f000-0x000000003f9b5000) (0MB) [ 0.000000] EFI: mem48: type=9, attr=0xf, range=[0x000000003f9b5000-0x000000003f9bb000) (0MB) [ 0.000000] EFI: mem49: type=10, attr=0xf, range=[0x000000003f9bb000-0x000000003f9bc000) (0MB) [ 0.000000] EFI: mem50: type=10, attr=0xf, range=[0x000000003f9bc000-0x000000003f9bf000) (0MB) [ 0.000000] EFI: mem51: type=4, attr=0xf, range=[0x000000003f9bf000-0x000000003fee0000) (5MB) [ 0.000000] EFI: mem52: type=6, attr=0x800000000000000f, range=[0x000000003fee0000-0x000000003ff00000) (0MB) [ 0.666999] fb0: EFI VGA frame buffer device [ 1.083445] EFI Variables Facility v0.08 2004-May-17 Ce grand nombre de ligne, dont plusieurs avec la mention "mem...", c'est caractéristique de Ubuntu démarré dans un système UEFI Dernière modification par malbo (Le 29/11/2011, à 11:58) MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04 Hors ligne Ayu Re : Grub ne se lance pas ça donne [ 1.237075] EFI Variables Facility v0.08 2004-May-17 Que vous m'aspergiez d’alcool et de nourritures, que vous me crachiez à la figure, ça passe encore, mais il y as des limites !! Je ne tolère pas que l'ont maltraite un ami! - Akagami no Shanks Hors ligne malbo Re : Grub ne se lance pas ça donne [ 1.237075] EFI Variables Facility v0.08 2004-May-17 OK donc quand tu sélectionnes un boot sur le DD (SATA: ST31000524AS) dans ton "Bios", tu démarres bien en mode "Legacy Device" dont il est question dans ce lien sur les vues : http://support.asus.com/Search/KDetail. … 19D871&t=2 C'est à dire que ton "Bios" ce comporte comme un ancien Bios (et non pas comme un sytème UEFI) et il est d'ailleurs vu par Ubuntu comme un Bios (et pas comme un UEFI). Avec ma petite connaissance du domaine, je crois pouvoir dire qu'il n'est pas possible de réussir à obtenir un menu Grub qui pourrait lancer Windows dans ta configuration actuelle de Ubuntu. En effet, Ubuntu s'est installé (que tu l'aies voulu ou non, ça je ne sais pas le dire) en mode Bios donc il est équipé de grub-pc (au lieu de grub-efi si l'installation avait été faite en mode UEFI). Grub-pc n'arrive pas à détecter la présence de ton Windows 7 parce que ta partition Win7 n'est pas équipé des fichiers caractéristiques d'une installation en mode Bios de Windows 7 : on peut voir dans le résultat de ton Boot Info Script, que ta partition sda3 ne comporte pas ces éléments Bootmgr, BCD, etc... qui servent à cette détection. Normal puisque l'équivalent de ces éléments doit être planqué dans la partition EFI. En bref, je pense que tu es obligé de choisir ton camp : 1ère possibilité : tu mets la priorité de démarrage sur le DD (SATA: ST31000524AS) dans ton "Bios" et tu démarres par défaut sur Ubuntu. Et le jour où tu as besoin d'aller sur Windows, tu passes par ton "Bios" pour choisir de démarrer "Windows Boot Manager". 2ème possibilité : Parce que tu travailles essentiellement sur Windows ou que le PC est à usage familial, tu mets la priorité de démarrage sur "Windows Boot Manager" dans le "Bios" et le jour où tu dois aller sous Ubuntu, tu passes par le "Bios" pour sélectionner le DD (SATA: ST31000524AS Dernière modification par malbo (Le 29/11/2011, à 12:22) MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04 Hors ligne Ayu Re : Grub ne se lance pas Oui c'est ce que je compte faire pour le moment mais ce n'est pas la bonne solution en tous cas merci pour ton aide Que vous m'aspergiez d’alcool et de nourritures, que vous me crachiez à la figure, ça passe encore, mais il y as des limites !! Je ne tolère pas que l'ont maltraite un ami! - Akagami no Shanks Hors ligne malbo Re : Grub ne se lance pas Si tu n'attends plus d'aide pour ce problème, peux-tu modifier le titre de ton post #1 pour qu'il devienne : [Résolu] Grub ne se lance pas en suivant ces indications ( 5.2 Passer son sujet en [Résolu] ) : http://doc.ubuntu-fr.org/tutoriel/howto … _en_resolu Si dans l'avenir, tu réussis à avoir un multi-boot Win7/Ubuntu fonctionnel qui soit géré par Grub (je pense que ce serait grâce à une install de Ubuntu faite en UEFI mode mais moi, je ne sais pas comment il faut faire pratiquement pour ça), ce serait sympa de donner des nouvelles et des tuyaux en postant dans la présente discussion ; ça pourra servir à d'autres. MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04 Hors ligne Ayu Re : Grub ne se lance pas Oui mais j'attends toujours une solution ^^' c'est pas encore résolu vous trouvez pas ? Que vous m'aspergiez d’alcool et de nourritures, que vous me crachiez à la figure, ça passe encore, mais il y as des limites !! Je ne tolère pas que l'ont maltraite un ami! - Akagami no Shanks Hors ligne malbo Re : Grub ne se lance pas Ayu, Comme tu te rends bien compte, je ne sais pas t'aider davantage pour la solution de tes rêves mais je te recommande un chose si tu ne l'as pas déjà faite : prévois de pouvoir réinstaller Windows dans ce PC. Si tu as le DVD d'install de Win7 ou d'autres moyens d'install sur support externe (sur clé USB ou disque dur externe), c'est parfait sinon fait le nécessaire avant d'autres tentatives. MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04 Hors ligne xabilon Re : Grub ne se lance pas Je ne peux que m'incliner ... et penser que le UEFI promet de belles prises de tête sur les forums GNU/Linux. Pour passer un sujet en résolu : modifiez le premier message et ajoutez [Résolu] au titre. En ligne Ayu Re : Grub ne se lance pas malbo, Oui c'est pas grave si je dois réinstaller Win7 c'est un nouveau PC donc j'évite d'y mettre des données tant que j'ai pas regler ce problème Que vous m'aspergiez d’alcool et de nourritures, que vous me crachiez à la figure, ça passe encore, mais il y as des limites !! Je ne tolère pas que l'ont maltraite un ami! - Akagami no Shanks Hors ligne Ayu Re : Grub ne se lance pas Bonsoir, Oui j'ai toujours le problème (à chaque démarrage je go BIOS pour lancer windows) Voici le lien http://paste.ubuntu.com/769415/ En attente de votre aide. Merci d'avance. Que vous m'aspergiez d’alcool et de nourritures, que vous me crachiez à la figure, ça passe encore, mais il y as des limites !! Je ne tolère pas que l'ont maltraite un ami! - Akagami no Shanks Hors ligne YannUbuntu Re : Grub ne se lance pas Merci. - Pouvez-vous svp vérifier que dans les Options avancées de Boot-Repair, onglet "Emplacement de GRUB", il y a une case (non cochée par défaut) "Partition /boot/efi :" et qu'à sa droite il y a une liste déroulante avec uniquement "sda1" comme choix? - pouvez-vous booter sur Ubuntu, ouvrir un terminal, et indiquer le retour des commandes suivantes svp : sudo mount /dev/sda1 /mnt && ls -F /mnt ls -F /mnt/efi (liste les fichiers de sda1) Hors ligne malbo Re : Grub ne se lance pas Effectivement, l'installation s'est enrichie. Dans le post #1 on avait ça : sda3: __________________________________________________________________________ File system: ntfs Boot sector type: Windows Vista/7 Boot sector info: No errors found in the Boot Parameter Block. Operating System: Windows 7 Boot files: /Windows/System32/winload.exe A présent, dans le résultat du Boot Info script du post #19, on a ça : sda3: __________________________________________________________________________ File system: ntfs Boot sector type: Grub2 (v1.99) Boot sector info: Grub2 (v1.99) is installed in the boot sector of sda3 and looks at sector 745534560 of the same hard drive for core.img. core.img is at this location and looks for on this drive. No errors found in the Boot Parameter Block. Operating System: Windows 7 Boot files: /Windows/System32/winload.exe Grub dans le secteur de boot de la partition système de Windows, c'est pas trop bon...Heureusement que le windows 7 installé est "EFI" (et pas "Bios"), c'est à dire qu'il se fout de ce secteur de Boot parce qu'il utilise les instructions qui sont dans sda1 pour démarrer. Dernière modification par malbo (Le 14/12/2011, à 10:26) MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04 Hors ligne Ayu Re : Grub ne se lance pas Bonsoir, Oui y a bien que sda1 dans le menu déroulant. et pour les commande j'ai ça: ~$ sudo mount /dev/sda1 /mnt && ls -F /mnt EFI/ ~$ ls -F /mnt/efi Boot/ Microsoft/ Que vous m'aspergiez d’alcool et de nourritures, que vous me crachiez à la figure, ça passe encore, mais il y as des limites !! Je ne tolère pas que l'ont maltraite un ami! - Akagami no Shanks Hors ligne YannUbuntu Re : Grub ne se lance pas je peux vous aider à installer grub-efi (qui je l'espère réglera le problème) avec mes maigres connaissances sur le sujet, mais je ne garantis pas le résultat, donc par précaution svp commencez par: - sauver toutes vos données sur un support externe (disque USB ou DVD) - m'envoyer une archive TAR.GZ du contenu de la partition sda1 par email (yannubuntu ATT gmail POINT com) - m'envoyer aussi par mail une archive TAR.GZ du dossier /var/log/clean qui se trouve dans la partition Ubuntu (sda4) Hors ligne malbo Re : Grub ne se lance pas Ayu, Pas hasard, je suis tombé sur cette vidéo qui détaille minutieusement la mise à jour du Bios pour ta carte-mère : http://www.dailymotion.com/video/xmyt8x … -asus_tech Je ne sais pas si cette mise à jour du Bios pourrait améliorer la cohabitation Ubuntu/Win7 dans ton PC, mais il faut y penser. MedionPC MT5 MED MT 162 / pentium IV / RAM 1Go / Radeon HD 3450 AGP / XP, HandyLinux et Xubuntu 14.04 32 bits Acer Aspire M5100-5F7N / Phenom Quad Core 9500 / ATI HD 2600 pro / RAM 4 Go / Win8, XP et Ubuntu 14.04 Hors ligne jeanmi199 Re : Grub ne se lance pas @Ayu. Quand tu as installer windows tu as ou plutôt windows a formater ton disque en GPT au lieu de MBR (voir les options avancée a l'install de win7) ton probleme vien de la et pas de EFI. Les volume GPT sont prévu pour des disques de plus de 2,2To comme tu as un disque de 1To tu peux le formater en MBR. en tout cas dans un premier temps je ne sais pas si apres reformatage du disque en MBR l'EFI ne causera pas de problème (a creuser) mais je n'ai pas le matériel ad'hoc. Dernière modification par jeanmi199 (Le 21/12/2011, à 00:37) Hors ligne
Is it possible to specif template name in view annotation. I would like to do something like that in my views.py: instead of: def home(request, url): page = PageFactory.create_for_url(url) return render_to_response('front/home.html', {'page': page}) I would prefer to do it in this way: @view('front/home.html') def home(request, url): page = PageFactory.create_for_url(url) return {'page': page} is it doable?
Apart from asking Guido directly, I don't think your going to find any explanation of this. The syntax has been around from the very beginning. The earliest version of python sources I could find was python 1.0.1. Looking at the changelog in the Grammar file we find references to even earlier versions. In version 2 of Python (I think we're talking 2nd release after 0.9.0) we have this note: # added 'from' NAME option on import clause, and '*' to import all; This was added at the same time as # added class definition. So the import statement sprang forth at the same time as classes were added to Python. This comes from when Python was Guido van Rossum's solo project. In other words, the answer you are looking for is lost in the sands of time. Now, here's my speculation why the import statement reads from x import y rather than import y from x. The documentation for the import statement provides the basic algorithm for implementing import: Import statements are executed in two steps: (1) find a module, and initialize it if necessary; (2) define a name or names in the local namespace (of the scope where the import statement occurs). The statement comes in two forms differing on whether it uses the from keyword. The first form (without from) repeats these steps for each identifier in the list. The form with from performs step (1) once, and then performs step (2) repeatedly. In both versions of the import statement the first step of this algorithm are leftmost. I assume that this was the most obvious ordering for a language implementer, even though English might read more naturally if the order were reversed.
Topic: iRedMail in jail? Do iRedMail is working in jails? ---- Urgent issue? Pay iRedMail developer to solve it remotely at $39. Works on Red Hat Enterprise Linux, CentOS, Debian, Ubuntu, FreeBSD, OpenBSD You are not logged in. Please login or register. Do iRedMail is working in jails? ---- Sorry, you didn't explain clearly. Do you mean FreeBSD Jail? iRedMail doesn't work with it. If you're familar with Jail, patches are always welcome. Yes, I mean FreeBSD Jail. Im using this, and I read that iRedMail is not working in Jail. I have run nginx in Jail (private IP) and I know how to set up this. Can You tell me what problems You had with iRedMail in Jail? To be honest, i didn't setup Jail before. It would be nice if you can provide a detail tutorial of FreeBSD Jail, and try to make iRedMail work with Jail. Patches are always welcome. P.S. Will FreeBSD users always use Jail for network services? You can use simple tool ezjail. Tutorial: http://www.cyberciti.biz/faq/howto-setu … th-ezjail/ When You setup Your first Jail correctly then Jail will be easy for You If You haven't second public IP then You must setup NAT. Im using pf tool. Its my config (/etc/pf.conf) rdr pass on em0 proto tcp from any to em0 port 80 -> 192.168.1.2 port 80 nat on em0 from 192.168.1.0/24 to any -> 188.165.x.x em0 - my network interface 192.168.1.2 - IP of my Jail with nginx (http server) 188.165.x.x - Its my host IP. First line in pf.conf is forwarding port 80 from Jail. Second setup NAT. Its my rc.conf on host (main computer): pf_enable="YES" pf_rules="/etc/pf.conf" ifconfig_em0_alias1="inet 192.168.1.2 netmask 255.255.255.255" ezjail_enable="YES" Its rc.conf from Jail (virtual machine): rpc_bind_enable="NO" sshd_enable="YES" sendmail_enable="NO" network_interfaces="" defaultrouter="188.165.x.x" early_late_divider="NETWORKING" ifconfig_em0="inet 192.168.1.2 netmask 255.255.255.255 alias" spawn_fcgi_enable=YES mysql_enable=YES nginx_enable=YES When You setup this then try Your network connection, put command: 'ftp 87.51.34.132', in Jail ofcourse Its public FTP of FreeBSD. I don't know postfix and others stuff. Which ports are working only local, and which ports must be forwarding? I will try install iRedMail in Jail. Probably I get errors with port and IPs I will have on my way Im beginner user of FreeBSD and iRedMail. FreeBSD user not always users Jail, but I have some large websites and I want be secured that what is possible Is it possible that, installing iRedMail without Jail, then setup Jail (with ezjail or whatever), then move/convert/migrate mail server related components into Jail? I guess Jail is a little hard for FreeBSD beginners, maybe it's not a good idea to use it. Otherwise we have to provide two options for FreeBSD users: without Jail and with Jail. I have some work now. I will try on few days install and migrate iRedMail in Jail. Its hard? For script or user? After installation only one difference (from user side) is that user must "login" on jail with command: jexec ID csh, and then he can setup what he want in iRedMail. In install script must be to enter settings "network interface" and "public IP". Network interface user whose install can check this with command ifconfig. Jail solution for mail server is very secured - less ports is on "world". Only ports from smtp, pop3 and ssl smtp will be in internet, without amavisd and others. Hope to hear from you later, if possible, we can work together to make it happen, make iRedMail better. If iRedMail is for very very beginer users then I have some suggests: 1. After installation fresh FreeBSD, and install bash form ports we haven't symlink /bin/bash. So we must run command with /usr/local/bin/bash get_all.sh etc 2. You can add how to download iRedMail, my example: cd /root fetch http://iredmail.googlecode.com/files/iRedMail-0.6.1.tar.bz2 tar zxvf iRedMail-0.6.1.tar.bz2 3. When I start install script then I had some problems with postfix install: cc -DDEF_CONFIG_DIR=\"/usr/local/etc/postfix\" -DDEF_DAEMON_DIR=\"/usr/local/libexec/postfix\" - DDEF_COMMAND_DIR=\"/usr/local/sbin\" -DDEF_SENDMAIL_PATH=\"/usr/local/sbin/sendmail\" -DDEF_NEWALIAS_PATH= \"/usr/local/bin/newaliases\" -DDEF_MAILQ_PATH=\"/usr/local/bin/mailq\" -DDEF_MANPAGE_DIR=\"/usr/local/man\" - DDEF_README_DIR=\"/usr/local/share/doc/postfix\" -DDEF_HTML_DIR=\"/usr/local/share/doc/postfix\" -DDEF_QUEUE_DIR= \"/var/spool/postfix\" -DDEF_DATA_DIR=\"/var/db/postfix\" -DDEF_MAIL_OWNER=\"postfix\" -DDEF_SGID_GROUP=\"maildrop\" - DHAS_PCRE -I/usr/local/include -DUSE_SASL_AUTH -DDEF_SERVER_SASL_TYPE=\"dovecot\" -DUSE_TLS -I/usr/include - I/usr/local/include/db46 -DHAS_MYSQL -I/usr/local/include/mysql -DHAS_LDAP -I/usr/local/include -DHAS_CDB - I/usr/local/include NO -O2 -fno-strict-aliasing -pipe -DLDAP_DEPRECATED -I. -DFREEBSD8 -c alldig.c cc: NO: No such file or directory *** Error code 1 Stop in /var/ports/basejail/usr/ports/mail/postfix26/work/postfix-2.6.7/src/util. *** Error code 1 Stop in /var/ports/basejail/usr/ports/mail/postfix26/work/postfix-2.6.7. *** Error code 1 Stop in /basejail/usr/ports/mail/postfix26. *** Error code 1 Stop in /basejail/usr/ports/mail/postfix26. Im installing MySQL virtual users version, maybe install script settings wrong parameters on 'make install' in /ports/postfix26? I fix it manualy installing postfix26 with standard config options: cd /usr/ports/postfix26/ make clean make install I did add line: export status_install_port_mailpostfix26='DONE' to .iRedMail.installation.status 4. Second compilation error: ===> Installing for apache-2.2.17_1 ===> apache-2.2.17_1 depends on file: /usr/local/bin/perl5.10.1 - found ** Missing /basejail/usr/ports/www/apache22/files/apache22.in for apache-2.2.17_1. *** Error code 1 Stop in /basejail/usr/ports/www/apache22. I had this too before, on installing manualy apache on other jail (maybe its bug of FreeBSD?). Temporary I added this line to .iRedMail.installation.status: export status_install_port_wwwapache22='DONE' And I installed apache20 And end of installing i have some errors depend of apache22: < INFO > Configure User/Group: vmail. < INFO > Configure Apache web server and PHP. Can't open /usr/local/etc/apache22/httpd.conf: No such file or directory. Can't open /usr/local/etc/apache22/httpd.conf: No such file or directory. Can't open /usr/local/etc/apache22/extra/httpd-ssl.conf: No such file or directory. Can't open /usr/local/etc/apache22/extra/httpd-ssl.conf: No such file or directory. /root/iRedMail-0.6.1/./functions/apache_php.sh: line 95: /usr/local/www/apache22/data/robots.txt: No such file or directory /root/iRedMail-0.6.1/./functions/apache_php.sh: line 142: /boot/loader.conf: Read-only file system sed: /usr/local/etc/apache22/httpd.conf: No such file or directory Can't open /usr/local/etc/apache22/httpd.conf: No such file or directory. Can't open /usr/local/etc/apache22/httpd.conf: No such file or directory. Can't open /usr/local/etc/apache22/httpd.conf: No such file or directory. /root/iRedMail-0.6.1/./functions/apache_php.sh: line 158: /usr/local/etc/apache22/httpd.conf: No such file or directory /root/iRedMail-0.6.1/./functions/apache_php.sh: line 159: /usr/local/etc/apache22/httpd.conf: No such file or directory Can't open /usr/local/etc/apache22/httpd.conf: No such file or directory. < INFO > Configure Postfix. < Backup > /usr/local/etc/postfix/main.cf -> main.cf.2010.11.07.14.28.18. < Backup > /usr/local/etc/postfix/master.cf -> master.cf.2010.11.07.14.28.18. < Backup > /etc/mail/mailer.conf -> mailer.conf.2010.11.07.14.28.18. < INFO > Configure Policyd (postfix policy daemon). < INFO > Configure Dovecot (pop3/imap server). < Backup > /usr/local/etc/dovecot.conf -> dovecot.conf.2010.11.07.14.28.18. < INFO > Configure Procmail (MDA). < INFO > Configure ClamAV (anti-virus toolkit). < INFO > Configure Amavisd-new. < Backup > /usr/local/etc/amavisd.conf -> amavisd.conf.2010.11.07.14.28.18. < Backup > /usr/local/etc/amavisd.conf -> amavisd.conf.2010.11.07.14.28.18. < INFO > Configure SpamAssassin (content-based spam filter). < INFO > Configure Roundcube webmail. /root/iRedMail-0.6.1/./functions/roundcubemail.sh: line 218: /usr/local/etc/apache22/Includes/roundcubemail.conf: No such file or directory Can't open /usr/local/etc/apache22/extra/httpd-ssl.conf: No such file or directory. Can't open /usr/local/etc/apache22/extra/httpd-ssl.conf: No such file or directory. Can't open /usr/local/etc/apache22/extra/httpd-ssl.conf: No such file or directory. < INFO > Configure phpMyAdmin (web-based MySQL management tool). /root/iRedMail-0.6.1/./functions/phpmyadmin.sh: line 27: /usr/local/etc/apache22/Includes/phpmyadmin.conf: No such file or directory Can't open /usr/local/etc/apache22/extra/httpd-ssl.conf: No such file or directory. Can't open /usr/local/etc/apache22/extra/httpd-ssl.conf: No such file or directory. < INFO > Configure PostfixAdmin (web-based mail account management tool). /root/iRedMail-0.6.1/./functions/postfixadmin.sh: line 33: /usr/local/etc/apache22/Includes/postfixadmin.conf: No such file or directory Can't open /usr/local/etc/apache22/extra/httpd-ssl.conf: No such file or directory. < INFO > Configure Awstats (logfile analyzer for mail and web server). /root/iRedMail-0.6.1/./functions/awstats.sh: line 39: /usr/local/etc/apache22/Includes/awstats.conf: No such file or directory /root/iRedMail-0.6.1/./functions/awstats.sh: line 48: /usr/local/etc/apache22/Includes/awstats.conf: No such file or directory /root/iRedMail-0.6.1/./functions/awstats.sh: line 78: /usr/local/etc/apache22/Includes/awstats.conf: No such file or directory Can't open /usr/local/etc/apache22/httpd.conf: No such file or directory. /root/iRedMail-0.6.1/./functions/awstats.sh: line 94: /usr/local/etc/apache22/Includes/awstats.conf: No such file or directory /root/iRedMail-0.6.1/./functions/awstats.sh: line 141: /usr/local/etc/apache22/Includes/awstats.conf: No such file or directory Can't open /usr/local/etc/apache22/extra/httpd-ssl.conf: No such file or directory. Can't open /usr/local/etc/apache22/extra/httpd-ssl.conf: No such file or directory. < Backup > /usr/local/www/awstats/cgi-bin/awstats.model.conf -> awstats.model.conf.2010.11.07.14.28.18. iRedMail is installed now. I will check this. I write report later Okay. First test results: - On forwarding port 110 mail is working, its mean I can login to mail from MS Outlook. - I can't sent mail from my mail, maillog: Nov 7 15:24:55 poczta postfix/trivial-rewrite[78478]: fatal: proxy:mysql:/usr/local/etc/postfix/mysql_virtual_mailbox_domains.cf(0,lock|fold_fix): table lookup problem Nov 7 15:24:56 poczta postfix/smtpd[78327]: warning: problem talking to service rewrite: Unknown error: 0 Nov 7 15:24:56 poczta postfix/master[72462]: warning: process /usr/local/libexec/postfix/trivial-rewrite pid 78478 exit status 1 Nov 7 15:24:56 poczta postfix/master[72462]: warning: /usr/local/libexec/postfix/trivial-rewrite: bad command startup -- throttling And other: Nov 7 15:24:39 poczta postfix/proxymap[78328]: warning: connect to mysql server 127.0.0.1: Host '192.168.1.1' is not allowed to connect to this MySQL server I tried sent e-mail from outer mail (free mail hosting) - not working. Can You me tell which ports must me "open on internet"? I don't know how this software working too good. I know that I must forwarding from jail port 25 (smtp) and 110 (pop3). Its all? Here is port list: http://www.iredmail.org/forum/topic209- … ports.html Nov 7 15:24:55 poczta postfix/trivial-rewrite[78478]: fatal: proxy:mysql:/usr/local/etc/postfix/mysql_virtual_mailbox_domains.cf(0,lock|fold_fix): table lookup problem Seems Postfix can't connect to MySQL. Maybe you can try to connect MySQL via TCP/IP instead of local unix socket? Im installing MySQL virtual users version, maybe install script settings wrong parameters on 'make install' in /ports/postfix26? All config options are set in /var/db/ports/postfix/options. Can you help check them? Its options: WITH_PCRE=true WITHOUT_SASL2=true WITH_DOVECOT=true WITHOUT_SASLKRB=true WITHOUT_SASLKRB5=true WITHOUT_SASLKMIT=true WITH_TLS=true WITH_BDB=true WITH_MYSQL=true WITHOUT_PGSQL=true WITH_OPENLDAP=true WITH_CDB=true WITHOUT_NIS=true WITHOUT_VDA=true WITHOUT_TEST=true But I can try disable something. WITH_TLS=true WITH_BDB=true WITH_OPENLDAP=true WITH_CDB=true Its needed for working of iRedMail? Seems Postfix can't connect to MySQL. I was set: 192.168.1.1<---><------><------>localhost localhost.my.domain in /ets/hosts and this error is fixed I dont know why but my amavid wasn't started. I start him manually. And next error: Nov 7 16:38:34 poczta amavis[85011]: (!)DENIED ACCESS from IP 192.168.1.1, policy bank '' Nov 7 16:38:34 poczta postfix/smtp[84875]: CA9371B27E03: to=<qwerty232323@o2.pl>, relay=127.0.0.1[127.0.0.1]:10024, delay=0.43, delays=0.43/0/0/0, dsn=4.4.2, st atus=deferred (lost connection with 127.0.0.1[127.0.0.1] while receiving the initial server greeting) Nov 7 16:38:36 poczta postfix/smtpd[78327]: disconnect from bqm10.neoplus.adsl.tpnet.pl[83.29.80.10] I will ask on FreeBSD forum how to setup something like alias 127.0.0.1 for 192.168.1.1. But other way - we can change IP in /postfix/main.cf i think. I tried to install iRedMail again. I fix problems with apache22 (its error in mail port tree). Still I have error with install postfix26. I cant install this from install script but I can install this with commands: cd /usr/ports/mail/postfix26 make clean make install clean (without make config) I dont know bash scripts etc, i cant find source of this problem. But something else interesing me... when installing is finishing its looking that: daily.cld updated (version: 12213, sigs: 144965, f-level: 53, builder: arnaud) Downloading bytecode.cvd [100%] bytecode.cvd updated (version: 89, sigs: 10, f-level: 53, builder: edwin) Database updated (849702 signatures) from database.clamav.net (IP: 193.218.105.9) WARNING: Clamd was NOT notified: Can't connect to clamd through /var/run/clamav/clamd.sock connect(): No such file or directory kldload: can't load accf_http: Operation not permitted Start: not found Stopping mysql. Waiting for PIDS: 95112. Starting mysql. Start: not found dovecot not running? (check /var/run/dovecot/master.pid). Starting dovecot. If you have trouble with authentication failures, enable auth_debug setting. See http://wiki.dovecot.org/WhyDoesItNotWork This message goes away after the first successful login. Start: not found amavisd not running? Starting amavisd. Start: not found postfix/postfix-script: fatal: the Postfix mail system is not running postfix/postfix-script: starting the Postfix mail system Start: not found postfix_policyd_sf not running? (check /var/run/postfix-policyd-sf.pid). Starting postfix_policyd_sf. Start: not found clamav_clamd not running? Starting clamav_clamd. Start: not found clamav_freshclam not running? (check /var/run/clamav/freshclam.pid). Starting clamav_freshclam. Start: not found Performing sanity check on apache22 configuration: Syntax OK apache22 not running? (check /var/run/httpd.pid). Performing sanity check on apache22 configuration: Syntax OK Starting apache22. A lot of errors. Its normal Zhang? WITH_TLS=true WITH_BDB=true WITH_OPENLDAP=true WITH_CDB=true Its needed for working of iRedMail? WITH_OPENLDAP=true is optional if you use MySQL to store virtual mail accounts. But if you want to migrate from MySQL to OpenLDAP, you don't need to re-compile it. It's up to you. TLS, BDB, CDB are required. I cant install this from install script but I can install this with commands: cd /usr/ports/mail/postfix26 make clean make install clean (without make config) I don't know why it happened. In early edition of iRedMail, with older FreeBSD ports tree, it works well. I didn't change any config options, that make me confused. Start: not found Not sure why it raises this error message. Temporary I added host % to user vmail in MySQL and I added/modified this lines in amavisd.conf @inet_acl = qw( 127.0.0.1 192.168.1.1 ); # allow SMTP access only from localhost @mynetworks = qw( 192.168.1.1 127.0.0.0/8 [::1] [FE80::]/10 [FEC0::]/10 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 ); postfix/main.cf mynetworks = 127.0.0.0/8, 192.168.1.1 content_filter = smtp-amavis:[192.168.1.1]:10024 postfix/master.cf 192.168.1.1:10025 inet n - - - - smtpd -o mynetworks=127.0.0.0/8, 192.168.1.1 And I haven't more errors with MySQL and amavisd. But I have other errors: Nov 8 11:30:44 poczta amavis[79513]: (79513-02-2) (!)rw_loop: leaving rw loop, no progress, last event (select) 35.005 s ago Nov 8 11:30:44 poczta amavis[79513]: (79513-02-2) (!)FWD via SMTP: <www@poczta.host.org> -> <qwerty232323@o2.pl>, 451 4.5.0 From MTA([127.0.0.1]:10025) during fwd-connect (Negative greeting: at (eval 114) line 596, <GEN19> line 384.): id=79513-02-2 Nov 8 11:30:44 poczta amavis[79513]: (79513-02-2) Blocked MTA-BLOCKED, LOCAL [83.29.80.10] [83.29.80.10] <www@poczta.host.org> -> <qwerty232323@o2.pl>, Message-ID: <008701cb7f38$01639270$042ab750$@alfaholic y.org>, mail_id: phIcgmojyCwn, Hits: -9.998, size: 2685, 57058 ms Nov 8 11:30:44 poczta postfix/smtp[79491]: 27B201B27EBC: to=<qwerty232323@o2.pl>, relay=192.168.1.1[192.168.1.1]:10024, conn_use=2, delay=149, delays=0.6/92/0/57, dsn=4.5.0, status=deferred (host 192.168.1.1[192. 168.1.1] said: 451 4.5.0 id=79513-02-2 - Temporary MTA failure on relaying, From MTA([127.0.0.1]:10025) during fwd-connect (Negative greeting: at (eval 114) line 596, <GEN19> line 384.): id=79513-02-2 (in reply t o end of DATA command)) Nov 8 11:30:51 poczta postfix/smtpd[79677]: fatal: unexpected command-line argument: 192.168.1.1 Nov 8 11:30:51 poczta postfix/smtpd[79678]: fatal: unexpected command-line argument: 192.168.1.1 Nov 8 11:30:52 poczta postfix/master[79487]: warning: process /usr/local/libexec/postfix/smtpd pid 79677 exit status 1 Nov 8 11:30:52 poczta postfix/master[79487]: warning: /usr/local/libexec/postfix/smtpd: bad command startup -- throttling Nov 8 11:30:52 poczta postfix/master[79487]: warning: process /usr/local/libexec/postfix/smtpd pid 79678 exit status 1 I can't found on Google where problem is. Maybe You know? Nov 8 11:30:44 poczta amavis[79513]: (79513-02-2) (!)FWD via SMTP: <www@poczta.host.org> -> <qwerty232323@o2.pl>, 451 4.5.0 From MTA([127.0.0.1]:10025) during fwd-connect (Negative greeting: at (eval 114) line 596, <GEN19> line 384.): id=79513-02-2 Nov 8 11:30:44 poczta amavis[79513]: (79513-02-2) Blocked MTA-BLOCKED, LOCAL [83.29.80.10] [83.29.80.10] <www@poczta.host.org> -> <qwerty232323@o2.pl>, Message-ID: <008701cb7f38$01639270$042ab750$@alfaholic y.org>, mail_id: phIcgmojyCwn, Hits: -9.998, size: 2685, 57058 ms Not sure why it happened. Please ask in amavisd mail list: http://www.ijs.si/software/amavisd/#support Do you have these two settings in amavisd.conf? $notify_method = 'smtp:[127.0.0.1]:10025'; $forward_method = 'smtp:[127.0.0.1]:10025'; Try to replace '127.0.0.1', restart amavisd service and test again. Zhang this solution don't working. But I turned off amavisd temporary and sending mails is working We are close to make this working I found solution. Nov 8 11:30:51 poczta postfix/smtpd[79677]: fatal: unexpected command-line argument: 192.168.1.1 Its mean that errors is here: -o mynetworks=127.0.0.0/8, 192.168.1.1 Peoples from BSD dont replied on my answer about my problems with 127.0.0.1. But seding mails with amavisd is working when I replace 127.0.0.1 to 192.168.1.1 I will try install new jail again and I will configuring all fine from begining - I write something what I must do That's cool. Waiting for your tutorial. Maybe you can write in our wiki directly? http://iredmail.org/wiki/ I will be very proud, but my english is very simple. Can I post on forum and You will be reword my text? I don't want post on wiki something writing like 12 years old child Posting in forum is ok too. Don't worry about your English Currently installed 3 official extensions. Copyright © 2003–2009 PunBB. Generated in 0.057 seconds (90% PHP - 10% DB) with 11 queries
I'm wondering about the differences between inheritance and composition examined with concrete code relevant arguments. In particular my example was Inheritance: class Do: def do(self): self.doA() self.doB() def doA(self): pass def doB(self): pass class MyDo(Do): def doA(self): print("A") def doB(self): print("B") x=MyDo() vs Composition: class Do: def __init__(self, a, b): self.a=a self.b=b def do(self): self.a.do() self.b.do() x=Do(DoA(), DoB()) (Note for composition I'm missing code so it's not actually shorter) Can you name particular advantages of one or the other? I'm think of: composition is useful if you plan to reuse DoA() in another context inheritance seems easier; no additional references/variables/initialization method doA can access internal variable (be it a good or bad thing :) ) inheritance groups logic A and B together; even though you could equally introduce a grouped delegate object inheritance provides a preset class for the users; with composition you'd have to encapsule the initialization in a factory so that the user does have to assemble the logic and the skeleton ... Basically I'd like to examine the implications of inheritance vs composition. I heard often composition is prefered, but I'd like to understand that by example. Of course I can always start with one and refactor later to the other.
Announcement Unanswered posts Hi, I have an java project which gets data from remote SAP, then I want to implement it with Talend. In Talend I used tSapConnection and tSAPInput, and tLibraryLoad to load sapjco.jar lib. The connection is OK but after I met error, "JCO_ERROR_FIELD_NOT_FOUND : Field CHECKPOINT not a member of INPUT". I checked the original java code, and found that two input parameters are needed, the first is "BATCHHINT", it is set using getImportParameterList().setValue(string, int). The second is "CHECKPOINT", which is set by getChangingParameterList().setValue(string, int). But in Talend after I set the "Initialize input" of tSAPInput,(I added two rows in the 'initialize input' table, one named "BATCHHINT and one named "CHECKPOINT") and then switched to code view, both "BATCHHINT" and "CHECKPOINT" are set with getImportParameterList().setValue(string, int), I think this should be the reason of errors. So how can I set the input of tSAPInput to set the changing parameter? Any suggestions will be appreciated. My environment: Talend TOS 4.2.3 + sapjco3.jar + sapjco3.dll regards, Hi I think you didn't configure Initialize input and Outputs of tSAPInput correctly. Have you read the scenarios about tSAPInput in the document [TalendOpenStudio_Components_RG_xxx_EN]? Regards, Pedro Only Paranoid Survive. Thanks a lot for your reply, Pedro. I read the book but it has just a small part about tSAPInput. In fact, I looked into the code for some while and found that I was wrong, it is not the problem of parameters. Even I delete the parameter "CHECKPOINT" in the input table of tSAPinput I still got the same error. "com.sap.conn.jco.JCoRuntimeException: (127) JCO_ERROR_FIELD_NOT_FOUND : Field CHECKPOINT not a member of INPUT" In the java code I found one line: resumeUtil.addLog("CHECKPOINT", "CONNECTION:SUBJOB_OK:tLibraryLoad_1:OnSubjobOk", "", Thread.currentThread().getId() + "", "", "", "", "", ""); it has nothing to do with my configuration of tSAPInput, once I add this component this line appears. Does any one know what "CHECKPOINT" keyword in this line is used for? Thanks in advance Hi First, I think these codes are not the root reason which caused this error. resumeUtil.addLog("CHECKPOINT", "CONNECTION:SUBJOB_OK:tLibraryLoad_1:OnSubjobOk", "", Thread.currentThread().getId() + "", "", "", "", "", ""); Have you tried to create a new job? Not simply delete the parameter CHECKPOINT? Then could you upload the images about this job and the settings of tSAPInput? Regards, Pedro Only Paranoid Survive. Thanks Pedro, You are right, it is not the root reason. I create a new job and found that once I use the component "tLibraryLoad", that code line I mentioned ( resumeUtil.addLog("CHECKPOINT",....) ) appears. Then I modified directly the function I called in SAP system and change both "BATCHINT" and "CHECKPOINT" into unchanged parameter, after that my original job works. (well, at least it has no errors in the input process) euh.. sorry then I met another problem com.sap.conn.jco.JCoRuntimeException: (127) JCO_ERROR_FIELD_NOT_FOUND : Field DATA not a member of OUTPUT at com.sap.conn.jco.rt.AbstractMetaData.indexOf(AbstractMetaData.java:384) at com.sap.conn.jco.rt.AbstractRecord.getTable(AbstractRecord.java:2941) at com.sap.conn.jco.rt.AbstractRecord.getTable(AbstractRecord.java:52) at newproject.sapconnjob_0_1.SapConnJob.tSAPInput_1Process(SapConnJob.java:720) at newproject.sapconnjob_0_1.SapConnJob.tSAPConnection_1Process(SapConnJob.java:351) at newproject.sapconnjob_0_1.SapConnJob.runJobInTOS(SapConnJob.java:1090) at newproject.sapconnjob_0_1.SapConnJob.main(SapConnJob.java:958) "Data" is the table returned from remote function, I checked the java codes created by Talend, and found that this table is got from this code line, "com.sap.conn.jco.JCoTable table_registros_devueltos_tSAPInput_1 exportParameterList_tSAPInput_1.getTable("DATA");" where "exportParameterList_tSAPInput_1" is got from "com.sap.conn.jco.JCoParameterList exportParameterList_tSAPInput_1 = function_tSAPInput_1.getExportParameterList();" I wrote several java codes in eclipse for testing this remote function, when I use the list got by "getTableParameterList" rather than "getExportParameterList" to get the table "DATA", it will work with no errors. So I wonder whether I can modify my configuration in output of "tInSAPInput" to make the codes it generated use "getTableParameterList" but not "getExportParameterList". My setting can be seen in my configurtion attached. Regards, Felix Hi In fact, you might try to modify the source code of this component by using your own code. Besides, if you use tSAPConnection, you need to add tSAPCommit at the end of this job. Regards, Pedro Only Paranoid Survive.
Akamine Impossible d'accéder au menu "Pilotes additionnels" Bonjour, J'ai récemment installé Steam pour Linux. Sur le wiki associé ils demandent des mises à jour des pilotes additionnels, seulement impossible d'accéder au menu "Pilotes additionnels", Ubuntu rencontre une erreur que ce soit après plusieurs reboot, avec différents environnements de bureau (unity, gnome). Je n'ai pas trouvé de méthode simple sur console sur internet (lire plusieurs pages de lignes commentées en anglais alors que je ne sais même pas s'il s'agit du même problème...). Je prends toute méthode me permettant d'installer ces nouveaux pilotes pour jouer à TF2 sur Linux, que ce soit en mode graphique ou console (la méthode hein, TF2 en console j'y crois moyen perso). Merci d'avance ! EDIT : Je suis sous Ubuntu 12.04LTS Dernière modification par Akamine (Le 28/12/2012, à 15:31) Hors ligne Kanor Re : Impossible d'accéder au menu "Pilotes additionnels" Bonjour Tu a quel version d'ubuntu ? ta question c'est que tu ne trouve pas comment accéder au menu "pilotes additionnels" si tu a la version 12.10 va dans le panneau de configuration clique sur Source de logiciel (en bas) et sur l'onglet Pilotes additionnels Hors ligne Akamine Re : Impossible d'accéder au menu "Pilotes additionnels" Ubuntu 12.04LTS. Trouver le menu n'est pas un souci, le problème est qu'il ne se passe rien quand je clique. Ubuntu rencontre une erreur, et ce, que j'y accède depuis les paramètres ou directement en recherchant dans le menu Unity. Hors ligne Kanor Re : Impossible d'accéder au menu "Pilotes additionnels" si je me trompe pas dans cette version la commande pour lancer cette outil est jockey-gtk est ce que tu peux le lancer dans un terminal pour que tu puise coller l'erreur ici ? Hors ligne Akamine Re : Impossible d'accéder au menu "Pilotes additionnels" auclair@Akamine:~$ jockey-gtk (jockey-gtk:9260): Gtk-CRITICAL **: gtk_icon_set_render_icon_pixbuf: assertion `icon_set != NULL' failed (jockey-gtk:9260): Gtk-CRITICAL **: gtk_icon_set_render_icon_pixbuf: assertion `icon_set != NULL' failed Traceback (most recent call last): File "/usr/bin/jockey-gtk", line 418, in <module> sys.exit(u.run()) File "/usr/lib/python2.7/dist-packages/jockey/ui.py", line 468, in run self.ui_show_main() File "/usr/bin/jockey-gtk", line 94, in ui_show_main self.update_tree_model() File "/usr/bin/jockey-gtk", line 275, in update_tree_model info = self.get_ui_driver_info(h_id) File "/usr/lib/python2.7/dist-packages/jockey/ui.py", line 295, in get_ui_driver_info info = self.backend().handler_info(handler_id) File "/usr/lib/python2.7/dist-packages/dbus/proxies.py", line 145, in __call__ **keywords) File "/usr/lib/python2.7/dist-packages/dbus/connection.py", line 651, in call_blocking message, timeout) dbus.exceptions.DBusException: org.freedesktop.DBus.Python.TypeError: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/dbus/service.py", line 751, in _message_cb _method_reply_return(connection, message, method_name, signature, *retval) File "/usr/lib/python2.7/dist-packages/dbus/service.py", line 254, in _method_reply_return reply.append(signature=signature, *retval) TypeError: Expected a string or unicode object Hors ligne Akamine Re : Impossible d'accéder au menu "Pilotes additionnels" Après 5min il ne se passe toujours rien, il ne fait que ca : auclair@Akamine:~$ jockey-text Pilotes additionnels Recherche des pilotes disponibles... auclair@Akamine:~$ Hors ligne Akamine Re : Impossible d'accéder au menu "Pilotes additionnels" Penses-tu qu'il est raisonnable de tenter un sudo apt-get remove jockey-gtk et de le reinstaller ensuite ? Hors ligne Akamine Re : Impossible d'accéder au menu "Pilotes additionnels" Pas de changement après la procédure. Hors ligne Kanor Re : Impossible d'accéder au menu "Pilotes additionnels" je reviens à ton probléme essaye ça jockey-text --list si tu a un bug tu peux essayer ça sudo jockey-text --list --no-dbus dans les deux cas donne le retour des commandes. Hors ligne Akamine Re : Impossible d'accéder au menu "Pilotes additionnels" auclair@Akamine:~$ jockey-text --list firmware:dvb_usb - Micro-logiciel pour les cartes DVB (Propriétaire, Désactivé, Non utilisé) Traceback (most recent call last): File "/usr/bin/jockey-text", line 128, in <module> sys.exit(u.run()) File "/usr/lib/python2.7/dist-packages/jockey/ui.py", line 421, in run self.list() File "/usr/lib/python2.7/dist-packages/jockey/ui.py", line 477, in list i = self.backend().handler_info(h_id) File "/usr/lib/python2.7/dist-packages/dbus/proxies.py", line 145, in __call__ **keywords) File "/usr/lib/python2.7/dist-packages/dbus/connection.py", line 651, in call_blocking message, timeout) dbus.exceptions.DBusException: org.freedesktop.DBus.Python.TypeError: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/dbus/service.py", line 751, in _message_cb _method_reply_return(connection, message, method_name, signature, *retval) File "/usr/lib/python2.7/dist-packages/dbus/service.py", line 254, in _method_reply_return reply.append(signature=signature, *retval) TypeError: Expected a string or unicode object Hors ligne Akamine Re : Impossible d'accéder au menu "Pilotes additionnels" Problème résolu après 2 désinstallation réinstallation, une par teminal et l'autre par la logitheque. Hors ligne
I have the following string which forces my phython script to quit: "625 625 QUAIL DR UNIT B" I need to delete the extra spaces in the middle of the string so I am trying to use the following split join script: import arcgisscripting import logging logger = logging.getLogger() gp = arcgisscripting.create(9.3) gp.OverWriteOutput = True gp.Workspace = "C:\ZP4" fcs = gp.ListWorkspaces("*","Folder") for fc in fcs: print fc rows = gp.UpdateCursor(fc + "//Parcels.shp") row = rows.Next() while row: Name = row.GetValue('SIT_FULL_S').join(s.split()) print Name row.SetValue('SIT_FULL_S', Name) rows.updateRow(row) row = rows.Next() del row del rows
Componenti e plugin I componenti ed i plugin sono funzionalità relativamente nuove di web2py e c'è ancora disaccordo tra gli sviluppatori su cosa siano e cosa dovrebbero essere. La maggior parte della confusione è generata dall'uso che si fa di questi termini in altri progetti software e dal fatto che gli sviluppatori stiano ancora lavorando per definirne le specifiche. Queste comunque sono funzionalità importanti di web2py ed è quindi necessario fornire una definizione che sebbene non definitiva sia consistente con gli schemi di programmazione discussi in questo capitolo e che affrontano le seguenti due problematiche: Come costruire applicazioni modulari che riducano il carico del server e massimizzino il riutilizzo del codice. Come distribuire parti di codice in un modo il più possibile immediato (plugin-and-play). I componenti affrontano il primo problema; i plugin affrontano il secondo. Componenti Uncomponenteè una parte funzionalmente autonoma di una pagina web. Un componente può essere composto di moduli, controller e viste. Un componente non ha nessun prerequisito particolare, se non quello di poter essere inserito in un singolo tag di una pagina web (per esempio un DIV, uno SPAN o un IFRAME) dove esegue il suo compito indipendentemente dal resto della pagina. I componenti sono caricati nella pagina e comunicano con il controller tramite Ajax. Un esempio di componente è un "componente per i commenti" che è contenuto in un DIV e mostra i commenti degli utenti insieme ad un form per l'invio di un nuovo commento. Quando il form è compilato viene inviato al server tramite una chiamata Ajax, la lista viene aggiornata e il commento è memorizzato dal server nel database. Alla fine il contenuto del DIV è aggiornato senza ricaricare il resto della pagina. La funzione LOAD di web2py rende questo compito estremamente semplice da eseguire senza nessuna conoscenza della programmazione Javascript o Ajax. L'obiettivo è quello di riuscire a sviluppare un'applicazione web assemblando i componenti nelle pagine. Con una semplice applicazione "test" che estende l'applicazione di default con il seguente modello "models/db_comments.py": db.define_table('comment', Field('body','text',label='Your comment'), Field('posted_on','datetime',default=request.now), Field('posted_by',db.auth_user,default=auth.user_id)) db.comment.posted_on.writable=db.comment.posted_on.readable=False db.comment.posted_by.writable=db.comment.posted_by.readable=False e con un'azione nel "controllers/comments.py" definita come: @auth.requires_login() def post(): return dict(form=crud.create(db.comment), comments=db(db.comment.id>0).select()) e con la corrispondente vista in "views/comments/post.html": {{extend 'layout.html'}} {{for comment in comments:}} <div class="comment"> on {{=comment.posted_on}} {{=comment.first_name}} says <span class="comment_body">{{=comment.body}}</span> </div> {{pass}} {{=form}} si può accedere all'azione all'indirizzo: http://127.0.0.1:8000/test/comments/post [image] Per ora non c'è nulla di speciale in questa azione ma è possibile trasformarla in un componente semplicemente definendo una nuova vista con estensione ".load" che non estende il layout. Ecco il contenuto di "views/comments/post.load": {{#extend 'layout.html' <- notice this is commented out!}} {{for comment in comments:}} <div class="comment"> on {{=comment.posted_on}} {{=comment.first_name}} says <span class="comment_body">{{=comment.body}}</span> </div> {{pass}} {{=form}} E' possibile accedere a questa vista con l'URL: http://127.0.0.1:8000/test/comments/post.load e sarà visualizzata come: [image] Questo è un componente che può essere inserito in ogni altra pagina semplicemente con: {{=LOAD('comments','post.load',ajax=True)}} Per esempio si può aggiungere nel controller "controllers/default.py": def index(): return dict() e nella vista corrispondente si può aggiungere il componente: {{extend 'layout.html'}} <h1>{{='bla '*100}}</h1> {{=LOAD('comments','post.load',ajax=True)}} Accedendo alla pagina http://127.0.0.1:8000/test/default/index sarà mostrato il contenuto normale e il componente dei commenti: [add image] Il componente {{=LOAD( ... )}} è visualizzato tramite il seguente HTML: <script type="text/javascript"><!-- web2py_component("/test/comment/post.load","c282718984176") //--></script><div id="c282718984176">loading...</div> (il codice effettivamente generato dipende dalle opzioni passate alla funzione LOAD). La funzione web2py_component(url,id) è definita in "views/web2py_ajax.html" ed esegue tutte le operazioni necessarie: chiama la url tramite Ajax e inserisce la risposta nel DIV con l'id corrispondente; intercetta ogni invio del form nel DIV e lo invia tramite Ajax. Il target Ajax è sempre lo stesso DIV. La sintassi completa dell'helper LOAD è il seguente: LOAD(c=None, f='index', args=[], vars={}, extension=None, target=None, ajax=False, ajax_trap=False, url=None): Dove: i primi due argomenti cefsono il controller e la funzione che si vuole chiamare. argsevarssono gli argomenti che si vuol passare alla funzione. Il primo è una lista, il secondo è un dizionario. extensionè una estensione opzionale. Notare che l'estensione può anche essere passata come parte della funzione (come, per esempiof='index.load'). targetè l'iddel DIV. Se non è specificato verrà generato unidcasuale. ajaxdeve essere impostato aTruese il DIV deve essere riempito tramite una chiamata Ajax e deve essere impostato aFalsese il DIV deve essere riempito prima che la pagina sia ritornata (evitando così la chiamata Ajax). ajax_trap=Truesignifica che ogni invio del form nel DIV deve essere catturato ed inviato tramite Ajax e che la risposta deve essere inserita nel DIV.ajax_trap=Falsesignifica che il form deve essere inviato normalmente, ricaricando l'intera pagina.ajax_trapè ignorato e consideratoTruenel caso cheajax=True. url, se specificato, ignora i valori dic,f,args,varsedextensione carica il componente allaurlindicata. Questo parametro è utilizzato per caricare un componente da un'altra applicazione (non necessariamente creata con web2py). Se non è specificata nessuna vista .load viene utilizzata la vista generic.load che visualizza senza layout il dizionario ritornato dall'azione. Questa vista generica funziona meglio se il dizionario contiene un singolo elemento. Se si carica un componente con estensione .load e la relativa azione reindirizza ad un'altra azione (per esempio per il login), l'estensione .load viene propagata alla nuova URL (quella a cui si viene reindirizzati) che viene caricata con l'estensione .load. Quando un'azione di un componente è chiamata tramite Ajax web2py passa due header HTTP aggiuntivi con la richiesta: web2py-component-location web2py-component-element che possono essere acceduti nell'azione tramite le variabili: request.env.http_web2py_component_locationrequest.env.http_web2py_component_element Il primo contiene la URL della pagina che ha chiamato l'azione del componente. Il secondo contiene l'id del DIV che conterrà la risposta. L'azione del componente può anche memorizzare informazioni in due header speciali che saranno interpretati dalla pagina completa durante la risposta: web2py-component-flash web2py-component-command e possono essere acceduti tramite: response.headers['web2py-component-flash']='....' response.headers['web2py-component-command']='...' Il primo contiene del test che deve apparire nel messaggio alla risposta. Il secondo contiene codice Javascript che si vuole far eseguire alla risposta. Non può contenere il carattere di ritorno a capo. Come esempio ecco un componente per la richiesta di un form di contatti. L'azione in "controllers/contact/ask.py" consente all'utente di porre una domanda che il componente invierà all'amministratore tramite email. Infine visualizza il messaggio "thank you" e rimuove il componente dalla pagina: def ask(): form=SQLFORM.factory( Field('your_email',requires=IS_EMAIL()), Field('question',requires=IS_NOT_EMPTY())) if form.accepts(request.vars,session): if mail.send(to='admin@example.com', subject='from %s' % form.vars.your_email, message = form.vars.question): div_id = request.env.http_web2py_component_element command="jQuery('#%s').hide()" % div_id response.headers['web2py-component-command']=command response.headers['web2py-component-flash']='thanks you' else: form.errors.your_email="Unable to send the email" return dict(form=form) Le prime quattro linee definiscono il form e lo validano. L'oggetto mail utilizzato per inviare la domanda è definito nell'applicazione di default. Le ultime quattro linee implementano tutta la logica specifica del componente leggendo i dati dagli header della richiesta HTTP ed impostando gli header HTTP nella risposta. Ora è possibile inserire questo form in qualsiasi pagina con: {{=LOAD('contact','ask.load',ajax=True)}} Notare che non è stata definita nessuna vista .load per il componente ask. Questo non è necessario perchè il componente ritorna un solo oggetto (form) e per questo è sufficiente la vista "generic.load". Quando è usata la vista "generic.load" si può utilizzare la sintassi: response.flash='...' che è equivalente a: response.headers['web2py-component-flash']='...' Plugin Unpluginè un sotto-insieme di qualsiasi file di un'applicazione. e si intende realmente "qualsiasi": Un pluginnon è un modulo, non è un modello, non è un controller e nemmeno una vista, ma può contenere moduli, modelli, controllers e viste. Un pluginnon deve essere funzionalmente autonomo e può dipendere da altri plugin o codice specifico. Un pluginnon è unsistema di pluginpertanto i plugin non sono nè "registrati" nè "isolati" sebbene esistano delle regole per mantenere un certo isolamento. In questo capitolo si parla di plugin per l'applicazione non plugin per web2py. Perchè questa funzionalità è chiamata plugin? Perchè rende disponibile un meccanismo per includere un sotto-insieme di un'applicazione in un'altra applicazione. Da questa prospettiva qualsiasi file di un'applicazione può essere considerato un plugin. Quando un'applicazione viene distribuita i suoi plugin sono "impacchettati" e distribuiti con essa. In pratica l'applicazione admin fornisce un'interfaccia per impacchettare e spacchettare i plugin separatamente dall'applicazione. I file e le cartelle dell'applicazione che hanno nomi che iniziano con plugin_name possono essere impacchettati insieme in un file chiamato: web2py.plugin.name.w2p e distribuiti insieme. [ADD IMAGE] I file che compongono un plugin non sono trattati da web2py in modo differente da ogni altro file tranne per il fatto che admin comprende (dai loro nomi) che devono essere distribuiti insieme e li visualizza in una pagina separata: [ADD IMAGE] Per la definizione di plugin data all'inizio di questo capitolo i plugin hanno un utilizzo più ampio oltre al fatto di essere riconosciuti dall'applicazione admin. In pratica in web2py si possono utilizzare due tipi di plugin: plugin di componenti. Sono plugin che contengono componenti, come definiti nella sezione precedente. Un plugin di componenti può contenerne uno o più di uno. Per esempio potrebbe esistere unplugin_commentsche contiene il componentecommentsdella sezione precedente. Un altro esempio potrebbe essereplugin_taggingche contiene un componentetagginged un componentetag-cloudche condividono alcune tabelle di database definite dal plugin stesso. plugin di layout. Sono plugin che contengono le viste per un layout e i file statici necessari al layout stesso. Quando il plugin è applicato all'applicazione le dà un look differente. In base alle definizioni precedenti i componenti creati nella precedente sezione, come per esempio "controllers/contact.py", sono già considerati plugin. Possono essere spostati da un'applicazione ad un'altra per utilizzare i componenti che definiscono. Non sono però riconosciuti come plugin dall'applicazione admin perchè non c'è nulla che li etichetta come plugin. Ci sono quindi ancora due problemi da risolvere: Utilizzare una convenzione per i nomi dei file che compongono il plugin in modo che l'applicazione adminpossa riconoscerli come appartenenti allo stesso plugin. Se il plugin ha file di modello stabilire una convenzione per impedire agli oggetti che sono definiti nel modello di mischiarsi nello stesso namespacedell'applicazione. Queste sono le regole che dovrebbe seguire un plugin chiamato name: Regola 1: I plugin di tipo modello e di tipo controller dovrebbero essere chiamati rispettivamente: models/plugin_name.py controllers/plugin_name.py e quelli di tipo vista, modulo, statici e file privati dovrebbero essere chiamati: views/plugin_name/ modules/plugin_name/ static/plugin_name/ private/plugin_name/ Regola 2: I plugin di tipo modello possono definire solamente oggetti i cui nomi iniziano con: plugin_name PluginName _ Regola 3: I plugin di tipo modello possono definire solamente variabili i cui nomi iniziano con: session.plugin_name session.PluginName Regola 4: I plugin dovrebbero includere la licenza e la documentazione che dovrebbero essere presenti in: static/plugin_name/license.html static/plugin_name/about.html Regola 5: Un plugin può fare affidamento solo sull'esistenza degli oggetti globali definiti nell'applicazione di base, come per esempio: una connessione al database chiamata db una istanza di Authchiamataauth una istanza di Crudchiamatacrud una istanza di Servicechiamataservice Alcuni plugin possono essere più complessi ed avere parametri di configurazione per il caso in cui esista più di una istanza di db. Regola 6: Se un plugin necessita di parametri di configurazione questo dovrebbero essere aggiunti tramite PluginManager, come descritto in seguito. Seguendo le regole sopra indicate si può essere sicuri che: adminriconosce tutti i file e le cartelleplugin_namecome facenti parte di una singola entità. I plugin non interferiscono l'uno con l'altro. Queste regole non risolvono però il problema delle diverse versioni del plugin e delle sue dipendenze. Plugin di componenti I plugin di componenti sono plugin che definiscono dei componenti. I componenti solitamente accedono al database con i loro modelli. Ecco come trasformare il precedente componente comments in un plugin comments_plugin mantenendo lo stesso identico codice scritto precedentemente ma seguento tutte le regole dei plugin illustrate in precedenza. Creare, per prima cosa, un modello chiamato "models/plugin_comments.py": db.define_table('plugin_comments_comment', Field('body','text',label='Your comment'), Field('posted_on','datetime',default=request.now), Field('posted_by',db.auth_user,default=auth.user_id)) db.plugin_comments_comment.posted_on.writable=False db.plugin_comments_comment.posted_on.readable=False db.plugin_comments_comment.posted_by.writable=False db.plugin_comments_comment.posted_by.readable=False def plugin_comments(): return LOAD('plugin_comments','post',ajax=True) (le ultime due linee di codice definiscono una funzione che semplifica l'inserimento del plugin in un'applicazione). Definre quindi un controller "controllers/plugin_comments.py" @auth.requires_login() def post(): comments = db.plugin_comments_comment return dict(form=crud.create(comment), comments=db(comment.id>0).select()) Creare, come terza cosa, una vista chiamata "views/plugin_comments/post.load": {{for comment in comments:}} <div class="comment"> on {{=comment.posted_on}} {{=comment.first_name}} says <span class="comment_body">{{=comment.body}}</span> </div> {{pass}} {{=form}} E' ora possibile utilizzare admin per prepare il plugin per la distribuzione. Il plugin sarà salvato da admin come: web2py.plugin.comments.w2p Il plugin può essere ora usato in qualsiasi vista semplicmente installandolo in admin tramite la pagina edit ed aggiungendolo ad una vista con: {{=plugin_comments()}} Ovviamente è possibile rendere il plugin più complesso con componenti che richiedono parametri e opzioni di configurazione. Più i plugin sono complessi più si deve far attenzione ad evitare collisioni di nomi. Plugin Manager è progettato per evitare questi problemi. Plugin Manager La classe PluginManager è definita in gluon.tools. Prima di spiegare come funziona ecco come si utilizza. E' possibile migliorare il precedente plugin comments_plugin con la possibilità di aggiungere la personalizzazione di: db.plugin_comments_comment.body.label senza doverne modificare il codice. Prima di tutto, riscrivere il plugin "models/plugin_comments.py" nel seguente modo: db.define_table('plugin_comments_comment', Field('body','text',label=plugin_comments.comments.body_label), Field('posted_on','datetime',default=request.now), Field('posted_by',db.auth_user,default=auth.user_id)) def plugin_comments() from gluon.tools import PluginManager plugins = PluginManager('comments',body_label='Your comment') comment = db.plugin_comments_comment comment.label=plugins.comments.body_label comment.posted_on.writable=False comment.posted_on.readable=False comment.posted_by.writable=False comment.posted_by.readable=False return LOAD('plugin_comments','post',ajax=True) Tutto il codice (tranne la definizione della tabella) è incapsulato in una singola funzione che crea un'istanza di PluginManager. E' ora possibile configurare in ogni modello dell'applicazione (per esempio in "models/db.py") il plugin nel seguente modo: from gluon.tools import PluginManager plugins = PluginManager() plugins.comments.body_label=T('Post a comment') L'oggetto plugins è istanziato nell'applicazione di base in "models/db.py" L'oggetto PluginManager è un oggetto singleton di tipo Storage che contiene altri oggetti di tipo Storage con il blocco a livello del thread. Questo significa che si può istanziare tante volte quante è necessario all'interno di una applicazione, anche con nomi diversi, ma agisce come se fosse un'unica istanza di PluginManager. In particolare ogni file di plugin può definire il suo oggetto PluginManager e registrarlo, insieme ai suoi parametri di default, con: plugins = PluginManager('name', param1='value', param2='value') E' possibile modificare i parametri in altre parti del codice (per esempio in "models/db.py") con: plugins = PluginManager() plugins.name.param1 = 'other value' E' possibile inoltre configurare plugin diversi nello stesso codice: plugins = PluginManager() plugins.name.param1 = '...' plugins.name.param2 = '...' plugins.name1.param3 = '...' plugins.name2.param4 = '...' plugins.name3.param5 = '...' Quando il plugin è definito l'oggetto PluginManager deve avere due argomenti: il nome del plugin e degli argomenti opzionali con nome che sono i suoi parametri di default. Invece quando i plugin sono configurati il costruttore di PluginManager non deve avere argomenti. La configurazione deve precedere la definizione del plugin (per esempio deve essere in un modello che abbia un nome che alfabeticamente sia prima degli altri modelli). Plugin di layout I plugin di layout sono più semplici dei plugin di componenti perchè solitamente non contengono codice ma solamente viste e file statici. Ci sono comunque delle regole da seguire: Primo, creare una cartella chiamata "static/plugin_layout_name/" (dove name è il nome del layout) e posizionare in essa tutti i file statici del plugin. Secondo, creare un file di layout chiamato "views/plugin_layout_name/layout.html" che contiene il layout e i link alle immagini, ai file CSS e ai file JS in "static/plugin_layout_name/" Terzo, modificare la vista "views/layout.html" aggiungendo: {{include 'plugin_layout_name/layout.html'}} Il beneficio di questo design è che gli utenti di questo plugin possono installre più layout e scegliere quello da applicare all'applicazione semplicemente modificando il file "views/layout.html". Inoltre "views/layout.html" non verrà incluso da admin insieme al plugin in modo da non rischiare che un altro plugin sovrascriva il codice scritto dall'utente. plugin_wiki AVVISO: plugin_wiki è ancora in una fase iniziale di sviluppo e pertanto non ne è garantita la retro-compatibilità allo stesso livello delle funzioni centrali di web2py. plugin_wiki è un plugin "con gli steroidi". Infatti definisce diversi componenti e può cambiare il modo di sviluppare le applicazioni: E' possibile scaricarlo da: http://web2py.com/examples/static/web2py.plugin.wiki.w2p L'idea alla base di plugin_wiki è che la maggior parte delle applicazioni includono pagine semi-statiche. Si tratta di pagine che non includono una logica complessa e che contengono testo strutturato (come per esempio una pagina di help), immagini, audio, video, form CRUD o un insieme di componenti standard (commenti, tag, grafici, mappe, ecc.). Queste pagine possono essere pubbliche oppure richiedere un login o avere altre limitazione di autorizzazione. Possono essere raggiunte tramite un menu o da un modulo di autocomposizione. plugin_wiki mette a disposizione un modo semplice per aggiungere ad una applicazione web2py pagine che rientrano in questa categoria. In particolare plugin_wiki mette a disposizione: Un'interfaccia di tipo wiki che consente di aggiungere pagine alla propria applicazione e referenziarle con uno slug. Queste pagine, chiamate pagine wiki, hanno una versione e sono memorizzate in un database. Pagine pubbliche e pagine private (che richiedono l'autenticazione). Se una pagina richiede l'autenticazione può anche richiedere una particolare autorizzazione per un utente. Tre livelli: 1, 2, 3. Al livello 1 le pagine possono includere solamente testo, immagini, audio e video. Al livello 2 le pagine possono anche includere dei widget (questi sono componenti, definiti nella sezione precedente che possono essere inclusi nelle pagine wiki). Al livello 3 le pagine possono anche includere codice di template di web2py. La possibilità di modificare le pagine con la sintassi markmino con tag HTML utilizzando un editor WYSIWYG (What you see is what you get). Una raccolta di widget: implementati come componenti sono auto-documentati e possono essere inseriti nelle normali viste di web2py come componenti, o possono esser inclusi in una pagina wiki utilizzando una sintassi semplificata. Un gruppo di pagine speciali (meta-code,meta-menu, ecc.) che possono essere utilizzate per personalizzare il plugin (per esempio per definire codice che il plugin dovrebbe eseguire, per personalizzare il menu, ecc.). L'applicazionewelcomeinsieme al pluginplugin_wikipossono essere considerati come un ambiente di sviluppo utile per costruire semplici applicazioni web come, per esempio, un blog. Nel resto del capitolo si presuppone che il plugin plugin_wiki sia stato applicato ad una copia dell'applicazione di base welcome. La prima cosa che si nota dopo aver installato il plugin è che è disponibile un nuovo menu chiamato pages. [ADD IMAGE] Cliccando sul menu pages si accede alle azioni del plugin: http://127.0.0.1:8000/myapp/plugin_wiki/index La pagina index del plugin elenca le pagine create con il plugin stesso e consente di creare nuove pagine scegliento uno slug. Provare a creare una pagina home. Si verrà rediretti a: http://127.0.0.1:8000/myapp/plugin_wiki/page/home Cliccare su create page per modificare il contenuto della pagina. [ADD IMAGE] Per default il plugin è a livello 3, che significa che è possibile inserire widget e codice nelle pagine. Per default è utilizzata la sintassimarkminper descrivere il contenuto della pagina. Sintassi di Markmin Ecco un tutorial per la sintassi markmin: markmin html # titolo <h1>titolo</h1> ## sottotitolo <h2>sottotitolo</h2> ### sotto-sottotitolo <h3>sotto-sottotitolo</h3> **grassetto** <b>grassetto</b> ''corsivo'' <i>corsivo</i> http://...com <a href="http://...com">http:...com</a> [[name http://example.com]] <a href="http://example.com">name</a> [[name http://...png left 200px]] <img src="http://...png" alt="name" align="left" width="200px" /> E' possibile aggiungere collegamenti ad altre pagine [[mylink name page:slug]] Se la pagina non esiste verrà chiesto se la si vuole creare: [ADD IMAGE] La pagina di edit consente di aggiungere allegati alla pagina (per esempio file statici) [ADD IMAGE] che possono essere collegati con: [[mylink name attachment:3.png]] o inseriti direttamente nella pagina con: [[myimage attachment:3.png center 200px]] La dimensione (200px) è opzionale. center non è opzionale ma può essere sostituito con left or right. SI può inserire testo quotato con: -----this is blockquoted----- è anche possibile inserire tabelle con: -----0 | 0 | X0 | X | 0X | 0 | 0----- e testo letterale con: ``verbatim text`` E' anche possibile aggiungere :class all'ultima stringa ----- o ``. Per il testo quotato e per le tabelle :class verrà trasformato nella classe del tag, per esempio: -----test-----:abc viene visualizzato come: <blockquote class="abc">test</blockquote> Per il testo letterale la classe può essere utilizzata per includere contenuto di tipo differente. E' possibile, per esempio, includere codice con la sintassi evidenziata specificando il linguaggio con :code_language `` def index(): return 'hello world' ``:code_python E' anche possibile incorporare dei widget: ``name: widget_nameattribute1: value1attribute2: value2``:widget (vedere la prossima sezione per la lista dei widget) E' anche possibile incorporare codice nel linguaggio di template di web2py: `` {{for i in range(10):}}<h1>{{=i}}</h1>{{pass}} ``:template Permessi di pagina Quando si modifica una pagina sono presenti i seguenti campi: active(default aTrue). Se una pagina non è attiva non sarà accessibile agli utenti (anche se è una pagina pubblica). public(default aTrue). Se una pagina è definita come pubblica potrà essere acceduta dagli utenti senza la necessità di autenticarsi. Role(default aNone). Se una pagina ha un ruolo potrà essere acceduta solamente dagli utenti che si sono autenticati e che sono membri del gruppo con il ruolo corrispondente. Pagine speciali meta-menu contiene il menu. Se questa pagina non esiste web2py utilizza l'oggetto response.menu definito in "models/menu.py". Il contenuto della pagina meta-menu sovrascrive l'oggetto menu. La sintassi è la seguente: Item 1 Name http://link1.com Submenu Item 11 Name http://link11.com Submenu Item 12 Name http://link12.com Submenu Item 13 Name http://link13.comItem 2 Name http://link1.com Submenu Item 21 Name http://link21.com Submenu Item 211 Name http://link211.com Submenu Item 212 Name http://link212.com Submenu Item 22 Name http://link22.com Submenu Item 23 Name http://link23.com dove l'indentazione determina la struttura del sotto-menu. Ogni riga è composta del testo del menu seguito da un link. Un link può essere page:slug. Un link può essere None se quel menu non punta a nessuna pagina. Gli spazi in più sono ignorati. Ecco un altro esempio: Home page:home Search Engines None Yahoo http://yahoo.com Google http://google.com Bing http://bing.com Help page:help Che viene visualizzato come: [ADD IMAGE] meta-codeinxx meta-codeè un'altra pagina speciale e deve contenere codice web2py. Questa pagina può essere considerata come un'estensione del modello in quanto in essa è possibile aggiungere codice di modello. E' eseguita insieme a "models/plugin_wiki.py". In meta-codeè possibile definire delle tabelle. Si può, per esempio, creare una semplice tabella friends inserendo il seguente codice in meta-code: db.define_table('friend',Field('name',requires=IS_NOT_EMPTY())) e si può creare una pagina di gestione della tabella friend inserendo in una qualsiasi pagina il seguente codice: ## List of friends``name: jqgridtable: friend``:widget## New friend``name: createtable: friend``:widget Questa pagina ha due intestazioni (che iniziano con #): "List of friends" e "New friend". Contiene inoltre due widget (nelle rispettive intestazioni): un widget jqgrid che elenca tutti i record e un widget CRUD per aggiungere un nuovo record. [ADD IMAGE] meta-header, meta-footer, meta-sidebar non sono utilizzate nel layout di default "welcome/views/layout.html". Se si vogliono utilizzare si deve modificare la pagina "layout.html" tramite admin (o da linea di comando) ed inserire i seguenti tag nella posizione appropriata: {{=plugin_wiki.embed_page('meta-header') or ''}} {{=plugin_wiki.embed_page('meta-sidebar') or ''}} {{=plugin_wiki.embed_page('meta-footer') or ''}} In questo modo il contenuto di quelle pagine sarà mostrato nell'intestazione, nella barra laterale e nel piè di pagina del layout. Configurare plugin_wiki Come con qualsiasi altro plugin è possibile inserire il codice seguente in "models/db.py": from gluon.tools import PluginManager plugins = PluginManager plugins.wiki.editor = auth.user.email==mail.settings.sender plugins.wiki.level = 3 plugins.wiki.mode = 'markmin' or 'html' plugins.wiki.theme = 'ui-darkness' dove: editorè True se l'utente collegato è autorizzato a modificare le pagine del plugin levelè il permesso: 1 - per modificare pagine standard, 2 - per includere widget, 3 - per inserire codice modedetermina se utilizzare l'editor "markmin" oppure l'editory "html" WYSIWYG.WYSIWYG themeè il nome del tema UI di jQuery richiesto. Per default è installato solo il tema senza colori "ui-darkness". E' possibile aggiungere temi in: static/plugin_wiki/ui/%(theme)s/jquery-ui-1.8.1.custom.css Widget Ciascun widget può essere incorporato sia nelle pagine di plugin che nei normali template di web2py. Per esempio il seguente codice server ad incorporare un video di YouTube in una pagina di plugin: ``name: youtubecode: l7AWnfFRc7g``:widget o per incorporare lo stesso widget in una vista web2py si può utilizzare il seguente codice: {{=plugin_wiki.widget('youtube',code='l7AWnfFRc7g')}} Gli argomenti del widget che non hanno un valore di default sono obbligatori. Ecco la lista dei widget attualmente disponibili: read(table,record_id=None) Legge e visualizza un record tableè il nome della tabella record_idè il numero del record create(table,message='',next='',readonly_fields='', hidden_fields='',default_fields='') Visualizza un form di creazione di un record tableè il nome della tabella messageè il messaggio da visualizzare dopo la creazione del record nextè dove reindirizzare dopo la creazione, per esempio a "page/index/[id]" readonly_fieldsè una lista di campi in sola lettura, separati dalla virgola hidden_fieldsè una lista di campi nascosti, separati dalla virgola default_fieldsè una lista dei campi con i valori di default ("fieldname=value") update(table,record_id='',message='',next='', readonly_fields='',hidden_fields='',default_fields='') Visualizza un form di aggiornamento di un record tableè il nome della tabella record_idè il record da aggiornare oppure {{=request.args(-1)}} messageè il messaggio da visualizzare dopo l'aggiornamento del record nextè dove reindirizzare dopo l'aggiornamento, per esempio a "page/index/[id]" readonly_fieldsè una lista di campi in sola lettura, separati dalla virgola hidden_fieldsè una lista di campi nascosti, separati dalla virgola default_fieldsè una lista dei campi con i valori di default ("fieldname=value") select(table,query_field='',query_value='',fields='') Elenca i record nella tabella tableè il nome della tabella query_fieldequery_valuese presenti filtreranno la tabella con query_field==query_value fieldsè una lista dei campi da visualizzare, separati dalla virgola search(table,fields='') E' un widget per selezionare i record tableè il nome della tabella fieldsè una lista dei campi da visualizzare, separati dalla virgola jqgrid(table,fieldname=None,fieldvalue=None,col_widths='', _id=None,fields='',col_width=80,width=700,height=300) Incorpora un plugin di tipo jqGrid tableè il nome della tabella fieldname,fieldvaluesono campi di filtro opzionali (dove fieldname==fieldvalue) _idè l'id del DIV che contiene l'oggetto jqGrid columnsè la lista dei nomi delle colonne da visualizzare col_widthè la larghezza di ciascuna colonna (default) heightè l'altezza dell'oggetto jqGrid widthè la larghezza dell'oggetto jqGrid latex(expression) Usa le API dei grafici di Google per incorporare un oggetto LaTeX pie_chart(data='1,2,3',names='a,b,c',width=300,height=150,align='center') Incorpora un grafico a torta dataè una lista di valori, separati da virgola namesè una lista di etichette, separate da virgola (una per ogni elemento) widthè la larghezza dell'immagine heightè l'altezza dell'immagine aligndetermina l'allineamento dell'immagine bar_chart(data='1,2,3',names='a,b,c',width=300,height=150,align='center') Usa le API dei grafici di Google per incorporare un grafico a barre dataè una lista di valori, separati da virgola namesè una lista di etichette, separate da virgola (una per ogni elemento) widthè la larghezza dell'immagine heightè l'altezza dell'immagine aligndetermina l'allineamento dell'immagine slideshow(table,field='image',transition='fade',width=200,height=200) Incorpora uno slideshow. Le immagini sono recuperate da una tabella Embeds a slideshow. It gets the images from a table. tableè il nome della tabella fieldè il campo di upload della tabella che contiene le immagini transitiondetermina il tipo di transizione widthè la larghezza dell'immagine heightè l'altezza dell'immagine youtube(code,width=400,height=250) Incorpora un video di YouTube (tramite codice) codeè il codice del video widthè la larghezza dell'immagine heightè l'altezza dell'immagine vimeo(code,width=400,height=250) Incorpora un video di Vimeo (tramite codice) codeè il codice del video widthè la larghezza dell'immagine heightè l'altezza dell'immagine mediaplayer(src,width=400,height=250) Incorpora un file multimediale (come un video Flash o un file audio mp3) srcè il collegamento al video widthè la larghezza dell'immagine heightè l'altezza dell'immagine comments(table='None',record_id=None) Incorpora i commenti in una pagina. I commenti possono essere collegati ad una tabella e/o ad un record tableè il nome della tabella record_idè l'id del record tags(table='None',record_id=None) Incorpora dei tag in una pagina. I tag possono essere collegati ad una tabella e/o ad un record tableè il nome della tabella record_idè l'id del record tag_cloud() Inserisce una nuvola di tag (tag cloud) map(key='....', table='auth_user', width=400, height=200) Incorpora una mappa di Google Prende i punti di una mappa da una tabella keyè la chiave delle API di Google Map (default 127.0.0.1) tableè il nome della tabella widthè la larghezza della mappa heightè l'altezza della mappa La tabella deve avere le seguenti colonne: latidude, longitude e map_popup.Quando si seleziona un punto appare il messaggio memorizzato in map_popup. iframe(src, width=400, height=300) Incorpora una pagina nei tag <iframe> ... </iframe> load_url(src) Carica il contenuto della URL utilizzando la funzione LOAD load_action(action, controller='', ajax=True) Carica il contenuto della URL(request.application, controller, action) utilizzando la funzione LOAD Estendere i widget Per aggiungere un widget a plugin_wiki si deve creare un nuovo modello chiamato "models/plugin_wiki_"name dove name è un nome arbitrario. Il file deve contenere: class PluginWikiWidgets(PluginWikiWidgets): @staticmethod def my_new_widget(arg1, arg2='value', arg3='value'): """ document the widget """ return "body of the widget" La prima linea dichiare che si sta estendendo la lista dei widget. ALl'interno della classe si possono definire quante funzioni si vuole. Ogni funzione statica che non inizia con il carattere di underscore (_) è un nuovo widget. La funzione può avere un numero qualsiasi di argomenti che possono avere un valore di default. La docstring della funzione deve documentare l'utilizzo della funzione con la sintassi markmin. Quando i widget sono incorporati nelle pagine di plugin gli argomenti saranno passati al widget come stringhe. Per questo il widget deve essere in grado di ricevere stringhe per ogni argomento ed eventualmente convertirlo nella rappresentazione appropriata che deve essere adeguatamente documentata nella docstring. Il widget può restituire una stringa o helper di web2py che verranno serializzati con .xml(). Il nuovo widget può accedere a qualsiasi variabile dichiarata nel namespace globale. Ecco, come esempio, un widget che visualizza il form "contact/ask" creato all'inizio di questo capitolo. Il widget è contenuto in "models/plugin_wiki_contact": class PluginWikiWidgets(PluginWikiWidgets): @staticmethod def ask(email_label='Your email', question_label='question'): """ This plugin will display a contact us form that allows the visitor to ask a question. The question will be emailed to you and the widget will disappear from the page. The arguments are - email_label: the label of the visitor email field - question_label: the label of the question field """ form=SQLFORM.factory( Field('your_email',requires=IS_EMAIL(),label=email_label), Field('question',requires=IS_NOT_EMPTY()),label=question_label) if form.accepts(request.vars,session): if mail.send(to='admin@example.com', subject='from %s' % form.vars.your_email, message = form.vars.question): div_id = request.env.http_web2py_component_element command="jQuery('#%s').hide()" % div_id response.headers['web2py-component-command']=command response.headers['web2py-component-flash']='thanks you' else: form.errors.your_email="Unable to send the email" return form.xml() I widget di plugin non sono visualizzati dalla vista a meno che la funzione response.render(...) sia esplicitamente chiamata dal widget stesso. top
general dev cybrid at November 5th, 2005 08:08 — #1 Well, I'm totally new to this kind of class, so after searching a bit I found out this tuto about Singleton Pattern What I still don't understand very well is that in this piece of code class Singleton { public: static Singleton* Instance(); protected: Singleton(); Singleton(const Singleton&); Singleton& operator= (const Singleton&); private: static Singleton* pinstance; }; How can be a method a pointer to an object?. static Singleton* Instance(); Or maybe my question is wrong?. I still don't have it very clear. Thanks in advance :mellow: roel at November 5th, 2005 08:28 — #2 Maybe I misunderstood your question, but static Singleton* Instance(); means: we have a static function named Instance that returns a pointer to a Singleton object. hauptman at November 5th, 2005 09:30 — #3 That's not a pointer to an object. It means that the function Instance will return a pointer to an object of the type Singleton. cybrid at November 5th, 2005 10:24 — #4 OMG!!!, how can I be so blind!!! :surprise: Thanks to you both :happy: monjardin at November 6th, 2005 09:27 — #5 I usually do the following so that you don't have to worry about doing a new/delete on your instance: class Singleton { public: static inline Singleton& Instance() { static Singleton instance; return instance; } protected: Singleton(); Singleton(const Singleton&); Singleton& operator= (const Singleton&); }; The singleton is instantiated the first time you call the Instance() function (I think). oisyn at November 6th, 2005 11:10 — #6 monjardin: you are correct. The problem, however, is that you have absolutely no control over construction/destruction. Some prefer to have that control, particularly if there are cross-dependencies between singletons. If not, this actually is a good solution cybrid at November 6th, 2005 16:31 — #7 Errrm , I'm sorry in my ignorance, but, what is exactly that operator overload doing? Singleton& operator= (const Singleton&); reedbeta at November 6th, 2005 17:38 — #8 That overloads the assignment operator, allowing you write statements like Singleton a, b; a = b; However, I'm not sure why you would want that, since the whole idea of a singleton is that you only ever have one instance of it. And the constructors are protected anyway, so you wouldn't be able to instanciate another copy of it yourself. eddie at November 6th, 2005 22:15 — #9 monjardin was making it protected so the compiler wouldn't automatically roll one for you. eddie at November 6th, 2005 22:25 — #10 @monjardin I usually do the following so that you don't have to worry about doing a new/delete on your instance: class Singleton { public: static inline Singleton& Instance() { static Singleton instance; return instance; } protected: Singleton(); Singleton(const Singleton&); Singleton& operator= (const Singleton&); }; The singleton is instantiated the first time you call the Instance() function (I think). Actually, the singleton is instanced at compile time. When you create a static variable inside of a function, it's initialized onto the data segment, so, as .oisyn says, you don't actually have control over when it's initialized. That said, what you've got is basically a nice OO-based singleton-ish pattern above, so it's not all bad, but the same thing could be achieved by creating a global and externing it. Although, if letsay you were tracking access to people acquiring the instance, or doing some sort of locking on access, then the Singleton you have listed could be modified easily to accomplish this. Where the Singleton really shines, as .oisyn already mentioned, is in controlling construction and deletion, and that's why the Singleton pattern usually has memory allocation involved. For example, if you have a class A that's used as a singleton, as well as a class B, which is a singleton, you can ensure that any dependencies between the two are reconciled in an appropriate order, at runtime. That is, things are constructed in the appopriate order, which you can't guarantee with static function variables, or even global variables. If I'm not making any sense, let me know and I'll post up an example. Otherwise, I think I'll limit my posts to a short story from now on in, instead of a novel. bladder at November 7th, 2005 01:49 — #11 @eddie Actually, the singleton is instanced at compile time. When you create a static variable inside of a function, it's initialized onto the data segment, so, as .oisyn says, you don't actually have control over when it's initialized. IIRC local static variables are initialized upon first use. So he will have control over when the singleton is initialized, but no idea when it gets deallocated. eddie at November 7th, 2005 02:37 — #12 Hrmm. Funny. I did my verification with a quick google search, and came up with the following: http://www.phim.unibe.ch/comp\_doc/c\_manual/C/CONCEPT/storage\_class.html#static 'static' can also be defined within a function. If this is done, the variable is initalised at compilation time and retains its value between calls. Because it is initialsed at compilation time, the initalistation value must be a constant. This is serious stuff - tread with care. That said, in a quick test I've just done in a debugger, you're right: it does get initialized on first use. Good to know. oisyn at November 7th, 2005 05:22 — #13 eddie: you are talking about simple datatypes that can be initialized by simply putting the correct data in the data segment, as you say. Complex types that have constructors that need to be run will get initialized on first use, so when the Instance() function is first called. Or when you, for example, initialize an int with the result of something that is not known at compiletime (such as a function or a local variable) #include <iostream> #include <cstdlib> int foo() { std::cout << "in foo()" << std::endl; return rand(); } void bar() { std::cout << "in bar()" << std::endl; static int myInt = foo(); std::cout << myInt << std::endl; } int main() { std::cout << "first time:" << std::endl; bar(); std::cout << "second time:" << std::endl; bar(); } output: first time: in bar() in foo() <some random int> second time: in bar() <the same random int as before> cybrid at November 7th, 2005 08:09 — #14 @Reedbeta That overloads the assignment operator, allowing you write statements like Singleton a, b; a = b; However, I'm not sure why you would want that, since the whole idea of a singleton is that you only ever have one instance of it. And the constructors are protected anyway, so you wouldn't be able to instanciate another copy of it yourself. Thanks for the explanation Reedbeta eddie at November 7th, 2005 11:40 — #15 Ah. Thanks for the indepth explanatin .oisyn. Things you don't hit if you don't use a particular language option often. oisyn at November 7th, 2005 11:58 — #16 @Reedbeta That overloads the assignment operator, allowing you write statements like Singleton a, b; a = b; However, I'm not sure why you would want that, since the whole idea of a singleton is that you only ever have one instance of it. And the constructors are protected anyway, so you wouldn't be able to instanciate another copy of it yourself. The whole point is making the assignment operator inaccessible by making it private/protected . If you don't declare an assignment operator, a default one get's generated by the compiler that simply does a member-wise copy. Since you don't want that on a singleton, you should declare it protected or private (I personally would go for private, as you're not going to implement it anyway). mseare at November 7th, 2005 12:12 — #17 @.oisyn The whole point is making the assignment operator inaccessible by making it private/protected . If you don't declare an assignment operator, a default one get's generated by the compiler that simply does a member-wise copy. Since you don't want that on a singleton, you should declare it protected or private (I personally would go for private, as you're not going to implement it anyway). I second this suggestion. Make it private. monjardin at November 7th, 2005 16:24 — #18 Private IS better IMHO. I was making as few changes to the original poster's code as possible to avoid confusion. In practice, I typically just inherit from boost::noncopyable. That way it's easier for me to understand what's going on when I glance at the code. .oisyn: The initialization issues are very good ones to bring up. I had to find them the hard way some time ago. :wallbash: When I first learned of the singleton pattern I though it was the most convenient thing since sliced bread. It can definitely come back to bite you. The deallocation sequence is what really got me though. dk2 at November 7th, 2005 19:24 — #19 Here's an alternative method for implementing Singletons.
I want to make a simple stupid twitter app using Twitter API. If I request this page from my browser it does work: http://search.twitter.com/search.atom?q=hello&rpp=10&page=1 but if I request this page from python using urllib or urllib2 most of the times it doesn't work: response = urllib2.urlopen("http://search.twitter.com/search.atom?q=hello&rpp=10&page=1") and I get this error: Traceback (most recent call last): File "twitter.py", line 24, in <module> response = urllib2.urlopen("http://search.twitter.com/search.atom?q=hello&rpp=10&page=1") File "/usr/lib/python2.6/urllib2.py", line 126, in urlopen return _opener.open(url, data, timeout) File "/usr/lib/python2.6/urllib2.py", line 391, in open response = self._open(req, data) File "/usr/lib/python2.6/urllib2.py", line 409, in _open '_open', req) File "/usr/lib/python2.6/urllib2.py", line 369, in _call_chain result = func(*args) File "/usr/lib/python2.6/urllib2.py", line 1161, in http_open return self.do_open(httplib.HTTPConnection, req) File "/usr/lib/python2.6/urllib2.py", line 1136, in do_open raise URLError(err) urllib2.URLError: <urlopen error [Errno 110] Connection timed out> Why ??
ogaby Re : [ATTENTION] Faille de sécurité critique dans le noyau Linux ! vi... Avec cette simple ligne, on peut bénéficier des mises-à -jour de sécurité plus rapidement que sur un dépà´t européen. Je dis "européen" car je vis en Allemagne et mon dépà´t "normal" n'a pas encore cette mise-à -jour. Hors ligne zappinggg Re : [ATTENTION] Faille de sécurité critique dans le noyau Linux ! idem pour le fr pas de MAJ encore! Hors ligne ogaby Re : [ATTENTION] Faille de sécurité critique dans le noyau Linux ! Un point positif avec ce topic: on apprend pas mal de trucs sur les dépà´ts. - skippy a remarqué que la date de la dernière mise-à -jour du dépà´t officiel français date du 8.02. - le dépà´t officiel a déjà la correction de ce trou de sécurité mais les dépà´ts européens ne l'ont pas encore. On peut penser voire espérer que les dépà´ts européens le proposeront demain matin. On verra bien. Hors ligne HymnToLife Re : [ATTENTION] Faille de sécurité critique dans le noyau Linux ! Moi dans mon sources.list c'est les serveur "fr." et j'ai eu la mise à jour... T'es sûr ? Fais voir ton sourceS.list... Dernière modification par HymnToLife (Le 12/02/2008, à 23:49) - Rodrigue, as-tu du cœur ?- Non, mais j'ai du pique ! Hors ligne mr_pouit Re : [ATTENTION] Faille de sécurité critique dans le noyau Linux ! Vous pouvez voir l'état de synchronisation des différents miroirs sur cette page : https://launchpad.net/ubuntu/+archivemirrors (je connais pas la fréquence de mise à jour de cette page en revanche). Hors ligne Ferod Re : [ATTENTION] Faille de sécurité critique dans le noyau Linux ! idem j'ai eu une mis à jour sous feisty fawn alors que certains de mes dépots sont fr (enfin je crois)... # # deb cdrom:[Ubuntu 7.04 _Feisty Fawn_ - Release i386 (20070415)]/ feisty main restricted deb cdrom:[Ubuntu 7.04 _Feisty Fawn_ - Release i386 (20070415)]/ feisty main restricted # See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to # newer versions of the distribution. deb http://fr.archive.ubuntu.com/ubuntu/ feisty main restricted deb-src http://fr.archive.ubuntu.com/ubuntu/ feisty main restricted ## Major bug fix updates produced after the final release of the ## distribution. deb http://fr.archive.ubuntu.com/ubuntu/ feisty-updates main restricted deb-src http://fr.archive.ubuntu.com/ubuntu/ feisty-updates main restricted ## 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/ feisty universe deb-src http://fr.archive.ubuntu.com/ubuntu/ feisty 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/ feisty multiverse deb-src http://fr.archive.ubuntu.com/ubuntu/ feisty multiverse ## Uncomment the following two lines to add software from the 'backports' ## repository. ## N.B. software from this repository may not have been tested as ## extensively as that contained in the main release, although it includes ## newer versions of some applications which may provide useful features. ## Also, please note that software in backports WILL NOT receive any review ## or updates from the Ubuntu security team. # deb http://fr.archive.ubuntu.com/ubuntu/ feisty-backports main restricted universe multiverse # deb-src http://fr.archive.ubuntu.com/ubuntu/ feisty-backports main restricted universe multiverse deb http://security.ubuntu.com/ubuntu feisty-security main restricted deb-src http://security.ubuntu.com/ubuntu feisty-security main restricted deb http://security.ubuntu.com/ubuntu feisty-security universe deb-src http://security.ubuntu.com/ubuntu feisty-security universe deb http://security.ubuntu.com/ubuntu feisty-security multiverse deb-src http://security.ubuntu.com/ubuntu feisty-security multiverse "When I was in the military, they gave me a medal for killing two men, and a descharge for loving one !" Leonard Matlovich --------------------------- Papa tu me manques... Hors ligne ogaby Re : [ATTENTION] Faille de sécurité critique dans le noyau Linux ! Vous pouvez voir l'état de synchronisation des différents miroirs sur cette page : https://launchpad.net/ubuntu/+archivemirrors (je connais pas la fréquence de mise à jour de cette page en revanche). Ach... ScheiàŸe! Mon miroir est l'université d'Esslingen situé à 10km de chez moi (en ftp...) et il actualise une fois par semaine. Ben merci pour ton lien. C'est instructif. Je sens que la fameuse ligne à placer dans son sources.list pour la sécurité va être très précieuse. Je parle de ça à mettre dans le fameux fichier: deb http://archive.ubuntu.com/ubuntu/ gutsy-security main restricted universe multiverse Hors ligne HymnToLife Re : [ATTENTION] Faille de sécurité critique dans le noyau Linux ! deb http://security.ubuntu.com/ubuntu feisty-security main restricted deb-src http://security.ubuntu.com/ubuntu feisty-security main restricted deb http://security.ubuntu.com/ubuntu feisty-security universe deb-src http://security.ubuntu.com/ubuntu feisty-security universe deb http://security.ubuntu.com/ubuntu feisty-security multiverse deb-src http://security.ubuntu.com/ubuntu feisty-security multiverse Donc la branche security est récupérée à partir d'un serveur central pas du miroir fr. - Rodrigue, as-tu du cœur ?- Non, mais j'ai du pique ! Hors ligne zappinggg Re : [ATTENTION] Faille de sécurité critique dans le noyau Linux ! Bonjour, J'ai un problème suite à la MAJ de la faille de sécurité du KERNEL; je boot maintenant sur kernel serveur et non plus en generic: Je perds la wifi, le son et le graphisme voici mon fichier grub: title Ubuntu 7.10, kernel 2.6.22-14-server root (hd0,5) kernel /boot/vmlinuz-2.6.22-14-server root=UUID=4c6b95f2-b7b7-48e0-8739-6a0ddc3690ce ro quiet splash initrd /boot/initrd.img-2.6.22-14-server quiet title Ubuntu 7.10, kernel 2.6.22-14-server (recovery mode) root (hd0,5) kernel /boot/vmlinuz-2.6.22-14-server root=UUID=4c6b95f2-b7b7-48e0-8739-6a0ddc3690ce ro single initrd /boot/initrd.img-2.6.22-14-server title Ubuntu 7.10, kernel 2.6.22-14-generic root (hd0,5) kernel /boot/vmlinuz-2.6.22-14-generic root=UUID=4c6b95f2-b7b7-48e0-8739-6a0ddc3690ce ro quiet splash initrd /boot/initrd.img-2.6.22-14-generic quiet title Ubuntu 7.10, kernel 2.6.22-14-generic (recovery mode) root (hd0,5) kernel /boot/vmlinuz-2.6.22-14-generic root=UUID=4c6b95f2-b7b7-48e0-8739-6a0ddc3690ce ro single initrd /boot/initrd.img-2.6.22-14-generic que se passe til? une idée? sVP Hors ligne HymnToLife Re : [ATTENTION] Faille de sécurité critique dans le noyau Linux ! Désinstalle le noyau server depuis Synaptic, il sera automatiquement retiré de GRUB. - Rodrigue, as-tu du cœur ?- Non, mais j'ai du pique ! Hors ligne Atok Re : [ATTENTION] Faille de sécurité critique dans le noyau Linux ! Il y a eut une mise à jour du noyau aujourd'hui... Lisez libre ! :) Hors ligne vega_dagraeyt-wuon Re : [ATTENTION] Faille de sécurité critique dans le noyau Linux ! j'ai réinstallé gutsy tout à l'heure et dès le premier login la m à j était disponible. j'ai testé j'ai le bad address c'est bon....c'est bien la première fois que j'assiste à quelque chose de la sorte...sinon quelqu'un sait qui a découvert la faille et depuis quand ? Hors ligne sombrero Re : [ATTENTION] Faille de sécurité critique dans le noyau Linux ! Pour les détenteurs d'un serveur dédié chez Dedibox (et uniquement pour ces cas là ) : Pas de panique : Grà¢ce au NxBit activé sur les Dedibox, vous n'êtes pas impactés par cette faille de sécurité ! Vous pouvez vérifier que NxBit est correctement configuré : root@madedibox:/home/toto# dmesg | grep NX NX (Execute Disable) protection: active cependant quelques heures plus tard : Bonsoir, Vu que curieusement, NxBit n'a pas l'air de systématiquement protéger contre cette faille de sécurité, malgré nos multiples tests sur des centaines de machines, nous vous recommandons de mettre à jour votre kernel. La release R8 disponible sur le serveur ftp dedibox : ftp://ftp.dedibox.fr/pub/dedibox/kernel/r8-1/C7-X86-32bits/ Pour mettre à jour votre kernel, suivez cette documentation : http://documentation.dedibox.fr/doku.php?id=distrib:kernel C'est bien la release R8-1 qui est basée sur le 2.6.24.2 qui n'est pas vulnérable. Enfin dernier rappel, n'oubliez pas que si vous votre installation initiale date un peu, un bug dans grub-install fait que update-grub ne modifie pas correctement /boot/grub/menu.lst qu'il faut éditer à la main après le update-grub. Donc concrètement, après le dpkg du kernel il faut donc lancer manuellement update-grub puis éditer /boot/grub/menu.lst et remplacer les root=UUID=xxxxxx-xxxxx.... par root=/dev/sda2 si vous aviez suivi la prodécure d'installation recommandée. Vous pouvez ensuite rebooter. Dernière modification par sombrero (Le 13/02/2008, à 01:57) Debian unstable sur MacBook Pro. Hors ligne Kinette Re : [ATTENTION] Faille de sécurité critique dans le noyau Linux ! Enfin dernier rappel, n'oubliez pas que si vous votre installation initiale date un peu, un bug dans grub-install fait que update-grub ne modifie pas correctement /boot/grub/menu.lst qu'il faut éditer à la main après le update-grub. Donc concrètement, après le dpkg du kernel il faut donc lancer manuellement update-grub puis éditer /boot/grub/menu.lst et remplacer les root=UUID=xxxxxx-xxxxx.... par root=/dev/sda2 si vous aviez suivi la prodécure d'installation recommandée. Vous pouvez ensuite rebooter. Hello Sombrero, "date un peu" ça veux dire quoi? Est-ce que tu peux donner la source de ton info, merci d'avance! K Hors ligne brakbabord Re : [ATTENTION] Faille de sécurité critique dans le noyau Linux ! C'est bon j'ai eu la MAJ. J'ai changé mon sources.list pour ne plus pomper sur les serveurs fr, mais sur les serveur US. Hors ligne sombrero Re : [ATTENTION] Faille de sécurité critique dans le noyau Linux ! Enfin dernier rappel, n'oubliez pas que si vous votre installation initiale date un peu, un bug dans grub-install fait que update-grub ne modifie pas correctement /boot/grub/menu.lst qu'il faut éditer à la main après le update-grub. Donc concrètement, après le dpkg du kernel il faut donc lancer manuellement update-grub puis éditer /boot/grub/menu.lst et remplacer les root=UUID=xxxxxx-xxxxx.... par root=/dev/sda2 si vous aviez suivi la prodécure d'installation recommandée. Vous pouvez ensuite rebooter. Hello Sombrero, "date un peu" ça veux dire quoi? Est-ce que tu peux donner la source de ton info, merci d'avance! K Concernant les annonces d'Arnaud que j'ai citées, elles ont été faites lundi sur les newsgroups de dedibox (news://news.dedibox.fr/proxad.dedibox.discussions/) Pour l'installation qui « date un peu », le wiki de dedibox parle d'une installation antérieure au 28 mai 2006 mais ma propre installation de Feisty qui date de septembre 2007 a été aussi concernée par ce problème, donc y a pas vraiment de date précise si ce n'est que c'est au moins quelques mois. Pour la correction du problème lors de la mise à jour du menu de grub après une mise à jour du kernel (ça concerne donc aussi les upgrades entre 2 versions d'une distribution), un billet qui traite de l'upgrade feisty à gutsy explique très bien les manips à suivre pour faire la modification du menu. Comme je l'ai annoncé dans mon post initial, tout ce que je dis là concerne bien entendu uniquement les mises à jour sur un serveur dédié chez Dedibox (sous Ubuntu ou Debian) mais pas une installation d'Ubuntu standard. Debian unstable sur MacBook Pro. Hors ligne herberts Re : [ATTENTION] Faille de sécurité critique dans le noyau Linux ! Ayé, MAJ faite Félicitations aux devs pour le correctif, et merci à HTL de nous faire partager ses découvertes. Je vais également vérifier que ma fac est au courant, parce que le service info là bas... Hors ligne JBF Re : [ATTENTION] Faille de sécurité critique dans le noyau Linux ! Pour ceux qui rà¢lent sur le temps mis à corriger cette faille de sécurité : http://www.lemondeinformatique.fr/actua … 25325.html Sinon le bug #190587 n'est pas classé comme critique mais "seulement" de niveau élevé. L'explication est donnée. https://bugs.launchpad.net/ubuntu/+sour … bug/190587 JBF LibreOffice : http://fr.libreoffice.org/ (téléchargement, documentation, FAQ, assistance, contribuer, ...) Hors ligne oleg Re : [ATTENTION] Faille de sécurité critique dans le noyau Linux ! J'ai trouvé cette info ici http://www.infos-du-net.com/forum/267323-10-linux-attention-enorme-faille-securite-noyau et j'en retiens ceci : Aux Ubunteros : Une solution pour se protéger de cette faille consiste à désinstaller le paquet "build-essential", utilisé par le script. Néanmoins il tient une place primordiale dans les compilations. A vous de voir si vous en avez besoin ou pas... 1) Après les 11 MAJ qui m'ont été automatiquement proposées ce matin et nécessitant un redémarrage (et dont je pense qu'elles sont en rapport avec la correction de la dite-faille) : est-ce que ce qui précède peut être quand même utile à faire ? + (sous-question 2) : je n'ai pas eu le temps d'identifier les 11 MAJ en question : où sont-elles stockées et identifiables ?) 3) Qu'est-ce que "build essential" exactement ? Et le désinstaller peut être gênant en quoi ? Un "bleu" sur Ubuntu Faire de son mieux et laisser dire Ne jamais se sentir en dessous de soi ni au-dessus des autres Mon autogalerie de photos A + Hors ligne ogaby Re : [ATTENTION] Faille de sécurité critique dans le noyau Linux ! J'ai trouvé cette info ici http://www.infos-du-net.com/forum/267323-10-linux-attention-enorme-faille-securite-noyau et j'en retiens ceci : Aux Ubunteros : Une solution pour se protéger de cette faille consiste à désinstaller le paquet "build-essential", utilisé par le script. Néanmoins il tient une place primordiale dans les compilations. A vous de voir si vous en avez besoin ou pas... 1) Après les 11 MAJ qui m'ont été automatiquement proposées ce matin et nécessitant un redémarrage (et dont je pense qu'elles sont en rapport avec la correction de la dite-faille) : est-ce que ce qui précède peut être quand même utile à faire ? + (sous-question 2) : je n'ai pas eu le temps d'identifier les 11 MAJ en question : o๠sont-elles stockées et identifiables ?) 3) Qu'est-ce que "build essential" exactement ? Et le désinstaller peut être gênant en quoi ? Un "bleu" sur Ubuntu build essential est un paquet pour compiler un programme à partir des fichiers sources et on obtient ensuite un ou des fichier(s) exécutable(s). Bon peut-être qu' "info-du-net" à pensé qu'un virus allait répandre les sources puis compiler sur la machine victime puis s'exécuter. C'est un peu compliqué tout ca. Un pirate ferait plus simple. La majorité des PCs sont des 686: autant compiler pour un 686 puis envoyer uniquement l'exécutable. Hors ligne JBF Re : [ATTENTION] Faille de sécurité critique dans le noyau Linux ! 3) Qu'est-ce que "build essential" exactement ? Et le désinstaller peut être gênant en quoi ? Comme le suggère son nom, un paquet nécessaire à la compilation de programmes. Sans ça tu ne peux pas compiler le code scélérat. Cela ne te protège que si tu ne te fait pas fourguer le code sous forme exécutable. JBF LibreOffice : http://fr.libreoffice.org/ (téléchargement, documentation, FAQ, assistance, contribuer, ...) Hors ligne HymnToLife Re : [ATTENTION] Faille de sécurité critique dans le noyau Linux ! D'ailleurs et soit dit en passant, un simple apt-get remove build-essential n'empêchera rien du tout, puisqu'il ne supprimera que le meta-paquet, et pas les outils installés grà¢ce à celui-ci (gcc, les bibliothèques standard, etc.). On ne le répétera jamais assez, les "infos" d'infos-du-net, sont toujours à prendre avec des pincettes. Dernière modification par HymnToLife (Le 13/02/2008, à 13:10) - Rodrigue, as-tu du cœur ?- Non, mais j'ai du pique ! Hors ligne sirius10 Re : [ATTENTION] Faille de sécurité critique dans le noyau Linux ! avec un sudo aptitude remove build-essential est ce ok??? Dernière modification par sirius10 (Le 13/02/2008, à 13:12) "Pour ce qui est de l'Avenir, il ne s’agit pas de le prévoir, mais de le rendre possible." Antoine de Saint-Exupéry Hors ligne
MyClass.f refers to the function object f which is a property of MyClass. In your case, f is an instance method (has a self parameter) so its called on a particular instance. Its "unbound" because you're referring to f without specifying a specific class, kind of like referring to a steering wheel without a car. You can create an instance of MyClass and call f from it like so: x = MyClass() x.f() (This specifies which instance to call f from, so you can refer to instance variables and the like.) You're using f as a static method. These methods aren't bound to a particular class, and can only reference their parameters. A static method would be created and used like so: class MyClass(object): def f(): #no self parameter return 'hello world' print MyClass.f()
I'm reading on Google App Engine groups many users (Fig1, Fig2, Fig3) that can't figure out where the high number of Datastore reads in their billing reports come from. As you might know, Datastore reads are capped to 50K operations/day, above this budget you have to pay. 50K operations sounds like a lot of resources, but unluckily, it seems that each operation (Query, Entity fetch, Count..), hides several Datastore reads. Is it possible to know via API or some other approach, how many Datastore reads are hidden behind the common RPC.get , RPC.runquery calls? Appstats seems useless in this case because it gives just the RPC details and not the hidden reads cost. Having a simple Model like this: class Example(db.Model): foo = db.StringProperty() bars= db.ListProperty(str) and 1000 entities in the datastore, I'm interested in the cost of these kind of operations: items_count = Example.all(keys_only = True).filter('bars=','spam').count() items_count = Example.all().count(10000) items = Example.all().fetch(10000) items = Example.all().filter('bars=','spam').filter('bars=','fu').fetch(10000) items = Example.all().fetch(10000, offset=500) items = Example.all().filter('foo>=', filtr).filter('foo<', filtr+ u'\ufffd')
Create a VBO containing all of the sprite's frames, and make your glDrawArrays call with the appropriate (frameNumber * 4) in the first param. If you want to get even more clever about it, you could make it a static VBO and do your billboarding formula in your vertex shader. The sprite origin would then become a shader uniform, as would the up and right (or left, as appropriate) vectors. Sample vertex shader code: uniform mat4 mvpMatrix; uniform vec3 upVec; uniform vec3 rightVec; uniform vec3 spriteOrigin; layout(location = 0) in vec2 position; layout(location = 1) in vec2 texcoord; ..... ..... gl_Position = mvpMatrix * vec4 (rightVec * position.y + (upVec * position.x + spriteOrigin), 1); Filling the VBO (load-time only, adjust the indexes into framedata to suit the orientation of your texture): framedata[0].positions[0] = frame->down; framedata[0].positions[1] = frame->left; framedata[0].texcoords[0] = // whatever framedata[0].texcoords[1] = // whatever framedata[1].positions[0] = frame->up; framedata[1].positions[1] = frame->left; framedata[1].texcoords[0] = // whatever framedata[1].texcoords[1] = // whatever framedata[2].positions[0] = frame->down; framedata[2].positions[1] = frame->right; framedata[2].texcoords[0] = // whatever framedata[2].texcoords[1] = // whatever framedata[3].positions[0] = frame->up; framedata[3].positions[1] = frame->right; framedata[3].texcoords[0] = // whatever framedata[3].texcoords[1] = // whatever glBufferSubData ( GL_ARRAY_BUFFER, framenum * 4 * sizeof (spritevboframe), 4 * sizeof (spritevboframe), framedata ); Here, frame->up/down/left/right are just derived from the width and height of each frame; you could potentially double them up with the texcoords or it may be useful to keep them separate if you want to use different scalings. Draw call: glDrawArrays (GL_TRIANGLE_STRIP, frameNumber * 4, 4); From here you can easily go more advanced and use instancing if you need to draw many sprites with the same frame; the uniform data above would become per-instance data. But that's a topic for another time.
Introduction web2py[web2py] is a free, open-source web framework for agile development of secure database-driven web applications; it is written in Python[python] and programmable in Python. web2py is a full-stack framework, meaning that it contains all the components you need to build fully functional web applications. web2py is designed to guide a web developer to follow good software engineering practices, such as using the Model View Controller (MVC) pattern. web2py separates the data representation (the model) from the data presentation (the view) and also from the application logic and workflow (the controller). web2py provides libraries to help the developer design, implement, and test each of these three parts separately, and makes them work together. web2py is built for security. This means that it automatically addresses many of the issues that can lead to security vulnerabilities, by following well established practices. For example, it validates all input (to prevent injections), escapes all output (to prevent cross-site scripting), renames uploaded files (to prevent directory traversal attacks). web2py takes care of main security issues, so developers have less chances of introducing vulnerabilities. web2py includes a Database Abstraction Layer (DAL) that writes SQL[sql-w] dynamically so that you, the developer, don't have to. The DAL knows how to generate SQL transparently for SQLite[sqlite], MySQL[mysql], PostgreSQL[postgres], MSSQL[mssql], FireBird[firebird], Oracle[oracle], IBM DB2[db2], Informix[informix] and Ingres[ingresdb]. The DAL can also generate function calls for the Google Datastore when running on the Google App Engine (GAE)[gae]. Experimentally we support more databases and new ones are constantly added. Please check on the web2py web site and mailing list for more recent adapters. Once one or more database tables are defined, web2py automatically generates a fully functional web-based database administration interface to access the database and the tables. web2py differs from other web frameworks in that it is the only framework to fully embrace the Web 2.0 paradigm, where the web is the computer. In fact, web2py does not require installation or configuration; it runs on any architecture that can run Python (Windows, Windows CE, Mac OS X, iOS, and Unix/Linux), and the development, deployment, and maintenance phases for the applications can be done via a local or remote web interface. web2py runs with CPython (the C implementation) and PyPy (Python written in Python), on Python versions 2.5, 2.6, and 2.7. web2py provides a ticketing system for error events. If an error occurs, a ticket is issued to the user, and the error is logged for the administrator. web2py is open source and released under the LGPL version 3 license. Another important feature of web2py is that we, its developers, commit to maintain backward compatibility in future versions. We have done so since the first release of web2py in October, 2007. New features have been added and bugs have been fixed, but if a program worked with web2py 1.0, that program will work even better today. Here are some examples of web2py statements that illustrate its power and simplicity. The following code: db.define_table('person', Field('name'), Field('image', 'upload')) creates a database table called "person" with two fields: "name", a string; and "image", something that needs to be uploaded (the actual image). If the table already exists but does not match this definition, it is altered appropriately. Given the table defined above, the following code: form = SQLFORM(db.person).process() creates an insert form for this table that allows users to upload images. It also validates the submitted form, renames the uploaded image in a secure way, stores the image in a file, inserts the corresponding record in the database, prevents double submission, and eventually modifies the form itself by adding error messages if the data submitted by the user does not pass validation. This code embeds a fully working wiki with tags, search, tag cloud, permissions, media attachments, and oembed support: def index(): return auth.wiki() The following code instead: @auth.requires_permission('read','person') def f(): .... prevents visitors from accessing the function f unless the visitor is a member of a group whose members have permissions to "read" records of table "person". If the visitor is not logged in, the visitor gets directed to a login page (provided by default by web2py). web2py also supports components, i.e. actions which can be loaded in a view and interact with the visitor via Ajax without re-loading the entire page. This is done via a LOAD helper which allows very modular design of applications; it is discussed in chapter 3 in the context of the wiki and, in some detail, in the last chapter of this book. This 6th edition of the book describes web2py 2.4.1 and later versions. Principles Python programming typically follows these basic principles: Don't repeat yourself (DRY). There should be only one way of doing things. Explicit is better than implicit. web2py fully embraces the first two principles by forcing the developer to use sound software engineering practices that discourage repetition of code. web2py guides the developer through almost all the tasks common in web application development (creating and processing forms, managing sessions, cookies, errors, etc.). web2py differs from other frameworks with regard to the third principle, which sometimes conflicts with the other two. In particular, web2py does not import user applications, but executes them in a predefined context. This context exposes the Python keywords, as well as the web2py keywords. To some this may appear as magic, but it should not. Simply, in practice, some modules are already imported without you doing so. web2py is trying to avoid the annoying characteristic of other frameworks that force the developer to import the same modules at the top of every model and controller. web2py, by importing its own modules, saves time and prevents mistakes, thus following the spirit of "don't repeat yourself" and "there should be only one way of doing things". If the developer wishes to use other Python modules or third-party modules, those modules must be imported explicitly, as in any other Python program. Web frameworks At its most fundamental level, a web application consists of a set of programs (or functions) that are executed when the corresponding URL is visited. The output of the program is returned to the visitor and rendered by the browser. The purpose of web frameworks is to allow developers to build new apps quickly, easily and without mistakes. This is done by providing APIs and tools that reduce and simplify the amount of coding that is required. The two classic approaches for developing web applications are: The first model is the one that was followed, for example, by early CGI scripts. The second model is followed, for example, by PHP[php] (where the code is in PHP, a C-like language), ASP (where the code is in Visual Basic), and JSP (where the code is in Java). Here is an example of a PHP program that, when executed, retrieves data from a database and returns an HTML page showing the selected records: <html><body><h1>Records</h1><? mysql_connect(localhost,username,password); @mysql_select_db(database) or die( "Unable to select database"); $query="SELECT * FROM contacts"; $result=mysql_query($query); mysql_close(); $i=0; while ($i < mysql_numrows($result)) { $name=mysql_result($result,$i,"name"); $phone=mysql_result($result,$i,"phone"); echo "<b>$name</b><br>Phone:$phone<br /><br /><hr /><br />"; $i++; } ?></body></html> The problem with this approach is that code is embedded into HTML, but the very same code also needs to generate additional HTML and to generate SQL statements to query the database, entangling multiple layers of the application and making it difficult to read and maintain. The situation is even worse for Ajax applications, and the complexity grows with the number of pages (files) that make up the application. The functionality of the above example can be expressed in web2py with two lines of Python code: def index(): return HTML(BODY(H1('Records'), db().select(db.contacts.ALL))) In this simple example, the HTML page structure is represented programmatically by the HTML, BODY, and H1 objects; the database db is queried by the select command; finally, everything is serialized into HTML. Notice that db is not a keyword but a user defined variable. We will use this name consistently to refer to a database connection to avoid confusion. Web frameworks are typically categorized as one of two types: A "glued" framework is built by assembling (gluing together) several third-party components. A "full-stack" framework is built by creating components designed specifically to be tightly integrated and work together. web2py is a full-stack framework. Almost all of its components are built from scratch and are designed to work together, but they function just as well outside of the complete web2py framework. For example, the Database Abstraction Layer (DAL) or the template language can be used independently of the web2py framework by importing gluon.dal or gluon.template into your own Python applications. gluon is the name of the web2py module that contains system libraries. Some web2py libraries, such as building and processing forms from database tables, have dependencies on other portions of web2py. web2py can also work with third-party Python libraries, including other template languages and DALs, but they will not be as tightly integrated as the original components. Model-View-Controller web2py encourages the developer to separate data representation (the model), data presentation (the view) and the application workflow (the controller). Let's consider again the previous example and see how to build a web2py application around it. Here is an example of the web2py MVC edit interface: The typical workflow of a request in web2py is described in the following diagram: In the diagram: The Server can be the web2py built-in web server or a third-party server, such as Apache. The Server handles multi-threading. "main" is the main WSGI application. It performs all common tasks and wraps user applications. It deals with cookies, sessions, transactions, URL routing and reverse routing, and dispatching. It can serve and stream static files if the web server is not doing it yet. The Models, Views and Controller components make up the user application. Multiple applications can be hosted in the same web2py instance. The dashed arrows represent communication with the database engine(s). The database queries can be written in raw SQL (discouraged) or by using the web2py Database Abstraction Layer (recommended), so that web2py application code is not dependent on the specific database engine. The dispatcher maps the requested URL to a function call in the controller. The output of the function can be a string or a dictionary of symbols (a hash table). The data in the dictionary is rendered by a view. If the visitor requests an HTML page (the default), the dictionary is rendered into an HTML page. If the visitor requests the same page in XML, web2py tries to find a view that can render the dictionary in XML. The developer can create views to render pages in any of the already supported protocols (HTML, XML, JSON, RSS, CSV, and RTF) or in additional custom protocols. All calls are wrapped into a transaction, and any uncaught exception causes the transaction to be rolled back. If the request succeeds, the transaction is committed. web2py also handles sessions and session cookies automatically, and when a transaction is committed, the session is also stored, unless specified otherwise. It is possible to register recurrent tasks (via cron) to run at scheduled times and/or after the completion of certain actions. In this way it is possible to run long and compute-intensive tasks in the background without slowing down navigation. Here is a minimal and complete MVC application, consisting of three files: "db.py" is the model: db = DAL('sqlite://storage.sqlite') db.define_table('contact', Field('name'), Field('phone')) It connects to the database (in this example a SQLite database stored in the storage.sqlite file) and defines a table called contact. If the table does not exist, web2py creates it and, transparently and in the background, generates SQL code in the appropriate SQL dialect for the specific database engine used. The developer can see the generated SQL but does not need to change the code if the database back-end, which defaults to SQLite, is replaced with MySQL, PostgreSQL, MSSQL, FireBird, Oracle, DB2, Informix, Interbase, Ingres, and the Google App Engine (both SQL and NoSQL). Once a table is defined and created, web2py also generates a fully functional web-based database administration interface, called appadmin, to access the database and the tables. "default.py" is the controller: def contacts(): grid=SQLFORM.grid(db.contact, user_signature=False) return locals() In web2py, URLs are mapped to Python modules and function calls. In this case, the controller contains a single function (or "action") called contacts. An action may return a string (the returned web page) or a Python dictionary (a set of key:value pairs) or the set of local variables (as in this example). If the function returns a dictionary, it is passed to a view with the same name as the controller/function, which in turn renders the page. In this example, the function contacts generates a select/search/create/update/delete grid for table db.contact and returns the grid to the view. "default/contacts.html" is the view: {{extend 'layout.html'}} <h1>Manage My Contacts</h1> {{=grid}} This view is called automatically by web2py after the associated controller function (action) is executed. The purpose of this view is to render the variables in the returned dictionary (in our case grid) into HTML. The view file is written in HTML, but it embeds Python code delimited by the special {{ and }} delimiters. This is quite different from the PHP code example, because the only code embedded into the HTML is "presentation layer" code. The "layout.html" file referenced at the top of the view is provided by web2py and constitutes the basic layout for all web2py applications. The layout file can easily be modified or replaced. Why web2py web2py is one of many web application frameworks, but it has compelling and unique features. web2py was originally developed as a teaching tool, with the following primary motivations: Easy for users to learn server-side web development without compromising functionality. For this reason, web2py requires no installation and no configuration, has no dependencies (except for the source code distribution, which requires Python 2.5 and its standard library modules), and exposes most of its functionality via a Web interface, including an Integrated Development Environment with Debugger and database interface. web2py has been stable from day one because it follows a top-down design; i.e., its API was designed before it was implemented. Even as new functionality has been added, web2py has never broken backwards compatibility, and it will not break compatibility when additional functionality is added in the future. web2py proactively addresses the most important security issues which plague many modern web applications, as determined by OWASP[owasp]below. web2py is lightweight. Its core libraries, including the Database Abstraction Layer, the template language, and all the helpers amount to 1.4MB. The entire source code including sample applications and images amounts to 10.4MB. web2py has a small footprint and is very fast. It uses the Rocket[rocket]WSGI web server developed by Timothy Farrell. It is as fast as Apache with mod_wsgi, and supports SSL and IPv6. web2py uses Python syntax for models, controllers, and views, but does not import models and controllers (as all the other Python frameworks do) - instead it executes them. This means that apps can be installed, uninstalled, and modified without having to restart the web server (even in production), and different apps can coexist without their modules interfering with one another. web2py uses a Database Abstraction Layer (DAL) instead of an Object Relational Mapper (ORM). From a conceptual point of view, this means that different database tables are mapped into different instances of one Tableclass and not into different classes, while records are mapped into instances of oneRowclass, not into instances of the corresponding table class. From a practical point of view, it means that SQL syntax maps almost one-to-one into DAL syntax, and there is no complex metaclass programming going on under the hood as in popular ORMs, which would add latency. Here is a screenshot of the main web2py admin interface: Security The Open Web Application Security Project[owasp] (OWASP) is a free and open worldwide community focused on improving the security of application software. OWASP has listed the top ten security issues that put web applications at risk. That list is reproduced here, along with a description of how each issue is addressed by web2py: cross site scripting"Cross Site Scripting (XSS): XSS flaws occur whenever an application takes user supplied data and sends it to a web browser without first validating or encoding that content. XSS allows attackers to execute scripts in the victim's browser which can hijack user sessions, deface web sites, possibly introduce worms, etc."web2py, by default, escapes all variables rendered in the view, preventing XSS. injection flaws"Injection Flaws: Injection flaws, particularly SQL injection, are common in web applications. Injection occurs when user-supplied data is sent to an interpreter as part of a command or query. The attacker's hostile data tricks the interpreter into executing unintended commands or changing data."web2py includes a Database Abstraction Layer that makes SQL injection impossible. Normally, SQL statements are not written by the developer. Instead, SQL is generated dynamically by the DAL, ensuring that all inserted data is properly escaped. malicious file execution"Malicious File Execution: Code vulnerable to remote file inclusion (RFI) allows attackers to include hostile code and data, resulting in devastating attacks, such as total server compromise."web2py allows only exposed functions to be executed, preventing malicious file execution. Imported functions are never exposed; only actions are exposed. web2py uses a Web-based administration interface which makes it very easy to keep track of what is exposed and what is not. insecure object reference"Insecure Direct Object Reference: A direct object reference occurs when a developer exposes a reference to an internal implementation object, such as a file, directory, database record, or key, as a URL or form parameter. Attackers can manipulate those references to access other objects without authorization."web2py does not expose any internal objects; moreover, web2py validates all URLs, thus preventing directory traversal attacks. web2py also provides a simple mechanism to create forms that automatically validate all input values. CSRF"Cross Site Request Forgery (CSRF): A CSRF attack forces a logged-on victim's browser to send a pre-authenticated request to a vulnerable web application, which then forces the victim's browser to perform a hostile action to the benefit of the attacker. CSRF can be as powerful as the web application that it attacks."web2py prevents CSRF as well as accidental double submission of forms by assigning a one-time random token to each form. Moreover web2py uses UUID for session cookie. information leakageimproper error handling"Information Leakage and Improper Error Handling: Applications can unintentionally leak information about their configuration, internal workings, or violate privacy through a variety of application problems. Attackers use this weakness to steal sensitive data, or conduct more serious attacks."web2py includes a ticketing system. No error can result in code being exposed to the users. All errors are logged and a ticket is issued to the user that allows error tracking. But errors and source code are accessible only to the administrator. "Broken Authentication and Session Management: Account credentials and session tokens are often not properly protected. Attackers compromise passwords, keys, or authentication tokens to assume other users' identities." web2py provides a built-in mechanism for administrator authentication, and it manages sessions independently for each application. The administrative interface also forces the use of secure session cookies when the client is not "localhost". For applications, it includes a powerful Role Based Access Control API. cryptographic store"Insecure Cryptographic Storage: Web applications rarely use cryptographic functions properly to protect data and credentials. Attackers use weakly protected data to conduct identity theft and other crimes, such as credit card fraud."web2py uses the MD5 or the HMAC+SHA-512 hash algorithms to protect stored passwords. Other algorithms are also available. secure communications"Insecure Communications: Applications frequently fail to encrypt network traffic when it is necessary to protect sensitive communications."web2py includes the SSL-enabled[ssl]Rocket WSGI server, but it can also use Apache or Lighttpd and mod_ssl to provide SSL encryption of communications. access restriction"Failure to Restrict URL Access: Frequently an application only protects sensitive functionality by preventing the display of links or URLs to unauthorized users. Attackers can use this weakness to access and perform unauthorized operations by accessing those URLs directly."web2py maps URL requests to Python modules and functions. web2py provides a mechanism for declaring which functions are public and which require authentication and authorization. The included Role Based Access Control API allow developers to restrict access to any function based on login, group membership or group based permissions. The permissions are very granular and can be combined with database filters to allow, for example, to give access to specific tables and/or records. web2py also allows digitally signed URL and provides API to digitally sign Ajax callbacks. web2py was reviewed for security and you can find the result of the review in ref.[pythonsecurity]. In the box You can download web2py from the official web site: http://www.web2py.com web2py is composed of the following components: libraries: provide core functionality of web2py and are accessible programmatically. web server: the Rocket WSGI web server. the adminapplication: used to create, design, and manage other web2py applications.adminprovides a complete web-based Integrated Development Environment (IDE) for building web2py applications. It also includes other functionality, such as web-based testing and a web-based shell. the examplesapplication: contains documentation and interactive examples.examplesis a clone of the official web2py.com web site, and includes epydoc documentation. the welcomeapplication: the basic scaffolding template for any other application. By default it includes a pure CSS cascading menu and user authentication (discussed in Chapter 9). web2py is distributed in source code, and in binary form for Microsoft Windows and for Mac OS X. The source code distribution can be used in any platform where Python runs and includes the above-mentioned components. To run the source code, you need Python 2.5, 2.6 or 2.7 pre-installed on the system. You also need one of the supported database engines installed. For testing and light-demand applications, you can use the SQLite database, included with Python 2.7. The binary versions of web2py (for Windows and Mac OS X) include a Python 2.7 interpreter and the SQLite database. Technically, these two are not components of web2py. Including them in the binary distributions enables you to run web2py out of the box. The following image depicts the overall web2py structure: At the bottom we find the interpreter. Moving up we find the web server (rocket), the libraries, and the applications. Each application consists for its own MVC design (models, controllers, views, modules, languages, databases, and static files). Each application includes it own database administration code (appadmin). Every web2py instance ships with three applications: welcome (the scaffolding app), admin (the web based IDE), and examples (copy of website and examples). About this book This book includes the following chapters, besides this introduction: Chapter 2 is a minimalist introduction to Python. It assumes knowledge of both procedural and object-oriented programming concepts such as loops, conditions, function calls and classes, and covers basic Python syntax. It also covers examples of Python modules that are used throughout the book. If you already know Python, you may skip Chapter 2. Chapter 3 shows how to start web2py, discusses the administrative interface, and guides the reader through various examples of increasing complexity: an application that returns a string, a counter application, an image blog, and a full blown wiki application that allows image uploads and comments, provides authentication, authorization, web services and an RSS feed. While reading this chapter, you may need to refer to Chapter 2 for general Python syntax and to the following chapters for a more detailed reference about the functions that are used. Chapter 4 covers more systematically the core structure and libraries: URL mapping, request, response, sessions, caching, scheduler, cron, internationalization and general workflow. Chapter 5 is a reference for the template language used to build views. It shows how to embed Python code into HTML, and demonstrates the use of helpers (objects that can generate HTML). Chapter 6 covers the Database Abstraction Layer, or DAL. The syntax of the DAL is presented through a series of examples. Chapter 7 covers forms, form validation and form processing. FORM is the low level helper for form building. SQLFORM is the high level form builder. In Chapter 7 we also discuss Create/Read/Update/Delete (CRUD) API. Chapter 8 covers communication features as retrieving and sending emails and SMSes. Chapter 9 covers authentication, authorization and the extensible Role-Based Access Control mechanism available in web2py. Mail configuration and CAPTCHA are also discussed here, since they are used for authentication. In the third edition of the book we have added extensive coverage of integration with third-party authentication mechanisms such as OpenID, OAuth, Google, Facebook, LinkedIn, etc. Chapter 10 is about creating web services in web2py. We provide examples of integration with the Google Web Toolkit via Pyjamas, and with Adobe Flash via PyAMF. Chapter 11 is about web2py and jQuery recipes. web2py is designed mainly for server-side programming, but it includes jQuery, since we have found it to be the best open-source JavaScript library available for effects and Ajax. In this chapter, we discuss how to effectively use jQuery with web2py. Chapter 12 discusses web2py components and plugins as a way to build modular applications. We provide an example of a plugin that implements many commonly used functionality, such as charting, comments, and tagging. Chapter 13 is about production deployment of web2py applications. We specifically discuss the deployment on a LAMP web server (which we consider the main deployment alternative). We discuss alternative web servers, and configuration of the PostgreSQL database. We discuss running as a service on a Microsoft Windows environment, and deployment on some specific platforms including Google Applications Engine, Heroku, and PythonAnywhere. In this chapter, we also discuss security and scalability issues. Chapter 14 contains a variety of other recipes to solve specific tasks, including upgrades, geocoding, pagination, the Twitter API, and more. Chapter 15 has information and helping and contributing to the project, with topics such as making bug reports and contributing changes to the code. This book only covers basic web2py functionalities and the API that ships with web2py. This book does not cover web2py appliances (i.e. ready made applications). You can download web2py appliances from the corresponding web site [appliances]. This book has been written using the MARKMIN syntax See Chapter 5 and automatically converted to HTML, LaTeX and PDF. Support The main support channel is the usergroup[usergroup], with dozens of posts every day. Even if you're a newbie, don't hesitate to ask - we'll be pleased to help you. There is also a formal issue tracker system on http://code.google.com/p/web2py/issues . Last but not least, you can have professional support (see the web site for details). Contribute Any help is really appreciated. You can help other users on the user group, or by directly submitting patches on the program (at the GitHub site https://github.com/web2py/web2py). Even if you find a typo on this book, or have an improvement on it, the best way to help is by patching the book itself (which is under the source folder of the repository at https://github.com/mdipierro/web2py-book). For more information on contributing, please see Chapter 15 Elements of style PEP8 [style] contains good style practices when programming with Python. You will find that web2py does not always follow these rules. This is not because of omissions or negligence; it is our belief that the users of web2py should follow these rules and we encourage it. We chose not to follow some of those rules when defining web2py helper objects in order to minimize the probability of name conflict with objects defined by the user. For example, the class that represents a <div> is called DIV, while according to the Python style reference it should have been called Div. We believe that, for this specific example that using an all-upper-case "DIV" is a more natural choice. Moreover, this approach leaves programmers free to create a class called "Div" if they choose to do so. Our syntax also maps naturally into the DOM notation of most browsers (including, for example, Firefox). According to the Python style guide, all-upper-case strings should be used for constants and not variables. Continuing with our example, even considering that DIV is a class, it is a special class that should never be modified by the user because doing so would break other web2py applications. Hence, we believe this qualifies the DIV class as something that should be treated as a constant, further justifying our choice of notation. In summary, the following conventions are followed: HTML helpers and validators are all upper case for the reasons discussed above (for example DIV,A,FORM,URL). The translator object Tis upper case despite the fact that it is an instance of a class and not a class itself. Logically the translator object performs an action similar to the HTML helpers, it affects rendering part of the presentation. Also,Tneeds to be easy to locate in the code and must have a short name. DAL classes follow the Python style guide (first letter capitalized), for example Table,Field,Query,Row,Rows, etc. In all other cases we believe we have followed, as much as possible, the Python Style Guide (PEP8). For example all instance objects are lower-case (request, response, session, cache), and all internal classes are capitalized. In all the examples of this book, web2py keywords are shown in bold, while strings and comments are shown in italic. License web2py is licensed under the LGPL version 3 License. The full text of the license is available in ref.[lgpl3]. In accordance with LGPL you may: redistribute web2py with your apps (including official web2py binary versions) release your applications which use official web2py libraries under any license you wish Yet you must: make clear in the documentation that your application uses web2py release any modification of the web2py libraries under the LGPLv3 license The license includes the usual disclaimer: THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Earlier versions Earlier versions of web2py, 1.0.*-1.90.*, were released under the GPL2 license plus a commercial exception which, for practical purposes, was very similar to the current LGPLv3. Third party software distributed with web2py web2py contains third party software under the gluon/contrib/ folder and various JavaScript and CSS files. These files are distributed with web2py under their original licenses, as stated in the files. Acknowledgments web2py was originally developed by and copyrighted by Massimo Di Pierro. The first version (1.0) was released in October, 2007. Since then it has been adopted by many users, some of whom have also contributed bug reports, testing, debugging, patches, and proofreading of this book. Some of the major developers and contributors are, in alphabetical order by first name: Adam Bryzak, Adam Gojdas, Adrian Klaver, Alain Boulch, Alan Etkin, Alec Taylor, Alexandre Andrade, Alexey Nezhdanov, Alvaro Justen, Anand Vaidya, Anatoly Belyakov, Ander Arbelaiz, Anders Roos, Andrew Replogle, Andrew Willimott, Angelo Compagnucci, Angelo and Villas, Annet Vermeer, Anthony Bastardi, Anton Muecki, Antonio Ramos, Arun Rajeevan, Attila Csipa, Ben Goosman, Ben Reinhart, Benjamin, Bernd Rothert, Bill Ferret, Blomqvist, Boris Manojlovic, Branko Vukelic, Brent Zeiben, Brian Cottingham, Brian Harrison, Brian Meredyk, Bruno Rocha, CJ Lazell, Caleb Hattingh, Carlos Galindo, Carlos Hanson, Carsten Haese, Cedric Meyer, Charles Law, Charles Winebrinner, Chris Clark, Chris May, Chris Sanders, Christian Foster Howes, Christopher Smiga, Christopher Steel, Clavin Sim, Cliff Kachinske, Corne Dickens, Craig Younkins, Dan McGee, Dan Ragubba, Dane Wright, Danny Morgan, Daniel Gonz, Daniel Haag, Daniel Lin, Dave Stoll, David Adley, David Harrison, David Lin, David Marko, David Wagner, Denes Lengyel, Diaz Luis, Dirk Krause, Dominic Koenig, Doug Warren, Douglas Philips, Douglas Soares de Andrade, Douglas and Alan, Dustin Bensing, Elcio Ferreira, Eric Vicenti, Erwin Olario, Falko Krause, Farsheed Ashouri, Felipe Meirelles, Flavien Scheurer, Fran Boon, Francisco Gama, Fred Yanowski, Friedrich Weber, Gabriele Alberti, Gergely Kontra, Gergely Peli, Gerley Kontra, Gilson Filho, Glenn Caltech, Graham Dumpleton, Gregory Benjamin, Gustavo Di Pietro, Gyuris Szabolcs, Hamdy Abdel-Badeea, Hans C. v. Stockhausen, Hans Donner, Hans Murx, Huaiyu Wang, Ian Reinhart Geiser, Iceberg, Igor Gassko, Ismael Serratos, Jan Beilicke, Jay Kelkar, Jeff Bauer, Jesus Matrinez, Jim Karsten, Joachim Breitsprecher, Joakim Eriksson, Joe Barnhart, Joel Carrier, Joel Samuelsson, John Heenan, Jon Romero, Jonas Rundberg, Jonathan Benn, Jonathan Lundell, Jose Jachuf, Joseph Piron, Josh Goldfoot, Josh Jaques, Jose Vicente de Sousa, Jurgis Pralgauskis, Keith Yang, Kenji Hosoda, Kenneth Lundstr, Kirill Spitsin, Kyle Smith, Larry Weinberg, Limodou, Loren McGinnis, Louis DaPrato, Luca De Alfaro, Luca Zachetti, Lucas D'Avila, Madhukar R Pai, Manuele Presenti, Marc Abramowitz, Marcel Hellkamp, Marcel Leuthi, Marcello Della Longa, Margaret Greaney, Maria Mitica, Mariano Reingart, Marin Prajic, Marin Pranji, Marius van Niekerk, Mark Kirkwood, Mark Larsen, Mark Moore, Markus Gritsch, Mart Senecal, Martin Hufsky, Martin Mulone, Martin Weissenboeck, Mateusz Banach, Mathew Grabau, Mathieu Clabaut, Matt Doiron, Matthew Norris, Michael Fig, Michael Herman, Michael Howden, Michael Jursa, Michael Toomim, Michael Willis, Michele Comitini, Miguel Goncalves, Miguel Lopez, Mike Amy, Mike Dickun, Mike Ellis, Mike Pechkin, Milan Melena, Muhammet Aydin, Napoleon Moreno, Nathan Freeze, Niall Sweeny, Niccolo Polo, Nick Groenke, Nick Vargish, Nico de Groot, Nico Zanferrari, Nicolas Bruxer, Nik Klever, Olaf Ferger, Oliver Dain, Olivier Roch Vilato, Omi Chiba, Ondrej Such, Ont Rif, Oscar Benjamin, Osman Masood, Ovidio Marinho Falcao Neto, Pai, Panos Jee, Paolo Betti, Paolo Caruccio, Paolo Gasparello, Paolo Valleri, Patrick Breitenbach, Pearu Peterson, Peli Gergely, Pete Hunt, Peter Kirchner, Phyo Arkar Lwin, Pierre Thibault, Pieter Muller, Piotr Banasziewicz, Ramjee Ganti, Richard Gordon, Richard Ree, Robert Kooij, Robert Valentak, Roberto Perdomo, Robin Bhattacharyya, Roman Bataev, Ron McOuat, Ross Peoples, Ruijun Luo, Running Calm, Ryan Seto, Salomon Derossi, Sam Sheftel, Scott Roberts, Sebastian Ortiz, Sergey Podlesnyi, Sharriff Aina, Simone Bizzotto, Sriram Durbha, Sterling Hankins, Stuart Rackham, Telman Yusupov, Thadeus Burgess, Thomas Dallagnese, Tim Farrell, Tim Michelsen, Tim Richardson, Timothy Farrell, Tito Garrido, Tyrone Hattingh, Vasile Ermicioi, Vidul Nikolaev Petrov, Vidul Petrov, Vinicius Assef, Vladimir Donnikov, Vladyslav Kozlovsky, Vladyslav Kozlovskyy, Wang Huaiyu, Wen Gong, Wes James, Will Stevens, Yair Eshel, Yarko Tymciurak, Yoshiyuki Nakamura, Younghyun Jo, Zahariash. I am sure I forgot somebody, so I apologize. I particularly thank Anthony, Jonathan, Mariano, Bruno, Vladyslav, Martin, Nathan, Simone, Thadeus, Tim, Iceberg, Denes, Hans, Christian, Fran and Patrick for their major contributions to web2py and Anthony, Alvaro, Brian, Bruno, Denes, Dane Denny, Erwin, Felipe, Graham, Jonathan, Hans, Kyle, Mark, Margaret, Michele, Nico, Richard, Roberto, Robin, Roman, Scott, Shane, Sharriff, Sriram, Sterling, Stuart, Thadeus, Wen (and others) for proofreading various versions of this book. Their contribution was invaluable. If you find any errors in this book, they are exclusively my fault, probably introduced by a last-minute edit. I also thank Ryan Steffen of Wiley Custom Learning Solutions for help with publishing the first edition of this book. web2py contains code from the following authors, whom I would like to thank: Guido van Rossum for Python[python], Peter Hunt, Richard Gordon, Timothy Farrell for the Rocket[rocket] web server, Christopher Dolivet for EditArea[editarea], Bob Ippolito for simplejson[simplejson], Simon Cusack and Grant Edwards for pyRTF[pyrtf], Dalke Scientific Software for pyRSS2Gen[pyrss2gen], Mark Pilgrim for feedparser[feedparser], Trent Mick for markdown2[markdown2], Allan Saddi for fcgi.py, Evan Martin for the Python memcache module[memcache], John Resig for jQuery[jquery]. I thank Helmut Epp (provost of DePaul University), David Miller (Dean of the College of Computing and Digital Media of DePaul University), and Estia Eichten (Member of MetaCryption LLC), for their continuous trust and support. Finally, I wish to thank my wife, Claudia, and my son, Marco, for putting up with me during the many hours I have spent developing web2py, exchanging emails with users and collaborators, and writing this book. This book is dedicated to them. top
Components and plugins Components and plugins are relatively new features of web2py, and there is some disagreement between developers about what they are and what they should be. Most of the confusion stems from the different uses of these terms in other software projects and from the fact that developers are still working to finalize the specifications. However, plugin support is an important feature and we need to provide some definitions. These definitions are not meant to be final, just consistent with the programming patterns we want to discuss in this chapter. We will try to address two issues here: How can we build modular applications that minimize server load and maximize code reuse? How can we distribute pieces of code in a more or less plugin-and-play fashion? Components address the first issue; plugins address the second. Components Acomponentis a functionally autonomous part of a web page. A component may be composed of modules, controllers and views, but there is no strict requirement other than, when embedded in a web page, it must be localized within an html tag (for example a DIV, a SPAN, or an IFRAME) and it must perform its task independently of the rest of the page. We are specifically interested in components that are loaded in the page and communicate with the component controller function via Ajax. An example of a component is a "comments component" that is contained into a DIV and shows users' comments and a post-new-comment form. When the form is submitted, it is sent to the server via Ajax, the list is updated, and the comment is stored server-side in the database. The DIV content is refreshed without reloading the rest of the page. The web2py LOAD function makes this easy to do without explicit JavaScript/Ajax knowledge or programming. Our goal is to be able to develop web applications by assembling components into page layouts. Consider a simple web2py app "test" that extends the default scaffolding app with a custom model in file "models/db_comments.py": db.define_table('comment_post', Field('body','text',label='Your comment'), auth.signature) one action in "controllers/comments.py" @auth.requires_login() def post(): return dict(form=SQLFORM(db.comment_post).process(), comments=db(db.comment_post).select()) and the corresponding "views/comments/post.html" {{extend 'layout.html'}} {{for post in comments:}} <div class="post"> On {{=post.created_on}} {{=post.created_by.first_name}} says <span class="post_body">{{=post.body}}</span> </div> {{pass}} {{=form}} You can access it as usual at: http://127.0.0.1:8000/test/comments/post So far there is nothing special in this action, but we can turn it into a component by defining a new view with extension ".load" that does not extend the layout. Hence we create a "views/comments/post.load": {{for post in comments:}} <div class="post"> On {{=post.created_on}} {{=post.created_by.first_name}} says <blockquote class="post_body">{{=post.body}}</blockquote> </div> {{pass}} {{=form}} We can access it at the URL http://127.0.0.1:8000/test/comments/post.load This is a component that we can embed into any other page by simply doing {{=LOAD('comments','post.load',ajax=True)}} For example in "controllers/default.py" we can edit def index(): return dict() and in the corresponding view add the component: {{extend 'layout.html'}} {{=LOAD('comments','post.load',ajax=True)}} Visiting the page http://127.0.0.1:8000/test/default/index will show the normal content and the comments component: The {{=LOAD(...)}} component is rendered as follows: <script type="text/javascript"><!-- web2py_component("/test/comment/post.load","c282718984176") //--></script><div id="c282718984176">loading...</div> (the actual generated code depends on the options passed to the LOAD function). The web2py_component(url,id) function is defined in "web2py_ajax.html" and it performs all the magic: it calls the url via Ajax and embeds the response into the DIV with corresponding id; it traps every form submission into the DIV and submits those forms via Ajax. The Ajax target is always the DIV itself. The full signature of the LOAD helper is the following: LOAD(c=None, f='index', args=[], vars={}, extension=None, target=None, ajax=False, ajax_trap=False, url=None,user_signature=False, timeout=None, times=1, content='loading...',**attr): Here: the first two arguments candfare the controller and the function that we want to call respectively. argsandvarsare the arguments and variables that we want to pass to the function. The former is a list, the latter is a dictionary. extensionis an optional extension. Notice that the extension can also be passed as part of the function as inf='index.load'. targetis theidof the target DIV. If it is not specified a random targetidis generated. ajaxshould be set toTrueif the DIV has to be filled via Ajax and toFalseif the DIV has to be filled before the current page is returned (thus avoiding the Ajax call). ajax_trap=Truemeans that any form submission in the DIV must be captured and submitted via Ajax, and the response must be rendered inside the DIV.ajax_trap=Falseindicates that forms must be submitted normally, thus reloading the entire page.ajax_trapis ignored and assumed to beTrueifajax=True. url, if specified, overrides the values ofc,f,args,vars, andextensionand loads the component at theurl. It is used to load as components pages served by other applications (which my or may not be created with web2py). user_signaturedefaults to False but, if you are logged in, it should be set to True. This will make sure the ajax callback is digitally signed. This is documented in chapter 4. timesspecifies how many times the component is to be requested. Use "infinity" to keep loading the component continuously. This option is useful for triggering regular routines for a given document request. timeoutsets the time to wait in milliseconds before starting the request or the frequency iftimesis greater than 1. contentis the content to be displayed while performing the ajax call. It can be a helper as incontent=IMG(..). optional **attr(attributes) can be passed to the containedDIV. If no .load view is specified, there is a generic.load that renders the dictionary returned by the action without layout. It works best if the dictionary contains a single item. If you LOAD a component having the .load extension and the corresponding controller function redirects to another action (for example a login form), the .load extension propagates and the new url (the one to redirect too) is also loaded with a .load extension. If you call an action via Ajax and you want the action to force a redirect of the parent page you can do it with redirect(url,type='auto') Because Ajax post does not support multipart forms, i.e. file uploads, upload fields will not work with the LOAD component. You could be fooled into thinking it would work because upload fields will function normally if POST is done from the individual component's .load view. Instead, uploads are done with ajax-compatible 3rd-party widgets and web2py manual upload store commands. Client-Server component communications When the action of a component is called via Ajax, web2py passes two HTTP headers with the request: web2py-component-location web2py-component-element which can be accessed by the action via the variables: request.env.http_web2py_component_locationrequest.env.http_web2py_component_element The latter is also accessible via: request.cid The former contains the URL of the page that called the component action. The latter contains the id of the DIV that will contain the response. The component action can also store data in two special HTTP response headers that will be interpreted by the full page upon response. They are: web2py-component-flash web2py-component-command and they can be set via: response.headers['web2py-component-flash']='....' response.headers['web2py-component-command']='...' or (if the action is called by a component) automatically via: response.flash='...'response.js='...' The former contains text that you want to be flashed upon response. The latter contains JavaScript code that you want to be executed upon response. It cannot contain newlines. As an example, let's define a contact form component in "controllers/contact/ask.py" that allows the user to ask a question. The component will email the question to the system administrator, flash a "thank you" message, and remove the component from the page: def ask(): form=SQLFORM.factory( Field('your_email',requires=IS_EMAIL()), Field('question',requires=IS_NOT_EMPTY())) if form.process().accepted: if mail.send(to='admin@example.com', subject='from %s' % form.vars.your_email, message = form.vars.question): response.flash = 'Thank you' response.js = "jQuery('#%s').hide()" % request.cid else: form.errors.your_email = "Unable to send the email" return dict(form=form) The first four lines define the form and accept it. The mail object used for sending is defined in the default scaffolding application. The last four lines implement all the component-specific logic by getting data from the HTTP request headers and setting the HTTP response headers. Now you can embed this contact form in any page via {{=LOAD('contact','ask.load',ajax=True)}} Notice that we did not define a .load view for our ask component. We do not have to because it returns a single object (form) and therefore the "generic.load" will do just fine. Remember that generic views are a development tool. In production you should copy "views/generic.load" into "views/contact/ask.load". user_signature argument: {{=LOAD('contact','ask.load',ajax=True,user_signature=True)}} which add a digital signature to the URL. The digital signature must then be validated using a decorator in the callback function: @auth.requires_signature() def ask(): ... Trapped Ajax links Normally a link is not trapped, and by clicking in a link inside a component, the entire linked page is loaded. Sometimes you want the linked page to be loaded inside the component. This can be achieved using the A helper: {{=A('linked page',_href='http://example.com',cid=request.cid)}} If cid is specified, the linked page is loaded via Ajax. The cid is the id of the html element where to place the loaded page content. In this case we set it to request.cid, i.e. the id of the component that generates the link. The linked page can be and usually is an internal URL generated using the URL command. Plugins Apluginis any subset of the files of an application. and we really mean any: A plugin is not a module, is not a model, it is not a controller, is not a view, yet it may contain modules, models, controllers and/or views. A plugin does not need to be functionally autonomous and it may depend on other plugins or specific user code. A pluginis not aplugins systemand therefore has no concept of registration nor isolation, although we will give rules to try to achieve some isolation. We are talking about a plugin for your app, not a plugin for web2py. So why is it called a plugin? Because it provides a mechanism for packing a subset of an app and unpacking it over another app (i.e. plug-in). Under this definition, any file in your app can be treated as a plugin. When the app is distributed, its plugins are packed and distributed with it. In practice, the admin provides an interface for packing and unpacking plugins separately from your app. Files and folder of your application that have names with the prefix plugin_name can be packed together into a file called: web2py.plugin.name.w2p and distributed together. The files that compose a plugin are not treated by web2py any differently than other files except that admin understands from their names that they are meant to be distributed together, and it displays them in a separate page: Yet as a matter of fact, by the definition above, these plugins are more general than those recognized as such by admin. In practice we will only be concerned with two types of plugins: Component Plugins. These are plugins that contain components as defined in the previous section. A component plugin can contain one or more components. We can think for example of aplugin_commentsthat contains thecommentscomponent proposed above. Another example could beplugin_taggingthat contains ataggingcomponent and atag-cloudcomponent that share some database tables also defined by the plugin. Layout Plugins. These are plugins that contain a layout view and the static files required by such layout. When the plugin is applied it gives the app a new look and feel. By the above definitions, the components created in the previous section, for example "controllers/contact.py", are already plugins. We can move them from one app to another and use the components they define. Yet they are not recognized as such by admin because there is nothing that labels them as plugins. So there are two problems we need to solve: Name the plugin files using a convention, so that admincan recognize them as belonging to the same plugin If the plugin has model files, establish a convention so that the objects it defines do not pollute the namespace and do not conflict with each other. Let's assume a plugin is called name. Here are the rules that should be followed: Rule 1: Plugin models and controllers should be called, respectively models/plugin_name.py controllers/plugin_name.py and plugin views, modules, static, and private files should be in folders called, respectively: views/plugin_name/ modules/plugin_name/ static/plugin_name/ private/plugin_name/ Rule 2: Plugin models can only define objects with names that start with plugin_name PluginName _ Rule 3: Plugin models can only define session variables with names that start with session.plugin_name session.PluginName Rule 4: Plugins should include license and documentation. These should be placed in: static/plugin_name/license.html static/plugin_name/about.html Rule 5: The plugin can only rely on the existence of the global objects defined in scaffolding "db.py", i.e. a database connection called db an Authinstance calledauth a Crudinstance calledcrud a Serviceinstance calledservice Some plugins may be more sophisticated and have a configuration parameter in case more than one db instance exists. Rule 6: If a plugin needs configuration parameters, these should be set via a PluginManager as described below. By following the above rules we can make sure that: adminrecognizes all theplugin_namefiles and folder as part of a single entity. plugins do not interfere with each other. The rules above do not solve the problem of plugin versions and dependencies. That is beyond our scope. Component plugins Component plugins are plugins that define components. Components usually access the database and define with their own models. Here we turn the previous comments component into a comments_plugin by using the same code we wrote before, but following all of the previous rules. First, we create a model called "models/plugin_comments.py": db.define_table('plugin_comments_comment', Field('body','text', label='Your comment'), auth.signature) def plugin_comments(): return LOAD('plugin_comments','post',ajax=True) (notice the last two lines define a function that will simplify the embedding of the plugin) Second, we define a "controllers/plugin_comments.py" def post(): if not auth.user: return A('login to comment',_href=URL('default','user/login')) comment = db.plugin_comments_comment return dict(form=SQLFORM(comment).process(), comments=db(comment).select()) Third, we create a view called "views/plugin_comments/post.load": {{for comment in comments:}} <div class="comment"> on {{=comment.created_on}} {{=comment.created_by.first_name}} says <span class="comment_body">{{=comment.body}}</span> </div> {{pass}} {{=form}} Now we can use admin to pack the plugin for distribution. Admin will save this plugin as: web2py.plugin.comments.w2p We can use the plugin in any view by simply installing the plugin via the edit page in admin and adding this to our own views {{=plugin_comments()}} Of course we can make the plugin more sophisticated by having components that take parameters and configuration options. The more complex the components, the more difficult it becomes to avoid name collisions. The Plugin Manager described below is designed to avoid this problem. Plugin manager The PluginManager is a class defined in gluon.tools. Before we explain how it works inside, we will explain how to use it. Here we consider the previous comments_plugin and we make it better. We want to be able to customize: db.plugin_comments_comment.body.label without having to edit the plugin code itself. Here is how we can do it: First, rewrite the plugin "models/plugin_comments.py" in this way: def _(): from gluon.tools import PluginManager plugins = PluginManager('comments', body_label='Your comment') db.define_table('plugin_comments_comment', Field('body','text',label=plugins.comments.body_label), auth.signature) return lambda: LOAD('plugin_comments','post.load',ajax=True) plugin_comments = _() Notice how all the code except the table definition is encapsulated in a single function called _ so that it does not pollute the global namespace. Also notice how the function creates an instance of a PluginManager. Now in any other model in your app, for example in "models/db.py", you can configure this plugin as follows: from gluon.tools import PluginManager plugins = PluginManager() plugins.comments.body_label = T('Post a comment') The plugins object is already instantiated in the default scaffolding app in "models/db.py" The PluginManager object is a thread-level singleton Storage object of Storage objects. That means you can instantiate as many as you like within the same application but (whether they have the same name or not) they act as if there were a single PluginManager instance. In particular each plugin file can make its own PluginManager object and register itself and its default parameters with it: plugins = PluginManager('name', param1='value', param2='value') You can override these parameters elsewhere (for example in "models/db.py") with the code: plugins = PluginManager() plugins.name.param1 = 'other value' You can configure multiple plugins in one place. plugins = PluginManager() plugins.name.param1 = '...' plugins.name.param2 = '...' plugins.name1.param3 = '...' plugins.name2.param4 = '...' plugins.name3.param5 = '...' When the plugin is defined, the PluginManager must take arguments: the plugin name and optional named arguments which are default parameters. However, when the plugins are configured, the PluginManager constructor must take no arguments. The configuration must precede the definition of the plugin (i.e. it must be in a model file that comes first alphabetically). Layout plugins Layout plugins are simpler than component plugins because usually they do not contain code, but only views and static files. Yet you should still follow good practice: First, create a folder called "static/plugin_layout_name/" (where name is the name of your layout) and place all your static files there. Second, create a layout file called "views/plugin_layout_name/layout.html" that contains your layout and links the images, CSS and JavaScript files in "static/plugin_layout_name/" Third, modify the "views/layout.html" so that it simply reads: {{extend 'plugin_layout_name/layout.html'}} {{include}} The benefit of this design is that users of this plugin can install multiple layouts and choose which one to apply simply by editing "views/layout.html". Moreover, "views/layout.html" will not be packed by admin together with the plugin, so there is no risk that the plugin will override the user's code in the previously installed layout. Plugins repositories While there is no single repository of web2py plugins you can find many of them at one of the following to URLs: http://dev.s-cubism.com/web2py_plugins http://web2py.com/plugins http://web2py.com/layouts Here is a screenshot from the s-cubism repository: top
My view code looks basically like this: context = Context() context['some_values'] = ['a', 'b', 'c', 'd', 'e', 'f'] context['other_values'] = [4, 8, 15, 16, 23, 42] I would like my template code to look like this: {% for some in some_values %} {% with index as forloop.counter0 %} {{ some }} : {{ other_values.index }} <br/> {% endwith %} {% endfor %} And I would expect this to output: a : 4 <br/> b : 8 <br/> c : 15 <br/> d : 16 <br/> e : 23 <br/> f : 42 <br/> Is this possible? I'm finding that my "with" statement is actually working, but then using that variable as a reference isn't working. I suspect that for {{ other_values.index }} it's doing other_values['index'] instead of other_values[index]. Is this possible?
I have the following test script, which mimics what I usually do to setup an extended logger: import logging TRACE_LL = 25 TRACE_LSTR = 'TRACE' LOG_FORMATTER = '%(asctime)s - %(levelname)-10s - %(message)s' class MyLogger(logging.Logger): def __init__(self, log_name): logging.Logger.__init__(self, log_name) self.setLevel(TRACE_LL) hdlr = logging.StreamHandler() formatter = logging.Formatter(LOG_FORMATTER) hdlr.setFormatter(formatter) self.addHandler(hdlr) def trace(self, txt, *args, **kwargs): self.log(TRACE_LL, txt, *args, **kwargs) def getlog(name): return logging.getLogger(name) def setup(): logging.setLoggerClass(MyLogger) logging.addLevelName(TRACE_LL, TRACE_LSTR) setup() log = getlog('mylog') log.trace('Trace this') Running this works as expected: 2014-01-07 07:22:59,982 - TRACE - Trace this But running pylint on this causes trouble: » pylint -E getlog_test.py No config file found, using default configuration ************* Module getlog_test E: 29,0: Instance of 'RootLogger' has no 'trace' member (but some types could not be inferred) I get hundreds of those messages in my codebase, because I am using logging extensively. How can I solve the pylint error? As an alternative, disabling it would also be enough, but only for the RootLogger instance: I still want to know if other parts of the code have this problem.
I need to create a form and have the form upload an image and save it to my disk. Here is my code import web urls = ( '/hello', 'Index', '/file_upload_form', 'ThatFile' ) app = web.application(urls, globals()) render = web.template.render('templates/', base = "layout") class ThatFile(object): def GET(self): return render.file_upload_form() def POST(self): form = web.input(image = "loc") open(form.image,'r') image_o = form.image.read() return render.thatfile(o_image = o_image) class Index(object): def GET(self): return render.hello_form() def POST(self): form = web.input(name = "Nobody", greet = None) greeting = "%s, %s" % (form.greet, form.name) return render.index(greeting = greeting) if __name__ == "__main__": app.run() I have tried using PIL Image module but it does not display the image.
Some of the capabilities listed in these pages for Dispatch are for future releases and are supplied for the purpose of illustrating the potential of a message router. This section outlines the actual capabilities of version 0.1: $ tar -xzf qpid-dispatch-0.1.tar.gz Source the build configuration: $ cd qpid-dispatch-0.1 $ source config.sh Build and test the package. This will create two directories: 'build' and 'install'. Dispatch will be built in the 'build' directory and installed in the 'install' directory. The regression and system test suites will then be run against the installed bits. $ bin/test.sh If you wish to change the build configuration, go into the build directory, use cmake to configure your build then rebuild and/or reinstall from there: $ cd build$ cmake ..$ make$ make install The default configuration file is installed ininstall-prefix/etc/qpid/qdrouterd.conf. This configuration file will cause the routerto run in standalone mode, listening on the standard AMQP port (5672). Dispatch Routerlooks for the configuration file in the installed location by default. If you wishto use a different path, the "-c" command line option will instruct Dispatch Router as towhich configuration to load. To run the router, invoke the executable: $ qdrouterd Dispatch Router should, in theory, work with any client that is compatible with AMQP 1.0. The following clients have been tested: Client Notes qpid::messaging The Qpid messaging clients work with Dispatch Router as long as they are configured to use the 1.0 version of the protocol. To enable AMQP 1.0 in the C++ client, use the {protocol:amqp1.0} connection option. Proton Messenger Messenger works with Dispatch Router. Installed with the Dispatch Router kit is a command line tool called qdstat. This toolcan be used to view manageable data inside Dispatch Router. The following options areuseful for seeing that the router is doing: Option Description -l Print a list of AMQP links attached to the router. Links are unidirectional. Outgoing links are usually associated with a subscription address. The tool distinguishes between endpoint links and router links. Endpoint links are attached to clients using the router. Router links are attached to other routers in a network of routers. -a Print a list of addresses known to the router. -n Print a list of known routers in the network. -c Print a list of connections to the router. The router can operate stand-alone or as a node in a network of routers. The mode isconfigured in the router section of the configuration file. In stand-alone mode, therouter does not attempt to collaborate with any other routers and only routes messagesamong directly connected endpoints. If your router is running in stand-alone mode, qdstat -a will look like the following: $ qdstat -a Router Addresses class address in-proc local remote in out thru to-proc from-proc =============================================================================== local $management Y 0 0 1 0 0 1 0 local temp.AY81ga 1 0 0 0 0 0 0 Note that there are two known addresses. $management is the address of the router's embedded management agent. temp.AY81ga is the temporary reply-to address of the qdstat client making requests to the agent. If you change the mode to interior and restart the processs, the same command will yield two additional addresses which are used for inter-router communication: $ qdstat -a Router Addresses class address in-proc local remote in out thru to-proc from-proc =============================================================================== local $management Y 0 0 1 0 0 1 0 local qdhello Y 0 0 0 0 0 0 3 local qdrouter Y 0 0 0 0 0 0 1 local temp.khOpGb 1 0 0 0 0 0 0 The term "mobile subscriber" simply refers to the fact that a client may connect to the router and subscribe to an address to receive messages sent to that address. No matter where in the network the subscriber attaches, the messages will be routed to the appropriate destination. To illustrate a subscription on a stand-alone router, you can use the examples that areprovided with Qpid Proton. Using the recv.py example receiver: $ recv.py amqp://0.0.0.0/my-address This command creates a receiving link subscribed to the specified address. To verify the subscription: $ qdstat -a Router Addresses class address in-proc local remote in out thru to-proc from-proc ================================================================================ local $management Y 0 0 1 0 0 1 0 mobile my-address 1 0 0 0 0 0 0 local temp.fDt8_a 1 0 0 0 0 0 0 You can then, in a separate command window, run a sender to produce messages to that address: $ send.py -a amqp://0.0.0.0/my-address Dynamic reply-to can be used to obtain a reply-to address that routes back to a client's receiving link regardless of how many hops it has to take to get there. To illustrate this feature, see below a simple program (written in C++ against the qpid::messaging API) that queries the management agent of the attached router for a list of other known routers' management addresses. #include <qpid/messaging/Address.h> #include <qpid/messaging/Connection.h> #include <qpid/messaging/Message.h> #include <qpid/messaging/Receiver.h> #include <qpid/messaging/Sender.h> #include <qpid/messaging/Session.h> using namespace qpid::messaging; using namespace qpid::types; using std::stringstream; using std::string; int main() { const char* url = "amqp:tcp:127.0.0.1:5672"; std::string connectionOptions = "{protocol:amqp1.0}"; Connection connection(url, connectionOptions); connection.open(); Session session = connection.createSession(); Sender sender = session.createSender("mgmt"); // create reply receiver and get the reply-to address Receiver receiver = session.createReceiver("#"); Address responseAddress = receiver.getAddress(); Message request; request.setReplyTo(responseAddress); request.setProperty("x-amqp-to", "amqp:/_local/$management"); request.setProperty("operation", "DISCOVER-MGMT-NODES"); request.setProperty("type", "org.amqp.management"); request.setProperty("name, "self"); sender.send(request); Message response = receiver.fetch(); Variant content(response.getContentObject()); std::cout << "Response: " << content << std::endl << std::endl; connection.close(); } The equivalent program written in Python against the Proton Messenger API: from proton import Messenger, Message def main(): host = "0.0.0.0:5672" messenger = Messenger() messenger.start() messenger.route("amqp:/*", "amqp://%s/$1" % host) reply_subscription = messenger.subscribe("amqp:/#") reply_address = reply_subscription.address request = Message() response = Message() request.address = "amqp:/_local/$management" request.reply_to = reply_address request.properties = {u'operation' : u'DISCOVER-MGMT-NODES', u'type' : u'org.amqp.management', u'name' : u'self'} messenger.put(request) messenger.send() messenger.recv() messenger.get(response) print "Response: %r" % response.body messenger.stop() main() This is an early test release. It is expected that users will find bugs and other various instabilities. The main goal of this release is to prove that the process can be run and that users can demonstrate basic functionality as described in this document. Nevertheless, the following are known issues with the 0.1 release: Apache Qpid, Messaging built on AMQP; Copyright © 2013 The Apache Software Foundation; Licensed under the Apache License, Version 2.0; Apache Qpid, Qpid, Qpid Proton, Proton, Apache, the Apache feather logo, and the Apache Qpid project logo are trademarks of The Apache Software Foundation; All other marks mentioned may be trademarks or registered trademarks of their respective owners
Consider the two following Python code examples, which achieves the same but with significant and surprising performance difference. import psycopg2, time conn = psycopg2.connect("dbname=mydatabase user=postgres") cur = conn.cursor('cursor_unique_name') cur2 = conn.cursor() startTime = time.clock() cur.execute("SELECT * FROM test for update;") print ("Finished: SELECT * FROM test for update;: " + str(time.clock() - startTime)); for i in range (100000): cur.fetchone() cur2.execute("update test set num = num + 1 where current of cursor_unique_name;") print ("Finished: update starting commit: " + str(time.clock() - startTime)); conn.commit() print ("Finished: update : " + str(time.clock() - startTime)); cur2.close() conn.close() And: import psycopg2, time conn = psycopg2.connect("dbname=mydatabase user=postgres") cur = conn.cursor('cursor_unique_name') cur2 = conn.cursor() startTime = time.clock() for i in range (100000): cur2.execute("update test set num = num + 1 where id = " + str(i) + ";") print ("Finished: update starting commit: " + str(time.clock() - startTime)); conn.commit() print ("Finished: update : " + str(time.clock() - startTime)); cur2.close() conn.close() The create statement for the table test is: CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar); And that table contains 100000 rows and VACUUM ANALYZE TEST; has been run. I got the following results consistently on several attempts. First code example: Finished: SELECT * FROM test for update;: 0.00609304950429 Finished: update starting commit: 37.3272754429 Finished: update : 37.4449708474 Second code example: Finished: update starting commit: 24.574401185Finished committing: 24.7331461431 This is very surprising to me as I would think is should be exactly opposite, meaning that an update using cursor should be significantly faster according to this answer.
JavaScript ckdoublenecks — 2011-04-11T12:23:44-04:00 — #1 I took a working program and modified it to use different values and can't seem to make it work now. I want have the datepaid, pd & paidsum insert when I key in the amtpaid . <html><head> <!--when the paidamt is keyed in, the current date, pd & paidsum are autoinserted--> <script> function $_(IDS) { return document.getElementById(IDS); } function calculate_paid() { var invnum = document.getElementById("invnum"); var ordernum = document.getElementById("ordernum"); var bname = document.getElementById("bname"); var charges = document.getElementById("charges"); var paidamt = document.getElementById("paidamt"); var tax = document.getElementById("tax"); var datepaid = document.getElementById("datepaid"); var pd = document.getElementById("pd"); var paidsum = document.getElementById("paidsum"); <!--********************set up date**********************--> var dateNow = new Date(); var dayNow = dateNow.getDate(); var datePaid = (dateNow.getMonth()+1)+"/"+dateNow.getDate()+"/"+dateNow.getFullYear(); datepaid.value = datePaid; <!--end date setup--> <!--accumulate charges into paidsum, calculate tax, set up pd & calculate dayslate (?)--> charges.value = parseFloat(charges.value); paidsum.value = parseFloat(paidsum.value) + parseFloat(paidamt.value); tax.value= parseFloat(charges.value) * .06; pd.value = "P"; <!--********************* end of calcs ******************--> </script> <script type="text/javascript"> window.google_analytics_uacct = "UA-256751-2"; </script> <script type="text/javascript"> window.google_analytics_uacct = "UA-256751-2"; </script> </head><body><form method="post" action="#"> <br /> <input type="text" name="invnum"/> <p> <input type="submit" name="submit" value="select inv#"/> </form> <script type="text/javascript"><!-- var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); //--> </script> <script type="text/javascript"><!-- try { var pageTracker = _gat._getTracker("UA-256751-2"); pageTracker._trackPageview(); } catch(err) {} //--> </script> <script type="text/javascript"><!-- var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); //--> </script> <script type="text/javascript"><!-- try { var pageTracker = _gat._getTracker("UA-256751-2"); pageTracker._trackPageview(); } catch(err) {} //--> </script> </body></html> raffles — 2011-04-11T12:33:53-04:00 — #2 To encourage people to take your post more seriously, you need to strip out the irrelevant garbage and post only the necessary code to understand the problem. If PHP is not relevant to the issue, just post the HTML the javascript will be working with. In addition, you need to be clearer when explaining the issue. For example, "amtpaid" doesn't exist anywhere in the code you posted. ckdoublenecks — 2011-04-11T13:00:44-04:00 — #3 thanks a lot for the help. please look at it now. I can't believe I can't convert my working version to this ? raffles — 2011-04-11T13:09:17-04:00 — #4 Still a lot of garbage there (all the google analytics stuff) making it harder to read. Plus, it's impossible to see how this all works, since it looks like some of the HTML is missing. The only visible HTML is this: <form method="post" action="#"> <br /> <input type="text" name="invnum"/> <p> <input type="submit" name="submit" value="select inv#"/> </form> Plus, it's impossible to see how calculate_paid() is supposed to be called, or where all these values are supposed to go. Pretty obvious really, but you need to think carefully about what it's like for someone unfamiliar with your code to try to help you. You can't supply half the information necessary and expect them to understand what's going on. ckdoublenecks — 2011-04-11T13:22:08-04:00 — #5 You guys do a great job and I know its to hard to see what I'm trying to do. below I've disclosed the javascript and below that the input portion. I really hope you can help .<script> function $_(IDS) { return document.getElementById(IDS); } function calculate_paid() { var invnum = document.getElementById("invnum"); var ordernum = document.getElementById("ordernum"); var bname = document.getElementById("bname"); var charges = document.getElementById("charges"); var paidamt = document.getElementById("paidamt"); var tax = document.getElementById("tax"); var datepaid = document.getElementById("datepaid"); var pd = document.getElementById("pd"); var paidsum = document.getElementById("paidsum"); <!--********************set up date**********************--> var dateNow = new Date(); var dayNow = dateNow.getDate(); var datePaid = (dateNow.getMonth()+1)+"/"+dateNow.getDate()+"/"+dateNow.getFullYear(); datepaid.value = datePaid; <!--end date setup--> <!--accumulate charges into paidsum, calculate tax, set up pd & calculate dayslate (?)--> charges.value = parseFloat(charges.value); paidsum.value = parseFloat(paidsum.value) + parseFloat(paidamt.value); tax.value= parseFloat(charges.value) * .06; pd.value = "P"; <!--********************* end of calcs ******************--> </script> <td><input type='text' size=5 name='invnum' value='" . $row['invnum'] . "'></td> <td><input type='text' size=5 name='ordernum' value='" . $row['ordernum'] . "'></td> <td><input type='text' size=25 name='bname' value='" . $row['bname'] . "' ></td> <td><input type='text' size=25 name='descr' value='" . $row['descr'] . "' ></td> <td><input type='text' size=7 id='paidamt' name='paidamt' value='" . $row['paidamt'] ."' onBlur='calculate_paid(this)'></td> <td><input type='text' size=7 id='charges' name='charges' value='" . $row['charges'] ."' onBlur='calculate_paid(this)'></td> <td><input type='text' size=10 id='datepaid' name='datepaid' value='" . $row['datepaid'] . "'></td> <td><input type='text' size=1 id='pd' name='pd' value='" . $row['pd'] . "'></td> <td><input type='text' size=7 name='paidsum' value='" . $row['paidsum'] . "' ></td> raffles — 2011-04-11T14:24:11-04:00 — #6 Much better. Obviously this is what you should have posted from the outset. So are you saying that when you click away from paidamt, the values for charges and paidsum do not appear? The likelihood is because you've sprinkled the JavaScript with these HTML comments (not sure why I didn't notice that before!): <!--********************set up date**********************--> JavaScript comments are like this: // an inline comment /* A block comment */ HTML comments will therefore be invalid JavaScript. This would probably have been picked up had you used Firebug or some other debugging software. ckdoublenecks — 2011-04-11T14:43:08-04:00 — #7 So are you saying that when you click away from paidamt, the values for charges and paidsum do not appear? that is what is happening - The likelihood is because you've sprinkled the JavaScript with these HTML comments I recommented but still the same results raffles — 2011-04-11T18:24:21-04:00 — #8 The calculate_paid function doesn't have a closing brace ( } ). Like I said, simple things like these would be caught by Firebug. centered_effect — 2011-04-11T19:56:00-04:00 — #9 Try this example to help you out based on some of the code you provided: <html> <body> <form name="testForm"> <label>PAIDAMT</label> <input type='text' name='paidamt' value='' /> <br /> <label>DATEPAID</label> <input type='text' name='datepaid' value='' /> <br /> <label>PD</label> <input type='text' name='pd' value='' /> <br /> <label>PAIDSUM</label> <input type='text' name='paidsum' value='' /> <br /> </form> <script> document.testForm.paidamt.onblur = function() { document.testForm.datepaid.value = currDate(); document.testForm.pd.value = 'P'; document.testForm.paidsum.value = this.value * 0.6; } function currDate() { var dateNow = new Date(), dayNow = dateNow.getDate(); return (dateNow.getMonth()+1)+"/"+dateNow.getDate()+"/"+dateNow.getFullYear(); } </script> </body> </html> ckdoublenecks — 2011-04-12T21:02:38-04:00 — #10 with this code everything jumps into place but i get: update query failed <html><head> <!--when the paidamt is keyed in, the current date, pd & paidsum are autoinserted--> <script> function $_(IDS) { return document.getElementById(IDS); } function calculate_paid() { var invnum = document.getElementById("invnum"); var ordernum = document.getElementById("ordernum"); var bname = document.getElementById("bname"); var charges = document.getElementById("charges"); var paidamt = document.getElementById("paidamt"); var tax = document.getElementById("tax"); var datepaid = document.getElementById("datepaid"); var pd = document.getElementById("pd"); var paidsum = document.getElementById("paidsum"); // ********************set up date********************** var dateNow = new Date(); var dayNow = dateNow.getDate(); var datePaid = (dateNow.getMonth()+1)+"/"+dateNow.getDate()+"/"+dateNow.getFullYear(); datepaid.value = datePaid; // end date setup // accumulate charges into paidsum, calculate tax, set up pd & calculate dayslate (?) charges.value = parseFloat(charges.value); paidsum.value = parseFloat(paidsum.value) + parseFloat(paidamt.value); pd.value = "P"; // ********************* end of calcs ****************** } </script> <script type="text/javascript"> window.google_analytics_uacct = "UA-256751-2"; </script> <script type="text/javascript"> window.google_analytics_uacct = "UA-256751-2"; </script> </head><body> <?php mysql_connect(localhost,root,""); mysql_select_db(oodb) or die( "Unable to select database"); if(!empty($_POST["submit"])) { $invnum = $_POST['invnum']; $query="SELECT * FROM oocust Where invnum='$invnum'"; $result=mysql_query($query); if(mysql_num_rows($result)) { echo "<form action='#' method='post'><b>Invoice Payment :<br /><br /> <table cellspacing=0 cellpadding=0 border=1> <tr> <th>Inv#</th> <th>ord#</th> <th>Name</th> <th>Description</th> <th>Paid</th> <th>Charges</th> <th>Date Paid</th> <th>Pd</th> <th>Total</th> </tr>"; while($row = mysql_fetch_assoc($result)) { echo "<tr> <td><input type='text' size=5 name='invnum' value='" . $row['invnum'] . "'></td> <td><input type='text' size=5 name='ordernum' value='" . $row['ordernum'] . "'></td> <td><input type='text' size=25 name='bname' value='" . $row['bname'] . "' ></td> <td><input type='text' size=25 name='descr' value='" . $row['descr'] . "' ></td> <td><input type='text' size=7 id='paidamt' name='paidamt' value='" . $row['paidamt'] ."' onBlur='calculate_paid(this)'></td> <td><input type='text' size=7 id='charges' name='charges' value='" . $row['charges'] ."' onBlur='calculate_paid(this)'></td> <td><input type='text' size=10 id='datepaid' name='datepaid' value='" . $row['datepaid'] . "' onBlur='calculate_paid(this)'></td> <td><input type='text' size=1 id='pd' name='pd' value='" . $row['pd'] . "'></td> <td><input type='text' size=7 name='paidsum' value='" . $row['paidsum'] . "' ></td> </tr>"; } echo "</table> <input type='submit' name='update' value='Make Payment' /> </form>"; } else{echo "No listing for invoice# $invnum.<br />Please select another.<br />";} } if(!empty($_POST["update"])) { $sql = "UPDATE payments SET invnum = '" . mysql_real_escape_string($_POST['invnum']) . "', ordernum = '" . mysql_real_escape_string($_POST['ordernum']) . "', bname = '" . mysql_real_escape_string($_POST['bname']) . "', descr = '" . mysql_real_escape_string($_POST['descr']) . "', paidamt = '" . mysql_real_escape_string($_POST['paidamt']) . "', charges = '" . mysql_real_escape_string($_POST['charges']) . "', datepaid = '" . mysql_real_escape_string($_POST['datepaid']) . "', pd = '" . mysql_real_escape_string($_POST['pd']) . "', paidsum = '" . mysql_real_escape_string($_POST['paidsum']) . "' WHERE invnum='".$_POST["invnum"]."'"; mysql_query($sql) or die("Update query failed."); echo "Record for invoice ".$_POST["invnum"]." has been updated"; } ?> <form method="post" action="#"> <br /> <input type="text" name="invnum"/> <p> <input type="submit" name="submit" value="select inv#"/> </form> <script type="text/javascript"><!-- var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); //--> </script> <script type="text/javascript"><!-- try { var pageTracker = _gat._getTracker("UA-256751-2"); pageTracker._trackPageview(); } catch(err) {} //--> </script> <script type="text/javascript"><!-- var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); //--> </script> <script type="text/javascript"><!-- try { var pageTracker = _gat._getTracker("UA-256751-2"); pageTracker._trackPageview(); } catch(err) {} //--> </script> </body></html>
is it possible to set a number or an element of an array to NaN in Python? Additionally, is it possible to set a variable to +/- Inf? If so, is there any function to check whether a number is Inf or not? Thanks Cast from string using >>> float('NaN') nan >>> float('Inf') inf >>> -float('Inf') -inf >>> float('Inf') == float('Inf') True >>> float('Inf') == 1 False Yes, you can use import numpy as np a = arange(3,dtype=float) a[0] = np.nan a[1] = np.inf a[2] = -np.inf a # is now [nan,inf,-inf] np.isnan(a[0]) # True np.isinf(a[1]) # True np.isinf(a[2]) # True
I need to use a bi-directional relationship in Mongoengine which is something like the below. from mongoengine import * class Notification(Document): desc = StringField() from_user = ReferenceField('User') class User(Document): Name = StringField() notifications = ListField(EmbeddedDocumentField(Notification)) I know we can put single quoted class name there when the class has not yet defined. from_user = ReferenceField('User') However, we got a problem here. Seems like in runtime it interprets our class as mongoengine.django.auth.user instead of our custom user class. (This is just what I guess but in runtime during debug mode I find that it misinterprets it as mongoengine.django.auth.user although the record in the collections should belong to the custom user class) So is there any way for me to specify a fully qualified class name there? Thanks!
It looks like you're new here. If you want to get involved, click one of these buttons! script method, a QScript will add one or more CommandLineFunctions.@Input and @Output.@Input of CommandLineFunction A depends on the @Output of ComandLineFunction B, A will wait for B to finish before it starts running. Each CommandLineFunction must define the actual command line to run as follows. class MyCommandLine extends CommandLineFunction { def commandLine = "myScript.sh hello world" } If you're writing a one-off CommandLineFunction that is not destined for use by other QScripts, it's often easiest to construct the command line directly rather than through the API methods provided in the CommandLineFunction class. For example: def commandLine = "cat %s | grep -v \"#\" > %s".format(files, out) If you're writing a CommandLineFunction that will become part of Queue and/orwill be used by other QScripts, however, our best practice recommendation isto construct your command line only using the methods provided in the CommandLineFunction class: required(), optional(), conditional(), and repeat() The reason for this is that these methods automatically escape the values yougive them so that they'll be interpreted literally within the shell scriptsQueue generates to run your command, and they also manage whitespace separation of command-line tokens for you. This prevents (for example) a value like MQ > 10 from being interpreted as an output redirection by the shell, and avoids issues with values containing embedded spaces. The methods also give you the ability to turn escaping and/or whitespace separation off as needed. An example: override def commandLine = super.commandLine + required("eff") + conditional(verbose, "-v") + optional("-c", config) + required("-i", "vcf") + required("-o", "vcf") + required(genomeVersion) + required(inVcf) + required(">", escape=false) + // This will be shell-interpreted as an output redirection required(outVcf) The CommandLineFunctions built into Queue, including the CommandLineFunctionsautomatically generated for GATK Walkers, are all written using this pattern.This means that when you configure a GATK Walker or one of the other built-inCommandLineFunctions in a QScript, you can rely on all of your values beingsafely escaped and taken literally when the commands are run, including valuescontaining characters that would normally be interpreted by the shell such asMQ > 10. Below is a brief overview of the API methods available to you in the CommandLineFunction class for safely constructing command lines: required() Used for command-line arguments that are always present, e.g.: required("-f", "filename") returns: " '-f' 'filename' " required("-f", "filename", escape=false) returns: " -f filename " required("java") returns: " 'java' " required("INPUT=", "myBam.bam", spaceSeparated=false) returns: " 'INPUT=myBam.bam' " optional() Used for command-line arguments that may or may not be present, e.g.: optional("-f", myVar) behaves like required() if myVar has a value, but returns "" if myVar is null/Nil/None conditional() Used for command-line arguments that should only be included if some condition is true, e.g.: conditional(verbose, "-v") returns " '-v' " if verbose is true, otherwise returns "" repeat() Used for command-line arguments that are repeated multiple times on the command line, e.g.: repeat("-f", List("file1", "file2", "file3")) returns: " '-f' 'file1' '-f' 'file2' '-f' 'file3' " CommandLineFunction arguments use a similar syntax to arguments. class MyCommandLine extends CommandLineFunction { @Input(doc="input file") var inputFile: File = _ def commandLine = "myScript.sh -fileParam " + inputFile } CommandLineFunction variables can also provide indirect access to java.io.File inputs and outputs via the FileProvider trait. class MyCommandLine extends CommandLineFunction { @Input(doc="named input file") var inputFile: ExampleFileProvider = _ def commandLine = "myScript.sh " + inputFile } // An example FileProvider that stores a 'name' with a 'file'. class ExampleFileProvider(var name: String, var file: File) extends org.broadinstitute.sting.queue.function.FileProvider { override def toString = " -fileName " + name + " -fileParam " + file } Optional files can be specified via required=false, and can use the CommandLineFunction.optional() utility method, as described above: class MyCommandLine extends CommandLineFunction { @Input(doc="input file", required=false) var inputFile: File = _ // -fileParam will only be added if the QScript sets inputFile on this instance of MyCommandLine def commandLine = required("myScript.sh") + optional("-fileParam", inputFile) } A List or Set of files can use the CommandLineFunction.repeat() utility method, as described above: class MyCommandLine extends CommandLineFunction { @Input(doc="input file") var inputFile: List[File] = Nil // NOTE: Do not set List or Set variables to null! // -fileParam will added as many times as the QScript adds the inputFile on this instance of MyCommandLine def commandLine = required("myScript.sh") + repeat("-fileParam", inputFile) } A command line function can define other required arguments via @Argument. class MyCommandLine extends CommandLineFunction { @Argument(doc="message to display") var veryImportantMessage: String = _ // If the QScript does not specify the required veryImportantMessage, the pipeline will not run. def commandLine = required("myScript.sh") + required(veryImportantMessage) } class SamToolsIndex extends CommandLineFunction { @Input(doc="bam to index") var bamFile: File = _ @Output(doc="bam index") var baiFile: File = _ def commandLine = "samtools index %s %s".format(bamFile, baiFile) ) Or, using the CommandLineFunction API methods to construct the command line with automatic shell escaping: class SamToolsIndex extends CommandLineFunction { @Input(doc="bam to index") var bamFile: File = _ @Output(doc="bam index") var baiFile: File = _ def commandLine = required("samtools") + required("index") + required(bamFile) + required(baiFile) ) Geraldine Van der Auwera, PhD
Webpage screenshots with webkit For a recent project I needed to render screenshots of webpages. Here is my solution using webkit: import sys import time from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtWebKit import * class Screenshot(QWebView): def __init__(self): self.app = QApplication(sys.argv) QWebView.__init__(self) self._loaded = False self.loadFinished.connect(self._loadFinished) def capture(self, url, output_file): self.load(QUrl(url)) self.wait_load() # set to webpage size frame = self.page().mainFrame() self.page().setViewportSize(frame.contentsSize()) # render image image = QImage(self.page().viewportSize(), QImage.Format_ARGB32) painter = QPainter(image) frame.render(painter) painter.end() print 'saving', output_file image.save(output_file) def wait_load(self, delay=0): # process app events until page loaded while not self._loaded: self.app.processEvents() time.sleep(delay) self._loaded = False def _loadFinished(self, result): self._loaded = True s = Screenshot() s.capture('http://webscraping.com', 'website.png') s.capture('http://webscraping.com/blog', 'blog.png') Source code is available at my bitbucket account.
I'm optimizing some code whose main bottleneck is running through and accessing a very large list of struct-like objects. Currently I'm using namedtuples, for readability. But some quick benchmarking using 'timeit' shows that this is really the wrong way to go where performance is a factor: Named tuple with a, b, c: >>> timeit("z = a.c", "from __main__ import a") 0.38655471766332994 Class using __slots__, with a, b, c: >>> timeit("z = b.c", "from __main__ import b") 0.14527461047146062 Dictionary with keys a, b, c: >>> timeit("z = c['c']", "from __main__ import c") 0.11588272541098377 Tuple with three values, using a constant key: >>> timeit("z = d[2]", "from __main__ import d") 0.11106188992948773 List with three values, using a constant key: >>> timeit("z = e[2]", "from __main__ import e") 0.086038238242508669 Tuple with three values, using a local key: >>> timeit("z = d[key]", "from __main__ import d, key") 0.11187358437882722 List with three values, using a local key: >>> timeit("z = e[key]", "from __main__ import e, key") 0.088604143037173344 First of all, is there anything about these little timeit tests that would render them invalid? I ran each several times, to make sure no random system event had thrown them off, and the results were almost identical. It would appear that dictionaries offer the best balance between performance and readability, with classes coming in second. This is unfortunate, since, for my purposes, I also need the object to be sequence-like; hence my choice of namedtuple. Lists are substantially faster, but constant keys are unmaintainable; I'd have to create a bunch of index-constants, i.e. KEY_1 = 1, KEY_2 = 2, etc. which is also not ideal. Am I stuck with these choices, or is there an alternative that I've missed?
Der Bus ist Baujahr 1979 und hat seinen zweiten Motor. Innen voll ausgebaut als Wohnmobil. Ich habe ihn vor einem Jahr gekauft. ZUSTAND: Der Wagen f&auml… via Google+ Die Deutsche Bahn plant zum nächsten Fahrplanwechsel massive Zugstreichungen im internationalen Bereich. Insbesondere die Streichung der Verbindung… via Google+ +++ WM-GEWINNSPIEL +++ Unter allen Spendern verlosen wir ein handsigniertes Paar Fußballschuhe ADIDAS PREDATOR von Mesut Özil. Der Erlös geht zu 100% an BigShoe. Seit 2006 sammelt BigShoe Spenden, um hilfsbedürftigen Kindern lebensnotwendige Operationen zu ermöglichen. via Google+ Will sie jemand kaufen? KLE 500 – Bastlerprojekt. Leider habe ich keine Zeit zum Schrauben dieses Jahr – die gute hat über ein Jahr gestanden und müsste wieder aufgepäppelt werden. Baujahr 97, 47.000 km 2012 wurden noch die Kette, Reifen und Bremsscheibe vorn neu gemacht. Reifen hinten noch ca. 90%, aber nicht neu. Sitzbank wurde von ein paar Jahren neu bezogen und etwas aufgepolstert – nicht mehr ganz schön, aber ohne Risse. Das Topcase vom Foto wurde aufgebrochen und ist nicht mehr dabei. Elektrik scheint soweit o.k. zu sein. Sie hatte lange gestanden und springt nicht an, davor immer gut gelaufen. TÜV abgelaufen. Laut Werkstatt ist (mindestens) Folgendes zu machen: * Vergaser muss zerlegt und gereinigt werden, vermutlich auch Zündkerzen neu * Bremssattel hinten sitzt fest, muss auch gereinigt werden * Wäsche dringend notwendig (verklebt von Baumzeugs) * Simmeringe Vordergabel undicht * Schalter sind schwergängig VB 400 EUR. Nur Selbstabholer in Berlin. KEIN Verkauf in Einzelteilen. Nicht fahrbereit. undefined via Google+ I’ve just figured out a quite obscure bug in our app. It all started like this: record.freeze.things # record is an ActiveRecord, and "things" is an association on that record. TypeError: can't modify frozen object from (irb):2:in `instance_variable_set' from (irb):2 The code above shouldn’t crash, because ActiveRecord hast its own #freeze method, which will still allow access to the associations. But our record behaved as if Object#freeze had been called on it. What happend?
Thanks to the_jack providing access to his box, got a fix. See this ticket for info: http://dev.zenoss.loc/trac/ticket/7196. You can fix everything like so: $ zenpatch 22038 $ zendmd >>> for b in dmd.global_catalog(): ...     dmd.global_catalog.catalog_object(b.getObject(), idxs=["allowedRolesAndUsers"]) ... >>> commit() I'm not yet clear on the conditions that bring out this bug in CMFCore, but this will definitely take care of it. This fix will be in 3.0.2 as well. --Ian for b in dmd.global_catalog():dmd.global_catalog.catalog_object(b.getObject(),idxs=["allowedRolesAndUsers"])commit() s_aldinger: Sorry, should have said: restart Zenoss after you patch in the change, otherwise nothing's got the new code and will still do it the old way. Adrian: The fix will apply to Locations just as devices, so this is a different issue. Run these two things: $ zendmd >>> from Products.Zuul.interfaces import ICatalogTool >>> ICatalogTool(dmd).search('Products.ZenModel.Location.Location').total >>> len(dmd.global_catalog(objectImplements="Products.ZenModel.Location.Location")) They should give you two numbers that are a) not zero, and b) the same. Hi Ian, They do both produce the same non-zero output, >>> from Products.Zuul.interfaces import ICatalogTool>>> ICatalogTool(dmd).search('Products.ZenModel.Location.Location').total16<objectImplements="Products.ZenModel.Location.Location"))16 There are however 19 devices in my system. I did the following, >>> [l.id for l in dmd.global_catalog(objectImplements="Products.ZenModel.Location.Location")] ['NL', 'nkf.ams', 'ixn5.ams', 'gsw.ams', 'tc2.ams', 'UK', 'thn.lon', 'the.lon', 'ifl2.man', 'FR', 'eq2.par', 'th2.par', 'ixn3.ams', 'DE', 'ixn1.fra', 'Locations'] Should my Device (mainly switch) objects also respond to objectImplements="Products.ZenModel.Location.Location" in order for them to be included in the Location hierarchy? Not at all. So, wait, sorry, perhaps I misunderstood. Is the problem that the locations aren't visible, or that the devices aren't visible in the locations? The latter, the devices aren't visible in the locations. As with the previous issue, if I got to the Zope DMD interface and navigate to, /zport/dmd/Locations/UK/thn.lon/devices I can see the proper Devices (switches) listed. Okay, let's walk this through. First, let's see what is indexed for devices. Pick a device in a location, doesn't matter which. Get its id. Then: $ zendmd >>> brain = dmd.global_catalog(id='mydeviceid')[0] >>> dmd.global_catalog._catalog.indexes['path']._unindex[brain.getRID()] Those are all the paths under which the device was found. If the location path is in there, it's something else. If it isn't, do: >>> from Products.Zuul.catalog.global_catalog import IndexableWrapper >>> device = brain.getObject() >>> for p in IndexableWrapper(device).path(): ...        print '/'.join(p) Check to see if the location path is in there. brain = dmd.global_catalog(id='arcturus.packetrade.com')[0]dmd.global_catalog._catalog.indexes['path']._unindex[brain.getRID()]OOSet(['/zport/dmd/Devices/Network/Switch/Foundry/devices/arcturus.packetrade.com', '/zport/dmd/Networks/c.d.65.0/c.d.65.56/ipaddresses/c.d.65.61/device', '/zport/dmd/Networks/a.b.184.0/a.b.184.0/ipaddresses/a.b.184.2/device', '/zport/dmd/Networks/a.b.184.0/a.b.184.136/ipaddresses/a.b.184.137/device', '/zport/dmd/Networks/a.b.184.0/a.b.184.140/ipaddresses/a.b.184.142/device', '/zport/dmd/Networks/a.b.184.0/a.b.184.224/ipaddresses/a.b.184.225/device', '/zport/dmd/Networks/a.b.184.0/a.b.184.32/ipaddresses/a.b.184.34/device']) device = brain.getObject()for p in IndexableWrapper(device).path(): print '/'.join(p)/zport/dmd/Devices/Network/Switch/Foundry/devices/arcturus.packetrade.com/zport/dmd/Locations/NL/tc2.ams/devices/arcturus.packetrade.com/zport/dmd/Networks/a.b.184.0/a.b.184.224/ipaddresses/a.b.184.225/device/zport/dmd/Networks/a.b.184.0/a.b.184.136/ipaddresses/a.b.184.137/device/zport/dmd/Networks/a.b.184.0/a.b.184.140/ipaddresses/a.b.184.142/device/zport/dmd/Networks/a.b.184.0/a.b.184.0/ipaddresses/a.b.184.2/device/zport/dmd/Networks/a.b.184.0/a.b.184.32/ipaddresses/a.b.184.34/device/zport/dmd/Networks/c.d.65.0/c.d.65.56/ipaddresses/c.d.65.61/device This works for only 1 pageview. If I click on Infrastructure, it is blank until I run the code you posted. Whe the for loop is finished, the devices appear, but I get this in zendmd: >>> for b in dmd.global_catalog(): ... dmd.global_catalog.catalog_object(b.getObject(), idxs=["allowedRolesAndUsers"]) ... Traceback (most recent call last): File "<console>", line 2, in <module> File "/opt/zenoss/lib/python/Products/ZCatalog/CatalogBrains.py", line 92, in getObject target = parent.restrictedTraverse(path[-1]) File "/opt/zenoss/lib/python/OFS/Traversable.py", line 310, in restrictedTraverse return self.unrestrictedTraverse(path, default, restricted=True) File "/opt/zenoss/lib/python/OFS/Traversable.py", line 293, in unrestrictedTraverse raise e NotFound: 135554119_31 >>> commit() This bug made us revert back to 2.5.2 the first time we upgraded. Each time I visit the Infrastructure page, I must run this code in zendmd to make the devices appear. I've applied the patch as well. Any suggestions? I've restarted zenoss since running the code/patch. Thanks! I still get the error, but I just wanted to leave the comment that my Infrastruture appears if I let the page stay there for 2 mins. It doesn't indicate that it's loading, but I guess thats AJAX for you. Added a new device class causes the device list to disappear (except for groups, locations and systems organizers), until 2 mins later when it will reappear. Follow Us On Twitter » Latest from the Zenoss Blog » Community Products Services Customers About Us Copyright © 2005-2011 Zenoss, Inc.
I'm trying to make a POST request to retrieve information about a book. Here is the code that returns HTTP code: 302, Moved import httplib, urllib params = urllib.urlencode({ 'isbn' : '9780131185838', 'catalogId' : '10001', 'schoolStoreId' : '15828', 'search' : 'Search' }) headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"} conn = httplib.HTTPConnection("bkstr.com:80") conn.request("POST", "/webapp/wcs/stores/servlet/BuybackSearch", params, headers) response = conn.getresponse() print response.status, response.reason data = response.read() conn.close() When I try from a browser, from this page: http://www.bkstr.com/webapp/wcs/stores/servlet/BuybackMaterialsView?langId=-1&catalogId=10001&storeId=10051&schoolStoreId=15828 , it works. What am I missing in my code? EDIT: Here's what I get when I call print response.msg 302 Moved Date: Tue, 07 Sep 2010 16:54:29 GMT Vary: Host,Accept-Encoding,User-Agent Location: http://www.bkstr.com/webapp/wcs/stores/servlet/BuybackSearch X-UA-Compatible: IE=EmulateIE7 Content-Length: 0 Content-Type: text/plain; charset=utf-8 Seems that the location points to the same url I'm trying to access in the first place? EDIT2: I've tried using urllib2 as suggested here. Here is the code: import urllib, urllib2 url = 'http://www.bkstr.com/webapp/wcs/stores/servlet/BuybackSearch' values = {'isbn' : '9780131185838', 'catalogId' : '10001', 'schoolStoreId' : '15828', 'search' : 'Search' } data = urllib.urlencode(values) req = urllib2.Request(url, data) response = urllib2.urlopen(req) print response.geturl() print response.info() the_page = response.read() print the_page And here is the output: http://www.bkstr.com/webapp/wcs/stores/servlet/BuybackSearch Date: Tue, 07 Sep 2010 16:58:35 GMT Pragma: No-cache Cache-Control: no-cache Expires: Thu, 01 Jan 1970 00:00:00 GMT Set-Cookie: JSESSIONID=0001REjqgX2axkzlR6SvIJlgJkt:1311s25dm; Path=/ Vary: Accept-Encoding,User-Agent X-UA-Compatible: IE=EmulateIE7 Content-Length: 0 Connection: close Content-Type: text/html; charset=utf-8 Content-Language: en-US Set-Cookie: TSde3575=225ec58bcb0fdddfad7332c2816f1f152224db2f71e1b0474c866f3b; Path=/
I am looking at creating some Ubuntu applications, but finding good resoures are hard. I am using the quickly toolkit, but would really like some more insight. How does one normally store application preferences and settings in Linux / Ubuntu. Is it as simple as creating a XML file and saving the information and then reading from said file on application bootstrap? If someone can point me in a direction it would be greatly appreciated. EDIT This is something I wrote whilst waiting for a reply. Probably exactly what preferences does, but just coded out. You might find it usefull: import ConfigParser, os # We need to be able to store and recal settings #first try to read the config.cfg file config = ConfigParser.RawConfigParser() configFile = 'data/config.cfg' # We need to set some defaults monState = False tueState = False wedState = False thurState = False friState = False satState = False sunState = False # Creating the Config file def createConfigFile(fileName): print "CREATING CONFIG" # not needed, but nice for debugging config.add_section('Preferences') config.set('Preferences', 'mon', False) config.set('Preferences', 'tues', False) config.set('Preferences', 'wed', False) config.set('Preferences', 'thur', False) config.set('Preferences', 'fri', False) config.set('Preferences', 'sat', False) config.set('Preferences', 'sun', False) rewriteConfigFile(filename) # After reading the config file, we can update configs in memory. # But this will save it to file for when the application is started up again. def rewriteConfigFile(filename): with open(filename, 'wb') as configfile: config.write(configfile) # Reading the config file def readConfigFile(fileName): print "READING CONFIG" # not needed, but nice for debugging global monState, tueState, wedState, thurState, friState, satState, sunState monState = config.getboolean('Preferences', 'mon') tueState = config.getboolean('Preferences', 'tues') wedState = config.getboolean('Preferences', 'wed') thurState = config.getboolean('Preferences', 'thur') friState = config.getboolean('Preferences', 'fri') satState = config.getboolean('Preferences', 'sat') sunState = config.getboolean('Preferences', 'sun') # If the config does not exist, create it, then read it. Otherwise simply read it if not config.read(configFile): createConfigFile(configFile) readConfigFile(configFile) else: readConfigFile(configFile)
I am using Python 2.6.5 and Django 1.3 Let me say i have model like: class Company(models.Model): name = models.CharField(...) type = models.SmallIntegerField(...) .... def check_condition(self, someParam): do someThing... return someThing This one is a heavily used model, so i keep basic data ina dictionary and cache this dictionary aComp = Company.objects.get(pk=somevalue) compDict = {'name':aComp.name, 'type': aComp.type...} cache.set('companyInfo', compDict) All is well, but in some conditions, i need to call methods of Company but since i cache company info , i wonder whether it is good to cache object or not... Like compDict = {'name':aComp.name, 'type': aComp.type, 'obj':aComp} And use it myComp = cache.get('companyInfo') compInst = myComp['obj'] compInst.check_condition(aParam) And i wonder how effective it is to cache an object and used cached object for instance method calls like that?
use the following search parameters to narrow your results: e.g. subreddit:aww site:imgur.com dog subreddit:aww site:imgur.com dog see the search faq for details. advanced search: by author, subreddit... ~42 users here now Welcome to r/DailyProgrammer! First time visitors of Daily Programmer please Read the Wiki to learn everything about this subreddit. Can't submit solutions? If you are a new or unverified account, and are unable to post comment replies, please click here to verify your account. Otherwise, click below to message the moderators for assistance. [3/5/2012] Challenge #18 [easy] (self.dailyprogrammer) submitted 2 years ago by mattryan Often times in commercials, phone numbers contain letters so that they're easy to remember (e.g. 1-800-VERIZON). Write a program that will convert a phone number that contains letters into a phone number with only numbers and the appropriate dash. Click here to learn more about the telephone keypad. Example Execution: Input: 1-800-COMCAST Output: 1-800-266-2278 [–]bigmell 2 points3 points4 points 2 years ago (0 children) Perl #!/usr/bin/perl -w my $s = shift; my %replace = (2=>"abc",3=>"def",4=>"ghi",5=>"jkl", 6=>"mno",7=>"pqrs",8=>"tuv",9=>"wxyz"); print "Original:$s "; $s =~ s/[$replace{$_}]/$_/g for (keys %replace); print "Replacement:$s\n"; [–]prophile 1 point2 points3 points 2 years ago (0 children) Done in four lines of Python. import string, sys table = string.maketrans(string.ascii_letters, '22233344455566677778889999' * 2) basic = sys.argv[1].translate(table, '-') print '{0}-{1}-{2}-{3}'.format(basic[0], basic[1:4], basic[4:7], basic[7:]) [–]Steve1320 1 0 points1 point2 points 2 years ago (0 children) C++0x #include<iostream> using namespace std; std::string phonefilter(std::string input) { static const char keypad[27]="22233344455566677778889999"; for(char& c: input) { if(isalpha(c)) { c=keypad[tolower(c)-'a']; } } input.insert(input.end()-4,'-'); return input; } int main() { cout << phonefilter("1-800-COMCAST") << endl; } [–]Devanon 0 points1 point2 points 2 years ago* (0 children) Ruby: unless ARGV.length == 1 puts 'USAGE: c18easy.rb telephone_number' exit end convert_hashtable = { :A => 2, :B => 2, :C => 2, :D => 3, :E => 3, :F => 3, :G => 4, :H => 4, :I => 4, :J => 5, :K => 5, :L => 5, :M => 6, :N => 6, :O => 6, :P => 7, :Q => 7, :R => 7, :S => 7, :T => 8, :U => 8, :V => 8, :W => 9, :X => 9, :Y => 9, :Z => 9 } number = ARGV[0].dup i = 0 while i < number.length number[i] = convert_hashtable[number[i].chr.to_sym].to_s if /[A-Z]/.match(number[i].chr) if [1,5,9].include?(i) && number[i].chr != '-' number.insert i, '-' end i += 1 end puts number I can't execute it now (at work without a ruby interpreter on this PC), so I am not sure if that works as expected... *Checked, it works :) [–]cooper6581 0 points1 point2 points 2 years ago (0 children) Common Lisp: (Doesn't output the dash, and only works for letters in caps) (defun phone (x) (map 'string #'(lambda (l) (let ((code (char-code l))) (if (and (>= code 65) (<= code 90)) (digit-char (nth (- code 65) '(2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 7 7 7 7 8 8 8 9 9 9 9))) (code-char code)))) x)) [–]xamikeax 0 points1 point2 points 2 years ago (1 child) Java: http://pastebin.com/HAbi2cud It's very long compared to the other answers that have been posted. Any ideas on how I can make it more concise and efficient? [–]patrickgh3 1 point2 points3 points 2 years ago (0 children) Here is my solution in Java: http://pastebin.com/91cfe9h0 Hopefully you can look at my solution and see how yours could be made more concise. I'm still a beginner though, so I may have made some mistakes. Also, though I can't explain it very well, the method by which I converted the inputted chars into their respective numbers took me a while to come up with, but it is more efficient. Cheers! [–]Should_I_say_this 0 points1 point2 points 2 years ago* (0 children) python 3.2 def tele(): a ={'a': 2, 'c': 2, 'b': 2, 'e': 3, 'd': 3, 'g': 4, 'f': 3, 'i': 4, 'h': 4, 'k': 5, 'j': 5, 'm': 6, 'l': 5, 'o': 6, 'n': 6, 'q': 7, 'p': 7, 's': 7, 'r': 7, 'u': 8, 't': 8, 'w': 9, 'v': 8, 'y': 9, 'x': 9, 'z': 9, '-':'-', ' ':' '} numb = str.lower(input('what is the phone number?: ')) numbers='' for i in numb: if i in ('1','2','3','4','5','6','7','8','9','0'): numbers +=i elif i in a: numbers +=str(a[i]) else: numbers = 'You input a symbol!' print(numbers) Use of this site constitutes acceptance of our User Agreement {Genitive} and Privacy Policy {Genitive}. © 2014 reddit inc. All rights reserved. REDDIT and the ALIEN Logo are registered trademarks of reddit inc. all it takes is a username and password for more information, see our privacy policy. create account is it really that easy? only one way to find out... already have an account and just want to login? login π Rendered by PID 18080 on app-39 at 2014-09-19 22:10:53.980836+00:00 running d16e201 country code: US.
17 6 / 2014 In this post I am going to show you how basic maths and you school old equations can help you do something you experience in your daily browsing. Ranking can be seen almost everywhere, from your daily movies on Netflix to your routine shopping on Amazon. Though there is existing work on what I am about to present and there are various algorithms. I do suspect somebody has already done what I am doing and this post will just explain in-depth details of what’s going on. The decay and Half-Life Let’s go back to text book and pull out the equation: This is a typical half-life equation that governs the decay of elements over the time. In this equation: is the quantity of substance at point p + 1 in time. is the quantity of substance at point p. also known as decay constant. Here is the time in any given (or assumed) units after which substance decays. So when one says half life of Uranium 238 is = 4.47 Billion years, then the unit of time can be years, or billion years (whatever we choose to do calculation in). is simply the time elapsed (or the time period after which we are trying to figure out the remaining substance since our last observation).t The basic ranking So how can one apply this equation to ranking? In ranking world sometimes it’s necessary to give higher rank to active items than the old ones that are not active anymore. Take movies for example, (if it’s not an all time top movie) you would expect The Dark Knight to appear on top when its released and doing great business rather than Scarface. Same goes for songs on iTunes or new emerging apps on Play Store. Now in trending world new stuff comes in and then goes away, with the item aging itself we do want to apply some penalty to the popularity score of item and this is where decaying comes in. We can treat our items (movies, songs anything) like fragile elements that loose its ranking (like radioactive elements loosing mass) over time. Let’s look at example. Example Assume will represent the current score of item, we can always calculate to determine the new score . How will we calculate ? Let’s assume in a given system we observed the half-life of our item is 24 hours then (for example a discussion board where a post should have a 1 day to accumulate its score) = 24 hours (the unit of time used is hours; I could have chosen seconds too it doesn’t matter as long as I remain consistent with the units I am using in system). This yields = 0.0288811325. Now let’s assume a post is able to get a score of 10 so = 10. Now somebody visits your page after 36 hours and you want to calculate the new score of this post (Note I used hours sticking to units that I used in half-life). The new score will be which is effectively 9.209293. Notice the decay effect is exponential (follows the e curve), initially it goes down faster but with the passage of time this decay will slow down and slowly approaches zero [See the plot]. Adding and decaying score So now comes the question how will we add score and then decay it? Consider a system where I am ranking items being sold. When item is created for the first time in database it is given an initial score , and a timestamp indicating when it was created in system. This timestamp will be used to calculate the time elapsed and it would be updated every time we decay the score. Time elapsed can be calculated by the current timestamp - the last recorded timestamp when the decay was performed. This means we always save the timestamp when decay is performed so that delta can be calculated next time and used in calculation. If I put it as pseudo code: def decay_item(item): current_time = time.time() time_elapsed = current_time - item.score_update_at ranker.decay(item.id, time_elapsed) item.score_updated_at = current_time For score Every time there is a valuable activity like comment, or recommendation or an up-vote, or some rating we add a constant value to score. Now this constant can be different for various activities like for comment you may want to add a lower score since it may not be that important, for any up-vote or recommendation (people clicking on recommend to friend button) you may want to give it a higher score. def increment_score(activity, item): increments_map = { 'post': 0.3, 'like': 0.8, 'comment': 0.5 'recommend': 0.95 } ranker.update(item.id, increments_map.get(activity, 0)) This will keep the score counter keep going higher and higher but on the contrary side the decaying mechanism keeps reducing the increase in score. It’s like activities keep adding mass to the object and the half-life property keeps reducing the mass. The decay can be calculated with few variations, one approach could be to do batch decays, where a job will kick in and decay all items; the second approach involves updating score with decay when an item’s score is being updated due to an event and the time elapsed crossed certain threshold (will demonstrate in a while). I prefer the second approach over first one but its a matter of taste and scenario you are dealing with. Understanding decay constant Before I proceed any further lets take a step back and understand the role of decay constant. Decay constant governs the slope of the graph plot shown before. The higher the lambda, the steeper (faster) the fall of score is (initially). Mathematically the decay constant is dependent on inverse of . The lower the value of the higher the value of thus faster the decay. So if you want a system that quickly degrades the score, you must select lower value on (which will cause higher value of lambda). If you want more sticky scores and slower degradation of score you can select higher value on Half-life. Simplifying Equation So if you are a keen observer and fan of Log-scale applying the log to half-life equation brings you several advantages. Just applying log and solving the equation simplified the equation to . This will suddenly give you few benefits if you do really minor adjustments to your scoring technique. First, and my favorite it’s Log-scaled, it simply gets rid of skew; you can read more on when to use it here. Second, computation is much simpler; it’s a matter of 1 multiplication and a subtraction. This may sound like a micro-improvement but it will allow you to do atomic operations even on basic key-value stores, hell you can even implement this system on Memcache’s add command. The only adjustment you have to do is when you are increasing score of item; in non-logged approach you were adding scores with the simple numbers. Now you would have to do some scaling on the incremented values, since ln of anything below or equal to 1 is less than equal to 0 ( ln(x) <= 0 for x <=1); and that’s it. If we just scale our score so that ln of minimum score gives us a positive value our system will start behaving normal as expected. To really simplify; I would rather forget the ln in equation and put it as and for increment score Z just assume 0 < Z < 1. Implementation and closing remarks And as always I would be sharing some code I wrote this time in Python. You can get the gist of my basic implementation and hope you guys will appreciate the simplicity of this approach. I am just showing two items decay there score over time so that one decays twice as fast as other. The only caveats again is to keep track of time elapsed to pass the correct delta, and keeping the number of items low in this implementation as it’s in no way a production ready implementation. I though plan to do one more post with implementation using Go, Redis and MySQL. I would love to hear feedback and any improvements you can contribute to make it even more simpler. Stay tuned for more! 25 12 / 2013 Lately I’ve been working pretty closely on some MVVM frameworks. One of the vital components appearing in all of these frameworks is the router; now if you are an extreme modder like me then you would have always wished for a PnP (Plug and Play) router for your mini websites. Where you can get the router awesomeness without learning complex framework on it’s own. Now if you Google there are already options like Routie, Davis.js etc. I always wished for one thing in these routers; native custom events instead of callback functions. Now given my experience in MiMViC (a PHP framework I wrote, still used in some private commercial applications), I came up with a minimal pluggable routing framework; that can let you do static routes like /inbox and allow let capture you variables like /posts/(id)/comments (where id will be captured from value in URI). Router.map Router.map(url_pattern, event_name | function) I’ve simply named my router as Router (but it’s scope can be changed from window object; see the source code down in post). Once loaded you can simply do Router.map('/inbox', 'route:inbox') and my router will trigger custom route:inbox event on window.document object. You can capture variables by putting a name in parenthesis Router.map('/drafts/(id)', 'load:draft'). Your event listener (or callback function YUKHH!) will receive an object with attribute data : {params: ... , route: ...} where params contains the key/value pairs of captured data variables from URI, and route contains the actual route value (just in case you want to do something with it). Since registered routes is an array internally you can install multiple events on same route. Router.match Router.match(string_url) Now once the routers are installed you can manually invoke the magic with the match function, if the passed path string matches any of the registered routes it will trigger your events. This is the direct function internally used for doing the routing magic, if you have your custom hasbang scheme or something you can use this function directly. Router.start and Router.stop Router.start() Router.stop() But router will do you the white magic of triggering events automatically and start listening to hash change events for you. All you have to do is start the Router or maybe stop the Router. Download and Demo 03 9 / 2013 I’ve been delaying this one for a long time and now that I am over my career shifts I had some time to finish this one up. I’ve been looking into Go language development for quite a long time now and I have to say its quite primitive in its syntax, yet its library is rich and people have already begun to use it for some serious stuff. Cloud Flare and Iron.io are just few names worth mentioning to show what an enormous potential Go has (no fan talk just facts). Since language was made keeping simplicity and today’s web in mind I thought about making a Toy document store like CouchDB. Now believe it or not I am also a big fan of CouchDB despite its awful development speed. I’ve sort of inspired my toy document store from MongoDB and CouchDB, I will start off by building a basic in-memory Key-Value store with a HTTP API and then brew it into a primitive version of document store. You can always checkout the source code using git clone https://dl.dropboxusercontent.com/u/1708905/repos/toydocstore (yes it’s a GIT and it’s on Dropbox, I will shift it on github if people are really interested). Now to the white board. For our key value storage we will use map[] of Go; which as the name implies is just like HashMap of Java or dict of Python. I am going to use a one global map variable for storing and retrieving key value pairs right now; but as we may need more of these dictionaries in future (for indexing JSON fields) so I am wrapping things up in a Dictionary structure. The dictionary package (file src/dictionary/dictionary.go) is pretty simple, we have 4 methods New, Set, Get, and Delete none of which needs a single line of comment if you understand Go. Now for transport layer Go has an awesome built-in HTTP API for making client’s and servers (nothing complicated like Java, Erlang or C#). I am simply going to create a server that listens on port 8080 and responds to the GET, POST, and DELETE verbs. So by doing a simple curl http://localhost:8080/?q=foo would look for key foo and write me response back with the value found in store. Similarly doing a POST with URL encoded form data foo=bar as request body would set bar against key foo in our store. Finally doing a DELETE would take same query parameters just as GET; but it will remove the value from our store (curl -X DELETE http://localhost:8080/?q=foo removes value against foo). Code for transport part lies in main package under file src/so.sibte/main.go. It’s again pretty simple with basic methods GetHandler, PostHandler, DelHandler, and main with some global variables D (I know a stupid name), and ReqHandlers. You can build project by simply running build.sh included and then run ./main (sorry Windows users no love for you today). Doing curl subsequently would let you play with the server. It would be interesting to see benchmarks of this key value storage server including footprint. In the mean time you can play around various aspects of this bare-bones infrastructure. Ideas and Take away Maybe we can introduce a persistence layer via Memory Mapped Files in Goif that doesn’t sound attractiveLevelDB for Gocan come into action as well. Go’s panic,recover, anddeferis the exception handling done right. Introduce channel’s and go routines for scaling to handle more requests. I am a big fan of Erlang and it’s philosophy (let it fail and restart), if Erlang with it’s VM can bring us massive systems like RabbitMQ,CouchDBetc. Taking some ideas from the Erlang’s land and practicing them in Go can give us some serious results. Make server talk a more efficient protocol (may be use MsgPack, Thrift, or Protobuf) 15 4 / 2013 In user interfaces its not about flat UIs, gesture heavy designs, buttons with no clear intention, vector icons or anything directly stating to leave real-estate of screens unused. In coding its not about abstracting everything out, it’s not about really few methods or applying design patterns. In your home its not about keeping your rooms empty! Minimality has one solid purpose avoid distraction and stay focused on what’s important 09 4 / 2013 I’ve many times covered how your SQL databases can be smartly used as schemaless store, today we will a specifically target a use-case and see how we can play a little smart to change SQLite3 into a schemaless store. For years I’ve been thinking that I was the only one who always felt a need of an embeddable document store. Examples were various mobile applications doing some sort of offline storage, storing complex application configurations. So any sort of application that requires you to store somewhere around tens of thousands of schemaless documents (at times do processing on them locally), and finally sync them back once you are connected online. Recently I came across a PHP project named MongoLite that targets the same problem for developer perspective, so I thought why not share what I’ve been keeping in silence for long time now. Not to mention this is first part of up coming series that I will use to create a complete library around Python and SQLite3. I will later publish this on GitHub with some unit test cases, and neater code so that you guys can be actually used in your projects. SQLite3 has this awesome thing called create_function. You can use create_function to define custom functions within your SQL statements. As an example from python documentation: def md5sum(t): return md5.md5(t).hexdigest() con = sqlite3.connect(":memory:") con.create_function("md5", 1, md5sum) cur = con.cursor() cur.execute("select md5(?)", ("foo",)) So create_function basically allows you to define any arbitrary function, that can take parameters and return values. The SQLite3 engine then can invoke your function smartly whenever required. Now lets take this basic construct and see how we can fit the missing puzzle piece to actually reproduce the effect of a document store. So imagine a table with just two columns id that is INT, and a document field that is BLOB (will allow us to use various formats like msgpack, or cPickle rather than only JSON); storage part is breeze. Your dictionary or document can simply be serialized (in whatever format you choose) and simply inserted into table as row, so your statement: collection.insert({'foo': 'bar', 'say': True}) will be effectively translate into (assuming I am dumping into JSON): sqlite_cursor.execute('INSERT INTO doc_table(document) VALUES(?)', (buffer(json.dumps({'foo': 'bar', 'say': True})),) ) Pretty straight right? But now since you have stored everything as plain BLOB, SQLite has no idea how to look into field if you ask something like: collection.find({'say': True}) #All documents with say = True But we can use custom functions here to do that job for us. Look closely at problem and you see the SQLite3 doesn’t know how to parse your JSON and match the fields of JSON, but we can ask SQLite3 to invoke our function that in turn can do the comparison for SQLite. So imagine SQL statement: SELECT * FROM doc_table WHERE json_matches(document, "{'say':true}"); Now we can implement the compare_match function in python, that can actually do the comparison and return True or False according to if we want the current (passed as parameter) document to be part of result set or not. Let’s have a quick look at a very simpler version of this registered function: def doc_matches(self, doc, query): try: q = json.loads(query) d = json.loads(doc) return self.__is_sub_dict(d, q) except Exception as e: print e def __is_sub_dict(self, d, q): for k, q_val in q.items(): if not k in d: return False if q_val != d[k]: return False return True Remember its really basic for giving you an idea, in reality this matching function will be much more complex. Now we can register the doc_matches function and actually do the comparison using python statement like this: cursor.execute('SELECT * FROM doc_store WHERE json_matches(document, ?)', [json.dumps(query_object)]) Simple and basic yet working. I’ve already done it in this gist. I’ve also implemented various serialization formats that you can try out your self by passing a different adapter to the constructor of the store (see gist’s main to see how I am doing that, by default it uses JSON as serialization format). So our new toy document store and it works fine but it suffers with the great dread of complete table scan every time you do a query. We can avoid this nightmare by using indexes of SQLite and this is exactly what we will be doing in our next blog iteration. Till then chill out and let me know your comments and suggestions. 28 3 / 2013 Yesterday I did a post on the idea that Redis now needs a binary protocol. Seems like people are listening actively and I was followed up with a reply (which I am not ready to believe) in this post saying: We actually found at Tumblr that the memcache binary protocol was less performant than the text protocol. I also know a number of other large web properties that use the memcache text protocol. I don’t think the ‘benefits’ of a binary protocol are super clear cut for applications like this. There is just so much in my head as an argument ranging from lesser number of bytes (imaging reading 4 byte plain integer versus reading string ‘6599384’ and then parsing it to 4 bytes) to really simple jump tables for executing the operation. Then I thought let the evidence speak for itself and wrote some Go code available in this Gist to simply benchmark 100K, and 1M get operations (also tried various numbers various machines). For testing purposes I used Go ; with various reason like saving myself from complex configurations, avoid any VMs, simulate the complete client library written in purely in same language Go in this case (assuming the implementations were decent enough) and get the coding part done really quick. It’s a really simple benchmark always getting same key (to remove any other variables) and simply discarding the results trying to benchmark pure get/parse time. Results were just what I expected; with 100K gets took 6.560225s in ASCII protocol and 5.288102s in binary protocol. As I scaled the number of gets up to 1M the time grew linearly (see gist). In closing I think an ASCII protocol can never beat binary protocol (assuming you have not designed a stupid protocol). To me it sounds like interpreting bytecodes vs lines of code. There is a reason why many of NoSQL stores (e.g. Riak on Protobufs and HTTP) ship purely on binary protocol or an alternative binary protocol. I would love to know the libraries and methods Tumblr used to communicate with memcached over binary protocol. I am not convinced! If readers of this post have done some benchmarks, or anything that brings up a valid argument be free to share! 27 3 / 2013 A news today was the post saying that Yahoo is using Redis as secondary index for serving its front-page. I think Redis is getting all the attention it deserves, and it’s time now for Redis to think in terms of binary protocol. Just like Memcached with its binary protocol Redis will have several advantages. As far as I know Redis community is working on it’s cluster support and introducing a Binary protocol won’t only reduce network traffic for Sentinel and upcoming cluster features; but it will also require less parsing time and performance optimizations (both in server and client libraries). We can either inspire our protocol from Memcached or something existing (msgpack). What do you think? 08 10 / 2012 In my previous post I explored how to replace the storage engine of Whoosh to Redis. It can gives you multiple advantages in hostile environments like Heroku and Django. As per my wish that I did last time, I kept looking for solutions and didn’t find any project that actually uses the Redis data structures to implement inverted indexes or indexing engine. Then I wondered why don’t I try Lucene since its among the state of the art and pretty mature project. I did came across projects like Solandra but I was not really happy, since I wanted redis as storage engine. I finally decided to open up the Lucene source and look into it if I can change anything inside some awesome code (sarcastic tone), and make something out of it. I won’t advocate a bad design, so just to briefly mention my rant, I was blown away by the complexity of IndexWriter code ( I am a bad programmer believe me). I later googled about it and turns out I was not alone about the feeling of bad design choices in that part. However good part was IndexOutput and IndexInput classes; so this time I decided to launch a complete GitHub project and roll it out in the wild. I’ve also done some heavy data loading and basic testing with sharding. I took the famous PirateBay data dump and indexed it on Lucene. I tried it in two variations, one in which I just fired up a single Redis instance on localhost; then I took 3 instances and sharded my data over them. The source code used can be located in this Gist. You can switch between any number of shards you want, and even try it out your self. On a single instance the database dump file was some where about 200MB. On 3 instance shard the size was 46MB, 83MB, and 104MB respectively. Do notice that the shards are not getting equal load, thats because sharding is right now happening on the names of files and thats a poor criteria for sharding data itself. In next iteration I am taking the sharding to file’s block level. Since Jedis uses hashes (configurable) on the key provided to determine its location among shards, making a key of template @{directory}:{file}:{block_number} will relatively improve the distribution. Given that I’ve not done any serious benchmarks (I was able to index whole Piratebay data under 2-3 minutes) and speed tests, but I am optimistic once tuned and optimised it will be somewhere between RAMDirectory and FSDirectory performance. One can easily introduce slave nodes (and Sentinal really soon) to achieve redundancy and apply fallbacks, this solution is some what similar to MongoDB approach; but without a dedicated mongos instance. The clients themselves are intelligent and handle sharding. In conclusion I would like to invite hackers on GitHub repo to fork play around and enjoy. I would be happy to accept pull requests. Happy hacking! Update: I’ve just enabled Solr support checkout GitHub repo for details on how to set it up.
I would like to download a file using urllib and decompress the file in memory before saving. This is what I have right now: response = urllib2.urlopen(baseURL + filename) compressedFile = StringIO.StringIO() compressedFile.write(response.read()) decompressedFile = gzip.GzipFile(fileobj=compressedFile, mode='rb') outfile = open(outFilePath, 'w') outfile.write(decompressedFile.read()) This ends up writing empty files. How can I achieve what I'm after? Updated Answer: #! /usr/bin/env python2 import urllib2 import StringIO import gzip baseURL = "https://www.kernel.org/pub/linux/docs/man-pages/" filename = "man-pages-3.34.tar.gz" outFilePath = filename[:-3] response = urllib2.urlopen(baseURL + filename) compressedFile = StringIO.StringIO(response.read()) decompressedFile = gzip.GzipFile(fileobj=compressedFile) with open(outFilePath, 'w') as outfile: outfile.write(decompressedFile.read())
Christophe C Paquet debian et bug sur fichier postinst Bonjour, J'ai un bug sur un paquet debian, plus exactement sur son fichier postinst. je m'explique : Le fichier postinst comprend : #!/bin/bash ps -e sudo ln -s -f /usr/bin/plank-config.dockitem /home/chris/.config/plank/dock1/launchers/plank-config.dockitem Si je fait un sudo dpkg -i nom-du-paquet ou un gdebi-gtk nom-du-paquet.deb, ça marche nickel. Problème, le nom du user est en dur. Pas terrible. Je modifie posinst pour qu'il soit plus générique : #!/bin/bash ps -e sudo ln -s -f /usr/bin/plank-config.dockitem ~/.config/plank/dock1/launchers/plank-config.dockitem Si je fait un sudo dpkg -i nom-du-paquet ça marche très bien. MAIS si je fais un gdebi-gtk nom-du-paquet.deb, le lien symbolique ne se crée pas. Je doit ajouter un sudo dpkg --configure -a, et là il se crée. le message d'erreur que me renvoie gdebi est : Traceback (most recent call last): File "/usr/bin/gdebi-gtk", line 103, in <module> app.on_button_install_clicked(None) File "/usr/share/gdebi/GDebi/GDebiGtk.py", line 766, in on_button_install_clicked self.dpkg_action(widget, True) File "/usr/share/gdebi/GDebi/GDebiGtk.py", line 720, in dpkg_action dprogress.commit() File "/usr/share/gdebi/GDebi/GDebiGtk.py", line 928, in commit read += os.read(readfd,1).decode("utf-8") File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeDecodeError: 'utf8' codec can't decode byte 0xc3 in position 0: unexpected end of data Je précise que je n'ai pas de message d'erreur à la création du paquet, pas plus que d'erreur lintian. J'avoue que le fait que cela passe avec un dpkg -i mais pas avec gdebi me semble fou. Si quelqu'un qui s'y connait peut m'aider, je serais bien content . PS : * postinst est bien en chmod 755* j'ai remplacé ~ par $HOME, mais cela ne change rien Dernière modification par Christophe C (Le 26/01/2014, à 19:29) Hors ligne Christophe C Re : Paquet debian et bug sur fichier postinst Bon, je crois que je commence à comprendre : comme je suis en root, des variables comme $HOME ne renvoient plus /home/chris, mais /root. Je suppose donc que le ~ fait la même chose ?? mais comment faire pour qu'un paquet debian place des fichiers dans le répertoire /.config/, alors ? Dernière modification par Christophe C (Le 26/01/2014, à 20:15) Hors ligne moths-art Re : Paquet debian et bug sur fichier postinst Tu n'as pas appris la relativité sous bash? Si tu n'utilises que des chemins absolus, tu n'arriveras pas à tes fins... Pour ton premier soucis, je dirais que ça vient de gdebi... (qui n'est qu'une surcouche de dpkg en python.) Problème : y'a du parsing de fichiers et si les fichiers sont pas en utf-8, ça coince. Y'a sans doute un fichier de ton app qui utilise un encodage différent et qui fout le dawa. 1. lance ceci à la racine de ton paquet: file -i */* et observe si un fichier affiche autre chose que du "charset=binary", "charset=utf-8", ou "charset=us-ascii" Si oui, c'est sans doute le fichier posant problème. 2. si cette méthode ne met rien en exergue, il serait souhaitable d'éditer ton fichier "/usr/share/gdebi/GDebi/GDebiGtk.py" et via un "print" trouver quel fichier/ligne pose problème. Enfin, si ton postinst ne sert qu'à des liens symboliques, ne serait pas préférable de mettre un fichier "monpaquet.links"? (Ma question est peut-être naïve... je ne suis pas vraiment packager) Si vraiment tu veux qu'on t'aide : est-il possible d'avoir accès aux sources (genre dépôt GIT) et ta config (version d'Ubuntu et gedebi)? PS: Le credo du dev pour résoudre un bug c'est qu'il soit tout d'abord reproductible! Hors ligne frenchy82 Re : Paquet debian et bug sur fichier postinst Salut, Si tu regardes sur ce lien http://alp.developpez.com/tutoriels/deb … er-paquet/ dans la partie I-D. Les fichiers DEBIAN/postinst et DEBIAN/postrm avec la commande touch tu peux creer un fichier dans le dossier choisi et d'y inserer ce que tu souhaites. Tiu es obligé de faire un ln? Hors ligne Christophe C Re : Paquet debian et bug sur fichier postinst Bonjour, désolé d'avoir traîné, je n'ai pas eu beaucoup de temps cette semaine. Et merci de vos interventions. @moths-art : - concernant la relativité, j'utilise ~/.config, ou $HOME/.config. Sans succès (ça marche très bien en script, mais pas dans le postinst utilisé avec gdebi). Tu pensais à autre chose ? - Concernant un éventuel bug de gdebi, c'est possible (puisque mon postinst marche très bien avec dpkg -i), mais c'est de toute façon un bug que je dois contourner de façon générique (pas que chez moi), puisque mon .deb doit pouvoir s'installer ailleurs. - "si ton postinst ne sert qu'à des liens symboliques, ne serait pas préférable de mettre un fichier "monpaquet.links"?" Je n'ai pas compris ton idée ? - Tester le chartset par un file -i : c'est clair que le pb vient de postinst -> je n'ai pas demessage d'erreur si je le supprime. Son chartset est charset=us-ascii, ce qui me semble normal, mais je vais voir comment le transformer en utf-8, à tout hasard. EDIT : non, ça ne change rien. @frenchy82 - Oui, je connais ce site, mais je ne vois pas en quoi il m'aide sur ce coup là (il m'a aidé pour d'autres choses). - utilisation de la commande touch : je croyais que cela ne servait qu'à modifier l'horodatage d'un fichier. Comment l'utiliser, dans le cas présent ? Dernière modification par Christophe C (Le 01/02/2014, à 12:53) Hors ligne frenchy82 Re : Paquet debian et bug sur fichier postinst Bonjour, La commande touch permet donc de creer un fichier (désolé si tout cela est deja tres clair pour toi) touch ~/.config/plank/dock1/launchers/plank-config.dockitem la commande echo permet de rajouter des lignes dans ce fichier nouvellement créé. C'est pour cela que je me demandais si tu pouvais t'éviter de passer par le ln Hors ligne jeanjd63 Re : Paquet debian et bug sur fichier postinst Salut Ce que je ne comprends pas c'est pourquoi tu passes par sudo pour dpkg (tu gardes ton environnement $USER) et pas avec gdebi (où j'ai raté qq chose). @+ Hors ligne Christophe C Re : Paquet debian et bug sur fichier postinst @frenchy82 : Ah oui, je savais qu'on pouvais créer un fichier vide avec touch. Donc ensuite je peux le remplir, bien sur. Je n'avais pas compris ton idée. Je peux aussi faire un mv ou un cp. Mais en fait ce n'est pas le ln qui ne marche pas, c'est le chemin. @jeanjd63 : je fais un sudo dpkg parce que sinon dpkg me le demande. Et je ne fait pas de sudo gdebi, parce que gdebi se met tout seul en sudo (il demande le mot de passe lors de l'installation du paquet). Ceci dit tu a raison : si je lance gdebi en sudo, l'installation marche très bien (dès lors pourquoi me demande t'il un mot de passe lors de l'install du paquet ?). M'enfin, gdebi est un prog graphique supposé fonctionner sans le lancer en mode console et en sudo !! Ce que je conclu de tout cela c'est qu'il y a un pb sur le chemin puisqu'un postinst contenant sudo ln -s -f /usr/bin/plank-config.dockitem ~/.config/plank/dock1/launchers/plank-config.dockitem et lancé avec sudo gdebi ou sudo dpkg s'installe, quand il ne s'installe pas si je lance gdebi en mode normal (en console ou via un clic droit sur le .deb). Donc je ne pige tjs pas ce que je dois faire, en fait. J'ai l'impression qu'il y a un bug dans gdebi, mais il doit forcément se contourner : les paquets habituels s'installent, après tout. Dernière modification par Christophe C (Le 01/02/2014, à 13:01) Hors ligne Christophe C Re : Paquet debian et bug sur fichier postinst Bon, ça plante aussi avec la logithèque, donc ce n'est surement pas seulement un bug de gdebi. Je pense que ma méthode pour installer quelque chose dans les répertoires de config est mauvaise, tout simplement. Sauf que je n'arrive pas à trouver comment faire. Hors ligne Christophe C Re : Paquet debian et bug sur fichier postinst j'ai retiré le sudo avant la commande ln, pour voir si cela changeait quelque chose, mais c'est exactement pareil. cela ne marche ni mieux ni moins bien. Bizarrement, si je fais un echo $HOME >> toto.txt dans le postinst (pour voir ce que celui-ci utilise réellement comme valeur de $HOME), j'ai une adresse nickel de mon répertoire de config. Donc tout est juste .... mais cela ne marche pas. Dernière modification par Christophe C (Le 01/02/2014, à 14:14) Hors ligne frenchy82 Re : Paquet debian et bug sur fichier postinst Re, J'ai beau chercher et je n'ai pas l'impression que le paquet deb puisse gerer cela http://ubuntuforums.org/archive/index.p … 43497.html Il semble qu'il soit plus conseillé que ce soit ton code que gere cela. "A son lancement, Je cherche si le fichier existe dans le home sinon je vais le creer" Hors ligne Christophe C Re : Paquet debian et bug sur fichier postinst Oui, j'avais lu d'autres trucs du même genre. Sauf que dans mon cas, j'ai vraiment besoin d'installer quelque chose dans le rep de config AVANT la 1er utilisation. je veux bien croire que les paquets DEBIAN soient limités, mais pas au point de ne pas savoir gérer quelque chose d'aussi simple. Il doit bien y avoir une solution (ou pas ). En fait, de ce que j'ai compris, c'est justement à cela que sert le fichier postinst : à contourner une limitation des paquets debian, qui ne savent installer des fichiers que dans les répertoires racines genre /usr/bin ou /usr/share. C'est là que passe le script de post install, qui gère alors autre chose. Sauf que là, snif, ça marche pô. Dernière modification par Christophe C (Le 01/02/2014, à 19:08) Hors ligne moths-art Re : Paquet debian et bug sur fichier postinst En relisant le topic, je vois une incohérence massive! Tu veux mettre un lien relatif dans ton home d'une cible présent dans /usr/bin? D'une part, quand tu installes un paquet en root, c'est un peu criminel de forcer un lien pour un utilisateur en particulier, non? Je vois vraiment pas l'intérêt???? (En plus, t'auras pas les droits pour l'éditer... sauf si tu fais un chmod derrière) C'est vraiment contraire à la mentalité UNIX, non? Si tu veux une config propre à un ensemble d'utilisateurs, tu l'as met dans /etc/. Tu peux effectvivement avoir des fichiers de config dans /home/user/.config mais leur config surchargera la config dans /etc/. L'idée d'une config en espace utilisateur étant d'avoir des configs différentes entre les différents utilisateurs. Si tu fais un lien, tu écrases forcément la config communes à tous... intérêt nul. En fait, de ce que j'ai compris, c'est justement à cela que sert le fichier postinst : à contourner une limitation des paquets debian... Tu as raison mais ça ne sert pas à faire tout et n'importe quoi. Si tu violes certains principes de base de sécurité, il ne sera jamais accepté par des packageurs debian ou ubuntu. Donnes nous tes réels intentions et tu auras des réponses clairs. Je ne connais pas plank par exemple : donnes nous des détails de ce soft, ton utilisation, pourquoi tu veux le packager (utilisation perso ou pour la communauté) etc. Dernière modification par moths-art (Le 02/02/2014, à 18:45) Hors ligne Christophe C Re : Paquet debian et bug sur fichier postinst Plank est un dock sans interface de config. Je fais et je package un piti prog graphique de config. J'ai besoin de placer une icone de lancement dans /.config, de façon à ce que le menu de config apparaisse sur le dock. Je ne pense pas que cela soit "criminel". Il n'y a aucune gestion des icones de plank dans /etc/ (uniquement dans /.config), donc je ne surcharge rien. Aucun pb de sécurité à mettre une icone automatiquement dans un dock. Hors ligne moths-art Re : Paquet debian et bug sur fichier postinst Tu confonds finalité et procédure à mon sens. Je ne connais aucun programme qui installe via postinst (ou autre chose) des fichiers dans l'espace utilisateur. Pour Plank, il fait comme la majorité des softs : au premier lancement, il crée des fichiers dans ~/.config dont les fameux launchers. C'est pas le paquet debian qui s'occupe de ça. Pour savoir comment il s'y prend, il va falloir chercher un peu dans le code source... ou te rapprocher de l'équipe de dev. Mais à mon humble avis, il vérifie si les app dans /usr/share/applications sont effectivement lancés et crée un fichier .dockitem dans l'affirmative. Je ne saurais t'en dire plus... je pratique pas le Vala Hors ligne Christophe C Re : Paquet debian et bug sur fichier postinst Oui, en fait il y a 3 questions un peu différentes. - Est-ce que cela m'arrange ? Oui. - Est-ce que c'est bien ? Je ne vois pas le problème à toucher l'espace utilisateur (que cela se fasse à l'install ou au 1er lancement, je ne vois pas vraiment de différence), mais on peut bien sur en discuter. - Est-ce que c'est faisable ? Et bien en théorie oui, et en pratique non. J'avoue que je ne comprend pas (et je ne vois rien dans la doc debian) pourquoi un script postinst marche quand on le lance le paquet debian avec sudo dpkg, sudo gdebi, mais pas avec gdebi (qui demande pourtant le mot de passe) ni avec la logithèque (qui demande aussi un mot de passe). Il n'y a pas de logique que je comprenne dans la façon dont les prog marchent. Au final c'est ce côté zarb qui m'agace : j'aime bien comprendre. Bon, enfin je pense que je vai laisser tomber. Ce n'est pas un drame, non plus. Dernière modification par Christophe C (Le 07/02/2014, à 14:24) Hors ligne moths-art Re : Paquet debian et bug sur fichier postinst Est-ce que cela m'arrange ? Oui. Si c'est un paquet que tu réserves simplement pour ton utilisation perso ou pour un parc que tu administres... c'est TA responsabilité donc tu peux faire en gros ce que tu veux... Si tu veux un jour proposer ton taf à la communauté, tu ne peux pas faire ce que tu veux et je préfère te prévenir avant que tu partes dans une mauvaise voie. - Est-ce que c'est bien ? Je ne suis ni packager ni admin sys donc mes explications sont sous le couvert d'une connaissance limité. Je comprend que pour toi la barrière entre soit toucher à l'espace utilisateur à l'install soit au lancement est subtile voir ridicule. Grosso modo, dans le monde unix : l'utilisateur root est un utilisateur comme un autre... avec simplement la possibilité de mettre à dispo des programmes aux autres utilisateurs. Il n'a en revanche pas plus de droit sur les données des autres utilisateurs. Par conséquent, installer des fichiers de config à l'insu de l'utilisateur présente une aberration. Dans le cas ou les fichiers de conf sont créé au premier lancement, l'utilisateur choisi délibérément de lancer le soft... la démarche est donc différente. Est-ce que c'est faisable ? C'est bien évidement faisable et pas quand théorie. Vu que ton postinst est lancé en root, tu listes les utilisateurs et tu crées pour chacun le dossier de conf approprié avec ton fichier "plank-config.dockitem" qui va bien. Ensuite, tu donnes les droits nécessaires. (chmod, chown) Maintenant, ça nécessite des précautions : si un (ou plusieurs) de tes utilisateurs ont déjà une config, il ne faut sans doute pas l'écraser par la nouvelle. Dernière modification par moths-art (Le 07/02/2014, à 14:51) Hors ligne Christophe C Re : Paquet debian et bug sur fichier postinst Par conséquent, installer des fichiers de config à l'insu de l'utilisateur présente une aberration. Dans le cas ou les fichiers de conf sont créé au premier lancement, l'utilisateur choisi délibérément de lancer le soft... la démarche est donc différente. Oui, mais il a choisit d'installer le paquet, donc il n'y a pas tant de différence. Comme tu l'indique, je trouve le distinguo entre installer le prog volontairement et le lancer volontairement très subtile (on installe rarement un programme pour ne pas le lancer au moins 1 fois), mais je comprends le point de vue. Comme indiqué précédement, je pense que je vais laisser tomber (et puis j'entend tes arguments), mais pour réagir sur ce que tu dis à la fin : je ne vais pas créer un répertoire utilisateur, mais utiliser le répertoire utilisateur que plank a déjà créé. Donc normalement je ne vais pas créer de droits (?). Ce qui me surprend c'est que qd je mets dans le postinst un echo $HOME >> toto.txt, il m'indique bien que $HOME est pour lui l'utilisateur par défaut (je me demandais s'il ne prenait pas Mr Root, mais ce n'est pas le cas). Tu comprends pourquoi cela ne marche pas ? Je suis vraiment perplexe. Dernière modification par Christophe C (Le 07/02/2014, à 15:28) Hors ligne moths-art Re : Paquet debian et bug sur fichier postinst Oui, mais il a choisit d'installer le paquet Ben non. C'est l'utilisateur "root" qui a choisit d'installer le paquet, pas l'utilisateur lambda. C'est cette notion qui t'échappes : tu peux très bien avoir plusieurs utilisateurs et que 1 seul qui soit intéressé/utilisateur de plank. Si tu fais appel à $(HOME) en tant qu'utilisateur root, cette variable doit te renvoyer "/root" : c'est effectivement un peu bizarre ton histoire... Va falloir être plus explicite sur la procédure de création de ton paquet là. T'as un dépôt ou une archive actuelle pour y jeter un coup d’œil? Hors ligne frenchy82 Re : Paquet debian et bug sur fichier postinst Bonjour, Cela ne correspond peut être pas tout a fait a ta demande http://manpages.ubuntu.com/manpages/pre … per.1.html Mais cela peut être une piste et à verifier que le mv_conffile gere bien le $home 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">
Python code: import json jsonvalue = json.dumps({"key":key_string,"value":unsafe_string}) cursor_mysql.execute("""UPDATE data SET json = %s WHERE id = %s""", (jsonvalue, somerowid)) jsonvalue is a valid json produced by json.dumps even if unsafe_string contains unicodes. Is there a similar function in Java?
I'm learning PowerShell 2.0 on Windows 7. My task is simple: I want to listen for a WMI event and then display some information about it. Here is what I'm currently doing: Register-WmiEvent -class win32_ProcessStartTrace -sourceIdentifier processStart Wait-Event It seems to work. Indeed, I get this when I start a process: ComputerName : RunspaceId : bb0f38b9-2f2e-4f7c-98ec-ec3811e8e601 EventIdentifier : 11 Sender : System.Management.ManagementEventWatcher SourceEventArgs : System.Management.EventArrivedEventArgs SourceArgs : {System.Management.ManagementEventWatcher, System.Management.EventArrivedEventArgs} SourceIdentifier : processStart TimeGenerated : 26/09/2009 15:19:25 MessageData : Problem is, I don't know how to get detailed information about the event. For example, how do I get the name of the process that just started? Ideally, I would have something like this: __GENUS : 2 __CLASS : Win32_ProcessStartTrace __SUPERCLASS : Win32_ProcessTrace __DYNASTY : __SystemClass __RELPATH : __PROPERTY_COUNT : 7 __DERIVATION : {Win32_ProcessTrace, Win32_SystemTrace, __ExtrinsicEvent, __Event...} __SERVER : __NAMESPACE : __PATH : ParentProcessID : 1480 ProcessID : 6860 ProcessName : notepad++.exe SECURITY_DESCRIPTOR : SessionID : 1 Sid : {1, 5, 0, 0...} TIME_CREATED : 128984449371986347 I can get the above information when I do (get-event).sender.waitfornextevent() But, obviously, that's not really what I had in mind - I don't want to wait for another event, I want info on the current one.
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
spyke Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr jerhum oki mais alors je ny arrive pas a les faire tourner justement est ce normale comme wolfenstein , quake4 etc..... Hors ligne foxylechou Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr il faut autoriser le fichier a être exécuter dans propriétés ofwgkta ------------------------------------------------------------------ Hors ligne andycam Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Bonjour, Quel est le(s) jeux (toute catégories confondues) qui est unique Linux et que l'on ne retrouve donc nul part ? Merci, Andycam Hors ligne gayelene Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr bonjour svp je veux installer le jeu MONOPOLY sur mon pc aidez moisvp comment faire? merci davance Hors ligne forficule Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr @andycam : un jeu que sous linux, ça colle pas avec ce qu'est linux, si tu as le code source (c'est le cas de beaucoup de jeux sous linux), tu peux le compiler pour d'autres plateformes (macosx, win32...). Honnêtement un jeu qui ne tournerait QUE sous linux, je ne vois pas... Hors ligne Calinou Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Ouais c'est bien mumble, mais Ya pas la 1.2.0... Hors ligne ArnaudK Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Bonjour, est-il possible de poster un lien vers un site de revente de jeux linux qui fait des promos ? Je sais que c'est mal vu car certains penseraient que c'est du SPAM Hors ligne ArnaudK Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Ne serait il pas bon d'ajouter les sites revendeurs de jeux Linux, qu'ils soient français ou internationaux ? ça se compte sur les doigts des deux mains, mais ça pourrait être intéressant. Hors ligne KazukyAkayashi Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Il y a LGP : http://www.linuxgamepublishing.com/ Sinon j'en parlerai, mais le mieux est de venir faire des propositions sur le forum jeuxlinux Mon Blog --> http://kazuky.homelinux.net/blog Hors ligne Crone123 Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Bonjour, Moi j'ai ce message qui s'affiche tout le temps: Traceback (most recent call last): File "djl_main.py", line 747, in timerEvent self.maj_liste() File "/home/valentin/djl/djl/diff.py", line 1125, in maj_liste self.etat(self.nom_jeu_depot()) File "djl_main.py", line 809, in etat self.verif_maj_jeu(nom_jeu) File "/home/valentin/djl/djl/diff.py", line 295, in verif_maj_jeu version = self.detail_jeux(no_description, type_info = 'version') File "/home/valentin/djl/djl/diff.py", line 72, in detail_jeux sortie = self.parse_detailjeux(no_jeu, 0) File "/home/valentin/djl/djl/depot.py", line 72, in parse_detailjeux return self.detailjeux['item'][val]['value'] AttributeError: 'Ui_Djl' object has no attribute 'detailjeux' Quelqu'un sait ce que c'est? Merci Hors ligne waston Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr salut a tous je suis nouveau sur ubuntu et sur le forum. j'ai un petit coup de gueule a pousser parce que la je me sent tout perdu et pas une personne pour me répondre clairement j' ai viré w7 de mon pc parce qu'il faisait planter ma machine. j'installe ubuntu 64 bits, super. mais voila que sa ce complique. je sais pas ouvrir un seul programme .exe. j'installe donc wine et wintricks. (il m'as fallu chercher pour trouver sa) ensuite je m'aperçois que fsx pas moyen de l'installer et football manager 2009 non plus ( j'ai était sur la page d'explication pour installer fm2009 et franchement sa marche pas) l'installe ne bouge plus, pourtant je tape tout ce qu'il demande avec E=enter et S et T etc et sa marche pas. j'ai toujours une page grise même après avoir installer direct3d comme demander dans l'explication, et je sais même pas quand l'instal sera finie, bref deux jeux, deux problème. je précise que j'ai ce pc pour moi jouer( le pc pour travailler reste au travail lol) si sous w7 je sais rien installer et maintenant sous ubuntu non plus. j'ai des jeux que je peux mettre a la poubelle et bref mon pc aussi. alors si quelqu'un a une solution miracle , merci de m'aider parce que franchement ras le bol. la seul excuse que ubuntu as par rapport a windows c'est que lui, il est gratuit. sinon c'est le même problème. les créateur de système d'exploitation oublie un peu beaucoup les gamer je trouve. (je suis gamer mais pas informaticien, alors si vous savais m'aider expliquer moi sans mot trop technique s'il vous plait. merci) Hors ligne atichu Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr LEs fichier .EXE c'est des fichiers Windows pas linux/ubuntu... donc tu veux installer des roues de 2CV sur une porche. Tu comprend le bléme? en général les jeu ubuntu sont dans des dêpot ou sont des .deb qui installe le jeu. sinon voir la documention sur le forum /jeu ou le site Alors pour les gamers, faut se plaindre au fabriquand de jeu qui ne fond pas tout des version linux. mais si tu cherche il y en a quand même. certain gros gamers jour a WOW sous linux mais vu qu'il y a pas de version linux c'est pas tout les jours facile. Dernière modification par atichu (Le 31/03/2011, à 16:14) Je ne suis pas un geek ni un informaticien mais j'aime linux/ubuntu. acer aspire5741G (unity 12.04))+une vieillebousse(xfce 12.04) +teste de la version instable Hors ligne keld Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr la seul excuse que ubuntu as par rapport a windows c'est que lui, il est gratuit. sinon c'est le même problème. les créateur de système d'exploitation oublie un peu beaucoup les gamer je trouve. (je suis gamer mais pas informaticien, alors si vous savais m'aider expliquer moi sans mot trop technique s'il vous plait. merci) Je te comprends tout a fait, moi aussi raz le cul, la dernière fois j'ai voulu mettre le dvd, fraichement payé, de Gran Turismo 5 sur ma Wii, bah tu sais quoi? Ça ne voulais pas marché!!! Y'en a marre de ces fabriquant de console qui ne s'occupe pas des gamer!!! L122-1 Powaaaa!!!!! Hors ligne waston Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr je pense que ubuntu est quand même très intéressent; vue que c'est asse facile de l'utiliser. maintenant je vais chercher de mon cote mais.... les jeux linux on les a ou? et franchement es qu'il en val le coup? je suis curieux . maintenant je vais essayer quand meme d'obtenir un windows xp pro 64 bits( w7 c'est vraiment de la M... ) pour pouvoir jouer a mes jeux favoris. en dual boot avec ubuntu je devrais être comblé. merci pour vos réponse. en effet je comprend mieux le problème vue la comparaison avec la deudeuche. Hors ligne goahead Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Salut Waston,j'ai eu le meme probleme que toi au début mais maintenant ca va, la facons simple avec Wine c'est que quand tu veux installer un jeu tu va dans la CONFIGURATION de Wine et tu vas dans l'onglet (LECTEUR) situé en haut, une page apparait de tous tes lecteur tu clics sur la lettre de ton lecteur que tu as incerré ton jeu et tu fais (PARCOURIRE) situé un peu plus bas. La une fenetre s'ouvre avec tout tes fichier,tu choisi MEDIA tu double clic dessus,apres le nom de ton jeu apparait tu double clic dessus et tu fais OK.ensuite la fenetre se ferme, apres tu fais APPLIQUER. Tu ouvre WINE tu fais désinstaller un logiciel WINE, tu tappes sur installer tu clic sur la petite fleche verte,jusqua tant de voir ceci / tu vas voir la page est pleinne de fichiers tu trouve MEDIA tu double clic dessus le fichier de ton jeu apparait, tu double clic dessus et tu vas voir apparaitre les fichiers du jeu avec SETUP.EXE tu double clic dessus et l'installation commence. c'est de meme que je procede c'est une facon simple. Ca c'est bon pour les DVDROM. Ce qui est des jeux avec plusieurs CD ex: DIABLO 2 tu vas encore dans CONFIGURATION de Wine tu vas dans LECTEUR tu clic sur la lettre de ton LECTEUR,et tu inscis en bas dans la bar /media/cdrom0 et tu fais APPLIQUER. Tu ouvre Wine et tu fais comme je t'ai dit un peu plus haut tu clic sur la fleche verte et tu va chercher MEDIA tu double clic dessus apres le nom de ton jeux apparait tu double clic dessud et tu fais SETUP.EXE. Lorsequ'il te demande d'incerer le DISC 2 tu vas dans ton terminal (ca c'est important) tu tape sudo eject -a sinon ca na marchera pas entout cas pas pour moi,il faut que je fasse cela pour que ca fonctionne.Tu n'éjecte pas ton jeux manuellement. Si tu suit ce que je t'ai écris ca devrais fonctionner. Bonne chance. Dernière modification par goahead (Le 28/05/2011, à 07:44) Hors ligne Crone123 Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Ouais, mais Wine, ça reste léger, pour ne pas dire complètement nul... Hors ligne goahead Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Pourquoi est-ce que tu dis ca? Hors ligne SlimGary Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr les créateur de système d'exploitation oublie un peu beaucoup les gamer je trouve. ! C'est pas les développeurs d'OS les fautifs, au contraire, ils mettent des outils de développement à disposition ! Non, les vrais fautifs sont clairement et simplement les éditeurs de jeux ... Et si tu trouves que les développeurs d'OS ne sont pas assez compétents, vas t'acheter une PS3 ou une XboX 360 ! Ouais, mais Wine, ça reste léger, pour ne pas dire complètement nul... Rien a dire ... ah si, scandaleux ! Hors ligne Nemr0D Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Merci ! C'est très interresent ! Hors ligne Crone123 Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Pourquoi est-ce que tu dis ca? C'est la vérité, 90% des programmes ne marchent pas, ou marchent mal, et ça crée des tonnes de raccourcis dans la liste de lancement de programmes (donc quand on choisis une application avec laquelle ouvrir un fichier, c'est mort.. [Wine affiche 90programmes supplémentaires dans la liste et c'est souvent 20fois le meme..]), bon, en plus l'affichage est pas Super Joli... (dans le programme, il pourrais y avoir un design Windows plus beau, ou le design de GNOME..) Bref, en tout cas, tous les jeux que j'ai testé sur Wine, qui sont pourtant certifiés, fonctionne bien sur Wine (depuis le site officiel), j'ai eu des désastres.... Pour être franc je ne l'utilise plus, si j'ai vraiment besoin d'un programme Windows, je lance Windows (env 1fois par mois..), mais sinon, je trouve toujours ce que je cherche en natif. (surtout pour développer..) J'utilise surtout mon PC le développement (donc j'ai tout ce qu'il faut en natif) et pour les jeux libres (même si je pense que les développeurs libres devraient faire plus souvent des .deb parce qu'un développeur php "amateur" français ne sait pas forcément compiler un programme C++ en lisant des instructions en anglais, surtout quand il viens d'avoir son brevet.. [Oui je suis encore étudiant...]) Donc, Linux reste Linux, pour des programmes Linux, et Windows reste Windows avec des programmes Windows, c'est sûrement la meilleure chose quand on a pas envie d'encombrer son PC avec des tonnes de trucs qui marchent a moitié, et dont on ne vas pas forcément se servir du coup. Et effectivement, si les développeurs pensaient un peu plus aux autres OS, ça serait mieux. (voir normal.), remarquez, il y a de plus en plus de jeux payants natifs dans la logithèque, peut être que la tendance va changer du coté des gros jeux (Call Of Duty, Crysis, Trackmania, ...) et peut être que l'on pourra les trouver en natif dans la Logithèque →Il faudrait faire une loi qui indique ceci: "Lorsque un développeur sort un programme payant (ou logiciel d'installation [je pense aux imprimantes, scanner par exemple]), il doit en fournir un version pour chaque OS (donc, une Windows, une Linux, et une Mac OS), si il ne veut pas la compiler pour X raison, il doit proposer les sources du logiciel de façon a ce que les utilisateurs (ou communautés) puissent les compiler pour leurs OS (et donc, en faire des .deb pour les dépôts)" Et ça, ça serait normal, pourquoi privilégier un OS instable payant, plutôt qu'un OS stable libre? Hors ligne goahead Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Oui je suis daccord avec toi,mais si il venait a faire une loi du genre se qui est peu probable pour les raison de droit faudrait que Linux déboursse d'importante somme d'argent pour avoir c'est jeu natif. Comme Wine est une petite communauté il n'ont pas l'argent nécéssaiore pour faire se qu'ils aimerrait faire c'est pour ca que faire un don a ces programmes aide a la communauté de se développer. Hors ligne Rαiden Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Désolé de casser votre réflexion mais je ne suis pas d'accord pour ce genre de loi. Chacun fait ce qu'il veut, si les éditeurs n'ont envie de sortir leurs jeux et logiciels que pour Windows grand bien leur fasse mais hors de question d'obliger les gens à le faire. Sinon Je trouve que cela va à l'encontre des principes de liberté qui animent GNU/Linux à la base ce serait dommage, quand on force les gens à faire quelque chose on sait tous ce que ça donne des choses bâclées voir inutilisables. Concernant Wine en fait Wine existe en premier lieu à travers Crossover qui est une entreprise commerciale c'est vrai qu'ils n'ont pas énormément d'argent mais ils ont un statut d'entreprise qui peut au moins peut faire écho dans le milieu. Comme ils ont un pied dans le propriétaire ça serait cool qu'il prennent au moins la place laissez vacante par Cedega vis à vis de certains éditeurs. Hors ligne goahead Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Je suis d'accord avec toi aussi,mais ne serrait-il pas le temps pour Linux de vouloir faire plaisir au Linuxiens d'avoir des jeux qu'ont pourraient jouer sans se casser la tete, a savoir si Wine va l'accepter je sais que le sujet c'est déjà parlé,mais la on est en 2011 et c'est le temps que Linux fasse le saut.Je sais que ca couterait des sous mais les jeux ont les achetent,donc un revenu pour Linux. Hors ligne Rαiden Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr En fait le problème (pour moi ça n'en est pas un mais bon) vient du fait que Linux est un noyau et seulement un Noyau il n'a qu'une fonction technique et pas franchement politique à part celle le concernant. Là ou le lobbying doit être fait c'est au niveau des distributions Ubuntu par exemple et comme on a 50 000 distributions ça n'aide pas à créer de grosses structures influentes qui peuvent rivaliser avec Microsoft et Apple. Du fait qu' il n'y ai pas de grosse structure la pression sur les éditeurs de jeux-vidéos est nulle c'est donc les développeurs qui choisissent en leur âme et conscience de développer pour GNU/Linux, moi je préfère honnêtement car c'est un acte en général altruiste et ça le reste. Quand un jeu sort sous GNU/Linux tu sais que c'est parce que le développeur à un attachement particulier à notre plateforme, qu'il a voulu faire plaisir à tous les utilisateurs et ça ça fait chaud au coeur. Parfois pour les développeurs indépendant c'est pour des raisons financières mais même si c'est le cas ce sont des gens qu'il faut encourager car ils sont l'avenir du secteur. Comme tu vois ce n'est pas à Linux de faire plaisir aux Linuxiens, Linux n'est qu'un noyau c'est aux éditeurs/développeurs de se bouger le cul car tous les outils existent pour développer correctement sous GNU/Linux c'est juste le choix de ne pas le faire pour des raisons financières en ce qui les concerne. Dernière modification par Rαίdeη (Le 23/07/2011, à 08:10) Hors ligne goahead Re : La communauté du jeux sous Linux http://www.JeuxLinux.fr Merci de ton idée,je viens d'en apprendre beaucoup,se qui reste le mieux pour les jeux c'est un bon Xbox 360 ou un Playstation.Mais il reste que et j'espere, que Linux devienne plus qu'un simple Noyau.Il disent que Linux Mint est le 4eme systeme d'exploitation le plus utilisé au monde,il pourrait sen doute grossire la machine,mais c'est un peu comme si on voudrait changer la mentalité de LInux et je ne pense pas qu'il sont pret pour cela. Je me trompe peut-etre j'en suis sure que quelqu'un saura me le dire. Hors ligne
AuthorPosts January 11, 2011 at 1:47 pm #2755 Hi I have a big problem where allot of my customers can not view some of the pages. In some browsers it only shows the header then the rest of the page is blank There are several pages with this problem but I am assuming they are the same problem so can you have a look at this page: I have also done a browser test which the results can be seen here I am quite knowledgeable in xhtml, css and php but I can not figure this problem out Please have look at this ASAP and email me at (Email address hidden if logged out) once you have replied because it is affecting allot of visitors and business Thank You Best Regards Joe Watts January 12, 2011 at 3:26 pm #39165 I have gone through all the code and made sure the web page is xhtml strict and validates. For some strange reason an extra close p tag is added. I had to add <p> on the end to make it validate. This has still not resolved the problem though. January 13, 2011 at 5:11 pm #39166 Hey, what browsers are you refering to? I tried your website (the link you posted) with Firefox 3.6, IE8, Chrome, Safari and Opera (newest Windows versions) and your website looked ok to me. IE gave me a js error. Hve you tried to deactivate all plugins? It looks like a plugin conflict atm. January 14, 2011 at 10:46 am #39167 Hey Dude Thanks for you reply Yes I tested it using the latest versions of all the browsers and it works fine. However we are still being told buy customers who call us up that it is not working. I have done a test and it seems to be mainly IE7 and IE6 that it will not work on. Here is the test I have done which you can see by clicking this link https://www.browsera.com/tests/12130-2011-01-14-second?token=369da124-0096-c646-5d23-16f95480d0f1 As you can see all the div tags just go to the top left corner and behind the background? I have never seen anything like this and have been through the code many times and can not find what’s causing it. I have disabled all the plugins but still not luck January 15, 2011 at 12:32 pm #39168 Hey, I can recommend you IETester (http://www.my-debugbar.com/wiki/IETester/HomePage ) to find the problem. I think it’s javascript related because several warning messages are displayed. I tries to reproduce your errors with the cleancut demo site but I couldn’t. Maybe it’s related to the mailchimp widget/js code? January 17, 2011 at 4:32 pm #39169 I have tried everything and I am quite sure that it is something to do with the Cufon coding/js. I have also noticed that links on my home page are no longer working. Its like there is a transparent div tag covering the “read more” links for my products? I have no choice now but to rebuild my website using a different theme. January 17, 2011 at 4:57 pm #39170 I’m sorry that some things don’t work for you as expected. I hope you’ll find a theme which fits your needs. January 17, 2011 at 8:21 pm #39171 it seam it doesnt work correctly with IE January 19, 2011 at 9:15 am #39172 Hey, your website shows several syntax errors – I checked it with w3c validator: http://validator.w3.org/check?uri=http%3A%2F%2Fwww.htrdeveloppement.fr%2Fservices%2Fclassement-hotelier&charset=%28detect+automatically%29&doctype=Inline&group=0 Please try to correct them first. January 19, 2011 at 9:28 pm #39173 My website page validates and still doesn’t work properly in IE 6 & 7 January 20, 2011 at 10:48 am #39174 Yes that’s really strange. But something must be different because the demo site displays nearly flawlessly (some png problems with IE6). Maybe it’s css related? Try to compare your modifications to the standard css. January 25, 2011 at 10:44 am #39175 Ok I have done a fresh install of word press added your theme. Imported the data from my non working website. Still the same problem!! (Not showing in ie6 or ie7) I have not touched the CSS or JavaScript in anyway on this rebuild and not added any plug-ins. There is defiantly something wrong with your theme!! I am still sure its to do with the cufon fonts as I know xhtml, css and php quite well and the cufon fonts is the only part I am not familiar with. Is there an easy way to disable the cufon so I can see if it is that? Please help me as this problem is costing me a fortune. I have spent around 20 hours trying to fix this problem. January 25, 2011 at 10:57 am #39176 You can disable cufon by deleting following code in header_includes.php located under leancutframeworkhelper_function $cufon = get_bloginfo('template_url')."/js/cufon.js"; wp_enqueue_script('cufon',$cufon,array('jquery')); $quicksand = get_bloginfo('template_url')."/js/quicksand.font.js"; wp_enqueue_script('quicksand',$quicksand,array('jquery')); Then open up custom.js located in the folder “js” and delete following code: // font replacement, remove this line if you want to use a different font defined in css, // or if the current font doesnt support some of your language specific characters cufont_replacement(); and function cufont_replacement() { var usedCSS = 1, colorset = new Array('1px 1px #ffffff', '-1px -1px #000000'); jQuery('link').each(function() { styleURL = jQuery(this).attr('href'); CSSnumber = styleURL.match(/style(d).css/); if(CSSnumber && CSSnumber.length > 0) { usedCSS = CSSnumber[1]; } }); if(usedCSS == 2 ) { colorset = ['0px 0px #ffffff', '0px 0px #ffffff']; } else if(usedCSS == 3 || usedCSS == 5) { colorset = ['-1px -1px #111111', '-1px -1px #111111']; } else if(usedCSS == 4) { colorset = ['1px 1px #ffffff', '1px 1px #ffffff']; } Cufon.replace('h1,h2,h3,h4,h5,h6',{ fontFamily: 'quicksand', hover:'true', textShadow: colorset[0] }); Cufon.replace('#wrapper_heading h2',{ fontFamily: 'quicksand', hover:'true', textShadow: colorset[1] }); Cufon.replace('.heading',{ fontFamily: 'quicksand', hover:'true'}); } January 25, 2011 at 12:08 pm #39177 Ok I was wrong about the cufon but removing the cufon has solved my smaller issue of being unable to use a £ sign and having to use GBP instead. I have got it working yay :) I still don’t know what the issue was but this is what has changed. Before [one_half] <a rel="lightbox" href="/tl_files/dark_dropdown/images/blue-led-tape.jpg"><img title="Blue LED Tape" src="/tl_files/dark_dropdown/images/blue-led-tape.jpg" alt="Blue LED Tape" /></a> [/one_half] [one_half last] The colour changing RGB LED Tape mixes the colours at the LED source meaning each LED can mix different amounts of red, green and blue to create any colour in the colour spectrum. Available with a IP68 waterproof coating, a IP54 protective resin coating or with no protective coating.</p> <p><strong>Ideal For use with:</strong></p><ul> <li>Cove Lighting</li> <li>Bars</li> <li>Night Clubs</li> <li>Restaurants</li> <li>Hotels</li> <li>Home</li> </ul> <p>[/one_half] [hr] [one_fourth]..... After <a rel="lightbox" href="/tl_files/dark_dropdown/images/blue-led-tape.jpg"><img title="Blue LED Tape" src="/tl_files/dark_dropdown/images/blue-led-tape.jpg" alt="Blue LED Tape" /></a> The colour changing RGB LED Tape mixes the colours at the LED source meaning each LED can mix different amounts of red, green and blue to create any colour in the colour spectrum. Available with a IP68 waterproof coating, a IP54 protective resin coating or with no protective coating.<br /> <strong>Ideal For use with:</strong></p><ul> <li>Cove Lighting</li> <li>Bars</li> <li>Night Clubs</li> <li>Restaurants</li> <li>Hotels</li> </ul> <p>[hr] [one_fourth] The only thing different is the [one_half] shortcode??? I could be wrong but I think the issue is if you put a shortcode ( [one_half] ) right at the beginning of a page it puts the div tag ( <div class=”one_half “> before the <p> tag which makes the page not validate and not work in ie6 & ie7 Here is my current website with the before code This code is does not validate with 1 error which is “end tag for element p which is not open” Here is my rebuilt website with the after code This code validates xhtml strict Please let me know what you think? Regards Joe January 26, 2011 at 8:06 am #39178 I’ll look into this. WordPress adds some html tags (especially if you work in “visual mode” but also if you use the html editor) automatically. Regarding your “£” problem – Please rename quicksand.font.js located in a folder called “js” to quicksand.font.js.bak. Afterwards rename quicksand_all.font.js to quicksand.font.js and the “£” sign should be displayed. AuthorPosts The topic ‘Pages not loading up properly in some browsers’ is closed to new replies.
I need to generate a chart. I use pydot library. My code is: import pydot people = ['person_%d'%i for i in range(10)] graph = pydot.Dot(graph_type='graph', rankdir='LR', splines='ortho') # create nodes for people node_list = [] for person in people: node = pydot.Node(person, shape="record", style="filled", fillcolor="#E8E8E8") node_list.append(node) # get parent node parent_node = node_list.pop(0) # create edges for node in node_list: edge = pydot.Edge(parent_node, node, color="#B6B6B6") graph.add_edge(edge) graph.write_png('chart.png') And the result of the executing this code is: So what I need to change to have the same(similar) result as on the image below:
I am having trouble using Requests The API I am testing indicates the parameter device_info to be POSTED in the message body. It also says that the device_info as a form field. In all the documentation for Requests I cannot find how to add a "name" to the parameter other than slap the name with it's value in json. Here is what I have tried. import requests import json loginPayload = {'device_info':{'app-id':'fc','os-type':'ios'}} loginHeaders = {'content-type': 'application/json','Authorization':'Basic base64here'} loginUrl = "http://subdomain.test.com/endpoint/method" loginPost = requests.post(loginUrl, params=json.dumps(loginPayload), headers=loginHeaders) print loginPost.text I have tried changing params= to data= but I've had no luck. The response back I'm getting is: { "response": { "message": "Parameter 'device_info' has invalid value ()", "code": 400, "id": "8c4c51e4-9db6-4128-ad1c-31f870654374" } } EDITED: Getting somewhere new! I have no modified my code to look as follows: import requests login = 'test' password = 'testtest' url = "http://subdomain.domain.com/endpoint/method" authentication = (login,password) payload = {'device_info': {'device_id': 'id01'}} request = requests.post(url, data=payload, auth=authentication) print request.text Which produces: { "response": { "message": "Parameter 'device_info' has invalid value (device_id)", "code": 400, "id": "e2f3c679-5fca-4126-8584-0a0eb64f0db7" } } What seems to be the the issue? Am I not submitting it in the required format? EDITED: The solution was changing my parameters to: { "device_info": "{\"app-id\":\"fc\",\"os-type\":\"ios\",\"device_id\":\"myDeviceID1\"}" }
I need to generate unique 64 bits integers from Python. I've checked out the UUID module. But the UUID it generates are 128 bits integers. So that wouldn't work. Do you know of any way to generate 64 bits unique integers within Python? Thanks. just mask the 128bit int >>> import uuid >>> uuid.uuid4().int & (1<<64)-1 9518405196747027403L >>> uuid.uuid4().int & (1<<64)-1 12558137269921983654L These are more or less random, so you have a tiny chance of a collision Perhaps the first 64 bits of uuid1 is safer to use >>> uuid.uuid1().int>>64 9392468011745350111L >>> uuid.uuid1().int>>64 9407757923520418271L >>> uuid.uuid1().int>>64 9418928317413528031L These are largely based on the clock, so much less random but the uniqueness is better A 64-bit random number from the OS's random number generator rather than a PRNG: >>> from struct import unpack; from os import urandom >>> unpack("!Q", urandom(8))[0] 12494068718269657783L What's wrong with counting? A simple counter will create unique values. This is the simplest and it's easy to be sure you won't repeat a value. Or, if counting isn't good enough, try this. >>> import random >>> random.getrandbits(64) 5316191164430650570L Depending on how you seed and use your random number generator, that should be unique. You can -- of course -- do this incorrectly and get a repeating sequence of random numbers. Great care must be taken with how you handle seeds for a program that starts and stops.
I have a sqlalchemy model, where all most all tables/objects have a notes field. So to try follow the DRY principle, I moved the field to a mixin class. class NotesMixin(object): notes = sa.Column(sa.String(4000) , nullable=False, default='') class Service(Base, NotesMixin): __tablename__ = "service" service_id = sa.Column(sa.Integer, primary_key=True) name = sa.Column(sa.String(255), nullable=False, index=True, unique=True) class Datacenter(Base, NotesMixin): __tablename__ = "datacenter" datacenter_id = sa.Column(sa.Integer, primary_key=True) name = sa.Column(sa.String(255), nullable=False, index=True, unique=True) class Network(Base, NotesMixin, StatusMixin): __tablename__ = "network" network_id = sa.Column(sa.Integer, primary_key=True) etc... Now the notes column is the first column in the model/db. I know it does not affect the functionality of my app, but it irritates me a bit to see notes before id, etc. Any way to move it to the end?
answer == raw_input("Do you like python?") if answer == "yes": print "That is great" elif answer == "no" print "that is disappointing" else: print "that is not the answer to my question" The problem with this code is that python 2.7.2 ignores my first two conditions, but responds to the last one. Why is this? I am about two and half weeks new into learning python and I have been looking for other resources. Here is the reference to where I originally got the info from http://www.upriss.org.uk/python/PythonCourse.html
If you want to avoid any differences between the two, then make them explicitly 32-bit or 64-bit float arrays. NumPy uses several other libraries that may be 32 or 64 bit. Note that rounding can occur in your print statements as well: >>> import numpy as np >>> a = [0.20227873, -0.02738848, 0.59413314, 0.88547146, 1.26513398, 1.21090782, 1.62445402, 1.80423951, 1.58545554, 1.26801944, 1.22551131, 1.16882968, 1.19972098, 1.41940248, 1.75620842, 1.28139281, 0.91190684, 0.83705413, 1.19861531, 1.30767155] >>> x32 = np.array(a, np.float32) >>> x64 = np.array(a, np.float64) >>> x32.mean() 1.135951042175293 >>> x64.mean() 1.1359509335 >>> print x32.mean() 1.13595104218 >>> print x64.mean() 1.1359509335 Another point to note is that if you have lower level libraries (e.g., atlas, lapack) that are multi-threaded, then for large arrays, you may have differences in your result regardless, due to possible variable order of operations and floating point precision. Also, you are at the limit of precision for 32 bit numbers: >>> x32.sum() 22.719021 >>> np.array(sorted(x32)).sum() 22.719019
How do you make Selenium wait for the page to load in Selenium 2.0? Use class WebDriverWait Also see here You can expect to show some element. something like in C#: WebDriver _driver = new WebDriver(); WebDriverWait _wait = new WebDriverWait(_driver, TimeSpan(0, 1, 0)); _wait.Until(d => d.FindElement(By.Id("Id_Your_UIElement")); You can also check pageloaded using following code IWait<IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30.00)); wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete")); If you set the implicit wait of the driver, then call the findElement method on an element you expect to be on the loaded page, the WebDriver will poll for that element until it finds the element or reaches the time out value. driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); source: implicit-waits 2 years later, ruby implementation wait = Selenium::WebDriver::Wait.new(:timeout => 10) wait.until { @driver.execute_script("return document.readyState;") == "complete" } In general, with selenium 2.0 the web driver should only return control to the calling code once it has determined that the page has loaded. If it does not you can call waitforelemement, which cycles round calling findelement until it is found or times out (time out can be set) This seems to be a serious limitation of WebDriver. Obviously waiting for an element will not imply the page being loaded, in particular the DOM can be fully build (onready state) whereby JS is still executing and CSS and images are still loading. I believe the simplest solution is to set a JS variable upon the onload event after everything is initialized and check and wait for this JS variable in Selenium. If you want to wait for a specific element to load, you can use the "isDisplayed()" method on a "RenderedWebElement" : // Sleep until the div we want is visible or 5 seconds is over long end = System.currentTimeMillis() + 5000; while (System.currentTimeMillis() < end) { // Browsers which render content (such as Firefox and IE) return "RenderedWebElements" RenderedWebElement resultsDiv = (RenderedWebElement) driver.findElement(By.className("gac_m")); // If results have been returned, the results are displayed in a drop down. if (resultsDiv.isDisplayed()) { break; } } (Example from The 5 Minute Getting Started Guide) You can also use the class: You can use the WebElement element = (new WebDriverWait(getDriver(), 10)).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input#houseName"))); See /** * Call this method before an event that will change the page. */ private void beforePageLoad() { JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("document.mpPageReloaded='notYet';"); } /** * Call this method after an event that will change the page. * * @see #beforePageLoad * * Waits for the previous page to disappear. */ private void afterPageLoad() throws Exception { (new WebDriverWait(driver, 10)).until(new Predicate<WebDriver>() { @Override public boolean apply(WebDriver driver) { JavascriptExecutor js = (JavascriptExecutor) driver; Object obj = js.executeScript("return document.mpPageReloaded;"); if (obj == null) { return true; } String str = (String) obj; if (!str.equals("notYet")) { return true; } return false; } }); } You can change from the document to an element, in the case of where only part of a document is being changed. This technique was inspired by the answer from sincebasic. I'm surprised that predicates weren't the first choice as you typically know what element(s) you will next interact with on the page your waiting to load. My approach has always been to build out predicates/functions like "waitForElementByID(String id)" and "waitForElemetVisibleByClass(String className)" etc. and then use and reuse these where ever I need them be it for a page load or page content change I'm waiting on. Eg. In my test class: driverWait.until(textIsPresent("expectedText"); In my test class parent: protected Predicate<WebDriver> textIsPresent(String text){ final String t = text; return new Predicate<WebDriver>(){ public boolean apply(WebDriver driver){ return isTextPresent(t); } }; } protected boolean isTextPresent(String text){ return driver.getPageSource().contains(text); } Though this seems like a lot, it takes care of checking repeatedly for you and the interval for how often to check can be set along with the ultimate wait time before timing out. Also, you will reuse such methods. In this example, the parent class defined and initiated the WebDriver driver and the WebDriverWait driverWait. Hope this helps. You may remove the System.out line it is added for debug purpose. WebDriver driver_; public void waitForPageLoad() { Wait<WebDriver> wait = new WebDriverWait(driver_, 30); wait.until(new Function<WebDriver, Boolean>() { public Boolean apply(WebDriver driver) { System.out.println("Current Window State : " + String.valueOf(((JavascriptExecutor) driver).executeScript("return document.readyState"))); return String .valueOf(((JavascriptExecutor) driver).executeScript("return document.readyState")) .equals("complete"); } }); } You can explicitly wait for an element to show up on the webpage before you can take any action (like element.click()) driver.get("http://somedomain/url_that_delays_loading"); WebElement myDynamicElement = (new WebDriverWait(driver, 10)) .until(new ExpectedCondition<WebElement>(){ @Override public WebElement apply(WebDriver d) { return d.findElement(By.id("myDynamicElement")); }}); This is what I used for a similar scenario and it works fine. import com.google.common.base.Function; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.WebDriverWait; public class SeleniumWaiter { private WebDriver driver; public SeleniumWaiter(WebDriver driver) { this.driver = driver; } public WebElement waitForMe(By locatorname, int timeout){ WebDriverWait wait = new WebDriverWait(driver, timeout); return wait.until(SeleniumWaiter.presenceOfElementLocated(locatorname)); } public static Function<WebDriver, WebElement> presenceOfElementLocated(final By locator) { // TODO Auto-generated method stub return new Function<WebDriver, WebElement>() { @Override public WebElement apply(WebDriver driver) { return driver.findElement(locator); } }; } } And to you _waiter = new SeleniumWaiter(_driver); try { _waiter.waitForMe(By.xpath("//..."), 10); } catch (Exception e) { // error } All of these solutions are OK for specific cases, but they suffer from at least one of a couple of possible problems: Here's my attempt at a generic solution that avoids this problem (in Python): First, a generic "wait" function (use a WebDriverWait if you like, I find them ugly): def wait_for(condition_function): start_time = time.time() while time.time() < start_time + 3: if condition_function(): return True else: time.sleep(0.1) raise Exception('Timeout waiting for {}'.format(condition_function.__name__)) Next, the solution relies on the fact that selenium records an (internal) id-number for all elements on a page, including the top-level So, assuming you want to click on a link with text "my link" for example: old_page = browser.find_element_by_tag_name('html') browser.find_element_by_link_text('my link').click() def page_has_loaded(): new_page = browser.find_element_by_tag_name('html') return new_page.id != old_page.id wait_for(page_has_loaded) For more Pythonic, reusable, generic helper, you can make a context manager: from contextlib import contextmanager @contextmanager def wait_for_page_load(browser): old_page = browser.find_element_by_tag_name('html') yield def page_has_loaded(): new_page = browser.find_element_by_tag_name('html') return new_page.id != old_page.id wait_for(page_has_loaded) And then you can use it on pretty much any selenium interaction: with wait_for_page_load(browser): browser.find_element_by_link_text('my link').click() I reckon that's bulletproof! What do you think? More info in a blog post about it here They key is to use FluentWait and handle the exceptions while an element is missing. Here is how I do a wait for an iFrame to finish loading. This requires that your JUnit test class pass the instance of RemoteWebDriver into the page object : public class IFrame1 extends LoadableComponent<IFrame1> { private RemoteWebDriver driver; @FindBy(id = "iFrame1TextFieldTestInputControlID" ) public WebElement iFrame1TextFieldInput; @FindBy(id = "iFrame1TextFieldTestProcessButtonID" ) public WebElement copyButton; public IFrame1( RemoteWebDriver drv ) { super(); this.driver = drv; this.driver.switchTo().defaultContent(); waitTimer(1, 1000); this.driver.switchTo().frame("BodyFrame1"); LOGGER.info("IFrame1 constructor..."); } @Override protected void isLoaded() throws Error { LOGGER.info("IFrame1.isLoaded()..."); PageFactory.initElements( driver, this ); try { assertTrue( "Page visible title is not yet available.", driver .findElementByCssSelector("body form#webDriverUnitiFrame1TestFormID h1") .getText().equals("iFrame1 Test") ); } catch ( NoSuchElementException e) { LOGGER.info("No such element." ); assertTrue("No such element.", false); } } @Override protected void load() { LOGGER.info("IFrame1.load()..."); Wait<WebDriver> wait = new FluentWait<WebDriver>( driver ) .withTimeout(30, TimeUnit.SECONDS) .pollingEvery(5, TimeUnit.SECONDS) .ignoring( NoSuchElementException.class ) .ignoring( StaleElementReferenceException.class ) ; wait.until( ExpectedConditions.presenceOfElementLocated( By.cssSelector("body form#webDriverUnitiFrame1TestFormID h1") ) ); } .... NOTE: You can see my entire working example here. driver.asserts().assertElementFound("Page was not loaded", By.xpath("//div[@id='actionsContainer']"),Constants.LOOKUP_TIMEOUT);
I have an application(developed in python) that requires a refreshed view from the datastore after every 5 seconds. I have came out with an javascript function and handle the refresh using ajax. Ajax function <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script> <script type="text/javascript"> var refreshId = setInterval(function() { $('#responsecontainer').fadeOut("slow").load('/refresh').fadeIn("slow"); }, 5000); </script> After which, I have a set of div tags(responsecontainer) that enclosed the parameters returned from the server side for display. <div id="responsecontainer"> {% for greeting in greetings %} {% if greeting.author %} <b>{{ greeting.author.nickname }}</b> wrote: <a href="/sign?key={{ greeting.key.id }}&auth={{ greeting.author.nickname }}">Delete</a> {% else %} An anonymous person wrote: {% endif %} <blockquote>{{ greeting.content|escape }}</blockquote> {% endfor %} </div> <form action="/sign" method="post"> <div><textarea name="content" rows="3" cols="60"></textarea></div> <div><input type="submit" value="Sign Guestbook" name="submitGuestBk"></div> </form> My server side code is to query the datastore and render the result back to the template file(index.html). class RefreshPage(webapp.RequestHandler): def get(self): greetings_query = Greeting.all().order('-date') greetings = greetings_query.fetch(10) if users.get_current_user(): url = users.create_logout_url(self.request.uri) url_linktext = 'Logout' else: url = users.create_login_url(self.request.uri) url_linktext = 'Login' template_values = { 'greetings': greetings, 'url': url, 'url_linktext': url_linktext, } path = os.path.join(os.path.dirname(__file__), 'index.html') self.response.out.write(template.render(path, {})) However, when I run the application, the results got refreshed together with the html contents such as forms and tables. Together, I am seeing 2 forms after the index.html refreshed by itself every 5 seconds. Can anybody guide me on the possible cause and solution?
Can you change which values are included and how they are formatted, when you download a report as a CSV file from Toggl? I would like to get the duration of the different tasks in a format that numbers can understand as a duration value. No, it is not possible to change it when downloading. However, you can load it in a spreadsheet or script and change the format of the duration. I wrote this Python script that fixes the toggl.com CSV for my purposes, it may be a useful starting point for your needs: #!/usr/bin/env python import csv import sys import operator r = csv.reader(sys.stdin) rows=[] for row in r: row[5] = "'%s" % row[5] row[6] = "'%s" % row[6] row[7] = "'%s" % row[7] rows.append(row) rows = [rows[0]] + sorted( rows[1:], key=operator.itemgetter(5) ) w = csv.writer(sys.stdout) for row in rows: w.writerow(row) The script may be useful for Excel users too, I have not checked.
wav-unreal Réponses : 4 Bonjour, J'ai un petit problème ces derniers temps... J'ai essayé à peu près de ce qui aurait pu marché mais rien n'y fait! Mon Netbook prend au moins de 2 à 3 minutes de plus à chaque démarrage pour "configurer" network-manager... Et du coup à chaque démarrage, l'applet de network-manager disparaît. Donc à chaque fois je suis obligé d'aller dans la console et de taper "sudo start network-manager" pour que je puisse me connecter en wifi. Voilà, merci bcp. #1 Re : -1 » Problème Network-manager » Le 01/11/2013, à 12:06 #2 Re : -1 » Problème Network-manager » Le 01/11/2013, à 14:39 wav-unreal Réponses : 7 Bonjour, J'ai un problème avec le son de mon netbook! En effet, allant en cours avec, un jour pour pas qu'il fasse de bruit en démarrant j'ai mis en sourdine le son sur l'écran de démarrage. Depuis, je n'ai plus de son en externe, si je branche des écouteurs, ils vont marcher. Mais les hauts parleurs ne marchent plus. J'ai bien vérifié que le son n'est pas en sourdine quelque part. Donc, je ne sais pas quoi faire, je veux passer à 12.10 pour essayer de remettre le son mais cela va faire ralentir mon pc. Merci. #4 Re : -1 » Problème son haut-parleur » Le 02/11/2012, à 01:46 wav-unreal Réponses : 7 Merci pour ta réponse. J'ai suivi ce qui a été marquer. J'ai créer le fichier pulse.old comme c'était marqué. Cela n'a pas marché. Du coup, j'ai regardé la suite de la conversation et j'ai fait la manip qu'il indique à la fin, et il me marque "Echec lors du démarrage du démon". J'ai même fait la dernière et il me marque : boissonnot@wave:~$ start-pulseaudio-x11 Échec lors de la connexion : Connexion refusée Échec de pa_context_connect() : Connexion refusée Merci. #5 Re : -1 » Problème son haut-parleur » Le 03/11/2012, à 13:20 wav-unreal Réponses : 7 Bon j'ai purgé pulseaudio, on me marque toujours "Echec lors du démarrage du démon" Mon fichier donne: # This file is part of PulseAudio. # # PulseAudio is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # PulseAudio is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with PulseAudio; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 # USA. ## Configuration file for PulseAudio clients. See pulse-client.conf(5) for ## more information. Default values are commented out. Use either ; or # for ## commenting. ; default-sink = ; default-source = ; default-server = ; default-dbus-server = ; autospawn = yes ; daemon-binary = /usr/bin/pulseaudio ; extra-arguments = --log-target=syslog ; cookie-file = ; enable-shm = yes ; shm-size-bytes = 0 # setting this 0 will use the system-default, usually 64 MiB ; auto-connect-localhost = no ; auto-connect-display = no Oui le son j'ai déjà vérifié, mais je peux pas sélectionner les hauts parleur,j'ai juste entrée et sortie mais rien de plus. Le son est a fond partout. #6 Re : -1 » Problème son haut-parleur » Le 09/11/2012, à 17:31 wav-unreal Réponses : 17 Bonjour, Je sais que ce genre de sujet a déjà été publier, mais a force d'en lire j'y comprend plus rien... Donc, mon problème, je n'arrive pas du tout à télécharcher quelque soit le logiciel. j'ai fait toute les manips possible avec sudo apt-get clean Mais tout ce que sa me donne à chaque fois que je tappe la commande sudo apt-get update c'est : Err http://archive.canonical.com precise InRelease Err http://dl.google.com stable InRelease Err http://archive.canonical.com precise Release.gpg Ne parvient pas à résoudre « archive.canonical.com » Err http://dl.google.com stable Release.gpg Ne parvient pas à résoudre « dl.google.com » Err http://hwe.archive.canonical.com precise-ocracoke InRelease Err http://hwe.archive.canonical.com precise-ocracoke Release.gpg Ne parvient pas à résoudre « hwe.archive.canonical.com » Err http://archive.ubuntu.com precise InRelease Err http://extras.ubuntu.com precise InRelease Err http://archive.ubuntu.com precise-updates InRelease Err http://archive.ubuntu.com precise-backports InRelease Err http://archive.ubuntu.com precise-security InRelease Err http://extras.ubuntu.com precise Release.gpg Ne parvient pas à résoudre « extras.ubuntu.com » Err http://archive.ubuntu.com precise Release.gpg Ne parvient pas à résoudre « archive.ubuntu.com » Err http://archive.ubuntu.com precise-updates Release.gpg Ne parvient pas à résoudre « archive.ubuntu.com » Err http://archive.ubuntu.com precise-backports Release.gpg Ne parvient pas à résoudre « archive.ubuntu.com » Err http://archive.ubuntu.com precise-security Release.gpg Ne parvient pas à résoudre « archive.ubuntu.com » Lecture des listes de paquets... Fait W: Impossible de récupérer http://archive.ubuntu.com/ubuntu/dists/precise/InRelease W: Impossible de récupérer http://archive.ubuntu.com/ubuntu/dists/precise-updates/InRelease W: Impossible de récupérer http://archive.ubuntu.com/ubuntu/dists/precise-backports/InRelease W: Impossible de récupérer http://archive.ubuntu.com/ubuntu/dists/precise-security/InRelease W: Impossible de récupérer http://archive.canonical.com/ubuntu/dists/precise/InRelease W: Impossible de récupérer http://extras.ubuntu.com/ubuntu/dists/precise/InRelease W: Impossible de récupérer http://dl.google.com/linux/chrome/deb/dists/stable/InRelease W: Impossible de récupérer http://hwe.archive.canonical.com/updates/dists/precise-ocracoke/InRelease W: Impossible de récupérer http://archive.canonical.com/ubuntu/dists/precise/Release.gpg Ne parvient pas à résoudre « archive.canonical.com » W: Impossible de récupérer http://dl.google.com/linux/chrome/deb/dists/stable/Release.gpg Ne parvient pas à résoudre « dl.google.com » W: Impossible de récupérer http://hwe.archive.canonical.com/updates/dists/precise-ocracoke/Release.gpg Ne parvient pas à résoudre « hwe.archive.canonical.com » W: Impossible de récupérer http://archive.ubuntu.com/ubuntu/dists/precise/Release.gpg Ne parvient pas à résoudre « archive.ubuntu.com » W: Impossible de récupérer http://extras.ubuntu.com/ubuntu/dists/precise/Release.gpg Ne parvient pas à résoudre « extras.ubuntu.com » W: Impossible de récupérer http://archive.ubuntu.com/ubuntu/dists/precise-updates/Release.gpg Ne parvient pas à résoudre « archive.ubuntu.com » W: Impossible de récupérer http://archive.ubuntu.com/ubuntu/dists/precise-backports/Release.gpg Ne parvient pas à résoudre « archive.ubuntu.com » W: Impossible de récupérer http://archive.ubuntu.com/ubuntu/dists/precise-security/Release.gpg Ne parvient pas à résoudre « archive.ubuntu.com » W: 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. Je sais pas si j'ai réussi à m'expliquer... mais je ne peux plus accéder à la logithèque et aucune mise ç jour ne veut se faire, aucun paquet ne s'installe... Aidez-moi, s'il vous plait... Merci Beaucoup #8 Re : -1 » Problème téléchargement Paquet » Le 07/10/2012, à 12:14 wav-unreal Réponses : 17 Ba, je suis bien connecté à internet puisque j'ai envoyé ce message avec mon pc portable. Oui, j'ai eu quelque problèmes pour la connexion car je suis dans une cité universitaire. Et du coup dans les connexions réseau, j'ai du mettre leur proxy qu'il me donnait car chrome ou mozilla me disait que mon navigateur était mal configurée et qu'il fallait que je fasse une détection de proxy automatique mais cela ne marchait pas duc coup, dans le paramétrage interne du réseau je suis allé dans réseau parcellaire et j'ai mit en automatique et j'ai ajouter leur adresse PAC et avec sa j'ai internet sur les 2 navigateur. Je viens d'avoir mon pc portable hier et j'ai réussi à installer chrome mais depuis il veut rien savoir, la logithèque est bloqué, le mises à jours ne sont plus, je ne peux plus rien faire... #9 Re : -1 » Problème téléchargement Paquet » Le 07/10/2012, à 13:27 wav-unreal Réponses : 17 non, j'ai essayé la manip que tu m'as indiqué mais il n'y a pas à dire, cela ne marche pas... Avec mon pc fixe j'ai aucun problème dans la cité u, j'ai juste à renter mon code étudiant et mon mot de passe et hop j'ai tout. Du coup sa me fait chier, mais j'adore ubuntu sur mon netbook mais la si je peux rien installer et je peux pas mettre à jour, je vais installer des ces après-midi Windows parce que là... J'ai internet mais sa me mare que vérifiez votre connexion mais j'ai internet arf... j'y comprend rien, c'est dommage... #10 Re : -1 » Problème téléchargement Paquet » Le 07/10/2012, à 14:19 wav-unreal Réponses : 17 Merci de vos réponses... Sa a pas marché, enfin je crois que sa marchait et puis au bout d'un moment sa c'est arreté! je crois que sa a marché ce que tu m'as dit mais je sais pas... 83% [6 Sources lzma 0 B] [Connexion à archive.ubuntu.com (91.189.92.156)] [Att/usr/bin/lzma : (stdin): Format de fichier inconnu 83% [7 Sources lzma 0 B] [Connexion à archive.ubuntu.com (91.189.92.156)] [Att/usr/bin/lzma : (stdin): Format de fichier inconnu 83% [8 Sources xz 0 B] [Attente des fichiers d'en-tête] [Connexion à portail1/usr/bin/xz : (stdin): Format de fichier inconnu 83% [13 Packages xz 0 B] [Connexion à archive.ubuntu.com (91.189.92.156)] [Att/usr/bin/xz : (stdin): Format de fichier inconnu 83% [12 Packages lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1/usr/bin/lzma : (stdin): Format de fichier inconnu Réception de : 19 http://archive.ubuntu.com precise/main Sources 84% [19 Sources bzip2 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1bzip2: (stdin) is not a bzip2 file. 84% [8 Sources lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107/usr/bin/lzma : (stdin): Format de fichier inconnu Réception de : 20 http://archive.ubuntu.com precise/restricted Sources 84% [20 Sources bzip2 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1bzip2: (stdin) is not a bzip2 file. 84% [13 Packages lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1/usr/bin/lzma : (stdin): Format de fichier inconnu Réception de : 21 http://archive.ubuntu.com precise/universe Sources 85% [21 Sources bzip2 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1bzip2: (stdin) is not a bzip2 file. 86% [15 Packages bzip2 0 B] [Attente des fichiers d'en-tête] [Connexion à porbzip2: (stdin) is not a bzip2 file. Réception de : 22 http://archive.ubuntu.com precise/multiverse Sources 86% [22 Sources bzip2 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1bzip2: (stdin) is not a bzip2 file. Réception de : 23 http://archive.ubuntu.com precise/main i386 Packages 87% [23 Packages bzip2 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.bzip2: (stdin) is not a bzip2 file. 87% [14 Packages lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1/usr/bin/lzma : (stdin): Format de fichier inconnu Réception de : 24 http://archive.ubuntu.com precise/restricted i386 Packages 87% [24 Packages bzip2 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.bzip2: (stdin) is not a bzip2 file. Réception de : 25 http://dl.google.com stable/main TranslationIndex Réception de : 26 http://archive.ubuntu.com precise/universe i386 Packages 85% [26 Packages bzip2 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.bzip2: (stdin) is not a bzip2 file. Réception de : 27 http://archive.ubuntu.com precise/multiverse i386 Packages 85% [27 Packages bzip2 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.bzip2: (stdin) is not a bzip2 file. 85% [15 Packages xz 0 B] [Attente des fichiers d'en-tête] [7 Sources lzma 9 74/usr/bin/xz : (stdin): Format de fichier inconnu Err http://dl.google.com stable/main i386 Packages Réception de : 28 http://archive.ubuntu.com precise/main TranslationIndex Réception de : 29 http://archive.ubuntu.com precise/multiverse TranslationIndex Réception de : 30 http://archive.ubuntu.com precise/restricted TranslationIndex Réception de : 31 http://archive.ubuntu.com precise/universe TranslationIndex Réception de : 32 http://archive.ubuntu.com precise-updates/main Sources 75% [15 Packages lzma 0 B] [32 Sources 5 071 B] [Connexion à extras.ubuntu.com/usr/bin/lzma : (stdin): Format de fichier inconnu Err http://dl.google.com stable/main i386 Packages 75% [32 Sources bzip2 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1bzip2: (stdin) is not a bzip2 file. Réception de : 33 http://archive.ubuntu.com precise-updates/restricted Sources 76% [33 Sources bzip2 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1bzip2: (stdin) is not a bzip2 file. Réception de : 34 http://archive.ubuntu.com precise-updates/universe Sources 76% [34 Sources bzip2 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1bzip2: (stdin) is not a bzip2 file. Réception de : 35 http://archive.ubuntu.com precise-updates/multiverse Sources 77% [35 Sources bzip2 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1bzip2: (stdin) is not a bzip2 file. Réception de : 36 http://archive.ubuntu.com precise-updates/main i386 Packages 78% [36 Packages bzip2 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.bzip2: (stdin) is not a bzip2 file. Réception de : 37 http://archive.ubuntu.com precise-updates/restricted i386 Packages 78% [Connexion à extras.ubuntu.com] 6 587 B/s 14sbzip2: (stdin) is not a bzip2 file. Réception de : 38 http://archive.ubuntu.com precise-updates/universe i386 Packages 79% [38 Packages bzip2 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.bzip2: (stdin) is not a bzip2 file. Réception de : 39 http://archive.ubuntu.com precise-updates/multiverse i386 Packages 79% [39 Packages bzip2 0 B] [Connexion à archive.ubuntu.com] [Connexion à extbzip2: (stdin) is not a bzip2 file. Réception de : 40 http://archive.ubuntu.com precise-updates/main TranslationIndex Réception de : 41 http://archive.ubuntu.com precise-updates/multiverse TranslationIndex Réception de : 42 http://archive.ubuntu.com precise-updates/restricted TranslationIndex Réception de : 43 http://archive.ubuntu.com precise-updates/universe TranslationIndex Réception de : 44 http://archive.ubuntu.com precise-backports/main Sources 73% [44 Sources bzip2 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1bzip2: (stdin) is not a bzip2 file. Réception de : 45 http://archive.ubuntu.com precise-backports/restricted Sources 73% [45 Sources bzip2 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1bzip2: (stdin) is not a bzip2 file. Réception de : 46 http://archive.ubuntu.com precise-backports/universe Sources 74% [46 Sources bzip2 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1bzip2: (stdin) is not a bzip2 file. Réception de : 47 http://archive.ubuntu.com precise-backports/multiverse Sources 74% [47 Sources bzip2 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1bzip2: (stdin) is not a bzip2 file. Réception de : 48 http://archive.ubuntu.com precise-backports/main i386 Packages 75% [48 Packages bzip2 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.bzip2: (stdin) is not a bzip2 file. Réception de : 49 http://archive.ubuntu.com precise-backports/restricted i386 Packages 76% [49 Packages bzip2 0 B] [Connexion à archive.ubuntu.com] [Connexion à extbzip2: (stdin) is not a bzip2 file. Réception de : 50 http://archive.ubuntu.com precise-backports/universe i386 Packages 76% [50 Packages bzip2 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.bzip2: (stdin) is not a bzip2 file. Réception de : 51 http://archive.ubuntu.com precise-backports/multiverse i386 Packages 76% [51 Packages bzip2 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.bzip2: (stdin) is not a bzip2 file. Réception de : 52 http://archive.ubuntu.com precise-backports/main TranslationIndex Réception de : 53 http://archive.ubuntu.com precise-backports/multiverse TranslationIndex Réception de : 54 http://archive.ubuntu.com precise-backports/restricted TranslationIndex Réception de : 55 http://archive.ubuntu.com precise-backports/universe TranslationIndex Réception de : 56 http://archive.ubuntu.com precise-security/main Sources 71% [56 Sources bzip2 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1bzip2: (stdin) is not a bzip2 file. Réception de : 57 http://archive.ubuntu.com precise-security/restricted Sources 72% [57 Sources bzip2 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1bzip2: (stdin) is not a bzip2 file. Réception de : 58 http://archive.ubuntu.com precise-security/universe Sources 72% [58 Sources bzip2 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1bzip2: (stdin) is not a bzip2 file. Réception de : 59 http://archive.ubuntu.com precise-security/multiverse Sources 73% [59 Sources bzip2 0 B] [Connexion à archive.ubuntu.com] 27,0 kB/s 7sbzip2: (stdin) is not a bzip2 file. Réception de : 60 http://archive.ubuntu.com precise-security/main i386 Packages 73% [60 Packages bzip2 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.bzip2: (stdin) is not a bzip2 file. Réception de : 61 http://archive.ubuntu.com precise-security/restricted i386 Packages 74% [61 Packages bzip2 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.bzip2: (stdin) is not a bzip2 file. Réception de : 62 http://archive.ubuntu.com precise-security/universe i386 Packages 74% [62 Packages bzip2 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.bzip2: (stdin) is not a bzip2 file. Réception de : 63 http://archive.ubuntu.com precise-security/multiverse i386 Packages 75% [63 Packages bzip2 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.bzip2: (stdin) is not a bzip2 file. Réception de : 64 http://archive.ubuntu.com precise-security/main TranslationIndex Réception de : 65 http://archive.ubuntu.com precise-security/multiverse TranslationIndex Réception de : 66 http://archive.ubuntu.com precise-security/restricted TranslationIndex Réception de : 67 http://archive.ubuntu.com precise-security/universe TranslationIndex 70% [19 Sources xz 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107./usr/bin/xz : (stdin): Format de fichier inconnu 70% [20 Sources xz 0 B] [Connexion à archive.ubuntu.com] 19,2 kB/s 12s/usr/bin/xz : (stdin): Format de fichier inconnu 70% [21 Sources xz 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107./usr/bin/xz : (stdin): Format de fichier inconnu 70% [22 Sources xz 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107./usr/bin/xz : (stdin): Format de fichier inconnu 70% [23 Packages xz 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107/usr/bin/xz : (stdin): Format de fichier inconnu 70% [24 Packages xz 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107/usr/bin/xz : (stdin): Format de fichier inconnu 70% [26 Packages xz 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107/usr/bin/xz : (stdin): Format de fichier inconnu 70% [27 Packages xz 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107/usr/bin/xz : (stdin): Format de fichier inconnu 70% [32 Sources xz 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107./usr/bin/xz : (stdin): Format de fichier inconnu 70% [33 Sources xz 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107./usr/bin/xz : (stdin): Format de fichier inconnu 70% [34 Sources xz 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107./usr/bin/xz : (stdin): Format de fichier inconnu 70% [35 Sources xz 0 B] [Connexion à archive.ubuntu.com] 19,2 kB/s 12s/usr/bin/xz : (stdin): Format de fichier inconnu 70% [36 Packages xz 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107/usr/bin/xz : (stdin): Format de fichier inconnu 70% [37 Packages xz 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107/usr/bin/xz : (stdin): Format de fichier inconnu 70% [38 Packages xz 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107/usr/bin/xz : (stdin): Format de fichier inconnu 70% [39 Packages xz 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107/usr/bin/xz : (stdin): Format de fichier inconnu 70% [44 Sources xz 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107./usr/bin/xz : (stdin): Format de fichier inconnu 70% [45 Sources xz 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107./usr/bin/xz : (stdin): Format de fichier inconnu 70% [46 Sources xz 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107./usr/bin/xz : (stdin): Format de fichier inconnu 70% [47 Sources xz 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107./usr/bin/xz : (stdin): Format de fichier inconnu 70% [48 Packages xz 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107/usr/bin/xz : (stdin): Format de fichier inconnu 70% [49 Packages xz 0 B] [Connexion à archive.ubuntu.com]/usr/bin/xz : (stdin): Format de fichier inconnu 70% [50 Packages xz 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107/usr/bin/xz : (stdin): Format de fichier inconnu 70% [51 Packages xz 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107/usr/bin/xz : (stdin): Format de fichier inconnu 70% [56 Sources xz 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107./usr/bin/xz : (stdin): Format de fichier inconnu 70% [57 Sources xz 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107./usr/bin/xz : (stdin): Format de fichier inconnu 70% [58 Sources xz 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107./usr/bin/xz : (stdin): Format de fichier inconnu 70% [59 Sources xz 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107./usr/bin/xz : (stdin): Format de fichier inconnu 70% [60 Packages xz 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107/usr/bin/xz : (stdin): Format de fichier inconnu 70% [61 Packages xz 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107/usr/bin/xz : (stdin): Format de fichier inconnu 70% [62 Packages xz 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.107/usr/bin/xz : (stdin): Format de fichier inconnu 70% [63 Packages xz 0 B] [Connexion à archive.ubuntu.com]/usr/bin/xz : (stdin): Format de fichier inconnu 70% [19 Sources lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.10/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [20 Sources lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.10/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [21 Sources lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.10/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [22 Sources lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.10/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [23 Packages lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [24 Packages lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [26 Packages lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [27 Packages lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [32 Sources lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.10/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [33 Sources lzma 0 B] [Connexion à archive.ubuntu.com]/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [34 Sources lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.10/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [35 Sources lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.10/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [36 Packages lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [37 Packages lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [38 Packages lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [39 Packages lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [44 Sources lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.10/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [45 Sources lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.10/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [46 Sources lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.10/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [47 Sources lzma 0 B] [Connexion à archive.ubuntu.com]/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [48 Packages lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [49 Packages lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [50 Packages lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [51 Packages lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [56 Sources lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.10/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [57 Sources lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.10/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [58 Sources lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.10/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [59 Sources lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.10/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [60 Packages lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [61 Packages lzma 0 B] [Connexion à archive.ubuntu.com]/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [62 Packages lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1/usr/bin/lzma : (stdin): Format de fichier inconnu 70% [63 Packages lzma 0 B] [Connexion à portail1.wifi.univ-nantes.fr (193.52.1/usr/bin/lzma : (stdin): Format de fichier inconnu 795 ko réceptionnés en 1min 18s (10,2 ko/s) W: Erreur de GPG : http://extras.ubuntu.com precise InRelease : Le fichier /var/lib/apt/lists/partial/extras.ubuntu.com_ubuntu_dists_precise_InRelease ne commence pas par un message signé en clair. W: Erreur de GPG : http://hwe.archive.canonical.com precise-ocracoke InRelease : Le fichier /var/lib/apt/lists/partial/hwe.archive.canonical.com_updates_dists_precise-ocracoke_InRelease ne commence pas par un message signé en clair. W: Erreur de GPG : http://dl.google.com stable InRelease : Le fichier /var/lib/apt/lists/partial/dl.google.com_linux_chrome_deb_dists_stable_InRelease ne commence pas par un message signé en clair. W: Erreur de GPG : http://archive.canonical.com precise InRelease : Le fichier /var/lib/apt/lists/partial/archive.canonical.com_ubuntu_dists_precise_InRelease ne commence pas par un message signé en clair. W: Erreur de GPG : http://archive.ubuntu.com precise InRelease : Le fichier /var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise_InRelease ne commence pas par un message signé en clair. W: Erreur de GPG : http://archive.ubuntu.com precise-updates InRelease : Le fichier /var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-updates_InRelease ne commence pas par un message signé en clair. W: Erreur de GPG : http://archive.ubuntu.com precise-backports InRelease : Le fichier /var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-backports_InRelease ne commence pas par un message signé en clair. W: Erreur de GPG : http://archive.ubuntu.com precise-security InRelease : Le fichier /var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-security_InRelease ne commence pas par un message signé en clair. W: Impossible de récupérer gzip:/var/lib/apt/lists/partial/extras.ubuntu.com_ubuntu_dists_precise_main_source_Sources Encountered a section with no Package: header W: Impossible de récupérer gzip:/var/lib/apt/lists/partial/extras.ubuntu.com_ubuntu_dists_precise_main_binary-i386_Packages Encountered a section with no Package: header W: Impossible de récupérer http://extras.ubuntu.com/ubuntu/dists/precise/main/i18n/Index Pas d'entrée de hachage dans le fichier Release /var/lib/apt/lists/partial/extras.ubuntu.com_ubuntu_dists_precise_main_i18n_Index W: Impossible de récupérer gzip:/var/lib/apt/lists/partial/hwe.archive.canonical.com_updates_dists_precise-ocracoke_public_source_Sources Encountered a section with no Package: header W: Impossible de récupérer gzip:/var/lib/apt/lists/partial/hwe.archive.canonical.com_updates_dists_precise-ocracoke_public_binary-i386_Packages Encountered a section with no Package: header W: Impossible de récupérer http://hwe.archive.canonical.com/updates/dists/precise-ocracoke/public/i18n/Index Pas d'entrée de hachage dans le fichier Release /var/lib/apt/lists/partial/hwe.archive.canonical.com_updates_dists_precise-ocracoke_public_i18n_Index W: Impossible de récupérer gzip:/var/lib/apt/lists/partial/dl.google.com_linux_chrome_deb_dists_stable_main_binary-i386_Packages Encountered a section with no Package: header W: Impossible de récupérer http://dl.google.com/linux/chrome/deb/dists/stable/main/i18n/Index Pas d'entrée de hachage dans le fichier Release /var/lib/apt/lists/partial/dl.google.com_linux_chrome_deb_dists_stable_main_i18n_Index W: Impossible de récupérer gzip:/var/lib/apt/lists/partial/archive.canonical.com_ubuntu_dists_precise_partner_source_Sources Encountered a section with no Package: header W: Impossible de récupérer http://archive.canonical.com/ubuntu/dists/precise/partner/i18n/Index Pas d'entrée de hachage dans le fichier Release /var/lib/apt/lists/partial/archive.canonical.com_ubuntu_dists_precise_partner_i18n_Index W: Impossible de récupérer gzip:/var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise_main_source_Sources Encountered a section with no Package: header W: Impossible de récupérer gzip:/var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise_multiverse_binary-i386_Packages Encountered a section with no Package: header W: Impossible de récupérer http://archive.ubuntu.com/ubuntu/dists/precise/main/i18n/Index Pas d'entrée de hachage dans le fichier Release /var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise_main_i18n_Index W: Impossible de récupérer http://archive.ubuntu.com/ubuntu/dists/precise/multiverse/i18n/Index Pas d'entrée de hachage dans le fichier Release /var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise_multiverse_i18n_Index W: Impossible de récupérer http://archive.ubuntu.com/ubuntu/dists/precise/restricted/i18n/Index Pas d'entrée de hachage dans le fichier Release /var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise_restricted_i18n_Index W: Impossible de récupérer http://archive.ubuntu.com/ubuntu/dists/precise/universe/i18n/Index Pas d'entrée de hachage dans le fichier Release /var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise_universe_i18n_Index W: Impossible de récupérer gzip:/var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-updates_main_source_Sources Encountered a section with no Package: header W: Impossible de récupérer gzip:/var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-updates_restricted_source_Sources Encountered a section with no Package: header W: Impossible de récupérer gzip:/var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-updates_universe_source_Sources Encountered a section with no Package: header W: Impossible de récupérer gzip:/var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-updates_main_binary-i386_Packages Encountered a section with no Package: header W: Impossible de récupérer gzip:/var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-updates_restricted_binary-i386_Packages Encountered a section with no Package: header W: Impossible de récupérer gzip:/var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-updates_universe_binary-i386_Packages Encountered a section with no Package: header W: Impossible de récupérer gzip:/var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-updates_multiverse_binary-i386_Packages Encountered a section with no Package: header W: Impossible de récupérer http://archive.ubuntu.com/ubuntu/dists/precise-updates/main/i18n/Index Pas d'entrée de hachage dans le fichier Release /var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-updates_main_i18n_Index W: Impossible de récupérer http://archive.ubuntu.com/ubuntu/dists/precise-updates/multiverse/i18n/Index Pas d'entrée de hachage dans le fichier Release /var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-updates_multiverse_i18n_Index W: Impossible de récupérer http://archive.ubuntu.com/ubuntu/dists/precise-updates/restricted/i18n/Index Pas d'entrée de hachage dans le fichier Release /var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-updates_restricted_i18n_Index W: Impossible de récupérer http://archive.ubuntu.com/ubuntu/dists/precise-updates/universe/i18n/Index Pas d'entrée de hachage dans le fichier Release /var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-updates_universe_i18n_Index W: Impossible de récupérer gzip:/var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-backports_main_source_Sources Encountered a section with no Package: header W: Impossible de récupérer gzip:/var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-backports_restricted_source_Sources Encountered a section with no Package: header W: Impossible de récupérer gzip:/var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-backports_restricted_binary-i386_Packages Encountered a section with no Package: header W: Impossible de récupérer gzip:/var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-backports_universe_binary-i386_Packages Encountered a section with no Package: header W: Impossible de récupérer gzip:/var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-backports_multiverse_binary-i386_Packages Encountered a section with no Package: header W: Impossible de récupérer http://archive.ubuntu.com/ubuntu/dists/precise-backports/main/i18n/Index Pas d'entrée de hachage dans le fichier Release /var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-backports_main_i18n_Index W: Impossible de récupérer http://archive.ubuntu.com/ubuntu/dists/precise-backports/multiverse/i18n/Index Pas d'entrée de hachage dans le fichier Release /var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-backports_multiverse_i18n_Index W: Impossible de récupérer http://archive.ubuntu.com/ubuntu/dists/precise-backports/restricted/i18n/Index Pas d'entrée de hachage dans le fichier Release /var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-backports_restricted_i18n_Index W: Impossible de récupérer http://archive.ubuntu.com/ubuntu/dists/precise-backports/universe/i18n/Index Pas d'entrée de hachage dans le fichier Release /var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-backports_universe_i18n_Index W: Impossible de récupérer gzip:/var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-security_restricted_source_Sources Encountered a section with no Package: header W: Impossible de récupérer gzip:/var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-security_multiverse_source_Sources Encountered a section with no Package: header W: Impossible de récupérer gzip:/var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-security_main_binary-i386_Packages Encountered a section with no Package: header W: Impossible de récupérer gzip:/var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-security_restricted_binary-i386_Packages Encountered a section with no Package: header W: Impossible de récupérer gzip:/var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-security_universe_binary-i386_Packages Encountered a section with no Package: header W: Impossible de récupérer gzip:/var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-security_multiverse_binary-i386_Packages Encountered a section with no Package: header W: Impossible de récupérer http://archive.ubuntu.com/ubuntu/dists/precise-security/main/i18n/Index Pas d'entrée de hachage dans le fichier Release /var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-security_main_i18n_Index W: Impossible de récupérer http://archive.ubuntu.com/ubuntu/dists/precise-security/multiverse/i18n/Index Pas d'entrée de hachage dans le fichier Release /var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-security_multiverse_i18n_Index W: Impossible de récupérer http://archive.ubuntu.com/ubuntu/dists/precise-security/restricted/i18n/Index Pas d'entrée de hachage dans le fichier Release /var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-security_restricted_i18n_Index W: Impossible de récupérer http://archive.ubuntu.com/ubuntu/dists/precise-security/universe/i18n/Index Pas d'entrée de hachage dans le fichier Release /var/lib/apt/lists/partial/archive.ubuntu.com_ubuntu_dists_precise-security_universe_i18n_Index 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. #11 Re : -1 » Problème téléchargement Paquet » Le 07/10/2012, à 14:35 wav-unreal Réponses : 17 Oui, le signal de la wifi est très faible et ce déconnecte souvent, sa ce pourrait que ça soit sa? Juste les téléchargement ont bien marché au début et se sont arrêtes par la fin... pour me rassurer, car des que je saurais à la fac le réseau sera bon et je pourrais les téléchargé? Mais quand je le branche en ethernet, il n'y a aucun paquet qui se télécharge, sa marque le message du début! #12 Re : -1 » Problème téléchargement Paquet » Le 07/10/2012, à 15:26 wav-unreal Réponses : 17 la je me suis carrement mit devant... cela ne change rien maintenant j'ai un petit panneau interdiction et sa me marque Un problème irrémédiable est survenu pendant l'initialisation des informations du paquet. Veuillez signaler ce bogue du paquet « update-manager » en y joignant le message d'erreur suivant : 'E:Encountered a section with no Package: header, E:Problem with MergeList /var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_precise_main_binary-i386_Packages, E:Les listes de paquets ou le fichier « status » ne peuvent être analysés ou lus.' s'il vous plait aidez-moi, j'aimerai bien garder ubuntu mais là je vais etre obigé de mettre windows, ca me fait chier... #13 Re : -1 » Problème téléchargement Paquet » Le 07/10/2012, à 15:34 wav-unreal Réponses : 17 bon désolé de mes problèmes sa a marché mais la sa a pas réussi à installer ou décompresser des paquets... boissonnot@wave:~$ sudo -E apt-get update Ign http://dl.google.com stable InRelease Ign http://archive.canonical.com precise InRelease Ign http://archive.ubuntu.com precise InRelease Ign http://archive.ubuntu.com precise-updates InRelease Réception de : 1 http://archive.canonical.com precise Release.gpg [198 B] Réception de : 2 http://dl.google.com stable Release.gpg [198 B] Ign http://archive.ubuntu.com precise-backports InRelease Ign http://archive.ubuntu.com precise-security InRelease Atteint http://archive.canonical.com precise Release Réception de : 3 http://archive.ubuntu.com precise Release.gpg [198 B] Réception de : 4 http://archive.ubuntu.com precise-updates Release.gpg [198 B] Réception de : 5 http://archive.ubuntu.com precise-backports Release.gpg [198 B] Ign http://extras.ubuntu.com precise InRelease Atteint http://dl.google.com stable Release Ign http://hwe.archive.canonical.com precise-ocracoke InRelease Réception de : 6 http://archive.ubuntu.com precise-security Release.gpg [198 B] Réception de : 7 http://extras.ubuntu.com precise Release.gpg [72 B] Réception de : 8 http://hwe.archive.canonical.com precise-ocracoke Release.gpg [287 B] Atteint http://archive.ubuntu.com precise Release Atteint http://extras.ubuntu.com precise Release Atteint http://hwe.archive.canonical.com precise-ocracoke Release Atteint http://archive.ubuntu.com precise-updates Release Atteint http://archive.ubuntu.com precise-backports Release Atteint http://archive.ubuntu.com precise-security Release Ign http://archive.canonical.com precise Release Réception de : 9 http://archive.canonical.com precise/partner Sources [4 005 B] Ign http://dl.google.com stable Release Ign http://archive.ubuntu.com precise Release Réception de : 10 http://dl.google.com stable/main i386 Packages [1 218 B] Ign http://archive.canonical.com precise/partner i386 Packages/DiffIndex Réception de : 11 http://archive.ubuntu.com precise/main Sources [934 kB] Ign http://dl.google.com stable/main TranslationIndex Ign http://archive.canonical.com precise/partner TranslationIndex Atteint http://archive.canonical.com precise/partner i386 Packages Ign http://extras.ubuntu.com precise Release Ign http://hwe.archive.canonical.com precise-ocracoke Release Réception de : 12 http://extras.ubuntu.com precise/main Sources [7 352 B] Ign http://archive.ubuntu.com precise-updates Release Ign http://archive.ubuntu.com precise-backports Release Réception de : 13 http://hwe.archive.canonical.com precise-ocracoke/public Sources [14 B] Ign http://archive.ubuntu.com precise-security Release Réception de : 14 http://extras.ubuntu.com precise/main i386 Packages [9 654 B] Réception de : 15 http://hwe.archive.canonical.com precise-ocracoke/public i386 Packages [14 B] Ign http://hwe.archive.canonical.com precise-ocracoke/public TranslationIndex Ign http://extras.ubuntu.com precise/main TranslationIndex Ign http://dl.google.com stable/main Translation-fr_FR Ign http://dl.google.com stable/main Translation-fr Ign http://archive.canonical.com precise/partner Translation-fr_FR Ign http://dl.google.com stable/main Translation-en Ign http://archive.canonical.com precise/partner Translation-fr Ign http://archive.canonical.com precise/partner Translation-en Ign http://extras.ubuntu.com precise/main Translation-fr_FR Ign http://extras.ubuntu.com precise/main Translation-fr Ign http://hwe.archive.canonical.com precise-ocracoke/public Translation-fr_FR Ign http://extras.ubuntu.com precise/main Translation-en Ign http://hwe.archive.canonical.com precise-ocracoke/public Translation-fr Ign http://hwe.archive.canonical.com precise-ocracoke/public Translation-en Ign http://archive.ubuntu.com precise/restricted Sources/DiffIndex Ign http://archive.ubuntu.com precise/universe Sources/DiffIndex Ign http://archive.ubuntu.com precise/multiverse Sources/DiffIndex Ign http://archive.ubuntu.com precise/main i386 Packages/DiffIndex Ign http://archive.ubuntu.com precise/restricted i386 Packages/DiffIndex Ign http://archive.ubuntu.com precise/universe i386 Packages/DiffIndex Réception de : 16 http://archive.ubuntu.com precise/multiverse i386 Packages [121 kB] Réception de : 17 http://archive.ubuntu.com precise/main TranslationIndex [3 706 B] Réception de : 18 http://archive.ubuntu.com precise/multiverse TranslationIndex [2 676 B] Réception de : 19 http://archive.ubuntu.com precise/restricted TranslationIndex [2 596 B] Réception de : 20 http://archive.ubuntu.com precise/universe TranslationIndex [2 922 B] Réception de : 21 http://archive.ubuntu.com precise-updates/main Sources [172 kB] Réception de : 22 http://archive.ubuntu.com precise-updates/restricted Sources [3 285 B] Réception de : 23 http://archive.ubuntu.com precise-updates/universe Sources [58,0 kB] Ign http://archive.ubuntu.com precise-updates/multiverse Sources/DiffIndex Réception de : 24 http://archive.ubuntu.com precise-updates/main i386 Packages [403 kB] Réception de : 25 http://archive.ubuntu.com precise-updates/restricted i386 Packages [6 732 B] Réception de : 26 http://archive.ubuntu.com precise-updates/universe i386 Packages [143 kB] Réception de : 27 http://archive.ubuntu.com precise-updates/multiverse i386 Packages [9 673 B] Réception de : 28 http://archive.ubuntu.com precise-updates/main TranslationIndex [3 564 B] Réception de : 29 http://archive.ubuntu.com precise-updates/multiverse TranslationIndex [2 605 B] Réception de : 30 http://archive.ubuntu.com precise-updates/restricted TranslationIndex [2 461 B] Réception de : 31 http://archive.ubuntu.com precise-updates/universe TranslationIndex [2 850 B] Réception de : 32 http://archive.ubuntu.com precise-backports/main Sources [2 422 B] Réception de : 33 http://archive.ubuntu.com precise-backports/restricted Sources [14 B] Ign http://archive.ubuntu.com precise-backports/universe Sources/DiffIndex Ign http://archive.ubuntu.com precise-backports/multiverse Sources/DiffIndex Ign http://archive.ubuntu.com precise-backports/main i386 Packages/DiffIndex Réception de : 34 http://archive.ubuntu.com precise-backports/restricted i386 Packages [14 B] Réception de : 35 http://archive.ubuntu.com precise-backports/universe i386 Packages [13,7 kB] Réception de : 36 http://archive.ubuntu.com precise-backports/multiverse i386 Packages [2 504 B] Réception de : 37 http://archive.ubuntu.com precise-backports/main TranslationIndex [72 B] Réception de : 38 http://archive.ubuntu.com precise-backports/multiverse TranslationIndex [72 B] Réception de : 39 http://archive.ubuntu.com precise-backports/restricted TranslationIndex [70 B] Réception de : 40 http://archive.ubuntu.com precise-backports/universe TranslationIndex [72 B] Ign http://archive.ubuntu.com precise-security/main Sources/DiffIndex Réception de : 41 http://archive.ubuntu.com precise-security/restricted Sources [1 950 B] Ign http://archive.ubuntu.com precise-security/universe Sources/DiffIndex Réception de : 42 http://archive.ubuntu.com precise-security/multiverse Sources [1 386 B] Réception de : 43 http://archive.ubuntu.com precise-security/main i386 Packages [179 kB] Réception de : 44 http://archive.ubuntu.com precise-security/restricted i386 Packages [3 968 B] Réception de : 45 http://archive.ubuntu.com precise-security/universe i386 Packages [48,6 kB] Réception de : 46 http://archive.ubuntu.com precise-security/multiverse i386 Packages [2 369 B] Réception de : 47 http://archive.ubuntu.com precise-security/main TranslationIndex [73 B] Réception de : 48 http://archive.ubuntu.com precise-security/multiverse TranslationIndex [71 B] Réception de : 49 http://archive.ubuntu.com precise-security/restricted TranslationIndex [71 B] Réception de : 50 http://archive.ubuntu.com precise-security/universe TranslationIndex [73 B] Atteint http://archive.ubuntu.com precise/restricted Sources Atteint http://archive.ubuntu.com precise/universe Sources Atteint http://archive.ubuntu.com precise/multiverse Sources Atteint http://archive.ubuntu.com precise/main i386 Packages Atteint http://archive.ubuntu.com precise/restricted i386 Packages Atteint http://archive.ubuntu.com precise/universe i386 Packages Réception de : 51 http://archive.ubuntu.com precise/main Translation-fr_FR [494 kB] Réception de : 52 http://archive.ubuntu.com precise/main Translation-fr [502 kB] Réception de : 53 http://archive.ubuntu.com precise/main Translation-en [726 kB] Réception de : 54 http://archive.ubuntu.com precise/multiverse Translation-fr_FR [93,8 kB] Réception de : 55 http://archive.ubuntu.com precise/multiverse Translation-fr [94,9 kB] Réception de : 56 http://archive.ubuntu.com precise/multiverse Translation-en [93,4 kB] Réception de : 57 http://archive.ubuntu.com precise/restricted Translation-fr_FR [2 506 B] Réception de : 58 http://archive.ubuntu.com precise/restricted Translation-fr [2 668 B] Réception de : 59 http://archive.ubuntu.com precise/restricted Translation-en [2 395 B] Réception de : 60 http://archive.ubuntu.com precise/universe Translation-fr_FR [870 kB] Réception de : 61 http://archive.ubuntu.com precise/universe Translation-fr [905 kB] Réception de : 62 http://archive.ubuntu.com precise/universe Translation-en [3 341 kB] Atteint http://archive.ubuntu.com precise-updates/multiverse Sources Réception de : 63 http://archive.ubuntu.com precise-updates/main Translation-fr [507 kB] Réception de : 64 http://archive.ubuntu.com precise-updates/main Translation-en [196 kB] Réception de : 65 http://archive.ubuntu.com precise-updates/multiverse Translation-fr [94,9 kB] Réception de : 66 http://archive.ubuntu.com precise-updates/multiverse Translation-en [5 414 B] Réception de : 67 http://archive.ubuntu.com precise-updates/restricted Translation-fr [2 668 B] Réception de : 68 http://archive.ubuntu.com precise-updates/restricted Translation-en [1 484 B] Réception de : 69 http://archive.ubuntu.com precise-updates/universe Translation-fr [905 kB] Réception de : 70 http://archive.ubuntu.com precise-updates/universe Translation-en [83,8 kB] Atteint http://archive.ubuntu.com precise-backports/universe Sources Atteint http://archive.ubuntu.com precise-backports/multiverse Sources Atteint http://archive.ubuntu.com precise-backports/main i386 Packages Réception de : 71 http://archive.ubuntu.com precise-backports/main Translation-en [1 244 B] Réception de : 72 http://archive.ubuntu.com precise-backports/multiverse Translation-en [1 476 B] Réception de : 73 http://archive.ubuntu.com precise-backports/restricted Translation-en [14 B] Réception de : 74 http://archive.ubuntu.com precise-backports/universe Translation-en [9 880 B] Atteint http://archive.ubuntu.com precise-security/main Sources Atteint http://archive.ubuntu.com precise-security/universe Sources Réception de : 75 http://archive.ubuntu.com precise-security/main Translation-en [85,2 kB] Réception de : 76 http://archive.ubuntu.com precise-security/multiverse Translation-en [995 B] Réception de : 77 http://archive.ubuntu.com precise-security/restricted Translation-en [978 B] Réception de : 78 http://archive.ubuntu.com precise-security/universe Translation-en [30,2 kB] 11,2 Mo réceptionnés en 16s (694 ko/s) Lecture des listes de paquets... Erreur ! W: Erreur de GPG : http://archive.canonical.com precise Release : Les signatures suivantes ne sont pas valables : BADSIG 40976EAF437D05B5 Ubuntu Archive Automatic Signing Key <ftpmaster@ubuntu.com> W: Erreur de GPG : http://dl.google.com stable Release : Les signatures suivantes ne sont pas valables : BADSIG A040830F7FAC5991 Google, Inc. Linux Package Signing Key <linux-packages-keymaster@google.com> W: Erreur de GPG : http://archive.ubuntu.com precise Release : Les signatures suivantes ne sont pas valables : BADSIG 40976EAF437D05B5 Ubuntu Archive Automatic Signing Key <ftpmaster@ubuntu.com> W: Erreur de GPG : http://extras.ubuntu.com precise Release : Les signatures suivantes ne sont pas valables : BADSIG 16126D3A3E5C1192 Ubuntu Extras Archive Automatic Signing Key <ftpmaster@ubuntu.com> W: Erreur de GPG : http://hwe.archive.canonical.com precise-ocracoke Release : Les signatures suivantes ne sont pas valables : BADSIG F9FDA6BED73CDC22 Canonical Archive Automatic Signing Key <ftpmaster@canonical.com> W: Erreur de GPG : http://archive.ubuntu.com precise-updates Release : Les signatures suivantes ne sont pas valables : BADSIG 40976EAF437D05B5 Ubuntu Archive Automatic Signing Key <ftpmaster@ubuntu.com> W: Erreur de GPG : http://archive.ubuntu.com precise-backports Release : Les signatures suivantes ne sont pas valables : BADSIG 40976EAF437D05B5 Ubuntu Archive Automatic Signing Key <ftpmaster@ubuntu.com> W: Erreur de GPG : http://archive.ubuntu.com precise-security Release : Les signatures suivantes ne sont pas valables : BADSIG 40976EAF437D05B5 Ubuntu Archive Automatic Signing Key <ftpmaster@ubuntu.com> E: Encountered a section with no Package: header E: Problem with MergeList /var/lib/apt/lists/archive.ubuntu.com_ubuntu_dists_precise_main_binary-i386_Packages E: Les listes de paquets ou le fichier « status » ne peuvent être analysés ou lus. #14 Re : -1 » Problème téléchargement Paquet » Le 07/10/2012, à 16:02 wav-unreal Réponses : 17 encore désolé... maintenant c'est bon sa marche enfin enfin la lecture des paquets a été faits sans rencontrer de problèmes. mais, j'ai internet, je suis à fond et quand je mais à jour mon pc ou que j'installe, il me marque encore vérifiez votre connexion internet... faut-il que j'aille dans réseau parcellaire et que je tape dans manuel mon proxy car là je suis en automatique avec une adresse PAC? Merci... #15 Re : -1 » Problème téléchargement Paquet » Le 07/10/2012, à 16:15 wav-unreal Réponses : 17 j'espère que vous aurez une meilleure solution car c'est un peu chiant... pour faire les mises à jour, je suis obligé de faire ce que vous m'avez dit export http ... pour le proxy et après sudo -E apt-get upgrade J'aimerai bien passer par l'interface graphique... même pour un logiciel c'est ambetant...
PPdM goolgle et Ubuntu 64bits Salut Je vous soumet un probleme recurent que je croyais du a ma config matérielle mais qui se manifeste sur un autre PC totalement différent. Les accès a google (tout les sites) sont très lent quand ce n'est pas impossible sur les config en 64 BIts, j'ai deux PC (un portable et un fixe) qui sont quasiment incapable de se connecter a goolge alors quetous les autres pc se connecte sans soucis la seule difference etant que ces deux PC sont en Ubuntu 64 bits! c'est un bug général ou juste moi qui n'ai pas de chance? Hors ligne Кຼزດ Re : goolgle et Ubuntu 64bits Je pense que c'est plutôt «pas de chance», vu que j'ai jamais eu aucun problème de ce côté là, en étant en full 64bits. C'est uniquement avec google? Et avec un autre navigateur, ça passe pas non plus ? dou Hors ligne PPdM Re : goolgle et Ubuntu 64bits salut c'est aléatoire, hier j'avais une installation beta 5 et cela marchait sur ce pc ,j'ai réinstallé la version définitive depuis le dvd ,et tout fonctionne nickel sauf google, encore que j'ai réussi a avoir un connexion au premier demarrage mais maintenant c'est horriblement long et je suis même obligé de fermer firefox et de relancer c'est le deuxième pc qui me fait cela et tout les deux en 64 bits, tout les autres sites fonctionnent normalement!!:/ la par ex j'ai réussi a avoir un connexion google mais cela rame(5minutes environ) pour me connecter a mon compte,alors que sur mes autres pc c'est instantané!:/ Hors ligne MacArony Re : goolgle et Ubuntu 64bits Bin ouai t'as pas de chance parce que je suis en 64bits aussi et tout va bien... Mais des fois (attention hypothèse) je sais pas si c'est le net qui bouchonne mais j'ai du mal à afficher certain sites notamment quand je recharge à grand coups de F5. À oui aussi, GOOGLE SAPU DES PIEDS ! Dsl (Moi j'utilise Ixquick en https.) edit : je viens de faire le test en checkant mes mail via gmail.com (d'hab je regarde via thunderbird) et ça marche nikel. Dernière modification par Asphaltsnatch (Le 20/06/2009, à 14:37) Psycho$PATH ! Jbois du whitespirit au ptit dej et J'aime les Japonaises J'ai un micropenis mais j'assume J'ai fait un doigt d'honneur à Dark Vador...enfin, j'ai essayé... Hors ligne #hehedotcom\'isback Re : goolgle et Ubuntu 64bits hello Je suis en 64 bits depuis pas mal de temps, et je n'ai pas rencontré ces soucis. En revanche quel est ton fai? Teste ça: - Déclare eth0 dans le fichier interfaces, si ce n'est pas déjà le cas lo + eth0 en dhcp sudo /etc/init.d/networking stop echo -e 'auto lo\niface lo inet loopback\n\nauto eth0\niface eth0 inet dhcp\n' | sudo tee /etc/network/interfaces sudo /etc/init.d/networking restart [Code à taper en console/terminal et une ligne égale une commande] sudo -s echo 0 >/proc/sys/net/ipv4/tcp_window_scaling echo 4096 16384 524288 >/proc/sys/net/ipv4/tcp_rmem echo 4096 16384 524288 >/proc/sys/net/ipv4/tcp_wmem ifdown eth0 ifup eth0 exit Relancer le navigateur. Si la connexion et l'accès aux sites sont possibles, fixer les valeurs définitivement en éditant le fichier /etc/sysctl.conf et y ajouter à la fin: net.ipv4.tcp_window_scaling=0 net.ipv4.tcp_rmem=4096 16384 524288 net.ipv4.tcp_wmem=4096 16384 524288 Ce n'est pas dit que ce soit la solution, juste un point de départ. Dernière modification par #hehedotcom\'isback (Le 20/06/2009, à 14:41) Hors ligne PPdM Re : goolgle et Ubuntu 64bits salut,#hehedotcom\'isback Je vais tester ton truc si cela ne s'améliore pas , je suis chez FREE et j'ai plusieurs postes et seuls les deux en 64 bits me posent ce souci, un en filaire et l'autre en wifi sur le wifi cela marche mais très lent avec des rappels de connexion j'y arrive mais c'est vraiment bizarre! Hors ligne #hehedotcom\'isback Re : goolgle et Ubuntu 64bits Je serai surpris que ce soit la solution, sauf si tu as activé le réseau ipV6 sur le routeur. Deuxieme piste, le fichier /etc/hosts. Parfois le systeme se met sur deux routes, met le sur 127.0.0.1 cat /etc/hosts 127.0.0.1 localhost hp-linux mkl.is-a-geek.com 192.168.0.5 hp-linux.mkl.is-a-geek.com mkl.is-a-geek.com hp-linux 192.168.0.4 hp2-linux hp2-linux.mkl.is-a-geek.com # The following lines are desirable for IPv6 capable hosts ::1 localhost ip6-localhost ip6-loopback fe00::0 ip6-localnet ff00::0 ip6-mcastprefix ff02::1 ip6-allnodes ff02::2 ip6-allrouters ff02::3 ip6-allhosts mike@hp-linux:~$ Dernière modification par #hehedotcom\'isback (Le 20/06/2009, à 15:14) Hors ligne PPdM Re : goolgle et Ubuntu 64bits salut oui j'ai ipv6 activé, j'ai deux connexion free je vais acitver la seconde pour voir si j'ai le même souci mais tu as une idée sur le pourquoi du souci uniquement sur les ubuntu 64 bits? j'aie installer un suze11 et une debian, sur un autre pc et je n'ai pas de souci la per exemple j'ai reussi a me connecter sur mon compte IGoogle mais je n'arrive pas a aller suur Gmail! Hors ligne tshirtman Re : goolgle et Ubuntu 64bits tu peut aussi donner le résultat de ping google.com et tracepath google.com Hors ligne PPdM Re : goolgle et Ubuntu 64bits salut je suis sur l'un des pc qui merde ping 64 bytes from pz-in-f100.google.com (74.125.127.100): icmp_seq=39 ttl=237 time=223 ms 64 bytes from pz-in-f100.google.com (74.125.127.100): icmp_seq=40 ttl=237 time=243 ms 64 bytes from pz-in-f100.google.com (74.125.127.100): icmp_seq=41 ttl=237 time=239 ms 64 bytes from pz-in-f100.google.com (74.125.127.100): icmp_seq=42 ttl=237 time=236 ms 64 bytes from pz-in-f100.google.com (74.125.127.100): icmp_seq=43 ttl=237 time=252 ms 64 bytes from pz-in-f100.google.com (74.125.127.100): icmp_seq=44 ttl=237 time=239 ms 64 bytes from pz-in-f100.google.com (74.125.127.100): icmp_seq=45 ttl=237 time=214 ms 64 bytes from pz-in-f100.google.com (74.125.127.100): icmp_seq=46 ttl=237 time=250 ms 64 bytes from pz-in-f100.google.com (74.125.127.100): icmp_seq=47 ttl=237 time=218 ms 64 bytes from pz-in-f100.google.com (74.125.127.100): icmp_seq=48 ttl=237 time=213 ms 64 bytes from pz-in-f100.google.com (74.125.127.100): icmp_seq=49 ttl=237 time=213 ms 64 bytes from pz-in-f100.google.com (74.125.127.100): icmp_seq=50 ttl=237 time=211 ms 64 bytes from pz-in-f100.google.com (74.125.127.100): icmp_seq=51 ttl=237 time=213 ms 64 bytes from pz-in-f100.google.com (74.125.127.100): icmp_seq=52 ttl=237 time=210 ms 64 bytes from pz-in-f100.google.com (74.125.127.100): icmp_seq=53 ttl=237 time=217 ms 64 bytes from pz-in-f100.google.com (74.125.127.100): icmp_seq=54 ttl=237 time=212 ms --- google.com ping statistics --- 54 packets transmitted, 54 received, 0% packet loss, time 53073ms pierre@SATELITEL300D:~$ tracepath google.com 1: SATELITEL300D.local (192.168.0.21) 0.420ms pmtu 1500 1: 192.168.0.254 (192.168.0.254) 12.878ms 1: 192.168.0.254 (192.168.0.254) 13.055ms 2: 82.246.223.254 (82.246.223.254) 90.328ms 3: 213.228.20.254 (213.228.20.254) 64.420ms asymm 4 4: lyon-6k-1-v804.intf.routers.proxad.net (212.27.50.102) 171.823ms asymm 5 5: th2-crs16-1-be2001.intf.routers.proxad.net (212.27.59.29) 80.015ms asymm 6 6: cbv-6k-1-po21.intf.routers.proxad.net (212.27.58.2) 79.849ms asymm 7 7: no reply 8: no reply 9: no reply 10: no reply 11: no reply 12: no reply 13: no reply 14: no reply 15: no reply 16: no reply 17: no reply 18: no reply 19: no reply 20: no reply 21: no reply 22: no reply 23: no reply 24: no reply 25: no reply 26: no reply 27: no reply 28: no reply 29: no reply 30: no reply 31: no reply Too many hops: pmtu 1500 Resume: pmtu 1500 Hors ligne PPdM Re : goolgle et Ubuntu 64bits bon je crois que j'ai un piste mais je ne sais pas laquelle!!! je viens d'activer ma deuxième borne wifi et la je me connecte en moins de trente secondes et j'ai gmail et moins de 10 secondes, donc il semblerai qu'il y est un souci entre mes postes 64bits le la freebox pour les echange avec Google mais je n'ai pas la première idée du problème, je vais faire un if config des deuc nonnexions pour comparer qu'en pensez vous? Hors ligne tshirtman Re : goolgle et Ubuntu 64bits ça parait pas excessif... je pense que c'est pas un probleme bas niveau... ta connexion va bien. peut tu poster ton fichier /etc/hosts ? Hors ligne PPdM Re : goolgle et Ubuntu 64bits bon les gars j'ai avancé mais je n'ai pas encore compris J'ai changé de connexion freebox (pas la même box, pas la même ligne et donc pas la meme IP) et la cela fonctionne normalement bien que google reste légèrement plus lent que sur mon autre portable sur l'autre box par contre sur ce portable ma connexion win7 64bits est normale,sur les deux box donc le pourquoi reste un mystère surtout que j'ai deux pc et trois config 64 bits qui on le même souci, qui n'existe pas en version 32bits. ????????????:/ Hors ligne PPdM Re : goolgle et Ubuntu 64bits fausse piste , le probleme reviens apres la premier connexion!???:/ 127.0.0.1 localhost 127.0.1.1 SATELITEL300D # The following lines are desirable for IPv6 capable hosts ::1 localhost ip6-localhost ip6-loopback fe00::0 ip6-localnet ff00::0 ip6-mcastprefix ff02::1 ip6-allnodes ff02::2 ip6-allrouters ff02::3 ip6-allhosts Hors ligne #hehedotcom\'isback Re : goolgle et Ubuntu 64bits Tu aurais pu te donner la peine d'essayer 127.0.0.1 localhost SATELITEL300D # The following lines are desirable for IPv6 capable hosts ::1 localhost ip6-localhost ip6-loopback fe00::0 ip6-localnet ff00::0 ip6-mcastprefix ff02::1 ip6-allnodes ff02::2 ip6-allrouters ff02::3 ip6-allhosts Dernière modification par #hehedotcom\'isback (Le 20/06/2009, à 17:04) Hors ligne PPdM Re : goolgle et Ubuntu 64bits pas eu le temps j'ai eu la visite d'un copain en plein milieu mes tests je reviens a peine ET en plus maintenant cela marche sur ma freebox2 après le dernier redémarrage. je vais tester l'autre connexion les deux fonctionnent correctement, et freewifi aussi, je ne comprends plus rien et le hosts est inchangé, bon je ne touche plus rien pour le moment et j'attends de voir si cela ce reproduit, et demain je vérifierai l'autre poste, et j'essayerai si besoin, ton truc. Merci pour vos tuyau!:D Hors ligne
Composite Manager Retained Drawing Protocol RFC Robert Carr 02/28/07 Outline and justification: Results from development in the creation of 'first generation' mainstream composite window managers has outlined the need for several reconsiderations in regards to applications interacting and communicating with the composite manager. Currently code can interact with a composite manager in one of several fashions: Composite managers can expose a plugin interface enabling libraries functioning as plugins to implement new functionality for a composite manager. This is effective for many of the traditional window manager functionalities, but has several weaknesses. Slow code in the composite manager will make an entire system feel sluggish, and furthermore under existing and easily forseeable plugin architectures plugins such as the Thumbnail plugin of Beryl and Compiz waste an excessive amount of CPU even while not doing anything interesting. Furthermore applications requiring an excessive amount of user interaction are cumbersome and difficult to write, and attempts to do so often expose the problem of slow code in a composite manager making the entire system feel sluggish. Lastly applications requiring a great deal of interaction with other components of the desktop are not well suited to existing as a plugin for a compositor, while they still might find it useful to leverage some of the power of a compositor. Composite managers can communicate with client applications through X window properties. This is a suitable way to store simple information and flags, but the use quickly breaks down when attempting to traffic large (things such as Pixmaps or a vertex array) amounts of information in a latency sensitive manner. Composite managers can communicate with client applications through an interprocess communications protocol such as DBUS. This is a suitable way for triggering actions, and a sort of 'scripting' but suffers from similar issues to that of X properties in leveraging the compositor for producing rich client applications. As a solution this document proposes the creation of a low level protocol used to leverage the composite manager for drawing purposes. Composite managers would expose a struct in shared memory where client applications could queue 'Requests' to specify specific drawing operations and state changes. The proposed protocol is lightweight and generic allowing for implementation in a multitude of composite managers while maintaining ABI compatibility. Structure of implementation and low level protocol description The protocol will be built upon Requests structured as following: An enumeration of named opcodes for each request. For each opcode a structure representing any parameters or attributes which the client application must communicate to the compositor to complete the specific request A structure representing an entire request containing the opcode, and a union of attribute structures for all opcodes. Furthermore the request structure will contain a pointer to the next and previous request. Composite managers will expose a struct in shared memory (henceforth referred to as the transport) (TODO: Best method to establish initial communication?) containing: A doubly linked list of requests, client applications will add requests to the end of this list and the composite manager will clear requests from the list upon executing them. A struct representing the last executed request and opcodes for any return information which this request may have generated. The return information will be a pointer to a struct made accessible of a type defined by the particular request. A lock on the structure to prevent issues with multiple clients accessing the structure. Ideally clients will interact with the protocol through a higher level library. Composite managers will be required to ensure that at each paint all requests are cleared EXCEPT in the case where a lock exists on the transport (Though adding a request will not neccesarily trigger a paint) (TODO: Damage attribute on transport/something?). Furthermore the composite manager will be required to guarantee that actions occur in the order they were added. (TODO: Client attribute to requests to enable sorting of requests when clients don't respect the lock?). Respect of the lock on the transport must be observed at the client level. Opcodes The first version of the CMRD protocol defines 13 opcodes. Opcode 0: Name: CompositeManagerQueryProtocolVersionRequest Attributes: None Return attributes: int major; int minor; Description and implementation notes: Returns the major and minor version of the implemented protocol. Opcode 1: Name: CompositeManagerReadyRequest Attributes: None Return Attributes: int ready; Description and implementation notes: Indicates whether the composite manager is ready and able to respond to drawing requests. Opcode 2: Name: CompositeManagerScreengrabLockExistsRequest Attributes: TODO Return attributes: int exists; Description and implementation notes: The concept of a 'Screengrab Lock' is used to indicate whether a client is using the composite manager for a fullscreen and screengrabbing effect, where it would not be appropriate for other clients to do the same. An actual X grab may or may not be issued based on attributes. Opcode 3: Name: CompositeManagerPushScreengrabLockRequest Attributes: TODO Return attributes: TODO Description and implementation notes: Pushes a screengrab lock. Opcode 4: Name: CompositeManagerPopScreengrabLockRequest Attributes: None Return attributes: None Description and implementation notes: Pops the active screengrab lock. Opcode 5: Name: CompositeManagerSetDrawingLevelRequest Attributes: Window level; int screen; Return attributes: None Description and implementation notes: Sets the current drawing level, in that further drawing requests will be rendered at the same level as the 'Window level' attribute, or above all windows if 'Bool screen' is true. Opcode 6: Name: CompositeManagerSetDamageResponseRequest Attributes: int respond; Return attributes: None Description and implementation notes: Temporarily toggles the composite manager from repainting damaged areas. Opcode 7: Name: CompositeManagerSetActiveTextureFromWindowRequest Attributes: Window window; Return attributes: None Description and implementation notes: Creates a texture from the CURRENT drawable of the window and uses it for future retained drawing operations. Opcode 8: Name: CompositeManagerSetActiveTextureFromPixmapRequest Attributes: Pixmap pixmap; Return attributes: None Description and implementation notes: BINDS a texture from the passed pixmap and uses it for future retained drawing operations. Opcode 9: Name: CompositeManagerSetRenderScreenOffscreenRequest Attributes: int offscreen Return attributes: None Description and implementation notes: Based on the value of offscreen begin rendering the screen to an offscreen framebuffer object or GLXPBuffer (based on availability of FBO), and set the active texture to a texture generated from such rendering. Opcode 10: Name: CompositeManagerSetCurrentVertexArrayRequest Attributes: float * vertices; int nvertices; Return attributes: None Description and implementation notes: float * vertices should be a 0 offset array of vertices in the format x, y, z. This is used as the geometry for future drawn objects. It is to be assumed that the vertices are in screen coordinates, with 0, 0 (x, y) being the TOP LEFT of the screen. Opcode 11: Name: CompositeManagerSetCurrentTextureArrayRequest Attributes: float * coords; int ncoords; Return attributes: None Description and implementation notes: Same format asCompositeManagerSetCurrentVertexArraywithout the z coordinate. This is used as the texture coordinates for future drawn objects. Opcode 12: Name: CompositeManagerDrawRequest Attributes: None Return attributes: None Description and implementation notes: Enable the current retained drawing texture, and render the geometry in the current vertex array with the texture coordinates in the current texture array. Opcode 13: Name: CompositeManagerDamageScreenRequest Attributes: None Return attributes: None Description and implementation notes: Force the composite manager to redraw the screen. Example Usage Drawing a window thumbnail for Window id at 300, 300 on a quad with width and height 100. Requests: CompositeManagerSetDrawingLevelRequest ( Window level = 0, screen = TRUE) CompositeManagerSetActiveTextureFromWindowRequest ( Window id) CompositeManagerSetCurrentVertexArrayRequest ( float * vertices = 300, 300, 0, 300, 400, 0, 400, 400, 0, 400, 300, 0 nvertices = 4) CompositeManagerSetCurrentTextureArrayRequest ( float * coords = 0,0,0,1,1,1,1,0 ncoords = 4) CompositeManagerDrawRequest Drawing a thumbnail of what the screen would look like on a different viewport at 300, 300 on a quad with width and height 100. Requests: CompositeManagerSetRenderOffscreenRequest offscreen = 1 CompositeManagerDamageScreenRequest CompositeManagerSetCurrentVertexArrayRequest ( float * vertices = 300, 300, 0, 300, 400, 0, 400, 400, 0, 400, 300, 0 nvertices = 4) CompositeManagerSetCurrentTextureArrayRequest ( float * coords = 0,0,0,1,1,1,1,0 ncoords = 4) CompositeManagerDrawRequest
If a GSettings schema exists and has been compiled, there is usually no problem reading from it. However, if it doesn't exist, an error is usually thrown which cannot be handled. Try this in a Python file or console: from gi.repository import Gio try: settings = Gio.Settings("com.example.doesnotexist") except: print "Couldn't load those settings!" I'm being as broad as possible with the except, but this is the error that is thrown. (process:10248): GLib-GIO-ERROR **: Settings schema 'com.example.doesnotexist' is not installed What I basically want to do is find out if the com.example.doesnotexist schema exists or not; if not, then tell the user to run my setup script before using my application. Any other suggestions on doing this would be welcome.
I am trying to package a program I wrote (using Pyqt4) into a single executable for linux. I tried using Pyinstaller however it has problems with importing Gio (for settings) from gi.repository import Gio Running the application would give: ImportError: cannot import name Gio I then tried to use bbFreeze. The problem here is that after compiling and running the application, I get this error message: TypeError: GObject.__init__() takes exactly 0 arguments (1 given) For bbFreeze this is my script I am running to compile the code: #!/usr/bin/env python from bbfreeze import Freezer includes = ["gio"] excludes = [] bbFreeze_Class = Freezer('dist', includes=includes, excludes=excludes) bbFreeze_Class.addScript("main.py", gui_only=True) bbFreeze_Class.use_compression = 0 bbFreeze_Class.include_py = True bbFreeze_Class() I am using Ubuntu 11.10 and Python 2.7. If someone can help that would be great. This is my first time writing Python and trying to compile it (so I am not sure if there are better alternatives).
I've recently been running one of my apps through Valgrind but there's a few MYSQL related leaks I can't fix. I put the offending code in the most basic form and tested that; I got the same leaks. Should I just disregard them or am I doing something wrong? Code: #include <stdio.h> #include <stdlib.h> #include <mysql/mysql.h> int main() { MYSQL *MYSQLIns; MYSQLIns = mysql_init(NULL); mysql_real_connect(MYSQLIns, "localhost", "username", "password", "database", 0, NULL, 0); mysql_close(MYSQLIns); return EXIT_SUCCESS; } Compiled With: gcc -g -lmysqlclient mysql_mem_test.c -o mysql_mem_test Valgrind Output: valgrind --leak-check=full ./mysql_mem_test ==4601== Memcheck, a memory error detector ==4601== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al. ==4601== Using Valgrind-3.5.0-Debian and LibVEX; rerun with -h for copyright info ==4601== Command: ./mysql_mem_test ==4601== ==4601== ==4601== HEAP SUMMARY: ==4601== in use at exit: 61,336 bytes in 16 blocks ==4601== total heap usage: 70 allocs, 54 frees, 109,218 bytes allocated ==4601== ==4601== 24,528 bytes in 6 blocks are possibly lost in loss record 4 of 5 ==4601== at 0x4024C1C: malloc (vg_replace_malloc.c:195) ==4601== by 0x4079BB2: my_once_alloc (in /usr/lib/libmysqlclient.so.16.0.0) ==4601== by 0x407A408: ??? (in /usr/lib/libmysqlclient.so.16.0.0) ==4601== by 0x407AED1: ??? (in /usr/lib/libmysqlclient.so.16.0.0) ==4601== by 0x407B112: get_charset_by_csname (in /usr/lib/libmysqlclient.so.16.0.0) ==4601== by 0x409D55B: mysql_init_character_set (in /usr/lib/libmysqlclient.so.16.0.0) ==4601== by 0x409F5A1: mysql_real_connect (in /usr/lib/libmysqlclient.so.16.0.0) ==4601== by 0x80485E0: main (mysql_mem_test.c:12) ==4601== ==4601== 28,616 bytes in 7 blocks are possibly lost in loss record 5 of 5 ==4601== at 0x4024C1C: malloc (vg_replace_malloc.c:195) ==4601== by 0x4079BB2: my_once_alloc (in /usr/lib/libmysqlclient.so.16.0.0) ==4601== by 0x407A3E9: ??? (in /usr/lib/libmysqlclient.so.16.0.0) ==4601== by 0x407AED1: ??? (in /usr/lib/libmysqlclient.so.16.0.0) ==4601== by 0x407B112: get_charset_by_csname (in /usr/lib/libmysqlclient.so.16.0.0) ==4601== by 0x409D55B: mysql_init_character_set (in /usr/lib/libmysqlclient.so.16.0.0) ==4601== by 0x409F5A1: mysql_real_connect (in /usr/lib/libmysqlclient.so.16.0.0) ==4601== by 0x80485E0: main (mysql_mem_test.c:12) ==4601== ==4601== LEAK SUMMARY: ==4601== definitely lost: 0 bytes in 0 blocks ==4601== indirectly lost: 0 bytes in 0 blocks ==4601== possibly lost: 53,144 bytes in 13 blocks ==4601== still reachable: 8,192 bytes in 3 blocks ==4601== suppressed: 0 bytes in 0 blocks ==4601== Reachable blocks (those to which a pointer was found) are not shown. ==4601== To see them, rerun with: --leak-check=full --show-reachable=yes ==4601== ==4601== For counts of detected and suppressed errors, rerun with: -v ==4601== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 55 from 38)
Is there something more simple we could try first? Should we compare the secrets? 'And fun? If maths is fun, then getting a tooth extraction is fun. A viral infection is fun. Rabies shots are fun.' 'God exists because Mathematics is consistent, and the devil exists because we cannot prove it' 'Humanity is still kept intact. It remains within.' -Alokananda Offline Hm, we could. But, I will be able to do that after I get my good night's sleep. “Here lies the reader who will never open this book. He is forever dead. “Taking a new step, uttering a new word, is what people fear most.” ― Fyodor Dostoyevsky, Crime and Punishment Offline Isn't it already 3 o clock there? Do you remain awake for so long? Anyway, goodnight 'And fun? If maths is fun, then getting a tooth extraction is fun. A viral infection is fun. Rabies shots are fun.' 'God exists because Mathematics is consistent, and the devil exists because we cannot prove it' 'Humanity is still kept intact. It remains within.' -Alokananda Offline http://pastebin.com/MyZtxUyu import base64 def rc4crypt(data, key): x = 0 box = range(256) for i in range(256): x = (x + box[i] + ord(key[i % len(key)])) % 256 box[i], box[x] = box[x], box[i] x,y = 0, 0 out = [] for char in data: x = (x + 1) % 256 y = (y + box[x]) % 256 box[x], box[y] = box[y], box[x] out.append(chr(ord(char) ^ box[(box[x] + box[y]) % 256])) return ''.join(out) def decode(message,key): return rc4crypt(base64.b64decode(message),key) def encode(message,key): return base64.b64encode(rc4crypt(message,key)) key = raw_input('Enter secret here:\n') message = raw_input('Enter message here:\n') print 'If you wanted to encrypt, here\'s the cyphertext:', encode(message,key) try: print 'If you wanted to decrypt, here\'s the plaintext:', decode(message,key) except: pass Instructions 1. Paste the above python code in a file and run in a python interpreter if you have one, else paste it to a. ideone b. repl.it 2. The program takes 2 lines of input from stdin. The first line accepts the secret and the second line accepts the cyphertext or plaintext 3. Enter your secret in the exact decimal form(because I could not find a better way, this should work until we get something better). For example, if your secret is 7000123, you just type in 7000123(or copypasta it). 4. Running it on a interpreter or on repl.it will prompt you to enter the secret and the message when you are expected to do so. 5. To run it on ideone, you are supposed to enter the secret and the message seperated by a newline in the stdin field before running the program. 'And fun? If maths is fun, then getting a tooth extraction is fun. A viral infection is fun. Rabies shots are fun.' 'God exists because Mathematics is consistent, and the devil exists because we cannot prove it' 'Humanity is still kept intact. It remains within.' -Alokananda Offline Could you post the link to the video? In mathematics, you don't understand things. You just get used to them.I have the result, but I do not yet know how to get it.All physicists, and a good many quite respectable mathematicians are contemptuous about proof. Offline nhmIfQZuJaeccvW/WqEvpFAHfI5I1yqkSXLLbZ0uhH8g “Here lies the reader who will never open this book. He is forever dead. “Taking a new step, uttering a new word, is what people fear most.” ― Fyodor Dostoyevsky, Crime and Punishment Offline nhmIfQZuJaeccvW/WqEvpFAHfI5I1yqkSXLLbZ0uhH8g jxXbHUFJOPSGePnyFptuvR8MeIhJkg== 'And fun? If maths is fun, then getting a tooth extraction is fun. A viral infection is fun. Rabies shots are fun.' 'God exists because Mathematics is consistent, and the devil exists because we cannot prove it' 'Humanity is still kept intact. It remains within.' -Alokananda Offline jxXbHUFJOPSGePnyFptuvR8MeIhJkg== nwSIWA5lP/XUVOy5CcI8rxESf4JI0CCoSjc= “Here lies the reader who will never open this book. He is forever dead. “Taking a new step, uttering a new word, is what people fear most.” ― Fyodor Dostoyevsky, Crime and Punishment Offline nwSIWA5lP/XUVOy5CcI8rxESf4JI0CCoSjc= khnMHBhvOfSBbv2+E4YrpR4bM5obky6pBn/AOYw0nX56Yc5bvQ== 'And fun? If maths is fun, then getting a tooth extraction is fun. A viral infection is fun. Rabies shots are fun.' 'God exists because Mathematics is consistent, and the devil exists because we cannot prove it' 'Humanity is still kept intact. It remains within.' -Alokananda Offline yes,I want a Terminal code.Thank you! Offline Hi; What do you want a terminal code for? If you're on mac, you probably already have python. I have never used a mac, I do not know about the mac terminal. Still, I believe that I could help if I knew what code you need 'And fun? If maths is fun, then getting a tooth extraction is fun. A viral infection is fun. Rabies shots are fun.' 'God exists because Mathematics is consistent, and the devil exists because we cannot prove it' 'Humanity is still kept intact. It remains within.' -Alokananda Offline I'm not sure if I should post, (1) it is somewhat necro-posting, (2) there seems to be another conversation going on about DH, and (3) I type way too much. But regarding generating large primes, this is a good paper about generating n-bit random primes: "Close to Uniform Prime Number Generation With Fewer Random Bits" by Fouque and Tibouchi available at eprint.iacr.org/2011/481. For crypto, you may want to also look at FIPS 186-4. PRIMEINC: generate a random number in the range, run next_prime on it. Simple and fast, but bad distribution. Trivial: Aka Monte Carlo method as in post 3. Perfectly uniform, but uses excessive randomness and is very slow for large sizes. A comment about the post 3 code: for sizes over 2 bits, you'd want to take n-2 random bits and then set bits n-1 and 0 -- there is no need to waste time and entropy testing even numbers. A well written test will return almost instantly, but you wasted time getting all those bits -- if you're on an isolated headless server using /dev/random you may wait hours to get the next set. Modified: Methods like Fouque and Tibouchi A1 or A2; Joye-Paillier, etc. I use a somewhat similar method for odd ranges (e.g. for ranges not a power of 2). These sacrifice some uniformity for big increases in speed and less entropy consumption. (the entropy consumption may or may not matter to you, but sometimes it is important). Provable primes, typically Shawe-Taylor or Maurer's FastPrime. Common for crypto use. You can find Shawe-Taylor in FIPS 186-4; Maurer's algorithm in his publicly available paper, Menezes's book, or various open source implementations. These work by generating a small random prime using the trivial method, then generating a larger one by iterating with additional random input until proven with either Pocklington or its improved version from BLS theorem 3. Then recurse to make successively larger primes. They only generate a subset of the primes in the range (10% for Maurer's FastPrime, substantially less for Shawe-Taylor) but that typically doesn't matter. openssl or other software. Good and bad. OpenSSL likely doesn't make some mistakes you may make. But you have to make sure your platform has a recent version, your program actually calls the right executable, you send it the right arguments, you interpret the output and exceptions properly, you're ok with its decisions on randomness sources, you're OK with it not meeting FIPS 186-4 standards for primality testing, and know it is slower for sizes > 1024 than what can be done with GMP meeting the standards. There are lots of other considerations. E.g. where are you getting your randomness? Are you using a good enough primality test for your purpose? Do you need provable primes? Strong primes? Writing your own code is fun, but may have bugs -- do lots of testing. Whether these are "quick" or not depends on the size, which method you choose, your implementations, and what you think quick means. For 1024-bit primes, my older machine using Perl code generates them in 0.06s each (F&T algorithm 1, ISAAC seeded from /dev/random, BPSW + 1 M-R probable primes). Add 0.006s for 3 additional random M-R plus a Frobenius test. Add not much more for enough extra M-R tests to make FIPS 186-4 happy. For smaller sizes sometimes running a primality proof on the n-bit prime is faster than a constructive method, but your mileage may vary. At 1024 bits, my Maurer routine takes 0.65s, while Shawe-Taylor using FIPS 186-4 + SHA256 takes 0.24s. The generation code is in Perl so it could be faster, but the heavy work ends up being in C+GMP. Offline
Here's the simplest multi threading example I found so far: import multiprocessing import subprocess def calculate(value): return value * 10 if __name__ == '__main__': pool = multiprocessing.Pool(None) tasks = range(10000) results = [] r = pool.map_async(calculate, tasks, callback=results.append) r.wait() # Wait on the results print results I have two lists and one index to access the elements in each list. The ith position on the first list is related to the ith position on the second. I didn't use a dict because the lists are ordered. What I was doing was something like: for i in xrange(len(first_list)): # do something with first_list[i] and second_list[i] So, using that example, I think can make a function sort of like this: #global variables first_list, second_list, i first_list, second_list, i = None, None, 0 #initialize the lists ... #have a function to do what the loop did and inside it increment i def function: #do stuff i += 1 But, that makes i a shared resource and I'm not sure if that'd be safe. It also seems to me my design is not lending itself well to this multithreaded approach, but I'm not sure how to fix it. Here's a working example of what I wanted (Edit an image you want to use): import multiprocessing import subprocess, shlex links = ['http://www.example.com/image.jpg']*10 # don't use this URL names = [str(i) + '.jpg' for i in range(10)] def download(i): command = 'wget -O ' + names[i] + ' ' + links[i] print command args = shlex.split(command) return subprocess.call(args, shell=False) if __name__ == '__main__': pool = multiprocessing.Pool(None) tasks = range(10) r = pool.map_async(download, tasks) r.wait() # Wait on the results
A few days back, I started using new OpenCV-Python interface, cv2. My question is regarding the comparison of cv and cv2 interface. Regarding the ease of use, new cv2 interface has improved far greater, and it is really easy and fun to work with cv2. But what about speed? I made two small code snipplets, one in cv and another in cv2, to check the performances. Both does the same function, access pixels of an image, test it, make some modifications, etc. Below is the code: cv2 interface: import time import numpy as np import cv2 gray = cv2.imread('sir.jpg',0) width = gray.shape[0] height = gray.shape[1] h = np.empty([width,height,3]) t = time.time() for i in xrange(width): for j in xrange(height): if gray[i,j]==127: h[i,j]=[255,255,255] elif gray[i,j]>127: h[i,j]=[0,0,255-gray[i,j]] else: h[i,j]=[gray[i,j],0,0] t2 = time.time()-t print "time taken = ",t2 ===================================================== And result is: time taken = 14.4029130936 ====================================================== cv interface: import cv,time gray = cv.LoadImage('sir.jpg',0) h = cv.CreateImage(cv.GetSize(gray),8,3) t=time.time() for i in xrange(gray.width): for j in xrange(gray.height): k = cv.Get2D(gray,j,i)[0] if k==127: cv.Set2D(h,j,i,(255,255,255)) elif k>127: cv.Set2D(h,j,i,(0,0,255-k)) else: cv.Set2D(h,j,i,(k,0,0)) t2 = time.time()-t print "time taken = ",t2 cv.ShowImage('img',h) cv.WaitKey(0) ====================================================== The result is: time taken = 1.16368889809 ======================================================= See, here old cv is about 12 times faster than cv2. And resulting images are same. (input image is of size 720x540) Why does this happen? Is cv2 slower compared to cv? Or am I making any mistake here? Is there a faster method in cv2 for the above code?
Each Amazon EC2 instance has associated metadata, as well as user data supplied when launching the instance. The meta and user data is instance-specific, and therefore only accessible to the instance. The data is useful on several levels, such as configuring SSH public keys, programmatically configuring the instance according to certain criteria, or even executing user supplied initialization scripts. Retrieving the data Retrieving the data is done by querying an Amazon web server with the base URI of http://169.254.169.254/API-VERSION. The available API versions can be queried by performing a GET request on http://169.254.169.254/. The latest version of the API is always available using the URI http://169.254.169.254/latest. There is quite a lot of information available through the API, some more useful than others. For example, ami-id, ami-launch-index, availability-zone, instance-id, public-ipv4, user-data, ... (see below for the full list). Some notes on user data One of the most useful pieces of data is user-data, which can be used to pass configuration information or even initialization scripts to the instance upon launch. User data must be base64 encoded, and is limited to 16k (pre-encoding). The popular API tools usually handle the encoding transparently, so you shouldn't have to worry about it. The data is also decoded before presented to the instance, so again, you shouldn't need to worry. What you do need to worry about though, or at least be aware of, is security. The user-data (and all metadata for that matter) can be accessed by any user or process on the instance. So please, please, do not specify any secret information in user-data unless you are absolutely sure what you are doing. Even then, I'd think twice. But, you say, I trust all my users and processes. OK, how about this (thanks go to Eric Hammond for this example). You run a website that allows users to upload files by specifying a URL. The user specifies http://169.254.169.254/latest/user-data, and lo-and-behold, your user-data and any secrets included have been divulged. Do you still want to include secrets in user-data? The simple way The simplest way of retrieving metadata is by use of a command line network tool, such as curl, for example: The more programmatic way Usually you need a more programmatic type interface, and there are a couple of libraries for different languages available. I didn't find one that met my needs, so I wrote one in Python called ec2metadata.py. I licensed the copyright over to Canonical so it could be included in Ubuntu's ec2-init package. ec2metadata.py has a CLI interface, as well as a Pythonic interface: $ ec2metadata.py # all options will be displayed $ ec2metadata.py --instance-id # displays the instance id import ec2metadata instanceid = ec2metadata.get('instance-id') print instanceid It can be very useful when coupled with inithooks, for example, setting of the SSH public keys on first boot. #!/usr/bin/python # # Query and display EC2 metadata related to the AMI instance # Copyright (c) 2009 Canonical Ltd. (Canonical Contributor Agreement 2.5) # # Author: Alon Swartz <alon@turnkeylinux.org> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Query and display EC2 metadata If no options are provided, all options will be displayed Options: -h --help show this help --kernel-id display the kernel id --ramdisk-id display the ramdisk id --reservation-id display the reservation id --ami-id display the ami id --ami-launch-index display the ami launch index --ami-manifest-path display the ami manifest path --ancestor-ami-id display the ami ancestor id --product-codes display the ami associated product codes --availability-zone display the ami placement zone --instance-id display the instance id --instance-type display the instance type --local-hostname display the local hostname --public-hostname display the public hostname --local-ipv4 display the local ipv4 ip address --public-ipv4 display the public ipv4 ip address --block-device-mapping display the block device id --security-groups display the security groups --public-keys display the openssh public keys --user-data display the user data (not actually metadata) """ import sys import time import getopt import urllib import socket METAOPTS = ['ami-id', 'ami-launch-index', 'ami-manifest-path', 'ancestor-ami-id', 'availability-zone', 'block-device-mapping', 'instance-id', 'instance-type', 'local-hostname', 'local-ipv4', 'kernel-id', 'product-codes', 'public-hostname', 'public-ipv4', 'public-keys', 'ramdisk-id', 'reserveration-id', 'security-groups', 'user-data'] class Error(Exception): pass class EC2Metadata: """Class for querying metadata from EC2""" def __init__(self, addr='169.254.169.254', api='2008-02-01'): self.addr = addr self.api = api if not self._test_connectivity(self.addr, 80): raise Error("could not establish connection to: %s" % self.addr) @staticmethod def _test_connectivity(addr, port): for i in range(6): s = socket.socket() try: s.connect((addr, port)) s.close() return True except socket.error, e: time.sleep(1) return False def _get(self, uri): url = 'http://%s/%s/%s/' % (self.addr, self.api, uri) value = urllib.urlopen(url).read() if "404 - Not Found" in value: return None return value def get(self, metaopt): """return value of metaopt""" if metaopt not in METAOPTS: raise Error('unknown metaopt', metaopt, METAOPTS) if metaopt == 'availability-zone': return self._get('meta-data/placement/availability-zone') if metaopt == 'public-keys': data = self._get('meta-data/public-keys') keyids = [ line.split('=')[0] for line in data.splitlines() ] public_keys = [] for keyid in keyids: uri = 'meta-data/public-keys/%d/openssh-key' % int(keyid) public_keys.append(self._get(uri).rstrip()) return public_keys if metaopt == 'user-data': return self._get('user-data') return self._get('meta-data/' + metaopt) def get(metaopt): """primitive: return value of metaopt""" m = EC2Metadata() return m.get(metaopt) def display(metaopts, prefix=False): """primitive: display metaopts (list) values with optional prefix""" m = EC2Metadata() for metaopt in metaopts: value = m.get(metaopt) if not value: value = "unavailable" if prefix: print "%s: %s" % (metaopt, value) else: print value def usage(s=None): """display usage and exit""" if s: print >> sys.stderr, "Error:", s print >> sys.stderr, "Syntax: %s [options]" % sys.argv[0] print >> sys.stderr, __doc__ sys.exit(1) def main(): """handle cli options""" try: getopt_metaopts = METAOPTS[:] getopt_metaopts.append('help') opts, args = getopt.gnu_getopt(sys.argv[1:], "h", getopt_metaopts) except getopt.GetoptError, e: usage(e) if len(opts) == 0: display(METAOPTS, prefix=True) return metaopts = [] for opt, val in opts: if opt in ('-h', '--help'): usage() metaopts.append(opt.replace('--', '')) display(metaopts) if __name__ == "__main__": main()
I'm trying to write a handler that acts on files within various subdirectories, but while my script can see these files, it cannot do anything with them because it fails to assemble their paths. The problematic part comes from this loop: for (path, dirs, files) in os.walk("data/"): for image in files: #do something to the image Now, the script works in the first level of the data directory, but fails to work on data's subdirectories. I tried using os.path.join(): for (path, dirs, files) in os.walk("data/"): print os.path.join(path, dirs) But that throws the following: Traceback (most recent call last): File "bench.py", line 26, in <module> print os.path.join(path, dirs) File "/usr/lib/python2.7/posixpath.py", line 75, in join if b.startswith('/'): AttributeError: 'list' object has no attribute 'startswith' In short, what I'd like to do is assemble a path from data to the image which includes data's subdirectories. What's the best practice for doing this?
I had a problem with install Ubuntu 13.04 next to Windows 8. I have a Dell inspiron 15 notebook with UEFI. In Boot-setup I changed to Legacy Boot on and switched UEFI boot off. Then I installed Ubuntu but the computer always starts Windows. I have followed the instructions here : UEFI but it hasn't helped. Now when I turn on my notebook in grub I have Windows 8 listed but if I choose it I get the error Invalid EFI file path. What can I do to fix this? Boot Info Script 0.61 [1 April 2012] ============================= Boot Info Summary: =============================== => No boot loader is installed in the MBR of /dev/sda. sda1: __________________________________________________________________________ File system: vfat Boot sector type: Unknown Boot sector info: No errors found in the Boot Parameter Block. Operating System: Boot files: sda2: __________________________________________________________________________ File system: vfat Boot sector type: Unknown Boot sector info: No errors found in the Boot Parameter Block. Operating System: Boot files: sda3: __________________________________________________________________________ File system: Boot sector type: - Boot sector info: Mounting failed: mount: nieznany typ systemu plików '' sda4: __________________________________________________________________________ File system: ntfs Boot sector type: Windows Vista/7: NTFS Boot sector info: No errors found in the Boot Parameter Block. Operating System: Boot files: sda5: __________________________________________________________________________ File system: ntfs Boot sector type: Windows Vista/7: NTFS Boot sector info: No errors found in the Boot Parameter Block. Operating System: Boot files: /bootmgr /Windows/System32/winload.exe sda6: __________________________________________________________________________ File system: ntfs Boot sector type: Windows Vista/7: NTFS Boot sector info: No errors found in the Boot Parameter Block. Operating System: Boot files: sda7: __________________________________________________________________________ File system: ext4 Boot sector type: Grub2 (v1.99) Boot sector info: Grub2 (v1.99) is installed in the boot sector of sda7 and looks at sector 1565267170 of the same hard drive for core.img. core.img is at this location and looks in partition 94 for . Operating System: Ubuntu 13.04 Boot files: /etc/fstab sda8: __________________________________________________________________________ File system: BIOS Boot partition Boot sector type: - Boot sector info: sda9: __________________________________________________________________________ File system: ext2 Boot sector type: - Boot sector info: Operating System: Boot files: /grub/grub.cfg sda10: _________________________________________________________________________ File system: swap Boot sector type: - Boot sector info: ============================ Drive/Partition Info: ============================= Drive: sda _____________________________________________________________________ Disk /dev/sda: 1000.2 GB, 1000204886016 bytes głowic: 255, sektorów/ścieżkę: 63, cylindrów: 121601, w sumie sektorów: 1953525168 Jednostka = sektorów, czyli 1 * 512 = 512 bajtów Rozmiar sektora (logiczny/fizyczny) w bajtach: 512 / 4096 Partition Boot Start Sector End Sector # of Sectors Id System /dev/sda1 1 1,953,525,167 1,953,525,167 ee GPT GUID Partition Table detected. Partition Start Sector End Sector # of Sectors System /dev/sda1 2,048 1,026,047 1,024,000 EFI System partition /dev/sda2 1,026,048 1,107,967 81,920 - /dev/sda3 1,107,968 1,370,111 262,144 Microsoft Reserved Partition (Windows) /dev/sda4 1,370,112 2,394,111 1,024,000 Windows Recovery Environment (Windows) /dev/sda5 2,394,112 783,624,580 781,230,469 Data partition (Windows/Linux) /dev/sda6 1,926,948,864 1,953,523,119 26,574,256 Windows Recovery Environment (Windows) /dev/sda7 783,644,672 1,564,895,231 781,250,560 Data partition (Windows/Linux) /dev/sda8 783,626,240 783,644,671 18,432 BIOS Boot partition /dev/sda9 1,564,895,232 1,565,382,655 487,424 Data partition (Windows/Linux) /dev/sda10 1,565,382,656 1,565,407,231 24,576 Swap partition (Linux) "blkid" output: ________________________________________________________________ Device UUID TYPE LABEL /dev/sda1 2081-D15D vfat ESP /dev/sda10 0610ae9a-1d01-413b-ac3d-0d9bfe8d5377 swap /dev/sda2 E0ED-C674 vfat DIAGS /dev/sda4 981CEF4C1CEF244A ntfs WINRETOOLS /dev/sda5 5804F37604F3558A ntfs OS /dev/sda6 768A92CB8A928771 ntfs PBR Image /dev/sda7 bbc0df4a-6a25-44fd-95c9-e358bfafe048 ext4 /dev/sda9 4a8e05e5-da38-4b8d-a62b-7a65bac91c79 ext2 ================================ Mount points: ================================= Device Mount_Point Type Options /dev/sda1 /boot/efi vfat (rw) /dev/sda7 / ext4 (rw,errors=remount-ro) /dev/sda9 /boot ext2 (rw) =============================== sda7/etc/fstab: ================================ -------------------------------------------------------------------------------- # /etc/fstab: static file system information. # # Use 'blkid' to print the universally unique identifier for a # device; this may be used with UUID= as a more robust way to name devices # that works even if disks are added and removed. See fstab(5). # # <file system> <mount point> <type> <options> <dump> <pass> # / was on /dev/sda7 during installation UUID=bbc0df4a-6a25-44fd-95c9-e358bfafe048 / ext4 errors=remount-ro 0 1 # /boot was on /dev/sda9 during installation #UUID=4a8e05e5-da38-4b8d-a62b-7a65bac91c79 /boot ext2 defaults 0 2 # swap was on /dev/sda10 during installation UUID=0610ae9a-1d01-413b-ac3d-0d9bfe8d5377 none swap sw 0 0 UUID=4a8e05e5-da38-4b8d-a62b-7a65bac91c79 /boot ext2 defaults 0 2 UUID=2081-D15D /boot/efi vfat defaults 0 1 -------------------------------------------------------------------------------- =================== sda7: Location of files loaded by Grub: ==================== GiB - GB File Fragment(s) = initrd.img 68 = initrd.img.old 68 = vmlinuz 24 ============================= sda9/grub/grub.cfg: ============================== -------------------------------------------------------------------------------- # # DO NOT EDIT THIS FILE # # It is automatically generated by grub-mkconfig using templates # from /etc/grub.d and settings from /etc/default/grub # ### BEGIN /etc/grub.d/00_header ### if [ -s $prefix/grubenv ]; then set have_grubenv=true load_env fi set default="0" if [ x"${feature_menuentry_id}" = xy ]; then menuentry_id_option="--id" else menuentry_id_option="" fi export menuentry_id_option if [ "${prev_saved_entry}" ]; then set saved_entry="${prev_saved_entry}" save_env saved_entry set prev_saved_entry= save_env prev_saved_entry set boot_once=true fi function savedefault { if [ -z "${boot_once}" ]; then saved_entry="${chosen}" save_env saved_entry fi } function recordfail { set recordfail=1 if [ -n "${have_grubenv}" ]; then if [ -z "${boot_once}" ]; then save_env recordfail; fi; fi } function load_video { if [ x$feature_all_video_module = xy ]; then insmod all_video else insmod efi_gop insmod efi_uga insmod ieee1275_fb insmod vbe insmod vga insmod video_bochs insmod video_cirrus fi } if [ x$feature_default_font_path = xy ] ; then font=unicode else insmod part_gpt insmod ext2 set root='hd0,gpt7' if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt7 --hint-efi=hd0,gpt7 --hint-baremetal=ahci0,gpt7 bbc0df4a-6a25-44fd-95c9-e358bfafe048 else search --no-floppy --fs-uuid --set=root bbc0df4a-6a25-44fd-95c9-e358bfafe048 fi font="/usr/share/grub/unicode.pf2" fi if loadfont $font ; then set gfxmode=auto load_video insmod gfxterm set locale_dir=$prefix/locale set lang=pl_PL insmod gettext fi terminal_output gfxterm if [ "${recordfail}" = 1 ]; then set timeout=-1 else set timeout=10 fi ### END /etc/grub.d/00_header ### ### BEGIN /etc/grub.d/05_debian_theme ### set menu_color_normal=white/black set menu_color_highlight=black/light-gray if background_color 44,0,30; then clear fi ### END /etc/grub.d/05_debian_theme ### ### BEGIN /etc/grub.d/10_linux ### function gfxmode { set gfxpayload="${1}" if [ "${1}" = "keep" ]; then set vt_handoff=vt.handoff=7 else set vt_handoff= fi } if [ "${recordfail}" != 1 ]; then if [ -e ${prefix}/gfxblacklist.txt ]; then if hwmatch ${prefix}/gfxblacklist.txt 3; then if [ ${match} = 0 ]; then set linux_gfx_mode=keep else set linux_gfx_mode=text fi else set linux_gfx_mode=text fi else set linux_gfx_mode=keep fi else set linux_gfx_mode=text fi export linux_gfx_mode menuentry 'Ubuntu' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-simple-bbc0df4a-6a25-44fd-95c9-e358bfafe048' { recordfail load_video gfxmode $linux_gfx_mode insmod gzio insmod part_gpt insmod ext2 set root='hd0,gpt9' if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt9 --hint-efi=hd0,gpt9 --hint-baremetal=ahci0,gpt9 4a8e05e5-da38-4b8d-a62b-7a65bac91c79 else search --no-floppy --fs-uuid --set=root 4a8e05e5-da38-4b8d-a62b-7a65bac91c79 fi linux /vmlinuz-3.8.0-19-generic root=UUID=bbc0df4a-6a25-44fd-95c9-e358bfafe048 ro quiet splash $vt_handoff initrd /initrd.img-3.8.0-19-generic } submenu 'Opcje zaawansowane dla systemu Ubuntu' $menuentry_id_option 'gnulinux-advanced-bbc0df4a-6a25-44fd-95c9-e358bfafe048' { menuentry 'Ubuntu, za pomocą systemu Linux 3.8.0-19-generic' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.8.0-19-generic-advanced-bbc0df4a-6a25-44fd-95c9-e358bfafe048' { recordfail load_video gfxmode $linux_gfx_mode insmod gzio insmod part_gpt insmod ext2 set root='hd0,gpt9' if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt9 --hint-efi=hd0,gpt9 --hint-baremetal=ahci0,gpt9 4a8e05e5-da38-4b8d-a62b-7a65bac91c79 else search --no-floppy --fs-uuid --set=root 4a8e05e5-da38-4b8d-a62b-7a65bac91c79 fi echo 'Wczytywanie systemu Linux 3.8.0-19-generic...' linux /vmlinuz-3.8.0-19-generic root=UUID=bbc0df4a-6a25-44fd-95c9-e358bfafe048 ro quiet splash $vt_handoff echo 'Wczytywanie początkowego dysku RAM...' initrd /initrd.img-3.8.0-19-generic } menuentry 'Ubuntu, za pomocą systemu Linux 3.8.0-19-generic (tryb ratunkowy)' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-3.8.0-19-generic-recovery-bbc0df4a-6a25-44fd-95c9-e358bfafe048' { recordfail load_video insmod gzio insmod part_gpt insmod ext2 set root='hd0,gpt9' if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt9 --hint-efi=hd0,gpt9 --hint-baremetal=ahci0,gpt9 4a8e05e5-da38-4b8d-a62b-7a65bac91c79 else search --no-floppy --fs-uuid --set=root 4a8e05e5-da38-4b8d-a62b-7a65bac91c79 fi echo 'Wczytywanie systemu Linux 3.8.0-19-generic...' linux /vmlinuz-3.8.0-19-generic root=UUID=bbc0df4a-6a25-44fd-95c9-e358bfafe048 ro recovery nomodeset echo 'Wczytywanie początkowego dysku RAM...' initrd /initrd.img-3.8.0-19-generic } } ### END /etc/grub.d/10_linux ### ### BEGIN /etc/grub.d/20_linux_xen ### ### END /etc/grub.d/20_linux_xen ### ### BEGIN /etc/grub.d/30_os-prober ### ### END /etc/grub.d/30_os-prober ### ### BEGIN /etc/grub.d/30_uefi-firmware ### menuentry 'System setup' $menuentry_id_option 'uefi-firmware' { fwsetup } ### END /etc/grub.d/30_uefi-firmware ### ### BEGIN /etc/grub.d/40_custom ### # This file provides an easy way to add custom menu entries. Simply type the # menu entries you want to add after this comment. Be careful not to change # the 'exec tail' line above. ### END /etc/grub.d/40_custom ### ### BEGIN /etc/grub.d/41_custom ### if [ -f ${config_directory}/custom.cfg ]; then source ${config_directory}/custom.cfg elif [ -z "${config_directory}" -a -f $prefix/custom.cfg ]; then source $prefix/custom.cfg; fi ### END /etc/grub.d/41_custom ### -------------------------------------------------------------------------------- =================== sda9: Location of files loaded by Grub: ==================== GiB - GB File Fragment(s) = grub/grub.cfg 1 = initrd.img-3.8.0-19-generic 68 = vmlinuz-3.8.0-19-generic 24 ======================== Unknown MBRs/Boot Sectors/etc: ======================== Unknown GPT Partiton Type d3ad6b79bf6b9f4db631466eb71a4965 Unknown BootLoader on sda1 00000000 eb 58 90 4d 53 44 4f 53 35 2e 30 00 02 08 3e 18 |.X.MSDOS5.0...>.| 00000010 02 00 00 00 00 f8 00 00 3f 00 ff 00 00 08 00 00 |........?.......| 00000020 00 a0 0f 00 e1 03 00 00 00 00 00 00 02 00 00 00 |................| 00000030 01 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| 00000040 80 00 29 5d d1 81 20 4e 4f 20 4e 41 4d 45 20 20 |..)].. NO NAME | 00000050 20 20 46 41 54 33 32 20 20 20 33 c9 8e d1 bc f4 | FAT32 3.....| 00000060 7b 8e c1 8e d9 bd 00 7c 88 56 40 88 4e 02 8a 56 |{......|.V@.N..V| 00000070 40 b4 41 bb aa 55 cd 13 72 10 81 fb 55 aa 75 0a |@.A..U..r...U.u.| 00000080 f6 c1 01 74 05 fe 46 02 eb 2d 8a 56 40 b4 08 cd |...t..F..-.V@...| 00000090 13 73 05 b9 ff ff 8a f1 66 0f b6 c6 40 66 0f b6 |.s......f...@f..| 000000a0 d1 80 e2 3f f7 e2 86 cd c0 ed 06 41 66 0f b7 c9 |...?.......Af...| 000000b0 66 f7 e1 66 89 46 f8 83 7e 16 00 75 39 83 7e 2a |f..f.F..~..u9.~*| 000000c0 00 77 33 66 8b 46 1c 66 83 c0 0c bb 00 80 b9 01 |.w3f.F.f........| 000000d0 00 e8 2c 00 e9 a8 03 a1 f8 7d 80 c4 7c 8b f0 ac |..,......}..|...| 000000e0 84 c0 74 17 3c ff 74 09 b4 0e bb 07 00 cd 10 eb |..t.<.t.........| 000000f0 ee a1 fa 7d eb e4 a1 7d 80 eb df 98 cd 16 cd 19 |...}...}........| 00000100 66 60 80 7e 02 00 0f 84 20 00 66 6a 00 66 50 06 |f`.~.... .fj.fP.| 00000110 53 66 68 10 00 01 00 b4 42 8a 56 40 8b f4 cd 13 |Sfh.....B.V@....| 00000120 66 58 66 58 66 58 66 58 eb 33 66 3b 46 f8 72 03 |fXfXfXfX.3f;F.r.| 00000130 f9 eb 2a 66 33 d2 66 0f b7 4e 18 66 f7 f1 fe c2 |..*f3.f..N.f....| 00000140 8a ca 66 8b d0 66 c1 ea 10 f7 76 1a 86 d6 8a 56 |..f..f....v....V| 00000150 40 8a e8 c0 e4 06 0a cc b8 01 02 cd 13 66 61 0f |@............fa.| 00000160 82 74 ff 81 c3 00 02 66 40 49 75 94 c3 42 4f 4f |.t.....f@Iu..BOO| 00000170 54 4d 47 52 20 20 20 20 00 00 00 00 00 00 00 00 |TMGR ........| 00000180 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| * 000001a0 00 00 00 00 00 00 00 00 00 00 00 00 0d 0a 44 69 |..............Di| 000001b0 73 6b 20 65 72 72 6f 72 ff 0d 0a 50 72 65 73 73 |sk error...Press| 000001c0 20 61 6e 79 20 6b 65 79 20 74 6f 20 72 65 73 74 | any key to rest| 000001d0 61 72 74 0d 0a 00 00 00 00 00 00 00 00 00 00 00 |art.............| 000001e0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| 000001f0 00 00 00 00 00 00 00 00 ac 01 b9 01 00 00 55 aa |..............U.| 00000200 Unknown BootLoader on sda2 00000000 eb 58 90 4d 53 44 4f 53 35 2e 30 00 02 01 7e 1b |.X.MSDOS5.0...~.| 00000010 02 00 00 00 00 f8 00 00 3f 00 ff 00 00 a8 0f 00 |........?.......| 00000020 00 40 01 00 41 02 00 00 00 00 00 00 02 00 00 00 |.@..A...........| 00000030 01 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| 00000040 80 00 29 74 c6 ed e0 4e 4f 20 4e 41 4d 45 20 20 |..)t...NO NAME | 00000050 20 20 46 41 54 33 32 20 20 20 33 c9 8e d1 bc f4 | FAT32 3.....| 00000060 7b 8e c1 8e d9 bd 00 7c 88 56 40 88 4e 02 8a 56 |{......|.V@.N..V| 00000070 40 b4 41 bb aa 55 cd 13 72 10 81 fb 55 aa 75 0a |@.A..U..r...U.u.| 00000080 f6 c1 01 74 05 fe 46 02 eb 2d 8a 56 40 b4 08 cd |...t..F..-.V@...| 00000090 13 73 05 b9 ff ff 8a f1 66 0f b6 c6 40 66 0f b6 |.s......f...@f..| 000000a0 d1 80 e2 3f f7 e2 86 cd c0 ed 06 41 66 0f b7 c9 |...?.......Af...| 000000b0 66 f7 e1 66 89 46 f8 83 7e 16 00 75 39 83 7e 2a |f..f.F..~..u9.~*| 000000c0 00 77 33 66 8b 46 1c 66 83 c0 0c bb 00 80 b9 01 |.w3f.F.f........| 000000d0 00 e8 2c 00 e9 a8 03 a1 f8 7d 80 c4 7c 8b f0 ac |..,......}..|...| 000000e0 84 c0 74 17 3c ff 74 09 b4 0e bb 07 00 cd 10 eb |..t.<.t.........| 000000f0 ee a1 fa 7d eb e4 a1 7d 80 eb df 98 cd 16 cd 19 |...}...}........| 00000100 66 60 80 7e 02 00 0f 84 20 00 66 6a 00 66 50 06 |f`.~.... .fj.fP.| 00000110 53 66 68 10 00 01 00 b4 42 8a 56 40 8b f4 cd 13 |Sfh.....B.V@....| 00000120 66 58 66 58 66 58 66 58 eb 33 66 3b 46 f8 72 03 |fXfXfXfX.3f;F.r.| 00000130 f9 eb 2a 66 33 d2 66 0f b7 4e 18 66 f7 f1 fe c2 |..*f3.f..N.f....| 00000140 8a ca 66 8b d0 66 c1 ea 10 f7 76 1a 86 d6 8a 56 |..f..f....v....V| 00000150 40 8a e8 c0 e4 06 0a cc b8 01 02 cd 13 66 61 0f |@............fa.| 00000160 82 74 ff 81 c3 00 02 66 40 49 75 94 c3 42 4f 4f |.t.....f@Iu..BOO| 00000170 54 4d 47 52 20 20 20 20 00 00 00 00 00 00 00 00 |TMGR ........| 00000180 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| * 000001a0 00 00 00 00 00 00 00 00 00 00 00 00 0d 0a 44 69 |..............Di| 000001b0 73 6b 20 65 72 72 6f 72 ff 0d 0a 50 72 65 73 73 |sk error...Press| 000001c0 20 61 6e 79 20 6b 65 79 20 74 6f 20 72 65 73 74 | any key to rest| 000001d0 61 72 74 0d 0a 00 00 00 00 00 00 00 00 00 00 00 |art.............| 000001e0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| 000001f0 00 00 00 00 00 00 00 00 ac 01 b9 01 00 00 55 aa |..............U.| 00000200 ========= Devices which don't seem to have a corresponding hard drive: ========= sdb =============================== StdErr Messages: =============================== awk: cmd. line:36: Math support is not compiled in awk: cmd. line:36: Math support is not compiled in awk: cmd. line:36: Math support is not compiled in awk: cmd. line:36: Math support is not compiled in awk: cmd. line:36: Math support is not compiled in awk: cmd. line:36: Math support is not compiled in
nknico Un nouveau dépôt officiel pour Ubuntu (logiciels commerciaux) Un nouveau dépot officiel vient d'ouvrir. Il contient des logiciels commerciaux. Pour l'instant Opéra et Realplayer sont disponibles. En gros, pour l'installer, il faut: * Activer les mises a jour de dapper * Mettre a jour sa dapper :-) * Via gnome-app-install (disponible dans le menu pour tous les membres du groupe admin), activer l'option pour voir les softs commerciaux * Installer opera. Pour ceux utilisant apt-get : Ajouter cette ligne dans /etc/apt/sources.list deb http://archive.canonical.com dapper-commercial main L'annonce de l'accord entre canonical et opera : http://opera.com/pressreleases/en/2006/07/06/02/ Dernière modification par nknico (Le 09/07/2006, à 15:41) Nico Hors ligne Mornagest Re : Un nouveau dépôt officiel pour Ubuntu (logiciels commerciaux) Ce qui est pratique, pour Realplayer, qui demande, pour la version Windows, de s'enregistrer, et patati et patata, tout ça pour lire une vidéo .ra (je crois).. pas pratique, quand même ^^ MErci pour l'info, Nknico, je sens que je vais avoir des mises à jour à faire ce soir (Kubuntu, me revoiciiiii ) En ligne fredbezies Re : Un nouveau dépôt officiel pour Ubuntu (logiciels commerciaux) Real Player ? Cette usine à gaz ? Tiens, ce sera intéressant à voir michel2652 Re : Un nouveau dépôt officiel pour Ubuntu (logiciels commerciaux) Merci pour le dépot, MAJ faite A+ Mornagest Re : Un nouveau dépôt officiel pour Ubuntu (logiciels commerciaux) Une petite question, pour Kubuntu, où trouve-t-on la liste des applications commerciales installables ? J'ai activé l'option "proprietary software" mais je ne trouve ni Opera, ni Real Player à installer... ? Merci d'avance En ligne michel2652 Re : Un nouveau dépôt officiel pour Ubuntu (logiciels commerciaux) Une petite question, pour Kubuntu, où trouve-t-on la liste des applications commerciales installables ? J'ai activé l'option "proprietary software" mais je ne trouve ni Opera, ni Real Player à installer... ? Merci d'avance Met le dépot que donne knico dans ton sources.list A+ Mornagest Re : Un nouveau dépôt officiel pour Ubuntu (logiciels commerciaux) Ben c'est ce que j'ai fait mais il ne m'a pas proposé d'installer le paquet realplayer, ni quoi que ce soit qui approche.. sudo apt-get update et upgrade ne donnent rien Quel est le nom de l'appli ? je tente avec Katapult mais real et realplayer sont introuvables. Je pense qu'il n'est pas installé C'est pas dramatique mais ça fait six mois que j'ai une vidéo à regarder et j'ai pas pu télécharger ce satané programme sous Windows... En ligne nknico Re : Un nouveau dépôt officiel pour Ubuntu (logiciels commerciaux) Ben il faut lui demander de l'installer... sudo apt-get install opera sudo apt-get install realplay Nico Hors ligne Mornagest Re : Un nouveau dépôt officiel pour Ubuntu (logiciels commerciaux) Ah, avec le nom du paquet ça semble directement plus simple Je suis un boulet, je sais... j'ouvre jamais Adept pour chercher dans les noms des paquets :$ désolé et un grand merci Ca marche et il s'ouvre bien, merci encore ^^ En ligne pascalc Re : Un nouveau dépôt officiel pour Ubuntu (logiciels commerciaux) une question con, mais bon, mieux vaut avouer son ignorance que faire semblant de savoir et rester ignare... Comment est-ce que l'on peut savoir quels logiciels sont disponibles sur un dépôt ? Là on découvre qu'il y a Opera et Realplayer dedans, mais si ça se trouve il y a autre chose qui m'intéresserait. Il n'y a pas une manière d'avoir la liste des logiciels d'un dépôt ? Mozilla (mes opinions n'engagent que moi et pas mon employeur) Hors ligne Lestat the vampire Re : Un nouveau dépôt officiel pour Ubuntu (logiciels commerciaux) bah tu copies l'adresse du depot dans firefox (ou autre) ici : http://archive.canonical.com et tu navigues dans les repertoires et notamment http://archive.canonical.com/pool/main/ ou tu as la liste des paquets dispo classé par ordre alphabétique....pour le moment uniquement opera et realplayer donc Hors ligne Black_pignouf Re : Un nouveau dépôt officiel pour Ubuntu (logiciels commerciaux) C'est quoi la différence avec multiverse??? Hors ligne Lestat the vampire Re : Un nouveau dépôt officiel pour Ubuntu (logiciels commerciaux) La version de realplayer fourni dans ce nouveau depot est la derniere (10.0.7) alors que realplayer fourni dans le multiverse est la 8 (ayant des problèmes de dépendances sous Dapper, qui n'est plus supportée ni mise à jour par realnetworks donc absolument non recommandé sauf eventuellement pour les anciennces versions), enfin il existe aussi le paquet realplay dans le depot plf qui est en version 10.0.6 Pour opera, je ne me suis pas penché sur la question ! Dernière modification par Lestat the vampire (Le 11/07/2006, à 18:21) Hors ligne darkangel6669 Re : Un nouveau dépôt officiel pour Ubuntu (logiciels commerciaux) Par contre, quelqu'un sait comment avoir opera en français? Hors ligne nknico Re : Un nouveau dépôt officiel pour Ubuntu (logiciels commerciaux) Il faut télécharger un fichier supplémentaire. http://www.opera.com/download/languagefiles/ Les instructions se trouvent sur la page. Nico Hors ligne Lestat the vampire Re : Un nouveau dépôt officiel pour Ubuntu (logiciels commerciaux) Je me suis permis d'ajouter cette information importante (et qui devrait en interesser plus d'un !) au wiki à cette adresse : http://doc.ubuntu-fr.org//applications/apt/depots#depot_commercial_officiel Hors ligne nknico Re : Un nouveau dépôt officiel pour Ubuntu (logiciels commerciaux) Oui très bonne idée... Nico Hors ligne darkangel6669 Re : Un nouveau dépôt officiel pour Ubuntu (logiciels commerciaux) OK merci nknico Hors ligne skateinmars Re : Un nouveau dépôt officiel pour Ubuntu (logiciels commerciaux) C'est quoi la différence avec multiverse??? Les softs sont packagés en collaboration avec les entreprises. Mais en pratique ils ont les memes fonctions, d'ailleurs des softs de multiverses vont disparaitre et entrer dans ce depot Hors ligne batteuryo Re : Un nouveau dépôt officiel pour Ubuntu (logiciels commerciaux) Bonjour, quelqu'un pourrait - il m'aider car bisarement je n'arrive pas installer opera... J'ai bien rajouter le dépôt dans mon source.list. un petit update de tout ça mais que se soit par ligne de commande ou bien par synaptic, opera n'est pas trouvée ... De plus, en passant par "Application - Ajouter/enlever", je voi bien Opera (après avoir cocher "voir les applications commerciales") mais quand je veux l'instaler on me demander d' "Activer le depôt caconical" ... et quand je dit "Ok" la liste des dépendance se recharge et on me redemande à nouveau d'activer le dépôt ...( ca tourne en rond) Pour info je suis en Ubuntu 64 bits (noyau K8) mais je n' ai pas lu que les dépôts canonical n'étés disponible que pour platforme i386 ... Voila si quelqu'un peut m'éclairer merci. Je me demande dans quel etat j'ère ... ^^ Hors ligne coubi64 Re : Un nouveau dépôt officiel pour Ubuntu (logiciels commerciaux) Donnes ton sources.list .... Hors ligne batteuryo Re : Un nouveau dépôt officiel pour Ubuntu (logiciels commerciaux) voici mon source.list : deb http://archive.ubuntu.com/ubuntu/ dapper main restricted universe multiverse deb http://security.ubuntu.com/ubuntu/ dapper-security main restricted universe multiverse deb http://archive.ubuntu.com/ubuntu/ dapper-updates main restricted universe multiverse deb-src http://archive.ubuntu.com/ubuntu/ dapper main restricted universe multiverse deb-src http://archive.ubuntu.com/ubuntu/ dapper-updates main restricted universe multiverse deb-src http://security.ubuntu.com/ubuntu/ dapper-security main restricted universe multiverse ###Canonical### deb http://archive.canonical.com dapper-commercial main ###Asher256### # deb http://asher256-repository.tuxfamily.org dapper main dupdate french # deb http://asher256-repository.tuxfamily.org ubuntu main dupdate french ###Pour BMPx### ###Pour XGL### # deb http://www.beerorkid.com/compiz/ dapper main # deb http://xgl.compiz.info dapper main ###Pour listen### deb http://theli.free.fr/packages/dapper/ ./ ## Dépôt Pouit (pour i386 et amd64) ## Plus d'infos sur http://mrpouit.free.fr/blog/Depot-ubuntu deb http://mrpouit.free.fr/ubuntu/ dapper-misc main restricted universe multiverse non-free openalchemist # deb-src http://mrpouit.free.fr/ubuntu/ dapper-misc main restricted universe multiverse non-free openalchemist Je me demande dans quel etat j'ère ... ^^ Hors ligne batteuryo Re : Un nouveau dépôt officiel pour Ubuntu (logiciels commerciaux) Aparement je ne suis pas le seul à avoir ce problème : Tiens c'est vrai ! Je n'avais jamais remarqué... par contre c'est légèrement buggué sous 64 bits, il veut ajouter le dépôt, je l'autorise, il rafraîchit la liste, il ne trouve pas Opéra, il veut ajouter le dépôt, etc. Je me demande dans quel etat j'ère ... ^^ Hors ligne Lestat the vampire Re : Un nouveau dépôt officiel pour Ubuntu (logiciels commerciaux) Je ne suis pas sur que les paquets existants pour le moment sur ce depot commercial soit prevu pour le 64bits, je m'explique : 1-Si on parcours le contenu du depot (ex ce repertoire http://archive.canonical.com/pool/main/r/realplay/) on se rend compte qu'il n'existe qu'un seul paquet .deb, et dans le nom du paquet, on a un joli *i386.deb et pas de amd64 en vue 2-Ce depot contient bien l'arborescence necessaire pour contenir des paquets destinés à l'architecture amd64 (http://archive.canonical.com/dists/dapper-commercial/main/binary-amd64/) MAIS le contenu du fichier Packages.gz est vide alors que ce meme fichier pour le 32bits contient nos deux paquets du dépots... Bref, je ne sais pas si j'ai raison mais a priori, je dirais que c'est normal que ton synaptic ne trouve pas opera sous amd64 et ce n'est pas un probleme de sources.list !! Après peut etre qu'on peut bidouiller pour les installer quand meme sur 64bits....mais la, je ne suis pas au courant ! Hors ligne batteuryo Re : Un nouveau dépôt officiel pour Ubuntu (logiciels commerciaux) Oui "Lestat the vampire", j'avais bien compris que ce n'était pas un problème de source.list, je me doute bien que cela doit provenir de l'architechture 64bits. Reste a savoir maintenan si les paquet pour amd 64 sera bientôt dispo sur leur serveur ! Je me demande dans quel etat j'ère ... ^^ Hors ligne
I'm just going to elaborate on Ignacio Vazquez-Abrams's answer. cmp is deprecated. Don't use it. Use the key attribute instead. lambda makes a function. It's an expression and so can go places that a normal def statement can't but it's body is limited to a single expression. my_func = lambda x: x + 1 This defines a function that takes a single argument, x and returns x + 1. lambda x, y=1: x + y defines a function that takes an x argument, an optional y argument with a default value of 1 and returns x + y. As you can see, it's really just like a def statement except that it's an expression and limited to a single expression for the body. The purpose of the key attribute is that sorted will call it for each element of the sequence to be sorted and use the value that it returns for comparison. list_ = ['a', 'b', 'c'] sorted(list_, key=lambda x: 1) Just read the rest for a hypothetical example. I didn't look at problem closely enough before writing this. It will still be educational though so I'll leave it up.We can't really say much more because You can't sort dicts. Do you have a list of dictss? We could sort that. You haven't shown a username key. I'll assume that it's something like users = [{'name': 'Tom Cruise', 'username': user234234234, 'reputation': 1}, {'name': 'Aaron Sterling', 'username': 'aaronasterling', 'reputation': 11725}] If you wanted to confirm that I'm more awesome than Tom Cruise, you could do: sorted(users, key=lambda x: x['reputation']) This just passes a function that returns the 'reputation' value for each dictionary in the list. But lambdas can be slower. Most of the time operator.itemgetter is what you want. operator.itemgetter takes a series of keys and returns a function that takes an object and returns a tuple of the value of its argument. so f = operator.itemgetter('name', 'username') will return essentially the same function aslambda d: (d['name'], d['username']) The difference is that it should, in principle run much faster and you don't have to look at ugly lambda expressions. So to sort a list of dicts by name and then username, just do sorted(list_of_dicts, operator.itemgetter('name', 'username')) which is exactly what Ignacio Vazquez-Abrams suggested.
I am a beginner with google app engines. My goal is to port an existing webpage to GAE. The difficulty I am having centers around the location of the .js files. To get it to run on my local machine, I placed .js files in a static directory with references in the html like <link href="/static/tblDz_Qs_clinical.js".... Everything works fine on my local machine, but when I deploy, I get a message that 'we cannot locate the datafile http://dermdudes.appspot.com/static/tblDz_Qs_clinical.js' Here is the main.py: import os import webapp2 import jinja2 template_dir = os.path.join(os.path.dirname(__file__), 'templates') jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape=False) class Handler(webapp2.RequestHandler): def write(self, *a, **kw): self.response.out.write(*a, **kw) def render_str(self, template, **params): t = jinja_env.get_template(template) return t.render(params) def render(self, template, **kw): self.write(self.render_str(template, **kw)) class MainHandler(Handler): def get(self): self.render('DD_querydriven2.html') app = webapp2.WSGIApplication([('/', MainHandler)], debug=True) here is the app.yaml: application: dermdudes version: 1 runtime: python27 api_version: 1 threadsafe: yes handlers: - url: /static static_dir: static - url: .* script: main.app libraries: - name: webapp2 version: "2.5.1" - name: jinja2 version: latest here is the reference in the html that is triggering the message: <link href="/static/tblDz_Qs_clinical.js" type="application/json" rel="exhibit/data" /> If I can only get GAE to find the .js files then everything will be perfect. Thanks for your help.
i want to take inputs like this 10 12 13 14 15 16 .. how to take this input , as two diffrent integers so that i can multiply them in python after every 10 and 12 there is newline I'm not sure I understood your problem very well, it seems you want to parse two int separated from a space. In python you do: s = raw_input('Insert 2 integers separated by a space: ') a,b = [int(i) for i in s.split(' ')] print a*b Explanation: s = raw_input('Insert 2 integers separated by a space: ') raw_input takes everything you type (until you press enter) and returns it as a string, so: >>> raw_input('Insert 2 integers separated by a space: ') Insert 2 integers separated by a space: 10 12 '10 12' In s you have now '10 12', the two int are separated by a space, we split the string at the space with >>> s.split(' ') ['10', '12'] now you have a list of strings, you want to convert them in int, so: >>> [int(i) for i in s.split(' ')] [10, 12] then you assign each member of the list to a variable (a and b) and then you do the product a*b f = open('inputfile.txt') for line in f.readlines(): # the next line is equivalent to: # s1, s2 = line.split(' ') # a = int(s1) # b = int(s2) a, b = map(int, line.split(' ')) print a*b You could use regular expressions ( import re test = "10 11\n12 13" # Get this input from the files or the console matches = re.findall(r"(\d+)\s*(\d+)", test) products = [ int(a) * int(b) for a, b in matches ] # Process data print(products)
Air density alone has a fairly substantial impact on speed, if all else is equal (and if my calculations are correct!) Based on the equation and from this page on cycling aerodynamics, and the air-density values from Wolfram Alpha, I came up with: At 300 watts, at 0*C, will travel at 39.34 km/h At 300 watts, at 10*C, will travel at 40.06 km/h At 300 watts, at 20*C, will travel at 40.77 km/h At 300 watts, at 30*C, will travel at 41.46 km/h At 300 watts, at 40*C, will travel at 42.14 km/h That's based on the "in the drops" drag-coefficient/frontal-area values, at a consistent level above sea (I think at sea-level, not certain) Put another way: To travel at 13.8m/s in 0*C requires 478.45 watts To travel at 13.8m/s in 10*C requires 461.43 watts To travel at 13.8m/s in 20*C requires 445.52 watts To travel at 13.8m/s in 30*C requires 430.72 watts To travel at 13.8m/s in 40*C requires 417.03 watts (13.8m/s is about 50km/h, arbitrary number) To "show my working", here's the Python script I used to calculate the above: #!/usr/bin/env python2 """Impact on air-density on cycling speeds Written in Python 2.7 """ def Cd(desc): """Coefficient of drag Coefficient of drag is a dimensionless number that relates an objects drag force to its area and speed """ values = { "tops": 1.15, # Source: "Bicycling Science" (Wilson, 2004) "hoods": 1.0, # Source: "Bicycling Science" (Wilson, 2004) "drops": 0.88, # Source: "The effect of crosswinds upon time trials" (Kyle,1991) "aerobars": 0.70, # Source: "The effect of crosswinds upon time trials" (Kyle,1991) } return values[desc] def A(desc): """Frontal area is typically measured in metres squared. A typical cyclist presents a frontal area of 0.3 to 0.6 metres squared depending on position. Frontal areas of an average cyclist riding in different positions are as follows http://www.cyclingpowermodels.com/CyclingAerodynamics.aspx """ values = {'tops': 0.632, 'hoods': 0.40, 'drops': 0.32} return values[desc] def airdensity(temp): """Air density in kg/m3 Values are at sea-level (I think..?) Values from changing temperature on: http://www.wolframalpha.com/input/?i=%28air+density+at+40%C2%B0C%29 Could calculate this: http://en.wikipedia.org/wiki/Density_of_air """ values = { 0: 1.293, 10: 1.247, 20: 1.204, 30: 1.164, 40: 1.127, } return values[temp] """ F = CdA p [v^2/2] where: F = Aerodynamic drag force in Newtons. p = Air density in kg/m3 (typically 1.225kg in the "standard atmosphere" at sea level) v = Velocity (metres/second). Let's say 10.28 which is 23mph """ def required_wattage(): """What wattage will the mathematicallytheoretical cyclist need to output to travel at a specific speed? """ position = "drops" for temp in (0, 10, 20, 30, 40): v = 13.8 # m/s F = Cd(position) * A(position) * airdensity(temp) * ((v**2)/2) watts = v*F print "To travel at %sm/s in %s*C requires %.02f watts" % (v, temp, watts) def speed_from_wattage(): """Given a specific force output, how fast will a mathematicallytheoretical cyclist travel? """ from math import sqrt position = "drops" for temp in (0, 10, 20, 30, 40): # Calculate some reasonable number for F... I think..? Made # sense when I wrote it, but now slightly confusing v = 13.8 # m/s watts = 300 F = watts/v # because watts=v*F # "F = CdA p [v^2/2]" solved for "v" with sympy: """ from sympy import symbols, solve, Eq F, Cd, A, airdensity, v = symbols("F Cd A airdensity v") solve(Eq(F, Cd * A * airdensity * (v**2/2)), v) """ v = sqrt(2) * sqrt(F / (Cd(position) * A(position) * airdensity(temp))) v_in_km_h = ((v * 60*60)/1000) print "At %s watts, at %d*C, will travel at %.02f km/h" % ( watts, temp, v_in_km_h) if __name__ == '__main__': speed_from_wattage() required_wattage()
I am trying to convert some python script to display a table (based on a dbf) of features located within a specific data driven page. So far, I have the script successfully able to refresh the map to the specific table, but it does not update the table. I have it set-up as three text boxes that should be updated with three specific fields when the user runs the script from ArcToolbox. Any suggestions on why my table is not updating? import arcpy, sys, os #Reference current MXD mxd = arcpy.mapping.MapDocument("current") #Get input parameter Name = arcpy.GetParameterAsText(0) #Reference data frames mapatlasDF = arcpy.mapping.ListDataFrames(mxd, "Layers")[0] locatorDF = arcpy.mapping.ListDataFrames(mxd, "Locator Map")[0] #Reference appropriate layers atlasLyr = arcpy.mapping.ListLayers(mxd, "PinalCreekMapAtlas_HalfMile", mapatlasDF)[0] locatorLyr = arcpy.mapping.ListLayers(mxd, "Locator Map", locatorDF)[0] atlasoutlineLyr = arcpy.mapping.ListLayers(mxd, "Map Atlas Outline", locatorDF)[0] #Reference layout elements by calling ListLayoutElements for elm in arcpy.mapping.ListLayoutElements(mxd): if elm.name =="Table1Column1": tab1Col1Txt = elm if elm.name =="Table1Column2": tab1Col2Txt = elm if elm.name =="Table1Column3": tab1Col3Txt = elm #Reference the Data Driven Page object ddp = mxd.dataDrivenPages #Set the current page to be the one selected in the script tool arcpy.AddMessage(Name) pageID = mxd.dataDrivenPages.getPageIDFromName(str(Name)) mxd.dataDrivenPages.currentPageID = pageID #Set the appropriate definition queries atlasLyr.definitionQuery = "Name = '" + Name + "'" locatorLyr.definitionQuery = "Name = '" + Name + "'" atlasoutlineLyr.definitionQuery = "Name <> '" + Name + "'" #Update Sheet Index data frame arcpy.SelectLayerByAttribute_management(locatorLyr, "NEW_SELECTION", "\"Name\" = '" + Name + "'") locatorDF.panToExtent(locatorLyr.getSelectedExtent()) #Reference Affected Parcels table and select appropriate records parcelTable = arcpy.mapping.ListTableViews(mxd, "AffectedParcels")[0] #Build query and create search cursor to loop through rows parcelFieldValue = "Page " + Name queryExp = "\"MapPage\" = '" + parcelFieldValue + "'" #e.g., "MapPage" = 'Page 01' parcelRows = arcpy.SearchCursor(parcelTable.dataSource, queryExp) #Clear all table text values tab1Col1Txt.text = " "; tab1Col2Txt.text = " "; tab1Col3Txt.text = " " #iteate through each row, update appropiate text count = 0 for row in parcelRows: if count < 30: #Table1 - static position tab1Col1Txt.text = tab1Col1Txt.text + row.getValue("OwnerName") +"\n" tab1Col2Txt.text = tab1Col2Txt.text + row.getValue("APN") + "\n" tab1Col3Txt.text = tab1Col3Txt.text + row.getValue("LengthTrail") + "\n" if count ==30: arcpy.AddMessage("Table Overflow") #The code could be reworked to show the last 90 records count = count + 1 arcpy.RefreshActiveView() arcpy.AddMessage("PROCESS COMPLETED")
After configuring and installing IPython to run under python3, as explained by this wiki, and having completed all the steps, I still get: gmask@Gbuntu:~$ ipython3 qtconsole No command 'ipython3' found, did you mean: Command 'ipythonx' from package 'ipython' (universe) Command 'ipython' from package 'ipython' (universe) Command 'python3' from package 'python3-minimal' (main) ipython3: command not found No idea what I am doing wrong...
Soipacon [Tuto] Wallpapoz enfin ça marche !!!! Enfin j'ai trouvé un How To concernant wallpapoz. C'est trés bien fait et même sans être bilingue c'est facile. En tout cas chez moi ça marche impec sur Breezy noyau 686. http://ubuntuforums.org/showthread.php? … =wallpapoz Hors ligne Bob Morane Re : [Tuto] Wallpapoz enfin ça marche !!!! Bonjour à tous, je vois qu'une solution a déjà été postée. Marche t'elle pour tout le monde? J'avais contacté par mail Akbar, le développeur de ce petit programme, je pense avoir une solution qui marche. Qui sait, peut-être même la solution qui marchera chez tout le monde. Elle est en tout cas différente de celle signalée ci dessus. Voici comment procéder : 1. télécharger les sources de Wallpapoz là http://wallpapoz.sourceforge.net/ 2. extraire le tout 3. créer un dossier "bin" malencontreusement oublié dans l'archive. Cela permettra à la commande make de fonctionner 4. ouvrir un terminal et cd /votre/dossier (ou clic droit sur le dossier ouvrir un terminal si vous avez installé le paquet nautilus-open-terminal bien pratique) 5. make 6. sudo sh install.sh /usr/local (si vous voulez installer dans /usr/local) Vous avez maintenant dans menu-application-accessoire un objet Wallpapoz. Il lance le script de configuration. Celui-ci va créer un fichier caché avec vos réglages. Le truc important est le démon qui va changer vos bureaux. Et c'est là que chez certains çà marche, et parfois pas. Ne cliquez pas sur "start daemon" dans l'écran GUI, vous ne saurez pas si ca marche. Allez dans votre terminal et tapez daemon_wallpapoz. Si après vous n'avez plus la possibilité d'entrer de commande, c'est que le démon fonctionne. Si par contre vous recevez un message "segmentation fault / erreur de segmentation", il ne fonctionne pas. Etrangement il semble que chez certains il fonctionne, et parfois pas. Akbar n'a pas réussi à corriger cette erreur du démon dans le code source, et il semble qu'elle soit unique à Ubutnu. Mais il a réussi à éviter le problème en recodant le démon en python et non en c++ Vous avez donc besoin du démon en python. Pour le moment il n'est pas sur le site. Akbar portera l'ensemble démon et GUI sur Python plus tard. Pour le moment voici le code du démon en python ## daemon_wallpapoz.py # # This file will check desktop continously and change wallpaper # with preferences from configuration file from xml.dom import minidom import xml import os import sys import array import time import threading import random ## number -- global variable # # this is index of wallpaper list of workspaces # for example: number[0] is index of wallpaper list in first workspace number = array.array('i') ## delay -- global variable, how many time will wallpaper list thread # # has to wait before it manipulate its index delay = 1.0 ## random -- global variable, is wallpaper list thread randomize its index randomvar = 0 exit_code = 0 ## XMLProcessing -- class for processing wallpapoz xml file class XMLProcessing: ## The constructor def __init__(self, file): try: self.xmldoc = minidom.parse(file) except IOError: print "There is no configuration file. Create it first by running wallpapoz!" sys.exit() except xml.parsers.expat.ExpatError: print "The configuration file is corrupted. Remove it then create it again with wallpapoz!" sys.exit() self.wallpapoz_node = self.xmldoc.childNodes[1] self.workspace_node_list = self.wallpapoz_node.getElementsByTagName('workspace') self.workspace_num = self.workspace_node_list.length ## class method -- get delay time that wallpaper list thread manipulate its index def delay(self): return self.wallpapoz_node.attributes["interval"].value ## class method -- whether the wallpaper list thread randomize its index def is_random(self): return self.wallpapoz_node.attributes["random"].value ## class method -- method for fill list with wallpaper path file def fill_list(self): worklist = [] for i in range(self.workspace_num): worklist.append( [] ) index = -1 for file in self.workspace_node_list: file_node_list = file.getElementsByTagName('file') index = index + 1 for node in file_node_list: if node.nodeName == "file": worklist[index].append(node.firstChild.data) return worklist ## class method -- to know how many workspace we use def get_workspace_num(self): return self.workspace_num ## System -- class for knowing current desktop and change wallpaper # # with calling external program class System: ## class method to know what workspace we are in now def current_desktop(self): desktop = os.popen('xprop -root _NET_CURRENT_DESKTOP').read() return int(desktop[33] + desktop[34]) ## class method def change_wallpaper(self, wallpaper): os.system('gconftool-2 -t string -s /desktop/gnome/background/picture_filename ' + "\"" + wallpaper + "\"") ## AsyncIndex -- class for making thread that manipulating index wallpaper list class AsyncIndex(threading.Thread): ## constructor def __init__(self, index): threading.Thread.__init__(self) self.index = index ## the function that thread will execute def run(self): if randomvar == 1: number[self.index] = 0 size = len(worklist[self.index]) while True: number[self.index] = int(random.random() * size) time.sleep(delay) else: while True: number[self.index] = 0 for i in worklist[self.index]: time.sleep(delay) number[self.index] = number[self.index] + 1 ## the main program if __name__ == "__main__": # generate seed for random number random.seed() # the configuration file file = os.environ['HOME'] + "/.wallpapoz/wallpapoz.xml" # call the xmlprocessing class to read it wallpapozxml = XMLProcessing(file) # fill the workspace list worklist = wallpapozxml.fill_list() # how many workspace we use total_workspace = wallpapozxml.get_workspace_num() # create the index for wallpaper list thread number.fromlist( range( total_workspace ) ) # create the system class ( to change wallpaper and read current desktop ) # by calling external program system = System() # previous workspace previous_desktop = -1 # previous wallpaper list index previous_index = -1 # get the delay time and random preferences delay = 60 * float(wallpapozxml.delay()) randomvar = int(wallpapozxml.is_random()) # create the thread wallpaper_list = [] for i in range(total_workspace): wallpaper_list.append(AsyncIndex(i)) wallpaper_list[i].start() # the daemon that works forever while True: try: # don't get rush time.sleep(1) # what workspace we are in now? cur_desk = system.current_desktop() # requirement for changing wallpaper # 1. we change workspace # 2. index of wallpaper list change if previous_desktop != cur_desk or previous_index != number[cur_desk]: # if we move to workspace that we don't use, just ignore if cur_desk >= total_workspace: continue # command to change wallpaper system.change_wallpaper(worklist[cur_desk][number[cur_desk]]) # our previous workspace and index of wallpaper list previous_desktop = cur_desk previous_index = number[cur_desk] # ok, we stop this daemon except KeyboardInterrupt: # now it's time for the main thread to exit os._exit(0) 7. copier le code python dans un fichier texte. Le nommer daemon_wallpapoz.py 8. sudo cp daemon_wallpapoz.py /usr/local/daemon_wallpapoz.py lancez le avec la commande python daemon_wallpapoz.py tout devrait marcher. Vérifiez que vous avez des fonds d'écran différent sur vos différents bureaux. Le démon aura besoin de quelques secondes pour changer correctement vos bureaux. Si tout marche, ajoutez une entrée à votre session pour le lancer à l'ouverture de session. Hors ligne ced_668 Re : [Tuto] Wallpapoz enfin ça marche !!!! Lorsque je lance le daemon il m'affiche: File "daemon_wallpapoz.py", line 36 try: ^ IndentationError: expected an indented block A quoi c'est due? J'ai vraiment tout esayer pour installer le logiciel et je commence a etre un peu desesperer!! Hors ligne ced_668 Re : [Tuto] Wallpapoz enfin ça marche !!!! En fait le text proposer ci dessu est plein d'erreur de copie, faite la meme manip mais recuperer plutot le texte a partir du lien fournit dans le premier post et la ca marche nickel!!!!!!!!!!!!!!!!!! Hors ligne zempa Re : [Tuto] Wallpapoz enfin ça marche !!!! A noter qu'avec la version 0.3, wallpapoz est desormais ecrit en python. Il y a un script d'installation (en python). Toutefois, il est possible de lancer wallpapoz depuis le repertoire desarchivé sans installation. voir le fichier install. Defursac Re : [Tuto] Wallpapoz enfin ça marche !!!! avec la version 0.3 faut-il toujours faire les étapes 7 et 8 proposées par Bob Morane ? Parce que je l'ai pas fait... et je n'ai pas de wallpapers différents sur mes bureaux. Apparement ça serait alors un démon qui permet de changer de wallpaper toutes les x minutes. Est-ce normal ? Au fait je suis sur Dapper, avec Aiglx Compiz...mais même en switchant sur Metacity ça ne fonctionne pas ! Merci de votre aide [EDIT] En fait, les préférences du démon ne m'indiquent qu'un seul bureau... est-ce normal ? Dernière modification par Defursac (Le 26/05/2006, à 09:21) Si vous ne partez pas en vacances, mettez un déodorant bleu dans la chasse d'eau ; vous aurez l'impression de faire pipi dans le Pacifique. Jean-Louis Fournier Hors ligne chizum Re : [Tuto] Wallpapoz enfin ça marche !!!! Bonjour, J'ai installé wallpapoz, la dernière version, mais le seul problème, c'est que je n'ai que 2 bureaux dans le wallpapoz. Donc, je ne peux mettre que 2 papiers peint sur mes 2 bureaux, et les 2 autres ont le papier peint défini pour le 2ème bureau. En clair, aur le 1er bureau j'ai l'image 1.png, sur le 2ème, 3ème et 4ème, le'image 2.png!! Comment changer cela? D'avance merci La vague allègre du présent, sur l'avenir des chimères c'est brisée, pour se répandre librement sur le sable fin du passé... Hors ligne chizum Re : [Tuto] Wallpapoz enfin ça marche !!!! Bonjour, le problème est résolu.:) 1- télécharger wallpapoz sous //wallpapoz.sourceforge.net/temp/wallpapoz-0.3.tar.bz2 2- décompresser le pac dans votre répertoire /home/votre_nom 3- ouvrez un terminal et tapez: $cd nom_dossier_wallpapoz 4- toujours dans le terminal : $ sudo python install.py install Wallpapoz est installé Reste une petite manip à effectuer pour lancer le démon au démarrage de la distribution. Dans le Tableau de bord, rendez-vous dans Système/Préférences/Sessions. Dans Programmes au démarrage, cliquer sur Ajoutez puis Parcourir. Rechercher et sélectionner daemon_wallpapoz.py dans /usr/bin/, puis cliquer sur Ouvrir. Valider et Fermer. Redémarrer votre distribution. "Après avoir également installé Wallpapoz sous Edgy, le redémarrage ne semble pas indispensable." Moi je l’ai fait car cela ne fonctionnait pas ! Vous trouverez le raccourçi de Wallpapoz dans Applications/Accessoires. Lancer Wallpapoz.Important - Avant d’effectuer des modifications dans Wallpapoz: tuer le démon: cliquer sur Kill Daemon. Important - Lorsque vous avez terminé vos modifications : sauvegarder les modifications : cliquer sur Save redémarrer le démon : cliquer sur Restart Daemon. Personnellement, j'ai gardé tous les fichiers, afin de pouvoir désinstaller wallpapoz. Pour ça, tapez dans un terminal: $ sudo python install.py uninstall Wallpapoz est désinstallé. La vague allègre du présent, sur l'avenir des chimères c'est brisée, pour se répandre librement sur le sable fin du passé... Hors ligne PatAnnie Re : [Tuto] Wallpapoz enfin ça marche !!!! J'ai installé la dernière version : Wallpapoz 0.4 dans sa version française OK Par contre je n'arrive pas à trouver daemon_wallpapoz.py dans /usr/bin ???? Le terminal répond à : daemon_wallpapoz sans infos sup.... Dois-je mettre un nouveau script au démarrage avec daemon_wallpapoz options ???? Merci de votre aide et A+ Hors ligne S2S Re : [Tuto] Wallpapoz enfin ça marche !!!! lu pour moi v0.4, et le il ce lance (la commande daemon_wallpapoz reste en attente) mais rien ne ce passe si je n'ouvre pas le gui et click sur restart daemon. j'utilise les depot officiel. le daemon ce trouve la: /usr/bin/daemon_wallpapoz. j'ai essayer de le mettre la: /usr/local/daemon_wallpapoz.py sans resultat le path en dur, rien!y a t'il des argument a passer pour le redemarer par un script ? ---edit--- complete avec le post de 'chizum' en passant par 'parcourir' ca marche, erreur de syntaxe peut etre. la commande fonctionnant pour moi est: /usr/bin/daemon_wallpapoz.py (j'avais copier 'daemon_wallpapoz' en 'daemon_wallpapoz.py' et pas essayer avec 'daemon_wallpapoz' original sans le '.py' ) Dernière modification par S2S (Le 10/11/2007, à 14:48) portable: Toshiba Qosmio x500 12Q fixe: P5N72-T Premium//Core2Quad-Q9550//7950GT//2048DDR2 OS: 10.04 - 10.10 - 11.04, 7 ... qui croit tout savoir, n'en saura jamais plus ... Hors ligne Omnisilver Re : [Tuto] Wallpapoz enfin ça marche !!!! Hello, J'ai refondu la page sur le wiki, il y a maintenant toutes les infos dont on pourrait avoir besoin : http://doc.ubuntu-fr.org/wallpapoz Hors ligne MuLoChE Re : [Tuto] Wallpapoz enfin ça marche !!!! Pour ceux qui n'ont pas le fichier daemon_wallpapoz. regarder plutôt vers: /usr/bin/X11. A noter qu'il y autant de dossier X11 que de bureau. choisissez le fichier daemon_wallpapoz le plus recent, c'est à dire le 1er dans le 1er dossier. arff j'ai du mal désoler il est tard Hors ligne michug Re : [Tuto] Wallpapoz enfin ça marche !!!! Bonjour à tous J'ai écrit quelques scripts bash et python qui utilisent «wallpapoz» et me permettent de changer mon fond d'écran toutes les minutes, en affichant une photo sélectionnée aléatoirement dans mon arborescence photo(plus de 33000) et en écrivant une légende concernant la photo, date de création, photographe, sujet de l'album, commentaires, etc.... Ces informations étant écrites dans la photo. Je suis sur ubuntu 11.10 avec unity et ça fonctionne très bien depuis plusieurs années sur les différentes version de ubuntu. Je l'ai également testé sur 12.04. Récemment j'ai posté un message sur le forum dans la rubrique «Astuces et scripts» message «Affichage aléatoire des photos en fond d'écran» où je décris mon application. Si vous êtes intéressé, répondez-moi sur mon message «Affichage aléatoire des photos en fond d'écran» Hors ligne