text
stringlengths 256
65.5k
|
|---|
Someone is trying to sell Lisp to me, as a super powerful language that can do everything ever, and then some.
Is there a practical code example of Lisp's power?
(Preferably alongside equivalent logic coded in a regular language.)
I like macros.
Here's code to stuff away attributes for people from LDAP. I just happened to have that code lying around and fiigured it'd be useful for others.
Some people are confused over a supposed runtime penalty of macros, so I've added an attempt at clarifying things at the end.
In The Beginning, There Was Duplication
(defun ldap-users ()
(let ((people (make-hash-table :test 'equal)))
(ldap:dosearch (ent (ldap:search *ldap* "(&(telephonenumber=*) (cn=*))"))
(let ((mail (car (ldap:attr-value ent 'mail)))
(uid (car (ldap:attr-value ent 'uid)))
(name (car (ldap:attr-value ent 'cn)))
(phonenumber (car (ldap:attr-value ent 'telephonenumber))))
(setf (gethash uid people)
(list mail name phonenumber))))
people))
You can think of a "let binding" as a local variable, that disappears outside the LET form. Notice the form of the bindings -- they are very similar, differing only in the attribute of the LDAP entity and the name ("local variable") to bind the value to. Useful, but a bit verbose and contains duplication.
On the Quest for Beauty
Now, wouldn't it be nice if we didn't have to have all that duplication? A common idiom is is WITH-... macros, that binds values based on an expression that you can grab the values from. Let's introduce our own macro that works like that, WITH-LDAP-ATTRS, and replace it in our original code.
(defun ldap-users ()
(let ((people (make-hash-table :test 'equal))) ; equal so strings compare equal!
(ldap:dosearch (ent (ldap:search *ldap* "(&(telephonenumber=*) (cn=*))"))
(with-ldap-attrs (mail uid name phonenumber) ent
(setf (gethash uid people)
(list mail name phonenumber))))
people))
Did you see how a bunch of lines suddenly disappeared, and was replaced with just one single line? How to do this? Using macros, of course -- code that writes code! Macros in Lisp is a totally different animal than the ones you can find in C/C++ through the use of the pre-processor: here, you can run
Getting Rid of Ugly
So, let's see how this was done. To replace one attribute, we define a function.
(defun ldap-attr (entity attr)
`(,attr (car (ldap:attr-value ,entity ',attr))))
The backquote syntax looks a bit hairy, but what it does is easy. When you call LDAP-ATTRS, it'll spit out a list that contains the
Anyway. Moving along, to the rest of the macro.
(defmacro with-ldap-attrs (attrs ent &rest body)
`(let ,(loop for attr in attrs
collecting `,(ldap-attr ent attr))
,@body))
The
Result
You can easily verify that this will give you the right thing. Macros are often written this way: you start off with code you want to make simpler (the output), what you want to write instead (the input), and then you start molding the macro until your input gives the correct output. The function
(macroexpand-1 '(with-ldap-attrs (mail phonenumber) ent
(format t "~a with ~a" mail phonenumber)))
evaluates to
(let ((mail (car (trivial-ldap:attr-value ent 'mail)))
(phonenumber (car (trivial-ldap:attr-value ent 'phonenumber))))
(format t "~a with ~a" mail phonenumber))
If you compare the LET-bindings of the expanded macro with the code in the beginning, you'll find that it is in the same form!
Compile-time vs Runtime: Macros vs Functions
A macro is code that is run at
Basically, it lets you write your code in verbs that can be found in the problem domain, instead of low-level primitives from the language! As a silly example, consider the following (if
(defmacro my-when (test &rest body)
`(if ,test
(progn ,@body)))
;; one form
(if (numberp 1)
(print "yay, a number"))
;; two forms
(if (numberp 1)
(progn
(assert-world-is-sane t)
(print "phew!"))))
With our new friend, my-when, we could both a) use the more appropriate verb if we don't have a false branch, and b) add an implicit sequencing operator, i.e.
(my-when (numberp 1)
(assert-world-is-sane t)
(print "phew!"))
The compiled code will never contain
Lisp> (macroexpand-1 '(my-when (numberp 1)
(print "yay!")))
(if (numberp 1)
(progn (print "yay!")))
Note that
Hope that clarifies things. Macros is a powerful tool, and one of the features in Lisp I like.
The best example I can think of that is widely available is the book by Paul Graham, On Lisp. The full PDF can be downloaded from the link I just gave. You could also try Practical Common Lisp (also fully available on the web).
I have a lot of unpractical examples. I once wrote a program in about 40 lines of lisp which could parse itself, treat its source as a lisp list, do a tree traversal of the list and build an expression that evaluated to WALDO if the waldo identifier existed in the source or evaluate to nil if waldo was not present. The returned expression was constructed by adding calls to car/cdr to the original source that was parsed. I have no idea how to do this in other languages in 40 lines of code. Perhaps perl can do it in even fewer lines.
You may find this article helpful: http://www.defmacro.org/ramblings/lisp.html
That said, it's very, very hard to give short, practical examples of Lisp's power because it really shines only in non-trivial code. When your project grows to a certain size, you will appreciate Lisp's abstraction facilities and be glad that you've been using them. Reasonably short code samples, on the other hand, will never give you a satisfying demonstration of what makes Lisp great because other languages' predefined abbreviations will look more attractive in small examples than Lisp's flexibility in managing domain-specific abstractions.
Actually, a good practical example is the Lisp LOOP Macro.
The LOOP macro is simply that -- a Lisp macro. Yet it basically defines a mini looping DSL (Domain Specific Language).
When you browse through that little tutorial, you can see (even as a novice) that it's difficult to know what part of the code is part of the Loop macro, and which is "normal" Lisp.
And that's one of the key components of Lisps expressiveness, that the new code really can't be distinguished from the system.
While in, say, Java, you may not (at a glance) be able to know what part of a program comes from the standard Java library versus your own code, or even a 3rd party library, you DO know what part of the code is the Java language rather than simply method calls on classes. Granted, it's ALL the "Java language", but as programmer, you are limited to only expressing your application as a combination of classes and methods (and now, annotations). Whereas in Lisp, literally everything is up for grabs.
Consider the Common SQL interface to connect Common Lisp to SQL. Here, http://clsql.b9.com/manual/loop-tuples.html, they show how the CL Loop macro is extended to make the SQL binding a "first class citizen".
You can also observe constructs such as "[select [first-name] [last-name] :from [employee] :order-by [last-name]]". This is part of the CL-SQL package and implemented as a "reader macro".
See, in Lisp, not only can you make macros to create new constructs, like data structures, control structures, etc. But you can even change the syntax of the language through a reader macro. Here, they're using a reader macro (in the case, the '[' symbol) to drop in to a SQL mode to make SQL work like embedded SQL, rather than as just raw strings like in many other languages.
As application developers, our task is to convert our processes and constructs in to a form that the processor can understand. That means we, inevitably, have to "talk down" to the computer language, since it "doesn't understand" us.
Common Lisp is one of the few environments where we can not only build our application from the top down, but where we can lift the language and environment up to meet us half way. We can code at both ends.
Mind, as elegant as this can be, it's no panacea. Obviously there are other factors that influence language and environment choice. But it's certainly worth learning and playing with. I think learning Lisp is a great way to advance your programming, even in other languages.
I like CLOS and multimethods.
Most, if not all, object-oriented programming languages have the basic notions of classes and methods. The following snippet in Python defines the classes PeelingTool and Vegetable (something similar to the Visitor pattern):
class PeelingTool:
"""I'm used to peel things. Mostly fruit, but anything peelable goes."""
def peel(self, veggie):
veggie.get_peeled(self)
class Veggie:
"""I'm a defenseless Veggie. I obey the get_peeled protocol
used by the PeelingTool"""
def get_peeled(self, tool):
pass
class FingerTool(PeelingTool):
...
class KnifeTool(PeelingTool):
...
class Banana(Veggie):
def get_peeled(self, tool):
if type(tool) == FingerTool:
self.hold_and_peel(tool)
elif type(tool) == KnifeTool:
self.cut_in_half(tool)
You put the
The Common Lisp Object System version:
(defclass peeling-tool () ())
(defclass knife-tool (peeling-tool) ())
(defclass finger-tool (peeling-tool) ())
(defclass veggie () ())
(defclass banana (veggie) ())
(defgeneric peel (veggie tool)
(:documentation "I peel veggies, or actually anything that wants to be peeled"))
;; It might be possible to peel any object using any tool,
;; but I have no idea how. Left as an exercise for the reader
(defmethod peel (veggie tool)
...)
;; Bananas are easy to peel with our fingers!
(defmethod peel ((veggie banana) (tool finger-tool))
(with-hands (left-hand right-hand) *me*
(hold-object left-hand banana)
(peel-with-fingers right-hand tool banana)))
;; Slightly different using a knife
(defmethod peel ((veggie banana) (tool knife-tool))
(with-hands (left-hand right-hand) *me*
(hold-object left-hand banana)
(cut-in-half tool banana)))
Anything can be written in any language that's Turing complete; the difference between the languages is how much many hoops you have to jump through to get the equivalent result.
A powerful languages like Common Lisp, with functionality such as macros and the CLOS, allows you to achieve results fast and easy without jumping through so many hoops that you either settle for a subpar solution, or find yourself becoming a kangaroo.
There are plenty of killer features in Lisp, but macros is one I love particularily, because there's not really a barrier anymore between what the language defines and what I define. For example, Common Lisp doesn't have a
(defmacro while (condition &body body)
`(if ,condition
(progn
,@body
(do nil ((not ,condition))
,@body))))
Et voilà ! You just extended the Common Lisp language with a new fundamental construct. You can now do:
(let ((foo 5))
(while (not (zerop (decf foo)))
(format t "still not zero: ~a~%" foo)))
Which would print:
Doing that in any non-Lisp language is left as an exercise for the reader...
I found this article quite interesting:
The author of the article, Brandon Corfman, writes about a study that compares solutions in Java, C++ and Lisp to a programming problem, and then writes his own solution in C++. The benchmark solution is Peter Norvig's 45 lines of Lisp (written in 2 hours).
Corfman finds that it is difficult to reduce his solution to less than 142 lines of C++/STL. His analysis of why, is an interesting read.
The thing that I like most about Lisp (and Smalltalk) systems, is that they feel alive. You can easily probe & modify Lisp systems while they are running.
If this sounds mysterious, start Emacs & type some lisp code. Type
Another thing is that the code = list equivalence make the frontier between code and data very thin. And thanks to macros, it is very easy to extend the language and make quick DSLs.
For instance, it is possible to code a basic Html builder with which the code is very close to the produced Html output:
(html
(head
(title "The Title"))
(body
(h1 "The Headline" :class "headline")
(p "Some text here" :id "content")))
=>
<html>
<head>
<title>The title</title>
</head>
<body>
<h1 class="headline">The Headline</h1>
<p id="contents">Some text here</p>
</body>
</html>
In the Lisp code, auto indentation make the code look like the output, except there is no closing tags.
(babel:octets-to-string
(with-output-to-sequence (*html-stream*)
<div (constantAttribute 42
someJavaScript `js-inline(print (+ 40 2))
runtimeAttribute ,(concatenate 'string "&foo" "&bar"))
<someRandomElement
<someOther>>>))
=>
"<div constantAttribute=\"42\"
someJavaScript=\"javascript: print((40 + 2))\"
runtimeAttribute=\"&foo&bar\">
<someRandomElement>
<someOther/>
</someRandomElement>
</div>"
this is basically the same thing as lisp's backtick reader (which is for list quasi quoting), but it also works for various other things like xml (installed on a special <> syntax), javascript (installed on `js-inline), etc.
to make it clear, this is implemented in a
this is not for the faint of heart, but this is what the lib compiles the above into:
(progn
(write-sequence
#(60 100 105 118 32 99 111 110 115 116 97 110 116 65 116 116 114 105 98
117 116 101 61 34 52 50 34 32 115 111 109 101 74 97 118 97 83 99 114
105 112 116 61 34 106 97 118 97 115 99 114 105 112 116 58 32 112 114
105 110 116 40 40 52 48 32 43 32 50 41 41 34 32 114 117 110 116 105
109 101 65 116 116 114 105 98 117 116 101 61 34)
*html-stream*)
(write-quasi-quoted-binary
(let ((*transformation*
#<quasi-quoted-string-to-quasi-quoted-binary {1006321441}>))
(transform-quasi-quoted-string-to-quasi-quoted-binary
(let ((*transformation*
#<quasi-quoted-xml-to-quasi-quoted-string {1006326E51}>))
(locally
(declare (sb-ext:muffle-conditions sb-ext:compiler-note))
(let ((it (concatenate 'string "runtime calculated: " "&foo" "&bar")))
(if it
(transform-quasi-quoted-xml-to-quasi-quoted-string/attribute-value it)
nil))))))
*html-stream*)
(write-sequence
#(34 62 10 32 32 60 115 111 109 101 82 97 110 100 111 109 69 108 101 109
101 110 116 62 10 32 32 32 32 60 115 111 109 101 79 116 104 101 114 47
62 10 32 32 60 47 115 111 109 101 82 97 110 100 111 109 69 108 101 109
101 110 116 62 10 60 47 100 105 118 62 10)
*html-stream*)
+void+)
for reference, the two big byte vectors in the above look like this when converted to string:
"<div constantAttribute=\"42\"
someJavaScript=\"javascript: print((40 + 2))\"
runtimeAttribute=\""
and the second one:
and it combines well with other lisp structures like macros and functions. now, compare this to JSP's...
Better late than never?
I was an AI student at MIT in the 70s. Like every other student, I thought language was paramount. Nevertheless, LISP was the primary language. These are some things I still think it is pretty good for:
Mainly what LISP does for me is mental exercise. Then I can carry that over into more practical languages.
P.S. Speaking of Lambda Calculus, what also started in the 70s, in that same AI millieu, was that OO started invading everybody's brain, and somehow, interest in what it
I like this macro example from http://common-lisp.net/cgi-bin/viewcvs.cgi/cl-selenium/?root=cl-selenium It's a Common Lisp binding to Selenium (a web browser test framework), but instead of mapping every method, it reads Selenium's own API definition XML document at compile time and generates the mapping code using macros. You can see the generated API here: common-lisp.net/project/cl-selenium/api/selenium-package/index.html
This is essentially driving macros with external data, which happens to be an XML document in this case, but could have been as complex is reading from a database or network. This is the power of having the entire Lisp environment available to you at compile time.
Have you taken a look at this explanation of why macros are powerful and flexible? No examples in other languages though, sorry, but it might sell you on macros.
@Mark,
While there is some truth to what you are saying, I believe it is not always as straight forward.
Programmers and people in general don't always take the time to evaluate all the possibilities and decide to switch languages. Often It's the managers that decide, or the schools that teach the first languages ... and programmers never have the need to invest enough amount of time to get to a certain level were they can decide this language saves me more time than that language.
Plus you have to admit that languages that have the backing of huge commercial entities such as Microsoft or Sun will always have an advantage in the market compared to languages without such backing.
In order to answer the original question, Paul Graham tries to give an example here even though I admit it is not necessarily as
One thing I like is the fact that I can upgrade code "run-time" without losing application state. It's a thing only useful in some cases, but when it is useful, having it already there (or, for only a minimal cost during development) is MUCH cheaper than having to implement it from scratch. Especially since this comes at "no to almost no" cost.
One specific thing that impressed me is the ability to write your own object-oriented programming extension, if you happen not to like the included CLOS.
There's also a package called Screamer that allows nondeterministic programming (which I haven't evaluated).
Any language that allows you to change it to support different programming paradigms has to be flexible.
You might find this post by Eric Normand helpful. He describes how as a codebase grows, Lisp helps by letting you build the language up to your application. While this often takes extra effort early on, it gives you a big advantage later.
The simple fact that it's a multi-paradigm language makes it very very flexible.
John Ousterhout made this interesting observation regarding Lisp in 1994:
|
I've spent the last few hours looking at Django Docs and similar questions on here but I'm still unclear on how to tackle the problem...
In essense I want to access the list of email addresses relevent to a certain group, so I can send an email to these customers who are part of this group (named group_one, group_two etc)
class Group(models.Model):
name = models.CharField(primary_key=True)
mailing_list = models.ManyToManyField("Customer", null=True)
class Customer(models.Model):
name = models.CharField()
email = models.EmailField(primary_key=True)
I've tried
group_mail_list = Group.objects.filter(name=group_two)
And this returns an Query Object for group_two but when I try to do a __contains filter I get a error:
TypeError: Related Field has invalid lookup: contains
Anyone help me out? Not sure if it's because it's a many-to-many relationship perhaps?
Thanks in advance :)
|
I need to label N objects with unique tuples (A, B, C), where A < B < C and the maximal number of identical As is M. The same for Bs and Cs each. Among all solutions one with the lowest highest value of C is searched for. (This last sentence means: if one of two solutions has a highest C of 4 and the other of 5, then the first one is to right answer.)
Example:
M = 1
N = 4
# As Bs Cs
objects = [(1, 2, 3),
(2, 3, 4),
(3, 4, 5),
(4, 5, 6)]
M = 2
N = 4
objects = [(1, 2, 3),
(1, 2, 4),
(2, 3, 4),
(2, 3, 5)]
# or e.g
objects = [(1, 2, 3),
(2, 3, 4),
(2, 4, 5),
(3, 4, 5)]
M = 3
N = 8
objects = [(1, 2, 3),
(2, 3, 4),
(2, 3, 5),
(2, 4, 5),
(3, 4, 5),
(3, 4, 6),
(3, 5, 6),
(4, 5, 6)]
The program I came up with is a complicated if else monster:
import sys
# useage: labelme.py <N> <M>
class ObjectListTree(object):
"""Create many possible paths.
Store the parent in each node.
The last nodes are appended to the class wide endnodes.
"""
endnodes = []
def __init__(self, parent, label, counter, n, M, N):
self.parent = parent
self.M = M
self.N = N
self.label = label
self.counter = counter
self.n = n
if n < N:
self.inc_a()
self.inc_b()
self.inc_c()
else:
ObjectListTree.endnodes.append(self)
def inc_a(self):
if self.label[0]+1 < self.label[1]:
if self.counter[1] < self.M:
if self.counter[2] < self.M:
self.plus_1()
else:
self.plus_1_3()
else:
if self.counter[2] < self.M:
self.plus_1_2()
else:
self.plus_all()
elif self.label[1]+1 < self.label[2]:
if self.counter[2] < self.M:
self.plus_1_2()
else:
self.plus_all()
else:
self.plus_all()
def inc_b(self):
if self.counter[0] == self.M:
return
if self.label[1]+1 < self.label[2] and self.counter[2] < self.M:
self.plus_2()
else:
self.plus_2_3()
def inc_c(self):
if self.counter[0] == self.M or self.counter[1] == self.M:
return
else:
self.plus_3()
def plus_all(self):
ObjectListTree(self, (self.label[0]+1, self.label[1]+1, self.label[2]+1),
counter = [1, 1, 1,],
n = self.n+1, N=self.N, M=self.M)
def plus_1_2(self):
ObjectListTree(self, (self.label[0]+1, self.label[1]+1, self.label[2]),
counter = [1, 1, self.counter[2]+1,],
n = self.n+1, N=self.N, M=self.M)
def plus_1_3(self):
ObjectListTree(self, (self.label[0]+1, self.label[1], self.label[2]+1),
counter = [1, self.counter[1]+1, 1,],
n = self.n+1, N=self.N, M=self.M)
def plus_1(self):
ObjectListTree(self, (self.label[0]+1, self.label[1], self.label[2]),
counter = [1, self.counter[1]+1, self.counter[2]+1,],
n = self.n+1, N=self.N, M=self.M)
def plus_2(self):
ObjectListTree(self, (self.label[0], self.label[1]+1, self.label[2]),
counter = [self.counter[0]+1, 1, self.counter[2]+1,],
n = self.n+1, N=self.N, M=self.M)
def plus_2_3(self):
ObjectListTree(self, (self.label[0], self.label[1]+1, self.label[2]+1),
counter = [self.counter[0]+1, 1, 1,],
n = self.n+1, N=self.N, M=self.M)
def plus_3(self):
ObjectListTree(self, (self.label[0], self.label[1], self.label[2]+1),
counter = [self.counter[0]+1, self.counter[1]+1, 1,],
n = self.n+1, N=self.N, M=self.M)
tree = ObjectListTree(parent=None, label=(1, 2, 3), counter = [1,1,1,], n=1, N=int(sys.argv[1]), M=int(sys.argv[2]))
best_path = tree.endnodes[0]
for n in tree.endnodes:
if n.label[2] < best_path.label[2]:
best_path = n
objects = []
while best_path:
objects.append(best_path.label)
best_path = best_path.parent
objects.reverse()
print objects
But I have the feeling that this should actually be something simple like a combination of two or three functions from the itertools module wrapped in a set or something. Can anyone see a simple solution?
|
Brothers In Arms: Road To Hill 30
This walkthrough will explain the advantages and disadvantages of all of the weapons in the game. It is just a condensed explanation, so no history or historical facts will be quoted.
THE***************************************************** RIFLE'S*************************************************
The American M1 Garand:
The M1 Garand is, basically, your mainstay gun. In every mission you are always equipped with one. It has an ammo pool of 88 and a clip of 7 shots. It is a good long range weapon, and an exellent mid range weapon, heck, you can also use it as an close range weapon if the enemy assaults!!!! In the lower difficulties (easy to medium) it kills in one shot in the torso and head. In the higher difficulties (high and Authentic) it kills in two shots depending on where you place it. This weapon can be used to suppress fire or go on the assault, although it is more wise to assault or suppress with a machinegun, but it is still THE all around weapon in the game. It's advantages over the K98 are faster reloads, faster shooting, ability to see your surroundings even with the sight up (an essential ability in the Authentic mode), an easy to use sight, and better all around capability. It will be your weapon of choice as American
squad leader Matt Baker.
The K98:
This is the German counterpart to the M1 Garand. It is the most accurate weapon you encounter on a steady basis, meaning sniper rifles are only used if equipped to you, or if your very lucky and find one sitting around. It has an ammo pool of 65 and a clip size of 5, meaning you must make every shot count in order to survive:(. Don't worry, because since most enemy units carry these anyway, you can easily find them as a backup if you need it and you will have a nearly inexhaustible supply of ammo (YAY!!!). It is an great long rane weapon, an exellent mid range weapon, but a poor short range or assault weapon. The damage output is much the same as the M1 Garand, but since the sight zooms in a little bit more, it is easier to get critical shots in. It's bolt action system is not great for speed, but simply increases accuracy to a greater extent than the M1, but hiders your ability to assess your surroundings with the sight up. It is a poor assault and suppresive weapon, but exels in picking up critical shots, so if your M1 Garand runs dry, just pick up one of these. It's advantages are a little more range, a little more power, and a easy to use sight. It lacks the most of the abilities that the M1 has, but can be deadly if used properly.
The***************************************************** Assault************************************************* Rifles**************************************************
The BAR (Browning Automatic Rifle):
This is one of the most effective weapons in the game, having a high damage output, high clip size, and high ammo pool count. It has just about the same damage output as the M1, but has a much higher fire rate, meaning if used correctly, you can mow down yoour enemies, so to speak. It is a mediocre long range weapon (the sight does not zoom as much), Great mid range weapon, and exellent short range/assault weapon. It's high clip count and damage output make it an even greater choice than an machine gun. It has many advantages, such as being a versatile weapon, unlike the STG, the German version. It is the goto weapon for assaults, and make sure you use it to it's full extent when you do get the chance to use it.
The STG 44 (Sturmgewehr 44):
Has the same basic features as the BAR, but with a less effective sight. This makes it a poor long range weapon, good mid range weapon, and a exellent short range weapon due to the bullet sprays tight pattern. It has the same advantages, but because of its being specified as a Assault rifle, it makes it very poor in long range accuracy, but very good at assault, even better than the BAR, but lacks the ability to lend you long range accuracy in fire or shooting from cover.
The*****************************************************
Machineguns*********************************************
The Thompson Sub-machinegun:
It is the weapon that is paired up with the M1 most of the time. it has a good sight and has alright clip and ammo pool size. It has poor long range accuracy and ok mid range accuracy, but great short range accuracy. It has the advantages of blocking out your surroundings at close range, and that's what hiders it's long range accuracy. Not too much advantages over the MP40, but seems to be more succesful at making Germans duck for cover. It is one of the weapons you will constantly use.
The MP40 (Machine Pistol 40)
This weapon is the second most dangerous weapon you encounter, because of it's large clip and ammo size, that dwarves that of the Thompsons. Damage output for this is the same as that of the Tommy, around 4 shots, but that is better than wasting 4 out of 7 bullets from your M1, or 4 out of 5 from your K98. It is a great backup weapon.
THOSE ARE ALL OF THE WEAPONS THAT YOU BASICALLY USE ON A REGULAR BASIS!!!! WEAPONS NOT MENTIONED ARE THE M4 Carbine and the Pistol. THANK YOU AND HOPE THAT THIS GUIDE WILL HELP YOU TO CHOOSE YOUR WEAPONS SETUP WISELY!!!!!
|
McPeter
Re : Un 'autre' générateur de sources.list en ligne
Je viens de rectifier le soucis sur le nom du fichier bash.
Par contre je ne vois aucun soucis à l'exécution :\
pourrais tu me dire quel navigateur tu as utilisé et quel message d'erreur ça te renvoit ? (un copié/collé du message)
le chmod +x est inutile là puisque qu'on utilise directement 'bash fichier' (plus simple poru le commun des mortels )
Hors ligne
McPeter
Re : Un 'autre' générateur de sources.list en ligne
Hors ligne
McPeter
Re : Un 'autre' générateur de sources.list en ligne
noruas beep ?!
Hors ligne
SoCko
Re : Un 'autre' générateur de sources.list en ligne
Merci à toi McPeter pour ce générateur. Très utile et ergonomique, on a un sources.list en une dizaine de secondes!
Hors ligne
tripes_inn
Re : Un 'autre' générateur de sources.list en ligne
merci je reinstalle tout et je suis bien content de ne pas avoir à tout retrouver.
j'ai dù corriger le fichier pour que synaptic l'accepte.
je joins l'original
###############################################################################
## UBUNTU LUCID LYNX - 10.04 - Date : 11/09/2010
##
## SOURCES.LIST GENERATOR Version 0.3-10.04
## http://sources-list.ubuntu-fr-secours.org
###############################################################################
# deb cdrom:[Ubuntu 10.04 LTS _Lucid Lynx_ - Release i386 (20100429)]/ lucid main restricted
## DEPOTS PRINCIPAUX
deb http://archive.ubuntu.com/ubuntu lucid main
# deb-src http://archive.ubuntu.com/ubuntu lucid main
## DEPOTS RESTRICTED
deb http://archive.ubuntu.com/ubuntu lucid restricted
# deb-src http://archive.ubuntu.com/ubuntu lucid restricted
## DEPOTS UNIVERSE (logiciels libres)
deb http://archive.ubuntu.com/ubuntu lucid universe
# deb-src http://archive.ubuntu.com/ubuntu lucid universe
## DEPOTS MULTIVERSE (logiciels non-libres)
deb http://archive.ubuntu.com/ubuntu lucid multiverse
# deb-src http://archive.ubuntu.com/ubuntu lucid multiverse
## DEPOTS DE MISES A JOUR EN PRES VERSION
# deb http://archive.ubuntu.com/ubuntu lucid-proposed main restricted universe multiverse
# deb-src http://archive.ubuntu.com/ubuntu lucid-proposed
## DEPOTS NON PRIS EN CHARGE
# deb http://archive.ubuntu.com/ubuntu lucid-backports main restricted universe multiverse
# deb-src http://archive.ubuntu.com/ubuntu lucid-backports
## DEPOTS DE MISES A JOUR DE SECURITE
deb http://archive.ubuntu.com/ubuntu lucid-security main restricted universe multiverse
# deb-src http://archive.ubuntu.com/ubuntu lucid-security
## DEPOTS DE MISES A JOUR IMPORTANTES
deb http://archive.ubuntu.com/ubuntu lucid-updates main restricted universe multiverse
# deb-src http://archive.ubuntu.com/ubuntu lucid-updates
## DEPOTS COMMERCIAUX
deb http://archive.canonical.com/ubuntu lucid partner
# deb-src http://archive.canonical.com/ubuntu lucid partner
deb http://archive.canonical.com/ubuntu lucid-security partner
# deb-src http://archive.canonical.com/ubuntu lucid-security partner
deb http://
j'ai supprimer
deb http://
à la fin et c bon
Samsung N145 plus
ubuntu 11.10 64 bits
Hors ligne
alej
Re : Un 'autre' générateur de sources.list en ligne
Et en ne gardant que les lignes utiles, en synthèse, ça donne ça...
deb http://archive.ubuntu.com/ubuntu lucid main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu lucid-security main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu lucid-updates main restricted universe multiverse
deb http://archive.canonical.com/ubuntu lucid partner
deb http://archive.canonical.com/ubuntu lucid-security partner
Un peu + digeste, non ?
Hors ligne
McPeter
Re : Un 'autre' générateur de sources.list en ligne
Tu as surtout loupé ton copié/collé ...
le dépôt canonical c'est ça :
## DEPOTS COMMERCIAUX
deb http://archive.canonical.com/ubuntu lucid partner
# deb-src http://archive.canonical.com/ubuntu lucid partner
deb http://archive.canonical.com/ubuntu lucid-security partner
# deb-src http://archive.canonical.com/ubuntu lucid-security partner
deb http://archive.canonical.com/ubuntu lucid-updates partner
# deb-src http://archive.canonical.com/ubuntu lucid-updates partner
Donc soit y'a eu un bug au téléchargement du sources.list soit tu t'es loupé au copié/collé ...
mais c'est pas juste une histoire de "supprimer la fin".
merci je reinstalle tout et je suis bien content de ne pas avoir à tout retrouver.
j'ai dù corriger le fichier pour que synaptic l'accepte.
je joins l'original
...
## DEPOTS COMMERCIAUX
deb http://archive.canonical.com/ubuntu lucid partner
# deb-src http://archive.canonical.com/ubuntu lucid partner
deb http://archive.canonical.com/ubuntu lucid-security partner
# deb-src http://archive.canonical.com/ubuntu lucid-security partner
deb http://
j'ai supprimer
deb http://
à la fin et c bon
Hors ligne
McPeter
Re : Un 'autre' générateur de sources.list en ligne
Et en ne gardant que les lignes utiles, en synthèse, ça donne ça...
deb http://archive.ubuntu.com/ubuntu lucid main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu lucid-security main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu lucid-updates main restricted universe multiverse
deb http://archive.canonical.com/ubuntu lucid partner
deb http://archive.canonical.com/ubuntu lucid-security partner
Un peu + digeste, non ?
Pas compris l'intervention là :\
ça vient faire quoi dans la choucroute ?
Hors ligne
jajaX
Re : Un 'autre' générateur de sources.list en ligne
salut
la mise à jour pour avoir un source.list pour la 10.10 est prévue pour quand ?
@+ jajaX [Membre de Breizhtux : LUG de Saint Brieuc]ACER Aspire 8930G 904G50Bn & HP dv7 2230f sous Kubuntu 14.04 The Trusty Tahr (64 bits) & KDE SC 4.13.2/Amarok 2.8ACER Aspire 5612 WLMI & HP Compaq NX6310 sous kubuntu 14.04 The Trusty Tahr (32 bits) & KDE SC 4.13.2/Amarok 2.8
Hors ligne
noruas
Re : Un 'autre' générateur de sources.list en ligne
Désolé, j'étais parti faire un tour sur Arch ^^
Au sujet de mon problème, j'ai essayé toutes les possibilités de ton générateur sur 5 machines, dont une m'appartenant, j'ai toujours eu des soucis.
La génération des scripts automatiques se fait chez moi (sources.list_autoFull ou sources.list_autoFiles), mais ne renvois que des erreurs lorsque j'arrive à l'étape 5... donc échec.
Je suis donc obligé de me rabattre sur la génération d'un "sources.list" et d'un "sources.list_key", mais même là, j'ai des soucis.
En fait, j'ai le même problème que "tripes_inn", mon fichier "sources.list" n'est jamais généré complètement, il m'en manque plus de la moitié et il se termine en général par "deb http://"...
Par contre, j'ai beau le régénérer plusieurs fois, ce n'est jamais à la même ligne que ça s'arrête, mais il n'est jamais complet.
Pour solutionner ça, je copie colle le sources.list affiché dans le récapitulatif dans le fichier qu'il était censé me générer.
Ensuite, tout se passe à merveille.
Hors ligne
McPeter
Re : Un 'autre' générateur de sources.list en ligne
Oui j'ai malheureusement vu qu'il y avait un gros bug sur le script de génération
Je vais donc reprendre tout ça proprement
La version 10.10 arrive bientôt
Hors ligne
noruas
Re : Un 'autre' générateur de sources.list en ligne
Oui et avec la version 10.10 le dépot officiel EXTRAS.
PS: après test sur ma Maverick fraichement installée, il n'y a que le dépot Exaile qui n'existe pas encore pour cette version d'Ubuntu, les autres sont déjà opérationels.
Dernière modification par noruas (Le 11/10/2010, à 14:59)
Hors ligne
Isaric
Re : Un 'autre' générateur de sources.list en ligne
Je n'ai pas vu les dépôts alors, je les proposes :
ekiga (pas encore en 10.10 - 64)
ppa:sevmek/ppa%%%empathy%%%
ppa:telepathy/ppa
SFLphone doc
deb http://ppa.launchpad.net/savoirfairelinux/ppa/ubuntu YOUR_UBUNTU_VERSION_HERE mainBrasero (pas encore en 10.10 - 64)
ppa:renbag/ppaVlc
ppa:n-muench/vlcGnome Nanny (pour les version antérieures à 10.10)
ppa:nanny/ppaXbmc (doit être vide en 10.10-64)
ppa:henningpingel/xbmc
"Être bahá'í signifie simplement aimer la terre toute entière, aimer l'humanité et essayer de la servir, travailler pour la paix universelle et la famille humaine" 'Abdul'l-Bahá
"Vouloir s'ouvrir aux autres n'est pas une preuve de faiblesse, c'est une preuve d'intelligence" Matthieu Ricard.
ma config
Hors ligne
Isaric
Re : Un 'autre' générateur de sources.list en ligne
Aussi gThumb :
ppa:webupd8team/gthumb
"Être bahá'í signifie simplement aimer la terre toute entière, aimer l'humanité et essayer de la servir, travailler pour la paix universelle et la famille humaine" 'Abdul'l-Bahá
"Vouloir s'ouvrir aux autres n'est pas une preuve de faiblesse, c'est une preuve d'intelligence" Matthieu Ricard.
ma config
Hors ligne
Isaric
Re : Un 'autre' générateur de sources.list en ligne
Dernière modification par Isaric (Le 20/10/2010, à 12:14)
"Être bahá'í signifie simplement aimer la terre toute entière, aimer l'humanité et essayer de la servir, travailler pour la paix universelle et la famille humaine" 'Abdul'l-Bahá
"Vouloir s'ouvrir aux autres n'est pas une preuve de faiblesse, c'est une preuve d'intelligence" Matthieu Ricard.
ma config
Hors ligne
caracolito
Re : Un 'autre' générateur de sources.list en ligne
Excellent travail Génial ! il manque seulement la dernière version: la 10.10
Les arbres enseignent la patience: Ils ne baissent pas les bras à la première tempête venue. [C.Beaupré]
Quand je ne sais pas traduire je me fais aider par: translate.google.com
Hors ligne
McPeter
Re : Un 'autre' générateur de sources.list en ligne
ça va venir ... ainsi que la correction du bug sur la création des sources auto
Hors ligne
serviteur
Re : Un 'autre' générateur de sources.list en ligne
salut,
J'ai installé recement Ubuntu Ultimate Edition 2.7 base sur lucid 10.04 LTS ;
Voici mon ficuier source.list :
#deb cdrom:[Ubuntu 10.04 LTS _Lucid Lynx_ - Release i386 (20100429)]/ lucid main restricted
# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
deb http://us.archive.ubuntu.com/ubuntu/ lucid main restricted
deb-src http://us.archive.ubuntu.com/ubuntu/ lucid main restricted
## Major bug fix updates produced after the final release of the
## distribution.
deb http://us.archive.ubuntu.com/ubuntu/ lucid-updates main restricted
deb-src http://us.archive.ubuntu.com/ubuntu/ lucid-updates main restricted
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team. Also, please note that software in universe WILL NOT receive any
## review or updates from the Ubuntu security team.
deb http://us.archive.ubuntu.com/ubuntu/ lucid universe
deb-src http://us.archive.ubuntu.com/ubuntu/ lucid universe
deb http://us.archive.ubuntu.com/ubuntu/ lucid-updates universe
deb-src http://us.archive.ubuntu.com/ubuntu/ lucid-updates universe
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
deb http://us.archive.ubuntu.com/ubuntu/ lucid multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ lucid multiverse
deb http://us.archive.ubuntu.com/ubuntu/ lucid-updates multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ lucid-updates multiverse
## Uncomment the following two lines to add software from the 'backports'
## repository.
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
# deb http://us.archive.ubuntu.com/ubuntu/ lucid-backports main restricted universe multiverse
# deb-src http://us.archive.ubuntu.com/ubuntu/ lucid-backports main restricted universe multiverse
## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
# deb http://archive.canonical.com/ubuntu lucid partner
# deb-src http://archive.canonical.com/ubuntu lucid partner
deb http://security.ubuntu.com/ubuntu lucid-security main restricted
deb-src http://security.ubuntu.com/ubuntu lucid-security main restricted
deb http://security.ubuntu.com/ubuntu lucid-security universe
deb-src http://security.ubuntu.com/ubuntu lucid-security universe
deb http://security.ubuntu.com/ubuntu lucid-security multiverse
deb-src http://security.ubuntu.com/ubuntu lucid-security multiverse
je n'arrive pas à faire une mise à jour pour pourvoir installé des logiciels dans les dépots que ce par le terminal ou synaptic
en tapant sudo apt-get update voici les erreurs :
creation@creation-Jesus:~$ sudo apt-get update
Atteint http://archive.canonical.com lucid Release.gpg
Ign http://archive.canonical.com/ubuntu/ lucid/partner Translation-fr
Réception de : 1 http://security.ubuntu.com lucid-security Release.gpg [198B]
Ign http://security.ubuntu.com/ubuntu/ lucid-security/main Translation-fr
Atteint http://packages.medibuntu.org karmic Release.gpg
Ign http://packages.medibuntu.org/ karmic/free Translation-fr
Ign http://packages.medibuntu.org/ karmic/non-free Translation-fr
Atteint http://ppa.launchpad.net lucid Release.gpg
Ign http://ppa.launchpad.net/compiz/ubuntu/ lucid/main Translation-fr
Réception de : 2 http://us.archive.ubuntu.com lucid Release.gpg [189B]
Réception de : 3 http://us.archive.ubuntu.com/ubuntu/ lucid/main Translation-fr [452kB]
Atteint http://archive.canonical.com lucid Release
Ign http://security.ubuntu.com/ubuntu/ lucid-security/restricted Translation-fr
Ign http://security.ubuntu.com/ubuntu/ lucid-security/universe Translation-fr
Ign http://security.ubuntu.com/ubuntu/ lucid-security/multiverse Translation-fr
Réception de : 4 http://security.ubuntu.com lucid-security Release [38,5kB]
Atteint http://packages.medibuntu.org karmic Release
Atteint http://ppa.launchpad.net lucid Release
Réception de : 5 http://downloadue.info lucid Release.gpg
Ign http://downloadue.info/repo/ lucid/all Translation-fr
Atteint http://archive.canonical.com lucid/partner Packages
Atteint http://packages.medibuntu.org karmic/free Packages
Atteint http://ppa.launchpad.net lucid/main Packages
Ign http://downloadue.info lucid Release
Atteint http://packages.medibuntu.org karmic/non-free Packages
Ign http://deb.playonlinux.com lucid Release.gpg
Ign http://downloadue.info lucid/all Packages
Ign http://deb.playonlinux.com/ lucid/main Translation-fr
Réception de : 6 http://deb.playonlinux.com lucid Release [1 722B]
Ign http://downloadue.info lucid/all Packages
Réception de : 7 http://us.archive.ubuntu.com/ubuntu/ lucid/restricted Translation-fr [2 628B]
Réception de : 8 http://us.archive.ubuntu.com/ubuntu/ lucid/universe Translation-fr [702kB]
Ign http://deb.playonlinux.com lucid/main Packages
Err http://downloadue.info lucid/all Packages
Connexion à downloadue.info: 80 (174.120.62.91) impossible. - connect (110: Connexion terminée par expiration du délai d'attente)
Ign http://security.ubuntu.com lucid-security/main Packages
Réception de : 9 http://security.ubuntu.com lucid-security/restricted Packages [14B]
Réception de : 10 http://security.ubuntu.com lucid-security/main Sources [35,2kB]
Réception de : 11 http://us.archive.ubuntu.com/ubuntu/ lucid/multiverse Translation-fr [83,2kB]
Réception de : 12 http://us.archive.ubuntu.com lucid-updates Release.gpg [198B]
Ign http://us.archive.ubuntu.com/ubuntu/ lucid-updates/main Translation-fr
Ign http://us.archive.ubuntu.com/ubuntu/ lucid-updates/restricted Translation-fr
Ign http://us.archive.ubuntu.com/ubuntu/ lucid-updates/universe Translation-fr
Ign http://us.archive.ubuntu.com/ubuntu/ lucid-updates/multiverse Translation-fr
Réception de : 13 http://us.archive.ubuntu.com lucid Release [57,2kB]
Ign http://security.ubuntu.com lucid-security/restricted Sources
Réception de : 14 http://us.archive.ubuntu.com lucid-updates Release [44,7kB]
Réception de : 15 http://security.ubuntu.com lucid-security/universe Packages [47,5kB]
Réception de : 16 http://us.archive.ubuntu.com lucid/main Packages [1 386kB]
Ign http://deb.playonlinux.com lucid/main Packages
Réception de : 17 http://security.ubuntu.com lucid-security/universe Sources [12,9kB]
Atteint http://deb.playonlinux.com lucid/main Packages
Réception de : 18 http://security.ubuntu.com lucid-security/multiverse Packages [2 013B]
Ign http://security.ubuntu.com lucid-security/multiverse Sources
Ign http://security.ubuntu.com lucid-security/main Packages
Ign http://security.ubuntu.com lucid-security/restricted Sources
Ign http://security.ubuntu.com lucid-security/multiverse Sources
Réception de : 19 http://security.ubuntu.com lucid-security/main Packages [129kB]
Réception de : 20 http://security.ubuntu.com lucid-security/restricted Sources [20B]
Réception de : 21 http://security.ubuntu.com lucid-security/multiverse Sources [572B]
Ign http://us.archive.ubuntu.com lucid/restricted Packages
Réception de : 22 http://us.archive.ubuntu.com lucid/main Sources [659kB]
Réception de : 23 http://us.archive.ubuntu.com lucid/restricted Sources [3 775B]
Réception de : 24 http://us.archive.ubuntu.com lucid/universe Packages [5 448kB]
Réception de : 25 http://us.archive.ubuntu.com lucid/universe Sources [3 165kB]
Réception de : 26 http://us.archive.ubuntu.com lucid/multiverse Packages [180kB]
Réception de : 27 http://us.archive.ubuntu.com lucid/multiverse Sources [119kB]
Réception de : 28 http://us.archive.ubuntu.com lucid-updates/main Packages [343kB]
Réception de : 29 http://us.archive.ubuntu.com lucid-updates/restricted Packages [3 240B]
Réception de : 30 http://us.archive.ubuntu.com lucid-updates/main Sources [134kB]
Réception de : 31 http://us.archive.ubuntu.com lucid-updates/restricted Sources [1 443B]
Réception de : 32 http://us.archive.ubuntu.com lucid-updates/universe Packages [146kB]
Réception de : 33 http://us.archive.ubuntu.com lucid-updates/universe Sources [56,8kB]
Réception de : 34 http://us.archive.ubuntu.com lucid-updates/multiverse Packages [7 373B]
Réception de : 35 http://us.archive.ubuntu.com lucid-updates/multiverse Sources [3 669B]
Ign http://us.archive.ubuntu.com lucid/restricted Packages
Réception de : 36 http://us.archive.ubuntu.com lucid/restricted Packages [6 133B]
13,3Mo réceptionnés en 36min 59s (5 977o/s)
W: Impossible de récupérer http://downloadue.info/repo/dists/lucid/all/binary-i386/Packages.gz Connexion à downloadue.info: 80 (174.120.62.91) impossible. - connect (110: Connexion terminée par expiration du délai d'attente)
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.
creation@creation-Jesus:~$
J'aimerai avoir si c'est possible une source.list adaptée avec le serveur national d' Afrique du Sud car il est proche du pays où je reside.
Cordialement
" Le disciple (serviteur) n'est pas plus que le maître; mais tout disciple accompli sera comme son maître." Luc 6:40; Jean. 13:16
'' J'ai été crucifié avec Christ et je suis une nouvelle création" GAL2: 20, 2Cor5: 17, Rom 6:6-7
HP xw4600 Workstation: Intel Core 2 Quad Q9300, 4 GB RAM, Nvidia Geforce GTX 580
Hors ligne
jajaX
Re : Un 'autre' générateur de sources.list en ligne
salut
tu as 2 serveurs qui ne répondent pas. pas grave retente plus tard ou demain.
@+ jajaX [Membre de Breizhtux : LUG de Saint Brieuc]ACER Aspire 8930G 904G50Bn & HP dv7 2230f sous Kubuntu 14.04 The Trusty Tahr (64 bits) & KDE SC 4.13.2/Amarok 2.8ACER Aspire 5612 WLMI & HP Compaq NX6310 sous kubuntu 14.04 The Trusty Tahr (32 bits) & KDE SC 4.13.2/Amarok 2.8
Hors ligne
wendyam
Re : Un 'autre' générateur de sources.list en ligne
Bonjour les amis!!!
J'ai télécharger ubuntu sur le même site qui a une taille de 695 Mo en image et je n'arrive pas a le gravé ni de l'installer en utilisant un cd virtuel.
Alors ou je peu trouve le bon pour télécharger ?
Merci
Hors ligne
noruas
Re : Un 'autre' générateur de sources.list en ligne
@Isaric
Je ne comprend pas bien tes demandes, je suis également sous 10.10 64bits et tous les logiciels que tu cites sont disponibles chez moi, certains faisant partie intégrante de l'installation de base d'Ubuntu (Brasero, Empathy par exemple....)
Hors ligne
Isaric
Re : Un 'autre' générateur de sources.list en ligne
En général c'est les dernières versions, que l'on trouve rarement pas dans les dépôts.
Dernière modification par Isaric (Le 28/11/2010, à 18:52)
"Être bahá'í signifie simplement aimer la terre toute entière, aimer l'humanité et essayer de la servir, travailler pour la paix universelle et la famille humaine" 'Abdul'l-Bahá
"Vouloir s'ouvrir aux autres n'est pas une preuve de faiblesse, c'est une preuve d'intelligence" Matthieu Ricard.
ma config
Hors ligne
noruas
Re : Un 'autre' générateur de sources.list en ligne
Très bonne remarque, même s'il est vrai que je n'utilise les ppa que lorsqu'un soft me pose problèmes ou n'est pas stable sur ma machine.
D'ailleurs, ne serait-il pas judicieux de rajouter un onglet dans le générateur pour les dépots ppa les plus couramment demandés/utilisés ?
Ainsi nous garderions un onglet des logiciels additionnels (non installés par défaut dans la distribution) et un autre avec les dépôts ppa pour bénéficier d'une version plus récente et "en général" moins buggée d'une appli...
PS: j'aime bien ton blog "feuille de route" et astuces ^^
Dernière modification par noruas (Le 28/11/2010, à 19:11)
Hors ligne
blattes86
Re : Un 'autre' générateur de sources.list en ligne
Bonjour @ tous.
Je viens pour lancer un appel a Azema McPeter. Je vous explique, pour mon boulot ( je travaille dans une association prônant le logiciel libre ) je vais avoir besoin de créer une grosse documentation afin d'aider les personnes voulant reproduire notre association.
Utilisant le logiciel apt-mirror , je comptais créer une générateur permettant d'afficher aussi bien un sources.list qu'un mirror.list afin d'éviter aux personnes de ce prendre autant la tête que moi.
Néanmoins, n'aimant pas réinventé la roue et étant aussi un peu fainéant, j'aurais voulu savoir si un projet tel que celui-ci pouvait vous intéresser ou au pire si votre code source était disponible dans un coin perdu du net.
En espérant, une réponse favorable de votre part.
Dernière modification par blattes86 (Le 13/01/2011, à 16:21)
Hors ligne
|
Ruby has a couple of well-known libraries for unit testing, mocking and stubbing HTTP interactions. My typical toolset includes RSpec, WebMock and VCR. I had the chance to work on a Python project recently and did some investigation into similar libraries for Python.
General testing libraries
The two most popular python test libraries + runners are py.test and nose. A neat feature of py.test is that is gets by with only the builtin ‘assert’ keyword: the test runner expands assertion failures to show exactly how the assertion failed e.g.:
===================== FAILURES =====================
_____________________ test_web _____________________
def test_web():
resp = c.get('/')
> assert resp.status == '404'
E assert '200 OK' == '404'
E - 200 OK
E + 404
lib/test_snack_overflow.py:9: AssertionError
============= 1 failed in 0.24 seconds =============
One gotcha is that py.test silences stdout by default, so you’ll need to pass the -s flag to see any debugging output.
Test doubles
The mock library can be installed through pip for Python 2 and comes as part of the standard library of Python 3. As an example of mocking out an environment variable using a context manager:
with mock.patch.dict('os.environ', {'APP_NAME': 'HelloWorld'}):
assert app.name = 'HelloWorld'
There’s also a decorator form, nice because it clearly states what modules are being mocked in your tests:
@mock.patch('crazyservice')
def test_nationals_stats(_crazyservice):
_crazyservice.date = "2013-04-06 12:31 AM"
Another gotcha for newcomers to Python testing: not all methods can be replaced at runtime. A good example is stubbing DateTime.now in ruby: the equivalent monkeypatching in python raises:
TypeError: can’t set attributes of built-in/extension type ‘datetime.datetime’
as these methods cannot be replaced in CPython. You’ll need to write a wrapper function and mock that out instead in your tests.
Web testing
The werkzeug WSGI library includes simple utilities to make request testing as easy as with rack-test. Another library I’m a big fan of is HTTPretty, which is similar to Ruby’s WebMock or FakeWeb. Finally, Ruby’s VCR gem is invaluable for recording real HTTP interactions. A port exists on python called vcr.py.
|
I'm trying to create a custom function that I can place in a queryset "chain" that will apply a filter to the queryset. Like with normal Django queryset filters, it will take the queryset to the left of it and pass the resulting queryset to the right.
Before adding my custom function to the queryset chain:
models.MyModel.objects.all()
models.MyModel.objects.some_manger_function()
models.MyModel.objects.some_manger_function().count()
models.MyModel.objects.some_manger_function().filter(title='something')
After adding my custom function to the queryset chain:
models.MyModel.objects.all().my_custom_filter()
models.MyModel.objects.some_manger_function().my_custom_filter()
models.MyModel.objects.some_manger_function().my_custom_filter().count()
models.MyModel.objects.some_manger_function().my_custom_filter()\
.filter(title='something')
I'm not sure how to construct my function to do this. Does it need some sort of decorator around it?
???? def my_custom_filter(???):
???? return qs.filter(id__gte=10)
Does anyone know a good way to accomplish this?
The following might work, but I was hoping for something a little more Django-like.
def my_custom_filter(qs):
return qs.filter(id__gte=1)
my_custom_filter(models.MyModel.objects.all()).count()
Any advice is much appreciated.
Thanks, Joe
UPDATE: I'm trying to work out the details of Ignacio's solution. I've not done too much with QuerySet overriding so I'm piecing together what I'm able to find...
class MyQuerySet(QuerySet):
def filter(self, *args, **kwargs):
return super(self.__class__, self).filter(*args, **kwargs).\
filter(id__gt=5)
class MyManager(models.Manager):
def testqs(self):
return MyQuerySet(self.model)
However, I don't think this is working the way I expect. Any suggestions?
>>> models.MyModel.objects.testqs().filter()
UPDATE 2:This article proved to be useful. http://zmsmith.com/2010/04/using-custom-django-querysets/
|
too long didn't read- https://bitbucket.org/techtonik/async-console-input - public domain/MIT example for Windows implemented in pure Python (ctypes)
What is asynchronous input?
Given:The program need to terminate immediately when a subprocess exits or user hits 'q'. It should not eat 100% CPU time.
Blocking synchronous input:
import sys, subprocess
from msvcrt import getch, kbhit
p = subprocess.Popen([r"notepad"], shell=True)
while True:
char = getch()
if char == 'q':
sys.exit('terminated by user')
if p.poll() != None:
sys.exit('terminated by child exit')
This one doesn't work (doesn't exits immediately when child process terminates), because getch() blocks execution key is pressed, and even if child process exits, it won't be detected until some key is pressed.
Non-blocking synchronous input (polling):
import sys, subprocess
from msvcrt import getch, kbhit
p = subprocess.Popen([r"notepad"], shell=True)
while True:
while kbhit():
if getch() == 'q':
sys.exit('terminated by user')
if p.poll() != None:
sys.exit('terminated by child exit')
This works ok, but constant polling uses 100% of CPU resources. It is possible to insert
time.sleep() instructions to reduce the carbon footprint, but these crutches will greatly slow down the console when you add z-type to console to spend your time until the background process is finished.
Asynchronous console input on Windows with Python
Asynchronous input allows your program to receive notification from operating system when an input is available. This means that you define events your program needs to
react(not necessary console events), send this list to operating system and put your program into
wait mode. When system sees this event, your wait function returns and it's possible to inspect/filter event to a greater detail.
Windows provides
WaitForMultipleObjectswait function, and in Linux I believe it is
selectcall. If you've tried to understand how Twisted works, but couldn't - will it make more clear if I say that
twisted reactoris a
wait function? What you do when you code with twisted is just configuring events to react, making chains of them so that one event reacts to another event. This allow to build very interesting, complex and de-coupled asynchronous applications in a couple of days.
O.k. Getting back from Twisted to the asynchronous console input on Windows. Below is the full source code that uses
WaitForMultipleObjects. I am afraid that's minimal complete example possible to build with ctypes using Windows API. Tested with Python 2.5
Non-blocking asynchronous input from console:
https://bitbucket.org/techtonik/async-console-input
"""
Example of non-blocking asynchronous console input using
Windows API calls in Python. This can become handy for
async console tools such as IRC client.
Public domain or MIT license
by anatoly techtonik
Notes:
1. WaitForMultipleObjects is used to listen for the
signals from process and stdin handles
2. When handle is signalled it remains in this state
until reset
3. msvcrt.* keyboard functions don't clear signalled
state from stdin handle, that's why console API
functions are used to clear the input buffer
instead of kbhit()/getch() loop
"""
import ctypes
import ctypes.wintypes
import subprocess
# open notepad in separate process and monitor its execution
# at the same time asynchronously processing events from
# standard input without wasting 100% CPU on looping
# OpenProcess desired access flag
# "the right to use the object for synchronization. This
# enables a thread to wait until the object is in the
# signaled state"
SYNCHRONIZE=0x00100000L
# Constant to get stdin handle with GetStdHandle() call
STD_INPUT_HANDLE = -10
# Constant for infinite timeout in WaitForMultipleObjects()
INFINITE = -1
# --- processing input structures -------------------------
# INPUT_RECORD structure
# events:
EVENTIDS = dict(
FOCUS_EVENT = 0x0010,
KEY_EVENT = 0x0001, # only key event is handled
MENU_EVENT = 0x0008,
MOUSE_EVENT = 0x0002,
WINDOW_BUFFER_SIZE_EVENT = 0x0004)
EVENTS = dict(zip(EVENTIDS.values(), EVENTIDS.keys()))
# records:
class _uChar(ctypes.Union):
_fields_ = [('UnicodeChar', ctypes.wintypes.WCHAR),
('AsciiChar', ctypes.wintypes.c_char)]
class KEY_EVENT_RECORD(ctypes.Structure):
_fields_ = [
('keyDown', ctypes.wintypes.BOOL),
('repeatCount', ctypes.wintypes.WORD),
('virtualKeyCode', ctypes.wintypes.WORD),
('virtualScanCode', ctypes.wintypes.WORD),
('char', _uChar),
('controlKeyState', ctypes.wintypes.DWORD)]
class _Event(ctypes.Union):
_fields_ = [('keyEvent', KEY_EVENT_RECORD)]
# MOUSE_EVENT_RECORD MouseEvent;
# WINDOW_BUFFER_SIZE_RECORD WindowBufferSizeEvent;
# MENU_EVENT_RECORD MenuEvent;
# FOCUS_EVENT_RECORD FocusEvent;
class INPUT_RECORD(ctypes.Structure):
_fields_ = [
('eventType', ctypes.wintypes.WORD),
('event', _Event)]
# --- /processing input structures ------------------------
np = subprocess.Popen([r"notepad"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
# OpenProcess returns handle that can be used in wait functions
# params: desiredAccess, inheritHandle, processId
nph = ctypes.windll.kernel32.OpenProcess(SYNCHRONIZE, False, np.pid)
print("Started Notepad with pid=%s, handle=%s" % (np.pid, nph))
ch = ctypes.windll.kernel32.GetStdHandle(STD_INPUT_HANDLE)
handles = [ch, nph]
ctypes.windll.kernel32.FlushConsoleInputBuffer(ch)
eventnum = ctypes.wintypes.DWORD()
eventread = ctypes.wintypes.DWORD()
inbuf = (INPUT_RECORD * 1)()
print "[q]uit, [s]top console processing, launch bro[w]ser"
stopflag = False
while not stopflag and nph in handles:
print "Waiting for handles %s.." % handles
HandleArrayType = ctypes.wintypes.HANDLE * len(handles)
handle_array = HandleArrayType(*handles)
# params: count, handles, waitAll, milliseconds
ret = ctypes.windll.kernel32.WaitForMultipleObjects(
len(handle_array), handle_array, False, INFINITE)
if handles[ret] == ch:
"""
# msvcrt won't work, because it doesn't reset
# signalled state of stdin handle
import msvcrt
while msvcrt.kbhit():
print "key!"
print msvcrt.getch()
continue
"""
# --- processing input ---------------------------
ctypes.windll.kernel32.GetNumberOfConsoleInputEvents(
ch, ctypes.byref(eventnum))
for i in range(eventnum.value):
# params: handler, buffer, length, eventsnum
ctypes.windll.kernel32.ReadConsoleInputW(
ch, ctypes.byref(inbuf), 2, ctypes.byref(eventread))
if EVENTS[inbuf[0].eventType] != 'KEY_EVENT':
print EVENTS[inbuf[0].eventType]
pass
else:
keyEvent = inbuf[0].event.keyEvent
if not keyEvent.keyDown:
continue
char = keyEvent.char.UnicodeChar.lower()
#print char, keyEvent
if char == 'q':
print('[q] key pressed. Exiting..')
stopflag = True
elif char == 's':
handles.remove(ch)
elif char == 'w':
import webbrowser
webbrowser.open('http://techtonik.rainforce.org')
#print char
# --- /processing input --------------------------
elif handles[ret] == nph:
print("Notepad is closed. Exiting..")
handles.remove(nph)
else:
print("Warning: Unknown return value '%s'" % ret)
ctypes.windll.kernel32.FlushConsoleInputBuffer(ch)
ctypes.windll.kernel32.CloseHandle(nph)
print "Done."
Where can it be useful?
Writing first Windows console IRC client in Python and make it cross-platform? Network log viewers with keyboard shortcuts? Real-time roguelikes? Matrix sniffer screensaver? I don't know - its your time. Hope I saved you some though.
Enjoy! If you want to enhance this stuff - feel free to join ever empty https://groups.google.com/forum/#!forum/rainforce for public discussion.
|
I have some issue with too many Threads unfinished. I think that queue command .join() just close queue and not the threads using it.
In my script I need to check 280k domains and for each domain get list of his MX records and obtain an IPv6 address of servers if it has it.
I used threads and thanks for them the script its many times faster. But there is a problem, although there is join() for the queue, number of alive threads is growing till an error occur that informs that cant create any new thread (limitation of OS?).
How can I terminate/close/stop/reset threads after each For loop when I am retrieving new domain from database?
Thread Class definition...
class MX_getAAAA_thread(threading.Thread):
def __init__(self,queue,id_domain):
threading.Thread.__init__(self)
self.queue = queue
self.id_domain = id_domain
def run(self):
while True:
self.mx = self.queue.get()
res = dns.resolver.Resolver()
res.lifetime = 1.5
res.timeout = 0.5
try:
answers = res.query(self.mx,'AAAA')
ip_mx = str(answers[0])
except:
ip_mx = "N/A"
lock.acquire()
sql = "INSERT INTO mx (id_domain,mx,ip_mx) VALUES (" + str(id_domain) + ",'" + str(self.mx) + "','" + str(ip_mx) + "')"
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
print "MX" , '>>' , ip_mx, ' :: ', str(self.mx)
lock.release()
self.queue.task_done()
Thread class in use... (The main For-loop is not here, this is just part of his body)
try:
answers = resolver.query(domain, 'MX')
qMX = Queue.Queue()
for i in range(len(answers)):
t = MX_getAAAA_thread(qMX,id_domain)
t.setDaemon(True)
threads.append(t)
t.start()
for mx in answers:
qMX.put(mx.exchange)
qMX.join()
except NoAnswer as e:
print "MX - Error: No Answer"
except Timeout as etime:
print "MX - Error: dns.exception.Timeout"
print "end of script"
I tried to:
for thread in threads:
thread.join()
after the queue was done, but thread.join() never stops waiting, despite fact that there is no need to wait, because when queue.join() executes there is nothing to do for threads.
|
When building a public key using the OpenSSL::PKey::RSA module by passing it a .pem file, what is the cause for a response:
OpenSSL::PKey::RSAError: Neither PUB key nor PRIV key:: nested asn1 error
from /Users/Matt/projects/placepop/lib/apn.rb:48:in `initialize'
from /Users/Matt/projects/placepop/lib/apn.rb:48:in `new'
from /Users/Matt/projects/placepop/lib/apn.rb:48:in `open'
from (irb):1
Here is the source:
cert = File.join(rails_root, 'config', 'apns', 'sandbox-cert.pem')
APN_CONFIG = { :delivery => {
:host => 'gateway.sandbox.push.apple.com',
:cert => cert,
:passphrase => "",
:port => 2195 },
:feedback => {
:host => 'feedback.sandbox.push.apple.com',
:port => 2196,
:passphrase => "",
:cert => cert} }
options = APN_CONFIG[:delivery].merge(options)
cert = File.read(options[:cert])
ctx = OpenSSL::SSL::SSLContext.new
ctx.key = OpenSSL::PKey::RSA.new(cert, options[:passphrase])
ctx.cert = OpenSSL::X509::Certificate.new(cert)
sock = TCPSocket.new(options[:host], options[:port])
ssl = OpenSSL::SSL::SSLSocket.new(sock, ctx)
ssl.sync = true
ssl.connect
|
Introduction
web2py[web2py] est un framework web libre et open-source pour le développement agile et sécurisé d'applications web pilotées par base de données; il est écrit en Python[python] et programmable en Python. web2py est un framework complet, contenant donc tous les composants nécessaires pour construire des applications web totalement fonctionnelles.
web2py est conçu pour guider le développeur web à suivre les bonnes pratiques de l'ingénierie logicielle, telles que l'utilisation du pattern Modèle Vue Contrôleur (MVC). web2py sépare la représentation des données (modèle) de la présentation des données (la vue) et également de la logique applicative et de ses flux de travail (le contrôleur). web2py fournit des librairies pour aider le développeur à dessiner, implémenter et tester chacune des trois parties séparément, et les faire fonctionner ensemble.
web2py est construit pour la sécurité. Cela signifie qu'il élimine automatiquement la plupart des problèmes qui peuvent amener à des failles de sécurité, en suivant des pratiques bien établies. Par exemple, toute entrée est validée (pour éviter les injections), toute sortie est contrôlée (pour éviter le cross-site scripting), et tout fichier uploadé est renommé (pour éviter toute attaque traverse de répertoireà. web2py fait attention aux principaux problèmes de sécurité, afin que les développeurs aient le moins de chande d'introduire des failles dans leur développement.
web2py inclut une couche d'abstraction à la base de données (Database Abstraction Layer -DAL) qui écrit les requêtes SQL[sql-w] dynamiquement afin que vous, développeurs, n'ayez pas à le faire. Cette couche d'abstraction (DAL) sait parfaitement comment générer les requêtes SQL de manière transparente pour SQLite[sqlite], MySQL[mysql], PostgreSQL[postgres], MSSQL[mssql], FireBird[firebird], Oracle[oracle], IBM DB2[db2], Informix[informix] et Ingres[ingresdb].
La couche d'abstraction peut également générer des appels de fonction pour le Datastore Google lorsqu'elle fonctionne sur les Google App Engine (GAE)[gae]. De manière expérimentale, nous supportons plus de bases de données et de nouvelles sont constamment ajoutées. Veuillez vérifier le site web de web2py et la mailing list pour trouver les connecteurs les plus récents. Une fois qu'une ou plusieurs tables ont été définies, web2py génère automatiquement une interface d'aministration web complète pour accéder à la base de données et aux tables.
web2py diffère des autres frameworks web du fait que ce soit le seul à totalement adopter le paradigme Web 2.0, où le web est l'ordinateur. En fait, web2py ne nécessite aucune installation ou configuration; il fonctionne sur n'importe quelle architecture qui peut exécuter du Python (Windows, Windows CE, Mac OS X, iOS, et Unix/Linux), et le développement, le déploiement, et les phases de maintenance phases pour les applications peuvent être faites via une interface web locale ou distante. web2py fonctionne avec CPython (l'implémentation C) et PyPy (Python écrit en Python), sur les versions Python 2.5, 2.6, et 2.7.
web2py fournit un système de tickets pour les erreurs remontées. Si une erreur survient, un ticket est attribué à l'utilisateur et l'erreur est enregistrée pour l'administrateur.
web2py est open source et distribué sous la licence LGPG version 3.
Une autre fonctionnalité importante de web2py est que nous, ses développeurs, travaillons à maintenir une rétro-compatibilité pour les versions futures. Ce maintien est assuré depuis la sortie de la première release de web2py en Octobre 2007. De nouvelles fonctionnalités ont été ajoutées et des bugs ont été corrigés, mais si le programme fonctionnait avec web2py 1.0, alors ce programme fonctionnera même mieux aujourd'hui.
Trouvez ici quelques exemples de déclarations web2py qui illustrent leur pouvoir et leur simplicité. Le code suivant :
db.define_table('person', Field('name'), Field('image', 'upload'))
créé une table de base de données appelée "person" avec deux champs : "name", une chaîne de caractères ; et "image", quelque chose qui a besoin d'être uploadé (l'image actuelle dans ce cas). Si la table existe déjà mais ne correspond pas à cette définition, elle va être modifiée en conséquence.
Etant donné la table définie ci-dessus, le code suivant :
form = SQLFORM(db.person).process()
créé un formulaire d'insertion pour cette tables qui permet aux utilisateurs d'uploader les images. Cela valide également le formulaire soumis, renomme l'image envoyée de manière sécurisée, stocke l'image dans un fichier, insère l'enregistrement correspondant dans la base de données, évite une double soumission, et modifie éventuellement le formulaire lui-même en ajoutant les messages d'erreur si les données transmises par l'utilisateur ne sont pas valides.
Ce code embarque un wiki totalement fonctionnel contenant tags, recherche, nuage de tags, permissions, pièces jointes, et le support:
def index(): return auth.wiki()
Alors que le code suivant :
@auth.requires_permission('read','person')
def f(): ....
empêche les visiteurs d'accéder à la fonction f à moins que le visiteur soit un membre du groupe ayant les droits de "lecture" sur les enregistrement de la table "person". Si le visiteur n'est pas connecté, il est redirigé sur une page d'identification (fournie automatiquement par défaut par web2py).
web2Py supporte également les composants, c'est à dire les actions qui peuvent être chargées dans une vue et intéragir avec le visiteur via des requêtes Ajax sans avoir à recharger la page entière. Ceci est fait via l'assistant LOAD qui autorise un design très modulaire des applications; ce sujet est traité dans le chapitre 3 dans le contexte du wiki et un peu plus en détails dans le dernier chapitre de ce livre.
Cette 5ème édition de ce livre décrit web2py 2.4.1 et les versions suivantes.
Principes
La programmation Python respecte typiquement les principes de base suivants :
Ne pas se répéter soi-même.
Il ne devrait y avoir qu'une seule façon de faire les choses.
Explicite est mieux qu'implicite.
web2py englobe totalement les deux premiers principes en forçant le développeur à utiliser les pratiques d'ingénierie logicielle du son décourageant toute répétition de code. web2py accompagne le développeur à travers quasiment toutes les tâches communes dans le développement d'application web (création et traitement des formulaires, gestion des sessions, des cookies, des erreurs, etc...)
web2py diffère des autres frameworks par rapport au troisième principe, entrant parfois en conflit avec les deux autres. En particulier, web2py n'importe pas les applications utilisateur, mais les exécute dans un contexte prédéfini. Ce contexte révèle les mots-clés Python, aussi bien que les mots-clés web2py.
Pour certains, ceci peut apparaître comme magique, mais cela ne devrait pas. Simplement, en pratique, quelques modules sont déjà importés sans que vous l'ayez fait. web2py essaie d'éviter ces caractéristiques ennuyantes des autres frameworks qui forcent le développeur à importer les mêmes modules en haut de chaque modèle et contrôleur.
web2py, en important ses propres modules, fait gagner du temps et évite des erreurs, qui plus est en respectant l'esprit du "ne te répète pas toi-même" et "il ne devrait y avoir qu'une façon de faire les choses".
Si le développeur souhaite utiliser d'autres modules Python ou des modules tiers, ces modules doivent être importés explicitement, comme dans n'importe quel autre programme Python.
Frameworks web
A son niveau le plus fondamental, une application web consiste en un ensemble de programmes (ou fonctions) qui sont exécutées lorsque l'URL correspondante est visitée. La sortie du programme est retournée au visiteur et rendue par le navigateur.
Le but des frameworks web est d'autoriser les développeurs à construire de nouvelles applications rapidement, facilement et sans erreurs. C'est faisable en fournissant les APIs et les outils qui réduisent et simplifient la quantité de code requise.
Les deux approches classiques pour le developpement d'applications web sont:
Le premier modèle est celui qui est suivi, par exemple, immédiatement par des scripts CGI. Le second modèle est suivi, par exemple, par PHP[php] (où le code est en PHP, un langage similaire au C), ASP (où le code est en Visual Basic), et JSP (où le code est en Java).
Ci-dessous, un exemple de programme PHP qui retrouve les données depuis une base de données lors de son exécution, et qui retourne une page HTML affichant les enregistrement sélectionnés :
<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>
Le problème avec cette approche est que le code est embarqué dans l'HTML, et ce même code a besoin de générer du contenu HTML additionel. Il a également besoin de générer des déclarations SQL pour requêter la base de données, et en mélangeant ces différentes couches de l'application, la lecture et la maintenance du code devient très difficile. Cette situation est d'autant plus difficile pour des applications Ajax, que la complexité augmente avec le nombre de pages (fichiers) qui constituent l'application.
Cette fonctionnalité présentée dans l'exemple ci-dessus peut être exprimée avec seulement deux lignes de code Python dans web2py :
def index():
return HTML(BODY(H1('Records'), db().select(db.contacts.ALL)))
Dans cet exemple simple, la structure de la page HTML est représentée de manière programmée par les objets HTML, BODY, et H1; la base de données db est requêtée par la commande select; et finalement, tout est sérialisé dans l'HTML. Notons bien que db n'est pas un mot-clé mais bien une variable définie par l'utilisateur. Cette terminologie sera utilisée tout au long du document pour représenter la connection à la base de données pour éviter toute confusion.
Les frameworks web sont généralement catégorisés comme l'un des types suivants : Un framework "glue" est un framework construit en assemblant (en collant ensemble) plusieurs composants tiers. Un framework "complet" est construit en créant des composants prévus spécifiquement pour être étroitement intégrés et fonctionnels ensemble.
web2py est un framework complet. Presque tous ses composants sont construits de zéro et sont prévus pour fonctionner ensemble, mais fonctionnant aussi bien en dehors du framework web2py. Pour exemple, la couche d'abstration à la base de données (DAL) or les templates de langues peuvent être utilisés indépendamment du framework web2Py en important gluon.dal ou gluon.template dans vos propres propres applications Python. gluon est le nom du module web2py qui contient des librairies système. Quelques librairies web2py, telles que la construction pour le traitement des tables de la base de données par les formulaires, ont des dépendances avec d'autres parties de web2Py. web2py peut également fonctionner avec des librairies Python tierces, incluant d'autres templates de langue et couches d'abstrations à la base de données, mais ne seront pas aussi bien intégrés que les composants originaux.
Modèle-Vue-Contrôleur
wzb2py encourage le développeur à séparer la représentation des données (le modèle), la présentation des données (la vue) et le traitement du flux applicatif (le contrôleur). Reconsidérons l'exemple précédent et voyons comment il est possible de construire une application web2py autour. Ci-après, un exemple d'interface d'édition MVC web2py :
Le flux générique d'une requête web2py est décrit dans le diagramme suivant :
Dans le diagramme :
Le serveur peut être intégré au serveur web we2py où bien un serveur tiers, tel qu'un serveur Apache. Le serveur prend en charge le multi-threading .
"main" est l'application WSGI principale. Elle exécute toutes les tâches communes et englobe les application utilisateur. Il gère les cookies, les sessions, les transactions, le routage d'URL et le routage inverse, ainsi que le déploiement.
Elle peut proposer et diffuser des fichiers statiques si le serveur ne le fait pas encore.
Les composants Modèle (Model), Vue (View) et Contrôleur (Controller) construisent l'application utilisateur.
Plusieurs applications peuvent être hébergées sur une même instance web2py.
Les flèches en pointillés représentent la communication avec le(s) moteur(s) de base de données. Les requêtes à la base peuvent être écrites en langage SQL pur (déconseillé) ou en utilisant la couche d'abstration à la base de données (recommandé), afin que le code de l'application web2py ne soit pas dépendant d'un moteur spécifique de base de données.
Le répartiteur créé le lien entre les URL demandées et un appel de fonction dans le contrôleur. La sortie de la fonction peut être une chaîne de caractères ou un dictionnaire de symboles (une table de hash). Les données contenues dans le dictionnaire sont affichées par une vue. Si le visiteur demande une page HTML (comportement par défaut), le dictionnaire est rendu comme page HTML. Si le visiteur demande la même page en XML, web2py essaie de trouver une vue qui peut effectuer le rendu du dictionnaire en XML. Le développeur peut créer des vues pour effectuer des rendus dans n'importe lequel des protocoles déjà supportés (HTML, XML, JSON, RSS, CSV, et RTF) ou dans des protocoles personnalisés additionels.
Tous les appels sont englobés dans une transaction, et n'impote quelle exception non traitée entraînera l'annulation de la transaction. Si la requête réussit, la transaction est validée.
web2py prend également en charge les sessions et les cookies de session automatiquement, et lorsqu'une transaction est validée, la session est alors stockée, à moins qu'un autre comportement n'ait été spécifié.
Il est possible d'enregistrer des tâches récurrentes (via cron) pour démarrer de manière programmée et/ou après l'exécution de certaines actions. Par ce moyen, il est possible de démarrer de longues tâches intensives en arrière-plan sans ralentir la navigation.
Ci-après, une application minimale et complète MVC, en trois fichiers :
"db.py" est le modèle :
db = DAL('sqlite://storage.sqlite')
db.define_table('contact',
Field('name'),
Field('phone'))
Une connexion à la base de données est établie (dans cet exemple, une base de données SQLite est stockée dans le fichier storage.sqlite) et une table nommée contact est définie. Si la table n'existe pas, web2Py la créé et, de manière transparente en arrière-plan, génère le code SQL approprié pour le moteur de base de données choisi et utilisé. Le développeur peut voir la requête SQL générée mais n'a pas besoin de changer le code si le système de base de données, par défaut en SQLite, est remplacé par MySQL, PostgreSQL, MSSQL, FireBird, Oracle, DB2, Informix, Interbase, Ingres ou Google App Engine (SQL et NoSQL).
Une fois la table définie et créée, web2py génère également une interface de gestion web entièrement fonctionnel pour la base de données, appelée appadmin, pour accéder à la base et à ses tables.
"default.py" est le contrôleur :
def contacts():
grid=SQLFORM.grid(db.contact, user_signature=False)
return locals()
Dans web2py, les URLs sont liées à des modules Python et à des appels de fonction. Dans ce cas, le contrôleur contient une fonction unique (ou "action") appelé contacts. Une action peut retourner une châine de caractères (la page web) ou un dictionnaire Python (un ensemble de paires clé:valeur) ou un ensemble de variables locales (comme dans cet exemple). Si la fonction retourne un dictionnaire, le tout est transmis à une vue avec le même nom que le nom de la fonction (ou du contrôleur), qui effectue le rendu de la page en retour. Dans cet exemple, la fonction contacts génère une grille de select/search/create/update/delete pour la table db.contact et renvoie la grille à la vue.
"default/contacts.html" est la vue:
{{extend 'layout.html'}}
<h1>Manage My Contacts</h1>
{{=grid}}
Cette vue est appelée automatiquement par web2py après que la fonction associée du contrôleur (action) ait été exécutée. Le but de cette vue est d'effectuer le rendu des variables contenues par le dictionnaire retourné (dans notre cas grid) en HTML. Le fichier de vue est écrit en HTML, mais peut embarquer du code Python délimité par les balises spéciales {{ et }}. Ceci diffère un peu du code d'exemple PHP, car le seul code embarqué dans l'HTML est le code de "couche de présentation". Le fichier "layout.html" au début de la vue est fournie par web2py et constitue la mise en page pour toutes les applications web2py. Ce fichier peut facilement être modifié ou remplacé.
Pourquoi Web2py
web2py est l'un des nombreux frameworks d'application web, mais il est devenu très persuasif grâce à de nombreuses fonctionnalités uniques. web2py était à la base développé comme un outil d'apprenrissage, avec les motivations principales suivantes :
Facilité pour les utilisateurs à apprendre le développement côté serveur sans compromettre de fonctionnalité. Pour cette raison, web2py ne requiert aucune installation ou configuration, n'a pas de dépendences (à l'exception de la distribution du code source qui requiert Python 2.5 et ses librairies standard), et présente la plupart de ses fonctiionnalités via une interface web, incluant un Environnement de Développement Intégré avec les outils de débogage et une interface pour la base de données.
web2py a été stable dès le premier jour grâce à une approche descendante; c'est à dire que l'API a été dessinée avant d'être implémentée. Même si de nouvelles fonctionnalités ont été ajoutées, web2py n'a jamais cessé sa rétro-compatibilité, et ne l'arrêtera pas lorsque de nouvelles fonctionnalités seront ajoutées dans le futur.
web2py s'intéresse de manière pro-active aux plus importantes failles de sécurité qui peuvent tourmenter les applications web les plus modernes comme déterminé par OWASP[owasp]ci-après.
web2py est très léger. Le coeur du système (librairies), incluant la couche d'abstration à la base de données, les modèles de langues, et tous les assistants ne pèsent que 1.4MO. Le code source entier incluant les des exemples d'application et les images pèsent environ 10.4MO.
web2py a une empreinte très petite et est très rapide. Il utilise le serveur web WSGI Rocket rocketdéveloppé par Timothy Farrell. Sa rapidité est comparable à celle obtenue grâce au module Apache mod_wsgi, et supporte SSL et IPv6.
web2py utilise la syntaxe Python pour les modèles, les contrôleurs et les vues, mais n'importe pas les modèles et contrôleurs (comme font tous les autres frameworks) - au lieu de cela, il les exécute. Cela signifie que les applications peuvent être installées, déinstallées et modifiées sans avoir à redémarrer le serveur web (même en production), et différentes applications peuvent co-exister sans qu'il y ait d'interférence entre les modules.
web2py utilise une couche d'abstraction à la base de données (Database Abstraction Layer - DAL) au lieu d'un d'un Mapping Objet-Relationnel (Object Relational Mapper - ORM). D'un point de vue conceptuel, ceci signifie que différentes tables de la base de données sont mappées en différentes instances d'une classe Tableet non pas en différentes classes, alors que les enregistrements sont mappés en instances d'une classeRowet non en instances d'une classe de la table correspondate. D'un point de vue pratique, cela signifie que la syntaxe SQL effectue des correspondances presque une à une en syntaxe DAL, et qu'il n'y a aucune meta-classe complexe à programmer comme dans la plupart des ORM, ce qui ajouterait de la latence.
Ci-après, une capture d'écran de l'interface admin principale de web2py :
Sécurité
L'"Open Web Application Security Project" [owasp] (OWASP) est une communauté internationale libre et ouverte avec pour principal but l'amélioration de la sécurité des applications logicielles.
OWASP a listé le top 10 des problèmes de sécurité entraînant un risque pour les applications web. Cette liste est copiée ici, avec une description pour chacune sur l'impact avec web2Py :
cross site scripting"Cross Site Scripting (XSS): les failles XSS apparaissent lorsqu'une application utilise des données fournies par l'utilisateur et les envoie à un navigateur web sans effectuer une première validation ou encodage du contenu. XSS permet aux attaquants d'exécuter des scripts sur le navigateur de la victime qui peuvent détourner des sessions utilisateur, dégrader des sites web, potentiellement injecter des virus, etc..."web2py, par défaut, rejette toute variable injectée dans la vue, pour éviter tout XSS.
injection flaws"Les failles d'injection : ces failles, particulièrement en injection SQL, sont communes aux applications web. Une injection arrive lorsque les données fournies par l'utilisateur sont envoyées à un interpréteur comme commande ou requête. Les données de l'attaquant brouillent l'interpréteur en exécutant des commandes inattendues ou en changeand des données."web2py inclut une couche d'abstraction à la base de données rendant l'injection SQL impossible. Normalement, les déclarations SQL ne sont pas écrités par le développeur. Au lieu de cela, la requête SQL est générée dynamiquement par la couche d'abstraction à la base de données, s'assurant ainsi que toute donnée à insérer dans la base est correctement formatée.
malicious file execution"Exécution de fichier malicieux : du code vulnérable à de l'inclusion de fichier distant (Remote File Inclusion - RFI) permet à un attaquant d'inclure du code et des données hostiles, résultant en des attaques dévastatrices, telle qu'une mise en péril d'un serveur entier."web2py n'autorise que les fonctions exposées à être exécutées, évitant ainsi l'exécution de fichier malicieux. Les fonctions importées ne sont jamais exposées; seules les actions sont exposées. web2py utilise un interface d'aministration web qui rend très facile le suivi de ce qui est exposé et de ce qui ne l'est pas.
insecure object reference"Référence directe à un oject non sécurité : une référence directe à un objet peut survenir lorsqu'un développeur expose une référence à l'implémentation d'un objet interne, tel qu'un fichier, un répertoire, un enregistrement en base de données ou une clé, comme une URL ou un paramètre de formulaire. Les attaquants peuvent manipuler ces références pour obtenir l'accès à d'autres objets sans autorisation."web2py n'expose aucun objet interne; de plus, web2py valide toutes les URLs, évitant ainsi les attaques transverses de répertoire (directory travesal attacks). web2py fournit également un mécanisme simple pour crééer des formulaires qui valident automatiquement toutes les valeurs en entrée.
CSRF"Les requêtes criminelles Cross-Site (Cross Site Request Forgery - CSRF): Une attaque CSRF force le navigateur d'une victime connectée à envoyer une requête pré-authentifiée à une application web vulnérable, forçant ainsi le navigateur de la victime à exécuter une action hostile au bénéfice de l'attaquant. CSRF peut être aussi puissant que l'application web qu'il attaque."web2py évite les CSRF aussi bien que les doubles soumissions accidentelles de formulaires en assigant un jeton aléatoire éphémère à chaque formulaire. De plus, web2py utilise un UUID pour les cookies de session.
information leakageimproper error handling"Les fuites d'information et la prise en charge d'erreurs incorrectes : Les applications peuvent non intentionnellement laisser des fuites d'information sur leur configuration, des travaux internes, ou porter atteinte à l'intimité à travers une variété de problèmes applicatifs. Les attaquants utilisent cette faiblesse pour voler des données sensibles, ou conduire à des attaques plus sérieuses."web2py inclut un système de ticket. AUcune erreur ne peut résulter en code qui serait exposé à l'utilisateur. Toutes les erreurs sont loguées et un ticket est assigné à l'utilisateur autorisant le suivi de l'erreur. Mais les erreurs et le code source impliqué ne sont uniquement accessibles que par l'administrateur.
"Authentification cassée et gestion de session : les identifiants de compte et les jetons de session ne sont souvent pas protégés correctement. Les attaquants peuvent détourner les mots de passe, les clés ou les jetons d'authentifications pour utiliser l'identité d'autres utilisateurs." web2Py fournit un mécanisme intégré pour l'authentification administrateur, et gère les sessions indépendamment pour chaque application. L'interface d'administration force l'utilisation de cookies de session sécurisés lorsque le client n'est pas en "localhost". Pour les applications, une puissante API basée sur des contrôles d'accès par rôle (Role Base Access Control) est inclue.
cryptographic store"Stockage cryptographique non sécurisé : les applications web utilisent très rarement les fonctions de cryptographie correctement pour protéger les données et les identifiants de connexion. Les attaquants utilisent des données faiblement protégées pour effectuer du vol d'identification et autres crimes, telles que les fraudes de carte de crédit."web2py utilise les algorithmes de hachage MD5 ou HMAC+SHA-512 pour protéger les mots de passe stockés. Les autres algorithmes sont également disponibles.
secure communications"Communications non sécurisées : les applications échouent fréquemment pour chiffrer le trafic réseau lorsqu'il est nécessaire de protéger des communications sensibles."web2py inclut le serveur[ssl]Rocket WSGI incluant le support SSL activé par défaut, mais peut également utiliser Apache ou Lighttpd et le module mod_ssl pour fournir la couche de chiffrement SSL des communications.
access restriction"Echec de restriction d'accès à certaines URL : La plupart du temps, une application protège uniquement les fonctionnalités sensibles en évitant l'affichage de liens ou URLs à des utilisateurs non autorisés. Les attaquants peuvent utiliser cette faiblesse pour accéder et exécuter des opérations non autorisées en accédant à ces URLs directement."web2py effectue un lien entre chaque requête URL te les modules et fonctions Python. web2py fournit un mécanisme pour déclarer quelles fonctions sont publiques et lesquelles nécessitent une authentification préalable pour autorisation. L'API de contrôle d'accès par rôle autorise les développeurs à restreindre l'accès à n'importe quelle fonction en se basant sur le login, l'appartenance à un groupe ou les permissions de groupe. Les permissions sont très granulaires et peuvent être combinées avec des filtres de base de données pour permettre, par exemple, de donner un accès à certaines tables spécifiques et/ou à des enregistrements. web2py permet également d'utiliser les URLs signées numériquement et fournit une API pour signer numériquement les callbacks Ajax.
web2py a été revu pour sa sécurité et vous pouvez trouver le résultat de cette revue en référence [pythonsecurity].
Dans la boîte
Vous pouvez télécharger web2py depuis le site web officiel :
http://www.web2py.com
web2py est composé des éléments suivants :
librairies: fournissent le coeur des fonctionnalités de web2py et sont accessibles de manière programmable.
serveur web: le serveur web WSGI Rocket.
l'application admin: utilisée pour créer, dessiner et gérer les autres applications web2py.adminfournir un Environnement de Développement Intégré (EDI) web complet pour construire des applications web2py. Il inclut également d'autres fonctionnalités, telles qu'un moteur de test et un shell web.
les applications exemples: contiennent de la documentation et des exemples interactifs. Lesexemplessont un clone du site web officiel web2py.com, et incluent la documentation epydoc.
l'application bienvenue: le template de base pour n'importe quelle autre application. Par défaut, il inclut un menu déroulant pur CSS et un système d'authentification d'utilisateur (présenté dans le chapitre 9).
web2py est distribué en code source, et en fichiers binaires pour Microsoft Windows et Mac OS X.
La distribution du code source peut être utilisée sur n'importe quelle plateforme où Python est installé et inclut les composants ci-après mentionnés. Pour exécuter le code source, vous avez besoin de Python 2.5, 2.6 ou 2.7 pré-installé sur le système. Vous aurez également besoin d'installer l'un des moteurs de base de données supportés. Pour des tests et des applications nécessitant peu de requêtes, vous pouvez utiliser la base de données SQLite, inclue avec Python 2.7.
Les versions binaires de web2py (pour Windows et Mac OS X) incluent un interpréteur Python 2.7 et une base de données SQLite. Techniquement, ces deux composants ne font pas partie de web2py. En les incluant dans les distributions binaires, cela vous permet uniquement de démarrer web2py directement.
L'image suivante montre la structure globale de web2py :
Tout en bas, nous pouvons trouver l'interpréteur. En remontant, nous trouvons le serveur web (rocket), les librairies, et les applications. Chaque application possède son propre schéma MVC (modèles, contrôleurs, vues, modules, langages, bases de données, et fichiers statiques). Chaque application inclut son propre code d'administration de la base (appadmin). TOutes les instances web2py démarrent avec trois applications : welcome (l'application de base), admin (l'EDI web), et les exemples (copie du site web et exemples).
A propos de ce livre
Ce livre inclut les chapites suivants, suite à cette introduction :
Le chapitre 2 est une introduction minimaliste à Python. Il suppose une connaissance des concepts de la programmation procédurale et orientée objet tels que les boucles, les conditions, les appels de fonctions et de classes, et les principales syntaxes Python. Il couvre également les exemples de modules Python qui sont utilisés à tout au long de ce livre. Si vous connaissez déjà bien Python, vous pouvez passer ce chapitre.
Le chapitre 3montre comment démarrer web2py, parle de l'interface d'administration, et guide le lecteur à travers des exemples variés en augmentant la complexité: une application qui retourne une chaine de caractères, une application compteur, un blog, et une application complète de wiki qui autorise l'envoi d'images et de commentaires, fournit l'authentification, les autorisations, les services web et un flux RSS. En lisant ce chapitre, vous serez peut être amené à vous référer au chapitre 2 pour des syntaxes Python génériques et aux chapitres suivants pour des références plus détaillées sur les fonctions qui sont utilisées.
Le chapitre 4 couvre plus particulièrement la structure du coeur de web2py et les librairies : le mapping d'URL, les requêtes, les réponses, les sessions, le cache, l'ordonnanceur, le cron, l'internationalisation et les flux de travail généraux.
Le chapitre 5 est une référence pour le template de langue utilisée pour la construction des vues. Il montre comment embarquer du code Python dans du code HTML, et explique comment utilise les assistants (objets permettant la génération de code HTML).
Le chapitre 6 couvre la couche d'abstraction à la base de données, ou DAL (Database Abstraction Layer). La syntaxe de la DAL est présentée à travers une série d'exemples.
Le chapitre 7 couvre les formulaires, la validation de ces formulaires et leur traitement. FORM est un assistant bas-niveau pour la construction de formulaires. SQLFORM est un constructeur de formulaire haut-niveau. Dans le chapitre 7, nous verrons également des API Création/Lecture/Mise à jour/Suppression (Create/Read/Update/Delete - CRUD)
Le chapitre 8 couvre les fonctionnalités de communication, d'envoi d'emails et de SMS.
Le chapitre 9 couvre l'authentification, les autorisations et le mécanisme de contrôle d'accès basé sur les rôles disponible dans web2py. La configuration mail et CAPTCHA sont également présentées ici, puisqu'utilisées pour l'authentification. Dans la troisième édition de ce livre, une partie a été ajoutée pour les authentifications possibles avec l'intégration de mécanismes tiers tels que OpenID, OAuth, Google, Facebook, Linkedin, etc...
Le chapitre 10 est au sujet de la création de services web dans web2py. Nous fournissons des exemples d'intégration avec le Google Web Toolkit via Pyjamas, et avec Adobe Flash via PyAMF.
Le chapitre 11 est à propos de web2py et des possibilités avec jQuery. web2py est construit principalement pour de la programmation côté serveur, mais inclut jQuery, puiqu'elle s'avère être la meilleure librairie JavaScript disponible pour les effets et Ajax. Dans ce chapitre, nous discuterons donc des possibilités d'intégration de jQuery avec web2py.
Le chapitre 12 présente les composants et plugins web2py comme une possibilité de construire des applications modulables. Nous fournissons un exemple de plugin qui implémente les principales fonctionnalités, telles que la mise en forme de diagrammes, les commentaires et les tags.
Le chapitre 13 explique le déploiement en production d'applications web2py. Plus spécifiquement, le déploiement un serveur web LAMP est présenté (ce qui est considéré comme étant la principale alternative de déploiement). Des serveurs web alternatifs sont également présentés, ainsi que la configuration d'une base de données PostgreSQL. D'autres points sont présentés comme l'exécution en tant que service sur un environnement Microsoft Windows, et le déploiement sur certaines plateformes spécifiques incluant Google Applications Engine, Heroku, et PythonAnywhere. Dans ce chapitre, les problèmes de sécurité et s'évolutivité sont également soulevés.
Le chapitre 14 contient une variété d'autres possibilités pour résoudre des tâches spécifiques, incluant les mises à jour, le geocoding, la pagination, l'API Twitter et bien plus encore.
Ce livre couvre uniquement les fonctionnalités de base de web2py et l'API fournie avec web2py. Ce livre ne couvre pas les appliances web2py (i.e. des applications prêtes à l'emploi).
Vous pouvez télécharger les appliances web2py depuis le site correspondant [appliances]. Vous pouvez trouver des sujets complémentaires discutés dans les usergroup[usergroup]. Il y a également AlterEgo[alterego], l'ancien blog de web2py et sa FAQ.
Ce livre a été écrit en utilisant la syntaxe markmin et automatiquement converti en HTML, LaTeX et PDF.
Support
Le principal canal de support est le usergroup[usergroup], avec ses dizaines de posts par jour. Même si vous êtes un débutant, n'hésitez pas demander - nous serons ravis de pouvoir vous aider. Il y a également un système de suivi de bug officiel sur http://code.google.com/p/web2py/issues . Enfin, une information importante, vous pouvez obtenir du support professionnel (voir le site web pour plus de détails).
Contribute
Toute aide est vraiment appréciée. Vous pouvez aider les autres utilisateurs sur les groupes utilisateur, ou en envoyant directement des patchs sur le programme (sur le site GitHub https://github.com/web2py/web2py). Même si vous trouvez une erreur dans ce livre, ou si vous avez une amélioration à apporter, le meilleur moyen de le faire est de patcher le livre directement (sous le dossier source sur le repository à https://github.com/mdipierro/web2py-book).
Eléments de style
PEP8 [style] contient des bonnes pratiques de style lorsque l'on développe en Python. Vous verrez que web2py ne suit pas toujours ces règles. Ce n'est ni par oubli ni par négligence; c'est notre conviction que les utilisateurs devraient suivre ces règles et nous les y encourageons. Nous avons choisi de ne pas suivre certaines de ces règles en définissant les objects d'assistants afin de minimiser la probabilité de conflits de noms avec des objets définis par l'utilisateur.
Par exemple, la classe qui représente une <div> est appelée DIV, alors que si l'on se réfère à la référence Python, elle devrait avoir été appelée Div. Nous pensons que, pour cet exemple spécifique, utiliser une déclaration tout en majuscule "DIV", est un choix plus naturel. De plus, cette approche laisse aux programmeurs la liberté de créer une classe appelée "Div" s'ils le souhaitent. Notre syntaxe s'intègre également de manière naturelle à la notation DOM pour la plupart des navigateurs (incluant, par exemple, Firefox).
En se référant au guide de style Python, toutes les chaines de caractères majuscules devraient être utilisée pour des constantes et non pour des variables. En continuant avec notre exemple, même en considérant que DIV est une classe, c'est une classe spéciale qui ne devrait jamais être modifiée par l'utilisateur car une telle modification impacterait toutes les autres applications web2py. Par ailleurs, nous pensons qu'en qualifiant la classe DIV comme quelquechose de constant, ceci justifie totalement cette notation.
En résumé, les conventions suivantes sont respectées :
Les assistants HTML et les validateurs sont en majuscultes pour les raisons évoquées précédemment (par exemple, DIV,A,FORM,URL).
L'objet de traduction Test en majuscule malgré le fait que ce soit une instance de classe et non une classe. Logiquement, l'objet de traduction exécute une action similaire aux assistants HTML, et affecte une partie du rendu de la présentation. Aussi,Tnécessite d'être facile à localiser dans le code et doit avoir un nom court.
Les classes DAL suivent le guide de style Python (la première lettre uniquement en majuscule), par exemple Table,Field,Query,Row,Rows, etc...
Dans tous les autres cas, nous espérons avoir suivi, autant que possible, le Guide de Style Python (PEP8). Par exemple, toutes les instances d'objets sont en minuscules (request, response, session, cache), et toutes les classes internes sont en majuscules.
Dans tous les exemples de ce libre, les mots-clés web2py sont mis en gras, alors que les chaines de caractères et les commentaires sont mis en italique.
Licence
web2py est distribué sous licence LGPL version 3. Le texte complet de la licence est disponible en référence [lgpl3].
En respect de la licence LGPL, vous pouvez:
redistribuer web2py avec vos application (en incluant les versions binaires officielles)
mettre à disposition vos applications utilisant les librairies officielles web2py sous la licence que vous souhaitez
Cependant vous devez:
être clair dans votre documentation en mentionnant l'utilisation de web2py dans votre application
mettre à disposition toute modification des librairies web2py sous licence LGPLv3
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.
**Versions précédentes*
Les versions précédentes de web2py, 1.0.*-1.90.*, ont été mises à disposition sous la licence GPL2 avec une exception commerciale, qui pour des raisons pratiques, était très similaire à la licence courante LGPLv3.
Contenu tiers distribué avec web2py
web2py contient du contenu tiers dans le répertoire gluon/contrib et des fichiers JavaScript et CSS variés. Ces fichiers sont distribués avec web2py sous leurs licences originales, comme énoncé dans les fichiers.
Reconnaissances
web2py est développé et sous copyright de Massimo Di Pierro. La première version (1.0) a été mise en ligne en Octobre 2007. Depuis, elle a été adoptée par de nombreux utilisateurs, et certains d'entre eux ont contribué aux rapports de bugs, aux tests, au débug, aux patchs et à la relecture de ce livre.
La plupart des développeurs et des contributeurs sont, par ordre alphabétique :
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.
Je suis sûr que j'oublie des personnes, et j'en suis désolé.
Je remercie particulièrement Anthony, Jonathan, Mariano, Bruno, Vladyslav, Martin, Nathan, Simone, Thadeus, Tim, Iceberg, Denes, Hans, Christian, Fran et Patrick pour leurs contributions majeures à web2py et 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 (et les autres) pour leur relecture précise des différentes version de ce livre. Leur contribution est inestimable. Si vous trouvez des erreurs dans ce libre, elles sont exclusivement de ma faute, probablement introduite par une édition de dernière minute. Je remercie également Ryan Steffen de Wiley Custom Learning Solutions pour son aide lors de la publication de la première édition de ce livre.
web2py contient du code des auteurs suivants, que je tiens vraiment à remercier :
Guido van Rossum pour Python[python], Peter Hunt, Richard Gordon, Timothy Farrell pour le serveur web Rocket[rocket], Christopher Dolivet pour EditArea[editarea], Bob Ippolito pour simplejson[simplejson], Simon Cusack et Grant Edwards pour pyRTF[pyrtf], Dalke Scientific Software pour pyRSS2Gen[pyrss2gen], Mark Pilgrim pour feedparser[feedparser], Trent Mick pour markdown2[markdown2], Allan Saddi pour fcgi.py, Evan Martin pour le module Python memcache[memcache], John Resig pour jQuery[jquery]
Je remercie Helmut Epp (proviseur de DePaul University), David Miller (Doyen du College of Computing and Digital Media of DePaul University), et Estia Eichten (membre de MetaCryption LLC), pour leur confiance continue et leur support.
Enfin, je souhaite remercier ma femme, Claudia, et mon fils, Marco, pour m'avoir supporté durant les nombreuses heures que j'ai passées à développer web2py, en échangeant des emails avec des utilisateurs et collaborateurs, et en écrivant ce livre. Ce livre leur est dédié.
top
|
Create a Python script called whatever you want (say mystartup.py) and then set an environment variable PYTHONSTARTUP to the path of this script. Python will then load this script on startup of an interactive session (but not when running scripts). In this script, define a function similar to this:
def _(v):
if type(v) == type(0.0):
print "%e" % v
else:
print v
Then, in an interactive session:
C:\temp>set PYTHONSTARTUP=mystartup.py
C:\temp>python
ActivePython 2.5.2.2 (ActiveState Software Inc.) based on
Python 2.5.2 (r252:60911, Mar 27 2008, 17:57:18) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> _(1e12)
1.000000e+012
>>> _(14)
14
>>> _(14.0)
1.400000e+001
>>>
Of course, you can define the function to be called whaetver you want and to work exactly however you want.
Even better than this would be to use IPython. It's great, and you can set the number formatting how you want by using result_display.when_type(some_type)(my_print_func) (see the IPython site or search for more details on how to use this).
|
Here is a class vector in python 3, for n-dimmensional vectors. Please suggest ways to improve the code as well as fix bugs and errors.
The only rule is not using: numpy, sympy, scipy and so on. Only math, cmath, Rational, Decimal, ... Python 3 default packages..
This code is only for learning to make classes with python 3. I want comments to improve my python learning. For example, a way to improve the __init()__ constructor, and so on.
# /usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Created on Wed May 7 21:21:21 2014
@author: tobal
'''
from math import sqrt, acos, degrees, radians, cos, sin, fsum, hypot, atan2
class Vector(tuple):
'''"Class to calculate the usual operations with vectors in bi and
tridimensional coordinates. Too with n-dimmensinal.'''
# __slots__=('V') #It's not possible because V is a variable list of param.
def __new__(cls, *V):
'''The new method, we initialize the coordinates of a vector.
You can initialize a vector for example: V = Vector() or
V = Vector(a,b) or V = Vector(v1, v2, ..., vn)'''
if not V:
V = (0, 0)
elif len(V) == 1:
raise ValueError('A vector must have at least 2 coordinates.')
return tuple.__new__(cls, V)
def __add__(self, V):
'''The operator sum overloaded. You can add vectors writing V + W,
where V and W are two vectors.'''
if len(self) != len(V):
raise IndexError('Vectors must have same dimmensions.')
else:
added = tuple(a + b for a, b in zip(self, V))
return Vector(*added)
__radd__ = __add__
def __sub__(self, V):
'''The operator subtraction overloaded. You can subtract vectors writing
V - W, where V and W are two vectors.'''
if len(self) != len(V):
raise IndexError('Vectors must have same dimmensions.')
else:
subtracted = tuple(a - b for a, b in zip(self, V))
return Vector(*subtracted)
def __rsub__(self, V):
'''The operator subtraction overloaded. You can subtract vectors writing
W - V, where V and W are two vectors.'''
if len(self) != len(V):
raise IndexError('Vectors must have same dimmensions.')
else:
subtracted = tuple(b - a for a, b in zip(self, V))
return Vector(*subtracted)
def __mul__(self, V):
'''The operator mult overloaded. You can multipy 2 vectors coordinate
by coordinate.'''
if type(V) == type(self):
if len(self) != len(V):
raise IndexError('Vectors must have same dimmensions')
else:
multiplied = tuple(a * b for a, b in zip(self, V))
elif isinstance(V, type(1)) or isinstance(V, type(1.0)):
multiplied = tuple(a * V for a in self)
return Vector(*multiplied)
__rmul__ = __mul__
def __truediv__(self, V):
if type(V) == type(self):
if len(self) != len(V):
raise IndexError('Vectors must have same dimmensions.')
if 0 in V:
raise ZeroDivisionError('Division by 0.')
divided = tuple(a / b for a, b in zip(self, V))
elif isinstance(V, int) or isinstance(V, float):
divided = tuple(a / V for a in self)
return Vector(*divided)
__rtruediv__ = __truediv__
def __pow__(self, n):
'''The operator pow overloaded. You can powering vectors writing
V ** n, where V is a vector, and n is the power. If V = (a, b), then
V ** n calculates (a ** n, b ** n)'''
powered = tuple(a ** n for a in self)
return Vector(*powered)
def __iadd__(self, t):
sumplus = tuple(a + t for a in self)
return Vector(*sumplus)
def __isub__(self, t):
subminus = tuple(a - t for a in self)
return Vector(*subminus)
def __imul__(self, t):
mulplus = tuple(a * t for a in self)
return Vector(*mulplus)
def __itruediv__(self, t):
divplus = tuple(a / t for a in self)
return Vector(*divplus)
def __ipow__(self, t):
powplus = tuple(a ** t for a in self)
return Vector(*powplus)
def __neg__(self):
'''The operator negative overloaded. If V is a vector, you can
calculate -V, the vector V changed its sign in its coordinates.'''
opposite = tuple(-1 * a for a in self)
return Vector(*opposite)
def tofloat(self):
''' It converts a vector to float vector.'''
tofloatin = tuple(float(a) for a in self)
return Vector(*tofloatin)
def toint(self):
''' It converts a vector to integer vector.'''
tointeger = tuple(int(a) for a in self)
return Vector(*tointeger)
def inner(self, V):
''' Returns the dot product (inner product or scalar product) of self
and V vector
'''
return fsum(a * b for a, b in zip(self, V))
def isorthog(self, V):
'''Return if two vectors are or not orthogonals.'''
return self.inner(V) == 0
def norm(self):
'''Returns the norm (length, magnitude) of the vector'''
return sqrt(fsum(comp ** 2 for comp in self))
def isunit(self):
'''Returns if a vector has got norm equal 1 or not respect the
euclidian norm.'''
return self.norm() == 1
def pnorm(self, p):
'''Returns the p-norm of the vector'''
return pow(fsum(abs(comp) ** p for comp in self), p)
def infnorm(self):
'''Returns the infinity norm of the vector'''
return max(abs(comp) for comp in self)
def normalize(self):
'''Returns a normalized unit vector'''
norm = self.norm()
normed = tuple(comp / norm for comp in self)
return Vector(*normed)
def projection(self, V):
''' Returns the projection of 2 vectors.'''
if len(self) != len(V):
raise IndexError('Two vectors must have the same dimmension.')
else:
A = self.inner(V) / self.inner(self)
return A * self
def anglerad(self, V):
''' Returns the angle for 2 vectors in radians mode.'''
angle = acos(self.inner(V) / (self.norm() * V.norm()))
return angle
def angledeg(self, V):
''' Returns the angle for 2 vectors in radians mode.'''
angle = acos(self.inner(V) / (self.norm() * V.norm()))
return degrees(angle)
def prodvect(self, V):
''' Find out the vectorial product between two vectors'''
if len(self) > 3 or len(V) > 3 or len(self) != len(V):
raise IndexError('Sorry, two vectors must be 3D dimmensional.')
else:
e1 = Vector(1, 0, 0)
e2 = Vector(0, 1, 0)
e3 = Vector(0, 0, 1)
det1 = self[1] * V[2] - self[2] * V[1]
det2 = self[0] * V[2] - self[2] * V[0]
det3 = self[0] * V[1] - self[1] * V[0]
prodv = det1 * e1 - det2 * e2 + det3 * e3
return prodv
def areaparal(self, V):
'''Find out the area of a paralelogram from 2 vectors'''
return (self.prodvect(V)).norm()
def normalprodvect(self, V):
''' Find out n = (a x b) / |a x b|, normal unit vector to the plane.'''
return self.prodvect(V) / (self.prodvect(V)).norm()
def prodmixt(self, V, W):
''' Find out the mixt product between three vectors'''
if len(self) > 3 or len(V) > 3 or len(W) > 3 or len(self) != len(V)\
or len(self) != len(W) or len(V) != len(W):
raise IndexError('Sorry, three vectors must be 3D dimmensional.')
else:
det1 = V[1] * W[2] - V[2] * W[1]
det2 = V[0] * W[2] - V[2] * W[0]
det3 = V[0] * W[1] - V[1] * W[0]
prodm = det1 * self[0] - det2 * self[1] + det3 * self[2]
return prodm
def volparal(self, V, W):
'''Find out the paral.lepiped from three vectors'''
return abs(self.prodmixt(V, W))
def translate(self, t):
''' Find out the transalation vector t units.'''
V = list(self)
for i in range(0, len(V)):
V[i] += t
return Vector(*V)
def rot2d(self, deg):
''' Find out the rotated vector a certain number of degrees in 2D.'''
if len(self) != 2:
raise IndexError('Sorry, vector must be 2D dimmensional.')
else:
rad = radians(deg)
rot1 = Vector(cos(rad), -sin(rad))
rot2 = Vector(sin(rad), cos(rad))
p1 = rot1.inner(self)
p2 = rot2.inner(self)
rotated = Vector(p1, p2)
return rotated
def rot3d(self, N, deg):
''' Find out the rotated vector a certain number of degrees in 3D.'''
if len(self) != 3:
raise IndexError('Sorry, vector must be 3D dimmensional.')
else:
rad = radians(deg)
c11 = (1 - N[0] ** 2) * cos(rad) + N[0] ** 2
c12 = -N[0] * N[1] * cos(rad) - N[2] * sin(rad)
c13 = -N[0] * N[2] * cos(rad) + N[1] * sin(rad)
rot1 = Vector(c11, c12, c13)
c21 = -N[0] * N[1] * cos(rad) + N[2] * sin(rad)
c22 = (1 - N[1] ** 2) * cos(rad) + N[1] ** 2
c23 = -N[1] * N[2] * cos(rad) - N[0] * sin(rad)
rot2 = Vector(c21, c22, c23)
c31 = -N[0] * N[2] * cos(rad) - N[1] * sin(rad)
c32 = -N[1] * N[2] * cos(rad) + N[0] * sin(rad)
c33 = (1 - N[2] ** 2) * cos(rad) + N[2] ** 2
rot3 = Vector(c31, c32, c33)
p1 = rot1.inner(self)
p2 = rot2.inner(self)
p3 = rot3.inner(self)
rotated = Vector(p1, p2, p3)
return rotated
def rect2pol(self):
''' Converts rectangular coordinates in a 2D vector to polar
oordinates in radians way.'''
if len(self) != 2:
raise ValueError("The vector must be a 2D.")
else:
self0 = hypot(self[0], self[1])
if self[0] == 0.:
raise ZeroDivision("Error division, the denominator is zero.")
else:
self1 = atan2(self[1], self[0])
return Vector(self0, self1)
def rect2poldeg(self):
''' Converts rectangular coordinates in a 2D vector to polar
coordinates in sexagesimal degrees way.'''
V = self.rect2pol()
V0 = V[0]
V1 = degrees(V[1])
return Vector(V0, V1)
def pol2rect(self):
''' Converts polar coordinates in a 2D vector to rectangular
coordinates in radians way.'''
if len(self) != 2:
raise ValueError("The vector must be a 2D.")
else:
if self[0] < 0.:
raise ValueError("The radius must be positive.")
else:
self0 = self[0] * cos(self[1])
self1 = self[0] * sin(self[1])
return Vector(self0, self1)
def pol2rectdeg(self):
''' Converts rectangular coordinates in a 2D vector to polar
coordinates in sexagesimal degrees way.'''
if len(self) != 2:
raise ValueError("The vector must be a 2D.")
else:
if self[0] < 0.:
raise ValueError("The radius must be positive.")
else:
self0 = self[0] * cos(radians(self[1]))
self1 = self[0] * sin(radians(self[1]))
return Vector(self0, self1)
def rect2cyl(self):
''' Converts rectangular coordinates in a 3D vector to cylindrical
coordinates in radians way.'''
if len(self) != 3:
raise ValueError("The vector must be a 3D.")
else:
V = Vector(self[0], self[1])
W = V.rect2pol()
return Vector(W[0], W[1], self[2])
def rect2cyldeg(self):
''' Converts rectangular coordinates in a 3D vector to cylindrical
coordinates in sexagesimal degrees way.'''
if len(self) != 3:
raise ValueError("The vector must be a 3D.")
else:
V = Vector(self[0], self[1])
W = V.rect2poldeg()
return Vector(W[0], W[1], self[2])
def cyl2rect(self):
''' Converts cylindrical coordinates in a 3D vector to rectangular
coordinates in radians way.'''
if len(self) != 3:
raise ValueError("The vector must be a 3D.")
else:
V = Vector(self[0], self[1])
W = V.pol2rect()
return Vector(W[0], W[1], self[2])
def cyl2rectdeg(self):
''' Converts cylindrical coordinates in a 3D vector to rectangular
coordinates in sexagesimal degrees way.'''
if len(self) != 3:
raise ValueError("The vector must be a 3D.")
else:
V = Vector(self[0], self[1])
W = V.pol2rectdeg()
return Vector(W[0], W[1], self[2])
def rect2sph(self):
''' Converts rectangular coordinates in a 3D vector to spherical
coordinates in radians way.'''
if len(self) != 3:
raise ValueError("The vector must be a 3D.")
else:
self0 = sqrt(pow(self[0], 2.) +
pow(self[1], 2.) + pow(self[2], 2.))
self1 = atan2(sqrt(pow(self[0], 2.) + pow(self[1], 2.)), self[2])
self2 = atan2(self[1], self[0])
return Vector(self0, self1, self2)
def rect2sphdeg(self):
''' Converts rectangular coordinates in a 3D vector to spherical
coordinates in sexagesimal degrees way.'''
if len(self) != 3:
raise ValueError("The vector must be a 3D.")
else:
V = self.rect2sph()
return Vector(V[0], degrees(V[1]), degrees(V[2]))
def sph2rect(self):
''' Converts spherical coordinates in a 3D vector to rectangular
coordinates in radians way.'''
if len(self) != 3:
raise IndexError('The vector must be 3D.')
if self[0] < 0:
raise ValueError('The radius must be positive.')
else:
self0 = self[0] * sin(self[1]) * cos(self[2])
self1 = self[0] * sin(self[1]) * sin(self[2])
self2 = self[0] * cos(self[1])
return Vector(self0, self1, self2)
def sph2rectdeg(self):
''' Converts spherical coordinates in a 3D vector to rectangular
coordinates in sexagesimal degrees way.'''
if len(self) != 3:
raise IndexError('The vector must be 3D.')
if self[0] < 0:
raise ValueError('The radius must be positive.')
else:
self0 = self[0] * sin(radians(self[1])) * cos(radians(self[2]))
self1 = self[0] * sin(radians(self[1])) * sin(radians(self[2]))
self2 = self[0] * cos(radians(self[1]))
return Vector(self0, self1, self2)
def cyl2sph(self):
''' Converts cylindrical coordinates in a 3D vector to spherical
coordinates.'''
if len(self) != 3:
raise IndexError('The vector must be 3D.')
if self[0] < 0:
raise ValueError('The radius must be positive.')
else:
self0 = sqrt(pow(self[0], 2.) + pow(self[2], 2.))
self1 = atan2(self[0], self[2])
self2 = self[1]
return Vector(self0, self1, self2)
def sph2cyl(self):
''' Converts spherical coordinates in a 3D vector to cylindrical
coordinates.'''
if len(self) != 3:
raise IndexError('The vector must be 3D.')
if self[0] < 0:
raise ValueError('The radius must be positive.')
else:
self0 = self[0] * sin(self[1])
self1 = self[2]
self2 = self[0] * cos(self[1])
return Vector(self0, self1, self2)
def sph2cyldeg(self):
''' Converts spherical coordinates in a 3D vector to cylindrical
coordinates in sexagesimal degrees way.'''
if len(self) != 3:
raise IndexError('The vector must be 3D.')
if self[0] < 0:
raise ValueError('The radius must be positive.')
else:
self0 = self[0] * sin(radians(self[1]))
self1 = self[2]
self2 = self[0] * cos(radians(self[1]))
return Vector(self0, self1, self2)
All the code is here in git. You are welcome to contribute patches to the repository.
|
You should use one table for this, unless you need more stringent constraints.
Each area has the same number of rows and the same number of seats per row.
Let's say there are 5 rows in every area, and 6 seats in every row. You'd want to use something along these lines.
create table seats (
area char(1) not null check (area in ('A', 'B', 'C', 'D')),
row integer not null check ( row between 1 and 5 ),
seat integer not null check ( seat between 1 and 6 ),
primary key (area, row, seat)
);
To select a single seat, put three values in the WHERE clause.
select *
from seats
where area = 'A' and
row = 1 and
seat = 2;
To use a table like this to model seat reservations, populate it with every possible area, row, and seat. Then set a foreign key reference to it.
create table reservations (
performance_time datetime not null,
party_name varchar(40) not null,
area char(1) not null,
row integer not null,
seat integer not null,
primary key (performance_time, party_name, area, row, seat),
foreign key (area, row, seat) references seats (area, row, seat)
);
You can see all the seating for a performance with this query.
select s.area, s.row, s.seat, r.performance_time, r.party_name
from seats s
left join reservations r
on r.area = s.area and
r.row = s.row and
r.seat = s.seat and
r.performance_time = '2013-04-30 08:00 pm'
And you can get all the available seats for a performance with something along these lines.
with seating as (
select s.area, s.row, s.seat, r.performance_time, r.party_name
from seats s
left join reservations r
on r.area = s.area and
r.row = s.row and
r.seat = s.seat and
r.performance_time = '2013-04-30 08:00 pm'
)
select *
from seating
where performance_time is null
By default, SQL Server will create a clustered index for a primary key constraint. You'll want to give careful thought to the order of columns in your primary key constraints, and consider adding other indexes as well. (Especially since your outputs will often need to be ordered by area, row, and seat.)
|
Ras'
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
Hors ligne
ljere
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
voici le code
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# auteur Gabriel Pettier
# license GPL V3 or later
# sert uniquement a compter les points sur ce topic :http://forum.ubuntu-fr.org/viewtopic.php?pid=938704
# et donc probablement inutile a quiquonque vu que mon serveur se charge de le lancer tous les matins
# publié a seul but de vérification par les interressés. ;), peut aussi servir si mon serveur n'est plus là
# pour assurer le service un jour.
# nécessite python 2.4 minimum, python-beautifulsoup et python-mechanize.
# le fichier '.compteur_logins' doit contenir le login du posteur sur la première ligne, et son mot de passe
# sur la deuxième (cela et seulement cela).
from BeautifulSoup import BeautifulSoup
import urllib2
import re
import time
import sys
import mechanize as ClientForm
import mechanize as ClientCookie
ignoreList = (
'compteur des leve tot',
)
class Day:
"""un jours dure de 5h à 9h du matin exclu ([5h:9h[) il contient la derniere entrée (points) de ce jour pour chaques joueurs"""
def __init__(self):
self.entries={}
def addEntry(self, entry):
#plus simple de faire un try except que de verifier que l'entrée existe. :/
try:
self.entries[entry.name] = max(self.entries[entry.name],entry.date.points())
except:
self.entries[entry.name] = entry.date.points()
def __str__(self):
for entry in self.entries.items():
print entry,'+',entries[entry]
def utcFrance():
return 1 + time.localtime(time.time())[-1] #1 + 1 si on est a l'heure d'été
class Date:
def __init__(self,tuple=(20,0),utc=utcFrance()):
self.h = (int(tuple[0])-utcFrance()+24+utc)%24
self.m = int(tuple[1])
def __cmp__(self, other):
return cmp(self.points(),other.points())
def points(self):
pts = {5: 10, 6: 6, 7: 3, 8: 1}
return pts.get(self.h, 0)
class Entry:
def __init__(self,name='',date=Date(),edit=Date()):
self.name = name
self.date = max(date,edit)
def setName(self, name):
self.name = name
def setDate(self, date):
if date.points()>self.date.points(): self.date = date
class Score:
def __init__(self, tuple):
self.name = tuple[1]
self.num = int(tuple[0])
def __gt__(self, other):
return self.num>other.num
def __str__(self):
return '%i %s' %(self.num, self.name)
def getPage(url, entries, stat, urlscore):
# essaye jusqu'a 15 fois de récupérer la page
for i in range(15):
try:
page = BeautifulSoup(urllib2.urlopen(url))
break
except:
print 'essai: %s' % i
if i==14: raise
time.sleep(60)
print 'page récupéré, travail en cours'
for post in page.findAll("div","blockpost rowodd blockpost1")+page.findAll("div","blockpost roweven")+page.findAll("div","blockpost rowodd"):
str_date = str(post.find("h2").find("span").find("a")).split('>')[1]
if (
(str_date.split(' ')[0] in ['Hier']
and int(str_date.split(' ')[2].split('<')[0].split(':')[0]) in range(5,24))
or (str_date.split(' ')[0] in ["Aujourd\'hui"]
and int(str_date.split(' ')[2].split('<')[0].split(':')[0]) in range(5))
):
urlscore = url
try:
entry = Entry(str(post.find("div","postleft").find("a")).split(">")[1].split("<")[0])
except:
entry = Entry(str(post.find("div","postleft").find("strong")).split(">")[1].split("<")[0])
utc=utcFrance()
#print entry.name
if 'GMT' in str(post):
try:
#print str(post).split("GMT")[-1]
utc = int(str(post).split("GMT")[-1].split(" ")[0].split("<")[0])
print 'GMT found',utc
except:
print "no good GMT!"
entry.setDate(Date(str_date.split(" ")[2].split("<")[0].split(":"),utc))
if str_date.split(" ")[2].split("<")[0].split(":")[0] not in stat:
stat[str_date.split(" ")[2].split("<")[0].split(":")[0]] = 1
else:
stat[str_date.split(" ")[2].split("<")[0].split(":")[0]] += 1
if post.find('p','postedit') is not None:
print "edit found"
try:
entry.setDate(Date(str(post.find("p","postedit").find("em")).split("Ã ")[1][1:6].split(":"),utc))
except:
print 'error ->'+str(str(post.find("p","postedit").find("em")).split("Ã "))
#on ne veut pas les points des pseudos dans ignoreList
if entry.name not in ignoreList and (entry.date.points() is not 0): entries.addEntry(entry)
# erreur si le topic fait moins d'une page de long,FIXME!
#result = int(url.split('p=')[1]) < int(str(page.findAll('a')[-7]).split('p=')[1].split('"')[0]) #en espérant que le nombre de liens en bas de page ne change pas! :/
if str(page.find('p','pagelink conl')).split('conl">')[1].split('</p')[0].split(str(page.find('p','pagelink conl').find('strong'))) == ['', '']:
result = False
else:
try:
result = int(url.split('p=')[1]) < int(str(page.find('p','pagelink conl').findAll('a')[-2]).split('p=')[1].split('"')[0])
except IndexError:
result = False
#FIXED!
if not result:
# on vérifie si le sujet est fermé, auquel cas on renvoie le dernier lien fourni sur la page
if "Discussion fermée" in ''.join( (str( i) for i in page.findAll('p','postlink conr'))):
print str(page.findAll('div','postmsg')[-1])
result = str(page.findAll('div','postmsg')[-1].findAll('a')[-1]).split('"')[1]
return result, urlscore
def renderstats(stats):
if stats != {}:
DayStats = {'00': 0, '01': 0, '02': 0, '03': 0, '04': 0, '05': 0, '06': 0, '07': 0, '08': 0, '09': 0, '10': 0, '11': 0, '12': 0, '13': 0, '14': 0, '15': 0, '16': 0, '17': 0, '18': 0, '19': 0, '20': 0, '21': 0, '22': 0, '23': 0}
DayStats.update(stats)
HoursBar = 'h|'.join(sorted(DayStats.keys()))+'h'
HoursBar = HoursBar[20:]+'|'+HoursBar[:19]
HoursBar = HoursBar[0:len(HoursBar)-1]
HoursPie = 'h|'.join(sorted(stats.keys()))+'h'
for k in stats.keys():
HoursPie = HoursPie.replace(k+'h', k+'h%20-%20'+k+'h59')
DataBar = ','.join([str(DayStats[x]) for x in sorted(DayStats.keys())])
DataBar = ','.join(DataBar.split(',')[5:24])+','+','.join(DataBar.split(',')[0:5])
Vmax10 = str(10*(int(max([DayStats[x] for x in DayStats.keys()]))/10+1))
urlimage='[img=Répartition]http://chart.apis.google.com/chart?chs=675x280&cht=p3&chco=d80020,d88000,ffd840,20d820,2080ff,101080,a020d8&chf=bg,s,00000000&chl='+HoursPie+'&chd=t:'+','.join([str(stats[x]) for x in sorted(stats.keys())])+'&chp=1.6&chtt=R%C3%A9partition%20des%20posts&chts=606060,16[/img]'
urlimage+='[img=Posts/heure]http://chart.apis.google.com/chart?chs=675x280&cht=bvs&chxt=x,y&chds=0,'+Vmax10+'&chxr=1,0,'+Vmax10+((Vmax10 == '30' and ',5') or '')+'&chf=b0,lg,0,803000,0,ffc080,1|bg,s,00000000&chxl=0:|'+HoursBar+'h'+'&chxp=0,0.7,4.9,9.1,13.2,17.3,21.5,25.6,29.8,33.9,38,42.2,46.3,50.5,54.6,58.8,62.9,67,71.2,75.3,79.4,83.6,87.7,91.8,96&chd=t:'+DataBar+'&chm=N,803000,0,-1,12&chtt=|Nombre%20de%20posts%20par%20heure&chts=606060,16[/img]'
return urlimage
return None
def post(_file, stats):
# le fichier '.compteur_logins' doit contenir le login du posteur sur la première ligne, et son mot de passe sur la deuxième (cela et seulement cela).
file = open(".compteur_logins","r")
login = file.readline().split('\n')[0]
password = file.readline().split('\n')[0]
file.close()
cookieJar = ClientCookie.CookieJar()
opener = ClientCookie.build_opener(ClientCookie.HTTPCookieProcessor(cookieJar))
opener.addheaders = [("User-agent","Mozilla/5.0 (compatible)")]
ClientCookie.install_opener(opener)
fp = ClientCookie.urlopen("http://forum.ubuntu-fr.org/login.php")
forms = ClientForm.ParseResponse(fp)
fp.close()
form = forms[1]
form["req_username"] = login
form["req_password"] = password
fp = ClientCookie.urlopen(form.click())
fp.close()
file = open('url','r')
tid = file.readline().split('=')[1][:-2] # la première ligne contenant l'addresse du topic.
file.close()
fp = ClientCookie.urlopen("http://forum.ubuntu-fr.org/post.php?tid="+tid)
forms = ClientForm.ParseResponse(fp)
fp.close()
print "http://forum.ubuntu-fr.org/post.php?tid="+tid
print forms[0]
form = forms[1]
title = (((_file == "count") and "Scores totaux, depuis le début") or "scores de la période en cours")
form["req_message"] = title+" :[ code]"+'\xe2\x80\xad'
file = open(_file, 'r')
scores=file.readlines()
urlimage = renderstats(stats)
stats = {}
for i in range(len(scores)):#on veut toutes les lignes restantes
if i == 0:
tmpRange = 0
elif scores[i].split(" ")[0] == scores[i-1].split(" ")[0]:
pass
else:
tmpRange = i
#et on ajoute la ligne avec le bon rang a l'entrée
form["req_message"] += (
(('\xe2\x80\xae' in scores[i-1] and '\xe2\x80\xac') or '')+
(("Quelqu'un" in scores[i] and "*** champion des leves tot ***\n") or '')+
str(tmpRange+1)+
") "+scores[i]+
(("Quelqu'un" in scores[i]
and "******************************************************************************\n") or '')
)
form["req_message"] += "[ /code]"+(urlimage or '')
fp = ClientCookie.urlopen(form.click())
fp.close()
def main(urlfile, files):
debug = False
stats = {}
f=open(urlfile,"r")
url=urlscore=f.readline().split('\n')[0]
f.close()
entries = Day()
while True:
print "lecture de la page "+url
res = getPage(url, entries, stats, urlscore)
urlscore = res[1]
if not res[0]: break
url=url.split('p=')[0]+'p='+str(1+int(url.split('p=')[1]))
if res[0] is not True:
url = url.split('?')[0]+'?'+res[0].split('?')[1]+'&p=1'
if not debug:
f=open(urlfile,"w")
f.write(urlscore+'\n')
f.close()
for file in files:
f=open(file,'r')
lines=(file=="count10days" and ((time.localtime()[2]==2 and ["0 "+entries.entries.keys()[0]+"\n"]) or f.readlines()) or f.readlines())
f.close()
exp = re.compile("^[0-9]+\s*")
scores = []
print "lecture scores courants"
for line in lines:
if line not in [' ','']:
scores.append(Score([(line.split(' ')[0]),exp.split(line)[1].split('\n')[0]]))
new_scores=[]
for entry,num in entries.entries.items():
for score in scores:
if entry.lower() == score.name.lower():
score.num+=num
break
if score is scores[-1]:
new_scores.append(Score([num,entry]))
break
scores+=new_scores
# vérification des doublons
for nScore in range(len(scores)-1):
for mScore in range(nScore+1,len(scores)-1):
try:
if scores[nScore].name.lower() == scores[mScore].name.lower():
scores[nScore].num+=scores[mScore].num
del(scores[mScore])
except:
pass
scores.sort(reverse=True)
if not debug:
for score in scores: print score
f=open(file, "w")
for score in scores: #print score
f.write('%s\n'%score)
f.close()
for i in range(15):
try:
post(file, stats)
stats = {}
break
except:
if i == 14: raise
time.sleep(60)
time.sleep(10)
main("url",["count","count10days"])
#post("count",{})
#post("count10days",{})
et l'erreur qui va avec
./Nouveau\ compteur.py
lecture de la page http://forum.ubuntu-fr.org/viewtopic.php?pid=9590061#p9590061
page récupéré, travail en cours
edit found
error ->['<em>Derni\xc3\xa8re modification par pierguiard (Hier \xc3\xa0 12:35)</em>']
lecture scores courants
Traceback (most recent call last):
File "./Nouveau compteur.py", line 304, in <module>
main("url",["count","count10days"])
File "./Nouveau compteur.py", line 264, in main
scores.append(Score([(line.split(' ')[0]),exp.split(line)[1].split('\n')[0]]))
IndexError: list index out of range
Hors ligne
Mindiell
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
Merci, je te dis ça dans la soirée (si j'ai le temps)
Hors ligne
raspouillas
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
Bonjour du bon matin ...
raspouillas
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
Je suis seul !
raspouillas
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
Non !
ps: Il faut bien que je dépasse @Rap' ...
Floyd Pepper
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
Bonjour
Vieux papy triste et Hétérocentriste (conditionné), en attente d'être complètement con×. J'aurais tendance à ne pas utiliser de smilleys.
Le plus tu t'fais chier, le plus t'es emmerdé.
Hors ligne
ljere
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
hello tout le monde
Hors ligne
PPdM
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
Salut
Le réel ne peut s'exprimer que par l'absurde.
Hors ligne
Ras'
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
!!
Hors ligne
Mindiell
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
Coucou
Hors ligne
souen
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
Salut!!! (connexion en panne ce matin)
Hors ligne
souen
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
L'absurde ne peut s'exprimer que par le réel.
Hors ligne
Mindiell
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
réel a écrit :absurde a écrit :
...
...
...
A ce train là, on est mal barré !
Hors ligne
Floyd Pepper
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
Ça c'est reel
1 1769 FloydPepper
2 1530 pierguiard
3 1463 MdMax
4 1247 Azurea
5 1192 souen
6 952 Ras'
7 750 raspouillas
8 552 Arcans
9 428 peterp@n
10 359 golgoth42
11 281 mindiell
12 277 omc
13 219 Πυλάδης
14 176 pololasi
15 117 edge_one
16 101 nathéo
17 99 karameloneboudeplus
18 61 agarwood
19 60 Niltugor
20 52 1101011
20 52 jeyenkil
22 43 Crocoii
23 42 nakraïou
23 42 DaveNull
25 40 Biaise
26 39 Clem_ufo
27 38 Atem18
28 34 ljere
29 22 marinmarais
30 18 Ju
31 13 Le grand rohr sha
32 10 Phoenix
32 10 FLOZz
32 10 sakul
32 10 SopolesRâ
36 6 wiscot
36 6 timsy
36 6 Slystone
36 6 Hibou57
36 6 tshirtman
36 6 marting
36 6 c4nuser
43 4 Morgiver
43 4 :!pakman
45 3 Phoenamandre
45 3 gonzolero
45 3 helly
45 3 Le Rouge
49 1 herewegoagain
49 1 TheUploader
49 1 Kyansaa
49 1 Xiti29
Mais en y regardant de près, c'est absurde !
Edit: @ljere
J'ai vu ton intervention sur le TdcT, je pense que ton idée première est la bonne, pour voir j'aimerais bien que tu relance ton cpt pour vérification, des points et des places. Et comme l'a dit papy si il y a un problème avec un de ses post creuse plutôt par là. Enfin je dis ça je dis rien, le codage en py je connais pas …
Dernière modification par Floyd Pepper (Le 13/06/2012, à 20:27)
Vieux papy triste et Hétérocentriste (conditionné), en attente d'être complètement con×. J'aurais tendance à ne pas utiliser de smilleys.
Le plus tu t'fais chier, le plus t'es emmerdé.
Hors ligne
souen
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
Mais en y regardant de près, c'est absurde !
...mais le réel est absurde!!!
Hors ligne
ljere
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
comme je l'avais dit à pierguiard l'erreur ne vient pas de son édition de poste c'est le comportement normal du script, l'erreur se produit après
scores.append(Score([(line.split(' ')[0]),exp.split(line)[1].split('\n')[0]]))
IndexError: list index out of range
Hors ligne
souen
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
Une dernière pour la route...
Le sens de la vie, c’est ce qui reste quand on se débarrasse de tout ce qui est absurde.
Hors ligne
PPdM
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
@Floyd Papy
c'est pépé pas papy nanmais ho!
Hors ligne
Floyd Pepper
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
De peur de dire une grosse connerie je ne peux que m'en remettre à toi, mais cette erreur n'empêchait pas ton compteur de compter juste, non ?
Vieux papy triste et Hétérocentriste (conditionné), en attente d'être complètement con×. J'aurais tendance à ne pas utiliser de smilleys.
Le plus tu t'fais chier, le plus t'es emmerdé.
Hors ligne
Floyd Pepper
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
@Floyd Papy
c'est pépé pas papy nanmais ho!
Ah ouai, ça c'est vrai, mille excuses, j'avais oublié que le papy c'était moi.
Dédoublement inverse de la personnalité, ça devient critique …
Vieux papy triste et Hétérocentriste (conditionné), en attente d'être complètement con×. J'aurais tendance à ne pas utiliser de smilleys.
Le plus tu t'fais chier, le plus t'es emmerdé.
Hors ligne
ljere
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
ah non ce n'est pas ce compteur la que j'avais testé c'est un script qui n'est pas du tout automatisé (d’où les erreurs lors du premier essai)solution non viable pour ce topic
Hors ligne
raspouillas
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
Qui est le plus vieux dans le forum Ubuntu ?
Ras'
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
Y'avait un topic là dessus j'crois...
Hors ligne
raspouillas
Re : Topic des lève-tôt… Faisons manger leurs caleçons aux couche-tard! [4]
boujour ...
|
LOG:
====
Jul 5 10:03:22 SWH-iRed-1 amavis[1853]: (01853-01) Passed CLEAN, <websupport@atlantic.net> -> <mailman-subscribe@lists.sensusplenoir.com>, Message-ID: <51d6e01b.TLq2r6xMGZdBrWGe%websupport@atlantic.net>, mail_id: ox3SqxCSbfs5, Hits: 0.011, size: 316845, queued_as: C974940D08, 30507 ms
Jul 5 10:03:23 SWH-iRed-1 postfix/smtp[2082]: 356C040CF8: to=<mailman-subscribe@lists.sensusplenoir.com>, relay=127.0.0.1[127.0.0.1]:10024, delay=31, delays=0.38/0.05/0.02/31, dsn=2.0.0, status=sent (250 2.0.0 from MTA([127.0.0.1]:10025): 250 2.0.0 Ok: queued as C974940D08)
Jul 5 10:03:23 SWH-iRed-1 postfix/qmgr[1689]: 356C040CF8: removed
Jul 5 10:03:23 SWH-iRed-1 postfix/error[2104]: C974940D08: to=<mailman-subscribe@lists.sensusplenoir.com>, relay=none, delay=0.47, delays=0.14/0.08/0/0.25, dsn=4.3.0, status=deferred (mail transport unavailable)
Jul 5 10:03:23 SWH-iRed-1 postfix/qmgr[1689]: C974940D08: from=<websupport@atlantic.net>, size=317397, nrcpt=1 (queue active)
Jul 5 10:03:23 SWH-iRed-1 postfix/error[2104]: C974940D08: to=<mailman-subscribe@lists.sensusplenoir.com>, relay=none, delay=0.59, delays=0.51/0/0/0.08, dsn=4.3.0, status=deferred (mail transport unavailable)
Additions to /etc/postfix/main.cf(test domain is sensusplenoir.com)
===========================================================
relay_domains = lists.sensusplenoir.com, $mydestination, proxy:mysql:/etc/postfix/mysql/relay_domains.cf
mailman_destination_recipient_limit = 1
And created the database entries as needed:
INSERT INTO `vmail`.`domain` (`domain`, `description`, `disclaimer`, `aliases`, `mailboxes`, `maxquota`, `quota`, `transport`, `backupmx`, `defaultuserquota`, `defaultuseraliases`, `defaultpasswordscheme`, `minpasswordlength`, `maxpasswordlength`, `created`, `modified`, `expired`, `active`) VALUES ('lists.sensusplenoir.com', '', '', '0', '0', '0', '0', 'mailman:', '0', '1024', '', '', '0', '0', NOW(), '0000-00-00 00:00:00', '9999-12-31 00:00:00', '1');
INSERT INTO `alias` (`address`, `goto`, `name`, `moderators`, `accesspolicy`, `domain`, `created`, `modified`, `expired`, `active`) VALUES
('listname@sensusplenoir.com', 'listname@lists.sensusplenoir.com', '', '', 'public', 'sensusplenoir.com', NOW(), NOW(), '9999-12-31 00:00:00', 1),
('listname-admin@sensusplenoir.com', 'listname-admin@lists.sensusplenoir.com', '', '', 'public', 'sensusplenoir.com', NOW(), NOW(), '9999-12-31 00:00:00', 1),
('listname-bounces@sensusplenoir.com', 'listname-bounces@lists.sensusplenoir.com', '', '', 'public', 'sensusplenoir.com', NOW(), NOW(), '9999-12-31 00:00:00', 1),
('listname-confirm@sensusplenoir.com', 'listname-confirm@lists.sensusplenoir.com', '', '', 'public', 'sensusplenoir.com', NOW(), NOW(), '9999-12-31 00:00:00', 1),
('listname-join@sensusplenoir.com', 'listname-join@lists.sensusplenoir.com', '', '', 'public', 'sensusplenoir.com', NOW(), NOW(), '9999-12-31 00:00:00', 1),
('listname-leave@sensusplenoir.com', 'listname-leave@lists.sensusplenoir.com', '', '', 'public', 'sensusplenoir.com', NOW(), NOW(), '9999-12-31 00:00:00', 1),
('listname-owner@sensusplenoir.com', 'listname-owner@lists.sensusplenoir.com', '', '', 'public', 'sensusplenoir.com', NOW(), NOW(), '9999-12-31 00:00:00', 1),
('listname-requests@sensusplenoir.com', 'listname-requests@lists.sensusplenoir.com', '', '', 'public', 'sensusplenoir.com', NOW(), NOW(), '9999-12-31 00:00:00', 1),
('listname-subscribe@sensusplenoir.com', 'listname-subscribe@lists.sensusplenoir.com', '', '', 'public', 'sensusplenoir.com', NOW(), NOW(), '9999-12-31 00:00:00', 1),
('listname-unsubscribe@sensusplenoir.com', 'listname-unsubscribe@lists.sensusplenoir.com', '', '', 'public', 'sensusplenoir.com', NOW(), NOW(), '9999-12-31 00:00:00', 1);
from socket import *
try:
fqdn = getfqdn()
except:
fqdn = 'mm_cfg_has_unknown_host_domains'
DEFAULT_URL_HOST = fqdn
DEFAULT_EMAIL_HOST = fqdn
# Because we've overriden the virtual hosts above add_virtualhost
# MUST be called after they have been defined.
add_virtualhost(DEFAULT_URL_HOST, DEFAULT_EMAIL_HOST)
##############################################################
# Put YOUR site-specific configuration below, in mm_cfg.py . #
# See Defaults.py for explanations of the values. #
# ksmemekddNote - if you're looking for something that is imported from mm_cfg, but you
# didn't find it above, it's probably in Defaults.py.
MTA = 'Postfix'
I'm a bit unsure of the mailmain config above, as we have several different domains that well be using these mailing lists so i left it at fqdn.
I skipped the html setup for now. I figure I'd leave that for when I get the mailing lists up first.
The domain is a demo domain only for development only...just an fyi in case someone is wondering why i used a real domain.
|
leYB
Re : lexmark x2670
Que dit :
ls -l /usr/local/lexmark/lxk08/bin/printdriver
-rwxr-xr-x 1 root bin 63851 2008-11-06 09:47 /usr/local/lexmark/lxk08/bin/printdriver
Hors ligne
leYB
Re : lexmark x2670
En changeant le groupe c'est toujours pareil?
sudo chgrp root /usr/local/lexmark/lxk08/bin/printdriver
Cela donne:
~$ sudo chgrp root /usr/local/lexmark/lxk08/bin/printdriver
Je vérifie les droits et permissions ensuite:
~$ ls -l /usr/local/lexmark/lxk08/bin/printdriver
-rwxr-xr-x 1 root root 63851 2008-11-06 09:47 /usr/local/lexmark/lxk08/bin/printdriver
J'ai testé la réimpression et c'est toujours impossible comme on peut voir dans /var/log/cups/error_log:
E [29/Jan/2012:11:30:27 +0100] -2600-Series: Directory "/usr/local/lexmark/lxk08/bin" has insecure permissions (040775/uid=0/gid=2).
E [29/Jan/2012:11:30:27 +0100] [Job 6] Unable to start filter "/usr/local/lexmark/lxk08/bin/printdriver" - Success.
E [29/Jan/2012:11:30:27 +0100] [Job 6] Stopping job because the scheduler could not execute a filter.
Dernière modification par leYB (Le 29/01/2012, à 12:39)
Hors ligne
demonipuch
Re : lexmark x2670
Directory "/usr/local/lexmark/lxk08/bin" has insecure permissions (040775/uid=0/gid=2).
Il faudrait peut-être modifier aussi les permissions du dossier :
chmod 755 /usr/local/lexmark/lxk08/bin
voire
chmod -R 755 /usr/local/lexmark/lxk08/bin
pour modifier les permissions du dossier et de son contenu.
Si ca ne marche toujours pas alors je n'ai pas d'autres idées... Contactez le support de Lexmark peut-être
Hors ligne
leYB
Re : lexmark x2670
Directory "/usr/local/lexmark/lxk08/bin" has insecure permissions (040775/uid=0/gid=2).
Il faudrait peut-être modifier aussi les permissions du dossier :
chmod 755 /usr/local/lexmark/lxk08/bin
voire
chmod -R 755 /usr/local/lexmark/lxk08/bin
pour modifier les permissions du dossier et de son contenu.
Si ca ne marche toujours pas alors je n'ai pas d'autres idées... Contactez le support de Lexmark peut-être
Ton aide a permis de résoudre la moitié des problèmes, puisque un nouveau est apparu.
Grâce à toi, je n'ai plus de messages de type "problème de filtre: driver insécurisé" et je t'en remercie!
Mais notre ennemi Lexmark a plus d'un tour dans son sac puisque maintenant que les droits sont valides: j'ai droit à un nouveau message familier lui aussi des "Lexmarkiens" sous 11.10: "The printer cannot communicate with the computer"
Extrait de var/log/cups/error_log: (à scroller pour en voir l'entièreté)
D [29/Jan/2012:15:04:07 +0100] [Job 8] Job restarted by user.
D [29/Jan/2012:15:04:07 +0100] [Job 8] job-sheets=none,none
D [29/Jan/2012:15:04:07 +0100] [Job 8] argv[0]="Lexmark_2600_Series"
D [29/Jan/2012:15:04:07 +0100] [Job 8] argv[1]="8"
D [29/Jan/2012:15:04:07 +0100] [Job 8] argv[2]="yannis"
D [29/Jan/2012:15:04:07 +0100] [Job 8] argv[3]="Page de test"
D [29/Jan/2012:15:04:07 +0100] [Job 8] argv[4]="1"
D [29/Jan/2012:15:04:07 +0100] [Job 8] argv[5]="job-uuid=urn:uuid:4cc0d717-ac13-30ca-72ce-7e3b92dabedd job-originating-host-name=localhost time-at-creation=1327845358 time-at-processing=1327845801 AP_D_InputSlot="
D [29/Jan/2012:15:04:07 +0100] [Job 8] argv[6]="/var/spool/cups/d00008-001"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[0]="CUPS_CACHEDIR=/var/cache/cups"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[1]="CUPS_DATADIR=/usr/share/cups"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[2]="CUPS_DOCROOT=/usr/share/cups/doc-root"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[3]="CUPS_FONTPATH=/usr/share/cups/fonts"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[4]="CUPS_REQUESTROOT=/var/spool/cups"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[5]="CUPS_SERVERBIN=/usr/lib/cups"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[6]="CUPS_SERVERROOT=/etc/cups"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[7]="CUPS_STATEDIR=/var/run/cups"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[8]="HOME=/var/spool/cups/tmp"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[9]="PATH=/usr/lib/cups/filter:/usr/bin:/usr/sbin:/bin:/usr/bin"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[10]="SERVER_ADMIN=root@PCY"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[11]="SOFTWARE=CUPS/1.5.0"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[12]="TMPDIR=/var/spool/cups/tmp"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[13]="USER=root"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[14]="CUPS_SERVER=/var/run/cups/cups.sock"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[15]="CUPS_ENCRYPTION=IfRequested"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[16]="IPP_PORT=631"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[17]="CHARSET=utf-8"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[18]="LANG=fr_FR.UTF-8"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[19]="PPD=/etc/cups/ppd/Lexmark_2600_Series.ppd"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[20]="RIP_MAX_CACHE=128m"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[21]="CONTENT_TYPE=application/vnd.cups-banner"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[22]="DEVICE_URI=usb://Lexmark/2600%20Series?serial=3053730C5917301&interface=1"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[23]="PRINTER_INFO=Lexmark 2600 Series"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[24]="PRINTER_LOCATION="
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[25]="PRINTER=Lexmark_2600_Series"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[26]="PRINTER_STATE_REASONS=none"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[27]="CUPS_FILETYPE=document"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[28]="FINAL_CONTENT_TYPE=printer/Lexmark_2600_Series"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[29]="AUTH_I****"
D [29/Jan/2012:15:04:07 +0100] [Job 8] Started filter /usr/lib/cups/filter/bannertops (PID 11762)
D [29/Jan/2012:15:04:07 +0100] [Job 8] Started filter /usr/lib/cups/filter/pstopdf (PID 11763)
D [29/Jan/2012:15:04:07 +0100] [Job 8] Started filter /usr/lib/cups/filter/pdftopdf (PID 11764)
D [29/Jan/2012:15:04:07 +0100] [Job 8] Started filter /usr/lib/cups/filter/gstoraster (PID 11765)
D [29/Jan/2012:15:04:07 +0100] [Job 8] Started filter /usr/local/lexmark/lxk08/bin/printdriver (PID 11767)
D [29/Jan/2012:15:04:07 +0100] [Job 8] Started backend /usr/lib/cups/backend/usb (PID 11768)
D [29/Jan/2012:15:04:07 +0100] [Job 8] Restarted by "yannis".
D [29/Jan/2012:15:04:07 +0100] [Job 8] pstopdf 5 args: 8 yannis Page de test 1 job-uuid=urn:uuid:4cc0d717-ac13-30ca-72ce-7e3b92dabedd job-originating-host-name=localhost time-at-creation=1327845358 time-at-processing=1327845801 AP_D_InputSlot=
D [29/Jan/2012:15:04:07 +0100] [Job 8] PPD: /etc/cups/ppd/Lexmark_2600_Series.ppd
D [29/Jan/2012:15:04:07 +0100] [Job 8] load_banner(filename="/var/spool/cups/d00008-001")
D [29/Jan/2012:15:04:07 +0100] [Job 8] 1 #CUPS-BANNER
D [29/Jan/2012:15:04:07 +0100] [Job 8] 2 Show printer-name printer-info printer-location printer-make-and-model printer-driver-name printer-driver-version paper-size imageable-area
D [29/Jan/2012:15:04:07 +0100] [Job 8] 3 Header Printer Test Page
D [29/Jan/2012:15:04:07 +0100] [Job 8] 4 Footer Printer Test Page
D [29/Jan/2012:15:04:07 +0100] [Job 8] 5 Notice CUPS 1.5.0.
D [29/Jan/2012:15:04:07 +0100] [Job 8] 6 Image images/cups.png
D [29/Jan/2012:15:04:07 +0100] [Job 8] 7 Image images/color-wheel.png
D [29/Jan/2012:15:04:07 +0100] [Job 8] Page = 595x842; 10,36 to 586,837
D [29/Jan/2012:15:04:07 +0100] [Job 8] print_device
D [29/Jan/2012:15:04:07 +0100] [Job 8] usb_find_busses=7
D [29/Jan/2012:15:04:07 +0100] [Job 8] PNG image: 128x128x8, color_type=6 (RGB+ALPHA)
D [29/Jan/2012:15:04:07 +0100] [Job 8] PNG image: 192x128x8, color_type=2 (RGB)
D [29/Jan/2012:15:04:07 +0100] [Job 8] Resolution:
D [29/Jan/2012:15:04:07 +0100] [Job 8] Page size: A4
D [29/Jan/2012:15:04:07 +0100] [Job 8] Width: 595.20, height: 841.80, absolute margins: 9.60, 36.00, 585.60, 837.00
D [29/Jan/2012:15:04:07 +0100] [Job 8] Relative margins: 9.60, 36.00, 9.60, 4.80
D [29/Jan/2012:15:04:07 +0100] [Job 8] PPD options: -dDEVICEWIDTHPOINTS=595.20 -dDEVICEHEIGHTPOINTS=841.80
D [29/Jan/2012:15:04:07 +0100] [Job 8] PostScript to be injected:
D [29/Jan/2012:15:04:07 +0100] [Job 8] Running cat | /usr/bin/gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dCompatibilityLevel=1.3 -dAutoRotatePages=/None -dAutoFilterColorImages=false -dNOPLATFONTS -dPARANOIDSAFER -dNOINTERPOLATE -sstdout=%stderr -dColorImageFilter=/FlateEncode -dPDFSETTINGS=/printer -dColorConversionStrategy=/LeaveColorUnchanged -dDoNumCopies -dDEVICEWIDTHPOINTS=595.20 -dDEVICEHEIGHTPOINTS=841.80 -sOutputFile=- -c .setpdfwrite -f -
D [29/Jan/2012:15:04:07 +0100] [Job 8] usb_find_devices=13
D [29/Jan/2012:15:04:07 +0100] [Job 8] STATE: +connecting-to-device
D [29/Jan/2012:15:04:07 +0100] [Job 8] STATE: -connecting-to-device
D [29/Jan/2012:15:04:07 +0100] [Job 8] PPD uses qualifier 'Color.Plain.'
D [29/Jan/2012:15:04:07 +0100] [Job 8] Calling FindDeviceById(Lexmark_2600_Series)
D [29/Jan/2012:15:04:07 +0100] [Job 8] Failed to send: org.freedesktop.DBus.Error.AccessDenied:Rejected send message, 1 matched rules; type="method_call", sender=":1.197" (uid=7 pid=11765 comm="Lexmark_2600_Series 8 yannis Page de test 1 job-uu") interface="org.freedesktop.ColorManager" member="FindDeviceById" error name="(unset)" requested_reply="0" destination="org.freedesktop.ColorManager" (uid=102 pid=996 comm="/usr/lib/i386-linux-gnu/colord/colord ")
D [29/Jan/2012:15:04:07 +0100] [Job 8] Failed to get profile filename!
D [29/Jan/2012:15:04:07 +0100] [Job 8] no profiles specified in PPD
D [29/Jan/2012:15:04:07 +0100] [Job 8] Set job-printer-state-message to "no profiles specified in PPD", current level=INFO
D [29/Jan/2012:15:04:07 +0100] [Job 8] Ghostscript command line: /usr/bin/gs -dQUIET -dPARANOIDSAFER -dNOPAUSE -dBATCH -dNOINTERPOLATE -sDEVICE=cups -sstdout=%stderr -sOutputFile=%stdout -sOutputType=2 -r600x600 -dDEVICEWIDTHPOINTS=595 -dDEVICEHEIGHTPOINTS=841 -dcupsMediaType=1 -dcupsBitsPerColor=8 -dcupsColorOrder=0 -dcupsColorSpace=1 -dcupsCompression=8 -dcupsRowStep=1 -scupsPageSizeName=A4 -I/usr/share/cups/fonts -c -f -_
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[0]="CUPS_CACHEDIR=/var/cache/cups"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[1]="CUPS_DATADIR=/usr/share/cups"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[2]="CUPS_DOCROOT=/usr/share/cups/doc-root"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[3]="CUPS_FONTPATH=/usr/share/cups/fonts"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[4]="CUPS_REQUESTROOT=/var/spool/cups"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[5]="CUPS_SERVERBIN=/usr/lib/cups"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[6]="CUPS_SERVERROOT=/etc/cups"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[7]="CUPS_STATEDIR=/var/run/cups"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[8]="HOME=/var/spool/cups/tmp"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[9]="PATH=/usr/lib/cups/filter:/usr/bin:/usr/sbin:/bin:/usr/bin"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[10]="SERVER_ADMIN=root@PCY"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[11]="SOFTWARE=CUPS/1.5.0"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[12]="USER=root"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[13]="CUPS_SERVER=/var/run/cups/cups.sock"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[14]="CUPS_ENCRYPTION=IfRequested"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[15]="IPP_PORT=631"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[16]="CHARSET=utf-8"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[17]="LANG=fr_FR.UTF-8"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[18]="PPD=/etc/cups/ppd/Lexmark_2600_Series.ppd"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[19]="RIP_MAX_CACHE=128m"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[20]="CONTENT_TYPE=application/vnd.cups-banner"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[21]="DEVICE_URI=usb://Lexmark/2600%20Series?serial=3053730C5917301&interface=1"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[22]="PRINTER_INFO=Lexmark 2600 Series"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[23]="PRINTER_LOCATION="
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[24]="PRINTER=Lexmark_2600_Series"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[25]="PRINTER_STATE_REASONS=none"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[26]="CUPS_FILETYPE=document"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[27]="FINAL_CONTENT_TYPE=printer/Lexmark_2600_Series"
D [29/Jan/2012:15:04:07 +0100] [Job 8] envp[28]="AUTH_INFO_REQUIRED=none"
D [29/Jan/2012:15:04:07 +0100] [Job 8] Start rendering...
D [29/Jan/2012:15:04:07 +0100] [Job 8] Set job-printer-state-message to "Start rendering...", current level=INFO
D [29/Jan/2012:15:04:07 +0100] [Job 8] Processing page 1...
D [29/Jan/2012:15:04:07 +0100] [Job 8] Set job-printer-state-message to "Processing page 1...", current level=INFO
D [29/Jan/2012:15:04:07 +0100] [Job 8] Set job-printer-state-message to "The Printer cannot communicate with the computer.", current level=ERROR
D [29/Jan/2012:15:04:07 +0100] [Job 8] End of messages
D [29/Jan/2012:15:04:07 +0100] [Job 8] printer-state=3(idle)
D [29/Jan/2012:15:04:07 +0100] [Job 8] printer-state-message="The Printer cannot communicate with the computer."
D [29/Jan/2012:15:04:07 +0100] [Job 8] printer-state-reasons=none
J'ai bien vérifié sur CUPS, ma machine est reconnue et connectée, les câbles USB aussi, j'ai rebooté mon PC au cas où et voilà!
Si tu as d'autres pistes à explorer, je suis ton homme.
En attendant, je vais faire un mail salé à Lexmark Corp...
Hors ligne
leYB
Re : lexmark x2670
UP!
Toujours pas de réponse de lexmark depuis une semaine... Et vous, vous avez des idées?
Hors ligne
leYB
Re : lexmark x2670
Voilà, Lexmark a répondu... Voilà ce que j'ai reçu.
On ne peut faire plus clair et concis!
Utilisateurs Ubuntu, si vous voulez une imprimante Lexmark, PASSEZ VOTRE CHEMIN, Y'A RIEN À VOIR!!
"Demande reçue par e-mail le : 29.01.2012
Dossier n° : 1-7XXXXXXXX1
Madame, Monsieur,
Merci d’avoir contacté le support technique de Lexmark concernant votre imprimante Lexmark X2670 ayant le numéro de série 5XXXX01.
Nous tenons à vous informer que nous ne supportons pas le système d’exploitation Linux.
Si vous avez d’autres questions n’hésitez pas à contacter notre support technique par téléphone au :
Tél. : 01.55.17.41.69.
Fax : 01.55.69.57.63.
Du lundi au vendredi : 9h à 18h
Afin de vous répondre dans les meilleurs délais, Lexmark vous prie de ne modifier ni le sujet ni le contenu de l’e-mail original et de toujours répondre à la même adresse e-mail.
Veuillez répondre à cet e-mail en utilisant le bouton de réponse afin de sauvegarder notre correspondance antérieure.
Cordialement,
Sihame DAKHCH
Support Technique Lexmark
Tél : 01.55.17.41.69.
Fax : 01.55.69.57.63.
www.lexmark.fr
[THREAD ID:1-3JLRQW3]
**********Message d'origine**********
Bonjour,
Pour commencer, une précision: je suis sous système d'exploitation UBUNTU 11.10, dérivée de Debian. Ne trouvant pas Ubuntu dans votre liste, je me suis inscrit sous Debian/GNU. Les deux systèmes sont cousins mais pas totalement identiques, je vous prie de bien vouloir me préciser si vos réponses concernent Debian ou Ubuntu spécifiquement, et bien évidemment je souhaite qu'elles fonctionnent sous Ubuntu version 11.10.
Cela fait plusieurs fois que je "bidouille" pour me servir de la X2670 à cause de l'ancienneté du driver (en passant, inaccessible via la version française de votre site), vous serait-il donc possible de le mettre à jour en fonction des conditions actuelles de ce système d'exploitation afin de nous simplifier son utilisation?
Ubuntu est l'un des OS les plus répandus dans le monde quand même!!
Je suis vraiment mécontent de votre politique d'abandon de cet OS.Pourquoi agir de la sorte?
Cette fois-ci encore, je suis bloqué! Malgré mes recherches ainsi que celle de l'aide de la communauté Ubuntu,impossible de pouvoir utiliser l'imprimante et le scanner depuis mon passage à la version 11.10. La version actuelle de CUPS que j'utilise est la 1.5.pour votre information.
Après avoir difficilement résolu un problème de droits utilisateurs du driver qui m'empêchait de la faire fonctionner, je me retrouve maintenant avec un message qui indique que ma machine ne peut communiquer avec mon PC, alors que CUPS la détecte connectée, que le câble USB neuf l'est également et même après un reboot de mon PC.
Je me doute que vous ne mettrez pas à jour le driver dans la seconde, à défaut merci de me fournir des façons de faire fonctionner une X2670 sous Ubuntu 11.10 (imprimante ET scanner) pour que je puisse entraider à mon tour et ENFIN TRAVAILLER SANS PERDRE MON TEMPS.
Cordialement."
J'ai bien fait de commander une HP moi, ne voyant rien venir de la part de Lexmark!
Dernière modification par leYB (Le 10/02/2012, à 23:01)
Hors ligne
z0u
Re : lexmark x2670
hello, me revoilà (à nouveau...), les versions d'ubuntu avancent mais mes difficultés persistent avec cette imprimante... cette fois je suis sous la 12.04 (32bits), à laquelle je compte bien ne plus toucher avant un moment si j'arrive enfin à faire marcher cette Lexmark !!
alors voilà, l'installation du pilote semble vouloir se lancer mais s'interrompt avant de commencer avec un message me disant que la version 1.2 ou ultérieure de CUPS est nécessaire pour l’installation. Or selon ce que j'ai pu voir dans la logithèque, c'est la version cups 1.5.3 qui est déjà présente dans la 12.04. J'ai toujours le driver qui a fonctionné sur des versions plus anciennes, il doit quand même y avoir moyen de le faire ,fonctionner, non ?
La grande question que je me pose est donc : pourquoi ça coince ? et comment expliquer gentiment à mon ordinateur qu'il peut à nouveau (et pour de bon) être ami avec mon imprimante ? peut-on repasser à une version antérieure de CUPS, et si oui comment faut-il s'y prendre ?
Et dire que j'ai fait fonctionner cette imprimante sans problème avec des versions antérieures à la 10.04...
Dernière modification par z0u (Le 19/01/2013, à 11:19)
Hors ligne
z0u
Re : lexmark x2670
juste un petit up, en reprenant ma dernière question : est-t-il possible de repasser à une version antérieure de CUPS, car il semblerait que ce soit de là que vienne le problème ? et si oui comment faut-il s'y prendre ?
merci pour votre aide
Hors ligne
z0u
Re : lexmark x2670
et encore un petit up...
au passage, voici le message d'erreur qui s'affiche au début de l'installation.
The installer has detected the operating system does not meet CUPS minimum version requirements. Please install CUPS version 1.2 or higher and run the installer again.
Hors ligne
navtex
Re : lexmark x2670
Voyager 14.04 sur Dell vostro 1720 2.66GHz × 2 - Ram 4Gio
Voyager- 14.04 sur Asus X56V 2.16GHz × 2 - Ram 3,9 Gio
Xubuntu 14.04 sur Panasonic CF-M34 PIII 0,93Ghz 500Mo
(Keep the wind in your back) mon ébauche blog- http://voiliershy.wordpress.com/
Hors ligne
|
this a second post, part of my previous question.
I wrote a function in Python 2.7 (on Window OS 64bit) in order to calculate the mean value of of the intersection area from a reference polygon (Ref) and one or more segmented (Seg) polygon(s) in ESRI shapefile format. The code is quite slow because i have more that 2000 reference polygon (s) and for each Ref_polygon the function run for every time for all Seg polygons(s) (more than 7000). I am sorry but the function is a prototype.
following the suggestions of David Robinson
from multiprocessing import Pool
p = Pool() # run multiple processes
for l in p.imap_unordered(process_reference_object, range(ref_layer.GetFeatureCount())):
file_out.write(l)
and TimothyAWiseman, i wish to use in the optimize way multiprocessing in order to increase the speed of my function.
i have the following questions:
where is the best position to locate p = Pool().... Inside the second function (ex: segmentation_accuracy) or in the end?
i had try to insert here (in the end of segmentation_accuracy)
p = Pool()
for l in p.imap_unordered(object_accuracy, range(ref_layer.GetFeatureCount())):
file_out.write(l)
file_out.close()
but my PC is freezing
can i improve (i think yes) my code and how?
from shapely.geometry import Polygon
import math
import numpy as np
import osgeo.gdal
import ogr
import numpy
import os
from multiprocessing import Pool
def shapefile_NameFilter(inFile):
if inFile.endswith(".shp"):
return inFile
else:
raise ValueError('"%s" is not an ESRI shapefile' % inFile)
def object_accuracy(ref,seg, index,threshold=10.0,noData=-9999):
"""
segmetation accuracy metrics
"""
ref_layer = ref
seg_layer = seg
# convert in a shapely polygon
ref_feature = ref_layer.GetFeature(index)
# get FID (=Feature ID)
FID = str(ref_feature.GetFID())
ref_geometry = ref_feature.GetGeometryRef()
# exterior boundaries
pts = ref_geometry.GetGeometryRef(0)
points = []
for p in xrange(pts.GetPointCount()):
points.append((pts.GetX(p), pts.GetY(p)))
# convert in a shapely polygon
ref_polygon_exterior = Polygon(points)
nHole = ref_geometry.GetGeometryCount()
if nHole != 1:
for h in range(1, nHole):
# interior boundaries or "holes" of the feature
pts = ref_geometry.GetGeometryRef(h)
points = []
for p in range(pts.GetPointCount()):
points.append((pts.GetX(p), pts.GetY(p)))
ref_polygon_interior = Polygon(points)
ref_polygon_exterior = ref_polygon_exterior.difference(ref_polygon_interior)
# Net Reference Polygon
ref_polygon = ref_polygon_exterior
# get the area
ref_Area = ref_polygon.area
# get centroid of the reference object-i
geom, xy = ref_polygon.centroid.wkt.split(None, 1)
xy = xy.strip('()').split()
xcr, ycr = (float(i) for i in xy)
# create empty lists
nObject = 0
Area_seg, Area_intersect = ([] for _ in range(2))
RAor, RAos = ([] for _ in range(2))
OverSeg, UnderSeg, OverMerg, UnderMerg = ([] for _ in range(4))
qr, SimSize, SegError, Dsr = ([] for _ in range(4))
# For each segmented objects-j
for segment in xrange(seg_layer.GetFeatureCount()):
seg_feature = seg_layer.GetFeature(segment)
seg_geometry = seg_feature.GetGeometryRef()
pts = seg_geometry.GetGeometryRef(0)
points = []
for p in xrange(pts.GetPointCount()):
points.append((pts.GetX(p), pts.GetY(p)))
seg_polygon_exterior = Polygon(points)
nHole = seg_geometry.GetGeometryCount()
if nHole != 1:
for h in range(1, nHole):
# interior boundaries or "holes" of the feature
pts = seg_geometry.GetGeometryRef(h)
points = []
for p in range(pts.GetPointCount()):
points.append((pts.GetX(p), pts.GetY(p)))
seg_polygon_interior = Polygon(points)
seg_polygon_exterior = seg_polygon_exterior.difference(seg_polygon_interior)
# Net Segemted Polygon
seg_polygon = seg_polygon_exterior
seg_Area = seg_polygon.area
# get centroid of the segemented object-j
geom, xy = seg_polygon.centroid.wkt.split(None, 1)
xy = xy.strip('()').split()
xcs, ycs = (float(i) for i in xy)
# intersection (overlap) of reference object with the segmented object
intersect_polygon = ref_polygon.intersection(seg_polygon)
# area of intersection (= 0, No intersection)
intersect_Area = intersect_polygon.area
# Refinement in order to eliminate spurious effects
if intersect_Area > (ref_Area*(float(threshold)/100)):
# Union
union_polygon = ref_polygon.union(seg_polygon)
# area of union
union_Area = union_polygon.area
# Number of segmented objects
nObject += 1
# segmented object area
Area_seg.append(seg_Area)
# intersected (=overlapped) region area
Area_intersect.append(intersect_Area)
# Area-Based Measures
# Relative Area of a reference object (RAor)
RAor.append(intersect_Area/ref_Area)
# Relative Area of a segmented object (RAos)
RAos.append(intersect_Area/seg_Area)
# OverSegmentation (OverSeg)
OverSeg.append(1-(intersect_Area/ref_Area))
# UnderSegmentation (UnderSeg)
UnderSeg.append(1-(intersect_Area/seg_Area))
# OverMerging (OverMerg)
OverMerg.append((ref_Area - intersect_Area)/ref_Area)
# UnderMerging (UnderMerg)
UnderMerg.append((seg_Area -intersect_Area)/ref_Area)
# Quality rate (qr)
qr.append(1-(intersect_Area/(union_Area)))
# SimSize
SimSize.append(min(ref_Area,seg_Area)/max(ref_Area,seg_Area))
# Mean Absolute Segmentation Error (SegError)
SegError.append(abs(ref_Area - seg_Area)/(ref_Area + seg_Area))
# Location-based Measures
# Position discrepancy of segmented object to a reference object
# Euclidean distance in the xy plane
Eucdist_sr = math.sqrt(math.pow((xcs-xcr),2)+math.pow((ycs-ycr),2))
Dsr.append(Eucdist_sr)
# No segmented objects of intrest
if nObject == 0:
AREAs_average, SDs, seg_AreaMax = (noData for _ in range(3))
AREAo_average, SDo, intersect_AreaMax = (noData for _ in range(3))
ORrs,RAor_average,RAos_average = (noData for _ in range(3))
OverSeg_average,UnderSeg_average = (noData for _ in range(2))
OverMerg_average,UnderMerg_average = (noData for _ in range(2))
qr_average,SimSize_average,SegError_average, AFI = (noData for _ in range(4))
Dsr_avarage,RPsr_average,dmax,D = (noData for _ in range(4))
else:
ORrs = (1.0/nObject)*100
AREAs_average = numpy.average(Area_seg)
SDs = numpy.std(Area_seg)
seg_AreaMax = numpy.max(Area_seg)
AREAo_average = numpy.average(Area_intersect)
SDo = numpy.std(Area_intersect)
intersect_AreaMax = numpy.max(Area_intersect)
# Avarage for all segmented objects
RAor_average = numpy.average(RAor)*100
RAos_average = numpy.average(RAos)*100
OverSeg_average = numpy.average(OverSeg)
UnderSeg_average = numpy.average(UnderSeg)
OverMerg_average = numpy.average(OverMerg)
UnderMerg_average = numpy.average(UnderMerg)
qr_average = numpy.average(qr)
SimSize_average = numpy.average(SimSize)
SegError_average = numpy.average(SegError)
# Area Fit Index
AFI = (ref_Area-seg_AreaMax)/ref_Area
Dsr_avarage = numpy.average(Dsr)
# Maximum Distance
dmax = numpy.max(Dsr)
# Avarage Realative Position (RPsr)
RPsr_average = numpy.average(numpy.array(Dsr)/numpy.max(Dsr))
# D index
D = math.sqrt((math.pow(OverSeg_average,2)+math.pow(UnderSeg_average,2))/2)
return(" ".join(["%s" %i for i in [FID, ref_Area, nObject, ORrs,\
AREAs_average, SDs, seg_AreaMax, AREAo_average, SDo, intersect_AreaMax,\
RAor_average, RAos_average, OverSeg_average, UnderSeg_average,\
OverMerg_average, UnderMerg_average,qr_average, SimSize_average,\
SegError_average, AFI, Dsr_avarage, RPsr_average, dmax, D]])+ "\n")
def segmentation_accuracy(reference,segmented,outFile,threshold=10.0,noData=-9999):
"""
Segmentation accuracy
"""
# check if reference and segmented are ESRI shapefile format
reference = shapefile_NameFilter(reference)
segmented = shapefile_NameFilter(segmented)
# open shapefile
ref = osgeo.ogr.Open(reference)
if ref is None:
raise SystemExit('Unable to open %s' % reference)
seg = osgeo.ogr.Open(segmented)
if seg is None:
raise SystemExit('Unable to open %s' % segmented)
ref_layer = ref.GetLayer()
seg_layer = seg.GetLayer()
# create outfile
if not os.path.split(outFile)[0]:
file_path, file_name_ext = os.path.split(os.path.abspath(reference))
outFile_filename = os.path.splitext(os.path.basename(outFile))[0]
file_out = open(os.path.abspath("{0}\\{1}.txt".format(file_path, outFile_filename)), "w")
else:
file_path_name, file_ext = os.path.splitext(outFile)
file_out = open(os.path.abspath("{0}.txt".format(file_path_name)), "w")
# Header
file_out.write(" ".join(["%s" %i for i in ["ReferenceFID","AREAr",\
"nObject","ORrs","AREAs","SDs","AREAsMAX","AREAo","SDo","AREAoMAX",\
"RAor","RAos","OverSeg","UnderSeg","OverMerg","UnderMerg","qr","SimSize",\
"SegError","AFI","Dsr","RPro","dmax","D"]])+ "\n")
for index in xrange(ref_layer.GetFeatureCount()):
file_out.write(object_accuracy(index))
file_out.close()
|
I can't seem to get Python to import a module in a subfolder. I get the error when I try to create an instance of the class from the imported module, but the import itself succeeds. Here is my directory structure:
Server -server.py -Models --user.py
Here's the contents of server.py:
from sys import path
from os import getcwd
path.append(getcwd() + "\\models") #Yes, i'm on windows
print path
import user
u=user.User() #error on this line
And user.py:
class User(Entity):
using_options(tablename='users')
username = Field(String(15))
password = Field(String(64))
email = Field(String(50))
status = Field(Integer)
created = Field(DateTime)
The error is: AttributeError: 'module' object has no attribute 'User'
|
I'm writing a log collection / analysis application in Python and I need to write a "rules engine" to match and act on log messages.
It needs to feature:
Regular expression matching for the message itself
Arithmetic comparisons for message severity/priority
Boolean operators
I envision An example rule would probably be something like:
(message ~ "program\\[\d+\\]: message" and severity >= high) or (severity >= critical)
I'm thinking about using PyParsing or similar to actually parse the rules and construct the parse tree.
The current (not yet implemented) design I have in mind is to have classes for each rule type, and construct and chain them together according to the parse tree. Then each rule would have a "matches" method that could take a message object return whether or not it matches the rule.
Very quickly, something like:
class RegexRule(Rule):
def __init__(self, regex):
self.regex = regex
def match(self, message):
return self.regex.match(message.contents)
class SeverityRule(Rule):
def __init__(self, operator, severity):
self.operator = operator
def match(self, message):
if operator == ">=":
return message.severity >= severity
# more conditions here...
class BooleanAndRule(Rule):
def __init__(self, rule1, rule2):
self.rule1 = rule1
self.rule2 = rule2
def match(self, message):
return self.rule1.match(message) and self.rule2.match(message)
These rule classes would then be chained together according to the parse tree of the message, and the match() method called on the top rule, which would cascade down until all the rules were evaluated.
I'm just wondering if this is a reasonable approach, or if my design and ideas are way totally out of whack? Unfortunately I never had the chance to take a compiler design course or anything like that in Unviersity so I'm pretty much coming up with this stuff of my own accord.
Could someone with some experience in these kinds of things please chime in and evaluate the idea?
EDIT:Some good answers so far, here's a bit of clarification.
The aim of the program is to collect log messages from servers on the network and store them in the database. Apart from the collection of log messages, the collector will define a set of rules that will either match or ignore messages depending on the conditions and flag an alert if necessary.
I can't see the rules being of more than a moderate complexity, and they will be applied in a chain (list) until either a matching alert or ignore rule is hit. However, this part isn't quite as relevant to the question.
As far the syntax being close to Python syntax, yes that is true, however I think it would be difficult to filter the Python down to the point where the user couldn't inadvertently do some crazy stuff with the rules that was not intended.
|
g_barthe
interface python et apprentissage boa constrictor
Bonjour,
Je voudrais commencer à developper qq applications (avec interfaces graphiques) en python (pour windows et linux). Je recherche donc un éditeur qui permettrait de realiser l'interface de maniere simple et non en code pur. J'ai bien trouvé "wxglade" mais la lib wx n'a pas l'air d'etre présente de base avec python sur tous les environnements. (je peux me tromper) mais sous windows apparement je ne l'ai pas.
Il y a la librairie tk qui a l'air d'être prise en compte de manière générale mais la les éditeurs que j'ai trouvé"vtcl" n'arrive pas a se decompresser sous windows et comme je suis amené a developper sous ubuntu et windows je voudrais etre sur une librairie qui soit intégrée facilement à mon environnement de prog.
Y a t'il un avantage d'une librairie par rapport a l'autre ?
merci à vous et j'espère que j'ai été clair.
Dernière modification par g_barthe (Le 02/05/2006, à 18:18)
Mon forum perso sur le génie climatique http://le-genie-climatique.positifforum.com/
Le forum des travaux manuels : http://pausebroderie.fr/
Hors ligne
PierreR
Re : interface python et apprentissage boa constrictor
Pour TKinter, il y a peut être COBRA, mais je ne l'ai jamais utilisé.
Sinon, tu dois pouvoir utiliser GTK avec glade. GTK est le toolkit graphique utilisé par Gnome et il existe sous ubuntu et windows (mais pas mac OS). Il est plus complexe -- dans le sens offre plus de fonctionnalités -- que TKinter mais tout dépend de ce que tu veux faire -- GTK n'est pas installé par défaut sous windows par exemple (mais python non plus donc bon).
Hors ligne
g_barthe
Re : interface python et apprentissage boa constrictor
bonjour
j'ai reussi a faire fonctionner qq scripts python sous ubuntu avec la lib wx. Mais j'ai installé vtcl depuis synaptic d'ubuntu en gros c'est glade pour me facilité la tâche de création de l'interface mais il exporte le code source uniquement en C et pas python. La vie d'un nouveau pythonien n'est pas facile tous les jours. Je crois que je vais rester à la création manuelle de l'interface et non pas graphique car je n'arrive pas a comprendre le fonctionnement de vtcl et je ne trouve pas de tuto sur le net.
Je cherche à faire une application un peu scientifique avec qq calculs pour mon boulot en génie climatique (calculs de clim, chauffage, ventilation). En gros ce sera des boutons de validation, zone de saisie...
Merci à vous
Mon forum perso sur le génie climatique http://le-genie-climatique.positifforum.com/
Le forum des travaux manuels : http://pausebroderie.fr/
Hors ligne
bipede
Re : interface python et apprentissage boa constrictor
Si tu veux tester un bon rad pour python et wxPython, essaies boa-constructor.
C'est le meilleur à l'heure actuelle. Et il est dans les dépôts...
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
Je peux que recommander d'écrire son code dans un éditeur. Les avantages sont si nombreux.
Pour un bon début : http://wiki.wxpython.org/
PierreR
Re : interface python et apprentissage boa constrictor
Oui, mais là on parlait de l'interface graphique et à écrire à la main c'est vraiment prise de tête quand le truc devient un peu gros.
Désolé de m'être trompé plus haut, je voulais effectivement parler de boa (et pas cobra). Sinon pour glade, il ne faut pas générer le code -- même en C c'est déconseillé et plus supporté depuis un moment -- mais utiliser libglade qui a je crois un wrapper python.
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
@PierreR
Oui, mais là on parlait de l'interface graphique et à écrire à la main c'est vraiment prise de tête quand le truc devient un peu gros.
---
Pas du tout, c'est justement l'inverse qui se produit. Quelle est ton expérience? Sur quoi te bases-tu ? Argumentes !
Etant intimement lié à wxPython, je peux te dire que cette question a été posée des dizaines et des dizaines de fois sur la liste des wxPython users (et revient régulièrement). C'est toujours la même réponse qui revient. La même que celle que j'ai donné.
PS: ...mais là on parlait de l'interface graphique... wxPython ne s'occupe que de l'interface graphique.
PierreR
Re : interface python et apprentissage boa constrictor
Heu, il y du y avoir un quiproquo, je voulais dire que quand on fait une interface graphique, à partir du moment ou le truc devient un peu gros (i.e. s'il y a plus d'un champ de texte et deux boutons) c'est très appréciable de disposer d'une interface graphique comme Glade.
Pour répondre à ta question, je dois avouer que je n'ai jamais utilisé wxwidgets (que ce soit en python ou en C++). Quand je faisais du python, je me contentais de Tkinter et c'est vrai que j'écrivais tout à la main et que je suis encore vivant.
Mais un des avantages que je vois aux éditeurs graphiques et de limiter à 0 u presque le risque de mélanger dans le code ce qui a trait à l'interface graphique et le reste rendant très facile un redesign complet de la dite interface même par quelqu'un qui n'aurai jamais touché une ligne de code. Je pensais au début que ce genre d'outils n'était qu'un "truc de feignant" promesse d'interfaces graphiques déguelasses. mais j'ai récemment participé à un projet qui utilise libglade (en C, je ne sais pas ce que ça donne en python mais ça doit être au moins aussi facile d'utilisation) et j'ai pu faire des changements très profond dans l'interface graphique en seulement quelques heures (et quelques centaines de clics et seulement une grosse dizaine de lignes de codes modifiées).
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
PierreR
Bon si tu le dis.
Quand je remanie complètement une interface graphique contenant disons 10 - 50 contrôles, il me faut tout au plus 10 minutes et à peu près zéro clics de souris et le code application - partie calcul - n'est pas mélangé avec celui de l'interface graphique.
Ajouter deux paires - texte et texte d'entrée - à une fenêtre de dialogue qui en contient déjà 10, dois bien prendre 2 bonnes minutes.
Chacun sa méthode. Je dois dire que j'utilise des "sizers".
PierreR
Re : interface python et apprentissage boa constrictor
Effectivement, les gouts et les couleurs !
Mais je suis d'accord que pour quelqu'un de soigneux -- contrairement à moi -- tout écrire à la main est tout aussi jouable et présente certains avantages. Personellement, j'apprécie particulièrement quand j'utilise glade de voir en direct le résultat, de pouvoir tester le redimensionnement, etc sans avoir à recompiler quoi que ce soit -- en C ou C++, effectivement, la question ne se pose pas avec Python -- et donc sans attendre.
Mais je reconnais effectivement que c'est plus un gout et un avis personnel que quelque chose d'indiscutable, dans le même genre, je n'ai jamais été un grand fan des traitements de texte wysywyg comme openoffice -- je préfère LaTeX ou des éditeurs de page web du même genre alors qu'en fait pour qulqu'un de soigneux ce sont sûrement des outils qui permettent d'arriver aux même résultat avec peut être moins d'effort.
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
PierreR
Ta remarque concernant Python est très judicieuse. En effet, Python étant interprété, il me suffit d'un F5 (run script) dans mon éditeur pour voir le résultat.
J'apprécie aussi ta remarque à propos de LaTeX. Je suis du même avis, mais n'avait pas osé mettre le sujet sur la table (analogie).
Un point que j'affectionne particulièrement quand on travail à la main: la possibilité de créer aisément un classe dérivée d'un classe de base. C'est quelque chose que je fais très souvent et que je vois chez beaucoup de personnes avec qui j'échange du code. Par exemple: un contrôle d'entrée de texte qui n'accepte que les lettres minuscules ou un nombre.
Une petite question. Quand tu parles de "tester le redimensionnement". Cela signifierait-t-il que tu places les contrôles en définissant leurs positions en "pixels" ?
aleph
Re : interface python et apprentissage boa constrictor
Honte de mon orthographe...
PierreR
Re : interface python et apprentissage boa constrictor
On est quitte, je vois que j'ai fait une quantité de fautes de frappe proprement hallucinante.
Pour l'orienté objet, j'avoue qu'en C je n'ai pas encore vraiment pris l'habitude et en C++ je n'ai jamais fait de grosses interfaces graphiques mais j'entend bien l'argument. Notons toutefois qu'il y a toujours la possibilité de faire cela en laissant un "trou" avec l'interface graphique qu'on remplit ensuite à la main -- il y a même un "widget" special pour ça dans glade je crois.
Pour la dernière question, non je ne place jamais les widgets avec des positions absolues, je voulais dire vérifier que j'ai bien choisies les propriétés d'expansion des widgets de ma fenêtre et que c'est bien la vue arborescente et pas le bouton fermer qui occupe toute la place quand on l'agrandit par exemple -- mais ceci est peut être simplement du à mon inexpérience de GTK.
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
PierreR
Merci.
g_barthe
Re : interface python et apprentissage boa constrictor
Bonjour,
J'ai installé boa constrictor sur windows au bureau tout va bien et sur ma machine ubuntu breezy chez moi. Jusque la tout va bien. petit bémol sur Ubuntu ou les éléments de l'interface sont tronqués même en etendant les fenetres mais bon passons.
J'ai testé un exemple trouvé sur le net sous windows et ca fonctionne mais sous linux non. Alors la je me pose des questions sur la portabilité. Doit-on faire qqch de précis. Je joins le code :
fichier Frame1.py :
#Boa:Frame:Frame1
import wx
def create(parent):
return Frame1(parent)
[wxID_FRAME1, wxID_FRAME1STATUSBAR1,
] = [wx.NewId() for _init_ctrls in range(2)]
[wxID_FRAME1MENUFILEITEMS0, wxID_FRAME1MENUFILEITEMS1,
wxID_FRAME1MENUFILEITEMS2, wxID_FRAME1MENUFILEITEMS3,
wxID_FRAME1MENUFILEITEMS4,
] = [wx.NewId() for _init_coll_menuFile_Items in range(5)]
[wxID_FRAME1MENUHELPABOUT] = [wx.NewId() for _init_coll_menuHelp_Items in range(1)]
class Frame1(wx.Frame):
def _init_coll_menuBar1_Menus(self, parent):
# generated method, don't edit
parent.Append(menu=self.menuFile, title='File')
parent.Append(menu=self.menuHelp, title='Help')
def _init_coll_menuHelp_Items(self, parent):
# generated method, don't edit
parent.Append(help='Display general information about Notebook',
id=wxID_FRAME1MENUHELPABOUT, kind=wx.ITEM_NORMAL, text='About')
self.Bind(wx.EVT_MENU, self.OnMenuHelpAboutMenu,
id=wxID_FRAME1MENUHELPABOUT)
def _init_coll_menuFile_Items(self, parent):
# generated method, don't edit
parent.Append(help='', id=wxID_FRAME1MENUFILEITEMS0,
kind=wx.ITEM_NORMAL, text='Open')
parent.Append(help='', id=wxID_FRAME1MENUFILEITEMS1,
kind=wx.ITEM_NORMAL, text='Save')
parent.Append(help='', id=wxID_FRAME1MENUFILEITEMS2,
kind=wx.ITEM_NORMAL, text='Save As')
parent.Append(help='', id=wxID_FRAME1MENUFILEITEMS3,
kind=wx.ITEM_NORMAL, text='Close')
parent.Append(help='', id=wxID_FRAME1MENUFILEITEMS4,
kind=wx.ITEM_NORMAL, text='Exit')
self.Bind(wx.EVT_MENU, self.OnMenuFileItems0Menu,
id=wxID_FRAME1MENUFILEITEMS0)
self.Bind(wx.EVT_MENU, self.OnMenuFileItems1Menu,
id=wxID_FRAME1MENUFILEITEMS1)
self.Bind(wx.EVT_MENU, self.OnMenuFileItems2Menu,
id=wxID_FRAME1MENUFILEITEMS2)
self.Bind(wx.EVT_MENU, self.OnMenuFileItems3Menu,
id=wxID_FRAME1MENUFILEITEMS3)
self.Bind(wx.EVT_MENU, self.OnMenuFileItems4Menu,
id=wxID_FRAME1MENUFILEITEMS4)
def _init_coll_statusBar1_Fields(self, parent):
# generated method, don't edit
parent.SetFieldsCount(1)
parent.SetStatusText(number=0, text='Status')
parent.SetStatusWidths([-1])
def _init_utils(self):
# generated method, don't edit
self.menuFile = wx.Menu(title='')
self.menuHelp = wx.Menu(title='')
self.menuBar1 = wx.MenuBar()
self._init_coll_menuFile_Items(self.menuFile)
self._init_coll_menuHelp_Items(self.menuHelp)
self._init_coll_menuBar1_Menus(self.menuBar1)
def _init_ctrls(self, prnt):
# generated method, don't edit
wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt,
pos=wx.Point(466, 359), size=wx.Size(400, 250),
style=wx.DEFAULT_FRAME_STYLE, title='G\xe9nie climatique')
self._init_utils()
self.SetClientSize(wx.Size(392, 216))
self.SetMenuBar(self.menuBar1)
self.statusBar1 = wx.StatusBar(id=wxID_FRAME1STATUSBAR1,
name='statusBar1', parent=self, style=0)
self._init_coll_statusBar1_Fields(self.statusBar1)
self.SetStatusBar(self.statusBar1)
def __init__(self, parent):
self._init_ctrls(parent)
def OnMenuFileItems0Menu(self, event):
event.Skip()
def OnMenuFileItems1Menu(self, event):
event.Skip()
def OnMenuFileItems2Menu(self, event):
event.Skip()
def OnMenuFileItems3Menu(self, event):
event.Skip()
def OnMenuFileItems4Menu(self, event):
event.Skip()
def OnMenuHelpAboutMenu(self, event):
event.Skip()
fichier App1.py :
#Boa:App:BoaApp
import wx
import Frame1
modules ={'Frame1': [1, 'Main frame of Application', 'Frame1.py']}
class BoaApp(wx.App):
def OnInit(self):
wx.InitAllImageHandlers()
self.main = Frame1.create(None)
self.main.Show()
self.SetTopWindow(self.main)
return True
def main():
application = BoaApp(0)
application.MainLoop()
if __name__ == '__main__':
main()
Mon forum perso sur le génie climatique http://le-genie-climatique.positifforum.com/
Le forum des travaux manuels : http://pausebroderie.fr/
Hors ligne
bipede
Re : interface python et apprentissage boa constrictor
C'est un problème de codage de caractères :
si tu changes ta ligne :
style=wx.DEFAULT_FRAME_STYLE, title='G\xe9nie climatique')
dans Frame1.py par :
style=wx.DEFAULT_FRAME_STYLE, title='Génie climatique')
Et que tu ajoutes la ligne :
#-*- coding: utf8 -*-
En première ligne de tes deux scripts, ça va marcher...
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
Boa ou les dix doigts ?
La même application écrite à la main. Pour moi, il n'y a pas photo quant à la clarté du code.
Sans compter les imperfections (erreur) dans le code généré par boa.
# -*- coding: iso-8859-1 -*-
#--------------------------------------------------------------------
# Name: simple.py
# Purpose: Small demo
# Author: Jean-Michel Fauth, Switzerland
# Copyright:
# Licence: None, free software
#--------------------------------------------------------------------
# os dev: w2k sp4
# py dev: Python 2.4.2
# wx dev: wxPython 2.6.3.2
# Revision: 2 May 2006
#--------------------------------------------------------------------
import wx
class MyPanel(wx.Panel):
def __init__(self, parent, id):
wx.Panel.__init__(self, parent, id, wx.DefaultPosition, wx.DefaultSize)
class MyFrame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, (300, 200))
self.CentreOnScreen()
# menus
menu1 = wx.Menu()
menu101 = menu1.Append(101, '&Open...\tCtrl+o', 'Ouvre un fichier')
menu103 = menu1.Append(102, '&Save as...\tCtrl+s', 'Enregistre un fichier sous')
menu102 = menu1.Append(103, 'Save\tCtrl+s', 'Enregistre le fichier courant')
menu104 = menu1.Append(104, '&Close')
menu105 = menu1.Append(105, '&Exit', 'Quitte cette application')
menu2 = wx.Menu()
menu201 = menu2.Append(201, '&About...', 'A propos')
menuBar = wx.MenuBar()
menuBar.Append(menu1, '&File')
menuBar.Append(menu2, '&Help')
self.SetMenuBar(menuBar)
# statusbar
sb = wx.StatusBar(self, wx.NewId())
self.SetStatusBar(sb)
self.Bind(wx.EVT_MENU, self.OnMenu101, menu101)
self.Bind(wx.EVT_MENU, self.OnMenu102, menu102)
self.Bind(wx.EVT_MENU, self.OnMenu103, menu103)
self.Bind(wx.EVT_MENU, self.OnMenu104, menu104)
self.Bind(wx.EVT_MENU, self.OnMenu105, menu105)
self.Bind(wx.EVT_MENU, self.OnMenu201, menu201)
# panel contenant les widgets
self.pa = MyPanel(self, wx.NewId())
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
def OnMenu101(self, event):
print 'Menu101'
def OnMenu102(self, event):
print 'Menu102'
def OnMenu103(self, event):
print 'Menu103'
def OnMenu104(self, event):
print 'Menu104'
def OnMenu105(self, event):
print 'Menu105'
self.OnCloseWindow(None)
def OnMenu201(self, event):
print 'Menu201'
def OnCloseWindow(self, event):
self.Destroy()
class MyApp(wx.App):
def OnInit(self):
frame = MyFrame(None, -1, 'Génie climatique')
frame.Show(True)
self.SetTopWindow(frame)
return True
def main():
app = MyApp(False)
app.MainLoop()
if __name__ == '__main__':
main()
#eof
bipede
Re : interface python et apprentissage boa constrictor
Boa ou les dix doigts ?
La même application écrite à la main. Pour moi, il n'y a pas photo quant à la clarté du code.
Sans compter les imperfections (erreur) dans le code généré par boa.
Tu prêches un convaincu
Mais notre ami veut utiliser un RAD.
Quant au code généré par Boa, il n'est pas si sale que cela, et je trouve que l'objet y est bien utilisé...
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
bipede :
Quant au code généré par Boa, il n'est pas si sale que cela, et je trouve que l'objet y est bien utilisé...
---
Il est même très propre, c'est à dire bien conçu. Ce que je veux montrer ici est que l'utilisation d'un IDE n'est pas la panacée.
Le code généré par Boa doit faire deux choses:
- écrire le code de l'application.
- écrire le code de façon à ce que Boa puisque le récupérer et l'éditer à nouveau. D'où une certaine lourdeur. Une structure de code qui ne correspond pas à ce que l'application est censée faire, mais une structure qui est plus conforme à Boa.
Quelques autres commentaires en vrac :
- wx.InitAllImageHandlers() n'est par nécessaire, cette tâche est effectuée en interne par OnInit(), voir wxPython doc. Cette tâche est exécutée deux fois !
- event.Skip() dans les menus est inutile. Un "pass" eut été suffisant. A quoi bon surcharger, la queue des événements. Il faut bien que Boa mette quelque chose.
- Boa ne génère pas l'événement OnCloseWindow(), très important dans la pratique. Cette partie du code doit de toute façon est rajoutée à la main.
- Mon code avait des doc strings dans le function (triple double quoted strings). Il semblerait que ces doc strings se soient perdus en route !
Ma conclusion :
On en arrive à cette absurdité où seuls les personnes sachant développer à la main sont à même de comprendre correctement le code généré par Boa.
Ceci est vrai pour tous les IDEs.
Je ne peux que recommander une visite chez wxPython.org et télécharger la demo.
aleph
Re : interface python et apprentissage boa constrictor
Petite remarque annexe:
L'IDE ne se nomme pas Boa constrictor, mais Boa constructor. En espérant que vous ayez compris la subtilité du nom.
g_barthe
Re : interface python et apprentissage boa constrictor
Je vous remercie tous pour ces différentes remarques et je sais très bien que les IDE ne sont pas une solution très propre. Moi même pour du HTML je fais tout à la main, je gère mieux ce que je fais je trouve. Mais la n'y connaissant rien à python je voulais déjà créer un joli interface graphique de manière rapide sans trop avoir à comprendre la construction ce que je ferais pour le coeur du programme bien sur. Par la suite oui je redécortiquerais la partie interface pour la recoder de manière simple sans boa.
Mon forum perso sur le génie climatique http://le-genie-climatique.positifforum.com/
Le forum des travaux manuels : http://pausebroderie.fr/
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
Permets moi d'insister. Est-ce que tu as la demo de wxPython ?
Tous les widgets expliqués, le code pour chaque widget, modification et essai, tout ceci interactivement...sans jamais quitter l'application.
g_barthe
Re : interface python et apprentissage boa constrictor
je viens de le télécharger et effectivement je connaissais pas et ca m'a l'air très instructif et très bien fait. Je vais me pencher ( pas top qd meme) bon c nul, sur cette doc et continuer mon apprentissage et je vous tiendrais au courant de l'evolution.
Merci de votre aide.
Mon forum perso sur le génie climatique http://le-genie-climatique.positifforum.com/
Le forum des travaux manuels : http://pausebroderie.fr/
Hors ligne
aleph
Re : interface python et apprentissage boa constrictor
Enfin ! Si j'ose dire. Comme cela fait bientôt 5 ans que je contribue assez fidèlement au projet wxPython, cela me fait plaisir. Je suis sous win, tu me pardonneras.
Bonne continuation.
bipede
Re : interface python et apprentissage boa constrictor
- wx.InitAllImageHandlers() n'est par nécessaire, cette tâche est effectuée en interne par OnInit(), voir wxPython doc. Cette tâche est exécutée deux fois !
Même si sur le reste je suis complètement d'accord avec toi, sur ce point précis non. L'initialisation des handlers d'images n'est pas automatique, et on doit l'ajouter à la méthode OnInit() de la classe wx.App si on veut que tous les formats d'images soient reconnus (j'ai expérimenté).
Je suis content de rencontrer un contributeur au projet wxpython dont je suis un adepte forcené .
Il est dommage que tu ne travailles que sur windows, car j'ai pu constater des différences de comportement de certains wxWidgets entre les deux OS que je n'ai jamais pu m'expliquer.
Hors ligne
|
Short version: What's the best hashing algorithm for a multiset implemented as a dictionary of unordered items?
I'm trying to hash an immutable multiset (which is a bag or multiset in other languages: like a mathematical set except that it can hold more than one of each element) implemented as a dictionary. I've created a subclass of the standard library class collections.Counter, similar to the advice here: Python hashable dicts, which recommends a hash function like so:
class FrozenCounter(collections.Counter):
# ...
def __hash__(self):
return hash(tuple(sorted(self.items())))
Creating the full tuple of items takes up a lot of memory (relative to, say, using a generator) and hashing will occur in an extremely memory intensive part of my application. More importantly, my dictionary keys (multiset elements) probably won't be order-able.
I'm thinking of using this algorithm:
def __hash__(self):
return functools.reduce(lambda a, b: a ^ b, self.items(), 0)
I figure using bitwise XOR means order doesn't matter for the hash value unlike in the hashing of a tuple? I suppose I could semi-implement the Python tuple-hashing alogrithm on the unordered stream of tuples of my data. See https://github.com/jonashaag/cpython/blob/master/Include/tupleobject.h (search in the page for the word 'hash') -- but I barely know enough C to read it.
Thoughts? Suggestions? Thanks.
(
If you're wondering why I'm messing around with trying to hash a multiset:The input data for my problem are sets of multisets, and within each set of multisets, each multiset must be unique. I'm working on a deadline and I'm not an experienced coder, so I wanted to avoid inventing new algorithms where possible. It seems like the most Pythonic way to make sure I have unique of a bunch of things is to put them in a
set(), but the things must be hashable.)
What I've gathered from the comments
Both @marcin and @senderle gave pretty much the same answer: use hash(frozenset(self.items())). This makes sense because items() "views" are set-like. @marcin was first but I gave the check mark to @senderle because of the good research on the big-O running times for different solutions. @marcin also reminds me to include an __eq__ method -- but the one inherited from dict will work just fine. This is how I'm implementing everything -- further comments and suggestions based on this code are welcome:
class FrozenCounter(collections.Counter):
# Edit: A previous version of this code included a __slots__ definition.
# But, from the Python documentation: "When inheriting from a class without
# __slots__, the __dict__ attribute of that class will always be accessible,
# so a __slots__ definition in the subclass is meaningless."
# http://docs.python.org/py3k/reference/datamodel.html#notes-on-using-slots
# ...
def __hash__(self):
"Implements hash(self) -> int"
if not hasattr(self, '_hash'):
self._hash = hash(frozenset(self.items()))
return self._hash
|
I want to get all the freebusy events of my Google Calendar between two given dates. I'm following the documentation of the freebusy object.
Basically, I have an index.html with a form that allows to choose two dates. I send those dates to my application (Python Google AppEngine backed).
This is the code, simplified, to make it more readable:
CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client_secrets.json')
decorator = oauth2decorator_from_clientsecrets(
CLIENT_SECRETS,
scope='https://www.googleapis.com/auth/calendar',
message=MISSING_CLIENT_SECRETS_MESSAGE)
service = build('calendar', 'v3')
class MainPage(webapp2.RequestHandler):
@decorator.oauth_required
def get(self):
# index.html contains a form that calls my_form
template = jinja_enviroment.get_template("index.html")
self.response.out.write(template.render())
class MyRequestHandler(webapp2.RequestHandler):
@decorator.oauth_aware
def post(self):
if decorator.has_credentials():
# time_min and time_max are fetched from form, and processed to make them
# rfc3339 compliant
time_min = some_process(self.request.get(time_min))
time_max = some_process(self.request.get(time_max))
#Â Construct freebusy query request's body
freebusy_query = {
"timeMin" : time_min,
"timeMax" : time_max,
"items" :[
{
"id" : my_calendar_id
}
]
}
http = decorator.http()
request = service.freebusy().query(freebusy_query)
result = request.execute(http=http)
else:
# raise error: no user credentials
app = webapp2.WSGIApplication([
('/', MainPage),
('/my_form', MyRequestHandler),
(decorator.callback_path, decorator.callback_handler())
], debug=True)
But I get this error in the freebusy call (interesting part of the stack trace):
File "/Users/jorge/myapp/oauth2client/appengine.py", line 526, in setup_oauth
return method(request_handler, *args, **kwargs)
File "/Users/jorge/myapp/myapp.py", line 204, in post
request = service.freebusy().query(freebusy_query)
TypeError: method() takes exactly 1 argument (2 given)
I've done some research, but I didn't found any running example with calendar v3 and freebusy call on Python. I successfully executed the call in the API explorer.
If I understood the error, seems that the oauth_aware decorator filters in any way all the calls of the code under its control. A callable is passed to the method OAuthDecorator.oauth_aware of oauth2client. And this callable is an instance of webapp2.RequestHandler. Like MyRequestHandler.
If the user is properly logged, then the oauth_aware method returns a call to desired method, by calling method(request_handler, *args, **kwargs). And here comes the error. A TypeError, because method is taking more arguments than allowed.
That's my interpretation, but I don't know if I'm right. Should I call freebusy().query() in any other way? Does any piece of my analysis really make sense? I'm lost with this...
Many thanks in advance
|
I want to measure the execution time of the Python method sayHello() using the method getExecutionTime(). They are both in a module and the getExecutionTime()-method should be callable from outside.
The code looks like this:
def getExecutionTime():
t = timeit.Timer("sayHello", "from __main__ import sayHello")
return t.timeit(2)
def sayHello():
print("Hello")
I keep getting an ImportError saying: "Cannot import name sayHello in File ..."
I added the scope argument ("from __main__ import sayHello") to the Timer constructor to make the sayHello() method available within the timeit scope.
Note: I don't want to call getExecutionTime() in the main part of this method, I want to that method from somewhere else.
Can anyone help? Thanks.
|
I have the following ANTLR grammar that forms part of a larger expression parser:
grammar ProblemTest;
atom : constant
| propertyname;
constant: (INT+ | BOOL | STRING | DATETIME);
propertyname
: IDENTIFIER ('/' IDENTIFIER)*;
IDENTIFIER
: ('a'..'z'|'A'..'Z'|'0'..'9'|'_')+;
INT
: '0'..'9'+;
BOOL : ('true' | 'false');
DATETIME
: 'datetime\'' '0'..'9'+ '-' '0'..'9'+ '-' + '0'..'9'+ 'T' '0'..'9'+ ':' '0'..'9'+ (':' '0'..'9'+ ('.' '0'..'9'+)*)* '\'';
STRING
: '\'' ( ESC_SEQ | ~('\\'|'\'') )* '\''
;
fragment
HEX_DIGIT : ('0'..'9'|'a'..'f'|'A'..'F') ;
fragment
ESC_SEQ
: '\\' ('b'|'t'|'n'|'f'|'r'|'\"'|'\''|'\\')
| UNICODE_ESC
| OCTAL_ESC
;
fragment
OCTAL_ESC
: '\\' ('0'..'3') ('0'..'7') ('0'..'7')
| '\\' ('0'..'7') ('0'..'7')
| '\\' ('0'..'7')
;
fragment
UNICODE_ESC
: '\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT
;
If I invoke this in the interpreter from within ANTLR works with
'Hello\\World'
then this is getting interpreted as a propertyname instead of a constant. The same happens if I compile this in C# and run it in a test harness, so it is not a problem with the dodgy interpreter
I'm sure I am missing something really obvious... but why is this happening? It's clear there is a problem with the string matcher, but I would have thought at the very least that the fact that IDENTIFIER does not match the ' character would mean that this would throw a NoViableAltException instead of just falling through?
|
#2676 Le 15/02/2013, à 19:14
mulder29
Re : TVDownloader: télécharger les médias du net !
Et je reçois
python: can't open file
alors que j'ai installé Python 2.7.3, hier.
Hors ligne
#2677 Le 15/02/2013, à 19:26
k3c
Re : TVDownloader: télécharger les médias du net !
si tu tapes
which python
ça affiche quoi ?
Dernière modification par k3c (Le 15/02/2013, à 19:28)
Hors ligne
#2678 Le 15/02/2013, à 20:20
mulder29
Re : TVDownloader: télécharger les médias du net !
ça affiche :
/usr/bin/python
Hors ligne
#2679 Le 15/02/2013, à 22:38
JessicaNichenin
Re : TVDownloader: télécharger les médias du net !
j'utilise la version 0.6 du script et cela ne marche plus
python get.py http://videos.tf1.fr/unforgettable/episode-16-saison-01-la-fille-de-l-air-7817948.html
['rtmpdump', '-r', 'rtmpte://wske.wat.tv/ondemand/mp4:vod/H264-384x288/31/87/9433187.h264', '-c', '1935', '-m', '10', '-w', 'ebb7a6fbdc9021db95e2bd537d73fabb9717508f085bea50bde75f7a8e27698c', '-x', '343642', '-o', 'episode-16-saison-01-la-fille-de-l-air-7817948.mp4', ' --resume']
Erreur : le sous-process s'est terminé avec (le code d'erreur est 1)
Erreur : le sous-process s'est terminé avec (le code d'erreur est 1)
Erreur : le sous-process s'est terminé avec (le code d'erreur est 1)
Erreur : le sous-process s'est terminé avec (le code d'erreur est 1)
Merci pour ce merveilleux script
Hors ligne
#2680 Le 16/02/2013, à 00:17
k3c
Re : TVDownloader: télécharger les médias du net !
Cette version est peu testée, mais télécharge les 3 épisodes de Unforgettable
# -*- coding:utf-8 -*-
# TF1 TMC NT1 HD1 version 0.7 par k3c, correction de 11gjm, modif pour TF1 unforgettable
import subprocess, optparse, re, sys, shlex
import socket
from urllib2 import urlopen
import time, md5, random, urllib2
import bs4 as BeautifulSoup
listeUserAgents = [ 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_5; fr-fr) AppleWebKit/525.18 (KHTML, like Gecko) Version/3.1.2 Safari/525.20.1',
'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.186 Safari/535.1',
'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.27 Safari/525.',
'Mozilla/5.0 (X11; U; Linux x86_64; en-us) AppleWebKit/528.5+ (KHTML, like Gecko, Safari/528.5+) midori',
'Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.107 Safari/535.1',
'Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/312.1 (KHTML, like Gecko) Safari/312',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.12 Safari/535.11',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.8 (KHTML, like Gecko) Chrome/17.0.940.0 Safari/535.8' ]
def get_wat(id):
def base36encode(number):
if not isinstance(number, (int, long)):
raise TypeError('number must be an integer')
if number < 0:
raise ValueError('number must be positive')
alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
base36 = ''
while number:
number, i = divmod(number, 36)
base36 = alphabet[i] + base36
return base36 or alphabet[0]
ts = base36encode(int(time.time()))
timesec = hex(int(ts, 36))[2:]
while(len(timesec)<8):
timesec = "0"+timesec
token = md5.new("9b673b13fa4682ed14c3cfa5af5310274b514c4133e9b3a81e6e3aba00912564/web/"+str(id)+""+timesec).hexdigest()
id_url1 = "http://www.wat.tv/get/web/"+str(id)+"?token="+token+"/"+timesec+"&getURL=1&country=FR"
return id_url1
def main():
gg@gg-SATELLITE-L755:~$ cat !$
cat hd3.py
# -*- coding:utf-8 -*-
# TF1 TMC NT1 HD1 version 0.7 par k3c, correction de 11gjm, modif pour TF1 unforgettable
import subprocess, optparse, re, sys, shlex
import socket
from urllib2 import urlopen
import time, md5, random, urllib2
import bs4 as BeautifulSoup
listeUserAgents = [ 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_5; fr-fr) AppleWebKit/525.18 (KHTML, like Gecko) Version/3.1.2 Safari/525.20.1',
'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.186 Safari/535.1',
'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.27 Safari/525.',
'Mozilla/5.0 (X11; U; Linux x86_64; en-us) AppleWebKit/528.5+ (KHTML, like Gecko, Safari/528.5+) midori',
'Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.107 Safari/535.1',
'Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/312.1 (KHTML, like Gecko) Safari/312',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.12 Safari/535.11',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.8 (KHTML, like Gecko) Chrome/17.0.940.0 Safari/535.8' ]
def get_wat(id):
def base36encode(number):
if not isinstance(number, (int, long)):
raise TypeError('number must be an integer')
if number < 0:
raise ValueError('number must be positive')
alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
base36 = ''
while number:
number, i = divmod(number, 36)
base36 = alphabet[i] + base36
return base36 or alphabet[0]
ts = base36encode(int(time.time()))
timesec = hex(int(ts, 36))[2:]
while(len(timesec)<8):
timesec = "0"+timesec
token = md5.new("9b673b13fa4682ed14c3cfa5af5310274b514c4133e9b3a81e6e3aba00912564/web/"+str(id)+""+timesec).hexdigest()
id_url1 = "http://www.wat.tv/get/web/"+str(id)+"?token="+token+"/"+timesec+"&getURL=1&country=FR"
return id_url1
def main():
# timeout en secondes
socket.setdefaulttimeout(90)
usage = "usage: python tmc_tf1.py [options] <url de l'emission>"
parser = optparse.OptionParser( usage = usage )
parser.add_option( "--nocolor", action = 'store_true', default = False, help = 'desactive la couleur dans le terminal' )
parser.add_option( "-v", "--verbose", action = "store_true", default = False, help = 'affiche les informations de debugage' )
( options, args ) = parser.parse_args()
if( len( args ) > 2 or args[ 0 ] == "" ):
parser.print_help()
parser.exit( 1 )
debut_id = ''
html = urlopen(sys.argv[1]).read()
nom = sys.argv[1].split('/')[-1:][0]
no = nom.split('.')[-2:][0]
soup = BeautifulSoup.BeautifulSoup(html)
if 'tmc.tv' in str(soup) or 'tf1.fr' in str(soup):
debut_id = str(soup.find('div', attrs={'class' : 'unique' }))
if 'nt1.tv' in str(soup) or 'hd1.tv' in str(soup):
debut_id = str(soup.find('section', attrs={'class' : 'player-unique' }))
id = [x.strip() for x in re.findall("mediaId :([^,]*)", debut_id)][0]
id_url1 = get_wat(id)
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', random.choice(listeUserAgents))]
data = opener.open(id_url1).read()
opener.close()
if data[0:4] == 'http':
ua = random.choice(listeUserAgents)
arguments = 'curl "%s" -L -g -A "%s" -o "%s.mp4"' % (data, ua, no)
print arguments
process = subprocess.Popen(arguments, stdout=subprocess.PIPE, shell=True).communicate()[0]
if data[0:4] == 'rtmp':
host = re.search('rtmpte://(.*)/ondemand', data).group(1)
host = host.replace('rtmpte', 'rtmpe')
data0 = re.search('rtmpte://(.*)h264', data).group(0)
cmds = 'rtmpdump -r "%s" -c 443 -m 10 -w b23434cbed89c9eaf520373c4c6f26e1f7326896dee4b1719e8d9acda0c19e99 -x 343427 -o "%s.mp4" " --resume"' % (data0, str(no))
f = open(str(no), 'w')
f.write(cmds)
f.close()
arguments = shlex.split( cmds )
print arguments
cpt = 0
while True:
p = subprocess.Popen( arguments,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
if p.returncode != 0:
print "Erreur : le sous-process s\'est terminé avec (le code d\'erreur est " + str(p.returncode) + ")"
# status = False
if cpt > 5:
break
cpt += 1
time.sleep(3)
else:
# status = True
break
if __name__ == "__main__":
Hors ligne
#2681 Le 16/02/2013, à 01:15
angeline
Re : TVDownloader: télécharger les médias du net !
Bonsoir à tous.
Ce soir, je découvre que "www.francetvinfo.fr" a encore changé de protocole, et plus possible télécharger le journal de France2 le 20 heures.
Je suis en Amérique du sud.
Est-ce vrai aussi pour vous ?
Merci.
ıɔǝɔ ǝɯɯoɔ xnǝıɯ ʇsǝ,ɔ nʇunqnʞ
Hors ligne
#2682 Le 16/02/2013, à 08:52
gl38
Re : TVDownloader: télécharger les médias du net !
Le journal de 20h de France 2 du 15/2 se télécharge normalement chez moi (en France).
Cordialement,
Guy
Hors ligne
#2683 Le 16/02/2013, à 10:09
k3c
Re : TVDownloader: télécharger les médias du net !
@ angeline
avec pluzzdl 0.9.4 je viens de télécharger le journal de 20 h
gg@gg-SATELLITE-L755:~$ pluzzdl -v http://pluzz.francetv.fr/videos/jt20h.html
[DEBUG ] main.py pluzzdl 0.9.4 avec Python 2.7.3 (i686)
[DEBUG ] main.py OS : Linux #58-Ubuntu SMP Thu Jan 24 15:51:02 UTC 2013
[DEBUG ] Navigateur.py GET http://pluzz.francetv.fr/videos/jt20h.html
[DEBUG ] PluzzDL.py ID de l'émission : 77106215
[DEBUG ] Navigateur.py GET http://www.pluzz.fr/appftv/webservices/video/getInfosOeuvre.php?mode=zeri&id-diffusion=77106215
[DEBUG ] PluzzDL.py Lien MMS : mms://a988.v101995.c10199.e.vm.akamaistream.net/7/988/10199/3f97c7e6/ftvigrp.download.akamai.com/10199/cappuccino/production/publication/Autre/Autre/2013/S07/J5/738525_jt20h_20130215.wmv
[DEBUG ] PluzzDL.py Lien RTMP : None
[DEBUG ] PluzzDL.py URL manifest : http://ftvodhdsecz-f.akamaihd.net/z/streaming-adaptatif/2013/S07/J5/77106215-20130215-,398,632,934,k.mp4.csmil/manifest.f4m
[DEBUG ] PluzzDL.py URL m3u8 : http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J5/77106215-20130215.m3u8
[DEBUG ] PluzzDL.py Utilisation de DRM : non
[DEBUG ] PluzzDL.py Chaine : France 2
[DEBUG ] Historique.py Historique chargé
[DEBUG ] Navigateur.py GET http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J5/77106215-20130215.m3u8
[DEBUG ] Navigateur.py GET http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J5/77106215-20130215-840k.m3u8
[DEBUG ] PluzzDL.py Nombre de fragments : 242
[INFO ] PluzzDL.py Début du téléchargement des fragments
et ça se finit par
[DEBUG ] Navigateur.py GET http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J5/77106215-20130215-840k/77106215-20130215-240.ts
[DEBUG ] Navigateur.py GET http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J5/77106215-20130215-840k/77106215-20130215-241.ts
[INFO ] PluzzDL.py Fin du téléchargement
[INFO ] PluzzDL.py Création du fichier MKV (vidéo finale) ; veuillez attendre quelques instants
[INFO ] PluzzDL.py Fin !
[DEBUG ] Historique.py Historique sauvé
gg@gg-SATELLITE-L755:~$
Hors ligne
#2684 Le 16/02/2013, à 11:29
mulder29
Re : TVDownloader: télécharger les médias du net !
Ah mince, et toujours pas de solution pour moi ? :S
Hors ligne
#2685 Le 16/02/2013, à 12:16
thom83
Re : TVDownloader: télécharger les médias du net !
Bonjour,
@ k3c
J'ai testé la version 0.7 ci-dessus (la partie inférieure) avec succès après avoir ajouté le «main()» qui va bien.
Est-il possible d'améliorer cette version en favorisant les variantes HD des émissions plutôt qu'en SD, quitte à ce que cela prenne plus de place sur le disque ?
Cela ferait une différence sur un écran un peu grand...
Dernière modification par thom83 (Le 16/02/2013, à 12:17)
Hors ligne
#2686 Le 16/02/2013, à 12:33
ynad
Re : TVDownloader: télécharger les médias du net !
@ mulder29
voila comment j'ai fait:
j'ai créer un répertoire D8
dans ce répertoire j'ai copier coller le script #2646 page 106 de k3C dans un éditeur de texte et sauvegarder en d8.py
dans le même répertoire j'ai ouvert un terminal et lancer la commande:
python d8.py http://www.d8.tv/d8-series/pid5313-d8-h.html
si la vidéo est toujours en ligne elle se charge dans ce répertoire
ce script est valable pour d8, k3c en a fait d'autres pour tf1 etc.
il y a pluzdl pour le site de pluzz.
espérant t'aider un peu...
Hors ligne
#2687 Le 16/02/2013, à 13:39
k3c
Re : TVDownloader: télécharger les médias du net !
@ thom83
je prux sortir un hack rapidement, quitte à faire propre plus tard
Hors ligne
#2688 Le 16/02/2013, à 14:05
mulder29
Re : TVDownloader: télécharger les médias du net !
On me met encore
m = re.search('\d{6}$',sys.argv[1])
bash: Erreur de syntaxe près du symbole inattendu « ( »
~$ if m is None:
> try:
> id = s.findAll('div',attrs={"class":u"block-common block-player-programme"})[0]('canal:player')[0]['videoid']
bash: Erreur de syntaxe près du symbole inattendu « ( »
~$ except:
Commande 'except:' non trouvée, vouliez-vous dire :
La commande 'except' du paquet 'qmail' (universe)
except: : commande introuvable
~$
Display all 2596 possibilities? (y or n)
~$ t 'imposiible de trouver l\'id de la video'
>
Sans doute là que ça coince.
J'ai tapé la ligne de commande dans le Terminal, rien ne se passe.
(en revanche, ma flèche du curseur est devenue une croix)
Hors ligne
#2689 Le 16/02/2013, à 14:10
angeline
Re : TVDownloader: télécharger les médias du net !
@K3c,
Merci, j'ai le même début, mais pas la même fin
cb@cb-desktop:~$ pluzzdl -v http://pluzz.francetv.fr/videos/jt20h.html
[DEBUG ] main.py pluzzdl 0.9.4 avec Python 2.7.3 (i686)
[DEBUG ] main.py OS : Linux #58-Ubuntu SMP Thu Jan 24 15:51:02 UTC 2013
[DEBUG ] Navigateur.py GET http://pluzz.francetv.fr/videos/jt20h.html
[DEBUG ] PluzzDL.py ID de l'émission : 77106215
[DEBUG ] Navigateur.py GET http://www.pluzz.fr/appftv/webservices/video/getInfosOeuvre.php?mode=zeri&id-diffusion=77106215
[DEBUG ] PluzzDL.py Lien MMS : mms://a988.v101995.c10199.e.vm.akamaistream.net/7/988/10199/3f97c7e6/ftvigrp.download.akamai.com/10199/cappuccino/production/publication/Autre/Autre/2013/S07/J5/738525_jt20h_20130215.wmv
[DEBUG ] PluzzDL.py Lien RTMP : None
[DEBUG ] PluzzDL.py URL manifest : http://ftvodhdsecz-f.akamaihd.net/z/streaming-adaptatif/2013/S07/J5/77106215-20130215-,398,632,934,k.mp4.csmil/manifest.f4m
[DEBUG ] PluzzDL.py URL m3u8 : http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J5/77106215-20130215.m3u8
[DEBUG ] PluzzDL.py Utilisation de DRM : non
[DEBUG ] PluzzDL.py Chaine : France 2
[DEBUG ] Historique.py Historique chargé
[DEBUG ] Navigateur.py GET http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J5/77106215-20130215.m3u8
[DEBUG ] Navigateur.py Forbidden
Traceback (most recent call last):
File "/usr/share/pluzzdl/main.py", line 91, in <module>
progressFnct = progressFnct )
File "/usr/share/pluzzdl/PluzzDL.py", line 119, in __init__
downloader.telecharger()
File "/usr/share/pluzzdl/PluzzDL.py", line 259, in telecharger
self.m3u8 = self.navigateur.getFichier( self.m3u8URL )
File "/usr/share/pluzzdl/Navigateur.py", line 58, in getFichier
page = self.urlOpener.open( requete, timeout = self.timeOut )
File "/usr/lib/python2.7/urllib2.py", line 406, in open
response = meth(req, response)
File "/usr/lib/python2.7/urllib2.py", line 519, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python2.7/urllib2.py", line 444, in error
return self._call_chain(*args)
File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 527, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden
[DEBUG ] Historique.py Historique sauvé
Je sèche.
PS.: cela va si mal que cela en France... que les infos ne doivent pas sortir de l'hexagone ?
Edit: Oubliez la ligne au dessus... Avec Opera, cela se charge, mais très lentement, (en pointillés) du à mon internet très lent, et ce n'est pas regardable! D'où la nécessité de télécharger.
Dernière modification par angeline (Le 16/02/2013, à 14:25)
ıɔǝɔ ǝɯɯoɔ xnǝıɯ ʇsǝ,ɔ nʇunqnʞ
Hors ligne
#2690 Le 16/02/2013, à 15:05
k3c
Re : TVDownloader: télécharger les médias du net !
@ mulder29
tu exécutes du bash, pas du python
@ angeline
n'étant pas en France, il te faudrait un proxy France,non ?
Hors ligne
#2691 Le 16/02/2013, à 15:12
mulder29
Re : TVDownloader: télécharger les médias du net !
ok et comment je fais pour passer en mode "python" ?
Hors ligne
#2692 Le 16/02/2013, à 15:13
angeline
Re : TVDownloader: télécharger les médias du net !
@K3c
Par Opera ou Firefox, je ne passe pas par un proxy actuellement.
Avec Opera, j'ai droit à un bonus de 50 secondes de pub... qui fonctionne très bien !
Par Firefox, c'est bloqué par AdBlock, mais le journal dans tous les cas arrive trop lentement.
Le pb me parait autre part.
ıɔǝɔ ǝɯɯoɔ xnǝıɯ ʇsǝ,ɔ nʇunqnʞ
Hors ligne
#2693 Le 16/02/2013, à 15:53
angeline
Re : TVDownloader: télécharger les médias du net !
@Kc2
Si je récupère
[DEBUG ] PluzzDL.py Lien MMS : mms://a988.v101995.c10199.e.vm.akamaistream.net/7/988/10199/3f97c7e6/ftvigrp.download.akamai.com/10199/cappuccino/production/publication/Autre/Autre/2013/S07/J5/738525_jt20h_20130215.wmv
que je change le "mms" en "rtsp" le journal est téléchargeable par mon downloader préféré !
Mais pas par "pluzzdl"
ıɔǝɔ ǝɯɯoɔ xnǝıɯ ʇsǝ,ɔ nʇunqnʞ
Hors ligne
#2694 Le 16/02/2013, à 23:22
angeline
Re : TVDownloader: télécharger les médias du net !
C'était trop beau... cela n'a pas duré.
[DEBUG ] PluzzDL.py Lien MMS : None
[DEBUG ] PluzzDL.py Lien RTMP : None
Donc, comment passer par un proxy S.V.P.
ıɔǝɔ ǝɯɯoɔ xnǝıɯ ʇsǝ,ɔ nʇunqnʞ
Hors ligne
#2695 Le 16/02/2013, à 23:28
mulder29
Re : TVDownloader: télécharger les médias du net !
Ok, j'ai installé idle, j'ai lancé une python shell et j'ai ouvert mon dossier leafpad d8.py en prenant soin de copier/coller le texte
J'ai ensuite copié dans le terminal le lien
python d8.py http://www.d8.tv/d8-series/pid5313-d8-h.html
et... il n'a l'air de rien se passer en fait.
Hors ligne
#2696 Le 17/02/2013, à 00:11
k3c
Re : TVDownloader: télécharger les médias du net !
@ angeline
$ pluzzdl --help
usage: pluzzdl [options] urlEmission
Télécharge les émissions de Pluzz
positional arguments:
urlEmission URL de l'émission Pluzz a charger
optional arguments:
-h, --help show this help message and exit
-b, --progressbar affiche la progression du téléchargement
-p PROXY, --proxy PROXY
utilise un proxy HTTP au format suivant
http://URL:PORT
-s, --sock si un proxy est fourni avec l'option -p, un proxy
SOCKS5 est utilisé au format suivant ADRESSE:PORT
-v, --verbose affiche les informations de debugage
-t, --soustitres récupère le fichier de sous-titres de la vidéo (si
disponible)
--nocolor désactive la couleur dans le terminal
--version show program's version number and exit
donc pluzzdl -p http://1.2.3.4:80 ...
en supposant que 1.2.3.4:80 est un proxy français valide
@ mulder 29
quand je lance ta commande, ça m'affiche
python d8.py http://www.d8.tv/d8-series/pid5313-d8-h.html
rtmpdump -r "rtmp://vod-fms.canalplus.fr/ondemand/videos/1302/1047160_20_1500k.mp4" -o "H.mp4"
en fait cette procédure lance juste la commande ci-dessus
Hors ligne
#2697 Le 17/02/2013, à 00:51
angeline
Re : TVDownloader: télécharger les médias du net !
@K3c
Merci pour la réponse.
Cependant, je doute !
J'ai essayé 6/7 proxy... pas un ne veut coopérer.
Par un navigateur: Firefox, Opéra, ou Chromium, l'émission passe. Sans proxy.
Par pluzzdll, toujours la même interdiction
cb@cb-desktop:~$ pluzzdl -v http://pluzz.francetv.fr/videos/jt20h.html
[DEBUG ] main.py pluzzdl 0.9.4 avec Python 2.7.3 (i686)
[DEBUG ] main.py OS : Linux #58-Ubuntu SMP Thu Jan 24 15:51:02 UTC 2013
[DEBUG ] Navigateur.py GET http://pluzz.francetv.fr/videos/jt20h.html
[DEBUG ] PluzzDL.py ID de l'émission : 77496935
[DEBUG ] Navigateur.py GET http://www.pluzz.fr/appftv/webservices/video/getInfosOeuvre.php?mode=zeri&id-diffusion=77496935
[DEBUG ] PluzzDL.py Lien MMS : mms://a988.v101995.c10199.e.vm.akamaistream.net/7/988/10199/3f97c7e6/ftvigrp.download.akamai.com/10199/cappuccino/production/publication/Autre/Autre/2013/S07/J6/740386_jt20h_20130216.wmv
[DEBUG ] PluzzDL.py Lien RTMP : None
[DEBUG ] PluzzDL.py URL manifest : http://ftvodhdsecz-f.akamaihd.net/z/streaming-adaptatif/2013/S07/J6/77496935-20130216-,398,632,934,k.mp4.csmil/manifest.f4m
[DEBUG ] PluzzDL.py URL m3u8 : http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J6/77496935-20130216.m3u8
[DEBUG ] PluzzDL.py Utilisation de DRM : non
[DEBUG ] PluzzDL.py Chaine : France 2
[DEBUG ] Historique.py Historique chargé
[DEBUG ] Navigateur.py GET http://medias2.francetv.fr/catchup-mobile/france-dom-tom/non-token/non-drm/m3u8/2013/S07/J6/77496935-20130216.m3u8
[DEBUG ] Navigateur.py Forbidden
Traceback (most recent call last):
File "/usr/share/pluzzdl/main.py", line 91, in <module>
progressFnct = progressFnct )
File "/usr/share/pluzzdl/PluzzDL.py", line 119, in __init__
downloader.telecharger()
File "/usr/share/pluzzdl/PluzzDL.py", line 259, in telecharger
self.m3u8 = self.navigateur.getFichier( self.m3u8URL )
File "/usr/share/pluzzdl/Navigateur.py", line 58, in getFichier
page = self.urlOpener.open( requete, timeout = self.timeOut )
File "/usr/lib/python2.7/urllib2.py", line 406, in open
response = meth(req, response)
File "/usr/lib/python2.7/urllib2.py", line 519, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python2.7/urllib2.py", line 444, in error
return self._call_chain(*args)
File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 527, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden
[DEBUG ] Historique.py Historique sauvé
Par chance, France télévision s'est réveillé, et maintenant une URL en mms apparait.
Il est 18h ici, je télécharge.
Avec proxy j'obtiens:
pluzzdl -v -p http://176.31.247.227:8085 http://pluzz.francetv.fr/videos/jt20h.html
[DEBUG ] main.py pluzzdl 0.9.4 avec Python 2.7.3 (i686)
[DEBUG ] main.py OS : Linux #58-Ubuntu SMP Thu Jan 24 15:51:02 UTC 2013
[DEBUG ] Navigateur.py GET http://pluzz.francetv.fr/videos/jt20h.html
[CRITICAL] PluzzDL.py Impossible de récupérer l'ID de l'émission
Mais je pense que peu de proxy laissent passer les infos de vidéo, du moins dans les gratuits.
Je reste à l'écoute.
Dernière modification par angeline (Le 17/02/2013, à 00:53)
ıɔǝɔ ǝɯɯoɔ xnǝıɯ ʇsǝ,ɔ nʇunqnʞ
Hors ligne
#2698 Le 17/02/2013, à 02:17
mulder29
Re : TVDownloader: télécharger les médias du net !
@ mulder 29
quand je lance ta commande, ça m'affiche
python d8.py http://www.d8.tv/d8-series/pid5313-d8-h.html
rtmpdump -r "rtmp://vod-fms.canalplus.fr/ondemand/videos/1302/1047160_20_1500k.mp4" -o "H.mp4"
en fait cette procédure lance juste la commande ci-dessus
Euh, moi, ça reste sur la ligne sur python...
et aucune autre réaction o_O
Ok, donc il y a vraiment un bug dans mon système et python est inutilisable chez moi.
Hors ligne
#2699 Le 17/02/2013, à 02:20
k3c
Re : TVDownloader: télécharger les médias du net !
si tu tapes dans un terminal
python
ça t'affiche quoi ?
Hors ligne
#2700 Le 17/02/2013, à 10:59
mulder29
Re : TVDownloader: télécharger les médias du net !
Ça m'affiche :
Python 2.7.3 (default, Aug 1 2012, 05:16:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
par rapport à la commande fait précédemment, tu en déduis ?
Hors ligne
|
I am using Python 3.2.I wrote a build log file by using the following code:
rsltFile = open('buildLog.txt', 'wb')
p = subprocess.Popen('call ant compile', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout.readlines():
rsltFile.write(line)
retval = p.wait()
Then I am using the following to send an email with above file attached:
def send_mail(send_from, send_to, subject, text, files=[], server="XXX.XXX.com"):
assert type(send_to)==list
assert type(files)==list
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach( MIMEText(text) )
for f in files:
part = MIMEBase('application', "octet-stream")
part.set_payload( open(f,"rb").read() )
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
msg.attach(part)
smtp = smtplib.SMTP(server)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()
but I got the following error:
File "C:\workspace\VCT2400_Service\ServiceApplication\autobuild\myMail.py", line 29, in send_mail
smtp.sendmail(send_from, send_to, msg.as_string())
File "C:\Python32\lib\email\message.py", line 168, in as_string
g.flatten(self, unixfrom=unixfrom)
File "C:\Python32\lib\email\generator.py", line 91, in flatten
self._write(msg)
File "C:\Python32\lib\email\generator.py", line 137, in _write
self._dispatch(msg)
File "C:\Python32\lib\email\generator.py", line 163, in _dispatch
meth(msg)
File "C:\Python32\lib\email\generator.py", line 224, in _handle_multipart
g.flatten(part, unixfrom=False, linesep=self._NL)
File "C:\Python32\lib\email\generator.py", line 91, in flatten
self._write(msg)
File "C:\Python32\lib\email\generator.py", line 137, in _write
self._dispatch(msg)
File "C:\Python32\lib\email\generator.py", line 163, in _dispatch
meth(msg)
File "C:\Python32\lib\email\generator.py", line 192, in _handle_text
raise TypeError('string payload expected: %s' % type(payload))
TypeError: string payload expected: <class 'bytes'>
|
I have an XML file with several thousand records in it in the form of:
<custs> <record cust_ID="B123456@Y1996" l_name="Jungle" f_name="George" m_name="OfThe" city="Fairbanks" zip="00010" current="1" /> <record cust_ID="Q975697@Z2000" l_name="Freely" f_name="I" m_name="P" city="Yellow River" zip="03010" current="1" /> <record cust_ID="M7803@J2323" l_name="Jungle" f_name="Jim" m_name="" city="Fallen Arches" zip="07008" current="0" /></custs> # (I know it's not normalized. This is just sample data)
How can I convert this into a CSV or tab-delimited file? I know I can hard-code it in Python using re.compile() statements, but there has to be something easier, and more portable among diff XML file layouts.
I've found a couple threads here about attribs, (Beautifulsoup unable to extract data using attrs=class, Extracting an attribute value with beautifulsoup) and they have gotten me almost there with:
# Python 3.30
#
from bs4 import BeautifulSoup
import fileinput
Input = open("C:/Python/XML Tut/MinGrp.xml", encoding = "utf-8", errors = "backslashreplace")
OutFile = open('C:/Python/XML Tut/MinGrp_Out.ttxt', 'w', encoding = "utf-8", errors = "backslashreplace")
soup = BeautifulSoup(Input, features="xml")
results = soup.findAll('custs', attrs={})
# output = results [0]#[0]
for each_tag in results:
cust_attrb_value = results[0]
# print (cust_attrb_value)
OutFile.write(cust_attrb_value)
OutFile.close()
What's the next (last?) step?
|
Topic: Jquery update through XML
Hi,
We are building a web app that needs to be able to update records through jquery in an XML format to our controller.
We already have this working, but when updating we always get something like this in our database
--- !map:ActiveSupport::HashWithIndifferentAccess
div: !map:ActiveSupport::HashWithIndifferentAccess
class: tables
div: !map:ActiveSupport::HashWithIndifferentAccess
style: "position: relative;"
class: table
div: !map:ActiveSupport::HashWithIndifferentAccess
class: tablePart simple
div: !map:ActiveSupport::HashWithIndifferentAccess
class: block
network_infrastructure_id: "1"
network_infrastructure_name: VISI-201-NW
This is the HTML we are sending through xml.
<div class="tables"><div style="position: relative;" class="table"><div class="tablePart simple"><div class="block" network_infrastructure_id="1" network_infrastructure_name="VISI-201-NW"></div></div></div></div>
This is the jquery code we are using
$.ajax({
type: "PUT",
url: "/network_internet_control_layouts/"+room_id+".xml",
data: '<network-internet-control-layout><layout>'+$("div#temp").html()+'</layout></network-internet-control-layout>',
contentType: 'application/xml', // format of request payload
dataType: 'xml', // format of the response
success: function(msg) {
alert( "Data Saved: " + msg );
}
});
Do I need to escape something or what could be the problem?
Last edited by reyntjensw (2011-03-29 03:21:16)
|
FelixP
[Résolu] Sources de Logiciels ne veut plus démarrer…
Salut ! Je reposte mon problème car il semblerait que mon ancien post soit tombé dans les abîsses…
Lorsque je veux ouvrir la liste des sources de logiciels, j'obtiens une erreur…
Ce problème est apparu, je crois, après ajout du dépot permettant d'installer camllight, et d'autres personnes ont déjà eu le même problème, mais je n'ai pas compris comment le résoudre…
Sources de logiciels ne démarre pas dans Quantal [Résolu]
Voici ce que j'ai en console :
felix@astrotux:~$ software-properties-gtk
gpg: /tmp/tmp4xm_2e/trustdb.gpg: base de confiance créée
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/UbuntuDrivers/detect.py", line 162, in packages_for_modalias
cache_map = packages_for_modalias.cache_maps[apt_cache_hash]
KeyError: 5193189
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/bin/software-properties-gtk", line 103, in <module>
app = SoftwarePropertiesGtk(datadir=options.data_dir, options=options, file=file)
File "/usr/lib/python3/dist-packages/softwareproperties/gtk/SoftwarePropertiesGtk.py", line 178, in __init__
self.init_drivers()
File "/usr/lib/python3/dist-packages/softwareproperties/gtk/SoftwarePropertiesGtk.py", line 1097, in init_drivers
self.devices = detect.system_device_drivers()
File "/usr/lib/python3/dist-packages/UbuntuDrivers/detect.py", line 415, in system_device_drivers
for pkg, pkginfo in system_driver_packages(apt_cache).items():
File "/usr/lib/python3/dist-packages/UbuntuDrivers/detect.py", line 319, in system_driver_packages
for p in packages_for_modalias(apt_cache, alias):
File "/usr/lib/python3/dist-packages/UbuntuDrivers/detect.py", line 164, in packages_for_modalias
cache_map = _apt_cache_modalias_map(apt_cache)
File "/usr/lib/python3/dist-packages/UbuntuDrivers/detect.py", line 129, in _apt_cache_modalias_map
m = package.candidate.record['Modaliases']
File "/usr/lib/python3/dist-packages/apt/package.py", line 429, in record
return Record(self._records.record)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 491: invalid continuation byte
Pouvez-vous m'aider à résoudre ce problème ? Je vous en remercie d'avance !
Félix
Dernière modification par FelixP (Le 02/12/2012, à 23:18)
Hors ligne
FelixP
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Voilà le contenu de mon fichier !
# deb cdrom:[Ubuntu 12.10 _Quantal Quetzal_ - Release amd64 (20121017.5)]/ quantal main restricted
# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
deb http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal main restricted
deb-src http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal main restricted
## Major bug fix updates produced after the final release of the
## distribution.
deb http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-updates main restricted
deb-src http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-updates main restricted
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team. Also, please note that software in universe WILL NOT receive any
## review or updates from the Ubuntu security team.
deb http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal universe
deb-src http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal universe
deb http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-updates universe
deb-src http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-updates universe
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
deb http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal multiverse
deb-src http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal multiverse
deb http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-updates multiverse
deb-src http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-updates multiverse
## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
deb http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-backports main restricted universe multiverse
deb-src http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-backports main restricted universe multiverse
deb http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-security main restricted
deb-src http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-security main restricted
deb http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-security universe
deb-src http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-security universe
deb http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-security multiverse
deb-src http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-security multiverse
## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
deb http://archive.canonical.com/ubuntu quantal partner
deb-src http://archive.canonical.com/ubuntu quantal partner
## This software is not part of Ubuntu, but is offered by third-party
## developers who want to ship their latest software.
deb http://extras.ubuntu.com/ubuntu quantal main
deb-src http://extras.ubuntu.com/ubuntu quantal main
deb http://boisson.homeip.net/depot quantal divers
deb-src http://boisson.homeip.net/depot quantal divers
deb http://ftp.free.org/mirrors/archive.ubuntu.com/ubuntu/ quantal-proposed restricted main multiverse universe
Hors ligne
FelixP
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
D'accord, merci déjà ! Sinon, j'avais changé les sources pour mettre "les plus rapides" mais ce n'est hélas absolument pas le cas…
Comment puis-je rétablir les sources par défaut ?
Hors ligne
amj
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Hors ligne
FelixP
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Ah c'est bon j'ai trouvé un générateur en ligne, il m'a fourni ceci :
#############################################################
################### OFFICIAL UBUNTU REPOS ###################
#############################################################
###### Ubuntu Main Repos
deb http://fr.archive.ubuntu.com/ubuntu/ quantal main restricted universe multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ quantal main restricted universe multiverse
###### Ubuntu Update Repos
deb http://fr.archive.ubuntu.com/ubuntu/ quantal-security main restricted universe multiverse
deb http://fr.archive.ubuntu.com/ubuntu/ quantal-updates main restricted universe multiverse
deb http://fr.archive.ubuntu.com/ubuntu/ quantal-proposed main restricted universe multiverse
deb http://fr.archive.ubuntu.com/ubuntu/ quantal-backports main restricted universe multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ quantal-security main restricted universe multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ quantal-updates main restricted universe multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ quantal-proposed main restricted universe multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ quantal-backports main restricted universe multiverse
###### Ubuntu Partner Repo
deb http://archive.canonical.com/ubuntu quantal partner
###### Ubuntu Extras Repo
deb http://extras.ubuntu.com/ubuntu quantal main
##############################################################
##################### UNOFFICIAL REPOS ######################
##############################################################
###### 3rd Party Binary Repos
## Run this command: sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 1378B444
deb http://ppa.launchpad.net/libreoffice/ppa/ubuntu quantal main # LibreOffice - http://www.documentfoundation.org/download/
## Run this command: sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 247510BE
deb http://ppa.launchpad.net/ubuntu-mozilla-daily/ppa/ubuntu quantal main # Mozilla Daily Build Team - http://edge.launchpad.net/~ubuntu-mozilla-daily/+archive/ppa
et
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 1378B444
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 247510BE
Hors ligne
FelixP
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Ah je n'avais pas vu votre réponse ! C'est parfait, merci beaucoup !
Hors ligne
amj
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
peut-être aussi
qui étais déjà dans vos sources
Dernière modification par amj (Le 12/11/2012, à 21:52)
Hors ligne
FelixP
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Celle-là je n'en ai plus besoin… C'était pour camllight, un langage affreux qu'on nous oblige à utiliser en prépa…
Hors ligne
FelixP
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Bon, ça résoud pas mon problème initial mais c'est une bonne alternative ! Merci !
Hors ligne
FelixP
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Merci ! Bonne soirée à vous !
Hors ligne
tutoux
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Bonjour,
ça ressemble à ce que j'ai raconté ici :
http://forum.ubuntu-fr.org/viewtopic.ph … #p11498311
peut-être que la démarche indiquée marchera dans ton cas :
http://ubuntuforums.org/archive/index.p … 02417.html
on y croit... :-)
Hors ligne
FelixP
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
En fait j'ai constaté que si je n'ajoute pas le dépot
deb http://boisson.homeip.net/depot quantal divers
je n'ai pas le problème et il apparait PENDANT l'install (hors dépot) du paquet camllight et disparait à la désinstall.
Je vais demander au créateur du paquet demain car je le connais, de voir quel serait le problème.
Hors ligne
fran.b
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
J'ai supprimé tous les accents pour les paquets quantal. Mais c'est étonnant, c'est spécifique à quantal ce problème semble-t-il....Est ce que désormais le problème est résolu?
Hors ligne
FelixP
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
je testerai ce soir et vous dirai !
Hors ligne
FelixP
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Génial ! L'installation hors dépot fonctionne à merveille ! Par contre l'ajout du dépôt provoque toujours le bug…
Hors ligne
fran.b
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Bon, il faut comprendre.
Le problème est dans le fichier /var/lib/apt/lists/boisson.homeip.net_ubuntu_dists_quantal_divers_binary-i386_Packages.
Que contient-il?
Est ce que le problème a lieu lors de
# apt-get install camllight
ou bien à l'utilisation d'un synaptic quelconque (je pense à une erreur de software-properties-gtk)
Je pense au bug https://bugs.launchpad.net/ubuntu/+sour … ug/1026066
Dernière modification par fran.b (Le 14/11/2012, à 23:13)
Hors ligne
FelixP
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Non, c'est avant même update que le bug arrive, donc avant la création de /var/lib/apt/lists/boisson*
Et il n'y a effectivement que software-properties-gtk qui bugue. Cette fenêtre :
Je peux installer des logiciels sans problème.
Comme je disais il suffit que l'install arrive au choix "nettoyer sites.el ?", et je peux constater déjà l'apparition du bug.
Hors ligne
fran.b
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Bon, c'est un problème spécifique à software-properties-gtk qui existait à l'époque de natty et qui semble resurgir. Peut être qu'en installant la version de precise?? Eventuellement ne édition à la main du fichier /var/lib/apt/lists/boisson.homeip.net_ubuntu_dists_quantal_divers_binary-i386_Packages en virant les accents devrait arranger les choses.
Hors ligne
FelixP
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Non, ça ne fait rien… La seule façon de réparer le bug une fois la source ajoutée et update fait, est de supprimer le dépôt de la liste… J'ai fait une vidéo de capture d'écran, je vais essayer de l'uploader !
Hors ligne
FelixP
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Désolé, je pense que c'est en flash… Mais je ne sais pas comment faire autrement !
http://www.youtube.com/watch?v=gK6lq5Zu … e=youtu.be
Hors ligne
amj
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Désolé, je pense que c'est en flash… Mais je ne sais pas comment faire autrement !
http://www.youtube.com/watch?v=gK6lq5Zu … e=youtu.be
non je pense que youtube est en html5
Hors ligne
FelixP
Re : [Résolu] Sources de Logiciels ne veut plus démarrer…
Il y a des vidéos dans les 2 formats… Ils sont en train «d'opérer le changement» ^^
Hors ligne
|
It is recommended to not to use import * in Python. Can anyone please share the reason for that, so that I can avoid it doing next time?
According to the Python Zen:
... can't argue with that, surely?
You don't pass
Since Python lacks an "include" statement,
The
Also, it has a concrete possibility of hiding bugs.
import os, sys, foo, sqlalchemy, mystuff
from bar import *
Now, if the bar module has any of the "
Don't misunderstand me: if the
I think in medium-to-big projects, or small ones with several contributors, a minimum of hygiene is needed in terms of statical analysis -- running at least pyflakes or even better a properly configured pylint -- to catch several kind of bugs before they happen.
Of course since this is python -- feel free to break rules, and to explore -- but be wary of projects that could grow tenfold, if the source code is missing discipline it will be a problem.
That is because you are polluting the namespace. You will import all the functions and classes in your own namespace, which may clash with the functions you define yourself.
Furthermore, I think using a qualified name is more clear for the maintenance task; you see on the code line itself where a function comes from, so you can check out the docs much more easily.
In module foo:
def myFunc():
print 1
In your code:
from foo import *
def doThis():
myFunc() # Which myFunc is called?
def myFunc():
print 2
say you have the following code in a module called foo:
import ElementTree as etree
and then in your own module you have:
from lxml import etree
from foo import *
You now have a difficult-to-debug module that
|
Rules in Flask are unique. If you define the absolute same URL to the same function it will by default clash because you're doing something which we stop you from doing since from our perspective that is wrong.
There is one reason why you would want to have more than one URL to the absolute same endpoint and that is backwards compatibility with a rule that existed in the past. Since WZ0.8 and Flask 0.8 you can explicitly specify an alias for a route:
@app.route('/')
@app.route('/index.html', alias=True)
def index():
return ...
In this case if the user requests /index.html Flask will automatically issue a permanently redirect to just /.
That does not mean a function could not be bound to more than one url though, but in this case you would need to change the endpoint:
@app.route('/')
def index():
...
app.add_url_rule('/index.html', view_func=index, endpoint='alt_index')
Or alternatively:
@app.route('/')
@app.route('/index.html', endpoint='alt_index')
def index():
...
In this case you can define a view a second time under a different name. However this is something you generally want to avoid because then the view function would have to check request.endpoint to see what is called. Instead better do something like this:
@app.route('/')
def index():
return _index(alt=False)
@app.route('/index.html')
def alt_index():
return _index(alt=True)
def _index(alt):
...
In both of these cases URL generation is url_for('index') or url_for('alt_index').
You can also do this on the routing system level:
@app.route('/', defaults={'alt': False})
@app.route('/index.html', defaults={'alt': True})
def index(alt):
...
In this case url generation is url_for('index', alt=True) or url_for('index', alt=False).
|
You can use Bulbs (http://bulbflow.com/) with Neo4j Server or Rexster:
>>> from bulbs.neo4jserver import Graph
>>> g = Graph()
>>> g.vertices.create(name="James")
>>> g.vertices.create(name="Julie")
>>> g.edges.create(james, "knows", julie)
Or to use Rexster, just change the import:
>>> from bulbs.rexster import Graph
>>> g = Graph()
>>> g.vertices.create(name="James")
>>> g.vertices.create(name="Julie")
>>> g.edges.create(james, "knows", julie)
Note though with Rexster, it supports multiple graph databases so make sure you change the default DB URI in the config:
>>> from bulbs.rexster import Graph, Config
>>> config = Config('http://localhost:8182/graph/neo4jsample')
>>> g = Graph(config)
>>> ...
|
Anna's second solution is the inspiration for this one.
First, load all the words into memory and divide the dictionary into sections based on word length.
For each length, make n copies of an array of pointers to the words. Sort each array so that the strings appear in order when rotated by a certain number of letters. For example, suppose the original list of 5-letter words is [plane, apple, space, train, happy, stack, hacks]. Then your five arrays of pointers will be:
rotated by 0 letters: [apple, hacks, happy, plane, space, stack, train]
rotated by 1 letter: [hacks, happy, plane, space, apple, train, stack]
rotated by 2 letters: [space, stack, train, plane, hacks, apple, happy]
rotated by 3 letters: [space, stack, train, hacks, apple, plane, happy]
rotated by 4 letters: [apple, plane, space, stack, train, hacks, happy]
(Instead of pointers, you can use integers identifying the words, if that saves space on your platform.)
To search, just ask how much you would have to rotate the pattern so that the question marks appear at the end. Then you can binary search in the appropriate list.
If you need to find matches for ??ppy, you would have to rotate that by 2 to make ppy??. So look in the array that is in order when rotated by 2 letters. A quick binary search finds that "happy" is the only match.
If you need to find matches for th??g, you would have to rotate that by 4 to make gth??. So look in array 4, where a binary search finds that there are no matches.
This works no matter how many question marks there are, as long as they all appear together.
Space required in addition to the dictionary itself: For words of length N, this requires space for (N times the number of words of length N) pointers or integers.
Time per lookup: O(log n) where n is the number of words of the appropriate length.
Implementation in Python:
import bisect
class Matcher:
def __init__(self, words):
# Sort the words into bins by length.
bins = []
for w in words:
while len(bins) <= len(w):
bins.append([])
bins[len(w)].append(w)
# Make n copies of each list, sorted by rotations.
for n in range(len(bins)):
bins[n] = [sorted(bins[n], key=lambda w: w[i:]+w[:i]) for i in range(n)]
self.bins = bins
def find(self, pattern):
bins = self.bins
if len(pattern) >= len(bins):
return []
# Figure out which array to search.
r = (pattern.rindex('?') + 1) % len(pattern)
rpat = (pattern[r:] + pattern[:r]).rstrip('?')
if '?' in rpat:
raise ValueError("non-adjacent wildcards in pattern: " + repr(pattern))
a = bins[len(pattern)][r]
# Binary-search the array.
class RotatedArray:
def __len__(self):
return len(a)
def __getitem__(self, i):
word = a[i]
return word[r:] + word[:r]
ra = RotatedArray()
start = bisect.bisect(ra, rpat)
stop = bisect.bisect(ra, rpat[:-1] + chr(ord(rpat[-1]) + 1))
# Return the matches.
return a[start:stop]
words = open('/usr/share/dict/words', 'r').read().split()
print "Building matcher..."
m = Matcher(words) # takes 1-2 seconds, for me
print "Done."
print m.find("st??k")
print m.find("ov???low")
On my computer, the system dictionary is 909KB big and this program uses about 3.2MB of memory in addition to what it takes just to store the words (pointers are 4 bytes). For this dictionary, you could cut that in half by using 2-byte integers instead of pointers, because there are fewer than 216 words of each length.
Measurements: On my machine, m.find("st??k") runs in 0.000032 seconds, m.find("ov???low") in 0.000034 seconds, and m.find("????????????????e") in 0.000023 seconds.
By writing out the binary search instead of using class RotatedArray and the bisect library, I got those first two numbers down to 0.000016 seconds: twice as fast. Implementing this in C++ would make it faster still.
|
How could I create playlists for all of the albums in iTunes for which I have all of the songs? Assume that track number & track count metadata is accurate where specified, and don't worry about catching tracks which lack that metadata. I assume this will require AppleScript.
I realized this was a complicated enough question I ought to try to skin the cat myself. Here is one approach:
-- Creates a playlist for each full album you have in iTunes
-- Set the playlistPrefix and playlistSuffix as desired before running
-- Based on code by Brad Campbell
-- http://www.bradcampbell.com/2009/05/26/make-a-whole-album-playlist-in-itunes/
tell application "iTunes"
set playlistPrefix to "FA: "
set playlistSuffix to ""
-- The "FA: " prefix will help cluster full albums in iTunes' playlists,
-- and is narrow enough to not get in your way when viewing on an iPhone
set albumBuckets to {} as list
set allSongs to (every track of library playlist 1 whose enabled is true and podcast is false and kind contains "audio") as list
-- Find all partial albums in iTunes
repeat with currentTrack in allSongs
set albumName to album of currentTrack as text
set artistName to artist of currentTrack as text
-- First check for missing values, then perform integer comparison
-- Zero is on the left to force interger type coercion, just in case
if album of currentTrack is not missing value and 0 is less than length of albumName then
if artist of currentTrack is not missing value and 0 is less than length of artistName then
if track number of currentTrack is not missing value and 0 is less than track number of currentTrack then
if track count of currentTrack is not missing value and 0 is less than track count of currentTrack then
if albumBuckets does not contain album of currentTrack then
copy album of currentTrack to the end of albumBuckets
end if
end if
end if
end if
end if
end repeat
repeat with currentAlbum in albumBuckets
set albumSongs to (every track of library playlist 1 whose album is currentAlbum)
set firstTrack to first item of albumSongs
-- Filter album list to act only on full albums
if (count of albumSongs) is equal to track count of first item of albumSongs and 1 is less than (count of albumSongs) then
-- This is a full album, construct the playlist
-- Sort tracks by track number
set albumSongsSorted to {} as list
repeat with i from 1 to (count of albumSongs)
repeat with trk in albumSongs
if track number of trk is i then
set nextSong to trk
copy nextSong to the end of albumSongsSorted
end if
end repeat
end repeat
-- Don't show artist name for compilations
if firstTrack is not compilation then
set playlistNameArtist to artist of firstTrack & " - "
else
set playlistNameArtist to ""
end if
set albumPlaylistName to playlistPrefix & playlistNameArtist & currentAlbum & playlistSuffix
-- Create playlist
if user playlist albumPlaylistName exists then
try
delete tracks of user playlist albumPlaylistName
end try
else
make new user playlist with properties {name:albumPlaylistName}
end if
try
repeat with trk in albumSongsSorted
duplicate trk to user playlist albumPlaylistName
end repeat
end try
end if
end repeat
display dialog "Playlists created! Check iTunes for playlists beginning with '" & playlistPrefix & "'"
end tell
To try this out, just copy and paste the code block into AppleScript Editor and push Run. Do be aware there's no easy "undo" button - you'll have to just hold down the delete key if you want to ditch all the created playlists.
There's probably a faster algorithm (i.e. one that makes only a single pass through iTunes' library) but I couldn't figure how to work with two dimensional variables in AppleScript, which seems like a prerequisite.
A bonus side effect of this script is that it may surface ancient albums in your library you have moved on from and can safely delete :)
protected by Community⦠May 24 '13 at 2:12
Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.
Would you like to answer one of these unanswered questions instead?
|
Module blast_xml
source code
Bio.SearchIO parser for BLAST+ XML output formats.
_empty_bytes_string = ''
_ELEM_QRESULT_OPT = {'Statistics_db-len': ('stat_db_len', <typ...
_ELEM_HIT = {'Hit_accession': ('accession', <type 'str'>), 'Hi...
_ELEM_HSP = {'Hsp_bit-score': ('bitscore', <type 'float'>), 'H...
_ELEM_FRAG = {'Hsp_align-len': ('aln_span', <type 'int'>), 'Hs...
_ELEM_META = {'BlastOutput_db': ('target', <type 'str'>), 'Bla...
_ELEM_QRESULT_FALLBACK = {'BlastOutput_query-ID': ('id', <type...
_WRITE_MAPS = {'hit': (('id', 'id'), ('def', 'description'), (...
_DTD_OPT = ('BlastOutput_query-seq', 'BlastOutput_mbstat', 'It...
_RE_VERSION = re.compile(r'\d+\.\d+\.\d+\+?')
__package__ = 'Bio.SearchIO.BlastIO'
_ELEM_QRESULT_OPT
Value:
{'Statistics_db-len': ('stat_db_len', <type 'int'>),
'Statistics_db-num': ('stat_db_num', <type 'int'>),
'Statistics_eff-space': ('stat_eff_space', <type 'float'>),
'Statistics_entropy': ('stat_entropy', <type 'float'>),
'Statistics_hsp-len': ('stat_hsp_len', <type 'int'>),
'Statistics_kappa': ('stat_kappa', <type 'float'>),
'Statistics_lambda': ('stat_lambda', <type 'float'>)}
_ELEM_HIT
Value:
{'Hit_accession': ('accession', <type 'str'>),
'Hit_len': ('seq_len', <type 'int'>)}
_ELEM_HSP
Value:
{'Hsp_bit-score': ('bitscore', <type 'float'>),
'Hsp_density': ('density', <type 'float'>),
'Hsp_evalue': ('evalue', <type 'float'>),
'Hsp_gaps': ('gap_num', <type 'int'>),
'Hsp_identity': ('ident_num', <type 'int'>),
'Hsp_positive': ('pos_num', <type 'int'>),
'Hsp_score': ('bitscore_raw', <type 'int'>)}
_ELEM_FRAG
Value:
{'Hsp_align-len': ('aln_span', <type 'int'>),
'Hsp_hit-frame': ('hit_frame', <type 'int'>),
'Hsp_hit-from': ('hit_start', <type 'int'>),
'Hsp_hit-to': ('hit_end', <type 'int'>),
'Hsp_hseq': ('hit', <type 'str'>),
'Hsp_pattern-from': ('pattern_start', <type 'int'>),
'Hsp_pattern-to': ('pattern_end', <type 'int'>),
'Hsp_qseq': ('query', <type 'str'>),
...
_ELEM_META
Value:
{'BlastOutput_db': ('target', <type 'str'>),
'BlastOutput_program': ('program', <type 'str'>),
'BlastOutput_reference': ('reference', <type 'str'>),
'BlastOutput_version': ('version', <type 'str'>),
'Parameters_entrez-query': ('param_entrez_query', <type 'str'>),
'Parameters_expect': ('param_evalue_threshold', <type 'float'>),
'Parameters_filter': ('param_filter', <type 'str'>),
'Parameters_gap-extend': ('param_gap_extend', <type 'int'>),
...
_ELEM_QRESULT_FALLBACK
Value:
{'BlastOutput_query-ID': ('id', <type 'str'>),
'BlastOutput_query-def': ('description', <type 'str'>),
'BlastOutput_query-len': ('len', <type 'str'>)}
_WRITE_MAPS
Value:
{'hit': (('id', 'id'),
('def', 'description'),
('accession', 'accession'),
('len', 'seq_len')),
'hsp': (('bit-score', 'bitscore'),
('score', 'bitscore_raw'),
('evalue', 'evalue'),
('query-from', 'query_start'),
...
_DTD_OPT
Value:
('BlastOutput_query-seq',
'BlastOutput_mbstat',
'Iteration_query-def',
'Iteration_query-len',
'Iteration-hits',
'Iteration_stat',
'Iteration_message',
'Parameters_matrix',
...
|
#2601 Le 29/12/2012, à 21:49
bibichouchou
Re : TVDownloader: télécharger les médias du net !
Dans le gestionnaire de paquet, as-tu remarqué s'il y avait une coche en face des lignes
http://ppa.launchpad.net/chaoswizard/tvdownloader/ubuntu quantal main
Si les lignes ne sont pas cochées, c'est que le dépôt n'est pas activé.
TVdownloader ne permet (permettait ?) de récupérer que les versions françaises des programmes, enfin il me semble. Je crois qu'à l'époque j'avais vu des discussions pour un programme dédié à arte afin de récupérer au choix les versions fr ou de. Serait-ce Quarte ??
Dernière modification par bibichouchou (Le 29/12/2012, à 21:54)
Hors ligne
#2602 Le 29/12/2012, à 21:54
pouchyk
Re : TVDownloader: télécharger les médias du net !
Merci f.x0 et bibichou !
Je suis un peu honteuse : je viens de trouver dans les paquetages quelque chose qui m'intéresse : mediathekview !
Ce logiciel recense quelques émissions de chaines allemandes - dont beaucoup m'intéressent, et d'autres restent à découvrir - et il permet d'enregistrer ces émissions...
Cela dit, je ne serais même pas aller chercher, si je n'avais pas su par ce forum qu'il y avait possibilité d'enregistrer des émissions, dont les podcast ne sont pas proposés sur les chaines.
Linux est décidément un OS super ! Et moi, j'ai encore plein de choses à apprendre !
Du coup, je ne vais sans doute plus vous embêter avec mes questions. Mais je vous remercie pour votre gentillesse à tous !
Bon réveillon de la St Sylvestre à tous, et je vous souhaite une bonne année 2013 !
Dernière modification par pouchyk (Le 29/12/2012, à 21:55)
Kubuntu 14.04 sur son Dell Inspiron 5720
Merci à tous ceux qui sont d'un grand secours sur ce forum !
Hors ligne
#2603 Le 29/12/2012, à 21:55
bibichouchou
Re : TVDownloader: télécharger les médias du net !
@pouchyk
Comme disent nos cousins de l'autre côte du Rhin, guten Rutsch !
Hors ligne
#2604 Le 29/12/2012, à 21:55
J5012
Re : TVDownloader: télécharger les médias du net !
ha chez moi le depot tvdnl est dans /etc/apt/sources.list.d
le /etc/apt/sources.list appelle ce fichier (une nouvelle dispo depuis 10.04 je crois)
il est possible que la section quantal ne soit pas encore operationnelle
je viens de verifier la config des paquets sur le depot, et il n'y a que precise qui permette l'install de tvdownloader, de pluzzdl, des autres outils ...
la section quantal ne permet l'install que de pluzzdl
soit tu restes en quantal pour le depot, et tu installes pluzzdl, ou tu installes tvdownloader depuis le site externe
soit tu tentes le depot pour precise ... il te suffit de changer quantal en precise dans la config du depot et de rafraichir
Hors ligne
#2605 Le 29/12/2012, à 22:12
pouchyk
Re : TVDownloader: télécharger les médias du net !
Einen guten Rutsch wünsche ich dir auch, Bibichouchou. Es freut mich, einen Germanisten hier zu treffen
Merci J5012 pour ton intervention... Mais je viens de trouver mon bonheur (il ne me faut pas grand chose n'est-ce pas?) avec MediathekView, et du coup, ça règle le problème par lâche abandon
Kubuntu 14.04 sur son Dell Inspiron 5720
Merci à tous ceux qui sont d'un grand secours sur ce forum !
Hors ligne
#2606 Le 29/12/2012, à 22:48
bibichouchou
Re : TVDownloader: télécharger les médias du net !
@pouchyk
Es freut mich auch Aber ich muss mein Deutsch immer noch verbessern
Merci à toi pour MediathekView.
Je récupère aussi des émissions sur arte en français et en allemand. Je m'étais fait un petit script mais il n'est pas codé très proprement
Hors ligne
#2607 Le 29/12/2012, à 22:50
pouchyk
Re : TVDownloader: télécharger les médias du net !
Je suis contente d'avoir - pour une fois - servi à quelque chose sur ce forum... même si ma contribution est minuscule : ça me permet de finir l'année avec un peu d'espoir pour l'an prochain
Kubuntu 14.04 sur son Dell Inspiron 5720
Merci à tous ceux qui sont d'un grand secours sur ce forum !
Hors ligne
#2608 Le 29/12/2012, à 23:35
k3c
Re : TVDownloader: télécharger les médias du net !
@ pouchyk
Pour les émissions d'Arte, qarte est excellent, comme déjà dit.
Hors ligne
#2609 Le 30/12/2012, à 00:26
Flo_
Re : TVDownloader: télécharger les médias du net !
Super MediathekView, je ne connaissais pas non plus.
Il n'ont pas l'air de s'embêter avec tout plein de scripts outre-Reins, tout à l'air de passer par rtmp ^^.
Flo
Dernière modification par Flo_ (Le 30/12/2012, à 00:29)
Hors ligne
#2610 Le 30/12/2012, à 13:13
pouchyk
Re : TVDownloader: télécharger les médias du net !
@bibichouchou
Je ne sais pas quelle est ta maitrise de l'allemand, et si tu aimes voir des vidéos dans cette langue... Mais pour le cas où cela t'intéresserait, il y a parfois des émissions sympas (notamment sur l'histoire - c'est ce qui m'intéresse le plus - mais il y a des tas d'autres sujets) sur
ZDF Zeitgeschichte
ou à récupérer ici
ZDF History
ou à récupérer ici
Podcast de ZDF
(mon côté prof : j'imagine que tout le monde va forcément s'intéresser à la même chose que moi et être avide de faire de l'allemand par n'importe quel moyen )
Kubuntu 14.04 sur son Dell Inspiron 5720
Merci à tous ceux qui sont d'un grand secours sur ce forum !
Hors ligne
#2611 Le 30/12/2012, à 15:21
bibichouchou
Re : TVDownloader: télécharger les médias du net !
@pouchyk
merci bcp de l'info. j'y jetterai un coup d'oeil dès que j'ai le temps. j'aime bien l'histoire aussi... et les sciences
PS : il ne faut pas qu'on fasse trop de hors-sujet sinon on va se faire gronder
Hors ligne
#2612 Le 30/12/2012, à 23:19
chaoswizard
Re : TVDownloader: télécharger les médias du net !
il ne faut pas qu'on fasse trop de hors-sujet sinon on va se faire gronder
Ah bon, par qui ?
Quand on est à 105 pages de messages, je crois que personne ne va râlait...
Ubuntu ==> Debian ==> Archlinux
Hors ligne
#2613 Le 31/12/2012, à 00:08
11gjm
Re : TVDownloader: télécharger les médias du net !
Bonjour ,
@k3c : Pour info . Je sais bien que cela ne résoud pas le PB .
---- avec captvty ----
http://www.tou.tv/belle-maman
Belle maman S2008E01.ts (53,6Mo)
----------------------
sans proxy .
Une adresse à tester :
http://www.xroxy.com/proxylist.php?port … liability=
Cordialement .
Hors ligne
#2614 Le 31/12/2012, à 12:28
k3c
Re : TVDownloader: télécharger les médias du net !
@ 11gjm
Merci
Le proxy n'est pas le problème, en fait il y a plein de vidéos non géolocalisées, comme les 70 épisodes de balades urbaines ou les chroniques d'une mère indigne.
Captvty fait comme Pluzz, utilise les liens m3u8 pour téléphones portables
Ce code est censé fonctionner,
https://github.com/bvanheu/Tou.tv-conso … /client.py
mais pas pour moi, je peux obtenir des infos sur des vidéos, mais au moment de télécharger j'ai toujours vidéo introuvable
Je commence à regarder plus en détail
Dernière modification par k3c (Le 31/12/2012, à 17:16)
Hors ligne
#2615 Le 04/01/2013, à 00:53
rvhm
Re : TVDownloader: télécharger les médias du net !
Bonjour
J’ai un problème avec le logiciel
Je l’ouvre, il me marque « Patientez pendant l’actualisation de tvdownloader » et ça se bloque
Et deux trois minutes en faisant controle alt suppr après il m’indique fermez l’application « main py »
et tout s’arête. Comment faire pour que le logiciel fonctionne ?
merci
Hors ligne
#2616 Le 04/01/2013, à 01:50
bibichouchou
Re : TVDownloader: télécharger les médias du net !
@rvhm
salut,
ctrl + alt +suppr ??? es-tu sous window$ ? viens-tu de l'installer ? ou est-ce que tu avais réussi à le faire marcher et le problème vient d'apparaître ?
Hors ligne
#2617 Le 04/01/2013, à 06:59
k3c
Re : TVDownloader: télécharger les médias du net !
si tu lances tvdownloader par
python -v /usr/share//tvdownloader/main.py
ça affiche quoi dans la console à la fin ?
Hors ligne
#2618 Le 04/01/2013, à 19:13
rvhm
Re : TVDownloader: télécharger les médias du net !
à la fin ça affiche :
import encodings.string_escape # precompiled from /usr/lib/python2.7/encodings/string_escape.pyc
Hors ligne
#2619 Le 04/01/2013, à 19:44
k3c
Re : TVDownloader: télécharger les médias du net !
@ rvhm
Radin ! :-)
Tu pourrais nous mettre plus de lignes ?
Hors ligne
#2620 Le 04/01/2013, à 20:03
rvhm
Re : TVDownloader: télécharger les médias du net !
# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
# /usr/lib/python2.7/site.pyc matches /usr/lib/python2.7/site.py
import site # precompiled from /usr/lib/python2.7/site.pyc
# /usr/lib/python2.7/os.pyc matches /usr/lib/python2.7/os.py
import os # precompiled from /usr/lib/python2.7/os.pyc
import errno # builtin
import posix # builtin
# /usr/lib/python2.7/posixpath.pyc matches /usr/lib/python2.7/posixpath.py
import posixpath # precompiled from /usr/lib/python2.7/posixpath.pyc
# /usr/lib/python2.7/stat.pyc matches /usr/lib/python2.7/stat.py
import stat # precompiled from /usr/lib/python2.7/stat.pyc
# /usr/lib/python2.7/genericpath.pyc matches /usr/lib/python2.7/genericpath.py
import genericpath # precompiled from /usr/lib/python2.7/genericpath.pyc
# /usr/lib/python2.7/warnings.pyc matches /usr/lib/python2.7/warnings.py
import warnings # precompiled from /usr/lib/python2.7/warnings.pyc
# /usr/lib/python2.7/linecache.pyc matches /usr/lib/python2.7/linecache.py
import linecache # precompiled from /usr/lib/python2.7/linecache.pyc
# /usr/lib/python2.7/types.pyc matches /usr/lib/python2.7/types.py
import types # precompiled from /usr/lib/python2.7/types.pyc
# /usr/lib/python2.7/UserDict.pyc matches /usr/lib/python2.7/UserDict.py
import UserDict # precompiled from /usr/lib/python2.7/UserDict.pyc
# /usr/lib/python2.7/_abcoll.pyc matches /usr/lib/python2.7/_abcoll.py
import _abcoll # precompiled from /usr/lib/python2.7/_abcoll.pyc
# /usr/lib/python2.7/abc.pyc matches /usr/lib/python2.7/abc.py
import abc # precompiled from /usr/lib/python2.7/abc.pyc
# /usr/lib/python2.7/_weakrefset.pyc matches /usr/lib/python2.7/_weakrefset.py
import _weakrefset # precompiled from /usr/lib/python2.7/_weakrefset.pyc
import _weakref # builtin
# /usr/lib/python2.7/copy_reg.pyc matches /usr/lib/python2.7/copy_reg.py
import copy_reg # precompiled from /usr/lib/python2.7/copy_reg.pyc
# /usr/lib/python2.7/traceback.pyc matches /usr/lib/python2.7/traceback.py
import traceback # precompiled from /usr/lib/python2.7/traceback.pyc
# /usr/lib/python2.7/sysconfig.pyc matches /usr/lib/python2.7/sysconfig.py
import sysconfig # precompiled from /usr/lib/python2.7/sysconfig.pyc
# /usr/lib/python2.7/re.pyc matches /usr/lib/python2.7/re.py
import re # precompiled from /usr/lib/python2.7/re.pyc
# /usr/lib/python2.7/sre_compile.pyc matches /usr/lib/python2.7/sre_compile.py
import sre_compile # precompiled from /usr/lib/python2.7/sre_compile.pyc
import _sre # builtin
# /usr/lib/python2.7/sre_parse.pyc matches /usr/lib/python2.7/sre_parse.py
import sre_parse # precompiled from /usr/lib/python2.7/sre_parse.pyc
# /usr/lib/python2.7/sre_constants.pyc matches /usr/lib/python2.7/sre_constants.py
import sre_constants # precompiled from /usr/lib/python2.7/sre_constants.pyc
# /usr/lib/python2.7/_sysconfigdata.pyc matches /usr/lib/python2.7/_sysconfigdata.py
import _sysconfigdata # precompiled from /usr/lib/python2.7/_sysconfigdata.pyc
# /usr/lib/python2.7/_sysconfigdata_nd.pyc matches /usr/lib/python2.7/_sysconfigdata_nd.py
import _sysconfigdata_nd # precompiled from /usr/lib/python2.7/_sysconfigdata_nd.pyc
# /usr/lib/python2.7/sitecustomize.pyc matches /usr/lib/python2.7/sitecustomize.py
import sitecustomize # precompiled from /usr/lib/python2.7/sitecustomize.pyc
# /usr/lib/python2.7/dist-packages/apport_python_hook.pyc matches /usr/lib/python2.7/dist-packages/apport_python_hook.py
import apport_python_hook # precompiled from /usr/lib/python2.7/dist-packages/apport_python_hook.pyc
# /usr/lib/python2.7/glob.pyc matches /usr/lib/python2.7/glob.py
import glob # precompiled from /usr/lib/python2.7/glob.pyc
# /usr/lib/python2.7/fnmatch.pyc matches /usr/lib/python2.7/fnmatch.py
import fnmatch # precompiled from /usr/lib/python2.7/fnmatch.pyc
import encodings # directory /usr/lib/python2.7/encodings
# /usr/lib/python2.7/encodings/__init__.pyc matches /usr/lib/python2.7/encodings/__init__.py
import encodings # precompiled from /usr/lib/python2.7/encodings/__init__.pyc
# /usr/lib/python2.7/codecs.pyc matches /usr/lib/python2.7/codecs.py
import codecs # precompiled from /usr/lib/python2.7/codecs.pyc
import _codecs # builtin
# /usr/lib/python2.7/encodings/aliases.pyc matches /usr/lib/python2.7/encodings/aliases.py
import encodings.aliases # precompiled from /usr/lib/python2.7/encodings/aliases.pyc
# /usr/lib/python2.7/encodings/utf_8.pyc matches /usr/lib/python2.7/encodings/utf_8.py
import encodings.utf_8 # precompiled from /usr/lib/python2.7/encodings/utf_8.pyc
Python 2.7.3 (default, Sep 26 2012, 21:51:14)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
# /usr/lib/python2.7/encodings/utf_32_be.pyc matches /usr/lib/python2.7/encodings/utf_32_be.py
import encodings.utf_32_be # precompiled from /usr/lib/python2.7/encodings/utf_32_be.pyc
# /usr/lib/python2.7/optparse.pyc matches /usr/lib/python2.7/optparse.py
import optparse # precompiled from /usr/lib/python2.7/optparse.pyc
# /usr/lib/python2.7/textwrap.pyc matches /usr/lib/python2.7/textwrap.py
import textwrap # precompiled from /usr/lib/python2.7/textwrap.pyc
# /usr/lib/python2.7/string.pyc matches /usr/lib/python2.7/string.py
import string # precompiled from /usr/lib/python2.7/string.pyc
import strop # builtin
# /usr/lib/python2.7/gettext.pyc matches /usr/lib/python2.7/gettext.py
import gettext # precompiled from /usr/lib/python2.7/gettext.pyc
# /usr/lib/python2.7/locale.pyc matches /usr/lib/python2.7/locale.py
import locale # precompiled from /usr/lib/python2.7/locale.pyc
import operator # builtin
# /usr/lib/python2.7/functools.pyc matches /usr/lib/python2.7/functools.py
import functools # precompiled from /usr/lib/python2.7/functools.pyc
import _functools # builtin
import _locale # builtin
# /usr/lib/python2.7/copy.pyc matches /usr/lib/python2.7/copy.py
import copy # precompiled from /usr/lib/python2.7/copy.pyc
# /usr/lib/python2.7/weakref.pyc matches /usr/lib/python2.7/weakref.py
import weakref # precompiled from /usr/lib/python2.7/weakref.pyc
# /usr/lib/python2.7/struct.pyc matches /usr/lib/python2.7/struct.py
import struct # precompiled from /usr/lib/python2.7/struct.pyc
import _struct # builtin
import logging # directory /usr/lib/python2.7/logging
# /usr/lib/python2.7/logging/__init__.pyc matches /usr/lib/python2.7/logging/__init__.py
import logging # precompiled from /usr/lib/python2.7/logging/__init__.pyc
import time # builtin
import cStringIO # builtin
import thread # builtin
# /usr/lib/python2.7/threading.pyc matches /usr/lib/python2.7/threading.py
import threading # precompiled from /usr/lib/python2.7/threading.pyc
# /usr/lib/python2.7/collections.pyc matches /usr/lib/python2.7/collections.py
import collections # precompiled from /usr/lib/python2.7/collections.pyc
import _collections # builtin
# /usr/lib/python2.7/keyword.pyc matches /usr/lib/python2.7/keyword.py
import keyword # precompiled from /usr/lib/python2.7/keyword.pyc
# /usr/lib/python2.7/heapq.pyc matches /usr/lib/python2.7/heapq.py
import heapq # precompiled from /usr/lib/python2.7/heapq.pyc
import itertools # builtin
# /usr/lib/python2.7/bisect.pyc matches /usr/lib/python2.7/bisect.py
import bisect # precompiled from /usr/lib/python2.7/bisect.pyc
import _bisect # builtin
import _heapq # builtin
# /usr/lib/python2.7/atexit.pyc matches /usr/lib/python2.7/atexit.py
import atexit # precompiled from /usr/lib/python2.7/atexit.pyc
import PyQt4 # directory /usr/lib/python2.7/dist-packages/PyQt4
# /usr/lib/python2.7/dist-packages/PyQt4/__init__.pyc matches /usr/lib/python2.7/dist-packages/PyQt4/__init__.py
import PyQt4 # precompiled from /usr/lib/python2.7/dist-packages/PyQt4/__init__.pyc
dlopen("/usr/lib/python2.7/dist-packages/PyQt4/QtGui.so", 2);
dlopen("/usr/lib/python2.7/dist-packages/sip.so", 2);
import sip # dynamically loaded from /usr/lib/python2.7/dist-packages/sip.so
dlopen("/usr/lib/python2.7/dist-packages/PyQt4/QtCore.so", 2);
import PyQt4.QtCore # dynamically loaded from /usr/lib/python2.7/dist-packages/PyQt4/QtCore.so
import PyQt4.QtGui # dynamically loaded from /usr/lib/python2.7/dist-packages/PyQt4/QtGui.so
import GUI # directory /usr/share/tvdownloader/GUI
# /usr/share/tvdownloader/GUI/__init__.pyc matches /usr/share/tvdownloader/GUI/__init__.py
import GUI # precompiled from /usr/share/tvdownloader/GUI/__init__.pyc
# /usr/share/tvdownloader/GUI/MainWindow.pyc matches /usr/share/tvdownloader/GUI/MainWindow.py
import GUI.MainWindow # precompiled from /usr/share/tvdownloader/GUI/MainWindow.pyc
import GUI.Qt # directory /usr/share/tvdownloader/GUI/Qt
# /usr/share/tvdownloader/GUI/Qt/__init__.pyc matches /usr/share/tvdownloader/GUI/Qt/__init__.py
import GUI.Qt # precompiled from /usr/share/tvdownloader/GUI/Qt/__init__.pyc
# /usr/share/tvdownloader/GUI/Qt/MyQTableWidget.pyc matches /usr/share/tvdownloader/GUI/Qt/MyQTableWidget.py
import GUI.Qt.MyQTableWidget # precompiled from /usr/share/tvdownloader/GUI/Qt/MyQTableWidget.pyc
# /usr/share/tvdownloader/GUI/ConvertQString.pyc matches /usr/share/tvdownloader/GUI/ConvertQString.py
import GUI.ConvertQString # precompiled from /usr/share/tvdownloader/GUI/ConvertQString.pyc
import unicodedata # builtin
# /usr/share/tvdownloader/GUI/Qt/MyQPushButton.pyc matches /usr/share/tvdownloader/GUI/Qt/MyQPushButton.py
import GUI.Qt.MyQPushButton # precompiled from /usr/share/tvdownloader/GUI/Qt/MyQPushButton.pyc
# /usr/share/tvdownloader/API.pyc matches /usr/share/tvdownloader/API.py
import API # precompiled from /usr/share/tvdownloader/API.pyc
# /usr/lib/python2.7/httplib.pyc matches /usr/lib/python2.7/httplib.py
import httplib # precompiled from /usr/lib/python2.7/httplib.pyc
import array # builtin
# /usr/lib/python2.7/socket.pyc matches /usr/lib/python2.7/socket.py
import socket # precompiled from /usr/lib/python2.7/socket.pyc
import _socket # builtin
dlopen("/usr/lib/python2.7/lib-dynload/_ssl.so", 2);
import _ssl # dynamically loaded from /usr/lib/python2.7/lib-dynload/_ssl.so
# /usr/lib/python2.7/urlparse.pyc matches /usr/lib/python2.7/urlparse.py
import urlparse # precompiled from /usr/lib/python2.7/urlparse.pyc
# /usr/lib/python2.7/mimetools.pyc matches /usr/lib/python2.7/mimetools.py
import mimetools # precompiled from /usr/lib/python2.7/mimetools.pyc
# /usr/lib/python2.7/tempfile.pyc matches /usr/lib/python2.7/tempfile.py
import tempfile # precompiled from /usr/lib/python2.7/tempfile.pyc
# /usr/lib/python2.7/random.pyc matches /usr/lib/python2.7/random.py
import random # precompiled from /usr/lib/python2.7/random.pyc
# /usr/lib/python2.7/__future__.pyc matches /usr/lib/python2.7/__future__.py
import __future__ # precompiled from /usr/lib/python2.7/__future__.pyc
import math # builtin
import binascii # builtin
# /usr/lib/python2.7/hashlib.pyc matches /usr/lib/python2.7/hashlib.py
import hashlib # precompiled from /usr/lib/python2.7/hashlib.pyc
dlopen("/usr/lib/python2.7/lib-dynload/_hashlib.so", 2);
import _hashlib # dynamically loaded from /usr/lib/python2.7/lib-dynload/_hashlib.so
import _random # builtin
import fcntl # builtin
# /usr/lib/python2.7/rfc822.pyc matches /usr/lib/python2.7/rfc822.py
import rfc822 # precompiled from /usr/lib/python2.7/rfc822.pyc
# /usr/lib/python2.7/ssl.pyc matches /usr/lib/python2.7/ssl.py
import ssl # precompiled from /usr/lib/python2.7/ssl.pyc
# /usr/lib/python2.7/base64.pyc matches /usr/lib/python2.7/base64.py
import base64 # precompiled from /usr/lib/python2.7/base64.pyc
# /usr/share/tvdownloader/APIPrive.pyc matches /usr/share/tvdownloader/APIPrive.py
import APIPrive # precompiled from /usr/share/tvdownloader/APIPrive.pyc
import zlib # builtin
# /usr/lib/python2.7/pickle.pyc matches /usr/lib/python2.7/pickle.py
import pickle # precompiled from /usr/lib/python2.7/pickle.pyc
import marshal # builtin
# /usr/lib/python2.7/htmlentitydefs.pyc matches /usr/lib/python2.7/htmlentitydefs.py
import htmlentitydefs # precompiled from /usr/lib/python2.7/htmlentitydefs.pyc
# /usr/share/tvdownloader/Fichier.pyc matches /usr/share/tvdownloader/Fichier.py
import Fichier # precompiled from /usr/share/tvdownloader/Fichier.pyc
dlopen("/usr/lib/python2.7/lib-dynload/datetime.so", 2);
import datetime # dynamically loaded from /usr/lib/python2.7/lib-dynload/datetime.so
# /usr/share/tvdownloader/Option.pyc matches /usr/share/tvdownloader/Option.py
import Option # precompiled from /usr/share/tvdownloader/Option.pyc
# /usr/share/tvdownloader/Navigateur.pyc matches /usr/share/tvdownloader/Navigateur.py
import Navigateur # precompiled from /usr/share/tvdownloader/Navigateur.pyc
# /usr/lib/python2.7/urllib.pyc matches /usr/lib/python2.7/urllib.py
import urllib # precompiled from /usr/lib/python2.7/urllib.pyc
# /usr/lib/python2.7/urllib2.pyc matches /usr/lib/python2.7/urllib2.py
import urllib2 # precompiled from /usr/lib/python2.7/urllib2.pyc
import mechanize # directory /usr/lib/python2.7/dist-packages/mechanize
# /usr/lib/python2.7/dist-packages/mechanize/__init__.pyc matches /usr/lib/python2.7/dist-packages/mechanize/__init__.py
import mechanize # precompiled from /usr/lib/python2.7/dist-packages/mechanize/__init__.pyc
# /usr/lib/python2.7/dist-packages/mechanize/_version.pyc matches /usr/lib/python2.7/dist-packages/mechanize/_version.py
import mechanize._version # precompiled from /usr/lib/python2.7/dist-packages/mechanize/_version.pyc
# /usr/lib/python2.7/dist-packages/mechanize/_mechanize.pyc matches /usr/lib/python2.7/dist-packages/mechanize/_mechanize.py
import mechanize._mechanize # precompiled from /usr/lib/python2.7/dist-packages/mechanize/_mechanize.pyc
# /usr/lib/python2.7/dist-packages/mechanize/_html.pyc matches /usr/lib/python2.7/dist-packages/mechanize/_html.py
import mechanize._html # precompiled from /usr/lib/python2.7/dist-packages/mechanize/_html.pyc
# /usr/lib/python2.7/dist-packages/mechanize/_sgmllib_copy.pyc matches /usr/lib/python2.7/dist-packages/mechanize/_sgmllib_copy.py
import mechanize._sgmllib_copy # precompiled from /usr/lib/python2.7/dist-packages/mechanize/_sgmllib_copy.pyc
# /usr/lib/python2.7/markupbase.pyc matches /usr/lib/python2.7/markupbase.py
import markupbase # precompiled from /usr/lib/python2.7/markupbase.pyc
# /usr/lib/python2.7/dist-packages/mechanize/_beautifulsoup.pyc matches /usr/lib/python2.7/dist-packages/mechanize/_beautifulsoup.py
import mechanize._beautifulsoup # precompiled from /usr/lib/python2.7/dist-packages/mechanize/_beautifulsoup.pyc
# /usr/lib/python2.7/dist-packages/mechanize/_form.pyc matches /usr/lib/python2.7/dist-packages/mechanize/_form.py
import mechanize._form # precompiled from /usr/lib/python2.7/dist-packages/mechanize/_form.pyc
# /usr/lib/python2.7/HTMLParser.pyc matches /usr/lib/python2.7/HTMLParser.py
import HTMLParser # precompiled from /usr/lib/python2.7/HTMLParser.pyc
# /usr/lib/python2.7/inspect.pyc matches /usr/lib/python2.7/inspect.py
import inspect # precompiled from /usr/lib/python2.7/inspect.pyc
# /usr/lib/python2.7/dis.pyc matches /usr/lib/python2.7/dis.py
import dis # precompiled from /usr/lib/python2.7/dis.pyc
# /usr/lib/python2.7/opcode.pyc matches /usr/lib/python2.7/opcode.py
import opcode # precompiled from /usr/lib/python2.7/opcode.pyc
import imp # builtin
# /usr/lib/python2.7/tokenize.pyc matches /usr/lib/python2.7/tokenize.py
import tokenize # precompiled from /usr/lib/python2.7/tokenize.pyc
# /usr/lib/python2.7/token.pyc matches /usr/lib/python2.7/token.py
import token # precompiled from /usr/lib/python2.7/token.pyc
# /usr/lib/python2.7/dist-packages/mechanize/_request.pyc matches /usr/lib/python2.7/dist-packages/mechanize/_request.py
import mechanize._request # precompiled from /usr/lib/python2.7/dist-packages/mechanize/_request.pyc
# /usr/lib/python2.7/dist-packages/mechanize/_rfc3986.pyc matches /usr/lib/python2.7/dist-packages/mechanize/_rfc3986.py
import mechanize._rfc3986 # precompiled from /usr/lib/python2.7/dist-packages/mechanize/_rfc3986.pyc
# /usr/lib/python2.7/dist-packages/mechanize/_sockettimeout.pyc matches /usr/lib/python2.7/dist-packages/mechanize/_sockettimeout.py
import mechanize._sockettimeout # precompiled from /usr/lib/python2.7/dist-packages/mechanize/_sockettimeout.pyc
# /usr/lib/python2.7/dist-packages/mechanize/_urllib2_fork.pyc matches /usr/lib/python2.7/dist-packages/mechanize/_urllib2_fork.py
import mechanize._urllib2_fork # precompiled from /usr/lib/python2.7/dist-packages/mechanize/_urllib2_fork.pyc
# /usr/lib/python2.7/dist-packages/mechanize/_clientcookie.pyc matches /usr/lib/python2.7/dist-packages/mechanize/_clientcookie.py
import mechanize._clientcookie # precompiled from /usr/lib/python2.7/dist-packages/mechanize/_clientcookie.pyc
# /usr/lib/python2.7/dist-packages/mechanize/_headersutil.pyc matches /usr/lib/python2.7/dist-packages/mechanize/_headersutil.py
import mechanize._headersutil # precompiled from /usr/lib/python2.7/dist-packages/mechanize/_headersutil.pyc
# /usr/lib/python2.7/dist-packages/mechanize/_util.pyc matches /usr/lib/python2.7/dist-packages/mechanize/_util.py
import mechanize._util # precompiled from /usr/lib/python2.7/dist-packages/mechanize/_util.pyc
# /usr/lib/python2.7/calendar.pyc matches /usr/lib/python2.7/calendar.py
import calendar # precompiled from /usr/lib/python2.7/calendar.pyc
# /usr/lib/python2.7/dist-packages/mechanize/_response.pyc matches /usr/lib/python2.7/dist-packages/mechanize/_response.py
import mechanize._response # precompiled from /usr/lib/python2.7/dist-packages/mechanize/_response.pyc
# /usr/lib/python2.7/sgmllib.pyc matches /usr/lib/python2.7/sgmllib.py
import sgmllib # precompiled from /usr/lib/python2.7/sgmllib.pyc
# /usr/lib/python2.7/dist-packages/mechanize/_useragent.pyc matches /usr/lib/python2.7/dist-packages/mechanize/_useragent.py
import mechanize._useragent # precompiled from /usr/lib/python2.7/dist-packages/mechanize/_useragent.pyc
# /usr/lib/python2.7/dist-packages/mechanize/_auth.pyc matches /usr/lib/python2.7/dist-packages/mechanize/_auth.py
import mechanize._auth # precompiled from /usr/lib/python2.7/dist-packages/mechanize/_auth.pyc
# /usr/lib/python2.7/dist-packages/mechanize/_gzip.pyc matches /usr/lib/python2.7/dist-packages/mechanize/_gzip.py
import mechanize._gzip # precompiled from /usr/lib/python2.7/dist-packages/mechanize/_gzip.pyc
# /usr/lib/python2.7/dist-packages/mechanize/_opener.pyc matches /usr/lib/python2.7/dist-packages/mechanize/_opener.py
import mechanize._opener # precompiled from /usr/lib/python2.7/dist-packages/mechanize/_opener.pyc
# /usr/lib/python2.7/dist-packages/mechanize/_urllib2.pyc matches /usr/lib/python2.7/dist-packages/mechanize/_urllib2.py
import mechanize._urllib2 # precompiled from /usr/lib/python2.7/dist-packages/mechanize/_urllib2.pyc
# /usr/lib/python2.7/dist-packages/mechanize/_debug.pyc matches /usr/lib/python2.7/dist-packages/mechanize/_debug.py
import mechanize._debug # precompiled from /usr/lib/python2.7/dist-packages/mechanize/_debug.pyc
# /usr/lib/python2.7/dist-packages/mechanize/_http.pyc matches /usr/lib/python2.7/dist-packages/mechanize/_http.py
import mechanize._http # precompiled from /usr/lib/python2.7/dist-packages/mechanize/_http.pyc
# /usr/lib/python2.7/robotparser.pyc matches /usr/lib/python2.7/robotparser.py
import robotparser # precompiled from /usr/lib/python2.7/robotparser.pyc
# /usr/lib/python2.7/dist-packages/mechanize/_lwpcookiejar.pyc matches /usr/lib/python2.7/dist-packages/mechanize/_lwpcookiejar.py
import mechanize._lwpcookiejar # precompiled from /usr/lib/python2.7/dist-packages/mechanize/_lwpcookiejar.pyc
import sqlite3 # directory /usr/lib/python2.7/sqlite3
# /usr/lib/python2.7/sqlite3/__init__.pyc matches /usr/lib/python2.7/sqlite3/__init__.py
import sqlite3 # precompiled from /usr/lib/python2.7/sqlite3/__init__.pyc
# /usr/lib/python2.7/sqlite3/dbapi2.pyc matches /usr/lib/python2.7/sqlite3/dbapi2.py
import sqlite3.dbapi2 # precompiled from /usr/lib/python2.7/sqlite3/dbapi2.pyc
dlopen("/usr/lib/python2.7/lib-dynload/_sqlite3.so", 2);
import _sqlite3 # dynamically loaded from /usr/lib/python2.7/lib-dynload/_sqlite3.so
# /usr/lib/python2.7/dist-packages/mechanize/_firefox3cookiejar.pyc matches /usr/lib/python2.7/dist-packages/mechanize/_firefox3cookiejar.py
import mechanize._firefox3cookiejar # precompiled from /usr/lib/python2.7/dist-packages/mechanize/_firefox3cookiejar.pyc
# /usr/lib/python2.7/dist-packages/mechanize/_mozillacookiejar.pyc matches /usr/lib/python2.7/dist-packages/mechanize/_mozillacookiejar.py
import mechanize._mozillacookiejar # precompiled from /usr/lib/python2.7/dist-packages/mechanize/_mozillacookiejar.pyc
# /usr/lib/python2.7/dist-packages/mechanize/_msiecookiejar.pyc matches /usr/lib/python2.7/dist-packages/mechanize/_msiecookiejar.py
import mechanize._msiecookiejar # precompiled from /usr/lib/python2.7/dist-packages/mechanize/_msiecookiejar.pyc
# /usr/lib/python2.7/dist-packages/mechanize/_pullparser.pyc matches /usr/lib/python2.7/dist-packages/mechanize/_pullparser.py
import mechanize._pullparser # precompiled from /usr/lib/python2.7/dist-packages/mechanize/_pullparser.pyc
import xml # directory /usr/lib/python2.7/xml
# /usr/lib/python2.7/xml/__init__.pyc matches /usr/lib/python2.7/xml/__init__.py
import xml # precompiled from /usr/lib/python2.7/xml/__init__.pyc
import xml.sax # directory /usr/lib/python2.7/xml/sax
# /usr/lib/python2.7/xml/sax/__init__.pyc matches /usr/lib/python2.7/xml/sax/__init__.py
import xml.sax # precompiled from /usr/lib/python2.7/xml/sax/__init__.pyc
# /usr/lib/python2.7/xml/sax/xmlreader.pyc matches /usr/lib/python2.7/xml/sax/xmlreader.py
import xml.sax.xmlreader # precompiled from /usr/lib/python2.7/xml/sax/xmlreader.pyc
# /usr/lib/python2.7/xml/sax/handler.pyc matches /usr/lib/python2.7/xml/sax/handler.py
import xml.sax.handler # precompiled from /usr/lib/python2.7/xml/sax/handler.pyc
# /usr/lib/python2.7/xml/sax/_exceptions.pyc matches /usr/lib/python2.7/xml/sax/_exceptions.py
import xml.sax._exceptions # precompiled from /usr/lib/python2.7/xml/sax/_exceptions.pyc
# /usr/lib/python2.7/xml/sax/saxutils.pyc matches /usr/lib/python2.7/xml/sax/saxutils.py
import xml.sax.saxutils # precompiled from /usr/lib/python2.7/xml/sax/saxutils.pyc
# /usr/share/tvdownloader/GUI/Signaux.pyc matches /usr/share/tvdownloader/GUI/Signaux.py
import GUI.Signaux # precompiled from /usr/share/tvdownloader/GUI/Signaux.pyc
# /usr/share/tvdownloader/PluginManager.pyc matches /usr/share/tvdownloader/PluginManager.py
import PluginManager # precompiled from /usr/share/tvdownloader/PluginManager.pyc
# /usr/share/tvdownloader/Plugin.pyc matches /usr/share/tvdownloader/Plugin.py
import Plugin # precompiled from /usr/share/tvdownloader/Plugin.pyc
# /usr/share/tvdownloader/Preferences.pyc matches /usr/share/tvdownloader/Preferences.py
import Preferences # precompiled from /usr/share/tvdownloader/Preferences.pyc
# /usr/share/tvdownloader/GUI/PreferencesDialog.pyc matches /usr/share/tvdownloader/GUI/PreferencesDialog.py
import GUI.PreferencesDialog # precompiled from /usr/share/tvdownloader/GUI/PreferencesDialog.pyc
# /usr/share/tvdownloader/GUI/PreferencePluginDialog.pyc matches /usr/share/tvdownloader/GUI/PreferencePluginDialog.py
import GUI.PreferencePluginDialog # precompiled from /usr/share/tvdownloader/GUI/PreferencePluginDialog.pyc
# /usr/share/tvdownloader/Downloader.pyc matches /usr/share/tvdownloader/Downloader.py
import Downloader # precompiled from /usr/share/tvdownloader/Downloader.pyc
# /usr/lib/python2.7/subprocess.pyc matches /usr/lib/python2.7/subprocess.py
import subprocess # precompiled from /usr/lib/python2.7/subprocess.pyc
import gc # builtin
import select # builtin
# /usr/lib/python2.7/shlex.pyc matches /usr/lib/python2.7/shlex.py
import shlex # precompiled from /usr/lib/python2.7/shlex.pyc
import fonctions # directory /usr/share/tvdownloader/fonctions
# /usr/share/tvdownloader/fonctions/__init__.pyc matches /usr/share/tvdownloader/fonctions/__init__.py
import fonctions # precompiled from /usr/share/tvdownloader/fonctions/__init__.pyc
# /usr/share/tvdownloader/fonctions/urlToRtmpdump.pyc matches /usr/share/tvdownloader/fonctions/urlToRtmpdump.py
import fonctions.urlToRtmpdump # precompiled from /usr/share/tvdownloader/fonctions/urlToRtmpdump.pyc
# /usr/share/tvdownloader/GUI/AProposDialog.pyc matches /usr/share/tvdownloader/GUI/AProposDialog.py
import GUI.AProposDialog # precompiled from /usr/share/tvdownloader/GUI/AProposDialog.pyc
# /usr/share/tvdownloader/Historique.pyc matches /usr/share/tvdownloader/Historique.py
import Historique # precompiled from /usr/share/tvdownloader/Historique.pyc
# /usr/share/tvdownloader/GUI/FenetreAttenteProgressDialog.pyc matches /usr/share/tvdownloader/GUI/FenetreAttenteProgressDialog.py
import GUI.FenetreAttenteProgressDialog # precompiled from /usr/share/tvdownloader/GUI/FenetreAttenteProgressDialog.pyc
# /usr/share/tvdownloader/GUI/UpdateManagerDialog.pyc matches /usr/share/tvdownloader/GUI/UpdateManagerDialog.py
import GUI.UpdateManagerDialog # precompiled from /usr/share/tvdownloader/GUI/UpdateManagerDialog.pyc
# /usr/share/tvdownloader/UpdateManager.pyc matches /usr/share/tvdownloader/UpdateManager.py
import UpdateManager # precompiled from /usr/share/tvdownloader/UpdateManager.pyc
# plugins/Pluzz.pyc matches plugins/Pluzz.py
import Pluzz # precompiled from plugins/Pluzz.pyc
# plugins/W9Replay.pyc matches plugins/W9Replay.py
import W9Replay # precompiled from plugins/W9Replay.pyc
# plugins/FranceInter.pyc matches plugins/FranceInter.py
import FranceInter # precompiled from plugins/FranceInter.pyc
# plugins/Podcasts.pyc matches plugins/Podcasts.py
import Podcasts # precompiled from plugins/Podcasts.pyc
# plugins/CanalPlus.pyc matches plugins/CanalPlus.py
import CanalPlus # precompiled from plugins/CanalPlus.pyc
# plugins/M6Replay.pyc matches plugins/M6Replay.py
import M6Replay # precompiled from plugins/M6Replay.pyc
import Crypto # directory /usr/lib/python2.7/dist-packages/Crypto
# /usr/lib/python2.7/dist-packages/Crypto/__init__.pyc matches /usr/lib/python2.7/dist-packages/Crypto/__init__.py
import Crypto # precompiled from /usr/lib/python2.7/dist-packages/Crypto/__init__.pyc
import Crypto.Cipher # directory /usr/lib/python2.7/dist-packages/Crypto/Cipher
# /usr/lib/python2.7/dist-packages/Crypto/Cipher/__init__.pyc matches /usr/lib/python2.7/dist-packages/Crypto/Cipher/__init__.py
import Crypto.Cipher # precompiled from /usr/lib/python2.7/dist-packages/Crypto/Cipher/__init__.pyc
# /usr/lib/python2.7/dist-packages/Crypto/Cipher/DES.pyc matches /usr/lib/python2.7/dist-packages/Crypto/Cipher/DES.py
import Crypto.Cipher.DES # precompiled from /usr/lib/python2.7/dist-packages/Crypto/Cipher/DES.pyc
# /usr/lib/python2.7/dist-packages/Crypto/Cipher/blockalgo.pyc matches /usr/lib/python2.7/dist-packages/Crypto/Cipher/blockalgo.py
import Crypto.Cipher.blockalgo # precompiled from /usr/lib/python2.7/dist-packages/Crypto/Cipher/blockalgo.pyc
import Crypto.Util # directory /usr/lib/python2.7/dist-packages/Crypto/Util
# /usr/lib/python2.7/dist-packages/Crypto/Util/__init__.pyc matches /usr/lib/python2.7/dist-packages/Crypto/Util/__init__.py
import Crypto.Util # precompiled from /usr/lib/python2.7/dist-packages/Crypto/Util/__init__.pyc
# /usr/lib/python2.7/dist-packages/Crypto/Util/py3compat.pyc matches /usr/lib/python2.7/dist-packages/Crypto/Util/py3compat.py
import Crypto.Util.py3compat # precompiled from /usr/lib/python2.7/dist-packages/Crypto/Util/py3compat.pyc
dlopen("/usr/lib/python2.7/dist-packages/Crypto/Cipher/_DES.so", 2);
import Crypto.Cipher._DES # dynamically loaded from /usr/lib/python2.7/dist-packages/Crypto/Cipher/_DES.so
# plugins/RadioFrance.pyc matches plugins/RadioFrance.py
import RadioFrance # precompiled from plugins/RadioFrance.pyc
# plugins/Europe1.pyc matches plugins/Europe1.py
import Europe1 # precompiled from plugins/Europe1.pyc
# plugins/Arte.pyc matches plugins/Arte.py
import Arte # precompiled from plugins/Arte.pyc
# /usr/lib/python2.7/encodings/raw_unicode_escape.pyc matches /usr/lib/python2.7/encodings/raw_unicode_escape.py
import encodings.raw_unicode_escape # precompiled from /usr/lib/python2.7/encodings/raw_unicode_escape.pyc
# /usr/lib/python2.7/encodings/string_escape.pyc matches /usr/lib/python2.7/encodings/string_escape.py
import encodings.string_escape # precompiled from /usr/lib/python2.7/encodings/string_escape.pyc
Hors ligne
#2621 Le 04/01/2013, à 20:13
11gjm
Re : TVDownloader: télécharger les médias du net !
Bonjour ,
Meileurs voeux à tous .
@k3c : si cela peut t'aider .
http://api.tou.tv/v1/TouTVAPIService.svc?xsd=xsd1
http://api.tou.tv/v1/TouTVAPIService.svc?xsd=xsd2
http://api.tou.tv/v1/TouTVAPIService.svc?xsd=xsd3
http://api.tou.tv/v1/TouTVAPIService.svc?xsd=xsd4
http://api.tou.tv/v1/TouTVAPIService.svc?xsd=xsd5
Cordialement .
Hors ligne
#2622 Le 04/01/2013, à 20:23
k3c
Re : TVDownloader: télécharger les médias du net !
@ rvhm
Dans mon cas les dernières lignes affichées sont
# plugins/CanalPlus.pyc matches plugins/CanalPlus.py
import CanalPlus # precompiled from plugins/CanalPlus.pyc
# plugins/Europe1.pyc matches plugins/Europe1.py
import Europe1 # precompiled from plugins/Europe1.pyc
# plugins/Pluzz.pyc matches plugins/Pluzz.py
import Pluzz # precompiled from plugins/Pluzz.pyc
# /usr/lib/python2.7/encodings/string_escape.pyc matches /usr/lib/python2.7/encodings/string_escape.py
import encodings.string_escape # precompiled from /usr/lib/python2.7/encodings/string_escape.pyc
# /usr/lib/python2.7/encodings/raw_unicode_escape.pyc matches /usr/lib/python2.7/encodings/raw_unicode_escape.py
import encodings.raw_unicode_escape # precompiled from /usr/lib/python2.7/encodings/raw_unicode_escape.pyc
puis la fenêtre TVDownloader se lance.
Donc on a quasiment le même affichage final, sauf que tu restes bloqué.
Bizarre
@11gjm
merci
Comment as-tu trouvé ces adresses ? Un coup de wireshark ?
Hors ligne
#2623 Le 04/01/2013, à 20:54
rvhm
Re : TVDownloader: télécharger les médias du net !
oui c'est ça
ça reste toujours bloqué
peut etre que j'ai des mauvaise ppa
Hors ligne
#2624 Le 04/01/2013, à 21:17
11gjm
Re : TVDownloader: télécharger les médias du net !
Bonjour ,
@k3c :
Tu nous as indiqué l'adresse pour lire le fichier "client.py" .
Je l'ai copié , puis ouvert .
---
TOUTV_WSDL_URL = "http://api.tou.tv/v1/TouTVAPIService.svc?wsdl"
TOUTV_PLAYLIST_URL = "http://api.radio-canada.ca/validationMe … utput=json"
TOUTV_JSON_URL = "https://api.tou.tv/v1/toutvapiservice.svc/json/"
---
Puis , j'ai modifié certaines adresses .
Cordialement .
Dernière modification par 11gjm (Le 04/01/2013, à 21:19)
Hors ligne
#2625 Le 05/01/2013, à 11:47
bibichouchou
Re : TVDownloader: télécharger les médias du net !
@ rvhm
où en es-tu avec tvdownloader ? d'après les messages du forum, tu as déjà eu un problème similaire en août 2012. Comment l'avais-tu réglé à l'époque ?
PS : apparemment, tu es sous linux. mais en voyant ctrl + alt + suppr, j'ai eu des frayeurs
@ chaoswizard, k3c et les autres :
il serait peut-être de bon ton d'indiquer ce qui marche ou pas ou ce qui est en chantier sur la première page de ce forum. certains s'embêtent à installer tvdownloader et se rendent compte que ça ne fait pas ce qu'ils espèrent. de plus, il y a eu pas mal de scripts autonomes depuis notamment par k3c. on pourrait peut-être faire des liens vers les messages pertinents (la dernière version du-dit script).
pour tvdownloader, de mémoire, il y a :
arte (cassé ?)
pluzz (cassé)
canal + (fonctionnel ?)
lcp (cassé)
public senat (fonctionnel ?)
m6 (cassé)
w9 (cassé)
france inter (cassé)
pour les scripts autonomes, il y a:
pluzzdl (fonctionnel)
tf1/tmc/nt1/hd1 (fonctionnel)
nrj12 (fonctionnel)
tv5monde (fonctionnel)
tou.tv (cassé)
je ne sais plus si il y a un script pour d8/d17. Merci de me corriger si je me suis trompé ou si j'ai oublié des scripts.
Ah et j'aimerais bien savoir si une nouvelle mouture de tvdownloader est dans les cartons...
Amicalement.
Dernière modification par bibichouchou (Le 05/01/2013, à 11:50)
Hors ligne
|
After switching from optparse to argparse - I'm experiencing strange errors. Argparse parse args only if leave no space:
myScript.py -oOpt
or put an equal sign:
myScript.py -o=Opt
and it doesn't work the normal way:
myScript.py -o Opt
Here's my argparse initialization:
#!/usr/bin/env python
# to get description use the -h flag
import argparse, os, sys
# ======================
# Python2.7 is expected:
if sys.version_info[0] != 2 or sys.version_info[1] < 7:
sys.exit('This program needs Python2.7+')
# ==========
# preambule:
desc = """Enter dirs in the current dir and makes gro out of state.cpt there."""
# parser = argparse.ArgumentParser()
parser = argparse.ArgumentParser(description=desc, version='2.3', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-w', '--workWith',
help = 'to specify a Gromacs exec suffix',
dest = 'wW',
action = 'store',
default = '-4.5.5-single',
)
parser.add_argument('-g', '--gro',
help = '.gro postfix: <nameOfTheDir><postfix>.gro',
dest = 'myGroPostfix',
action = 'store',
default = "_membrane",
)
parser.add_argument('-H', '--here',
help = 'toggles - single (current) dir behaviour (the output will be state.gro)',
dest = 'Here',
action = 'store_true',
)
parser.add_argument('-D', '--dirs',
help = 'include these dirs (python\'s rgxp in SINGLE quotes), defaults to \'\'',
dest = 'inclDirs',
action = 'store',
default = '',
)
args = parser.parse_args()
print args.wW
Edit:
Even more:
gmx_bk-simulate-mems.py -j bk-runs-mpi.bash -p 1 -w="-4.5.5-double_non-parallel_gcc" 2&> ../`date +%Y-%b-%d-%H%M%S`.log &
gives:
gmx_bk-simulate-mems.py: error: unrecognized arguments: 2
it looks like argparse treats 2&> as option (or 2&> and ../date +%Y-%b-%d-%H%M%S.log as options)!
Edit 2:
So to summarize:
For
argparse-"-4.5.5-double_non-parallel_gcc"is a bad option name - and that's why it is required to write is as-w="-4.5.5-double_non-parallel_gcc". Foroptparseandbash(!) this is fine.basheven gives an error at-w="-4.5.5-double_non-parallel_gcc"- it thinks that the arg is="-4.5.5-double_non-parallel_gcc"(!);
There's no such thing as
2&>.2>should might be used and it gives no errors;
This is
shellwho splits the line into args, notpython;
argparseis much better thanoptparse.
|
I am trying to grab frames from camera and add them into a single image to get the effect as in this image: http://www.danheller.com/images/California/DeathValley/Nite/tent-star-trails.jpg
But my image turns white after a couple of seconds. Here is the code:
#!/usr/bin/python
import cv
stream = cv.CaptureFromCAM(0)
cv.NamedWindow("Stream",1)
out = cv.CreateImage((640, 480), 8, 3)
while True:
frame = cv.QueryFrame(stream)
cv.Add(frame, out, out, None)
cv.ShowImage("Stream", out)
cv.WaitKey(25)
Can anyone help?
|
I've been opening quite a few bugs lately for distributions failing these 2 criteria, so, I figured I'd save everyone some effort and unify it cohesively.
Reason
While it may seem a trivial squabble, ABSTRACT and LICENSE components of your meta-data are reasonably important for communicating what your dist is to the world, for both human and automated consumers.
The ABSTRACT field manifests itself in quite a few places:
Search Results
Author Module listings
https://metacpan.org/author/DCONWAY # All the empty lines are due to the lack of an abstract
Data from MetaCPAN::API
http://api.metacpan.org/release/Acme-Bleach # abstract exists
http://api.metacpan.org/release/DCONWAY/Attribute-Types-0.10 # No Abstract
And the LICENSE field appears in a few places as well:
On the release page
On each modules page
In MetaCPAN::APIresults - http://api.metacpan.org/release/Acme-Bleach # license 'unknown'
http://api.metacpan.org/release/Dist-Zilla# license 'perl_5'
http://api.metacpan.org/release/Dist-Zilla# license '
For me personally, these 2 fields are essential data which I have to use in downstream packaging ( Gentoo Ebuilds ), and having the fields correctly populated makes it much easier to automate packaging in a reliable way.
Licensing Options
What values you can use for a license descriptor depends somewhat on what toolchain you're using, and what level of the CPAN Meta Spec it supports.
Meta v1
The V1 metaspec has a rather short selection of licenses you can choose from.
These licenses are listed in the Module::Build::API:
apache- Apache License, Version 2.0.
apache_1_1- Apache Software License, Version 1.1
artistic- Artistic License
artistic_2- Artistic 2.0 License
bsd- BSD License
gpl- GNU General Public License
lgpl- GNU Lesser General Public License
mit- MIT License
mozilla- Mozilla Public License.
open_source- Some other Open Source Initiative-approved license listed at http://www.opensource.org/licenses/.
perl- The same terms as Perl itself.User may choose between either the GPL or the Artistic license.
restrictive- The distribution may not be redistributed without special permission from the author and/or copyright holder.
unrestricted- The distribution is licensed under a license that is not approved by www.opensource.org but that allows distribution without restrictions.
Meta v2
The Meta v2 Spec has a much wider and more accurate set of supported licenses, as well as the capacity to specify multiple licenses.
These licenses are for the most part documented in Software::License :
agpl_3- GNU Affero General Public License, Version 3
apache_1_1- The Apache Software License, Version 1.1
apache_2_0- The Apache License, Version 2.0
artistic_1- The Artistic License
artistic_2- The Artistic License 2.0
bsd- The (three-clause) BSD License
unrestricted- the "public domain"-like CC0 license, version 1.0
freebsd- The FreeBSD License (aka two-clause BSD)
gfdl_1_2- The GNU Free Documentation License v1.2
gfdl_1_3- The GNU Free Documentation License v1.3
gpl_1- GNU General Public License, Version 1
gpl_2- GNU General Public License, Version 2
gpl_3- GNU General Public License, Version 3
lgpl_2_1- GNU Lesser General Public License, Version 2.1
lgpl_3_0- GNU Lesser General Public License, Version 3
mit- The MIT (aka X11) License
mozilla_1_0- Mozilla Public License 1.0
mozilla_1_1- The Mozilla Public License 1.1
restricted- describes a "license" that gives no license for re-use
openssl- The OpenSSL License
perl_5- The Perl 5 License (Artistic 1 & GPL 1)
open_source- Some other Open Source Initiative-approved license listed at http://www.opensource.org/licenses/.
qpl_1_0- The Q Public License, Version 1.0
ssleay- The Original SSLeay License
sun- Sun Internet Standards Source License (SISSL)
zlib- The zlib License
Specifying the metadata
ExtUtils::MakeMaker
ExtUtils::MakeMaker as far as I'm aware only officially supports Meta v1 license types.
[CORRECTION] But, it would appear, that, assuming you have a recent enough version of CPAN::Meta and ExtUtils::MakeMaker installed, you can specify either a v2-style license or a v1-style license. If you specify a v1 style license, CPAN::Meta will upconvert it before it emits META.json, and if you specify a v2 style license, that will go as-is in META.json and be downconverted to v1 style before going into META.yml. ( Make sure you read the section on the caveats later ).
Though, I'd advise using v2 style where possible, as you're less likely to lose intent in downconversion.
Setting Abstract and License can be done a variety of ways:
# Explictitly Set Abstract
ABSTRACT => 'A module that eats bees'
# Try get the abstract from a module
ABSTRACT_FROM => 'Path/To/File.pm'
# Explicitly Set a v1 License
LICENSE => 'perl'
Module::Install
Despite being mostly a wrapper of sorts for ExtUtils::MakeMaker, Module::Install provides some enhancement with ability to parse and extract metadata from existing files. But alas, it is still limited to the v1 license set.
# try determine license/abstract ( amongst other things ) from Foo::Bar
all_from 'lib/Foo/Bar.pm'
# explicitly specify the abstract
abstract 'Something that eats elephants'
# try determine abstract from a file
abstract_from 'lib/Mammoth/Eater.pm'
# explicitly define a v1 license
license 'perl';
# try determine license from a file
license_from 'lib/Great/Cthulhu.pm'
Module::Build
I personally like Module::Build better than the previous 2 modules, but everyone is free to disagree and have their personal preferences. And indeed, it would appear Module::Build versions greater than 0.3624 can specify version 2 license types by referring to the appropriate subclass of Software::License
Module::Build->new(
...
# Explicitly define abstract
dist_abstract => 'Something that eats Cthulhus',
# If not explicitly defined, MB looks for the same module it got the version from
# and tries to get the abstract out of that
# Explicitly set to use Software::License::GPL_2
license => 'GPL_2',
# v1 => gpl
# v2 => gpl_2
...
)
Dist::Zilla
Dist::Zilla has in my opinion a much higher standard of metadata quality, and making Abstract and License available are practically a requirement of building a dist with it.
; dist.ini
license = Perl_5
Determining the abstract is usually done automatically, and most prefer this approach. It does so by determining the "Main Module" ( usually the one with the shortest string length ), and then extracting the abstract from that.
This can be overridden via:
main_module = path/to/module.pm
And you can always define the abstract explicitly:
abstract = Dist::Zilla goes RAWR and BITES OFF CTHULHUS NOSES.
V1 Caveats
Unfortunately, there are some problems with all the toolchains that only understand v1 spec natively, and thats even when they do emit a META.json file, that file is upconverted from a v1 META.yml format, which yeilds a few difficulties.
Mostly, the license you specified in the configuration might not be the license that ends up in the V2 meta file, and likewise, might not be the value that gets displayed via MetaCPAN's API.
This is due to the inherent limitation of the initial license types.
V1 for example, only had gpl, not gpl_1 , gpl_2 and gpl_3, so when you upconvert gpl to a meta2 license type, it can't guess which one you meant, and instead, defaults to simply open_source. ( see more licenses upconversion issues )
And inversely, if you have a V2-only system, anything that downconverts META.json to v1 if it needs a v1 file( instead of doing the right thing and reading the META.yml, which is already in v1 format ) , will risk having the license type broken:
( Nice big list of the downconversions here: https://metacpan.org/source/RJBS/CPAN-Meta-2.113640/lib/CPAN/Meta/Converter.pm#L179 )
Anything that simultaneously sets v1 and v2 licenses by using Software::License should be fine however, its just the conversions between Meta versions that causes issues. But its still sadly something that needs to be taken into account till all parts of the toolchain and running on the v2 spec.
|
This is the tutorial I wish I had for integrating Passport.js with Sails.js. When creating web applications, you'd love to have a user sign-in and sign-out function, while limiting access to certain functions if the visitor is merely a guest.
Enter Passport.js. This fantastic piece of unobtrusive Express middleware provides many mechanisms of authorization, including the usual username/password, or even social media such as Twitter and Facebook.
Sails.js is based off Express, so we'd expect Passport.js to slide in nicely, and it certainly does. Without further ado, let's get to making an application!
We create our Sails app which we'll name auth. the current version of sails i'm using is 0.9.7.
sails new auth --template=jade
By default Sails.js uses the EJS templating language, which I'm not a huge fan of, so I'm changing it to Jade. Let's install that dependency using NPM:
npm install jade
Next we install Passport.js and the Local strategy:
npm install passport && npm install passport-local
Because we're using Passport.js as an Express middleware, we need to configure that. Create a file in the folder "config" named "passport.js".
// Location: /config/passport.js var passport = require('passport'), LocalStrategy = require('passport-local').Strategy, bcrypt = require('bcrypt'); passport.serializeUser(function(user, done) { done(null, user[0].id); }); passport.deserializeUser(function(id, done) { User.findById(id, function (err, user) { done(err, user); }); }); passport.use(new LocalStrategy( function(username, password, done) { User.findByUsername(username).done(function(err, user) { if (err) { return done(null, err); } if (!user || user.length < 1) { return done(null, false, { message: 'Incorrect User'}); } bcrypt.compare(password, user[0].password, function(err, res) { if (!res) return done(null, false, { message: 'Invalid Password'}); return done(null, user); }); }); }) ); module.exports = { express: { customMiddleware: function(app){ console.log('express midleware for passport'); app.use(passport.initialize()); app.use(passport.session()); } } };
In the above piece of code many things are happening:
Modules are being required: passport and its local strategy, as well as bcrypt which is our password encryption module.
serializeUser and deserializeUser is being configured to tell Sails how to parse User into req.session and passport.session.
The custom local strategy that we will be using is being defined, accessible later from our authentication controller.
Next, we'd want to create the User model, and its controller:
sails g model Usersails g controller User
We'll give our User model two fields, a username field and a password field, with optional but commonly added validations.
//User.js module.exports = { attributes: { username: { type: 'string', required: true, unique: true }, password: { type: 'string', required: true }, };
We don't want to store our password as plaintext, so we'll use bcrypt. We'll want to install that npm dependency first:
npm install bcrypt
Following which, we'll require the module in our User model. To convert a password from plaintext to an encrypted one, we'll use bcrypt. When a POST request is sent to create a User, the beforeCreate function is called. We will overide the beforeCreate method to encrypt the password before saving:
var bcrypt = require('bcrypt'); module.exports = { attributes: { username: { type: 'string', required: true, unique: true }, password: { type: 'string', required: true }, }, beforeCreate: function(user, cb) { bcrypt.genSalt(10, function(err, salt) { bcrypt.hash(user.password, salt, function(err, hash) { if (err) { console.log(err); cb(err); }else{ user.password = hash; cb(null, user); } }); }); } };
Finally, in our API, we do not wish to return the password to the client. To do so, we override the toJSON method on the User model, and delete the password attribute from the User object. Behold, our completed User model:
var bcrypt = require('bcrypt'); module.exports = { attributes: { username: { type: 'string', required: true, unique: true }, password: { type: 'string', required: true }, //Override toJSON method to remove password from API toJSON: function() { var obj = this.toObject(); // Remove the password object value delete obj.password; // return the new object without password return obj; } }, beforeCreate: function(user, cb) { bcrypt.genSalt(10, function(err, salt) { bcrypt.hash(user.password, salt, function(err, hash) { if (err) { console.log(err); cb(err); }else{ user.password = hash; cb(null, user); } }); }); } };
Next, we'll need an auth controller to handle authorizations:
sails g controller Auth
In this Auth controller we need three actions, login (GET and POST -> the "process" action) and logout. We'll use passport in this controller, so we'll need to require it too. We'll be using passport's methods primarily here:
// Location: /api/controllers/AuthController.js var passport = require("passport"); module.exports = { login: function(req,res){ res.view("auth/login"); }, process: function(req,res){ passport.authenticate('local', function(err, user, info){ if ((err) || (!user)) { res.redirect('/login'); return; } req.logIn(user, function(err){ if (err) res.redirect('/login'); return res.redirect('/'); }); })(req, res); }, logout: function (req,res){ req.logout(); res.send('logout successful'); }, _config: {} };
We'll add in the respective routes in our routes file:
// Location: config/routes.js module.exports.routes = { '/': { view: 'home/index' }, 'get /login': "AuthController.login", 'post /login': 'AuthController.process', 'get /logout': 'AuthController.logout', }
Populate our login page with HTML:
form(action='/login', method='post') div label Username: input(type='text', name='username') div label Password: input(type='password', name='password') div input(type='submit', value='Log In')
For more information on how passport works visit the documentation here. If a user is signed in, req.isAuthenticated will return true. We'll make use of that in a policy to check for authentication:
// Location: /api/policies/authenticated.js module.exports = function(req, res, next){ if (req.isAuthenticated()){ return next(); }else{ return res.send(403, { message: 'Not Authorized' }); } }
We can then edit our config/policies.js to require authentication for all controllers, while whitelisting the auth controller:
// Location: config/policies.js module.exports.policies = { '*': "authenticated", UserController: { "create": true, } AuthController: { '*': true, } }
That should about do it! As homework, create your own sign-up page (I'm lazy). Many thanks to those who helped me along the way (Matt Raykowski yup you!).
UPDATE:
I updated the code for the middleware, such that it works for all my readers. Thanks for everybody's input!
|
Legos are perfect. I liked them as a kid, I liked them as a slightly older kid (even while pretending that I was too old for such things), and I like them now (having graduated from ninja temples to recreations of Fallingwater). There's something about playing with them that brings out creativity and imagination: even though I might not tinker with them as much as I did many years ago, they evoke a very specific sort of joy that I can't resist.
Which brings me to the downside of having such a childlike habit: as an adult, you have to buy your own toys.
And jeez, these little bricks can get expensive: that Fallingwater set runs for $99.99, which is low compared to some of the "grown-up" sets dedicated to adult Lego fans like myself, who have more disposable income than self-control.
But have they always been so expensive?
To answer this question, I needed to get as much data about Legos as I could find. Thankfully, I found BrickSet, a sort of Lego database, which comes with its own handy export feature so I didn't even have to bother with scraping. (I uploaded a .csv of their entire data as a Gist to avoid hammering their servers, but I recommend checking out the site — pretty neat stuff.)
Assumptions and Notes
Worth noting a few things here:
Obviously the integrity of my analysis is limited by the integrity of the data. While I couldn't find a better source than BrickSet, I'm sure its still missing a few sets and details.
I'm filtering out any sets with less than two pieces or a price of less than two dollars. Notably, this excludes items listed as 'sets' that don't have any actual pieces.
I'm not taking inflation into account.
These graphs are drawn with the wonderful python-nvd3 library.
Prices are in USD.
Alright, that's all the boring stuff. Let's get started!
import pandas as pd
import numpy as np
from nvd3 import lineChart, discreteBarChart
filename = 'legos.csv'
outfile = open('legos.html', 'w')
# Main charting function. Pretty ugly.
def print_chart(name, df, bar=False):
width = 800
height = 300
xdata = list(df.keys())
try:
xdata = map(lambda x: float(x), xdata)
except:
pass
ydata = list(df.values)
if bar:
chart = discreteBarChart(name=name.replace(" ", ""), height=height, width=width)
chart.add_serie(name=name, y=ydata, x=xdata)
else:
chart = lineChart(name=name.replace(" ", ""), height=height, width=width, x_axis_format='')
extra_serie = {"date_format": "%Y"}
chart.add_serie(name=name, y=ydata, x=xdata)
chart.buildcontent()
outfile.write(chart.htmlcontent)
# Some boring parsing
data = pd.read_csv(filename)
data.fillna(0)
data = data[(data['Pieces'] > 1) & (data['USPrice'] > 1)]
Price over time
The first thing I wanted to check was the obvious hypothesis: your average Lego set has gotten more expensive over time.
Let's take a look:
print_chart("Price over time", data.groupby('Year')['USPrice'].mean())
At first glance, it looks like, yes, 1 price is increasing steadily over time. However, raw price per set is something of a flawed metric: after all, a $200 set with one thousand pieces is a better deal than a $10 set with twenty. What happens if we look at price per brick, instead of just price?
data['$/p'] = data['USPrice'] / data['Pieces']
print_chart("Price per brick over time", data.groupby('Year')['$/p'].mean())
Well, that's certainly a different picture. Price per brick appears to have peaked in the early nineties and slowly come back to earth since then, where it hovers around a quarter.
Price per brand
So, price hasn't particularly increased over time. Another popular hypothesis is that Lego's profits has come from the premium they charge for licensed sets: from the perennial Star Wars 2 sets to more adventurous collaborations like The Avengers and even Minecraft, its easy to imagine that the company imposes something of a 'brand tax' on these sets. Let's group the sets by theme and see for ourselves:
print_chart("Average price per brick grouped by theme", data.groupby('Theme')['$/p'].mean().order(), bar=True)
Huh -- not exactly what I was expecting. While it's definitely true that the more generic Legos are cheaper -- "Homemaker", "Freestyle", and "Classic" being amongst the cheapest themes -- The Lego Movie and Minecraft 3 are also on the cheaper end of the spectrum. Instead, it looks like the real heavy hitters are the niche sets: those for children ("Education", "Baby") and for programmers and tinkerers ("Galidor", "Mindstorms").
Should you buy in bulk?
print_chart("Price per brick grouped by pieces", data[(data['Pieces'] > 15)].groupby('Pieces')['$/p'].mean())
Short answer: yes.
Long answer: well, yeah, but after a certain point it won't make too big of a difference. Those tiny accessory and minifig-heavy sets will kill your wallet in the long run, though.
So, what's changed?
For my money, the biggest thing that's changed is my perception -- and my tastes, I suppose, as the sets that catch my eye nowadays tend to be much more expensive than the simple (and ninja-filled) sets of my childhood.
Which is relevant in of itself: Lego's push to appeal to the adults who grew up with the blocks is a relatively recent one, as they continue to segment their audience. This can be visualized (albeit roughly) by graphing standard deviation of prices over time, showing that the range of prices itself has increased:
print_chart("Variance over time", data.groupby('Year')['USPrice'].agg({'variance' : np.std})['variance'])
|
I'm trying to measure the execution time of a small Python code snippet of mine and I'm wondering what's the best way to do so.
Ideally, I would like to run some sort of setup (which takes a loooong time), then run some test code a couple of times, and get the minimum time of these runs.
timeit() seemed appropriate, but I'm not sure how to obtain the minimum time without re-executing the setup. Small code snippet demonstrating the question:
import timeit
setup = 'a = 2.0' # expensive
stmt = 'b = a**2' # also takes significantly longer than timer resolution
# this executes setup and stmt 10 times and the minimum of these 10
# runs is returned:
timings1 = timeit.repeat(stmt = stmt, setup = setup, repeat = 10, number = 1)
# this executes setup once and stmt 10 times but the overall time of
# these 10 runs is returned (and I would like to have the minimum
# of the 10 runs):
timings2 = timeit.repeat(stmt = stmt, setup = setup, repeat = 1, number = 10)
|
Let me reformulate. I am inside a ForEach loop what is supposed to add calculated decimal? values to the decimal? originalAmount that is of course null on the first time as you pointed out. So I just need to check null first otherwise do the addition.
decimal? convertedAmount = Calculate(inputValue); //always returns a value
originalAmount = originalAmount==null ? convertedAmount : originalAmount + convertedAmount;
The originalAmount is defined earlier, outside the loop.
Sorry for the confusion, the question can be closed / deleted if necessary.
|
JavaScript
mattastic — 2010-07-20T05:24:31-04:00 — #1
Hi Folks,
Is there a way to use them in strings?
Can I search for them and replace them with an ascii value or silimar somehow?
Thanks in advace
autisticcuckoo — 2010-07-22T01:18:41-04:00 — #2
I don't understand.
If it's from an input field it's already a string!
Do you mean the text comes from a database and you're creating JavaScript containing that text using server-side programming? In that case you need to escape special characters in the server-side script that generates the code. It's not a JavaScript problem.
Why should that cause an error (unless homepage[0] is undefined)?
When asking for help online it's always a good idea to be as explicit as possible about what you're trying to do, and why. Providing code examples of existing code also helps. I don't quite understand what you are trying to do, or how.
mattastic — 2010-07-21T04:49:39-04:00 — #3
Thanks for your reply.
Its from a user input field so I'm not sure where the special chars will be and what they are.
I query the database and create my html, could I use a regular expression or similar when doing this to convert all the special chars to javascript friendly text?
For example this code causes an error:
homepage[0] += "example - example"
Many thanks
autisticcuckoo — 2010-07-21T01:48:49-04:00 — #4
What special characters? If you want to include a character that you cannot input directly from your keyboard, or cannot be represented using the character encoding you use, you can use escape notation.
Octal escape notation:
var copyright = "\\251 2010";
Unicode escape notation:
var copyright = "\\u00a9 2010";
Literal notation:
var copyright = "© 2010";
For characters that are special to JavaScript, escape them with a preceding backslash:
var s1 = "My \\"new\\" car";
var s2 = 'Jane\\'s car';
mattastic — 2010-08-03T06:17:38-04:00 — #5
Thanks for your reply.
The javascript thats causing an error is below.
Can you help?
Thankyou
homepage[0] = "<h2 class='draggable'>Bring n buy</h2><div class='container'>"
homepage[0] += '<ul>'
homepage[0] += "<li><a href='index.cfm?area=marketplace/index&page=view-forum&forumid=267'>Kingsize bed frame</a></li>"
Error: unterminated string literal
Source File: http://intranet/portal.cfm
Line: 24, Column: 16
Source Code:
homepage[0] += "<li><a href='index.cfm?area=marketplace/index&page=view-forum&forumid=267'>
autisticcuckoo — 2010-08-04T01:09:23-04:00 — #6
Do you have this JavaScript code between <script> and </script> rather than in an external script file (<script src="..."></script>?
If so, the problem is most likely the closing tags you have in your strings.
In HTML (which includes pretend-XHTML) the script element type has a content model of CDATA, which behaves a bit oddly. One oddity is that the first occurrance of the character sequence '</' followed by a name-start character will be interpreted as </script> and thereby close the script tag.
To prevent this you need to escape that character sequence, which you can do by inserting a backslash character between the '<' and the '/'. That 'escapes' the '/' character.
homepage[0] += "<li><a href='index.cfm?area=marketplace/index&page=view-forum&forumid=267'>Kingsize bed frame<\\/a><\\/li>"
Without the backslash characters in the end tags, the script tag is closed after 'bed frame' which means the string constant isn't properly terminated.
|
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
|
Andreas R.
Impossible de joindre les serveurs.
Bonsoir,
Je suis sous Kubuntu 5.10 fraichement installé (mais pas pour la premiere fois ).
J'ai donc petit(gros) probleme.
Lorsque je lance un apt-get update je reçois ceci.
funky@funkycrash:~$ sudo apt-get update
Err http://kubuntu.org breezy Release.gpg
Connexion à kubuntu.org: 80 (1.0.0.0) impossible, délai de connexion dépassé
Err ftp://bolugftp.uni-bonn.de breezy Release.gpg
Connexion à bolugftp.uni-bonn.de: 21 (1.0.0.0) impossible, délai de connexion dépassé
Err http://www.mirrorservice.org breezy Release.gpg
Connexion à www.mirrorservice.org: 80 (1.0.0.0) impossible, délai de connexion dépassé
Err http://mirror.cc.columbia.edu breezy Release.gpg
Connexion à mirror.cc.columbia.edu: 80 (1.0.0.0) impossible, délai de connexion dépassé
0% [Connexion à kubuntu.org (1.0.0.0)]
J'ai le net qui fonctionne a merveille, et mon sources.list me semble correct :
Kubuntu
deb http://kubuntu.org/packages/kde351 breezy main
deb ftp://bolugftp.uni-bonn.de/pub/kde/stable/3.5.1/kubuntu breezy main
deb http://www.mirrorservice.org/sites/ftp.kde.org/pub/kde/stable/3.5.1/kubuntu breezy main
deb http://mirror.cc.columbia.edu/pub/software/kde/stable/3.5.1/kubuntu breezy main
## Dépôts source officiels (rarement utiles pour l'utilisateur final -- supprimez les # pour les activer)
# deb-src http://fr.archive.ubuntu.com/ubuntu/ breezy main restricted universe multiverse
# deb-src http://fr.archive.ubuntu.com/ubuntu/ breezy-updates main restricted universe multiverse
# deb-src http://fr.archive.ubuntu.com/ubuntu/ breezy-security main restricted universe multiverse
# deb-src http://fr.archive.ubuntu.com/ubuntu/ breezy-backports main restricted universe multiverse
# deb-src http://archive.ubuntu.com/ubuntu breezy-backports main universe multiverse restricted
## Dépôt PLF (ce dépôt n'est pas supporté par Cannonical et doit être utilisé à vos propres risques)
# deb http://packages.freecontrib.org/ubuntu/plf/ breezy free non-free
# deb-src http://packages.freecontrib.org/ubuntu/plf/ breezy free non-free
## OpenOffice.org2
#deb http://people.ubuntu.com/~doko/OOo2 ./
## Spécifiques à KDE
# KDE (ce dépôt fournit la dernière version de KDE)
deb http://kubuntu.org/packages/kde-latest breezy main
# KOffice (ce dépôt fournit la dernière version de KOffice)
#deb http://kubuntu.org/packages/koffice-latest/ breezy main
# Amarok (ce dépôt fournit la dernière version de Amarok)
deb http://kubuntu.org/packages/amarok-latest breezy main
Je ne comprends vraiment pas, a moins que peut-être les serveurs soient down?
Merci de votre aide.
Hors ligne
kornwall
Re : Impossible de joindre les serveurs.
presque bon ton sources.list
supprimez les # pour les activer
# deb-src http://fr.archive.ubuntu.com/ubuntu/ breezy main restricted universe multiverse
# deb-src http://fr.archive.ubuntu.com/ubuntu/ breezy-updates main restricted universe multiverse
# deb-src http://fr.archive.ubuntu.com/ubuntu/ breezy-security main restricted universe multiverse
# deb-src http://fr.archive.ubuntu.com/ubuntu/ breezy-backports main restricted universe multiverse
# deb-src http://archive.ubuntu.com/ubuntu breezy-backports main universe multiverse restricted
supprimez les # pour les activer
# deb http://packages.freecontrib.org/ubuntu/plf/ breezy free non-free
# deb-src http://packages.freecontrib.org/ubuntu/plf/ breezy free non-free
supprimez les # pour les activer
#deb http://people.ubuntu.com/~doko/OOo2 ./
#deb http://kubuntu.org/packages/koffice-latest/ breezy main
pour toutes ces ligne, il faut supprimer le # devant
ca marchera un peu mieux
ce qui fait que ca doit être comme ceci :
tu m'en diras des nouvelles
Kubuntudeb http://kubuntu.org/packages/kde351 breezy maindeb ftp://bolugftp.uni-bonn.de/pub/kde/stable/3.5.1/kubuntu breezy maindeb http://www.mirrorservice.org/sites/ftp.kde.org/pub/kde/stable/3.5.1/kubuntu breezy maindeb http://mirror.cc.columbia.edu/pub/software/kde/stable/3.5.1/kubuntu breezy main
## Dépôts source officiels (rarement utiles pour l'utilisateur final -- supprimez les # pour les activer)
deb-src http://fr.archive.ubuntu.com/ubuntu/ breezy main restricted universe multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ breezy-updates main restricted universe multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ breezy-security main restricted universe multiverse
deb-src http://fr.archive.ubuntu.com/ubuntu/ breezy-backports main restricted universe multiverse
deb-src http://archive.ubuntu.com/ubuntu breezy-backports main universe multiverse restricted
## Dépôt PLF (ce dépôt n'est pas supporté par Cannonical et doit être utilisé à vos propres risques)
deb http://packages.freecontrib.org/ubuntu/plf/ breezy free non-free
deb-src http://packages.freecontrib.org/ubuntu/plf/ breezy free non-free
## OpenOffice.org2
deb http://people.ubuntu.com/~doko/OOo2 ./
## Spécifiques à KDE
# KDE (ce dépôt fournit la dernière version de KDE)
deb http://kubuntu.org/packages/kde-latest breezy main
# KOffice (ce dépôt fournit la dernière version de KOffice)
deb http://kubuntu.org/packages/koffice-latest/ breezy main
# Amarok (ce dépôt fournit la dernière version de Amarok)
deb http://kubuntu.org/packages/amarok-latest breezy main
Dernière modification par kornwall (Le 03/03/2006, à 02:15)
Golom golom
Hors ligne
Andreas R.
Re : Impossible de joindre les serveurs.
Merci pour ta réponse, mais c'est moi-même qui les avais rajoutés pour faire des tests . Je n'arrive toujours pas a me connecter c'est incroyable.
Peut etre a cause de ma configuration reseau ?
Je passe par un switch, puis par un routeur.
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...
~27 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/7/2012] Challenge #19 [easy] (self.dailyprogrammer)
submitted 2 years ago by mattryan
Challenge #19 will use The Adventures of Sherlock Holmes from Project Gutenberg.
Write a program that counts the number of alphanumeric characters there are in The Adventures of Sherlock Holmes. Exclude the Project Gutenberg header and footer, book title, story titles, and chapters. Post your code and the alphanumeric character count.
[–]luxgladius0 0 1 point2 points3 points 2 years ago (0 children)
Alphanumeric characters as in only the characters that are A-Z, a-z, and 0-9? Odd request, but ok. Hardest part is removing all the stuff, but I've already done that for the other two, so...
Perl
use LWP::UserAgent; my $ua = LWP::UserAgent->new; my $text = $ua->get('http://www.gutenberg.org/cache/epub/1661/pg1661.txt')->content; $text =~ s/\r//g; #get rid of annoying CRs @section = split /^(?=(?:[XVI]+\. THE )?ADVENTURE)/m, $text; shift @section; #remove file header $section[-1] =~ s/^\s*End of the Project Gutenberg EBook.*//ms; #remove end matter foreach (@section) { my ($title) = /^(.*)/; s/^.*\n(?:\s*\n)*//; $title =~ s/\s+$//m; push @title, $title; $text{$title} = $_; } $text = join '', map {$text{$_}} @title; $text =~ s/^\s*[IVX]*\.\s*\n(\s*\n)*//mg; $text =~ s/[^a-z0-9]//ig; print length $text;
Output 431301
[–]whiteychs0 0 1 point2 points3 points 2 years ago* (4 children)
Perl utilizing bash with wget. No other languages going to try?
$x=`wget -q -O- www.gutenberg.org/cache/epub/1661/pg1661.txt`; $x=~s/[[\W|\s]//g; $x =~ s/^.*?THEADVENTURESOF/THEADVENTURESOF/g; $x=~s/EndoftheProjectGutenberg.*//g;print(length$x);
[–]bigmell 0 points1 point2 points 2 years ago (0 children)
it would take too much effort wink
nice solution btw, got 432139 characters using yours.
[–]cooper6581 0 points1 point2 points 2 years ago (1 child)
It's been a long time since I've used Perl, so sorry if this is a dumb question, but is this one counting punctuation?
[–]whiteychs0 0 0 points1 point2 points 2 years ago (0 children)
No, it catches punctuation with \W.
[–]bigmell 0 points1 point2 points 2 years ago* (3 children)
Perl pass the txt file as a command line arg.
my $count = 0; while(<>){ my @line = split /\w/; $count+= scalar(@line); } print "$count characters in Sherlock Holmes, I'll put it on the book list, im reading Darth Plageuis the wise now :)\n";
oh i got 126300 characters is that right?
[–]luxgladius0 0 0 points1 point2 points 2 years ago (1 child)
Few things, aside from the details of excluding headers and footers, story titles, etc...
As written, this will count the number of words, not characters... sort of. Actually, it will count the number of fields delimited by non-word characters, so, for example "something in the cellar--something which" would come out as 7 because of the extra blank string between the two hyphens.
yea changed the regular expresion to \w instead of \W and that produces a count of 460691 which is closer to your number. Cool the only difference between the easy and difficult project was the regular expression.
[–]cooper6581 0 points1 point2 points 2 years ago (0 children)
Python:
#!/usr/bin/env python import sys def create_text(f): buffer = [] lines = open(f).readlines() chapters = [ "II.", "IV. The Boscombe Valley Mystery", "V. The Five Orange Pips", "VI. The Man with the Twisted Lip", "IX. The Adventure of the Engineer's Thumb", "X. The Adventure of the Noble Bachelor", "XI. The Adventure of the Beryl Coronet"] for line in lines[61:12630]: hit = 0 for chapter in chapters: if chapter.lower() in line.lower(): hit = 1 break if not hit: buffer.append(line) return buffer def count_chars(b): chars = 0 for line in b: for c in line: if c.isalnum(): chars += 1 return chars if __name__ == '__main__': buffer = create_text(sys.argv[1]) print count_chars(buffer)
Output:
new-host-3:easy cooper$ ./challenge.py ./pg1661.txt 429546
[–]Kil_Roy 0 points1 point2 points 2 years ago (3 children)
After 3 hours, in python =D
#opening the file for reading filein = open("C:\sherlock.txt", "r") holmes = filein.read() #finding and deleting everything before the first book starts #(determined by the first three indexes of "ADVENTURE") for i in range(0,3): holmes = holmes[holmes.index("ADVENTURE"):] holmes = holmes[holmes.index("\n"):] #break document up into the different books #The end of each book is found by finding the begining of the next #The book is stored in it's respective variable and then thrown out of #of the holmes variable books = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for i in range(0,11): if i < 6: books[i] = holmes[:holmes.index("ADVENTURE")] #Starting with book six the titles change format from "Adventure # ..." # To "# The Adventure of..." so the 10 chars before "ADVENTURE" must also be thrown out else: books[i] = holmes[:holmes.index("ADVENTURE") - 10] holmes = holmes[holmes.index("ADVENTURE"):] holmes = holmes[holmes.index("\n"):] #Books[11] is the last book so we find the end with the index of "End of the Project Gutenberg" books[11] = holmes[:holmes.index("End of the Project Gutenberg")] #The first book seems to be the only one that has chapter numbers, so we'll throw those out now books[0] = books[0].replace("I.\n","") books[0] = books[0].replace("II.\n","") books[0] = books[0].replace("III.\n","") #removing non-alphanumerics with regular expressions import re pattern = re.compile('\W') totalLen = 0 lens = [0,0,0,0,0,0,0,0,0,0,0] for x in range(0,11): books[x] = re.sub(pattern, '', books[x]) lens[x] = len(books[x]) totalLen += lens[x] #and finally print the total number of charachters print totalLen](/spoiler)
Notes:
I'm new at this, advising greatly appreciated
For some reason whenever I tried to create an empty list, then fill it with my for loops I received the following error:
IndexError: list assignment index out of range
I'm still not sure why... can anyone help me?
Also, I returned 390,539 for the number of characters.
[–]Gasten 0 points1 point2 points 2 years ago (2 children)
You mean this part, right?
lens = [0,0,0,0,0,0,0,0,0,0,0] for x in range(0,11): books[x] = re.sub(pattern, '', books[x]) lens[x] = len(books[x])
The thing with arrays (lists) is that the first item will be [0], the second [1] and so on (the last item will be [totalLength-1]. This means that if you have 11 items in your list, the last item will be [10]. You have one too many iterations in your loop.
IIRC:Also check out python specific "array.length()" and "for x in array" as a more dynamic shorthand for "range()"
[–]Kil_Roy 0 points1 point2 points 2 years ago (1 child)
I did not.
Thanks for catching that.
[–]Gasten 0 points1 point2 points 2 years ago (0 children)
Also, this part:
#Books[11] is the last book so we find the end with the index of "End of the Project Gutenberg" books[11] = holmes[:holmes.index("End of the Project Gutenberg")]
It's good python-practice to refer to the last item in a list with [-1]. You should always try to keep your lists length-insensitive so the code is easier to reuse and modify.
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 7368 on app-11 at 2014-09-20 02:37:28.800065+00:00 running d16e201 country code: US.
|
The role of the network administrator is broad and varied. While most of our time is spent with day-to-day operational tasks such as assigning IP addresses and configuring hosts and applications to use an existing network, we'll occasionally be called upon to do some more interesting things.
One of the more interesting and rewarding activities of the network administrator involves the planning and design of a brand-new network and the selection and configuration of network applications to run across it. Network design inevitably involves compromise, trading off one characteristic against another. Common trade-offs are link bandwidth against cost, or latency against loss, or bandwidth against latency.
Consider the case of a remotely located site that you wish to network-connect to a central site. A satellite-based connection might offer high bandwidth at a reasonable cost but offer latency times of over a second or more, compared to a terrestrial link which might offer lower bandwidth but with latency of the order of hundreds of milliseconds instead for much the same price. A dedicated point-to-point link might offer a virtually loss-less connection but at a higher cost than a frame relay connection that exhibits some datagram loss.
Choosing the best solution requires a detailed understanding of the end-user requirements and the network applications they will be using. Sometimes the best or only way of knowing what is the best network design is to actually try a few different ones and see which works best. Doing that is difficult and expensive unless you have a way of emulating the behavior of each of the options with your existing network. This is just one use of NISTNet.
NISTNet is a software package developed by Mark Carson of the North American National Institute of Standards and Technology (NIST) that allows network designers, application developers, and network researchers to pretty accurately emulate the performance conditions presented by a variety of TCP/IP networks and network paths.
NISTNet replaces the normal Linux IP forwarding mechanism with one that allows the network administrator to set and control the levels of each of a number of key network behaviors. These behaviors include datagram loss, datagram delay, delay variation, and the maximum available bandwidth in the forward and backward directions. Real networks display each of these characteristics. Consider the following examples:
NISTNet allows each of these conditions to be intentionally introduced into an otherwise healthy network connection to allow administrators to emulate larger, more complex networks and observe the resulting behavior of network protocols and applications.
NISTNet provides both command line and X11-based userspace clients to control the operation of the kernel code.
The NISTNet software package is public domain software and so is freely available for all to use and abuse as they please. The software provides a number of loadable kernel modules and corresponding userspace applications to control the behavior of the modules. Kernel patch files are supplied that provide replacement timer code that allows finer clock resolution, which is essential for accurate emulation.
The most recent version of the NISTNet software is version 2.0 alpha, revision 3. This version compiles against the most current 2.0 and 2.2 version kernels. The NISTNet source code is available from the NISTNet web site.
The software is fairly easy to compile. No special libraries are required. There are only two small tricks. First, make sure that your kernel source is either in the /usr/src/linux directory or that there is a symlink pointing to where you have your kernel source. There are scripts that automate the application of the fast-timer patches that assume this to be the case. Second, be sure to remember to inspect the monitor/Imakefile file and make sure the OURXAWLIB define is pointing to the version of the Athena Widgets library you wish to use; the default is probably OK.
To compile the software you should run the Patch.Kernel script to patch the kernel. Recompile the kernel with the patches applied using the usual process. Be sure to select both of the new configuration options presented:
Kernel hacking ---> [*] Fast timer [*] Packet routine hacking
When the kernel is compiled and installed, return to the top level of the NISTNet source and run:
make make install
This will compile both the text and X11 versions of the userspace programs as well as the new kernel modules, and will install them in fairly sensible locations on your machine. Debian users note: the kernel modules are installed in the /lib/modules/misc/, which is probably not what you want. You can easily move them into the appropriate misc/ subdirectory of the kernel you've compiled. The installation step will also create some special device files in the /dev/ directory that provide the interface that the userspace programs will use to talk to the kernel modules.
The way you'd usually use NISTNet is to install the software on a Linux-based router installed in your test environment. The router would have a number of network interfaces configured. For example, you might have two Ethernet interfaces configured, each supporting a different IP network. You'd place your test hosts on either side of the router and configure NISTNet to exhibit the characteristics you wish to model and run your test.
The primary module is nistnet.o, which is the main body of the network emulation code that augments the normal IP forwarding routines in the kernel. The first thing you need to do is to load the module. You can use either insmod or modprobe to do this:
modprobe nistnet
When the module is loaded you will be able try out the client. You must have root permissions to run the client programs. While the text mode interface is convenient for scripting purposes, I find the X11 client much easier to use. The X11 client is called xnistnet.
When you first start the xnistnet client you will be presented with a large display looking something like that of figure 1.
Figure 1. NISTNet GUI client (click on image for full size view).
Each row of the display represents an emulation rule. In the left-hand panel, you configure the hosts or services that must match for that rule to apply when forwarding. You may specify host or network addresses, protocols such as TCP and UDP, and ports by name or by number. You must supply both a source and destination pattern, and rules are not bidirectional; that is, you must configure a rule for each direction. The rules for configuring a pattern are simple enough, but don't look it initially.
In the right-hand panel you configure the actual conditions that will be applied when that rule is matched, and in the right-most fields you are able to see some running statistics for the connections represented by the rule.
More comprehensive instructions and explanations of each of the fields are supplied with the package, so there is little point in reproducing them here. Instead, let's look at a simple example.
Let's imagine that our lab setup is built of three Linux machines. One, the NISTNet router, has an Ethernet interface and a PPP interface to another Linux machine with a null modem link at 33.6 kilobits/second. The third Linux machine is on the Ethernet network and has the IP address of 192.168.1.1 that we'll use to send test traffic to the PPP-connected Linux machine, which has the address 192.168.2.1. Our test environment is illustrated in figure 2.
Figure 2. Example test environment.
We'll illustrate the capability of NISTNet using a simple ping test. In practice you'd probably be using something much more relevant to your application. In a stable state, no rules configured, our ping test looks like:
ping -c 10 -i 2 -s 1460 192.168.2.1
PING 192.168.2.1 (192.168.2.1): 1460 data bytes
1468 bytes from 192.168.2.1: icmp_seq=0 ttl=254 time=1097.6 ms
1468 bytes from 192.168.2.1: icmp_seq=1 ttl=254 time=1064.4 ms
1468 bytes from 192.168.2.1: icmp_seq=2 ttl=254 time=1057.2 ms
1468 bytes from 192.168.2.1: icmp_seq=3 ttl=254 time=1021.9 ms
1468 bytes from 192.168.2.1: icmp_seq=4 ttl=254 time=1004.6 ms
1468 bytes from 192.168.2.1: icmp_seq=5 ttl=254 time=1004.8 ms
1468 bytes from 192.168.2.1: icmp_seq=6 ttl=254 time=1053.1 ms
1468 bytes from 192.168.2.1: icmp_seq=7 ttl=254 time=1056.1 ms
1468 bytes from 192.168.2.1: icmp_seq=8 ttl=254 time=1018.9 ms
1468 bytes from 192.168.2.1: icmp_seq=9 ttl=254 time=1062.7 ms
--- 192.168.2.1 ping statistics ---
10 packets transmitted, 10 packets received, 0% packet loss
round-trip min/avg/max = 1004.6/1044.1/1097.6 ms
Let's add a rule that will insert a 500 millisecond delay in datagrams in the forward direction only. To do this we start the xnistnet client and enter the address of our source machine, 192.168.1.1, into the source field of a rule, and the destination address, 192.168.2.1, into the destination field of the same rule. We then enter 500 into the field labelled "Delay (mS)" in the right-hand panel, and hit the "Update" button to activate it. When we now look at our ping test we see:
ping -c 10 -i 2 -s 1460 192.168.2.1
PING 192.168.2.1 (192.168.2.1): 1460 data bytes
1468 bytes from 192.168.2.1: icmp_seq=0 ttl=254 time=1566.8 ms
1468 bytes from 192.168.2.1: icmp_seq=1 ttl=254 time=1602.2 ms
1468 bytes from 192.168.2.1: icmp_seq=2 ttl=254 time=1552.5 ms
1468 bytes from 192.168.2.1: icmp_seq=3 ttl=254 time=1524.8 ms
1468 bytes from 192.168.2.1: icmp_seq=4 ttl=254 time=1515.1 ms
1468 bytes from 192.168.2.1: icmp_seq=5 ttl=254 time=1515.4 ms
1468 bytes from 192.168.2.1: icmp_seq=6 ttl=254 time=1517.0 ms
1468 bytes from 192.168.2.1: icmp_seq=7 ttl=254 time=1537.3 ms
1468 bytes from 192.168.2.1: icmp_seq=8 ttl=254 time=1517.8 ms
1468 bytes from 192.168.2.1: icmp_seq=9 ttl=254 time=1518.9 ms
--- 192.168.2.1 ping statistics ---
10 packets transmitted, 10 packets received, 0% packet loss
round-trip min/avg/max = 1515.1/1536.7/1602.2 ms
It's easy to see that that did precisely what was expected of it.
Let's try another test. Let's this time try having NISTNet emulate a circuit with 25% datagram loss. To do this we edit our rule, entering 0 into the delay field, entering 25 into the "Drop %" field and again hitting "Update". When we run our ping test it now looks like:
ping -c 10 -i 2 -s 1460 192.168.2.1
PING 192.168.2.1 (192.168.2.1): 1460 data bytes
1468 bytes from 192.168.2.1: icmp_seq=0 ttl=254 time=1014.3 ms
1468 bytes from 192.168.2.1: icmp_seq=2 ttl=254 time=1011.1 ms
1468 bytes from 192.168.2.1: icmp_seq=3 ttl=254 time=1004.4 ms
1468 bytes from 192.168.2.1: icmp_seq=4 ttl=254 time=1027.4 ms
1468 bytes from 192.168.2.1: icmp_seq=6 ttl=254 time=1033.9 ms
1468 bytes from 192.168.2.1: icmp_seq=7 ttl=254 time=1056.5 ms
1468 bytes from 192.168.2.1: icmp_seq=9 ttl=254 time=1043.5 ms
--- 192.168.2.1 ping statistics ---
10 packets transmitted, 7 packets received, 30% packet loss
round-trip min/avg/max = 1004.4/1027.3/1056.5 ms
Ten datagrams is too short a test to expect very accurate results for this sort of test, but it's clear that again NISTNet has done what we've asked of it.
Finally, let's change our test such that rather than dropping 25% of datagrams, we duplicate them. To do this we zero the drop field, and enter 25 into the "Dup %" field instead, hitting the "Update" button once more to activate the change. Our ping test now looks like:
ping -c 10 -i 2 -s 1460 192.168.2.1
PING 192.168.2.1 (192.168.2.1): 1460 data bytes
1468 bytes from 192.168.2.1: icmp_seq=0 ttl=254 time=1097.0 ms
1468 bytes from 192.168.2.1: icmp_seq=0 ttl=254 time=1698.0 ms (DUP!)
1468 bytes from 192.168.2.1: icmp_seq=0 ttl=254 time=1893.2 ms (DUP!)
1468 bytes from 192.168.2.1: icmp_seq=1 ttl=254 time=1013.8 ms
1468 bytes from 192.168.2.1: icmp_seq=2 ttl=254 time=1137.5 ms
1468 bytes from 192.168.2.1: icmp_seq=3 ttl=254 time=1080.7 ms
1468 bytes from 192.168.2.1: icmp_seq=4 ttl=254 time=993.6 ms
1468 bytes from 192.168.2.1: icmp_seq=5 ttl=254 time=993.7 ms
1468 bytes from 192.168.2.1: icmp_seq=6 ttl=254 time=1219.9 ms
1468 bytes from 192.168.2.1: icmp_seq=6 ttl=254 time=1770.3 ms (DUP!)
1468 bytes from 192.168.2.1: icmp_seq=6 ttl=254 time=1828.0 ms (DUP!)
1468 bytes from 192.168.2.1: icmp_seq=7 ttl=254 time=1266.5 ms
1468 bytes from 192.168.2.1: icmp_seq=7 ttl=254 time=1514.3 ms (DUP!)
1468 bytes from 192.168.2.1: icmp_seq=8 ttl=254 time=1041.2 ms
1468 bytes from 192.168.2.1: icmp_seq=9 ttl=254 time=1065.5 ms
--- 192.168.2.1 ping statistics ---
10 packets transmitted, 10 packets received, +5 duplicates, 0% packet loss
round-trip min/avg/max = 993.6/1307.5/1893.2 ms
Magic stuff!
You can design tests that combine all of these together, and of course we've only looked at the simplest of capabilities. NISTNet has a whole suite of much more sophisticated things it can do with datagrams.
One final thing to look at are the statistics that are collected in real time. Start a ping test and scroll the right-hand panel across to the right-most fields. You will see running tallies of packet sizes, bytes transmitted, average bandwidth, and others. These are useful for keeping an eye on progress of the tests.
If you're in a situation where you need to quickly test how a network application or protocol will perform under realistically poor conditions, then NISTNet provides an excellent solution. Mark has gone to a lot of work to ensure that the emulation is as accurate and useful as possible, and I'm sure you'll agree that it truly is one of those tools that you know will come in handy one day; keep it around.
Terry Dawson is the author of a number of network-related HOWTO documents for the Linux Documentation Project, a co-author of the 2nd edition of O'Reilly's Linux Network Administrators Guide, and is an active participant in a number of other Linux projects.
Read more Linux Network Administration columns.
Discuss this article in the O'Reilly Network Linux Forum.
Return to the Linux DevCenter.
Copyright © 2009 O'Reilly Media, Inc.
|
Some answers claimed a "10x" speed advantage for deque vs list-used-as-FIFO when both have 1000 entries, but that's a bit of an overbid:
$ python -mtimeit -s'q=range(1000)' 'q.append(23); q.pop(0)'
1000000 loops, best of 3: 1.24 usec per loop
$ python -mtimeit -s'import collections; q=collections.deque(range(1000))' 'q.append(23); q.popleft()'
1000000 loops, best of 3: 0.573 usec per loop
python -mtimeit is your friend -- a really useful and simple micro-benchmarking approach! With it you can of course also trivially explore performance in much-smaller cases:
$ python -mtimeit -s'q=range(100)' 'q.append(23); q.pop(0)'
1000000 loops, best of 3: 0.972 usec per loop
$ python -mtimeit -s'import collections; q=collections.deque(range(100))' 'q.append(23); q.popleft()'
1000000 loops, best of 3: 0.576 usec per loop
(not very different for 12 instead of 100 items btw), and in much-larger ones:
$ python -mtimeit -s'q=range(10000)' 'q.append(23); q.pop(0)'
100000 loops, best of 3: 5.81 usec per loop
$ python -mtimeit -s'import collections; q=collections.deque(range(10000))' 'q.append(23); q.popleft()'
1000000 loops, best of 3: 0.574 usec per loop
You can see that the claim of O(1) performance for deque is well founded, while a list is over twice as slow around 1,000 items, an order of magnitude around 10,000. You can also see that even in such cases you're only wasting 5 microseconds or so per append/pop pair and decide how significant that wastage is (though if that's all you're doing with that container, deque has no downside, so you might as well switch even if 5 usec more or less won't make an important difference).
|
toma222
[HOW TO] adesklets : configuration des desklets
Il existe désormais un article sur le wiki concernant Adesklets donc je vous conseille de vous y fier, ce tutoriel n'étant plus mis à jour.
J'ouvre ce deuxième post au sujet de adesklets, afin de permettre une meilleure lisibilité de l'ensemble.Celui-ci a donc pour but la configuration des desklets de adesklets, donc on considère que adesklets fonctionne déjà (sinon merci de poster sur l'un des deux sujets : adesklets : installation sous Breezy ou adesklets : installation sous Dapper ou Edgy).
Configuration des desklets
Ici, il faut comprendre que le système est différent de celui de gdesklets. En effet, dans celui-ci il suffit de glisser le desklet qui nous intéresse dans le programme, de double-cliquer dessus et de faire clique-droit pour pouvoir le configurer de façon graphique. Pour adesklets, les choses paraissent plus compliquées, mais c'est loin d'être insurmontable.
Tout d'abord, il faut télécharger l'archive du desklet qui nous intéresse et la décompresser (on peut par exemple créer un répertoire dans son home où on stockera tous les desklets). Dans le dossier décompressé, on trouvera plusieurs fichiers intéressants :
- le README. A lire impérativement, on peut y trouver des informations utiles (comme les dépendances nécessaires) au bon fonctionnement du desklet.
- un fichier config.txt. C'est en éditant ce fichier qu'on pourra configurer notre desklet (dimensions, couleurs, icônes...). Ce fichier s'avère généralement bien fait et dépend du desklets en question donc je ne rentrerais pas dans les détails.
- un dossier contenant les images du desklet (que l'on peut changer dans certains, par exemple pour moi les boutons de xmms_bar).
- enfin, le fichier nom_du_desklet.py. C'est ce fichier qui permet de lancer notre desklet. On peut par exemple double-cliquer dessus et lancer dans un terminal. On nous demande alors si l'on veut le tester (dans ce cas il ne se relancera pas la prochaine fois qu'on démarre adesklets) ou l'enregistrer (pour qu'il apparaisse au prochain démarrage de adesklets).
Remarque : il se peut que vous rencontriez une erreur concernant le police VeraBD lors du lancement d'un desklets. Dans ce cas, vous pouvez par exemple la remplacer par Vera dans le fichier de configuration du desklet concerné.
Quelques astuces pour certains desklets
Je reprend quelques astuces citées dans le premier post.
- System Monitor : il se peut que la configuration par défaut du desklet pose problème. Par exemple, par défaut il y a un module pour la batterie, donc si vous n'avez pas de portable ou qu'il n'a pas de gestion de la batterie, il vous faut supprimer la partie correspondante dans le config. txt (en pensant à compléter le ) et ] si nécessaires). Il se peut également que les chemins indiqués ne correspondent pas à votre configuration (par exemple j'ai du modifier /proc/acpi/thermal_zone/TRM/temperature en /proc/acpi/thermal_zone/THRM/temperature)
- Calendar (astuce donnée par mariop31) : pour mettre le calendrier en français, ajouter dans Calendar.py les lignes :
import locale
locale.setlocale(locale.LC_ALL,'fr_FR.UTF-8')
- Weather (repris du post de Aldones) : pour connaître le code de votre ville, à entrer dans le config.txt à la ligne 'location', allez sur http://fr.weather.com/?from=footer, entrez le nom de votre ville et récupérez dans la barre d'adresses le code (4 lettres et 4 chiffres).
Vous pouvez mettre ici tous les problèmes rencontrés sur les desklets, les astuces que vous auriez trouvé et toutes les remarques sont évidemment les bienvenues. Pensez également à aller faire un tour sur http://adesklets.sourceforge.net/ et pourquoi pas si vous vous débrouillez en anglais à poster sur leur forum.
Dernière modification par toma222 (Le 01/08/2007, à 19:02)
Hors ligne
Doppler
Re : [HOW TO] adesklets : configuration des desklets
ça peut servir : http://adesklets.sourceforge.net/doc/fr
Hors ligne
toma222
Re : [HOW TO] adesklets : configuration des desklets
Oui, effectivement j'ai pas pensé à le donner, merci (je l'ajoute dans la partie installation).
Dernière modification par toma222 (Le 06/12/2005, à 17:31)
Hors ligne
Doppler
Re : [HOW TO] adesklets : configuration des desklets
Un peu d'aide pour débuter avec Modubar et Yab (en pensant à ceux qui ne pratiquent pas l'anglais et pour remercier Toma, Rapass et vous zot' de votre aide )
Modubar est un une barre de lancement qui déchire
En fait c'est Yab améliorée, Modubar en reprend la base et y ajoute juste la possibilité d'intégrer des "modules" à la barre.
Pour exemple Modubar comporte un module lors de sa mise en place, l'horloge. On peut en mettre d'autres, encore faut il savoir les concevoir pour le moment (mais ça risque changer)...
Si vous n'avez que faire de l'horloge et des futurs modules, prennez Yab, c'est exactement pareil sans cette option.
Si vous avez envie du joujou sachez qu'il ne consomme pas plus de ressources dans l'état (avec l'horloge en fonction) que Yab.
Prérequis:
adesklets 0.4.0 ou plus, ainsi que toutes ses dépendances, sont requis pour faire fonctionner cette appli correctement. N'importe quelle machine capable de faire tourner Yab ne devrait avoir aucun problème à faire de même avec Modubar.
Et puis évidement Modubar ou Yab que l'on trouve par là http://adesklets.sourceforge.net/desklets.html
Installation:
c'est comme pour les autres desklets, du moins ceux qui ne demandent pas de paquets spécifiques, en dix secondes c'est fait.
Paramétrer les lanceurs:
Une fois la barre affichée on trouve les cholies icones qui lancent emacs, firefox, gimp, le terminal et xmms. C'est sympathique mais évidement on veut améliorer tout ça.
Dans le fichier config.txt on va trouver les lignes suivantes:
'icons': [('emacs.png', 'GNU Emacs', 'emacs'),
('firefox.png', 'Firefox', 'firefox'),
('gimp.png', 'The GIMP', 'gimp-2.0'),
('terminal.png', 'Terminal', 'xterm'),
('xmms.png', 'XMMS', 'xmms')],
C'est ici que l'on va paramétrer les lanceurs.
Pour commencer, leur ordre: c'est simple la première ligne de la partie de code qui nous interesse (concernant emacs) affichera le premier lanceur en partant de la gauche, ainsi de suite.
Pour chaque lanceur on a un paramétrage de type:
('l'adresse de l'icone', 'la légende qui s'affiche sous l'icone du lanceur', 'la commande qu'il déclanche'),
('firefox.png', 'Firefox', 'firefox'),
Si on veut dans l'ordre firefox, evolution et le terminal ça donne:
'icons': [('firefox.png', 'Firefox', 'firefox'),
('evolution.png', 'Evolution', 'evolution')],
('/home/toto/adesklets/modubar-0.0.1/icons/terminal.png', 'Terminal', 'xterm')],
Pour que cela fonctionne il faut d'une part avoir envoyé au préalable une icone en png nommé evolution dans .../modubar-0.0.1/icons/
et d'autre part s'appeller toto et avoir un dossier nommé adesklets dans son dossier perso etc...
Si c'est le cas tout va bien sinon adaptez avec la direction où se trouve l'icone que vous visez, cela fonctionne aussi.
Vous avez le choix, soit appeller une icone contenue dans le dossier icons de modubar en donnant juste son nom, ou bien aller chercher n'importe quelle icone (en png) n'importe où.
Aprés enregistrement des modifications (Les sauvegardes sont tes amies...) et restart d'adesklets ça doit rouler.
Autres paramètres pour les icones
En réglant les nombres suivants (nb de pixels) la taille maximale des icones varie
'icon_max_height': 80, 'icon_max_width': 80,
idem pour leur taille minimale
'icon_min_height': 54, 'icon_min_width': 54,
Pour accélérer ou ralentir la vitesse de grossissement des icones modifiez 1.0 (seconde) ci dessous:
- par 2.0 par exemple (effet lent) ou par 0.0 (pas d'effet)
'icon_maximize_threshold': 1.0,
Dernier paramètre de la catégorie, l'espacement des icones, modifiez juste la valeur de:
'icon_spacing': 5,
Les légendes ne vous plaisent pas ?
Pour changer la police, remplacez Vera par Impact ou une autre dans la ligne suivante:
(les noms de polices contenant un espace font planter)
'caption_font': 'Vera',
Pour sa taille modifiez la valeur (comme 16 par exemple) dans :
'caption_size': 16,
Et si l'on veut qu'elle soit rouge et non grises, on change 'AAAAAA' par 'FF0000' ici:
(toute couleur héxadécimale devrait faire l'affaire)
'caption_color': 'AAAAAA',
Pour modifier l'aspect de l'effet d'aparition de la légende bidouillez ces lignes
- remplacer True par False pour supprimer l'effet
- augmenter 0.5 permettra de faire durer l'effet (pendant x seconde)
- modifier le nombre de pas - ici 30 - influence la fluidité
'caption_fade_in': True,
'caption_fade_in_duration': 0.5,
'caption_fade_in_steps': 30,
Vous voulez les légendes au dessus des icones et non en dessous ?
Changez False par True ici :
'caption_above': False,
Et pour en finir avec les légendes cette ligne permet de modifier le temps qu'elles restent affichées après le passage de la souris.
Cela doit avoir une utilité mais perso j'laisse comme ça, ça a l'air d'une formule pour exprimer "le moins de temps possible"
'caption_delay': 0.10000000000000001,
Pour ce qui est de l'aspect de la barre...
Trop large ? Trop fine ?
Modifiez l'épaisseur en triturant :
'bar_height': 32,
Les couleurs se décident par ces lignes
- Background 1 = dégradé sur le fond de la barre vertical partant du haut vers le bas
- Background 2 = idem mais partant du bas et en allant vers le haut
- Foreground = contour de la barre
Il ne reste plus qu'à modifier les couleurs ^^ j'vais tester pour voir si des fois des images...
'bar_background_1': 'AAAAAA', 'bar_background_2': 'AAAAAA', 'bar_foreground': '000000',
De la transparence ?
Pour régler l'opacité des backgrounds il suffit de jouer sur le pourcentage suivant:
(100 opaque - None invisible)
'bar_opacity_1': 100,
'bar_opacity_2': None,
Un dernier mot sur les dégradés, on peut jouer sur leur angle en modifiant le degré exprimé ici:
'bar_gradient_angle': 0,
Les Clics
Deux lignes bonus qui sont forts sympatiques...
Clic effect va permettre de modifier la teinte (en %) qui est superposée à l'icone quand on clique dessus
- alpha détermine l'opacité
- red green et blue sont les teintes permettant ainsi l'accés au prisme RVB, on va pouvoir faire dans la finesse !
Clic effect duration laisse la possibilité d'augmenter la durée de l'effet (en secondes) après le clic, bien pratique aussi ^^
'click_effect': 'tint(alpha=100,red=100,green=100,blue=100);',
'click_effect_duration': 0.10000000000000001,
Que reste t'il ?
Et bien les réglages des modules (mod_etc...) et donc de l'horloge pour commencer.
Je n'ai aucune idée de tout ce que peuvent contenir les modules ni comment les réaliser, à découvrir ^^
Pour les paramétrages en tout cas vous devriez pouvoir expérimenter ça par vous même.
Les lignes mod_background, mod_clock_font et autres devraient vous être compréhensibles maintenant.
En fait il faut juste éviter de toucher à:
'modules': [('clock', 1)],
Cette ligne sert à ajouter des modules, ça devrait venir plus tard...
Enjoy
Dernière modification par Doppler (Le 07/12/2005, à 06:27)
Hors ligne
toma222
Re : [HOW TO] adesklets : configuration des desklets
Merci Doppler .
Hors ligne
geronimoO
Re : [HOW TO] adesklets : configuration des desklets
bonjour, je repost mon pb avec le desklet SystemMonitor, quand je le test voici le message d'erreur, et vu mes connaissances en C (quasi nul ) j'y arrive pas:
Traceback (most recent call last):
File "./SystemMonitor.py", line 1107, in ?
EventHandler(dirname(__file__)).pause()
File "./SystemMonitor.py", line 974, in __init__
adesklets.Events_handler.__init__(self)
File "usr/lib/python2.4/site-packages/adesklets/events_handler.py", line 157, in __init__
File "./SystemMonitor.py", line 989, in ready
join(self.basedir,'config.txt'))
File "./SystemMonitor.py", line 265, in __init__
adesklets.ConfigFile.__init__(self, identifier, filename)
File "usr/lib/python2.4/site-packages/adesklets/configfile.py", line 162, in __init__
File "usr/lib/python2.4/site-packages/adesklets/configfile.py", line 205, in _load_and_save
File "usr/lib/python2.4/site-packages/adesklets/configfile.py", line 41, in __call__
File "/usr/lib/python2.4/compiler/transformer.py", line 52, in parse
return Transformer().parsesuite(buf)
File "/usr/lib/python2.4/compiler/transformer.py", line 129, in parsesuite
return self.transform(parser.suite(text))
File "<string>", line 95
'background images': ['images/shared/bg_top.png',
^
SyntaxError: invalid syntax
si quelqu'un a une idée...elle sera la bienvenue
" Un bon indien est un indien mort "
Général Sheridan, cavalerie des Etats Unis.
Hors ligne
toma222
Re : [HOW TO] adesklets : configuration des desklets
Salut, juste pour info, les desklets sont programmés en python, pas en C. Je te post mon config.txt si ça peut t'aider :
id0 = {'background colour': (210, 210, 210, 130),
'background images': ['images/shared/bg_top.png',
'images/shared/bg_middle.png',
'images/shared/bg_bottom.png'],
'meters': [('CPUMeter',
{'horizontal padding': 8,
'icon': 'images/icons/cpu.png',
'krell': 'images/shared/krell.png',
'meter font name': 'VeraBd',
'meter font size': 8,
'trough': 'images/shared/trough.png',
'vertical padding': 8}),
('MemoryMeter',
{'horizontal padding': 8,
'icon': 'images/icons/memory.png',
'krell': 'images/shared/krell.png',
'meter font name': 'VeraBd',
'meter font size': 8,
'trough': 'images/shared/trough.png',
'update speed': 10,
'vertical padding': 8}),
('SwapMeter',
{'horizontal padding': 8,
'icon': 'images/icons/swap.png',
'krell': 'images/shared/krell_blue.png',
'meter font name': 'VeraBd',
'meter font size': 8,
'trough': 'images/shared/trough.png',
'update speed': 30,
'vertical padding': 8}),
('DiskSpaceMeter',
{'horizontal padding': 8,
'icon': 'images/icons/diskfree.png',
'krell': 'images/shared/krell_blue_small.png',
'meter font name': 'Vera',
'meter font size': 6,
'trough': 'images/shared/trough_small.png',
'update speed': 60,
'vertical padding': 2}),
('TemperatureMeter',
{'file': '/proc/acpi/thermal_zone/THRM/temperature',
'horizontal padding': 8,
'icon': 'images/icons/temperature.png',
'krell': 'images/shared/krell_red.png',
'max_temp': 100.0,
'meter font name': 'VeraBd',
'meter font size': 8,
'trough': 'images/shared/trough.png',
'update_speed': 30,
'vertical padding': 8})],
'text colour': (0, 0, 0, 200),
'update speed': 1}
Hors ligne
geronimoO
Re : [HOW TO] adesklets : configuration des desklets
Salut, juste pour info, les desklets sont programmés en python, pas en C. Je te post mon config.txt si ça peut t'aider :
merki;)
je test ça et vous tiens au courant
PS: bon je sais pas s'il y a du mieux mais voila le message d'erreur:
./config.txt: line 2: syntax error near unexpected token `('
./config.txt: line 2: `id0 = {'background colour': (210, 210, 210, 130),'
Dernière modification par geronimoO (Le 07/12/2005, à 16:38)
" Un bon indien est un indien mort "
Général Sheridan, cavalerie des Etats Unis.
Hors ligne
Aldones
Re : [HOW TO] adesklets : configuration des desklets
Hello !
id0 = {'background colour': (210, 210, 210, 130),
'background images': ['images/shared/bg_top.png',
'images/shared/bg_middle.png',
'images/shared/bg_bottom.png'],
'meters': [('CPUMeter',
{'horizontal padding': 8,
'icon': 'images/icons/cpu.png',
'krell': 'images/shared/krell.png',
'meter font name': 'VeraBd',
'meter font size': 8,
'trough': 'images/shared/trough.png',
'vertical padding': 8}),
('MemoryMeter',
{'horizontal padding': 8,
'icon': 'images/icons/memory.png',
'krell': 'images/shared/krell.png',
'meter font name': 'VeraBd',
'meter font size': 8,
'trough': 'images/shared/trough.png',
'update speed': 10,
'vertical padding': 8}),
('SwapMeter',
{'horizontal padding': 8,
'icon': 'images/icons/swap.png',
'krell': 'images/shared/krell_blue.png',
'meter font name': 'VeraBd',
'meter font size': 8,
'trough': 'images/shared/trough.png',
'update speed': 30,
'vertical padding': 8}),
('NetworkMeter',
{'horizontal padding': 8,
'icon': 'images/icons/network.png',
'interface name': 'eth0',
'krell': ['images/shared/krell_green_small.png',
'images/shared/krell_red_small.png'],
'max down speed': 400,
'max up speed': 80,
'meter font name': 'Vera',
'meter font size': 7,
'trough': 'images/shared/trough_small.png',
'update speed': 2,
'vertical padding': 4}),
('DiskIOMeter',
{'disk name': 'hda',
'horizontal padding': 8,
'icon': 'images/icons/disk.png',
'krell': ['images/shared/krell_green_small.png',
'images/shared/krell_red_small.png'],
'max read speed': 10240,
'max write speed': 10240,
'meter font name': 'Vera',
'meter font size': 7,
'trough': 'images/shared/trough_small.png',
'update speed': 2,
'vertical padding': 4}),
('DiskSpaceMeter',
{'horizontal padding': 8,
'icon': 'images/icons/diskfree.png',
'krell': 'images/shared/krell_blue_small.png',
'meter font name': 'Vera',
'meter font size': 6,
'trough': 'images/shared/trough_small.png',
'update speed': 60,
'vertical padding': 2})],
'text colour': (0, 0, 0, 200),
'update speed': 1}
id20 = {'background colour': (210, 210, 210, 130),
'background images': ['images/shared/bg_top.png',
'images/shared/bg_middle.png',
'images/shared/bg_bottom.png'],
'meters': [('CPUMeter',
{'horizontal padding': 8,
'icon': 'images/icons/cpu.png',
'krell': 'images/shared/krell.png',
'meter font name': 'VeraBd',
'meter font size': 8,
'trough': 'images/shared/trough.png',
'vertical padding': 8}),
('MemoryMeter',
{'horizontal padding': 8,
'icon': 'images/icons/memory.png',
'krell': 'images/shared/krell.png',
'meter font name': 'VeraBd',
'meter font size': 8,
'trough': 'images/shared/trough.png',
'update speed': 10,
'vertical padding': 8}),
('SwapMeter',
{'horizontal padding': 8,
'icon': 'images/icons/swap.png',
'krell': 'images/shared/krell_blue.png',
'meter font name': 'VeraBd',
'meter font size': 8,
'trough': 'images/shared/trough.png',
'update speed': 30,
'vertical padding': 8}),
('NetworkMeter',
{'horizontal padding': 8,
'icon': 'images/icons/network.png',
'interface name': 'eth0',
'krell': ['images/shared/krell_green_small.png',
'images/shared/krell_red_small.png'],
'max down speed': 400,
'max up speed': 80,
'meter font name': 'Vera',
'meter font size': 7,
'trough': 'images/shared/trough_small.png',
'update speed': 2,
'vertical padding': 4}),
('DiskIOMeter',
{'disk name': 'hda',
'horizontal padding': 8,
'icon': 'images/icons/disk.png',
'krell': ['images/shared/krell_green_small.png',
'images/shared/krell_red_small.png'],
'max read speed': 10240,
'max write speed': 10240,
'meter font name': 'Vera',
'meter font size': 7,
'trough': 'images/shared/trough_small.png',
'update speed': 2,
'vertical padding': 4})],
'text colour': (0, 0, 0, 200),
'update speed': 1}
id21 = {'background colour': (210, 210, 210, 130),
'background images': ['images/shared/bg_top.png',
'images/shared/bg_middle.png',
'images/shared/bg_bottom.png'],
'meters': [('DiskSpaceMeter',
{'horizontal padding': 8,
'icon': 'images/icons/diskfree.png',
'krell': 'images/shared/krell_blue_small.png',
'meter font name': 'Vera',
'meter font size': 6,
'trough': 'images/shared/trough_small.png',
'update speed': 60,
'vertical padding': 2})],
'text colour': (0, 0, 0, 200),
'update speed': 1}
A copier/coller dans ton config.txt de sysmonitor, il fonctionne nickel
Hors ligne
da_last_dodo
Re : [HOW TO] adesklets : configuration des desklets
Bonjour,
Est ce que quelqu'un sait comment faire pour que le fond (de SystemMonitor biensûr !) soit transparent ?
J'ai enlevé la ligne background color.... et ça n'a rien donné.
Merci d'avance
Netbook Acer 1410 - Dual Ubuntu 10.04 / Windows 7
Hors ligne
Doppler
Re : [HOW TO] adesklets : configuration des desklets
Salut Dodo, de ce que je comprend il n'y a pas de ligne pour paramétrer le pourcentage de transparence comme avec Yab. SystemMonitor appelle bg_bottom.png , bg_middle.png et bg_top.png qui sont les images de fond.
Le seul moyen qui me vient c'est d'ouvrir ces fichiers dans Gimp, et de là faire un fond totalement transparent puis de sauver.
ça devrait faire l'affaire mais c'est pas pratique.
Edition: essaie de coller un None à la place des valeurs dans :
'background images': ['images/shared/bg_top.png',
'images/shared/bg_middle.png',
'images/shared/bg_bottom.png'],
J'ai pas system alors je suis pas sur du comment ^^
Dernière modification par Doppler (Le 07/12/2005, à 19:34)
Hors ligne
da_last_dodo
Re : [HOW TO] adesklets : configuration des desklets
Merci pour ta réponse Doppler. SystemMonitor n'aime pas trop ta suggestion "None"
[shez@ubuntu:~/Apps/SystemMonitor-0.1.3]$ python SystemMonitor.py
Traceback (most recent call last):
File "SystemMonitor.py", line 1107, in ?
EventHandler(dirname(__file__)).pause()
File "SystemMonitor.py", line 974, in __init__
adesklets.Events_handler.__init__(self)
File "/usr/lib/python2.4/site-packages/adesklets/events_handler.py", line 157, in __init__
self.ready()
File "SystemMonitor.py", line 1019, in ready
self.run_display()
File "SystemMonitor.py", line 1049, in run_display
bg_top = adesklets.load_image(join(self.basedir,self.config["background images"][0]))
File "/usr/lib/python2.4/site-packages/adesklets/commands.py", line 646, in load_image
return comm.out()
File "/usr/lib/python2.4/site-packages/adesklets/commands_handler.py", line 103, in out
raise ADESKLETSError(4,message)
adesklets.error_handler.ADESKLETSError: adesklets command error - could not load image './None' - file does not exist
Sinon, pour transformer les images que tu as cité en images transparent avec Gimp, on fait comment (je ne suis pas un pro du Gimp ) ?
Dernière modification par da_last_dodo (Le 07/12/2005, à 19:44)
Netbook Acer 1410 - Dual Ubuntu 10.04 / Windows 7
Hors ligne
Doppler
Re : [HOW TO] adesklets : configuration des desklets
Ici je viens d'ouvrir l'un des trois png en question dans Gimp, j'ai fait un control A control X et hop enregistrer. ça a l'air d'aller...
Bon pour le coup c'est 100% transparent ^^
ps désolé pour les erreurs, c'était une idée comme ça...
Dernière modification par Doppler (Le 07/12/2005, à 19:48)
Hors ligne
da_last_dodo
Re : [HOW TO] adesklets : configuration des desklets
Merci pour l'astuce pour faire les transparents (plutot une image vide avec les mêmes dimensions, mais bon...).
Puis, j'ai mis le background color à 0, 0, 0, 0
Et maintenant, tout fonctionne ! Je vais enfin me passer de conky (qui est un p'tit peu moche à mon gout)
Encore une fois merci Doppler
ps : juste un dernier truc, ou est ce que je peut trouver les équivalence pour les couleurs en 4 chiffres (style 0, 0, 0, 0 correspont à transparent...) ?
Dernière modification par da_last_dodo (Le 07/12/2005, à 20:03)
Netbook Acer 1410 - Dual Ubuntu 10.04 / Windows 7
Hors ligne
Doppler
Re : [HOW TO] adesklets : configuration des desklets
Dirien chuis trop content de pouvoir aider pour une fois ^^
C'est vrai que faire apparaitre une image vierge c'est franchement inutile, autant rien faire apparaitre. Doit y avoir moyen... à trouver...
PS à ton PS: aucune idée, ça ressemble à un alpha=0 red=0 green=0 blue=0 (en %) mais à part ça... bon faut vraiment que j'installe system monitor ^^
Dernière modification par Doppler (Le 07/12/2005, à 20:16)
Hors ligne
Doppler
Re : [HOW TO] adesklets : configuration des desklets
Classe !
Viva Tux n' Tosh ^^
Hors ligne
belou
Re : [HOW TO] adesklets : configuration des desklets
da_last_dodo : ta montre avec date, c'est un desklets qui va avec adesklets ou gdesklets
ou est ce qu on peut le trouver ?
Hors ligne
da_last_dodo
Re : [HOW TO] adesklets : configuration des desklets
C'était un gdesklet (je me suis converti au adesklets maintenant ;-) )
Au niveau ressources, je trouve que gdesklets pompe énormement.
Voici mon nouveau bureau (j'ai qu'un 15" et on vite fait le tour avec le nombre de desklets)
Dernière modification par da_last_dodo (Le 08/12/2005, à 22:48)
Netbook Acer 1410 - Dual Ubuntu 10.04 / Windows 7
Hors ligne
geronimoO
Re : [HOW TO] adesklets : configuration des desklets
oller dans ton config.txt de sysmonitor, il fonctionne nickel
merci je test de suite!
PS: merci ça fonctionne merci a toi Aldones!
Dernière modification par geronimoO (Le 09/12/2005, à 12:34)
" Un bon indien est un indien mort "
Général Sheridan, cavalerie des Etats Unis.
Hors ligne
geronimoO
Re : [HOW TO] adesklets : configuration des desklets
bon j'ai un pb assez particulier, voir étrange
j'ai pris le config.txt de Aldones, le desklets se lance.
Maintenant je voudrais modifier certaines choses comme la connection au web qui chez moi se fait par eth0 et non ppp0.
J'edit le fichier, le modifie (en root ) et l'enregistre. Si je retourne dans ce fichier mes modifs ont jusqu'à la bien été prise en compte.
Maintenant je lance le desklet, mon interface web est inactive. Je ferme mon desklet, retourne sous le fichier config.txt, il s'est remis comme auparavant!
J'ai tenté en le modifiant et fermant la session, en enlevant les droits utilisateurs dessus, rien n'y fait!
help
" Un bon indien est un indien mort "
Général Sheridan, cavalerie des Etats Unis.
Hors ligne
seb2py
Re : [HOW TO] adesklets : configuration des desklets
C'est vrai que faire apparaitre une image vierge c'est franchement inutile, autant rien faire apparaitre. Doit y avoir moyen... à trouver...
Chez moi, j'ai simplement modifié la ligne comme suit :
id1 = {'background_image': '',
et j'ai un fond transparent !!!
Sous Ubuntu Precise / Unity
Hors ligne
Bismut
Re : [HOW TO] adesklets : configuration des desklets
J'ai un problème peut-être similaire... J'essaie de faire fonctionner Yab et System Monitor...
Après moultes bidouillages, j'arrive enfin à faire afficher les 2 desklets au lancement de adesklets. Malheureusement, certaines modifications des fichiers de config. n'ont aucun effet.
Par exemple, les 2 desklets se lancent en haut à gauche, l'un sur l'autre... Je les déplace, ok... mais si je ferme et je relance, paf, ils sont de nouveau en haut à gauche...
J'ai trouvé un fichier .adesklets dans mon répertoire perso. qui indique apparemment l'ensemble de mes desklets et leur position : Je spécifie bien à Yab par exemple d'être à 600 - 600 mais s'ouvre quand même en haut à gauche...
Bref, rien ne semble y faire... une idée ?
PS : Un clic droit et Configure sur un Desklet ne fait absolument rien, c'est normal ?
Dernière modification par Bismut (Le 19/12/2005, à 22:04)
Mac Mini 2009 avec Archlinux
Asus EeePC S101 avec Archlinux
HTC Magic avec Android
Hors ligne
toma222
Re : [HOW TO] adesklets : configuration des desklets
Essaies de supprimer le fichier .adesklets et de réenregister tes desklets. Le configure par clic droit qui ne donne rien, c'est normal. De toute façon, si ça marchait, ça t'ouvrirais juste le fichier config.txt de ton desklet.
Hors ligne
belou
Re : [HOW TO] adesklets : configuration des desklets
coment qu'on fait pour que mon Modubar soit tjrs visible
marre de tjrs afficher bureau pour pouvoir lancer un appli
Hors ligne
|
Sounds simple enough
def create_cookie():
bag = string.ascii_uppercase + string.ascii_lowercase + string.digits
cookie = Cookie.SimpleCookie()
cookie['sessionid'] = ''.join(random.sample(bag,24))
cookie['sessionid']['expires'] = 600
return 'Set-Cookie: ', cookie.output().replace('Set-Cookie: ', '', 1)
cookie.output() is Set-Cookie: sessionid=YmsrvCMFapXk6wAt4EVKz2uU; expires=Sun, 14-Aug-2011 21:48:19 GMT
headers.append(('Content-type', 'text/html'))
headers.append(('Content-Length', str(output_len)))
headers.append(create_cookie)
This is my response ('200 OK', [('Content-type', 'text/html'), ('Content-Length', '1204'), ('Set-Cookie', 'sessionid=YmsrvCMFapXk6wAt4EVKz2uU; expires=Sun, 14-Aug-2011 21:48:19 GMT')], 'html stuff')
This is what I get from envirion: HTTP_COOKIE: sessionid=YmsrvCMFapXk6wAt4EVKz2uU
And when I click another link on my page, no more HTTP_COOKIE Using the chrome dev console I can see the request cookie and the page header contains: Cookie:: sessionid=YmsrvCMFapXk6wAt4EVKz2uU
Now, this bothers me a bit. First of all why does it have double :: ? I tried using 'Set-Cookie' instead of 'Set-Cookie: ' in the create_cookie function. Doing that I didn't get any HTTP_COOKIE at all from environ.
So after lots of searching in the web and everyone just talking middleware (don't suggest I use one please - I'm doing this to learn the wsgi) ... I've come up empty.
|
After a few weeks of fruitful and not so fruitful work sessions, I am slowly approaching the benchmark for a 0.1 release of z3c.formjs. So what will be provided in the 0.1 release?
Easy to use JavaScript button widget built right into z3c.form
Easy JavaScript event handler attachment to form widgets
A demo of the above two features.
Currently the JavaScript buttons work and the generic JavaScript event handlers for any widget are almost ready – it can be done, it’s just not easy. I also now have a demo of button usage. In fact, here is a code snippet from that demo:
import zope.interface
from z3c.form import form, button
from z3c.formui import layout
from z3c.formjs import jsbutton
class IButtons(zope.interface.Interface):
show = jsbutton.JSButton(title=u'Show Code')
hide = jsbutton.JSButton(title=u'Hide Code')
class ButtonForm(layout.FormLayoutSupport, form.EditForm):
buttons = button.Buttons(IButtons)
@jsbutton.handler(IButtons['show'])
def handleShow(self, id):
return '$("#code").slideDown()'
@jsbutton.handler(IButtons['hide'])
def handleHide(self, id):
return '$("#code").slideUp()'
As you can see, creating JavaScript buttons is as simple as creating regular buttons. Under the hood there is some rather complicated code that makes heavy use of Zope’s component architecture to allow for maximum customization and (drum roll) js library agnosticism. That’s right – you will be able to customize z3c.formjs to work with any JavaScript library you want. By default though, JavaScript renderers for jQuery are provided.
What about future releases?
I’m looking at some pretty nifty possible features for doing common – yet tedious JavaScript tasks. Here is a scenario I plan to make simple to do. Let’s say you have an address form which includes fields for city and state. If the user enters in San Francisco for the city and New York for the state, that shouldn’t validate. The trick is connecting the city and state fields so that a modification to the state updates the validation of the city. In a form this might look like:
@jsevent.handler(fields['state'], event=jsevent.CHANGED)
def handleStateChange(self, id):
return jsevent.updateWidgetFor(self.fields['city']).render()
So this would generate JavaScript code (using whatever js framework renderers have been written for) such that when the state field iss changed there would be an HTTP Post sent to the server with the data for the state. The post will probably be sent to a url like context/@@form.html/widgets/city/get?state=WA. Then the city widget would be replaced with the HTTP Post returns – presumably a widget with a modified js validator.
But these are just thoughts at this point and the API is very likely to change as problems and their solutions are discovered.
|
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 making a 2D board game for python for hw.
I asked user to input a integer for the board size. for example, 7. I have modified a bit (only show the important ones) before posting. the function is like follows
def asksize():
while True:
ask=raw_input("Input board size: ")
try:
size=int(ask)
return size
except ValueError:
print "Please enter a integer"
Because it is variable board size, I need reuse the variable size in other function, use it for checking user's move is valid or not, how can I reuse the variable?
def checkmove(move):
#move is sth like eg. A1:B2
move=move.split(":") #I split it so it becomes ['A','1']['B','2']
if size>=int(move[0][1]) and int(move[0][1])>=1 and size>=int(move[1][1]) and int(move[1][1])>=1: #for example if board size is 7, this is to check whether user input is between 1 to 7 within the board
return True
else:
return False
In my checkmove function, I can't use size in my argument because it is not defined, how can I make it workable?
Thanks
|
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
|
redcat
Introduction
Since about four years ago Debian has distributed patches to its indexes of packages available for download -- so that rather than having to download the full lists (currently about 30MB uncompressed or 6MB compressed) every time you want to get a package that's only just become available, you can just get the changes to the list (which after compression is only about 10kB every six hours).
See the link above for background, but the basic summary is that every time the archive is updated, a compressed "ed-style" diff is generated that lists each line that was changed in the original Packages or Sources index -- since those are text files, with stanzas sorted by package name, that works out very well. An additional index of the ed-style diffs is also constructed so apt can determine what it needs to download and apply to update its old indexes, and that's pretty much it.
Unfortunately, this turns out to be a bit slow for many people -- as attested to by apt bugs #383881 and #372712, probably among others. The problem is two fold: first, editing a 30MB file isn't always trivial -- you need to read 30MB off the disk, write 30MB to the disk, and if you want to avoid doing that multiple times, you need enough memory to cache 60MB (mmaps of both the original file and the modified file); and if you've got multiple entries in your sources.list, you need to multiply that out for each of them. That might not be a major problem if you're on a modern system; but it often becomes a problem when multiple pdiffs are required to bring your Packages file up to date. In this case, apt simply applies each pdiff in turn (pausing to download and decompress the next pdiff in turn).
It's possible, at least in theory, to do substantially better than this: downloading all the pdiff files necessary, manipulating them as necessary, and then applying them in a single pass over the original index should reduce the delays substantially. Unfortunately this isn't so easy in practice, as the manipulation necessary to apply a series of diffs in one pass isn't at all obvious.
This program aims to remedy that, providing a straightforward implementation of the necessary manipulations. It takes as input an ordered series of ed diffs, combines them internally, then either (a) outputs a single ed diff that has the same result as applying them all in sequence, or (b) applies the patches against stdin.
It's python based, so here's the boilerplate:
#!/usr/bin/env python
# Copyright (c) 2009 Anthony Towns
#
# 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.
Dealing with diffs
We're going to start with an basic class representing a set of modifications that apply to a text file. Only two sorts of modifications are permitted: inserting some lines, and deleting some lines. This matches what is handled by diff, and what is needed for this problem, though obviously it's nowhere near the only modifications that could potentially be made.
In order to manage the internal data structure a little more easily, we'll use the following "Struct" class which allows us to define classes with just a few fixed members and easily create and use them.
class Struct(object):
__slots__ = ()
def __init__(self, *args, **kwargs):
d = dict(zip(self.__slots__, args))
d.update(kwargs)
for x in self.__slots__:
setattr(self, x, d.get(x,None))
The data structure we use is important. It's essentially a single ordered array of changes in the form of an offset (how many lines after the end of the last change does this change begin), how many lines to delete (possibly zero), and what lines to add (possibly none).
class Change(Struct):
__slots__ = ("offset", "del_cnt", "add_cnt", "add_lines")
In addition, since changes will generally be nearby, we'll keep a cache of the current absolute position in the file -- that is, the current change we're looking at, and the line number where the previous change was finished. It would be fantastic if we could cache this for every modification, but that would mean we'd have to update every line number after any insertion/deletion we make, so it's better to just use offsets.
class LineNrCache(Struct)
__slots__ = ("change", "line")
class Modifications(object):
def __init__(self):
self.changes = [] # list of Change objects
self.line_nr_cache = LineNrCache(change=0, line=0)
The main operation on this data structure will be inserts, like so:
def insert(self, i, offset, del_cnt, add_lines):
self.changes.insert(i,
Change(offset, del_cnt, len(add_lines), add_lines) )
But before we can do anything useful with this, we need to be a bit cleverer as to how we manipulate it. The most important aspect is that we want to be able to easily make modifications at a particular line number -- so we'll create a function to prepare our data structure for precisely that. modfor() will take a line number, and return an index into the array that's calibrated so that deletions and insertions happen at the right line number, based on all the current offsets (and it will both start from linenr_cache and update it to be a little clever about what's going on).
Implementing the function is then a matter of incrementing/decrementing until either we discover we've never looked at a line number this high before, and have to extend our array, or we find a pre-existing modification that covers our line number and just have to deal with the three possible states we could have: we'd skipped past this line in the offset, this line is in the middle of text we'd added previously, or this is exactly where we started making a change previously.
def mod_for(self, line):
assert line >= 0
i = self.line_nr_cache.change
pos = self.line_nr_cache.line
changes = self.changes # abbreviation
assert (i == len(changes) == 0) or (0 <= i and i < len(changes))
while True:
assert 0 <= i and i <= len(changes)
if i == len(changes):
self.insert(i, line-pos, 0, [])
break
if pos + changes[i].offset + changes[i].add_cnt < line:
pos += changes[i].offset + change[i].add_cnt
i += 1
continue
elif line < pos:
assert i > 0
i -= 1
pos -= changes[i].offset + changes[i].add_cnt
continue
assert i == 0 or pos <= line
assert line <= pos + changes[i].offset + changes[i].add_cnt
if line < pos + changes[i].offset:
changes[i].offset -= (line-pos)
self.insert(i, line-pos, 0, [])
break
elif pos + changes[i].offset < line:
split = line - pos - changes[i].offset
self.insert(i+1, 0, 0, changes[i].add_lines[split:])
changes[i].add_cnt = split
changes[i].add_lines = changes[i].add_lines[:split]
i += 1
break
else:
assert line == pos + changes[i].offset
break
assert 0 <= i and i < len(changes)
self.line_nr_cache.change = i
self.line_nr_cache.line = line - changes[i].offset
return i
Of course, endlessly splitting up our data structure is going to get annoying, but there's a simple observation we can make: if a modification's offset is zero, we can easily merge it with the previous modification. So when we manipulate the array, whether by calling mod_for or more manually, we'll make sure to check for this condition, and tidy up after ourselves.
def merge_next(self, i):
assert i+1 < len(self.changes) and self.changes[i+1].offset == 0
c_i = self.line_nr_cache.change
c_p = self.line_nr_cache.line
if c_i == i+1:
c_i -= 1
c_p -= self.change[i].offset + self.change[i].add_cnt
self.line_nr_cache.change = c_i
self.line_nr_chace.line = c_p
self.changes.pop(i+1)
So with all that established, we can now insert lines!
def insert_lines(self, line, strs):
mod = self.mod_for(line)
self.changes[mod].add_cnt += len(strs)
self.changes[mod].add_lines = strs + self.add_lines[mod]
if mod > 0 and self.changes[mod].offset == 0:
self.merge_next(mod-1)
assert mod == len(self.changes) or self.changes[mod].offset > 0
assert mod-1 <= 0 or self.changes[mod-1].offset > 0
The other half of our job is, of course, to remove lines. This is a little bit more complicated, because we might find ourselves (a) removing original lines, (b) removing added lines, (c) overlapping previously removed lines, (d) crossing modification boundaries.
So we do this piecemeal. If our current block has added lines, these are the first to go. Having done that, if we want to remove more lines, we can, but only up to the offset to the next block. If we reduce that to zero, we need to merge the current block and the next block, at which point we can start again. (Of course, if there isn't a next block, we can remove as many lines as we like without worrying) Anyway, iterating through that eventually gets enough lines deleted, and we can just merge with the previous block if necessary, and declare ourselves successfully completed.
def remove_lines(self, line, cnt):
mod = self.mod_for(line)
changes = self.changes # abbreviation
while cnt > 0:
k = min(changes[mod].add_cnt, cnt)
changes[mod].add_lines = self.add_lines[mod][k:]
changes[mod].add_cnt -= k
cnt -= k
if mod+1 < len(changes):
k = min(changes[mod+1].offset, cnt)
changes[mod].del_cnt += k
changes[mod+1].offset -= k
cnt -= k
if changes[mod+1].offset == 0:
self.merge_next(mod)
else:
changes[mod].del_cnt += cnt
cnt = 0
if mod > 0 and changes[mod].offset == 0:
self.merge_next(mod-1)
assert mod-1 == 0 or changes[mod-1].offset > 0
Having gotten ourselves a list of modifications, applying them to a file is fairly easy: we copy some lines from input to output, skip some lines from the input, and then write the added lines to the output, and repeat.
def apply_against_file(self, file, out):
for change in self.changes):
for _ in xrange(change.offset):
out.write(file.readline())
for _ in xrange(change.del_cnt):
file.readline()
assert change.add_cnt == len(change.add_lines)
for line in change.add_lines:
out.write(line + "\n")
while True:
line = file.readline()
if line == "":
break
out.write(line)
Ed-style diffs
So far we've been pretty generic: we've defined a class with an insertlines function and a removelines function, but not any sort of file format that represents the lines to be inserted or removed. As per our motivation, we want to deal with ed-style diffs. First comes parsing, which we'll use a generator for. We'll only accept commands like "0a" (append after the 0th line), "1,2c" (change lines from 1 to 2 to the text that follows) and "1,2d" (delete lines from 1 to 2 inclusive). Note that with this syntax it's not possible to express "add a line containing a single dot (.)". You would generally use the "s/.//" command after appending a line containing two dots for that operation, however lines with a single dot aren't valid in the Packages or Sources files we're dealing with, so we simply won't address this issue.
def red_components(file):
cmdwanted = True
lines = []
for line in file:
line = line.rstrip("\n")
if cmdwanted:
if line == "":
continue
line, cmd = line[:-1], line[-1]
if "," in line:
vals = line.split(",", 1)
else:
vals = line, line
vals = [int(x) for x in vals]
offset = vals[0]-1
del_cnt = vals[1]-vals[0]+1
if cmd == "d":
yield (offset, del_cnt, [])
elif cmd == "c":
cmdwanted = False
elif cmd == "a":
offset += 1
del_cnt = 0
cmdwanted = False
else:
raise Exception("Could not parse ed command: \"%s%s\"" %
(line,cmd))
else:
if line == ".":
yield (offset, del_cnt, lines)
lines = []
cmdwanted = True
else:
lines.append(line)
if not cmdwanted:
raise Exception("ed input hit eof within text block")
return
With that little bit of parsing out of the way, we can extend our previous class to deal with Ed Diffs explicitly:
class EdModifications(Modifications):
def read_diff(self, file):
for offset, del_cnt, add_lines in red_components(file):
if del_cnt > 0:
self.remove_lines(offset, del_cnt)
if add_lines != []:
self.insert_lines(offset, add_lines)
return
In addition, we'd like to be able to output a cumulative diff. There are any number of valid ways to do this as far as ed is concerned, but the way diff does it, and the only way apt is willing to accept, is to have each the changes listed in reverse order -- from the ones affecting the end of the file, to the start. The advantage this offers is that the line numbers specified in the ed file match the line numbers in the original file, which is kinda nifty.
Either way makes very little difference to us though. We can work out the old line numbers by simply counting the offsets (which was the text in the original file that makes it through unchanged) and the deleted text (which was also in the original file), and not counting the added text (which obviously wasn't in the original file). Iterating that way to the last modification lets us work out the line numbers we need, and then it's just a matter of iterating back to the start, and outputting in ed format.
(Note again that we don't take care to avoid lines with single dots, relying on them simply not appearing in the first place)
def write_diff(self, out):
line = 0
for change in self.changes:
line += change.offset + change.del_cnt
for change in reversed(self.changes):
line -= change.del_cnt
if change.del_cnt <= 1:
lines = "%d" % (line+1)
else:
lines = "%d,%d" % (line+1, line+change.del_cnt)
if change.add_cnt == 0:
if change.del_cnt == 0:
continue
else:
out.write("%sd\n" % (lines))
else:
if change.del_cnt == 0:
out.write("%da\n" % (line)) # NB: not line+1
else:
out.write("%sc\n" % (lines))
for added_line in change.add_lines:
out.write("%s\n" % (added_line))
out.write(".\n")
line -= change.offset
main()
And that was our module. To demonstrate it we supply a simple main() function that accepts a series of ed diffs on the command line, and either outputs a cumulative diff, or acts as a filter on stdin applying all the patches in bulk.
def main():
import sys, gzip
if len(sys.argv) == 1 or (len(sys.argv) == 2 and sys.argv[1] == "-f"):
print "Usage: %s [-f] <diff>..."
print """
One of more diff files must be specified. Gzip compression is assumed if
.gz extension is used.
If -f is specified, patch will be applied to stdin, with result on stdout.
Otherwise, combined diff is produced on stdout."""
sys.exit(0)
if sys.argv[1] == "-f":
just_dump_ed = False
files = sys.argv[2:]
else:
just_dump_ed = True
files = sys.argv[1:]
diffs = EdModifications()
for filename in files:
if filename.endswith(".gz"):
file = gzip.GzipFile(filename, "r")
else:
file = open(filename, "r")
diffs.read_diff(file)
if just_dump_ed:
diffs.write_diff(sys.stdout)
else:
diffs.apply_against_file(sys.stdin, sys.stdout)
if __name__ == "__main__":
main()
|
I want to add a field to an existing mapped class, how would I update the sql table automatically. Does sqlalchemy provide a method to update the database with a new column, if a field is added to the class.
SQLAlchemy itself doesn't support automatic updates of schema, but there is a third party SQLAlchemy Migrate tool to automate migrations. Look though "Database schema versioning" chapter to see how it works.
Sometimes Migrate is too much work - you just want to column automatically added when you run your changed code. So here is a function that does that.
Caveats: it pokes around in the SQLAlchemy internals and tends to require small changes every time SQLAlchemy undergoes a major revision. (There's probably a much better way of doing this - I am not a SQLAlchemy expert). It also doesn't handle constraints.
import logging
import re
import sqlalchemy
from sqlalchemy import MetaData, Table, exceptions
import sqlalchemy.engine.ddl
_new_sa_ddl = sqlalchemy.__version__.startswith('0.7')
def create_and_upgrade(engine, metadata):
"""For each table in metadata, if it is not in the database then create it.
If it is in the database then add any missing columns and warn about any columns
whose spec has changed"""
db_metadata = MetaData()
db_metadata.bind = engine
for model_table in metadata.sorted_tables:
try:
db_table = Table(model_table.name, db_metadata, autoload=True)
except exceptions.NoSuchTableError:
logging.info('Creating table %s' % model_table.name)
model_table.create(bind=engine)
else:
if _new_sa_ddl:
ddl_c = engine.dialect.ddl_compiler(engine.dialect, None)
else:
# 0.6
ddl_c = engine.dialect.ddl_compiler(engine.dialect, db_table)
# else:
# 0.5
# ddl_c = engine.dialect.schemagenerator(engine.dialect, engine.contextual_connect())
logging.debug('Table %s already exists. Checking for missing columns' % model_table.name)
model_columns = _column_names(model_table)
db_columns = _column_names(db_table)
to_create = model_columns - db_columns
to_remove = db_columns - model_columns
to_check = db_columns.intersection(model_columns)
for c in to_create:
model_column = getattr(model_table.c, c)
logging.info('Adding column %s.%s' % (model_table.name, model_column.name))
assert not model_column.constraints, \
'Arrrgh! I cannot automatically add columns with constraints to the database'\
'Please consider fixing me if you care!'
model_col_spec = ddl_c.get_column_specification(model_column)
sql = 'ALTER TABLE %s ADD %s' % (model_table.name, model_col_spec)
engine.execute(sql)
# It's difficult to reliably determine if the model has changed
# a column definition. E.g. the default precision of columns
# is None, which means the database decides. Therefore when I look at the model
# it may give the SQL for the column as INTEGER but when I look at the database
# I have a definite precision, therefore the returned type is INTEGER(11)
for c in to_check:
model_column = model_table.c[c]
db_column = db_table.c[c]
x = model_column == db_column
logging.debug('Checking column %s.%s' % (model_table.name, model_column.name))
model_col_spec = ddl_c.get_column_specification(model_column)
db_col_spec = ddl_c.get_column_specification(db_column)
model_col_spec = re.sub('[(][\d ,]+[)]', '', model_col_spec)
db_col_spec = re.sub('[(][\d ,]+[)]', '', db_col_spec)
db_col_spec = db_col_spec.replace('DECIMAL', 'NUMERIC')
db_col_spec = db_col_spec.replace('TINYINT', 'BOOL')
if model_col_spec != db_col_spec:
logging.warning('Column %s.%s has specification %r in the model but %r in the database' %
(model_table.name, model_column.name, model_col_spec, db_col_spec))
if model_column.constraints or db_column.constraints:
# TODO, check constraints
logging.debug('Column constraints not checked. I am too dumb')
for c in to_remove:
model_column = getattr(db_table.c, c)
logging.warning('Column %s.%s in the database is not in the model' % (model_table.name, model_column.name))
def _column_names(table):
# Autoloaded columns return unicode column names - make sure we treat all are equal
return set((unicode(i.name) for i in table.c))
# database.py has definition for engine.
# from sqlalchemy import create_engine
# engine = create_engine('mysql://......', convert_unicode=True)
from database import engine
from sqlalchemy import DDL
add_column = DDL('ALTER TABLE USERS ADD COLUMN city VARCHAR(60) AFTER email')
engine.execute(add_column)
|
How to write a setup.py file so that a binary egg distribution (bdist_egg) inludes a sample configuration file and upon installation puts it into the {prefix}/etc directory?
A sample project source directory looks somewhat like this:
bin/ myappetc/ myapp.cfgmyapp/ __init__.py [...]setup.py
The setup.py looks somewhat like this:
from distutils.command.install_data import install_data
packages = ['myapp', ]
scripts = ['bin/myapp',]
cmdclasses = {'install_data': install_data}
data_files = [('etc', ['etc/myapp.cfg'])]
setup_args = {
'name': 'MyApp',
'version': '0.1',
'packages': packages,
'cmdclass': cmdclasses,
'data_files': data_files,
'scripts': scripts,
# 'include_package_data': True,
'test_suite': 'nose.collector'
}
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(**setup_args)
setuptools are installed in both the build environment and in the installation environment. The 'include_package_data' commented out or not does not help. Thanks.
|
#1001 Le 25/04/2010, à 17:05
oGu
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Bonjour à tous !
Tout d'abord félicitations pour l'excellente tenue de ce forum et pour tous les scripts que j'ai piqué sur ce topic!!
Etant passé de Firefox à IceCat dernièrement, j'aimerais qu'un Ubuntero sachant scripter adapte ce fichier (qui défragmente les données sqlite de Firefox) à mon nouveau browser :
#!/usr/bin/env python
# coding=utf8
from os import getenv,getuid,kill,waitpid
from subprocess import call,Popen,PIPE
from os.path import abspath,join,exists
from signal import SIGTERM
def recup_rep_profiles():
base_profile=join(getenv('HOME'),".mozilla","firefox")
profiles_ini=join(base_profile,"profiles.ini")
rep_profiles=[]
lignes=open(profiles_ini).read().splitlines()
for ligne in lignes:
ligne=ligne.strip()
if ligne.startswith("Path="):
rep_profiles.append(join(base_profile,ligne[5:]))
return rep_profiles
def patch_sessionstore(sessionstore):
if not exists(sessionstore): return
chaine=open(sessionstore,"rb").read()
chaine=chaine.replace('session:{state:"running"}})','session:{state:"stopped"}})')
open(sessionstore,"wb").write(chaine)
def recup_firefox_pids():
lignes=Popen(['pgrep','-x','firefox','-U',str(getuid())],stdout=PIPE).communicate()[0]
firefox_pids=[]
for ligne in lignes.splitlines():
ligne=ligne.strip()
if not ligne: continue
firefox_pids.append(int(ligne))
return firefox_pids
def kill_firefox(firefox_pids):
for pid in firefox_pids: kill(pid,SIGTERM)
# Récupère les chemins vers les profiles
profiles=recup_rep_profiles()
# Récupère les PID des processus Firefox en cours d’exécution
pids=recup_firefox_pids()
# Demande confirmation si Firefox est en cours d’exécution
if pids:
retour=call(['zenity','--question','--title=Attention','--text=Firefox est encours d’exécution\nSi vous cliquez sur Valider, Firefox sera fermé le temps d’effectuer l’optimisation et relancé après'])
if retour==1: exit(1)
# Arrête Firefox
kill_firefox(pids)
# Patche les fichiers sessionstore.js
for profile in profiles:
patch_sessionstore(join(profile,"sessionstore.js"))
# Compacte les bases de données
progress=Popen(["zenity","--title","Optimisation","--text","Optimisation en cours...","--progress","--pulsate","--auto-close"],stdin=PIPE)
for profile in profiles:
Popen(['find',profile,'-name','*.sqlite','-print','-exec','sqlite3','{}','VACUUM',';'],stdout=progress.stdin)
progress.stdin.close()
# Relance Firefox s’il était lancé
if pids:
Popen(['firefox'],stderr=open("/dev/null"),stdout=open("/dev/null"))
Est-ce techniquement possible? Si oui merci d'avance à celui/ceux qui se pencheront sur la transformation de ce code!
Bye!
Ogu
Dernière modification par oGu (Le 25/04/2010, à 17:06)
Ubunteros de tous les pays, unissez-vous !
Hors ligne
#1002 Le 27/04/2010, à 13:02
bugs néo
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
ce script permet de rendre plus rapide Firefox?
jeu de course open source earth-race (le jeu est en réécriture complète depuis janvier, afin de pouvoir aller plus vite par la suite)
Hors ligne
#1003 Le 27/04/2010, à 14:12
oGu
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Bonjour!
Oui, c'est ce qu'il est censé faire : en défragmentant les bases de données (awesome bar etc...) il rend leur accès plus rapide.
Après j'ignore si l'effet est réel, ou si c'est un placebo...
Quelques liens :
-ici la page avec le script originel (tiens, je me rends compte que l'accentuation pose problème avec le script que j'ai posté, ce qui n'est pas le cas sur le script initial)
http://zigazou.wordpress.com/2009/05/21/optimisation-et-gain-despace-sous-firefox-3/
-pour les fans de la ligne de commande, la procédure à suivre :
http://www.webdevonlinux.fr/2009/04/optimiser-le-demarrage-de-firefox/
Dernière modification par oGu (Le 27/04/2010, à 14:17)
Ubunteros de tous les pays, unissez-vous !
Hors ligne
#1004 Le 29/04/2010, à 12:46
2F
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
bonjour,
un script utile (de débutant mais qui focntionne) pour éviter de se déplacer quand on fait de la maintenance.
il permet d'avoir pas mal d'infos sur une machine win et après permet quasiement tout si vous faites vos scripts en bat, reg ou vbs pour les lancer sur la machine distante.
il faut :
-winexe
-zenity
-un dossier en lecture seule au moins, accessible depuis le réseau (à renseigner dans gdiag.conf)
-la suite pstools à insérer dans ce même dossier
ce script peut être très évolutif et très utile, j'utilise moi, une version non graphique avec nos scripts perso du boulot qu'on lance directement par le menu.
donc j'ai voulu le rendre général. vos remarques, conseils sont les bienvenu.
gdiag.sh
#! /bin/bash
# Effectue des diagnostiques et rapporte des informations sur des pc win
# Licence : GPL
# Dépendance : winexe, zenity, la suite pstools sur un serveur, rdesktop, samba
# Il faut un accès en lecture seule au moins sur un serveur acessible depuis l'exterieur (a renseigner dans gdiag.conf)
#à finir
#finir lancement script personnaliser (script) : vérifier la présence du fichier sur le serveur
#possibilité de tuer un processus avec tskill PID
. ./gdiag.conf
pingo="Ping"
nmap="Nmap"
proc="Processus en cours"
heure="Resynchroniser date & heure"
service="Services (processus) : start, stop, restart"
script="Lancer un script .vbs .reg ou .bat"
psinfo="Infos PC (programmes installés, SP, ram, HDD, etc..)"
mstsc="Ouvrir port RDP, rdesktop & fermer RDP"
msconfig="Afficher msconfig démarrage"
browse="Parcourir le disque C:/"
logs="Afficher les erreurs du journal d'évènements des 24H"
diag="Diag complet"
reboot="Rebooter la machine"
console="Accéder à la console DOS distante"
autre="Passer sur une autre machine"
quit="Quitter"
machine () {
target=$(zenity --entry --title="Gdiag" --text="Nom de machine ou IP");
if ping -c 1 -w 3 $target
then
mdp=$(zenity --entry --hide-text --title="Gdiag" --text="Mot de passe administrateur");
menu
else
echo "$target ne ping pas !!" | zenity --text-info --title="$target NE PING PAS !" --width 500 --height 200 && machine
fi
}
machine
menu () {
rm -Rf res.txt && killall winexe
action=`zenity --list --title "$titre" --width 500 --height 550 --radiolist --column=Choix --column "Action" TRUE "$pingo" FALSE "$nmap" FALSE "$proc" FALSE "$heure" FALSE "$service" FALSE "$script" FALSE "$psinfo" FALSE "$mstsc" FALSE "$msconfig" FALSE "$browse" FALSE "$logs" FALSE "$reboot" FALSE "$console" FALSE "$autre" FALSE "$diag" FALSE "$quit"`
}
while [ "$choix" != "quit" ]; do
menu
case "$action" in
"$pingo")
ping $target | zenity --text-info --width 700 --height 500 --title="$pingo de $target"
;;
"$nmap")
nmap $target | zenity --text-info --width 700 --height 500 --title="$nmap de $target"
;;
"$proc")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k qprocess * /system & exit" | zenity --text-info --width 600 --height 800 --title="$proc"
;;
"$heure")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k w32tm /resync /rediscover & exit" | zenity --progress --pulsate --auto-close && echo "Allume un cierge mais $target devrait être à l'heure maintenant" | zenity --text-info --title="$heure de $target" --width 400 --height 200
;;
#stopper, relancer ou lancer un service : mettre le nom du service sans l'extension
"$service")
serv=$(zenity --entry --title="Gdiag" --text="Nom du service");
action=`zenity --list --title "Services" --width 500 --height 550 --radiolist --column=choix --column "Action" TRUE "lancer" FALSE "stopper" FALSE "relancer" FALSE "$quit"`
case "$action" in
"lancer")
acte=start
;;
"stopper")
acte=stop
;;
"relancer")
acte=restart
;;
"quit")
menu
;;
esac
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k \\\\"$serveur"\psservice.exe /accepteula $acte $serv & exit" | zenity --progress --pulsate --auto-close && echo "le service $serv est $acte sur $target" | zenity --text-info --width 400 --height 200 --title="$relancetb2 sur $target"
;;
# pour lancer un programme bat vbs ou reg depuis le dossier du serveur : mettre le nom exacte du fichier avec extension
"$script")
#choix du fichier script
file=$(zenity --entry --title="Gdiag" --text="Nom du script dans le dossier $serveur avec son extension :");
#vérifie l'extension du fichier
ext=`echo $file | grep -o '\.[^.]*$'`
case $ext in
".bat")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k start \\\\"$serveur"\\"$file" & exit" | zenity --progress --pulsate --auto-close && echo "$file lancé sur $target" | zenity --text-info --title="Lancement de $file sur $target" --width 400 --height 200
;;
".BAT")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k start \\\\"$serveur"\\"$file" & exit" | zenity --progress --pulsate --auto-close && echo "$file lancé sur $target" | zenity --text-info --title="Lancement de $file sur $target" --width 400 --height 200
;;
".vbs")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k cscript \\\\"$serveur"\"$file" & exit"" | zenity --progress --pulsate --auto-close && echo "$file lancé sur $target" | zenity --text-info --title="Lancement de $file sur $target" --width 400 --height 200
;;
".VBS")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k cscript \\\\"$serveur"\"$file" & exit"" | zenity --progress --pulsate --auto-close && echo "$file lancé sur $target" | zenity --text-info --title="Lancement de $file sur $target" --width 400 --height 200
;;
".reg")
winexe -U "$target"/administrateur%$mdp //"$target" "regedit /S \\\\"$serveur"\"$file" & exit"" | zenity --progress --pulsate --auto-close && echo "$file lancé sur $target" | zenity --text-info --title="Lancement de $file sur $target" --width 400 --height 200
;;
".REG")
winexe -U "$target"/administrateur%$mdp //"$target" "regedit /S \\\\"$serveur"\"$file" & exit"" | zenity --progress --pulsate --auto-close && echo "$file lancé sur $target" | zenity --text-info --title="Lancement de $file sur $target" --width 400 --height 200
;;
*)
zenity --warning --text="extension non supportée"
;;
esac
;;
#liste les infos pc
"$psinfo")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k \\\\"$serveur"\psinfo.exe -d -s /accepteula & exit" | zenity --text-info --title="$psinfo de $target" --width 700 --height 300
;;
#ouvre le port RDP, lance rdesktop et ferme le port RDP
"$mstsc")
winexe -U "$target"/administrateur%$mdp //"$target" "regedit /S \\\\"$serveur"\mstscon.reg"
notify-send -i /usr/share/icons/gnome/scalable/apps/gnome-terminal.svg Hop "Ouverture du Terminal serveur client sur "$target"" && sleep 5 && rdesktop "$target" && winexe -U "$target"/administrateur%$mdp //"$target" "regedit /S \\\\"$serveur"\mstscoff.reg" && notify-send -i /usr/share/icons/gnome/scalable/apps/gnome-terminal.svg Hop "Fermeture du Terminal serveur client sur "$target""
;;
#msconfig
"$msconfig")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k reg query HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run & exit" > res.txt 2>&1 | zenity --progress --pulsate --auto-close
cat res.txt |grep REG_SZ | zenity --text-info --title="$msconfig de $target" --width 700 --height 300
;;
"$browse")
`nautilus smb://administrateur@"$target"/c$`
;;
#affiche les erreurs du journal d'évènements des 24H
"$logs")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k \\\\"$serveur"\psloglist.exe -d 1 -f e /accepteula & exit" >res.txt | zenity --progress --pulsate --auto-close && cat res.txt|grep -e ] -e Time| zenity --text-info --title="$autorun de $target" --width 400 --height 200
;;
#ping, nmap, liste processus, infos pc, msconfig et erreurs journal évènement des 24H
"$diag")
rm -f resultat.txt
ping3=`ping -c 3 "$target"`
echo -n "#### \\033[1;31mPING\\033[0m ####"
echo -n "#### PING ####" > resultat.txt
echo " " >> resultat.txt
echo " " >> resultat.txt
echo -n "$ping3" >> resultat.txt
echo " " >> resultat.txt
echo " " >> resultat.txt
echo -n "#### \\033[1;31mNMAP\\033[0m ####" &&
echo " " >> resultat.txt
echo "#### NMAP ####" >> resultat.txt
echo " " >> resultat.txt
gnome-terminal -x nmap "$target" -o nmap.txt && sleep 4 && cat nmap.txt |grep -v Nmap | grep -v Interesting >> resultat.txt
echo -n "#### \\033[1;31mINFOS PC\\033[0m ####"
echo -n "#### INFOS PC ####" >> resultat.txt
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k \\\\"$serveur"\psinfo.exe -d -s /accepteula & exit" >> resultat.txt
echo " " >> resultat.txt
echo -n "#### \\033[1;31mPROCESSUS\\033[0m ####"
echo -n "#### PROCESSUS ####" >> resultat.txt
echo " " >> resultat.txt
echo " " >> resultat.txt
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k qprocess * /system & exit" >> resultat.txt
echo -n "#### \\033[1;31mMSCONFIG\\033[0m ####"
echo " " >> resultat.txt
echo -n "#### MSCONFIG ####" >> resultat.txt
echo " " >> resultat.txt
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k reg query HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run & exit" > res.txt && cat res.txt |grep REG_SZ >> resultat.txt
echo " "
echo "rapport terminé" && clear && cat resultat.txt | zenity --text-info --title="$diag de $target" --width 800 --height 600
;;
#reboot
"$reboot")
net rpc shutdown -r -C "Votre ordianteur va redémarrer" -f -I "$target" -U administrateur%$mdp | zenity --text-info --title="reboot de $target en cours..." --width 400 --height 400
;;
#ok, tapez exit pour terminer le processus correctement
"$console")
gnome-terminal -x winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k qprocess * /system" &
;;
"$autre")
machine
;;
"$quit")
break;;
*)
esac
done
exit 0
le fichier de conf pauvre mais utile pour que ca serve à tout le monde
gdiag.conf
#mettre de la forme serveur="ip-serveur\mon dossier\scripts"
serveur=
et 2 tout petit .reg (a mettre aussi dans le dossier) qui servent dans le script... à vous de faire les votre après :
mstscon.reg
Windows Registry Editor Version 5.00[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server]"fDenyTSConnections"=dword:00000000
mstscoff.reg
Windows Registry Editor Version 5.00[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server]"fDenyTSConnections"=dword:00000001
voilà.
Bon app!
Dernière modification par 2F (Le 04/05/2010, à 17:02)
Hors ligne
#1005 Le 08/05/2010, à 16:28
malagasy
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Bonjour,
je n'y connais rien du tout en script, alors je voudrai savoir si quelqu'un peut me faire un petit script qui lance au démarrage de gnome:
compiz --replace
puisque depuis la mise à jour vers lucid, gnome n'aime pas trop compiz, et il faut que je lance cette commande à chaque fois,
Merci
Hors ligne
#1006 Le 08/05/2010, à 17:16
Levi59
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Bonjour,
je n'y connais rien du tout en script, alors je voudrai savoir si quelqu'un peut me faire un petit script qui lance au démarrage de gnome:
compiz --replace
puisque depuis la mise à jour vers lucid, gnome n'aime pas trop compiz, et il faut que je lance cette commande à chaque fois,
Merci
pourquoi un script? il te suffit de mettre "compiz-replace" dans les programmes au démarrage non?
Au pire si il faut le lancer en décalé, met "sleep X && compiz-replace" en remplaçant X par le nombre de seconde nécessaires.
Hors ligne
#1007 Le 08/05/2010, à 20:51
#1008 Le 08/05/2010, à 21:24
Levi59
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
c'est pour ça que j'adore cette communauté .. merci, ça marche
À vot' service M'sieurs! ^^
Dernière modification par Levi59 (Le 08/05/2010, à 21:25)
Hors ligne
#1009 Le 08/05/2010, à 22:59
#1010 Le 18/05/2010, à 10:16
yamo
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Bonjour,
Comme j'en avait marre de synaptic je me suis fait un script de mise à jour basé sur apt-get.
Tout d'abord, j'ai pris l'habitude de mettre tous mes scripts dans ~/bin ça permet d'avoir un répertoire home un peu rangé! Et de les lancer très simplement sans devoir ajouter ./ au début
Vous aller trouver étrange que je commence tout de suite par mettre à jour mais c'est par ce que j'utilise cron-apt qui permet de télécharger en tâche de fond les paquets, comme ça les mises paraissent encore plus rapides!
Attention, la mise à jour d'un système n'est pas triviale, lisez ces scripts avant de les utiliser. Personnellement, j'essaie toujours de comprendre ce que va faire une commande avant de l'exécuter.
Je n'ai laissé que la version console, la version graphique n'a pas vraiment d’intérêt vu que ça fonctionne bien de base en graphique.
~/bin/update.console.sh :
#!/bin/bash
# ~/bin/update.console.sh
# mise à jour du 11/12/2011
echo "mise à jour" &&
sudo nice -n 19 ionice -c 3 apt-get dist-upgrade -y &&
echo "nettoyage" &&
sudo nice -n 19 ionice -c 3 apt-get clean &&
echo "nettoyage" &&
sudo nice -n 19 ionice -c 3 apt-get autoclean &&
echo "coup de balai" &&
sudo nice -n 19 ionice -c 3 apt-get autoremove &&
echo "toc toc toc" &&
sudo nice -n 19 ionice -c 3 apt-get -qq update &&
## l'usage de -qq est totalement déconseillé en dehors d'update!
echo "mise à jour" &&
sudo nice -n 19 ionice -c 3 apt-get dist-upgrade -y &&
echo "dernieres mises à jour" &&
grep -v '\(half\|configure\|trigproc\|triggers-pending\|startup\|install-info\|unpacked\|config-files\|triggers-awaited\|installed\)' /var/log/dpkg.log
Pour tester mon script voici un script d'installation :
mkdir ~/bin & cd ~/bin/ &&
wget http://pasdenom.info/scripts/update.console.sh &&
chmod 554 ~/bin/update.console.sh
Enfin pour lancer le script il suffit de taper en console :
update.console.sh
Dernière modification par yamo (Le 11/12/2011, à 12:31)
Hors ligne
#1011 Le 28/05/2010, à 12:49
kazylax
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Bonjour,
un script existe pour Emesene ? de msn messenger
Cordialement,
Hors ligne
#1012 Le 28/05/2010, à 13:11
kyncani
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
J'aimerais savoir comment récupérer la liste des paquets installé manuellement.
Je sais récupérer la liste de tous les paquet installer, mais c'est très casse pied de la nettoyer pour ne conserver que les 60 intéressants...
J'ai donc mis les tag "auto" qu'il faut dans aptitude mais je ne sais pas comment en extraire la liste
aptitude search '~i!~M'
Hors ligne
#1013 Le 28/05/2010, à 20:56
Phendrax
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Yop
J'ai écrit une petite interface en python pour xinput que j'ai appelé gtk-xinput. Cela permet de facilement créer des pointeurs à l'écran et de leur associer des souris.
L'interface affiche donc la liste des pointeurs et chaque souris qui lui est associée. Sur le screen on peut voir par exemple que Logitech G500 est associée au pointeur dont l'id=2.
On peut créer des nouveaux pointeurs à l'écran avec le bouton "Ajouter" (en leur donnant un nom contenant uniquement des caractères alphanumériques) et en supprimer avec le bouton "Supprimer".
Le bouton "Recharger" sert à rafraichir l'affichage, par exemple si on vient de brancher une nouvelle souris.
Par défaut les souris sont associées au pointeur Virtual core. Il suffit de les glisser vers le pointeur que l'on veut.
Pour l'installer il est nécessaire d'avoir python, pygtk, libglade et xinput
sudo apt-get install python python-gtk2 libglade2-0 xinput
Le paquet debian de gtk-xinput peut être téléchargé ici : http://dl.free.fr/getfile.pl?file=/zoIHihCO
Le programme peut ensuite être lancé avec la commande gtk-xinput.
[Edit : il semblerait que le programme ne fonctionne que sous Lucid Lynx notamment à cause de la méthode set_visible() qui ne semble pas exister dans les versions précédentes et à cause de l'affichage de la commande xinput qui diffère selon les versions]
Dernière modification par Phendrax (Le 28/05/2010, à 21:47)
HP Pavillon dv6800 - Ubuntu 10.10 - GNOME 2.32.0
Hors ligne
#1014 Le 29/05/2010, à 01:42
BorX
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Marrant
Ça permet d'utiliser plusieurs souris en même temps ??
Autant je trouve ça vraiment intéressant, autant j'ai du mal à voir dans quel contexte l'utiliser...
A plusieurs ?
Pour les ambidextres ?
Hors ligne
#1015 Le 29/05/2010, à 04:43
kyncani
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Deux personnes sur une même machine
Hors ligne
#1016 Le 29/05/2010, à 12:01
hulk
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
MON scripte iptables
utilisation iptables start ou iptables stop
a placer dans /etc/init.d/ et a rendre exécutable puis l'activer avec update-rc.d
#! /bin/sh
### BEGIN INIT INFO
# Provides: iptables
# Required-Start:
# Required-Stop:
# Should-Start:
# Should-Stop:
# Default-Start: 2 3 4 5
# Default-Stop: 1 6
# Short-Description: script iptables
### END INIT INFO
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
case "$1" in
start)
### SUPRESSION de TOUTES LES ANCIENNES TABLES (OUVRE TOUS!!) ###
iptables -F
iptables -X
### BLOC TOUS !! (seules les autorisations des raigle aprés celle-ci sont prise en compte) ###
iptables -P INPUT DROP
iptables -P OUTPUT DROP
iptables -P FORWARD DROP
### ACCEPT ALL interface loopbaak ###
iptables -I INPUT -i lo -j ACCEPT
iptables -I OUTPUT -o lo -j ACCEPT
### axepte en entrer les connection deja etablie (en gros sa permet d'axépter que les conection inicier
### par sont propre PC)
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
### DNS indispensable pour naviguer facilement sur le web ###
iptables -A OUTPUT -p udp -m udp --dport 53 -j ACCEPT
### HTTP navigation internet non sécuriséer ###
iptables -A OUTPUT -p tcp -m tcp --dport 80 -j ACCEPT
### HTTPS pour le site de banque .... ###
iptables -A OUTPUT -p tcp -m tcp --dport 443 -j ACCEPT
### emesene,pindgin,amsn... ####
iptables -A OUTPUT -p tcp -m tcp --dport 1863 -j ACCEPT
### pop thunderbird ... réceptions des message ####
iptables -A OUTPUT -p tcp -m tcp --dport 110 -j ACCEPT
### smtp thunderbird ... envoi des messages ###
iptables -A OUTPUT -p tcp -m tcp --dport 25 -j ACCEPT
### ntpdate ( client ntp )... sincro a un serveur de temp ###
iptables -A OUTPUT -p udp -m udp --dport 123 -j ACCEPT
### client-transmition
iptables -A OUTPUT -p udp -m udp --sport 51413 -j ACCEPT
iptables -A OUTPUT -p tcp -m tcp -s 192.168.1.2/255.255.255.255 --sport 30000:65000 -o eth0 -j ACCEPT
# remplacer 192.168.1.2 par votre adresse ip et eth0 par l'interface connecter a internet.
### ping ... autorise a pinger un ordinateur distent ###
iptables -A OUTPUT -p icmp -j ACCEPT
### ping ... autorise l'extèrieur a vous pinger ###
# iptables -A INPUT -p icmp -j ACCEPT # enlever le # du début de ligne pour activer cette règle
### LOG ### Log tous ce qui qui n'est pas accepter par une règles précédente
# prés requit : sudo apt-get install sysklogd
# echo 'kern.warning /var/log/iptables.log' > /etc/syslog.conf
iptables -A OUTPUT -j LOG --log-level 4
iptables -A INPUT -j LOG --log-level 4
iptables -A FORWARD -j LOG --log-level 4
;;
stop)
### OUVRE TOUS !! ###
iptables -F
iptables -X
;;
*)
N=/etc/init.d/${0##*/}
echo "Usage: $N {start|stop}" >&2
exit 1
;;
esac
exit 0
pour vérifier les log en temps réel 10 dernier entréer.
tail -f /var/log/iptables.log
Dernière modification par hulk (Le 07/12/2010, à 23:15)
Amilo A 1667G , turion64 , X700 .
debian squeeze amd64
driver libre radeon
Hors ligne
#1017 Le 31/05/2010, à 20:56
shamanphenix
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Pendant que je vous lisais, ça m'a donné envie, alors j'ai rapidement fait un premier jet (il faudrait que je rajoute un vidage de la corbeille, des miniatures Nautilus, etc. mais là n'est pas la question pour le moment ) pour mettre à jour mon système :
#!/bin/sh
# Permets de nettoyer et mettre à jour son système.
# Dépendance(s) : libnotify-bin ou zenity
# zenity --info --text="Mise à jour du système"
notify-send --icon=/usr/share/icons/hicolor/48x48/status/aptdaemon-working.png "Mise à jour du système"
# Mettre à jour la liste des fichiers disponibles dans les dépôts :
# zenity --info --text="Mise à jour de la liste des fichiers disponibles dans les dépôts"
notify-send --icon=/usr/share/icons/hicolor/48x48/status/aptdaemon-update-cache.png "Mise à jour de la liste des fichiers disponibles dans les dépôts"
sudo apt-get update
# Mettre à jour tous les paquets installés vers les dernières versions :
# zenity --info --text="Mise à jour de tous les paquets installés vers les dernières versions"
notify-send --icon=/usr/share/icons/hicolor/48x48/status/aptdaemon-upgrade.png "Mise à jour de tous les paquets installés vers les dernières versions"
sudo apt-get upgrade -y
# Mettre à jour tous les paquets installés vers les dernières versions en installant de nouveaux paquets si nécessaire :
# zenity --info --text="Mise à jour de tous les paquets installés vers les dernières versions en installant de nouveaux paquets si nécessaire"
notify-send --icon=/usr/share/icons/hicolor/48x48/status/aptdaemon-upgrade.png "Mise à jour de tous les paquets installés vers les dernières versions en installant de nouveaux paquets si nécessaire"
sudo apt-get dist-upgrade -y
# Supprimer les copies des paquets installés :
# zenity --info --text="Suppression des copies des paquets installés"
notify-send --icon=/usr/share/icons/hicolor/48x48/status/aptdaemon-cleanup.png "Suppression des copies des paquets installés"
sudo apt-get clean
# Supprimer les copies des paquets désinstallés :
# zenity --info --text="Suppression copies des paquets désinstallés"
notify-send --icon=/usr/share/icons/hicolor/48x48/status/aptdaemon-cleanup.png "Suppression copies des paquets désinstallés"
sudo apt-get autoclean -y
# zenity --info --text="Le système a été mis à jour"
notify-send --icon=/usr/share/icons/hicolor/48x48/status/aptdaemon-upgrade.png "Le système a été mis à jour"
Alors je sais, c'est super mal de mettre des "sudo" dans un script, et en plus c'est tout pourri puisque dans ce cas on est obligé de lancer le bouzin dans un terminal pour saisir le mot de passe root alors que j'aurais bien voulu le mettre dans mes scripts Nautilus...
Est-ce que l'un(e) d'entre vous aurait une idée géniale, par hasard ?
[edit]PS : c'est dommage que la balise "code" du forum ne colorie pas le texte, ça aiderait beaucoup à la lisibilité.[/edit]
Dernière modification par shamanphenix (Le 31/05/2010, à 20:57)
"Ubuntu". Si tous les gens du monde voulaient bien se tenir par la main... ce serait bien plus facile pour les électrocuter.
What did /home/user/DARTHVADER say to /home/user/DARTHVADER/LUKESKYWALKER ?I AM YOUR PARENT FOLDER.
Hors ligne
#1018 Le 31/05/2010, à 21:01
TatrefThekiller
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
gksudo ?
Hors ligne
#1019 Le 31/05/2010, à 21:12
shamanphenix
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
gksudo ?
En effet c'est une bonne idée, je pourrais remplacer le premier "sudo" par un "gksudo" (ça devrait suffire pour les autres, non ?), mais je dois avouer que je préfèrerais que cela soit entièrement automatisé (je sais saymal).
"Ubuntu". Si tous les gens du monde voulaient bien se tenir par la main... ce serait bien plus facile pour les électrocuter.
What did /home/user/DARTHVADER say to /home/user/DARTHVADER/LUKESKYWALKER ?I AM YOUR PARENT FOLDER.
Hors ligne
#1020 Le 31/05/2010, à 22:00
kyncani
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Ce genre de truc en en-tête peut marcher je crois :
if test `id -u` -ne 0; then
if test "$DISPLAY" = ""; then
exec sudo "$0" "$@"
else
exec gksudo "$0" "$@"
fi
exit 1
fi
Hors ligne
#1021 Le 01/06/2010, à 00:04
BorX
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Ou sinon
o Donner au script les droits root :
-rwx------ root root leScript
o Y virer tous les sudo qui sont à l'intérieur
o Et l'appeler avec sudo leScript
Ce qui continuera à demander un mot de passe à son lancement, sauf si on modifie le fichier /etc/sudoers de façon à ce script puisse être exécuté avec un sudo sans mot de passe.
Quelque chose du style
%sudo ALL=NOPASSWD: leScript
Mais je ne me souviens plus trop de la syntaxe.
C'est pas compliqué, faut chercher un tout petit peu
Hors ligne
#1022 Le 01/06/2010, à 08:21
draco31.fr
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
[edit]PS : c'est dommage que la balise "code" du forum ne colorie pas le texte, ça aiderait beaucoup à la lisibilité.[/edit]
C'est possible sur le wiki si tu indiques le langage ... mais à ma connaissance, ça n'a pas été prévu pour le forum.
Cela dit, il te suffit d'en faire la demande sur le topic de la nouvelle version du forum, ou de créer un rapport de bug sur launchpad pour le projet ubuntu-fr.org
Hors ligne
#1023 Le 01/06/2010, à 12:38
Levi59
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
shamanphenix a écrit :
[edit]PS : c'est dommage que la balise "code" du forum ne colorie pas le texte, ça aiderait beaucoup à la lisibilité.[/edit]
C'est possible sur le wiki si tu indiques le langage ... mais à ma connaissance, ça n'a pas été prévu pour le forum.
Cela dit, il te suffit d'en faire la demande sur le topic de la nouvelle version du forum, ou de créer un rapport de bug sur launchpad pour le projet ubuntu-fr.org
Ou encore de créer un plugin FF bien que ce ne soit pas du tout dans mes cordes... ^^
Si quelqu'un en est capable, voila un bon challenge!
Hors ligne
#1024 Le 01/06/2010, à 22:41
Nik0s
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
J'ai créé un petit script pour récupérer des wallpapers sur Interfacelift. Il y a, je pense, possibilité de l'améliorer, mais en voici le code
retiré
Dernière modification par Nik0s (Le 03/06/2010, à 20:46)
Hors ligne
|
Fibonacci
We started this series (no pun intended) by providing a simple Python script that gave us the Fibonacci numbers less than 50.
As previously mentionned, the code was (save as
fibonacci.py):
a, b = 0, 1
print a,
while b < 50:
print b,
a, b = b, a + b
We would then run it as:
$ python fibo.py
Fibospeak
We then added a way to speak those same numbers (save as
fibospeak.py):
import os
def say(something):
os.system('espeak -ven+f2 "{0}"'.format(something))
a, b = 0, 1
say(a)
while b < 50:
say(b)
a, b = b, a+b
Everything below the line in the middle of the code is pretty much the same, except we use
say()instead of
say()in the first part of our code.
As part of our original challenge, we offered an alternate challenge, for those who are more visual:
Fibocairo
We will be using pycairo. We will visualize the Fibonacci numbers, but without using actual numbers. We will draw big dots instead.
There is some basic setup to do before we can use it to, say, draw a line, or save an image. We wont go into all the details, there are some good tutorials on the pycairo site. But just to get an idea here is an excerpt:
import cairo
WIDTH = 350
HEIGHT = 450
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT)
ctx = cairo.Context(surface)
ctx.set_line_width(DOTSIZE)
ctx.set_source_rgb(1, 0, 0) # red
We create a surface (
which we will later save as a PNG) that is 350 by 450 (
we use constants to define those, ALLCAPS is the standard for constants in Python) then create a context from that surface. We could scale it, as is demoed in the tutorial on the pycairo site, but we will stay with pixels for right now so we dont make things more complicated than they need to be.
We will replace our
say()function from our previous example, by a new one, which we will call
drawdots().
DOTSIZE = 3
def drawdots(ctx, qty):
""" generate a vertical sequence of qty number of dots """
ctx.save() # save our position before doing anything
ctx.set_line_width(DOTSIZE)
ctx.set_source_rgb(1, 0, 0) # RED color
for _ in xrange(qty):
ctx.rectangle(-DOTSIZE, -DOTSIZE, DOTSIZE, DOTSIZE)
ctx.stroke()
ctx.translate(0, DOTSIZE * 4) # move down 4 times dotsize
ctx.restore() # restore our position
We are passing the context to this function, so we can do stuff to it. First, we save it (so we can restore it at the end). We set the line width to 3 and the color to red (1,0,0 in RGB). We are ready to do the work, we will loop for the Fibonacci number that is passed (qty).
Note: we didn't do afor i in xrange()because wedon't needan actual value. The "standard" way to discard a variable in a loop like this is to use the underscore (_). It keeps pylint happy instead of complaining about a variable that is defined, but not used. It is as if I was sayingforJust like in the spoken language when somebody replies "whatever!", it implies whatever, i don't care. The same applies here.whateverin xrange().
Inside the loop, I am preparing a small rectangle (a square, really), painting it and moving down on my surface with ctx.translate().
Let us now move on to the last part, the main loop we have covered several times by now:
a, b = 0, 1
ctx.translate(30, 30) # for item 0, skip over some space
while b < 50:
ctx.translate(30, 0)
drawdots(ctx, b)
a, b = b, a + b
All that we have changed is that instead of
printing, we
translate(move) and
drawdots.
Putting it all together (save as
fibocairo.py):
#!/usr/bin/env python
""" Representing Fibonacci numbers visually, as big dots """
import cairo
# hardwired limit
LIMIT = 50
DOTSIZE = 3
# These work for the current limits.
# You will need to adjust these if the above are changed.
# It is not linear and depend in both x and y on Fibonacci numbers.
WIDTH = 350
HEIGHT = 450
def drawdots(ctx, qty):
""" generate a vertical sequence of qty number of dots """
ctx.save() # save our position before doing anything
ctx.set_line_width(DOTSIZE)
ctx.set_source_rgb(1, 0, 0) # RED color
for _ in xrange(qty):
ctx.rectangle(-DOTSIZE, -DOTSIZE, DOTSIZE, DOTSIZE)
ctx.stroke()
ctx.translate(0, DOTSIZE * 4) # move down 4 times dotsize
ctx.restore() # restore our position
def main():
""" our main loop to generate a PNG file with a """
# here, we are just setting up cairo
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT)
ctx = cairo.Context(surface)
# where the actual work is done
a, b = 0, 1
ctx.translate(30, 30) # for item 0, skip over some space
while b < 50:
ctx.translate(30, 0)
drawdots(ctx, b)
a, b = b, a + b
surface.write_to_png('fibocairo.png') # done, write to png
if __name__ == "__main__":
main()
The line:
surface.write_to_png('fibocairo.png') # done, write to png
is where we save the surface to a png file. There are other formats supported by pycairo.
Visual?
I did say it would be visual, didn't I. The last line of the main() function saves the surface to fibocairo.png, and this is how it looks:
Perhaps it is not as impressive as the code looks...
Fibotangle
So let us try drawing rectangles that we will rotate around a point, as a visual representation. Perhaps this will look a little bit more interesting...
Instead of a
drawdots()function we will write a
draw(). We are not drawing dots, nor any other typical shape here, so we'll just leave it a generic
draw().
def draw(ctx, fibo):
""" a rotational shape based on fibo number of rectangles """
for i in xrange(fibo):
ctx.save()
ctx.rotate(i * 2 * math.pi / fibo)
ctx.rectangle(-20, -50, 20, 50)
ctx.stroke()
ctx.restore()
The main loop that we've covered in the past few examples does have to change now. The shapes are much bigger and we need to start a new line everytime we've drawn 5 shapes.
# where the actual work is done
a, b = 0, 1
ctx.translate(0, 120)
ctx.save()
ctx.translate(120, 0) # for item 0, skip over some space
count = 0
while b < 50:
count += 1
if count == 5:
ctx.restore()
ctx.translate(0, 120)
ctx.save()
count = 0
ctx.translate(120, 0)
draw(ctx, b)
a, b = b, a + b
We've added a counter, we increment it in the loop. We could have used a modulo instead of a counter and comparison to 5, but the logic would have been more obtuse. We will cover an example of that in the future, however.
Putting it all together, we get (save to
fibotangle.py):
#!/usr/bin/env python
""" Representing Fibonacci numbers visually, as rotated rectangles """
import cairo
import math
# hardwired limit
LIMIT = 50
WIDTH = 720
HEIGHT = 320
def draw(ctx, fibo):
""" a rotational shape based on fibo number of rectangles """
for i in xrange(fibo):
ctx.save()
ctx.rotate(i * 2 * math.pi / fibo)
ctx.rectangle(-20, -50, 20, 50)
ctx.stroke()
ctx.restore()
def main():
""" our main loop to generate a PNG file with a """
# here, we are just setting up cairo
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, WIDTH, HEIGHT)
ctx = cairo.Context(surface)
ctx.set_line_width(3)
# where the actual work is done
a, b = 0, 1
ctx.translate(0, 120)
ctx.save()
ctx.translate(120, 0) # for item 0, skip over some space
count = 0
while b < 50:
count += 1
if count == 5:
ctx.restore()
ctx.translate(0, 120)
ctx.save()
count = 0
ctx.translate(120, 0)
draw(ctx, b)
a, b = b, a + b
surface.write_to_png('fibotangles.png') # done, write to png
if __name__ == "__main__":
main()
And what does it look like?
This is way more interesting. The complexity level just adds something that is much more satisfying to the eye, than just a series of dots, or numbers.
Showing this around, I usually get a comment that the last three look like flowers, perhaps a rose, a daisy and a sunflower. Interestingly, many daisies and sunflowers have 34 petals (our last shape) and 55, 89 and 144 are all possible counts of florets on a sunflower, all Fibonacci numbers. It is a fact that many flowers have a number of petals from the Fibonacci sequence. It is not a coincidence, it is tied to the golden angle, spirals and phyllotaxis.
Anyway, just mentioning this as an interesting anecdote, as the answer to where you can find the Fibonacci numbers around us (question #2 of the original challenge), and to introduce our next math concept. There is math all around us in nature.
It is in the title
When I concluded the first article on Fibonacci numbers, I had a section with this title:
Bucolic Mix
And we were talking (literally) about Fibonacci numbers.
Bucolic Mixwas one remix that
Mobydid of a
Brian Enosong. One reader thought I was perhaps making a reference to
Moby's 257 zerosong (using recordings from numbers stations - that's a story for another post).
Good guess, but I was simply making a reference to the title of that
Brian Enosong:
Fractal Zoom (Bucholic Mix)
Yes, we are about to talk about Fractals. Order in chaos, you know: On fractals (next article)
|
The subprocessmodule, which was introduced in Python 2.4, provides you with aconvenient interface for spawning subprocesses, and for interactingwith these subprocesses in your parent process. The module wasintroduced in PEP 324, andis a replacement for the proliferation of other functions and modulesthat were used previously for spawning and interacting with processes.The subprocess module aims to provide a more consistent interface,regardless of the particulars of how you need to interact with thesubprocesses.
subprocess module
Subprocesses are encapsulated in a Popen object. You interact witha subprocess via its stdin, stdout, and stderr streams. When youcreate a new Popen object, you can give a value of PIPE for thestdin, stdout, and stderr keyword parameters. If you do, thenthe Popen object that you get back will have stdin, stdout,and/or stderr attributes. Each of these is a file-like object,giving you access to the corresponding stream of the subprocess.
Now, you have to be careful how you use these pipe objects, since it’seasy to fall into a situation where you have deadlock. For instance,your parent process might be trying to write some data into thestdin pipe, to send some information into the subprocess. Thesubprocess, on the other hand, is trying to write some data into thestdout pipe, to send some information back out to the parentprocess. If the stdout pipe’s buffer is full, then the subprocesswill block trying write into the pipe; it won’t be able to proceeduntil the parent process has read some data from the stdout pipe,clearing room in the buffer for the new data. However, the parentprocess is currently trying to write into the stdin pipe. If thiswrite is also blocked, then we have deadlock â neither process canproceed.
communicate method
The usual solution in these cases is to use the Popen object’scommunicate method. This method takes in an optional string to sendto the subprocess on stdin. It then collects all of the stdout andstderr output from the subprocess, and returns these. Thecommunicate method takes responsibility for avoiding deadlock; itonly sends the next chunk of the stdin string when the subprocess isready to read it, and it only tries to read the next chuck of stdoutor stderr when the subprocess is ready to provide it.
Under the covers, the communicate method uses a select loop toperform this choreography with the subprocess. (At least for the Uniximplementation of the subprocess module, that is.) This solution isnice because it doesn’t require introducing threading into the parentprocess. During each iteration of the loop, it calls the OS’sselect system call, giving it the file descriptors of the stdin,stdout, and stderr pipes. The select call tells us which of thesefile descriptors can perform an I/O operation without blocking. Ifnone of them can immediately, it will block until one of them can.Once the select call returns, we read from or write to the pipesthat are ready. We repeat this process until we see EOF on bothstdout and stderr; this indicates that the subprocess has finished âor at least, that it’s through communicating with us.
The communicate method provides a nice, simple interface forinteracting with a subprocess, without having to worry about deadlocksituations. Unfortunately, it has two main drawbacks:
(If neither of these is an issue for you, then the rest of this postis less interesting to you â communicate does exactly what youwant!)
The first item is a problem if your subprocess creates a lot of output â the worry is the output will be too large to fit into a Python string. If it is, then the parent process will (at best) start to thrash as it eats into virtual memory.
The second item is a problem if you have to spawn multiplesubprocesses, and interact with them simultaneously. You could arguethat there’s no need to fix this problem if you haven’t fixed thefirst: since the communicate method is just going to collect thestdout and stderr into strings, then you could just loop through eachof your subprocesses, calling communicate on each in turn:
import subprocess
sp1 = subprocess.Popen([“ls”, “-l”],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
sp2 = subprocess.Popen([“ls”, “-al”],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
for sp in [sp1, sp2]:
(stdout, stderr) = sp.communicate()
print stdout
The end result would be what you want â all of the stdout and stderr strings for all of your subprocesses.
However, doing so can make your subprocesses take longer to run, sinceyou won’t be able to exploit parallelism as much. Since you’re firingoff these subprocesses at the same time, you supposedly want them toexecute simultaneously, allowing the OS to schedule them appropriateso that they finish as quickly as possible. However, you’veintroduced a serialization into this logic, since your parent processis only able to interact with one subprocess at a time. For instance,subprocess #2 might be waiting for some input, while the parentprocess is still snarfing up the output from subprocess #1. In thiscase, subprocess #2 is not going to be able to start executinguntil subprocess #1 has
communicate loop has completely eliminated the benefit of startingthe subprocesses simultaneously.
In later posts, I will outline how to solve these two problems.
|
Gnome desktop application framework based on Webkit, HTML5, CSS3, Javascript and Python
"AppKit" will be a framework for gnome desktop application powered by WebKit engine, which means we can bring web technology such as HTML5, CSS3, Javascript and Web browser engine to desktop.
Linux, Gnome
$ pip install appkit
$ pip install git+git://github.com/nitipit/appkit.git
#!/usr/bin/env python
from appkit.api.v0_2_8 import App
app = App(__name__)
@app.route('/')
def home():
return '<a href="/test/Hello/World/" />Link</a>'
@app.route('/test/<text1>/<text2>/')
def test(text1=None, text2=None):
return '<h1>' + text1 + ' ' + text2 + '</h1>'
app.run()
|
Judepaum
[Résolu] Twinview changement résolution impossible
Bonjour et bonne année !
Je viens de faire une installation fraîche de 12.10 et j'ai pas mal de soucis pour retrouver la configuration de TwinView que j'avais sur 12.04 ...
Donc, dans les faits, dans nvidia-settings je ne peux choisir que Off ou Auto pour la résolution et cette dernière est bloquée sur 800x600 alors que je souhaite du 1024x768 ... Mais le plus troublant c'est que si je supprime /etc/X11/xorg.conf, que je redémarre, que je recrée xorg.conf avec nvidia-xconfig je peux choisir la résolution que je veux pour mon deuxième écran dans nvidia-settings ! Malheureusement, après un redémarrage mon deuxième écran revient en 800x600 alors que j'avais bien sauvegarder mon xorg.conf ...
Dans le doute, j'ai essayé nvidia-current, nvidia-current-updates et nvidia-experimental-310 mais j'ai toujours le même résultat ...
Voici mon xorg.conf :
# nvidia-settings: X configuration file generated by nvidia-settings
# nvidia-settings: version 304.51 (buildd@batsu) Fri Oct 12 12:53:54 UTC 2012
# nvidia-xconfig: X configuration file generated by nvidia-xconfig
# nvidia-xconfig: version 310.14 (buildmeister@swio-display-x86-rhel47-06.nvidia.com) Tue Oct 9 13:04:01 PDT 2012
Section "ServerLayout"
Identifier "Layout0"
Screen 0 "Screen0" 0 0
InputDevice "Keyboard0" "CoreKeyboard"
InputDevice "Mouse0" "CorePointer"
Option "Xinerama" "0"
EndSection
Section "Files"
EndSection
Section "InputDevice"
# generated from default
Identifier "Mouse0"
Driver "mouse"
Option "Protocol" "auto"
Option "Device" "/dev/psaux"
Option "Emulate3Buttons" "no"
Option "ZAxisMapping" "4 5"
EndSection
Section "InputDevice"
# generated from default
Identifier "Keyboard0"
Driver "kbd"
EndSection
Section "Monitor"
Identifier "Monitor0"
VendorName "Unknown"
ModelName "HannStar Display Corp HSD160PHW1"
HorizSync 30.0 - 75.0
VertRefresh 59.0
Option "DPMS"
EndSection
Section "Device"
Identifier "Device0"
Driver "nvidia"
VendorName "NVIDIA Corporation"
BoardName "GeForce GTX 260M"
EndSection
Section "Screen"
Identifier "Screen0"
Device "Device0"
Monitor "Monitor0"
DefaultDepth 24
Option "Stereo" "0"
Option "nvidiaXineramaInfoOrder" "DFP-0"
Option "metamodes" "DFP: nvidia-auto-select +0+0, CRT: nvidia-auto-select +1366+0"
SubSection "Display"
Depth 24
EndSubSection
EndSection
Merci d'avance
Dernière modification par Judepaum (Le 14/01/2013, à 11:34)
Hors ligne
Maisondouf
Re : [Résolu] Twinview changement résolution impossible
Forcément si tu laisses le choix au driver avec "nvidia-auto-select", il va pas forcer, le gars ....
Remplaces ta ligne "metamodes" avec une comme ça où tu mets tes résolutions d'écran:
Option "metamodes" "DFP: 1366x768+0+0, CRT: 1024x768+1366+0"
Surtout, mets bien le bon décalage sur le deuxième écran.
ASUS M5A88-v EVO avec AMD FX(tm)-8120 Eight-Core Processor, OS principal Precise 12.04.1 LTS 63bits½
Bricoleur, menteur, inculte, inadapté social et mythomane, enfin d'après certains....
"the secret of my form is summed up in two words, no sport" (Winston Churchill)
Hors ligne
Judepaum
Re : [Résolu] Twinview changement résolution impossible
J'avais déjà essayé de modifier cette ligne manuellement pour forcer la résolution et ça ne marche pas ...
Dans le doute j'ai retenté avec la tienne et ça ne fonctionne pas mieux .... D'ailleurs quand je mets cette ligne manuellement, mon deuxième écran n'est pas détecté sur la page de login alors que c'était le cas avant et que c'est le cas aussi avec nvidia-auto-select.
Hors ligne
Judepaum
Re : [Résolu] Twinview changement résolution impossible
Up
Hors ligne
Angelsword
Re : [Résolu] Twinview changement résolution impossible
La sauvegarde à chaque redémarrage est aussi un problème pour moi, mais moi c'est pour le rafraîchissement, donc je surveille ce topic au cas ou ...
Hors ligne
classdroogies
Re : [Résolu] Twinview changement résolution impossible
Salut,
Supprime ton xorg.conf et essai de faire ta config avec xrandr.
Poste le contenu de /var/log/Xorg.0.log
Hors ligne
Angelsword
Re : [Résolu] Twinview changement résolution impossible
Salut et merci pour ta réponse.
Je ne sais pas ce qu'il s'est passé, mais ce matin les paramètres étaient sauvegardé comme je l'ai souhaité o_0
Et depuis tout va bien, j'ai gardé le Xorg.conf, après j'ai fait tellement de manipulations que je ne saurais dire ce qui a validé tout ça.
Je me souviens avoir utilisé la commande :
gksu nvidia-settings
Mais je me souviens qu'au redémarrage ça n'avait pas fonctionné.
Mon Xorg.conf :
# nvidia-settings: X configuration file generated by nvidia-settings
# nvidia-settings: version 304.51 (buildd@aatxe) Fri Oct 12 12:54:02 UTC 2012
Section "ServerLayout"
Identifier "Layout0"
Screen 0 "Screen0" 0 0
InputDevice "Keyboard0" "CoreKeyboard"
InputDevice "Mouse0" "CorePointer"
Option "Xinerama" "0"
EndSection
Section "Files"
EndSection
Section "InputDevice"
# generated from default
Identifier "Mouse0"
Driver "mouse"
Option "Protocol" "auto"
Option "Device" "/dev/psaux"
Option "Emulate3Buttons" "no"
Option "ZAxisMapping" "4 5"
EndSection
Section "InputDevice"
# generated from default
Identifier "Keyboard0"
Driver "kbd"
EndSection
Section "InputClass"
Identifier "Mouse Remap"
MatchDevicePath "/dev/input/event*"
Option "ButtonMapping" "1 2 3 4 5 6 7 8 9 10 11 12 0 0 0 16 17 18 19 20 21"
EndSection
Section "Monitor"
# HorizSync source: edid, VertRefresh source: edid
Identifier "Monitor0"
VendorName "Unknown"
ModelName "BenQ XL2420T"
HorizSync 30.0 - 140.0
VertRefresh 56.0 - 120.0
Option "DPMS"
EndSection
Section "Device"
Identifier "Device0"
Driver "nvidia"
VendorName "NVIDIA Corporation"
BoardName "GeForce GTX 275"
EndSection
Section "Screen"
# Removed Option "metamodes" "DFP-1: 1920x1080_120 +0+0, DFP-0: 1920x1080_60 +1920+0; DFP-0: nvidia-auto-select +0+0; DFP-0: 1920x1080 +0+0; DFP-0: 1920x1080_60 +0+0; DFP-0: 1920x1080_60_0 +0+0; DFP-0: 1680x1050 +0+0; DFP-0: 1680x1050_60 +0+0; DFP-0: 1280x1024 +0+0; DFP-0: 1280x1024_75 +0+0; DFP-0: 1280x1024_60 +0+0; DFP-0: 1280x960 +0+0; DFP-0: 1280x960_60 +0+0; DFP-0: 1152x864 +0+0; DFP-0: 1152x864_75 +0+0; DFP-0: 1024x768 +0+0; DFP-0: 1024x768_75 +0+0; DFP-0: 1024x768_60 +0+0; DFP-0: 800x600 +0+0; DFP-0: 800x600_75 +0+0; DFP-0: 800x600_60 +0+0; DFP-0: 800x600_56 +0+0; DFP-0: 640x480 +0+0; DFP-0: 640x480_75 +0+0; DFP-0: 640x480_60 +0+0; DFP-0: nvidia-auto-select +0+0"
# Removed Option "metamodes" "DFP-1: 1920x1080_120 +0+0, DFP-0: 1920x1080_60 +1920+0; DFP-0: nvidia-auto-select +0+0; DFP-0: nvidia-auto-select +0+0; DFP-0: 1920x1080 +0+0; DFP-0: 1920x1080 +0+0; DFP-0: 1920x1080_60 +0+0; DFP-0: 1920x1080_60 +0+0; DFP-0: 1920x1080_60_0 +0+0; DFP-0: 1920x1080_60_0 +0+0; DFP-0: 1680x1050 +0+0; DFP-0: 1680x1050 +0+0; DFP-0: 1680x1050_60 +0+0; DFP-0: 1680x1050_60 +0+0; DFP-0: 1280x1024 +0+0; DFP-0: 1280x1024 +0+0; DFP-0: 1280x1024_75 +0+0; DFP-0: 1280x1024_75 +0+0; DFP-0: 1280x1024_60 +0+0; DFP-0: 1280x1024_60 +0+0; DFP-0: 1280x960 +0+0; DFP-0: 1280x960 +0+0; DFP-0: 1280x960_60 +0+0; DFP-0: 1280x960_60 +0+0; DFP-0: 1152x864 +0+0; DFP-0: 1152x864 +0+0; DFP-0: 1152x864_75 +0+0; DFP-0: 1152x864_75 +0+0; DFP-0: 1024x768 +0+0; DFP-0: 1024x768 +0+0; DFP-0: 1024x768_75 +0+0; DFP-0: 1024x768_75 +0+0; DFP-0: 1024x768_60 +0+0; DFP-0: 1024x768_60 +0+0; DFP-0: 800x600 +0+0; DFP-0: 800x600 +0+0; DFP-0: 800x600_75 +0+0; DFP-0: 800x600_75 +0+0; DFP-0: 800x600_60 +0+0; DFP-0: 800x600_60 +0+0; DFP-0: 800x600_56 +0+0; DFP-0: 800x600_56 +0+0; DFP-0: 640x480 +0+0; DFP-0: 640x480 +0+0; DFP-0: 640x480_75 +0+0; DFP-0: 640x480_75 +0+0; DFP-0: 640x480_60 +0+0; DFP-0: 640x480_60 +0+0; DFP-0: nvidia-auto-select +0+0; DFP-0: nvidia-auto-select +0+0"
Identifier "Screen0"
Device "Device0"
Monitor "Monitor0"
DefaultDepth 24
Option "Stereo" "0"
Option "nvidiaXineramaInfoOrder" "DFP-1"
Option "metamodes" "DFP-1: 1920x1080_120 +0+0, DFP-0: 1920x1080_60 +1920+0; DFP-0: nvidia-auto-select +0+0; DFP-0: nvidia-auto-select +0+0; DFP-0: 1920x1080 +0+0; DFP-0: 1920x1080 +0+0; DFP-0: 1920x1080_60 +0+0; DFP-0: 1920x1080_60 +0+0; DFP-0: 1920x1080_60_0 +0+0; DFP-0: 1920x1080_60_0 +0+0; DFP-0: 1680x1050 +0+0; DFP-0: 1680x1050 +0+0; DFP-0: 1680x1050_60 +0+0; DFP-0: 1680x1050_60 +0+0; DFP-0: 1280x1024 +0+0; DFP-0: 1280x1024 +0+0; DFP-0: 1280x1024_75 +0+0; DFP-0: 1280x1024_75 +0+0; DFP-0: 1280x1024_60 +0+0; DFP-0: 1280x1024_60 +0+0; DFP-0: 1280x960 +0+0; DFP-0: 1280x960 +0+0; DFP-0: 1280x960_60 +0+0; DFP-0: 1280x960_60 +0+0; DFP-0: 1152x864 +0+0; DFP-0: 1152x864 +0+0; DFP-0: 1152x864_75 +0+0; DFP-0: 1152x864_75 +0+0; DFP-0: 1024x768 +0+0; DFP-0: 1024x768 +0+0; DFP-0: 1024x768_75 +0+0; DFP-0: 1024x768_75 +0+0; DFP-0: 1024x768_60 +0+0; DFP-0: 1024x768_60 +0+0; DFP-0: 800x600 +0+0; DFP-0: 800x600 +0+0"
SubSection "Display"
Depth 24
EndSubSection
EndSection
Hors ligne
Judepaum
Re : [Résolu] Twinview changement résolution impossible
Merci beaucoup classdroogies !
Ca fonctionne au poil avec xrandr et sans xorg.conf ! Tu as une idée du pourquoi du comment ?
Mon Xorg.0.log si ça peut aider à trouver pourquoi je ne peux pas directement faire ça avec nvidia-settings :
[ 95.762]
X.Org X Server 1.13.0
Release Date: 2012-09-05
[ 95.762] X Protocol Version 11, Revision 0
[ 95.762] Build Operating System: Linux 3.2.0-32-generic x86_64 Ubuntu
[ 95.762] Current Operating System: Linux ju-G60J 3.5.0-21-generic #32-Ubuntu SMP Tue Dec 11 18:51:59 UTC 2012 x86_64
[ 95.762] Kernel command line: BOOT_IMAGE=/boot/vmlinuz-3.5.0-21-generic root=UUID=b27dfa5d-f893-4a8c-90cd-db237f878bb1 ro quiet splash
[ 95.762] Build Date: 27 November 2012 07:44:35AM
[ 95.762] xorg-server 2:1.13.0-0ubuntu6.1 (For technical support please see http://www.ubuntu.com/support)
[ 95.762] Current version of pixman: 0.26.0
[ 95.762] Before reporting problems, check http://wiki.x.org
to make sure that you have the latest version.
[ 95.762] Markers: (--) probed, (**) from config file, (==) default setting,
(++) from command line, (!!) notice, (II) informational,
(WW) warning, (EE) error, (NI) not implemented, (??) unknown.
[ 95.762] (==) Log file: "/var/log/Xorg.0.log", Time: Mon Jan 14 10:29:01 2013
[ 95.763] (==) Using system config directory "/usr/share/X11/xorg.conf.d"
[ 95.763] (==) No Layout section. Using the first Screen section.
[ 95.763] (==) No screen section available. Using defaults.
[ 95.763] (**) |-->Screen "Default Screen Section" (0)
[ 95.763] (**) | |-->Monitor "<default monitor>"
[ 95.763] (==) No monitor specified for screen "Default Screen Section".
Using a default monitor configuration.
[ 95.764] (==) Automatically adding devices
[ 95.764] (==) Automatically enabling devices
[ 95.764] (==) Automatically adding GPU devices
[ 95.764] (WW) The directory "/usr/share/fonts/X11/cyrillic" does not exist.
[ 95.764] Entry deleted from font path.
[ 95.764] (WW) The directory "/usr/share/fonts/X11/100dpi/" does not exist.
[ 95.764] Entry deleted from font path.
[ 95.764] (WW) The directory "/usr/share/fonts/X11/75dpi/" does not exist.
[ 95.764] Entry deleted from font path.
[ 95.764] (WW) The directory "/usr/share/fonts/X11/100dpi" does not exist.
[ 95.764] Entry deleted from font path.
[ 95.764] (WW) The directory "/usr/share/fonts/X11/75dpi" does not exist.
[ 95.764] Entry deleted from font path.
[ 95.764] (WW) The directory "/var/lib/defoma/x-ttcidfont-conf.d/dirs/TrueType" does not exist.
[ 95.764] Entry deleted from font path.
[ 95.764] (==) FontPath set to:
/usr/share/fonts/X11/misc,
/usr/share/fonts/X11/Type1,
built-ins
[ 95.764] (==) ModulePath set to "/usr/lib/x86_64-linux-gnu/xorg/extra-modules,/usr/lib/xorg/extra-modules,/usr/lib/xorg/modules"
[ 95.764] (II) The server relies on udev to provide the list of input devices.
If no devices become available, reconfigure udev or disable AutoAddDevices.
[ 95.764] (II) Loader magic: 0x7fc5b3286c40
[ 95.764] (II) Module ABI versions:
[ 95.764] X.Org ANSI C Emulation: 0.4
[ 95.764] X.Org Video Driver: 13.0
[ 95.764] X.Org XInput driver : 18.0
[ 95.764] X.Org Server Extension : 7.0
[ 95.767] (--) PCI:*(0:1:0:0) 10de:0618:1043:2033 rev 162, Mem @ 0xf2000000/16777216, 0xe0000000/268435456, 0xf0000000/33554432, I/O @ 0x0000d000/128, BIOS @ 0x????????/131072
[ 95.767] (II) Open ACPI successful (/var/run/acpid.socket)
[ 95.767] Initializing built-in extension Generic Event Extension
[ 95.767] Initializing built-in extension SHAPE
[ 95.767] Initializing built-in extension MIT-SHM
[ 95.767] Initializing built-in extension XInputExtension
[ 95.767] Initializing built-in extension XTEST
[ 95.767] Initializing built-in extension BIG-REQUESTS
[ 95.767] Initializing built-in extension SYNC
[ 95.767] Initializing built-in extension XKEYBOARD
[ 95.767] Initializing built-in extension XC-MISC
[ 95.767] Initializing built-in extension SECURITY
[ 95.767] Initializing built-in extension XINERAMA
[ 95.768] Initializing built-in extension XFIXES
[ 95.768] Initializing built-in extension RENDER
[ 95.768] Initializing built-in extension RANDR
[ 95.768] Initializing built-in extension COMPOSITE
[ 95.768] Initializing built-in extension DAMAGE
[ 95.768] Initializing built-in extension MIT-SCREEN-SAVER
[ 95.768] Initializing built-in extension DOUBLE-BUFFER
[ 95.768] Initializing built-in extension RECORD
[ 95.768] Initializing built-in extension DPMS
[ 95.768] Initializing built-in extension X-Resource
[ 95.768] Initializing built-in extension XVideo
[ 95.768] Initializing built-in extension XVideo-MotionCompensation
[ 95.768] Initializing built-in extension XFree86-VidModeExtension
[ 95.768] Initializing built-in extension XFree86-DGA
[ 95.768] Initializing built-in extension XFree86-DRI
[ 95.768] Initializing built-in extension DRI2
[ 95.768] (II) LoadModule: "glx"
[ 95.768] (II) Loading /usr/lib/x86_64-linux-gnu/xorg/extra-modules/libglx.so
[ 95.783] (II) Module glx: vendor="NVIDIA Corporation"
[ 95.783] compiled for 4.0.2, module version = 1.0.0
[ 95.783] Module class: X.Org Server Extension
[ 95.783] (II) NVIDIA GLX Module 310.14 Tue Oct 9 12:14:30 PDT 2012
[ 95.783] Loading extension GLX
[ 95.783] (==) Matched nvidia as autoconfigured driver 0
[ 95.783] (==) Matched nouveau as autoconfigured driver 1
[ 95.783] (==) Matched nv as autoconfigured driver 2
[ 95.783] (==) Matched vesa as autoconfigured driver 3
[ 95.783] (==) Matched modesetting as autoconfigured driver 4
[ 95.783] (==) Matched fbdev as autoconfigured driver 5
[ 95.783] (==) Assigned the driver to the xf86ConfigLayout
[ 95.783] (II) LoadModule: "nvidia"
[ 95.783] (II) Loading /usr/lib/x86_64-linux-gnu/xorg/extra-modules/nvidia_drv.so
[ 95.783] (II) Module nvidia: vendor="NVIDIA Corporation"
[ 95.783] compiled for 4.0.2, module version = 1.0.0
[ 95.783] Module class: X.Org Video Driver
[ 95.783] (II) LoadModule: "nouveau"
[ 95.783] (II) Loading /usr/lib/xorg/modules/drivers/nouveau_drv.so
[ 95.784] (II) Module nouveau: vendor="X.Org Foundation"
[ 95.784] compiled for 1.13.0, module version = 1.0.2
[ 95.784] Module class: X.Org Video Driver
[ 95.784] ABI class: X.Org Video Driver, version 13.0
[ 95.784] (II) LoadModule: "nv"
[ 95.784] (WW) Warning, couldn't open module nv
[ 95.784] (II) UnloadModule: "nv"
[ 95.784] (II) Unloading nv
[ 95.784] (EE) Failed to load module "nv" (module does not exist, 0)
[ 95.784] (II) LoadModule: "vesa"
[ 95.784] (II) Loading /usr/lib/xorg/modules/drivers/vesa_drv.so
[ 95.784] (II) Module vesa: vendor="X.Org Foundation"
[ 95.784] compiled for 1.12.99.902, module version = 2.3.2
[ 95.784] Module class: X.Org Video Driver
[ 95.784] ABI class: X.Org Video Driver, version 13.0
[ 95.784] (II) LoadModule: "modesetting"
[ 95.784] (II) Loading /usr/lib/xorg/modules/drivers/modesetting_drv.so
[ 95.784] (II) Module modesetting: vendor="X.Org Foundation"
[ 95.784] compiled for 1.13.0, module version = 0.5.0
[ 95.784] Module class: X.Org Video Driver
[ 95.784] ABI class: X.Org Video Driver, version 13.0
[ 95.784] (II) LoadModule: "fbdev"
[ 95.785] (II) Loading /usr/lib/xorg/modules/drivers/fbdev_drv.so
[ 95.785] (II) Module fbdev: vendor="X.Org Foundation"
[ 95.785] compiled for 1.12.99.902, module version = 0.4.3
[ 95.785] Module class: X.Org Video Driver
[ 95.785] ABI class: X.Org Video Driver, version 13.0
[ 95.785] (==) Matched nvidia as autoconfigured driver 0
[ 95.785] (==) Matched nouveau as autoconfigured driver 1
[ 95.785] (==) Matched nv as autoconfigured driver 2
[ 95.785] (==) Matched vesa as autoconfigured driver 3
[ 95.785] (==) Matched modesetting as autoconfigured driver 4
[ 95.785] (==) Matched fbdev as autoconfigured driver 5
[ 95.785] (==) Assigned the driver to the xf86ConfigLayout
[ 95.785] (II) LoadModule: "nvidia"
[ 95.785] (II) Loading /usr/lib/x86_64-linux-gnu/xorg/extra-modules/nvidia_drv.so
[ 95.785] (II) Module nvidia: vendor="NVIDIA Corporation"
[ 95.785] compiled for 4.0.2, module version = 1.0.0
[ 95.785] Module class: X.Org Video Driver
[ 95.785] (II) UnloadModule: "nvidia"
[ 95.785] (II) Unloading nvidia
[ 95.785] (II) Failed to load module "nvidia" (already loaded, 32709)
[ 95.785] (II) LoadModule: "nouveau"
[ 95.785] (II) Loading /usr/lib/xorg/modules/drivers/nouveau_drv.so
[ 95.785] (II) Module nouveau: vendor="X.Org Foundation"
[ 95.785] compiled for 1.13.0, module version = 1.0.2
[ 95.785] Module class: X.Org Video Driver
[ 95.785] ABI class: X.Org Video Driver, version 13.0
[ 95.785] (II) UnloadModule: "nouveau"
[ 95.785] (II) Unloading nouveau
[ 95.785] (II) Failed to load module "nouveau" (already loaded, 32709)
[ 95.785] (II) LoadModule: "nv"
[ 95.785] (WW) Warning, couldn't open module nv
[ 95.785] (II) UnloadModule: "nv"
[ 95.785] (II) Unloading nv
[ 95.785] (EE) Failed to load module "nv" (module does not exist, 0)
[ 95.785] (II) LoadModule: "vesa"
[ 95.785] (II) Loading /usr/lib/xorg/modules/drivers/vesa_drv.so
[ 95.785] (II) Module vesa: vendor="X.Org Foundation"
[ 95.785] compiled for 1.12.99.902, module version = 2.3.2
[ 95.785] Module class: X.Org Video Driver
[ 95.785] ABI class: X.Org Video Driver, version 13.0
[ 95.785] (II) UnloadModule: "vesa"
[ 95.785] (II) Unloading vesa
[ 95.785] (II) Failed to load module "vesa" (already loaded, 0)
[ 95.785] (II) LoadModule: "modesetting"
[ 95.786] (II) Loading /usr/lib/xorg/modules/drivers/modesetting_drv.so
[ 95.786] (II) Module modesetting: vendor="X.Org Foundation"
[ 95.786] compiled for 1.13.0, module version = 0.5.0
[ 95.786] Module class: X.Org Video Driver
[ 95.786] ABI class: X.Org Video Driver, version 13.0
[ 95.786] (II) UnloadModule: "modesetting"
[ 95.786] (II) Unloading modesetting
[ 95.786] (II) Failed to load module "modesetting" (already loaded, 0)
[ 95.786] (II) LoadModule: "fbdev"
[ 95.786] (II) Loading /usr/lib/xorg/modules/drivers/fbdev_drv.so
[ 95.786] (II) Module fbdev: vendor="X.Org Foundation"
[ 95.786] compiled for 1.12.99.902, module version = 0.4.3
[ 95.786] Module class: X.Org Video Driver
[ 95.786] ABI class: X.Org Video Driver, version 13.0
[ 95.786] (II) UnloadModule: "fbdev"
[ 95.786] (II) Unloading fbdev
[ 95.786] (II) Failed to load module "fbdev" (already loaded, 0)
[ 95.786] (II) NVIDIA dlloader X Driver 310.14 Tue Oct 9 11:54:19 PDT 2012
[ 95.786] (II) NVIDIA Unified Driver for all Supported NVIDIA GPUs
[ 95.786] (II) NOUVEAU driver Date: Wed Sep 12 13:42:43 2012 +0200
[ 95.786] (II) NOUVEAU driver for NVIDIA chipset families :
[ 95.786] RIVA TNT (NV04)
[ 95.786] RIVA TNT2 (NV05)
[ 95.786] GeForce 256 (NV10)
[ 95.786] GeForce 2 (NV11, NV15)
[ 95.786] GeForce 4MX (NV17, NV18)
[ 95.786] GeForce 3 (NV20)
[ 95.786] GeForce 4Ti (NV25, NV28)
[ 95.786] GeForce FX (NV3x)
[ 95.786] GeForce 6 (NV4x)
[ 95.786] GeForce 7 (G7x)
[ 95.786] GeForce 8 (G8x)
[ 95.786] GeForce GTX 200 (NVA0)
[ 95.786] GeForce GTX 400 (NVC0)
[ 95.786] (II) VESA: driver for VESA chipsets: vesa
[ 95.786] (II) modesetting: Driver for Modesetting Kernel Drivers: kms
[ 95.786] (II) FBDEV: driver for framebuffer: fbdev
[ 95.786] (++) using VT number 7
[ 95.787] (II) Loading sub module "wfb"
[ 95.787] (II) LoadModule: "wfb"
[ 95.787] (II) Loading /usr/lib/xorg/modules/libwfb.so
[ 95.788] (II) Module wfb: vendor="X.Org Foundation"
[ 95.788] compiled for 1.13.0, module version = 1.0.0
[ 95.788] ABI class: X.Org ANSI C Emulation, version 0.4
[ 95.788] (II) Loading sub module "ramdac"
[ 95.788] (II) LoadModule: "ramdac"
[ 95.788] (II) Module "ramdac" already built-in
[ 95.788] (WW) Falling back to old probe method for vesa
[ 95.788] (WW) Falling back to old probe method for modesetting
[ 95.788] (EE) open /dev/dri/card0: No such file or directory
[ 95.788] (EE) open /dev/dri/card0: No such file or directory
[ 95.788] (WW) Falling back to old probe method for fbdev
[ 95.788] (II) Loading sub module "fbdevhw"
[ 95.788] (II) LoadModule: "fbdevhw"
[ 95.788] (II) Loading /usr/lib/xorg/modules/libfbdevhw.so
[ 95.788] (II) Module fbdevhw: vendor="X.Org Foundation"
[ 95.788] compiled for 1.13.0, module version = 0.0.2
[ 95.788] ABI class: X.Org Video Driver, version 13.0
[ 95.788] (EE) open /dev/fb0: No such file or directory
[ 95.788] (II) NVIDIA(0): Creating default Display subsection in Screen section
"Default Screen Section" for depth/fbbpp 24/32
[ 95.788] (==) NVIDIA(0): Depth 24, (==) framebuffer bpp 32
[ 95.788] (==) NVIDIA(0): RGB weight 888
[ 95.788] (==) NVIDIA(0): Default visual is TrueColor
[ 95.788] (==) NVIDIA(0): Using gamma correction (1.0, 1.0, 1.0)
[ 95.788] (**) NVIDIA(0): Enabling 2D acceleration
[ 96.555] (WW) NVIDIA(GPU-0): The EDID read for display device CRT-0 is invalid:
[ 96.555] (WW) NVIDIA(GPU-0): unrecognized EDID Header.
[ 96.555] (--) NVIDIA(GPU-0):
[ 96.555] (--) NVIDIA(GPU-0): Raw EDID bytes:
[ 96.555] (--) NVIDIA(GPU-0):
[ 96.555] (--) NVIDIA(GPU-0): fd df fe fe fe fe fe fd 26 cd 50 46 00 00 00 00
[ 96.555] (--) NVIDIA(GPU-0): 28 0c 01 03 0e 22 1b 78 eb a6 9c a1 5a 4b 98 24
[ 96.555] (--) NVIDIA(GPU-0): 16 4c 57 bf ef 00 81 80 81 8f 71 40 71 4f 01 01
[ 96.555] (--) NVIDIA(GPU-0): 01 01 01 01 01 01 30 2a 00 98 51 00 2a 40 30 70
[ 96.555] (--) NVIDIA(GPU-0): 13 00 52 0e 11 00 00 1e 00 00 00 fd 00 32 4b 18
[ 96.555] (--) NVIDIA(GPU-0): 50 0e 00 0a 20 20 20 20 20 20 00 00 00 ff 00 30
[ 96.555] (--) NVIDIA(GPU-0): 0a 20 20 20 20 20 20 20 20 20 20 20 00 00 00 fc
[ 96.555] (--) NVIDIA(GPU-0): 00 41 53 34 33 31 35 20 20 20 20 20 20 20 00 e3
[ 96.555] (--) NVIDIA(GPU-0):
[ 96.555] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 96.555] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 96.555] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 96.555] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 96.555] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 96.556] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 96.556] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 96.556] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 96.556] (--) NVIDIA(GPU-0):
[ 96.556] (II) NVIDIA(GPU-0): Display (HannStar Display Corp HSD160PHW1 (DFP-0)) does not
[ 96.556] (II) NVIDIA(GPU-0): support NVIDIA 3D Vision stereo.
[ 96.557] (II) NVIDIA(0): NVIDIA GPU GeForce GTX 260M (G92) at PCI:1:0:0 (GPU-0)
[ 96.557] (--) NVIDIA(0): Memory: 1048576 kBytes
[ 96.557] (--) NVIDIA(0): VideoBIOS: 62.92.a2.00.08
[ 96.557] (II) NVIDIA(0): Detected PCI Express Link width: 16X
[ 96.565] (--) NVIDIA(0): Valid display device(s) on GeForce GTX 260M at PCI:1:0:0
[ 96.565] (--) NVIDIA(0): CRT-0 (connected)
[ 96.565] (--) NVIDIA(0): HannStar Display Corp HSD160PHW1 (DFP-0) (connected)
[ 96.565] (--) NVIDIA(0): DFP-1
[ 96.565] (--) NVIDIA(0): CRT-0: 400.0 MHz maximum pixel clock
[ 96.565] (--) NVIDIA(0): HannStar Display Corp HSD160PHW1 (DFP-0): 330.0 MHz maximum pixel clock
[ 96.565] (--) NVIDIA(0): HannStar Display Corp HSD160PHW1 (DFP-0): Internal Dual Link LVDS
[ 96.565] (--) NVIDIA(0): DFP-1: 165.0 MHz maximum pixel clock
[ 96.565] (--) NVIDIA(0): DFP-1: Internal Single Link TMDS
[ 96.565] (**) NVIDIA(0): Using HorizSync/VertRefresh ranges from the EDID for display
[ 96.565] (**) NVIDIA(0): device CRT-0 (Using EDID frequencies has been enabled on
[ 96.565] (**) NVIDIA(0): all display devices.)
[ 96.570] (**) NVIDIA(0): Using HorizSync/VertRefresh ranges from the EDID for display
[ 96.570] (**) NVIDIA(0): device HannStar Display Corp HSD160PHW1 (DFP-0) (Using
[ 96.570] (**) NVIDIA(0): EDID frequencies has been enabled on all display
[ 96.570] (**) NVIDIA(0): devices.)
[ 96.570] (==) NVIDIA(0):
[ 96.570] (==) NVIDIA(0): No modes were requested; the default mode "nvidia-auto-select"
[ 96.570] (==) NVIDIA(0): will be used as the requested mode.
[ 96.570] (==) NVIDIA(0):
[ 96.571] (II) NVIDIA(0): Validated MetaModes:
[ 96.571] (II) NVIDIA(0): "DFP-0:nvidia-auto-select,CRT-0:nvidia-auto-select"
[ 96.571] (II) NVIDIA(0): Virtual screen size determined to be 2390 x 768
[ 97.639] (--) NVIDIA(0): DPI set to (99, 97); computed from "UseEdidDpi" X config
[ 97.639] (--) NVIDIA(0): option
[ 97.639] (II) UnloadModule: "nouveau"
[ 97.639] (II) Unloading nouveau
[ 97.639] (II) UnloadModule: "vesa"
[ 97.639] (II) Unloading vesa
[ 97.639] (II) UnloadModule: "modesetting"
[ 97.639] (II) Unloading modesetting
[ 97.639] (II) UnloadModule: "fbdev"
[ 97.639] (II) Unloading fbdev
[ 97.639] (II) UnloadSubModule: "fbdevhw"
[ 97.639] (II) Unloading fbdevhw
[ 97.639] (--) Depth 24 pixmap format is 32 bpp
[ 97.640] (II) NVIDIA: Using 768.00 MB of virtual memory for indirect memory access.
[ 97.652] (II) NVIDIA(0): Setting mode "DFP-0:nvidia-auto-select,CRT-0:nvidia-auto-select"
[ 97.957] Loading extension NV-GLX
[ 97.999] (==) NVIDIA(0): Disabling shared memory pixmaps
[ 97.999] (==) NVIDIA(0): Backing store disabled
[ 97.999] (==) NVIDIA(0): Silken mouse enabled
[ 97.999] (==) NVIDIA(0): DPMS enabled
[ 97.999] Loading extension NV-CONTROL
[ 97.999] Loading extension XINERAMA
[ 97.999] (II) Loading sub module "dri2"
[ 97.999] (II) LoadModule: "dri2"
[ 97.999] (II) Module "dri2" already built-in
[ 97.999] (II) NVIDIA(0): [DRI2] Setup complete
[ 97.999] (II) NVIDIA(0): [DRI2] VDPAU driver: nvidia
[ 97.999] (--) RandR disabled
[ 98.004] (II) Initializing extension GLX
[ 98.016] (II) XKB: reuse xkmfile /var/lib/xkb/server-B20D7FC79C7F597315E3E501AEF10E0D866E8E92.xkm
[ 98.018] (II) config/udev: Adding input device Power Button (/dev/input/event2)
[ 98.018] (**) Power Button: Applying InputClass "evdev keyboard catchall"
[ 98.018] (II) LoadModule: "evdev"
[ 98.018] (II) Loading /usr/lib/xorg/modules/input/evdev_drv.so
[ 98.018] (II) Module evdev: vendor="X.Org Foundation"
[ 98.018] compiled for 1.13.0, module version = 2.7.3
[ 98.018] Module class: X.Org XInput Driver
[ 98.018] ABI class: X.Org XInput driver, version 18.0
[ 98.018] (II) Using input driver 'evdev' for 'Power Button'
[ 98.018] (**) Power Button: always reports core events
[ 98.018] (**) evdev: Power Button: Device: "/dev/input/event2"
[ 98.018] (--) evdev: Power Button: Vendor 0 Product 0x1
[ 98.018] (--) evdev: Power Button: Found keys
[ 98.018] (II) evdev: Power Button: Configuring as keyboard
[ 98.018] (**) Option "config_info" "udev:/sys/devices/LNXSYSTM:00/LNXPWRBN:00/input/input2/event2"
[ 98.018] (II) XINPUT: Adding extended input device "Power Button" (type: KEYBOARD, id 6)
[ 98.018] (**) Option "xkb_rules" "evdev"
[ 98.018] (**) Option "xkb_model" "pc105"
[ 98.018] (**) Option "xkb_layout" "fr"
[ 98.018] (**) Option "xkb_variant" "latin9"
[ 98.020] (II) XKB: reuse xkmfile /var/lib/xkb/server-816A055A5FF7D63897839A4BDEDC3908551E49DA.xkm
[ 98.020] (II) config/udev: Adding input device Video Bus (/dev/input/event4)
[ 98.020] (**) Video Bus: Applying InputClass "evdev keyboard catchall"
[ 98.020] (II) Using input driver 'evdev' for 'Video Bus'
[ 98.020] (**) Video Bus: always reports core events
[ 98.020] (**) evdev: Video Bus: Device: "/dev/input/event4"
[ 98.020] (--) evdev: Video Bus: Vendor 0 Product 0x6
[ 98.020] (--) evdev: Video Bus: Found keys
[ 98.020] (II) evdev: Video Bus: Configuring as keyboard
[ 98.020] (**) Option "config_info" "udev:/sys/devices/LNXSYSTM:00/device:00/PNP0A08:00/device:41/LNXVIDEO:00/input/input4/event4"
[ 98.020] (II) XINPUT: Adding extended input device "Video Bus" (type: KEYBOARD, id 7)
[ 98.020] (**) Option "xkb_rules" "evdev"
[ 98.020] (**) Option "xkb_model" "pc105"
[ 98.020] (**) Option "xkb_layout" "fr"
[ 98.020] (**) Option "xkb_variant" "latin9"
[ 98.021] (II) config/udev: Adding input device Lid Switch (/dev/input/event0)
[ 98.021] (II) No input driver specified, ignoring this device.
[ 98.021] (II) This device may have been added with another device file.
[ 98.021] (II) config/udev: Adding input device Sleep Button (/dev/input/event1)
[ 98.021] (**) Sleep Button: Applying InputClass "evdev keyboard catchall"
[ 98.021] (II) Using input driver 'evdev' for 'Sleep Button'
[ 98.021] (**) Sleep Button: always reports core events
[ 98.021] (**) evdev: Sleep Button: Device: "/dev/input/event1"
[ 98.021] (--) evdev: Sleep Button: Vendor 0 Product 0x3
[ 98.021] (--) evdev: Sleep Button: Found keys
[ 98.021] (II) evdev: Sleep Button: Configuring as keyboard
[ 98.021] (**) Option "config_info" "udev:/sys/devices/LNXSYSTM:00/device:00/PNP0C0E:00/input/input1/event1"
[ 98.021] (II) XINPUT: Adding extended input device "Sleep Button" (type: KEYBOARD, id 8)
[ 98.021] (**) Option "xkb_rules" "evdev"
[ 98.021] (**) Option "xkb_model" "pc105"
[ 98.021] (**) Option "xkb_layout" "fr"
[ 98.021] (**) Option "xkb_variant" "latin9"
[ 98.021] (II) config/udev: Adding input device USB 2.0 UVC 2.0M Webcam (/dev/input/event11)
[ 98.021] (**) USB 2.0 UVC 2.0M Webcam: Applying InputClass "evdev keyboard catchall"
[ 98.021] (II) Using input driver 'evdev' for 'USB 2.0 UVC 2.0M Webcam'
[ 98.021] (**) USB 2.0 UVC 2.0M Webcam: always reports core events
[ 98.021] (**) evdev: USB 2.0 UVC 2.0M Webcam: Device: "/dev/input/event11"
[ 98.021] (--) evdev: USB 2.0 UVC 2.0M Webcam: Vendor 0x64e Product 0xa122
[ 98.021] (--) evdev: USB 2.0 UVC 2.0M Webcam: Found keys
[ 98.021] (II) evdev: USB 2.0 UVC 2.0M Webcam: Configuring as keyboard
[ 98.021] (**) Option "config_info" "udev:/sys/devices/pci0000:00/0000:00:1a.0/usb1/1-1/1-1.6/1-1.6:1.0/input/input11/event11"
[ 98.021] (II) XINPUT: Adding extended input device "USB 2.0 UVC 2.0M Webcam" (type: KEYBOARD, id 9)
[ 98.021] (**) Option "xkb_rules" "evdev"
[ 98.021] (**) Option "xkb_model" "pc105"
[ 98.021] (**) Option "xkb_layout" "fr"
[ 98.021] (**) Option "xkb_variant" "latin9"
[ 98.022] (II) config/udev: Adding input device HDA Intel Headphone (/dev/input/event10)
[ 98.022] (II) No input driver specified, ignoring this device.
[ 98.022] (II) This device may have been added with another device file.
[ 98.022] (II) config/udev: Adding input device HDA Intel Line (/dev/input/event8)
[ 98.022] (II) No input driver specified, ignoring this device.
[ 98.022] (II) This device may have been added with another device file.
[ 98.022] (II) config/udev: Adding input device HDA Intel Mic (/dev/input/event9)
[ 98.022] (II) No input driver specified, ignoring this device.
[ 98.022] (II) This device may have been added with another device file.
[ 98.022] (II) config/udev: Adding input device ROCCAT ROCCAT Kova[+] (/dev/input/event7)
[ 98.022] (**) ROCCAT ROCCAT Kova[+]: Applying InputClass "evdev pointer catchall"
[ 98.022] (**) ROCCAT ROCCAT Kova[+]: Applying InputClass "evdev keyboard catchall"
[ 98.022] (II) Using input driver 'evdev' for 'ROCCAT ROCCAT Kova[+]'
[ 98.022] (**) ROCCAT ROCCAT Kova[+]: always reports core events
[ 98.022] (**) evdev: ROCCAT ROCCAT Kova[+]: Device: "/dev/input/event7"
[ 98.022] (--) evdev: ROCCAT ROCCAT Kova[+]: Vendor 0x1e7d Product 0x2d50
[ 98.022] (--) evdev: ROCCAT ROCCAT Kova[+]: Found 9 mouse buttons
[ 98.022] (--) evdev: ROCCAT ROCCAT Kova[+]: Found scroll wheel(s)
[ 98.022] (--) evdev: ROCCAT ROCCAT Kova[+]: Found relative axes
[ 98.022] (--) evdev: ROCCAT ROCCAT Kova[+]: Found x and y relative axes
[ 98.022] (--) evdev: ROCCAT ROCCAT Kova[+]: Found absolute axes
[ 98.022] (II) evdev: ROCCAT ROCCAT Kova[+]: Forcing absolute x/y axes to exist.
[ 98.022] (--) evdev: ROCCAT ROCCAT Kova[+]: Found keys
[ 98.022] (II) evdev: ROCCAT ROCCAT Kova[+]: Configuring as mouse
[ 98.022] (II) evdev: ROCCAT ROCCAT Kova[+]: Configuring as keyboard
[ 98.022] (II) evdev: ROCCAT ROCCAT Kova[+]: Adding scrollwheel support
[ 98.022] (**) evdev: ROCCAT ROCCAT Kova[+]: YAxisMapping: buttons 4 and 5
[ 98.022] (**) evdev: ROCCAT ROCCAT Kova[+]: EmulateWheelButton: 4, EmulateWheelInertia: 10, EmulateWheelTimeout: 200
[ 98.022] (**) Option "config_info" "udev:/sys/devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.4/2-1.4:1.0/input/input7/event7"
[ 98.022] (II) XINPUT: Adding extended input device "ROCCAT ROCCAT Kova[+]" (type: KEYBOARD, id 10)
[ 98.022] (**) Option "xkb_rules" "evdev"
[ 98.022] (**) Option "xkb_model" "pc105"
[ 98.022] (**) Option "xkb_layout" "fr"
[ 98.022] (**) Option "xkb_variant" "latin9"
[ 98.023] (II) evdev: ROCCAT ROCCAT Kova[+]: initialized for relative axes.
[ 98.023] (WW) evdev: ROCCAT ROCCAT Kova[+]: ignoring absolute axes.
[ 98.023] (**) ROCCAT ROCCAT Kova[+]: (accel) keeping acceleration scheme 1
[ 98.023] (**) ROCCAT ROCCAT Kova[+]: (accel) acceleration profile 0
[ 98.023] (**) ROCCAT ROCCAT Kova[+]: (accel) acceleration factor: 2.000
[ 98.023] (**) ROCCAT ROCCAT Kova[+]: (accel) acceleration threshold: 4
[ 98.023] (II) config/udev: Adding input device ROCCAT ROCCAT Kova[+] (/dev/input/mouse1)
[ 98.023] (II) No input driver specified, ignoring this device.
[ 98.023] (II) This device may have been added with another device file.
[ 98.023] (II) config/udev: Adding input device ROCCAT ROCCAT Kova[+] (/dev/input/event12)
[ 98.023] (**) ROCCAT ROCCAT Kova[+]: Applying InputClass "evdev keyboard catchall"
[ 98.023] (II) Using input driver 'evdev' for 'ROCCAT ROCCAT Kova[+]'
[ 98.023] (**) ROCCAT ROCCAT Kova[+]: always reports core events
[ 98.023] (**) evdev: ROCCAT ROCCAT Kova[+]: Device: "/dev/input/event12"
[ 98.023] (--) evdev: ROCCAT ROCCAT Kova[+]: Vendor 0x1e7d Product 0x2d50
[ 98.023] (--) evdev: ROCCAT ROCCAT Kova[+]: Found keys
[ 98.023] (II) evdev: ROCCAT ROCCAT Kova[+]: Configuring as keyboard
[ 98.023] (**) Option "config_info" "udev:/sys/devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.4/2-1.4:1.1/input/input12/event12"
[ 98.023] (II) XINPUT: Adding extended input device "ROCCAT ROCCAT Kova[+]" (type: KEYBOARD, id 11)
[ 98.023] (**) Option "xkb_rules" "evdev"
[ 98.023] (**) Option "xkb_model" "pc105"
[ 98.023] (**) Option "xkb_layout" "fr"
[ 98.023] (**) Option "xkb_variant" "latin9"
[ 98.024] (II) config/udev: Adding input device Asus Laptop extra buttons (/dev/input/event5)
[ 98.024] (**) Asus Laptop extra buttons: Applying InputClass "evdev keyboard catchall"
[ 98.024] (II) Using input driver 'evdev' for 'Asus Laptop extra buttons'
[ 98.024] (**) Asus Laptop extra buttons: always reports core events
[ 98.024] (**) evdev: Asus Laptop extra buttons: Device: "/dev/input/event5"
[ 98.024] (--) evdev: Asus Laptop extra buttons: Vendor 0 Product 0
[ 98.024] (--) evdev: Asus Laptop extra buttons: Found keys
[ 98.024] (II) evdev: Asus Laptop extra buttons: Configuring as keyboard
[ 98.024] (**) Option "config_info" "udev:/sys/devices/platform/asus_laptop/input/input5/event5"
[ 98.024] (II) XINPUT: Adding extended input device "Asus Laptop extra buttons" (type: KEYBOARD, id 12)
[ 98.024] (**) Option "xkb_rules" "evdev"
[ 98.024] (**) Option "xkb_model" "pc105"
[ 98.024] (**) Option "xkb_layout" "fr"
[ 98.024] (**) Option "xkb_variant" "latin9"
[ 98.024] (II) config/udev: Adding input device AT Translated Set 2 keyboard (/dev/input/event3)
[ 98.024] (**) AT Translated Set 2 keyboard: Applying InputClass "evdev keyboard catchall"
[ 98.024] (II) Using input driver 'evdev' for 'AT Translated Set 2 keyboard'
[ 98.024] (**) AT Translated Set 2 keyboard: always reports core events
[ 98.024] (**) evdev: AT Translated Set 2 keyboard: Device: "/dev/input/event3"
[ 98.024] (--) evdev: AT Translated Set 2 keyboard: Vendor 0x1 Product 0x1
[ 98.024] (--) evdev: AT Translated Set 2 keyboard: Found keys
[ 98.024] (II) evdev: AT Translated Set 2 keyboard: Configuring as keyboard
[ 98.024] (**) Option "config_info" "udev:/sys/devices/platform/i8042/serio0/input/input3/event3"
[ 98.024] (II) XINPUT: Adding extended input device "AT Translated Set 2 keyboard" (type: KEYBOARD, id 13)
[ 98.024] (**) Option "xkb_rules" "evdev"
[ 98.024] (**) Option "xkb_model" "pc105"
[ 98.024] (**) Option "xkb_layout" "fr"
[ 98.024] (**) Option "xkb_variant" "latin9"
[ 98.025] (II) config/udev: Adding input device SynPS/2 Synaptics TouchPad (/dev/input/event6)
[ 98.025] (**) SynPS/2 Synaptics TouchPad: Applying InputClass "evdev touchpad catchall"
[ 98.025] (**) SynPS/2 Synaptics TouchPad: Applying InputClass "touchpad catchall"
[ 98.025] (**) SynPS/2 Synaptics TouchPad: Applying InputClass "Default clickpad buttons"
[ 98.025] (II) LoadModule: "synaptics"
[ 98.025] (II) Loading /usr/lib/xorg/modules/input/synaptics_drv.so
[ 98.025] (II) Module synaptics: vendor="X.Org Foundation"
[ 98.025] compiled for 1.12.99.905, module version = 1.6.2
[ 98.025] Module class: X.Org XInput Driver
[ 98.025] ABI class: X.Org XInput driver, version 18.0
[ 98.025] (II) Using input driver 'synaptics' for 'SynPS/2 Synaptics TouchPad'
[ 98.025] (**) SynPS/2 Synaptics TouchPad: always reports core events
[ 98.025] (**) Option "Device" "/dev/input/event6"
[ 98.025] (--) synaptics: SynPS/2 Synaptics TouchPad: x-axis range 1472 - 5626
[ 98.025] (--) synaptics: SynPS/2 Synaptics TouchPad: y-axis range 1408 - 4716
[ 98.025] (--) synaptics: SynPS/2 Synaptics TouchPad: pressure range 0 - 255
[ 98.025] (--) synaptics: SynPS/2 Synaptics TouchPad: finger width range 0 - 15
[ 98.025] (--) synaptics: SynPS/2 Synaptics TouchPad: buttons: left right
[ 98.025] (--) synaptics: SynPS/2 Synaptics TouchPad: Vendor 0x2 Product 0x7
[ 98.025] (--) synaptics: SynPS/2 Synaptics TouchPad: touchpad found
[ 98.025] (**) SynPS/2 Synaptics TouchPad: always reports core events
[ 98.026] (**) Option "config_info" "udev:/sys/devices/platform/i8042/serio4/input/input6/event6"
[ 98.026] (II) XINPUT: Adding extended input device "SynPS/2 Synaptics TouchPad" (type: TOUCHPAD, id 14)
[ 98.026] (**) synaptics: SynPS/2 Synaptics TouchPad: (accel) MinSpeed is now constant deceleration 2.5
[ 98.026] (**) synaptics: SynPS/2 Synaptics TouchPad: MaxSpeed is now 1.75
[ 98.026] (**) synaptics: SynPS/2 Synaptics TouchPad: AccelFactor is now 0.038
[ 98.026] (**) SynPS/2 Synaptics TouchPad: (accel) keeping acceleration scheme 1
[ 98.026] (**) SynPS/2 Synaptics TouchPad: (accel) acceleration profile 1
[ 98.026] (**) SynPS/2 Synaptics TouchPad: (accel) acceleration factor: 2.000
[ 98.026] (**) SynPS/2 Synaptics TouchPad: (accel) acceleration threshold: 4
[ 98.026] (--) synaptics: SynPS/2 Synaptics TouchPad: touchpad found
[ 98.026] (II) config/udev: Adding input device SynPS/2 Synaptics TouchPad (/dev/input/mouse0)
[ 98.026] (**) SynPS/2 Synaptics TouchPad: Ignoring device from InputClass "touchpad ignore duplicates"
[ 98.501] (WW) NVIDIA(GPU-0): The EDID read for display device CRT-0 is invalid:
[ 98.501] (WW) NVIDIA(GPU-0): unrecognized EDID Header.
[ 98.501] (--) NVIDIA(GPU-0):
[ 98.501] (--) NVIDIA(GPU-0): Raw EDID bytes:
[ 98.501] (--) NVIDIA(GPU-0):
[ 98.501] (--) NVIDIA(GPU-0): fd df fe fe fe fe fe fd 26 cd 50 46 00 00 00 00
[ 98.501] (--) NVIDIA(GPU-0): 28 0c 01 03 0e 22 1b 78 eb a6 9c a1 5a 4b 98 24
[ 98.501] (--) NVIDIA(GPU-0): 16 4c 57 bf ef 00 81 80 81 8f 71 40 71 4f 01 01
[ 98.501] (--) NVIDIA(GPU-0): 01 01 01 01 01 01 30 2a 00 98 51 00 2a 40 30 70
[ 98.501] (--) NVIDIA(GPU-0): 13 00 52 0e 11 00 00 1e 00 00 00 fd 00 32 4b 18
[ 98.501] (--) NVIDIA(GPU-0): 50 0e 00 0a 20 20 20 20 20 20 00 00 00 ff 00 30
[ 98.501] (--) NVIDIA(GPU-0): 0a 20 20 20 20 20 20 20 20 20 20 20 00 00 00 fc
[ 98.501] (--) NVIDIA(GPU-0): 00 41 53 34 33 31 35 20 20 20 20 20 20 20 00 e3
[ 98.501] (--) NVIDIA(GPU-0):
[ 98.501] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 98.501] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 98.501] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 98.501] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 98.501] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 98.501] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 98.501] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 98.501] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 98.501] (--) NVIDIA(GPU-0):
[ 98.501] (**) NVIDIA(0): Using HorizSync/VertRefresh ranges from the EDID for display
[ 98.501] (**) NVIDIA(0): device CRT-0 (Using EDID frequencies has been enabled on
[ 98.501] (**) NVIDIA(0): all display devices.)
[ 98.505] (II) NVIDIA(GPU-0): Display (HannStar Display Corp HSD160PHW1 (DFP-0)) does not
[ 98.505] (II) NVIDIA(GPU-0): support NVIDIA 3D Vision stereo.
[ 98.505] (**) NVIDIA(0): Using HorizSync/VertRefresh ranges from the EDID for display
[ 98.505] (**) NVIDIA(0): device HannStar Display Corp HSD160PHW1 (DFP-0) (Using
[ 98.506] (**) NVIDIA(0): EDID frequencies has been enabled on all display
[ 98.506] (**) NVIDIA(0): devices.)
[ 98.758] (WW) NVIDIA(GPU-0): The EDID read for display device CRT-0 is invalid:
[ 98.758] (WW) NVIDIA(GPU-0): unrecognized EDID Header.
[ 98.758] (--) NVIDIA(GPU-0):
[ 98.758] (--) NVIDIA(GPU-0): Raw EDID bytes:
[ 98.758] (--) NVIDIA(GPU-0):
[ 98.758] (--) NVIDIA(GPU-0): fd df fe fe fe fe fe fd 26 cd 50 46 00 00 00 00
[ 98.758] (--) NVIDIA(GPU-0): 28 0c 01 03 0e 22 1b 78 eb a6 9c a1 5a 4b 98 24
[ 98.758] (--) NVIDIA(GPU-0): 16 4c 57 bf ef 00 81 80 81 8f 71 40 71 4f 01 01
[ 98.758] (--) NVIDIA(GPU-0): 01 01 01 01 01 01 30 2a 00 98 51 00 2a 40 30 70
[ 98.758] (--) NVIDIA(GPU-0): 13 00 52 0e 11 00 00 1e 00 00 00 fd 00 32 4b 18
[ 98.758] (--) NVIDIA(GPU-0): 50 0e 00 0a 20 20 20 20 20 20 00 00 00 ff 00 30
[ 98.758] (--) NVIDIA(GPU-0): 0a 20 20 20 20 20 20 20 20 20 20 20 00 00 00 fc
[ 98.758] (--) NVIDIA(GPU-0): 00 41 53 34 33 31 35 20 20 20 20 20 20 20 00 e3
[ 98.758] (--) NVIDIA(GPU-0):
[ 98.758] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 98.758] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 98.758] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 98.758] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 98.758] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 98.758] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 98.758] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 98.758] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 98.758] (--) NVIDIA(GPU-0):
[ 98.758] (**) NVIDIA(0): Using HorizSync/VertRefresh ranges from the EDID for display
[ 98.758] (**) NVIDIA(0): device CRT-0 (Using EDID frequencies has been enabled on
[ 98.758] (**) NVIDIA(0): all display devices.)
[ 98.763] (II) NVIDIA(GPU-0): Display (HannStar Display Corp HSD160PHW1 (DFP-0)) does not
[ 98.763] (II) NVIDIA(GPU-0): support NVIDIA 3D Vision stereo.
[ 98.763] (**) NVIDIA(0): Using HorizSync/VertRefresh ranges from the EDID for display
[ 98.764] (**) NVIDIA(0): device HannStar Display Corp HSD160PHW1 (DFP-0) (Using
[ 98.764] (**) NVIDIA(0): EDID frequencies has been enabled on all display
[ 98.764] (**) NVIDIA(0): devices.)
[ 104.130] (WW) NVIDIA(GPU-0): The EDID read for display device CRT-0 is invalid:
[ 104.130] (WW) NVIDIA(GPU-0): unrecognized EDID Header.
[ 104.130] (--) NVIDIA(GPU-0):
[ 104.130] (--) NVIDIA(GPU-0): Raw EDID bytes:
[ 104.130] (--) NVIDIA(GPU-0):
[ 104.130] (--) NVIDIA(GPU-0): fd df fe fe fe fe fe fd 26 cd 50 46 00 00 00 00
[ 104.130] (--) NVIDIA(GPU-0): 28 0c 01 03 0e 22 1b 78 eb a6 9c a1 5a 4b 98 24
[ 104.130] (--) NVIDIA(GPU-0): 16 4c 57 bf ef 00 81 80 81 8f 71 40 71 4f 01 01
[ 104.130] (--) NVIDIA(GPU-0): 01 01 01 01 01 01 30 2a 00 98 51 00 2a 40 30 70
[ 104.130] (--) NVIDIA(GPU-0): 13 00 52 0e 11 00 00 1e 00 00 00 fd 00 32 4b 18
[ 104.130] (--) NVIDIA(GPU-0): 50 0e 00 0a 20 20 20 20 20 20 00 00 00 ff 00 30
[ 104.130] (--) NVIDIA(GPU-0): 0a 20 20 20 20 20 20 20 20 20 20 20 00 00 00 fc
[ 104.130] (--) NVIDIA(GPU-0): 00 41 53 34 33 31 35 20 20 20 20 20 20 20 00 e3
[ 104.130] (--) NVIDIA(GPU-0):
[ 104.130] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 104.130] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 104.130] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 104.130] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 104.130] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 104.130] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 104.130] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 104.130] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 104.130] (--) NVIDIA(GPU-0):
[ 104.130] (**) NVIDIA(0): Using HorizSync/VertRefresh ranges from the EDID for display
[ 104.130] (**) NVIDIA(0): device CRT-0 (Using EDID frequencies has been enabled on
[ 104.130] (**) NVIDIA(0): all display devices.)
[ 104.136] (II) NVIDIA(GPU-0): Display (HannStar Display Corp HSD160PHW1 (DFP-0)) does not
[ 104.136] (II) NVIDIA(GPU-0): support NVIDIA 3D Vision stereo.
[ 104.136] (**) NVIDIA(0): Using HorizSync/VertRefresh ranges from the EDID for display
[ 104.136] (**) NVIDIA(0): device HannStar Display Corp HSD160PHW1 (DFP-0) (Using
[ 104.136] (**) NVIDIA(0): EDID frequencies has been enabled on all display
[ 104.136] (**) NVIDIA(0): devices.)
[ 105.505] (II) NVIDIA(0): Setting mode "LVDS-0: nvidia-auto-select @1366x768 +0+0"
[ 106.888] (II) NVIDIA(0): Setting mode "LVDS-0: nvidia-auto-select @1366x768 +0+0, VGA-0: 800x600_60 @800x600 +1366+0"
[ 107.395] (WW) NVIDIA(GPU-0): The EDID read for display device CRT-0 is invalid:
[ 107.395] (WW) NVIDIA(GPU-0): unrecognized EDID Header.
[ 107.395] (--) NVIDIA(GPU-0):
[ 107.395] (--) NVIDIA(GPU-0): Raw EDID bytes:
[ 107.395] (--) NVIDIA(GPU-0):
[ 107.395] (--) NVIDIA(GPU-0): fd df fe fe fe fe fe fd 26 cd 50 46 00 00 00 00
[ 107.395] (--) NVIDIA(GPU-0): 28 0c 01 03 0e 22 1b 78 eb a6 9c a1 5a 4b 98 24
[ 107.395] (--) NVIDIA(GPU-0): 16 4c 57 bf ef 00 81 80 81 8f 71 40 71 4f 01 01
[ 107.395] (--) NVIDIA(GPU-0): 01 01 01 01 01 01 30 2a 00 98 51 00 2a 40 30 70
[ 107.395] (--) NVIDIA(GPU-0): 13 00 52 0e 11 00 00 1e 00 00 00 fd 00 32 4b 18
[ 107.395] (--) NVIDIA(GPU-0): 50 0e 00 0a 20 20 20 20 20 20 00 00 00 ff 00 30
[ 107.395] (--) NVIDIA(GPU-0): 0a 20 20 20 20 20 20 20 20 20 20 20 00 00 00 fc
[ 107.395] (--) NVIDIA(GPU-0): 00 41 53 34 33 31 35 20 20 20 20 20 20 20 00 e3
[ 107.395] (--) NVIDIA(GPU-0):
[ 107.395] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 107.396] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 107.396] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 107.396] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 107.396] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 107.396] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 107.396] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 107.396] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 107.396] (--) NVIDIA(GPU-0):
[ 107.396] (**) NVIDIA(0): Using HorizSync/VertRefresh ranges from the EDID for display
[ 107.396] (**) NVIDIA(0): device CRT-0 (Using EDID frequencies has been enabled on
[ 107.396] (**) NVIDIA(0): all display devices.)
[ 107.399] (II) NVIDIA(GPU-0): Display (HannStar Display Corp HSD160PHW1 (DFP-0)) does not
[ 107.399] (II) NVIDIA(GPU-0): support NVIDIA 3D Vision stereo.
[ 107.399] (**) NVIDIA(0): Using HorizSync/VertRefresh ranges from the EDID for display
[ 107.399] (**) NVIDIA(0): device HannStar Display Corp HSD160PHW1 (DFP-0) (Using
[ 107.399] (**) NVIDIA(0): EDID frequencies has been enabled on all display
[ 107.399] (**) NVIDIA(0): devices.)
[ 107.585] (WW) NVIDIA(GPU-0): The EDID read for display device CRT-0 is invalid:
[ 107.727] (WW) NVIDIA(GPU-0): unrecognized EDID Header.
[ 107.727] (--) NVIDIA(GPU-0):
[ 107.727] (--) NVIDIA(GPU-0): Raw EDID bytes:
[ 107.727] (--) NVIDIA(GPU-0):
[ 107.727] (--) NVIDIA(GPU-0): fd df fe fe fe fe fe fd 26 cd 50 46 00 00 00 00
[ 107.727] (--) NVIDIA(GPU-0): 28 0c 01 03 0e 22 1b 78 eb a6 9c a1 5a 4b 98 24
[ 107.727] (--) NVIDIA(GPU-0): 16 4c 57 bf ef 00 81 80 81 8f 71 40 71 4f 01 01
[ 107.727] (--) NVIDIA(GPU-0): 01 01 01 01 01 01 30 2a 00 98 51 00 2a 40 30 70
[ 107.727] (--) NVIDIA(GPU-0): 13 00 52 0e 11 00 00 1e 00 00 00 fd 00 32 4b 18
[ 107.727] (--) NVIDIA(GPU-0): 50 0e 00 0a 20 20 20 20 20 20 00 00 00 ff 00 30
[ 107.727] (--) NVIDIA(GPU-0): 0a 20 20 20 20 20 20 20 20 20 20 20 00 00 00 fc
[ 107.727] (--) NVIDIA(GPU-0): 00 41 53 34 33 31 35 20 20 20 20 20 20 20 00 e3
[ 107.727] (--) NVIDIA(GPU-0):
[ 107.727] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 107.727] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 107.727] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 107.727] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 107.727] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 107.727] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 107.727] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 107.727] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 107.727] (--) NVIDIA(GPU-0):
[ 107.727] (**) NVIDIA(0): Using HorizSync/VertRefresh ranges from the EDID for display
[ 107.727] (**) NVIDIA(0): device CRT-0 (Using EDID frequencies has been enabled on
[ 107.727] (**) NVIDIA(0): all display devices.)
[ 107.732] (II) NVIDIA(GPU-0): Display (HannStar Display Corp HSD160PHW1 (DFP-0)) does not
[ 107.732] (II) NVIDIA(GPU-0): support NVIDIA 3D Vision stereo.
[ 107.732] (**) NVIDIA(0): Using HorizSync/VertRefresh ranges from the EDID for display
[ 107.732] (**) NVIDIA(0): device HannStar Display Corp HSD160PHW1 (DFP-0) (Using
[ 107.732] (**) NVIDIA(0): EDID frequencies has been enabled on all display
[ 107.732] (**) NVIDIA(0): devices.)
[ 107.858] (WW) NVIDIA(GPU-0): The EDID read for display device CRT-0 is invalid:
[ 107.858] (WW) NVIDIA(GPU-0): unrecognized EDID Header.
[ 107.858] (--) NVIDIA(GPU-0):
[ 107.858] (--) NVIDIA(GPU-0): Raw EDID bytes:
[ 107.858] (--) NVIDIA(GPU-0):
[ 107.858] (--) NVIDIA(GPU-0): fd df fe fe fe fe fe fd 26 cd 50 46 00 00 00 00
[ 107.858] (--) NVIDIA(GPU-0): 28 0c 01 03 0e 22 1b 78 eb a6 9c a1 5a 4b 98 24
[ 107.858] (--) NVIDIA(GPU-0): 16 4c 57 bf ef 00 81 80 81 8f 71 40 71 4f 01 01
[ 107.858] (--) NVIDIA(GPU-0): 01 01 01 01 01 01 30 2a 00 98 51 00 2a 40 30 70
[ 107.858] (--) NVIDIA(GPU-0): 13 00 52 0e 11 00 00 1e 00 00 00 fd 00 32 4b 18
[ 107.858] (--) NVIDIA(GPU-0): 50 0e 00 0a 20 20 20 20 20 20 00 00 00 ff 00 30
[ 107.858] (--) NVIDIA(GPU-0): 0a 20 20 20 20 20 20 20 20 20 20 20 00 00 00 fc
[ 107.858] (--) NVIDIA(GPU-0): 00 41 53 34 33 31 35 20 20 20 20 20 20 20 00 e3
[ 107.858] (--) NVIDIA(GPU-0):
[ 107.858] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 107.858] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 107.858] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 107.858] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 107.858] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 107.858] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 107.858] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 107.858] (--) NVIDIA(GPU-0): 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 107.858] (--) NVIDIA(GPU-0):
[ 107.858] (**) NVIDIA(0): Using HorizSync/VertRefresh ranges from the EDID for display
[ 107.858] (**) NVIDIA(0): device CRT-0 (Using EDID frequencies has been enabled on
[ 107.858] (**) NVIDIA(0): all display devices.)
[ 107.864] (II) NVIDIA(GPU-0): Display (HannStar Display Corp HSD160PHW1 (DFP-0)) does not
[ 107.864] (II) NVIDIA(GPU-0): support NVIDIA 3D Vision stereo.
[ 107.864] (**) NVIDIA(0): Using HorizSync/VertRefresh ranges from the EDID for display
[ 107.864] (**) NVIDIA(0): device HannStar Display Corp HSD160PHW1 (DFP-0) (Using
[ 107.864] (**) NVIDIA(0): EDID frequencies has been enabled on all display
[ 107.864] (**) NVIDIA(0): devices.)
[ 109.032] (II) NVIDIA(0): Setting mode "LVDS-0: nvidia-auto-select @1366x768 +0+0, VGA-0: nvidia-auto-select @1024x768 +1366+0"
[ 110.378] (II) XKB: reuse xkmfile /var/lib/xkb/server-C814AC61323ADD9F3C69F18721C056518480B483.xkm
Hors ligne
classdroogies
Re : [Résolu] Twinview changement résolution impossible
Le fichier xorg.conf n'est plus indispensable et nvidia utilise de plus en plus xrandr, après le pilote proprio depuis plusieurs versions c'est
D'après ce que je vois il semblerait qu'un des écrans soit mal détecté.
Pour plus d'infos il faudrait le fichier Xorg.0.log, en utilisant le fichier xorg.conf que tu avais mis en place.
Pour le test si tu remplace ceci dans ton ancien xorg.conf :
Option "metamodes" "DFP: nvidia-auto-select +0+0, CRT: nvidia-auto-select +1366+0"
Par :
Option "MetaModes" "LVDS-0: nvidia-auto-select @1366x768 +0+0, VGA-0: nvidia-auto-select @1024x768 +1366+0"
Ca devrait marcher.....
Enfin ça marche déjà de toute façon
Dernière modification par classdroogies (Le 14/01/2013, à 22:36)
Hors ligne
Maisondouf
Re : [Résolu] Twinview changement résolution impossible
C'est sur qu'avec ça, elle va marcher beaucoup moins bien...
[ 95.783] (==) Matched nvidia as autoconfigured driver 0[ 95.783] (==) Matched nouveau as autoconfigured driver 1[ 95.783] (==) Matched nv as autoconfigured driver 2[ 95.783] (==) Matched vesa as autoconfigured driver 3[ 95.783] (==) Matched modesetting as autoconfigured driver 4[ 95.783] (==) Matched fbdev as autoconfigured driver 5
ASUS M5A88-v EVO avec AMD FX(tm)-8120 Eight-Core Processor, OS principal Precise 12.04.1 LTS 63bits½
Bricoleur, menteur, inculte, inadapté social et mythomane, enfin d'après certains....
"the secret of my form is summed up in two words, no sport" (Winston Churchill)
Hors ligne
|
For my Python 2.7.3 project I have a class called custom_date, which has a property called fixed_date:
from datetime import date
class custom_date():
def __init__(self, fixed_date):
self.fixed_date = fixed_date
def __lt__(self, other):
return self.fixed_date < other
#__gt__, __ge__, __le__, __eq__, __ne__ all implemented the same way
My idea is to be able to directly compare custom_date.fixed_date with the builtin date.
Problem
If I compare a custom_date object to a date object, it's fine. However, if I compare a date object to a custom_date, it returns a TypeError
>>> from datetime import date
>>> x = custom_date(date(2013,2,1))
>>> y = date(2013,2,2)
>>> x > y
False
>>> y > x
TypeError: can't compare datetime.date to instance
Is there any way around this?
|
Consider the following Friendship model, where for every friendship made, there is a User who sent the friend request, and a User who received the friend request:
from django.contrib.auth.models import User
class Friendship(models.Model):
sender = models.ForeignKey(User)
receiver = models.ForeignKey(User)
How would I construct a query that would give me all the usernames of the Users who are in a Friendship with, say, user123?
Keep in mind, user123 could be the sender or the receiver of any friendship he is in.
Also, I only want User.username values to be returned, not an entire User object.
So far, I have this clunky half/solution (I'm using list() so that I can add both user123's receiving friends and user123's sending friends, to eventually produce a list of all friends). The problem is, I'm getting all the User objects, and I only want the usernames...and there's gotta be a better way to do this.
friends_a = list(Friendship.objects.filter(sender=user123).values('receiver'))
friends_b = list(Friendship.objects.filter(receiver=user123).values('sender'))
friends_a = [] if not friends_a else friends_a[0].values()
friends_b = [] if not friends_b else friends_b[0].values()
all_friends = friends_a + friends_b
|
JavaScript
one_relic — 2011-07-27T20:46:59-04:00 — #1
First and foremost, I want to state that while I have a basic understanding of javascript, I'm still fairly new to it, so any assistance or advice is greatly appreciated.
I've recently been going through the process of redesigning my website to include some jquery functionality, mainly the use of a background image slider as my primary 'pages' for my website. All of the work I've put in so far has been based off of the great background slider by Marco Kuiper, and uses portions of his original code.
As I was working along with my redesign, I hit a bit of a snag that I can't seem to get past it... Each slide contains a nav bar with text information about that specific slide. As Marco's original code tried to minimize html and keep everything on the css and js side, all of the text for these slides is contained within JSON strings and values within the script.js file (example below).
{
"title" : "Aperture",
"cssclass" : "cam",
"image" : "bg_cam.jpg",
"text" : "In optics, an aperture is a hole or an opening through which light travels. More specifically, the aperture of an optical system is the opening that determines the cone angle of a bundle of rays that come to a focus in the image plane. The aperture determines how collimated the admitted rays are, which is of great importance for the appearance at the image plane. If an aperture is narrow, then highly collimated rays are admitted, resulting in a sharp focus at the image plane.",
"url" : 'http://www.sxc.hu/photo/1270466',
"urltext" : 'View picture'
},
I've been trying to modify this text to include standard html-style elements like <i> and <b>, and font color changes outside of the css, but when I make these changes they simply don't have any effect on the front end version of the design (see the example below):
Is there any way that I can modify this text to include these sort of element changes while it is still contained within the .js file?
Additionally, I am interested in trying to add content (mosiac-style blocks, contact forms, etc.) on top of the backgrounds, but need it to stay specific to certain slides (portfolio work, contact page, etc.). Is this possible with this time of image slider?
Thanks in advance for all of the help and assistance.
ralphm — 2011-07-27T21:11:26-04:00 — #2
Hi one.relic. Welcome to SitePoint.
I'm not qualified to answer your question, but I'll just pick up on this point:
original code tried to minimize html and keep everything on the css and js side, all of the text for these slides is contained within JSON strings and values within the script.js file
It's not a good idea to place page content in a JS file instead of in the HTML. It makes the content very inaccessible, and search engines won't see it either. So I would re-think that strategy.
one_relic — 2011-07-27T21:36:54-04:00 — #3
Thank you for the suggestion Ralph, it's greatly appreciated. I've actually been thinking the same thing honestly, I'm just not sure exactly how to put the page content back into the html file while still maintaining the same look/feel to the js.
ralphm — 2011-07-27T21:40:22-04:00 — #4
I'd suggest getting an alternative that is built as I've suggested. Indeed, all the examples of this I've seen have the content in the HTML. Could you perhaps just use that Mosaic script you linked to? Does it do what you want? If not, could you describe how you want the page to work? I've bookmarked quite a few gallery scripts like this, so I might know of something that does what you want.
E.g. Something like Supersized might fit the bill better.
one_relic — 2011-07-27T21:56:12-04:00 — #5
could you describe how you want the page to work?
Absolutely. Let me go into a bit further detail to see if it makes sense...
I'm re-building my personal portfolio website from the ground up. I want it to have four main [i]pages(/slides)[i]:
• Welcome
• About
• Work/Portfolio
• Contact
I would love for each of the pages/slides to look and act as they do in the original slider link that I posted.
Then on each page/slide, I want to have the ability to add additional content as needed, ie.: Resume and any pertinent information on the 'about' page, portfolio samples and text descriptions on the portfolio page, contact form and 'follow' links on the contact page.
I hope that makes a bit more sense about what I am trying to achieve.
|
If you register a tag like this:
# mytags.py
import datetime
from django import template
register = template.Library()
@register.simple_tag
def my_current_time(format_string):
return datetime.datetime.now().strftime(format_string)
Then use it:
# details.html
{% load mytags %}
{% <check this completion list
It doesn't show up in IntelliSense in the template editor. If you replace
simple_tag
with
tag
or
assignment_tag
, it shows up in completions as expected.
Note: When testing this, it's best to close/reopen the solution after changing the tag code, in order to avoid false positives. I found that if you make it
tag
or
assignment_tag
then change it to
simple_tag
without reloading, it will still show up in completions. But it won't after you reload the solution.
https://docs.djangoproject.com/en/dev/howto/custom-template-tags/
|
How can I print the following lines of code but get a floating point number of of it instead of a rounded int?
print "Math Question: ", 100 - 25 * 3 % 4
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
Division with
from __future__ import divison
or run Python with the
Python3 has this behaviour by default
If you use integers, Python assumes you really mean them to be integers and does integer math. If you use floats, it will do floating point math.
Try something like this to get floating point output:
print 3/4.0
|
What does the TombstonedTaskError mean? It is being raised while trying to add a task to the queue, from a cron-job:
Traceback (most recent call last):
File "/base/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 501, in __call__
handler.get(*groups)
File "/base/data/home/apps/.../tasks.py", line 132, in get
).add(queue_name = 'userfeedcheck')
File "/base/python_lib/versions/1/google/appengine/api/labs/taskqueue/taskqueue.py", line 495, in add
return Queue(queue_name).add(self)
File "/base/python_lib/versions/1/google/appengine/api/labs/taskqueue/taskqueue.py", line 563, in add
self.__TranslateError(e)
File "/base/python_lib/versions/1/google/appengine/api/labs/taskqueue/taskqueue.py", line 619, in __TranslateError
raise TombstonedTaskError(error.error_detail)
TombstonedTaskError
Searching the documentation only has the following to say:
exception TombstonedTaskError(InvalidTaskError)
Task has been tombstoned.
..which isn't particularly helpful.
I couldn't find anything useful in the App Engine code either..
|
I'm writing a computer program to play the word game "Ghost."
Here's how the current programs works:
--User selects a letter (right now it only works if the user moves first)
--Computer has a list of all possible odd-numbered words in its dictionary (this is so that the user will have to complete each word and therefore lose). After each letter the user selects, the list of words that the computer has is trimmed via this loop:
wordList = [w for w in wordList if w.startswith(currentWord)]
so that it only has words in its "wordList" that conform to the currentWord that is collaboratively being spelled.
--The computer then randomly selects a word from its current list of words and returns the appropriate letter of the word via It then updates its list to include the letter it selected via this code sample:
randomnumber = random.randint(0, len(wordList)-1)
currentWord+=wordList[randomnumber][len(currentWord)]
wordList = [w for w in wordList if w.startswith(currentWord)]
--This then continues until either the user spells a word and that is detected via the checkLoss function, or if the computer is unable to continue a word without losing and triggers the checkBluff function. The checkBluff function requires the user to write what word he is thinking to make sure he isn't making one up.
--*HERE'S THE PROBLEM: * obviously, because the computer randomly selects which character to pick there are certain words that will force a loss. For example, if the the first player selects the word "d", there is a very high probability that the computer will select an "e" because there are so many words that have "de" and the very beginning. However, if the user on the third turn selects the letter "e" such that the current spelling is "dee" the computer has no words in its list (there is only one word in the english language that fits that form: 'deed' and it is even-numbered and thus losing), so the bluff function is triggered and the computer loses when the user reveals he was thinking of a real word "deed."
SO, I would like an algorithm that makes the computer think in advance such that it does not ever pick a follow-up letter for which the first player can force a loss. So, if a "d" is picked, the computer should never pick an "e", because that would force a loss with a subequent e. Similarly, if the user selects an "h" the computer should never follow with an "o" because the user can then say "c" which forces a "k" spelling the word "hock."
I cannot think of a way to do this.
If needed, here's the program in its full incarnation:
import os, random, sys, math, string
def checkBluff(currentWord, choice, fullList):
if choice.startswith(currentWord):
#print "this is accurate"
for line in fullList:
if line == choice:
return 1
return 0
def checkLoss(currentWord, fullList):
for line in fullList:
if currentWord == line:
return 1
return 0
def instantiateWordList(dictionary, wordList):
for line in dictionary:
wordList.append(line.strip())
return wordList
def main():
fullDict = open("wordlist.txt", "r") #fullDict contains all possible words
winFirst = open("firstwin.txt", "r") #winFirst contains all odd-numbered words
winSecond = open("secondwin.txt", "r")#winSecond contains all even-numbered words
turn = "Human"
currentWord = ""
wordList = []
fullList= []
bluff = ""
#Instantiates a list with every word for use in evaluating win/loss
for line in fullDict:
fullList.append(line.strip())
#Decide who goes first
choice = raw_input("1. I will go first \n2. I will go second\n>>")[0]
if choice == "1":
wordList = instantiateWordList(winSecond, wordList)
turn == "Human"
else:
wordList = instantiateWordList(winFirst, wordList)
turn == "Computer"
while True:
if turn == "Human":
choice = raw_input("Choose a letter: ")[0]
currentWord+=choice
if checkLoss(currentWord, fullList) == 1:
print "You have lost by spelling the word "+ currentWord
break
print "**Current Word**"+ currentWord
wordList = [w for w in wordList if w.startswith(currentWord)]
turn = "Computer"
if turn == "Computer":
try:
randomnumber = random.randint(0, len(wordList)-1)
currentWord+=wordList[randomnumber][len(currentWord)]
print "I am thinking of the word: "+ str(wordList[randomnumber])
wordList = [w for w in wordList if w.startswith(currentWord)]
print "**Current word**: "+ currentWord
print "length: "+ str(len(wordList))
turn = "Human"
except StandardError:
bluff = raw_input("I call bluff. What word were you thinking of?\n>>")
if checkBluff(currentWord, bluff, fullList) == 1:
print "You actually won!"
break
else:
print "You lost. You lying son of a bitch."
break
if __name__ == "__main__":
main()
|
Cooking with Python, Part 1
Pages: 1, 2
Recipe 5.10: Selecting the nth Smallest Element of a Sequence
Credit: Raymond Hettinger, David Eppstein, Shane Holloway, Chris Perkins
Problem
You need to get from a sequence the nth item in rank order (e.g., the middle item, known as the median). If the sequence was sorted, you would just use seq[n]. But the sequence isn't sorted, and you wonder if you can do better than just sorting it first.
Solution
Perhaps you can do better, if the sequence is big, has been shuffled enough, and comparisons between its items are costly. Sort is very fast, but in the end (when applied to a thoroughly shuffled sequence of length n) it always takes O(nlogn) time, while there exist algorithms that can be used to get the nth smallest element in time O(n). Here is a function with a solid implementation of such an algorithm:
import random
def select(data, n):
" Find the nth rank ordered element (the least value has rank 0). "
# make a new list, deal with <0 indices, check for valid index
data = list(data)
if n<0:
n += len(data)
if not 0 <= n < len(data):
raise ValueError, "can't get rank %d out of %d" % (n, len(data))
# main loop, quicksort-like but with no need for recursion
while True:
pivot = random.choice(data)
pcount = 0
under, over = [ ], [ ]
uappend, oappend = under.append, over.append
for elem in data:
if elem < pivot:
uappend(elem)
elif elem > pivot:
oappend(elem)
else:
pcount += 1
numunder = len(under)
if n < numunder:
data = under
elif n < numunder + pcount:
return pivot
else:
data = over
n -= numunder + pcount
Related Reading
Discussion
This recipe is meant for cases in which repetitions count. For example, the median of the list [1, 1, 1, 2, 3] is 1 because that is the third one of the five items in rank order. If, for some strange reason, you want to discount duplications, you need to reduce the list to its unique items first (e.g., by applying the Recipe 18.1), after which you may want to come back to this recipe.
Input argument data can be any bounded iterable; the recipe starts by calling list on it to ensure that. The algorithm then loops, implementing at each leg a few key ideas: randomly choosing a pivot element; slicing up the list into two parts, made up of the items that are "under" and "over" the pivot respectively; continuing work for the next leg on just one of the two parts, since we can tell which one of them the nth element will be in, and the other part can safely be ignored. The ideas are very close to that in the classic algorithm known as quicksort (except that quicksort cannot ignore either part, and thus must use recursion, or recursion-removal techniques such as keeping an explicit stack, to make sure it deals with both parts).
The random choice of pivot makes the algorithm robust against unfavorable data orderings (the kind that wreak havoc with naive quicksort); this implementation decision costs about log2N calls to random.choice. Another implementation issue worth pointing out is that the recipe counts the number of occurrences of the pivot: this precaution ensures good performance even in the anomalous case where data contains a high number of repetitions of identical values.
Extracting the bound methods .append of lists under and over as local variables uappend and oappend may look like a pointless, if tiny, complication, but it is, in fact, a very important optimization technique in Python. To keep the compiler simple, straightforward, unsurprising, and robust, Python does not hoist constant computations out of loops, nor does it "cache" the results of method lookup. If you call under.append and over.append in the inner loop, you pay the cost of lookup each and every time. If you want something hoisted, hoist it yourself. When you're considering an optimization, you should always measure the code's performance with and without that optimization, to check that the optimization does indeed make an important difference. According to my measurements, removing this single optimization slows performance down by about 50% for the typical task of picking the 5000th item of range(10000). Considering the tiny amount of complication involved, a difference of 50% is well worth it.
A natural idea for optimization, which just didn't make the grade once carefully measured, is to call cmp(elem, pivot) in the loop body, rather than making separate tests for elem < pivot and elem > pivot. Unfortunately, measurement shows that cmp doesn't speed things up; in fact, it slows them down, at least when the items of data are of elementary types such as numbers and strings.
So, how does select's performance compare with the simpler alternative of:
def selsor(data, n):
data = list(data)
data.sort( )
return data[n]
On thoroughly shuffled lists of 3,001 integers on my machine, this recipe's select takes about 16 milliseconds to find the median, while selsor takes about 13 milliseconds; considering that sort could take advantage of any partial sortedness in the data, for this kind of length, and on elementary data whose comparisons are fast, it's not to your advantage to use select. For a length of 30,001, performance becomes very close between the two approaches—around 170 milliseconds either way. When you push the length all the way to 300,001, select provides an advantage, finding the median in about 2.2 seconds, while selsor takes about 2.5.
The break-even point will be smaller if the items in the sequence have costly comparison methods, since the key difference between the two approaches is in the number of comparisons performed--select takes O(n), selsor takes O(n log n). For example, say we need to compare instances of a class designed for somewhat costly comparisons (simulating four-dimensional points that will often coincide on the first few dimensions):
class X(object):
def _ _init_ _(self):
self.a = self.b = self.c = 23.51
self.d = random.random( )
def _dats(self):
return self.a, self.b, self.c, self.d
def _ _cmp_ _(self, oth):
return cmp(self._dats, oth._dats)
Here, select already becomes faster than selsor when what we're computing is the median of vectors of 201 such instances.
In other words, although select has more general overhead, when compared to the wondrously efficient coding of lists' sort method, nevertheless, if n is large enough and each comparison is costly enough, select is still well worth considering.
See Also
Library Reference and Python in a Nutshell docs about method sort of type list, and about module random.
View catalog information for Python Cookbook, Second Edition
Return to Python DevCenter.
|
Tagged: portfolio tags
AuthorPosts
May 9, 2013 at 3:23 am #23012
Hi Guys,
One small thing, I followed this thread.. [ http://www.kriesi.at/support/topic/view-portfolio-entries-based-on-tags ] to get the tags working on Portfolio entries, the code Nick provided is fine and I’m able to add tags in the backend to portfolio items, However, I cannot get them displayed on the front end.
I’ve followed the WP codex and added the following code:
<?php the_tags(‘<span>Tags: </span>’,’ • ‘,’
‘); ?>
And they’re not showing up, I’ve also tried following this thread [ http://www.kriesi.at/support/topic/add-tags-for-portfolio-posts ] and nothing yet.
Can you please advice how to get the Portfolio Tags displayed on the front end using the code Nick provided?
Cheers,
-A
May 9, 2013 at 8:24 am #118229
Open up wp-contentthemesangularincludesloop-portfolio-single.php and replace
the_content(__('Read more →','avia_framework'));
with
the_content(__('Read more →','avia_framework'));
the_tags('<strong>'.__('Tags:','avia_framework').'</strong><span> ');
This will add the tags to the single portfolio entry page. If you want to use the ajax portfolio modify wp-contentthemesangularincludeshelper-templates.php instead.
May 9, 2013 at 3:13 pm #118230
Thanks Dude,
But it seems the tags still not appear, let me clarify – there were several posts on this topic in the forum that I was able to get them displayed but when the tags were clicked they returned 404 page not found error, then Nick provided the a code that will set the portfolio tags apart from the default wp posts tags, the other member i assume got it working..
Are you sure this should work with Nick’s code? [ http://www.kriesi.at/support/topic/view-portfolio-entries-based-on-tags ] (you can see it at the bottom)
Sorry, I just cant see them, though I did add tags and i can clearly see them in the backend
Thanks again,
-A
May 10, 2013 at 4:19 pm #118231
Can we view a portfolio item on your site live? That is the default wordpress code for spitting out the tags. If its in an ajax portfolio (where the portfolio item opens on the same page) you’ll need to do as Dude said and add the above code to your helper-templates.php file as well as the single portfolio loop.
Regards,
Devin
May 11, 2013 at 3:53 am #118232
Hi Devin,
Sure, but warning you buddy as the site is in Hebrew and is fully loaded – It’s almost a year since we started getting it up and running fast and now there no turning back so we have to continue work with the theme, back then the Angular was one of the first themes that offered responsive design + the drag&drop template builder which was (and still) a big plus for us – obviously now there are other frameworks that will more suite for the job – but for now we’ll have to settle for this one.
Anyhow here is the link, and I added some txt where i pasted the code provided..
Also, I’ve just added the Facebook comments plugin and activated the comments for single-portfolio and for some reason the comments are being duplicated at the bottom of the page, any ideas on that? though i think it’s related to ACF(advanced custom fields) plugin that is being used on single-portfolio..
Many Thanks,
-A
May 13, 2013 at 9:23 am #118233
I just noticed that Nicks code registers a new taxonomy and this taxonomy won’t work with the_tags(). You need to use the standard “post_tag” taxonomy instead. Open up wp-contentthemesangularincludesadminregister-portfolio.php and replace:
$args = array(
'labels' => $labels,
'public' => true,
'show_ui' => true,
'capability_type' => 'post',
'hierarchical' => false,
'rewrite' => array('slug'=>$slugRule,'with_front'=>true),
'query_var' => true,
'show_in_nav_menus'=> false,
'supports' => array('title','thumbnail','excerpt','editor','comments')
);
with
$args = array(
'labels' => $labels,
'public' => true,
'show_ui' => true,
'capability_type' => 'post',
'hierarchical' => false,
'rewrite' => array('slug'=>$slugRule,'with_front'=>true),
'query_var' => true,
'taxonomies' => array('post_tag'),
'show_in_nav_menus'=> false,
'supports' => array('title','thumbnail','excerpt','editor','comments')
);
May 14, 2013 at 1:58 pm #118234
Thanks Dude,
but still after replacing the code above with the one i had (which was the same) still not showing the tags on the page.
If you mean that i should NOT use Nick’s “Portfolio Tags” code which created another Portfolio ‘Meta Box’ in the portfolio WP editor and just use the standard Tags meta box then the tags are indeed are shown and displayed in the front end, however clicking on any of them returns “Nothing found” – “message and that their are no posts matched your criteria” as you can see over here:
http://www.theterminal.co.il/packages/טיול-גיפים-בצפון-תאילנד-רד-בריק-red-brick/ (you can see the tags shown below)
Please help..
Cheers,
-A
May 14, 2013 at 2:26 pm #118235
That’s a problem of the wp query: http://wordpress.org/support/topic/custom-post-type-tagscategories-archive-page – use following code (insert it at the bottom of functions.php) to fix it:
if(!function_exists('avia_fix_tag_archive_page'))
{
function avia_fix_tag_archive_page($query) {
$post_types = get_post_types();
if ( is_category() || is_tag()) {
$post_type = get_query_var(get_post_type());
if ($post_type) {
$post_type = $post_type;
} else {
$post_type = $post_types;
}
$query->set('post_type', $post_type);
return $query;
}
}
add_filter('pre_get_posts', 'avia_fix_tag_archive_page');
}
May 14, 2013 at 4:23 pm #118236
Related question about the tags, or faceted navigation of portfolio items. My portfolio currently has 43 items, which means the portfolio items are displayed on three pages (pagination of pages with portfolio items). For a long time I could not figure out why the tags were not working, but today I figured out the issue. At least on my site, the tags/faceted navigation only work with the portfolio items on the current page loaded in the browser, but not the other portfolio items on the other pages.
The first page of portfolio items loads by default. If someone clicks on a tag, depending on the tag, it may appear that I have no projects for that tag, when I do, but they are on the other pages. Potential employers & clients might not go further than just clicking on the tag on the first page. It would be fantastic if a user could click on a tag, and have all of the matching portfolio items be listed, not just those on the current page loaded in the browser.
How can I get the tags to work with all of the portfolio items, and not just those shown on a single page?
May 14, 2013 at 10:24 pm #118237
Thanks Dude for your efforts, appreciated! this works just fine…
I guess I should ignore the other Portfolio Meta Box that Nick’s code registered, and use the standard wp tags? I’m not really interested to use the blog or blog posts so there is no need really to have separate tags for each post type.
Thanks again..
-A
May 15, 2013 at 4:37 am #118238
AuthorPosts
The topic ‘PORTFOLIO TAGS’ is closed to new replies.
|
I am having an issue on saving my model, my UserProfile reference on a foreign key to a Customer, and I have gotten sure that my form in sending the needed info and the customer object is being loaded, however when I save my model, this lost the reference to customer
My code is
models.py
from django.db import models
from customers.models import Customer
from django.contrib.auth.models import User, Group
from django.contrib.sites.models import Site
from anfitrion.models import ModelBase
from django.db.models.signals import post_save
class UserProfile(ModelBase):
user = models.OneToOneField(User)
customer = models.ForeignKey(Customer)
address = models.CharField(max_length = 255)
phone_home = models.CharField(max_length = 16)
phone_office = models.CharField(max_length = 16)
expiration = models.DateTimeField(null=True, blank=True)
picture = models.ImageField(upload_to='profiles/%Y/%m/%d')
observations = models.TextField(null=True, blank=True)
status = models.BooleanField()
def __str__(self):
return "%s's profile" % self.user
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile, created = UserProfile.objects.get_or_create(user=instance)
post_save.connect(create_user_profile, sender=User)
class SiteProfile(ModelBase):
site = models.OneToOneField(Site)
def __str__(self):
return "%s's profile" % self.user
def create_site_profile(sender, instance, created, **kwargs):
if created:
profile, created = SiteProfile.objects.get_or_create(site=instance)
post_save.connect(create_site_profile, sender=Site)
function running the saveing
def users_save (request):
#try:
if request.is_ajax() and request.POST:
user_id = request.POST['user_id']
s = get_current_site(request)
u = User (
username = request.POST['username'],
first_name = request.POST['first_name'],
last_name = request.POST['last_name'],
email = request.POST['email']
)
u.set_password(request.POST['password'])
c = None
if int( request.POST['customer_id'] ) > 0:
c = Customer.objects.get(id=request.POST['customer_id'])
up = UserProfile(
customer = c,
address = request.POST['address'],
phone_home = request.POST['phone_home'],
phone_office = request.POST['phone_office']
)
up.user = u
u.save()
if int( request.POST['group_id'] ) > 0:
g = Group.objects.get( id = request.POST['group_id'] )
g.user_set.add(u)
return HttpResponse(1, mimetype='application/json')
|
malbo
[Tuto] identifier si on est dans un système UEFI ou Bios
ATTENTION : CETTE MÉTHODE D’IDENTIFICATION EST OBSOLÈTE : IL FAUT UTILISER LA PROCÉDURE DE LA DOC : http://doc.ubuntu-fr.org/efi#identifier … n_mode_efi
Le problème se pose pour des PC achetés en 2011 (et +) pour ceux qui souhaitent faire cohabiter Windows préinstallé et Ubuntu dans leur PC.
Il y a plusieurs façon d'installer Ubuntu et, suivant le support d'installation (live-CD, une clé USB, autre...), il est possible qu'on ne sache pas si on s'apprête à installer dans un système Bios (classique) ou dans un système UEFI (successeur du Bios). Pour compliquer la chose, certaines carte-mères disposent d'un machin qui est compatible des deux modes et qui propose au choix à l'utilisateur de voir un live-CD en environnement Bios (souvent nommé "Legacy Bios") ou bien en environnement UEFI. Oui, ça sent bien le pâté.
J'indique ci-dessous le moyen de vérifier ce qu'il en est avant de se lancer dans l'installation proprement dite. A signaler : j'ai pompé la méthode de l'expert srs5694 du forum anglais : http://ubuntuforums.org/showpost.php?p= … ostcount=4
Depuis la session live de Ubuntu 11.10 (essai sans installer), passer cette commande dans un terminal (il y a une commande alternative proposée dans le post #26 par YannUbuntu) :Attention : cette commande pour déterminer si on est en session EFI (ou pas) est obsolète pour Ubuntu 12.10. Il faut utiliser la procédure de la doc : http://doc.ubuntu-fr.org/efi#identifier … n_mode_efi
dmesg | grep EFI
Cette commande ne présente aucun danger : elle demande d'afficher dans le terminal toutes les lignes qui mentionnent "EFI" dans le fichier log du démarrage de Ubuntu.
------------------------------------------------------------------------------------------------------------------------------------------------------CAS 1 : SI UBUNTU EST ACTUELLEMENT DÉMARRÉ EN SESSION LIVE DANS UN SYSTÈME BIOS CLASSIQUE
voici le résultat que vous obtenez :
dmesg | grep EFI
[ 1.241248] EFI Variables Facility v0.08 2004-May-17
Ou encore ce genre de lignes (s'il s'agit d'un PC récent équipé d'un système UEFI) :
dmesg | grep EFI
[ 0.000000] ACPI: UEFI 00000000bafe7000 0003E (v01 DELL QA09 00000002 PTL 00000002)
[ 0.000000] ACPI: UEFI 00000000bafe6000 00042 (v01 PTL COMBUF 00000001 PTL 00000001)
[ 0.000000] ACPI: UEFI 00000000bafe5000 00256 (v01 DELL QA09 00000002 PTL 00000002)
Bien que le terme "UEFI" soit mentionné, le PC est démarré en mode "Bios" classique (et pas en mode EFI) à condition qu'il n'y ait pas plusieurs lignes comportant "EFI: mem" qui précèdent les lignes "ACPI: UEFI" (si on a la présence de lignes "EFI: mem", on est dans le CAS 2 ci-après)
------------------------------------------------------------------------------------------------------------------------------------------------------
CAS 2 : SI UBUNTU EST ACTUELLEMENT DÉMARRÉ EN SESSION LIVE DANS UN SYSTÈME UEFI :
Voici le genre de résultat, avec plusieurs lignes comportant "EFI: mem" (c'est le mapping de la mémoire) :Attention : cette commande pour déterminer si on est en session EFI (ou pas) est obsolète pour Ubuntu 12.10. Il faut utiliser la procédure de la doc : http://doc.ubuntu-fr.org/efi#identifier … n_mode_efi
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
A signaler : quand on est dans ce CAS 2, le live CD Ubuntu ne démarre pas comme habituellement. Il propose un menu Grub comme sur cette vue :
---------------------------------------------------------------------------------------------------------------------------------------------------------------
QU'EST-CE QU'ON EN FAIT ?
Si vous êtes dans le CAS 1, vous vous apprêtez à installer Ubuntu de façon classique. C'est sympa ? Pas forcément parce que ça dépend des goûts et des habitudes : si Windows est préinstallé en mode UEFI et que vous installez Ubuntu en mode Bios, il faudra passer par le "Bios" ( ou ce qui en tient lieu sur votre PC) pour passer par Ubuntu ou par Windows (pas de menu Grub proposant le dual-boot). C'est ce qui est arrivé à Ayu qui n'apprécie pas cette situation : http://forum.ubuntu-fr.org/viewtopic.php?id=738321
Si vous êtes dans le CAS 2, vous vous apprêtez à installer en mode UEFI. Je ne sais pas bien à l'heure actuelle (j'apprends) si le dual-boot géré par Grub sera possible dans tous les cas. Je veux dire qu'il faudra peut-être passer par le "Bios" pour certaines config ( ce qui n'est pas non plus une tragédie : il me semble que ces nouveaux "Bios" sont faits pour être vus et utilisés fréquemment alors que le vieux Bios était peu visité par le quidam ). Ce que je sais, c'est que la doc suivante ne vous concerne plus (vous allez utiliser grub-efi, pas grub-pc) : http://doc.ubuntu-fr.org/grub-pc
Et pleins d'autres doc du site - relatives au Bios - sont obsolètes pour vous. C'est le progrès.
Dernière modification par malbo (Le 30/10/2012, à 12:40)
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
azdep
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Bonjour,
Avec mon portable Asus, le livecd francophone 12.04 Desktop 64bits ne reconnait pas l'uefi, j'ai du utilisé le cd ubuntu.com.
Hors ligne
YannUbuntu
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Bonjour,
Avec mon portable Asus, le livecd francophone 12.04 Desktop 64bits ne reconnait pas l'uefi, j'ai du utilisé le cd ubuntu.com.
Bonjour
Pouvez-vous indiquer le résultat de "dmesg | grep EFI" saisi dans chacun des live-CD svp ?
Hors ligne
azdep
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Bonjour,
en fait j'ai rebooter sur chacun des livecd, et la chose est plus subtile que je le pensais.
Avec le livecd francophe :
J'appuie sur ECHAP au démarrage pour avoir le bootmenu, dans la liste apparait entre autre P2:MASHITA........., que je sélectionne.
Le résultat de dmesg | grep EFI :
[ 4.832430] EFI Variables Facility v0.08 2004-May-17
Avec le livecd "original" :
J'appuie sur ECHAP au démarrage pour avoir le bootmenu, dans la liste apparait entre
- P2:MASHITA...... et
- UEFI P2:MASHITA.....
si je sélectionne le premier j'ai la même réponse à la commande dmesg.
Par contre si je sélectionne le second j'ai :
[ 0.000000] EFI v2.31 by American Megatrends
[ 0.000000] Kernel-defined memdesc doesn't match the one from EFI!
[ 0.000000] EFI: mem00: type=3, attr=0xf, range=[0x0000000000000000-0x0000000000008000) (0MB)
[ 0.000000] EFI: mem01: type=7, attr=0xf, range=[0x0000000000008000-0x000000000004e000) (0MB)
[ 0.000000] EFI: mem02: type=4, attr=0xf, range=[0x000000000004e000-0x0000000000060000) (0MB)
[ 0.000000] EFI: mem03: type=3, attr=0xf, range=[0x0000000000060000-0x000000000009f000) (0MB)
[ 0.000000] EFI: mem04: type=6, attr=0x800000000000000f, range=[0x000000000009f000-0x00000000000a0000) (0MB)
[ 0.000000] EFI: mem05: type=2, attr=0xf, range=[0x0000000000100000-0x00000000005b9000) (4MB)
[ 0.000000] EFI: mem06: type=7, attr=0xf, range=[0x00000000005b9000-0x0000000001000000) (10MB)
[ 0.000000] EFI: mem07: type=2, attr=0xf, range=[0x0000000001000000-0x0000000001100000) (1MB)
[ 0.000000] EFI: mem08: type=7, attr=0xf, range=[0x0000000001100000-0x0000000008000000) (111MB)
[ 0.000000] EFI: mem09: type=4, attr=0xf, range=[0x0000000008000000-0x0000000008837000) (8MB)
[ 0.000000] EFI: mem10: type=3, attr=0xf, range=[0x0000000008837000-0x0000000008839000) (0MB)
[ 0.000000] EFI: mem11: type=4, attr=0xf, range=[0x0000000008839000-0x0000000008882000) (0MB)
[ 0.000000] EFI: mem12: type=3, attr=0xf, range=[0x0000000008882000-0x0000000008886000) (0MB)
[ 0.000000] EFI: mem13: type=4, attr=0xf, range=[0x0000000008886000-0x000000000888b000) (0MB)
[ 0.000000] EFI: mem14: type=3, attr=0xf, range=[0x000000000888b000-0x000000000888c000) (0MB)
[ 0.000000] EFI: mem15: type=4, attr=0xf, range=[0x000000000888c000-0x000000000888e000) (0MB)
[ 0.000000] EFI: mem16: type=3, attr=0xf, range=[0x000000000888e000-0x000000000888f000) (0MB)
[ 0.000000] EFI: mem17: type=4, attr=0xf, range=[0x000000000888f000-0x0000000008892000) (0MB)
[ 0.000000] EFI: mem18: type=3, attr=0xf, range=[0x0000000008892000-0x00000000088a2000) (0MB)
[ 0.000000] EFI: mem19: type=4, attr=0xf, range=[0x00000000088a2000-0x0000000008ca5000) (4MB)
[ 0.000000] EFI: mem20: type=3, attr=0xf, range=[0x0000000008ca5000-0x0000000008ca6000) (0MB)
[ 0.000000] EFI: mem21: type=4, attr=0xf, range=[0x0000000008ca6000-0x0000000008caa000) (0MB)
[ 0.000000] EFI: mem22: type=3, attr=0xf, range=[0x0000000008caa000-0x0000000008cab000) (0MB)
[ 0.000000] EFI: mem23: type=4, attr=0xf, range=[0x0000000008cab000-0x0000000008cb0000) (0MB)
[ 0.000000] EFI: mem24: type=3, attr=0xf, range=[0x0000000008cb0000-0x0000000008cb1000) (0MB)
[ 0.000000] EFI: mem25: type=4, attr=0xf, range=[0x0000000008cb1000-0x0000000008cb2000) (0MB)
[ 0.000000] EFI: mem26: type=3, attr=0xf, range=[0x0000000008cb2000-0x0000000008cb5000) (0MB)
[ 0.000000] EFI: mem27: type=4, attr=0xf, range=[0x0000000008cb5000-0x0000000008cb7000) (0MB)
[ 0.000000] EFI: mem28: type=3, attr=0xf, range=[0x0000000008cb7000-0x0000000008cb8000) (0MB)
[ 0.000000] EFI: mem29: type=4, attr=0xf, range=[0x0000000008cb8000-0x0000000008cc4000) (0MB)
[ 0.000000] EFI: mem30: type=3, attr=0xf, range=[0x0000000008cc4000-0x0000000008cc8000) (0MB)
[ 0.000000] EFI: mem31: type=4, attr=0xf, range=[0x0000000008cc8000-0x0000000008cc9000) (0MB)
[ 0.000000] EFI: mem32: type=3, attr=0xf, range=[0x0000000008cc9000-0x0000000008cca000) (0MB)
[ 0.000000] EFI: mem33: type=4, attr=0xf, range=[0x0000000008cca000-0x0000000008cd6000) (0MB)
[ 0.000000] EFI: mem34: type=3, attr=0xf, range=[0x0000000008cd6000-0x0000000008cd9000) (0MB)
[ 0.000000] EFI: mem35: type=4, attr=0xf, range=[0x0000000008cd9000-0x0000000008cda000) (0MB)
[ 0.000000] EFI: mem36: type=3, attr=0xf, range=[0x0000000008cda000-0x0000000008cdc000) (0MB)
[ 0.000000] EFI: mem37: type=4, attr=0xf, range=[0x0000000008cdc000-0x0000000008cde000) (0MB)
[ 0.000000] EFI: mem38: type=3, attr=0xf, range=[0x0000000008cde000-0x0000000008cdf000) (0MB)
[ 0.000000] EFI: mem39: type=4, attr=0xf, range=[0x0000000008cdf000-0x0000000008cee000) (0MB)
[ 0.000000] EFI: mem40: type=3, attr=0xf, range=[0x0000000008cee000-0x0000000008cef000) (0MB)
[ 0.000000] EFI: mem41: type=4, attr=0xf, range=[0x0000000008cef000-0x0000000008cf7000) (0MB)
[ 0.000000] EFI: mem42: type=3, attr=0xf, range=[0x0000000008cf7000-0x0000000008cfb000) (0MB)
[ 0.000000] EFI: mem43: type=4, attr=0xf, range=[0x0000000008cfb000-0x0000000008d03000) (0MB)
[ 0.000000] EFI: mem44: type=3, attr=0xf, range=[0x0000000008d03000-0x0000000008d06000) (0MB)
[ 0.000000] EFI: mem45: type=4, attr=0xf, range=[0x0000000008d06000-0x0000000008d0b000) (0MB)
[ 0.000000] EFI: mem46: type=3, attr=0xf, range=[0x0000000008d0b000-0x0000000008d0c000) (0MB)
[ 0.000000] EFI: mem47: type=4, attr=0xf, range=[0x0000000008d0c000-0x0000000008d0e000) (0MB)
[ 0.000000] EFI: mem48: type=3, attr=0xf, range=[0x0000000008d0e000-0x0000000008d12000) (0MB)
[ 0.000000] EFI: mem49: type=4, attr=0xf, range=[0x0000000008d12000-0x0000000008d76000) (0MB)
[ 0.000000] EFI: mem50: type=3, attr=0xf, range=[0x0000000008d76000-0x0000000008d77000) (0MB)
[ 0.000000] EFI: mem51: type=4, attr=0xf, range=[0x0000000008d77000-0x0000000008d78000) (0MB)
[ 0.000000] EFI: mem52: type=3, attr=0xf, range=[0x0000000008d78000-0x0000000008d79000) (0MB)
[ 0.000000] EFI: mem53: type=4, attr=0xf, range=[0x0000000008d79000-0x0000000008d83000) (0MB)
[ 0.000000] EFI: mem54: type=3, attr=0xf, range=[0x0000000008d83000-0x0000000008d88000) (0MB)
[ 0.000000] EFI: mem55: type=4, attr=0xf, range=[0x0000000008d88000-0x0000000008d9e000) (0MB)
[ 0.000000] EFI: mem56: type=3, attr=0xf, range=[0x0000000008d9e000-0x0000000008d9f000) (0MB)
[ 0.000000] EFI: mem57: type=4, attr=0xf, range=[0x0000000008d9f000-0x0000000008da1000) (0MB)
[ 0.000000] EFI: mem58: type=3, attr=0xf, range=[0x0000000008da1000-0x0000000008dab000) (0MB)
[ 0.000000] EFI: mem59: type=4, attr=0xf, range=[0x0000000008dab000-0x0000000008dba000) (0MB)
[ 0.000000] EFI: mem60: type=3, attr=0xf, range=[0x0000000008dba000-0x0000000008dbe000) (0MB)
[ 0.000000] EFI: mem61: type=4, attr=0xf, range=[0x0000000008dbe000-0x0000000008dc8000) (0MB)
[ 0.000000] EFI: mem62: type=3, attr=0xf, range=[0x0000000008dc8000-0x0000000008dc9000) (0MB)
[ 0.000000] EFI: mem63: type=4, attr=0xf, range=[0x0000000008dc9000-0x0000000008dcd000) (0MB)
[ 0.000000] EFI: mem64: type=3, attr=0xf, range=[0x0000000008dcd000-0x0000000008dd3000) (0MB)
[ 0.000000] EFI: mem65: type=4, attr=0xf, range=[0x0000000008dd3000-0x0000000008ddd000) (0MB)
[ 0.000000] EFI: mem66: type=3, attr=0xf, range=[0x0000000008ddd000-0x0000000008de2000) (0MB)
[ 0.000000] EFI: mem67: type=4, attr=0xf, range=[0x0000000008de2000-0x0000000008de6000) (0MB)
[ 0.000000] EFI: mem68: type=3, attr=0xf, range=[0x0000000008de6000-0x0000000008dea000) (0MB)
[ 0.000000] EFI: mem69: type=4, attr=0xf, range=[0x0000000008dea000-0x0000000008df1000) (0MB)
[ 0.000000] EFI: mem70: type=3, attr=0xf, range=[0x0000000008df1000-0x0000000008df3000) (0MB)
[ 0.000000] EFI: mem71: type=4, attr=0xf, range=[0x0000000008df3000-0x0000000008df4000) (0MB)
[ 0.000000] EFI: mem72: type=3, attr=0xf, range=[0x0000000008df4000-0x0000000008dfa000) (0MB)
[ 0.000000] EFI: mem73: type=4, attr=0xf, range=[0x0000000008dfa000-0x0000000008dfb000) (0MB)
[ 0.000000] EFI: mem74: type=3, attr=0xf, range=[0x0000000008dfb000-0x0000000008dfd000) (0MB)
[ 0.000000] EFI: mem75: type=4, attr=0xf, range=[0x0000000008dfd000-0x0000000008e07000) (0MB)
[ 0.000000] EFI: mem76: type=3, attr=0xf, range=[0x0000000008e07000-0x0000000008e0c000) (0MB)
[ 0.000000] EFI: mem77: type=4, attr=0xf, range=[0x0000000008e0c000-0x0000000008e0d000) (0MB)
[ 0.000000] EFI: mem78: type=3, attr=0xf, range=[0x0000000008e0d000-0x0000000008e0e000) (0MB)
[ 0.000000] EFI: mem79: type=4, attr=0xf, range=[0x0000000008e0e000-0x0000000008e0f000) (0MB)
[ 0.000000] EFI: mem80: type=3, attr=0xf, range=[0x0000000008e0f000-0x0000000008e11000) (0MB)
[ 0.000000] EFI: mem81: type=4, attr=0xf, range=[0x0000000008e11000-0x0000000008e14000) (0MB)
[ 0.000000] EFI: mem82: type=3, attr=0xf, range=[0x0000000008e14000-0x0000000008e15000) (0MB)
[ 0.000000] EFI: mem83: type=4, attr=0xf, range=[0x0000000008e15000-0x0000000008e1a000) (0MB)
[ 0.000000] EFI: mem84: type=3, attr=0xf, range=[0x0000000008e1a000-0x0000000008e1c000) (0MB)
[ 0.000000] EFI: mem85: type=4, attr=0xf, range=[0x0000000008e1c000-0x0000000008e21000) (0MB)
[ 0.000000] EFI: mem86: type=3, attr=0xf, range=[0x0000000008e21000-0x0000000008e22000) (0MB)
[ 0.000000] EFI: mem87: type=4, attr=0xf, range=[0x0000000008e22000-0x0000000008e30000) (0MB)
[ 0.000000] EFI: mem88: type=3, attr=0xf, range=[0x0000000008e30000-0x0000000008e33000) (0MB)
[ 0.000000] EFI: mem89: type=4, attr=0xf, range=[0x0000000008e33000-0x0000000008e44000) (0MB)
[ 0.000000] EFI: mem90: type=3, attr=0xf, range=[0x0000000008e44000-0x0000000008e4e000) (0MB)
[ 0.000000] EFI: mem91: type=4, attr=0xf, range=[0x0000000008e4e000-0x0000000008e51000) (0MB)
[ 0.000000] EFI: mem92: type=3, attr=0xf, range=[0x0000000008e51000-0x0000000008e54000) (0MB)
[ 0.000000] EFI: mem93: type=4, attr=0xf, range=[0x0000000008e54000-0x0000000008e5f000) (0MB)
[ 0.000000] EFI: mem94: type=3, attr=0xf, range=[0x0000000008e5f000-0x0000000008e61000) (0MB)
[ 0.000000] EFI: mem95: type=4, attr=0xf, range=[0x0000000008e61000-0x0000000008e62000) (0MB)
[ 0.000000] EFI: mem96: type=3, attr=0xf, range=[0x0000000008e62000-0x0000000008e67000) (0MB)
[ 0.000000] EFI: mem97: type=4, attr=0xf, range=[0x0000000008e67000-0x0000000008e76000) (0MB)
[ 0.000000] EFI: mem98: type=3, attr=0xf, range=[0x0000000008e76000-0x0000000008e7c000) (0MB)
[ 0.000000] EFI: mem99: type=4, attr=0xf, range=[0x0000000008e7c000-0x0000000008e86000) (0MB)
[ 0.000000] EFI: mem100: type=3, attr=0xf, range=[0x0000000008e86000-0x0000000008e89000) (0MB)
[ 0.000000] EFI: mem101: type=4, attr=0xf, range=[0x0000000008e89000-0x0000000008e91000) (0MB)
[ 0.000000] EFI: mem102: type=3, attr=0xf, range=[0x0000000008e91000-0x0000000008e95000) (0MB)
[ 0.000000] EFI: mem103: type=4, attr=0xf, range=[0x0000000008e95000-0x0000000008eae000) (0MB)
[ 0.000000] EFI: mem104: type=3, attr=0xf, range=[0x0000000008eae000-0x0000000008eaf000) (0MB)
[ 0.000000] EFI: mem105: type=4, attr=0xf, range=[0x0000000008eaf000-0x0000000008eb4000) (0MB)
[ 0.000000] EFI: mem106: type=3, attr=0xf, range=[0x0000000008eb4000-0x0000000008ec7000) (0MB)
[ 0.000000] EFI: mem107: type=4, attr=0xf, range=[0x0000000008ec7000-0x0000000008ecd000) (0MB)
[ 0.000000] EFI: mem108: type=3, attr=0xf, range=[0x0000000008ecd000-0x0000000008ed0000) (0MB)
[ 0.000000] EFI: mem109: type=4, attr=0xf, range=[0x0000000008ed0000-0x0000000008ed6000) (0MB)
[ 0.000000] EFI: mem110: type=3, attr=0xf, range=[0x0000000008ed6000-0x0000000008ed8000) (0MB)
[ 0.000000] EFI: mem111: type=4, attr=0xf, range=[0x0000000008ed8000-0x0000000008ed9000) (0MB)
[ 0.000000] EFI: mem112: type=3, attr=0xf, range=[0x0000000008ed9000-0x0000000008edc000) (0MB)
[ 0.000000] EFI: mem113: type=4, attr=0xf, range=[0x0000000008edc000-0x0000000008ef5000) (0MB)
[ 0.000000] EFI: mem114: type=3, attr=0xf, range=[0x0000000008ef5000-0x0000000008ef6000) (0MB)
[ 0.000000] EFI: mem115: type=4, attr=0xf, range=[0x0000000008ef6000-0x0000000008f00000) (0MB)
[ 0.000000] EFI: mem116: type=3, attr=0xf, range=[0x0000000008f00000-0x0000000008f04000) (0MB)
[ 0.000000] EFI: mem117: type=4, attr=0xf, range=[0x0000000008f04000-0x0000000008f07000) (0MB)
[ 0.000000] EFI: mem118: type=3, attr=0xf, range=[0x0000000008f07000-0x0000000008f1b000) (0MB)
[ 0.000000] EFI: mem119: type=4, attr=0xf, range=[0x0000000008f1b000-0x0000000008f28000) (0MB)
[ 0.000000] EFI: mem120: type=3, attr=0xf, range=[0x0000000008f28000-0x0000000008f30000) (0MB)
[ 0.000000] EFI: mem121: type=4, attr=0xf, range=[0x0000000008f30000-0x0000000008f32000) (0MB)
[ 0.000000] EFI: mem122: type=3, attr=0xf, range=[0x0000000008f32000-0x0000000008f34000) (0MB)
[ 0.000000] EFI: mem123: type=4, attr=0xf, range=[0x0000000008f34000-0x0000000008f37000) (0MB)
[ 0.000000] EFI: mem124: type=3, attr=0xf, range=[0x0000000008f37000-0x0000000008f4c000) (0MB)
[ 0.000000] EFI: mem125: type=4, attr=0xf, range=[0x0000000008f4c000-0x0000000008f54000) (0MB)
[ 0.000000] EFI: mem126: type=3, attr=0xf, range=[0x0000000008f54000-0x0000000008f59000) (0MB)
[ 0.000000] EFI: mem127: type=4, attr=0xf, range=[0x0000000008f59000-0x0000000008f5a000) (0MB)
[ 0.000000] EFI: mem128: type=3, attr=0xf, range=[0x0000000008f5a000-0x0000000008f60000) (0MB)
[ 0.000000] EFI: mem129: type=4, attr=0xf, range=[0x0000000008f60000-0x0000000008f66000) (0MB)
[ 0.000000] EFI: mem130: type=3, attr=0xf, range=[0x0000000008f66000-0x0000000008f6d000) (0MB)
[ 0.000000] EFI: mem131: type=4, attr=0xf, range=[0x0000000008f6d000-0x0000000008f78000) (0MB)
[ 0.000000] EFI: mem132: type=3, attr=0xf, range=[0x0000000008f78000-0x0000000008f7a000) (0MB)
[ 0.000000] EFI: mem133: type=4, attr=0xf, range=[0x0000000008f7a000-0x0000000008f7c000) (0MB)
[ 0.000000] EFI: mem134: type=3, attr=0xf, range=[0x0000000008f7c000-0x0000000008f81000) (0MB)
[ 0.000000] EFI: mem135: type=4, attr=0xf, range=[0x0000000008f81000-0x0000000008f93000) (0MB)
[ 0.000000] EFI: mem136: type=3, attr=0xf, range=[0x0000000008f93000-0x0000000008f97000) (0MB)
[ 0.000000] EFI: mem137: type=4, attr=0xf, range=[0x0000000008f97000-0x0000000008f9c000) (0MB)
[ 0.000000] EFI: mem138: type=3, attr=0xf, range=[0x0000000008f9c000-0x0000000008fa8000) (0MB)
[ 0.000000] EFI: mem139: type=4, attr=0xf, range=[0x0000000008fa8000-0x0000000008fae000) (0MB)
[ 0.000000] EFI: mem140: type=3, attr=0xf, range=[0x0000000008fae000-0x0000000008fb7000) (0MB)
[ 0.000000] EFI: mem141: type=4, attr=0xf, range=[0x0000000008fb7000-0x0000000008fbb000) (0MB)
[ 0.000000] EFI: mem142: type=3, attr=0xf, range=[0x0000000008fbb000-0x0000000008fbc000) (0MB)
[ 0.000000] EFI: mem143: type=4, attr=0xf, range=[0x0000000008fbc000-0x0000000008fd9000) (0MB)
[ 0.000000] EFI: mem144: type=3, attr=0xf, range=[0x0000000008fd9000-0x0000000008fdb000) (0MB)
[ 0.000000] EFI: mem145: type=4, attr=0xf, range=[0x0000000008fdb000-0x0000000008fdc000) (0MB)
[ 0.000000] EFI: mem146: type=3, attr=0xf, range=[0x0000000008fdc000-0x0000000008fdd000) (0MB)
[ 0.000000] EFI: mem147: type=4, attr=0xf, range=[0x0000000008fdd000-0x0000000008fe6000) (0MB)
[ 0.000000] EFI: mem148: type=3, attr=0xf, range=[0x0000000008fe6000-0x0000000008fff000) (0MB)
[ 0.000000] EFI: mem149: type=4, attr=0xf, range=[0x0000000008fff000-0x0000000009028000) (0MB)
[ 0.000000] EFI: mem150: type=3, attr=0xf, range=[0x0000000009028000-0x000000000902f000) (0MB)
[ 0.000000] EFI: mem151: type=4, attr=0xf, range=[0x000000000902f000-0x0000000009030000) (0MB)
[ 0.000000] EFI: mem152: type=3, attr=0xf, range=[0x0000000009030000-0x0000000009079000) (0MB)
[ 0.000000] EFI: mem153: type=4, attr=0xf, range=[0x0000000009079000-0x000000000907b000) (0MB)
[ 0.000000] EFI: mem154: type=3, attr=0xf, range=[0x000000000907b000-0x00000000090a4000) (0MB)
[ 0.000000] EFI: mem155: type=4, attr=0xf, range=[0x00000000090a4000-0x00000000090a5000) (0MB)
[ 0.000000] EFI: mem156: type=3, attr=0xf, range=[0x00000000090a5000-0x00000000090af000) (0MB)
[ 0.000000] EFI: mem157: type=4, attr=0xf, range=[0x00000000090af000-0x00000000090b3000) (0MB)
[ 0.000000] EFI: mem158: type=3, attr=0xf, range=[0x00000000090b3000-0x00000000090d5000) (0MB)
[ 0.000000] EFI: mem159: type=4, attr=0xf, range=[0x00000000090d5000-0x00000000090d8000) (0MB)
[ 0.000000] EFI: mem160: type=3, attr=0xf, range=[0x00000000090d8000-0x0000000009101000) (0MB)
[ 0.000000] EFI: mem161: type=4, attr=0xf, range=[0x0000000009101000-0x0000000009102000) (0MB)
[ 0.000000] EFI: mem162: type=3, attr=0xf, range=[0x0000000009102000-0x0000000009118000) (0MB)
[ 0.000000] EFI: mem163: type=4, attr=0xf, range=[0x0000000009118000-0x0000000009129000) (0MB)
[ 0.000000] EFI: mem164: type=3, attr=0xf, range=[0x0000000009129000-0x000000000912a000) (0MB)
[ 0.000000] EFI: mem165: type=4, attr=0xf, range=[0x000000000912a000-0x000000000912b000) (0MB)
[ 0.000000] EFI: mem166: type=3, attr=0xf, range=[0x000000000912b000-0x000000000913e000) (0MB)
[ 0.000000] EFI: mem167: type=4, attr=0xf, range=[0x000000000913e000-0x0000000009146000) (0MB)
[ 0.000000] EFI: mem168: type=3, attr=0xf, range=[0x0000000009146000-0x0000000009150000) (0MB)
[ 0.000000] EFI: mem169: type=4, attr=0xf, range=[0x0000000009150000-0x0000000009154000) (0MB)
[ 0.000000] EFI: mem170: type=3, attr=0xf, range=[0x0000000009154000-0x00000000091dc000) (0MB)
[ 0.000000] EFI: mem171: type=4, attr=0xf, range=[0x00000000091dc000-0x00000000091de000) (0MB)
[ 0.000000] EFI: mem172: type=3, attr=0xf, range=[0x00000000091de000-0x00000000091df000) (0MB)
[ 0.000000] EFI: mem173: type=4, attr=0xf, range=[0x00000000091df000-0x00000000091e2000) (0MB)
[ 0.000000] EFI: mem174: type=3, attr=0xf, range=[0x00000000091e2000-0x00000000091e3000) (0MB)
[ 0.000000] EFI: mem175: type=4, attr=0xf, range=[0x00000000091e3000-0x00000000091f6000) (0MB)
[ 0.000000] EFI: mem176: type=3, attr=0xf, range=[0x00000000091f6000-0x00000000091fc000) (0MB)
[ 0.000000] EFI: mem177: type=4, attr=0xf, range=[0x00000000091fc000-0x00000000091fd000) (0MB)
[ 0.000000] EFI: mem178: type=3, attr=0xf, range=[0x00000000091fd000-0x00000000091ff000) (0MB)
[ 0.000000] EFI: mem179: type=4, attr=0xf, range=[0x00000000091ff000-0x0000000009204000) (0MB)
[ 0.000000] EFI: mem180: type=3, attr=0xf, range=[0x0000000009204000-0x000000000920a000) (0MB)
[ 0.000000] EFI: mem181: type=4, attr=0xf, range=[0x000000000920a000-0x0000000009242000) (0MB)
[ 0.000000] EFI: mem182: type=3, attr=0xf, range=[0x0000000009242000-0x0000000009248000) (0MB)
[ 0.000000] EFI: mem183: type=4, attr=0xf, range=[0x0000000009248000-0x000000000924f000) (0MB)
[ 0.000000] EFI: mem184: type=3, attr=0xf, range=[0x000000000924f000-0x0000000009262000) (0MB)
[ 0.000000] EFI: mem185: type=4, attr=0xf, range=[0x0000000009262000-0x000000000928d000) (0MB)
[ 0.000000] EFI: mem186: type=3, attr=0xf, range=[0x000000000928d000-0x000000000928f000) (0MB)
[ 0.000000] EFI: mem187: type=4, attr=0xf, range=[0x000000000928f000-0x0000000009291000) (0MB)
[ 0.000000] EFI: mem188: type=3, attr=0xf, range=[0x0000000009291000-0x0000000009293000) (0MB)
[ 0.000000] EFI: mem189: type=4, attr=0xf, range=[0x0000000009293000-0x000000000929a000) (0MB)
[ 0.000000] EFI: mem190: type=3, attr=0xf, range=[0x000000000929a000-0x00000000092a7000) (0MB)
[ 0.000000] EFI: mem191: type=4, attr=0xf, range=[0x00000000092a7000-0x00000000092b5000) (0MB)
[ 0.000000] EFI: mem192: type=3, attr=0xf, range=[0x00000000092b5000-0x00000000092e3000) (0MB)
[ 0.000000] EFI: mem193: type=4, attr=0xf, range=[0x00000000092e3000-0x00000000092ec000) (0MB)
[ 0.000000] EFI: mem194: type=3, attr=0xf, range=[0x00000000092ec000-0x00000000092ef000) (0MB)
[ 0.000000] EFI: mem195: type=4, attr=0xf, range=[0x00000000092ef000-0x0000000012b46000) (152MB)
[ 0.000000] EFI: mem196: type=7, attr=0xf, range=[0x0000000012b46000-0x0000000012b4a000) (0MB)
[ 0.000000] EFI: mem197: type=2, attr=0xf, range=[0x0000000012b4a000-0x0000000012b4c000) (0MB)
[ 0.000000] EFI: mem198: type=7, attr=0xf, range=[0x0000000012b4c000-0x0000000012d14000) (1MB)
[ 0.000000] EFI: mem199: type=4, attr=0xf, range=[0x0000000012d14000-0x0000000012d18000) (0MB)
[ 0.000000] EFI: mem200: type=7, attr=0xf, range=[0x0000000012d18000-0x0000000012d20000) (0MB)
[ 0.000000] EFI: mem201: type=4, attr=0xf, range=[0x0000000012d20000-0x0000000012d55000) (0MB)
[ 0.000000] EFI: mem202: type=7, attr=0xf, range=[0x0000000012d55000-0x0000000012dbd000) (0MB)
[ 0.000000] EFI: mem203: type=1, attr=0xf, range=[0x0000000012dbd000-0x0000000012e25000) (0MB)
[ 0.000000] EFI: mem204: type=7, attr=0xf, range=[0x0000000012e25000-0x0000000012e40000) (0MB)
[ 0.000000] EFI: mem205: type=4, attr=0xf, range=[0x0000000012e40000-0x0000000012fbc000) (1MB)
[ 0.000000] EFI: mem206: type=3, attr=0xf, range=[0x0000000012fbc000-0x0000000012fbd000) (0MB)
[ 0.000000] EFI: mem207: type=4, attr=0xf, range=[0x0000000012fbd000-0x0000000012fc0000) (0MB)
[ 0.000000] EFI: mem208: type=3, attr=0xf, range=[0x0000000012fc0000-0x0000000012fc3000) (0MB)
[ 0.000000] EFI: mem209: type=4, attr=0xf, range=[0x0000000012fc3000-0x0000000013142000) (1MB)
[ 0.000000] EFI: mem210: type=3, attr=0xf, range=[0x0000000013142000-0x0000000013152000) (0MB)
[ 0.000000] EFI: mem211: type=4, attr=0xf, range=[0x0000000013152000-0x0000000013198000) (0MB)
[ 0.000000] EFI: mem212: type=3, attr=0xf, range=[0x0000000013198000-0x000000001319c000) (0MB)
[ 0.000000] EFI: mem213: type=4, attr=0xf, range=[0x000000001319c000-0x000000001342d000) (2MB)
[ 0.000000] EFI: mem214: type=7, attr=0xf, range=[0x000000001342d000-0x0000000013462000) (0MB)
[ 0.000000] EFI: mem215: type=4, attr=0xf, range=[0x0000000013462000-0x0000000013542000) (0MB)
[ 0.000000] EFI: mem216: type=7, attr=0xf, range=[0x0000000013542000-0x000000001355f000) (0MB)
[ 0.000000] EFI: mem217: type=4, attr=0xf, range=[0x000000001355f000-0x0000000013a07000) (4MB)
[ 0.000000] EFI: mem218: type=7, attr=0xf, range=[0x0000000013a07000-0x0000000020000000) (197MB)
[ 0.000000] EFI: mem219: type=0, attr=0xf, range=[0x0000000020000000-0x0000000020200000) (2MB)
[ 0.000000] EFI: mem220: type=7, attr=0xf, range=[0x0000000020200000-0x0000000036352000) (353MB)
[ 0.000000] EFI: mem221: type=2, attr=0xf, range=[0x0000000036352000-0x00000000371a1000) (14MB)
[ 0.000000] EFI: mem222: type=7, attr=0xf, range=[0x00000000371a1000-0x0000000040004000) (142MB)
[ 0.000000] EFI: mem223: type=0, attr=0xf, range=[0x0000000040004000-0x0000000040005000) (0MB)
[ 0.000000] EFI: mem224: type=7, attr=0xf, range=[0x0000000040005000-0x00000000999d9000) (1433MB)
[ 0.000000] EFI: mem225: type=2, attr=0xf, range=[0x00000000999d9000-0x00000000c8eab000) (756MB)
[ 0.000000] EFI: mem226: type=5, attr=0x800000000000000f, range=[0x00000000c8eab000-0x00000000c8ead000) (0MB)
[ 0.000000] EFI: mem227: type=0, attr=0xf, range=[0x00000000c8ead000-0x00000000c8fc0000) (1MB)
[ 0.000000] EFI: mem228: type=5, attr=0x800000000000000f, range=[0x00000000c8fc0000-0x00000000c8fd9000) (0MB)
[ 0.000000] EFI: mem229: type=6, attr=0x800000000000000f, range=[0x00000000c8fd9000-0x00000000c8fe6000) (0MB)
[ 0.000000] EFI: mem230: type=5, attr=0x800000000000000f, range=[0x00000000c8fe6000-0x00000000c9022000) (0MB)
[ 0.000000] EFI: mem231: type=6, attr=0x800000000000000f, range=[0x00000000c9022000-0x00000000c9082000) (0MB)
[ 0.000000] EFI: mem232: type=5, attr=0x800000000000000f, range=[0x00000000c9082000-0x00000000c9099000) (0MB)
[ 0.000000] EFI: mem233: type=6, attr=0x800000000000000f, range=[0x00000000c9099000-0x00000000c90a8000) (0MB)
[ 0.000000] EFI: mem234: type=6, attr=0x800000000000000f, range=[0x00000000c90a8000-0x00000000c90c3000) (0MB)
[ 0.000000] EFI: mem235: type=0, attr=0xf, range=[0x00000000c90c3000-0x00000000c910a000) (0MB)
[ 0.000000] EFI: mem236: type=0, attr=0xf, range=[0x00000000c910a000-0x00000000c911a000) (0MB)
[ 0.000000] EFI: mem237: type=10, attr=0xf, range=[0x00000000c911a000-0x00000000c953b000) (4MB)
[ 0.000000] EFI: mem238: type=0, attr=0xf, range=[0x00000000c953b000-0x00000000c9558000) (0MB)
[ 0.000000] EFI: mem239: type=0, attr=0xf, range=[0x00000000c9558000-0x00000000c955e000) (0MB)
[ 0.000000] EFI: mem240: type=0, attr=0xf, range=[0x00000000c955e000-0x00000000c95c3000) (0MB)
[ 0.000000] EFI: mem241: type=10, attr=0xf, range=[0x00000000c95c3000-0x00000000c9751000) (1MB)
[ 0.000000] EFI: mem242: type=10, attr=0xf, range=[0x00000000c9751000-0x00000000c980d000) (0MB)
[ 0.000000] EFI: mem243: type=10, attr=0xf, range=[0x00000000c980d000-0x00000000c981e000) (0MB)
[ 0.000000] EFI: mem244: type=10, attr=0xf, range=[0x00000000c981e000-0x00000000c9828000) (0MB)
[ 0.000000] EFI: mem245: type=10, attr=0xf, range=[0x00000000c9828000-0x00000000c982c000) (0MB)
[ 0.000000] EFI: mem246: type=10, attr=0xf, range=[0x00000000c982c000-0x00000000c9843000) (0MB)
[ 0.000000] EFI: mem247: type=9, attr=0xf, range=[0x00000000c9843000-0x00000000c9847000) (0MB)
[ 0.000000] EFI: mem248: type=9, attr=0xf, range=[0x00000000c9847000-0x00000000c9848000) (0MB)
[ 0.000000] EFI: mem249: type=10, attr=0xf, range=[0x00000000c9848000-0x00000000c988b000) (0MB)
[ 0.000000] EFI: mem250: type=4, attr=0xf, range=[0x00000000c988b000-0x00000000c99d0000) (1MB)
[ 0.000000] EFI: mem251: type=3, attr=0xf, range=[0x00000000c99d0000-0x00000000c9c5e000) (2MB)
[ 0.000000] EFI: mem252: type=4, attr=0xf, range=[0x00000000c9c5e000-0x00000000c9c6d000) (0MB)
[ 0.000000] EFI: mem253: type=3, attr=0xf, range=[0x00000000c9c6d000-0x00000000c9c7f000) (0MB)
[ 0.000000] EFI: mem254: type=4, attr=0xf, range=[0x00000000c9c7f000-0x00000000c9c80000) (0MB)
[ 0.000000] EFI: mem255: type=3, attr=0xf, range=[0x00000000c9c80000-0x00000000c9c82000) (0MB)
[ 0.000000] EFI: mem256: type=4, attr=0xf, range=[0x00000000c9c82000-0x00000000c9c89000) (0MB)
[ 0.000000] EFI: mem257: type=6, attr=0x800000000000000f, range=[0x00000000c9c89000-0x00000000c9ff5000) (3MB)
[ 0.000000] EFI: mem258: type=4, attr=0xf, range=[0x00000000c9ff5000-0x00000000ca000000) (0MB)
[ 0.000000] EFI: mem259: type=7, attr=0xf, range=[0x0000000100000000-0x000000042fe00000) (13054MB)
[ 0.000000] EFI: mem260: type=0, attr=0x8000000000000000, range=[0x00000000cb000000-0x00000000cf200000) (66MB)
[ 0.000000] EFI: mem261: type=11, attr=0x8000000000000001, range=[0x00000000f8000000-0x00000000fc000000) (64MB)
[ 0.000000] EFI: mem262: type=11, attr=0x8000000000000001, range=[0x00000000fec00000-0x00000000fec01000) (0MB)
[ 0.000000] EFI: mem263: type=11, attr=0x8000000000000001, range=[0x00000000fed00000-0x00000000fed04000) (0MB)
[ 0.000000] EFI: mem264: type=11, attr=0x8000000000000001, range=[0x00000000fed1c000-0x00000000fed20000) (0MB)
[ 0.000000] EFI: mem265: type=11, attr=0x8000000000000001, range=[0x00000000fee00000-0x00000000fee01000) (0MB)
[ 0.000000] EFI: mem266: type=11, attr=0x8000000000000001, range=[0x00000000ff000000-0x0000000100000000) (16MB)
[ 4.414152] fb0: EFI VGA frame buffer device
[ 4.860429] EFI Variables Facility v0.08 2004-May-17
[ 7.499759] fb: conflicting fb hw usage inteldrmfb vs EFI VGA - removing generic driver
En résumé avec le cd francophone je n'ai pas de choix. Avec le cd original je peux soit booter en UEFI soit non. Par contre je ne sais pas pourquoi.
Dernière modification par azdep (Le 20/06/2012, à 18:28)
Hors ligne
malbo
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
J'ai fait l'essai avec VirtualBox avec l'option EFI activée (case cochée "Activer EFI (os spéciaux seulement)" dans les options avancées).
1) démarrage sur liveCD virtuel de la version officielle "ubuntu-12.04-desktop-amd64.iso"
Résultat : le démarrage se fait automatiquement sur le liveCD virtuel avec apparition de l'écran caractéristique du démarrage en EFI (menu en noir et blanc avec le titre GNU GRUB...) : http://www.hostingpics.net/viewer.php?i … 132006.png
2) démarrage sur le liveCD virtuel de la version francophone "ubuntu-12.04-desktop-amd64-fr.iso"
Résultat : le liveCD n'est tout simplement pas reconnu, c'est à dire que la machine virtuelle démarre sur le disque dur (virtuel) alors qu'elle devrait démarrer sur le liveCD virtuel s'il était fonctionnel.
C'est donc un résultat conforme à ce qui a été décrit par azdep dans le post #4, c'est à dire que le liveCD francophone n'est pas vu comme UEFI.
Dernière modification par malbo (Le 25/06/2012, à 11:35)
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
Tsintao
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Cher Monsieur Malbo, pour faire suite à votre requête du lundi 25 juin à 13h17… ;-)
Je confirme que la version française du CD d'installation de Ubuntu 12.04 ne permet pas de démarrage en UEFI. Et c'est bien naturel puisqu'il ne contient pas
|…|-- efi| `-- boot| `-- bootx64.efi|…
… contrairement à l'installeur «officiel».
J'ignore si c'est la seule condition pour que l'installeur puisse démarrer en UEFI, mais je suppose que la présence de cette arborescence, avec un *.efi au bout, est une condition sine qua non pour être détecté (et lancé) par le bootmanager UEFI (que ce soit celui du firmware ou pas).
(mais je rapelle, au passage, qu'il n'est pas indispensable de démarrer le CD d'installation en UEFI pour pouvoir installer Ubuntu 12.04 sur un système UEFI [ni même pour en préparer un, d'ailleurs]. Cela requiert, toutefois, une bonne compréhension de l'EFI et quelques précautions pour éviter des pertes de données et de temps. Il n'est simplement pas possible de s'en remettre entièrement à l'installeur de Ubuntu 12.04 pour réaliser toutes les phases de l'installation automatiquement)
Dernière modification par Tsintao (Le 25/06/2012, à 17:29)
Hors ligne
malbo
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Merci pour cette confirmation Tsintao.
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
Tsintao
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
De rien et merci à toi pour la série de fils consacrée au sujet (que j'avais loupée).
Hors ligne
azdep
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Bonjour,
merci à Tsintao,
(mais je rapelle, au passage, qu'il n'est pas indispensable de démarrer le CD d'installation en UEFI pour pouvoir installer Ubuntu 12.04 sur un système UEFI [ni même pour en préparer un, d'ailleurs]. Cela requiert, toutefois, une bonne compréhension de l'EFI et quelques précautions pour éviter des pertes de données et de temps. Il n'est simplement pas possible de s'en remettre entièrement à l'installeur de Ubuntu 12.04 pour réaliser toutes les phases de l'installation automatiquement)
Ce serait bien de décrire la procédure d'installation EFI sans démarrer le cd en UEFI, car j'ai essayé pas mal de manip pour faire un dual boot avec windows7 sur 2 disques durs, Ubuntu démarre presque dans tout les cas, mais souvent Windows ne repart pas, il suffit dans ce cas d'enlever le second disque sur lequel Ubuntu est installé.
Je comprend bien qu'on ne peut pas s'en remettre qu'à l'installeur, mais c'est qu'en même dommage d'avoir un cd francophone moins disant que l'original. Il faut aussi penser que dans les utilisateurs d'Ubuntu il n'y a pas que des ingénieurs informaticiens.
Hors ligne
Tsintao
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Ce serait bien de décrire la procédure d'installation EFI sans démarrer le cd en UEFI
Salut Azdep,
Le fil de récapitulation de mon installation, avec rEFInd en tant que bootmanager et ELILO en tant que bootloader Linux, constitue, en lui même, un petit "guide" pour une installation de Ubuntu (ou autre distribution GNU/Linux) sur un système EFI avec Windows7 pré-installé. Et il est tout à fait possible de l'implémenter sans démarrer le CD d'installation en mode UEFI.
Je rechigne à en faire un guide plus générique, parce que
C'est une manière de faire, il y en a d'autres ;
Je n'ai aucune certitude que cela fonctionnerait sur tous les firmware EFI ;
Il faudrait que je donne tellement d'informations « génériques » que cela découragerait les utilisateurs visés (plutôt novices et/ou ne disposant pas d'assez de temps pour lire et intégrer le nécessaire vital).
Cela prend beaucoup de temps et cela m'engagerait vis-à-vis des utilisateurs qui me feraient confiance. Or, si j'oublie un détail par mégarde ou par ignorance, cela peut conduire à des pertes de données.
Plusieurs fils, dont ceux de Malbo, traitent du sujet sur ce forum. C'est loin d'être idéal, les informations étant disséminées… mais tant que les distributions ne seront pas disponibles avec un installeur qui automatise tout le processus sur des bases saines, il n'y a pas de miracle : les gens devront procéder eux même à quelques phases de l'installation et, préalablement, lire un peu sur le sujet pour comprendre ce qu'ils font.
Maintenant, si la demande est forte pour écrire une procédure limitée à rEFInd+ELILO mieux adaptée à un novice, j'envisagerai la possibilité ;-)
Dernière modification par Tsintao (Le 26/06/2012, à 11:31)
Hors ligne
azdep
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Bien sur Tsintao je comprend très bien ta réponse, et je sais le travail que demande ce genre de guide, c'est pour ca que la proposition de YannUbuntu de rajouter l'EFI dans le cd d'install. est surement plus simple. Ca en vaut d'autant plus le coup que la 12.04 est une LTS. Pendant mes essais et avant d'essayer le cd original, j'ai essayer le livecd Fedora et lui a fonctionner. Par acquis de conscience j'ai essayé le cd original qui heureusement à fonctionné, sinon j'aurai été un peu frustré
Dernière modification par azdep (Le 27/06/2012, à 08:17)
Hors ligne
malbo
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
c'est pour ça que la proposition de malbo de rajouter l'EFI dans le cd d'install. est surement plus simple.
En fait, c'est YannUbuntu qui a exprimé cela : http://forum.ubuntu-fr.org/viewtopic.ph … 1#p9746621
Cela dit je suis bien d'accord : ce serait inadmissible que le liveCD Francophone ne soit pas fonctionnel pour installer en EFI.
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
azdep
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Oups, j'ai corrigé la source !
Hors ligne
kao_chen
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Bonjour, j'ai fait le souhait d'acheter une carte mère équipé en EFI sur ce post :
http://forum.ubuntu-fr.org/viewtopic.ph … 1#p9842021
et on m'a conseillé de passer vous voir par ici.
Pour résumé, j'ai repéré une carte mère (GA-Z77X-D3H) qui m’intéresse mais j'ai vu qu'elle était équipé d'un EFI seulement, je voulais savoir si pour installer Ubuntu, uniquement (pas de dual boot Windows) je rencontrerai pas d'incompatibilité. D'après ce que j'ai lu ci dessus, ça devrait passer, notamment avec la version officielle. Si vous me le déconseillez vraiment, je trouverai une autre carte, sinon je tenterai ma chance.
Merci d'avance,
Kao
Hors ligne
malbo
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
kao_chen,
Je n'ai lu nulle part que des cartes mères UEFI soient incompatibles avec Ubuntu. Tu peux acheter n'importe quelle carte-mère soit UEFI/BIOS soit UEFI seulement.
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
kao_chen
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Ok cool merci,
J'avais lu qu'il pouvait y avoir des problèmes de compatibilité avec Grub2 mais il semble que cela ne concerne que l'activation de l'option secure boot
http://www.clubic.com/linux-os/debian/u … rub-2.html
Hors ligne
malbo
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Dans ce post : http://forum.ubuntu-fr.org/viewtopic.ph … 1#p9478871
tshirtman (qui semble très bien informé sur le sujet) répond "non" à la question "est ce que dans quelques années tout les PC en vente auront des carte mere avec UEFI empêchant l'installation d'autre chose que windows ? Y compris les carte meres vendues séparément ?"
Tu peux poster dans cette discussion pour te faire confirmer la chose dans ton cas particulier mais à mon avis, il n'y a pas de danger pour toi.
Dernière modification par malbo (Le 30/06/2012, à 09:07)
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
Tsintao
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
La réponse est effectivement "non". Par contre, les PC's pré-installés avec Win8 pourraient très prochainement commencer à poser de petits problèmes à ceux qui auraient l'audace de vouloir faire ce qu'ils veulent de leur ordinateur : Linux Torvalds on Windows 8, UEFI and Fedora.
... Mais ça ne s'applique pas au cas de Kao_chen, grand bien lui fasse ^^
Hors ligne
polyp
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Bonsoir,
avec Asus UX31A, le BIOS est..un BIOS, Cas 1 :
dmesg | grep EFI
[ 1.241248] EFI Variables Facility v0.08 2004-May-17
Mais, une fois l'installation (12.04 de ubuntu.com) faite (chargeur de démarrage sur /dev/sda, classique quoi!), la machine
ne redémarre plus.
- Précision 1 : Après plusieurs essais infructueux (Debian Wheezy puis Ubuntu 12.04) j'ai fait un ménage un peu violent...et viré toutes les partitions Fat32 de quelques Mo à 300 Mo au début du disque.. (Oui, des fois on fait des choses idiotes..)
- Précision 2: Ultrabook=SSD non extractible=Impossible de faire l'install depuis une autre machine.
Je n'ai aucune envie de garder Windows, et peut donc me passer de tout mécanisme de compatibilité concernant le chargeur de démarrage.
Bref, j'ai l'impression d'être revenu en mode débutant...
Une idée ?
Merci d'avance.
Cdlt.
Hors ligne
YannUbuntu
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Si vous aviez Windows en EFI, il va probablement vous falloir recréer la partition EFI puis réinstaller grub-efi. Voir ce tuto de Malbo: http://forum.ubuntu-fr.org/viewtopic.ph … 1#p9866321
Hors ligne
polyp
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Bonsoir,
sauf que la re-création de la partition Windows/EFI (pas Windows lui-même) nécessite un retour atelier..
Je vais voir ce que donne la suppression de la partition GPT et son remplacement par une partition MBR classique; c'est ma dernière cartouche.. ;-(
Merci.
Hors ligne
YannUbuntu
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
sauf que la re-création de la partition Windows/EFI (pas Windows lui-même) nécessite un retour atelier...
- La partition EFI : non, vous pouvez créer une partition EFI avec gParted. (FAT32, >200Mo, début du disque, drapeau boot)
- le fichier WIndows EFI: ça doit pouvoir se faire via le DVD Windows je pense, mais comme vous n'avez pas besoin de WIndows, ce n'est pas le problème.
Dernière modification par YannUbuntu (Le 05/07/2012, à 00:16)
Hors ligne
polyp
Re : [Tuto] identifier si on est dans un système UEFI ou Bios
Merci pour toutes vos infos .
Je suis en train de refaire la partition à la main en suivant http://forum.ubuntu-fr.org/viewtopic.ph … 1#p7281381
Et....Ca marche !
Quelques modifs :
- il manque un mkdir /boot/efi
- Lors de l'install le nom de l'hote change de ubuntu à xxxxx
echo "127.0.0.1 xxxxx" >> /etc/hosts
- Par sécurité : cp -r /boot/efi/EFI/ubuntu /boot/efi/EFI/xxxxx
MERCI. !!
Hors ligne
|
[Windows 7 64 bit; Python 2.7]
If I try to use Urllib2, I get this error
Traceback (most recent call last):
File "C:\Users\cYanide\Documents\Python Challenge\1\1.py", line 7, in <module>
response = urllib2.urlopen('http://python.org/')
File "C:\Python27\lib\urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "C:\Python27\lib\urllib2.py", line 400, in open
response = meth(req, response)
File "C:\Python27\lib\urllib2.py", line 513, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python27\lib\urllib2.py", line 438, in error
return self._call_chain(*args)
File "C:\Python27\lib\urllib2.py", line 372, in _call_chain
result = func(*args)
File "C:\Python27\lib\urllib2.py", line 521, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
**urllib2.HTTPError: HTTP Error 407: Proxy Authentication Required**
Now, I'm behind a college proxy which requires authentication so that's probably the reason why this is happening. But isn't Urllib2 supposed to pull the authentication and proxy information from the system settings?
I understand there's some extra code I can insert into my program to 'hardcode' the proxy information in the program but I really don't want to do that unless it's the last resort. It would hinder the portability of the program across computers with different authentication IDs and Passwords in the college.
|
Topic: [SOLVED] dashboard statistics pgsql 1.4.1
==== Required information ====
- iRedMail version: 1.4.1 upgraded from 1.4.0
- Store mail accounts in which backend (LDAP/MySQL/PGSQL): PGSQL
- Linux/BSD distribution name and version: debian 7 64bit
- Related log if you're reporting an issue:
====
Hi, Happy New Year to everybody
after updating, the "Statistics Of Latest 24 Hours" in the dashboard remain at zero.
the lo of my postgres "/var/log/postgresql/postgresql-9.1-main.log"
2014-01-02 17:29:05 CET ERROR: column "C" does not exist at character 463
2014-01-02 17:29:05 CET STATEMENT:
-- Get number of incoming mails.
SELECT COUNT(msgs.mail_id) AS total
FROM msgs
LEFT JOIN msgrcpt ON (msgs.mail_id = msgrcpt.mail_id)
-- LEFT JOIN maddr AS sender ON (msgs.sid = sender.id)
LEFT JOIN maddr AS recip ON (msgrcpt.rid = recip.id)
WHERE
-- msgs.content NOT IN ('S', 's', 'Y', 'V', 'B')
msgs.content="C"
AND recip.domain IN ('com.xxx', 'it.xxx', 'net.xxx', 'de.xxx', 'br.com.xxx', 'org.xxx', 'eu.xxx') AND msgs.time_iso > CURRENT_TIMESTAMP - INTERVAL '86400 seconds'
2014-01-02 17:29:05 CET ERROR: column "C" does not exist at character 393
2014-01-02 17:29:05 CET STATEMENT:
-- Get number of outgoing mails.
SELECT COUNT(msgs.mail_id) AS total
FROM msgs
RIGHT JOIN msgrcpt ON (msgs.mail_id = msgrcpt.mail_id)
RIGHT JOIN maddr AS sender ON (msgs.sid = sender.id)
WHERE
-- msgs.content NOT IN ('S', 's', 'Y', 'V', 'B')
msgs.content="C"
AND sender.domain IN ('com.xxx', 'it.xxx', 'net.xxx', 'de.xxx', 'br.com.xxx', 'org.xxx', 'eu.xxx') AND msgs.time_iso > CURRENT_TIMESTAMP - INTERVAL '86400 seconds'
thanks
----
Urgent issue? Pay iRedMail developer to solve it remotely at $39.
|
Magic 8 Ball is a toy you can use to seek advices when you are bored or need to make some tough decisions but you cannot ask anybody else, even your parents, siblings, friends or your cat. There are a lot of Magic 8 Ball tools out there, both online and offline, but you can create your own Magic 8 Ball script with your unique answers very easily.
Here is a simple Magic 8 Ball script in python, if you dont like these answer, just edit the script to add whatever answers you prefer:
To use this script, just copy paste the script into a text file and save it as a python script with the .py extension. For example, my script is m8.py and I saved it on the desktop. Next, you will need to make the script executable:
After that you just need to double click on the file and choose to run it in the terminal:
And here is how the script works:
Here is a simple Magic 8 Ball script in python, if you dont like these answer, just edit the script to add whatever answers you prefer:
#!/usr/bin/env python
# Magic 8 ball program
import random
answers = ["As I see it, yes","It is certain","It is decidedly so","Most likely","Outlook good","Signs point to yes","Without a doubt","Yes","Yes definitely","You may rely on it","Better not tell you now","Cannot predict now","Concentrate and ask again","Don't count on it","My reply is no","My sources say no","Outlook not so good","Very doubtful"]
raw_input("Hello candy-ass, what you need to know?\n")
response = random.choice(answers)
print response +'\n'
while (True):
raw_input("Any other question?\n")
print random.choice(answers) + '\n'
To use this script, just copy paste the script into a text file and save it as a python script with the .py extension. For example, my script is m8.py and I saved it on the desktop. Next, you will need to make the script executable:
sudo chmod +x m8.py
After that you just need to double click on the file and choose to run it in the terminal:
And here is how the script works:
|
JavaScript
paul_wilkins — 2013-04-26T23:39:48-04:00 — #1
While watching Nicholas Zakas' Maintainable JavaScript talk at the Fluent 2012 conference, there was a very informative section in there about keeping JavaScript separate from the HTML, and other similar concerns of separation.
You can see it from the 25:40 section of the video.
pullo — 2013-04-27T08:26:40-04:00 — #2
Hi Paul,
Thanks for posting the link to that talk. I was reminded of a lot of things that I should be doing more often
I do however have one question:
At 27:02 in the video, he tells us to "Keep your HTML out of JavaScript", citing the reason that if there is something wrong with the layout, you shouldn't have to find the problem in a JS file.
E.g. this is bad:
var element = document.getElementById("container");
element.innerHTML = "<div class=\\"popup\\"></div>"
By way of a solution he proposes using some form of template (e.g. [Moustache or [URL="http://handlebarsjs.com/"]Handlebars](http://mustache.github.io/)), or pulling back markup from the server and injecting it into the page.
So far, so good, right?
Well, the other day I saw you post this code, with which you can generate random numbers for a lottery.
I noticed that if you pick nine or more numbers, the numbers overflow their container. So, I thought I'd change the markup and make the box expand to fit the numbers.
As you might already guess, I couldn't find the markup in the HTML section of the fiddle, but instead found it buried deep in the JS. I had a quick play with it, but soon gave up owing to the confusing nature of the escaped backslashes, the inline CSS and the string concatenation.
container.innerHTML = '<div id="container' + idx + '" style="' + 'position:relative;' + 'width:160px;height:50px;' + 'font-family:verdana,arial,sans-serif;' + 'font-size:12px;' + 'color:#000000;' + 'background-color:#fffff0;' + 'text-align:center;' + 'border : 1px solid #000000">' + '<input type="button" id="play' + idx + '"' + 'value="' + buttonText + '" style="margin:5px">' + '<div id="result' + idx + '" style="' + 'width:150px;' + 'font-family:verdana,arial,sans-serif;' + 'font-size:12px;' + 'color:#000000">' + initialText + '<\\/div><\\/div>';
document.body.appendChild(container);
I know this code was only intended to demonstrate a specific functionality, but this got me to wondering, how we might apply what Nicholas Zakas tells us in his talk.
I would be interested in your thoughts on this.
paul_wilkins — 2013-04-27T08:35:12-04:00 — #3
Removing the CSS from the JavaScript that's intended to be HTML, would be a good first step to things.
Then, the remaining HTML could be placed in to the web page as hidden content, or in to a template file of some kind for later use.
How do you feel about refactoring that code, as an example of how to apply such better practices?
pullo — 2013-04-27T09:30:01-04:00 — #4
Sure!
Ok, I've done this: http://jsfiddle.net/hibbard_eu/8R42e/
As you can see, I've created a template div element, which I've hidden using CSS.
I can then clone this with JS and manipulate it as required before inserting it into the page.
The code could probably do with some refactoring, but does this seem like a good start?
I've also used classes for the styling, as the dynamically generated elements are assigned varying ids, e.g.
container.innerHTML = '<div id="container' + idx + ...
jeff_mott — 2013-04-27T17:28:16-04:00 — #5
Here's an interesting trick that gets used far less often than it should.
<script id="list-template" type="text/x-handlebars-template">
<p>YUI is brought to you by:</p>
<ul>
{{#items}}
<li><a href="{{url}}">{{name}}</a></li>
{{/items}}
</ul>
</script>
This way, your markup stays in your HTML files; there's no need for any backslash escaping; and the browser won't render this template because it's wrapped in a script tag.
Then somewhere in your JavaScript (this uses YUI, but you get the gist):
// Extract the template string and compile it into a reusable function.
var template = Y.Handlebars.compile(Y.one('#list-template').getHTML());
// Render the template to HTML using the specified data.
var html = template({
items: [
{name: 'pie', url: 'http://pieisgood.org/'},
{name: 'mountain dew', url: 'http://www.mountaindew.com/'},
{name: 'kittens', url: 'http://www.flickr.com/search/?q=kittens'},
{name: 'rainbows', url: 'http://www.youtube.com/watch?v=OQSNhk5ICTI'}
]
});
paul_wilkins — 2013-04-27T18:45:11-04:00 — #6
Yes, that's a good start.
The following can be removed entirely:
template.style.display = 'block';
because it is only the template section that is hidden. When it's copied out using cloneNode and renamed, it's no longer hidden.
The template doesn't need to be appended to the page immediately after it has been read too.
container.innerHTML = '';
var template = document.getElementById('template').cloneNode(true);
container.appendChild(template);
template.id = "container" + idx;
template.className = "container";
Instead, changes are better off being made before it has been added to the page, which helps to avoid performance issues too.
var template = document.getElementById('template').cloneNode(true);
template.id = "container" + idx;
template.className = "container";
...
container.appendChild(template);
There's not much performance-wise to currently worry about, but I plan to take that appendChild down below the element updates and the event attachments.
The section with the roll button can be updated now.
var button = template.getElementsByTagName("input")[0];
button.id = "play" + idx;
button.value = buttonText;
...
var controlButton = document.getElementById("play" + idx);
if (window.addEventListener) {
controlButton.addEventListener("click", justOnce, false);
} else if (window.attachEvent) {
controlButton.attachEvent("onclick", justOnce);
}
The button variable can be renamed to something a but more expressive, to playButton.
And that event code is too complex for its own good. We can either move the cross-compatibility addEvent code out to a separate function, or we can use a more simple convention instead. Let's go with the simple and use onclick.
We can also entirely get rid of the controlButton variable too.
var playButton = template.getElementsByTagName("input")[0];
playButton.id = "play" + idx;
playButton.value = buttonText;
playButton.onclick = justOnce;
That's much better.
There's a minor conflict after that in the justOnce function because it is expecting the controlButton global variable, but that's easily fixed, by using the this keyword instead.
And why is the b variable there in the justOnce function? Normally it would be evt or some other similar event keyword, but the variable is not used at all in this function, so that variable can be removed too.
Before:
function justOnce(b) {
controlButton.blur();
...
}
After:
function justOnce() {
var button = this;
button.blur();
...
}
After these changes, we now are left with a structure where the template is obtained, changes are made to the content of that template, and at the end of things the template is placed inside of the container.
function lotto() {
// functions
...
var container = document.getElementById('container');
// updates to the template
...
container.innerHTML = '';
appendChild(template);
}
Now because I'm lazy developer, I'm going to have JSLint help me with tidying up the rest of this code, which results in the following code: http://jsfiddle.net/pmw57/8R42e/15/
Now that the code is structured and safe, there are many other improvements that should be made to it as well.
The large list of variables means that we should break the main lotto function up in to separate parts
I want to create a single global lotto object, which we can use to initialize button text values and to act as the single interface for our script
The numsort function can be much simpler, and achieve the same job
Most of the code should be broken up in to separate functions, dedicated to just one task
And the list of improvements goes on
paul_wilkins — 2013-04-27T19:42:22-04:00 — #7
I have to head off, but as something to look forward to, here's what the roll function looks like after having made a few improvements:
function roll(button) {
if (!validateRollingOptions(opts.pick, opts.from, opts.to)) {
return false;
}
var draw = drawNumbers(opts.pick, opts.from, opts.to);
draw.sort(numericSort);
updateResult(draw.join(' '));
setupNextRoll({
target: button,
totalRolls: opts.totalRolls,
rollDelay: opts.rollDelay,
callback: roll
});
}
pullo — 2013-04-28T16:49:50-04:00 — #8
Thanks for pointing that out, Jeff.
I've been wanting to have a look at Handlebars for a while now (along with so much other cool stuff - where does the time go??).
Maybe when we've worked through refactoring the code here, it would be possible to convert it to use Handlebars (and/or Moustache) as a final step.
pullo — 2013-04-28T17:16:46-04:00 — #9
Hi Paul,
I've just finished reading through your first refactoring of the code.
Thank you very much for this, as writing maintainable code, which reflects current best practices is definitely something I could be better at. It is certainly very educational to see how somebody else would go about things.
I should also get into the habit of using JS lint more often. I also ran the code through it so that I could better comprehend your final Fiddle and was quite surprised at the amount of warnings it spat out.
Most of them were logical really, but these are all things which can potentially make your code less error prone in the long run.
Allow me:
function numsort(n1, n2) {
return (n1 - n2);
}
var draw = [19, 32, 18, 36, 4, 43, 5] ;
console.log(draw.sort(numsort));
// [4, 5, 18, 19, 32, 36, 43]
I am looking forward to the second instalment. Things look as though they are shaping up quite nicely.
paul_wilkins — 2013-04-28T20:28:47-04:00 — #10
Thanks.
Going through the code at http://jsfiddle.net/pmw57/8R42e/15/ there are more issues with it that was dealing with now.
It is tempting to define a global object for the code, by that is not required yet at this stage
the "choose your lottery format" piece needs to be moved out as configuration options
the configuration options will need to be provided through a global object for the code, so we now have a good reason to define the code as a global object
the playing variable can be renamed to something a bit more expressive, such as isRolling
timer doesn't seem to be needed, as we are not stopping the timed event at any stage
counter is for the number of times the numbers are rolled, which should be moved out to a configurable options object
idx and individually numbered identifier should not be required. Experiments with having multiple lotto rollers will need to be done in order to troubleshoot any remaining issues with that
container and template need to be configurable options
the play button and result sections should be not be retrieved from the page, but instead be assigned when the lotto section is being created
numsort should be replaced with much simpler code, and be renamed to numberSort
the roll function needs a much simpler structure, which should result inonly three functions being called. One for validation, one to get the drawn numbers and one to show them
the template modifications should be moved to a separate function
the check that getDocumentById exists should throw an error if it doesn't
the firstChild check shouldn't be needed due to the refactoring, but testing will confirm that
the onsubmit function should just pass the form element to an init function
Those are the broad strokes of what needs to be done, which I'll temporarily attempt to work on from the ipad for a while.
paul_wilkins — 2013-04-28T23:12:54-04:00 — #11
The timer that is declared in the lotto function is used I only one place, and that is where the decision on whether to keep the rolling going on occurs.
timer = setTimeout(roll, 50);
if (counter > 50) {
clearTimeout(timer);
isRolling = false;
counter = 0;
}
By reorganizing that, we can remove the need for clearing the timer.
But, I cannot do this with my ipad because when I head off to edit some code, I'm forced to reload this comment page when I return, which forces me to lose all that I have typed up before.
The third time is the charm, time to admit defeat and do something else until at get back to a real computer.
paul_wilkins — 2013-04-29T00:31:18-04:00 — #12
Okay now - removing the need for the timer.
We can check if we need the timer before setting it. That will allow us to remove the need for the separate timer variable.
if (counter <= 50) {
setTimeout(roll, 50);
else {
isRolling = false;
counter = 0;
}
Those 50's each have different meanings, so we should place those in a config options area.
var lotto = function (pick, from, to) {
var opts = {
totalRolls: 50,
rollDelay: 50
},
...
After other refactorings have occurred to simplify things, we'll replace those function parameters with a single options object instead.
The playing variable can be renamed to isRolling, and we can come back to that one later to decide if it's better as a variable, or a property on the button.
buttonText and initalText can go in to the opts object:
var opts = {
buttonText: "Lotto Lucky Dip",
initialText: "Your Lucky Numbers",
...
playButton.value = opts.buttonText;
...
resultDiv.innerHTML = opts.initialText;
Let us now split up the roll function in to separate parts.
First there is the validation code, which uses pick, from and to.
if (from >= to) {
window.alert("from value must be less than to value");
return false;
}
if ((to + 1) - from < pick) {
window.alert("Error - You want " + pick + " numbers.\
\
" + "The range you have entered is from " + from + " to " + to + ".\
" + "This leaves " + (rng + 1) + " available random numbers.");
return false;
}
Because both parts return false, we can use a standard validation technique of having an isValid variable at the start of the function, which gets set to false if anything fails, and then return isValid.
function validateChoices(pick, from, to) {
var isValid = true;
if (from >= to) {
window.alert("from value must be less than to value");
isValid = false;
}
if ((to + 1) - from < pick) {
window.alert("Error - You want " + pick + " numbers.\
\
" + "The range you have entered is from " + from + " to " + to + ".\
" + "This leaves " + (rng + 1) + " available random numbers.");
isValid = false;
}
return isValid;
}
...
if (!validateChoices(pick, from, to)) {
return false;
}
and the part of the roll function that draws the different numbers, can be extracted out to a drawNumbers function
function drawNumbers(pick, from, to) {
var draw = [],
rng = to - from,
e = (rng + 1),
i,
j,
number;
isRolling = true;
for (i = 0; i < pick; i += 1) {
number = parseInt(from + Math.random() * e, 10);
for (j = 0; j < pick; j) {
if (number !== draw[j]) {
j += 1;
} else {
number = parseInt(from + Math.random() * e, 10);
j = 0;
}
}
draw[i] = number;
}
return draw;
}
...
var i,
dum = "",
disp,
draw = drawNumbers(pick, from, to);
That drawNumbers function can now be refactored, so that instead of rng and e variables, we can just use a delta variable.
var draw = [],
delta = to - from + 1, // inclusive of both ends
and the random number functions we can move out to a separate getRandomInteger function
function getRandomInteger(from, to) {
var delta = to - from + 1; // inclusive of both ends
return parseInt(from + Math.random() * delta, 10);
}
...
number = getRandomInteger(from, to);
but we still need to simplify the nested loop that draws a new random number, which is currently:
for (i = 0; i < pick; i += 1) {
number = getRandomInteger(from, to);
for (j = 0; j < pick; j) {
if (number !== draw[j]) {
j += 1;
} else {
number = getRandomInteger(from, to);
j = 0;
}
}
draw[i] = number;
}
It may be easier to see what we need to do if we switch around the if/else statement
if (number === draw[j]) {
number = getRandomInteger(from, to);
j = 0;
} else {
j += 1;
}
So what we need to do, is to keep on picking numbers until we find one that has not already been picked.
We have a couple of different options here. We could tidy up the existing structure, or we could come up with a completely different solution where we randomize an array of numbers and then pick the first n from that array.
I'll leave off temporarily here to take care of some things, and consider those options.
pullo — 2013-04-29T05:31:46-04:00 — #13
Howdy,
So, I've just finished working through your latest set of refactorings.
I like how you are applying the single responsibility principle (if you can call it that). Already the code is starting to become a lot more readable.
I have some questions and some observations.
I'll reply to your posts separately, so as to make things easier to follow.
This was bothering me when I did the initial separation of HTML and JS.
Do you think you are ever likely to need multiple lotto rollers on the same page?
That would be good.
See my previous post
Why would you check for this?
What purpose does this line actually serve?
if ((document.getElementById && document.firstChild) && window.addEventListener || window.attachEvent) {
paul_wilkins — 2013-04-29T05:39:59-04:00 — #14
It's not ordinarily likely, but I can see a use for it.
there may be a page may list different pre-defined lotto draws
or a demo page that shows how different types of settings work
or people may be able to save lotto settings that they like, as different rollers on a custom page
It was a common technique with older web browsers, for example, with IE4 and earlier not supporting getElementById. It's not a check that we tend to use nowdays, but for the sake of completion I'll leave it in with an appropriately thrown exception.
pullo — 2013-04-29T05:48:51-04:00 — #15
I followed along with all of the refactorings, however one thing occurred to me.
If you move the validation into its own method, where should the call to validateChoices go?
Ideally, you want it to be called once, when the user presses "Update Lucky Dip" and not, as is currently happening, when the user presses "Lotto Lucky Dip" to start the draw.
However, as validateChoices is defined from within the lotto function, you cannot simply write:
form.onsubmit = function () {
var form = this,
pick = Number(form.elements.pick.value) || 0,
from = Number(form.elements.from.value) || 0,
to = Number(form.elements.to.value) || 0;
if (!validateChoices(pick, from, to)) {
return false;
}
lotto(pick, from, to);
return false;
};
This is where I get a bit confused with JS. In ruby you could write Lotto::validateChoices (Lotto being a class).
Anyway, I moved this:
if (!validateChoices(pick, from, to)) {
return false;
}
to the top of the lotto function after the variable declarations, so at least it only gets called once.
The downside of that, is that the function itself has no concept of the variable rng, so you have to write:
window.alert("Error - You want " + pick + " numbers.\
\
" + "The range you have entered is from " + from + " to " + to + ".\
" + "This leaves " + ((to - from) + 1) + " available random numbers.");
instead of:
window.alert("Error - You want " + pick + " numbers.\
\
" + "The range you have entered is from " + from + " to " + to + ".\
" + "This leaves " + (rng + 1) + " available random numbers.");
What are your thoughts on this?
pullo — 2013-04-29T05:51:19-04:00 — #16
Good point!
Ah ok. Thanks!
paul_wilkins — 2013-04-29T05:53:37-04:00 — #17
My thoughts on this are that it's okay for the range variable to be calculated in a few different sections. If a third or more situations occur though, that is a good time to refactor things further.
Alternatively, you can have a getRange() function which accepts to and from, and returns the calculated range to both areas.
Whichever one you choose is a choice on your part as author, about which one you feel will result in a greater understanding for the person reading the code.
paul_wilkins — 2013-04-29T07:08:34-04:00 — #18
It is tempting to randomize an array of values, but we don't know if people will choose to pick numbers from a large range of potential millions, so I'll go with the less brittle technique of checking if the chosen number already exists in the array.
I've moved the inner loop out to a separate function called arrayHasNumber(), which has allowed me to use a while loop in there, which represents what we are wanting to achieve to a much more accurate degree.
function drawNumbers(pick, from, to) {
var draw = [],
i,
number;
for (i = 0; i < pick; i += 1) {
do {
number = getRandomInteger(from, to);
} while (arrayHasNumber(draw, number));
draw[i] = number;
}
return draw;
}
With the arrayHasNumber function, I don't know if a persons web browser yet supports the Array.indexOf method, so we can check if that method exists before using it, and if not we can fall back to looping through the array.
In fact, there's a better way of doing this, so here it is just in a code block, to show what was going to be used:
function arrayHasNumber(array, number) {
// use native technique if available
if (Array.indexOf) {
return (array.indexOf(number) > -1);
}
// otherwise check manually
var i,
hasNumber = false;
for (i = 0; i < array.length; i += 1) {
if (number === array[i]) {
hasNumber = true;
break;
}
}
return hasNumber;
}
A better way, is to provide compatibility code for the Array.indexOf method right from the start, which we can get from https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
}
Now we can replace that arrayHasNumber function with:
function arrayHasNumber(array, number) {
return array.indexOf(number) > -1;
}
We might even remove the arrayHasNumber function and just put its code directly in the while loop, but that comes down to a choice of which is more expressive.
Either this:
} while (draw.indexOf(number) > -1);
or that:
} while (numberAlreadyExists(number, draw));
I might go for the latter, but it depends too on the potential audience.
The next part to refactor is the display of the drawn numbers.
for (i = 0; i < pick; i += 1) {
disp = dum += (draw[i] + " ");
}
counter += 1;
document.getElementById("result" + idx).firstChild.data = disp;
The loop can be replaced with a simple join statement, so we don't need the dum variable.
The resultDiv was defined earlier on, so we can use that here too instead of searching for it.
And the disp variable is used only once, so we can place the join at the end of the assignment.
So the above code is brought down to just the following:
resultDiv.innerHTML = draw.join(' ');
The last part of the roll function is about setting up the next roll:
counter += 1;
if (counter <= opts.totalRolls) {
setTimeout(roll, 50);
} else {
isRolling = false;
counter = 0;
}
The isRolling variable being in the same place as resetting the counter helps me to realise that the isRolling variable isn't even needed. We can just check if the counter is greater than 0, so all isRolling parts can be removed, and the playButton onclick function can instead have this in there instead:
if (counter > 0) {
return false;
}
So let's move the remaining code to its own function called setupNextRoll()
function setupNextRoll(totalRolls, rollDelay, callback) {
counter += 1;
if (counter <= totalRolls) {
setTimeout(callback, rollDelay);
} else {
counter = 0;
}
}
...
setupNextRoll(opts.totalRolls, opts.rollDelay, roll);
I'm passing the roll function at the end, because if we didn't do that then we would need the setupNextRoll function to refer to the roll function that is below it, which in turn refers to the function above it. Linting software complains about calls that go upwards, and the callback is a highly effective method to convey what is happening, so it solves a number of related issues.
That should do us for this part of things in the roll function. It's now looking nice and expressive, where validate before drawing, sorting, and showing the numbers, thengo to the next roll.
function roll() {
if (!validateChoices(pick, from, to)) {
return false;
}
var draw = drawNumbers(pick, from, to);
draw.sort(numericSort);
resultDiv.innerHTML = draw.join(' ');
setupNextRoll(opts.totalRolls, opts.rollDelay, roll);
}
The resultDiv part could be moved out to a separate function so that we can more easily separate the action of rolling from the act of showing the content, but there are bigger fish to fry for now.
Now that the roll function has been simplified we can move the function parameters to the opts object, which will help us to keep our configuration information all in the same consistent location.
var lotto = function (options) {
var opts = {
buttonText: "Lotto Lucky Dip",
initialText: "Your Lucky Numbers",
pick: options.pick,
from: options.from,
to: options.to,
totalRolls: 50,
rollDelay: 50
},
...
if (!validateChoices(opts.pick, opts.from, opts.to)) {
...
var draw = drawNumbers(opts.pick, opts.from, opts.to);
...
var form = this;
lotto({
pick: Number(form.elements.pick.value) || 0,
from: Number(form.elements.from.value) || 0,
to: Number(form.elements.to.value) || 0
});
What we end up with is shown at http://jsfiddle.net/pmw57/8R42e/18/
We are nearly ready now to init the lotto object using custom parameters, which will be delved in to about tomorrow.
pullo — 2013-04-29T09:04:32-04:00 — #19
Wow! Good stuff!
That is really well explained and easy to follow.
I have a couple of questions:
In your opinion, at what point does it become feasible to start monkey patching objects, as opposed to rolling your own (admittedly more limited) solution
I didn't quite get why you need to pass roll as a callback to setupNextRoll.
Look forward to the next instalment.
paul_wilkins — 2013-04-29T16:30:04-04:00 — #20
That can be something that different people disagree with, for myself, I am hesitant to fiddle with any pre-existing objects. In this case with Array.indexOf, it's a method that is built in to many web browsers and the behavior is well defined, so I am happy to help bring less capable web browsers along for the ride. Such As IE.
It's something that you have to be careful of though. The Prototype library monkey-patched getElementsByClassName which ended up causing all sorts of grief when web browsers eventually decided to do things slightly different.
A good explanation of what happened ther can be found in John Resig's getElementsByClassName pre-prototype 1.6 article.
The main thing that I was worrying about there was in terms of the linter that I use to help keep the code clean and tidy. JSLint can be a harsh mistress at times, but it helps to ensure that your code has a minimum of problematic issues. One of those is in regard to placing calls to functions further down that may not exist yet. This can be a complex issue, but here's a basic rundown of the situation.
You may have some code, that goes:
function foo() {
bar(); // this works
}
foo();
function bar() {
...
}
The problem comes when someone changes the second function to a function expression, for which there may be several reasons to do so.
function foo() {
bar(); // doesn't work
}
foo();
var bar = function () {
...
}
That doesn't work because the second function doesn't exist until it is actually defined. So, placing calls to lower areas of code can be problematic. So coders help to prevent that problem by placing calls to code that is above them.
So what happens when you have two functions that call each other?
function foo() {
setTimeout(bar);
}
function bar() {
alert('called');
if (Math.random() > 0.3) {
foo();
}
}
bar();
The first function is placing a call to the second one, which can cause problems due to what we saw above.
If you are going to live by rule that you don't call functions below you, something has to occur to stop the first function from calling further down. We can achieve that by passing it in to the first function as a callback, which also makes the function more flexible in how it behaves too.
function foo(callback) {
setTimeout(callback);
}
function bar() {
alert('called');
if (Math.random() > 0.3) {
foo(bar);
}
}
bar();
next page →
|
Are unix/linux sha256/sha512 passwords in /etc/shadow key-strengthened?
Yes. They use a crypt procedure that does a default of 5000 rounds of hashing. The sha256-crypt/sha512-crypt procedure is described hereand in java
Can I change the number of rounds?
Yes. Simply edit /etc/pam.d/passwd or /etc/pam.d/common-password (or solaris equivalent) and add 'rounds=73500` at the end of the line that looks similar to:
password [success=2 default=ignore] pam_unix.so obscure sha512 rounds=73500
and then change your password using passwd. Why 73500? Well, timing crypt with rounds=5000, I was getting about 3.4 ms per password. (5000*50/3.4 ~ 73500). You can check if a password in your /etc/shadow files was done an abnormal number of rounds if it looks starts with yourusername:$6$rounds=73500$RFzXZTGB$ where $6$ indicates the crypt procedure used (sha256-crypt is $5$, sha512-crypt $6$) followed by number of rounds and then the salt.
But I want bcrypt; Can I switch to that:
Check /etc/pam.d/ and (1) change all references of pam_unix.so to pam_unix2.so (check that the file is there) and (2) then change sha512 to blowfish in /etc/pam.d/common-password
http://serverfault.com/questions/10585/enable-blowfish-based-hash-support-for-crypt/11685#11685
One noticeable difference between bcrypt vs sha512-crypt; is that bcrypt work-factor scales exponentially; e.g., a work-factor of 12, should take double as long as a work-factor of 11, while sha512-crypt rounds scale linearly (e.g., rounds=10000 should take twice as long as rounds=5000). This is simply because bcrypt says do 2work-factor rounds. As a quick benchmark on my machine, one bcrypt round is more expensive than a sha512-crypt round; with a rough equivalence of ~4 ms with rounds=5000 or work-factor=6 (26=64 bcrypt-rounds). But as both can be scaled up this should not be an issue until the number of rounds overflow the unsigned 32-bit/64-bit int (when rounds = 4 billion or 1019 respectively).
Python timing Stuff With sha512-crypt
You can check crypt via python (in linux this performs just as fast as the C version as it just is a thin wrapper for the crypt library written in C)
>>> import crypt
>>> crypt.crypt('testtest', '$6$6LzxTFam$')
In python on my machine with the crypt module it takes about 3.4 ms per sha512-crypt password at 5000 rounds and ~50 ms with 73500 rounds.
>>> import timeit
>>> timer = timeit.Timer("crypt.crypt('testtest', '$6$6LzxTFam$')", setup="import crypt")
>>> timer.timeit(1000)
3.4215329647064209
# with 73500 rounds:
>>> timeit.Timer("crypt.crypt('testtest', '$6$rounds=73500$RFzXTGB$')", 'import crypt').timeit(1000)
50.738550186157227
|
Is there a effective quick way to generate a large prime of a given length?
'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 know where you are going with this and it is not necessary.
To answer your question, there is no extremely quick way.
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.
Online
Where am I going?
while True:
randomnumber = random.randrange(2**(length-1),(2**(length))-1)
if primep(randomnumber):
print randomnumber
break
Thats all I got from stackoverflow
Last edited by Agnishom (2013-09-21 21:16:47)
'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
You think you need a large prime to learn Diffie- Hellman. I can denmonstrate the procedure using a small one.
Thats all I got from stackoverflow
Hohohohohohohahahaha, they are always good for a laugh. To think that such brilliant people can still have a wonderful sense of humor gives me much hope for the human race.
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.
Online
You think you need a large prime to learn Diffie- Hellman. I can denmonstrate the procedure using a small one.
I can too. But that is not secure enough.
Sorry, I did not get the humor
'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 agree. But I thought you wanted to see how it worked?
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.
Online
I think the only problem is - after Alice and Bob have the shared secret, how do they exchange messages using it?
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
I have been waiting to answer that one since yesterday. But it seems I have missed Agnishom today.
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.
Online
I think the only problem is - after Alice and Bob have the shared secret, how do they exchange messages using it?
They use a symmetric cypher, like RC4 with the key.
'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
Let us take the generally accepted p from http://tools.ietf.org/html/rfc2409#section-6.2
179769313486231590770839156793787453197860296048756011706444423684197180216158519368947833795864925541502180565485980503646440548199239100050792877003355816639229553136239076508735759914822574862575007425302077447712589550957937778424442426617334727629299387668709205606050270810842907692932019128194467627007
The generator g is
2
'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
Hi Agnishom
My number:
170889576082067697731054176601909874828559452754928289693960008087616417613737398548717155229171096112124599345710842437121675819339812482513978573388985033018038377053945453188374711735023121936105534290646082341664680937820085667262891263915428892361981765346083422852575547729295502827704976423861860303103
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
Hi anonymnesty,
g[sup]b[/sup] (mod p)
173419298906489863864646388281941306843742681293608592957943679413527102401811311961611828206757391788738800024670641247258673805804085888390828078173388181181530749311360724611386280929348614725682444473741887149211776384725911058474047582365359321545094524307293842804350322782081718297375589621859722244791
Last edited by Agnishom (2013-09-22 16:34:05)
'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, just call me Stefy. It's easier for everybody that way.
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
Hi Stefy,
Sorry for the typo. Is what you posted in #11 g[sup]a[/sup] (mod p) ?
How should I use the secret key to message you now? What about RC4?
'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 have tested on my computer(Mac on Terminal).That doesn't generate any numbers!
Offline
I have tested on my computer(Mac on Terminal).That doesn't generate any numbers!
I am sorry, primep is defined externally. Do you want the full working code?
Last edited by Agnishom (2013-09-23 03:02:37)
'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
Hi Stefy,
Sorry for the typo. Is what you posted in #11 g[sup]a[/sup] (mod p) ?
How should I use the secret key to message you now? What about RC4?
It is.
Is there something more simple we could try first?
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
I have a nice tut on this if you need to see how it is done.
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.
Online
Hi bobbym
You can post them, if you want.
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
It uses baby sized numbers but maybe that is best for an example.
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.
Online
Sure. Any example would suffice, seeing how I am not sure at all how to use the shared secret.
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
Neither am I. How about we try to follow their example?
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.
Online
Their?
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
The video I have. They use an example. They go through the technique step by step. Should be easy to do with a real problem later on.
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.
Online
Could you post the link to the video?
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
|
Running python version 2.4.3. I am using python-amazon-product-api. However in api.py the following lines of code is causing problem:
if sys.version_info[:2] > (2, 4): # pragma: no cover
from urllib2 import quote
from hashlib import sha256 # pylint: disable-msg=E0611
else:
from urllib import quote
from Crypto.Hash import SHA256 as sha256
As my version is 2.4.3 it go in to else and try to import Crypto. So i downloaded that but i got import error in SHA256.py cannot import _SHA256. There is no _SHA256.py in library. After all my unsuccessful efforts i quit to use pyCrypto and i try to use standalone hashlib library. So i modified else part in api.py:
else:
from hashlib import hashlib
sha256 = hashlib.sha256()
Then again while importing hashlib i got this import error.
File "C:\Python24\lib\site-packages\hashlib.py", line 63, in __get_builtin_constructor
import _md5
ImportError: DLL load failed: The specified module could not be found.
I posted similar question yesterday but not able to find the exact solution that is why i am posting this again. I desperately need a solution :(
|
I am trying to copy from one location to other as below and running into following error,can anyone provide inputs as to how to overcome this?
import argparse
import shutil, errno
def copystuff(src, dst):
try:
shutil.copytree(src, dst)
except OSError as exc: # python >2.5
if exc.errno == errno.ENOTDIR:
shutil.copy(src, dst)
else: raise
def main ():
source= "\\Terminal\workspace\username\nfc\AU_LINUX_ANDROID_JB_3.2_RB2.04.03.00.129.005"
destination= "\\fosters\loc\LA\Build"
copy_list=['\out\target\product\msm8226\obj\KERNEL_OBJ\vmlinux']
for item in copy_list:
src = source + item
dest = destination + item
copystuff(src,dest)
if __name__ == '__main__':
Error:-
WindowsError: [Error 3] The system cannot find the path specified: '\\Terminal\workspace\username\nfc\AU_LINUX_ANDROID_JB_3.2_RB2.04.03.00.129.005\out\\target\\product\\msm8226\\obj\\KERNEL_OBJ\\vmlinux/*.*'
|
I'm trying to produce a plot in a loop that updates itself every iteration. Working in a linux environment with python 2.6.6 I have it working, but when I run the same code in windows XP with python 2.7.3 it fails. Minimal code that has produced this error for me is:
import matplotlib.pyplot as plt
plt.ion()
plt.figure(1)
for i in range(10):
plt.clf()
plt.plot(i,i**2,'bo')
plt.axis([-1,10, -1, 90])
plt.draw()
In linux I see a blue dot that moves itself along a parabola. In MSwindows I get an empty window to begin with and then a plot with a point at (9,81) appears. This seems pretty straightforward, but maybe I'm missing something small. Any suggestions?
|
I would like to use properties from an inheriting model's Meta class to configure a field defined in an abstract model higher up the inheritance tree:
class NamedModel(models.Model):
class Meta:
abstract = True
verbose_name = 'object'
name = models.CharField("Name",
max_length=200,
db_index=True,
help_text="A meaningful name for this %s." % Meta.verbose_name)
# see what I'm trying to do here?
)
...
class OwnedModel(NamedModel):
class Meta(NamedModel.Meta):
verbose_name = 'owned object'
I would like the help text on the name field of OwnedModel forms to say 'A meaningful name for this owned object'. But it does not: the word 'owned' is missing, which would suggest that the verbose_name from the NamedModel.Meta is used when the model is set up, not OwnedModel.Meta.
This isn't quite what I expect from an inheritance point of view: is there some way to get the field to be created whereby Meta.verbose_name refers to the value on the non-abstract model class, not the abstract one on which the field was defined?
Or am I being daft?
(This may seem like a trivial example, and it is: but it's just to illustrate the point of something more important and complex I am trying to do)
Many thanks in advance.
|
Please don't do that :) Dynamically re-sizing arrays as necessary is unnecessarily confusing. Multi-dimensional arrays are unnecessarily confusing too. So dynamically re-sizing a multi-dimensional array is unnecessarily torturous.
When the size of the array is dynamic, don't use an array. Use a Collection, instead, such as the List(Of T) class. And rather than using multiple dimensions, make a custom class that defines the objects that the list contains, for instance:
Public Class Person
Public Property ID As String
Public Property PhoneNumbers As New List(Of PhoneNumber)
End Class
Public Class PhoneNumber
Public Property Number As String
Public Property Description As String
End Class
Then, you can define your dynamic list of people, like this:
Dim people As New List(Of Person)
And you can add any number of phone numbers to a person, like this:
Dim person As New Person()
Dim phone As New PhoneNumber()
phone.Number = "123-123-1234"
person.PhoneNumbers.Add(phone)
Dim phone2 = New PhoneNumber()
phone2.Number = "123-123-4567"
person.PhoneNumbers.Add(phone2)
And you can, similarly, add multiple people, like this:
Dim person2 As New Person()
' ...
people.Add(person)
Dim person2 As New Person()
' ...
people.Add(person2)
|
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',
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
one action in "controllers/comments.py"
@auth.requires_login()
def post():
return dict(form=crud.create(db.comment),
comments=db(db.comment).select())
and the corresponding "views/comments/post.html"
{{extend 'layout.html'}}
{{for comment in comments:}}
<div class="comment">
on {{=comment.posted_on}} {{=comment.posted_by.first_name}}
says <span class="comment_body">{{=comment.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":
{{#extend 'layout.html' <- notice this is commented out!}}
{{for comment in comments:}}
<div class="comment">
on {{=comment.posted_on}} {{=comment.posted_by.first_name}}
says <span class="comment_body">{{=comment.body}}</span>
</div>
{{pass}}
{{=form}}
We can access it at the URL
http://127.0.0.1:8000/test/comments/post.load
and it will look like this:
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'}}
<p>{{='bla '*100}}</p>
{{=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,
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.
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.
*Please note:* 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'),
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)
(notice the last two lines define a function that will simplify the embedding of the plugin)
Second, we define a "controllers/plugin_comments.py"
@auth.requires_login()
def post():
comment = db.plugin_comments_comment
return dict(form=crud.create(comment),
comments=db(comment).select())
Third, we create a view called "views/plugin_comments/post.load":
{{for comment in comments:}}
<div class="comment">
on {{=comment.posted_on}} {{=comment.posted_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:
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.load',ajax=True)
Notice how all the code except the table definition is encapsulated in a single function. Also notice how the function creates an instance of a PluginManager.
Now in any other model in your app, for example in "models/db.py", you can configure this plugin as follows:
from gluon.tools import PluginManager
plugins = PluginManager()
plugins.comments.body_label = T('Post a comment')
The plugins object is already instantiated in the default scaffolding app in "models/db.py"
The PluginManager object is a thread-level singleton Storage object of Storage objects. That means you can instantiate as many as you like within the same application but (whether they have the same name or not) they act as if there were a single PluginManager instance.
In particular each plugin file can make its own PluginManager object and register itself and its default parameters with it:
plugins = PluginManager('name', param1='value', param2='value')
You can override these parameters elsewhere (for example in "models/db.py") with the code:
plugins = PluginManager()
plugins.name.param1 = 'other value'
You can configure multiple plugins in one place.
plugins = PluginManager()
plugins.name.param1 = '...'
plugins.name.param2 = '...'
plugins.name1.param3 = '...'
plugins.name2.param4 = '...'
plugins.name3.param5 = '...'
When the plugin is defined, the PluginManager must take arguments: the plugin name and optional named arguments which are default parameters. However, when the plugins are configured, the PluginManager constructor must take no arguments. The configuration must precede the definition of the plugin (i.e. it must be in a model file that comes first alphabetically).
Layout plugins
Layout plugins are simpler than component plugins because usually they do not contain code, but only views and static files. Yet you should still follow good practice:
First, create a folder called "static/plugin_layout_name/" (where name is the name of your layout) and place all your static files there.
Second, create a layout file called "views/plugin_layout_name/layout.html" that contains your layout and links the images, CSS and JavaScript files in "static/plugin_layout_name/"
Third, modify the "views/layout.html" so that it simply reads:
{{extend 'plugin_layout_name/layout.html'}}
{{include}}
The benefit of this design is that users of this plugin can install multiple layouts and choose which one to apply simply by editing "views/layout.html". Moreover, "views/layout.html" will not be packed by admin together with the plugin, so there is no risk that the plugin will override the user's code in the previously installed layout.
plugin_wiki
DISCLAIMER: plugin_wiki is still very much under development and therefore we do not promise backward compatibility to the same level as for web2py core functions.
plugin_wiki is a plugin on steroids. What we mean is that it defines multiple useful components and it may change the way you develop your applications:
You can download it from
http://web2py.com/examples/static/web2py.plugin.wiki.w2p
The idea behind plugin_wiki is that most applications include pages that are semi-static. These are pages that do not include complex custom logic. They contain structured text (think of a help page), images, audio, video, crud forms, or a set of standard components (comments, tags, charts, maps), etc. These pages may be public, require login or have other authorization restrictions. These pages may be linked by a menu or only be reachable via wizard form. plugin_wiki provides an easy way to add pages that fit in this category to your regular web2py applications.
In particular plugin_wiki provides:
A wiki-like interface that allows to add pages to your app and reference them by a slug. These pages (which we will refer to as wiki pages) have versions and are stored in the database.
Public and private pages (require login). If a page requires login, it may also require that the user have a particular group membership.
Three levels: 1,2,3. At level 1, pages can only include text, images, audio and video. At level 2, pages can also include widgets (these are components as defined in the previous section that can be embedded in wiki pages). At level 3, pages can also include web2py template code.
A choice of editing pages with the markmin syntax or in HTML using a WYSIWYG editor.
A collection of widgets: implemented as components. They are self documenting and they can be embedded as regular components in normal web2py views or, using a simplified syntax, into wiki pages.
A set of special pages (meta-code,meta-menu, etc.) that can be used to customize the plugin (for example define code the plugin should run, customize the menu, etc.)
Thewelcomeapp plus theplugin_wikican be thought of as a development environment in itself that is suitable for building simple web applications such as a blog.
From here on we will assume the plugin_wiki is applied to a copy of the welcome scaffolding app.
The first thing you notice after installing the plugin is that it adds a new menu item called pages.
Click on the pages menu item and you will be redirected to the plugin action:
http://127.0.0.1:8000/myapp/plugin_wiki/index
The plugin index page lists the pages created using the plugin itself and allows you to create new ones by choosing a slug. Try creating a home page. You will be redirected to
http://127.0.0.1:8000/myapp/plugin_wiki/page/home
Click on create page to edit its content.
By default, the plugin is at level 3, which means you can insert widgets as well as code in pages. By default it uses the markmin syntax to describe the page content.
MARKMIN syntax
Here is a primer for the markmin syntax:
markmin html
# title <h1>title</h1>
## subtitle <h2>subtitle</h2>
### subsubtitle <h3>subsubtitle</h3>
**bold** <strong>bold</strong>
''italic'' <i>italic</i>
http://... <a href="http://...com">http:...</a>
http://...png <img src="http://...png" />
http://...mp3 <audio src="http://...mp3"></audio>
http://...mp4 <video src="http://...mp4"></video>
qr:http://... <a href="http://..."><img src="qr code"/></a>
embed:http://... <iframe src="http://..."></iframe>
Notice that links, images, audio, and video files are embedded automatically. For more information on MARKMIN syntax, please refer to Chapter 5.
If the page does not exist, you will be asked to create one.
The edit page allows you to add attachments to pages (i.e. static files)
and you can link to them as
[[mylink name attachment:3.png]]
or embed them with
[[myimage attachment:3.png center 200px]]
The size (200px) is optional. center is not optional but it may be replaced by left or right.
You can embed blockquoted text with
-----this is blockquoted-----
as well as tables
-----0 | 0 | X0 | X | 0X | 0 | 0-----
and verbatim text
``verbatim text``
You can also prepend an optional :class to the final ----- or the final ``. For blockquoted text and tables it will be translated in the class of the tag, for example:
-----test-----:abc
renders as
<blockquote class="abc">test</blockquote>
For verbatim text the class can be used to embed content of different types.
You can, for example, embed code with syntax highlighting by specifying the language with :code_language
``
def index(): return 'hello world'
``:code_python
You can embed widgets:
``name: widget_nameattribute1: value1attribute2: value2``:widget
From the edit page you can click on "widget builder" to insert widgets from a list, interactively:
(for a list of widgets see the next subsection).
You can also embed web2py template language code:
``
{{for i in range(10):}}<h1>{{=i}}</h1>{{pass}}
``:template
Page permissions
When editing a page you will find the following fields:
active(defaults toTrue). If a page is not active, it will not be accessible to visitors (even if public).
public(defaults toTrue). If a page is public, it can be accessed by visitors without logging in.
role(defaults to None). If a page has a role, the page can be accessed only by visitors who are logged in and are members of the group with the corresponding role.
Special pages
meta-menu contains the menu. If this page does not exist, web2py uses the response.menu defined in "models/menu.py". The content of the meta-menu page overrides the menu. The syntax is the following:
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
where the indentation determines the submenu structure. Each item is composed of the text of the menu item followed by a link. A link can be page:slug. A link None does not link to any page. Extra spaces are ignored.
Here is another example:
Home page:home
Search Engines None
Yahoo http://yahoo.com
Google http://google.com
Bing http://bing.com
Help page:help
This renders as follows:
meta-codeis another special page and it must contain web2py code. This is an extension of your models, and in fact you can put model code here. It is executed when "models/plugin_wiki.py" code is executed.
You can define tables in meta-code.
For example, you can create a simple table "friends" by placing this in meta-code:
db.define_table('friend',Field('name',requires=IS_NOT_EMPTY()))
and you can create a friend-management interface by embedding in a page of your choice the following code:
## List of friends``name: jqgridtable: friend``:widget## New friend``name: createtable: friend``:widget
The page has two headers (starting with #): "List of friends" and "New friend". The page contains two widgets (under the corresponding headers): a jqgrid widget that lists friends and a crud create widget to add a new friend.
meta-header, meta-footer, meta-sidebar are not used by the default layout in "welcome/views/layout.html". If you want to use them, edit "layout.html" using admin (or the shell) and place the following tags in the appropriate places:
{{=plugin_wiki.embed_page('meta-header') or ''}}
{{=plugin_wiki.embed_page('meta-sidebar') or ''}}
{{=plugin_wiki.embed_page('meta-footer') or ''}}
In this way, the content of those pages will show up in the header, sidebar and footer in the layout.
Configuring plugin_wiki
As with any other plugins in "models/db.py" you can do
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'
where
editoris true if the current logged-in user is authorized to edit plugin_wiki pages
levelis the permission: 1 to edit regular pages, 2 to embed widgets in pages, 3 to embed code
modedetermines whether to use a "markmin" editor or a WYSIWYG "html" editor.WYSIWYG
themeis the name of the required jQuery UI Theme. By default only the color-neutral "ui-darkness" is installed.
You can add themes here:
static/plugin_wiki/ui/%(theme)s/jquery-ui-1.8.1.custom.css
Current widgets
Each widget can be embedded both in plugin_wiki pages and in normal web2py templates.
For example, to embed a YouTube video in a plugin_wiki page, you can do
``name: youtubecode: l7AWnfFRc7g``:widget
or to embed the same widget in a web2py view, you can do:
{{=plugin_wiki.widget('youtube',code='l7AWnfFRc7g')}}
In either case, this is the output:
Widget arguments that do not have a default value are required.
Here is a list of all current widgets:
read
read(table,record_id=None)
Reads and displays a record
tableis the name of a table
record_idis a record number
create
create(table,message='',next='',readonly_fields='', hidden_fields='',default_fields='')
Displays a record create form
tableis the name of a table
messageis a the message to be displayed after record is created
nextis where to redirect, example "page/index/[id]"
readonly_fieldsis a list of comma separated fields
hidden_fieldsis a list of comma separated fields
default_fieldsis a list of comma separatedfieldname=value
update
update(table,record_id='',message='',next='', readonly_fields='',hidden_fields='',default_fields='')
Displays a record update form
tableis the name of a table
record_idis he record to be updated or{{=request.args(-1)}}
messageis a the message to be displayed after record is created
nextis where to redirect, example "page/index/[id]"
readonly_fieldsis a list of comma separated fields
hidden_fieldsis a list of comma separated fields
default_fieldsis a list of comma separatedfieldname=value
select
select(table,query_field='',query_value='',fields='')
Lists all records in the table
tableis the name of a table
query_fieldandquery_valueif present will filter records by according to the queryquery_field == query_value
fieldsis a list of comma separate fields to be displayed
search
search(table,fields='')
Widgets for selecting records
tableis the name of a table
fieldsis a list of comma separated fields to be displayed
jqgrid
jqgrid(table,fieldname=None,fieldvalue=None,col_widths='',
colnames=None,_id=None,fields='',col_width=80,width=700,height=300)
Embeds a jqGrid plugin
tableis the table name
fieldname,fieldvalueare an optional filter:fieldname==fieldvalue
col_widthsis the width of each column
colnamesis a list of column names that are displayed
_idis the "id" of the TABLE that contains the jqGrid
fieldsis a list of columns to be displayed
col_widthis the default width of columns
heightis the height of the jqGrid
widthis the width of the jqGrid
Once you have the plugin_wiki installed, you can easily use the jqGrid in your other views too. Example usage (displays yourtable filtered by fk_id==47):
{{=plugin_wiki.widget('jqgrid','yourtable','fk_id',47,'70,150',
'Id,Comments',None,'id,notes',80,300,200)}}
latex
latex(expression)
Uses Google charting API to embed LaTeX
pie_chart
pie_chart(data='1,2,3',names='a,b,c',width=300,height=150,align='center')
Embed a pie chart
datais a list of comma separated values
namesis a list of comma separated labels (one for data item)
widthis the width of the image
heightis the height of the image
aligndetermines the alignment of the image
bar_chart
bar_chart(data='1,2,3',names='a,b,c',width=300,height=150,align='center')
Uses Google charting API to embed a bar chart
datais a list of comma separated values
namesis a list of comma separated labels (one for data item)
widthis the width of the image
heightis the height of the image
aligndetermines the alignment of the image
slideshow
slideshow(table, field='image', transition='fade', width=200, height=200)
Embeds a slideshow. It gets the images from a table.
tableis the table name
fieldis the upload field in the table that contains images
transitiondetermines the type of transition, e.g. fade, etc.
widthis the width of the image
heightis the height of the image
youtube
youtube(code, width=400, height=250)
Embeds a YouTube video (by code)
codeis the code of the video
widthis the width of the image
heightis the height of the image
vimeo
vimeo(code, width=400, height=250)
Embeds a Vimeo video (by code)
codeis the code of the video
widthis the width of the image
heightis the height of the image
mediaplayer
mediaplayer(src, width=400, height=250)
Embeds a media file (such as Flash video or an mp3 file)
srcis the src of the video
widthis the width of the image
heightis the height of the image
comments
comments(table='None', record_id=None)
Embeds comments in the page
Comments can be linked to a table and/or a record
tableis the table name
record_idis the id of the record
tags
tags(table='None', record_id=None)
Embeds tags in the page
tags can be linked to a table and/or a record
tableis the table name
record_idis the id of the record
tag_cloud
tag_cloud()
Embeds a tag cloud
map
map(key='....', table='auth_user', width=400, height=200)
Embeds a Google map.
It gets points on the map from a table
keyis the google map api key (default works for 127.0.0.1)
tableis the table name
widthis the map width
heightis the map height
The table must have columns: latitude, longitude and map_popup. When clicking on a dot, the map_popup message will appear.
iframe
iframe(src, width=400, height=300)
Embeds a page in an <iframe></iframe>
load_url
load_url(src)
Loads the content of the url using the LOAD function
load_action
load_action(action, controller='', ajax=True)
Loads the content of URL(request.application, controller, action) using the LOAD function
Extending widgets
Widgets to plugin_wiki can be added by creating a new model file called "models/plugin_wiki_"name where name is arbitrary and the file contains something like:
class PluginWikiWidgets(PluginWikiWidgets):
@staticmethod
def my_new_widget(arg1, arg2='value', arg3='value'):
"""
document the widget
"""
return "body of the widget"
The first line states that you are extending the list of widgets. Inside the class, you can define as many functions as needed. Each static function is a new widget, except for functions that start with underscores. The function can take an arbitrary number of arguments which may or not have default values. The docstring of the function must document the function using the markmin syntax itself.
When widgets are embedded into plugin_wiki pages, arguments will be passed to the widget as strings. This means the widget function must be able to accept strings for every argument and eventually convert them into the required representation. You can decide what the string representation must be - just make sure this is documented in the docstring.
The widget can return a string of web2py helpers. In this latter case they will be serialized using .xml().
Notice how the new widget can access any variable declared in the global namespace.
As an example, we are going to create a new widget that display the "contact/ask" form created at the beginning of this chapter. This can be done by creating a file "models/plugin_wiki_contact" that contains:
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.process().accepted:
if mail.send(to='admin@example.com',
subject='from %s' % form.vars.your_email,
message = form.vars.question):
command="jQuery('#%s').hide()" % div_id
response.flash = 'Thank you'
response.js = "jQuery('#%s').hide()" % request.cid
else:
form.errors.your_email="Unable to send the email"
return form.xml()
plugin_wiki widgets are not rendered by a view unless the response.render(...) function is called explicitly by the widget.
top
|
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()
|
Like in this question, except I want to be able to have querysets that return a mixed body of objects:
>>> Product.objects.all()
[<SimpleProduct: ...>, <OtherProduct: ...>, <BlueProduct: ...>, ...]
I figured out that I can't just set Product.Meta.abstract to true or otherwise just OR together querysets of differing objects. Fine, but these are all subclasses of a common class, so if I leave their superclass as non-abstract I should be happy, so long as I can get its manager to return objects of the proper class. The query code in django does its thing, and just makes calls to Product(). Sounds easy enough, except it blows up when I override Product.__new__, I'm guessing because of the __metaclass__ in Model... Here's non-django code that behaves pretty much how I want it:
class Top(object):
_counter = 0
def __init__(self, arg):
Top._counter += 1
print "Top#__init__(%s) called %d times" % (arg, Top._counter)
class A(Top):
def __new__(cls, *args, **kwargs):
if cls is A and len(args) > 0:
if args[0] is B.fav:
return B(*args, **kwargs)
elif args[0] is C.fav:
return C(*args, **kwargs)
else:
print "PRETENDING TO BE ABSTRACT"
return None # or raise?
else:
return super(A).__new__(cls, *args, **kwargs)
class B(A):
fav = 1
class C(A):
fav = 2
A(0) # => None
A(1) # => <B object>
A(2) # => <C object>
But that fails if I inherit from django.db.models.Model instead of object:
File "/home/martin/beehive/apps/hello_world/models.py", line 50, in <module>
A(0)
TypeError: unbound method __new__() must be called with A instance as first argument (got ModelBase instance instead)
Which is a notably crappy backtrace; I can't step into the frame of my __new__ code in the debugger, either. I have variously tried super(A, cls), Top, super(A, A), and all of the above in combination with passing cls in as the first argument to __new__, all to no avail. Why is this kicking me so hard? Do I have to figure out django's metaclasses to be able to fix this or is there a better way to accomplish my ends?
|
Introduction
web2py[web2py] est un framework web libre et open-source pour le développement agile et sécurisé d'applications web pilotées par base de données; il est écrit en Python[python] et programmable en Python. web2py est un framework complet, contenant donc tous les composants nécessaires pour construire des applications web totalement fonctionnelles.
web2py est conçu pour guider le développeur web à suivre les bonnes pratiques de l'ingénierie logicielle, telles que l'utilisation du pattern Modèle Vue Contrôleur (MVC). web2py sépare la représentation des données (modèle) de la présentation des données (la vue) et également de la logique applicative et de ses flux de travail (le contrôleur). web2py fournit des librairies pour aider le développeur à dessiner, implémenter et tester chacune des trois parties séparément, et les faire fonctionner ensemble.
web2py est construit pour la sécurité. Cela signifie qu'il élimine automatiquement la plupart des problèmes qui peuvent amener à des failles de sécurité, en suivant des pratiques bien établies. Par exemple, toute entrée est validée (pour éviter les injections), toute sortie est contrôlée (pour éviter le cross-site scripting), et tout fichier uploadé est renommé (pour éviter toute attaque traverse de répertoireà. web2py fait attention aux principaux problèmes de sécurité, afin que les développeurs aient le moins de chande d'introduire des failles dans leur développement.
web2py inclut une couche d'abstraction à la base de données (Database Abstraction Layer -DAL) qui écrit les requêtes SQL[sql-w] dynamiquement afin que vous, développeurs, n'ayez pas à le faire. Cette couche d'abstraction (DAL) sait parfaitement comment générer les requêtes SQL de manière transparente pour SQLite[sqlite], MySQL[mysql], PostgreSQL[postgres], MSSQL[mssql], FireBird[firebird], Oracle[oracle], IBM DB2[db2], Informix[informix] et Ingres[ingresdb].
La couche d'abstraction peut également générer des appels de fonction pour le Datastore Google lorsqu'elle fonctionne sur les Google App Engine (GAE)[gae]. De manière expérimentale, nous supportons plus de bases de données et de nouvelles sont constamment ajoutées. Veuillez vérifier le site web de web2py et la mailing list pour trouver les connecteurs les plus récents. Une fois qu'une ou plusieurs tables ont été définies, web2py génère automatiquement une interface d'aministration web complète pour accéder à la base de données et aux tables.
web2py diffère des autres frameworks web du fait que ce soit le seul à totalement adopter le paradigme Web 2.0, où le web est l'ordinateur. En fait, web2py ne nécessite aucune installation ou configuration; il fonctionne sur n'importe quelle architecture qui peut exécuter du Python (Windows, Windows CE, Mac OS X, iOS, et Unix/Linux), et le développement, le déploiement, et les phases de maintenance phases pour les applications peuvent être faites via une interface web locale ou distante. web2py fonctionne avec CPython (l'implémentation C) et PyPy (Python écrit en Python), sur les versions Python 2.5, 2.6, et 2.7.
web2py fournit un système de tickets pour les erreurs remontées. Si une erreur survient, un ticket est attribué à l'utilisateur et l'erreur est enregistrée pour l'administrateur.
web2py est open source et distribué sous la licence LGPG version 3.
Une autre fonctionnalité importante de web2py est que nous, ses développeurs, travaillons à maintenir une rétro-compatibilité pour les versions futures. Ce maintien est assuré depuis la sortie de la première release de web2py en Octobre 2007. De nouvelles fonctionnalités ont été ajoutées et des bugs ont été corrigés, mais si le programme fonctionnait avec web2py 1.0, alors ce programme fonctionnera même mieux aujourd'hui.
Trouvez ici quelques exemples de déclarations web2py qui illustrent leur pouvoir et leur simplicité. Le code suivant :
db.define_table('person', Field('name'), Field('image', 'upload'))
créé une table de base de données appelée "person" avec deux champs : "name", une chaîne de caractères ; et "image", quelque chose qui a besoin d'être uploadé (l'image actuelle dans ce cas). Si la table existe déjà mais ne correspond pas à cette définition, elle va être modifiée en conséquence.
Etant donné la table définie ci-dessus, le code suivant :
form = SQLFORM(db.person).process()
créé un formulaire d'insertion pour cette tables qui permet aux utilisateurs d'uploader les images. Cela valide également le formulaire soumis, renomme l'image envoyée de manière sécurisée, stocke l'image dans un fichier, insère l'enregistrement correspondant dans la base de données, évite une double soumission, et modifie éventuellement le formulaire lui-même en ajoutant les messages d'erreur si les données transmises par l'utilisateur ne sont pas valides.
Ce code embarque un wiki totalement fonctionnel contenant tags, recherche, nuage de tags, permissions, pièces jointes, et le support:
def index(): return auth.wiki()
Alors que le code suivant :
@auth.requires_permission('read','person')
def f(): ....
empêche les visiteurs d'accéder à la fonction f à moins que le visiteur soit un membre du groupe ayant les droits de "lecture" sur les enregistrement de la table "person". Si le visiteur n'est pas connecté, il est redirigé sur une page d'identification (fournie automatiquement par défaut par web2py).
web2Py supporte également les composants, c'est à dire les actions qui peuvent être chargées dans une vue et intéragir avec le visiteur via des requêtes Ajax sans avoir à recharger la page entière. Ceci est fait via l'assistant LOAD qui autorise un design très modulaire des applications; ce sujet est traité dans le chapitre 3 dans le contexte du wiki et un peu plus en détails dans le dernier chapitre de ce livre.
Cette 5ème édition de ce livre décrit web2py 2.4.1 et les versions suivantes.
Principes
La programmation Python respecte typiquement les principes de base suivants :
Ne pas se répéter soi-même.
Il ne devrait y avoir qu'une seule façon de faire les choses.
Explicite est mieux qu'implicite.
web2py englobe totalement les deux premiers principes en forçant le développeur à utiliser les pratiques d'ingénierie logicielle du son décourageant toute répétition de code. web2py accompagne le développeur à travers quasiment toutes les tâches communes dans le développement d'application web (création et traitement des formulaires, gestion des sessions, des cookies, des erreurs, etc...)
web2py diffère des autres frameworks par rapport au troisième principe, entrant parfois en conflit avec les deux autres. En particulier, web2py n'importe pas les applications utilisateur, mais les exécute dans un contexte prédéfini. Ce contexte révèle les mots-clés Python, aussi bien que les mots-clés web2py.
Pour certains, ceci peut apparaître comme magique, mais cela ne devrait pas. Simplement, en pratique, quelques modules sont déjà importés sans que vous l'ayez fait. web2py essaie d'éviter ces caractéristiques ennuyantes des autres frameworks qui forcent le développeur à importer les mêmes modules en haut de chaque modèle et contrôleur.
web2py, en important ses propres modules, fait gagner du temps et évite des erreurs, qui plus est en respectant l'esprit du "ne te répète pas toi-même" et "il ne devrait y avoir qu'une façon de faire les choses".
Si le développeur souhaite utiliser d'autres modules Python ou des modules tiers, ces modules doivent être importés explicitement, comme dans n'importe quel autre programme Python.
Frameworks web
A son niveau le plus fondamental, une application web consiste en un ensemble de programmes (ou fonctions) qui sont exécutées lorsque l'URL correspondante est visitée. La sortie du programme est retournée au visiteur et rendue par le navigateur.
Le but des frameworks web est d'autoriser les développeurs à construire de nouvelles applications rapidement, facilement et sans erreurs. C'est faisable en fournissant les APIs et les outils qui réduisent et simplifient la quantité de code requise.
Les deux approches classiques pour le developpement d'applications web sont:
Le premier modèle est celui qui est suivi, par exemple, immédiatement par des scripts CGI. Le second modèle est suivi, par exemple, par PHP[php] (où le code est en PHP, un langage similaire au C), ASP (où le code est en Visual Basic), et JSP (où le code est en Java).
Ci-dessous, un exemple de programme PHP qui retrouve les données depuis une base de données lors de son exécution, et qui retourne une page HTML affichant les enregistrement sélectionnés :
<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>
Le problème avec cette approche est que le code est embarqué dans l'HTML, et ce même code a besoin de générer du contenu HTML additionel. Il a également besoin de générer des déclarations SQL pour requêter la base de données, et en mélangeant ces différentes couches de l'application, la lecture et la maintenance du code devient très difficile. Cette situation est d'autant plus difficile pour des applications Ajax, que la complexité augmente avec le nombre de pages (fichiers) qui constituent l'application.
Cette fonctionnalité présentée dans l'exemple ci-dessus peut être exprimée avec seulement deux lignes de code Python dans web2py :
def index():
return HTML(BODY(H1('Records'), db().select(db.contacts.ALL)))
Dans cet exemple simple, la structure de la page HTML est représentée de manière programmée par les objets HTML, BODY, et H1; la base de données db est requêtée par la commande select; et finalement, tout est sérialisé dans l'HTML. Notons bien que db n'est pas un mot-clé mais bien une variable définie par l'utilisateur. Cette terminologie sera utilisée tout au long du document pour représenter la connection à la base de données pour éviter toute confusion.
Les frameworks web sont généralement catégorisés comme l'un des types suivants : Un framework "glue" est un framework construit en assemblant (en collant ensemble) plusieurs composants tiers. Un framework "complet" est construit en créant des composants prévus spécifiquement pour être étroitement intégrés et fonctionnels ensemble.
web2py est un framework complet. Presque tous ses composants sont construits de zéro et sont prévus pour fonctionner ensemble, mais fonctionnant aussi bien en dehors du framework web2py. Pour exemple, la couche d'abstration à la base de données (DAL) or les templates de langues peuvent être utilisés indépendamment du framework web2Py en important gluon.dal ou gluon.template dans vos propres propres applications Python. gluon est le nom du module web2py qui contient des librairies système. Quelques librairies web2py, telles que la construction pour le traitement des tables de la base de données par les formulaires, ont des dépendances avec d'autres parties de web2Py. web2py peut également fonctionner avec des librairies Python tierces, incluant d'autres templates de langue et couches d'abstrations à la base de données, mais ne seront pas aussi bien intégrés que les composants originaux.
Modèle-Vue-Contrôleur
wzb2py encourage le développeur à séparer la représentation des données (le modèle), la présentation des données (la vue) et le traitement du flux applicatif (le contrôleur). Reconsidérons l'exemple précédent et voyons comment il est possible de construire une application web2py autour. Ci-après, un exemple d'interface d'édition MVC web2py :
Le flux générique d'une requête web2py est décrit dans le diagramme suivant :
Dans le diagramme :
Le serveur peut être intégré au serveur web we2py où bien un serveur tiers, tel qu'un serveur Apache. Le serveur prend en charge le multi-threading .
"main" est l'application WSGI principale. Elle exécute toutes les tâches communes et englobe les application utilisateur. Il gère les cookies, les sessions, les transactions, le routage d'URL et le routage inverse, ainsi que le déploiement.
Elle peut proposer et diffuser des fichiers statiques si le serveur ne le fait pas encore.
Les composants Modèle (Model), Vue (View) et Contrôleur (Controller) construisent l'application utilisateur.
Plusieurs applications peuvent être hébergées sur une même instance web2py.
Les flèches en pointillés représentent la communication avec le(s) moteur(s) de base de données. Les requêtes à la base peuvent être écrites en langage SQL pur (déconseillé) ou en utilisant la couche d'abstration à la base de données (recommandé), afin que le code de l'application web2py ne soit pas dépendant d'un moteur spécifique de base de données.
Le répartiteur créé le lien entre les URL demandées et un appel de fonction dans le contrôleur. La sortie de la fonction peut être une chaîne de caractères ou un dictionnaire de symboles (une table de hash). Les données contenues dans le dictionnaire sont affichées par une vue. Si le visiteur demande une page HTML (comportement par défaut), le dictionnaire est rendu comme page HTML. Si le visiteur demande la même page en XML, web2py essaie de trouver une vue qui peut effectuer le rendu du dictionnaire en XML. Le développeur peut créer des vues pour effectuer des rendus dans n'importe lequel des protocoles déjà supportés (HTML, XML, JSON, RSS, CSV, et RTF) ou dans des protocoles personnalisés additionels.
Tous les appels sont englobés dans une transaction, et n'impote quelle exception non traitée entraînera l'annulation de la transaction. Si la requête réussit, la transaction est validée.
web2py prend également en charge les sessions et les cookies de session automatiquement, et lorsqu'une transaction est validée, la session est alors stockée, à moins qu'un autre comportement n'ait été spécifié.
Il est possible d'enregistrer des tâches récurrentes (via cron) pour démarrer de manière programmée et/ou après l'exécution de certaines actions. Par ce moyen, il est possible de démarrer de longues tâches intensives en arrière-plan sans ralentir la navigation.
Ci-après, une application minimale et complète MVC, en trois fichiers :
"db.py" est le modèle :
db = DAL('sqlite://storage.sqlite')
db.define_table('contact',
Field('name'),
Field('phone'))
Une connexion à la base de données est établie (dans cet exemple, une base de données SQLite est stockée dans le fichier storage.sqlite) et une table nommée contact est définie. Si la table n'existe pas, web2Py la créé et, de manière transparente en arrière-plan, génère le code SQL approprié pour le moteur de base de données choisi et utilisé. Le développeur peut voir la requête SQL générée mais n'a pas besoin de changer le code si le système de base de données, par défaut en SQLite, est remplacé par MySQL, PostgreSQL, MSSQL, FireBird, Oracle, DB2, Informix, Interbase, Ingres ou Google App Engine (SQL et NoSQL).
Une fois la table définie et créée, web2py génère également une interface de gestion web entièrement fonctionnel pour la base de données, appelée appadmin, pour accéder à la base et à ses tables.
"default.py" est le contrôleur :
def contacts():
grid=SQLFORM.grid(db.contact, user_signature=False)
return locals()
Dans web2py, les URLs sont liées à des modules Python et à des appels de fonction. Dans ce cas, le contrôleur contient une fonction unique (ou "action") appelé contacts. Une action peut retourner une châine de caractères (la page web) ou un dictionnaire Python (un ensemble de paires clé:valeur) ou un ensemble de variables locales (comme dans cet exemple). Si la fonction retourne un dictionnaire, le tout est transmis à une vue avec le même nom que le nom de la fonction (ou du contrôleur), qui effectue le rendu de la page en retour. Dans cet exemple, la fonction contacts génère une grille de select/search/create/update/delete pour la table db.contact et renvoie la grille à la vue.
"default/contacts.html" est la vue:
{{extend 'layout.html'}}
<h1>Manage My Contacts</h1>
{{=grid}}
Cette vue est appelée automatiquement par web2py après que la fonction associée du contrôleur (action) ait été exécutée. Le but de cette vue est d'effectuer le rendu des variables contenues par le dictionnaire retourné (dans notre cas grid) en HTML. Le fichier de vue est écrit en HTML, mais peut embarquer du code Python délimité par les balises spéciales {{ et }}. Ceci diffère un peu du code d'exemple PHP, car le seul code embarqué dans l'HTML est le code de "couche de présentation". Le fichier "layout.html" au début de la vue est fournie par web2py et constitue la mise en page pour toutes les applications web2py. Ce fichier peut facilement être modifié ou remplacé.
Pourquoi Web2py
web2py est l'un des nombreux frameworks d'application web, mais il est devenu très persuasif grâce à de nombreuses fonctionnalités uniques. web2py était à la base développé comme un outil d'apprenrissage, avec les motivations principales suivantes :
Facilité pour les utilisateurs à apprendre le développement côté serveur sans compromettre de fonctionnalité. Pour cette raison, web2py ne requiert aucune installation ou configuration, n'a pas de dépendences (à l'exception de la distribution du code source qui requiert Python 2.5 et ses librairies standard), et présente la plupart de ses fonctiionnalités via une interface web, incluant un Environnement de Développement Intégré avec les outils de débogage et une interface pour la base de données.
web2py a été stable dès le premier jour grâce à une approche descendante; c'est à dire que l'API a été dessinée avant d'être implémentée. Même si de nouvelles fonctionnalités ont été ajoutées, web2py n'a jamais cessé sa rétro-compatibilité, et ne l'arrêtera pas lorsque de nouvelles fonctionnalités seront ajoutées dans le futur.
web2py s'intéresse de manière pro-active aux plus importantes failles de sécurité qui peuvent tourmenter les applications web les plus modernes comme déterminé par OWASP[owasp]ci-après.
web2py est très léger. Le coeur du système (librairies), incluant la couche d'abstration à la base de données, les modèles de langues, et tous les assistants ne pèsent que 1.4MO. Le code source entier incluant les des exemples d'application et les images pèsent environ 10.4MO.
web2py a une empreinte très petite et est très rapide. Il utilise le serveur web WSGI Rocket rocketdéveloppé par Timothy Farrell. Sa rapidité est comparable à celle obtenue grâce au module Apache mod_wsgi, et supporte SSL et IPv6.
web2py utilise la syntaxe Python pour les modèles, les contrôleurs et les vues, mais n'importe pas les modèles et contrôleurs (comme font tous les autres frameworks) - au lieu de cela, il les exécute. Cela signifie que les applications peuvent être installées, déinstallées et modifiées sans avoir à redémarrer le serveur web (même en production), et différentes applications peuvent co-exister sans qu'il y ait d'interférence entre les modules.
web2py utilise une couche d'abstraction à la base de données (Database Abstraction Layer - DAL) au lieu d'un d'un Mapping Objet-Relationnel (Object Relational Mapper - ORM). D'un point de vue conceptuel, ceci signifie que différentes tables de la base de données sont mappées en différentes instances d'une classe Tableet non pas en différentes classes, alors que les enregistrements sont mappés en instances d'une classeRowet non en instances d'une classe de la table correspondate. D'un point de vue pratique, cela signifie que la syntaxe SQL effectue des correspondances presque une à une en syntaxe DAL, et qu'il n'y a aucune meta-classe complexe à programmer comme dans la plupart des ORM, ce qui ajouterait de la latence.
Ci-après, une capture d'écran de l'interface admin principale de web2py :
Sécurité
L'"Open Web Application Security Project" [owasp] (OWASP) est une communauté internationale libre et ouverte avec pour principal but l'amélioration de la sécurité des applications logicielles.
OWASP a listé le top 10 des problèmes de sécurité entraînant un risque pour les applications web. Cette liste est copiée ici, avec une description pour chacune sur l'impact avec web2Py :
cross site scripting"Cross Site Scripting (XSS): les failles XSS apparaissent lorsqu'une application utilise des données fournies par l'utilisateur et les envoie à un navigateur web sans effectuer une première validation ou encodage du contenu. XSS permet aux attaquants d'exécuter des scripts sur le navigateur de la victime qui peuvent détourner des sessions utilisateur, dégrader des sites web, potentiellement injecter des virus, etc..."web2py, par défaut, rejette toute variable injectée dans la vue, pour éviter tout XSS.
injection flaws"Les failles d'injection : ces failles, particulièrement en injection SQL, sont communes aux applications web. Une injection arrive lorsque les données fournies par l'utilisateur sont envoyées à un interpréteur comme commande ou requête. Les données de l'attaquant brouillent l'interpréteur en exécutant des commandes inattendues ou en changeand des données."web2py inclut une couche d'abstraction à la base de données rendant l'injection SQL impossible. Normalement, les déclarations SQL ne sont pas écrités par le développeur. Au lieu de cela, la requête SQL est générée dynamiquement par la couche d'abstraction à la base de données, s'assurant ainsi que toute donnée à insérer dans la base est correctement formatée.
malicious file execution"Exécution de fichier malicieux : du code vulnérable à de l'inclusion de fichier distant (Remote File Inclusion - RFI) permet à un attaquant d'inclure du code et des données hostiles, résultant en des attaques dévastatrices, telle qu'une mise en péril d'un serveur entier."web2py n'autorise que les fonctions exposées à être exécutées, évitant ainsi l'exécution de fichier malicieux. Les fonctions importées ne sont jamais exposées; seules les actions sont exposées. web2py utilise un interface d'aministration web qui rend très facile le suivi de ce qui est exposé et de ce qui ne l'est pas.
insecure object reference"Référence directe à un oject non sécurité : une référence directe à un objet peut survenir lorsqu'un développeur expose une référence à l'implémentation d'un objet interne, tel qu'un fichier, un répertoire, un enregistrement en base de données ou une clé, comme une URL ou un paramètre de formulaire. Les attaquants peuvent manipuler ces références pour obtenir l'accès à d'autres objets sans autorisation."web2py n'expose aucun objet interne; de plus, web2py valide toutes les URLs, évitant ainsi les attaques transverses de répertoire (directory travesal attacks). web2py fournit également un mécanisme simple pour crééer des formulaires qui valident automatiquement toutes les valeurs en entrée.
CSRF"Les requêtes criminelles Cross-Site (Cross Site Request Forgery - CSRF): Une attaque CSRF force le navigateur d'une victime connectée à envoyer une requête pré-authentifiée à une application web vulnérable, forçant ainsi le navigateur de la victime à exécuter une action hostile au bénéfice de l'attaquant. CSRF peut être aussi puissant que l'application web qu'il attaque."web2py évite les CSRF aussi bien que les doubles soumissions accidentelles de formulaires en assigant un jeton aléatoire éphémère à chaque formulaire. De plus, web2py utilise un UUID pour les cookies de session.
information leakageimproper error handling"Les fuites d'information et la prise en charge d'erreurs incorrectes : Les applications peuvent non intentionnellement laisser des fuites d'information sur leur configuration, des travaux internes, ou porter atteinte à l'intimité à travers une variété de problèmes applicatifs. Les attaquants utilisent cette faiblesse pour voler des données sensibles, ou conduire à des attaques plus sérieuses."web2py inclut un système de ticket. AUcune erreur ne peut résulter en code qui serait exposé à l'utilisateur. Toutes les erreurs sont loguées et un ticket est assigné à l'utilisateur autorisant le suivi de l'erreur. Mais les erreurs et le code source impliqué ne sont uniquement accessibles que par l'administrateur.
"Authentification cassée et gestion de session : les identifiants de compte et les jetons de session ne sont souvent pas protégés correctement. Les attaquants peuvent détourner les mots de passe, les clés ou les jetons d'authentifications pour utiliser l'identité d'autres utilisateurs." web2Py fournit un mécanisme intégré pour l'authentification administrateur, et gère les sessions indépendamment pour chaque application. L'interface d'administration force l'utilisation de cookies de session sécurisés lorsque le client n'est pas en "localhost". Pour les applications, une puissante API basée sur des contrôles d'accès par rôle (Role Base Access Control) est inclue.
cryptographic store"Stockage cryptographique non sécurisé : les applications web utilisent très rarement les fonctions de cryptographie correctement pour protéger les données et les identifiants de connexion. Les attaquants utilisent des données faiblement protégées pour effectuer du vol d'identification et autres crimes, telles que les fraudes de carte de crédit."web2py utilise les algorithmes de hachage MD5 ou HMAC+SHA-512 pour protéger les mots de passe stockés. Les autres algorithmes sont également disponibles.
secure communications"Communications non sécurisées : les applications échouent fréquemment pour chiffrer le trafic réseau lorsqu'il est nécessaire de protéger des communications sensibles."web2py inclut le serveur[ssl]Rocket WSGI incluant le support SSL activé par défaut, mais peut également utiliser Apache ou Lighttpd et le module mod_ssl pour fournir la couche de chiffrement SSL des communications.
access restriction"Echec de restriction d'accès à certaines URL : La plupart du temps, une application protège uniquement les fonctionnalités sensibles en évitant l'affichage de liens ou URLs à des utilisateurs non autorisés. Les attaquants peuvent utiliser cette faiblesse pour accéder et exécuter des opérations non autorisées en accédant à ces URLs directement."web2py effectue un lien entre chaque requête URL te les modules et fonctions Python. web2py fournit un mécanisme pour déclarer quelles fonctions sont publiques et lesquelles nécessitent une authentification préalable pour autorisation. L'API de contrôle d'accès par rôle autorise les développeurs à restreindre l'accès à n'importe quelle fonction en se basant sur le login, l'appartenance à un groupe ou les permissions de groupe. Les permissions sont très granulaires et peuvent être combinées avec des filtres de base de données pour permettre, par exemple, de donner un accès à certaines tables spécifiques et/ou à des enregistrements. web2py permet également d'utiliser les URLs signées numériquement et fournit une API pour signer numériquement les callbacks Ajax.
web2py a été revu pour sa sécurité et vous pouvez trouver le résultat de cette revue en référence [pythonsecurity].
Dans la boîte
Vous pouvez télécharger web2py depuis le site web officiel :
http://www.web2py.com
web2py est composé des éléments suivants :
librairies: fournissent le coeur des fonctionnalités de web2py et sont accessibles de manière programmable.
serveur web: le serveur web WSGI Rocket.
l'application admin: utilisée pour créer, dessiner et gérer les autres applications web2py.adminfournir un Environnement de Développement Intégré (EDI) web complet pour construire des applications web2py. Il inclut également d'autres fonctionnalités, telles qu'un moteur de test et un shell web.
les applications exemples: contiennent de la documentation et des exemples interactifs. Lesexemplessont un clone du site web officiel web2py.com, et incluent la documentation epydoc.
l'application bienvenue: le template de base pour n'importe quelle autre application. Par défaut, il inclut un menu déroulant pur CSS et un système d'authentification d'utilisateur (présenté dans le chapitre 9).
web2py est distribué en code source, et en fichiers binaires pour Microsoft Windows et Mac OS X.
La distribution du code source peut être utilisée sur n'importe quelle plateforme où Python est installé et inclut les composants ci-après mentionnés. Pour exécuter le code source, vous avez besoin de Python 2.5, 2.6 ou 2.7 pré-installé sur le système. Vous aurez également besoin d'installer l'un des moteurs de base de données supportés. Pour des tests et des applications nécessitant peu de requêtes, vous pouvez utiliser la base de données SQLite, inclue avec Python 2.7.
Les versions binaires de web2py (pour Windows et Mac OS X) incluent un interpréteur Python 2.7 et une base de données SQLite. Techniquement, ces deux composants ne font pas partie de web2py. En les incluant dans les distributions binaires, cela vous permet uniquement de démarrer web2py directement.
L'image suivante montre la structure globale de web2py :
Tout en bas, nous pouvons trouver l'interpréteur. En remontant, nous trouvons le serveur web (rocket), les librairies, et les applications. Chaque application possède son propre schéma MVC (modèles, contrôleurs, vues, modules, langages, bases de données, et fichiers statiques). Chaque application inclut son propre code d'administration de la base (appadmin). TOutes les instances web2py démarrent avec trois applications : welcome (l'application de base), admin (l'EDI web), et les exemples (copie du site web et exemples).
A propos de ce livre
Ce livre inclut les chapites suivants, suite à cette introduction :
Le chapitre 2 est une introduction minimaliste à Python. Il suppose une connaissance des concepts de la programmation procédurale et orientée objet tels que les boucles, les conditions, les appels de fonctions et de classes, et les principales syntaxes Python. Il couvre également les exemples de modules Python qui sont utilisés à tout au long de ce livre. Si vous connaissez déjà bien Python, vous pouvez passer ce chapitre.
Le chapitre 3montre comment démarrer web2py, parle de l'interface d'administration, et guide le lecteur à travers des exemples variés en augmentant la complexité: une application qui retourne une chaine de caractères, une application compteur, un blog, et une application complète de wiki qui autorise l'envoi d'images et de commentaires, fournit l'authentification, les autorisations, les services web et un flux RSS. En lisant ce chapitre, vous serez peut être amené à vous référer au chapitre 2 pour des syntaxes Python génériques et aux chapitres suivants pour des références plus détaillées sur les fonctions qui sont utilisées.
Le chapitre 4 couvre plus particulièrement la structure du coeur de web2py et les librairies : le mapping d'URL, les requêtes, les réponses, les sessions, le cache, l'ordonnanceur, le cron, l'internationalisation et les flux de travail généraux.
Le chapitre 5 est une référence pour le template de langue utilisée pour la construction des vues. Il montre comment embarquer du code Python dans du code HTML, et explique comment utilise les assistants (objets permettant la génération de code HTML).
Le chapitre 6 couvre la couche d'abstraction à la base de données, ou DAL (Database Abstraction Layer). La syntaxe de la DAL est présentée à travers une série d'exemples.
Le chapitre 7 couvre les formulaires, la validation de ces formulaires et leur traitement. FORM est un assistant bas-niveau pour la construction de formulaires. SQLFORM est un constructeur de formulaire haut-niveau. Dans le chapitre 7, nous verrons également des API Création/Lecture/Mise à jour/Suppression (Create/Read/Update/Delete - CRUD)
Le chapitre 8 couvre les fonctionnalités de communication, d'envoi d'emails et de SMS.
Le chapitre 9 couvre l'authentification, les autorisations et le mécanisme de contrôle d'accès basé sur les rôles disponible dans web2py. La configuration mail et CAPTCHA sont également présentées ici, puisqu'utilisées pour l'authentification. Dans la troisième édition de ce livre, une partie a été ajoutée pour les authentifications possibles avec l'intégration de mécanismes tiers tels que OpenID, OAuth, Google, Facebook, Linkedin, etc...
Le chapitre 10 est au sujet de la création de services web dans web2py. Nous fournissons des exemples d'intégration avec le Google Web Toolkit via Pyjamas, et avec Adobe Flash via PyAMF.
Le chapitre 11 est à propos de web2py et des possibilités avec jQuery. web2py est construit principalement pour de la programmation côté serveur, mais inclut jQuery, puiqu'elle s'avère être la meilleure librairie JavaScript disponible pour les effets et Ajax. Dans ce chapitre, nous discuterons donc des possibilités d'intégration de jQuery avec web2py.
Le chapitre 12 présente les composants et plugins web2py comme une possibilité de construire des applications modulables. Nous fournissons un exemple de plugin qui implémente les principales fonctionnalités, telles que la mise en forme de diagrammes, les commentaires et les tags.
Le chapitre 13 explique le déploiement en production d'applications web2py. Plus spécifiquement, le déploiement un serveur web LAMP est présenté (ce qui est considéré comme étant la principale alternative de déploiement). Des serveurs web alternatifs sont également présentés, ainsi que la configuration d'une base de données PostgreSQL. D'autres points sont présentés comme l'exécution en tant que service sur un environnement Microsoft Windows, et le déploiement sur certaines plateformes spécifiques incluant Google Applications Engine, Heroku, et PythonAnywhere. Dans ce chapitre, les problèmes de sécurité et s'évolutivité sont également soulevés.
Le chapitre 14 contient une variété d'autres possibilités pour résoudre des tâches spécifiques, incluant les mises à jour, le geocoding, la pagination, l'API Twitter et bien plus encore.
Ce livre couvre uniquement les fonctionnalités de base de web2py et l'API fournie avec web2py. Ce livre ne couvre pas les appliances web2py (i.e. des applications prêtes à l'emploi).
Vous pouvez télécharger les appliances web2py depuis le site correspondant [appliances]. Vous pouvez trouver des sujets complémentaires discutés dans les usergroup[usergroup]. Il y a également AlterEgo[alterego], l'ancien blog de web2py et sa FAQ.
Ce livre a été écrit en utilisant la syntaxe markmin et automatiquement converti en HTML, LaTeX et PDF.
Support
Le principal canal de support est le usergroup[usergroup], avec ses dizaines de posts par jour. Même si vous êtes un débutant, n'hésitez pas demander - nous serons ravis de pouvoir vous aider. Il y a également un système de suivi de bug officiel sur http://code.google.com/p/web2py/issues . Enfin, une information importante, vous pouvez obtenir du support professionnel (voir le site web pour plus de détails).
Contribute
Toute aide est vraiment appréciée. Vous pouvez aider les autres utilisateurs sur les groupes utilisateur, ou en envoyant directement des patchs sur le programme (sur le site GitHub https://github.com/web2py/web2py). Même si vous trouvez une erreur dans ce livre, ou si vous avez une amélioration à apporter, le meilleur moyen de le faire est de patcher le livre directement (sous le dossier source sur le repository à https://github.com/mdipierro/web2py-book).
Eléments de style
PEP8 [style] contient des bonnes pratiques de style lorsque l'on développe en Python. Vous verrez que web2py ne suit pas toujours ces règles. Ce n'est ni par oubli ni par négligence; c'est notre conviction que les utilisateurs devraient suivre ces règles et nous les y encourageons. Nous avons choisi de ne pas suivre certaines de ces règles en définissant les objects d'assistants afin de minimiser la probabilité de conflits de noms avec des objets définis par l'utilisateur.
Par exemple, la classe qui représente une <div> est appelée DIV, alors que si l'on se réfère à la référence Python, elle devrait avoir été appelée Div. Nous pensons que, pour cet exemple spécifique, utiliser une déclaration tout en majuscule "DIV", est un choix plus naturel. De plus, cette approche laisse aux programmeurs la liberté de créer une classe appelée "Div" s'ils le souhaitent. Notre syntaxe s'intègre également de manière naturelle à la notation DOM pour la plupart des navigateurs (incluant, par exemple, Firefox).
En se référant au guide de style Python, toutes les chaines de caractères majuscules devraient être utilisée pour des constantes et non pour des variables. En continuant avec notre exemple, même en considérant que DIV est une classe, c'est une classe spéciale qui ne devrait jamais être modifiée par l'utilisateur car une telle modification impacterait toutes les autres applications web2py. Par ailleurs, nous pensons qu'en qualifiant la classe DIV comme quelquechose de constant, ceci justifie totalement cette notation.
En résumé, les conventions suivantes sont respectées :
Les assistants HTML et les validateurs sont en majuscultes pour les raisons évoquées précédemment (par exemple, DIV,A,FORM,URL).
L'objet de traduction Test en majuscule malgré le fait que ce soit une instance de classe et non une classe. Logiquement, l'objet de traduction exécute une action similaire aux assistants HTML, et affecte une partie du rendu de la présentation. Aussi,Tnécessite d'être facile à localiser dans le code et doit avoir un nom court.
Les classes DAL suivent le guide de style Python (la première lettre uniquement en majuscule), par exemple Table,Field,Query,Row,Rows, etc...
Dans tous les autres cas, nous espérons avoir suivi, autant que possible, le Guide de Style Python (PEP8). Par exemple, toutes les instances d'objets sont en minuscules (request, response, session, cache), et toutes les classes internes sont en majuscules.
Dans tous les exemples de ce libre, les mots-clés web2py sont mis en gras, alors que les chaines de caractères et les commentaires sont mis en italique.
Licence
web2py est distribué sous licence LGPL version 3. Le texte complet de la licence est disponible en référence [lgpl3].
En respect de la licence LGPL, vous pouvez:
redistribuer web2py avec vos application (en incluant les versions binaires officielles)
mettre à disposition vos applications utilisant les librairies officielles web2py sous la licence que vous souhaitez
Cependant vous devez:
être clair dans votre documentation en mentionnant l'utilisation de web2py dans votre application
mettre à disposition toute modification des librairies web2py sous licence LGPLv3
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.
**Versions précédentes*
Les versions précédentes de web2py, 1.0.*-1.90.*, ont été mises à disposition sous la licence GPL2 avec une exception commerciale, qui pour des raisons pratiques, était très similaire à la licence courante LGPLv3.
Contenu tiers distribué avec web2py
web2py contient du contenu tiers dans le répertoire gluon/contrib et des fichiers JavaScript et CSS variés. Ces fichiers sont distribués avec web2py sous leurs licences originales, comme énoncé dans les fichiers.
Reconnaissances
web2py est développé et sous copyright de Massimo Di Pierro. La première version (1.0) a été mise en ligne en Octobre 2007. Depuis, elle a été adoptée par de nombreux utilisateurs, et certains d'entre eux ont contribué aux rapports de bugs, aux tests, au débug, aux patchs et à la relecture de ce livre.
La plupart des développeurs et des contributeurs sont, par ordre alphabétique :
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.
Je suis sûr que j'oublie des personnes, et j'en suis désolé.
Je remercie particulièrement Anthony, Jonathan, Mariano, Bruno, Vladyslav, Martin, Nathan, Simone, Thadeus, Tim, Iceberg, Denes, Hans, Christian, Fran et Patrick pour leurs contributions majeures à web2py et 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 (et les autres) pour leur relecture précise des différentes version de ce livre. Leur contribution est inestimable. Si vous trouvez des erreurs dans ce libre, elles sont exclusivement de ma faute, probablement introduite par une édition de dernière minute. Je remercie également Ryan Steffen de Wiley Custom Learning Solutions pour son aide lors de la publication de la première édition de ce livre.
web2py contient du code des auteurs suivants, que je tiens vraiment à remercier :
Guido van Rossum pour Python[python], Peter Hunt, Richard Gordon, Timothy Farrell pour le serveur web Rocket[rocket], Christopher Dolivet pour EditArea[editarea], Bob Ippolito pour simplejson[simplejson], Simon Cusack et Grant Edwards pour pyRTF[pyrtf], Dalke Scientific Software pour pyRSS2Gen[pyrss2gen], Mark Pilgrim pour feedparser[feedparser], Trent Mick pour markdown2[markdown2], Allan Saddi pour fcgi.py, Evan Martin pour le module Python memcache[memcache], John Resig pour jQuery[jquery]
Je remercie Helmut Epp (proviseur de DePaul University), David Miller (Doyen du College of Computing and Digital Media of DePaul University), et Estia Eichten (membre de MetaCryption LLC), pour leur confiance continue et leur support.
Enfin, je souhaite remercier ma femme, Claudia, et mon fils, Marco, pour m'avoir supporté durant les nombreuses heures que j'ai passées à développer web2py, en échangeant des emails avec des utilisateurs et collaborateurs, et en écrivant ce livre. Ce livre leur est dédié.
top
|
In the template below, I am trying to get the name of the court (that is captured through the "establishment" field). I am passing "club_id" through the avail_times function, but how do I pass the "establishment" field passed through the template from this?
The model:
class Club(models.Model):
establishment = models.CharField(max_length=200)
address = models.CharField(max_length=200)
def __unicode__(self):
return self.establishment
class Available(models.Model):
club = models.ForeignKey(Club)
court = models.CharField(max_length=200)
avail_time = models.DateTimeField('available time')
def __unicode__(self):
return self.court
The function:
def avail_times(request, club_id):
courts = Available.objects.filter(club__id=club_id)
return render_to_response('reserve/templates/avail_times.html', {'courts': courts})
The template:
<h1>All available courts for {{ court.club }}</h1>
<ul>
{% for court in courts %}
<li>{{ court }}</li>
{% endfor %}
</ul>
|
mac-gyver31
Re : Client Ubuntu + Active Directory et partage avec Windows serveur 2003
En fait ce post est plutôt tournée vers l'intégration d'un ordi dans un domaine windows 2003 dans le cadre d'un serveur LTSP.
Un serveur LTSP ?? Tu veux dire Linux Terminal Server Project ?
T'es sûr ? Car je ne vois pas bien le rapport, et c'est la première vois que je vois cette chose évoquée dans les posts de cette discussion
Il est temps d'enlever les fenêtres, et de construire un monde ouvert.
Hors ligne
florian_boy
Re : Client Ubuntu + Active Directory et partage avec Windows serveur 2003
Bonjour,
Je suis entrain d'installer un machine Ubuntu 10.4 et je voulais l'intégrer dans mon domaine AD.
J'ai repris en intégral le script proposé en 1er page, modifié les nom de domaine, tenté de modifié le AD-vol.conf, mais là, j'ai pas tout capté ...
J'ai lancé le script comme expliqué, il n'y a pas eu de bug ou autre mais à la fin, lors du test d'identification au domaine, j'ai ceci :
Error: Lsass Error [code 0x00080047]
40290 (0x9D62) LW_ERROR_LDAP_TIMEOUT - Unknown error
Après avoir redémarré l'ordi, j'ai remarqué qu'il n'y avais pas de dossier LIkewise dans mon "home" et qu'il m'avait été imposible d'ouvrir un session avec un compte AD
Si quelqu'un a une idée, merci ...
Un autre truc, ce ne sont pas des dossier personnel que je veux monter dans le fichier AD-vol.conf, mais des partitions présente sur le serveur, chaque personne ayant sa propre partition, alors si quelqu'un peux m'aider à bien définir les volumes à monter ou bien m'expliquer les codes de ce fichier, ce serai super.
Merci
Cordialement,
Hors ligne
Gaelephant
Re : Client Ubuntu + Active Directory et partage avec Windows serveur 2003
Script testé (et approuvé) dans le cadre d'une jonction "simple" d'un poste client Ubuntu 12.04 à un AD (win 2003).
Sachant que je galérais dans la modification à la main des fichiers de conf krb5 et smb, ce script m'a débloqué.
Plus qu'à le détailler/modifier pour l'adapter plus précisément à mes besoins, mais sur le principe, exécuté tel quel, il fonctionne parfaitement, du moins sur la partie "se loguer avec les identifiants de la base AD", ce qui est déjà un bon point de départ.
Hors ligne
Gaelephant
Re : Client Ubuntu + Active Directory et partage avec Windows serveur 2003
Script testé (et approuvé) dans le cadre d'une jonction "simple" d'un poste client Ubuntu 12.04 à un AD (win 2003).
Sachant que je galérais dans la modification à la main des fichiers de conf krb5 et smb, ce script m'a débloqué.
Plus qu'à le détailler/modifier pour l'adapter plus précisément à mes besoins, mais sur le principe, exécuté tel quel, il fonctionne parfaitement, du moins sur la partie "se loguer avec les identifiants de la base AD", ce qui est déjà un bon point de départ.
Histoire de préciser tout de même :
Le but final est de virer le Win2003 d'un serveur de fichier pour le remplacer par un linux (vraisemblablement Ubuntu).
Mais le DC resterait (pour le moment du moins) sous Win2003. Débutant sous linux, avant le lancer le grand chambardement, je souhaite faire quelques essais. J'ai donc commenté toutes les lignes faisant référence aux partages, puisque pour le moment, souhaitant avancer tranquillement par étapes, je ne m'intéresse qu'à la jonction d'un poste linux à l'AD. Histoire d'être sûr qu'au moins ça soit réalisable facilement et rapidement avant d'aller fouiller plus loin. D'autant plus qu'au final, les partages ne devront pas "être accessible depuis un linux", mais "être accessible depuis un windows tout en étant hébergé par un linux". Meme si l'un n'empêche pas l'autre, j'vais y aller doucement.
Script testé sur Ubuntu 12.04 client, tel quel, sans modification : fonctionne directement.
Cela dit, pas de dossier /etc/gdm/ chez moi (Unity oblige), du coup j'ai viré les lignes concernant gdm, et j'ai rajouté les lignes
allow-guest=false
greeter-hide-users=true
au fichier /etc/lightdm/lightdm.conf. Je pense que ça doit facilement se rajouter au script.
Au reboot de la machine, écran de connexion où il faut entrer identifiant puis mdp pour se logguer. Les identifiants locaux fonctionnent, les identifiants réseaux également, et ce sans avoir à rajouter un "DOMAIN\" avant le login. Bref, complètement transparent pour l'utilisateur.
Script testé sur Ubuntu 12.04 server tel quel, sans modification : échec à l'installation de likewise.
J'ai résolu le problème en modifiant dans le script la partie apt-get concernant likewise et en mettant à la place un simple
sudo dpkg -i ./likewise-open_6.1.0.406-0ubuntu5_i386.deb
en ayant au préalable téléchargé le .deb à la main (j'ai malencontreusement oublié de noter l'url où je l'ai choppé) et placé dans le même répertoire que le script. Ensuite, l'installation se déroule sans le moindre soucis.
Mais au reboot et à la connexion, ça n'est pas la même histoire :
- identifiant_local / pass : ça marche
- identifiant_réseau / pass : erreur (j'ai plus le message exact en tête, mais même message que lorsqu'on tape un mauvais password)
- identifiant@domain / pass : idem
- DOMAIN\identifiant / pass : erreur : ACCESS DENIED
Le access denied est je pense plutôt bon signe : il ne trouve pas d'erreur dans le duo log/pass, il n'arrive juste pas à ouvrir une session.
Avec comme question principale : il n'arrive pas à ouvrir une session, ou bien il pourrait y arriver mais refuse de le faire parce que "quelque chose" le lui interdit (par exemple, au pif, une ligne foireuse sur un fichier de conf planqué quelque part qui dise qu'il n'y a que la personne qui a installé l'os qui peut s'y connecter).
Encore en train de fouiller dans les fichiers de log voir où il peut bien y avoir une erreur, sans trouver pour le moment.Comme c'est le seul moyen qui me vienne à l'esprit pour tester si la jonction du poste à l'AD est bien effective, c'est gênant.
D'un autre côté, étant vraiment un gros débutant dans le monde linux, j'ai très bien pu foirer quelque part.
A noter qu'avant de tester ce script, et ce sur les deux OS, version classique et version server, j'avais déjà bidouillé les fichiers de conf de samba et de kerberos, suivi quelques tentatives de tuto sur le net sans succès, et donc je ne me suis pas particulièrement inquiété du fait que contrairement à annoncé, il ne m'a pas été demandé lors de l'installation les serveurs et royaumes kerberos.
D'autant plus que ça a fonctionné directement sur la version "client". Histoire d'exclure la possibilité que l'ancien fichier krb5.conf du server soit la cause du problème, j'ai directement copié à la place celui du client avant de faire mes tests.
Et ça m'embêterait beaucoup d'avoir à refaire une réinstallation complète de l'OS, vu que j'ai dégagé l'iso et que j'ai un débit foireux pour la retélécharger.
En espérant que ce retour d'expérience serve, par exemple à une amélioration du script
Hors ligne
Divad
Re : Client Ubuntu + Active Directory et partage avec Windows serveur 2003
Salut,
C'est vrai que pour tester, il vaut mieux partir d'un OS nouveau et fraichement à jour que de quelque chose bidouillé surtout concernant kerberos. Je ne comprends pas toujours ce que je fais et trouver une erreur d'une ancienne bidouille c'est pas gagné.
Concernant 12.04, je n'ai fait aucun test. Cependant, dans le script il y a ces deux lignes :
add-apt-repository ppa:likewise-open/likewise-open-ppa
apt-key adv --keyserver keyserver.ubuntu.com --recv-keys AAFDD5DB
Cela fait appel à un dépot externe car dans les dépôts de la 10.4 il y avait un likewise bugué que le ppa corrigeait. Je pense que dans la 12.04 ce bug doit être corrigé et le ppa plus nécessaire, voire même dépassé pouvant peut-etre causer des problèmes d'identification. Je pense donc qu'il faudrait que tu testes en enlevant ces deux lignes du script et partir sur une base clean avec le dépôt officiel de 12.04.
A propos de la connexion, as-tu essayé le test de connexion inclus dans le script ?
Hors ligne
Gaelephant
Re : Client Ubuntu + Active Directory et partage avec Windows serveur 2003
Concernant 12.04, je n'ai fait aucun test. Cependant, dans le script il y a ces deux lignes :
add-apt-repository ppa:likewise-open/likewise-open-ppa
apt-key adv --keyserver keyserver.ubuntu.com --recv-keys AAFDD5DB
Cela fait appel à un dépot externe car dans les dépôts de la 10.4 il y avait un likewise bugué que le ppa corrigeait. Je pense que dans la 12.04 ce bug doit être corrigé et le ppa plus nécessaire, voire même dépassé pouvant peut-etre causer des problèmes d'identification. Je pense donc qu'il faudrait que tu testes en enlevant ces deux lignes du script et partir sur une base clean avec le dépôt officiel de 12.04.
Justement, je test sur deux versions de 12.04, la classique et la server.
J'avais déjà essayé d'installer likewise depuis les dépôts offi sur la version client, en essayant de suivre pas à pas un tuto, mais sans succès : des erreurs à l'installation, ça foirait à un moment où un autre, j'avais laissé tombé.
Sur la "classique", ces deux lignes de ton script ne posent aucun problème, et tout fonctionne parfaitement, ça installe depuis les dépots indiqué, tout roule.
Sur la "server", l'installation de likewise pose soucis. Le même script, les mêmes lignes, une erreur ou les mots dpkg, --configure et likewise apparaissaient sur la même ligne.
Du coup j'ai récupéré le .deb depuis "https://launchpad.net/ubuntu/+source/likewise-open" (vive l'historique du navigateur pour retrouver l'adresse), et là l'installation se passe correctement.
A propos de la connexion, as-tu essayé le test de connexion inclus dans le script ?
Oui, testé, et affichant un magnifique succès et me recommandant de redémarrer.
D'ailleurs, pour preuve que la connexion est possible, si j'essaye de co un utilisateur n'existant pas, l'erreur est "login incorrect", alors qu'avec un utilisateur réseau existant, l'erreur est "access is denied". De plus, un "getent passwd" me donne le même résultat sur la version "client" (dont la jonction à l'AD est effective et réussie) et sur la version server (où là j'ai des "access is denied").
J'ai fait le tour des fichiers que j'avais modifié de façon indépendante sur le client et sur le server pour traquer les différences, sans avoir trouvé pour le moment. Bah, si je ne trouve pas, effectivement, réinstaller directement au propre la version server reste possible. Mais ça serait tellement plus agréable de comprendre pourquoi là ça ne fonctionne pas comme attendu.
Accessoirement, j'ai récupéré la fin du auth.log, qui concerne ma tentative de connexion avec le compte Admin du réseau :
srvtest login[902]: pam_winbind(login:auth): getting password (0x00000388)
srvtest login[902]: pam_winbind(login:auth): pam_get_item returned a password
srvtest login[902]: pam_winbind(login:auth): request wbcLogonUser failed: WBC_ERR_AUTH_ERROR, PAM error: PAM_SYSTEM_ERR (4), NTSTATUS: NTSTATUS_ACCESS_DENIED, Error message was: Access denied
srvtest login[902]: pam_winbind(login:auth): internal module error (retval = PAM_SYSTEM_ERR(4), user = 'DOMAINE\Administrateur")
srvtest login[902]: pam_winbind(login:auth): FAILED LOGIN (1) on '/dev/tty3' FOR 'DOMAINE\Administrateur', Authentification failure
Ce qui me laisse supposer que c'est du côté de /etc/pam.d/system-auth et du fichier pam_winbind.so qu'il va falloir chercher.
Hors ligne
Divad
Re : Client Ubuntu + Active Directory et partage avec Windows serveur 2003
hum, il y a peut-être un problème dans la configuration des fichiers. Dans tous les cas, je pense que le mieux est de repartir sur une installation propre. Car même si tu corriges une erreur et que cela marche, tu ne seras jamais sûr que la correction soit bonne étant donné que d'autres bidouilles ont pu affecter le système. Et si le problème persiste après réinstallation, au moins tu repars sur qqch de sain et propre. Travailler en production sur un Os bidouillé n'est jamais bon, d'autant plus pour un serveur. Il vaut mieux savoir de A à Z ce qu'on y a fait, cela facilitera la maintenance ultérieure.
par rapport à likewise, le message "dpkg, --configure et likewise " confirme qu'il y a eu un problème lors de l'installation du ppa. Et le deb que tu récupères est celui du dépôt officiel. ( d’ailleurs quelle version as-tu prise ?)
Je suis désolé pour l'iso parti à la poubelle, mais je te conseille de :
- récupérer l'iso !
- réinstaller au propre
- tester le script en entrant bien les noms de domain, et en supprimant les deux lignes mentionnées ci-dessus
- bidouiller si besoin
- garder l'iso ( ça peut resservir parfois !)
Hors ligne
Gaelephant
Re : Client Ubuntu + Active Directory et partage avec Windows serveur 2003
par rapport à likewise, le message "dpkg, --configure et likewise " confirme qu'il y a eu un problème lors de l'installation du ppa. Et le deb que tu récupères est celui du dépôt officiel. ( d’ailleurs quelle version as-tu prise ?)
C'est "amusant" de voir que le likewise proposé par ton script fonctionne sur le client, mais pas sur le serveur, et que la version "dépot officiel" ne fonctionne pas sur le client, mais semble fonctionner au poil sur le serveur. Enfin amusant. Façon de parler.
J'ai pris le paquet "likewise-open_6.1.0.406-0ubuntu5_i386.deb" dans la liste dispo sous "Precise Pangolin". vu que la machine sur laquelle je fais mes tests est une vieille bête.
C'est reparti pour une install propre, alors. Je reviendrais donner des nouvelles.
Hors ligne
Gaelephant
Re : Client Ubuntu + Active Directory et partage avec Windows serveur 2003
De retour après test sur Ubuntu server 12.04.1, à partir d'une install neuve, propre, et juste après mise à jour.
Toujours sur la partie "jonction à l'AD".
Réussite
A part un léger détail, ton script indique que
Lors de l'installation, il vous sera demandé :
- Royaume Realm Kerberos par defaut : ex : DOMAINE
- Serveur Kerberos du Royaume : ex : 192.168.0.010 nomduserveur
- Serveur administratif du royaume Kerberos : ex : nomduserveur
Hors, lors de l'exécution du script, le seul moment où il m'a été demandé quelque chose, c'est lors de la phase de test, l'identifiant, le nom de domaine et le pass. Ce qui n'a pas empêché de déboucher sur un SUCCESS (que j'avais déjà eu lors de mes tests précédents cela dit).
Différence notable avec mes précédents tests : pas besoin de se logguer sous la forme DOMAIN\user, entrer le nom d'un utilisateur réseau non créé sur la machine fonctionne directement.
Tout ça pour dire que si tu réactualises ton script avec une version du paquet likewise "à jour", toute la partie "jonction à l'AD" fonctionne sur ubuntu 12.04, client comme server.
Plus qu'à fouiller sur la partie "partage" pour voir ce que je vais en faire
Encore bravo, proposer un truc qui marche et qui facilite la vie, c'est méritoire !
Hors ligne
Divad
Re : Client Ubuntu + Active Directory et partage avec Windows serveur 2003
Super ! Comme quoi, une bonne installation enlève pas mal de problème !
J'ai mis à jour le premier poste en disant d'effacer les lignes mentionnées pour 12.04
Je pense que d'ici quelques mois, il va falloir que je me replonge là dedans ( 10.4 devient vieux! ) Je remettrai le script à jour.
Merci à toi aussi de faire profiter de ton travail !!
Hors ligne
Nathaly01
Re : Client Ubuntu + Active Directory et partage avec Windows serveur 2003
Bonjour,
D'abord, merci pour votre travail et le script que vous nous proposé ...
J'ai utilisé le script sur Ubuntu 12.04.2 et j'avais auparavant modifié le fichier /etc/lightdm/lightdm.conf en rajoutant cette ligne : greeter-show-manual-login=true
Le script s'est déroulé parfaitement, succès.
Seulement il y a quelques problèmes. Avec les compte AD, ubuntu utilise l'Anglais pour le nom des dossiers ainsi que pour les menus alors que tout devrait être en français.
En plus, lorsque je monte une partition/dossier (partage) du serveur 2003 sur laquelle j'ai tout les droit, et bien là, j'ai juste le droit de lire.
Pourtant dans l'observateur d'événement, sécurité, je retrouve bien mes ouvertures de session AD depuis le poste ubuntu en "succès", mais les droits sur les dossiers ne sont pas pris en compte ...
Avez vous une idée du pourquoi ??
Merci
Hors ligne
Nathaly01
Re : Client Ubuntu + Active Directory et partage avec Windows serveur 2003
Bonsoir,
J'ai résolu mon problème de droit dans les partages, en faite, j'avais fait une grosse bêtise dans les autorisations !!!
Mais j'arrive vraiment pas à résoudre mon problème de la langue du système ...
comptes locaux ==> en Français
comptes AD ==> en Anglais
J'ai tentée d'avoir le choix de la langue à l'ouverture de session grâce à "lightdm-gtk-greeter", mais sa ne fonctionne pas.
En espérant avoir une réponse ...
Merci
PS : Je viens de voir que je n'ai plus accès à mon imprimante réseau ni à mon scaner et ce, sur tous les comptes, autan locaux que comptes AD ...
Dernière modification par Nathaly01 (Le 06/06/2013, à 00:07)
Hors ligne
|
The Python language
About Python
Python is a general-purpose high-level programming language. Its design philosophy emphasizes programmer productivity and code readability. It has a minimalist core syntax with very few basic commands and simple semantics, but it also has a large and comprehensive standard library, including an Application Programming Interface (API)
list), tuples (tuple), hash tables (dict), and arbitrarily long integers (long).
Python supports multiple programming paradigms, including object-oriented (class), imperative (def), and functional (lambda) programming. Python has a dynamic type system and automatic memory management using reference counting (similar to Perl, Ruby, and Scheme).
Python was first released by Guido van Rossum in 1991. The language has an open, community-based development model managed by the non-profit Python Software Foundation. There are many interpreters and compilers that implement the Python language, including one in Java (Jython) but, in this brief review, we refer to the reference C implementation created by Guido.
You can find many tutorials, the official documentation and library references of the language on the official Python website.[python]
You may skip this chapter if you are already familiar with the Python language.
Starting up
The binary distributions of web2py for Microsoft Windows or Apple OS X come packaged with the Python interpreter built into the distribution file itself.
You can start it on Windows with the following command (type at the DOS prompt):
web2py.exe -S welcome
On Apple OS X, enter the following command type in a Terminal window (assuming you're in the same folder as web2py.app):
./web2py.app/Contents/MacOS/web2py -S welcome
On a Linux or other Unix box, chances are that you have Python already installed. If so, at a shell prompt type:
python web2py.py -S welcome
If you do not have Python 2.5 (or later 2.x) already installed, you will have to download and install it before running web2py.
The -S welcome command line option instructs web2py to run the interactive shell as if the commands were executed in a controller for the welcome application, the web2py scaffolding application. This exposes almost all web2py classes, objects and functions to you. This is the only difference between the web2py interactive command line and the normal Python command line.
The admin interface also provides a web-based shell for each application. You can access the one for the "welcome" application at.
http://127.0.0.1:8000/admin/shell/index/welcome
You can try all the examples in this chapter using the normal shell or the web-based shell.
help, dir
The Python language provides two commands to obtain documentation about objects defined in the current scope, both built-in and user-defined.
We can ask for help about an object, for example "1":
>>> help(1)
Help on int object:
class int(object)
| int(x[, base]) -> integer
|
| Convert a string or number to an integer, if possible. A floating point
| argument will be truncated towards zero (this does not include a string
| representation of a floating point number!) When converting a string, use
| the optional base. It is an error to supply a base when converting a
| non-string. If the argument is outside the integer range a long object
| will be returned instead.
|
| Methods defined here:
|
| __abs__(...)
| x.__abs__() <==> abs(x)
...
and, since "1" is an integer, we get a description about the int class and all its methods. Here the output has been truncated because it is very long and detailed.
Similarly, we can obtain a list of methods of the object "1" with the command dir:
>>> dir(1)
['__abs__', ..., '__xor__']
Types
Python is a dynamically typed language, meaning that variables do not have a type and therefore do not have to be declared. Values, on the other hand, do have a type. You can query a variable for the type of value it contains:
>>> a = 3
>>> print type(a)
<type 'int'>
>>> a = 3.14
>>> print type(a)
<type 'float'>
>>> a = 'hello python'
>>> print type(a)
<type 'str'>
Python also includes, natively, data structures such as lists and dictionaries.
str
Python supports the use of two different types of strings: ASCII strings and Unicode strings. ASCII strings are delimited by '...', "..." or by '..' or """...""". Triple quotes delimit multiline strings. Unicode strings start with a u followed by the string containing Unicode characters. A Unicode string can be converted into an ASCII string by choosing an encoding for example:
>>> a = 'this is an ASCII string'
>>> b = u'This is a Unicode string'
>>> a = b.encode('utf8')
After executing these three commands, the resulting a is an ASCII string storing UTF8 encoded characters. By design, web2py uses UTF8 encoded strings internally.
It is also possible to write variables into strings in various ways:
>>> print 'number is ' + str(3)
number is 3
>>> print 'number is %s' % (3)
number is 3
>>> print 'number is %(number)s' % dict(number=3)
number is 3
The last notation is more explicit and less error prone, and is to be preferred.
Many Python objects, for example numbers, can be serialized into strings using str or repr. These two commands are very similar but produce slightly different output. For example:
>>> for i in [3, 'hello']:
print str(i), repr(i)
3 3
hello 'hello'
For user-defined classes, str and repr can be defined/redefined using the special operators __str__ and __repr__. These are briefly described later on; for more, refer to the official Python documentation[pydocs] . repr always has a default value.
Another important characteristic of a Python string is that, like a list, it is an iterable object.
>>> for i in 'hello':
print i
h
e
l
l
o
list
The main methods of a Python list are append, insert, and delete:
>>> a = [1, 2, 3]
>>> print type(a)
<type 'list'>
>>> a.append(8)
>>> a.insert(2, 7)
>>> del a[0]
>>> print a
[2, 7, 3, 8]
>>> print len(a)
4
Lists can be sliced:
>>> print a[:3]
[2, 7, 3]
>>> print a[1:]
[7, 3, 8]
>>> print a[-2:]
[3, 8]
and concatenated:
>>> a = [2, 3]
>>> b = [5, 6]
>>> print a + b
[2, 3, 5, 6]
A list is iterable; you can loop over it:
>>> a = [1, 2, 3]
>>> for i in a:
print i
1
2
3
The elements of a list do not have to be of the same type; they can be any type of Python object.
There is a very common situation for which a list comprehension can be used. Consider the following code:
>>> a = [1,2,3,4,5]
>>> b = []
>>> for x in a:
if x % 2 == 0:
b.append(x * 3)
>>> b
[6, 12]
This code clearly processes a list of items, selects and modifies a subset of the input list, and creates a new result list, and this code can be entirely replaced with the following list comprehension:
>>> a = [1,2,3,4,5]
>>> b = [x * 3 for x in a if x % 2 == 0]
>>> b
[6, 12]
tuple
A tuple is like a list, but its size and elements are immutable, while in a list they are mutable. If a tuple element is an object, the object attributes are mutable. A tuple is delimited by round brackets.
>>> a = (1, 2, 3)
So while this works for a list:
>>> a = [1, 2, 3]
>>> a[1] = 5
>>> print a
[1, 5, 3]
the element assignment does not work for a tuple:
>>> a = (1, 2, 3)
>>> print a[1]
2
>>> a[1] = 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
A tuple, like a list, is an iterable object. Notice that a tuple consisting of a single element must include a trailing comma, as shown below:
>>> a = (1)
>>> print type(a)
<type 'int'>
>>> a = (1,)
>>> print type(a)
<type 'tuple'>
Tuples are very useful for efficient packing of objects because of their immutability, and the brackets are often optional:
>>> a = 2, 3, 'hello'
>>> x, y, z = a
>>> print x
2
>>> print z
hello
dict
A Python dict-ionary is a hash table that maps a key object to a value object. For example:
>>> a = {'k':'v', 'k2':3}
>>> a['k']
v
>>> a['k2']
3
>>> a.has_key('k')
True
>>> a.has_key('v')
False
Keys can be of any hashable type (int, string, or any object whose class implements the __hash__ method). Values can be of any type. Different keys and values in the same dictionary do not have to be of the same type. If the keys are alphanumeric characters, a dictionary can also be declared with the alternative syntax:
>>> a = dict(k='v', h2=3)
>>> a['k']
v
>>> print a
{'k':'v', 'h2':3}
Useful methods are has_key, keys, values and items:
>>> a = dict(k='v', k2=3)
>>> print a.keys()
['k', 'k2']
>>> print a.values()
['v', 3]
>>> print a.items()
[('k', 'v'), ('k2', 3)]
The items method produces a list of tuples, each containing a key and its associated value.
Dictionary elements and list elements can be deleted with the command del:
>>> a = [1, 2, 3]
>>> del a[1]
>>> print a
[1, 3]
>>> a = dict(k='v', h2=3)
>>> del a['h2']
>>> print a
{'k':'v'}
Internally, Python uses the hash operator to convert objects into integers, and uses that integer to determine where to store the value.
>>> hash("hello world")
-1500746465
About indentation
Python uses indentation to delimit blocks of code. A block starts with a line ending in colon, and continues for all lines that have a similar or higher indentation as the next line. For example:
>>> i = 0
>>> while i < 3:
>>> print i
>>> i = i + 1
>>>
0
1
2
It is common to use four spaces for each level of indentation. It is a good policy not to mix tabs with spaces, which can result in (invisible) confusion.
for...in
In Python, you can loop over iterable objects:
>>> a = [0, 1, 'hello', 'python']
>>> for i in a:
print i
0
1
hello
python
One common shortcut is xrange, which generates an iterable range without storing the entire list of elements.
>>> for i in xrange(0, 4):
print i
0
1
2
3
This is equivalent to the C/C++/C#/Java syntax:
for(int i=0; i<4; i=i+1) { print(i); }
Another useful command is enumerate, which counts while looping:
>>> a = [0, 1, 'hello', 'python']
>>> for i, j in enumerate(a):
print i, j
0 0
1 1
2 hello
3 python
There is also a keyword range(a, b, c) that returns a list of integers starting with the value a, incrementing by c, and ending with the last value smaller than b, a defaults to 0 and c defaults to 1. xrange is similar but does not actually generate the list, only an iterator over the list; thus it is better for looping.
You can jump out of a loop using break
>>> for i in [1, 2, 3]:
print i
break
1
You can jump to the next loop iteration without executing the entire code block with continue
>>> for i in [1, 2, 3]:
print i
continue
print 'test'
1
2
3
while
The while loop in Python works much as it does in many other programming languages, by looping an indefinite number of times and testing a condition before each iteration. If the condition is False, the loop ends.
>>> i = 0
>>> while i < 10:
i = i + 1
>>> print i
10
There is no loop...until construct in Python.
if...elif...else
>>> for i in range(3):
>>> if i == 0:
>>> print 'zero'
>>> elif i == 1:
>>> print 'one'
>>> else:
>>> print 'other'
zero
one
other
"elif" means "else if". Both elif and else clauses are optional. There can be more than one elif but only one else statement. Complex conditions can be created using the not, and and or operators.
>>> for i in range(3):
>>> if i == 0 or (i == 1 and i + 1 == 2):
>>> print '0 or 1'
try...except...else...finally
>>> try:
>>> a = 1 / 0
>>> except Exception, e:
>>> print 'oops: %s' % e
>>> else:
>>> print 'no problem here'
>>> finally:
>>> print 'done'
oops: integer division or modulo by zero
done
If the exception is raised, it is caught by the except clause, which is executed, while the else clause is not. If no exception is raised, the except clause is not executed, but the else one is. The finally clause is always executed.
There can be multiple except clauses for different possible exceptions:
>>> try:
>>> raise SyntaxError
>>> except ValueError:
>>> print 'value error'
>>> except SyntaxError:
>>> print 'syntax error'
syntax error
The else and finally clauses are optional.
Here is a list of built-in Python exceptions + HTTP (defined by web2py)
BaseException
+-- HTTP (defined by web2py)
+-- SystemExit
+-- KeyboardInterrupt
+-- Exception
+-- GeneratorExit
+-- StopIteration
+-- StandardError
| +-- ArithmeticError
| | +-- FloatingPointError
| | +-- OverflowError
| | +-- ZeroDivisionError
| +-- AssertionError
| +-- AttributeError
| +-- EnvironmentError
| | +-- IOError
| | +-- OSError
| | +-- WindowsError (Windows)
| | +-- VMSError (VMS)
| +-- EOFError
| +-- ImportError
| +-- LookupError
| | +-- IndexError
| | +-- KeyError
| +-- MemoryError
| +-- NameError
| | +-- UnboundLocalError
| +-- ReferenceError
| +-- RuntimeError
| | +-- NotImplementedError
| +-- SyntaxError
| | +-- IndentationError
| | +-- TabError
| +-- SystemError
| +-- TypeError
| +-- ValueError
| | +-- UnicodeError
| | +-- UnicodeDecodeError
| | +-- UnicodeEncodeError
| | +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
For a detailed description of each of them, refer to the official Python documentation.
web2py exposes only one new exception, called HTTP. When raised, it causes the program to return an HTTP error page (for more on this refer to Chapter 4).
Any object can be raised as an exception, but it is good practice to raise objects that extend one of the built-in exception classes.
def...return
Functions are declared using def. Here is a typical Python function:
>>> def f(a, b):
return a + b
>>> print f(4, 2)
6
There is no need (or way) to specify types of the arguments or the return type(s). In this example, a function f is defined that can take two arguments.
Functions are the first code syntax feature described in this chapter to introduce the concept of scope, or namespace. In the above example, the identifiers a and b are undefined outside of the scope of function f:
>>> def f(a):
return a + 1
>>> print f(1)
2
>>> print a
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
print a
NameError: name 'a' is not defined
Identifiers defined outside of function scope are accessible within the function; observe how the identifier a is handled in the following code:
>>> a = 1
>>> def f(b):
return a + b
>>> print f(1)
2
>>> a = 2
>>> print f(1) # new value of a is used
3
>>> a = 1 # reset a
>>> def g(b):
a = 2 # creates a new local a
return a + b
>>> print g(2)
4
>>> print a # global a is unchanged
1
If a is modified, subsequent function calls will use the new value of the global a because the function definition binds the storage location of the identifier a, not the value of a itself at the time of function declaration; however, if a is assigned-to inside function g, the global a is unaffected because the new local a hides the global value. The external-scope reference can be used in the creation of closures:
>>> def f(x):
def g(y):
return x * y
return g
>>> doubler = f(2) # doubler is a new function
>>> tripler = f(3) # tripler is a new function
>>> quadrupler = f(4) # quadrupler is a new function
>>> print doubler(5)
10
>>> print tripler(5)
15
>>> print quadrupler(5)
20
Function f creates new functions; and note that the scope of the name g is entirely internal to f. Closures are extremely powerful.
Function arguments can have default values, and can return multiple results:
>>> def f(a, b=2):
return a + b, a - b
>>> x, y = f(5)
>>> print x
7
>>> print y
3
Function arguments can be passed explicitly by name, and this means that the order of arguments specified in the caller can be different than the order of arguments with which the function was defined:
>>> def f(a, b=2):
return a + b, a - b
>>> x, y = f(b=5, a=2)
>>> print x
7
>>> print y
-3
Functions can also take a runtime-variable number of arguments:
>>> def f(*a, **b):
return a, b
>>> x, y = f(3, 'hello', c=4, test='world')
>>> print x
(3, 'hello')
>>> print y
{'c':4, 'test':'world'}
Here arguments not passed by name (3, 'hello') are stored in the tuple a, and arguments passed by name (c and test) are stored in the dictionary b.
In the opposite case, a list or tuple can be passed to a function that requires individual positional arguments by unpacking them:
>>> def f(a, b):
return a + b
>>> c = (1, 2)
>>> print f(*c)
3
and a dictionary can be unpacked to deliver keyword arguments:
>>> def f(a, b):
return a + b
>>> c = {'a':1, 'b':2}
>>> print f(**c)
3
lambda
lambda provides a way to create a very short unnamed function very easily:
>>> a = lambda b: b + 2
>>> print a(3)
5
The expression "lambda [a]:[b]" literally reads as "a function with arguments [a] that returns [b]". The lambda expression is itself unnamed, but the function acquires a name by being assigned to identifier a. The scoping rules for def apply to lambda equally, and in fact the code above, with respect to a, is identical to the function declaration using def:
>>> def a(b):
return b + 2
>>> print a(3)
5
The only benefit of lambda is brevity; however, brevity can be very convenient in certain situations. Consider a function called map that applies a function to all items in a list, creating a new list:
>>> a = [1, 7, 2, 5, 4, 8]
>>> map(lambda x: x + 2, a)
[3, 9, 4, 7, 6, 10]
This code would have doubled in size had def been used instead of lambda. The main drawback of lambda is that (in the Python implementation) the syntax allows only for a single expression; however, for longer functions, def can be used and the extra cost of providing a function name decreases as the length of the function grows. Just like def, lambda can be used to curry functions: new functions can be created by wrapping existing functions such that the new function carries a different set of arguments:
>>> def f(a, b): return a + b
>>> g = lambda a: f(a, 3)
>>> g(2)
5
There are many situations where currying is useful, but one of those is directly useful in web2py: caching. Suppose you have an expensive function that checks whether its argument is prime:
def isprime(number):
for p in range(2, number):
if (number % p) == 0:
return False
return True
This function is obviously time consuming.
Suppose you have a caching function cache.ram that takes three arguments: a key, a function and a number of seconds.
value = cache.ram('key', f, 60)
The first time it is called, it calls the function f(), stores the output in a dictionary in memory (let's say "d"), and returns it so that value is:
value = d['key']=f()
The second time it is called, if the key is in the dictionary and not older than the number of seconds specified (60), it returns the corresponding value without performing the function call.
value = d['key']
How would you cache the output of the function isprime for any input? Here is how:
>>> number = 7
>>> seconds = 60
>>> print cache.ram(str(number), lambda: isprime(number), seconds)
True
>>> print cache.ram(str(number), lambda: isprime(number), seconds)
True
The output is always the same, but the first time cache.ram is called, isprime is called; the second time it is not.
Python functions, created with eitherdeforlambdaallow re-factoring existing functions in terms of a different set of arguments.cache.ramandcache.diskare web2py caching functions.
class
Because Python is dynamically typed, Python classes and objects may seem odd. In fact, you do not need to define the member variables (attributes) when declaring a class, and different instances of the same class can have different attributes. Attributes are generally associated with the instance, not the class (except when declared as "class attributes", which is the same as "static member variables" in C++/Java).
Here is an example:
>>> class MyClass(object): pass
>>> myinstance = MyClass()
>>> myinstance.myvariable = 3
>>> print myinstance.myvariable
3
Notice that pass is a do-nothing command. In this case it is used to define a class MyClass that contains nothing. MyClass() calls the constructor of the class (in this case the default constructor) and returns an object, an instance of the class. The (object) in the class definition indicates that our class extends the built-in object class. This is not required, but it is good practice.
Here is a more complex class:
>>> class MyClass(object):
>>> z = 2
>>> def __init__(self, a, b):
>>> self.x = a
>>> self.y = b
>>> def add(self):
>>> return self.x + self.y + self.z
>>> myinstance = MyClass(3, 4)
>>> print myinstance.add()
9
Functions declared inside the class are methods. Some methods have special reserved names. For example, __init__ is the constructor. All variables are local variables of the method except variables declared outside methods. For example, z is a class variable, equivalent to a C++ static member variable that holds the same value for all instances of the class.
Notice that __init__ takes 3 arguments and add takes one, and yet we call them with 2 and 0 arguments respectively. The first argument represents, by convention, the local name used inside the method to refer to the current object. Here we use self to refer to the current object, but we could have used any other name. self plays the same role as *this in C++ or this in Java, but self is not a reserved keyword.
This syntax is necessary to avoid ambiguity when declaring nested classes, such as a class that is local to a method inside another class.
Special attributes, methods and operators
Class attributes, methods, and operators starting with a double underscore are usually intended to be private (i.e. to be used internally but not exposed outside the class) although this is a convention that is not enforced by the interpreter.
Some of them are reserved keywords and have a special meaning.
Here, as an example, are three of them:
__len__
__getitem__
__setitem__
They can be used, for example, to create a container object that acts like a list:
>>> class MyList(object):
>>> def __init__(self, *a): self.a = list(a)
>>> def __len__(self): return len(self.a)
>>> def __getitem__(self, i): return self.a[i]
>>> def __setitem__(self, i, j): self.a[i] = j
>>> b = MyList(3, 4, 5)
>>> print b[1]
4
>>> b.a[1] = 7
>>> print b.a
[3, 7, 5]
Other special operators include __getattr__ and __setattr__, which define the get and set attributes for the class, and __sum__ and __sub__, which overload arithmetic operators. For the use of these operators we refer the reader to more advanced books on this topic. We have already mentioned the special operators __str__ and __repr__.
File input/output
In Python you can open and write in a file with:
>>> file = open('myfile.txt', 'w')
>>> file.write('hello world')
>>> file.close()
Similarly, you can read back from the file with:
>>> file = open('myfile.txt', 'r')
>>> print file.read()
hello world
Alternatively, you can read in binary mode with "rb", write in binary mode with "wb", and open the file in append mode "a", using standard C notation.
The read command takes an optional argument, which is the number of bytes. You can also jump to any location in a file using seek.
You can read back from the file with read
>>> print file.seek(6)
>>> print file.read()
world
and you can close the file with:
>>> file.close()
In the standard distribution of Python, which is known as CPython, variables are reference-counted, including those holding file handles, so CPython knows that when the reference count of an open file handle decreases to zero, the file may be closed and the variable disposed. However, in other implementations of Python such as PyPy, garbage collection is used instead of reference counting, and this means that it is possible that there may accumulate too many open file handles at one time, resulting in an error before the gc has a chance to close and dispose of them all. Therefore it is best to explicitly close file handles when they are no longer needed. web2py provides two helper functions, read_file() and write_file() inside the gluon.fileutils namespace that encapsulate the file access and ensure that the file handles being used are properly closed.
When using web2py, you do not know where the current directory is, because it depends on how web2py is configured. The variablerequest.foldercontains the path to the current application. Paths can be concatenated with the commandos.path.join, discussed below.
exec, eval
Unlike Java, Python is a truly interpreted language. This means it has the ability to execute Python statements stored in strings. For example:
>>> a = "print 'hello world'"
>>> exec(a)
'hello world'
What just happened? The function exec tells the interpreter to call itself and execute the content of the string passed as argument. It is also possible to execute the content of a string within a context defined by the symbols in a dictionary:
>>> a = "print b"
>>> c = dict(b=3)
>>> exec(a, {}, c)
3
Here the interpreter, when executing the string a, sees the symbols defined in c (b in the example), but does not see c or a themselves. This is different than a restricted environment, since exec does not limit what the inner code can do; it just defines the set of variables visible to the code.
A related function is eval, which works very much like exec except that it expects the argument to evaluate to a value, and it returns that value.
>>> a = "3*4"
>>> b = eval(a)
>>> print b
12
import
For example, if you need to use a random number generator, you can do:
>>> import random
>>> print random.randint(0, 9)
5
This prints a random integer between 0 and 9 (including 9), 5 in the example. The function randint is defined in the module random. It is also possible to import an object from a module into the current namespace:
>>> from random import randint
>>> print randint(0, 9)
or import all objects from a module into the current namespace:
>>> from random import *
>>> print randint(0, 9)
or import everything in a newly defined namespace:
>>> import random as myrand
>>> print myrand.randint(0, 9)
In the rest of this book, we will mainly use objects defined in modules os, sys, datetime, time and cPickle.
All of the web2py objects are accessible via a module calledgluon, and that is the subject of later chapters. Internally, web2py uses many Python modules (for examplethread), but you rarely need to access them directly.
In the following subsections we consider those modules that are most useful.
os
This module provides an interface to the operating system API. For example:
>>> import os
>>> os.chdir('..')
>>> os.unlink('filename_to_be_deleted')
Some of theosfunctions, such aschdir, MUST NOT be used in web2py because they are not thread-safe.
os.path.join is very useful; it allows the concatenation of paths in an OS-independent way:
>>> import os
>>> a = os.path.join('path', 'sub_path')
>>> print a
path/sub_path
System environment variables can be accessed via:
>>> print os.environ
which is a read-only dictionary.
sys
The sys module contains many variables and functions, but the one we use the most is sys.path. It contains a list of paths where Python searches for modules. When we try to import a module, Python looks for it in all the folders listed in sys.path. If you install additional modules in some location and want Python to find them, you need to append the path to that location to sys.path.
>>> import sys
>>> sys.path.append('path/to/my/modules')
When running web2py, Python stays resident in memory, and there is only one sys.path, while there are many threads servicing the HTTP requests. To avoid a memory leak, it is best to check if a path is already present before appending:
>>> path = 'path/to/my/modules'
>>> if not path in sys.path:
sys.path.append(path)
datetime
The use of the datetime module is best illustrated by some examples:
>>> import datetime
>>> print datetime.datetime.today()
2008-07-04 14:03:90
>>> print datetime.date.today()
2008-07-04
Occasionally you may need to time-stamp data based on the UTC time as opposed to local time. In this case you can use the following function:
>>> import datetime
>>> print datetime.datetime.utcnow()
2008-07-04 14:03:90
The datetime module contains various classes: date, datetime, time and timedelta. The difference between two date or two datetime or two time objects is a timedelta:
>>> a = datetime.datetime(2008, 1, 1, 20, 30)
>>> b = datetime.datetime(2008, 1, 2, 20, 30)
>>> c = b - a
>>> print c.days
1
In web2py, date and datetime are used to store the corresponding SQL types when passed to or returned from the database.
time
The time module differs from date and datetime because it represents time as seconds from the epoch (beginning of 1970).
>>> import time
>>> t = time.time()
1215138737.571
Refer to the Python documentation for conversion functions between time in seconds and time as a datetime.
cPickle
This is a very powerful module. It provides functions that can serialize almost any Python object, including self-referential objects. For example, let's build a weird object:
>>> class MyClass(object): pass
>>> myinstance = MyClass()
>>> myinstance.x = 'something'
>>> a = [1 ,2, {'hello':'world'}, [3, 4, [myinstance]]]
and now:
>>> import cPickle
>>> b = cPickle.dumps(a)
>>> c = cPickle.loads(b)
In this example, b is a string representation of a, and c is a copy of a generated by de-serializing b.
cPickle can also serialize to and de-serialize from a file:
>>> cPickle.dump(a, open('myfile.pickle', 'wb'))
>>> c = cPickle.load(open('myfile.pickle', 'rb'))
top
|
#1001 Le 25/04/2010, à 17:05
oGu
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Bonjour à tous !
Tout d'abord félicitations pour l'excellente tenue de ce forum et pour tous les scripts que j'ai piqué sur ce topic!!
Etant passé de Firefox à IceCat dernièrement, j'aimerais qu'un Ubuntero sachant scripter adapte ce fichier (qui défragmente les données sqlite de Firefox) à mon nouveau browser :
#!/usr/bin/env python
# coding=utf8
from os import getenv,getuid,kill,waitpid
from subprocess import call,Popen,PIPE
from os.path import abspath,join,exists
from signal import SIGTERM
def recup_rep_profiles():
base_profile=join(getenv('HOME'),".mozilla","firefox")
profiles_ini=join(base_profile,"profiles.ini")
rep_profiles=[]
lignes=open(profiles_ini).read().splitlines()
for ligne in lignes:
ligne=ligne.strip()
if ligne.startswith("Path="):
rep_profiles.append(join(base_profile,ligne[5:]))
return rep_profiles
def patch_sessionstore(sessionstore):
if not exists(sessionstore): return
chaine=open(sessionstore,"rb").read()
chaine=chaine.replace('session:{state:"running"}})','session:{state:"stopped"}})')
open(sessionstore,"wb").write(chaine)
def recup_firefox_pids():
lignes=Popen(['pgrep','-x','firefox','-U',str(getuid())],stdout=PIPE).communicate()[0]
firefox_pids=[]
for ligne in lignes.splitlines():
ligne=ligne.strip()
if not ligne: continue
firefox_pids.append(int(ligne))
return firefox_pids
def kill_firefox(firefox_pids):
for pid in firefox_pids: kill(pid,SIGTERM)
# Récupère les chemins vers les profiles
profiles=recup_rep_profiles()
# Récupère les PID des processus Firefox en cours d’exécution
pids=recup_firefox_pids()
# Demande confirmation si Firefox est en cours d’exécution
if pids:
retour=call(['zenity','--question','--title=Attention','--text=Firefox est encours d’exécution\nSi vous cliquez sur Valider, Firefox sera fermé le temps d’effectuer l’optimisation et relancé après'])
if retour==1: exit(1)
# Arrête Firefox
kill_firefox(pids)
# Patche les fichiers sessionstore.js
for profile in profiles:
patch_sessionstore(join(profile,"sessionstore.js"))
# Compacte les bases de données
progress=Popen(["zenity","--title","Optimisation","--text","Optimisation en cours...","--progress","--pulsate","--auto-close"],stdin=PIPE)
for profile in profiles:
Popen(['find',profile,'-name','*.sqlite','-print','-exec','sqlite3','{}','VACUUM',';'],stdout=progress.stdin)
progress.stdin.close()
# Relance Firefox s’il était lancé
if pids:
Popen(['firefox'],stderr=open("/dev/null"),stdout=open("/dev/null"))
Est-ce techniquement possible? Si oui merci d'avance à celui/ceux qui se pencheront sur la transformation de ce code!
Bye!
Ogu
Dernière modification par oGu (Le 25/04/2010, à 17:06)
Ubunteros de tous les pays, unissez-vous !
Hors ligne
#1002 Le 27/04/2010, à 13:02
bugs néo
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
ce script permet de rendre plus rapide Firefox?
jeu de course open source earth-race (le jeu est en réécriture complète depuis janvier, afin de pouvoir aller plus vite par la suite)
Hors ligne
#1003 Le 27/04/2010, à 14:12
oGu
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Bonjour!
Oui, c'est ce qu'il est censé faire : en défragmentant les bases de données (awesome bar etc...) il rend leur accès plus rapide.
Après j'ignore si l'effet est réel, ou si c'est un placebo...
Quelques liens :
-ici la page avec le script originel (tiens, je me rends compte que l'accentuation pose problème avec le script que j'ai posté, ce qui n'est pas le cas sur le script initial)
http://zigazou.wordpress.com/2009/05/21/optimisation-et-gain-despace-sous-firefox-3/
-pour les fans de la ligne de commande, la procédure à suivre :
http://www.webdevonlinux.fr/2009/04/optimiser-le-demarrage-de-firefox/
Dernière modification par oGu (Le 27/04/2010, à 14:17)
Ubunteros de tous les pays, unissez-vous !
Hors ligne
#1004 Le 29/04/2010, à 12:46
2F
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
bonjour,
un script utile (de débutant mais qui focntionne) pour éviter de se déplacer quand on fait de la maintenance.
il permet d'avoir pas mal d'infos sur une machine win et après permet quasiement tout si vous faites vos scripts en bat, reg ou vbs pour les lancer sur la machine distante.
il faut :
-winexe
-zenity
-un dossier en lecture seule au moins, accessible depuis le réseau (à renseigner dans gdiag.conf)
-la suite pstools à insérer dans ce même dossier
ce script peut être très évolutif et très utile, j'utilise moi, une version non graphique avec nos scripts perso du boulot qu'on lance directement par le menu.
donc j'ai voulu le rendre général. vos remarques, conseils sont les bienvenu.
gdiag.sh
#! /bin/bash
# Effectue des diagnostiques et rapporte des informations sur des pc win
# Licence : GPL
# Dépendance : winexe, zenity, la suite pstools sur un serveur, rdesktop, samba
# Il faut un accès en lecture seule au moins sur un serveur acessible depuis l'exterieur (a renseigner dans gdiag.conf)
#à finir
#finir lancement script personnaliser (script) : vérifier la présence du fichier sur le serveur
#possibilité de tuer un processus avec tskill PID
. ./gdiag.conf
pingo="Ping"
nmap="Nmap"
proc="Processus en cours"
heure="Resynchroniser date & heure"
service="Services (processus) : start, stop, restart"
script="Lancer un script .vbs .reg ou .bat"
psinfo="Infos PC (programmes installés, SP, ram, HDD, etc..)"
mstsc="Ouvrir port RDP, rdesktop & fermer RDP"
msconfig="Afficher msconfig démarrage"
browse="Parcourir le disque C:/"
logs="Afficher les erreurs du journal d'évènements des 24H"
diag="Diag complet"
reboot="Rebooter la machine"
console="Accéder à la console DOS distante"
autre="Passer sur une autre machine"
quit="Quitter"
machine () {
target=$(zenity --entry --title="Gdiag" --text="Nom de machine ou IP");
if ping -c 1 -w 3 $target
then
mdp=$(zenity --entry --hide-text --title="Gdiag" --text="Mot de passe administrateur");
menu
else
echo "$target ne ping pas !!" | zenity --text-info --title="$target NE PING PAS !" --width 500 --height 200 && machine
fi
}
machine
menu () {
rm -Rf res.txt && killall winexe
action=`zenity --list --title "$titre" --width 500 --height 550 --radiolist --column=Choix --column "Action" TRUE "$pingo" FALSE "$nmap" FALSE "$proc" FALSE "$heure" FALSE "$service" FALSE "$script" FALSE "$psinfo" FALSE "$mstsc" FALSE "$msconfig" FALSE "$browse" FALSE "$logs" FALSE "$reboot" FALSE "$console" FALSE "$autre" FALSE "$diag" FALSE "$quit"`
}
while [ "$choix" != "quit" ]; do
menu
case "$action" in
"$pingo")
ping $target | zenity --text-info --width 700 --height 500 --title="$pingo de $target"
;;
"$nmap")
nmap $target | zenity --text-info --width 700 --height 500 --title="$nmap de $target"
;;
"$proc")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k qprocess * /system & exit" | zenity --text-info --width 600 --height 800 --title="$proc"
;;
"$heure")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k w32tm /resync /rediscover & exit" | zenity --progress --pulsate --auto-close && echo "Allume un cierge mais $target devrait être à l'heure maintenant" | zenity --text-info --title="$heure de $target" --width 400 --height 200
;;
#stopper, relancer ou lancer un service : mettre le nom du service sans l'extension
"$service")
serv=$(zenity --entry --title="Gdiag" --text="Nom du service");
action=`zenity --list --title "Services" --width 500 --height 550 --radiolist --column=choix --column "Action" TRUE "lancer" FALSE "stopper" FALSE "relancer" FALSE "$quit"`
case "$action" in
"lancer")
acte=start
;;
"stopper")
acte=stop
;;
"relancer")
acte=restart
;;
"quit")
menu
;;
esac
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k \\\\"$serveur"\psservice.exe /accepteula $acte $serv & exit" | zenity --progress --pulsate --auto-close && echo "le service $serv est $acte sur $target" | zenity --text-info --width 400 --height 200 --title="$relancetb2 sur $target"
;;
# pour lancer un programme bat vbs ou reg depuis le dossier du serveur : mettre le nom exacte du fichier avec extension
"$script")
#choix du fichier script
file=$(zenity --entry --title="Gdiag" --text="Nom du script dans le dossier $serveur avec son extension :");
#vérifie l'extension du fichier
ext=`echo $file | grep -o '\.[^.]*$'`
case $ext in
".bat")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k start \\\\"$serveur"\\"$file" & exit" | zenity --progress --pulsate --auto-close && echo "$file lancé sur $target" | zenity --text-info --title="Lancement de $file sur $target" --width 400 --height 200
;;
".BAT")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k start \\\\"$serveur"\\"$file" & exit" | zenity --progress --pulsate --auto-close && echo "$file lancé sur $target" | zenity --text-info --title="Lancement de $file sur $target" --width 400 --height 200
;;
".vbs")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k cscript \\\\"$serveur"\"$file" & exit"" | zenity --progress --pulsate --auto-close && echo "$file lancé sur $target" | zenity --text-info --title="Lancement de $file sur $target" --width 400 --height 200
;;
".VBS")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k cscript \\\\"$serveur"\"$file" & exit"" | zenity --progress --pulsate --auto-close && echo "$file lancé sur $target" | zenity --text-info --title="Lancement de $file sur $target" --width 400 --height 200
;;
".reg")
winexe -U "$target"/administrateur%$mdp //"$target" "regedit /S \\\\"$serveur"\"$file" & exit"" | zenity --progress --pulsate --auto-close && echo "$file lancé sur $target" | zenity --text-info --title="Lancement de $file sur $target" --width 400 --height 200
;;
".REG")
winexe -U "$target"/administrateur%$mdp //"$target" "regedit /S \\\\"$serveur"\"$file" & exit"" | zenity --progress --pulsate --auto-close && echo "$file lancé sur $target" | zenity --text-info --title="Lancement de $file sur $target" --width 400 --height 200
;;
*)
zenity --warning --text="extension non supportée"
;;
esac
;;
#liste les infos pc
"$psinfo")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k \\\\"$serveur"\psinfo.exe -d -s /accepteula & exit" | zenity --text-info --title="$psinfo de $target" --width 700 --height 300
;;
#ouvre le port RDP, lance rdesktop et ferme le port RDP
"$mstsc")
winexe -U "$target"/administrateur%$mdp //"$target" "regedit /S \\\\"$serveur"\mstscon.reg"
notify-send -i /usr/share/icons/gnome/scalable/apps/gnome-terminal.svg Hop "Ouverture du Terminal serveur client sur "$target"" && sleep 5 && rdesktop "$target" && winexe -U "$target"/administrateur%$mdp //"$target" "regedit /S \\\\"$serveur"\mstscoff.reg" && notify-send -i /usr/share/icons/gnome/scalable/apps/gnome-terminal.svg Hop "Fermeture du Terminal serveur client sur "$target""
;;
#msconfig
"$msconfig")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k reg query HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run & exit" > res.txt 2>&1 | zenity --progress --pulsate --auto-close
cat res.txt |grep REG_SZ | zenity --text-info --title="$msconfig de $target" --width 700 --height 300
;;
"$browse")
`nautilus smb://administrateur@"$target"/c$`
;;
#affiche les erreurs du journal d'évènements des 24H
"$logs")
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k \\\\"$serveur"\psloglist.exe -d 1 -f e /accepteula & exit" >res.txt | zenity --progress --pulsate --auto-close && cat res.txt|grep -e ] -e Time| zenity --text-info --title="$autorun de $target" --width 400 --height 200
;;
#ping, nmap, liste processus, infos pc, msconfig et erreurs journal évènement des 24H
"$diag")
rm -f resultat.txt
ping3=`ping -c 3 "$target"`
echo -n "#### \\033[1;31mPING\\033[0m ####"
echo -n "#### PING ####" > resultat.txt
echo " " >> resultat.txt
echo " " >> resultat.txt
echo -n "$ping3" >> resultat.txt
echo " " >> resultat.txt
echo " " >> resultat.txt
echo -n "#### \\033[1;31mNMAP\\033[0m ####" &&
echo " " >> resultat.txt
echo "#### NMAP ####" >> resultat.txt
echo " " >> resultat.txt
gnome-terminal -x nmap "$target" -o nmap.txt && sleep 4 && cat nmap.txt |grep -v Nmap | grep -v Interesting >> resultat.txt
echo -n "#### \\033[1;31mINFOS PC\\033[0m ####"
echo -n "#### INFOS PC ####" >> resultat.txt
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k \\\\"$serveur"\psinfo.exe -d -s /accepteula & exit" >> resultat.txt
echo " " >> resultat.txt
echo -n "#### \\033[1;31mPROCESSUS\\033[0m ####"
echo -n "#### PROCESSUS ####" >> resultat.txt
echo " " >> resultat.txt
echo " " >> resultat.txt
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k qprocess * /system & exit" >> resultat.txt
echo -n "#### \\033[1;31mMSCONFIG\\033[0m ####"
echo " " >> resultat.txt
echo -n "#### MSCONFIG ####" >> resultat.txt
echo " " >> resultat.txt
winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k reg query HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run & exit" > res.txt && cat res.txt |grep REG_SZ >> resultat.txt
echo " "
echo "rapport terminé" && clear && cat resultat.txt | zenity --text-info --title="$diag de $target" --width 800 --height 600
;;
#reboot
"$reboot")
net rpc shutdown -r -C "Votre ordianteur va redémarrer" -f -I "$target" -U administrateur%$mdp | zenity --text-info --title="reboot de $target en cours..." --width 400 --height 400
;;
#ok, tapez exit pour terminer le processus correctement
"$console")
gnome-terminal -x winexe -U "$target"/administrateur%$mdp //"$target" "cmd /k qprocess * /system" &
;;
"$autre")
machine
;;
"$quit")
break;;
*)
esac
done
exit 0
le fichier de conf pauvre mais utile pour que ca serve à tout le monde
gdiag.conf
#mettre de la forme serveur="ip-serveur\mon dossier\scripts"
serveur=
et 2 tout petit .reg (a mettre aussi dans le dossier) qui servent dans le script... à vous de faire les votre après :
mstscon.reg
Windows Registry Editor Version 5.00[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server]"fDenyTSConnections"=dword:00000000
mstscoff.reg
Windows Registry Editor Version 5.00[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server]"fDenyTSConnections"=dword:00000001
voilà.
Bon app!
Dernière modification par 2F (Le 04/05/2010, à 17:02)
Hors ligne
#1005 Le 08/05/2010, à 16:28
malagasy
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Bonjour,
je n'y connais rien du tout en script, alors je voudrai savoir si quelqu'un peut me faire un petit script qui lance au démarrage de gnome:
compiz --replace
puisque depuis la mise à jour vers lucid, gnome n'aime pas trop compiz, et il faut que je lance cette commande à chaque fois,
Merci
Hors ligne
#1006 Le 08/05/2010, à 17:16
Levi59
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Bonjour,
je n'y connais rien du tout en script, alors je voudrai savoir si quelqu'un peut me faire un petit script qui lance au démarrage de gnome:
compiz --replace
puisque depuis la mise à jour vers lucid, gnome n'aime pas trop compiz, et il faut que je lance cette commande à chaque fois,
Merci
pourquoi un script? il te suffit de mettre "compiz-replace" dans les programmes au démarrage non?
Au pire si il faut le lancer en décalé, met "sleep X && compiz-replace" en remplaçant X par le nombre de seconde nécessaires.
Hors ligne
#1007 Le 08/05/2010, à 20:51
#1008 Le 08/05/2010, à 21:24
Levi59
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
c'est pour ça que j'adore cette communauté .. merci, ça marche
À vot' service M'sieurs! ^^
Dernière modification par Levi59 (Le 08/05/2010, à 21:25)
Hors ligne
#1009 Le 08/05/2010, à 22:59
#1010 Le 18/05/2010, à 10:16
yamo
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Bonjour,
Comme j'en avait marre de synaptic je me suis fait un script de mise à jour basé sur apt-get.
Tout d'abord, j'ai pris l'habitude de mettre tous mes scripts dans ~/bin ça permet d'avoir un répertoire home un peu rangé! Et de les lancer très simplement sans devoir ajouter ./ au début
Vous aller trouver étrange que je commence tout de suite par mettre à jour mais c'est par ce que j'utilise cron-apt qui permet de télécharger en tâche de fond les paquets, comme ça les mises paraissent encore plus rapides!
Attention, la mise à jour d'un système n'est pas triviale, lisez ces scripts avant de les utiliser. Personnellement, j'essaie toujours de comprendre ce que va faire une commande avant de l'exécuter.
Je n'ai laissé que la version console, la version graphique n'a pas vraiment d’intérêt vu que ça fonctionne bien de base en graphique.
~/bin/update.console.sh :
#!/bin/bash
# ~/bin/update.console.sh
# mise à jour du 11/12/2011
echo "mise à jour" &&
sudo nice -n 19 ionice -c 3 apt-get dist-upgrade -y &&
echo "nettoyage" &&
sudo nice -n 19 ionice -c 3 apt-get clean &&
echo "nettoyage" &&
sudo nice -n 19 ionice -c 3 apt-get autoclean &&
echo "coup de balai" &&
sudo nice -n 19 ionice -c 3 apt-get autoremove &&
echo "toc toc toc" &&
sudo nice -n 19 ionice -c 3 apt-get -qq update &&
## l'usage de -qq est totalement déconseillé en dehors d'update!
echo "mise à jour" &&
sudo nice -n 19 ionice -c 3 apt-get dist-upgrade -y &&
echo "dernieres mises à jour" &&
grep -v '\(half\|configure\|trigproc\|triggers-pending\|startup\|install-info\|unpacked\|config-files\|triggers-awaited\|installed\)' /var/log/dpkg.log
Pour tester mon script voici un script d'installation :
mkdir ~/bin & cd ~/bin/ &&
wget http://pasdenom.info/scripts/update.console.sh &&
chmod 554 ~/bin/update.console.sh
Enfin pour lancer le script il suffit de taper en console :
update.console.sh
Dernière modification par yamo (Le 11/12/2011, à 12:31)
Hors ligne
#1011 Le 28/05/2010, à 12:49
kazylax
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Bonjour,
un script existe pour Emesene ? de msn messenger
Cordialement,
Hors ligne
#1012 Le 28/05/2010, à 13:11
kyncani
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
J'aimerais savoir comment récupérer la liste des paquets installé manuellement.
Je sais récupérer la liste de tous les paquet installer, mais c'est très casse pied de la nettoyer pour ne conserver que les 60 intéressants...
J'ai donc mis les tag "auto" qu'il faut dans aptitude mais je ne sais pas comment en extraire la liste
aptitude search '~i!~M'
Hors ligne
#1013 Le 28/05/2010, à 20:56
Phendrax
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Yop
J'ai écrit une petite interface en python pour xinput que j'ai appelé gtk-xinput. Cela permet de facilement créer des pointeurs à l'écran et de leur associer des souris.
L'interface affiche donc la liste des pointeurs et chaque souris qui lui est associée. Sur le screen on peut voir par exemple que Logitech G500 est associée au pointeur dont l'id=2.
On peut créer des nouveaux pointeurs à l'écran avec le bouton "Ajouter" (en leur donnant un nom contenant uniquement des caractères alphanumériques) et en supprimer avec le bouton "Supprimer".
Le bouton "Recharger" sert à rafraichir l'affichage, par exemple si on vient de brancher une nouvelle souris.
Par défaut les souris sont associées au pointeur Virtual core. Il suffit de les glisser vers le pointeur que l'on veut.
Pour l'installer il est nécessaire d'avoir python, pygtk, libglade et xinput
sudo apt-get install python python-gtk2 libglade2-0 xinput
Le paquet debian de gtk-xinput peut être téléchargé ici : http://dl.free.fr/getfile.pl?file=/zoIHihCO
Le programme peut ensuite être lancé avec la commande gtk-xinput.
[Edit : il semblerait que le programme ne fonctionne que sous Lucid Lynx notamment à cause de la méthode set_visible() qui ne semble pas exister dans les versions précédentes et à cause de l'affichage de la commande xinput qui diffère selon les versions]
Dernière modification par Phendrax (Le 28/05/2010, à 21:47)
HP Pavillon dv6800 - Ubuntu 10.10 - GNOME 2.32.0
Hors ligne
#1014 Le 29/05/2010, à 01:42
BorX
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Marrant
Ça permet d'utiliser plusieurs souris en même temps ??
Autant je trouve ça vraiment intéressant, autant j'ai du mal à voir dans quel contexte l'utiliser...
A plusieurs ?
Pour les ambidextres ?
Hors ligne
#1015 Le 29/05/2010, à 04:43
kyncani
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Deux personnes sur une même machine
Hors ligne
#1016 Le 29/05/2010, à 12:01
hulk
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
MON scripte iptables
utilisation iptables start ou iptables stop
a placer dans /etc/init.d/ et a rendre exécutable puis l'activer avec update-rc.d
#! /bin/sh
### BEGIN INIT INFO
# Provides: iptables
# Required-Start:
# Required-Stop:
# Should-Start:
# Should-Stop:
# Default-Start: 2 3 4 5
# Default-Stop: 1 6
# Short-Description: script iptables
### END INIT INFO
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
case "$1" in
start)
### SUPRESSION de TOUTES LES ANCIENNES TABLES (OUVRE TOUS!!) ###
iptables -F
iptables -X
### BLOC TOUS !! (seules les autorisations des raigle aprés celle-ci sont prise en compte) ###
iptables -P INPUT DROP
iptables -P OUTPUT DROP
iptables -P FORWARD DROP
### ACCEPT ALL interface loopbaak ###
iptables -I INPUT -i lo -j ACCEPT
iptables -I OUTPUT -o lo -j ACCEPT
### axepte en entrer les connection deja etablie (en gros sa permet d'axépter que les conection inicier
### par sont propre PC)
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
### DNS indispensable pour naviguer facilement sur le web ###
iptables -A OUTPUT -p udp -m udp --dport 53 -j ACCEPT
### HTTP navigation internet non sécuriséer ###
iptables -A OUTPUT -p tcp -m tcp --dport 80 -j ACCEPT
### HTTPS pour le site de banque .... ###
iptables -A OUTPUT -p tcp -m tcp --dport 443 -j ACCEPT
### emesene,pindgin,amsn... ####
iptables -A OUTPUT -p tcp -m tcp --dport 1863 -j ACCEPT
### pop thunderbird ... réceptions des message ####
iptables -A OUTPUT -p tcp -m tcp --dport 110 -j ACCEPT
### smtp thunderbird ... envoi des messages ###
iptables -A OUTPUT -p tcp -m tcp --dport 25 -j ACCEPT
### ntpdate ( client ntp )... sincro a un serveur de temp ###
iptables -A OUTPUT -p udp -m udp --dport 123 -j ACCEPT
### client-transmition
iptables -A OUTPUT -p udp -m udp --sport 51413 -j ACCEPT
iptables -A OUTPUT -p tcp -m tcp -s 192.168.1.2/255.255.255.255 --sport 30000:65000 -o eth0 -j ACCEPT
# remplacer 192.168.1.2 par votre adresse ip et eth0 par l'interface connecter a internet.
### ping ... autorise a pinger un ordinateur distent ###
iptables -A OUTPUT -p icmp -j ACCEPT
### ping ... autorise l'extèrieur a vous pinger ###
# iptables -A INPUT -p icmp -j ACCEPT # enlever le # du début de ligne pour activer cette règle
### LOG ### Log tous ce qui qui n'est pas accepter par une règles précédente
# prés requit : sudo apt-get install sysklogd
# echo 'kern.warning /var/log/iptables.log' > /etc/syslog.conf
iptables -A OUTPUT -j LOG --log-level 4
iptables -A INPUT -j LOG --log-level 4
iptables -A FORWARD -j LOG --log-level 4
;;
stop)
### OUVRE TOUS !! ###
iptables -F
iptables -X
;;
*)
N=/etc/init.d/${0##*/}
echo "Usage: $N {start|stop}" >&2
exit 1
;;
esac
exit 0
pour vérifier les log en temps réel 10 dernier entréer.
tail -f /var/log/iptables.log
Dernière modification par hulk (Le 07/12/2010, à 23:15)
Amilo A 1667G , turion64 , X700 .
debian squeeze amd64
driver libre radeon
Hors ligne
#1017 Le 31/05/2010, à 20:56
shamanphenix
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Pendant que je vous lisais, ça m'a donné envie, alors j'ai rapidement fait un premier jet (il faudrait que je rajoute un vidage de la corbeille, des miniatures Nautilus, etc. mais là n'est pas la question pour le moment ) pour mettre à jour mon système :
#!/bin/sh
# Permets de nettoyer et mettre à jour son système.
# Dépendance(s) : libnotify-bin ou zenity
# zenity --info --text="Mise à jour du système"
notify-send --icon=/usr/share/icons/hicolor/48x48/status/aptdaemon-working.png "Mise à jour du système"
# Mettre à jour la liste des fichiers disponibles dans les dépôts :
# zenity --info --text="Mise à jour de la liste des fichiers disponibles dans les dépôts"
notify-send --icon=/usr/share/icons/hicolor/48x48/status/aptdaemon-update-cache.png "Mise à jour de la liste des fichiers disponibles dans les dépôts"
sudo apt-get update
# Mettre à jour tous les paquets installés vers les dernières versions :
# zenity --info --text="Mise à jour de tous les paquets installés vers les dernières versions"
notify-send --icon=/usr/share/icons/hicolor/48x48/status/aptdaemon-upgrade.png "Mise à jour de tous les paquets installés vers les dernières versions"
sudo apt-get upgrade -y
# Mettre à jour tous les paquets installés vers les dernières versions en installant de nouveaux paquets si nécessaire :
# zenity --info --text="Mise à jour de tous les paquets installés vers les dernières versions en installant de nouveaux paquets si nécessaire"
notify-send --icon=/usr/share/icons/hicolor/48x48/status/aptdaemon-upgrade.png "Mise à jour de tous les paquets installés vers les dernières versions en installant de nouveaux paquets si nécessaire"
sudo apt-get dist-upgrade -y
# Supprimer les copies des paquets installés :
# zenity --info --text="Suppression des copies des paquets installés"
notify-send --icon=/usr/share/icons/hicolor/48x48/status/aptdaemon-cleanup.png "Suppression des copies des paquets installés"
sudo apt-get clean
# Supprimer les copies des paquets désinstallés :
# zenity --info --text="Suppression copies des paquets désinstallés"
notify-send --icon=/usr/share/icons/hicolor/48x48/status/aptdaemon-cleanup.png "Suppression copies des paquets désinstallés"
sudo apt-get autoclean -y
# zenity --info --text="Le système a été mis à jour"
notify-send --icon=/usr/share/icons/hicolor/48x48/status/aptdaemon-upgrade.png "Le système a été mis à jour"
Alors je sais, c'est super mal de mettre des "sudo" dans un script, et en plus c'est tout pourri puisque dans ce cas on est obligé de lancer le bouzin dans un terminal pour saisir le mot de passe root alors que j'aurais bien voulu le mettre dans mes scripts Nautilus...
Est-ce que l'un(e) d'entre vous aurait une idée géniale, par hasard ?
[edit]PS : c'est dommage que la balise "code" du forum ne colorie pas le texte, ça aiderait beaucoup à la lisibilité.[/edit]
Dernière modification par shamanphenix (Le 31/05/2010, à 20:57)
"Ubuntu". Si tous les gens du monde voulaient bien se tenir par la main... ce serait bien plus facile pour les électrocuter.
What did /home/user/DARTHVADER say to /home/user/DARTHVADER/LUKESKYWALKER ?I AM YOUR PARENT FOLDER.
Hors ligne
#1018 Le 31/05/2010, à 21:01
TatrefThekiller
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
gksudo ?
Hors ligne
#1019 Le 31/05/2010, à 21:12
shamanphenix
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
gksudo ?
En effet c'est une bonne idée, je pourrais remplacer le premier "sudo" par un "gksudo" (ça devrait suffire pour les autres, non ?), mais je dois avouer que je préfèrerais que cela soit entièrement automatisé (je sais saymal).
"Ubuntu". Si tous les gens du monde voulaient bien se tenir par la main... ce serait bien plus facile pour les électrocuter.
What did /home/user/DARTHVADER say to /home/user/DARTHVADER/LUKESKYWALKER ?I AM YOUR PARENT FOLDER.
Hors ligne
#1020 Le 31/05/2010, à 22:00
kyncani
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Ce genre de truc en en-tête peut marcher je crois :
if test `id -u` -ne 0; then
if test "$DISPLAY" = ""; then
exec sudo "$0" "$@"
else
exec gksudo "$0" "$@"
fi
exit 1
fi
Hors ligne
#1021 Le 01/06/2010, à 00:04
BorX
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
Ou sinon
o Donner au script les droits root :
-rwx------ root root leScript
o Y virer tous les sudo qui sont à l'intérieur
o Et l'appeler avec sudo leScript
Ce qui continuera à demander un mot de passe à son lancement, sauf si on modifie le fichier /etc/sudoers de façon à ce script puisse être exécuté avec un sudo sans mot de passe.
Quelque chose du style
%sudo ALL=NOPASSWD: leScript
Mais je ne me souviens plus trop de la syntaxe.
C'est pas compliqué, faut chercher un tout petit peu
Hors ligne
#1022 Le 01/06/2010, à 08:21
draco31.fr
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
[edit]PS : c'est dommage que la balise "code" du forum ne colorie pas le texte, ça aiderait beaucoup à la lisibilité.[/edit]
C'est possible sur le wiki si tu indiques le langage ... mais à ma connaissance, ça n'a pas été prévu pour le forum.
Cela dit, il te suffit d'en faire la demande sur le topic de la nouvelle version du forum, ou de créer un rapport de bug sur launchpad pour le projet ubuntu-fr.org
Hors ligne
#1023 Le 01/06/2010, à 12:38
Levi59
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
shamanphenix a écrit :
[edit]PS : c'est dommage que la balise "code" du forum ne colorie pas le texte, ça aiderait beaucoup à la lisibilité.[/edit]
C'est possible sur le wiki si tu indiques le langage ... mais à ma connaissance, ça n'a pas été prévu pour le forum.
Cela dit, il te suffit d'en faire la demande sur le topic de la nouvelle version du forum, ou de créer un rapport de bug sur launchpad pour le projet ubuntu-fr.org
Ou encore de créer un plugin FF bien que ce ne soit pas du tout dans mes cordes... ^^
Si quelqu'un en est capable, voila un bon challenge!
Hors ligne
#1024 Le 01/06/2010, à 22:41
Nik0s
Re : [ VOS SCRIPTS UTILES ] (et eventuelles demandes de scripts...)
J'ai créé un petit script pour récupérer des wallpapers sur Interfacelift. Il y a, je pense, possibilité de l'améliorer, mais en voici le code
retiré
Dernière modification par Nik0s (Le 03/06/2010, à 20:46)
Hors ligne
|
What you request cannot be done in Python 2.whatever, for a very specific reason. You want to write:
class Task(model):
title = ''
isDone = False
In Python 2.anything, whatever model may possibly be, this cannot ever allow you to predict any "ordering" for the two fields, because the semantics of a class statement are:
execute the body, thus preparing a dict
locate the metaclass and run special methods thereof
Whatever the metaclass may be, step 1 has destroyed any predictability of the fields' order.
Therefore, your desired use of positional parameters, in the snippet:
Task('Illustrate different syntax modes', True)
cannot associate the arguments' values with the model's various fields. (Trying to guess by type association -- hoping no two fields ever have the same type -- would be even more horribly unpythonic than your expressed desire to use db.tasklist and db['tasklist'] indifferently and interchangeably).
One of the backwards-incompatible changes in Python 3 was introduced specifically to deal with situations of this ilk. In Python 3, a custom metaclass can define a __prepare__ function which runs before "step 1" in the above simplified list, and this lets it have more control about the class's body. Specifically, quoting PEP 3115...:
__prepare__ returns a dictionary-like object which is used to store
the class member definitions during evaluation of the class body.
In other words, the class body is evaluated as a function block
(just like it is now), except that the local variables dictionary
is replaced by the dictionary returned from __prepare__. This
dictionary object can be a regular dictionary or a custom mapping
type.
...
An example would be a metaclass that
uses information about the
ordering of member declarations to create a C struct. The metaclass
would provide a custom dictionary that simply keeps a record of the
order of insertions.
You don't want to "create a C struct" as in this example, but the order of fields is crucial (to allow the use of positional parameters that you want) and so the custom metaclass (obtained through base model) would have a __prepare__ classmethod returning an ordered dictionary. This removes the specific issue, but, of course, only if you're willing to switch all of your code using this "magic ORM" to Python 3. Would you be?
Once that's settled, the issue is, what database operations do you want to perform, and how. Your example, of course, does not clarify this at all. Is the taskList attribute name special, or should any other attribute assigned to the db object be "autosaved" (by name and, what other characteristic[s]?) and "autoretrieved" upon use? Are there to be ways to remove entities, alter them, locate them (otherwise than by having once been listed in the same attribute of the db object)? How does your sample code know what DB service to use and how to authenticate to it (e.g. by userid and password) if it requires authentication?
The specific tasks you list would not be hard to implement (e.g. on top of Google App Engine's storage service, which does not require authentication nor specification of "what DB service to use"). model's metaclass would introspect the class's fields and generate a GAE Model for the class, the db object would use __setattr__ to set an atexit trigger for storing the final value of an attribute (as an entity in a different kind of Model of course), and __getattr__ to fetch that attribute's info back from storage. Of course without some extra database functionality this all would be pretty useless;-).
Edit: so I did a little prototype (Python 2.6, and based on sqlite) and put it up on http://www.aleax.it/lustdb.zip -- it's a 3K zipfile including 225-lines lustdb.py (too long to post here) and two small test files roughly equivalent to the OP's originals: test0.py is...:
from lustdb import *
class Task(Model):
title = ''
done = False
db.taskList = []
db.taskList.append(Task(title='Beat old sql interfaces', done=False))
db.taskList.append(Task(title='Illustrate different syntax modes', done=True))
and test1.p1 is...:
from lustdb import *
print 'Done tasks:'
for task in db.taskList:
if task.done:
print task
Running test0.py (on a machine with a writable /tmp directory -- i.e., any Unix-y OS, or, on Windows, one on which a mkdir \tmp has been run at any previous time;-) has no output; after that, running test1.py outputs:
Done tasks:
Task(done=True, title=u'Illustrate different syntax modes')
Note that these are vastly less "crazily magical" than the OP's examples, in many ways, such as...:
1. no (expletive delete) redundancy whereby `db.taskList` is a synonym of `db['taskList']`, only the sensible former syntax (attribute-access) is supported
2. no mysterious (and totally crazy) way whereby a `done` attribute magically becomes `isDone` instead midway through the code
3. no mysterious (and utterly batty) way whereby a `print task` arbitrarily (or magically?) picks and prints just one of the attributes of the task
4. no weird gyrations and incantations to allow positional-attributes in lieu of named ones (this one the OP agreed to)
The prototype of course (as prototypes will;-) leaves a lot to be desired in many respects (clarity, documentation, unit tests, optimization, error checking and diagnosis, portability among different back-ends, and especially DB features beyond those implied in the question). The missing DB features are legion (for example, the OP's original examples give no way to identify a "primary key" for a model, or any other kinds of uniqueness constraints, so duplicates can abound; and it only gets worse from there;-). Nevertheless, for 225 lines (190 net of empty lines, comments and docstrings;-), it's not too bad in my biased opinion.
The proper way to continue playing with this project would of course be to initiate a new lustdb open source project on the hosting part of code.google.com (or any other good open source hosting site with issue tracker, wiki, code reviews support, online browsing, DVCS support, etc, etc) - I'd do it myself but I'm close to the limit in terms of number of open source projects I can initiate on code.google.com and don't want to "burn" the last one or two in this way;-).
BTW, the lustdb name for the module is a play of word with the OP's initials (first two letters each of first and last names), in the tradition of awk and friends -- I think it sounds nicely (and most other obvious names such as simpledb and dumbdb are taken;-).
|
I'm finally settling back into the groove of some of my side projects. I guess I'm handling the new position a bit better as time goes on, and feel that I can spend some free time working on somethings that I want to do, not just things that I feel that I should do.
So, these side projects I do for fun, and they are the most fun when they combine together in sweet ways. During the dead of winter, I spent a bunch of weeks working on Photobomb . On of the features that I added was that you could add an image directly from your web cam. To do this, I used the PyGame Web Cam API, essentially because I saw the API, and knew that I would be able to use it relatively easily, which in fact turned out to be the case.
It also turned out that not everyone had PyGame already installed on their systems. As a result installing Photobomb meant a 25+ Megabyte download, most of which was PyGame. So I was advised to use GStreamer instead. I got started on this conversion back in April, by creating a simple web cam display application using gstreamer. I ran into a series of roadblocks, one such roadblock was removed by Chris Halse Rogers of desktop team fame, who knew why it kept crashing (basically, I was trying to access the xid of a widget that wasn't yet realized).
But I soon had a pipeline together that could display the web cam, but I could not figure out how to modify it so that it could save out a picture whilst still displaying the web cam output. I finally hopped into #gstreamer to see if someone could give me a pointer. Well, it turns out that someone already wrote a pipeline called caemerabin that does everything I need for the web cam, and more.
Well, it turned out that the documentation was out of sync with the current API. This isn't too surprising, as camerabin is still in gstreamer0.01-plugins-bad, and the API is actually improved by the changes. But I was struggling to understand camerabin, so I went back to #gstreamer. Often in IRC, someone will volunteer to spend some time helping you out with a problem. thiagoss (who I think might be this guy) really helped me out. I'm not sure, but I think he may actually be a primary author of camerabin. Anyway, he set me straight on a couple of things, namely:
1. use $gst-inspect camerabin to see what properties and methods the GStreamer elements really support (if they are out of sync with the docs).
2. use GST_DEBUG=2 to run your gstreamer apps, as this puts more warnings in your output.
Well, between these 2 tips, I was quickly able to realize that my WebCamBox widget would not much more than some Gtk/Gstreamer app boiler plate, with a wrapper around camerabin.
So, for example the "take picture" function just creates a time stamp, then tells the camerabin instance to emit a "capture-start" signal.
stamp = str(datetime.datetime.now())
extension = ".png"
directory = os.environ["HOME"] + _("/Pictures/")
self.filename = directory + self.filename_prefix + stamp + extension
self.camerabin.set_property("filename", self.filename)
self.camerabin.emit("capture-start")
return self.filename
Then in on_message, I capture the message that it is done, and fire a signal:
t = message.type
if t == gst.MESSAGE_ELEMENT:
if message.structure.get_name() == "image-captured":
#work around to keep the camera working after lots
#of pictures are taken
self.camerabin.set_state(gst.STATE_NULL)
self.camerabin.set_state(gst.STATE_PLAYING)
self.emit("image-captured", self.filename)
Play, Pause, and Start were trivially easy to implement:
self.camerabin.set_state(gst.STATE_PLAYING)
self.camerabin.set_state(gst.STATE_PAUSED)
self.camerabin.set_state(gst.STATE_NULL)
Like I say, there is also some boiler plate to instantiate the camera and associate it with a gtk.DrawingArea. It took me a lot of iterations to get it working, as you can see from all of these pictures of me working on it ...
The net result is that it's now pretty easy to create an app with a web cam in it. Here's all the code for the WebCamBox test app.
if __name__ == "__main__":
"""creates a test WebCamBox"""
import quickly.prompts
#create and show a test window
win = gtk.Window(gtk.WINDOW_TOPLEVEL)
win.set_title("WebCam Test Window")
win.connect("destroy",gtk.main_quit)
win.show()
#create a top level container
vbox = gtk.VBox(False, 10)
vbox.show()
win.add(vbox)
mb = WebCamBox()
mb.video_frame_rate = 30
vbox.add(mb)
mb.show()
mb.play()
mb.connect("image-captured", __image_captured)
play_butt = gtk.Button("Play")
pause_butt = gtk.Button("Pause")
stop_butt = gtk.Button("Stop")
pic_butt = gtk.Button("Picture")
play_butt.connect("clicked", lambda x:mb.play())
play_butt.show()
mb.pack_end(play_butt, False)
pause_butt.connect("clicked", lambda x:mb.pause())
pause_butt.show()
mb.pack_end(pause_butt, False)
stop_butt.connect("clicked", lambda x:mb.stop())
stop_butt.show()
mb.pack_end(stop_butt, False)
pic_butt.connect("clicked", lambda x:mb.take_picture())
pic_butt.show()
mb.pack_end(pic_butt, False)
gtk.main()
Almost all of it is standard code for creating widgets. I love that doing functions like play, pause, stop, and take a picture can be handled in lambdas. So much easier!
So my last step was to drop it into Photobomb. All I had to do was modify the CameraPage class that I had already set up for the PyGame based version.
import gtk
from quickly.widgets.web_cam_box import WebCamBox
from ImageListPage import ImageListPage
class CameraPage(ImageListPage):
def __init__(self):
gtk.VBox.__init__(self,False, 0)
self.__camera = WebCamBox()
self.__camera.connect("image-captured",self.image_captured)
self.__camera.show()
self.__camera.set_size_request(128, 128)
self.pack_start(self.__camera, False, False)
button = gtk.Button("Take Picture")
button.show()
button.connect("clicked", lambda x:self.__camera.take_picture())
self.pack_start(button, False, False)
def image_captured(self, widget, path):
self.emit("clicked",path)
def on_selected(self):
self.__camera.play()
def on_deselected(self):
self.__camera.stop()
Well, almost all I had to do. I discovered a bug where if the WebCamBox is not actually visible, it locks up Photobomb if you try to show it. For now, I've worked around this by putting the CameraPage as the first and open page, so it just works. However, I suspect the bug is due to the xid not being available when camerabin tries to display on it. I think with a little thought, I can block this condition, and perhaps not let the camera play if it's not ready yet.
Anyway, I ended up with a few lines of wrapper code, around my wrapper code, and it all works thanks to the efforts of the folks working on camerabin!
camerabin has a whole lot of functionality that I haven't wrapped yet. It takes video, including audio! Also, it looks like you can change encoders, and drop in filters and such into the pipeline. To handle this for now, WebCamBox exposes a "camerabin" public property, so if you are using the widget, you won't run into a wall.
|
I'm trying to use QGIS to loop through a set of points, find their elevation from a DEM and use that value to update the point layer's attribute table. The loop works fine until I try to use changeAttributeValues(), and I can change the attribute values outside of the loop, but when I try to put the two together I cause a dump.
while provider.nextFeature(feat):
geom = feat.geometry()
x = geom.asPoint()
res, ident = rlayer.identify(QgsPoint(x))
for (k,v) in ident.iteritems():
elevation = float(v)
attrs = { 2 : elevation }
caps = vlayer.dataProvider().capabilities()
if caps & QgsVectorDataProvider.ChangeAttributeValues:
vlayer.dataProvider().changeAttributeValues({ fid : attrs })
This causes the following error in Linux:
*** glibc detected *** python2: free(): invalid pointer: 0x00000000024655b8 ***
Edit:
The problem isn't the loop, it is now I'm calling changeAttributeValues(). I've simplified the script down to just update a single point and it causes the same core dump. Here's the updated script:
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from qgis.core import *
import qgis.utils
#initializes QGIS and points python to where it can find QGIS's stuff
QgsApplication.setPrefixPath("/usr/", True)
QgsApplication.initQgis()
vlayer = QgsVectorLayer("/gis/vector/elev_pts.shp", "elev_pts", "ogr")
if not vlayer.isValid():
print "Layer did not load!"
vlayer.dataProvider().changeAttributeValues({ 0: 2: 432.1 })
QgsApplication.exitQgis()
|
I managed to store a picture in the Google App engine blob (I can see it in the Blob Viewer from the dashboard, and also in my app using a serving handler).. However, now that i have this picture there..i want to resize it while serving it to the client...Problem is that i can't do that...I can't make an Image out of that blob...This is my code :
from google.appengine.api import images
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
....
class Image(webapp2.RequestHandler):
def get(self,id):
product = Product.by_id(int(id))
logging.info('pic key is' + str(product.small_pic.key()))
img = images.Image(blob_key=str(product.small_pic.key()))
img.im_feeling_lucky() # do a transform, otherwise GAE complains.
img.execute_transforms(output_encoding=images.JPEG,quality=1)
if img:
self.response.headers['Content-Type'] = 'image/png'
self.response.out.write(img)
else:
self.error(404)
The code from above is taken from this thread : GAE: How to get the blob-image height
When i run the code from above ex /img/373 i get the error :
The image "http:..../img/373" cannot be displayed because it contains errorsHow can i do this ?..What i want is to find out way to transform that blob in an image and then process the image...
|
I have this code in Google AppEngine (Python SDK):
from string import maketrans
intab = u"ÀÃÂÃÄÅà áâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÃÃŽÃìÃîïÙÚÛÜùúûüÿÑñ".encode('latin1')
outtab = u"aaaaaaaaaaaaooooooooooooeeeeeeeecciiiiiiiiuuuuuuuuynn".encode('latin1')
logging.info(len(intab))
logging.info(len(outtab))
trantab = maketrans(intab, outtab)
When I run the code in the interactive console I have no problem, but when I try it in GAE I get the following error:
raise ValueError, "maketrans arguments must have same length"ValueError: maketrans arguments must have same lengthINFO 2009-12-03 20:04:02,904 dev_appserver.py:3038] "POST /backendsavenew HTTP/1.1" 500 -INFO 2009-12-03 20:08:37,649 admin.py:112] 106INFO 2009-12-03 20:08:37,651 admin.py:113] 53ERROR 2009-12-03 20:08:37,653 init.py:388] maketrans arguments must have same length
I can't figure out why the intab it's doubled in size. The python file with the code is saved as UTF-8.
Thanks in advance for any help.
|
Great answers here! I'm developing a card game using Python and Pygame, which has no double-click support, so I stumbled upon the same problem.
Inspired on Marcel Böttcher's answer, to measure your own time and then double it, I've created a small tool to measure the speed of double-clicks, and I'm sharing with you:
import pygame
import random
pygame.init()
screen = pygame.display.set_mode((800, 600))
font = pygame.font.Font(None, 48)
clock = pygame.time.Clock()
start = None
done = False
while not done:
for event in pygame.event.get():
if (event.type == pygame.QUIT or
getattr(event, 'key', None) == pygame.K_ESCAPE):
done = True
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if start:
time = pygame.time.get_ticks() - start
color = (random.randint(0, 255),
random.randint(0, 255),
random.randint(0, 255))
screen.fill(color)
screen.blit(font.render(str(time), True, (255-color[0],
255-color[1],
255-color[2])), (0, 0))
print time
start = None
else:
start = pygame.time.get_ticks()
if start and pygame.time.get_ticks() - start > 900:
start = None
pygame.display.update()
clock.tick(60)
For the record, I tested with my stepfather, who's 71, very low dexterity (although no disability of any kind) and never used a computer / touch / mouse before in his life!
His results were pretty surprising to me: after a 3 minute training on how to grab and use a mouse (thanks to Solitaire), and what a double click is, he averaged on 250-320 ms for 30+ tries (mine was 140-180). Even when told the test was not about speed (which I guess he assumed to mean "take it easy"), his average was still in the 400-550ms range.
So I guess 500 is a pretty conservative default, and should handle fine most users. Even 350 would not prevent daddy to enjoy my silly game :)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.